1
0
mirror of https://github.com/emilk/egui.git synced 2026-08-30 13:20:05 -04:00

Choose your own font and size (#1154)

* Refactor text layout: don't need &Fonts in all functions
* Replace indexing in Fonts with member function
* Wrap Fonts in a Mutex
* Remove mutex for Font::glyph_info_cache
* Remove RwLock around Font::characters
* Put FontsImpl and GalleyCache behind the same Mutex
* Round font sizes to whole pixels before deduplicating them
* Make TextStyle !Copy
* Implement user-named TextStyle:s
* round font size earlier
* Cache fonts based on family and size
* Move TextStyle into egui and Style
* Remove body_text_style
* Query graphics about max texture size and use that as font atlas size
* Recreate texture atlas when it is getting full
This commit is contained in:
Emil Ernerfeldt
2022-01-24 14:32:36 +01:00
committed by GitHub
parent bb407e9b00
commit fa43d16c41
67 changed files with 1231 additions and 640 deletions

View File

@@ -1,6 +1,5 @@
use crate::{
mutex::{Arc, Mutex, RwLock},
text::TextStyle,
TextureAtlas,
};
use ahash::AHashMap;
@@ -59,7 +58,7 @@ impl Default for GlyphInfo {
pub struct FontImpl {
ab_glyph_font: ab_glyph::FontArc,
/// Maximum character height
scale_in_pixels: f32,
scale_in_pixels: u32,
height_in_points: f32,
// move each character by this much (hack)
y_offset: f32,
@@ -73,20 +72,13 @@ impl FontImpl {
atlas: Arc<Mutex<TextureAtlas>>,
pixels_per_point: f32,
ab_glyph_font: ab_glyph::FontArc,
scale_in_points: f32,
scale_in_pixels: u32,
y_offset: f32,
) -> FontImpl {
assert!(scale_in_points > 0.0);
assert!(scale_in_pixels > 0);
assert!(pixels_per_point > 0.0);
let scale_in_pixels = pixels_per_point * scale_in_points;
// Round to an even number of physical pixels to get even kerning.
// See https://github.com/emilk/egui/issues/382
let scale_in_pixels = scale_in_pixels.round();
let scale_in_points = scale_in_pixels / pixels_per_point;
let height_in_points = scale_in_points;
let height_in_points = scale_in_pixels as f32 / pixels_per_point;
// TODO: use v_metrics for line spacing ?
// let v = rusttype_font.v_metrics(Scale::uniform(scale_in_pixels));
@@ -162,7 +154,7 @@ impl FontImpl {
&mut self.atlas.lock(),
&self.ab_glyph_font,
glyph_id,
self.scale_in_pixels,
self.scale_in_pixels as f32,
self.y_offset,
self.pixels_per_point,
);
@@ -180,7 +172,7 @@ impl FontImpl {
) -> f32 {
use ab_glyph::{Font as _, ScaleFont};
self.ab_glyph_font
.as_scaled(self.scale_in_pixels)
.as_scaled(self.scale_in_pixels as f32)
.kern(last_glyph_id, glyph_id)
/ self.pixels_per_point
}
@@ -202,23 +194,21 @@ type FontIndex = usize;
// TODO: rename?
/// Wrapper over multiple `FontImpl` (e.g. a primary + fallbacks for emojis)
pub struct Font {
text_style: TextStyle,
fonts: Vec<Arc<FontImpl>>,
/// Lazily calculated.
characters: RwLock<Option<std::collections::BTreeSet<char>>>,
characters: Option<std::collections::BTreeSet<char>>,
replacement_glyph: (FontIndex, GlyphInfo),
pixels_per_point: f32,
row_height: f32,
glyph_info_cache: RwLock<AHashMap<char, (FontIndex, GlyphInfo)>>,
glyph_info_cache: AHashMap<char, (FontIndex, GlyphInfo)>,
}
impl Font {
pub fn new(text_style: TextStyle, fonts: Vec<Arc<FontImpl>>) -> Self {
pub fn new(fonts: Vec<Arc<FontImpl>>) -> Self {
if fonts.is_empty() {
return Self {
text_style,
fonts,
characters: RwLock::new(None),
characters: None,
replacement_glyph: Default::default(),
pixels_per_point: 1.0,
row_height: 0.0,
@@ -230,9 +220,8 @@ impl Font {
let row_height = fonts[0].row_height();
let mut slf = Self {
text_style,
fonts,
characters: RwLock::new(None),
characters: None,
replacement_glyph: Default::default(),
pixels_per_point,
row_height,
@@ -260,26 +249,20 @@ impl Font {
slf.glyph_info(c);
}
slf.glyph_info('°');
slf.glyph_info(crate::text::PASSWORD_REPLACEMENT_CHAR); // password replacement character
slf.glyph_info(crate::text::PASSWORD_REPLACEMENT_CHAR);
slf
}
/// All supported characters
pub fn characters(&self) -> BTreeSet<char> {
if self.characters.read().is_none() {
pub fn characters(&mut self) -> &BTreeSet<char> {
self.characters.get_or_insert_with(|| {
let mut characters = BTreeSet::new();
for font in &self.fonts {
characters.extend(font.characters());
}
self.characters.write().replace(characters);
}
self.characters.read().clone().unwrap()
}
#[inline(always)]
pub fn text_style(&self) -> TextStyle {
self.text_style
characters
})
}
#[inline(always)]
@@ -295,35 +278,30 @@ impl Font {
pub fn uv_rect(&self, c: char) -> UvRect {
self.glyph_info_cache
.read()
.get(&c)
.map(|gi| gi.1.uv_rect)
.unwrap_or_default()
}
/// Width of this character in points.
pub fn glyph_width(&self, c: char) -> f32 {
pub fn glyph_width(&mut self, c: char) -> f32 {
self.glyph_info(c).1.advance_width
}
/// `\n` will (intentionally) show up as the replacement character.
fn glyph_info(&self, c: char) -> (FontIndex, GlyphInfo) {
{
if let Some(font_index_glyph_info) = self.glyph_info_cache.read().get(&c) {
return *font_index_glyph_info;
}
fn glyph_info(&mut self, c: char) -> (FontIndex, GlyphInfo) {
if let Some(font_index_glyph_info) = self.glyph_info_cache.get(&c) {
return *font_index_glyph_info;
}
let font_index_glyph_info = self.glyph_info_no_cache_or_fallback(c);
let font_index_glyph_info = font_index_glyph_info.unwrap_or(self.replacement_glyph);
self.glyph_info_cache
.write()
.insert(c, font_index_glyph_info);
self.glyph_info_cache.insert(c, font_index_glyph_info);
font_index_glyph_info
}
#[inline]
pub(crate) fn glyph_info_and_font_impl(&self, c: char) -> (Option<&FontImpl>, GlyphInfo) {
pub(crate) fn glyph_info_and_font_impl(&mut self, c: char) -> (Option<&FontImpl>, GlyphInfo) {
if self.fonts.is_empty() {
return (None, self.replacement_glyph.1);
}
@@ -332,12 +310,10 @@ impl Font {
(Some(font_impl), glyph_info)
}
fn glyph_info_no_cache_or_fallback(&self, c: char) -> Option<(FontIndex, GlyphInfo)> {
fn glyph_info_no_cache_or_fallback(&mut self, c: char) -> Option<(FontIndex, GlyphInfo)> {
for (font_index, font_impl) in self.fonts.iter().enumerate() {
if let Some(glyph_info) = font_impl.glyph_info(c) {
self.glyph_info_cache
.write()
.insert(c, (font_index, glyph_info));
self.glyph_info_cache.insert(c, (font_index, glyph_info));
return Some((font_index, glyph_info));
}
}
@@ -379,11 +355,11 @@ fn allocate_glyph(
if v > 0.0 {
let px = glyph_pos.0 + x as usize;
let py = glyph_pos.1 + y as usize;
image[(px, py)] = (v * 255.0).round() as u8;
image[(px, py)] = fast_round(v * 255.0);
}
});
let offset_in_pixels = vec2(bb.min.x as f32, scale_in_pixels as f32 + bb.min.y as f32);
let offset_in_pixels = vec2(bb.min.x as f32, scale_in_pixels + bb.min.y as f32);
let offset = offset_in_pixels / pixels_per_point + y_offset * Vec2::Y;
UvRect {
offset,
@@ -407,3 +383,7 @@ fn allocate_glyph(
uv_rect,
}
}
fn fast_round(r: f32) -> u8 {
(r + 0.5).floor() as _ // rust does a saturating cast since 1.45
}

View File

@@ -1,63 +1,122 @@
use std::collections::BTreeMap;
use crate::{
mutex::{Arc, Mutex},
mutex::{Arc, Mutex, MutexGuard},
text::{
font::{Font, FontImpl},
Galley, LayoutJob,
},
TextureAtlas,
};
use emath::NumExt as _;
// TODO: rename
/// One of a few categories of styles of text, e.g. body, button or heading.
#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
// ----------------------------------------------------------------------------
/// How to select a sized font.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
pub enum TextStyle {
/// Used when small text is needed.
Small,
/// Normal labels. Easily readable, doesn't take up too much space.
Body,
/// Buttons. Maybe slightly bigger than `Body`.
Button,
/// Heading. Probably larger than `Body`.
Heading,
/// Same size as `Body`, but used when monospace is important (for aligning number, code snippets, etc).
Monospace,
pub struct FontId {
/// Height in points.
pub size: f32,
/// What font family to use.
pub family: FontFamily,
// TODO: weight (bold), italics, …
}
impl TextStyle {
pub fn all() -> impl ExactSizeIterator<Item = TextStyle> {
[
TextStyle::Small,
TextStyle::Body,
TextStyle::Button,
TextStyle::Heading,
TextStyle::Monospace,
]
.iter()
.copied()
impl Default for FontId {
#[inline]
fn default() -> Self {
Self {
size: 14.0,
family: FontFamily::Proportional,
}
}
}
/// Which style of font: [`Monospace`][`FontFamily::Monospace`] or [`Proportional`][`FontFamily::Proportional`].
#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
pub enum FontFamily {
/// A font where each character is the same width (`w` is the same width as `i`).
Monospace,
/// A font where some characters are wider than other (e.g. 'w' is wider than 'i').
Proportional,
impl FontId {
#[inline]
pub fn new(size: f32, family: FontFamily) -> Self {
Self { size, family }
}
#[inline]
pub fn proportional(size: f32) -> Self {
Self::new(size, FontFamily::Proportional)
}
#[inline]
pub fn monospace(size: f32) -> Self {
Self::new(size, FontFamily::Monospace)
}
}
#[allow(clippy::derive_hash_xor_eq)]
impl std::hash::Hash for FontId {
#[inline(always)]
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
let Self { size, family } = self;
crate::f32_hash(state, *size);
family.hash(state);
}
}
// ----------------------------------------------------------------------------
/// Font of unknown size.
///
/// Which style of font: [`Monospace`][`FontFamily::Monospace`], [`Proportional`][`FontFamily::Proportional`],
/// or by user-chosen name.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum FontFamily {
/// A font where some characters are wider than other (e.g. 'w' is wider than 'i').
///
/// Proportional fonts are easier to read and should be the preferred choice in most situations.
Proportional,
/// A font where each character is the same width (`w` is the same width as `i`).
///
/// Useful for code snippets, or when you need to align numbers or text.
Monospace,
/// One of the names in [`FontDefinitions::families`].
///
/// ```
/// # use epaint::FontFamily;
/// // User-chosen names:
/// FontFamily::Name("arial".into());
/// FontFamily::Name("serif".into());
/// ```
Name(Arc<str>),
}
impl Default for FontFamily {
#[inline]
fn default() -> Self {
FontFamily::Proportional
}
}
impl std::fmt::Display for FontFamily {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Monospace => "Monospace".fmt(f),
Self::Proportional => "Proportional".fmt(f),
Self::Name(name) => (*name).fmt(f),
}
}
}
// ----------------------------------------------------------------------------
/// A `.ttf` or `.otf` file and a font face index.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct FontData {
/// The content of a `.ttf` or `.otf` file.
pub font: std::borrow::Cow<'static, [u8]>,
/// Which font face in the file to use.
/// When in doubt, use `0`.
pub index: u32,
@@ -97,28 +156,12 @@ fn ab_glyph_font_from_font_data(name: &str, data: &FontData) -> ab_glyph::FontAr
///
/// Often you would start with [`FontDefinitions::default()`] and then add/change the contents.
///
/// This is how you install your own custom fonts:
/// ```
/// # use {epaint::text::{FontDefinitions, TextStyle, FontFamily}};
/// # use {epaint::text::{FontDefinitions, FontFamily, FontData}};
/// # struct FakeEguiCtx {};
/// # impl FakeEguiCtx { fn set_fonts(&self, _: FontDefinitions) {} }
/// # let ctx = FakeEguiCtx {};
/// let mut fonts = FontDefinitions::default();
///
/// // Large button text:
/// fonts.family_and_size.insert(
/// TextStyle::Button,
/// (FontFamily::Proportional, 32.0)
/// );
///
/// ctx.set_fonts(fonts);
/// ```
///
/// You can also install your own custom fonts:
/// ```
/// # use {epaint::text::{FontDefinitions, TextStyle, FontFamily, FontData}};
/// # struct FakeEguiCtx {};
/// # impl FakeEguiCtx { fn set_fonts(&self, _: FontDefinitions) {} }
/// # let ctx = FakeEguiCtx {};
/// # let egui_ctx = FakeEguiCtx {};
/// let mut fonts = FontDefinitions::default();
///
/// // Install my own font (maybe supporting non-latin characters):
@@ -126,14 +169,14 @@ fn ab_glyph_font_from_font_data(name: &str, data: &FontData) -> ab_glyph::FontAr
/// FontData::from_static(include_bytes!("../../fonts/Ubuntu-Light.ttf"))); // .ttf and .otf supported
///
/// // Put my font first (highest priority):
/// fonts.fonts_for_family.get_mut(&FontFamily::Proportional).unwrap()
/// fonts.families.get_mut(&FontFamily::Proportional).unwrap()
/// .insert(0, "my_font".to_owned());
///
/// // Put my font as last fallback for monospace:
/// fonts.fonts_for_family.get_mut(&FontFamily::Monospace).unwrap()
/// fonts.families.get_mut(&FontFamily::Monospace).unwrap()
/// .push("my_font".to_owned());
///
/// ctx.set_fonts(fonts);
/// egui_ctx.set_fonts(fonts);
/// ```
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
@@ -150,10 +193,8 @@ pub struct FontDefinitions {
/// When looking for a character glyph `epaint` will start with
/// the first font and then move to the second, and so on.
/// So the first font is the primary, and then comes a list of fallbacks in order of priority.
pub fonts_for_family: BTreeMap<FontFamily, Vec<String>>,
/// The [`FontFamily`] and size you want to use for a specific [`TextStyle`].
pub family_and_size: BTreeMap<TextStyle, (FontFamily, f32)>,
// TODO: per font size-modifier.
pub families: BTreeMap<FontFamily, Vec<String>>,
}
impl Default for FontDefinitions {
@@ -161,7 +202,7 @@ impl Default for FontDefinitions {
#[allow(unused)]
let mut font_data: BTreeMap<String, FontData> = BTreeMap::new();
let mut fonts_for_family = BTreeMap::new();
let mut families = BTreeMap::new();
#[cfg(feature = "default_fonts")]
{
@@ -185,7 +226,7 @@ impl Default for FontDefinitions {
FontData::from_static(include_bytes!("../../fonts/emoji-icon-font.ttf")),
);
fonts_for_family.insert(
families.insert(
FontFamily::Monospace,
vec![
"Hack".to_owned(),
@@ -194,7 +235,7 @@ impl Default for FontDefinitions {
"emoji-icon-font".to_owned(),
],
);
fonts_for_family.insert(
families.insert(
FontFamily::Proportional,
vec![
"Ubuntu-Light".to_owned(),
@@ -206,49 +247,240 @@ impl Default for FontDefinitions {
#[cfg(not(feature = "default_fonts"))]
{
fonts_for_family.insert(FontFamily::Monospace, vec![]);
fonts_for_family.insert(FontFamily::Proportional, vec![]);
families.insert(FontFamily::Monospace, vec![]);
families.insert(FontFamily::Proportional, vec![]);
}
let mut family_and_size = BTreeMap::new();
family_and_size.insert(TextStyle::Small, (FontFamily::Proportional, 10.0));
family_and_size.insert(TextStyle::Body, (FontFamily::Proportional, 14.0));
family_and_size.insert(TextStyle::Button, (FontFamily::Proportional, 14.0));
family_and_size.insert(TextStyle::Heading, (FontFamily::Proportional, 20.0));
family_and_size.insert(TextStyle::Monospace, (FontFamily::Monospace, 14.0));
Self {
font_data,
fonts_for_family,
family_and_size,
families,
}
}
}
// ----------------------------------------------------------------------------
/// The collection of fonts used by `epaint`.
///
/// Required in order to paint text.
pub struct Fonts {
pixels_per_point: f32,
definitions: FontDefinitions,
fonts: BTreeMap<TextStyle, Font>,
atlas: Arc<Mutex<TextureAtlas>>,
galley_cache: Mutex<GalleyCache>,
}
/// Create one and reuse. Cheap to clone.
///
/// You need to call [`Self::begin_frame`] and [`Self::font_image_delta`] once every frame.
///
/// Wrapper for `Arc<Mutex<FontsAndCache>>`.
pub struct Fonts(Arc<Mutex<FontsAndCache>>);
impl Fonts {
/// Create a new [`Fonts`] for text layout.
/// This call is expensive, so only create one [`Fonts`] and then reuse it.
pub fn new(pixels_per_point: f32, definitions: FontDefinitions) -> Self {
///
/// * `pixels_per_point`: how many physical pixels per logical "point".
/// * `max_texture_side`: largest supported texture size (one side).
pub fn new(
pixels_per_point: f32,
max_texture_side: usize,
definitions: FontDefinitions,
) -> Self {
let fonts_and_cache = FontsAndCache {
fonts: FontsImpl::new(pixels_per_point, max_texture_side, definitions),
galley_cache: Default::default(),
};
Self(Arc::new(Mutex::new(fonts_and_cache)))
}
/// Call at the start of each frame with the latest known
/// `pixels_per_point` and `max_texture_side`.
///
/// Call after painting the previous frame, but before using [`Fonts`] for the new frame.
///
/// This function will react to changes in `pixels_per_point` and `max_texture_side`,
/// as well as notice when the font atlas is getting full, and handle that.
pub fn begin_frame(&self, pixels_per_point: f32, max_texture_side: usize) {
let mut fonts_and_cache = self.0.lock();
let pixels_per_point_changed =
(fonts_and_cache.fonts.pixels_per_point - pixels_per_point).abs() > 1e-3;
let max_texture_side_changed = fonts_and_cache.fonts.max_texture_side != max_texture_side;
let font_atlas_almost_full = fonts_and_cache.fonts.atlas.lock().fill_ratio() > 0.8;
let needs_recreate =
pixels_per_point_changed || max_texture_side_changed || font_atlas_almost_full;
if needs_recreate {
let definitions = fonts_and_cache.fonts.definitions.clone();
*fonts_and_cache = FontsAndCache {
fonts: FontsImpl::new(pixels_per_point, max_texture_side, definitions),
galley_cache: Default::default(),
};
}
fonts_and_cache.galley_cache.flush_cache();
}
/// Call at the end of each frame (before painting) to get the change to the font texture since last call.
pub fn font_image_delta(&self) -> Option<crate::ImageDelta> {
self.lock().fonts.atlas.lock().take_delta()
}
/// Access the underlying [`FontsAndCache`].
#[doc(hidden)]
#[inline]
pub fn lock(&self) -> MutexGuard<'_, FontsAndCache> {
self.0.lock()
}
#[inline]
pub fn pixels_per_point(&self) -> f32 {
self.lock().fonts.pixels_per_point
}
#[inline]
pub fn max_texture_side(&self) -> usize {
self.lock().fonts.max_texture_side
}
/// Current size of the font image.
/// Pass this to [`crate::Tessellator`].
pub fn font_image_size(&self) -> [usize; 2] {
self.lock().fonts.atlas.lock().size()
}
/// Width of this character in points.
#[inline]
pub fn glyph_width(&self, font_id: &FontId, c: char) -> f32 {
self.lock().fonts.glyph_width(font_id, c)
}
/// Height of one row of text in points
#[inline]
pub fn row_height(&self, font_id: &FontId) -> f32 {
self.lock().fonts.row_height(font_id)
}
/// List of all known font families.
pub fn families(&self) -> Vec<FontFamily> {
self.lock()
.fonts
.definitions
.families
.keys()
.cloned()
.collect()
}
/// Layout some text.
///
/// This is the most advanced layout function.
/// See also [`Self::layout`], [`Self::layout_no_wrap`] and
/// [`Self::layout_delayed_color`].
///
/// The implementation uses memoization so repeated calls are cheap.
#[inline]
pub fn layout_job(&self, job: LayoutJob) -> Arc<Galley> {
self.lock().layout_job(job)
}
pub fn num_galleys_in_cache(&self) -> usize {
self.lock().galley_cache.num_galleys_in_cache()
}
/// How full is the font atlas?
///
/// This increases as new fonts and/or glyphs are used,
/// but can also decrease in a call to [`Self::begin_frame`].
pub fn font_atlas_fill_ratio(&self) -> f32 {
self.lock().fonts.atlas.lock().fill_ratio()
}
/// Will wrap text at the given width and line break at `\n`.
///
/// The implementation uses memoization so repeated calls are cheap.
pub fn layout(
&self,
text: String,
font_id: FontId,
color: crate::Color32,
wrap_width: f32,
) -> Arc<Galley> {
let job = LayoutJob::simple(text, font_id, color, wrap_width);
self.layout_job(job)
}
/// Will line break at `\n`.
///
/// The implementation uses memoization so repeated calls are cheap.
pub fn layout_no_wrap(
&self,
text: String,
font_id: FontId,
color: crate::Color32,
) -> Arc<Galley> {
let job = LayoutJob::simple(text, font_id, color, f32::INFINITY);
self.layout_job(job)
}
/// Like [`Self::layout`], made for when you want to pick a color for the text later.
///
/// The implementation uses memoization so repeated calls are cheap.
pub fn layout_delayed_color(
&self,
text: String,
font_id: FontId,
wrap_width: f32,
) -> Arc<Galley> {
self.layout_job(LayoutJob::simple(
text,
font_id,
crate::Color32::TEMPORARY_COLOR,
wrap_width,
))
}
}
// ----------------------------------------------------------------------------
pub struct FontsAndCache {
pub fonts: FontsImpl,
galley_cache: GalleyCache,
}
impl FontsAndCache {
fn layout_job(&mut self, job: LayoutJob) -> Arc<Galley> {
self.galley_cache.layout(&mut self.fonts, job)
}
}
// ----------------------------------------------------------------------------
/// The collection of fonts used by `epaint`.
///
/// Required in order to paint text.
pub struct FontsImpl {
pixels_per_point: f32,
max_texture_side: usize,
definitions: FontDefinitions,
atlas: Arc<Mutex<TextureAtlas>>,
font_impl_cache: FontImplCache,
sized_family: ahash::AHashMap<(u32, FontFamily), Font>,
}
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(
pixels_per_point: f32,
max_texture_side: usize,
definitions: FontDefinitions,
) -> Self {
assert!(
0.0 < pixels_per_point && pixels_per_point < 100.0,
"pixels_per_point out of range: {}",
pixels_per_point
);
// We want an atlas big enough to be able to include all the Emojis in the `TextStyle::Heading`,
// so we can show the Emoji picker demo window.
let mut atlas = TextureAtlas::new([2048, 64]);
let texture_width = max_texture_side.at_most(16 * 1024);
let initial_height = 512;
let mut atlas = TextureAtlas::new([texture_width, initial_height]);
{
// Make the top left pixel fully white:
@@ -259,31 +491,16 @@ impl Fonts {
let atlas = Arc::new(Mutex::new(atlas));
let mut font_impl_cache = FontImplCache::new(atlas.clone(), pixels_per_point, &definitions);
let fonts = definitions
.family_and_size
.iter()
.map(|(&text_style, &(family, scale_in_points))| {
let fonts = &definitions.fonts_for_family.get(&family);
let fonts = fonts.unwrap_or_else(|| {
panic!("FontFamily::{:?} is not bound to any fonts", family)
});
let fonts: Vec<Arc<FontImpl>> = fonts
.iter()
.map(|font_name| font_impl_cache.font_impl(font_name, scale_in_points))
.collect();
(text_style, Font::new(text_style, fonts))
})
.collect();
let font_impl_cache =
FontImplCache::new(atlas.clone(), pixels_per_point, &definitions.font_data);
Self {
pixels_per_point,
max_texture_side,
definitions,
fonts,
atlas,
galley_cache: Default::default(),
font_impl_cache,
sized_family: Default::default(),
}
}
@@ -292,110 +509,41 @@ impl Fonts {
self.pixels_per_point
}
#[inline]
pub fn definitions(&self) -> &FontDefinitions {
&self.definitions
}
#[inline(always)]
pub fn round_to_pixel(&self, point: f32) -> f32 {
(point * self.pixels_per_point).round() / self.pixels_per_point
}
/// Get the right font implementation from size and [`FontFamily`].
pub fn font(&mut self, font_id: &FontId) -> &mut Font {
let FontId { size, family } = font_id;
let scale_in_pixels = self.font_impl_cache.scale_as_pixels(*size);
#[inline(always)]
pub fn floor_to_pixel(&self, point: f32) -> f32 {
(point * self.pixels_per_point).floor() / self.pixels_per_point
}
self.sized_family
.entry((scale_in_pixels, family.clone()))
.or_insert_with(|| {
let fonts = &self.definitions.families.get(family);
let fonts = fonts.unwrap_or_else(|| {
panic!("FontFamily::{:?} is not bound to any fonts", family)
});
/// Call each frame to get the change to the font texture since last call.
pub fn font_image_delta(&self) -> Option<crate::ImageDelta> {
self.atlas.lock().take_delta()
}
let fonts: Vec<Arc<FontImpl>> = fonts
.iter()
.map(|font_name| self.font_impl_cache.font_impl(scale_in_pixels, font_name))
.collect();
/// Current size of the font image
pub fn font_image_size(&self) -> [usize; 2] {
self.atlas.lock().size()
Font::new(fonts)
})
}
/// Width of this character in points.
pub fn glyph_width(&self, text_style: TextStyle, c: char) -> f32 {
self.fonts[&text_style].glyph_width(c)
fn glyph_width(&mut self, font_id: &FontId, c: char) -> f32 {
self.font(font_id).glyph_width(c)
}
/// Height of one row of text. In points
pub fn row_height(&self, text_style: TextStyle) -> f32 {
self.fonts[&text_style].row_height()
}
/// Layout some text.
/// This is the most advanced layout function.
/// See also [`Self::layout`], [`Self::layout_no_wrap`] and
/// [`Self::layout_delayed_color`].
///
/// The implementation uses memoization so repeated calls are cheap.
pub fn layout_job(&self, job: LayoutJob) -> Arc<Galley> {
self.galley_cache.lock().layout(self, job)
}
/// Will wrap text at the given width and line break at `\n`.
///
/// The implementation uses memoization so repeated calls are cheap.
pub fn layout(
&self,
text: String,
text_style: TextStyle,
color: crate::Color32,
wrap_width: f32,
) -> Arc<Galley> {
let job = LayoutJob::simple(text, text_style, color, wrap_width);
self.layout_job(job)
}
/// Will line break at `\n`.
///
/// The implementation uses memoization so repeated calls are cheap.
pub fn layout_no_wrap(
&self,
text: String,
text_style: TextStyle,
color: crate::Color32,
) -> Arc<Galley> {
let job = LayoutJob::simple(text, text_style, color, f32::INFINITY);
self.layout_job(job)
}
/// Like [`Self::layout`], made for when you want to pick a color for the text later.
///
/// The implementation uses memoization so repeated calls are cheap.
pub fn layout_delayed_color(
&self,
text: String,
text_style: TextStyle,
wrap_width: f32,
) -> Arc<Galley> {
self.layout_job(LayoutJob::simple(
text,
text_style,
crate::Color32::TEMPORARY_COLOR,
wrap_width,
))
}
pub fn num_galleys_in_cache(&self) -> usize {
self.galley_cache.lock().num_galleys_in_cache()
}
/// Must be called once per frame to clear the [`Galley`] cache.
pub fn end_frame(&self) {
self.galley_cache.lock().end_frame();
}
}
impl std::ops::Index<TextStyle> for Fonts {
type Output = Font;
#[inline(always)]
fn index(&self, text_style: TextStyle) -> &Font {
&self.fonts[&text_style]
fn row_height(&mut self, font_id: &FontId) -> f32 {
self.font(font_id).row_height()
}
}
@@ -415,7 +563,7 @@ struct GalleyCache {
}
impl GalleyCache {
fn layout(&mut self, fonts: &Fonts, job: LayoutJob) -> Arc<Galley> {
fn layout(&mut self, fonts: &mut FontsImpl, job: LayoutJob) -> Arc<Galley> {
let hash = crate::util::hash(&job); // TODO: even faster hasher?
match self.cache.entry(hash) {
@@ -441,7 +589,7 @@ impl GalleyCache {
}
/// Must be called once per frame to clear the [`Galley`] cache.
pub fn end_frame(&mut self) {
pub fn flush_cache(&mut self) {
let current_generation = self.generation;
self.cache.retain(|_key, cached| {
cached.last_used == current_generation // only keep those that were used this frame
@@ -457,19 +605,17 @@ struct FontImplCache {
pixels_per_point: f32,
ab_glyph_fonts: BTreeMap<String, ab_glyph::FontArc>,
/// Map font names and size to the cached `FontImpl`.
/// Can't have f32 in a HashMap or BTreeMap, so let's do a linear search
cache: Vec<(String, f32, Arc<FontImpl>)>,
/// Map font pixel sizes and names to the cached `FontImpl`.
cache: ahash::AHashMap<(u32, String), Arc<FontImpl>>,
}
impl FontImplCache {
pub fn new(
atlas: Arc<Mutex<TextureAtlas>>,
pixels_per_point: f32,
definitions: &super::FontDefinitions,
font_data: &BTreeMap<String, FontData>,
) -> Self {
let ab_glyph_fonts = definitions
.font_data
let ab_glyph_fonts = font_data
.iter()
.map(|(name, font_data)| (name.clone(), ab_glyph_font_from_font_data(name, font_data)))
.collect();
@@ -482,42 +628,47 @@ impl FontImplCache {
}
}
pub fn ab_glyph_font(&self, font_name: &str) -> ab_glyph::FontArc {
self.ab_glyph_fonts
.get(font_name)
.unwrap_or_else(|| panic!("No font data found for {:?}", font_name))
.clone()
#[inline]
pub fn scale_as_pixels(&self, scale_in_points: f32) -> u32 {
let scale_in_pixels = self.pixels_per_point * scale_in_points;
// Round to an even number of physical pixels to get even kerning.
// See https://github.com/emilk/egui/issues/382
scale_in_pixels.round() as u32
}
pub fn font_impl(&mut self, font_name: &str, scale_in_points: f32) -> Arc<FontImpl> {
for entry in &self.cache {
if (entry.0.as_str(), entry.1) == (font_name, scale_in_points) {
return entry.2.clone();
}
}
pub fn font_impl(&mut self, scale_in_pixels: u32, font_name: &str) -> Arc<FontImpl> {
let scale_in_pixels = if font_name == "emoji-icon-font" {
(scale_in_pixels as f32 * 0.8).round() as u32 // TODO: remove font scale HACK!
} else {
scale_in_pixels
};
let y_offset = if font_name == "emoji-icon-font" {
scale_in_points * 0.235 // TODO: remove font alignment hack
let scale_in_points = scale_in_pixels as f32 / self.pixels_per_point;
scale_in_points * 0.29375 // TODO: remove font alignment hack
} else {
0.0
};
let y_offset = y_offset - 3.0; // Tweaked to make text look centered in buttons and text edit fields
let scale_in_points = if font_name == "emoji-icon-font" {
scale_in_points * 0.8 // TODO: remove HACK!
} else {
scale_in_points
};
let font_impl = Arc::new(FontImpl::new(
self.atlas.clone(),
self.pixels_per_point,
self.ab_glyph_font(font_name),
scale_in_points,
y_offset,
));
self.cache
.push((font_name.to_owned(), scale_in_points, font_impl.clone()));
font_impl
.entry((scale_in_pixels, font_name.to_owned()))
.or_insert_with(|| {
let ab_glyph_font = self
.ab_glyph_fonts
.get(font_name)
.unwrap_or_else(|| panic!("No font data found for {:?}", font_name))
.clone();
Arc::new(FontImpl::new(
self.atlas.clone(),
self.pixels_per_point,
ab_glyph_font,
scale_in_pixels,
y_offset,
))
})
.clone()
}
}

View File

@@ -10,7 +10,7 @@ mod text_layout_types;
pub const TAB_SIZE: usize = 4;
pub use {
fonts::{FontData, FontDefinitions, FontFamily, Fonts, TextStyle},
fonts::{FontData, FontDefinitions, FontFamily, FontId, Fonts, FontsImpl},
text_layout::layout,
text_layout_types::*,
};

View File

@@ -1,9 +1,41 @@
use std::ops::RangeInclusive;
use super::{Fonts, Galley, Glyph, LayoutJob, LayoutSection, Row, RowVisuals};
use super::{FontsImpl, Galley, Glyph, LayoutJob, LayoutSection, Row, RowVisuals};
use crate::{mutex::Arc, Color32, Mesh, Stroke, Vertex};
use emath::*;
// ----------------------------------------------------------------------------
/// Represents GUI scale and convenience methods for rounding to pixels.
#[derive(Clone, Copy)]
struct PointScale {
pub pixels_per_point: f32,
}
impl PointScale {
#[inline(always)]
pub fn new(pixels_per_point: f32) -> Self {
Self { pixels_per_point }
}
#[inline(always)]
pub fn pixels_per_point(&self) -> f32 {
self.pixels_per_point
}
#[inline(always)]
pub fn round_to_pixel(&self, point: f32) -> f32 {
(point * self.pixels_per_point).round() / self.pixels_per_point
}
#[inline(always)]
pub fn floor_to_pixel(&self, point: f32) -> f32 {
(point * self.pixels_per_point).floor() / self.pixels_per_point
}
}
// ----------------------------------------------------------------------------
/// Temporary storage before line-wrapping.
#[derive(Default, Clone)]
struct Paragraph {
@@ -16,14 +48,16 @@ struct Paragraph {
/// Layout text into a [`Galley`].
///
/// In most cases you should use [`Fonts::layout_job`] instead
/// In most cases you should use [`crate::Fonts::layout_job`] instead
/// since that memoizes the input, making subsequent layouting of the same text much faster.
pub fn layout(fonts: &Fonts, job: Arc<LayoutJob>) -> Galley {
pub fn layout(fonts: &mut FontsImpl, job: Arc<LayoutJob>) -> Galley {
let mut paragraphs = vec![Paragraph::default()];
for (section_index, section) in job.sections.iter().enumerate() {
layout_section(fonts, &job, section_index as u32, section, &mut paragraphs);
}
let point_scale = PointScale::new(fonts.pixels_per_point());
let mut rows = rows_from_paragraphs(paragraphs, job.wrap_width);
let justify = job.justify && job.wrap_width.is_finite();
@@ -33,15 +67,15 @@ pub fn layout(fonts: &Fonts, job: Arc<LayoutJob>) -> Galley {
for (i, row) in rows.iter_mut().enumerate() {
let is_last_row = i + 1 == num_rows;
let justify_row = justify && !row.ends_with_newline && !is_last_row;
halign_and_jusitfy_row(fonts, row, job.halign, job.wrap_width, justify_row);
halign_and_jusitfy_row(point_scale, row, job.halign, job.wrap_width, justify_row);
}
}
galley_from_rows(fonts, job, rows)
galley_from_rows(point_scale, job, rows)
}
fn layout_section(
fonts: &Fonts,
fonts: &mut FontsImpl,
job: &LayoutJob,
section_index: u32,
section: &LayoutSection,
@@ -52,7 +86,7 @@ fn layout_section(
byte_range,
format,
} = section;
let font = &fonts[format.style];
let font = fonts.font(&format.font_id);
let font_height = font.row_height();
let mut paragraph = out_paragraphs.last_mut().unwrap();
@@ -213,7 +247,7 @@ fn line_break(paragraph: &Paragraph, wrap_width: f32, out_rows: &mut Vec<Row>) {
}
fn halign_and_jusitfy_row(
fonts: &Fonts,
point_scale: PointScale,
row: &mut Row,
halign: Align,
wrap_width: f32,
@@ -278,7 +312,7 @@ fn halign_and_jusitfy_row(
// Add an integral number of pixels between each glyph,
// and add the balance to the spaces:
extra_x_per_glyph = fonts.floor_to_pixel(extra_x_per_glyph);
extra_x_per_glyph = point_scale.floor_to_pixel(extra_x_per_glyph);
extra_x_per_space = (target_width
- original_width
@@ -290,7 +324,7 @@ fn halign_and_jusitfy_row(
for glyph in &mut row.glyphs {
glyph.pos.x += translate_x;
glyph.pos.x = fonts.round_to_pixel(glyph.pos.x);
glyph.pos.x = point_scale.round_to_pixel(glyph.pos.x);
translate_x += extra_x_per_glyph;
if glyph.chr.is_whitespace() {
translate_x += extra_x_per_space;
@@ -303,7 +337,7 @@ fn halign_and_jusitfy_row(
}
/// Calculate the Y positions and tessellate the text.
fn galley_from_rows(fonts: &Fonts, job: Arc<LayoutJob>, mut rows: Vec<Row>) -> Galley {
fn galley_from_rows(point_scale: PointScale, job: Arc<LayoutJob>, mut rows: Vec<Row>) -> Galley {
let mut first_row_min_height = job.first_row_min_height;
let mut cursor_y = 0.0;
let mut min_x: f32 = 0.0;
@@ -314,13 +348,13 @@ fn galley_from_rows(fonts: &Fonts, job: Arc<LayoutJob>, mut rows: Vec<Row>) -> G
for glyph in &row.glyphs {
row_height = row_height.max(glyph.size.y);
}
row_height = fonts.round_to_pixel(row_height);
row_height = point_scale.round_to_pixel(row_height);
// Now positions each glyph:
for glyph in &mut row.glyphs {
let format = &job.sections[glyph.section_index as usize].format;
glyph.pos.y = cursor_y + format.valign.to_factor() * (row_height - glyph.size.y);
glyph.pos.y = fonts.round_to_pixel(glyph.pos.y);
glyph.pos.y = point_scale.round_to_pixel(glyph.pos.y);
}
row.rect.min.y = cursor_y;
@@ -329,7 +363,7 @@ fn galley_from_rows(fonts: &Fonts, job: Arc<LayoutJob>, mut rows: Vec<Row>) -> G
min_x = min_x.min(row.rect.min.x);
max_x = max_x.max(row.rect.max.x);
cursor_y += row_height;
cursor_y = fonts.round_to_pixel(cursor_y);
cursor_y = point_scale.round_to_pixel(cursor_y);
}
let format_summary = format_summary(&job);
@@ -339,7 +373,7 @@ fn galley_from_rows(fonts: &Fonts, job: Arc<LayoutJob>, mut rows: Vec<Row>) -> G
let mut num_indices = 0;
for row in &mut rows {
row.visuals = tessellate_row(fonts, &job, &format_summary, row);
row.visuals = tessellate_row(point_scale, &job, &format_summary, row);
mesh_bounds = mesh_bounds.union(row.visuals.mesh_bounds);
num_vertices += row.visuals.mesh.vertices.len();
num_indices += row.visuals.mesh.indices.len();
@@ -375,7 +409,7 @@ fn format_summary(job: &LayoutJob) -> FormatSummary {
}
fn tessellate_row(
fonts: &Fonts,
point_scale: PointScale,
job: &LayoutJob,
format_summary: &FormatSummary,
row: &mut Row,
@@ -394,11 +428,11 @@ fn tessellate_row(
}
let glyph_vertex_start = mesh.vertices.len();
tessellate_glyphs(fonts, job, row, &mut mesh);
tessellate_glyphs(point_scale, job, row, &mut mesh);
let glyph_vertex_end = mesh.vertices.len();
if format_summary.any_underline {
add_row_hline(fonts, row, &mut mesh, |glyph| {
add_row_hline(point_scale, row, &mut mesh, |glyph| {
let format = &job.sections[glyph.section_index as usize].format;
let stroke = format.underline;
let y = glyph.logical_rect().bottom();
@@ -407,7 +441,7 @@ fn tessellate_row(
}
if format_summary.any_strikethrough {
add_row_hline(fonts, row, &mut mesh, |glyph| {
add_row_hline(point_scale, row, &mut mesh, |glyph| {
let format = &job.sections[glyph.section_index as usize].format;
let stroke = format.strikethrough;
let y = glyph.logical_rect().center().y;
@@ -469,13 +503,13 @@ fn add_row_backgrounds(job: &LayoutJob, row: &Row, mesh: &mut Mesh) {
end_run(run_start.take(), last_rect.right());
}
fn tessellate_glyphs(fonts: &Fonts, job: &LayoutJob, row: &Row, mesh: &mut Mesh) {
fn tessellate_glyphs(point_scale: PointScale, job: &LayoutJob, row: &Row, mesh: &mut Mesh) {
for glyph in &row.glyphs {
let uv_rect = glyph.uv_rect;
if !uv_rect.is_nothing() {
let mut left_top = glyph.pos + uv_rect.offset;
left_top.x = fonts.round_to_pixel(left_top.x);
left_top.y = fonts.round_to_pixel(left_top.y);
left_top.x = point_scale.round_to_pixel(left_top.x);
left_top.y = point_scale.round_to_pixel(left_top.y);
let rect = Rect::from_min_max(left_top, left_top + uv_rect.size);
let uv = Rect::from_min_max(
@@ -523,14 +557,14 @@ fn tessellate_glyphs(fonts: &Fonts, job: &LayoutJob, row: &Row, mesh: &mut Mesh)
/// Add a horizontal line over a row of glyphs with a stroke and y decided by a callback.
fn add_row_hline(
fonts: &Fonts,
point_scale: PointScale,
row: &Row,
mesh: &mut Mesh,
stroke_and_y: impl Fn(&Glyph) -> (Stroke, f32),
) {
let mut end_line = |start: Option<(Stroke, Pos2)>, stop_x: f32| {
if let Some((stroke, start)) = start {
add_hline(fonts, [start, pos2(stop_x, start.y)], stroke, mesh);
add_hline(point_scale, [start, pos2(stop_x, start.y)], stroke, mesh);
}
};
@@ -559,14 +593,14 @@ fn add_row_hline(
end_line(line_start.take(), last_right_x);
}
fn add_hline(fonts: &Fonts, [start, stop]: [Pos2; 2], stroke: Stroke, mesh: &mut Mesh) {
fn add_hline(point_scale: PointScale, [start, stop]: [Pos2; 2], stroke: Stroke, mesh: &mut Mesh) {
let antialiased = true;
if antialiased {
let mut path = crate::tessellator::Path::default(); // TODO: reuse this to avoid re-allocations.
path.add_line_segment([start, stop]);
let options = crate::tessellator::TessellationOptions::from_pixels_per_point(
fonts.pixels_per_point(),
point_scale.pixels_per_point(),
);
path.stroke_open(stroke, &options, mesh);
} else {
@@ -574,12 +608,12 @@ fn add_hline(fonts: &Fonts, [start, stop]: [Pos2; 2], stroke: Stroke, mesh: &mut
assert_eq!(start.y, stop.y);
let min_y = fonts.round_to_pixel(start.y - 0.5 * stroke.width);
let max_y = fonts.round_to_pixel(min_y + stroke.width);
let min_y = point_scale.round_to_pixel(start.y - 0.5 * stroke.width);
let max_y = point_scale.round_to_pixel(min_y + stroke.width);
let rect = Rect::from_min_max(
pos2(fonts.round_to_pixel(start.x), min_y),
pos2(fonts.round_to_pixel(stop.x), max_y),
pos2(point_scale.round_to_pixel(start.x), min_y),
pos2(point_scale.round_to_pixel(stop.x), max_y),
);
mesh.add_colored_rect(rect, stroke.color);

View File

@@ -3,7 +3,7 @@
use std::ops::Range;
use super::{cursor::*, font::UvRect};
use crate::{mutex::Arc, Color32, Mesh, Stroke, TextStyle};
use crate::{mutex::Arc, Color32, FontId, Mesh, Stroke};
use emath::*;
/// Describes the task of laying out text.
@@ -14,14 +14,14 @@ use emath::*;
///
/// ## Example:
/// ```
/// use epaint::{Color32, text::{LayoutJob, TextFormat}, TextStyle};
/// use epaint::{Color32, text::{LayoutJob, TextFormat}, FontFamily, FontId};
///
/// let mut job = LayoutJob::default();
/// job.append(
/// "Hello ",
/// 0.0,
/// TextFormat {
/// style: TextStyle::Body,
/// font_id: FontId::new(14.0, FontFamily::Proportional),
/// color: Color32::WHITE,
/// ..Default::default()
/// },
@@ -30,7 +30,7 @@ use emath::*;
/// "World!",
/// 0.0,
/// TextFormat {
/// style: TextStyle::Monospace,
/// font_id: FontId::new(14.0, FontFamily::Monospace),
/// color: Color32::BLACK,
/// ..Default::default()
/// },
@@ -90,12 +90,12 @@ impl Default for LayoutJob {
impl LayoutJob {
/// Break on `\n` and at the given wrap width.
#[inline]
pub fn simple(text: String, text_style: TextStyle, color: Color32, wrap_width: f32) -> Self {
pub fn simple(text: String, font_id: FontId, color: Color32, wrap_width: f32) -> Self {
Self {
sections: vec![LayoutSection {
leading_space: 0.0,
byte_range: 0..text.len(),
format: TextFormat::simple(text_style, color),
format: TextFormat::simple(font_id, color),
}],
text,
wrap_width,
@@ -106,12 +106,12 @@ impl LayoutJob {
/// Does not break on `\n`, but shows the replacement character instead.
#[inline]
pub fn simple_singleline(text: String, text_style: TextStyle, color: Color32) -> Self {
pub fn simple_singleline(text: String, font_id: FontId, color: Color32) -> Self {
Self {
sections: vec![LayoutSection {
leading_space: 0.0,
byte_range: 0..text.len(),
format: TextFormat::simple(text_style, color),
format: TextFormat::simple(font_id, color),
}],
text,
wrap_width: f32::INFINITY,
@@ -156,7 +156,7 @@ impl LayoutJob {
pub fn font_height(&self, fonts: &crate::Fonts) -> f32 {
let mut max_height = 0.0_f32;
for section in &self.sections {
max_height = max_height.max(fonts.row_height(section.format.style));
max_height = max_height.max(fonts.row_height(&section.format.font_id));
}
max_height
}
@@ -213,10 +213,10 @@ impl std::hash::Hash for LayoutSection {
// ----------------------------------------------------------------------------
#[derive(Copy, Clone, Debug, Hash, PartialEq)]
#[derive(Clone, Debug, Hash, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct TextFormat {
pub style: TextStyle,
pub font_id: FontId,
/// Text color
pub color: Color32,
pub background: Color32,
@@ -233,7 +233,7 @@ impl Default for TextFormat {
#[inline]
fn default() -> Self {
Self {
style: TextStyle::Body,
font_id: FontId::default(),
color: Color32::GRAY,
background: Color32::TRANSPARENT,
italics: false,
@@ -246,9 +246,9 @@ impl Default for TextFormat {
impl TextFormat {
#[inline]
pub fn simple(style: TextStyle, color: Color32) -> Self {
pub fn simple(font_id: FontId, color: Color32) -> Self {
Self {
style,
font_id,
color,
..Default::default()
}