1
0
mirror of https://github.com/emilk/egui.git synced 2026-08-29 21:00:03 -04:00

Break out mod paint into new crate epaint

This commit is contained in:
Emil Ernerfeldt
2021-01-10 15:42:46 +01:00
parent c0041d032a
commit 26d576f510
42 changed files with 343 additions and 248 deletions

108
epaint/src/text/cursor.rs Normal file
View File

@@ -0,0 +1,108 @@
//! Different types of text cursors, i.e. ways to point into a [`super::Galley`].
/// Character cursor
#[derive(Clone, Copy, Debug, Default)]
#[cfg_attr(feature = "persistence", 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,
}
}
}
/// Row Cursor
#[derive(Clone, Copy, Debug, Default, PartialEq)]
#[cfg_attr(feature = "persistence", 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 = "persistence", 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 = "persistence", derive(serde::Deserialize, serde::Serialize))]
pub struct Cursor {
pub ccursor: CCursor,
pub rcursor: RCursor,
pub pcursor: PCursor,
}

517
epaint/src/text/font.rs Normal file
View File

@@ -0,0 +1,517 @@
use std::sync::Arc;
use {
ahash::AHashMap,
rusttype::{point, Scale},
};
use crate::{
mutex::{Mutex, RwLock},
text::galley::{Galley, Row},
TextureAtlas,
};
use emath::{vec2, Vec2};
// ----------------------------------------------------------------------------
#[derive(Clone, Copy, Debug)]
pub struct UvRect {
/// X/Y offset for nice rendering (unit: points).
pub offset: Vec2,
pub size: Vec2,
/// Top left corner UV in texture.
pub min: (u16, u16),
/// Bottom right corner (exclusive).
pub max: (u16, u16),
}
#[derive(Clone, Copy, Debug)]
pub struct GlyphInfo {
id: rusttype::GlyphId,
/// Unit: points.
pub advance_width: f32,
/// Texture coordinates. None for space.
pub uv_rect: Option<UvRect>,
}
impl Default for GlyphInfo {
fn default() -> Self {
Self {
id: rusttype::GlyphId(0),
advance_width: 0.0,
uv_rect: None,
}
}
}
// ----------------------------------------------------------------------------
/// A specific font with a size.
/// The interface uses points as the unit for everything.
pub struct FontImpl {
rusttype_font: Arc<rusttype::Font<'static>>,
/// Maximum character height
scale_in_pixels: f32,
height_in_points: f32,
// move each character by this much (hack)
y_offset: f32,
pixels_per_point: f32,
glyph_info_cache: RwLock<AHashMap<char, GlyphInfo>>, // TODO: standard Mutex
atlas: Arc<Mutex<TextureAtlas>>,
}
impl FontImpl {
pub fn new(
atlas: Arc<Mutex<TextureAtlas>>,
pixels_per_point: f32,
rusttype_font: Arc<rusttype::Font<'static>>,
scale_in_points: f32,
y_offset: f32,
) -> FontImpl {
assert!(scale_in_points > 0.0);
assert!(pixels_per_point > 0.0);
let scale_in_pixels = pixels_per_point * scale_in_points;
let height_in_points = scale_in_points;
// TODO: use v_metrics for line spacing ?
// let v = rusttype_font.v_metrics(Scale::uniform(scale_in_pixels));
// let height_in_pixels = v.ascent - v.descent + v.line_gap;
// let height_in_points = height_in_pixels / pixels_per_point;
Self {
rusttype_font,
scale_in_pixels,
height_in_points,
y_offset,
pixels_per_point,
glyph_info_cache: Default::default(),
atlas,
}
}
/// `\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);
}
}
// Add new character:
let glyph = self.rusttype_font.glyph(c);
if glyph.id().0 == 0 {
None
} else {
let glyph_info = allocate_glyph(
&mut self.atlas.lock(),
glyph,
self.scale_in_pixels,
self.y_offset,
self.pixels_per_point,
);
self.glyph_info_cache.write().insert(c, glyph_info);
Some(glyph_info)
}
}
pub fn pair_kerning(
&self,
last_glyph_id: rusttype::GlyphId,
glyph_id: rusttype::GlyphId,
) -> f32 {
let scale_in_pixels = Scale::uniform(self.scale_in_pixels);
self.rusttype_font
.pair_kerning(scale_in_pixels, last_glyph_id, glyph_id)
/ self.pixels_per_point
}
/// Height of one row of text. In points
pub fn row_height(&self) -> f32 {
self.height_in_points
}
pub fn pixels_per_point(&self) -> f32 {
self.pixels_per_point
}
}
type FontIndex = usize;
// TODO: rename?
/// Wrapper over multiple `FontImpl` (e.g. a primary + fallbacks for emojis)
#[derive(Default)]
pub struct Font {
fonts: Vec<Arc<FontImpl>>,
replacement_glyph: (FontIndex, GlyphInfo),
pixels_per_point: f32,
row_height: f32,
glyph_info_cache: RwLock<AHashMap<char, (FontIndex, GlyphInfo)>>,
}
impl Font {
pub fn new(fonts: Vec<Arc<FontImpl>>) -> Self {
if fonts.is_empty() {
return Default::default();
}
let pixels_per_point = fonts[0].pixels_per_point();
let row_height = fonts[0].row_height();
let mut slf = Self {
fonts,
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;
// 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) {
slf.glyph_info(c);
}
slf.glyph_info('°');
slf
}
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
pub fn row_height(&self) -> f32 {
self.row_height
}
pub fn uv_rect(&self, c: char) -> Option<UvRect> {
self.glyph_info_cache
.read()
.get(&c)
.and_then(|gi| gi.1.uv_rect)
}
pub fn glyph_width(&self, c: char) -> f32 {
self.glyph_info(c).1.advance_width
}
/// `\n` will (intentionally) show up as the replacement character.
fn glyph_info(&self, c: char) -> (FontIndex, GlyphInfo) {
{
if let Some(glyph_info) = self.glyph_info_cache.read().get(&c) {
return *glyph_info;
}
}
let font_index_glyph_info = self.glyph_info_no_cache_or_fallback(c);
let font_index_glyph_info = font_index_glyph_info.unwrap_or(self.replacement_glyph);
self.glyph_info_cache
.write()
.insert(c, font_index_glyph_info);
font_index_glyph_info
}
fn glyph_info_no_cache_or_fallback(&self, c: char) -> Option<(FontIndex, GlyphInfo)> {
for (font_index, font_impl) in self.fonts.iter().enumerate() {
if let Some(glyph_info) = font_impl.glyph_info(c) {
self.glyph_info_cache
.write()
.insert(c, (font_index, glyph_info));
return Some((font_index, glyph_info));
}
}
None
}
/// Typeset the given text onto one row.
/// Assumes there are no `\n` in the text.
/// Return `x_offsets`, one longer than the number of characters in the text.
fn layout_single_row_fragment(&self, text: &str) -> Vec<f32> {
let mut x_offsets = Vec::with_capacity(text.chars().count() + 1);
x_offsets.push(0.0);
let mut cursor_x_in_points = 0.0f32;
let mut last_glyph_id = None;
for c in text.chars() {
if !self.fonts.is_empty() {
let (font_index, glyph_info) = self.glyph_info(c);
let font_impl = &self.fonts[font_index];
if let Some(last_glyph_id) = last_glyph_id {
cursor_x_in_points += font_impl.pair_kerning(last_glyph_id, glyph_info.id)
}
cursor_x_in_points += glyph_info.advance_width;
cursor_x_in_points = self.round_to_pixel(cursor_x_in_points);
last_glyph_id = Some(glyph_info.id);
}
x_offsets.push(cursor_x_in_points);
}
x_offsets
}
/// Typeset the given text onto one row.
/// Any `\n` will show up as the replacement character.
/// Always returns exactly one `Row` in the `Galley`.
pub fn layout_single_line(&self, text: String) -> Galley {
let x_offsets = self.layout_single_row_fragment(&text);
let row = Row {
x_offsets,
y_min: 0.0,
y_max: self.row_height(),
ends_with_newline: false,
};
let width = row.max_x();
let size = vec2(width, self.row_height());
let galley = Galley {
text,
rows: vec![row],
size,
};
galley.sanity_check();
galley
}
/// Always returns at least one row.
pub fn layout_multiline(&self, text: String, max_width_in_points: f32) -> Galley {
self.layout_multiline_with_indentation_and_max_width(text, 0.0, max_width_in_points)
}
/// * `first_row_indentation`: extra space before the very first character (in points).
/// * `max_width_in_points`: wrapping width.
/// Always returns at least one row.
pub fn layout_multiline_with_indentation_and_max_width(
&self,
text: String,
first_row_indentation: f32,
max_width_in_points: f32,
) -> Galley {
let row_height = self.row_height();
let mut cursor_y = 0.0;
let mut rows = Vec::new();
let mut paragraph_start = 0;
while paragraph_start < text.len() {
let next_newline = text[paragraph_start..].find('\n');
let paragraph_end = next_newline
.map(|newline| paragraph_start + newline)
.unwrap_or_else(|| text.len());
assert!(paragraph_start <= paragraph_end);
let paragraph_text = &text[paragraph_start..paragraph_end];
let line_indentation = if rows.is_empty() {
first_row_indentation
} else {
0.0
};
let mut paragraph_rows = self.layout_paragraph_max_width(
paragraph_text,
line_indentation,
max_width_in_points,
);
assert!(!paragraph_rows.is_empty());
paragraph_rows.last_mut().unwrap().ends_with_newline = next_newline.is_some();
for row in &mut paragraph_rows {
row.y_min += cursor_y;
row.y_max += cursor_y;
}
cursor_y = paragraph_rows.last().unwrap().y_max;
cursor_y += row_height * 0.4; // Extra spacing between paragraphs. TODO: less hacky
rows.append(&mut paragraph_rows);
paragraph_start = paragraph_end + 1;
}
if text.is_empty() || text.ends_with('\n') {
rows.push(Row {
x_offsets: vec![0.0],
y_min: cursor_y,
y_max: cursor_y + row_height,
ends_with_newline: false,
});
}
let mut widest_row = 0.0;
for row in &rows {
widest_row = row.max_x().max(widest_row);
}
let size = vec2(widest_row, rows.last().unwrap().y_max);
let galley = Galley { text, rows, size };
galley.sanity_check();
galley
}
/// A paragraph is text with no line break character in it.
/// The text will be wrapped by the given `max_width_in_points`.
/// Always returns at least one row.
fn layout_paragraph_max_width(
&self,
text: &str,
mut first_row_indentation: f32,
max_width_in_points: f32,
) -> Vec<Row> {
if text.is_empty() {
return vec![Row {
x_offsets: vec![first_row_indentation],
y_min: 0.0,
y_max: self.row_height(),
ends_with_newline: false,
}];
}
let full_x_offsets = self.layout_single_row_fragment(text);
let mut row_start_x = 0.0; // NOTE: BEFORE the `first_row_indentation`.
let mut cursor_y = 0.0;
let mut row_start_idx = 0;
// start index of the last space. A candidate for a new row.
let mut last_space = None;
let mut out_rows = vec![];
for (i, (x, chr)) in full_x_offsets.iter().skip(1).zip(text.chars()).enumerate() {
debug_assert!(chr != '\n');
let potential_row_width = first_row_indentation + x - row_start_x;
if potential_row_width > max_width_in_points {
if let Some(last_space_idx) = last_space {
// We include the trailing space in the row:
let row = Row {
x_offsets: full_x_offsets[row_start_idx..=last_space_idx + 1]
.iter()
.map(|x| first_row_indentation + x - row_start_x)
.collect(),
y_min: cursor_y,
y_max: cursor_y + self.row_height(),
ends_with_newline: false,
};
row.sanity_check();
out_rows.push(row);
row_start_idx = last_space_idx + 1;
row_start_x = first_row_indentation + full_x_offsets[row_start_idx];
last_space = None;
cursor_y = self.round_to_pixel(cursor_y + self.row_height());
} else if out_rows.is_empty() && first_row_indentation > 0.0 {
assert_eq!(row_start_idx, 0);
// Allow the first row to be completely empty, because we know there will be more space on the next row:
let row = Row {
x_offsets: vec![first_row_indentation],
y_min: cursor_y,
y_max: cursor_y + self.row_height(),
ends_with_newline: false,
};
row.sanity_check();
out_rows.push(row);
cursor_y = self.round_to_pixel(cursor_y + self.row_height());
first_row_indentation = 0.0; // Continue all other rows as if there is no indentation
}
}
const NON_BREAKING_SPACE: char = '\u{A0}';
if chr.is_whitespace() && chr != NON_BREAKING_SPACE {
last_space = Some(i);
}
}
if row_start_idx + 1 < full_x_offsets.len() {
let row = Row {
x_offsets: full_x_offsets[row_start_idx..]
.iter()
.map(|x| first_row_indentation + x - row_start_x)
.collect(),
y_min: cursor_y,
y_max: cursor_y + self.row_height(),
ends_with_newline: false,
};
row.sanity_check();
out_rows.push(row);
}
out_rows
}
}
fn allocate_glyph(
atlas: &mut TextureAtlas,
glyph: rusttype::Glyph<'static>,
scale_in_pixels: f32,
y_offset: f32,
pixels_per_point: f32,
) -> GlyphInfo {
assert!(glyph.id().0 != 0);
let glyph = glyph.scaled(Scale::uniform(scale_in_pixels));
let glyph = glyph.positioned(point(0.0, 0.0));
let uv_rect = if let Some(bb) = glyph.pixel_bounding_box() {
let glyph_width = bb.width() as usize;
let glyph_height = bb.height() as usize;
if glyph_width == 0 || glyph_height == 0 {
None
} else {
let glyph_pos = atlas.allocate((glyph_width, glyph_height));
let texture = atlas.texture_mut();
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;
texture[(px, py)] = (v * 255.0).round() as u8;
}
});
let offset_in_pixels = vec2(bb.min.x as f32, scale_in_pixels as f32 + bb.min.y as f32);
let offset = offset_in_pixels / pixels_per_point + y_offset * Vec2::Y;
Some(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,
),
})
}
} else {
// No bounding box. Maybe a space?
None
};
let advance_width_in_points = glyph.unpositioned().h_metrics().advance_width / pixels_per_point;
GlyphInfo {
id: glyph.id(),
advance_width: advance_width_in_points,
uv_rect,
}
}

