mirror of
https://github.com/storytold/egui.git
synced 2026-11-23 11:02:38 +01:00
Render any glyph and colored emoji on native 🚀 (#8512)
Add full emoji support to eframe on native! Also supports any glyph that your system fonts support. Test string: ✨ We support ไทย, 한국어, and 🦀 🚀 🤖/🦾/📷/🎞️ Chain, in order, all merged into `emilk/emojis`: * https://github.com/emilk/egui/pull/8491 * https://github.com/emilk/egui/pull/8492 * https://github.com/emilk/egui/pull/8493 * https://github.com/emilk/egui/pull/8508 * https://github.com/emilk/egui/pull/8509 * https://github.com/emilk/egui/pull/8510 * https://github.com/emilk/egui/pull/8511 --------- Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
1 parent
e39e793d5c
commit
f2de65f636
91 files changed
+1980
-843
No files matched your search
@@ -30,4 +30,4 @@ jobs:
|
||||
with:
|
||||
mode: minimum
|
||||
count: 1
|
||||
labels: "CI, dependencies, docs and examples, ecolor, eframe, egui_extras, egui_glow, egui_inspection, egui_kittest, egui-wgpu, egui-winit, egui, emath, epaint, epaint_default_fonts, exclude from changelog, typo"
|
||||
labels: "CI, dependencies, docs and examples, ecolor, eframe, egui_extras, egui_glow, egui_inspection, egui_kittest, egui_system_fonts, egui-wgpu, egui-winit, egui, emath, epaint, epaint_default_fonts, exclude from changelog, typo"
|
||||
+102
-4
@@ -1256,6 +1256,7 @@ dependencies = [
|
||||
"egui-winit",
|
||||
"egui_glow",
|
||||
"egui_inspection",
|
||||
"egui_system_fonts",
|
||||
"glow",
|
||||
"glutin",
|
||||
"glutin-winit",
|
||||
@@ -1461,6 +1462,20 @@ dependencies = [
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "egui_system_fonts"
|
||||
version = "0.36.1"
|
||||
dependencies = [
|
||||
"egui",
|
||||
"epaint",
|
||||
"fontique",
|
||||
"log",
|
||||
"poll-promise",
|
||||
"skrifa",
|
||||
"sys-locale",
|
||||
"unicode-script",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "egui_tests"
|
||||
version = "0.36.1"
|
||||
@@ -1804,7 +1819,7 @@ version = "0.5.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bbc773e24e02d4ddd8395fd30dc147524273a83e54e0f312d986ea30de5f5646"
|
||||
dependencies = [
|
||||
"roxmltree",
|
||||
"roxmltree 0.20.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1820,6 +1835,28 @@ dependencies = [
|
||||
"ttf-parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fontique"
|
||||
version = "0.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6688bc1294fe7117d788937b6c53480169b29c566954af490830d4c09da9516a"
|
||||
dependencies = [
|
||||
"hashbrown 0.17.1",
|
||||
"linebender_resource_handle",
|
||||
"memmap2",
|
||||
"objc2 0.6.4",
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-text",
|
||||
"objc2-foundation 0.3.2",
|
||||
"parlance",
|
||||
"read-fonts",
|
||||
"roxmltree 0.21.1",
|
||||
"smallvec",
|
||||
"windows",
|
||||
"windows-core",
|
||||
"yeslogic-fontconfig-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "foreign-types"
|
||||
version = "0.5.0"
|
||||
@@ -2003,6 +2040,7 @@ dependencies = [
|
||||
"hashbrown 0.17.1",
|
||||
"log",
|
||||
"peniko",
|
||||
"png 0.18.1",
|
||||
"skrifa",
|
||||
"smallvec",
|
||||
"vello_common",
|
||||
@@ -2334,7 +2372,7 @@ dependencies = [
|
||||
"gif",
|
||||
"image-webp",
|
||||
"num-traits",
|
||||
"png",
|
||||
"png 0.17.16",
|
||||
"tiff",
|
||||
"zune-core",
|
||||
"zune-jpeg",
|
||||
@@ -3059,6 +3097,16 @@ dependencies = [
|
||||
"objc2-foundation 0.2.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-core-text"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d"
|
||||
dependencies = [
|
||||
"bitflags 2.13.1",
|
||||
"objc2-core-foundation",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-encode"
|
||||
version = "4.1.0"
|
||||
@@ -3351,6 +3399,12 @@ dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "parlance"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4b6937eda350acc1a5d05872c3cbf99fe78619c269096e2be3d4a350058639d5"
|
||||
|
||||
[[package]]
|
||||
name = "peniko"
|
||||
version = "0.6.1"
|
||||
@@ -3548,6 +3602,19 @@ dependencies = [
|
||||
"miniz_oxide",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "png"
|
||||
version = "0.18.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"
|
||||
dependencies = [
|
||||
"bitflags 2.13.1",
|
||||
"crc32fast",
|
||||
"fdeflate",
|
||||
"flate2",
|
||||
"miniz_oxide",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "poll-promise"
|
||||
version = "0.3.0"
|
||||
@@ -4039,6 +4106,15 @@ version = "0.20.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97"
|
||||
|
||||
[[package]]
|
||||
name = "roxmltree"
|
||||
version = "0.21.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f1964b10c76125c36f8afe190065a4bf9a87bf324842c05701330bba9f1cacbb"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustc-demangle"
|
||||
version = "0.1.27"
|
||||
@@ -4547,6 +4623,15 @@ dependencies = [
|
||||
"yaml-rust",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sys-locale"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8eab9a99a024a169fe8a903cf9d4a3b3601109bcc13bd9e3c6fff259138626c4"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tempfile"
|
||||
version = "3.27.0"
|
||||
@@ -4710,7 +4795,7 @@ dependencies = [
|
||||
"bytemuck",
|
||||
"cfg-if",
|
||||
"log",
|
||||
"png",
|
||||
"png 0.17.16",
|
||||
"tiny-skia-path",
|
||||
]
|
||||
|
||||
@@ -5037,7 +5122,7 @@ dependencies = [
|
||||
"kurbo 0.11.3",
|
||||
"log",
|
||||
"pico-args",
|
||||
"roxmltree",
|
||||
"roxmltree 0.20.0",
|
||||
"rustybuzz",
|
||||
"simplecss",
|
||||
"siphasher",
|
||||
@@ -5090,6 +5175,7 @@ dependencies = [
|
||||
"guillotiere",
|
||||
"log",
|
||||
"peniko",
|
||||
"png 0.18.1",
|
||||
"smallvec",
|
||||
"thiserror 2.0.18",
|
||||
]
|
||||
@@ -5103,6 +5189,7 @@ dependencies = [
|
||||
"bytemuck",
|
||||
"glifo",
|
||||
"hashbrown 0.17.1",
|
||||
"png 0.18.1",
|
||||
"vello_common",
|
||||
]
|
||||
|
||||
@@ -5913,6 +6000,17 @@ dependencies = [
|
||||
"linked-hash-map",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "yeslogic-fontconfig-sys"
|
||||
version = "6.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1d8b8abf912b9a29ff112e1671c97c33636903d13a69712037190e6805af4f76"
|
||||
dependencies = [
|
||||
"dlib",
|
||||
"once_cell",
|
||||
"pkg-config",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "yoke"
|
||||
version = "0.8.3"
|
||||
|
||||
@@ -8,6 +8,7 @@ members = [
|
||||
"crates/egui_glow",
|
||||
"crates/egui_inspection",
|
||||
"crates/egui_kittest",
|
||||
"crates/egui_system_fonts",
|
||||
"crates/egui-wgpu",
|
||||
"crates/egui-winit",
|
||||
"crates/egui",
|
||||
@@ -68,6 +69,7 @@ egui_demo_lib = { version = "0.36.1", path = "crates/egui_demo_lib", default-fea
|
||||
egui_glow = { version = "0.36.1", path = "crates/egui_glow", default-features = false }
|
||||
egui_inspection = { version = "0.36.1", path = "crates/egui_inspection", default-features = false }
|
||||
egui_kittest = { version = "0.36.1", path = "crates/egui_kittest", default-features = false }
|
||||
egui_system_fonts = { version = "0.36.1", path = "crates/egui_system_fonts", default-features = false }
|
||||
eframe = { version = "0.36.1", path = "crates/eframe", default-features = false }
|
||||
|
||||
accesskit = "0.24.1"
|
||||
@@ -92,6 +94,10 @@ ehttp = { version = "0.7.1", default-features = false }
|
||||
enum-map = "2.7" # Can't update to 3.1: its `enum-map-derive` moved to syn 3, duplicating the syn 2 that most other proc-macro crates still use
|
||||
env_logger = { version = "0.11.8", default-features = false } # 0.11.9+ pulls env_filter 1.x/2.x, duplicating the 0.1.x that android_logger needs
|
||||
font-types = { version = "0.12.2", default-features = false, features = ["std"] }
|
||||
fontique = { version = "0.11.1", default-features = false, features = [
|
||||
"system",
|
||||
"fontconfig-dlopen", # Load libfontconfig at runtime, so builds don't need its headers
|
||||
] }
|
||||
glow = "0.17.0" # Can't update to 0.18: wgpu 30's wgpu-hal pins glow 0.17, so bumping splits it into two versions
|
||||
glutin = { version = "0.32.3", default-features = false }
|
||||
glutin-winit = { version = "0.5.0", default-features = false }
|
||||
@@ -138,6 +144,7 @@ smallvec = "1.15"
|
||||
smithay-clipboard = "0.7.2" # 0.7.3 pulls smithay-client-toolkit 0.20 (calloop 0.14), duplicating the 0.19/0.13 that winit 0.30 needs
|
||||
static_assertions = "1.1"
|
||||
syntect = { version = "5.3", default-features = false }
|
||||
sys-locale = "0.3.2"
|
||||
tempfile = "3.27"
|
||||
thiserror = "2.0" # Held at 2.0.18 in `Cargo.lock`: `thiserror-impl` 2.0.19 moved to syn 3, duplicating the syn 2 that most other proc-macro crates still use
|
||||
tokio = "1.53"
|
||||
@@ -146,6 +153,7 @@ 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-script = "0.5.8"
|
||||
unicode-segmentation = "1.13"
|
||||
vello_cpu = { version = "0.2.0", default-features = false, features = [
|
||||
"std",
|
||||
|
||||
@@ -29,6 +29,7 @@ default = [
|
||||
"accesskit",
|
||||
"default_fonts",
|
||||
"links",
|
||||
"system_fonts",
|
||||
"wayland", # Required for Linux support (including CI!)
|
||||
"web_screen_reader",
|
||||
"wgpu",
|
||||
@@ -80,6 +81,11 @@ wayland = [
|
||||
"glutin-winit?/wayland",
|
||||
]
|
||||
|
||||
## Load system fonts on demand for characters that the installed fonts lack (native only).
|
||||
##
|
||||
## Turn it off at runtime with [`NativeOptions::system_font_fallback`].
|
||||
system_fonts = ["dep:egui_system_fonts"]
|
||||
|
||||
## Enable screen reader support (requires `ctx.options_mut(|o| o.screen_reader = true);`) on web.
|
||||
##
|
||||
## For other platforms, use the `accesskit` feature instead.
|
||||
@@ -160,6 +166,7 @@ image = { workspace = true, features = ["png"] } # Needed for app icon
|
||||
winit = { workspace = true, default-features = false, features = ["rwh_06"] }
|
||||
|
||||
# optional native:
|
||||
egui_system_fonts = { workspace = true, optional = true }
|
||||
egui-wgpu = { workspace = true, optional = true, features = [
|
||||
"winit",
|
||||
"capture",
|
||||
|
||||
@@ -378,6 +378,15 @@ pub struct NativeOptions {
|
||||
/// persisted (only if the "persistence" feature is enabled).
|
||||
pub persist_window: bool,
|
||||
|
||||
/// Load system fonts on demand for characters that the installed fonts lack,
|
||||
/// e.g. CJK, Arabic, or Devanagari (only if the `system_fonts` feature is enabled).
|
||||
///
|
||||
/// Turn this off if you bundle fonts that cover everything your app shows,
|
||||
/// or if you need identical text rendering on all machines.
|
||||
///
|
||||
/// Default: `true`.
|
||||
pub system_font_fallback: bool,
|
||||
|
||||
/// The folder where `eframe` will store the app state. If not set, eframe will use a default
|
||||
/// data storage path for each target system.
|
||||
pub persistence_path: Option<std::path::PathBuf>,
|
||||
@@ -462,6 +471,8 @@ impl Default for NativeOptions {
|
||||
|
||||
persist_window: true,
|
||||
|
||||
system_font_fallback: true,
|
||||
|
||||
persistence_path: None,
|
||||
|
||||
dithering: true,
|
||||
|
||||
@@ -217,6 +217,11 @@ impl EpiIntegration {
|
||||
Some(icon),
|
||||
);
|
||||
|
||||
#[cfg(feature = "system_fonts")]
|
||||
if native_options.system_font_fallback {
|
||||
egui_ctx.add_font_provider(Arc::new(egui_system_fonts::SystemFontProvider::new()));
|
||||
}
|
||||
|
||||
Self {
|
||||
frame,
|
||||
last_auto_save: Instant::now(),
|
||||
|
||||
@@ -8,8 +8,8 @@ use core::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
|
||||
use egui::{
|
||||
ColorImage, GlyphRasterizer, GlyphRasterizerRequest, MAX_GLYPH_SIZE, RasterizedGlyph,
|
||||
has_emoji_presentation, vec2,
|
||||
ColorImage, GlyphBitmap, GlyphRasterizer, GlyphRasterizerRequest, MAX_GLYPH_SIZE,
|
||||
RasterizedGlyph, has_emoji_presentation, vec2,
|
||||
};
|
||||
use wasm_bindgen::JsCast as _;
|
||||
use web_sys::{CanvasRenderingContext2d, HtmlCanvasElement};
|
||||
@@ -108,12 +108,14 @@ impl CanvasGlyphs {
|
||||
} = 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),
|
||||
bitmap: GlyphBitmap {
|
||||
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),
|
||||
is_color,
|
||||
},
|
||||
advance_px: advance as f32,
|
||||
is_color,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -54,6 +54,14 @@ experimental = []
|
||||
## [`mint`](https://docs.rs/mint) enables interoperability with other math libraries such as [`glam`](https://docs.rs/glam) and [`nalgebra`](https://docs.rs/nalgebra).
|
||||
mint = ["epaint/mint"]
|
||||
|
||||
## Bundle the monochrome emoji fonts `NotoEmoji-Regular` and `emoji-icon-font`,
|
||||
## and put them in the default [`FontDefinitions`].
|
||||
##
|
||||
## They add about 1 MB to the binary, and are only needed if you want the same
|
||||
## (monochrome) emoji on every platform, instead of the platform's own color emoji
|
||||
## (see [`GlyphRasterizer`] and [`FontProvider`]).
|
||||
monochrome_emoji_fonts = ["default_fonts", "epaint/monochrome_emoji_fonts"]
|
||||
|
||||
## Enable persistence of memory (window positions etc).
|
||||
persistence = ["serde", "epaint/serde", "ron"]
|
||||
|
||||
|
||||
+34
-28
@@ -16,13 +16,12 @@ use epaint::{
|
||||
};
|
||||
|
||||
use crate::{
|
||||
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,
|
||||
Align2, CursorIcon, DeferredViewportUiCallback, FontDefinitions, FontProvider, GlyphRasterizer,
|
||||
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,
|
||||
@@ -377,7 +376,7 @@ struct ContextImpl {
|
||||
fonts: Option<Fonts>,
|
||||
font_definitions: FontDefinitions,
|
||||
glyph_rasterizer: Option<GlyphRasterizer>,
|
||||
glyph_source_preference: Option<GlyphSourcePreference>,
|
||||
font_providers: Vec<Arc<dyn FontProvider>>,
|
||||
|
||||
memory: Memory,
|
||||
animation_manager: AnimationManager,
|
||||
@@ -594,14 +593,11 @@ impl ContextImpl {
|
||||
|
||||
is_new = true;
|
||||
profiling::scope!("Fonts::new");
|
||||
let mut fonts = Fonts::new(text_options, self.font_definitions.clone());
|
||||
let mut fonts = Fonts::new(text_options, self.font_definitions.clone())
|
||||
.with_font_providers(self.font_providers.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
|
||||
});
|
||||
|
||||
@@ -774,8 +770,8 @@ 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).
|
||||
/// It is used for grapheme clusters that no installed font can render,
|
||||
/// and that no [`FontProvider`] has a font for.
|
||||
///
|
||||
/// `eframe` sets this on web. Pass `None` to only use the installed fonts.
|
||||
pub fn set_glyph_rasterizer(&self, glyph_rasterizer: Option<GlyphRasterizer>) {
|
||||
@@ -785,19 +781,25 @@ impl Context {
|
||||
});
|
||||
}
|
||||
|
||||
/// 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).
|
||||
/// Add a [`FontProvider`], asked for fonts for characters that no installed font has.
|
||||
///
|
||||
/// 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.
|
||||
/// Fonts it finds are appended to the fallback chain of the requested font family.
|
||||
/// Providers are asked in the order they were added.
|
||||
///
|
||||
/// See [`GlyphSourcePreference`].
|
||||
pub fn set_glyph_source_preference(
|
||||
&self,
|
||||
prefer: impl Fn(&str) -> GlyphSource + Send + Sync + 'static,
|
||||
) {
|
||||
/// `eframe` adds a system font provider on native (see its `system_fonts` feature).
|
||||
pub fn add_font_provider(&self, font_provider: Arc<dyn FontProvider>) {
|
||||
self.write(|ctx| {
|
||||
ctx.glyph_source_preference = Some(Arc::new(prefer));
|
||||
ctx.font_providers.push(font_provider);
|
||||
ctx.fonts = None;
|
||||
});
|
||||
}
|
||||
|
||||
/// Replace all [`FontProvider`]s. See [`Self::add_font_provider`].
|
||||
///
|
||||
/// Pass an empty list to only use the installed fonts.
|
||||
pub fn set_font_providers(&self, font_providers: Vec<Arc<dyn FontProvider>>) {
|
||||
self.write(|ctx| {
|
||||
ctx.font_providers = font_providers;
|
||||
ctx.fonts = None;
|
||||
});
|
||||
}
|
||||
@@ -2196,6 +2198,8 @@ impl Context {
|
||||
///
|
||||
/// The new fonts will become active at the start of the next pass.
|
||||
/// This will overwrite the existing fonts.
|
||||
///
|
||||
/// These fonts will be used before any system fallback.
|
||||
pub fn set_fonts(&self, font_definitions: FontDefinitions) {
|
||||
profiling::function_scope!();
|
||||
|
||||
@@ -2212,13 +2216,15 @@ impl Context {
|
||||
}
|
||||
}
|
||||
|
||||
/// Tell `egui` which fonts to use.
|
||||
/// Add an additional font to `egui`.
|
||||
///
|
||||
/// The default `egui` fonts only support latin and cyrillic alphabets,
|
||||
/// but you can call this to install additional fonts that support e.g. korean characters.
|
||||
///
|
||||
/// The new font will become active at the start of the next pass.
|
||||
/// This will keep the existing fonts.
|
||||
///
|
||||
/// This font will be used before any system fallback.
|
||||
pub fn add_font(&self, new_font: FontInsert) {
|
||||
profiling::function_scope!();
|
||||
|
||||
@@ -3561,13 +3567,13 @@ impl Context {
|
||||
paint_stats.ui(ui);
|
||||
});
|
||||
|
||||
CollapsingHeader::new("🖼 Textures")
|
||||
CollapsingHeader::new("🖼️ Textures")
|
||||
.default_open(false)
|
||||
.show(ui, |ui| {
|
||||
self.texture_ui(ui);
|
||||
});
|
||||
|
||||
CollapsingHeader::new("🖼 Image loaders")
|
||||
CollapsingHeader::new("🖼️ Image loaders")
|
||||
.default_open(false)
|
||||
.show(ui, |ui| {
|
||||
self.loaders_ui(ui);
|
||||
|
||||
@@ -1603,7 +1603,7 @@ impl InputState {
|
||||
|
||||
ui.collapsing("Raw Input", |ui| raw.ui(ui));
|
||||
|
||||
crate::containers::CollapsingHeader::new("🖱 Pointer")
|
||||
crate::containers::CollapsingHeader::new("🖱️ Pointer")
|
||||
.default_open(false)
|
||||
.show(ui, |ui| {
|
||||
pointer.ui(ui);
|
||||
@@ -1615,7 +1615,7 @@ impl InputState {
|
||||
});
|
||||
}
|
||||
|
||||
crate::containers::CollapsingHeader::new("⬍ Scroll")
|
||||
crate::containers::CollapsingHeader::new("↕️ Scroll")
|
||||
.default_open(false)
|
||||
.show(ui, |ui| {
|
||||
wheel.ui(ui);
|
||||
|
||||
+8
-44
@@ -453,9 +453,9 @@ 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, GlyphRasterizer,
|
||||
GlyphRasterizerRequest, GlyphSource, GlyphSourcePreference, MAX_GLYPH_SIZE,
|
||||
RasterizedGlyph, default_glyph_source, has_emoji_presentation,
|
||||
FallbackRequest, FontData, FontDefinitions, FontFamily, FontId, FontInsert, FontPriority,
|
||||
FontProvider, FontTweak, GlyphBitmap, GlyphRasterizer, GlyphRasterizerRequest,
|
||||
InsertFontFamily, MAX_GLYPH_SIZE, RasterizedGlyph, has_emoji_presentation,
|
||||
},
|
||||
textures::{TextureFilter, TextureOptions, TextureWrapMode, TexturesDelta},
|
||||
};
|
||||
@@ -511,7 +511,7 @@ pub use self::{
|
||||
pub fn warn_if_debug_build(ui: &mut crate::Ui) {
|
||||
if cfg!(debug_assertions) {
|
||||
ui.label(
|
||||
RichText::new("⚠ Debug build ⚠")
|
||||
RichText::new("⚠️ Debug build ⚠️")
|
||||
.small()
|
||||
.color(ui.visuals().warn_fg_color),
|
||||
)
|
||||
@@ -585,46 +585,10 @@ macro_rules! github_link_file {
|
||||
/// The minus character: <https://www.compart.com/en/unicode/U+2212>
|
||||
pub(crate) const MINUS_CHAR_STR: &str = "−";
|
||||
|
||||
/// The default egui fonts supports around 1216 emojis in total.
|
||||
/// Here are some of the most useful:
|
||||
/// ∞⊗⎗⎘⎙⏏⏴⏵⏶⏷
|
||||
/// ⏩⏪⏭⏮⏸⏹⏺■▶📾🔀🔁🔃
|
||||
/// ☀☁★☆☐☑☜☝☞☟⛃⛶✔
|
||||
/// ↺↻⟲⟳⬅➡⬆⬇⬈⬉⬊⬋⬌⬍⮨⮩⮪⮫
|
||||
/// ♡
|
||||
/// 📅📆
|
||||
/// 📈📉📊
|
||||
/// 📋📌📎📤📥🔆
|
||||
/// 🔈🔉🔊🔍🔎🔗🔘
|
||||
/// 🕓🖧🖩🖮🖱🖴🖵🖼🗀🗁🗋🗐🗑🗙🚫❓
|
||||
///
|
||||
/// NOTE: In egui all emojis are monochrome!
|
||||
///
|
||||
/// You can explore them all in the Font Book in [the online demo](https://www.egui.rs/#demo).
|
||||
///
|
||||
/// In addition, egui supports a few special emojis that are not part of the unicode standard.
|
||||
/// This module contains some of them:
|
||||
pub mod special_emojis {
|
||||
/// Tux, the Linux penguin.
|
||||
pub const OS_LINUX: char = '🐧';
|
||||
|
||||
/// The Windows logo.
|
||||
pub const OS_WINDOWS: char = '';
|
||||
|
||||
/// The Android logo.
|
||||
pub const OS_ANDROID: char = '';
|
||||
|
||||
/// The Apple logo.
|
||||
pub const OS_APPLE: char = '';
|
||||
|
||||
/// The Github logo.
|
||||
pub const GITHUB: char = '';
|
||||
|
||||
/// The word `git`.
|
||||
pub const GIT: char = '';
|
||||
|
||||
// I really would like to have ferris here.
|
||||
}
|
||||
/// A few special emojis that are not part of the unicode standard,
|
||||
/// plus a list of the emojis in the default fonts.
|
||||
#[cfg(feature = "default_fonts")]
|
||||
pub use epaint::special_emojis;
|
||||
|
||||
/// The different types of built-in widgets in egui
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
|
||||
@@ -410,7 +410,7 @@ impl Options {
|
||||
use crate::Widget as _;
|
||||
use crate::containers::CollapsingHeader;
|
||||
|
||||
CollapsingHeader::new("⚙ Options")
|
||||
CollapsingHeader::new("⚙️ Options")
|
||||
.default_open(false)
|
||||
.show(ui, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
@@ -452,7 +452,7 @@ impl Options {
|
||||
style.ui(ui);
|
||||
});
|
||||
|
||||
CollapsingHeader::new("✒ Painting")
|
||||
CollapsingHeader::new("✒️ Painting")
|
||||
.default_open(false)
|
||||
.show(ui, |ui| {
|
||||
tessellation_options.ui(ui);
|
||||
@@ -461,7 +461,7 @@ impl Options {
|
||||
});
|
||||
});
|
||||
|
||||
CollapsingHeader::new("🖱 Input")
|
||||
CollapsingHeader::new("🖱️ Input")
|
||||
.default_open(false)
|
||||
.show(ui, |ui| {
|
||||
input_options.ui(ui);
|
||||
|
||||
@@ -42,7 +42,7 @@ impl Theme {
|
||||
#![expect(clippy::collapsible_else_if)]
|
||||
if self == Self::Dark {
|
||||
if ui
|
||||
.add(Button::new("☀").frame(false))
|
||||
.add(Button::new("☀️").frame(false))
|
||||
.on_hover_text("Switch to light mode")
|
||||
.clicked()
|
||||
{
|
||||
@@ -90,7 +90,7 @@ impl ThemePreference {
|
||||
pub fn icon(self) -> &'static str {
|
||||
match self {
|
||||
Self::Dark => "🌙",
|
||||
Self::Light => "☀",
|
||||
Self::Light => "☀️",
|
||||
Self::System => "💻",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1901,7 +1901,7 @@ impl Style {
|
||||
|
||||
ui.collapsing("🔠 Text styles", |ui| text_styles_ui(ui, text_styles));
|
||||
ui.collapsing("📏 Spacing", |ui| spacing.ui(ui));
|
||||
ui.collapsing("☝ Interaction", |ui| interaction.ui(ui));
|
||||
ui.collapsing("☝️ Interaction", |ui| interaction.ui(ui));
|
||||
ui.collapsing("🎨 Visuals", |ui| visuals.ui(ui));
|
||||
ui.collapsing("🔄 Scroll animation", |ui| scroll_animation.ui(ui));
|
||||
|
||||
|
||||
@@ -683,7 +683,7 @@ pub fn paint_texture_load_result(
|
||||
..Default::default()
|
||||
};
|
||||
job.append(
|
||||
"⚠",
|
||||
"⚠️",
|
||||
0.0,
|
||||
TextFormat::simple(font_id.clone(), ui.visuals().error_fg_color),
|
||||
);
|
||||
|
||||
@@ -86,4 +86,6 @@ wasm-bindgen-futures.workspace = true
|
||||
web-sys.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
# `monochrome_emoji_fonts` so that the snapshots keep their emoji:
|
||||
egui = { workspace = true, features = ["default_fonts", "monochrome_emoji_fonts"] }
|
||||
egui_kittest = { workspace = true, features = ["eframe", "snapshot", "wgpu"] }
|
||||
@@ -55,7 +55,7 @@ impl crate::DemoApp for ImageViewer {
|
||||
let label = ui.label("URI:");
|
||||
ui.text_edit_singleline(&mut self.uri_edit_text)
|
||||
.labelled_by(label.id);
|
||||
if ui.small_button("✔").clicked() {
|
||||
if ui.small_button("✔️").clicked() {
|
||||
ui.ctx().forget_image(&self.current_uri);
|
||||
self.uri_edit_text = self.uri_edit_text.trim().to_owned();
|
||||
self.current_uri = self.uri_edit_text.clone();
|
||||
|
||||
@@ -328,7 +328,7 @@ fn integration_ui(ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
|
||||
{
|
||||
let mut fullscreen = ui.input(|i| i.viewport().fullscreen.unwrap_or(false));
|
||||
if ui
|
||||
.checkbox(&mut fullscreen, "🗖 Fullscreen (F11)")
|
||||
.checkbox(&mut fullscreen, "🔳 Fullscreen (F11)")
|
||||
.on_hover_text("Fullscreen the window")
|
||||
.changed()
|
||||
{
|
||||
@@ -349,12 +349,12 @@ fn integration_ui(ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
|
||||
ui.selectable_value(
|
||||
&mut size,
|
||||
Some(egui::vec2(1280.0, 720.0)),
|
||||
"🖥 Desktop 720p",
|
||||
"🖥️ Desktop 720p",
|
||||
);
|
||||
ui.selectable_value(
|
||||
&mut size,
|
||||
Some(egui::vec2(1920.0, 1080.0)),
|
||||
"🖥 Desktop 1080p",
|
||||
"🖥️ Desktop 1080p",
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -226,13 +226,13 @@ impl WrapApp {
|
||||
),
|
||||
#[cfg(feature = "easymark")]
|
||||
(
|
||||
"🖹 EasyMark editor",
|
||||
"📝 EasyMark editor",
|
||||
Anchor::EasyMarkEditor,
|
||||
&mut self.state.easy_mark_editor as &mut dyn DemoApp,
|
||||
),
|
||||
#[cfg(feature = "http")]
|
||||
(
|
||||
"⬇ HTTP",
|
||||
"⬇️ HTTP",
|
||||
Anchor::Http,
|
||||
&mut self.state.http as &mut dyn DemoApp,
|
||||
),
|
||||
@@ -243,7 +243,7 @@ impl WrapApp {
|
||||
),
|
||||
#[cfg(feature = "image_viewer")]
|
||||
(
|
||||
"🖼 Image Viewer",
|
||||
"🖼️ Image Viewer",
|
||||
Anchor::ImageViewer,
|
||||
&mut self.state.image_viewer as &mut dyn DemoApp,
|
||||
),
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:7311e37b40ecf968be90d7f36ed5ee7316f2b46b1d308a6c2d922e179a1ac5ba
|
||||
size 335131
|
||||
oid sha256:44dc55002e51c8596a05fdc3e82c5249739db92ed9acf41b015d7e538b085bb8
|
||||
size 335296
|
||||
@@ -1,3 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:a11b9020bfd5c6f786c35399c463c41bdd97b68465bf11527dc76879ae105efe
|
||||
size 93101
|
||||
oid sha256:ec2b816a26cb6f193183db87ff9a38bc1e6330c2c9ac9ff958b076813c3b8124
|
||||
size 93379
|
||||
@@ -1,3 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:e11107b7e87e542ec8c7a18be35000db35830dfb01f88e2d2d579fab514f47e4
|
||||
size 168933
|
||||
oid sha256:9635c77760d0dc61fa43d3312b78e8293ce5d265266256c4fbbf2a53811a29fd
|
||||
size 169102
|
||||
@@ -1,3 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:935f309ffb3244a58c8dfbf7120498c52361cf9befcbca85d668afe080d8537e
|
||||
size 101599
|
||||
oid sha256:a0aa0dc62ae2ebefc2e920361c39fa51202ac5354346386baa1222c34ee96a39
|
||||
size 101872
|
||||
@@ -61,7 +61,7 @@ fn test_demo_app() {
|
||||
.get_by_role_and_label(Role::TextInput, "URI:")
|
||||
.type_text("file://../eframe/data/icon.png");
|
||||
|
||||
harness.get_by_role_and_label(Role::Button, "✔").click();
|
||||
harness.get_by_role_and_label(Role::Button, "✔️").click();
|
||||
|
||||
// Wait for the image to load
|
||||
harness.try_run_realtime().ok();
|
||||
|
||||
@@ -54,7 +54,8 @@ serde = { workspace = true, optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
criterion.workspace = true
|
||||
egui = { workspace = true, features = ["default_fonts"] }
|
||||
# `monochrome_emoji_fonts` so that the snapshots of the demos keep their emoji:
|
||||
egui = { workspace = true, features = ["default_fonts", "monochrome_emoji_fonts"] }
|
||||
egui_extras = { workspace = true, features = ["image", "svg"] }
|
||||
egui_kittest = { workspace = true, features = ["wgpu", "snapshot"] }
|
||||
image = { workspace = true, features = ["png"] }
|
||||
|
||||
@@ -38,9 +38,8 @@ impl crate::View for About {
|
||||
});
|
||||
|
||||
ui.label(format!(
|
||||
"egui is an immediate mode GUI library written in Rust. egui runs natively on {}{}{}, and \
|
||||
"egui is an immediate mode GUI library written in Rust. egui runs natively on {OS_APPLE}{OS_LINUX}{OS_WINDOWS}, and \
|
||||
on the web it is compiled to WebAssembly and rendered with WebGL or WebGPU.{}",
|
||||
OS_APPLE, OS_LINUX, OS_WINDOWS,
|
||||
if cfg!(target_arch = "wasm32") {
|
||||
" Everything you see is rendered as textured triangles. There is no DOM, HTML, JS or CSS. Just Rust."
|
||||
} else {""}
|
||||
@@ -115,5 +114,5 @@ fn links(ui: &mut egui::Ui) {
|
||||
"@ernerfeldt.bsky.social",
|
||||
"https://bsky.app/profile/ernerfeldt.bsky.social",
|
||||
);
|
||||
ui.hyperlink_to("📓 egui documentation", "https://docs.rs/egui/");
|
||||
ui.hyperlink_to("egui documentation", "https://docs.rs/egui/");
|
||||
}
|
||||
@@ -23,7 +23,7 @@ fn main() {\n\
|
||||
|
||||
impl crate::Demo for CodeEditor {
|
||||
fn name(&self) -> &'static str {
|
||||
"🖮 Code Editor"
|
||||
"⌨️ Code Editor"
|
||||
}
|
||||
|
||||
fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) {
|
||||
|
||||
@@ -102,7 +102,7 @@ impl CodeExample {
|
||||
|
||||
impl crate::Demo for CodeExample {
|
||||
fn name(&self) -> &'static str {
|
||||
"🖮 Code Example"
|
||||
"⌨️ Code Example"
|
||||
}
|
||||
|
||||
fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) {
|
||||
|
||||
@@ -331,6 +331,7 @@ impl DemoWindows {
|
||||
if ui.button("Organize windows").clicked() {
|
||||
ui.memory_mut(|mem| mem.reset_areas());
|
||||
}
|
||||
ui.add_space(4.0);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -445,7 +446,7 @@ mod tests {
|
||||
|
||||
fn remove_leading_emoji(full_name: &str) -> &str {
|
||||
if let Some((start, name)) = full_name.split_once(' ')
|
||||
&& start.len() <= 4
|
||||
&& start.len() <= 7 // An emoji, plus an optional variation selector
|
||||
&& start.bytes().next().is_some_and(|byte| byte >= 128)
|
||||
{
|
||||
return name;
|
||||
|
||||
@@ -7,7 +7,7 @@ impl crate::Demo for ExtraViewport {
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"🗖 Extra Viewport"
|
||||
"🖥️ Extra Viewport"
|
||||
}
|
||||
|
||||
fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) {
|
||||
|
||||
@@ -45,20 +45,14 @@ impl crate::View for FontBook {
|
||||
ui.add(crate::egui_github_link_file!());
|
||||
});
|
||||
|
||||
ui.label(format!(
|
||||
"The selected font supports {} characters.",
|
||||
self.available_glyphs
|
||||
.get(&self.font_id.family)
|
||||
.map(|map| map.len())
|
||||
.unwrap_or_default()
|
||||
));
|
||||
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = 0.0;
|
||||
ui.label("You can add more characters by installing additional fonts with ");
|
||||
ui.label("On web, the browser draws missing glyphs instead. ");
|
||||
ui.label("On native, eframe falls back to looking for a matching system font. ");
|
||||
ui.label("Bundle fonts with ");
|
||||
ui.add(egui::Hyperlink::from_label_and_url(
|
||||
egui::RichText::new("Context::set_fonts").text_style(egui::TextStyle::Monospace),
|
||||
"https://docs.rs/egui/latest/egui/struct.Context.html#method.set_fonts",
|
||||
egui::RichText::new("Context::add_font").text_style(egui::TextStyle::Monospace),
|
||||
"https://docs.rs/egui/latest/egui/struct.Context.html#method.add_font",
|
||||
));
|
||||
ui.label(".");
|
||||
});
|
||||
@@ -67,6 +61,26 @@ impl crate::View for FontBook {
|
||||
|
||||
egui::introspection::font_id_ui(ui, &mut self.font_id);
|
||||
|
||||
let font_id = self.font_id.clone();
|
||||
let available_glyphs = self
|
||||
.available_glyphs
|
||||
.entry(font_id.family.clone())
|
||||
.or_insert_with(|| available_characters(ui, &font_id.family));
|
||||
|
||||
let fonts_in_family = fonts_in_family(ui, &font_id.family);
|
||||
|
||||
egui::CollapsingHeader::new(format!(
|
||||
"The selected family has {} characters, from {} fonts",
|
||||
available_glyphs.len(),
|
||||
fonts_in_family.len()
|
||||
))
|
||||
.show(ui, |ui| {
|
||||
ui.label("In fallback order:");
|
||||
for name in fonts_in_family {
|
||||
ui.label(egui::RichText::new(name).text_style(egui::TextStyle::Monospace));
|
||||
}
|
||||
});
|
||||
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Filter:");
|
||||
ui.add(egui::TextEdit::singleline(&mut self.filter).desired_width(120.0));
|
||||
@@ -77,43 +91,83 @@ impl crate::View for FontBook {
|
||||
});
|
||||
|
||||
let filter = &self.filter;
|
||||
let available_glyphs = self
|
||||
.available_glyphs
|
||||
.entry(self.font_id.family.clone())
|
||||
.or_insert_with(|| available_characters(ui, &self.font_id.family));
|
||||
|
||||
let matching_glyphs: Vec<(char, &GlyphInfo)> = available_glyphs
|
||||
.iter()
|
||||
.filter(|(chr, glyph_info)| {
|
||||
filter.is_empty() || glyph_info.name.contains(filter) || *filter == chr.to_string()
|
||||
})
|
||||
.map(|(&chr, glyph_info)| (chr, glyph_info))
|
||||
.collect();
|
||||
|
||||
ui.separator();
|
||||
|
||||
egui::ScrollArea::vertical().show(ui, |ui| {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.spacing_mut().item_spacing = egui::Vec2::splat(2.0);
|
||||
// Each glyph gets a fixed-size cell so we can calculate what is visible,
|
||||
// and only paint those glyphs.
|
||||
let spacing = egui::Vec2::splat(2.0);
|
||||
let cell_size = egui::Vec2::splat((1.5 * font_id.size).round());
|
||||
|
||||
for (&chr, glyph_info) in available_glyphs.iter() {
|
||||
if filter.is_empty()
|
||||
|| glyph_info.name.contains(filter)
|
||||
|| *filter == chr.to_string()
|
||||
{
|
||||
let button = egui::Button::new(
|
||||
egui::RichText::new(chr.to_string()).font(self.font_id.clone()),
|
||||
)
|
||||
.frame(false);
|
||||
let num_columns = ((ui.available_width() + spacing.x) / (cell_size.x + spacing.x)).floor();
|
||||
let num_columns = (num_columns as usize).max(1);
|
||||
let num_rows = matching_glyphs.len().div_ceil(num_columns);
|
||||
|
||||
let tooltip_ui = |ui: &mut egui::Ui| {
|
||||
let font_id = self.font_id.clone();
|
||||
egui::ScrollArea::vertical().auto_shrink(false).show_rows(
|
||||
ui,
|
||||
cell_size.y + spacing.y,
|
||||
num_rows,
|
||||
|ui, rows| {
|
||||
ui.spacing_mut().item_spacing = spacing;
|
||||
|
||||
char_info_ui(ui, chr, glyph_info, font_id);
|
||||
};
|
||||
for row in rows {
|
||||
ui.horizontal(|ui| {
|
||||
let start = row * num_columns;
|
||||
let end = (start + num_columns).min(matching_glyphs.len());
|
||||
for &(chr, glyph_info) in &matching_glyphs[start..end] {
|
||||
let button =
|
||||
egui::Button::new(egui::RichText::new(chr).font(font_id.clone()))
|
||||
.frame(false);
|
||||
|
||||
if ui.add(button).on_hover_ui(tooltip_ui).clicked() {
|
||||
ui.copy_text(chr.to_string());
|
||||
let tooltip_ui = |ui: &mut egui::Ui| {
|
||||
char_info_ui(ui, chr, glyph_info, font_id.clone());
|
||||
};
|
||||
|
||||
if ui
|
||||
.add_sized(cell_size, button)
|
||||
.on_hover_ui(tooltip_ui)
|
||||
.clicked()
|
||||
{
|
||||
ui.copy_text(chr.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn fonts_in_family(ui: &egui::Ui, family: &egui::FontFamily) -> Vec<String> {
|
||||
ui.fonts(|fonts| {
|
||||
let mut names = fonts
|
||||
.definitions()
|
||||
.families
|
||||
.get(family)
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
|
||||
// Fonts found by a `FontProvider`, e.g. among the system fonts:
|
||||
names.extend(
|
||||
fonts
|
||||
.discovered_fonts()
|
||||
.iter()
|
||||
.filter(|font| font.families.iter().any(|insert| &insert.family == family))
|
||||
.map(|font| font.name.clone()),
|
||||
);
|
||||
|
||||
names
|
||||
})
|
||||
}
|
||||
|
||||
fn char_info_ui(ui: &mut egui::Ui, chr: char, glyph_info: &GlyphInfo, font_id: egui::FontId) {
|
||||
let resp = ui.label(egui::RichText::new(chr.to_string()).font(font_id));
|
||||
|
||||
|
||||
@@ -237,7 +237,7 @@ fn label_ui(ui: &mut egui::Ui) {
|
||||
let _ = ui.small_button("this button");
|
||||
ui.label(".");
|
||||
|
||||
ui.label("The default font supports all latin and cyrillic characters (ИÅđ…), common math symbols (∫√∞²⅓…), and many emojis (💓🌟🖩…).")
|
||||
ui.label("The default font supports all latin and cyrillic characters (ИÅđ…), common math symbols (∫√∞²⅓…), and many emojis (💓🌟📐…).")
|
||||
.on_hover_text("There is currently no support for right-to-left languages.");
|
||||
ui.label("See the 🔤 Font Book for more!");
|
||||
|
||||
|
||||
@@ -29,7 +29,7 @@ impl Modals {
|
||||
|
||||
impl crate::Demo for Modals {
|
||||
fn name(&self) -> &'static str {
|
||||
"🗖 Modals"
|
||||
"💭 Modals"
|
||||
}
|
||||
|
||||
fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) {
|
||||
|
||||
@@ -162,7 +162,7 @@ impl PaintBezier {
|
||||
|
||||
impl crate::Demo for PaintBezier {
|
||||
fn name(&self) -> &'static str {
|
||||
") Bézier Curve"
|
||||
"〰️ Bézier Curve"
|
||||
}
|
||||
|
||||
fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) {
|
||||
|
||||
@@ -74,7 +74,7 @@ impl Painting {
|
||||
|
||||
impl crate::Demo for Painting {
|
||||
fn name(&self) -> &'static str {
|
||||
"🖊 Painting"
|
||||
"🖊️ Painting"
|
||||
}
|
||||
|
||||
fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) {
|
||||
|
||||
@@ -20,7 +20,7 @@ impl Default for Panels {
|
||||
|
||||
impl crate::Demo for Panels {
|
||||
fn name(&self) -> &'static str {
|
||||
"🗖 Panels"
|
||||
"📰 Panels"
|
||||
}
|
||||
|
||||
fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) {
|
||||
@@ -122,10 +122,10 @@ impl crate::View for Panels {
|
||||
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Panel toggles:");
|
||||
ui.toggle_value(left, "⬅");
|
||||
ui.toggle_value(top, "⬆");
|
||||
ui.toggle_value(bottom, "⬇");
|
||||
ui.toggle_value(right, "➡");
|
||||
ui.toggle_value(left, "⬅️");
|
||||
ui.toggle_value(top, "⬆️");
|
||||
ui.toggle_value(bottom, "⬇️");
|
||||
ui.toggle_value(right, "➡️");
|
||||
});
|
||||
|
||||
ui.separator();
|
||||
|
||||
@@ -27,7 +27,7 @@ pub fn password_ui(ui: &mut egui::Ui, password: &mut String) -> egui::Response {
|
||||
let result = ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
// Toggle the `show_plaintext` bool with a button:
|
||||
let response = ui
|
||||
.selectable_label(show_plaintext, "👁")
|
||||
.selectable_label(show_plaintext, "👁️")
|
||||
.on_hover_text("Show/hide password");
|
||||
|
||||
if response.clicked() {
|
||||
|
||||
@@ -27,7 +27,7 @@ pub struct Scrolling {
|
||||
|
||||
impl crate::Demo for Scrolling {
|
||||
fn name(&self) -> &'static str {
|
||||
"↕ Scrolling"
|
||||
"↕️ Scrolling"
|
||||
}
|
||||
|
||||
fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) {
|
||||
@@ -301,10 +301,10 @@ impl crate::View for ScrollTo {
|
||||
.speed(1.0)
|
||||
.suffix("px")
|
||||
.ui(ui);
|
||||
if ui.button("⬇").clicked() {
|
||||
if ui.button("⬇️").clicked() {
|
||||
scroll_delta = Some(self.delta * Vec2::UP); // scroll down (move contents up)
|
||||
}
|
||||
if ui.button("⬆").clicked() {
|
||||
if ui.button("⬆️").clicked() {
|
||||
scroll_delta = Some(self.delta * Vec2::DOWN); // scroll up (move contents down)
|
||||
}
|
||||
});
|
||||
|
||||
@@ -40,7 +40,7 @@ impl Default for Sliders {
|
||||
|
||||
impl crate::Demo for Sliders {
|
||||
fn name(&self) -> &'static str {
|
||||
"⬌ Sliders"
|
||||
"↔️ Sliders"
|
||||
}
|
||||
|
||||
fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) {
|
||||
|
||||
@@ -186,7 +186,7 @@ impl TableDemo {
|
||||
},
|
||||
|ui| {
|
||||
self.reversed ^=
|
||||
ui.button(if self.reversed { "⬆" } else { "⬇" }).clicked();
|
||||
ui.button(if self.reversed { "⬆️" } else { "⬇️" }).clicked();
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
@@ -18,7 +18,7 @@ impl crate::Demo for WindowResizeTest {
|
||||
fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) {
|
||||
use egui::{Resize, ScrollArea, TextEdit, Window};
|
||||
|
||||
Window::new("↔ auto-sized")
|
||||
Window::new("↔️ auto-sized")
|
||||
.open(open)
|
||||
.auto_sized()
|
||||
.constrain_to(ui.available_rect_before_wrap())
|
||||
@@ -31,7 +31,7 @@ impl crate::Demo for WindowResizeTest {
|
||||
ui.heading("Resize the above area!");
|
||||
});
|
||||
|
||||
Window::new("↔ resizable + scroll")
|
||||
Window::new("↔️ resizable + scroll")
|
||||
.open(open)
|
||||
.vscroll(true)
|
||||
.resizable(true)
|
||||
@@ -45,7 +45,7 @@ impl crate::Demo for WindowResizeTest {
|
||||
lorem_ipsum(ui, crate::LOREM_IPSUM_LONG);
|
||||
});
|
||||
|
||||
Window::new("↔ resizable + embedded scroll")
|
||||
Window::new("↔️ resizable + embedded scroll")
|
||||
.open(open)
|
||||
.vscroll(false)
|
||||
.resizable(true)
|
||||
@@ -63,7 +63,7 @@ impl crate::Demo for WindowResizeTest {
|
||||
// ui.heading("Some additional text here, that should also be visible"); // this works, but messes with the resizing a bit
|
||||
});
|
||||
|
||||
Window::new("↔ resizable without scroll")
|
||||
Window::new("↔️ resizable without scroll")
|
||||
.open(open)
|
||||
.vscroll(false)
|
||||
.resizable(true)
|
||||
@@ -75,7 +75,7 @@ impl crate::Demo for WindowResizeTest {
|
||||
lorem_ipsum(ui, crate::LOREM_IPSUM);
|
||||
});
|
||||
|
||||
Window::new("↔ resizable with TextEdit")
|
||||
Window::new("↔️ resizable with TextEdit")
|
||||
.open(open)
|
||||
.vscroll(false)
|
||||
.resizable(true)
|
||||
@@ -86,7 +86,7 @@ impl crate::Demo for WindowResizeTest {
|
||||
ui.add_sized(ui.available_size(), TextEdit::multiline(&mut self.text));
|
||||
});
|
||||
|
||||
Window::new("↔ freely resized")
|
||||
Window::new("↔️ freely resized")
|
||||
.open(open)
|
||||
.vscroll(false)
|
||||
.resizable(true)
|
||||
|
||||
@@ -22,7 +22,7 @@ impl Default for TextEditDemo {
|
||||
|
||||
impl crate::Demo for TextEditDemo {
|
||||
fn name(&self) -> &'static str {
|
||||
"🖹 TextEdit"
|
||||
"✏️ TextEdit"
|
||||
}
|
||||
|
||||
fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) {
|
||||
|
||||
@@ -29,7 +29,7 @@ impl Default for TextLayoutDemo {
|
||||
|
||||
impl crate::Demo for TextLayoutDemo {
|
||||
fn name(&self) -> &'static str {
|
||||
"🖹 Text Layout"
|
||||
"📄 Text Layout"
|
||||
}
|
||||
|
||||
fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) {
|
||||
|
||||
@@ -12,7 +12,7 @@ impl Default for Tooltips {
|
||||
|
||||
impl crate::Demo for Tooltips {
|
||||
fn name(&self) -> &'static str {
|
||||
"🗖 Tooltips"
|
||||
"💬 Tooltips"
|
||||
}
|
||||
|
||||
fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) {
|
||||
|
||||
@@ -61,7 +61,7 @@ impl WidgetGallery {
|
||||
|
||||
impl crate::Demo for WidgetGallery {
|
||||
fn name(&self) -> &'static str {
|
||||
"🗄 Widget Gallery"
|
||||
"🗄️ Widget Gallery"
|
||||
}
|
||||
|
||||
fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) {
|
||||
|
||||
@@ -23,7 +23,7 @@ pub struct WindowOptions {
|
||||
impl Default for WindowOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
title: "🗖 Window Options".to_owned(),
|
||||
title: "🔲 Window Options".to_owned(),
|
||||
title_bar: true,
|
||||
closable: true,
|
||||
collapsible: true,
|
||||
@@ -42,7 +42,7 @@ impl Default for WindowOptions {
|
||||
|
||||
impl crate::Demo for WindowOptions {
|
||||
fn name(&self) -> &'static str {
|
||||
"🗖 Window Options"
|
||||
"🔲 Window Options"
|
||||
}
|
||||
|
||||
fn show(&mut self, ui: &mut egui::Ui, open: &mut bool) {
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:1bb3195aa5eb1fa7da6f6bb52eec745704e10eb82efb68d5f328f9bfa09fc2d4
|
||||
size 32538
|
||||
oid sha256:9b64acdb5117adfd9a72abd7d209aa2b735027910237a69192719fe11283f519
|
||||
size 32503
|
||||
@@ -1,3 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:b6351ddb148941f73a182e676a3be4ac5d7165c618324459d0061dbf93f213d9
|
||||
size 27023
|
||||
oid sha256:97cb0c0062e85631336514332fa9563a9f4f8a4702fb599070d37d992efae05b
|
||||
size 27214
|
||||
@@ -1,3 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:6df3c0a298d48a5f2e1b36207909e20ea545a72a97461a3ae0792d21e0554f93
|
||||
size 76567
|
||||
oid sha256:b6ff3c48abecb3776f1d4909f93adae57ed03b0d7082158b38925def8c222d90
|
||||
size 76865
|
||||
@@ -1,3 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:04f66c848c6f24607d19b809f411a9287ad45067b18da40cf48a77ff65ae9d91
|
||||
size 10875
|
||||
oid sha256:b8a6ab24302cac6ec80ac9b30354df8db96322a6f5131224eca98ccf75404b95
|
||||
size 11104
|
||||
@@ -1,3 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:611b18575d2768d40b89f28427bd987d90393e886da2a2c4e09ea6503f85acdd
|
||||
size 100303
|
||||
oid sha256:008a00f0130f3559788c5945fa3b72465d81847f43c5b1072d46f942986d0e9a
|
||||
size 55640
|
||||
@@ -1,3 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:a825dc9c62979fbb8d1ca3d441b4d9e7dbbd234b994901026f35fe7d591ff196
|
||||
size 60217
|
||||
oid sha256:c6469a1442ab031184ff19b2236ca4e041979205f47c0bb8dbf9b495c07b61de
|
||||
size 60286
|
||||
@@ -1,3 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:58d56dce5f1e9766dbfdca4ea98fb71f7062b23a0ee4b08ce7f76056513aa9a5
|
||||
size 33440
|
||||
oid sha256:3d89411d616afdb30e98051786689a97a61a76e8978547d9eada1dee5519d711
|
||||
size 33923
|
||||
@@ -1,3 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:ad81eeb593663cb26295e7fc51987b85a7084b32504e26364f54f9c2129cb790
|
||||
size 118048
|
||||
oid sha256:0dae980eb1c4fd51be7cd817b8d07a66b51a3abd7e58f5a84df221ce2184e977
|
||||
size 118965
|
||||
@@ -1,3 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:121c6d5ba129439d2d747da8e505cfff04a023c28d9a0e3aca324d77de1ef418
|
||||
size 79186
|
||||
oid sha256:9692a9e2f64a6f0288e86bd9e248a6dea54c2384d0c159d05542490ffb6738ba
|
||||
size 79979
|
||||
@@ -1,3 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:7ad81306e153798d72724e37f23a4037bf986f98e0ecbe3e8d294d23a92ef77c
|
||||
size 29975
|
||||
oid sha256:910d6d4ed7faf6376ac29380a880e25526e10421dd155664c4cd19e82dc5f669
|
||||
size 30622
|
||||
@@ -1,3 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:7bbfacbbc740729ce8729f4507c6cc155a0dcda51dd4442d3db332cf2f6fd9f1
|
||||
size 42790
|
||||
oid sha256:793b495d10b63537be6331746dead0c280efe244e37786d102b72b30126ccf81
|
||||
size 43008
|
||||
@@ -1,3 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:01493c64acb62a24d19c69579a8f8cb8e080a60747792bbbb98e1cccdfe9214f
|
||||
size 47175
|
||||
oid sha256:56ba6ff19a46375c89f94f7cf0a359fbde397ba619d67358539bd0b7382a2088
|
||||
size 47860
|
||||
@@ -1,3 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:2718c333123388c8751f461382867b0640ce7a02c220db311c06ff634e6178c1
|
||||
size 48620
|
||||
oid sha256:871bfe66576d6836784bbda58f884562721934b81791fb407d276c5c1cffc772
|
||||
size 48888
|
||||
@@ -1,3 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:a41a61cce2cda5fb9372324f915ffe2b47f68ead5e26b471ea29dfb5208695a7
|
||||
size 44600
|
||||
oid sha256:b64b2263c92680d3cb90d3e82783dfc69b8602d1e2155c778d5804dd9bd2c1bc
|
||||
size 44841
|
||||
+2
-2
@@ -1,3 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:bff8f0531d5cf92e0afe857a04705599d30e77d526091b03296e381b45f02170
|
||||
size 44488
|
||||
oid sha256:84d488c88126883a6ef8252f22d20c3d90c76c348941b207c9b2674479da6d38
|
||||
size 44756
|
||||
@@ -367,7 +367,7 @@ impl CodeTheme {
|
||||
ui.selectable_value(&mut self.dark_mode, true, "🌙 Dark theme")
|
||||
.on_hover_text("Use the dark mode theme");
|
||||
|
||||
ui.selectable_value(&mut self.dark_mode, false, "☀ Light theme")
|
||||
ui.selectable_value(&mut self.dark_mode, false, "☀️ Light theme")
|
||||
.on_hover_text("Use the light mode theme");
|
||||
});
|
||||
let current_theme_is_dark = self.is_dark();
|
||||
@@ -436,7 +436,7 @@ impl CodeTheme {
|
||||
ui.selectable_value(&mut self.dark_mode, true, "🌙 Dark theme")
|
||||
.on_hover_text("Use the dark mode theme");
|
||||
|
||||
ui.selectable_value(&mut self.dark_mode, false, "☀ Light theme")
|
||||
ui.selectable_value(&mut self.dark_mode, false, "☀️ Light theme")
|
||||
.on_hover_text("Use the light mode theme");
|
||||
});
|
||||
ui.scope(|ui| {
|
||||
|
||||
@@ -60,7 +60,8 @@ open = { workspace = true, optional = true }
|
||||
tempfile = { workspace = true, optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
egui = { workspace = true, features = ["default_fonts"] }
|
||||
# `monochrome_emoji_fonts` so that the snapshots keep their emoji:
|
||||
egui = { workspace = true, features = ["default_fonts", "monochrome_emoji_fonts"] }
|
||||
image = { workspace = true, features = ["png"] }
|
||||
egui_extras = { workspace = true, features = ["image", "http"] }
|
||||
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
# Changelog for egui_system_fonts
|
||||
All notable changes to the `egui_system_fonts` crate will be noted in this file.
|
||||
|
||||
|
||||
This file is updated upon each release.
|
||||
Changes since the last release can be found at <https://github.com/emilk/egui/compare/latest...HEAD> or by running the `scripts/generate_changelog.py` script.
|
||||
|
||||
|
||||
## Unreleased - Initial release
|
||||
@@ -0,0 +1,37 @@
|
||||
[package]
|
||||
name = "egui_system_fonts"
|
||||
version.workspace = true
|
||||
authors = ["Emil Ernerfeldt <emil.ernerfeldt@gmail.com>"]
|
||||
description = "Load system fonts on demand for characters the egui fonts lack"
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
homepage = "https://github.com/emilk/egui/tree/main/crates/egui_system_fonts"
|
||||
license.workspace = true
|
||||
readme = "README.md"
|
||||
repository = "https://github.com/emilk/egui/tree/main/crates/egui_system_fonts"
|
||||
categories = ["gui"]
|
||||
keywords = ["egui", "gui", "fonts", "text"]
|
||||
include = ["../../LICENSE-APACHE", "../../LICENSE-MIT", "**/*.rs", "Cargo.toml"]
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
rustdoc-args = ["--generate-link-to-definition"]
|
||||
|
||||
[lib]
|
||||
|
||||
|
||||
[dependencies]
|
||||
epaint = { workspace = true, features = ["color_fonts"] }
|
||||
|
||||
fontique.workspace = true
|
||||
log.workspace = true
|
||||
poll-promise.workspace = true
|
||||
skrifa.workspace = true
|
||||
sys-locale.workspace = true
|
||||
unicode-script.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
egui.workspace = true
|
||||
@@ -0,0 +1,16 @@
|
||||
# egui_system_fonts
|
||||
|
||||
[](https://crates.io/crates/egui_system_fonts)
|
||||
[](https://docs.rs/egui_system_fonts)
|
||||
|
||||
Load system fonts on demand for characters that the fonts installed in [egui](https://github.com/emilk/egui) lack.
|
||||
|
||||
The default egui fonts cover Latin, Greek, and Cyrillic. When egui is asked to render e.g. Japanese, Arabic, or Devanagari, it draws `◻`. `egui_system_fonts` provides a [`SystemFontProvider`] that asks the operating system for a font that covers the character, using the same font fallback as native apps (CoreText, DirectWrite, fontconfig, or Android's `fonts.xml`, via [`fontique`](https://crates.io/crates/fontique)). The font file is memory-mapped and installed as a fallback font in egui.
|
||||
|
||||
`eframe` installs it on native by default (feature `system_fonts`). Other integrations can add it themselves:
|
||||
|
||||
```rust
|
||||
egui_ctx.add_font_provider(std::sync::Arc::new(egui_system_fonts::SystemFontProvider::new()));
|
||||
```
|
||||
|
||||
System emoji fonts are skipped for now, since they contain bitmaps or color glyphs that epaint cannot render yet.
|
||||
@@ -0,0 +1,261 @@
|
||||
//! Load system fonts on demand for characters that the fonts installed in egui lack.
|
||||
//!
|
||||
//! [`SystemFontProvider`] is an [`epaint::text::FontProvider`] backed by [`fontique`],
|
||||
//! which uses the operating system's own font fallback (CoreText, DirectWrite, fontconfig,
|
||||
//! or Android's `fonts.xml`) to find an installed font for a script and locale.
|
||||
//!
|
||||
//! ```no_run
|
||||
//! # let egui_ctx = egui::Context::default();
|
||||
//! egui_ctx.add_font_provider(std::sync::Arc::new(egui_system_fonts::SystemFontProvider::new()));
|
||||
//! ```
|
||||
|
||||
use epaint::{
|
||||
mutex::Mutex,
|
||||
text::{
|
||||
FallbackRequest, FontData, FontFamily, FontInsert, FontPriority, FontProvider,
|
||||
InsertFontFamily,
|
||||
},
|
||||
};
|
||||
use fontique::{
|
||||
Collection, CollectionOptions, FallbackKey, GenericFamily, Language, QueryFamily, QueryFont,
|
||||
QueryStatus, Script, SourceCache, SourceCacheOptions,
|
||||
};
|
||||
use poll_promise::Promise;
|
||||
|
||||
struct SystemFonts {
|
||||
collection: Collection,
|
||||
source_cache: SourceCache,
|
||||
}
|
||||
|
||||
/// Finds installed system fonts for characters that the egui fonts lack.
|
||||
///
|
||||
/// Uses the operating system's own font fallback via [`fontique`],
|
||||
/// so e.g. 日本語 gets a Japanese font and العربية an Arabic font.
|
||||
/// The font files are memory-mapped, not copied.
|
||||
///
|
||||
/// Enumerating the system fonts can take hundreds of milliseconds,
|
||||
/// so [`Self::new`] starts doing that on a background thread.
|
||||
/// A lookup before it is done blocks until it is.
|
||||
pub struct SystemFontProvider {
|
||||
/// Loaded on a background thread by [`Self::new`].
|
||||
fonts: Mutex<Promise<SystemFonts>>,
|
||||
locale: Option<Language>,
|
||||
}
|
||||
|
||||
impl Default for SystemFontProvider {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl SystemFontProvider {
|
||||
/// Start enumerating the system fonts on a background thread.
|
||||
///
|
||||
/// Uses the system locale to pick between fonts (see [`Self::with_locale`]).
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
fonts: Mutex::new(Promise::spawn_thread(
|
||||
"egui_system_fonts",
|
||||
load_system_fonts,
|
||||
)),
|
||||
locale: sys_locale::get_locale().and_then(|locale| parse_locale(&locale)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The locale used to pick between fonts for the same script,
|
||||
/// e.g. between a Japanese and a Simplified Chinese font for CJK ideographs.
|
||||
///
|
||||
/// A BCP-47 language tag like `"ja"` or `"zh-Hans"`, or `None` for the platform default.
|
||||
///
|
||||
/// Default: the system locale.
|
||||
#[inline]
|
||||
pub fn with_locale(mut self, locale: Option<&str>) -> Self {
|
||||
self.locale = locale.and_then(parse_locale);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_locale(locale: &str) -> Option<Language> {
|
||||
match Language::parse(locale) {
|
||||
Ok(language) => Some(language),
|
||||
Err(err) => {
|
||||
log::warn!("Failed to parse locale {locale:?}: {err:?}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn load_system_fonts() -> SystemFonts {
|
||||
let start = std::time::Instant::now();
|
||||
let collection = Collection::new(CollectionOptions {
|
||||
shared: false,
|
||||
system_fonts: true,
|
||||
});
|
||||
log::debug!("Enumerated system fonts in {:?}", start.elapsed());
|
||||
SystemFonts {
|
||||
collection,
|
||||
source_cache: SourceCache::new(SourceCacheOptions::default()),
|
||||
}
|
||||
}
|
||||
|
||||
impl FontProvider for SystemFontProvider {
|
||||
fn font_for(&self, request: &FallbackRequest<'_>) -> Option<FontInsert> {
|
||||
let FallbackRequest { cluster, family } = request;
|
||||
let base_char = cluster.chars().next()?;
|
||||
|
||||
// Blocks if the background thread is not done enumerating the system fonts yet:
|
||||
let mut fonts = self.fonts.lock();
|
||||
let SystemFonts {
|
||||
collection,
|
||||
source_cache,
|
||||
} = fonts.block_until_ready_mut();
|
||||
|
||||
let generic = match family {
|
||||
FontFamily::Monospace => GenericFamily::Monospace,
|
||||
FontFamily::Proportional | FontFamily::Name(_) => GenericFamily::SansSerif,
|
||||
};
|
||||
|
||||
let mut query = collection.query(source_cache);
|
||||
if let Some(script) = script_of(base_char) {
|
||||
query.set_families([QueryFamily::Generic(generic)]);
|
||||
query.set_fallbacks(FallbackKey::new(script, self.locale.as_ref()));
|
||||
} else {
|
||||
// Punctuation, symbols, emoji, etc. belong to no script, so there is no fallback for them.
|
||||
// Try the generic families instead.
|
||||
query.set_families(
|
||||
[
|
||||
generic,
|
||||
GenericFamily::SystemUi,
|
||||
GenericFamily::Emoji,
|
||||
GenericFamily::Math,
|
||||
GenericFamily::Serif,
|
||||
GenericFamily::Monospace,
|
||||
]
|
||||
.map(QueryFamily::Generic),
|
||||
);
|
||||
}
|
||||
|
||||
let mut found = None;
|
||||
query.matches_with(|font| {
|
||||
if can_render(font, base_char) {
|
||||
found = Some(font.clone());
|
||||
QueryStatus::Stop
|
||||
} else {
|
||||
QueryStatus::Continue
|
||||
}
|
||||
});
|
||||
drop(query);
|
||||
let font = found?;
|
||||
|
||||
let family_name = collection.family_name(font.family.0).unwrap_or("unknown");
|
||||
let name = format!("system:{family_name}:{}:{}", font.family.1, font.index);
|
||||
log::debug!("Using {name:?} for {base_char:?}");
|
||||
|
||||
let (blob, _blob_id) = font.blob.into_raw_parts();
|
||||
Some(FontInsert {
|
||||
name,
|
||||
data: FontData::from_blob(blob, font.index),
|
||||
families: vec![InsertFontFamily {
|
||||
family: (*family).clone(),
|
||||
priority: FontPriority::Lowest,
|
||||
}],
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The script of a character, or `None` for characters shared between scripts (punctuation, symbols, …).
|
||||
fn script_of(c: char) -> Option<Script> {
|
||||
use unicode_script::UnicodeScript as _;
|
||||
|
||||
match c.script() {
|
||||
unicode_script::Script::Common
|
||||
| unicode_script::Script::Inherited
|
||||
| unicode_script::Script::Unknown => None,
|
||||
script => Script::parse(script.short_name()).ok(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Does the font have a glyph for the character that epaint can render?
|
||||
///
|
||||
/// That is an outline, a bitmap (`sbix`, `CBDT`), or a `COLR` glyph.
|
||||
fn can_render(font: &QueryFont, c: char) -> bool {
|
||||
use skrifa::MetadataProvider as _;
|
||||
|
||||
let Some(glyph_id) = font.charmap().and_then(|charmap| charmap.map(c)) else {
|
||||
return false;
|
||||
};
|
||||
let glyph_id = skrifa::GlyphId::new(glyph_id);
|
||||
if glyph_id == skrifa::GlyphId::NOTDEF {
|
||||
return false;
|
||||
}
|
||||
let Ok(font_ref) = skrifa::FontRef::from_index(font.blob.as_ref(), font.index) else {
|
||||
return false;
|
||||
};
|
||||
font_ref.outline_glyphs().get(glyph_id).is_some()
|
||||
|| font_ref.color_glyphs().get(glyph_id).is_some()
|
||||
|| font_ref
|
||||
.bitmap_strikes()
|
||||
.glyph_for_size(skrifa::instance::Size::unscaled(), glyph_id)
|
||||
.is_some()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn scripts() {
|
||||
assert_eq!(script_of('a'), Some(Script::from_bytes(*b"Latn")));
|
||||
assert_eq!(script_of('日'), Some(Script::from_bytes(*b"Hani")));
|
||||
assert_eq!(script_of('ع'), Some(Script::from_bytes(*b"Arab")));
|
||||
assert_eq!(script_of('1'), None);
|
||||
assert_eq!(script_of('⌥'), None);
|
||||
assert_eq!(script_of('\u{0301}'), None); // combining acute accent
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "Depends on which fonts are installed on this machine"]
|
||||
#[expect(clippy::print_stdout)]
|
||||
fn finds_system_fonts() {
|
||||
let provider = SystemFontProvider::new();
|
||||
for (c, script) in [
|
||||
('日', "CJK"),
|
||||
('ع', "Arabic"),
|
||||
('א', "Hebrew"),
|
||||
('क', "Devanagari"),
|
||||
('ก', "Thai"),
|
||||
('⌥', "Symbol"),
|
||||
] {
|
||||
let cluster = c.to_string();
|
||||
let request = FallbackRequest {
|
||||
cluster: &cluster,
|
||||
family: &FontFamily::Proportional,
|
||||
};
|
||||
let Some(insert) = provider.font_for(&request) else {
|
||||
panic!("No system font for {script} {c:?}");
|
||||
};
|
||||
println!("{script} {c:?}: {}", insert.name);
|
||||
assert!(insert.name.starts_with("system:"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "Depends on which fonts are installed on this machine"]
|
||||
fn renders_cjk_through_egui_context() {
|
||||
let ctx = egui::Context::default();
|
||||
let font_id = egui::FontId::proportional(14.0);
|
||||
let mut output = ctx.run_ui(Default::default(), |ui| {
|
||||
ui.fonts_mut(|fonts| assert!(!fonts.has_glyph(&font_id, '日')));
|
||||
});
|
||||
output.textures_delta.clear();
|
||||
|
||||
ctx.add_font_provider(Arc::new(SystemFontProvider::new()));
|
||||
let mut output = ctx.run_ui(Default::default(), |ui| {
|
||||
ui.fonts_mut(|fonts| assert!(fonts.has_glyph(&font_id, '日')));
|
||||
assert_eq!(ui.fonts(|fonts| fonts.discovered_fonts().len()), 1);
|
||||
});
|
||||
output.textures_delta.clear();
|
||||
}
|
||||
}
|
||||
@@ -35,6 +35,11 @@ cint = ["ecolor/cint"]
|
||||
## Enable the [`hex_color`] macro.
|
||||
color-hex = ["ecolor/color-hex"]
|
||||
|
||||
## Support bitmap (`sbix`, `CBDT`) and `COLR` glyphs, i.e. color emoji fonts like Apple Color Emoji and Segoe UI Emoji.
|
||||
##
|
||||
## Adds a PNG decoder to the binary, so it is off by default. `eframe` enables it on native via `egui_system_fonts`.
|
||||
color_fonts = ["vello_cpu/png", "vello_cpu/text"]
|
||||
|
||||
## If set, epaint will use `include_bytes!` to bundle some fonts.
|
||||
## If you plan on specifying your own fonts you may disable this feature.
|
||||
default_fonts = ["epaint_default_fonts"]
|
||||
@@ -42,6 +47,14 @@ default_fonts = ["epaint_default_fonts"]
|
||||
## [`mint`](https://docs.rs/mint) enables interoperability with other math libraries such as [`glam`](https://docs.rs/glam) and [`nalgebra`](https://docs.rs/nalgebra).
|
||||
mint = ["emath/mint"]
|
||||
|
||||
## Bundle the monochrome emoji fonts `NotoEmoji-Regular` and `emoji-icon-font`,
|
||||
## and put them in the default [`text::FontDefinitions`].
|
||||
##
|
||||
## They add about 1 MB to the binary, and are only needed if you want the same
|
||||
## (monochrome) emoji on every platform, instead of the platform's own color emoji
|
||||
## (see [`text::GlyphRasterizer`] and [`text::FontProvider`]).
|
||||
monochrome_emoji_fonts = ["default_fonts", "epaint_default_fonts/monochrome_emoji_fonts"]
|
||||
|
||||
## Enable parallel tessellation using [`rayon`](https://docs.rs/rayon).
|
||||
##
|
||||
## This can help performance for graphics-intense applications.
|
||||
|
||||
@@ -79,6 +79,12 @@ pub use emath::{Pos2, Rect, Vec2, pos2, vec2};
|
||||
pub use ecolor;
|
||||
pub use emath;
|
||||
|
||||
/// A few special emojis that are not part of the unicode standard.
|
||||
///
|
||||
/// Bundled in the default fonts, since no platform font has them.
|
||||
#[cfg(feature = "default_fonts")]
|
||||
pub use epaint_default_fonts::special_emojis;
|
||||
|
||||
#[cfg(feature = "color-hex")]
|
||||
pub use ecolor::hex_color;
|
||||
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
use core::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::Arc;
|
||||
|
||||
use nohash_hasher::IntMap;
|
||||
|
||||
use crate::text::{FontData, FontDefinitions, TextOptions, font_face::FontFace};
|
||||
use crate::text::{FontData, TextOptions, font_face::FontFace};
|
||||
|
||||
/// Unique ID for looking up a single font face/file.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
@@ -26,8 +27,8 @@ impl nohash_hasher::IsEnabled for FontFaceKey {}
|
||||
|
||||
/// Every parsed [`FontFace`], by key and by name.
|
||||
///
|
||||
/// This is the one place fonts get parsed, whether they come from
|
||||
/// [`FontDefinitions`] or are found later (e.g. by a font provider).
|
||||
/// This is the one place fonts get parsed, whether they are configured up front
|
||||
/// or discovered later by a font provider.
|
||||
pub(crate) struct FaceStore {
|
||||
options: TextOptions,
|
||||
by_key: IntMap<FontFaceKey, FontFace>,
|
||||
@@ -35,20 +36,22 @@ pub(crate) struct FaceStore {
|
||||
}
|
||||
|
||||
impl FaceStore {
|
||||
/// Parse every font in the definitions.
|
||||
///
|
||||
/// Panics if a font fails to parse.
|
||||
pub fn new(options: TextOptions, definitions: &FontDefinitions) -> Self {
|
||||
let mut slf = Self {
|
||||
pub fn new(options: TextOptions) -> Self {
|
||||
Self {
|
||||
options,
|
||||
by_key: Default::default(),
|
||||
by_name: Default::default(),
|
||||
};
|
||||
for (name, font_data) in &definitions.font_data {
|
||||
slf.install(name, font_data)
|
||||
.unwrap_or_else(|err| panic!("Error parsing {name:?} TTF/OTF font file: {err}"));
|
||||
}
|
||||
slf
|
||||
}
|
||||
|
||||
/// Apply new [`TextOptions`] (hinting, sub-pixel binning) to every face,
|
||||
/// and to faces installed later.
|
||||
pub fn set_options(&mut self, options: TextOptions) {
|
||||
self.options = options;
|
||||
#[expect(clippy::iter_over_hash_type, reason = "Order does not matter here")]
|
||||
for face in self.by_key.values_mut() {
|
||||
face.set_options(options);
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse a font and add it, unless a font with the same name is already installed.
|
||||
@@ -63,7 +66,7 @@ impl FaceStore {
|
||||
let font_face = FontFace::new(
|
||||
self.options,
|
||||
name.to_owned(),
|
||||
font_data.blob(),
|
||||
Arc::clone(&font_data.font),
|
||||
font_data.index,
|
||||
font_data.tweak.clone(),
|
||||
)?;
|
||||
@@ -73,11 +76,6 @@ impl FaceStore {
|
||||
Ok(key)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn key_by_name(&self, name: &str) -> Option<FontFaceKey> {
|
||||
self.by_name.get(name).copied()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn get(&self, key: FontFaceKey) -> Option<&FontFace> {
|
||||
self.by_key.get(&key)
|
||||
@@ -87,9 +85,4 @@ impl FaceStore {
|
||||
pub fn get_mut(&mut self, key: FontFaceKey) -> Option<&mut FontFace> {
|
||||
self.by_key.get_mut(&key)
|
||||
}
|
||||
|
||||
/// All installed faces, in no particular order.
|
||||
pub fn iter(&self) -> impl Iterator<Item = (FontFaceKey, &FontFace)> {
|
||||
self.by_key.iter().map(|(key, face)| (*key, face))
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use crate::text::{
|
||||
FontDefinitions, FontFamily,
|
||||
FontFamily,
|
||||
face_store::{FaceStore, FontFaceKey},
|
||||
font_provider::FontProviders,
|
||||
};
|
||||
|
||||
/// Index of a [`Family`] in `FontsImpl`.
|
||||
@@ -13,22 +14,17 @@ pub(crate) struct FamilyKey(pub(crate) usize);
|
||||
|
||||
/// The fallback chain of one [`FontFamily`], and the caches for resolving chars against it.
|
||||
///
|
||||
/// This is the only place that decides which face renders a given char.
|
||||
/// This is the only place that decides which face renders a given char:
|
||||
/// first the fonts the [`FontProviders`] install up front (the configured fonts),
|
||||
/// then fonts they discover on demand, then the `.notdef` glyph ("tofu") of the primary face.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Family {
|
||||
name: FontFamily,
|
||||
|
||||
/// Faces in priority order: the primary first, then the fallbacks.
|
||||
chain: Vec<FontFaceKey>,
|
||||
|
||||
/// The face used when no face in [`Self::chain`] supports a char.
|
||||
replacement_face_key: FontFaceKey,
|
||||
|
||||
/// The char that [`Self::replacement_face_key`] actually contains.
|
||||
///
|
||||
/// When the user asks about a char that no fallback face supports we
|
||||
/// render this char in its place.
|
||||
replacement_char: char,
|
||||
/// Configured fonts first, then any discovered by the [`FontProviders`].
|
||||
chain: Vec<FontFaceKey>,
|
||||
|
||||
/// Cache: `char → which face in the fallback chain owns this char`.
|
||||
///
|
||||
@@ -41,58 +37,31 @@ pub(crate) struct Family {
|
||||
}
|
||||
|
||||
impl Family {
|
||||
const PRIMARY_REPLACEMENT_CHAR: char = '◻'; // white medium square
|
||||
const FALLBACK_REPLACEMENT_CHAR: char = '?'; // fallback for the fallback
|
||||
|
||||
/// Look up the fallback chain of `name` in the definitions.
|
||||
///
|
||||
/// Panics if the family or one of its fonts is missing from the definitions.
|
||||
pub fn new(name: &FontFamily, definitions: &FontDefinitions, faces: &mut FaceStore) -> Self {
|
||||
let font_names = definitions
|
||||
.families
|
||||
.get(name)
|
||||
.unwrap_or_else(|| panic!("FontFamily::{name:?} is not bound to any fonts"));
|
||||
|
||||
let chain: Vec<FontFaceKey> = font_names
|
||||
.iter()
|
||||
.map(|font_name| {
|
||||
faces.key_by_name(font_name).unwrap_or_else(|| {
|
||||
let available: Vec<&str> = faces.iter().map(|(_, face)| face.name()).collect();
|
||||
panic!("No font data found for {font_name:?}. Installed fonts: {available:?}")
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut slf = Self {
|
||||
name: name.clone(),
|
||||
chain,
|
||||
replacement_face_key: FontFaceKey::INVALID,
|
||||
replacement_char: Self::PRIMARY_REPLACEMENT_CHAR,
|
||||
face_cache: Default::default(),
|
||||
characters: None,
|
||||
};
|
||||
|
||||
if !slf.chain.is_empty() {
|
||||
let (replacement_face_key, replacement_char) = slf
|
||||
.find_face_for_char(Self::PRIMARY_REPLACEMENT_CHAR, faces)
|
||||
.map(|key| (key, Self::PRIMARY_REPLACEMENT_CHAR))
|
||||
.or_else(|| {
|
||||
slf.find_face_for_char(Self::FALLBACK_REPLACEMENT_CHAR, faces)
|
||||
.map(|key| (key, Self::FALLBACK_REPLACEMENT_CHAR))
|
||||
})
|
||||
.unwrap_or_else(|| {
|
||||
log::warn!(
|
||||
"Failed to find replacement characters {:?} or {:?}. Will use empty glyph.",
|
||||
Self::PRIMARY_REPLACEMENT_CHAR,
|
||||
Self::FALLBACK_REPLACEMENT_CHAR
|
||||
);
|
||||
(FontFaceKey::INVALID, Self::PRIMARY_REPLACEMENT_CHAR)
|
||||
});
|
||||
slf.replacement_face_key = replacement_face_key;
|
||||
slf.replacement_char = replacement_char;
|
||||
/// Install the fonts the providers want for `name` up front, in provider order.
|
||||
pub fn new(name: &FontFamily, faces: &mut FaceStore, providers: &FontProviders) -> Self {
|
||||
let mut chain: Vec<FontFaceKey> = Vec::new();
|
||||
for insert in providers.fonts_for_family(name) {
|
||||
match faces.install(&insert.name, &insert.data) {
|
||||
Ok(key) => {
|
||||
if !chain.contains(&key) {
|
||||
chain.push(key);
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
panic!("Error parsing {:?} TTF/OTF font file: {err}", insert.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
if chain.is_empty() {
|
||||
log::error!("No font provider has any font for FontFamily::{name:?}");
|
||||
}
|
||||
|
||||
slf
|
||||
Self {
|
||||
name: name.clone(),
|
||||
chain,
|
||||
face_cache: Default::default(),
|
||||
characters: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
@@ -106,44 +75,104 @@ impl Family {
|
||||
self.chain.first().copied()
|
||||
}
|
||||
|
||||
/// The face used for chars no face in the chain has.
|
||||
#[inline]
|
||||
pub fn replacement_face_key(&self) -> FontFaceKey {
|
||||
self.replacement_face_key
|
||||
}
|
||||
|
||||
/// The char rendered in place of chars no face in the chain has.
|
||||
#[inline]
|
||||
pub fn replacement_char(&self) -> char {
|
||||
self.replacement_char
|
||||
}
|
||||
|
||||
/// Find which face in the fallback chain owns `c`.
|
||||
///
|
||||
/// Location-independent: fallback choice depends only on charmap support.
|
||||
/// Falls back to the replacement-glyph face when no face has `c`.
|
||||
/// Asks the [`FontProviders`] when no face has `c`,
|
||||
/// and falls back to the primary face (whose `.notdef` glyph we then render)
|
||||
/// when they have no font for it either.
|
||||
#[inline]
|
||||
pub fn resolve(&mut self, faces: &mut FaceStore, c: char) -> FontFaceKey {
|
||||
if let Some(font_key) = self.face_cache.get(&c) {
|
||||
pub fn resolve(
|
||||
&mut self,
|
||||
faces: &mut FaceStore,
|
||||
providers: &mut FontProviders,
|
||||
c: char,
|
||||
) -> FontFaceKey {
|
||||
let mut utf8 = [0_u8; 4];
|
||||
let cluster = c.encode_utf8(&mut utf8);
|
||||
self.resolve_cluster(faces, providers, cluster)
|
||||
}
|
||||
|
||||
/// Like [`Self::resolve`] for the first char of `cluster`,
|
||||
/// but lets the [`FontProviders`] see the whole grapheme cluster.
|
||||
#[inline]
|
||||
pub fn resolve_cluster(
|
||||
&mut self,
|
||||
faces: &mut FaceStore,
|
||||
providers: &mut FontProviders,
|
||||
cluster: &str,
|
||||
) -> FontFaceKey {
|
||||
let Some(base_char) = cluster.chars().next() else {
|
||||
return self.notdef_face();
|
||||
};
|
||||
if let Some(font_key) = self.face_cache.get(&base_char) {
|
||||
return *font_key;
|
||||
}
|
||||
self.resolve_slow(faces, c)
|
||||
self.resolve_slow(faces, providers, cluster, base_char)
|
||||
}
|
||||
|
||||
#[cold]
|
||||
fn resolve_slow(&mut self, faces: &mut FaceStore, c: char) -> FontFaceKey {
|
||||
fn resolve_slow(
|
||||
&mut self,
|
||||
faces: &mut FaceStore,
|
||||
providers: &mut FontProviders,
|
||||
cluster: &str,
|
||||
c: char,
|
||||
) -> FontFaceKey {
|
||||
let font_key = self
|
||||
// All the installed fonts, i.e. the configured ones
|
||||
// and then the ones we have already discovered…
|
||||
.find_face_for_char(c, faces)
|
||||
.unwrap_or(self.replacement_face_key);
|
||||
// …and if none of them has the char, ask the providers for a new font:
|
||||
.or_else(|| self.discover(faces, providers, cluster))
|
||||
// No font has the char, so we will render the `.notdef` glyph ("tofu"):
|
||||
.unwrap_or_else(|| {
|
||||
log::debug!(
|
||||
"No font for {c:?} (U+{:04X}) in {:?}: rendering the tofu glyph instead",
|
||||
c as u32,
|
||||
self.name
|
||||
);
|
||||
self.notdef_face()
|
||||
});
|
||||
self.face_cache.insert(c, font_key);
|
||||
font_key
|
||||
}
|
||||
|
||||
/// Walk the fallback chain and return the first face whose charmap supports `c`.
|
||||
/// The face whose `.notdef` glyph ("tofu") we render for chars no face has.
|
||||
#[inline]
|
||||
fn notdef_face(&self) -> FontFaceKey {
|
||||
self.primary().unwrap_or(FontFaceKey::INVALID)
|
||||
}
|
||||
|
||||
/// Ask the providers for a new font with the first char of `cluster`, and append it to the chain.
|
||||
fn discover(
|
||||
&mut self,
|
||||
faces: &mut FaceStore,
|
||||
providers: &mut FontProviders,
|
||||
cluster: &str,
|
||||
) -> Option<FontFaceKey> {
|
||||
let key = providers.discover(faces, &self.name, cluster)?;
|
||||
if !self.chain.contains(&key) {
|
||||
self.chain.push(key);
|
||||
self.characters = None;
|
||||
}
|
||||
Some(key)
|
||||
}
|
||||
|
||||
/// The first face in the whole chain whose charmap supports `c`.
|
||||
fn find_face_for_char(&self, c: char, faces: &mut FaceStore) -> Option<FontFaceKey> {
|
||||
Self::find_face_for_char_in(&self.chain, c, faces)
|
||||
}
|
||||
|
||||
/// The first of `chain` whose charmap supports `c`.
|
||||
///
|
||||
/// Does not touch [`Self::face_cache`].
|
||||
fn find_face_for_char(&self, c: char, faces: &mut FaceStore) -> Option<FontFaceKey> {
|
||||
self.chain.iter().copied().find(|&key| {
|
||||
fn find_face_for_char_in(
|
||||
chain: &[FontFaceKey],
|
||||
c: char,
|
||||
faces: &mut FaceStore,
|
||||
) -> Option<FontFaceKey> {
|
||||
chain.iter().copied().find(|&key| {
|
||||
faces
|
||||
.get_mut(key)
|
||||
.is_some_and(|face| face.glyph_id_resolution(c).is_some())
|
||||
|
||||
@@ -1,15 +1,23 @@
|
||||
use std::{borrow::Cow, sync::Arc};
|
||||
use std::sync::Arc;
|
||||
|
||||
use emath::Rangef;
|
||||
|
||||
use crate::text::{FontTweak, Tag};
|
||||
|
||||
/// Shared, immutable bytes of a font file.
|
||||
///
|
||||
/// Cheap to clone. Can wrap static bytes, a `Vec<u8>`, or a memory-mapped file.
|
||||
pub type Blob = Arc<dyn AsRef<[u8]> + Send + Sync>;
|
||||
|
||||
/// A `.ttf` or `.otf` file and a font face index.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[derive(Clone)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
|
||||
pub struct FontData {
|
||||
/// The content of a `.ttf` or `.otf` file.
|
||||
pub font: Cow<'static, [u8]>,
|
||||
///
|
||||
/// Shared, so that cloning a [`FontData`] does not copy the file.
|
||||
#[cfg_attr(feature = "serde", serde(with = "blob_serde"))]
|
||||
pub font: Blob,
|
||||
|
||||
/// Which font face in the file to use.
|
||||
/// When in doubt, use `0`.
|
||||
@@ -21,19 +29,26 @@ pub struct FontData {
|
||||
|
||||
impl FontData {
|
||||
pub fn from_static(font: &'static [u8]) -> Self {
|
||||
Self::from_blob(Arc::new(font), 0)
|
||||
}
|
||||
|
||||
pub fn from_owned(font: Vec<u8>) -> Self {
|
||||
Self::from_blob(Arc::new(font), 0)
|
||||
}
|
||||
|
||||
/// Use already shared bytes, e.g. a memory-mapped system font file, without copying them.
|
||||
pub fn from_blob(font: Blob, index: u32) -> Self {
|
||||
Self {
|
||||
font: Cow::Borrowed(font),
|
||||
index: 0,
|
||||
font,
|
||||
index,
|
||||
tweak: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_owned(font: Vec<u8>) -> Self {
|
||||
Self {
|
||||
font: Cow::Owned(font),
|
||||
index: 0,
|
||||
tweak: Default::default(),
|
||||
}
|
||||
/// The content of the font file.
|
||||
#[inline]
|
||||
pub fn bytes(&self) -> &[u8] {
|
||||
(*self.font).as_ref()
|
||||
}
|
||||
|
||||
pub fn tweak(self, tweak: FontTweak) -> Self {
|
||||
@@ -51,7 +66,7 @@ impl FontData {
|
||||
pub fn variation_axes(&self) -> Vec<FontVariationAxis> {
|
||||
use skrifa::MetadataProvider as _;
|
||||
|
||||
let Ok(font) = skrifa::FontRef::from_index(self.font.as_ref(), self.index) else {
|
||||
let Ok(font) = skrifa::FontRef::from_index(self.bytes(), self.index) else {
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
@@ -94,21 +109,42 @@ pub struct FontVariationAxis {
|
||||
|
||||
impl AsRef<[u8]> for FontData {
|
||||
fn as_ref(&self) -> &[u8] {
|
||||
self.font.as_ref()
|
||||
self.bytes()
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
/// Shared, immutable bytes of a font file.
|
||||
pub type Blob = Arc<dyn AsRef<[u8]> + Send + Sync>;
|
||||
|
||||
impl FontData {
|
||||
/// The font file bytes as a shared blob.
|
||||
pub(crate) fn blob(&self) -> Blob {
|
||||
match self.font.clone() {
|
||||
Cow::Borrowed(bytes) => Arc::new(bytes) as Blob,
|
||||
Cow::Owned(bytes) => Arc::new(bytes) as Blob,
|
||||
}
|
||||
impl PartialEq for FontData {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
let Self { font, index, tweak } = self;
|
||||
*index == other.index
|
||||
&& *tweak == other.tweak
|
||||
&& (Arc::ptr_eq(font, &other.font) || self.bytes() == other.bytes())
|
||||
}
|
||||
}
|
||||
|
||||
impl core::fmt::Debug for FontData {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
let Self { font, index, tweak } = self;
|
||||
f.debug_struct("FontData")
|
||||
.field("font", &format_args!("{} bytes", (**font).as_ref().len()))
|
||||
.field("index", index)
|
||||
.field("tweak", tweak)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
mod blob_serde {
|
||||
use super::Blob;
|
||||
|
||||
pub fn serialize<S: serde::Serializer>(blob: &Blob, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
serde::Serialize::serialize((**blob).as_ref(), serializer)
|
||||
}
|
||||
|
||||
pub fn deserialize<'de, D: serde::Deserializer<'de>>(
|
||||
deserializer: D,
|
||||
) -> Result<Blob, D::Error> {
|
||||
let bytes: Vec<u8> = serde::Deserialize::deserialize(deserializer)?;
|
||||
Ok(std::sync::Arc::new(bytes))
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,19 @@
|
||||
use std::{collections::BTreeMap, sync::Arc};
|
||||
|
||||
use crate::text::{FontData, FontFamily};
|
||||
use crate::text::{FontData, FontFamily, font_provider::FontProvider};
|
||||
|
||||
#[cfg(feature = "default_fonts")]
|
||||
use crate::text::FontTweak;
|
||||
|
||||
#[cfg(feature = "default_fonts")]
|
||||
use epaint_default_fonts::{EMOJI_ICON, HACK_REGULAR, NOTO_EMOJI_REGULAR, UBUNTU_LIGHT};
|
||||
use epaint_default_fonts::{EGUI_ICONS, HACK_REGULAR, UBUNTU_LIGHT};
|
||||
#[cfg(feature = "monochrome_emoji_fonts")]
|
||||
use epaint_default_fonts::{EMOJI_ICON, NOTO_EMOJI_REGULAR};
|
||||
|
||||
/// Describes the font data and the sizes to use.
|
||||
/// Describes a set of pre-configured fonts.
|
||||
///
|
||||
/// Often you would start with [`FontDefinitions::default()`] and then add/change the contents.
|
||||
/// These are the fonts epaint will use first, before falling back to any system fonts
|
||||
/// (if configured).
|
||||
///
|
||||
/// This is how you install your own custom fonts:
|
||||
/// ```
|
||||
@@ -126,46 +129,61 @@ impl Default for FontDefinitions {
|
||||
Arc::new(FontData::from_static(HACK_REGULAR)),
|
||||
);
|
||||
|
||||
// Some good looking emojis. Use as first priority:
|
||||
font_data.insert(
|
||||
"NotoEmoji-Regular".to_owned(),
|
||||
Arc::new(FontData::from_static(NOTO_EMOJI_REGULAR).tweak(FontTweak {
|
||||
scale: 0.81, // Make smaller
|
||||
..Default::default()
|
||||
})),
|
||||
);
|
||||
|
||||
font_data.insert(
|
||||
"Ubuntu-Light".to_owned(),
|
||||
Arc::new(FontData::from_static(UBUNTU_LIGHT)),
|
||||
);
|
||||
|
||||
// Bigger emojis, and more. <http://jslegers.github.io/emoji-icon-font/>:
|
||||
// The handful of icons in `egui::special_emojis`, which no platform font has:
|
||||
font_data.insert(
|
||||
"emoji-icon-font".to_owned(),
|
||||
Arc::new(FontData::from_static(EMOJI_ICON).tweak(FontTweak {
|
||||
"egui-icons".to_owned(),
|
||||
Arc::new(FontData::from_static(EGUI_ICONS).tweak(FontTweak {
|
||||
scale: 0.90, // Make smaller
|
||||
..Default::default()
|
||||
})),
|
||||
);
|
||||
|
||||
#[cfg(feature = "monochrome_emoji_fonts")]
|
||||
{
|
||||
// Some good looking emojis:
|
||||
font_data.insert(
|
||||
"NotoEmoji-Regular".to_owned(),
|
||||
Arc::new(FontData::from_static(NOTO_EMOJI_REGULAR).tweak(FontTweak {
|
||||
scale: 0.81, // Make smaller
|
||||
..Default::default()
|
||||
})),
|
||||
);
|
||||
|
||||
// Bigger emojis, and more. <http://jslegers.github.io/emoji-icon-font/>:
|
||||
font_data.insert(
|
||||
"emoji-icon-font".to_owned(),
|
||||
Arc::new(FontData::from_static(EMOJI_ICON).tweak(FontTweak {
|
||||
scale: 0.90, // Make smaller
|
||||
..Default::default()
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
// Last resort, after the fonts that cover the text of a script:
|
||||
let fallback_fonts: &[&str] = if cfg!(feature = "monochrome_emoji_fonts") {
|
||||
&["egui-icons", "NotoEmoji-Regular", "emoji-icon-font"]
|
||||
} else {
|
||||
&["egui-icons"]
|
||||
};
|
||||
let family = |fonts: &[&str]| -> Vec<String> {
|
||||
core::iter::chain(fonts, fallback_fonts)
|
||||
.map(|name| (*name).to_owned())
|
||||
.collect()
|
||||
};
|
||||
|
||||
families.insert(
|
||||
FontFamily::Monospace,
|
||||
vec![
|
||||
"Hack".to_owned(),
|
||||
"Ubuntu-Light".to_owned(), // fallback for √ etc
|
||||
"NotoEmoji-Regular".to_owned(),
|
||||
"emoji-icon-font".to_owned(),
|
||||
],
|
||||
);
|
||||
families.insert(
|
||||
FontFamily::Proportional,
|
||||
vec![
|
||||
"Ubuntu-Light".to_owned(),
|
||||
"NotoEmoji-Regular".to_owned(),
|
||||
"emoji-icon-font".to_owned(),
|
||||
],
|
||||
family(&[
|
||||
"Hack",
|
||||
"Ubuntu-Light", // fallback for √ etc
|
||||
]),
|
||||
);
|
||||
families.insert(FontFamily::Proportional, family(&["Ubuntu-Light"]));
|
||||
|
||||
Self {
|
||||
font_data,
|
||||
@@ -190,12 +208,17 @@ impl FontDefinitions {
|
||||
/// List of all the builtin font names used by `epaint`.
|
||||
#[cfg(feature = "default_fonts")]
|
||||
pub fn builtin_font_names() -> &'static [&'static str] {
|
||||
&[
|
||||
"Ubuntu-Light",
|
||||
"NotoEmoji-Regular",
|
||||
"emoji-icon-font",
|
||||
"Hack",
|
||||
]
|
||||
if cfg!(feature = "monochrome_emoji_fonts") {
|
||||
&[
|
||||
"Ubuntu-Light",
|
||||
"egui-icons",
|
||||
"NotoEmoji-Regular",
|
||||
"emoji-icon-font",
|
||||
"Hack",
|
||||
]
|
||||
} else {
|
||||
&["Ubuntu-Light", "egui-icons", "Hack"]
|
||||
}
|
||||
}
|
||||
|
||||
/// List of all the builtin font names used by `epaint`.
|
||||
@@ -204,3 +227,33 @@ impl FontDefinitions {
|
||||
&[]
|
||||
}
|
||||
}
|
||||
|
||||
/// The configured fonts are the head of every family's fallback chain:
|
||||
/// for each family they are handed out in the order they are listed,
|
||||
/// so the same text looks the same on every machine.
|
||||
///
|
||||
/// [`FontDefinitions`] never discovers anything on demand,
|
||||
/// and is always the first [`FontProvider`] asked.
|
||||
impl FontProvider for FontDefinitions {
|
||||
fn fonts_for_family(&self, family: &FontFamily) -> Vec<FontInsert> {
|
||||
let Some(font_names) = self.families.get(family) else {
|
||||
log::warn!("FontFamily::{family:?} is not bound to any fonts");
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
font_names
|
||||
.iter()
|
||||
.map(|name| {
|
||||
let data = self.font_data.get(name).unwrap_or_else(|| {
|
||||
let available: Vec<&String> = self.font_data.keys().collect();
|
||||
panic!("No font data found for {name:?}. Configured fonts: {available:?}")
|
||||
});
|
||||
FontInsert {
|
||||
name: name.clone(),
|
||||
data: (**data).clone(),
|
||||
families: Vec::new(),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
#![expect(clippy::mem_forget)]
|
||||
|
||||
#[cfg(feature = "color_fonts")]
|
||||
use std::sync::Arc;
|
||||
|
||||
use ahash::HashMap;
|
||||
use ecolor::Color32;
|
||||
use emath::{GuiRounding as _, OrderedFloat, vec2};
|
||||
@@ -10,9 +13,9 @@ use vello_cpu::{color, kurbo};
|
||||
use crate::{
|
||||
ColorImage, TextOptions,
|
||||
text::{
|
||||
FontTweak, VariationCoords,
|
||||
FontTweak, GlyphBitmap, VariationCoords,
|
||||
font_data::Blob,
|
||||
glyph_atlas::{GlyphBitmap, SubpixelBin},
|
||||
glyph_atlas::SubpixelBin,
|
||||
styled_metrics::{LocationHash, StyledMetrics},
|
||||
unicode::invisible_char,
|
||||
},
|
||||
@@ -56,6 +59,15 @@ pub(super) enum GlyphIdResolution {
|
||||
/// The parsed `skrifa` views into a font file, borrowing from the file's [`Blob`].
|
||||
struct DependentFontData<'a> {
|
||||
skrifa: skrifa::FontRef<'a>,
|
||||
|
||||
/// Index of this face in the font file (a font collection, e.g. `.ttc`, holds several).
|
||||
#[cfg(feature = "color_fonts")]
|
||||
index: u32,
|
||||
|
||||
/// Does the font have a `COLR`, `sbix`, `CBDT`, or `EBDT` table?
|
||||
#[cfg(feature = "color_fonts")]
|
||||
has_color_glyphs: bool,
|
||||
|
||||
charmap: skrifa::charmap::Charmap<'a>,
|
||||
outline_glyphs: skrifa::outline::OutlineGlyphCollection<'a>,
|
||||
metrics: skrifa::metrics::Metrics,
|
||||
@@ -78,23 +90,29 @@ impl FontCell {
|
||||
scale / units_per_em
|
||||
}
|
||||
|
||||
/// Render the outline of a glyph to a coverage bitmap.
|
||||
/// Render a glyph to a bitmap: a color glyph if the font has one, else the outline as coverage.
|
||||
///
|
||||
/// Returns `None` if the glyph has no outline (e.g. a space).
|
||||
fn rasterize_outline(
|
||||
/// Returns `None` if the glyph has neither (e.g. a space).
|
||||
fn rasterize_glyph(
|
||||
&mut self,
|
||||
metrics: &StyledMetrics,
|
||||
glyph_id: GlyphId,
|
||||
bin: SubpixelBin,
|
||||
hinting_target: skrifa::outline::Target,
|
||||
) -> Option<GlyphBitmap> {
|
||||
debug_assert!(
|
||||
glyph_id != skrifa::GlyphId::NOTDEF,
|
||||
"Can't rasterize glyph id 0"
|
||||
);
|
||||
|
||||
let location: skrifa::instance::LocationRef<'_> = (&metrics.location).into();
|
||||
|
||||
// Color emoji fonts often have empty outlines next to their bitmap or `COLR` glyphs,
|
||||
// so try those first:
|
||||
core::cfg_select! {
|
||||
feature = "color_fonts" => {
|
||||
if let Some(bitmap) = self.rasterize_color_glyph(metrics, glyph_id, location) {
|
||||
return Some(bitmap);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
let mut path = kurbo::BezPath::new();
|
||||
let mut pen = VelloPen {
|
||||
path: &mut path,
|
||||
@@ -152,6 +170,118 @@ impl FontCell {
|
||||
Some(GlyphBitmap {
|
||||
image,
|
||||
offset_px: vec2(bounds.x0 as f32, bounds.y0 as f32),
|
||||
is_color: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// Does this glyph have a color bitmap (`sbix`, `CBDT`) or a `COLR` paint graph?
|
||||
#[cfg(feature = "color_fonts")]
|
||||
fn has_color_glyph(&self, glyph_id: GlyphId, size: skrifa::instance::Size) -> bool {
|
||||
let font_data = self.borrow_dependent();
|
||||
font_data.has_color_glyphs
|
||||
&& (font_data.skrifa.color_glyphs().get(glyph_id).is_some()
|
||||
|| font_data
|
||||
.skrifa
|
||||
.bitmap_strikes()
|
||||
.glyph_for_size(size, glyph_id)
|
||||
.is_some())
|
||||
}
|
||||
|
||||
/// Rasterize a bitmap (`sbix`, `CBDT`) or `COLR` glyph, e.g. a color emoji.
|
||||
///
|
||||
/// Returns `None` if the glyph has neither.
|
||||
///
|
||||
/// Never sub-pixel positioned: [`crate::text::glyph_atlas::GlyphAtlas::allocate_outline`]
|
||||
/// bins color glyphs to whole pixels.
|
||||
#[cfg(feature = "color_fonts")]
|
||||
fn rasterize_color_glyph(
|
||||
&self,
|
||||
metrics: &StyledMetrics,
|
||||
glyph_id: GlyphId,
|
||||
location: skrifa::instance::LocationRef<'_>,
|
||||
) -> Option<GlyphBitmap> {
|
||||
use vello_cpu::peniko;
|
||||
|
||||
let font_data = self.borrow_dependent();
|
||||
let font_size_px = metrics.scale;
|
||||
let size = skrifa::instance::Size::new(font_size_px);
|
||||
|
||||
if !self.has_color_glyph(glyph_id, size) || font_size_px == 0.0 || !font_size_px.is_finite()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
|
||||
// We don't know the bounds of the glyph up front, so we render it onto a
|
||||
// canvas with room for one em on each side of the em box, then crop.
|
||||
let canvas_size = (3.0 * font_size_px)
|
||||
.ceil()
|
||||
.clamp(1.0, crate::text::MAX_GLYPH_SIZE as f32) as u16;
|
||||
let origin_x = font_size_px as f64;
|
||||
let origin_y = 2.0 * font_size_px as f64;
|
||||
|
||||
let font = peniko::FontData::new(
|
||||
peniko::Blob::new(Arc::clone(self.borrow_owner())),
|
||||
font_data.index,
|
||||
);
|
||||
let coords: Vec<i16> = location.coords().iter().map(|c| c.to_bits()).collect();
|
||||
|
||||
let mut ctx = vello_cpu::RenderContext::new(canvas_size, canvas_size);
|
||||
let mut resources = vello_cpu::Resources::new();
|
||||
ctx.set_paint(color::OpaqueColor::<color::Srgb>::WHITE);
|
||||
ctx.glyph_run(&mut resources, &font)
|
||||
.font_size(font_size_px)
|
||||
.hint(false)
|
||||
.normalized_coords(&coords)
|
||||
.fill_glyphs(core::iter::once(vello_cpu::Glyph {
|
||||
id: glyph_id.to_u32(),
|
||||
x: origin_x as f32,
|
||||
y: origin_y as f32,
|
||||
}));
|
||||
let mut pixmap = vello_cpu::Pixmap::new(canvas_size, canvas_size);
|
||||
ctx.render(&mut pixmap, &mut resources);
|
||||
|
||||
let canvas_size = canvas_size as usize;
|
||||
let pixels = pixmap.data_as_u8_slice();
|
||||
let alpha_at = |x: usize, y: usize| pixels[4 * (y * canvas_size + x) + 3];
|
||||
|
||||
// Crop to the painted pixels:
|
||||
let mut min = [canvas_size, canvas_size];
|
||||
let mut max = [0, 0];
|
||||
for y in 0..canvas_size {
|
||||
for x in 0..canvas_size {
|
||||
if alpha_at(x, y) != 0 {
|
||||
min = [min[0].min(x), min[1].min(y)];
|
||||
max = [max[0].max(x + 1), max[1].max(y + 1)];
|
||||
}
|
||||
}
|
||||
}
|
||||
if max[0] <= min[0] || max[1] <= min[1] {
|
||||
return None; // Nothing painted
|
||||
}
|
||||
let width = max[0] - min[0];
|
||||
let height = max[1] - min[1];
|
||||
|
||||
let cropped: Vec<Color32> = (min[1]..max[1])
|
||||
.flat_map(|y| (min[0]..max[0]).map(move |x| (x, y)))
|
||||
.map(|(x, y)| {
|
||||
let i = 4 * (y * canvas_size + x);
|
||||
// `vello_cpu::Pixmap` holds premultiplied RGBA8:
|
||||
Color32::from_rgba_premultiplied(
|
||||
pixels[i],
|
||||
pixels[i + 1],
|
||||
pixels[i + 2],
|
||||
pixels[i + 3],
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
|
||||
Some(GlyphBitmap {
|
||||
image: ColorImage::new([width, height], cropped),
|
||||
offset_px: vec2(
|
||||
min[0] as f32 - origin_x as f32,
|
||||
min[1] as f32 - origin_y as f32,
|
||||
),
|
||||
is_color: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -255,8 +385,21 @@ impl FontFace {
|
||||
})
|
||||
.flatten();
|
||||
|
||||
#[cfg(feature = "color_fonts")]
|
||||
let has_color_glyphs = {
|
||||
use skrifa::raw::TableProvider as _;
|
||||
skrifa_font.colr().is_ok()
|
||||
|| skrifa_font.sbix().is_ok()
|
||||
|| skrifa_font.cbdt().is_ok()
|
||||
|| skrifa_font.ebdt().is_ok()
|
||||
};
|
||||
|
||||
Ok::<DependentFontData<'_>, Box<dyn core::error::Error>>(DependentFontData {
|
||||
skrifa: skrifa_font,
|
||||
#[cfg(feature = "color_fonts")]
|
||||
index,
|
||||
#[cfg(feature = "color_fonts")]
|
||||
has_color_glyphs,
|
||||
charmap,
|
||||
outline_glyphs: glyphs,
|
||||
metrics,
|
||||
@@ -279,7 +422,34 @@ impl FontFace {
|
||||
})
|
||||
}
|
||||
|
||||
/// Code points that will always be replaced by the replacement character.
|
||||
/// Apply new [`TextOptions`]: hinting on/off and sub-pixel binning.
|
||||
///
|
||||
/// Anything cached about glyph ids and advances stays valid, since neither affects them.
|
||||
pub(crate) fn set_options(&mut self, options: TextOptions) {
|
||||
let Self {
|
||||
font,
|
||||
tweak,
|
||||
subpixel_binning,
|
||||
..
|
||||
} = self;
|
||||
*subpixel_binning = tweak.subpixel_binning.unwrap_or(options.subpixel_binning);
|
||||
let hinting_enabled = tweak.hinting.unwrap_or(options.font_hinting);
|
||||
font.with_dependent_mut(|_, font_data| {
|
||||
font_data.hinting_instance = hinting_enabled
|
||||
.then(|| {
|
||||
skrifa::outline::HintingInstance::new(
|
||||
&font_data.outline_glyphs,
|
||||
skrifa::instance::Size::unscaled(),
|
||||
skrifa::instance::LocationRef::default(),
|
||||
skrifa::outline::Target::default(),
|
||||
)
|
||||
.ok()
|
||||
})
|
||||
.flatten();
|
||||
});
|
||||
}
|
||||
|
||||
/// Code points that will always be replaced by the `.notdef` glyph ("tofu").
|
||||
///
|
||||
/// See also [`invisible_char`].
|
||||
fn ignore_character(&self, chr: char) -> bool {
|
||||
@@ -332,7 +502,7 @@ impl FontFace {
|
||||
}
|
||||
|
||||
if self.ignore_character(c) {
|
||||
return None; // these will result in the replacement character when rendering
|
||||
return None; // these will result in the `.notdef` glyph ("tofu") when rendering
|
||||
}
|
||||
|
||||
let resolution = if c == '\t' || c == '\u{2009}' || c == '\u{202F}' {
|
||||
@@ -403,6 +573,21 @@ impl FontFace {
|
||||
Some(glyph_info)
|
||||
}
|
||||
|
||||
/// The `.notdef` glyph ("tofu"), rendered in place of chars that no face has.
|
||||
pub(super) fn notdef_glyph_info(&self, metrics: &StyledMetrics) -> GlyphInfo {
|
||||
let font_data = self.font.borrow_dependent();
|
||||
let glyph_metrics = font_data
|
||||
.skrifa
|
||||
.glyph_metrics(skrifa::instance::Size::unscaled(), &metrics.location);
|
||||
GlyphInfo {
|
||||
id: Some(GlyphId::NOTDEF),
|
||||
advance_width_unscaled: glyph_metrics
|
||||
.advance_width(GlyphId::NOTDEF)
|
||||
.unwrap_or_default()
|
||||
.into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn styled_metrics(
|
||||
&self,
|
||||
@@ -460,10 +645,24 @@ impl FontFace {
|
||||
self.subpixel_binning
|
||||
}
|
||||
|
||||
/// Render the outline of a glyph to a coverage bitmap.
|
||||
/// Will this glyph be rendered as a color bitmap or `COLR` glyph, e.g. a color emoji?
|
||||
pub(crate) fn is_color_glyph(&self, metrics: &StyledMetrics, glyph_id: GlyphId) -> bool {
|
||||
core::cfg_select! {
|
||||
feature = "color_fonts" => {
|
||||
self.font
|
||||
.has_color_glyph(glyph_id, skrifa::instance::Size::new(metrics.scale))
|
||||
}
|
||||
_ => {
|
||||
let _ = (self, metrics, glyph_id);
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Render a glyph to a bitmap: a color glyph if the font has one, else the outline as coverage.
|
||||
///
|
||||
/// Not cached: see [`crate::text::glyph_atlas::GlyphAtlas::allocate_outline`].
|
||||
pub(crate) fn rasterize_outline(
|
||||
pub(crate) fn rasterize_glyph(
|
||||
&mut self,
|
||||
metrics: &StyledMetrics,
|
||||
glyph_id: GlyphId,
|
||||
@@ -471,7 +670,7 @@ impl FontFace {
|
||||
) -> Option<GlyphBitmap> {
|
||||
let hinting_target = self.tweak.hinting_target.into();
|
||||
self.font
|
||||
.rasterize_outline(metrics, glyph_id, bin, hinting_target)
|
||||
.rasterize_glyph(metrics, glyph_id, bin, hinting_target)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,362 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::text::{
|
||||
FontFamily, FontInsert, FontPriority, InsertFontFamily,
|
||||
face_store::{FaceStore, FontFaceKey},
|
||||
unicode::is_combining_mark,
|
||||
};
|
||||
|
||||
/// Input to a [`FontProvider`].
|
||||
pub struct FallbackRequest<'a> {
|
||||
/// A grapheme cluster that no installed font can render.
|
||||
///
|
||||
/// The returned font must have a glyph for its first character.
|
||||
pub cluster: &'a str,
|
||||
|
||||
/// The requested font family.
|
||||
pub family: &'a FontFamily,
|
||||
}
|
||||
|
||||
/// A source of fonts.
|
||||
///
|
||||
/// Fonts come from two kinds of providers, and egui treats them the same once they are installed:
|
||||
/// shaped, hinted, and kerned like any other font.
|
||||
///
|
||||
/// * *Configured* fonts are known up front, and form the head of every family's fallback chain.
|
||||
/// [`FontDefinitions`](crate::text::FontDefinitions) is itself such a provider,
|
||||
/// and is always the first one asked.
|
||||
/// * *Discovered* fonts are found on demand for a character no installed font has,
|
||||
/// e.g. among the system fonts. They are appended to the family's fallback chain.
|
||||
///
|
||||
/// A provider can do either or both. Providers are asked in order, and the first answer wins.
|
||||
///
|
||||
/// Install one with `egui::Context::add_font_provider` or [`Fonts::with_font_providers`](crate::text::Fonts::with_font_providers).
|
||||
/// `eframe` installs a system font provider on native (behind its `system_fonts` feature).
|
||||
///
|
||||
/// Any `Fn(&FallbackRequest<'_>) -> Option<FontInsert>` is a discovering [`FontProvider`].
|
||||
pub trait FontProvider: Send + Sync {
|
||||
/// The fonts to install for `family` up front, in priority order.
|
||||
///
|
||||
/// Called once per family (again after the providers change).
|
||||
fn fonts_for_family(&self, family: &FontFamily) -> Vec<FontInsert> {
|
||||
let _ = family;
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// Find a font with a glyph for the first character of `request.cluster`,
|
||||
/// after every installed font of the family missed.
|
||||
///
|
||||
/// Called at most once per (family, character), also when returning `None`.
|
||||
///
|
||||
/// The font is appended to the fallback chain of `request.family`
|
||||
/// and of the families in [`FontInsert::families`].
|
||||
/// The [`FontPriority`] is ignored: discovered fonts always come after the configured ones.
|
||||
fn font_for(&self, request: &FallbackRequest<'_>) -> Option<FontInsert> {
|
||||
let _ = request;
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
impl<F> FontProvider for F
|
||||
where
|
||||
F: Fn(&FallbackRequest<'_>) -> Option<FontInsert> + Send + Sync,
|
||||
{
|
||||
fn font_for(&self, request: &FallbackRequest<'_>) -> Option<FontInsert> {
|
||||
self(request)
|
||||
}
|
||||
}
|
||||
|
||||
/// The installed [`FontProvider`]s, in the order they are asked.
|
||||
///
|
||||
/// The first one is always the configured [`FontDefinitions`](crate::text::FontDefinitions).
|
||||
#[derive(Default)]
|
||||
pub(crate) struct FontProviders {
|
||||
providers: Vec<Arc<dyn FontProvider>>,
|
||||
|
||||
/// Fonts discovered so far, in the order they were found.
|
||||
discovered: Vec<FontInsert>,
|
||||
}
|
||||
|
||||
impl FontProviders {
|
||||
pub fn new(providers: Vec<Arc<dyn FontProvider>>) -> Self {
|
||||
Self {
|
||||
providers,
|
||||
discovered: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Fonts discovered so far, in the order they were found.
|
||||
pub fn discovered(&self) -> &[FontInsert] {
|
||||
&self.discovered
|
||||
}
|
||||
|
||||
/// The fonts every provider wants installed for `family` up front, in priority order.
|
||||
pub fn fonts_for_family(&self, family: &FontFamily) -> Vec<FontInsert> {
|
||||
self.providers
|
||||
.iter()
|
||||
.flat_map(|provider| provider.fonts_for_family(family))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Ask the providers for a font with a glyph for the first char of `cluster`,
|
||||
/// and install it into `faces`.
|
||||
///
|
||||
/// The caller caches the result, so each provider is asked at most once per (family, char).
|
||||
pub fn discover(
|
||||
&mut self,
|
||||
faces: &mut FaceStore,
|
||||
family: &FontFamily,
|
||||
cluster: &str,
|
||||
) -> Option<FontFaceKey> {
|
||||
let base_char = cluster.chars().next()?;
|
||||
if base_char.is_control() || is_combining_mark(base_char) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let request = FallbackRequest { cluster, family };
|
||||
|
||||
for provider in &self.providers {
|
||||
let Some(mut insert) = provider.font_for(&request) else {
|
||||
continue;
|
||||
};
|
||||
let key = match faces.install(&insert.name, &insert.data) {
|
||||
Ok(key) => key,
|
||||
Err(err) => {
|
||||
log::warn!(
|
||||
"Failed to parse font {:?} from a font provider: {err}",
|
||||
insert.name
|
||||
);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let has_glyph = faces
|
||||
.get_mut(key)
|
||||
.is_some_and(|face| face.glyph_id_resolution(base_char).is_some());
|
||||
if !has_glyph {
|
||||
log::warn!(
|
||||
"Font {:?} from a font provider has no glyph for {base_char:?}",
|
||||
insert.name
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
if !insert.families.iter().any(|f| f.family == *family) {
|
||||
insert.families.push(InsertFontFamily {
|
||||
family: family.clone(),
|
||||
priority: FontPriority::Lowest,
|
||||
});
|
||||
}
|
||||
self.discovered.push(insert);
|
||||
return Some(key);
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "default_fonts")]
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
|
||||
use epaint_default_fonts::{HACK_REGULAR, UBUNTU_LIGHT};
|
||||
|
||||
use super::*;
|
||||
use crate::{
|
||||
Color32, ColorImage,
|
||||
mutex::Mutex,
|
||||
text::{
|
||||
FontData, FontDefinitions, FontId, Fonts, GlyphBitmap, GlyphRasterizer,
|
||||
GlyphRasterizerRequest, RasterizedGlyph, TextOptions,
|
||||
},
|
||||
};
|
||||
|
||||
/// Latin capital letter schwa: in `Ubuntu-Light`, but not in `Hack`.
|
||||
const SCHWA: char = 'Ə';
|
||||
|
||||
/// In neither `Hack` nor `Ubuntu-Light`.
|
||||
const HANGUL: char = '한';
|
||||
|
||||
const DISCOVERED_FONT: &str = "discovered:Ubuntu-Light";
|
||||
|
||||
/// Only `Hack`, so that e.g. [`SCHWA`] is missing.
|
||||
fn hack_only() -> FontDefinitions {
|
||||
let mut definitions = FontDefinitions::empty();
|
||||
definitions.font_data.insert(
|
||||
"Hack".to_owned(),
|
||||
Arc::new(FontData::from_static(HACK_REGULAR)),
|
||||
);
|
||||
definitions
|
||||
.families
|
||||
.insert(FontFamily::Proportional, vec!["Hack".to_owned()]);
|
||||
definitions
|
||||
.families
|
||||
.insert(FontFamily::Monospace, vec!["Hack".to_owned()]);
|
||||
definitions
|
||||
}
|
||||
|
||||
/// A provider that records its requests, and returns `Ubuntu-Light` for everything if `provide`.
|
||||
fn recording_provider(
|
||||
requests: &Arc<Mutex<Vec<(FontFamily, String)>>>,
|
||||
provide: bool,
|
||||
) -> Arc<dyn FontProvider> {
|
||||
let requests = Arc::clone(requests);
|
||||
Arc::new(move |request: &FallbackRequest<'_>| {
|
||||
requests
|
||||
.lock()
|
||||
.push((request.family.clone(), request.cluster.to_owned()));
|
||||
provide.then(|| {
|
||||
FontInsert::new(
|
||||
DISCOVERED_FONT,
|
||||
FontData::from_static(UBUNTU_LIGHT),
|
||||
vec![InsertFontFamily {
|
||||
family: request.family.clone(),
|
||||
priority: FontPriority::Lowest,
|
||||
}],
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn color_rasterizer() -> GlyphRasterizer {
|
||||
GlyphRasterizer::new(|_: &GlyphRasterizerRequest<'_>| {
|
||||
Some(RasterizedGlyph {
|
||||
bitmap: GlyphBitmap {
|
||||
image: ColorImage::new([1, 1], vec![Color32::RED]),
|
||||
offset_px: emath::Vec2::ZERO,
|
||||
is_color: true,
|
||||
},
|
||||
advance_px: 10.0,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn fonts_with(provider: Arc<dyn FontProvider>, rasterizer: Option<GlyphRasterizer>) -> Fonts {
|
||||
let mut fonts =
|
||||
Fonts::new(TextOptions::default(), hack_only()).with_font_providers(vec![provider]);
|
||||
fonts.set_glyph_rasterizer(rasterizer);
|
||||
fonts
|
||||
}
|
||||
|
||||
fn first_glyph(fonts: &mut Fonts, c: char) -> crate::text::Glyph {
|
||||
let galley = fonts.with_pixels_per_point(1.0).layout_no_wrap(
|
||||
c.to_string(),
|
||||
FontId::proportional(14.0),
|
||||
Color32::WHITE,
|
||||
);
|
||||
galley.rows[0].row.glyphs[0]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_hit_installs_the_font_once() {
|
||||
let requests = Arc::new(Mutex::new(Vec::new()));
|
||||
let mut fonts = fonts_with(recording_provider(&requests, true), None);
|
||||
let font_id = FontId::proportional(14.0);
|
||||
|
||||
assert!(fonts.has_glyph(&font_id, SCHWA));
|
||||
assert!(fonts.has_glyph(&font_id, SCHWA));
|
||||
assert!(fonts.has_glyph(&font_id, 'a'));
|
||||
assert_eq!(
|
||||
*requests.lock(),
|
||||
vec![(FontFamily::Proportional, SCHWA.to_string())]
|
||||
);
|
||||
assert_eq!(fonts.discovered_fonts().len(), 1);
|
||||
|
||||
let glyph = first_glyph(&mut fonts, SCHWA);
|
||||
assert!(!glyph.uv_rect.is_nothing());
|
||||
assert!(!glyph.is_color);
|
||||
assert_eq!(requests.lock().len(), 1);
|
||||
|
||||
assert_eq!(
|
||||
fonts
|
||||
.with_pixels_per_point(1.0)
|
||||
.characters(&FontFamily::Proportional)
|
||||
.get(&SCHWA),
|
||||
Some(&vec![DISCOVERED_FONT.to_owned()])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_miss_is_remembered_per_family() {
|
||||
let requests = Arc::new(Mutex::new(Vec::new()));
|
||||
let mut fonts = fonts_with(recording_provider(&requests, false), None);
|
||||
|
||||
assert!(!fonts.has_glyph(&FontId::proportional(14.0), HANGUL));
|
||||
assert!(!fonts.has_glyph(&FontId::proportional(14.0), HANGUL));
|
||||
assert!(!fonts.has_glyph(&FontId::monospace(14.0), HANGUL));
|
||||
assert_eq!(
|
||||
*requests.lock(),
|
||||
vec![
|
||||
(FontFamily::Proportional, HANGUL.to_string()),
|
||||
(FontFamily::Monospace, HANGUL.to_string()),
|
||||
]
|
||||
);
|
||||
assert!(fonts.discovered_fonts().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_is_not_asked_for_control_chars_and_combining_marks() {
|
||||
let requests = Arc::new(Mutex::new(Vec::new()));
|
||||
let mut fonts = fonts_with(recording_provider(&requests, true), None);
|
||||
let font_id = FontId::proportional(14.0);
|
||||
|
||||
fonts.has_glyph(&font_id, '\n');
|
||||
fonts.has_glyph(&font_id, '\u{1AB0}'); // COMBINING DOUBLED CIRCUMFLEX ACCENT
|
||||
assert!(requests.lock().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn discovered_fonts_and_misses_survive_an_options_change() {
|
||||
let requests = Arc::new(Mutex::new(Vec::new()));
|
||||
let mut fonts = fonts_with(recording_provider(&requests, true), None);
|
||||
let font_id = FontId::proportional(14.0);
|
||||
|
||||
assert!(fonts.has_glyph(&font_id, SCHWA));
|
||||
// The provider returns `Ubuntu-Light` for this too, but it has no glyph for it:
|
||||
assert!(!fonts.has_glyph(&font_id, HANGUL));
|
||||
assert_eq!(requests.lock().len(), 2);
|
||||
assert_eq!(fonts.discovered_fonts().len(), 1);
|
||||
|
||||
// Change the text options; the faces and families must survive:
|
||||
let options = TextOptions {
|
||||
font_hinting: !TextOptions::default().font_hinting,
|
||||
..Default::default()
|
||||
};
|
||||
fonts.begin_pass(options);
|
||||
|
||||
assert!(fonts.has_glyph(&font_id, SCHWA));
|
||||
assert!(!fonts.has_glyph(&font_id, HANGUL));
|
||||
assert_eq!(
|
||||
requests.lock().len(),
|
||||
2,
|
||||
"The provider should not be asked again"
|
||||
);
|
||||
assert_eq!(fonts.discovered_fonts().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn discovered_font_beats_the_rasterizer() {
|
||||
let requests = Arc::new(Mutex::new(Vec::new()));
|
||||
let mut fonts = fonts_with(
|
||||
recording_provider(&requests, true),
|
||||
Some(color_rasterizer()),
|
||||
);
|
||||
|
||||
let glyph = first_glyph(&mut fonts, SCHWA);
|
||||
assert!(!glyph.is_color, "Should come from the discovered font");
|
||||
assert_eq!(requests.lock().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rasterizer_is_used_when_the_provider_misses() {
|
||||
let requests = Arc::new(Mutex::new(Vec::new()));
|
||||
let mut fonts = fonts_with(
|
||||
recording_provider(&requests, false),
|
||||
Some(color_rasterizer()),
|
||||
);
|
||||
|
||||
let glyph = first_glyph(&mut fonts, HANGUL);
|
||||
assert!(glyph.is_color, "Should come from the rasterizer");
|
||||
assert_eq!(requests.lock().len(), 1);
|
||||
}
|
||||
}
|
||||
@@ -3,14 +3,14 @@ use std::{collections::BTreeMap, sync::Arc};
|
||||
use crate::{
|
||||
Color32, TextureAtlas,
|
||||
text::{
|
||||
FontDefinitions, FontFamily, FontId, Galley, GlyphRasterizer, GlyphSource,
|
||||
GlyphSourcePreference, LayoutJob, TextOptions, VariationCoords,
|
||||
FontDefinitions, FontFamily, FontId, FontInsert, FontProvider, Galley, GlyphRasterizer,
|
||||
LayoutJob, TextOptions, VariationCoords,
|
||||
face_store::{FaceStore, FontFaceKey},
|
||||
family::{Family, FamilyKey},
|
||||
font_face::{FontFace, GlyphInfo, ShapedGlyph},
|
||||
font_provider::FontProviders,
|
||||
galley_cache::GalleyCache,
|
||||
glyph_atlas::{GlyphAtlas, OutlineGlyph, RasterGlyphAllocation},
|
||||
glyph_rasterizer::default_glyph_source,
|
||||
styled_metrics::StyledMetrics,
|
||||
text_layout::layout,
|
||||
},
|
||||
@@ -69,18 +69,22 @@ impl Fonts {
|
||||
self.galley_cache = Default::default();
|
||||
}
|
||||
|
||||
/// Decide where to look first for the glyphs of each grapheme cluster.
|
||||
/// Ask these for fonts, after the [`FontDefinitions`].
|
||||
///
|
||||
/// See [`GlyphSourcePreference`].
|
||||
/// The providers are asked in order, and the first font found is used.
|
||||
#[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);
|
||||
pub fn with_font_providers(mut self, font_providers: Vec<Arc<dyn FontProvider>>) -> Self {
|
||||
self.fonts.set_font_providers(font_providers);
|
||||
self
|
||||
}
|
||||
|
||||
/// The fonts discovered by the [`FontProvider`]s so far, in the order they were found.
|
||||
///
|
||||
/// These are not part of [`Self::definitions`].
|
||||
pub fn discovered_fonts(&self) -> &[FontInsert] {
|
||||
self.fonts.discovered_fonts()
|
||||
}
|
||||
|
||||
/// 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.
|
||||
@@ -89,13 +93,8 @@ impl Fonts {
|
||||
/// as well as notice when the font atlas is getting full, and handle that.
|
||||
pub fn begin_pass(&mut self, options: TextOptions) {
|
||||
if self.fonts.options() != &options {
|
||||
// Hinting and other options are baked into each parsed face, so start over:
|
||||
let definitions = self.fonts.definitions.clone();
|
||||
let mut fonts = FontsImpl::new(options, definitions);
|
||||
fonts.set_glyph_rasterizer(self.fonts.glyph_rasterizer.take());
|
||||
fonts.glyph_source_preference = Arc::clone(&self.fonts.glyph_source_preference);
|
||||
self.fonts = fonts;
|
||||
self.galley_cache = Default::default();
|
||||
self.fonts.set_options(options);
|
||||
self.galley_cache = Default::default(); // Galleys point into the old atlas.
|
||||
} else if 0.8 < self.fonts.glyphs.fill_ratio() {
|
||||
// The parsed faces are still fine; only the bitmaps need to go.
|
||||
self.fonts.glyphs.clear();
|
||||
@@ -266,6 +265,13 @@ impl FontsView<'_> {
|
||||
self.fonts.definitions.families.keys().cloned().collect()
|
||||
}
|
||||
|
||||
/// The fonts discovered by the [`FontProvider`]s so far, in the order they were found.
|
||||
///
|
||||
/// These are not part of [`Self::definitions`].
|
||||
pub fn discovered_fonts(&self) -> &[FontInsert] {
|
||||
self.fonts.discovered_fonts()
|
||||
}
|
||||
|
||||
/// Layout some text.
|
||||
///
|
||||
/// This is the most advanced layout function.
|
||||
@@ -340,7 +346,7 @@ impl FontsView<'_> {
|
||||
///
|
||||
/// Required in order to paint text.
|
||||
pub(crate) struct FontsImpl {
|
||||
definitions: FontDefinitions,
|
||||
definitions: Arc<FontDefinitions>,
|
||||
glyphs: GlyphAtlas,
|
||||
faces: FaceStore,
|
||||
|
||||
@@ -351,25 +357,49 @@ pub(crate) struct FontsImpl {
|
||||
/// Recycled `harfrust` shaping buffer to avoid per-layout allocations.
|
||||
shape_buffer: Option<harfrust::UnicodeBuffer>,
|
||||
glyph_rasterizer: Option<GlyphRasterizer>,
|
||||
glyph_source_preference: GlyphSourcePreference,
|
||||
font_providers: FontProviders,
|
||||
}
|
||||
|
||||
impl FontsImpl {
|
||||
/// Create a new [`FontsImpl`] for text layout.
|
||||
/// This call is expensive, so only create one [`FontsImpl`] and then reuse it.
|
||||
pub fn new(options: TextOptions, definitions: FontDefinitions) -> Self {
|
||||
let faces = FaceStore::new(options, &definitions);
|
||||
|
||||
Self {
|
||||
definitions,
|
||||
let mut slf = Self {
|
||||
definitions: Arc::new(definitions),
|
||||
glyphs: GlyphAtlas::new(options),
|
||||
faces,
|
||||
faces: FaceStore::new(options),
|
||||
families: Default::default(),
|
||||
family_keys: Default::default(),
|
||||
shape_buffer: Some(harfrust::UnicodeBuffer::new()),
|
||||
glyph_rasterizer: None,
|
||||
glyph_source_preference: Arc::new(default_glyph_source),
|
||||
}
|
||||
font_providers: Default::default(),
|
||||
};
|
||||
slf.set_font_providers(Vec::new());
|
||||
slf
|
||||
}
|
||||
|
||||
/// Ask these for fonts, after the configured [`FontDefinitions`].
|
||||
///
|
||||
/// Forgets the fallback chains, so the providers are asked again for each family.
|
||||
pub fn set_font_providers(&mut self, font_providers: Vec<Arc<dyn FontProvider>>) {
|
||||
let configured: Arc<dyn FontProvider> = Arc::<FontDefinitions>::clone(&self.definitions);
|
||||
let providers = core::iter::chain(core::iter::once(configured), font_providers).collect();
|
||||
self.font_providers = FontProviders::new(providers);
|
||||
self.families.clear();
|
||||
self.family_keys.clear();
|
||||
}
|
||||
|
||||
/// The fonts discovered by the [`FontProvider`]s so far, in the order they were found.
|
||||
pub fn discovered_fonts(&self) -> &[FontInsert] {
|
||||
self.font_providers.discovered()
|
||||
}
|
||||
|
||||
/// Apply new [`TextOptions`].
|
||||
///
|
||||
/// The parsed faces and the fallback chains survive; only the atlas starts over.
|
||||
pub fn set_options(&mut self, options: TextOptions) {
|
||||
self.faces.set_options(options);
|
||||
self.glyphs = GlyphAtlas::new(options);
|
||||
}
|
||||
|
||||
/// Use this platform glyph rasterizer, e.g. the browser on web.
|
||||
@@ -390,16 +420,6 @@ impl FontsImpl {
|
||||
self.glyphs.clear_raster_glyphs();
|
||||
}
|
||||
|
||||
/// 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.glyphs.options()
|
||||
}
|
||||
@@ -426,7 +446,7 @@ impl FontsImpl {
|
||||
}
|
||||
let key = FamilyKey(self.families.len());
|
||||
self.families
|
||||
.push(Family::new(family, &self.definitions, &mut self.faces));
|
||||
.push(Family::new(family, &mut self.faces, &self.font_providers));
|
||||
self.family_keys.insert(family.clone(), key);
|
||||
key
|
||||
}
|
||||
@@ -441,12 +461,19 @@ impl FontsImpl {
|
||||
/// See [`Family::resolve`].
|
||||
#[inline]
|
||||
pub fn resolve_face(&mut self, family: FamilyKey, c: char) -> FontFaceKey {
|
||||
self.families[family.0].resolve(&mut self.faces, c)
|
||||
self.families[family.0].resolve(&mut self.faces, &mut self.font_providers, c)
|
||||
}
|
||||
|
||||
/// Like [`Self::resolve_face`] for the first char of `cluster`,
|
||||
/// but lets the [`FontProvider`]s see the whole grapheme cluster.
|
||||
#[inline]
|
||||
pub fn resolve_cluster_face(&mut self, family: FamilyKey, cluster: &str) -> FontFaceKey {
|
||||
self.families[family.0].resolve_cluster(&mut self.faces, &mut self.font_providers, cluster)
|
||||
}
|
||||
|
||||
/// Resolve `c` to its (face, [`GlyphInfo`]) at the given face's location.
|
||||
///
|
||||
/// `\n` will (intentionally) show up as the replacement character.
|
||||
/// `\n` will (intentionally) show up as the `.notdef` glyph ("tofu").
|
||||
///
|
||||
/// `metrics` must be the resolved [`StyledMetrics`] for the face that ends
|
||||
/// up owning `c`. Most callers pass the metrics of their text run's primary
|
||||
@@ -467,12 +494,11 @@ impl FontsImpl {
|
||||
return (face_key, glyph_info);
|
||||
}
|
||||
|
||||
// `c` is in no face: render the replacement character instead.
|
||||
let replacement_char = self.family(family).replacement_char();
|
||||
// `c` is in no face: render the face's `.notdef` glyph ("tofu") instead.
|
||||
let glyph_info = self
|
||||
.faces
|
||||
.get_mut(face_key)
|
||||
.and_then(|face| face.glyph_info(replacement_char, metrics))
|
||||
.get(face_key)
|
||||
.map(|face| face.notdef_glyph_info(metrics))
|
||||
.unwrap_or(GlyphInfo::INVISIBLE);
|
||||
(face_key, glyph_info)
|
||||
}
|
||||
@@ -492,12 +518,6 @@ impl FontsImpl {
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Where to look first for the glyphs of this grapheme cluster.
|
||||
#[inline]
|
||||
pub fn glyph_source(&self, cluster: &str) -> GlyphSource {
|
||||
(self.glyph_source_preference)(cluster)
|
||||
}
|
||||
|
||||
/// Width of this character in points, at the font's default variation location.
|
||||
///
|
||||
/// Returns `0.0` if no font has the character.
|
||||
@@ -520,8 +540,10 @@ impl FontsImpl {
|
||||
/// for a character that would still render via the rasterizer (e.g. the browser on web).
|
||||
pub fn has_glyph(&mut self, family: &FontFamily, c: char) -> bool {
|
||||
let family = self.family_key(family);
|
||||
// TODO(emilk): this is a false negative if the user asks about the replacement character itself 🤦♂️
|
||||
self.resolve_face(family, c) != self.family(family).replacement_face_key()
|
||||
let face_key = self.resolve_face(family, c);
|
||||
self.faces
|
||||
.get_mut(face_key)
|
||||
.is_some_and(|face| face.glyph_id_resolution(c).is_some())
|
||||
}
|
||||
|
||||
/// Do the installed fonts have all the glyphs in this text?
|
||||
@@ -561,11 +583,6 @@ impl FontsImpl {
|
||||
.allocate_outline(face_key, face, metrics, shaped)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn has_glyph_rasterizer(&self) -> bool {
|
||||
self.glyph_rasterizer.is_some()
|
||||
}
|
||||
|
||||
/// Rasterize a grapheme cluster using the platform [`GlyphRasterizer`].
|
||||
///
|
||||
/// Returns `None` if there is no rasterizer, or it could not handle the cluster.
|
||||
@@ -593,6 +610,26 @@ impl FontsImpl {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The special emojis are in the private use area, so only our own bundled
|
||||
/// `egui-icons.ttf` has them.
|
||||
#[test]
|
||||
fn special_emojis_come_from_the_bundled_icon_font() {
|
||||
use epaint_default_fonts::special_emojis::{GIT, GITHUB, OS_ANDROID, OS_APPLE, OS_WINDOWS};
|
||||
|
||||
let mut fonts = Fonts::new(TextOptions::default(), FontDefinitions::default());
|
||||
let mut view = fonts.with_pixels_per_point(1.0);
|
||||
let characters = view.characters(&FontFamily::Proportional).clone();
|
||||
|
||||
for chr in [GIT, GITHUB, OS_ANDROID, OS_APPLE, OS_WINDOWS] {
|
||||
let faces = characters.get(&chr);
|
||||
assert!(
|
||||
faces.is_some_and(|faces| faces.iter().any(|name| name == "egui-icons")),
|
||||
"{chr:?} (U+{:04X}) should be in egui-icons, but was only in {faces:?}",
|
||||
chr as u32
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_fallback_glyph_width() {
|
||||
let mut fonts = Fonts::new(TextOptions::default(), FontDefinitions::empty());
|
||||
|
||||
@@ -3,9 +3,10 @@ use nohash_hasher::IntMap;
|
||||
use skrifa::GlyphId;
|
||||
|
||||
use crate::{
|
||||
ColorImage, FontColorTransferFunction, ImageDelta, TextOptions, TextureAtlas,
|
||||
FontColorTransferFunction, ImageDelta, TextOptions, TextureAtlas,
|
||||
text::{
|
||||
FontFamily, GlyphRasterizer, GlyphRasterizerRequest, MAX_GLYPH_SIZE,
|
||||
FontFamily, GlyphBitmap, GlyphRasterizer, GlyphRasterizerRequest, MAX_GLYPH_SIZE,
|
||||
RasterizedGlyph,
|
||||
face_store::FontFaceKey,
|
||||
font_face::{FontFace, ShapedGlyph},
|
||||
styled_metrics::StyledMetrics,
|
||||
@@ -43,6 +44,10 @@ impl UvRect {
|
||||
pub struct GlyphAllocation {
|
||||
/// UV rectangle for drawing.
|
||||
pub uv_rect: UvRect,
|
||||
|
||||
/// A color glyph (e.g. emoji), stored with its own colors in the atlas.
|
||||
/// Do not tint it with the text color.
|
||||
pub is_color: bool,
|
||||
}
|
||||
|
||||
/// An outline glyph in the atlas, positioned for one [`ShapedGlyph`].
|
||||
@@ -63,16 +68,6 @@ pub(crate) struct OutlineGlyph {
|
||||
pub(crate) struct RasterGlyphAllocation {
|
||||
pub allocation: GlyphAllocation,
|
||||
pub advance_px: f32,
|
||||
pub is_color: bool,
|
||||
}
|
||||
|
||||
/// A glyph bitmap, ready to be copied into the atlas.
|
||||
pub(crate) struct GlyphBitmap {
|
||||
/// Physical pixels. Coverage glyphs are white with alpha; color glyphs keep their colors.
|
||||
pub image: ColorImage,
|
||||
|
||||
/// Offset from the glyph origin to the top-left of the image, in physical pixels.
|
||||
pub offset_px: Vec2,
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
@@ -260,6 +255,9 @@ impl GlyphAtlas {
|
||||
|
||||
/// Get or render the glyph of `face` for `shaped`.
|
||||
///
|
||||
/// [`GlyphId::NOTDEF`] renders the face's `.notdef` glyph ("tofu"),
|
||||
/// which is what we show for characters no font has.
|
||||
///
|
||||
/// The bitmap is rendered at the sub-pixel bin of [`ShapedGlyph::h_pos`]
|
||||
/// (if the face has sub-pixel binning on, and the glyph is not CJK),
|
||||
/// so the same glyph can occupy up to four slots in the atlas.
|
||||
@@ -278,19 +276,14 @@ impl GlyphAtlas {
|
||||
is_cjk,
|
||||
} = *shaped;
|
||||
|
||||
if glyph_id == GlyphId::NOTDEF {
|
||||
// invisible
|
||||
return OutlineGlyph {
|
||||
allocation: GlyphAllocation::default(),
|
||||
x_px: h_pos.round() as i32,
|
||||
};
|
||||
}
|
||||
|
||||
let (x_px, bin) = if face.subpixel_binning() && !is_cjk {
|
||||
let subpixel_binning =
|
||||
face.subpixel_binning() && !is_cjk && !face.is_color_glyph(metrics, glyph_id);
|
||||
let (x_px, bin) = if subpixel_binning {
|
||||
SubpixelBin::new(h_pos)
|
||||
} else {
|
||||
// CJK scripts contain a lot of characters and could hog the glyph atlas
|
||||
// if we stored 4 subpixel offsets per glyph.
|
||||
// Color glyphs (emoji) are big, and gain nothing from subpixel positioning.
|
||||
(h_pos.round() as i32, SubpixelBin::Zero)
|
||||
};
|
||||
|
||||
@@ -302,14 +295,16 @@ impl GlyphAtlas {
|
||||
..
|
||||
} = self;
|
||||
let allocation = *outline_glyphs.entry(key).or_insert_with(|| {
|
||||
face.rasterize_outline(metrics, glyph_id, bin)
|
||||
face.rasterize_glyph(metrics, glyph_id, bin)
|
||||
.and_then(|bitmap| {
|
||||
let transfer = atlas.options().color_transfer_function;
|
||||
Self::allocate_bitmap(atlas, &bitmap, metrics.pixels_per_point, transfer)
|
||||
})
|
||||
.map(|mut uv_rect| {
|
||||
let transfer = Self::transfer_function(atlas, bitmap.is_color);
|
||||
let mut uv_rect =
|
||||
Self::allocate_bitmap(atlas, &bitmap, metrics.pixels_per_point, transfer)?;
|
||||
uv_rect.offset.y += metrics.y_offset_in_points;
|
||||
GlyphAllocation { uv_rect }
|
||||
Some(GlyphAllocation {
|
||||
uv_rect,
|
||||
is_color: bitmap.is_color,
|
||||
})
|
||||
})
|
||||
.unwrap_or_default()
|
||||
});
|
||||
@@ -341,30 +336,31 @@ impl GlyphAtlas {
|
||||
font_size_px: font_size * pixels_per_point,
|
||||
subpixel_offset_px: 0.0,
|
||||
};
|
||||
let allocation = (rasterizer.rasterize)(&request).and_then(|glyph| {
|
||||
// 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 {
|
||||
FontColorTransferFunction::Off
|
||||
} else {
|
||||
self.atlas.options().color_transfer_function
|
||||
};
|
||||
let bitmap = GlyphBitmap {
|
||||
image: glyph.image,
|
||||
offset_px: glyph.offset_px,
|
||||
};
|
||||
let uv_rect =
|
||||
Self::allocate_bitmap(&mut self.atlas, &bitmap, pixels_per_point, transfer)?;
|
||||
Some(RasterGlyphAllocation {
|
||||
allocation: GlyphAllocation { uv_rect },
|
||||
advance_px: glyph.advance_px,
|
||||
is_color: glyph.is_color,
|
||||
})
|
||||
});
|
||||
let allocation =
|
||||
(rasterizer.rasterize)(&request).and_then(|RasterizedGlyph { bitmap, advance_px }| {
|
||||
let is_color = bitmap.is_color;
|
||||
let transfer = Self::transfer_function(&self.atlas, is_color);
|
||||
let uv_rect =
|
||||
Self::allocate_bitmap(&mut self.atlas, &bitmap, pixels_per_point, transfer)?;
|
||||
Some(RasterGlyphAllocation {
|
||||
allocation: GlyphAllocation { uv_rect, is_color },
|
||||
advance_px,
|
||||
})
|
||||
});
|
||||
self.raster_glyphs.insert(key, allocation);
|
||||
allocation
|
||||
}
|
||||
|
||||
/// The transfer function assumes white coverage glyphs and discards color,
|
||||
/// so color glyphs (e.g. emoji) must skip it.
|
||||
fn transfer_function(atlas: &TextureAtlas, is_color: bool) -> FontColorTransferFunction {
|
||||
if is_color {
|
||||
FontColorTransferFunction::Off
|
||||
} else {
|
||||
atlas.options().color_transfer_function
|
||||
}
|
||||
}
|
||||
|
||||
/// Copy a bitmap into the atlas.
|
||||
///
|
||||
/// Returns `None` for empty and oversized bitmaps.
|
||||
|
||||
@@ -17,60 +17,38 @@ pub struct GlyphRasterizerRequest<'a> {
|
||||
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.
|
||||
/// A glyph bitmap, ready to be copied into the glyph atlas.
|
||||
#[derive(Clone)]
|
||||
pub struct GlyphBitmap {
|
||||
/// Pixels in physical pixels. Coverage glyphs are white with alpha;
|
||||
/// color glyphs retain their original colors.
|
||||
pub image: ColorImage,
|
||||
|
||||
/// Offset from the baseline to the image top-left, in physical pixels.
|
||||
/// Offset from the glyph origin to the image top-left, in physical pixels.
|
||||
pub offset_px: emath::Vec2,
|
||||
|
||||
/// A color glyph (e.g. emoji) that must not be tinted with the text color.
|
||||
pub is_color: bool,
|
||||
}
|
||||
|
||||
/// A glyph rasterized by a platform fallback.
|
||||
#[derive(Clone)]
|
||||
pub struct RasterizedGlyph {
|
||||
pub bitmap: GlyphBitmap,
|
||||
|
||||
/// Horizontal advance, in physical pixels.
|
||||
pub advance_px: f32,
|
||||
|
||||
/// Do not tint this glyph with the text color.
|
||||
pub is_color: bool,
|
||||
}
|
||||
|
||||
/// The callback of a [`GlyphRasterizer`].
|
||||
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`](crate::text::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`](crate::text::FontDefinitions) can render.
|
||||
///
|
||||
/// Set with `egui::Context::set_glyph_source_preference` or [`Fonts::with_glyph_source_preference`](crate::text::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`].
|
||||
/// Used for clusters that no installed font can render,
|
||||
/// after the [`FontProvider`](crate::text::FontProvider)s have been asked for a font for them.
|
||||
#[derive(Clone)]
|
||||
pub struct GlyphRasterizer {
|
||||
/// Rasterize one grapheme cluster.
|
||||
@@ -92,17 +70,6 @@ impl GlyphRasterizer {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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")
|
||||
@@ -118,7 +85,7 @@ impl core::fmt::Debug for GlyphRasterizer {
|
||||
/// False for text-presentation symbols (⏮, ✔, ♥) and for clusters
|
||||
/// with an explicit text presentation selector (⏮︎, U+FE0E).
|
||||
///
|
||||
/// Used by [`default_glyph_source`].
|
||||
/// Used by `eframe`'s web glyph rasterizer to guess whether a browser-drawn glyph is color.
|
||||
pub fn has_emoji_presentation(cluster: &str) -> bool {
|
||||
use unicode_properties::emoji::{
|
||||
EmojiStatus, UnicodeEmoji as _, is_emoji_presentation_selector,
|
||||
|
||||
@@ -7,6 +7,7 @@ mod font_data;
|
||||
mod font_definitions;
|
||||
mod font_face;
|
||||
mod font_id;
|
||||
mod font_provider;
|
||||
mod font_tweak;
|
||||
mod fonts;
|
||||
mod galley_cache;
|
||||
@@ -19,14 +20,15 @@ mod text_layout_types;
|
||||
mod unicode;
|
||||
|
||||
pub use {
|
||||
font_data::{FontData, FontVariationAxis},
|
||||
font_data::{Blob, FontData, FontVariationAxis},
|
||||
font_definitions::{FontDefinitions, FontInsert, FontPriority, InsertFontFamily},
|
||||
font_id::{FontFamily, FontId},
|
||||
font_provider::{FallbackRequest, FontProvider},
|
||||
font_tweak::{FontTweak, HintingTarget, SmoothHinting},
|
||||
fonts::{Fonts, FontsView, MAX_GLYPH_SIZE},
|
||||
glyph_rasterizer::{
|
||||
GlyphRasterizer, GlyphRasterizerRequest, GlyphSource, GlyphSourcePreference,
|
||||
RasterizedGlyph, default_glyph_source, has_emoji_presentation,
|
||||
GlyphBitmap, GlyphRasterizer, GlyphRasterizerRequest, RasterizedGlyph,
|
||||
has_emoji_presentation,
|
||||
},
|
||||
index::{ByteIndex, ByteRange, ByteRangeExt, CharIndex, CharRange, CharRangeExt},
|
||||
text_layout_types::*,
|
||||
|
||||
@@ -12,37 +12,21 @@ use crate::{
|
||||
ByteIndex, ByteRange,
|
||||
face_store::FontFaceKey,
|
||||
fonts::FontsImpl,
|
||||
glyph_atlas::UvRect,
|
||||
styled_metrics::StyledMetrics,
|
||||
unicode::{is_cjk, is_cjk_break_allowed},
|
||||
unicode::{is_cjk, is_cjk_break_allowed, is_combining_mark},
|
||||
},
|
||||
};
|
||||
|
||||
use super::{
|
||||
ByteRangeExt as _, Galley, Glyph, GlyphSource, LayoutJob, LayoutSection, PlacedRow, Row,
|
||||
RowVisuals, VariationCoords,
|
||||
ByteRangeExt as _, Galley, Glyph, LayoutJob, LayoutSection, PlacedRow, Row, RowVisuals,
|
||||
VariationCoords,
|
||||
family::FamilyKey,
|
||||
font_face::{FontFace, ShapedGlyph},
|
||||
glyph_atlas::{OutlineGlyph, RasterGlyphAllocation},
|
||||
font_face::{FontFace, GlyphInfo, ShapedGlyph},
|
||||
glyph_atlas::{GlyphAllocation, OutlineGlyph, RasterGlyphAllocation},
|
||||
};
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
/// Returns `true` if the character is a Unicode combining mark (categories Mn, Mc, Me).
|
||||
///
|
||||
/// These characters modify the preceding base character and should not be
|
||||
/// rendered as standalone replacement glyphs when the shaper can't handle them.
|
||||
#[inline]
|
||||
fn is_combining_mark(c: char) -> bool {
|
||||
use unicode_general_category::{GeneralCategory, get_general_category};
|
||||
matches!(
|
||||
get_general_category(c),
|
||||
GeneralCategory::NonspacingMark
|
||||
| GeneralCategory::SpacingMark
|
||||
| GeneralCategory::EnclosingMark
|
||||
)
|
||||
}
|
||||
|
||||
/// Represents GUI scale and convenience methods for rounding to pixels.
|
||||
#[derive(Clone, Copy)]
|
||||
struct PointScale {
|
||||
@@ -199,8 +183,9 @@ impl ShapingContext {
|
||||
physical_x: i32,
|
||||
advance_width_px: f32,
|
||||
face_metrics: &StyledMetrics,
|
||||
uv_rect: UvRect,
|
||||
alloc: GlyphAllocation,
|
||||
) -> Glyph {
|
||||
let GlyphAllocation { uv_rect, is_color } = alloc;
|
||||
Glyph {
|
||||
chr,
|
||||
pos: pos2(physical_x as f32 / self.pixels_per_point, f32::NAN),
|
||||
@@ -211,7 +196,7 @@ impl ShapingContext {
|
||||
font_height: self.font_metrics.row_height,
|
||||
font_ascent: self.font_metrics.ascent,
|
||||
uv_rect,
|
||||
is_color: false,
|
||||
is_color,
|
||||
section_index: self.section_index,
|
||||
first_vertex: 0,
|
||||
}
|
||||
@@ -226,14 +211,6 @@ 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`].
|
||||
@@ -320,7 +297,7 @@ fn layout_shaped_run(
|
||||
let glyph = if glyph_id == skrifa::GlyphId::NOTDEF {
|
||||
// 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.
|
||||
// or rendered as the `.notdef` glyph ("tofu") if no rasterizer can handle the cluster.
|
||||
if is_combining_mark(chr) || !is_new_cluster {
|
||||
continue;
|
||||
}
|
||||
@@ -355,25 +332,18 @@ fn layout_shaped_run(
|
||||
let (_, glyph_info) = fonts.glyph_info(ctx.family, chr, &fallback_metrics);
|
||||
let advance_width_px =
|
||||
glyph_info.advance_width_unscaled.0 * fallback_metrics.px_scale_factor;
|
||||
let OutlineGlyph { allocation, x_px } = fonts.allocate_glyph(
|
||||
let OutlineGlyph { allocation, x_px } = allocate_glyph_info(
|
||||
fonts,
|
||||
fallback_key,
|
||||
&fallback_metrics,
|
||||
&ShapedGlyph {
|
||||
glyph_id: glyph_info.id.unwrap_or(skrifa::GlyphId::NOTDEF),
|
||||
h_pos: paragraph.cursor_x_px,
|
||||
is_cjk: is_cjk(chr),
|
||||
},
|
||||
glyph_info,
|
||||
paragraph.cursor_x_px,
|
||||
chr,
|
||||
);
|
||||
|
||||
paragraph.cursor_x_px += advance_width_px;
|
||||
|
||||
ctx.glyph(
|
||||
chr,
|
||||
x_px,
|
||||
advance_width_px,
|
||||
&fallback_metrics,
|
||||
allocation.uv_rect,
|
||||
)
|
||||
ctx.glyph(chr, x_px, advance_width_px, &fallback_metrics, allocation)
|
||||
}
|
||||
} else {
|
||||
let OutlineGlyph {
|
||||
@@ -395,13 +365,7 @@ fn layout_shaped_run(
|
||||
|
||||
paragraph.cursor_x_px += advance_width_px;
|
||||
|
||||
ctx.glyph(
|
||||
chr,
|
||||
x_px,
|
||||
advance_width_px,
|
||||
face_metrics,
|
||||
glyph_alloc.uv_rect,
|
||||
)
|
||||
ctx.glyph(chr, x_px, advance_width_px, face_metrics, glyph_alloc)
|
||||
};
|
||||
paragraph.glyphs.push(glyph);
|
||||
cluster_glyph_count += 1;
|
||||
@@ -420,6 +384,32 @@ fn layout_shaped_run(
|
||||
}
|
||||
}
|
||||
|
||||
/// Put `glyph_info` in the atlas, or nothing at all if it is invisible.
|
||||
fn allocate_glyph_info(
|
||||
fonts: &mut FontsImpl,
|
||||
face_key: FontFaceKey,
|
||||
metrics: &StyledMetrics,
|
||||
glyph_info: GlyphInfo,
|
||||
h_pos_px: f32,
|
||||
chr: char,
|
||||
) -> OutlineGlyph {
|
||||
let Some(glyph_id) = glyph_info.id else {
|
||||
return OutlineGlyph {
|
||||
allocation: GlyphAllocation::default(),
|
||||
x_px: h_pos_px.round() as i32,
|
||||
};
|
||||
};
|
||||
fonts.allocate_glyph(
|
||||
face_key,
|
||||
metrics,
|
||||
&ShapedGlyph {
|
||||
glyph_id,
|
||||
h_pos: h_pos_px,
|
||||
is_cjk: is_cjk(chr),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// Emit one glyph for a rasterized cluster and advance the cursor.
|
||||
fn raster_glyph(
|
||||
ctx: &ShapingContext,
|
||||
@@ -430,87 +420,13 @@ fn raster_glyph(
|
||||
) -> Glyph {
|
||||
let physical_x = paragraph.cursor_x_px.round() as i32;
|
||||
paragraph.cursor_x_px += raster.advance_px;
|
||||
let mut glyph = ctx.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(
|
||||
fonts: &mut FontsImpl,
|
||||
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) = fonts.face(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) =
|
||||
fonts.rasterize_cluster(ctx.family, cluster, ctx.pixels_per_point, ctx.font_size)
|
||||
else {
|
||||
// Shape this one cluster with the font instead.
|
||||
let Some(font_face) = fonts.face(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(
|
||||
fonts,
|
||||
&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
|
||||
raster.allocation,
|
||||
)
|
||||
}
|
||||
|
||||
/// Emit zero-width continuation glyphs when a cluster has more characters than
|
||||
@@ -518,7 +434,7 @@ fn layout_raster_run(
|
||||
///
|
||||
/// This preserves the invariant `glyphs.len() == char_count` that all cursor
|
||||
/// and text-selection code depends on. Continuation glyphs have
|
||||
/// [`UvRect::default()`] so [`tessellate_glyphs`] skips them entirely.
|
||||
/// [`GlyphAllocation::default()`] so [`tessellate_glyphs`] skips them entirely.
|
||||
fn emit_continuation_glyphs(
|
||||
ctx: &ShapingContext,
|
||||
paragraph: &mut Paragraph,
|
||||
@@ -538,9 +454,13 @@ fn emit_continuation_glyphs(
|
||||
let physical_x = paragraph.cursor_x_px.round() as i32;
|
||||
|
||||
for chr in cluster_text.chars().skip(cluster_glyph_count) {
|
||||
paragraph
|
||||
.glyphs
|
||||
.push(ctx.glyph(chr, physical_x, 0.0, face_metrics, UvRect::default()));
|
||||
paragraph.glyphs.push(ctx.glyph(
|
||||
chr,
|
||||
physical_x,
|
||||
0.0,
|
||||
face_metrics,
|
||||
GlyphAllocation::default(),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -614,41 +534,28 @@ fn layout_section(
|
||||
let face_metrics =
|
||||
font_face.styled_metrics(pixels_per_point, font_size, &format.coords);
|
||||
|
||||
if run.source == GlyphSource::Platform && fonts.has_glyph_rasterizer() {
|
||||
shape_buffer = layout_raster_run(
|
||||
fonts,
|
||||
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(
|
||||
fonts,
|
||||
run,
|
||||
run_text,
|
||||
&glyph_buffer,
|
||||
&face_metrics,
|
||||
&mut ctx,
|
||||
paragraph,
|
||||
);
|
||||
|
||||
shape_buffer = glyph_buffer.clear();
|
||||
// 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(
|
||||
fonts,
|
||||
run,
|
||||
run_text,
|
||||
&glyph_buffer,
|
||||
&face_metrics,
|
||||
&mut ctx,
|
||||
paragraph,
|
||||
);
|
||||
|
||||
shape_buffer = glyph_buffer.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -938,14 +845,13 @@ fn replace_last_glyph_with_overflow_character(
|
||||
let OutlineGlyph {
|
||||
allocation: replacement_glyph_alloc,
|
||||
x_px,
|
||||
} = fonts.allocate_glyph(
|
||||
} = allocate_glyph_info(
|
||||
fonts,
|
||||
face_key,
|
||||
&font_face_metrics,
|
||||
&ShapedGlyph {
|
||||
glyph_id: glyph_info.id.unwrap_or(skrifa::GlyphId::NOTDEF),
|
||||
h_pos: overflow_glyph_x * pixels_per_point,
|
||||
is_cjk: is_cjk(overflow_character),
|
||||
},
|
||||
glyph_info,
|
||||
overflow_glyph_x * pixels_per_point,
|
||||
overflow_character,
|
||||
);
|
||||
|
||||
let font_metrics =
|
||||
@@ -1510,13 +1416,10 @@ fn segment_into_runs(fonts: &mut FontsImpl, family: FamilyKey, text: &str, out:
|
||||
let byte_offset = ByteIndex(byte_offset);
|
||||
let byte_end = byte_offset + grapheme_str.len();
|
||||
|
||||
let base_char = grapheme_str.chars().next().unwrap_or(' ');
|
||||
let font_key = fonts.resolve_face(family, base_char);
|
||||
let source = fonts.glyph_source(grapheme_str);
|
||||
let font_key = fonts.resolve_cluster_face(family, 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;
|
||||
@@ -1524,7 +1427,6 @@ fn segment_into_runs(fonts: &mut FontsImpl, family: FamilyKey, text: &str, out:
|
||||
out.push(TextRun {
|
||||
font_key,
|
||||
byte_range: byte_offset..byte_end,
|
||||
source,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1584,15 +1486,24 @@ mod tests {
|
||||
FontsImpl::new(TextOptions::default(), FontDefinitions::default())
|
||||
}
|
||||
|
||||
/// Only `Hack`, which has no emoji.
|
||||
#[cfg(feature = "default_fonts")]
|
||||
fn hack_only() -> FontDefinitions {
|
||||
let mut definitions = FontDefinitions::empty();
|
||||
definitions.font_data.insert(
|
||||
"Hack".to_owned(),
|
||||
Arc::new(FontData::from_static(epaint_default_fonts::HACK_REGULAR)),
|
||||
);
|
||||
definitions
|
||||
.families
|
||||
.insert(FontFamily::Proportional, vec!["Hack".to_owned()]);
|
||||
definitions
|
||||
}
|
||||
|
||||
#[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,
|
||||
})
|
||||
(request.cluster == "한").then(color_raster_glyph)
|
||||
});
|
||||
let mut fonts = FontsImpl::new(TextOptions::default(), FontDefinitions::default())
|
||||
.with_glyph_rasterizer(rasterizer);
|
||||
@@ -1646,14 +1557,8 @@ mod tests {
|
||||
|
||||
#[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,
|
||||
})
|
||||
});
|
||||
let rasterizer =
|
||||
GlyphRasterizer::new(|_: &GlyphRasterizerRequest<'_>| Some(color_raster_glyph()));
|
||||
// The default transfer function discards color for regular (white) glyphs:
|
||||
let options = TextOptions {
|
||||
color_transfer_function: crate::FontColorTransferFunction::TwoCoverageMinusCoverageSq,
|
||||
@@ -1681,33 +1586,35 @@ mod tests {
|
||||
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,
|
||||
})
|
||||
result.clone()
|
||||
})
|
||||
}
|
||||
|
||||
fn white_raster_glyph() -> RasterizedGlyph {
|
||||
RasterizedGlyph {
|
||||
image: ColorImage::new([1, 1], vec![Color32::WHITE]),
|
||||
offset_px: Vec2::ZERO,
|
||||
bitmap: GlyphBitmap {
|
||||
image: ColorImage::new([1, 1], vec![Color32::WHITE]),
|
||||
offset_px: Vec2::ZERO,
|
||||
is_color: false,
|
||||
},
|
||||
advance_px: 10.0,
|
||||
is_color: false,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "default_fonts")]
|
||||
fn color_raster_glyph() -> RasterizedGlyph {
|
||||
RasterizedGlyph {
|
||||
image: ColorImage::new([1, 1], vec![Color32::RED]),
|
||||
is_color: true,
|
||||
bitmap: GlyphBitmap {
|
||||
image: ColorImage::new([1, 1], vec![Color32::RED]),
|
||||
is_color: true,
|
||||
..white_raster_glyph().bitmap
|
||||
},
|
||||
..white_raster_glyph()
|
||||
}
|
||||
}
|
||||
|
||||
/// `(chr, is_color, has_pixels)` for each glyph.
|
||||
#[cfg(feature = "default_fonts")]
|
||||
fn glyph_summary(galley: &Galley) -> Vec<(char, bool, bool)> {
|
||||
galley
|
||||
.rows
|
||||
@@ -1718,59 +1625,13 @@ mod tests {
|
||||
}
|
||||
|
||||
#[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]
|
||||
#[cfg(feature = "default_fonts")] // Needs `hack_only`
|
||||
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);
|
||||
// No font has the emoji, so the rasterizer gets the whole cluster:
|
||||
let mut fonts =
|
||||
FontsImpl::new(TextOptions::default(), hack_only()).with_glyph_rasterizer(rasterizer);
|
||||
let family = "👨\u{200D}👩\u{200D}👧";
|
||||
let job = LayoutJob::simple(
|
||||
family.to_owned(),
|
||||
@@ -1791,37 +1652,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[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()));
|
||||
@@ -1869,7 +1699,7 @@ mod tests {
|
||||
assert_eq!(glyph.chr, '한');
|
||||
assert!(
|
||||
!glyph.uv_rect.is_nothing(),
|
||||
"Should render the replacement glyph"
|
||||
"Should render the `.notdef` glyph"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1933,6 +1763,8 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
// No bundled font has CJK glyphs, so the line breaks depend on
|
||||
// the width of the `.notdef` glyph of the primary font.
|
||||
fn test_cjk() {
|
||||
let pixels_per_point = 1.0;
|
||||
let mut fonts = test_fonts();
|
||||
@@ -1944,11 +1776,13 @@ mod tests {
|
||||
let galley = layout(&mut fonts, pixels_per_point, layout_job.into());
|
||||
assert_eq!(
|
||||
galley.rows.iter().map(|row| row.text()).collect::<Vec<_>>(),
|
||||
vec!["日本語と", "Englishの混在", "した文章"]
|
||||
vec!["日本語とEnglishの混", "在した文章"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
// No bundled font has CJK glyphs, so the line breaks depend on
|
||||
// the width of the `.notdef` glyph of the primary font.
|
||||
fn test_pre_cjk() {
|
||||
let pixels_per_point = 1.0;
|
||||
let mut fonts = test_fonts();
|
||||
@@ -1960,7 +1794,7 @@ mod tests {
|
||||
let galley = layout(&mut fonts, pixels_per_point, layout_job.into());
|
||||
assert_eq!(
|
||||
galley.rows.iter().map(|row| row.text()).collect::<Vec<_>>(),
|
||||
vec!["日本語とEnglish", "の混在した文章"]
|
||||
vec!["日本語とEnglishの混在した", "文章"]
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2102,7 +1936,7 @@ mod tests {
|
||||
// ɔ̃ = U+0254 (LATIN SMALL LETTER OPEN O) + U+0303 (COMBINING TILDE)
|
||||
// With text shaping, the combining tilde should NOT produce a separate
|
||||
// advance — it should be positioned above ɔ via GPOS anchors.
|
||||
// Note: the default fonts don't contain U+0254, so the replacement glyph
|
||||
// Note: the default fonts don't contain U+0254, so the `.notdef` 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 = test_fonts();
|
||||
|
||||
@@ -73,7 +73,7 @@ pub struct LayoutJob {
|
||||
/// starting on a new row.
|
||||
///
|
||||
/// If `false`, all `\n` characters will be ignored
|
||||
/// and show up as the replacement character.
|
||||
/// and show up as the `.notdef` glyph ("tofu").
|
||||
///
|
||||
/// Default: `true`.
|
||||
pub break_on_newline: bool,
|
||||
@@ -155,7 +155,7 @@ impl LayoutJob {
|
||||
}
|
||||
}
|
||||
|
||||
/// Does not break on `\n`, but shows the replacement character instead.
|
||||
/// Does not break on `\n`, but shows the `.notdef` glyph ("tofu") instead.
|
||||
#[inline]
|
||||
pub fn simple_singleline(text: String, font_id: FontId, color: Color32) -> Self {
|
||||
Self {
|
||||
|
||||
@@ -69,3 +69,18 @@ pub(super) fn is_cjk_break_allowed(c: char) -> bool {
|
||||
// See: https://en.wikipedia.org/wiki/Line_breaking_rules_in_East_Asian_languages#Characters_not_permitted_on_the_start_of_a_line.
|
||||
!")]}〕〉》」』】〙〗〟'\"⦆»ヽヾーァィゥェォッャュョヮヵヶぁぃぅぇぉっゃゅょゎゕゖㇰㇱㇲㇳㇴㇵㇶㇷㇸㇹㇺㇻㇼㇽㇾㇿ々〻‐゠–〜?!‼⁇⁈⁉・、:;,。.".contains(c)
|
||||
}
|
||||
|
||||
/// Returns `true` if the character is a Unicode combining mark (categories Mn, Mc, Me).
|
||||
///
|
||||
/// These characters modify the preceding base character and should not be
|
||||
/// rendered as standalone replacement glyphs when the shaper can't handle them.
|
||||
#[inline]
|
||||
pub(super) fn is_combining_mark(c: char) -> bool {
|
||||
use unicode_general_category::{GeneralCategory, get_general_category};
|
||||
matches!(
|
||||
get_general_category(c),
|
||||
GeneralCategory::NonspacingMark
|
||||
| GeneralCategory::SpacingMark
|
||||
| GeneralCategory::EnclosingMark
|
||||
)
|
||||
}
|
||||
@@ -25,6 +25,15 @@ include = [
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[features]
|
||||
default = []
|
||||
|
||||
## Bundle the monochrome emoji fonts [`NOTO_EMOJI_REGULAR`] and [`EMOJI_ICON`].
|
||||
##
|
||||
## They add about 1 MB to the binary, and are only needed if you want the same
|
||||
## (monochrome) emoji on every platform, instead of the platform's own color emoji.
|
||||
monochrome_emoji_fonts = []
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
rustdoc-args = ["--generate-link-to-definition"]
|
||||
Binary file not shown.
@@ -0,0 +1,23 @@
|
||||
egui-icons.ttf
|
||||
|
||||
A subset of emoji-icon-font.ttf (https://github.com/jslegers/emoji-icon-font),
|
||||
containing only the five glyphs that egui exposes as `egui::special_emojis`:
|
||||
|
||||
U+E618 the Android logo
|
||||
U+E61F the Windows logo
|
||||
U+E624 the GitHub logo
|
||||
U+E625 the word `git`
|
||||
U+F8FF the Apple logo
|
||||
|
||||
No platform font has these, so egui bundles them even when the rest of
|
||||
emoji-icon-font.ttf is left out (the `monochrome_emoji_fonts` feature).
|
||||
|
||||
Regenerate with:
|
||||
|
||||
pip install fonttools
|
||||
python3 -m fontTools.subset emoji-icon-font.ttf \
|
||||
--unicodes=E618,E61F,E624,E625,F8FF \
|
||||
--no-hinting --desubroutinize \
|
||||
--output-file=egui-icons.ttf
|
||||
|
||||
The license is that of emoji-icon-font.ttf: see emoji-icon-font-mit-license.txt.
|
||||
@@ -2,6 +2,8 @@
|
||||
//!
|
||||
//! This is intended to be consumed through the `epaint` crate.
|
||||
|
||||
pub mod special_emojis;
|
||||
|
||||
/// A typeface designed for source code.
|
||||
///
|
||||
/// Hack is designed to be a workhorse typeface for source code. It has deep
|
||||
@@ -17,6 +19,8 @@ pub const HACK_REGULAR: &[u8] = include_bytes!("../fonts/Hack-Regular.ttf");
|
||||
|
||||
/// A typeface containing emoji characters as designed for the Noto font family.
|
||||
///
|
||||
/// Requires the `monochrome_emoji_fonts` feature.
|
||||
///
|
||||
/// Noto is a collection of high-quality fonts with multiple weights and widths
|
||||
/// in sans, serif, mono, and other styles, in more than 1,000 languages and
|
||||
/// over 150 writing systems. Noto Emoji contains black-and-white emoji
|
||||
@@ -24,6 +28,7 @@ pub const HACK_REGULAR: &[u8] = include_bytes!("../fonts/Hack-Regular.ttf");
|
||||
///
|
||||
/// See [Google Fonts](https://fonts.google.com/noto/specimen/Noto+Emoji) for
|
||||
/// more information.
|
||||
#[cfg(feature = "monochrome_emoji_fonts")]
|
||||
pub const NOTO_EMOJI_REGULAR: &[u8] = include_bytes!("../fonts/NotoEmoji-Regular.ttf");
|
||||
|
||||
/// A typeface designed for use by Ubuntu.
|
||||
@@ -35,6 +40,8 @@ pub const NOTO_EMOJI_REGULAR: &[u8] = include_bytes!("../fonts/NotoEmoji-Regular
|
||||
/// See [Ubuntu design](https://design.ubuntu.com/font) for more information.
|
||||
pub const UBUNTU_LIGHT: &[u8] = include_bytes!("../fonts/Ubuntu-Light.ttf");
|
||||
|
||||
/// Requires the `monochrome_emoji_fonts` feature.
|
||||
///
|
||||
/// An experimental typeface that uses standardized
|
||||
/// [UNICODE planes](http://en.wikipedia.org/wiki/Plane_(Unicode))
|
||||
/// for icon fonts.
|
||||
@@ -44,4 +51,15 @@ pub const UBUNTU_LIGHT: &[u8] = include_bytes!("../fonts/Ubuntu-Light.ttf");
|
||||
///
|
||||
/// See [the `emoji-icon-font` repository](https://github.com/jslegers/emoji-icon-font)
|
||||
/// for more information.
|
||||
#[cfg(feature = "monochrome_emoji_fonts")]
|
||||
pub const EMOJI_ICON: &[u8] = include_bytes!("../fonts/emoji-icon-font.ttf");
|
||||
|
||||
/// The few icons that egui exposes as `egui::special_emojis`:
|
||||
/// the Android, Apple, GitHub, and Windows logos, and the word `git`.
|
||||
///
|
||||
/// This is a small (3.5 kB) subset of the
|
||||
/// [`emoji-icon-font`](https://github.com/jslegers/emoji-icon-font), bundled
|
||||
/// unconditionally because no platform font has these private-use codepoints.
|
||||
///
|
||||
/// See `fonts/egui-icons.txt` for how to regenerate it.
|
||||
pub const EGUI_ICONS: &[u8] = include_bytes!("../fonts/egui-icons.ttf");
|
||||
@@ -0,0 +1,47 @@
|
||||
//! A few special emojis that are not part of the unicode standard.
|
||||
//!
|
||||
//! Except for [`OS_LINUX`] they live in the private use area, so no platform
|
||||
//! font has them, which is why they are bundled in [`crate::EGUI_ICONS`].
|
||||
//!
|
||||
//! Besides these, egui renders whatever emoji the platform fonts have.
|
||||
//! With the `monochrome_emoji_fonts` feature you also get the bundled
|
||||
//! [`crate::NOTO_EMOJI_REGULAR`] and [`crate::EMOJI_ICON`], which add
|
||||
//! monochrome emoji and icons like:
|
||||
//!
|
||||
//! ```text
|
||||
//! ∞⊗⎗⎘⎙⏏⏴⏵⏶⏷
|
||||
//! ⏩⏪⏭⏮⏸⏹⏺■▶📾🔀🔁🔃
|
||||
//! ☀☁★☆☐☑☜☝☞☟⛃⛶✔
|
||||
//! ↺↻⟲⟳⬅➡⬆⬇⬈⬉⬊⬋⬌⬍⮨⮩⮪⮫
|
||||
//! ♡
|
||||
//! 📅📆
|
||||
//! 📈📉📊
|
||||
//! 📋📌📎📤📥🔆
|
||||
//! 🔈🔉🔊🔍🔎🔗🔘
|
||||
//! 🕓🖧🖩🖮🖱🖴🖵🖼🗀🗁🗋🗐🗑🗙🚫❓
|
||||
//! ```
|
||||
//!
|
||||
//! You can explore all the emoji of the current fonts in the Font Book in
|
||||
//! [the online demo](https://www.egui.rs/#demo).
|
||||
|
||||
/// Tux, the Linux penguin.
|
||||
///
|
||||
/// A normal emoji, covered by most emoji fonts.
|
||||
pub const OS_LINUX: char = '🐧';
|
||||
|
||||
/// The Windows logo.
|
||||
pub const OS_WINDOWS: char = '\u{E61F}';
|
||||
|
||||
/// The Android logo.
|
||||
pub const OS_ANDROID: char = '\u{E618}';
|
||||
|
||||
/// The Apple logo.
|
||||
pub const OS_APPLE: char = '\u{F8FF}';
|
||||
|
||||
/// The Github logo.
|
||||
pub const GITHUB: char = '\u{E624}';
|
||||
|
||||
/// The word `git`.
|
||||
pub const GIT: char = '\u{E625}';
|
||||
|
||||
// I really would like to have ferris here.
|
||||
@@ -58,10 +58,12 @@ skip = [
|
||||
{ name = "jni-sys" }, # 0.3.1 depends on 0.4
|
||||
{ name = "kurbo" }, # Old version because of resvg
|
||||
{ name = "phf" }, # mime_guess2 -> 0.11, unicode_names2 -> 0.13
|
||||
{ name = "png" }, # glifo (vello_cpu's text feature, for bitmap emoji) depends on 0.18, image 0.25.6 on 0.17
|
||||
{ name = "phf_generator" }, # same phf split as phf
|
||||
{ name = "phf_shared" }, # same phf split as phf
|
||||
{ name = "rand_core" }, # rand ecosystem is migrating 0.8 -> 0.10; phf_generator's rand 0.8 needs rand_core 0.6, getrandom 0.4/chacha20 need rand_core 0.10
|
||||
{ name = "redox_syscall" }, # old version via winit
|
||||
{ name = "roxmltree" }, # fontique (Android backend) depends on 0.21, resvg's usvg on 0.20
|
||||
{ name = "rustc-hash" }, # Small enough
|
||||
{ name = "thiserror" }, # ecosystem is in the process of migrating from 1.x to 2.x
|
||||
{ name = "thiserror-impl" }, # same as above
|
||||
|
||||
@@ -257,6 +257,7 @@ def main() -> None:
|
||||
"egui_glow",
|
||||
"egui_inspection",
|
||||
"egui_kittest",
|
||||
"egui_system_fonts",
|
||||
"egui-wgpu",
|
||||
"egui-winit",
|
||||
"egui",
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
(cd crates/egui-winit && cargo publish --quiet) && echo "✅ egui-winit"
|
||||
(cd crates/egui_glow && cargo publish --quiet) && echo "✅ egui_glow"
|
||||
(cd crates/egui-wgpu && cargo publish --quiet) && echo "✅ egui-wgpu"
|
||||
(cd crates/egui_system_fonts && cargo publish --quiet) && echo "✅ egui_system_fonts"
|
||||
(cd crates/egui_inspection && cargo publish --quiet) && echo "✅ eframe"
|
||||
(cd crates/eframe && cargo publish --quiet) && echo "✅ eframe"
|
||||
(cd crates/egui_extras && cargo publish --quiet) && echo "✅ egui_extras"
|
||||
|
||||
@@ -10,7 +10,11 @@ version.workspace = true
|
||||
ignored = ["image"] # We need the png feature
|
||||
|
||||
[dev-dependencies]
|
||||
egui = { workspace = true, default-features = true, features = ["experimental"] }
|
||||
# `monochrome_emoji_fonts` so that the snapshots keep their emoji:
|
||||
egui = { workspace = true, default-features = true, features = [
|
||||
"experimental",
|
||||
"monochrome_emoji_fonts",
|
||||
] }
|
||||
egui_kittest = { workspace = true, features = ["snapshot", "wgpu"] }
|
||||
egui_extras = { workspace = true, features = ["image"] }
|
||||
image = { workspace = true, features = ["png"] }
|
||||
|
||||
Reference in new issue
Block a user