mirror of
https://github.com/emilk/egui.git
synced 2026-08-30 13:20:05 -04:00
Move all crates into a crates directory (#1940)
This commit is contained in:
122
crates/epaint/src/text/cursor.rs
Normal file
122
crates/epaint/src/text/cursor.rs
Normal file
@@ -0,0 +1,122 @@
|
||||
//! Different types of text cursors, i.e. ways to point into a [`super::Galley`].
|
||||
|
||||
/// Character cursor
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
|
||||
pub struct CCursor {
|
||||
/// Character offset (NOT byte offset!).
|
||||
pub index: usize,
|
||||
|
||||
/// If this cursors sits right at the border of a wrapped row break (NOT paragraph break)
|
||||
/// do we prefer the next row?
|
||||
/// This is *almost* always what you want, *except* for when
|
||||
/// explicitly clicking the end of a row or pressing the end key.
|
||||
pub prefer_next_row: bool,
|
||||
}
|
||||
|
||||
impl CCursor {
|
||||
pub fn new(index: usize) -> Self {
|
||||
Self {
|
||||
index,
|
||||
prefer_next_row: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Two `CCursor`s are considered equal if they refer to the same character boundary,
|
||||
/// even if one prefers the start of the next row.
|
||||
impl PartialEq for CCursor {
|
||||
fn eq(&self, other: &CCursor) -> bool {
|
||||
self.index == other.index
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::Add<usize> for CCursor {
|
||||
type Output = CCursor;
|
||||
|
||||
fn add(self, rhs: usize) -> Self::Output {
|
||||
CCursor {
|
||||
index: self.index.saturating_add(rhs),
|
||||
prefer_next_row: self.prefer_next_row,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::Sub<usize> for CCursor {
|
||||
type Output = CCursor;
|
||||
|
||||
fn sub(self, rhs: usize) -> Self::Output {
|
||||
CCursor {
|
||||
index: self.index.saturating_sub(rhs),
|
||||
prefer_next_row: self.prefer_next_row,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::AddAssign<usize> for CCursor {
|
||||
fn add_assign(&mut self, rhs: usize) {
|
||||
self.index = self.index.saturating_add(rhs);
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::SubAssign<usize> for CCursor {
|
||||
fn sub_assign(&mut self, rhs: usize) {
|
||||
self.index = self.index.saturating_sub(rhs);
|
||||
}
|
||||
}
|
||||
|
||||
/// Row Cursor
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
|
||||
pub struct RCursor {
|
||||
/// 0 is first row, and so on.
|
||||
/// Note that a single paragraph can span multiple rows.
|
||||
/// (a paragraph is text separated by `\n`).
|
||||
pub row: usize,
|
||||
|
||||
/// Character based (NOT bytes).
|
||||
/// It is fine if this points to something beyond the end of the current row.
|
||||
/// When moving up/down it may again be within the next row.
|
||||
pub column: usize,
|
||||
}
|
||||
|
||||
/// Paragraph Cursor
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
|
||||
pub struct PCursor {
|
||||
/// 0 is first paragraph, and so on.
|
||||
/// Note that a single paragraph can span multiple rows.
|
||||
/// (a paragraph is text separated by `\n`).
|
||||
pub paragraph: usize,
|
||||
|
||||
/// Character based (NOT bytes).
|
||||
/// It is fine if this points to something beyond the end of the current paragraph.
|
||||
/// When moving up/down it may again be within the next paragraph.
|
||||
pub offset: usize,
|
||||
|
||||
/// If this cursors sits right at the border of a wrapped row break (NOT paragraph break)
|
||||
/// do we prefer the next row?
|
||||
/// This is *almost* always what you want, *except* for when
|
||||
/// explicitly clicking the end of a row or pressing the end key.
|
||||
pub prefer_next_row: bool,
|
||||
}
|
||||
|
||||
/// Two `PCursor`s are considered equal if they refer to the same character boundary,
|
||||
/// even if one prefers the start of the next row.
|
||||
impl PartialEq for PCursor {
|
||||
fn eq(&self, other: &PCursor) -> bool {
|
||||
self.paragraph == other.paragraph && self.offset == other.offset
|
||||
}
|
||||
}
|
||||
|
||||
/// All different types of cursors together.
|
||||
/// They all point to the same place, but in their own different ways.
|
||||
/// pcursor/rcursor can also point to after the end of the paragraph/row.
|
||||
/// Does not implement `PartialEq` because you must think which cursor should be equivalent.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
|
||||
pub struct Cursor {
|
||||
pub ccursor: CCursor,
|
||||
pub rcursor: RCursor,
|
||||
pub pcursor: PCursor,
|
||||
}
|
||||
407
crates/epaint/src/text/font.rs
Normal file
407
crates/epaint/src/text/font.rs
Normal file
@@ -0,0 +1,407 @@
|
||||
use crate::{
|
||||
mutex::{Mutex, RwLock},
|
||||
TextureAtlas,
|
||||
};
|
||||
use emath::{vec2, Vec2};
|
||||
use std::collections::BTreeSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
|
||||
pub struct UvRect {
|
||||
/// X/Y offset for nice rendering (unit: points).
|
||||
pub offset: Vec2,
|
||||
|
||||
/// Screen size (in points) of this glyph.
|
||||
/// Note that the height is different from the font height.
|
||||
pub size: Vec2,
|
||||
|
||||
/// Top left corner UV in texture.
|
||||
pub min: [u16; 2],
|
||||
|
||||
/// Bottom right corner (exclusive).
|
||||
pub max: [u16; 2],
|
||||
}
|
||||
|
||||
impl UvRect {
|
||||
pub fn is_nothing(&self) -> bool {
|
||||
self.min == self.max
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct GlyphInfo {
|
||||
pub(crate) id: ab_glyph::GlyphId,
|
||||
|
||||
/// Unit: points.
|
||||
pub advance_width: f32,
|
||||
|
||||
/// Texture coordinates. None for space.
|
||||
pub uv_rect: UvRect,
|
||||
}
|
||||
|
||||
impl Default for GlyphInfo {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
id: ab_glyph::GlyphId(0),
|
||||
advance_width: 0.0,
|
||||
uv_rect: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
/// A specific font with a size.
|
||||
/// The interface uses points as the unit for everything.
|
||||
pub struct FontImpl {
|
||||
name: String,
|
||||
ab_glyph_font: ab_glyph::FontArc,
|
||||
/// Maximum character height
|
||||
scale_in_pixels: u32,
|
||||
height_in_points: f32,
|
||||
// move each character by this much (hack)
|
||||
y_offset: f32,
|
||||
pixels_per_point: f32,
|
||||
glyph_info_cache: RwLock<ahash::HashMap<char, GlyphInfo>>, // TODO(emilk): standard Mutex
|
||||
atlas: Arc<Mutex<TextureAtlas>>,
|
||||
}
|
||||
|
||||
impl FontImpl {
|
||||
pub fn new(
|
||||
atlas: Arc<Mutex<TextureAtlas>>,
|
||||
pixels_per_point: f32,
|
||||
name: String,
|
||||
ab_glyph_font: ab_glyph::FontArc,
|
||||
scale_in_pixels: u32,
|
||||
y_offset_points: f32,
|
||||
) -> FontImpl {
|
||||
assert!(scale_in_pixels > 0);
|
||||
assert!(pixels_per_point > 0.0);
|
||||
|
||||
let height_in_points = scale_in_pixels as f32 / pixels_per_point;
|
||||
|
||||
// TODO(emilk): use these font metrics?
|
||||
// use ab_glyph::ScaleFont as _;
|
||||
// let scaled = ab_glyph_font.as_scaled(scale_in_pixels as f32);
|
||||
// dbg!(scaled.ascent());
|
||||
// dbg!(scaled.descent());
|
||||
// dbg!(scaled.line_gap());
|
||||
|
||||
// Round to closest pixel:
|
||||
let y_offset = (y_offset_points * pixels_per_point).round() / pixels_per_point;
|
||||
|
||||
Self {
|
||||
name,
|
||||
ab_glyph_font,
|
||||
scale_in_pixels,
|
||||
height_in_points,
|
||||
y_offset,
|
||||
pixels_per_point,
|
||||
glyph_info_cache: Default::default(),
|
||||
atlas,
|
||||
}
|
||||
}
|
||||
|
||||
fn ignore_character(&self, chr: char) -> bool {
|
||||
if self.name == "emoji-icon-font" {
|
||||
// HACK: https://github.com/emilk/egui/issues/1284 https://github.com/jslegers/emoji-icon-font/issues/18
|
||||
// Don't show the wrong fullwidth capital letters:
|
||||
if 'S' <= chr && chr <= 'Y' {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
matches!(
|
||||
chr,
|
||||
// Strip out a religious symbol with secondary nefarious interpretation:
|
||||
'\u{534d}' | '\u{5350}' |
|
||||
|
||||
// Ignore ubuntu-specific stuff in `Ubuntu-Light.ttf`:
|
||||
'\u{E0FF}' | '\u{EFFD}' | '\u{F0FF}' | '\u{F200}'
|
||||
)
|
||||
}
|
||||
|
||||
/// An un-ordered iterator over all supported characters.
|
||||
fn characters(&self) -> impl Iterator<Item = char> + '_ {
|
||||
use ab_glyph::Font as _;
|
||||
self.ab_glyph_font
|
||||
.codepoint_ids()
|
||||
.map(|(_, chr)| chr)
|
||||
.filter(|&chr| !self.ignore_character(chr))
|
||||
}
|
||||
|
||||
/// `\n` will result in `None`
|
||||
fn glyph_info(&self, c: char) -> Option<GlyphInfo> {
|
||||
{
|
||||
if let Some(glyph_info) = self.glyph_info_cache.read().get(&c) {
|
||||
return Some(*glyph_info);
|
||||
}
|
||||
}
|
||||
|
||||
if self.ignore_character(c) {
|
||||
return None;
|
||||
}
|
||||
|
||||
if c == '\t' {
|
||||
if let Some(space) = self.glyph_info(' ') {
|
||||
let glyph_info = GlyphInfo {
|
||||
advance_width: crate::text::TAB_SIZE as f32 * space.advance_width,
|
||||
..GlyphInfo::default()
|
||||
};
|
||||
self.glyph_info_cache.write().insert(c, glyph_info);
|
||||
return Some(glyph_info);
|
||||
}
|
||||
}
|
||||
|
||||
// Add new character:
|
||||
use ab_glyph::Font as _;
|
||||
let glyph_id = self.ab_glyph_font.glyph_id(c);
|
||||
|
||||
if glyph_id.0 == 0 {
|
||||
if invisible_char(c) {
|
||||
// hack
|
||||
let glyph_info = GlyphInfo::default();
|
||||
self.glyph_info_cache.write().insert(c, glyph_info);
|
||||
Some(glyph_info)
|
||||
} else {
|
||||
None // unsupported character
|
||||
}
|
||||
} else {
|
||||
let glyph_info = allocate_glyph(
|
||||
&mut self.atlas.lock(),
|
||||
&self.ab_glyph_font,
|
||||
glyph_id,
|
||||
self.scale_in_pixels as f32,
|
||||
self.y_offset,
|
||||
self.pixels_per_point,
|
||||
);
|
||||
|
||||
self.glyph_info_cache.write().insert(c, glyph_info);
|
||||
Some(glyph_info)
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn pair_kerning(
|
||||
&self,
|
||||
last_glyph_id: ab_glyph::GlyphId,
|
||||
glyph_id: ab_glyph::GlyphId,
|
||||
) -> f32 {
|
||||
use ab_glyph::{Font as _, ScaleFont};
|
||||
self.ab_glyph_font
|
||||
.as_scaled(self.scale_in_pixels as f32)
|
||||
.kern(last_glyph_id, glyph_id)
|
||||
/ self.pixels_per_point
|
||||
}
|
||||
|
||||
/// Height of one row of text. In points
|
||||
#[inline(always)]
|
||||
pub fn row_height(&self) -> f32 {
|
||||
self.height_in_points
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn pixels_per_point(&self) -> f32 {
|
||||
self.pixels_per_point
|
||||
}
|
||||
}
|
||||
|
||||
type FontIndex = usize;
|
||||
|
||||
// TODO(emilk): rename?
|
||||
/// Wrapper over multiple [`FontImpl`] (e.g. a primary + fallbacks for emojis)
|
||||
pub struct Font {
|
||||
fonts: Vec<Arc<FontImpl>>,
|
||||
/// Lazily calculated.
|
||||
characters: Option<BTreeSet<char>>,
|
||||
replacement_glyph: (FontIndex, GlyphInfo),
|
||||
pixels_per_point: f32,
|
||||
row_height: f32,
|
||||
glyph_info_cache: ahash::HashMap<char, (FontIndex, GlyphInfo)>,
|
||||
}
|
||||
|
||||
impl Font {
|
||||
pub fn new(fonts: Vec<Arc<FontImpl>>) -> Self {
|
||||
if fonts.is_empty() {
|
||||
return Self {
|
||||
fonts,
|
||||
characters: None,
|
||||
replacement_glyph: Default::default(),
|
||||
pixels_per_point: 1.0,
|
||||
row_height: 0.0,
|
||||
glyph_info_cache: Default::default(),
|
||||
};
|
||||
}
|
||||
|
||||
let pixels_per_point = fonts[0].pixels_per_point();
|
||||
let row_height = fonts[0].row_height();
|
||||
|
||||
let mut slf = Self {
|
||||
fonts,
|
||||
characters: None,
|
||||
replacement_glyph: Default::default(),
|
||||
pixels_per_point,
|
||||
row_height,
|
||||
glyph_info_cache: Default::default(),
|
||||
};
|
||||
|
||||
const PRIMARY_REPLACEMENT_CHAR: char = '◻'; // white medium square
|
||||
const FALLBACK_REPLACEMENT_CHAR: char = '?'; // fallback for the fallback
|
||||
|
||||
let replacement_glyph = slf
|
||||
.glyph_info_no_cache_or_fallback(PRIMARY_REPLACEMENT_CHAR)
|
||||
.or_else(|| slf.glyph_info_no_cache_or_fallback(FALLBACK_REPLACEMENT_CHAR))
|
||||
.unwrap_or_else(|| {
|
||||
panic!(
|
||||
"Failed to find replacement characters {:?} or {:?}",
|
||||
PRIMARY_REPLACEMENT_CHAR, FALLBACK_REPLACEMENT_CHAR
|
||||
)
|
||||
});
|
||||
slf.replacement_glyph = replacement_glyph;
|
||||
|
||||
slf
|
||||
}
|
||||
|
||||
pub fn preload_common_characters(&mut self) {
|
||||
// Preload the printable ASCII characters [32, 126] (which excludes control codes):
|
||||
const FIRST_ASCII: usize = 32; // 32 == space
|
||||
const LAST_ASCII: usize = 126;
|
||||
for c in (FIRST_ASCII..=LAST_ASCII).map(|c| c as u8 as char) {
|
||||
self.glyph_info(c);
|
||||
}
|
||||
self.glyph_info('°');
|
||||
self.glyph_info(crate::text::PASSWORD_REPLACEMENT_CHAR);
|
||||
}
|
||||
|
||||
/// All supported characters
|
||||
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());
|
||||
}
|
||||
characters
|
||||
})
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn round_to_pixel(&self, point: f32) -> f32 {
|
||||
(point * self.pixels_per_point).round() / self.pixels_per_point
|
||||
}
|
||||
|
||||
/// Height of one row of text. In points
|
||||
#[inline(always)]
|
||||
pub fn row_height(&self) -> f32 {
|
||||
self.row_height
|
||||
}
|
||||
|
||||
pub fn uv_rect(&self, c: char) -> UvRect {
|
||||
self.glyph_info_cache
|
||||
.get(&c)
|
||||
.map(|gi| gi.1.uv_rect)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Width of this character in points.
|
||||
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(&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.insert(c, font_index_glyph_info);
|
||||
font_index_glyph_info
|
||||
}
|
||||
|
||||
#[inline]
|
||||
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);
|
||||
}
|
||||
let (font_index, glyph_info) = self.glyph_info(c);
|
||||
let font_impl = &self.fonts[font_index];
|
||||
(Some(font_impl), glyph_info)
|
||||
}
|
||||
|
||||
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.insert(c, (font_index, glyph_info));
|
||||
return Some((font_index, glyph_info));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn invisible_char(c: char) -> bool {
|
||||
// See https://github.com/emilk/egui/issues/336
|
||||
|
||||
// From https://www.fileformat.info/info/unicode/category/Cf/list.htm
|
||||
('\u{200B}'..='\u{206F}').contains(&c) // TODO(emilk): heed bidi characters
|
||||
}
|
||||
|
||||
fn allocate_glyph(
|
||||
atlas: &mut TextureAtlas,
|
||||
font: &ab_glyph::FontArc,
|
||||
glyph_id: ab_glyph::GlyphId,
|
||||
scale_in_pixels: f32,
|
||||
y_offset: f32,
|
||||
pixels_per_point: f32,
|
||||
) -> GlyphInfo {
|
||||
assert!(glyph_id.0 != 0);
|
||||
use ab_glyph::{Font as _, ScaleFont};
|
||||
|
||||
let glyph =
|
||||
glyph_id.with_scale_and_position(scale_in_pixels, ab_glyph::Point { x: 0.0, y: 0.0 });
|
||||
|
||||
let uv_rect = font.outline_glyph(glyph).map(|glyph| {
|
||||
let bb = glyph.px_bounds();
|
||||
let glyph_width = bb.width() as usize;
|
||||
let glyph_height = bb.height() as usize;
|
||||
if glyph_width == 0 || glyph_height == 0 {
|
||||
UvRect::default()
|
||||
} else {
|
||||
let (glyph_pos, image) = atlas.allocate((glyph_width, glyph_height));
|
||||
glyph.draw(|x, y, v| {
|
||||
if v > 0.0 {
|
||||
let px = glyph_pos.0 + x as usize;
|
||||
let py = glyph_pos.1 + y as usize;
|
||||
image[(px, py)] = v;
|
||||
}
|
||||
});
|
||||
|
||||
let offset_in_pixels = vec2(bb.min.x, scale_in_pixels + bb.min.y);
|
||||
let offset = offset_in_pixels / pixels_per_point + y_offset * Vec2::Y;
|
||||
UvRect {
|
||||
offset,
|
||||
size: vec2(glyph_width as f32, glyph_height as f32) / pixels_per_point,
|
||||
min: [glyph_pos.0 as u16, glyph_pos.1 as u16],
|
||||
max: [
|
||||
(glyph_pos.0 + glyph_width) as u16,
|
||||
(glyph_pos.1 + glyph_height) as u16,
|
||||
],
|
||||
}
|
||||
}
|
||||
});
|
||||
let uv_rect = uv_rect.unwrap_or_default();
|
||||
|
||||
let advance_width_in_points =
|
||||
font.as_scaled(scale_in_pixels).h_advance(glyph_id) / pixels_per_point;
|
||||
|
||||
GlyphInfo {
|
||||
id: glyph_id,
|
||||
advance_width: advance_width_in_points,
|
||||
uv_rect,
|
||||
}
|
||||
}
|
||||
739
crates/epaint/src/text/fonts.rs
Normal file
739
crates/epaint/src/text/fonts.rs
Normal file
@@ -0,0 +1,739 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::{
|
||||
mutex::{Mutex, MutexGuard},
|
||||
text::{
|
||||
font::{Font, FontImpl},
|
||||
Galley, LayoutJob,
|
||||
},
|
||||
TextureAtlas,
|
||||
};
|
||||
use emath::NumExt as _;
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
/// How to select a sized font.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
|
||||
pub struct FontId {
|
||||
/// Height in points.
|
||||
pub size: f32,
|
||||
|
||||
/// What font family to use.
|
||||
pub family: FontFamily,
|
||||
// TODO(emilk): weight (bold), italics, …
|
||||
}
|
||||
|
||||
impl Default for FontId {
|
||||
#[inline]
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
size: 14.0,
|
||||
family: FontFamily::Proportional,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl FontId {
|
||||
#[inline]
|
||||
pub const fn new(size: f32, family: FontFamily) -> Self {
|
||||
Self { size, family }
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub const fn proportional(size: f32) -> Self {
|
||||
Self::new(size, FontFamily::Proportional)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub const 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,
|
||||
|
||||
/// Extra scale and vertical tweak to apply to all text of this font.
|
||||
pub tweak: FontTweak,
|
||||
}
|
||||
|
||||
impl FontData {
|
||||
pub fn from_static(font: &'static [u8]) -> Self {
|
||||
Self {
|
||||
font: std::borrow::Cow::Borrowed(font),
|
||||
index: 0,
|
||||
tweak: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_owned(font: Vec<u8>) -> Self {
|
||||
Self {
|
||||
font: std::borrow::Cow::Owned(font),
|
||||
index: 0,
|
||||
tweak: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn tweak(self, tweak: FontTweak) -> Self {
|
||||
Self { tweak, ..self }
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
/// Extra scale and vertical tweak to apply to all text of a certain font.
|
||||
#[derive(Copy, Clone, Debug, PartialEq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
|
||||
pub struct FontTweak {
|
||||
/// Scale the font by this much.
|
||||
///
|
||||
/// Default: `1.0` (no scaling).
|
||||
pub scale: f32,
|
||||
|
||||
/// Shift font downwards by this fraction of the font size (in points).
|
||||
///
|
||||
/// A positive value shifts the text downwards.
|
||||
/// A negative value shifts it upwards.
|
||||
///
|
||||
/// Example value: `-0.2`.
|
||||
pub y_offset_factor: f32,
|
||||
|
||||
/// Shift font downwards by this amount of logical points.
|
||||
///
|
||||
/// Example value: `2.0`.
|
||||
pub y_offset: f32,
|
||||
}
|
||||
|
||||
impl Default for FontTweak {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
scale: 1.0,
|
||||
y_offset_factor: -0.2, // makes the default fonts look more centered in buttons and such
|
||||
y_offset: 0.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
fn ab_glyph_font_from_font_data(name: &str, data: &FontData) -> ab_glyph::FontArc {
|
||||
match &data.font {
|
||||
std::borrow::Cow::Borrowed(bytes) => {
|
||||
ab_glyph::FontRef::try_from_slice_and_index(bytes, data.index)
|
||||
.map(ab_glyph::FontArc::from)
|
||||
}
|
||||
std::borrow::Cow::Owned(bytes) => {
|
||||
ab_glyph::FontVec::try_from_vec_and_index(bytes.clone(), data.index)
|
||||
.map(ab_glyph::FontArc::from)
|
||||
}
|
||||
}
|
||||
.unwrap_or_else(|err| panic!("Error parsing {:?} TTF/OTF font file: {}", name, err))
|
||||
}
|
||||
|
||||
/// Describes the font data and the sizes to use.
|
||||
///
|
||||
/// 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, FontFamily, FontData}};
|
||||
/// # struct FakeEguiCtx {};
|
||||
/// # impl FakeEguiCtx { fn set_fonts(&self, _: FontDefinitions) {} }
|
||||
/// # let egui_ctx = FakeEguiCtx {};
|
||||
/// let mut fonts = FontDefinitions::default();
|
||||
///
|
||||
/// // Install my own font (maybe supporting non-latin characters):
|
||||
/// fonts.font_data.insert("my_font".to_owned(),
|
||||
/// FontData::from_static(include_bytes!("../../fonts/Ubuntu-Light.ttf"))); // .ttf and .otf supported
|
||||
///
|
||||
/// // Put my font first (highest priority):
|
||||
/// fonts.families.get_mut(&FontFamily::Proportional).unwrap()
|
||||
/// .insert(0, "my_font".to_owned());
|
||||
///
|
||||
/// // Put my font as last fallback for monospace:
|
||||
/// fonts.families.get_mut(&FontFamily::Monospace).unwrap()
|
||||
/// .push("my_font".to_owned());
|
||||
///
|
||||
/// egui_ctx.set_fonts(fonts);
|
||||
/// ```
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub struct FontDefinitions {
|
||||
/// List of font names and their definitions.
|
||||
///
|
||||
/// `epaint` has built-in-default for these, but you can override them if you like.
|
||||
pub font_data: BTreeMap<String, FontData>,
|
||||
|
||||
/// Which fonts (names) to use for each [`FontFamily`].
|
||||
///
|
||||
/// The list should be a list of keys into [`Self::font_data`].
|
||||
/// 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 families: BTreeMap<FontFamily, Vec<String>>,
|
||||
}
|
||||
|
||||
impl Default for FontDefinitions {
|
||||
/// Specifies the default fonts if the feature `default_fonts` is enabled,
|
||||
/// otherwise this is the same as [`Self::empty`].
|
||||
#[cfg(not(feature = "default_fonts"))]
|
||||
fn default() -> Self {
|
||||
Self::empty()
|
||||
}
|
||||
|
||||
/// Specifies the default fonts if the feature `default_fonts` is enabled,
|
||||
/// otherwise this is the same as [`Self::empty`].
|
||||
#[cfg(feature = "default_fonts")]
|
||||
fn default() -> Self {
|
||||
let mut font_data: BTreeMap<String, FontData> = BTreeMap::new();
|
||||
|
||||
let mut families = BTreeMap::new();
|
||||
|
||||
font_data.insert(
|
||||
"Hack".to_owned(),
|
||||
FontData::from_static(include_bytes!("../../fonts/Hack-Regular.ttf")),
|
||||
);
|
||||
font_data.insert(
|
||||
"Ubuntu-Light".to_owned(),
|
||||
FontData::from_static(include_bytes!("../../fonts/Ubuntu-Light.ttf")),
|
||||
);
|
||||
|
||||
// Some good looking emojis. Use as first priority:
|
||||
font_data.insert(
|
||||
"NotoEmoji-Regular".to_owned(),
|
||||
FontData::from_static(include_bytes!("../../fonts/NotoEmoji-Regular.ttf")),
|
||||
);
|
||||
|
||||
// Bigger emojis, and more. <http://jslegers.github.io/emoji-icon-font/>:
|
||||
font_data.insert(
|
||||
"emoji-icon-font".to_owned(),
|
||||
FontData::from_static(include_bytes!("../../fonts/emoji-icon-font.ttf")).tweak(
|
||||
FontTweak {
|
||||
scale: 0.8, // make it smaller
|
||||
y_offset_factor: 0.07, // move it down slightly
|
||||
y_offset: 0.0,
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
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(),
|
||||
],
|
||||
);
|
||||
|
||||
Self {
|
||||
font_data,
|
||||
families,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl FontDefinitions {
|
||||
/// No fonts.
|
||||
pub fn empty() -> Self {
|
||||
let mut families = BTreeMap::new();
|
||||
families.insert(FontFamily::Monospace, vec![]);
|
||||
families.insert(FontFamily::Proportional, vec![]);
|
||||
|
||||
Self {
|
||||
font_data: Default::default(),
|
||||
families,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
/// The collection of fonts used by `epaint`.
|
||||
///
|
||||
/// Required in order to paint text. Create one and reuse. Cheap to clone.
|
||||
///
|
||||
/// Each [`Fonts`] comes with a font atlas textures that needs to be used when painting.
|
||||
///
|
||||
/// If you are using `egui`, use `egui::Context::set_fonts` and `egui::Context::fonts`.
|
||||
///
|
||||
/// You need to call [`Self::begin_frame`] and [`Self::font_image_delta`] once every frame.
|
||||
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.
|
||||
///
|
||||
/// * `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
|
||||
}
|
||||
|
||||
/// The font atlas.
|
||||
/// Pass this to [`crate::Tessellator`].
|
||||
pub fn texture_atlas(&self) -> Arc<Mutex<TextureAtlas>> {
|
||||
self.lock().fonts.atlas.clone()
|
||||
}
|
||||
|
||||
/// 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::HashMap<(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
|
||||
);
|
||||
|
||||
let texture_width = max_texture_side.at_most(8 * 1024);
|
||||
let initial_height = 64;
|
||||
let atlas = TextureAtlas::new([texture_width, initial_height]);
|
||||
|
||||
let atlas = Arc::new(Mutex::new(atlas));
|
||||
|
||||
let font_impl_cache =
|
||||
FontImplCache::new(atlas.clone(), pixels_per_point, &definitions.font_data);
|
||||
|
||||
Self {
|
||||
pixels_per_point,
|
||||
max_texture_side,
|
||||
definitions,
|
||||
atlas,
|
||||
font_impl_cache,
|
||||
sized_family: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn pixels_per_point(&self) -> f32 {
|
||||
self.pixels_per_point
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn definitions(&self) -> &FontDefinitions {
|
||||
&self.definitions
|
||||
}
|
||||
|
||||
/// 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);
|
||||
|
||||
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)
|
||||
});
|
||||
|
||||
let fonts: Vec<Arc<FontImpl>> = fonts
|
||||
.iter()
|
||||
.map(|font_name| self.font_impl_cache.font_impl(scale_in_pixels, font_name))
|
||||
.collect();
|
||||
|
||||
Font::new(fonts)
|
||||
})
|
||||
}
|
||||
|
||||
/// Width of this character in points.
|
||||
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
|
||||
fn row_height(&mut self, font_id: &FontId) -> f32 {
|
||||
self.font(font_id).row_height()
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
struct CachedGalley {
|
||||
/// When it was last used
|
||||
last_used: u32,
|
||||
galley: Arc<Galley>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct GalleyCache {
|
||||
/// Frame counter used to do garbage collection on the cache
|
||||
generation: u32,
|
||||
cache: nohash_hasher::IntMap<u64, CachedGalley>,
|
||||
}
|
||||
|
||||
impl GalleyCache {
|
||||
fn layout(&mut self, fonts: &mut FontsImpl, job: LayoutJob) -> Arc<Galley> {
|
||||
let hash = crate::util::hash(&job); // TODO(emilk): even faster hasher?
|
||||
|
||||
match self.cache.entry(hash) {
|
||||
std::collections::hash_map::Entry::Occupied(entry) => {
|
||||
let cached = entry.into_mut();
|
||||
cached.last_used = self.generation;
|
||||
cached.galley.clone()
|
||||
}
|
||||
std::collections::hash_map::Entry::Vacant(entry) => {
|
||||
let galley = super::layout(fonts, job.into());
|
||||
let galley = Arc::new(galley);
|
||||
entry.insert(CachedGalley {
|
||||
last_used: self.generation,
|
||||
galley: galley.clone(),
|
||||
});
|
||||
galley
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn num_galleys_in_cache(&self) -> usize {
|
||||
self.cache.len()
|
||||
}
|
||||
|
||||
/// Must be called once per frame to clear the [`Galley`] cache.
|
||||
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
|
||||
});
|
||||
self.generation = self.generation.wrapping_add(1);
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
struct FontImplCache {
|
||||
atlas: Arc<Mutex<TextureAtlas>>,
|
||||
pixels_per_point: f32,
|
||||
ab_glyph_fonts: BTreeMap<String, (FontTweak, ab_glyph::FontArc)>,
|
||||
|
||||
/// Map font pixel sizes and names to the cached [`FontImpl`].
|
||||
cache: ahash::HashMap<(u32, String), Arc<FontImpl>>,
|
||||
}
|
||||
|
||||
impl FontImplCache {
|
||||
pub fn new(
|
||||
atlas: Arc<Mutex<TextureAtlas>>,
|
||||
pixels_per_point: f32,
|
||||
font_data: &BTreeMap<String, FontData>,
|
||||
) -> Self {
|
||||
let ab_glyph_fonts = font_data
|
||||
.iter()
|
||||
.map(|(name, font_data)| {
|
||||
let tweak = font_data.tweak;
|
||||
let ab_glyph = ab_glyph_font_from_font_data(name, font_data);
|
||||
(name.clone(), (tweak, ab_glyph))
|
||||
})
|
||||
.collect();
|
||||
|
||||
Self {
|
||||
atlas,
|
||||
pixels_per_point,
|
||||
ab_glyph_fonts,
|
||||
cache: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
#[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, scale_in_pixels: u32, font_name: &str) -> Arc<FontImpl> {
|
||||
let (tweak, ab_glyph_font) = self
|
||||
.ab_glyph_fonts
|
||||
.get(font_name)
|
||||
.unwrap_or_else(|| panic!("No font data found for {:?}", font_name))
|
||||
.clone();
|
||||
|
||||
let scale_in_pixels = (scale_in_pixels as f32 * tweak.scale).round() as u32;
|
||||
|
||||
let y_offset_points = {
|
||||
let scale_in_points = scale_in_pixels as f32 / self.pixels_per_point;
|
||||
scale_in_points * tweak.y_offset_factor
|
||||
} + tweak.y_offset;
|
||||
|
||||
self.cache
|
||||
.entry((scale_in_pixels, font_name.to_owned()))
|
||||
.or_insert_with(|| {
|
||||
Arc::new(FontImpl::new(
|
||||
self.atlas.clone(),
|
||||
self.pixels_per_point,
|
||||
font_name.to_owned(),
|
||||
ab_glyph_font,
|
||||
scale_in_pixels,
|
||||
y_offset_points,
|
||||
))
|
||||
})
|
||||
.clone()
|
||||
}
|
||||
}
|
||||
19
crates/epaint/src/text/mod.rs
Normal file
19
crates/epaint/src/text/mod.rs
Normal file
@@ -0,0 +1,19 @@
|
||||
//! Everything related to text, fonts, text layout, cursors etc.
|
||||
|
||||
pub mod cursor;
|
||||
mod font;
|
||||
mod fonts;
|
||||
mod text_layout;
|
||||
mod text_layout_types;
|
||||
|
||||
/// One `\t` character is this many spaces wide.
|
||||
pub const TAB_SIZE: usize = 4;
|
||||
|
||||
pub use {
|
||||
fonts::{FontData, FontDefinitions, FontFamily, FontId, FontTweak, Fonts, FontsImpl},
|
||||
text_layout::layout,
|
||||
text_layout_types::*,
|
||||
};
|
||||
|
||||
/// Suggested character to use to replace those in password text fields.
|
||||
pub const PASSWORD_REPLACEMENT_CHAR: char = '•';
|
||||
814
crates/epaint/src/text/text_layout.rs
Normal file
814
crates/epaint/src/text/text_layout.rs
Normal file
@@ -0,0 +1,814 @@
|
||||
use std::ops::RangeInclusive;
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::{FontsImpl, Galley, Glyph, LayoutJob, LayoutSection, Row, RowVisuals};
|
||||
use crate::{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 {
|
||||
/// Start of the next glyph to be added.
|
||||
pub cursor_x: f32,
|
||||
|
||||
pub glyphs: Vec<Glyph>,
|
||||
|
||||
/// In case of an empty paragraph ("\n"), use this as height.
|
||||
pub empty_paragraph_height: f32,
|
||||
}
|
||||
|
||||
/// Layout text into a [`Galley`].
|
||||
///
|
||||
/// 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: &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(fonts, paragraphs, &job);
|
||||
|
||||
let justify = job.justify && job.wrap.max_width.is_finite();
|
||||
|
||||
if justify || job.halign != Align::LEFT {
|
||||
let num_rows = rows.len();
|
||||
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(
|
||||
point_scale,
|
||||
row,
|
||||
job.halign,
|
||||
job.wrap.max_width,
|
||||
justify_row,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
galley_from_rows(point_scale, job, rows)
|
||||
}
|
||||
|
||||
fn layout_section(
|
||||
fonts: &mut FontsImpl,
|
||||
job: &LayoutJob,
|
||||
section_index: u32,
|
||||
section: &LayoutSection,
|
||||
out_paragraphs: &mut Vec<Paragraph>,
|
||||
) {
|
||||
let LayoutSection {
|
||||
leading_space,
|
||||
byte_range,
|
||||
format,
|
||||
} = section;
|
||||
let font = fonts.font(&format.font_id);
|
||||
let font_height = font.row_height();
|
||||
|
||||
let mut paragraph = out_paragraphs.last_mut().unwrap();
|
||||
if paragraph.glyphs.is_empty() {
|
||||
paragraph.empty_paragraph_height = font_height; // TODO(emilk): replace this hack with actually including `\n` in the glyphs?
|
||||
}
|
||||
|
||||
paragraph.cursor_x += leading_space;
|
||||
|
||||
let mut last_glyph_id = None;
|
||||
|
||||
for chr in job.text[byte_range.clone()].chars() {
|
||||
if job.break_on_newline && chr == '\n' {
|
||||
out_paragraphs.push(Paragraph::default());
|
||||
paragraph = out_paragraphs.last_mut().unwrap();
|
||||
paragraph.empty_paragraph_height = font_height; // TODO(emilk): replace this hack with actually including `\n` in the glyphs?
|
||||
} else {
|
||||
let (font_impl, glyph_info) = font.glyph_info_and_font_impl(chr);
|
||||
if let Some(font_impl) = font_impl {
|
||||
if let Some(last_glyph_id) = last_glyph_id {
|
||||
paragraph.cursor_x += font_impl.pair_kerning(last_glyph_id, glyph_info.id);
|
||||
}
|
||||
}
|
||||
|
||||
paragraph.glyphs.push(Glyph {
|
||||
chr,
|
||||
pos: pos2(paragraph.cursor_x, f32::NAN),
|
||||
size: vec2(glyph_info.advance_width, font_height),
|
||||
uv_rect: glyph_info.uv_rect,
|
||||
section_index,
|
||||
});
|
||||
|
||||
paragraph.cursor_x += glyph_info.advance_width;
|
||||
paragraph.cursor_x = font.round_to_pixel(paragraph.cursor_x);
|
||||
last_glyph_id = Some(glyph_info.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// We ignore y at this stage
|
||||
fn rect_from_x_range(x_range: RangeInclusive<f32>) -> Rect {
|
||||
Rect::from_x_y_ranges(x_range, 0.0..=0.0)
|
||||
}
|
||||
|
||||
fn rows_from_paragraphs(
|
||||
fonts: &mut FontsImpl,
|
||||
paragraphs: Vec<Paragraph>,
|
||||
job: &LayoutJob,
|
||||
) -> Vec<Row> {
|
||||
let num_paragraphs = paragraphs.len();
|
||||
|
||||
let mut rows = vec![];
|
||||
|
||||
for (i, paragraph) in paragraphs.into_iter().enumerate() {
|
||||
let is_last_paragraph = (i + 1) == num_paragraphs;
|
||||
|
||||
if paragraph.glyphs.is_empty() {
|
||||
rows.push(Row {
|
||||
glyphs: vec![],
|
||||
visuals: Default::default(),
|
||||
rect: Rect::from_min_size(
|
||||
pos2(paragraph.cursor_x, 0.0),
|
||||
vec2(0.0, paragraph.empty_paragraph_height),
|
||||
),
|
||||
ends_with_newline: !is_last_paragraph,
|
||||
});
|
||||
} else {
|
||||
let paragraph_max_x = paragraph.glyphs.last().unwrap().max_x();
|
||||
if paragraph_max_x <= job.wrap.max_width {
|
||||
// early-out optimization
|
||||
let paragraph_min_x = paragraph.glyphs[0].pos.x;
|
||||
rows.push(Row {
|
||||
glyphs: paragraph.glyphs,
|
||||
visuals: Default::default(),
|
||||
rect: rect_from_x_range(paragraph_min_x..=paragraph_max_x),
|
||||
ends_with_newline: !is_last_paragraph,
|
||||
});
|
||||
} else {
|
||||
line_break(fonts, ¶graph, job, &mut rows);
|
||||
rows.last_mut().unwrap().ends_with_newline = !is_last_paragraph;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
rows
|
||||
}
|
||||
|
||||
fn line_break(
|
||||
fonts: &mut FontsImpl,
|
||||
paragraph: &Paragraph,
|
||||
job: &LayoutJob,
|
||||
out_rows: &mut Vec<Row>,
|
||||
) {
|
||||
// Keeps track of good places to insert row break if we exceed `wrap_width`.
|
||||
let mut row_break_candidates = RowBreakCandidates::default();
|
||||
|
||||
let mut first_row_indentation = paragraph.glyphs[0].pos.x;
|
||||
let mut row_start_x = 0.0;
|
||||
let mut row_start_idx = 0;
|
||||
let mut non_empty_rows = 0;
|
||||
|
||||
for i in 0..paragraph.glyphs.len() {
|
||||
let potential_row_width = paragraph.glyphs[i].max_x() - row_start_x;
|
||||
|
||||
if job.wrap.max_rows > 0 && non_empty_rows >= job.wrap.max_rows {
|
||||
break;
|
||||
}
|
||||
|
||||
if potential_row_width > job.wrap.max_width {
|
||||
if first_row_indentation > 0.0
|
||||
&& !row_break_candidates.has_good_candidate(job.wrap.break_anywhere)
|
||||
{
|
||||
// Allow the first row to be completely empty, because we know there will be more space on the next row:
|
||||
// TODO(emilk): this records the height of this first row as zero, though that is probably fine since first_row_indentation usually comes with a first_row_min_height.
|
||||
out_rows.push(Row {
|
||||
glyphs: vec![],
|
||||
visuals: Default::default(),
|
||||
rect: rect_from_x_range(first_row_indentation..=first_row_indentation),
|
||||
ends_with_newline: false,
|
||||
});
|
||||
row_start_x += first_row_indentation;
|
||||
first_row_indentation = 0.0;
|
||||
} else if let Some(last_kept_index) = row_break_candidates.get(job.wrap.break_anywhere)
|
||||
{
|
||||
let glyphs: Vec<Glyph> = paragraph.glyphs[row_start_idx..=last_kept_index]
|
||||
.iter()
|
||||
.copied()
|
||||
.map(|mut glyph| {
|
||||
glyph.pos.x -= row_start_x;
|
||||
glyph
|
||||
})
|
||||
.collect();
|
||||
|
||||
let paragraph_min_x = glyphs[0].pos.x;
|
||||
let paragraph_max_x = glyphs.last().unwrap().max_x();
|
||||
|
||||
out_rows.push(Row {
|
||||
glyphs,
|
||||
visuals: Default::default(),
|
||||
rect: rect_from_x_range(paragraph_min_x..=paragraph_max_x),
|
||||
ends_with_newline: false,
|
||||
});
|
||||
|
||||
row_start_idx = last_kept_index + 1;
|
||||
row_start_x = paragraph.glyphs[row_start_idx].pos.x;
|
||||
row_break_candidates = Default::default();
|
||||
non_empty_rows += 1;
|
||||
} else {
|
||||
// Found no place to break, so we have to overrun wrap_width.
|
||||
}
|
||||
}
|
||||
|
||||
row_break_candidates.add(i, ¶graph.glyphs[i..]);
|
||||
}
|
||||
|
||||
if row_start_idx < paragraph.glyphs.len() {
|
||||
if job.wrap.max_rows > 0 && non_empty_rows == job.wrap.max_rows {
|
||||
if let Some(last_row) = out_rows.last_mut() {
|
||||
replace_last_glyph_with_overflow_character(fonts, job, last_row);
|
||||
}
|
||||
} else {
|
||||
let glyphs: Vec<Glyph> = paragraph.glyphs[row_start_idx..]
|
||||
.iter()
|
||||
.copied()
|
||||
.map(|mut glyph| {
|
||||
glyph.pos.x -= row_start_x;
|
||||
glyph
|
||||
})
|
||||
.collect();
|
||||
|
||||
let paragraph_min_x = glyphs[0].pos.x;
|
||||
let paragraph_max_x = glyphs.last().unwrap().max_x();
|
||||
|
||||
out_rows.push(Row {
|
||||
glyphs,
|
||||
visuals: Default::default(),
|
||||
rect: rect_from_x_range(paragraph_min_x..=paragraph_max_x),
|
||||
ends_with_newline: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn replace_last_glyph_with_overflow_character(
|
||||
fonts: &mut FontsImpl,
|
||||
job: &LayoutJob,
|
||||
row: &mut Row,
|
||||
) {
|
||||
let overflow_character = match job.wrap.overflow_character {
|
||||
Some(c) => c,
|
||||
None => return,
|
||||
};
|
||||
|
||||
loop {
|
||||
let (prev_glyph, last_glyph) = match row.glyphs.as_mut_slice() {
|
||||
[.., prev, last] => (Some(prev), last),
|
||||
[.., last] => (None, last),
|
||||
_ => break,
|
||||
};
|
||||
|
||||
let section = &job.sections[last_glyph.section_index as usize];
|
||||
let font = fonts.font(§ion.format.font_id);
|
||||
let font_height = font.row_height();
|
||||
|
||||
let prev_glyph_id = prev_glyph.map(|prev_glyph| {
|
||||
let (_, prev_glyph_info) = font.glyph_info_and_font_impl(prev_glyph.chr);
|
||||
prev_glyph_info.id
|
||||
});
|
||||
|
||||
// undo kerning with previous glyph
|
||||
let (font_impl, glyph_info) = font.glyph_info_and_font_impl(last_glyph.chr);
|
||||
last_glyph.pos.x -= font_impl
|
||||
.zip(prev_glyph_id)
|
||||
.map(|(font_impl, prev_glyph_id)| font_impl.pair_kerning(prev_glyph_id, glyph_info.id))
|
||||
.unwrap_or_default();
|
||||
|
||||
// replace the glyph
|
||||
last_glyph.chr = overflow_character;
|
||||
let (font_impl, glyph_info) = font.glyph_info_and_font_impl(last_glyph.chr);
|
||||
last_glyph.size = vec2(glyph_info.advance_width, font_height);
|
||||
last_glyph.uv_rect = glyph_info.uv_rect;
|
||||
|
||||
// reapply kerning
|
||||
last_glyph.pos.x += font_impl
|
||||
.zip(prev_glyph_id)
|
||||
.map(|(font_impl, prev_glyph_id)| font_impl.pair_kerning(prev_glyph_id, glyph_info.id))
|
||||
.unwrap_or_default();
|
||||
|
||||
// check if we're still within width budget
|
||||
let row_end_x = last_glyph.max_x();
|
||||
let row_start_x = row.glyphs.first().unwrap().pos.x; // if `last_mut()` returned `Some`, then so will `first()`
|
||||
let row_width = row_end_x - row_start_x;
|
||||
if row_width <= job.wrap.max_width {
|
||||
break;
|
||||
}
|
||||
|
||||
row.glyphs.pop();
|
||||
}
|
||||
}
|
||||
|
||||
fn halign_and_jusitfy_row(
|
||||
point_scale: PointScale,
|
||||
row: &mut Row,
|
||||
halign: Align,
|
||||
wrap_width: f32,
|
||||
justify: bool,
|
||||
) {
|
||||
if row.glyphs.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let num_leading_spaces = row
|
||||
.glyphs
|
||||
.iter()
|
||||
.take_while(|glyph| glyph.chr.is_whitespace())
|
||||
.count();
|
||||
|
||||
let glyph_range = if num_leading_spaces == row.glyphs.len() {
|
||||
// There is only whitespace
|
||||
(0, row.glyphs.len())
|
||||
} else {
|
||||
let num_trailing_spaces = row
|
||||
.glyphs
|
||||
.iter()
|
||||
.rev()
|
||||
.take_while(|glyph| glyph.chr.is_whitespace())
|
||||
.count();
|
||||
|
||||
(num_leading_spaces, row.glyphs.len() - num_trailing_spaces)
|
||||
};
|
||||
let num_glyphs_in_range = glyph_range.1 - glyph_range.0;
|
||||
assert!(num_glyphs_in_range > 0);
|
||||
|
||||
let original_min_x = row.glyphs[glyph_range.0].logical_rect().min.x;
|
||||
let original_max_x = row.glyphs[glyph_range.1 - 1].logical_rect().max.x;
|
||||
let original_width = original_max_x - original_min_x;
|
||||
|
||||
let target_width = if justify && num_glyphs_in_range > 1 {
|
||||
wrap_width
|
||||
} else {
|
||||
original_width
|
||||
};
|
||||
|
||||
let (target_min_x, target_max_x) = match halign {
|
||||
Align::LEFT => (0.0, target_width),
|
||||
Align::Center => (-target_width / 2.0, target_width / 2.0),
|
||||
Align::RIGHT => (-target_width, 0.0),
|
||||
};
|
||||
|
||||
let num_spaces_in_range = row.glyphs[glyph_range.0..glyph_range.1]
|
||||
.iter()
|
||||
.filter(|glyph| glyph.chr.is_whitespace())
|
||||
.count();
|
||||
|
||||
let mut extra_x_per_glyph = if num_glyphs_in_range == 1 {
|
||||
0.0
|
||||
} else {
|
||||
(target_width - original_width) / (num_glyphs_in_range as f32 - 1.0)
|
||||
};
|
||||
extra_x_per_glyph = extra_x_per_glyph.at_least(0.0); // Don't contract
|
||||
|
||||
let mut extra_x_per_space = 0.0;
|
||||
if 0 < num_spaces_in_range && num_spaces_in_range < num_glyphs_in_range {
|
||||
// Add an integral number of pixels between each glyph,
|
||||
// and add the balance to the spaces:
|
||||
|
||||
extra_x_per_glyph = point_scale.floor_to_pixel(extra_x_per_glyph);
|
||||
|
||||
extra_x_per_space = (target_width
|
||||
- original_width
|
||||
- extra_x_per_glyph * (num_glyphs_in_range as f32 - 1.0))
|
||||
/ (num_spaces_in_range as f32);
|
||||
}
|
||||
|
||||
let mut translate_x = target_min_x - original_min_x - extra_x_per_glyph * glyph_range.0 as f32;
|
||||
|
||||
for glyph in &mut row.glyphs {
|
||||
glyph.pos.x += translate_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;
|
||||
}
|
||||
}
|
||||
|
||||
// Note we ignore the leading/trailing whitespace here!
|
||||
row.rect.min.x = target_min_x;
|
||||
row.rect.max.x = target_max_x;
|
||||
}
|
||||
|
||||
/// Calculate the Y positions and tessellate the text.
|
||||
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;
|
||||
let mut max_x: f32 = 0.0;
|
||||
for row in &mut rows {
|
||||
let mut row_height = first_row_min_height.max(row.rect.height());
|
||||
first_row_min_height = 0.0;
|
||||
for glyph in &row.glyphs {
|
||||
row_height = row_height.max(glyph.size.y);
|
||||
}
|
||||
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 = point_scale.round_to_pixel(glyph.pos.y);
|
||||
}
|
||||
|
||||
row.rect.min.y = cursor_y;
|
||||
row.rect.max.y = cursor_y + row_height;
|
||||
|
||||
min_x = min_x.min(row.rect.min.x);
|
||||
max_x = max_x.max(row.rect.max.x);
|
||||
cursor_y += row_height;
|
||||
cursor_y = point_scale.round_to_pixel(cursor_y);
|
||||
}
|
||||
|
||||
let format_summary = format_summary(&job);
|
||||
|
||||
let mut mesh_bounds = Rect::NOTHING;
|
||||
let mut num_vertices = 0;
|
||||
let mut num_indices = 0;
|
||||
|
||||
for row in &mut rows {
|
||||
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();
|
||||
}
|
||||
|
||||
let rect = Rect::from_min_max(pos2(min_x, 0.0), pos2(max_x, cursor_y));
|
||||
|
||||
Galley {
|
||||
job,
|
||||
rows,
|
||||
rect,
|
||||
mesh_bounds,
|
||||
num_vertices,
|
||||
num_indices,
|
||||
pixels_per_point: point_scale.pixels_per_point,
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct FormatSummary {
|
||||
any_background: bool,
|
||||
any_underline: bool,
|
||||
any_strikethrough: bool,
|
||||
}
|
||||
|
||||
fn format_summary(job: &LayoutJob) -> FormatSummary {
|
||||
let mut format_summary = FormatSummary::default();
|
||||
for section in &job.sections {
|
||||
format_summary.any_background |= section.format.background != Color32::TRANSPARENT;
|
||||
format_summary.any_underline |= section.format.underline != Stroke::none();
|
||||
format_summary.any_strikethrough |= section.format.strikethrough != Stroke::none();
|
||||
}
|
||||
format_summary
|
||||
}
|
||||
|
||||
fn tessellate_row(
|
||||
point_scale: PointScale,
|
||||
job: &LayoutJob,
|
||||
format_summary: &FormatSummary,
|
||||
row: &mut Row,
|
||||
) -> RowVisuals {
|
||||
if row.glyphs.is_empty() {
|
||||
return Default::default();
|
||||
}
|
||||
|
||||
let mut mesh = Mesh::default();
|
||||
|
||||
mesh.reserve_triangles(row.glyphs.len() * 2);
|
||||
mesh.reserve_vertices(row.glyphs.len() * 4);
|
||||
|
||||
if format_summary.any_background {
|
||||
add_row_backgrounds(job, row, &mut mesh);
|
||||
}
|
||||
|
||||
let glyph_vertex_start = mesh.vertices.len();
|
||||
tessellate_glyphs(point_scale, job, row, &mut mesh);
|
||||
let glyph_vertex_end = mesh.vertices.len();
|
||||
|
||||
if format_summary.any_underline {
|
||||
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();
|
||||
(stroke, y)
|
||||
});
|
||||
}
|
||||
|
||||
if format_summary.any_strikethrough {
|
||||
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;
|
||||
(stroke, y)
|
||||
});
|
||||
}
|
||||
|
||||
let mesh_bounds = mesh.calc_bounds();
|
||||
|
||||
RowVisuals {
|
||||
mesh,
|
||||
mesh_bounds,
|
||||
glyph_vertex_range: glyph_vertex_start..glyph_vertex_end,
|
||||
}
|
||||
}
|
||||
|
||||
/// Create background for glyphs that have them.
|
||||
/// Creates as few rectangular regions as possible.
|
||||
fn add_row_backgrounds(job: &LayoutJob, row: &Row, mesh: &mut Mesh) {
|
||||
if row.glyphs.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let mut end_run = |start: Option<(Color32, Rect)>, stop_x: f32| {
|
||||
if let Some((color, start_rect)) = start {
|
||||
let rect = Rect::from_min_max(start_rect.left_top(), pos2(stop_x, start_rect.bottom()));
|
||||
let rect = rect.expand(1.0); // looks better
|
||||
mesh.add_colored_rect(rect, color);
|
||||
}
|
||||
};
|
||||
|
||||
let mut run_start = None;
|
||||
let mut last_rect = Rect::NAN;
|
||||
|
||||
for glyph in &row.glyphs {
|
||||
let format = &job.sections[glyph.section_index as usize].format;
|
||||
let color = format.background;
|
||||
let rect = glyph.logical_rect();
|
||||
|
||||
if color == Color32::TRANSPARENT {
|
||||
end_run(run_start.take(), last_rect.right());
|
||||
} else if let Some((existing_color, start)) = run_start {
|
||||
if existing_color == color
|
||||
&& start.top() == rect.top()
|
||||
&& start.bottom() == rect.bottom()
|
||||
{
|
||||
// continue the same background rectangle
|
||||
} else {
|
||||
end_run(run_start.take(), last_rect.right());
|
||||
run_start = Some((color, rect));
|
||||
}
|
||||
} else {
|
||||
run_start = Some((color, rect));
|
||||
}
|
||||
|
||||
last_rect = rect;
|
||||
}
|
||||
|
||||
end_run(run_start.take(), last_rect.right());
|
||||
}
|
||||
|
||||
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 = 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(
|
||||
pos2(uv_rect.min[0] as f32, uv_rect.min[1] as f32),
|
||||
pos2(uv_rect.max[0] as f32, uv_rect.max[1] as f32),
|
||||
);
|
||||
|
||||
let format = &job.sections[glyph.section_index as usize].format;
|
||||
|
||||
let color = format.color;
|
||||
|
||||
if format.italics {
|
||||
let idx = mesh.vertices.len() as u32;
|
||||
mesh.add_triangle(idx, idx + 1, idx + 2);
|
||||
mesh.add_triangle(idx + 2, idx + 1, idx + 3);
|
||||
|
||||
let top_offset = rect.height() * 0.25 * Vec2::X;
|
||||
|
||||
mesh.vertices.push(Vertex {
|
||||
pos: rect.left_top() + top_offset,
|
||||
uv: uv.left_top(),
|
||||
color,
|
||||
});
|
||||
mesh.vertices.push(Vertex {
|
||||
pos: rect.right_top() + top_offset,
|
||||
uv: uv.right_top(),
|
||||
color,
|
||||
});
|
||||
mesh.vertices.push(Vertex {
|
||||
pos: rect.left_bottom(),
|
||||
uv: uv.left_bottom(),
|
||||
color,
|
||||
});
|
||||
mesh.vertices.push(Vertex {
|
||||
pos: rect.right_bottom(),
|
||||
uv: uv.right_bottom(),
|
||||
color,
|
||||
});
|
||||
} else {
|
||||
mesh.add_rect_with_uv(rect, uv, color);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Add a horizontal line over a row of glyphs with a stroke and y decided by a callback.
|
||||
fn add_row_hline(
|
||||
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(point_scale, [start, pos2(stop_x, start.y)], stroke, mesh);
|
||||
}
|
||||
};
|
||||
|
||||
let mut line_start = None;
|
||||
let mut last_right_x = f32::NAN;
|
||||
|
||||
for glyph in &row.glyphs {
|
||||
let (stroke, y) = stroke_and_y(glyph);
|
||||
|
||||
if stroke == Stroke::none() {
|
||||
end_line(line_start.take(), last_right_x);
|
||||
} else if let Some((existing_stroke, start)) = line_start {
|
||||
if existing_stroke == stroke && start.y == y {
|
||||
// continue the same line
|
||||
} else {
|
||||
end_line(line_start.take(), last_right_x);
|
||||
line_start = Some((stroke, pos2(glyph.pos.x, y)));
|
||||
}
|
||||
} else {
|
||||
line_start = Some((stroke, pos2(glyph.pos.x, y)));
|
||||
}
|
||||
|
||||
last_right_x = glyph.max_x();
|
||||
}
|
||||
|
||||
end_line(line_start.take(), last_right_x);
|
||||
}
|
||||
|
||||
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(emilk): reuse this to avoid re-allocations.
|
||||
path.add_line_segment([start, stop]);
|
||||
let feathering = 1.0 / point_scale.pixels_per_point();
|
||||
path.stroke_open(feathering, stroke, mesh);
|
||||
} else {
|
||||
// Thin lines often lost, so this is a bad idea
|
||||
|
||||
assert_eq!(start.y, stop.y);
|
||||
|
||||
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(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);
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
/// Keeps track of good places to break a long row of text.
|
||||
/// Will focus primarily on spaces, secondarily on things like `-`
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct RowBreakCandidates {
|
||||
/// Breaking at ` ` or other whitespace
|
||||
/// is always the primary candidate.
|
||||
space: Option<usize>,
|
||||
|
||||
/// Logograms (single character representing a whole word) are good candidates for line break.
|
||||
logogram: Option<usize>,
|
||||
|
||||
/// Kana (Japanese hiragana and katakana) may be line broken unless before a gyōtō kinsoku character.
|
||||
kana: Option<usize>,
|
||||
|
||||
/// Breaking at a dash is a super-
|
||||
/// good idea.
|
||||
dash: Option<usize>,
|
||||
|
||||
/// This is nicer for things like URLs, e.g. www.
|
||||
/// example.com.
|
||||
punctuation: Option<usize>,
|
||||
|
||||
/// Breaking after just random character is some
|
||||
/// times necessary.
|
||||
any: Option<usize>,
|
||||
}
|
||||
|
||||
impl RowBreakCandidates {
|
||||
fn add(&mut self, index: usize, glyphs: &[Glyph]) {
|
||||
let chr = glyphs[0].chr;
|
||||
const NON_BREAKING_SPACE: char = '\u{A0}';
|
||||
if chr.is_whitespace() && chr != NON_BREAKING_SPACE {
|
||||
self.space = Some(index);
|
||||
} else if is_cjk_ideograph(chr) {
|
||||
self.logogram = Some(index);
|
||||
} else if chr == '-' {
|
||||
self.dash = Some(index);
|
||||
} else if chr.is_ascii_punctuation() {
|
||||
self.punctuation = Some(index);
|
||||
} else if is_kana(chr) && (glyphs.len() == 1 || !is_gyoto_kinsoku(glyphs[1].chr)) {
|
||||
self.kana = Some(index);
|
||||
}
|
||||
self.any = Some(index);
|
||||
}
|
||||
|
||||
fn has_word_boundary(&self) -> bool {
|
||||
self.space.is_some() || self.logogram.is_some()
|
||||
}
|
||||
|
||||
fn has_good_candidate(&self, break_anywhere: bool) -> bool {
|
||||
if break_anywhere {
|
||||
self.any.is_some()
|
||||
} else {
|
||||
self.has_word_boundary()
|
||||
}
|
||||
}
|
||||
|
||||
fn get(&self, break_anywhere: bool) -> Option<usize> {
|
||||
if break_anywhere {
|
||||
self.any
|
||||
} else {
|
||||
self.space
|
||||
.or(self.kana)
|
||||
.or(self.logogram)
|
||||
.or(self.dash)
|
||||
.or(self.punctuation)
|
||||
.or(self.any)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn is_cjk_ideograph(c: char) -> bool {
|
||||
('\u{4E00}' <= c && c <= '\u{9FFF}')
|
||||
|| ('\u{3400}' <= c && c <= '\u{4DBF}')
|
||||
|| ('\u{2B740}' <= c && c <= '\u{2B81F}')
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn is_kana(c: char) -> bool {
|
||||
('\u{3040}' <= c && c <= '\u{309F}') // Hiragana block
|
||||
|| ('\u{30A0}' <= c && c <= '\u{30FF}') // Katakana block
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn is_gyoto_kinsoku(c: char) -> bool {
|
||||
// Gyōtō (meaning "beginning of line") kinsoku characters in Japanese typesetting are characters that may not appear at the start of a line, according to kinsoku shori rules.
|
||||
// The list of gyōtō kinsoku characters can be found at https://en.wikipedia.org/wiki/Line_breaking_rules_in_East_Asian_languages#Characters_not_permitted_on_the_start_of_a_line.
|
||||
")]}〕〉》」』】〙〗〟'\"⦆»ヽヾーァィゥェォッャュョヮヵヶぁぃぅぇぉっゃゅょゎゕゖㇰㇱㇲㇳㇴㇵㇶㇷㇸㇹㇺㇻㇼㇽㇾㇿ々〻‐゠–〜?!‼⁇⁈⁉・、:;,。.".contains(c)
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn test_zero_max_width() {
|
||||
let mut fonts = FontsImpl::new(1.0, 1024, super::FontDefinitions::default());
|
||||
let mut layout_job = LayoutJob::single_section("W".into(), super::TextFormat::default());
|
||||
layout_job.wrap.max_width = 0.0;
|
||||
let galley = super::layout(&mut fonts, layout_job.into());
|
||||
assert_eq!(galley.rows.len(), 1);
|
||||
}
|
||||
911
crates/epaint/src/text/text_layout_types.rs
Normal file
911
crates/epaint/src/text/text_layout_types.rs
Normal file
@@ -0,0 +1,911 @@
|
||||
#![allow(clippy::derive_hash_xor_eq)] // We need to impl Hash for f32, but we don't implement Eq, which is fine
|
||||
|
||||
use std::ops::Range;
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::{cursor::*, font::UvRect};
|
||||
use crate::{Color32, FontId, Mesh, Stroke};
|
||||
use emath::*;
|
||||
|
||||
/// Describes the task of laying out text.
|
||||
///
|
||||
/// This supports mixing different fonts, color and formats (underline etc).
|
||||
///
|
||||
/// Pass this to [`crate::Fonts::layout_job`] or [`crate::text::layout`].
|
||||
///
|
||||
/// ## Example:
|
||||
/// ```
|
||||
/// use epaint::{Color32, text::{LayoutJob, TextFormat}, FontFamily, FontId};
|
||||
///
|
||||
/// let mut job = LayoutJob::default();
|
||||
/// job.append(
|
||||
/// "Hello ",
|
||||
/// 0.0,
|
||||
/// TextFormat {
|
||||
/// font_id: FontId::new(14.0, FontFamily::Proportional),
|
||||
/// color: Color32::WHITE,
|
||||
/// ..Default::default()
|
||||
/// },
|
||||
/// );
|
||||
/// job.append(
|
||||
/// "World!",
|
||||
/// 0.0,
|
||||
/// TextFormat {
|
||||
/// font_id: FontId::new(14.0, FontFamily::Monospace),
|
||||
/// color: Color32::BLACK,
|
||||
/// ..Default::default()
|
||||
/// },
|
||||
/// );
|
||||
/// ```
|
||||
///
|
||||
/// As you can see, constructing a [`LayoutJob`] is currently a lot of work.
|
||||
/// It would be nice to have a helper macro for it!
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
|
||||
pub struct LayoutJob {
|
||||
/// The complete text of this job, referenced by [`LayoutSection`].
|
||||
pub text: String,
|
||||
|
||||
/// The different section, which can have different fonts, colors, etc.
|
||||
pub sections: Vec<LayoutSection>,
|
||||
|
||||
pub wrap: TextWrapping,
|
||||
|
||||
/// The first row must be at least this high.
|
||||
/// This is in case we lay out text that is the continuation
|
||||
/// of some earlier text (sharing the same row),
|
||||
/// in which case this will be the height of the earlier text.
|
||||
/// In other cases, set this to `0.0`.
|
||||
pub first_row_min_height: f32,
|
||||
|
||||
/// If `false`, all newlines characters will be ignored
|
||||
/// and show up as the replacement character.
|
||||
/// Default: `true`.
|
||||
pub break_on_newline: bool,
|
||||
|
||||
/// How to horizontally align the text (`Align::LEFT`, `Align::Center`, `Align::RIGHT`).
|
||||
pub halign: Align,
|
||||
|
||||
/// Justify text so that word-wrapped rows fill the whole [`TextWrapping::max_width`]
|
||||
pub justify: bool,
|
||||
}
|
||||
|
||||
impl Default for LayoutJob {
|
||||
#[inline]
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
text: Default::default(),
|
||||
sections: Default::default(),
|
||||
wrap: Default::default(),
|
||||
first_row_min_height: 0.0,
|
||||
break_on_newline: true,
|
||||
halign: Align::LEFT,
|
||||
justify: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl LayoutJob {
|
||||
/// Break on `\n` and at the given wrap width.
|
||||
#[inline]
|
||||
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(font_id, color),
|
||||
}],
|
||||
text,
|
||||
wrap: TextWrapping {
|
||||
max_width: wrap_width,
|
||||
..Default::default()
|
||||
},
|
||||
break_on_newline: true,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Does not break on `\n`, but shows the replacement character instead.
|
||||
#[inline]
|
||||
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(font_id, color),
|
||||
}],
|
||||
text,
|
||||
wrap: Default::default(),
|
||||
break_on_newline: false,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn single_section(text: String, format: TextFormat) -> Self {
|
||||
Self {
|
||||
sections: vec![LayoutSection {
|
||||
leading_space: 0.0,
|
||||
byte_range: 0..text.len(),
|
||||
format,
|
||||
}],
|
||||
text,
|
||||
wrap: Default::default(),
|
||||
break_on_newline: true,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.sections.is_empty()
|
||||
}
|
||||
|
||||
/// Helper for adding a new section when building a [`LayoutJob`].
|
||||
pub fn append(&mut self, text: &str, leading_space: f32, format: TextFormat) {
|
||||
let start = self.text.len();
|
||||
self.text += text;
|
||||
let byte_range = start..self.text.len();
|
||||
self.sections.push(LayoutSection {
|
||||
leading_space,
|
||||
byte_range,
|
||||
format,
|
||||
});
|
||||
}
|
||||
|
||||
/// The height of the tallest used font in the job.
|
||||
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(§ion.format.font_id));
|
||||
}
|
||||
max_height
|
||||
}
|
||||
}
|
||||
|
||||
impl std::hash::Hash for LayoutJob {
|
||||
#[inline]
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
let Self {
|
||||
text,
|
||||
sections,
|
||||
wrap,
|
||||
first_row_min_height,
|
||||
break_on_newline,
|
||||
halign,
|
||||
justify,
|
||||
} = self;
|
||||
|
||||
text.hash(state);
|
||||
sections.hash(state);
|
||||
wrap.hash(state);
|
||||
crate::f32_hash(state, *first_row_min_height);
|
||||
break_on_newline.hash(state);
|
||||
halign.hash(state);
|
||||
justify.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
|
||||
pub struct LayoutSection {
|
||||
/// Can be used for first row indentation.
|
||||
pub leading_space: f32,
|
||||
/// Range into the galley text
|
||||
pub byte_range: Range<usize>,
|
||||
pub format: TextFormat,
|
||||
}
|
||||
|
||||
impl std::hash::Hash for LayoutSection {
|
||||
#[inline]
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
let Self {
|
||||
leading_space,
|
||||
byte_range,
|
||||
format,
|
||||
} = self;
|
||||
crate::f32_hash(state, *leading_space);
|
||||
byte_range.hash(state);
|
||||
format.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
#[derive(Clone, Debug, Hash, PartialEq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
|
||||
pub struct TextFormat {
|
||||
pub font_id: FontId,
|
||||
/// Text color
|
||||
pub color: Color32,
|
||||
pub background: Color32,
|
||||
pub italics: bool,
|
||||
pub underline: Stroke,
|
||||
pub strikethrough: Stroke,
|
||||
/// If you use a small font and [`Align::TOP`] you
|
||||
/// can get the effect of raised text.
|
||||
pub valign: Align,
|
||||
// TODO(emilk): lowered
|
||||
}
|
||||
|
||||
impl Default for TextFormat {
|
||||
#[inline]
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
font_id: FontId::default(),
|
||||
color: Color32::GRAY,
|
||||
background: Color32::TRANSPARENT,
|
||||
italics: false,
|
||||
underline: Stroke::none(),
|
||||
strikethrough: Stroke::none(),
|
||||
valign: Align::BOTTOM,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TextFormat {
|
||||
#[inline]
|
||||
pub fn simple(font_id: FontId, color: Color32) -> Self {
|
||||
Self {
|
||||
font_id,
|
||||
color,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
|
||||
pub struct TextWrapping {
|
||||
/// Try to break text so that no row is wider than this.
|
||||
/// Set to [`f32::INFINITY`] to turn off wrapping.
|
||||
/// Note that `\n` always produces a new line.
|
||||
pub max_width: f32,
|
||||
|
||||
/// Maximum amount of rows the text should have.
|
||||
/// Set to `0` to disable this.
|
||||
pub max_rows: usize,
|
||||
|
||||
/// Don't try to break text at an appropriate place.
|
||||
pub break_anywhere: bool,
|
||||
|
||||
/// Character to use to represent clipped text, `…` for example, which is the default.
|
||||
pub overflow_character: Option<char>,
|
||||
}
|
||||
|
||||
impl std::hash::Hash for TextWrapping {
|
||||
#[inline]
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
let Self {
|
||||
max_width,
|
||||
max_rows,
|
||||
break_anywhere,
|
||||
overflow_character,
|
||||
} = self;
|
||||
crate::f32_hash(state, *max_width);
|
||||
max_rows.hash(state);
|
||||
break_anywhere.hash(state);
|
||||
overflow_character.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for TextWrapping {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
max_width: f32::INFINITY,
|
||||
max_rows: 0,
|
||||
break_anywhere: false,
|
||||
overflow_character: Some('…'),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
/// Text that has been layed out, ready for painting.
|
||||
///
|
||||
/// You can create a [`Galley`] using [`crate::Fonts::layout_job`];
|
||||
///
|
||||
/// This needs to be recreated if `pixels_per_point` (dpi scale) changes.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
|
||||
pub struct Galley {
|
||||
/// The job that this galley is the result of.
|
||||
/// Contains the original string and style sections.
|
||||
pub job: Arc<LayoutJob>,
|
||||
|
||||
/// Rows of text, from top to bottom.
|
||||
/// The number of characters in all rows sum up to `job.text.chars().count()`.
|
||||
/// Note that each paragraph (pieces of text separated with `\n`)
|
||||
/// can be split up into multiple rows.
|
||||
pub rows: Vec<Row>,
|
||||
|
||||
/// Bounding rect.
|
||||
///
|
||||
/// `rect.top()` is always 0.0.
|
||||
///
|
||||
/// With [`LayoutJob::halign`]:
|
||||
/// * [`Align::LEFT`]: rect.left() == 0.0
|
||||
/// * [`Align::Center`]: rect.center() == 0.0
|
||||
/// * [`Align::RIGHT`]: rect.right() == 0.0
|
||||
pub rect: Rect,
|
||||
|
||||
/// Tight bounding box around all the meshes in all the rows.
|
||||
/// Can be used for culling.
|
||||
pub mesh_bounds: Rect,
|
||||
|
||||
/// Total number of vertices in all the row meshes.
|
||||
pub num_vertices: usize,
|
||||
|
||||
/// Total number of indices in all the row meshes.
|
||||
pub num_indices: usize,
|
||||
|
||||
/// The number of physical pixels for each logical point.
|
||||
/// Since this affects the layout, we keep track of it
|
||||
/// so that we can warn if this has changed once we get to
|
||||
/// tessellation.
|
||||
pub pixels_per_point: f32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
|
||||
pub struct Row {
|
||||
/// One for each `char`.
|
||||
pub glyphs: Vec<Glyph>,
|
||||
|
||||
/// Logical bounding rectangle based on font heights etc.
|
||||
/// Use this when drawing a selection or similar!
|
||||
/// Includes leading and trailing whitespace.
|
||||
pub rect: Rect,
|
||||
|
||||
/// The mesh, ready to be rendered.
|
||||
pub visuals: RowVisuals,
|
||||
|
||||
/// If true, this [`Row`] came from a paragraph ending with a `\n`.
|
||||
/// The `\n` itself is omitted from [`Self::glyphs`].
|
||||
/// A `\n` in the input text always creates a new [`Row`] below it,
|
||||
/// so that text that ends with `\n` has an empty [`Row`] last.
|
||||
/// This also implies that the last [`Row`] in a [`Galley`] always has `ends_with_newline == false`.
|
||||
pub ends_with_newline: bool,
|
||||
}
|
||||
|
||||
/// The tessellated output of a row.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
|
||||
pub struct RowVisuals {
|
||||
/// The tessellated text, using non-normalized (texel) UV coordinates.
|
||||
/// That is, you need to divide the uv coordinates by the texture size.
|
||||
pub mesh: Mesh,
|
||||
|
||||
/// Bounds of the mesh, and can be used for culling.
|
||||
/// Does NOT include leading or trailing whitespace glyphs!!
|
||||
pub mesh_bounds: Rect,
|
||||
|
||||
/// The range of vertices in the mesh the contain glyphs.
|
||||
/// Before comes backgrounds (if any), and after any underlines and strikethrough.
|
||||
pub glyph_vertex_range: Range<usize>,
|
||||
}
|
||||
|
||||
impl Default for RowVisuals {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
mesh: Default::default(),
|
||||
mesh_bounds: Rect::NOTHING,
|
||||
glyph_vertex_range: 0..0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, PartialEq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
|
||||
pub struct Glyph {
|
||||
/// The character this glyph represents.
|
||||
pub chr: char,
|
||||
|
||||
/// Relative to the galley position.
|
||||
/// Logical position: pos.y is the same for all chars of the same [`TextFormat`].
|
||||
pub pos: Pos2,
|
||||
|
||||
/// Advance width and font row height.
|
||||
pub size: Vec2,
|
||||
|
||||
/// Position of the glyph in the font texture, in texels.
|
||||
pub uv_rect: UvRect,
|
||||
|
||||
/// Index into [`LayoutJob::sections`]. Decides color etc.
|
||||
pub section_index: u32,
|
||||
}
|
||||
|
||||
impl Glyph {
|
||||
pub fn max_x(&self) -> f32 {
|
||||
self.pos.x + self.size.x
|
||||
}
|
||||
|
||||
/// Same y range for all characters with the same [`TextFormat`].
|
||||
#[inline]
|
||||
pub fn logical_rect(&self) -> Rect {
|
||||
Rect::from_min_size(self.pos, self.size)
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
impl Row {
|
||||
/// Excludes the implicit `\n` after the [`Row`], if any.
|
||||
#[inline]
|
||||
pub fn char_count_excluding_newline(&self) -> usize {
|
||||
self.glyphs.len()
|
||||
}
|
||||
|
||||
/// Includes the implicit `\n` after the [`Row`], if any.
|
||||
#[inline]
|
||||
pub fn char_count_including_newline(&self) -> usize {
|
||||
self.glyphs.len() + (self.ends_with_newline as usize)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn min_y(&self) -> f32 {
|
||||
self.rect.top()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn max_y(&self) -> f32 {
|
||||
self.rect.bottom()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn height(&self) -> f32 {
|
||||
self.rect.height()
|
||||
}
|
||||
|
||||
/// Closest char at the desired x coordinate.
|
||||
/// Returns something in the range `[0, char_count_excluding_newline()]`.
|
||||
pub fn char_at(&self, desired_x: f32) -> usize {
|
||||
for (i, glyph) in self.glyphs.iter().enumerate() {
|
||||
if desired_x < glyph.logical_rect().center().x {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
self.char_count_excluding_newline()
|
||||
}
|
||||
|
||||
pub fn x_offset(&self, column: usize) -> f32 {
|
||||
if let Some(glyph) = self.glyphs.get(column) {
|
||||
glyph.pos.x
|
||||
} else {
|
||||
self.rect.right()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Galley {
|
||||
#[inline(always)]
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.job.is_empty()
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn text(&self) -> &str {
|
||||
&self.job.text
|
||||
}
|
||||
|
||||
pub fn size(&self) -> Vec2 {
|
||||
self.rect.size()
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
/// ## Physical positions
|
||||
impl Galley {
|
||||
/// Zero-width rect past the last character.
|
||||
fn end_pos(&self) -> Rect {
|
||||
if let Some(row) = self.rows.last() {
|
||||
let x = row.rect.right();
|
||||
Rect::from_min_max(pos2(x, row.min_y()), pos2(x, row.max_y()))
|
||||
} else {
|
||||
// Empty galley
|
||||
Rect::from_min_max(pos2(0.0, 0.0), pos2(0.0, 0.0))
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a 0-width Rect.
|
||||
pub fn pos_from_pcursor(&self, pcursor: PCursor) -> Rect {
|
||||
let mut it = PCursor::default();
|
||||
|
||||
for row in &self.rows {
|
||||
if it.paragraph == pcursor.paragraph {
|
||||
// Right paragraph, but is it the right row in the paragraph?
|
||||
|
||||
if it.offset <= pcursor.offset
|
||||
&& (pcursor.offset <= it.offset + row.char_count_excluding_newline()
|
||||
|| row.ends_with_newline)
|
||||
{
|
||||
let column = pcursor.offset - it.offset;
|
||||
|
||||
let select_next_row_instead = pcursor.prefer_next_row
|
||||
&& !row.ends_with_newline
|
||||
&& column >= row.char_count_excluding_newline();
|
||||
if !select_next_row_instead {
|
||||
let x = row.x_offset(column);
|
||||
return Rect::from_min_max(pos2(x, row.min_y()), pos2(x, row.max_y()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if row.ends_with_newline {
|
||||
it.paragraph += 1;
|
||||
it.offset = 0;
|
||||
} else {
|
||||
it.offset += row.char_count_including_newline();
|
||||
}
|
||||
}
|
||||
|
||||
self.end_pos()
|
||||
}
|
||||
|
||||
/// Returns a 0-width Rect.
|
||||
pub fn pos_from_cursor(&self, cursor: &Cursor) -> Rect {
|
||||
self.pos_from_pcursor(cursor.pcursor) // pcursor is what TextEdit stores
|
||||
}
|
||||
|
||||
/// Cursor at the given position within the galley
|
||||
pub fn cursor_from_pos(&self, pos: Vec2) -> Cursor {
|
||||
let mut best_y_dist = f32::INFINITY;
|
||||
let mut cursor = Cursor::default();
|
||||
|
||||
let mut ccursor_index = 0;
|
||||
let mut pcursor_it = PCursor::default();
|
||||
|
||||
for (row_nr, row) in self.rows.iter().enumerate() {
|
||||
let is_pos_within_row = pos.y >= row.min_y() && pos.y <= row.max_y();
|
||||
let y_dist = (row.min_y() - pos.y).abs().min((row.max_y() - pos.y).abs());
|
||||
if is_pos_within_row || y_dist < best_y_dist {
|
||||
best_y_dist = y_dist;
|
||||
let column = row.char_at(pos.x);
|
||||
let prefer_next_row = column < row.char_count_excluding_newline();
|
||||
cursor = Cursor {
|
||||
ccursor: CCursor {
|
||||
index: ccursor_index + column,
|
||||
prefer_next_row,
|
||||
},
|
||||
rcursor: RCursor {
|
||||
row: row_nr,
|
||||
column,
|
||||
},
|
||||
pcursor: PCursor {
|
||||
paragraph: pcursor_it.paragraph,
|
||||
offset: pcursor_it.offset + column,
|
||||
prefer_next_row,
|
||||
},
|
||||
};
|
||||
|
||||
if is_pos_within_row {
|
||||
return cursor;
|
||||
}
|
||||
}
|
||||
ccursor_index += row.char_count_including_newline();
|
||||
if row.ends_with_newline {
|
||||
pcursor_it.paragraph += 1;
|
||||
pcursor_it.offset = 0;
|
||||
} else {
|
||||
pcursor_it.offset += row.char_count_including_newline();
|
||||
}
|
||||
}
|
||||
cursor
|
||||
}
|
||||
}
|
||||
|
||||
/// ## Cursor positions
|
||||
impl Galley {
|
||||
/// Cursor to one-past last character.
|
||||
pub fn end(&self) -> Cursor {
|
||||
if self.rows.is_empty() {
|
||||
return Default::default();
|
||||
}
|
||||
let mut ccursor = CCursor {
|
||||
index: 0,
|
||||
prefer_next_row: true,
|
||||
};
|
||||
let mut pcursor = PCursor {
|
||||
paragraph: 0,
|
||||
offset: 0,
|
||||
prefer_next_row: true,
|
||||
};
|
||||
for row in &self.rows {
|
||||
let row_char_count = row.char_count_including_newline();
|
||||
ccursor.index += row_char_count;
|
||||
if row.ends_with_newline {
|
||||
pcursor.paragraph += 1;
|
||||
pcursor.offset = 0;
|
||||
} else {
|
||||
pcursor.offset += row_char_count;
|
||||
}
|
||||
}
|
||||
Cursor {
|
||||
ccursor,
|
||||
rcursor: self.end_rcursor(),
|
||||
pcursor,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn end_rcursor(&self) -> RCursor {
|
||||
if let Some(last_row) = self.rows.last() {
|
||||
crate::epaint_assert!(!last_row.ends_with_newline);
|
||||
RCursor {
|
||||
row: self.rows.len() - 1,
|
||||
column: last_row.char_count_excluding_newline(),
|
||||
}
|
||||
} else {
|
||||
Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// ## Cursor conversions
|
||||
impl Galley {
|
||||
// The returned cursor is clamped.
|
||||
pub fn from_ccursor(&self, ccursor: CCursor) -> Cursor {
|
||||
let prefer_next_row = ccursor.prefer_next_row;
|
||||
let mut ccursor_it = CCursor {
|
||||
index: 0,
|
||||
prefer_next_row,
|
||||
};
|
||||
let mut pcursor_it = PCursor {
|
||||
paragraph: 0,
|
||||
offset: 0,
|
||||
prefer_next_row,
|
||||
};
|
||||
|
||||
for (row_nr, row) in self.rows.iter().enumerate() {
|
||||
let row_char_count = row.char_count_excluding_newline();
|
||||
|
||||
if ccursor_it.index <= ccursor.index
|
||||
&& ccursor.index <= ccursor_it.index + row_char_count
|
||||
{
|
||||
let column = ccursor.index - ccursor_it.index;
|
||||
|
||||
let select_next_row_instead = prefer_next_row
|
||||
&& !row.ends_with_newline
|
||||
&& column >= row.char_count_excluding_newline();
|
||||
if !select_next_row_instead {
|
||||
pcursor_it.offset += column;
|
||||
return Cursor {
|
||||
ccursor,
|
||||
rcursor: RCursor {
|
||||
row: row_nr,
|
||||
column,
|
||||
},
|
||||
pcursor: pcursor_it,
|
||||
};
|
||||
}
|
||||
}
|
||||
ccursor_it.index += row.char_count_including_newline();
|
||||
if row.ends_with_newline {
|
||||
pcursor_it.paragraph += 1;
|
||||
pcursor_it.offset = 0;
|
||||
} else {
|
||||
pcursor_it.offset += row.char_count_including_newline();
|
||||
}
|
||||
}
|
||||
crate::epaint_assert!(ccursor_it == self.end().ccursor);
|
||||
Cursor {
|
||||
ccursor: ccursor_it, // clamp
|
||||
rcursor: self.end_rcursor(),
|
||||
pcursor: pcursor_it,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_rcursor(&self, rcursor: RCursor) -> Cursor {
|
||||
if rcursor.row >= self.rows.len() {
|
||||
return self.end();
|
||||
}
|
||||
|
||||
let prefer_next_row =
|
||||
rcursor.column < self.rows[rcursor.row].char_count_excluding_newline();
|
||||
let mut ccursor_it = CCursor {
|
||||
index: 0,
|
||||
prefer_next_row,
|
||||
};
|
||||
let mut pcursor_it = PCursor {
|
||||
paragraph: 0,
|
||||
offset: 0,
|
||||
prefer_next_row,
|
||||
};
|
||||
|
||||
for (row_nr, row) in self.rows.iter().enumerate() {
|
||||
if row_nr == rcursor.row {
|
||||
ccursor_it.index += rcursor.column.at_most(row.char_count_excluding_newline());
|
||||
|
||||
if row.ends_with_newline {
|
||||
// Allow offset to go beyond the end of the paragraph
|
||||
pcursor_it.offset += rcursor.column;
|
||||
} else {
|
||||
pcursor_it.offset += rcursor.column.at_most(row.char_count_excluding_newline());
|
||||
}
|
||||
return Cursor {
|
||||
ccursor: ccursor_it,
|
||||
rcursor,
|
||||
pcursor: pcursor_it,
|
||||
};
|
||||
}
|
||||
ccursor_it.index += row.char_count_including_newline();
|
||||
if row.ends_with_newline {
|
||||
pcursor_it.paragraph += 1;
|
||||
pcursor_it.offset = 0;
|
||||
} else {
|
||||
pcursor_it.offset += row.char_count_including_newline();
|
||||
}
|
||||
}
|
||||
Cursor {
|
||||
ccursor: ccursor_it,
|
||||
rcursor: self.end_rcursor(),
|
||||
pcursor: pcursor_it,
|
||||
}
|
||||
}
|
||||
|
||||
// TODO(emilk): return identical cursor, or clamp?
|
||||
pub fn from_pcursor(&self, pcursor: PCursor) -> Cursor {
|
||||
let prefer_next_row = pcursor.prefer_next_row;
|
||||
let mut ccursor_it = CCursor {
|
||||
index: 0,
|
||||
prefer_next_row,
|
||||
};
|
||||
let mut pcursor_it = PCursor {
|
||||
paragraph: 0,
|
||||
offset: 0,
|
||||
prefer_next_row,
|
||||
};
|
||||
|
||||
for (row_nr, row) in self.rows.iter().enumerate() {
|
||||
if pcursor_it.paragraph == pcursor.paragraph {
|
||||
// Right paragraph, but is it the right row in the paragraph?
|
||||
|
||||
if pcursor_it.offset <= pcursor.offset
|
||||
&& (pcursor.offset <= pcursor_it.offset + row.char_count_excluding_newline()
|
||||
|| row.ends_with_newline)
|
||||
{
|
||||
let column = pcursor.offset - pcursor_it.offset;
|
||||
|
||||
let select_next_row_instead = pcursor.prefer_next_row
|
||||
&& !row.ends_with_newline
|
||||
&& column >= row.char_count_excluding_newline();
|
||||
|
||||
if !select_next_row_instead {
|
||||
ccursor_it.index += column.at_most(row.char_count_excluding_newline());
|
||||
|
||||
return Cursor {
|
||||
ccursor: ccursor_it,
|
||||
rcursor: RCursor {
|
||||
row: row_nr,
|
||||
column,
|
||||
},
|
||||
pcursor,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ccursor_it.index += row.char_count_including_newline();
|
||||
if row.ends_with_newline {
|
||||
pcursor_it.paragraph += 1;
|
||||
pcursor_it.offset = 0;
|
||||
} else {
|
||||
pcursor_it.offset += row.char_count_including_newline();
|
||||
}
|
||||
}
|
||||
Cursor {
|
||||
ccursor: ccursor_it,
|
||||
rcursor: self.end_rcursor(),
|
||||
pcursor,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// ## Cursor positions
|
||||
impl Galley {
|
||||
pub fn cursor_left_one_character(&self, cursor: &Cursor) -> Cursor {
|
||||
if cursor.ccursor.index == 0 {
|
||||
Default::default()
|
||||
} else {
|
||||
let ccursor = CCursor {
|
||||
index: cursor.ccursor.index,
|
||||
prefer_next_row: true, // default to this when navigating. It is more often useful to put cursor at the begging of a row than at the end.
|
||||
};
|
||||
self.from_ccursor(ccursor - 1)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn cursor_right_one_character(&self, cursor: &Cursor) -> Cursor {
|
||||
let ccursor = CCursor {
|
||||
index: cursor.ccursor.index,
|
||||
prefer_next_row: true, // default to this when navigating. It is more often useful to put cursor at the begging of a row than at the end.
|
||||
};
|
||||
self.from_ccursor(ccursor + 1)
|
||||
}
|
||||
|
||||
pub fn cursor_up_one_row(&self, cursor: &Cursor) -> Cursor {
|
||||
if cursor.rcursor.row == 0 {
|
||||
Cursor::default()
|
||||
} else {
|
||||
let new_row = cursor.rcursor.row - 1;
|
||||
|
||||
let cursor_is_beyond_end_of_current_row = cursor.rcursor.column
|
||||
>= self.rows[cursor.rcursor.row].char_count_excluding_newline();
|
||||
|
||||
let new_rcursor = if cursor_is_beyond_end_of_current_row {
|
||||
// keep same column
|
||||
RCursor {
|
||||
row: new_row,
|
||||
column: cursor.rcursor.column,
|
||||
}
|
||||
} else {
|
||||
// keep same X coord
|
||||
let x = self.pos_from_cursor(cursor).center().x;
|
||||
let column = if x > self.rows[new_row].rect.right() {
|
||||
// beyond the end of this row - keep same colum
|
||||
cursor.rcursor.column
|
||||
} else {
|
||||
self.rows[new_row].char_at(x)
|
||||
};
|
||||
RCursor {
|
||||
row: new_row,
|
||||
column,
|
||||
}
|
||||
};
|
||||
self.from_rcursor(new_rcursor)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn cursor_down_one_row(&self, cursor: &Cursor) -> Cursor {
|
||||
if cursor.rcursor.row + 1 < self.rows.len() {
|
||||
let new_row = cursor.rcursor.row + 1;
|
||||
|
||||
let cursor_is_beyond_end_of_current_row = cursor.rcursor.column
|
||||
>= self.rows[cursor.rcursor.row].char_count_excluding_newline();
|
||||
|
||||
let new_rcursor = if cursor_is_beyond_end_of_current_row {
|
||||
// keep same column
|
||||
RCursor {
|
||||
row: new_row,
|
||||
column: cursor.rcursor.column,
|
||||
}
|
||||
} else {
|
||||
// keep same X coord
|
||||
let x = self.pos_from_cursor(cursor).center().x;
|
||||
let column = if x > self.rows[new_row].rect.right() {
|
||||
// beyond the end of the next row - keep same column
|
||||
cursor.rcursor.column
|
||||
} else {
|
||||
self.rows[new_row].char_at(x)
|
||||
};
|
||||
RCursor {
|
||||
row: new_row,
|
||||
column,
|
||||
}
|
||||
};
|
||||
|
||||
self.from_rcursor(new_rcursor)
|
||||
} else {
|
||||
self.end()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn cursor_begin_of_row(&self, cursor: &Cursor) -> Cursor {
|
||||
self.from_rcursor(RCursor {
|
||||
row: cursor.rcursor.row,
|
||||
column: 0,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn cursor_end_of_row(&self, cursor: &Cursor) -> Cursor {
|
||||
self.from_rcursor(RCursor {
|
||||
row: cursor.rcursor.row,
|
||||
column: self.rows[cursor.rcursor.row].char_count_excluding_newline(),
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user