347
epaint/src/text/fonts.rs Normal file
View File

@@ -0,0 +1,347 @@
use std::{
collections::BTreeMap,
hash::{Hash, Hasher},
sync::Arc,
};
use crate::{
mutex::Mutex,
text::font::{Font, FontImpl},
Texture, TextureAtlas,
};
// TODO: rename
/// One of a few categories of styles of text, e.g. body, button or heading.
#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[cfg_attr(feature = "persistence", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "persistence", serde(rename_all = "snake_case"))]
pub enum TextStyle {
/// Used when small text is needed.
Small,
/// Normal labels. Easily readable, doesn't take up too much space.
Body,
/// Buttons. Maybe slightly bigger than `Body`.
Button,
/// Heading. Probably larger than `Body`.
Heading,
/// Same size as `Body`, but used when monospace is important (for aligning number, code snippets, etc).
Monospace,
}
impl TextStyle {
pub fn all() -> impl Iterator<Item = TextStyle> {
[
TextStyle::Small,
TextStyle::Body,
TextStyle::Button,
TextStyle::Heading,
TextStyle::Monospace,
]
.iter()
.copied()
}
}
/// Which style of font: [`Monospace`][`FontFamily::Monospace`] or [`Proportional`][`FontFamily::Proportional`].
#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[cfg_attr(feature = "persistence", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "persistence", serde(rename_all = "snake_case"))]
pub enum FontFamily {
/// A font where each character is the same width (`w` is the same width as `i`).
Monospace,
/// A font where some characters are wider than other (e.g. 'w' is wider than 'i').
Proportional,
}
/// The data of a `.ttf` or `.otf` file.
pub type FontData = std::borrow::Cow<'static, [u8]>;
fn rusttype_font_from_font_data(name: &str, data: &FontData) -> rusttype::Font<'static> {
match data {
std::borrow::Cow::Borrowed(bytes) => rusttype::Font::try_from_bytes(bytes),
std::borrow::Cow::Owned(bytes) => rusttype::Font::try_from_vec(bytes.clone()),
}
.unwrap_or_else(|| panic!("Error parsing {:?} TTF/OTF font file", name))
}
/// Describes the font data and the sizes to use.
///
/// This is how you can tell Egui which fonts and font sizes to use.
///
/// Often you would start with [`FontDefinitions::default()`] and then add/change the contents.
///
/// ``` ignore
/// # let mut ctx = egui::CtxRef::default();
/// let mut fonts = egui::FontDefinitions::default();
/// // Large button text:
/// fonts.family_and_size.insert(
/// egui::TextStyle::Button,
/// (egui::FontFamily::Proportional, 32.0));
/// ctx.set_fonts(fonts);
/// ```
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "persistence", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "persistence", serde(default))]
pub struct FontDefinitions {
/// List of font names and their definitions.
/// The definition must be the contents of either a `.ttf` or `.otf` font file.
///
/// Egui has built-in-default for these,
/// but you can override them if you like.
#[cfg_attr(feature = "persistence", serde(skip))]
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 Egui will start with
/// the first font and then move to the second, and so on.
/// So the first font is the primary, and then comes a list of fallbacks in order of priority.
pub fonts_for_family: BTreeMap<FontFamily, Vec<String>>,
/// The [`FontFamily`] and size you want to use for a specific [`TextStyle`].
pub family_and_size: BTreeMap<TextStyle, (FontFamily, f32)>,
}
impl Default for FontDefinitions {
fn default() -> Self {
#[allow(unused)]
let mut font_data: BTreeMap<String, FontData> = BTreeMap::new();
let mut fonts_for_family = BTreeMap::new();
#[cfg(feature = "default_fonts")]
{
// TODO: figure out a way to make the WASM smaller despite including fonts. Zip them?
// Use size 13 for this. NOTHING ELSE:
font_data.insert(
"ProggyClean".to_owned(),
std::borrow::Cow::Borrowed(include_bytes!("../../fonts/ProggyClean.ttf")),
);
font_data.insert(
"Ubuntu-Light".to_owned(),
std::borrow::Cow::Borrowed(include_bytes!("../../fonts/Ubuntu-Light.ttf")),
);
// Some good looking emojis. Use as first priority:
font_data.insert(
"NotoEmoji-Regular".to_owned(),
std::borrow::Cow::Borrowed(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(),
std::borrow::Cow::Borrowed(include_bytes!("../../fonts/emoji-icon-font.ttf")),
);
fonts_for_family.insert(
FontFamily::Monospace,
vec![
"ProggyClean".to_owned(),
"Ubuntu-Light".to_owned(), // fallback for √ etc
"NotoEmoji-Regular".to_owned(),
"emoji-icon-font".to_owned(),
],
);
fonts_for_family.insert(
FontFamily::Proportional,
vec![
"Ubuntu-Light".to_owned(),
"NotoEmoji-Regular".to_owned(),
"emoji-icon-font".to_owned(),
],
);
}
#[cfg(not(feature = "default_fonts"))]
{
fonts_for_family.insert(FontFamily::Monospace, vec![]);
fonts_for_family.insert(FontFamily::Proportional, vec![]);
}
let mut family_and_size = BTreeMap::new();
family_and_size.insert(TextStyle::Small, (FontFamily::Proportional, 10.0));
family_and_size.insert(TextStyle::Body, (FontFamily::Proportional, 14.0));
family_and_size.insert(TextStyle::Button, (FontFamily::Proportional, 16.0));
family_and_size.insert(TextStyle::Heading, (FontFamily::Proportional, 20.0));
family_and_size.insert(TextStyle::Monospace, (FontFamily::Monospace, 13.0)); // 13 for `ProggyClean`
Self {
font_data,
fonts_for_family,
family_and_size,
}
}
}
/// The collection of fonts used by Egui.
///
/// Note: `Fonts::default()` is invalid (missing `pixels_per_point`).
#[derive(Default)]
pub struct Fonts {
pixels_per_point: f32,
definitions: FontDefinitions,
fonts: BTreeMap<TextStyle, Font>,
atlas: Arc<Mutex<TextureAtlas>>,
/// Copy of the texture in the texture atlas.
/// This is so we can return a reference to it (the texture atlas is behind a lock).
buffered_texture: Mutex<Arc<Texture>>,
}
impl Fonts {
pub fn from_definitions(pixels_per_point: f32, definitions: FontDefinitions) -> Self {
// We want an atlas big enough to be able to include all the Emojis in the `TextStyle::Heading`,
// so we can show the Emoji picker demo window.
let mut atlas = TextureAtlas::new(2048, 64);
{
// Make the top left pixel fully white:
let pos = atlas.allocate((1, 1));
assert_eq!(pos, (0, 0));
atlas.texture_mut()[pos] = 255;
}
let atlas = Arc::new(Mutex::new(atlas));
let mut font_impl_cache = FontImplCache::new(atlas.clone(), pixels_per_point, &definitions);
let fonts = definitions
.family_and_size
.iter()
.map(|(&text_style, &(family, scale_in_points))| {
let fonts = &definitions.fonts_for_family.get(&family);
let fonts = fonts.unwrap_or_else(|| {
panic!("FontFamily::{:?} is not bound to any fonts", family)
});
let fonts: Vec<Arc<FontImpl>> = fonts
.iter()
.map(|font_name| font_impl_cache.font_impl(font_name, scale_in_points))
.collect();
(text_style, Font::new(fonts))
})
.collect();
{
let mut atlas = atlas.lock();
let texture = atlas.texture_mut();
// Make sure we seed the texture version with something unique based on the default characters:
use std::collections::hash_map::DefaultHasher;
let mut hasher = DefaultHasher::default();
texture.pixels.hash(&mut hasher);
texture.version = hasher.finish();
}
Self {
pixels_per_point,
definitions,
fonts,
atlas,
buffered_texture: Default::default(), //atlas.lock().texture().clone();
}
}
pub fn pixels_per_point(&self) -> f32 {
self.pixels_per_point
}
pub fn definitions(&self) -> &FontDefinitions {
&self.definitions
}
/// Call each frame to get the latest available font texture data.
pub fn texture(&self) -> Arc<Texture> {
let atlas = self.atlas.lock();
let mut buffered_texture = self.buffered_texture.lock();
if buffered_texture.version != atlas.texture().version {
*buffered_texture = Arc::new(atlas.texture().clone());
}
buffered_texture.clone()
}
}
impl std::ops::Index<TextStyle> for Fonts {
type Output = Font;
fn index(&self, text_style: TextStyle) -> &Font {
&self.fonts[&text_style]
}
}
// ----------------------------------------------------------------------------
struct FontImplCache {
atlas: Arc<Mutex<TextureAtlas>>,
pixels_per_point: f32,
rusttype_fonts: std::collections::BTreeMap<String, Arc<rusttype::Font<'static>>>,
/// Map font names and size to the cached `FontImpl`.
/// Can't have f32 in a HashMap or BTreeMap, so let's do a linear search
cache: Vec<(String, f32, Arc<FontImpl>)>,
}
impl FontImplCache {
pub fn new(
atlas: Arc<Mutex<TextureAtlas>>,
pixels_per_point: f32,
definitions: &super::FontDefinitions,
) -> Self {
let rusttype_fonts = definitions
.font_data
.iter()
.map(|(name, font_data)| {
(
name.clone(),
Arc::new(rusttype_font_from_font_data(name, font_data)),
)
})
.collect();
Self {
atlas,
pixels_per_point,
rusttype_fonts,
cache: Default::default(),
}
}
pub fn rusttype_font(&self, font_name: &str) -> Arc<rusttype::Font<'static>> {
self.rusttype_fonts
.get(font_name)
.unwrap_or_else(|| panic!("No font data found for {:?}", font_name))
.clone()
}
pub fn font_impl(&mut self, font_name: &str, scale_in_points: f32) -> Arc<FontImpl> {
for entry in &self.cache {
if (entry.0.as_str(), entry.1) == (font_name, scale_in_points) {
return entry.2.clone();
}
}
let y_offset = if font_name == "emoji-icon-font" {
1.0 // TODO: remove font alignment hack
} else {
-3.0 // TODO: remove font alignment hack
};
let scale_in_points = if font_name == "emoji-icon-font" {
scale_in_points - 2.0 // TODO: remove HACK!
} else {
scale_in_points
};
let font_impl = Arc::new(FontImpl::new(
self.atlas.clone(),
self.pixels_per_point,
self.rusttype_font(font_name),
scale_in_points,
y_offset,
));
self.cache
.push((font_name.to_owned(), scale_in_points, font_impl.clone()));
font_impl
}
}

780
epaint/src/text/galley.rs Normal file
View File

@@ -0,0 +1,780 @@
//! A [`Galley`] is a piece of text after layout, i.e. where each character has been assigned a position.
//!
//! ## How it works
//! This is going to get complicated.
//!
//! To avoid confusion, we never use the word "line".
//! The `\n` character demarcates the split of text into "paragraphs".
//! Each paragraph is wrapped at some width onto one or more "rows".
//!
//! If this cursors sits right at the border of a wrapped row break (NOT paragraph break)
//! do we prefer the next row?
//! For instance, consider this single paragraph, word wrapped:
//! ``` text
//! Hello_
//! world!
//! ```
//!
//! The offset `6` is both the end of the first row
//! and the start of the second row.
//! [`CCursor::prefer_next_row`] etc selects which.
use super::cursor::*;
use emath::{pos2, NumExt, Rect, Vec2};
/// A collection of text locked into place.
#[derive(Clone, Debug, Default)]
pub struct Galley {
/// The full text, including any an all `\n`.
pub text: String,
/// Rows of text, from top to bottom.
/// The number of chars in all rows sum up to text.chars().count().
/// Note that each paragraph (pieces of text separated with `\n`)
/// can be split up into multiple rows.
pub rows: Vec<Row>,
// Optimization: calculated once and reused.
pub size: Vec2,
}
/// A typeset piece of text on a single row.
#[derive(Clone, Debug)]
pub struct Row {
/// The start of each character, probably starting at zero.
/// The last element is the end of the last character.
/// This is never empty.
/// Unit: points.
///
/// `x_offsets.len() + (ends_with_newline as usize) == text.chars().count() + 1`
pub x_offsets: Vec<f32>,
/// Top of the row, offset within the Galley.
/// Unit: points.
pub y_min: f32,
/// Bottom of the row, offset within the Galley.
/// Unit: points.
pub y_max: f32,
/// If true, this `Row` came from a paragraph ending with a `\n`.
/// The `\n` itself is omitted from `x_offsets`.
/// 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,
}
impl Row {
pub fn sanity_check(&self) {
assert!(!self.x_offsets.is_empty());
}
/// Excludes the implicit `\n` after the `Row`, if any.
pub fn char_count_excluding_newline(&self) -> usize {
assert!(!self.x_offsets.is_empty());
self.x_offsets.len() - 1
}
/// Includes the implicit `\n` after the `Row`, if any.
pub fn char_count_including_newline(&self) -> usize {
self.char_count_excluding_newline() + (self.ends_with_newline as usize)
}
pub fn min_x(&self) -> f32 {
*self.x_offsets.first().unwrap()
}
pub fn max_x(&self) -> f32 {
*self.x_offsets.last().unwrap()
}
pub fn height(&self) -> f32 {
self.y_max - self.y_min
}
pub fn rect(&self) -> Rect {
Rect::from_min_max(
pos2(self.min_x(), self.y_min),
pos2(self.max_x(), self.y_max),
)
}
/// 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, char_x_bounds) in self.x_offsets.windows(2).enumerate() {
let char_center_x = 0.5 * (char_x_bounds[0] + char_x_bounds[1]);
if desired_x < char_center_x {
return i;
}
}
self.char_count_excluding_newline()
}
pub fn x_offset(&self, column: usize) -> f32 {
self.x_offsets[column.min(self.x_offsets.len() - 1)]
}
}
impl Galley {
pub fn sanity_check(&self) {
let mut char_count = 0;
for row in &self.rows {
row.sanity_check();
char_count += row.char_count_including_newline();
}
assert_eq!(char_count, self.text.chars().count());
if let Some(last_row) = self.rows.last() {
debug_assert!(
!last_row.ends_with_newline,
"If the text ends with '\\n', there would be an empty row last.\n\
Galley: {:#?}",
self
);
}
}
}
/// ## Physical positions
impl Galley {
fn end_pos(&self) -> Rect {
if let Some(row) = self.rows.last() {
let x = row.max_x();
Rect::from_min_max(pos2(x, row.y_min), pos2(x, row.y_max))
} 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.y_min), pos2(x, row.y_max));
}
}
}
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) // The one 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 y_dist = (row.y_min - pos.y).abs().min((row.y_max - pos.y).abs());
if 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,
},
}
}
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() {
debug_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();
}
}
debug_assert_eq!(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: 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].max_x() {
// 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].max_x() {
// 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(),
})
}
}
// ----------------------------------------------------------------------------
#[test]
fn test_text_layout() {
impl PartialEq for Cursor {
fn eq(&self, other: &Cursor) -> bool {
(self.ccursor, self.rcursor, self.pcursor)
== (other.ccursor, other.rcursor, other.pcursor)
}
}
use crate::*;
let pixels_per_point = 1.0;
let fonts = text::Fonts::from_definitions(pixels_per_point, text::FontDefinitions::default());
let font = &fonts[TextStyle::Monospace];
let galley = font.layout_multiline("".to_owned(), 1024.0);
assert_eq!(galley.rows.len(), 1);
assert_eq!(galley.rows[0].ends_with_newline, false);
assert_eq!(galley.rows[0].x_offsets, vec![0.0]);
let galley = font.layout_multiline("\n".to_owned(), 1024.0);
assert_eq!(galley.rows.len(), 2);
assert_eq!(galley.rows[0].ends_with_newline, true);
assert_eq!(galley.rows[1].ends_with_newline, false);
assert_eq!(galley.rows[1].x_offsets, vec![0.0]);
let galley = font.layout_multiline("\n\n".to_owned(), 1024.0);
assert_eq!(galley.rows.len(), 3);
assert_eq!(galley.rows[0].ends_with_newline, true);
assert_eq!(galley.rows[1].ends_with_newline, true);
assert_eq!(galley.rows[2].ends_with_newline, false);
assert_eq!(galley.rows[2].x_offsets, vec![0.0]);
let galley = font.layout_multiline(" ".to_owned(), 1024.0);
assert_eq!(galley.rows.len(), 1);
assert_eq!(galley.rows[0].ends_with_newline, false);
let galley = font.layout_multiline("One row!".to_owned(), 1024.0);
assert_eq!(galley.rows.len(), 1);
assert_eq!(galley.rows[0].ends_with_newline, false);
let galley = font.layout_multiline("First row!\n".to_owned(), 1024.0);
assert_eq!(galley.rows.len(), 2);
assert_eq!(galley.rows[0].ends_with_newline, true);
assert_eq!(galley.rows[1].ends_with_newline, false);
assert_eq!(galley.rows[1].x_offsets, vec![0.0]);
let galley = font.layout_multiline("line\nbreak".to_owned(), 10.0);
assert_eq!(galley.rows.len(), 2);
assert_eq!(galley.rows[0].ends_with_newline, true);
assert_eq!(galley.rows[1].ends_with_newline, false);
// Test wrapping:
let galley = font.layout_multiline("word wrap".to_owned(), 10.0);
assert_eq!(galley.rows.len(), 2);
assert_eq!(galley.rows[0].ends_with_newline, false);
assert_eq!(galley.rows[1].ends_with_newline, false);
{
// Test wrapping:
let galley = font.layout_multiline("word wrap.\nNew paragraph.".to_owned(), 10.0);
assert_eq!(galley.rows.len(), 4);
assert_eq!(galley.rows[0].ends_with_newline, false);
assert_eq!(galley.rows[0].char_count_excluding_newline(), "word ".len());
assert_eq!(galley.rows[0].char_count_including_newline(), "word ".len());
assert_eq!(galley.rows[1].ends_with_newline, true);
assert_eq!(galley.rows[1].char_count_excluding_newline(), "wrap.".len());
assert_eq!(
galley.rows[1].char_count_including_newline(),
"wrap.\n".len()
);
assert_eq!(galley.rows[2].ends_with_newline, false);
assert_eq!(galley.rows[3].ends_with_newline, false);
let cursor = Cursor::default();
assert_eq!(cursor, galley.from_ccursor(cursor.ccursor));
assert_eq!(cursor, galley.from_rcursor(cursor.rcursor));
assert_eq!(cursor, galley.from_pcursor(cursor.pcursor));
let cursor = galley.end();
assert_eq!(cursor, galley.from_ccursor(cursor.ccursor));
assert_eq!(cursor, galley.from_rcursor(cursor.rcursor));
assert_eq!(cursor, galley.from_pcursor(cursor.pcursor));
assert_eq!(
cursor,
Cursor {
ccursor: CCursor::new(25),
rcursor: RCursor { row: 3, column: 10 },
pcursor: PCursor {
paragraph: 1,
offset: 14,
prefer_next_row: false,
}
}
);
let cursor = galley.from_ccursor(CCursor::new(1));
assert_eq!(cursor.rcursor, RCursor { row: 0, column: 1 });
assert_eq!(
cursor.pcursor,
PCursor {
paragraph: 0,
offset: 1,
prefer_next_row: false,
}
);
assert_eq!(cursor, galley.from_ccursor(cursor.ccursor));
assert_eq!(cursor, galley.from_rcursor(cursor.rcursor));
assert_eq!(cursor, galley.from_pcursor(cursor.pcursor));
let cursor = galley.from_pcursor(PCursor {
paragraph: 1,
offset: 2,
prefer_next_row: false,
});
assert_eq!(cursor.rcursor, RCursor { row: 2, column: 2 });
assert_eq!(cursor, galley.from_ccursor(cursor.ccursor));
assert_eq!(cursor, galley.from_rcursor(cursor.rcursor));
assert_eq!(cursor, galley.from_pcursor(cursor.pcursor));
let cursor = galley.from_pcursor(PCursor {
paragraph: 1,
offset: 6,
prefer_next_row: false,
});
assert_eq!(cursor.rcursor, RCursor { row: 3, column: 2 });
assert_eq!(cursor, galley.from_ccursor(cursor.ccursor));
assert_eq!(cursor, galley.from_rcursor(cursor.rcursor));
assert_eq!(cursor, galley.from_pcursor(cursor.pcursor));
// On the border between two rows within the same paragraph:
let cursor = galley.from_rcursor(RCursor { row: 0, column: 5 });
assert_eq!(
cursor,
Cursor {
ccursor: CCursor::new(5),
rcursor: RCursor { row: 0, column: 5 },
pcursor: PCursor {
paragraph: 0,
offset: 5,
prefer_next_row: false,
}
}
);
assert_eq!(cursor, galley.from_rcursor(cursor.rcursor));
let cursor = galley.from_rcursor(RCursor { row: 1, column: 0 });
assert_eq!(
cursor,
Cursor {
ccursor: CCursor::new(5),
rcursor: RCursor { row: 1, column: 0 },
pcursor: PCursor {
paragraph: 0,
offset: 5,
prefer_next_row: false,
}
}
);
assert_eq!(cursor, galley.from_rcursor(cursor.rcursor));
}
{
// Test cursor movement:
let galley = font.layout_multiline("word wrap.\nNew paragraph.".to_owned(), 10.0);
assert_eq!(galley.rows.len(), 4);
assert_eq!(galley.rows[0].ends_with_newline, false);
assert_eq!(galley.rows[1].ends_with_newline, true);
assert_eq!(galley.rows[2].ends_with_newline, false);
assert_eq!(galley.rows[3].ends_with_newline, false);
let cursor = Cursor::default();
assert_eq!(galley.cursor_up_one_row(&cursor), cursor);
assert_eq!(galley.cursor_begin_of_row(&cursor), cursor);
assert_eq!(
galley.cursor_end_of_row(&cursor),
Cursor {
ccursor: CCursor::new(5),
rcursor: RCursor { row: 0, column: 5 },
pcursor: PCursor {
paragraph: 0,
offset: 5,
prefer_next_row: false,
}
}
);
assert_eq!(
galley.cursor_down_one_row(&cursor),
Cursor {
ccursor: CCursor::new(5),
rcursor: RCursor { row: 1, column: 0 },
pcursor: PCursor {
paragraph: 0,
offset: 5,
prefer_next_row: false,
}
}
);
let cursor = Cursor::default();
assert_eq!(
galley.cursor_down_one_row(&galley.cursor_down_one_row(&cursor)),
Cursor {
ccursor: CCursor::new(11),
rcursor: RCursor { row: 2, column: 0 },
pcursor: PCursor {
paragraph: 1,
offset: 0,
prefer_next_row: false,
}
}
);
let cursor = galley.end();
assert_eq!(galley.cursor_down_one_row(&cursor), cursor);
let cursor = galley.end();
assert!(galley.cursor_up_one_row(&galley.end()) != cursor);
assert_eq!(
galley.cursor_up_one_row(&galley.end()),
Cursor {
ccursor: CCursor::new(15),
rcursor: RCursor { row: 2, column: 10 },
pcursor: PCursor {
paragraph: 1,
offset: 4,
prefer_next_row: false,
}
}
);
}
}

9
epaint/src/text/mod.rs Normal file
View File

@@ -0,0 +1,9 @@
pub mod cursor;
mod font;
mod fonts;
mod galley;
pub use {
fonts::{FontDefinitions, FontFamily, Fonts, TextStyle},
galley::{Galley, Row},
};