From ed3454301e663a7cb7d73cd56b57b188f4d14a2f Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Wed, 30 Aug 2023 04:31:21 +0200 Subject: Implement explicit text caching in the widget state tree --- graphics/src/text/cache.rs | 120 ++++++++++++++++++++ graphics/src/text/paragraph.rs | 246 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 366 insertions(+) create mode 100644 graphics/src/text/cache.rs create mode 100644 graphics/src/text/paragraph.rs (limited to 'graphics/src/text') diff --git a/graphics/src/text/cache.rs b/graphics/src/text/cache.rs new file mode 100644 index 00000000..8aea6715 --- /dev/null +++ b/graphics/src/text/cache.rs @@ -0,0 +1,120 @@ +use crate::core::{Font, Size}; +use crate::text; + +use rustc_hash::{FxHashMap, FxHashSet}; +use std::collections::hash_map; +use std::hash::{BuildHasher, Hash, Hasher}; + +#[allow(missing_debug_implementations)] +#[derive(Default)] +pub struct Cache { + entries: FxHashMap, + aliases: FxHashMap, + recently_used: FxHashSet, + hasher: HashBuilder, +} + +#[cfg(not(target_arch = "wasm32"))] +type HashBuilder = twox_hash::RandomXxHashBuilder64; + +#[cfg(target_arch = "wasm32")] +type HashBuilder = std::hash::BuildHasherDefault; + +impl Cache { + pub fn new() -> Self { + Self::default() + } + + pub fn get(&self, key: &KeyHash) -> Option<&cosmic_text::Buffer> { + self.entries.get(key) + } + + pub fn allocate( + &mut self, + font_system: &mut cosmic_text::FontSystem, + key: Key<'_>, + ) -> (KeyHash, &mut cosmic_text::Buffer) { + let hash = key.hash(self.hasher.build_hasher()); + + if let Some(hash) = self.aliases.get(&hash) { + let _ = self.recently_used.insert(*hash); + + return (*hash, self.entries.get_mut(hash).unwrap()); + } + + if let hash_map::Entry::Vacant(entry) = self.entries.entry(hash) { + let metrics = cosmic_text::Metrics::new(key.size, key.line_height); + let mut buffer = cosmic_text::Buffer::new(font_system, metrics); + + buffer.set_size( + font_system, + key.bounds.width, + key.bounds.height.max(key.line_height), + ); + buffer.set_text( + font_system, + key.content, + text::to_attributes(key.font), + text::to_shaping(key.shaping), + ); + + let bounds = text::measure(&buffer); + let _ = entry.insert(buffer); + + for bounds in [ + bounds, + Size { + width: key.bounds.width, + ..bounds + }, + ] { + if key.bounds != bounds { + let _ = self.aliases.insert( + Key { bounds, ..key }.hash(self.hasher.build_hasher()), + hash, + ); + } + } + } + + let _ = self.recently_used.insert(hash); + + (hash, self.entries.get_mut(&hash).unwrap()) + } + + pub fn trim(&mut self) { + self.entries + .retain(|key, _| self.recently_used.contains(key)); + + self.aliases + .retain(|_, value| self.recently_used.contains(value)); + + self.recently_used.clear(); + } +} + +#[derive(Debug, Clone, Copy)] +pub struct Key<'a> { + pub content: &'a str, + pub size: f32, + pub line_height: f32, + pub font: Font, + pub bounds: Size, + pub shaping: text::Shaping, +} + +impl Key<'_> { + fn hash(self, mut hasher: H) -> KeyHash { + self.content.hash(&mut hasher); + self.size.to_bits().hash(&mut hasher); + self.line_height.to_bits().hash(&mut hasher); + self.font.hash(&mut hasher); + self.bounds.width.to_bits().hash(&mut hasher); + self.bounds.height.to_bits().hash(&mut hasher); + self.shaping.hash(&mut hasher); + + hasher.finish() + } +} + +pub type KeyHash = u64; diff --git a/graphics/src/text/paragraph.rs b/graphics/src/text/paragraph.rs new file mode 100644 index 00000000..7b70376a --- /dev/null +++ b/graphics/src/text/paragraph.rs @@ -0,0 +1,246 @@ +use crate::core; +use crate::core::alignment; +use crate::core::text::{Hit, LineHeight, Shaping, Text}; +use crate::core::{Font, Pixels, Point, Size}; +use crate::text::{self, FontSystem}; + +use std::fmt; +use std::sync::{self, Arc}; + +#[derive(Clone, PartialEq, Default)] +pub struct Paragraph(Arc); + +struct Internal { + buffer: cosmic_text::Buffer, + content: String, // TODO: Reuse from `buffer` (?) + font: Font, + shaping: Shaping, + horizontal_alignment: alignment::Horizontal, + vertical_alignment: alignment::Vertical, + bounds: Size, + min_bounds: Size, +} + +impl Paragraph { + pub fn new() -> Self { + Self::default() + } + + pub fn with_text(text: Text<'_, Font>, font_system: &FontSystem) -> Self { + let mut font_system = font_system.write(); + + let mut buffer = cosmic_text::Buffer::new( + &mut font_system, + cosmic_text::Metrics::new( + text.size.into(), + text.line_height.to_absolute(text.size).into(), + ), + ); + + buffer.set_size( + &mut font_system, + text.bounds.width, + text.bounds.height, + ); + + buffer.set_text( + &mut font_system, + text.content, + text::to_attributes(text.font), + text::to_shaping(text.shaping), + ); + + let min_bounds = text::measure(&buffer); + + Self(Arc::new(Internal { + buffer, + content: text.content.to_owned(), + font: text.font, + horizontal_alignment: text.horizontal_alignment, + vertical_alignment: text.vertical_alignment, + shaping: text.shaping, + bounds: text.bounds, + min_bounds, + })) + } + + pub fn buffer(&self) -> &cosmic_text::Buffer { + &self.0.buffer + } + + pub fn downgrade(&self) -> Weak { + Weak { + raw: Arc::downgrade(&self.0), + min_bounds: self.0.min_bounds, + horizontal_alignment: self.0.horizontal_alignment, + vertical_alignment: self.0.vertical_alignment, + } + } + + pub fn resize(&mut self, new_bounds: Size, font_system: &FontSystem) { + if let Some(internal) = Arc::get_mut(&mut self.0) { + // If there is no strong reference holding on to the paragraph, we + // resize the buffer in-place + internal.buffer.set_size( + &mut font_system.write(), + new_bounds.width, + new_bounds.height, + ); + + internal.bounds = new_bounds; + internal.min_bounds = text::measure(&internal.buffer); + } else { + let metrics = self.0.buffer.metrics(); + + // If there is a strong reference somewhere, we recompute the buffer + // from scratch + *self = Self::with_text( + Text { + content: &self.0.content, + bounds: self.0.bounds, + size: Pixels(metrics.font_size), + line_height: LineHeight::Absolute(Pixels( + metrics.line_height, + )), + font: self.0.font, + horizontal_alignment: self.0.horizontal_alignment, + vertical_alignment: self.0.vertical_alignment, + shaping: self.0.shaping, + }, + font_system, + ); + } + } +} + +impl core::text::Paragraph for Paragraph { + type Font = Font; + + fn content(&self) -> &str { + &self.0.content + } + + fn text_size(&self) -> Pixels { + Pixels(self.0.buffer.metrics().font_size) + } + + fn line_height(&self) -> LineHeight { + LineHeight::Absolute(Pixels(self.0.buffer.metrics().line_height)) + } + + fn font(&self) -> Font { + self.0.font + } + + fn shaping(&self) -> Shaping { + self.0.shaping + } + + fn horizontal_alignment(&self) -> alignment::Horizontal { + self.0.horizontal_alignment + } + + fn vertical_alignment(&self) -> alignment::Vertical { + self.0.vertical_alignment + } + + fn bounds(&self) -> Size { + self.0.bounds + } + + fn min_bounds(&self) -> Size { + self.0.min_bounds + } + + fn hit_test(&self, point: Point) -> Option { + let cursor = self.0.buffer.hit(point.x, point.y)?; + + Some(Hit::CharOffset(cursor.index)) + } + + fn grapheme_position(&self, line: usize, index: usize) -> Option { + let run = self.0.buffer.layout_runs().nth(line)?; + + // TODO: Index represents a grapheme, not a glyph + let glyph = run.glyphs.get(index).or_else(|| run.glyphs.last())?; + + let advance_last = if index == run.glyphs.len() { + glyph.w + } else { + 0.0 + }; + + Some(Point::new( + glyph.x + glyph.x_offset * glyph.font_size + advance_last, + glyph.y - glyph.y_offset * glyph.font_size, + )) + } +} + +impl PartialEq for Internal { + fn eq(&self, other: &Self) -> bool { + self.content == other.content + && self.font == other.font + && self.shaping == other.shaping + && self.horizontal_alignment == other.horizontal_alignment + && self.vertical_alignment == other.vertical_alignment + && self.bounds == other.bounds + && self.min_bounds == other.min_bounds + && self.buffer.metrics() == other.buffer.metrics() + } +} + +impl Default for Internal { + fn default() -> Self { + Self { + buffer: cosmic_text::Buffer::new_empty(cosmic_text::Metrics { + font_size: 1.0, + line_height: 1.0, + }), + content: String::new(), + font: Font::default(), + shaping: Shaping::default(), + horizontal_alignment: alignment::Horizontal::Left, + vertical_alignment: alignment::Vertical::Top, + bounds: Size::ZERO, + min_bounds: Size::ZERO, + } + } +} + +impl fmt::Debug for Paragraph { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Paragraph") + .field("content", &self.0.content) + .field("font", &self.0.font) + .field("shaping", &self.0.shaping) + .field("horizontal_alignment", &self.0.horizontal_alignment) + .field("vertical_alignment", &self.0.vertical_alignment) + .field("bounds", &self.0.bounds) + .field("min_bounds", &self.0.min_bounds) + .finish() + } +} + +#[derive(Debug, Clone)] +pub struct Weak { + raw: sync::Weak, + pub min_bounds: Size, + pub horizontal_alignment: alignment::Horizontal, + pub vertical_alignment: alignment::Vertical, +} + +impl Weak { + pub fn upgrade(&self) -> Option { + self.raw.upgrade().map(Paragraph) + } +} + +impl PartialEq for Weak { + fn eq(&self, other: &Self) -> bool { + match (self.raw.upgrade(), other.raw.upgrade()) { + (Some(p1), Some(p2)) => p1 == p2, + _ => false, + } + } +} -- cgit From 89acf0217e0acd92a82bff1fd516cd4266c0878a Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Wed, 30 Aug 2023 05:06:08 +0200 Subject: Use `min_bounds` for cached text --- graphics/src/text/cache.rs | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) (limited to 'graphics/src/text') diff --git a/graphics/src/text/cache.rs b/graphics/src/text/cache.rs index 8aea6715..9e4fbf65 100644 --- a/graphics/src/text/cache.rs +++ b/graphics/src/text/cache.rs @@ -8,7 +8,7 @@ use std::hash::{BuildHasher, Hash, Hasher}; #[allow(missing_debug_implementations)] #[derive(Default)] pub struct Cache { - entries: FxHashMap, + entries: FxHashMap, aliases: FxHashMap, recently_used: FxHashSet, hasher: HashBuilder, @@ -25,7 +25,7 @@ impl Cache { Self::default() } - pub fn get(&self, key: &KeyHash) -> Option<&cosmic_text::Buffer> { + pub fn get(&self, key: &KeyHash) -> Option<&Entry> { self.entries.get(key) } @@ -33,7 +33,7 @@ impl Cache { &mut self, font_system: &mut cosmic_text::FontSystem, key: Key<'_>, - ) -> (KeyHash, &mut cosmic_text::Buffer) { + ) -> (KeyHash, &mut Entry) { let hash = key.hash(self.hasher.build_hasher()); if let Some(hash) = self.aliases.get(&hash) { @@ -59,7 +59,10 @@ impl Cache { ); let bounds = text::measure(&buffer); - let _ = entry.insert(buffer); + let _ = entry.insert(Entry { + buffer, + min_bounds: bounds, + }); for bounds in [ bounds, @@ -118,3 +121,9 @@ impl Key<'_> { } pub type KeyHash = u64; + +#[allow(missing_debug_implementations)] +pub struct Entry { + pub buffer: cosmic_text::Buffer, + pub min_bounds: Size, +} -- cgit From ce22d661fa2f4b50d2e7d9ba6bd07e625ec6789e Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Fri, 1 Sep 2023 03:25:29 +0200 Subject: Remove `Clone` implementation for `Paragraph` --- graphics/src/text/paragraph.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'graphics/src/text') diff --git a/graphics/src/text/paragraph.rs b/graphics/src/text/paragraph.rs index 7b70376a..f04b1e69 100644 --- a/graphics/src/text/paragraph.rs +++ b/graphics/src/text/paragraph.rs @@ -7,7 +7,7 @@ use crate::text::{self, FontSystem}; use std::fmt; use std::sync::{self, Arc}; -#[derive(Clone, PartialEq, Default)] +#[derive(PartialEq, Default)] pub struct Paragraph(Arc); struct Internal { -- cgit From 935c722a278071d3bcd0bf499a0ef8f687ed51ad Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Fri, 1 Sep 2023 03:59:57 +0200 Subject: Use `Arc::try_unwrap` in `Paragraph` We use `MaybeUninit` here instead of `Option` to save some cycles, but I will most likely change it for an `Option` since unsafe code is quite scary. --- graphics/src/text/paragraph.rs | 154 +++++++++++++++++++++++++---------------- 1 file changed, 95 insertions(+), 59 deletions(-) (limited to 'graphics/src/text') diff --git a/graphics/src/text/paragraph.rs b/graphics/src/text/paragraph.rs index f04b1e69..c6921005 100644 --- a/graphics/src/text/paragraph.rs +++ b/graphics/src/text/paragraph.rs @@ -5,10 +5,10 @@ use crate::core::{Font, Pixels, Point, Size}; use crate::text::{self, FontSystem}; use std::fmt; +use std::mem::MaybeUninit; use std::sync::{self, Arc}; -#[derive(PartialEq, Default)] -pub struct Paragraph(Arc); +pub struct Paragraph(MaybeUninit>); struct Internal { buffer: cosmic_text::Buffer, @@ -21,6 +21,12 @@ struct Internal { min_bounds: Size, } +impl Default for Paragraph { + fn default() -> Self { + Self(MaybeUninit::new(Arc::new(Internal::default()))) + } +} + impl Paragraph { pub fn new() -> Self { Self::default() @@ -52,7 +58,7 @@ impl Paragraph { let min_bounds = text::measure(&buffer); - Self(Arc::new(Internal { + Self(MaybeUninit::new(Arc::new(Internal { buffer, content: text.content.to_owned(), font: text.font, @@ -61,54 +67,80 @@ impl Paragraph { shaping: text.shaping, bounds: text.bounds, min_bounds, - })) + }))) } pub fn buffer(&self) -> &cosmic_text::Buffer { - &self.0.buffer + #[allow(unsafe_code)] + &unsafe { self.0.assume_init_ref() }.buffer } pub fn downgrade(&self) -> Weak { + #[allow(unsafe_code)] + let paragraph = unsafe { self.0.assume_init_ref() }; + Weak { - raw: Arc::downgrade(&self.0), - min_bounds: self.0.min_bounds, - horizontal_alignment: self.0.horizontal_alignment, - vertical_alignment: self.0.vertical_alignment, + raw: Arc::downgrade(paragraph), + min_bounds: paragraph.min_bounds, + horizontal_alignment: paragraph.horizontal_alignment, + vertical_alignment: paragraph.vertical_alignment, } } pub fn resize(&mut self, new_bounds: Size, font_system: &FontSystem) { - if let Some(internal) = Arc::get_mut(&mut self.0) { - // If there is no strong reference holding on to the paragraph, we - // resize the buffer in-place - internal.buffer.set_size( - &mut font_system.write(), - new_bounds.width, - new_bounds.height, - ); - - internal.bounds = new_bounds; - internal.min_bounds = text::measure(&internal.buffer); - } else { - let metrics = self.0.buffer.metrics(); - - // If there is a strong reference somewhere, we recompute the buffer - // from scratch - *self = Self::with_text( - Text { - content: &self.0.content, - bounds: self.0.bounds, - size: Pixels(metrics.font_size), - line_height: LineHeight::Absolute(Pixels( - metrics.line_height, - )), - font: self.0.font, - horizontal_alignment: self.0.horizontal_alignment, - vertical_alignment: self.0.vertical_alignment, - shaping: self.0.shaping, - }, - font_system, - ); + // Place uninit for now, we always write to `self.0` in the end + let paragraph = std::mem::replace(&mut self.0, MaybeUninit::uninit()); + + // Mutable self guarantees unique access and `uninit` call only happens + // in this method. + #[allow(unsafe_code)] + let paragraph = unsafe { paragraph.assume_init() }; + + match Arc::try_unwrap(paragraph) { + Ok(mut internal) => { + internal.buffer.set_size( + &mut font_system.write(), + new_bounds.width, + new_bounds.height, + ); + + internal.bounds = new_bounds; + internal.min_bounds = text::measure(&internal.buffer); + + let _ = self.0.write(Arc::new(internal)); + } + Err(internal) => { + let metrics = internal.buffer.metrics(); + + // If there is a strong reference somewhere, we recompute the + // buffer from scratch + let new_paragraph = Self::with_text( + Text { + content: &internal.content, + bounds: internal.bounds, + size: Pixels(metrics.font_size), + line_height: LineHeight::Absolute(Pixels( + metrics.line_height, + )), + font: internal.font, + horizontal_alignment: internal.horizontal_alignment, + vertical_alignment: internal.vertical_alignment, + shaping: internal.shaping, + }, + font_system, + ); + + // New paragraph should always be initialized + #[allow(unsafe_code)] + let _ = self.0.write(unsafe { new_paragraph.0.assume_init() }); + } + } + } + + fn internal_ref(&self) -> &Internal { + #[allow(unsafe_code)] + unsafe { + self.0.assume_init_ref() } } } @@ -117,49 +149,51 @@ impl core::text::Paragraph for Paragraph { type Font = Font; fn content(&self) -> &str { - &self.0.content + &self.internal_ref().content } fn text_size(&self) -> Pixels { - Pixels(self.0.buffer.metrics().font_size) + Pixels(self.internal_ref().buffer.metrics().font_size) } fn line_height(&self) -> LineHeight { - LineHeight::Absolute(Pixels(self.0.buffer.metrics().line_height)) + LineHeight::Absolute(Pixels( + self.internal_ref().buffer.metrics().line_height, + )) } fn font(&self) -> Font { - self.0.font + self.internal_ref().font } fn shaping(&self) -> Shaping { - self.0.shaping + self.internal_ref().shaping } fn horizontal_alignment(&self) -> alignment::Horizontal { - self.0.horizontal_alignment + self.internal_ref().horizontal_alignment } fn vertical_alignment(&self) -> alignment::Vertical { - self.0.vertical_alignment + self.internal_ref().vertical_alignment } fn bounds(&self) -> Size { - self.0.bounds + self.internal_ref().bounds } fn min_bounds(&self) -> Size { - self.0.min_bounds + self.internal_ref().min_bounds } fn hit_test(&self, point: Point) -> Option { - let cursor = self.0.buffer.hit(point.x, point.y)?; + let cursor = self.internal_ref().buffer.hit(point.x, point.y)?; Some(Hit::CharOffset(cursor.index)) } fn grapheme_position(&self, line: usize, index: usize) -> Option { - let run = self.0.buffer.layout_runs().nth(line)?; + let run = self.internal_ref().buffer.layout_runs().nth(line)?; // TODO: Index represents a grapheme, not a glyph let glyph = run.glyphs.get(index).or_else(|| run.glyphs.last())?; @@ -210,14 +244,16 @@ impl Default for Internal { impl fmt::Debug for Paragraph { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let paragraph = self.internal_ref(); + f.debug_struct("Paragraph") - .field("content", &self.0.content) - .field("font", &self.0.font) - .field("shaping", &self.0.shaping) - .field("horizontal_alignment", &self.0.horizontal_alignment) - .field("vertical_alignment", &self.0.vertical_alignment) - .field("bounds", &self.0.bounds) - .field("min_bounds", &self.0.min_bounds) + .field("content", ¶graph.content) + .field("font", ¶graph.font) + .field("shaping", ¶graph.shaping) + .field("horizontal_alignment", ¶graph.horizontal_alignment) + .field("vertical_alignment", ¶graph.vertical_alignment) + .field("bounds", ¶graph.bounds) + .field("min_bounds", ¶graph.min_bounds) .finish() } } @@ -232,7 +268,7 @@ pub struct Weak { impl Weak { pub fn upgrade(&self) -> Option { - self.raw.upgrade().map(Paragraph) + self.raw.upgrade().map(MaybeUninit::new).map(Paragraph) } } -- cgit From 51e69d7040c943aad8453bc03031c75b4cb302bb Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Fri, 1 Sep 2023 04:04:15 +0200 Subject: Replace `MaybeUninit` with `Option` in `paragraph` --- graphics/src/text/paragraph.rs | 72 ++++++++++++++++-------------------------- 1 file changed, 28 insertions(+), 44 deletions(-) (limited to 'graphics/src/text') diff --git a/graphics/src/text/paragraph.rs b/graphics/src/text/paragraph.rs index c6921005..8e8907f9 100644 --- a/graphics/src/text/paragraph.rs +++ b/graphics/src/text/paragraph.rs @@ -5,10 +5,10 @@ use crate::core::{Font, Pixels, Point, Size}; use crate::text::{self, FontSystem}; use std::fmt; -use std::mem::MaybeUninit; use std::sync::{self, Arc}; -pub struct Paragraph(MaybeUninit>); +#[derive(Clone, PartialEq, Default)] +pub struct Paragraph(Option>); struct Internal { buffer: cosmic_text::Buffer, @@ -21,12 +21,6 @@ struct Internal { min_bounds: Size, } -impl Default for Paragraph { - fn default() -> Self { - Self(MaybeUninit::new(Arc::new(Internal::default()))) - } -} - impl Paragraph { pub fn new() -> Self { Self::default() @@ -58,7 +52,7 @@ impl Paragraph { let min_bounds = text::measure(&buffer); - Self(MaybeUninit::new(Arc::new(Internal { + Self(Some(Arc::new(Internal { buffer, content: text.content.to_owned(), font: text.font, @@ -71,13 +65,11 @@ impl Paragraph { } pub fn buffer(&self) -> &cosmic_text::Buffer { - #[allow(unsafe_code)] - &unsafe { self.0.assume_init_ref() }.buffer + &self.internal().buffer } pub fn downgrade(&self) -> Weak { - #[allow(unsafe_code)] - let paragraph = unsafe { self.0.assume_init_ref() }; + let paragraph = self.internal(); Weak { raw: Arc::downgrade(paragraph), @@ -88,13 +80,10 @@ impl Paragraph { } pub fn resize(&mut self, new_bounds: Size, font_system: &FontSystem) { - // Place uninit for now, we always write to `self.0` in the end - let paragraph = std::mem::replace(&mut self.0, MaybeUninit::uninit()); - - // Mutable self guarantees unique access and `uninit` call only happens - // in this method. - #[allow(unsafe_code)] - let paragraph = unsafe { paragraph.assume_init() }; + let paragraph = self + .0 + .take() + .expect("paragraph should always be initialized"); match Arc::try_unwrap(paragraph) { Ok(mut internal) => { @@ -107,14 +96,14 @@ impl Paragraph { internal.bounds = new_bounds; internal.min_bounds = text::measure(&internal.buffer); - let _ = self.0.write(Arc::new(internal)); + self.0 = Some(Arc::new(internal)); } Err(internal) => { let metrics = internal.buffer.metrics(); // If there is a strong reference somewhere, we recompute the // buffer from scratch - let new_paragraph = Self::with_text( + *self = Self::with_text( Text { content: &internal.content, bounds: internal.bounds, @@ -129,19 +118,14 @@ impl Paragraph { }, font_system, ); - - // New paragraph should always be initialized - #[allow(unsafe_code)] - let _ = self.0.write(unsafe { new_paragraph.0.assume_init() }); } } } - fn internal_ref(&self) -> &Internal { - #[allow(unsafe_code)] - unsafe { - self.0.assume_init_ref() - } + fn internal(&self) -> &Arc { + self.0 + .as_ref() + .expect("paragraph should always be initialized") } } @@ -149,51 +133,51 @@ impl core::text::Paragraph for Paragraph { type Font = Font; fn content(&self) -> &str { - &self.internal_ref().content + &self.internal().content } fn text_size(&self) -> Pixels { - Pixels(self.internal_ref().buffer.metrics().font_size) + Pixels(self.internal().buffer.metrics().font_size) } fn line_height(&self) -> LineHeight { LineHeight::Absolute(Pixels( - self.internal_ref().buffer.metrics().line_height, + self.internal().buffer.metrics().line_height, )) } fn font(&self) -> Font { - self.internal_ref().font + self.internal().font } fn shaping(&self) -> Shaping { - self.internal_ref().shaping + self.internal().shaping } fn horizontal_alignment(&self) -> alignment::Horizontal { - self.internal_ref().horizontal_alignment + self.internal().horizontal_alignment } fn vertical_alignment(&self) -> alignment::Vertical { - self.internal_ref().vertical_alignment + self.internal().vertical_alignment } fn bounds(&self) -> Size { - self.internal_ref().bounds + self.internal().bounds } fn min_bounds(&self) -> Size { - self.internal_ref().min_bounds + self.internal().min_bounds } fn hit_test(&self, point: Point) -> Option { - let cursor = self.internal_ref().buffer.hit(point.x, point.y)?; + let cursor = self.internal().buffer.hit(point.x, point.y)?; Some(Hit::CharOffset(cursor.index)) } fn grapheme_position(&self, line: usize, index: usize) -> Option { - let run = self.internal_ref().buffer.layout_runs().nth(line)?; + let run = self.internal().buffer.layout_runs().nth(line)?; // TODO: Index represents a grapheme, not a glyph let glyph = run.glyphs.get(index).or_else(|| run.glyphs.last())?; @@ -244,7 +228,7 @@ impl Default for Internal { impl fmt::Debug for Paragraph { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let paragraph = self.internal_ref(); + let paragraph = self.internal(); f.debug_struct("Paragraph") .field("content", ¶graph.content) @@ -268,7 +252,7 @@ pub struct Weak { impl Weak { pub fn upgrade(&self) -> Option { - self.raw.upgrade().map(MaybeUninit::new).map(Paragraph) + self.raw.upgrade().map(Some).map(Paragraph) } } -- cgit From 6758de2b4348d8990205721027524cf87a9db128 Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Fri, 1 Sep 2023 04:14:06 +0200 Subject: Fix `Default` implementation for `Paragraph` --- graphics/src/text/paragraph.rs | 40 +++++++++++++++++++++++----------------- 1 file changed, 23 insertions(+), 17 deletions(-) (limited to 'graphics/src/text') diff --git a/graphics/src/text/paragraph.rs b/graphics/src/text/paragraph.rs index 8e8907f9..d99b8412 100644 --- a/graphics/src/text/paragraph.rs +++ b/graphics/src/text/paragraph.rs @@ -7,7 +7,7 @@ use crate::text::{self, FontSystem}; use std::fmt; use std::sync::{self, Arc}; -#[derive(Clone, PartialEq, Default)] +#[derive(Clone, PartialEq)] pub struct Paragraph(Option>); struct Internal { @@ -195,6 +195,28 @@ impl core::text::Paragraph for Paragraph { } } +impl Default for Paragraph { + fn default() -> Self { + Self(Some(Arc::new(Internal::default()))) + } +} + +impl fmt::Debug for Paragraph { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let paragraph = self.internal(); + + f.debug_struct("Paragraph") + .field("content", ¶graph.content) + .field("font", ¶graph.font) + .field("shaping", ¶graph.shaping) + .field("horizontal_alignment", ¶graph.horizontal_alignment) + .field("vertical_alignment", ¶graph.vertical_alignment) + .field("bounds", ¶graph.bounds) + .field("min_bounds", ¶graph.min_bounds) + .finish() + } +} + impl PartialEq for Internal { fn eq(&self, other: &Self) -> bool { self.content == other.content @@ -226,22 +248,6 @@ impl Default for Internal { } } -impl fmt::Debug for Paragraph { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let paragraph = self.internal(); - - f.debug_struct("Paragraph") - .field("content", ¶graph.content) - .field("font", ¶graph.font) - .field("shaping", ¶graph.shaping) - .field("horizontal_alignment", ¶graph.horizontal_alignment) - .field("vertical_alignment", ¶graph.vertical_alignment) - .field("bounds", ¶graph.bounds) - .field("min_bounds", ¶graph.min_bounds) - .finish() - } -} - #[derive(Debug, Clone)] pub struct Weak { raw: sync::Weak, -- cgit From 34495bba1c1ffaa4ea2bab46103b5d66e333c51e Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Mon, 4 Sep 2023 02:55:09 +0200 Subject: Introduce `keyed::Column` widget --- graphics/src/text/paragraph.rs | 2 ++ 1 file changed, 2 insertions(+) (limited to 'graphics/src/text') diff --git a/graphics/src/text/paragraph.rs b/graphics/src/text/paragraph.rs index d99b8412..ee7c04c8 100644 --- a/graphics/src/text/paragraph.rs +++ b/graphics/src/text/paragraph.rs @@ -27,6 +27,8 @@ impl Paragraph { } pub fn with_text(text: Text<'_, Font>, font_system: &FontSystem) -> Self { + log::trace!("\nAllocating paragraph: {}", text.content); + let mut font_system = font_system.write(); let mut buffer = cosmic_text::Buffer::new( -- cgit From 3450987355be7fe029db112474d06613929b54c7 Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Sat, 9 Sep 2023 11:21:32 +0200 Subject: Invalidate existing paragraphs when new fonts are loaded --- graphics/src/text/paragraph.rs | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) (limited to 'graphics/src/text') diff --git a/graphics/src/text/paragraph.rs b/graphics/src/text/paragraph.rs index ee7c04c8..cd12bc8f 100644 --- a/graphics/src/text/paragraph.rs +++ b/graphics/src/text/paragraph.rs @@ -19,6 +19,7 @@ struct Internal { vertical_alignment: alignment::Vertical, bounds: Size, min_bounds: Size, + version: text::Version, } impl Paragraph { @@ -27,9 +28,9 @@ impl Paragraph { } pub fn with_text(text: Text<'_, Font>, font_system: &FontSystem) -> Self { - log::trace!("\nAllocating paragraph: {}", text.content); + log::trace!("Allocating paragraph: {}", text.content); - let mut font_system = font_system.write(); + let (mut font_system, version) = font_system.write(); let mut buffer = cosmic_text::Buffer::new( &mut font_system, @@ -63,6 +64,7 @@ impl Paragraph { shaping: text.shaping, bounds: text.bounds, min_bounds, + version, }))) } @@ -70,6 +72,10 @@ impl Paragraph { &self.internal().buffer } + pub fn version(&self) -> text::Version { + self.internal().version + } + pub fn downgrade(&self) -> Weak { let paragraph = self.internal(); @@ -89,8 +95,10 @@ impl Paragraph { match Arc::try_unwrap(paragraph) { Ok(mut internal) => { + let (mut font_system, _) = font_system.write(); + internal.buffer.set_size( - &mut font_system.write(), + &mut font_system, new_bounds.width, new_bounds.height, ); @@ -246,6 +254,7 @@ impl Default for Internal { vertical_alignment: alignment::Vertical::Top, bounds: Size::ZERO, min_bounds: Size::ZERO, + version: text::Version::default(), } } } -- cgit From bbb9c2d92819f2ff96e51773037138fef488290a Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Sat, 9 Sep 2023 23:05:44 +0200 Subject: Count grapheme clusters in `Paragraph::grapheme_position` --- graphics/src/text/paragraph.rs | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) (limited to 'graphics/src/text') diff --git a/graphics/src/text/paragraph.rs b/graphics/src/text/paragraph.rs index cd12bc8f..e4350cff 100644 --- a/graphics/src/text/paragraph.rs +++ b/graphics/src/text/paragraph.rs @@ -189,8 +189,27 @@ impl core::text::Paragraph for Paragraph { fn grapheme_position(&self, line: usize, index: usize) -> Option { let run = self.internal().buffer.layout_runs().nth(line)?; - // TODO: Index represents a grapheme, not a glyph - let glyph = run.glyphs.get(index).or_else(|| run.glyphs.last())?; + // index represents a grapheme, not a glyph + // Let's find the first glyph for the given grapheme cluster + let mut last_start = None; + let mut graphemes_seen = 0; + + let glyph = run + .glyphs + .iter() + .find(|glyph| { + if graphemes_seen == index { + return true; + } + + if Some(glyph.start) != last_start { + last_start = Some(glyph.start); + graphemes_seen += 1; + } + + false + }) + .or_else(|| run.glyphs.last())?; let advance_last = if index == run.glyphs.len() { glyph.w -- cgit From 346af3f8b0baa418fd37b878bc2930ff0bd57cc0 Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Mon, 11 Sep 2023 02:47:24 +0200 Subject: Make `FontSystem` global and simplify `Paragraph` API --- graphics/src/text/paragraph.rs | 147 +++++++++++++++++++---------------------- 1 file changed, 69 insertions(+), 78 deletions(-) (limited to 'graphics/src/text') diff --git a/graphics/src/text/paragraph.rs b/graphics/src/text/paragraph.rs index e4350cff..d0396e8e 100644 --- a/graphics/src/text/paragraph.rs +++ b/graphics/src/text/paragraph.rs @@ -2,7 +2,7 @@ use crate::core; use crate::core::alignment; use crate::core::text::{Hit, LineHeight, Shaping, Text}; use crate::core::{Font, Pixels, Point, Size}; -use crate::text::{self, FontSystem}; +use crate::text; use std::fmt; use std::sync::{self, Arc}; @@ -27,13 +27,39 @@ impl Paragraph { Self::default() } - pub fn with_text(text: Text<'_, Font>, font_system: &FontSystem) -> Self { + pub fn buffer(&self) -> &cosmic_text::Buffer { + &self.internal().buffer + } + + pub fn downgrade(&self) -> Weak { + let paragraph = self.internal(); + + Weak { + raw: Arc::downgrade(paragraph), + min_bounds: paragraph.min_bounds, + horizontal_alignment: paragraph.horizontal_alignment, + vertical_alignment: paragraph.vertical_alignment, + } + } + + fn internal(&self) -> &Arc { + self.0 + .as_ref() + .expect("paragraph should always be initialized") + } +} + +impl core::text::Paragraph for Paragraph { + type Font = Font; + + fn with_text(text: Text<'_, Font>) -> Self { log::trace!("Allocating paragraph: {}", text.content); - let (mut font_system, version) = font_system.write(); + let mut font_system = + text::font_system().write().expect("Write font system"); let mut buffer = cosmic_text::Buffer::new( - &mut font_system, + font_system.raw(), cosmic_text::Metrics::new( text.size.into(), text.line_height.to_absolute(text.size).into(), @@ -41,13 +67,13 @@ impl Paragraph { ); buffer.set_size( - &mut font_system, + font_system.raw(), text.bounds.width, text.bounds.height, ); buffer.set_text( - &mut font_system, + font_system.raw(), text.content, text::to_attributes(text.font), text::to_shaping(text.shaping), @@ -64,30 +90,11 @@ impl Paragraph { shaping: text.shaping, bounds: text.bounds, min_bounds, - version, + version: font_system.version(), }))) } - pub fn buffer(&self) -> &cosmic_text::Buffer { - &self.internal().buffer - } - - pub fn version(&self) -> text::Version { - self.internal().version - } - - pub fn downgrade(&self) -> Weak { - let paragraph = self.internal(); - - Weak { - raw: Arc::downgrade(paragraph), - min_bounds: paragraph.min_bounds, - horizontal_alignment: paragraph.horizontal_alignment, - vertical_alignment: paragraph.vertical_alignment, - } - } - - pub fn resize(&mut self, new_bounds: Size, font_system: &FontSystem) { + fn resize(&mut self, new_bounds: Size) { let paragraph = self .0 .take() @@ -95,10 +102,11 @@ impl Paragraph { match Arc::try_unwrap(paragraph) { Ok(mut internal) => { - let (mut font_system, _) = font_system.write(); + let mut font_system = + text::font_system().write().expect("Write font system"); internal.buffer.set_size( - &mut font_system, + font_system.raw(), new_bounds.width, new_bounds.height, ); @@ -113,55 +121,42 @@ impl Paragraph { // If there is a strong reference somewhere, we recompute the // buffer from scratch - *self = Self::with_text( - Text { - content: &internal.content, - bounds: internal.bounds, - size: Pixels(metrics.font_size), - line_height: LineHeight::Absolute(Pixels( - metrics.line_height, - )), - font: internal.font, - horizontal_alignment: internal.horizontal_alignment, - vertical_alignment: internal.vertical_alignment, - shaping: internal.shaping, - }, - font_system, - ); + *self = Self::with_text(Text { + content: &internal.content, + bounds: internal.bounds, + size: Pixels(metrics.font_size), + line_height: LineHeight::Absolute(Pixels( + metrics.line_height, + )), + font: internal.font, + horizontal_alignment: internal.horizontal_alignment, + vertical_alignment: internal.vertical_alignment, + shaping: internal.shaping, + }); } } } - fn internal(&self) -> &Arc { - self.0 - .as_ref() - .expect("paragraph should always be initialized") - } -} - -impl core::text::Paragraph for Paragraph { - type Font = Font; - - fn content(&self) -> &str { - &self.internal().content - } - - fn text_size(&self) -> Pixels { - Pixels(self.internal().buffer.metrics().font_size) - } - - fn line_height(&self) -> LineHeight { - LineHeight::Absolute(Pixels( - self.internal().buffer.metrics().line_height, - )) - } - - fn font(&self) -> Font { - self.internal().font - } - - fn shaping(&self) -> Shaping { - self.internal().shaping + fn compare(&self, text: Text<'_, Font>) -> core::text::Difference { + let font_system = text::font_system().read().expect("Read font system"); + let paragraph = self.internal(); + let metrics = paragraph.buffer.metrics(); + + if paragraph.version != font_system.version + || paragraph.content != text.content + || metrics.font_size != text.size.0 + || metrics.line_height != text.line_height.to_absolute(text.size).0 + || paragraph.font != text.font + || paragraph.shaping != text.shaping + || paragraph.horizontal_alignment != text.horizontal_alignment + || paragraph.vertical_alignment != text.vertical_alignment + { + core::text::Difference::Shape + } else if paragraph.bounds != text.bounds { + core::text::Difference::Bounds + } else { + core::text::Difference::None + } } fn horizontal_alignment(&self) -> alignment::Horizontal { @@ -172,10 +167,6 @@ impl core::text::Paragraph for Paragraph { self.internal().vertical_alignment } - fn bounds(&self) -> Size { - self.internal().bounds - } - fn min_bounds(&self) -> Size { self.internal().min_bounds } -- cgit From 6448429103c9c82b90040ac5a5a097bdded23f82 Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Tue, 12 Sep 2023 14:51:00 +0200 Subject: Draft `Editor` API and `TextEditor` widget --- graphics/src/text/editor.rs | 327 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 327 insertions(+) create mode 100644 graphics/src/text/editor.rs (limited to 'graphics/src/text') diff --git a/graphics/src/text/editor.rs b/graphics/src/text/editor.rs new file mode 100644 index 00000000..53f63fea --- /dev/null +++ b/graphics/src/text/editor.rs @@ -0,0 +1,327 @@ +use crate::core::text::editor::{self, Action, Cursor}; +use crate::core::text::LineHeight; +use crate::core::{Font, Pixels, Point, Size}; +use crate::text; + +use cosmic_text::Edit; + +use std::fmt; +use std::sync::{self, Arc}; + +#[derive(Debug, PartialEq)] +pub struct Editor(Option>); + +struct Internal { + editor: cosmic_text::Editor, + font: Font, + bounds: Size, + min_bounds: Size, + version: text::Version, +} + +impl Editor { + pub fn new() -> Self { + Self::default() + } + + pub fn buffer(&self) -> &cosmic_text::Buffer { + &self.internal().editor.buffer() + } + + pub fn downgrade(&self) -> Weak { + let editor = self.internal(); + + Weak { + raw: Arc::downgrade(editor), + bounds: editor.bounds, + } + } + + fn internal(&self) -> &Arc { + self.0 + .as_ref() + .expect("editor should always be initialized") + } +} + +impl editor::Editor for Editor { + type Font = Font; + + fn with_text(text: &str) -> Self { + let mut buffer = cosmic_text::Buffer::new_empty(cosmic_text::Metrics { + font_size: 1.0, + line_height: 1.0, + }); + + buffer.set_text( + text::font_system() + .write() + .expect("Write font system") + .raw(), + text, + cosmic_text::Attrs::new(), + cosmic_text::Shaping::Advanced, + ); + + Editor(Some(Arc::new(Internal { + editor: cosmic_text::Editor::new(buffer), + ..Default::default() + }))) + } + + fn cursor(&self) -> editor::Cursor { + let internal = self.internal(); + + match internal.editor.select_opt() { + Some(selection) => { + // TODO + Cursor::Selection(vec![]) + } + None => { + let cursor = internal.editor.cursor(); + let buffer = internal.editor.buffer(); + + let lines_before_cursor: usize = buffer + .lines + .iter() + .take(cursor.line) + .map(|line| { + line.layout_opt() + .as_ref() + .expect("Line layout should be cached") + .len() + }) + .sum(); + + let line = buffer + .lines + .get(cursor.line) + .expect("Cursor line should be present"); + + let layout = line + .layout_opt() + .as_ref() + .expect("Line layout should be cached"); + + let mut lines = layout.iter().enumerate(); + + let (subline, offset) = lines + .find_map(|(i, line)| { + let start = line + .glyphs + .first() + .map(|glyph| glyph.start) + .unwrap_or(0); + let end = line + .glyphs + .last() + .map(|glyph| glyph.end) + .unwrap_or(0); + + let is_cursor_after_start = start <= cursor.index; + + let is_cursor_before_end = match cursor.affinity { + cosmic_text::Affinity::Before => { + cursor.index <= end + } + cosmic_text::Affinity::After => cursor.index < end, + }; + + if is_cursor_after_start && is_cursor_before_end { + let offset = line + .glyphs + .iter() + .take_while(|glyph| cursor.index > glyph.start) + .map(|glyph| glyph.w) + .sum(); + + Some((i, offset)) + } else { + None + } + }) + .unwrap_or((0, 0.0)); + + let line_height = buffer.metrics().line_height; + + let scroll_offset = buffer.scroll() as f32 * line_height; + + Cursor::Caret(Point::new( + offset, + (lines_before_cursor + subline) as f32 * line_height + - scroll_offset, + )) + } + } + } + + fn perform(&mut self, action: Action) { + let mut font_system = + text::font_system().write().expect("Write font system"); + + let editor = + self.0.take().expect("Editor should always be initialized"); + + // TODO: Handle multiple strong references somehow + let mut internal = Arc::try_unwrap(editor) + .expect("Editor cannot have multiple strong references"); + + let editor = &mut internal.editor; + + let mut act = |action| editor.action(font_system.raw(), action); + + match action { + Action::MoveLeft => act(cosmic_text::Action::Left), + Action::MoveRight => act(cosmic_text::Action::Right), + Action::MoveUp => act(cosmic_text::Action::Up), + Action::MoveDown => act(cosmic_text::Action::Down), + Action::Insert(c) => act(cosmic_text::Action::Insert(c)), + Action::Backspace => act(cosmic_text::Action::Backspace), + Action::Delete => act(cosmic_text::Action::Delete), + Action::Click(position) => act(cosmic_text::Action::Click { + x: position.x as i32, + y: position.y as i32, + }), + Action::Drag(position) => act(cosmic_text::Action::Drag { + x: position.x as i32, + y: position.y as i32, + }), + _ => todo!(), + } + + editor.shape_as_needed(font_system.raw()); + + self.0 = Some(Arc::new(internal)); + } + + fn bounds(&self) -> Size { + self.internal().bounds + } + + fn min_bounds(&self) -> Size { + self.internal().min_bounds + } + + fn update( + &mut self, + new_bounds: Size, + new_font: Font, + new_size: Pixels, + new_line_height: LineHeight, + ) { + let editor = + self.0.take().expect("editor should always be initialized"); + + let mut internal = Arc::try_unwrap(editor) + .expect("Editor cannot have multiple strong references"); + + let mut font_system = + text::font_system().write().expect("Write font system"); + + let mut changed = false; + + if new_font != internal.font { + for line in internal.editor.buffer_mut().lines.iter_mut() { + let _ = line.set_attrs_list(cosmic_text::AttrsList::new( + text::to_attributes(new_font), + )); + } + + changed = true; + } + + let metrics = internal.editor.buffer().metrics(); + let new_line_height = new_line_height.to_absolute(new_size); + + if new_size.0 != metrics.font_size + || new_line_height.0 != metrics.line_height + { + internal.editor.buffer_mut().set_metrics( + font_system.raw(), + cosmic_text::Metrics::new(new_size.0, new_line_height.0), + ); + + changed = true; + } + + if new_bounds != internal.bounds { + internal.editor.buffer_mut().set_size( + font_system.raw(), + new_bounds.width, + new_bounds.height, + ); + + internal.bounds = new_bounds; + changed = true; + } + + if changed { + internal.min_bounds = text::measure(&internal.editor.buffer()); + } + + self.0 = Some(Arc::new(internal)); + } +} + +impl Default for Editor { + fn default() -> Self { + Self(Some(Arc::new(Internal::default()))) + } +} + +impl PartialEq for Internal { + fn eq(&self, other: &Self) -> bool { + self.font == other.font + && self.bounds == other.bounds + && self.min_bounds == other.min_bounds + && self.editor.buffer().metrics() == other.editor.buffer().metrics() + } +} + +impl Default for Internal { + fn default() -> Self { + Self { + editor: cosmic_text::Editor::new(cosmic_text::Buffer::new_empty( + cosmic_text::Metrics { + font_size: 1.0, + line_height: 1.0, + }, + )), + font: Font::default(), + bounds: Size::ZERO, + min_bounds: Size::ZERO, + version: text::Version::default(), + } + } +} + +impl fmt::Debug for Internal { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Internal") + .field("font", &self.font) + .field("bounds", &self.bounds) + .field("min_bounds", &self.min_bounds) + .finish() + } +} + +#[derive(Debug, Clone)] +pub struct Weak { + raw: sync::Weak, + pub bounds: Size, +} + +impl Weak { + pub fn upgrade(&self) -> Option { + self.raw.upgrade().map(Some).map(Editor) + } +} + +impl PartialEq for Weak { + fn eq(&self, other: &Self) -> bool { + match (self.raw.upgrade(), other.raw.upgrade()) { + (Some(p1), Some(p2)) => p1 == p2, + _ => false, + } + } +} -- cgit From 1455911b636f19810e12eeb12a6eed11c5244cfe Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Tue, 12 Sep 2023 15:03:23 +0200 Subject: Add `Enter` variant to `Action` in `text::Editor` --- graphics/src/text/editor.rs | 1 + 1 file changed, 1 insertion(+) (limited to 'graphics/src/text') diff --git a/graphics/src/text/editor.rs b/graphics/src/text/editor.rs index 53f63fea..b4d6819f 100644 --- a/graphics/src/text/editor.rs +++ b/graphics/src/text/editor.rs @@ -176,6 +176,7 @@ impl editor::Editor for Editor { Action::MoveUp => act(cosmic_text::Action::Up), Action::MoveDown => act(cosmic_text::Action::Down), Action::Insert(c) => act(cosmic_text::Action::Insert(c)), + Action::Enter => act(cosmic_text::Action::Enter), Action::Backspace => act(cosmic_text::Action::Backspace), Action::Delete => act(cosmic_text::Action::Delete), Action::Click(position) => act(cosmic_text::Action::Click { -- cgit From abab1448576fbfa4717b65cdf1455debf44f2df5 Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Tue, 12 Sep 2023 18:20:02 +0200 Subject: Return `Cursor::Caret` if selection matches cursor position in `Editor::cursor` --- graphics/src/text/editor.rs | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) (limited to 'graphics/src/text') diff --git a/graphics/src/text/editor.rs b/graphics/src/text/editor.rs index b4d6819f..7b0ddec1 100644 --- a/graphics/src/text/editor.rs +++ b/graphics/src/text/editor.rs @@ -72,15 +72,18 @@ impl editor::Editor for Editor { fn cursor(&self) -> editor::Cursor { let internal = self.internal(); + let cursor = internal.editor.cursor(); + let buffer = internal.editor.buffer(); + match internal.editor.select_opt() { - Some(selection) => { + Some(selection) + if cursor.line != selection.line + || cursor.index != selection.index => + { // TODO Cursor::Selection(vec![]) } - None => { - let cursor = internal.editor.cursor(); - let buffer = internal.editor.buffer(); - + _ => { let lines_before_cursor: usize = buffer .lines .iter() -- cgit From 4389ab9865d13e17ce3c66223d7c149437be692b Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Tue, 12 Sep 2023 18:27:30 +0200 Subject: Fix cursor offset with `Affinity::After` at the end of lines in `Editor::cursor` --- graphics/src/text/editor.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'graphics/src/text') diff --git a/graphics/src/text/editor.rs b/graphics/src/text/editor.rs index 7b0ddec1..b39e9831 100644 --- a/graphics/src/text/editor.rs +++ b/graphics/src/text/editor.rs @@ -143,7 +143,10 @@ impl editor::Editor for Editor { None } }) - .unwrap_or((0, 0.0)); + .unwrap_or(( + 0, + layout.last().map(|line| line.w).unwrap_or(0.0), + )); let line_height = buffer.metrics().line_height; -- cgit From a28ed825c1f48c61a655c5583eb207999e98f400 Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Tue, 12 Sep 2023 20:57:46 +0200 Subject: Fix subline positioning in `Editor::cursor` --- graphics/src/text/editor.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'graphics/src/text') diff --git a/graphics/src/text/editor.rs b/graphics/src/text/editor.rs index b39e9831..52a5d942 100644 --- a/graphics/src/text/editor.rs +++ b/graphics/src/text/editor.rs @@ -144,7 +144,7 @@ impl editor::Editor for Editor { } }) .unwrap_or(( - 0, + layout.len().saturating_sub(1), layout.last().map(|line| line.w).unwrap_or(0.0), )); -- cgit From 40eb648f1e1e2ceb2782eddacbbc966f44de6961 Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Wed, 13 Sep 2023 15:00:33 +0200 Subject: Implement `Cursor::Selection` calculation in `Editor::cursor` --- graphics/src/text/editor.rs | 118 ++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 115 insertions(+), 3 deletions(-) (limited to 'graphics/src/text') diff --git a/graphics/src/text/editor.rs b/graphics/src/text/editor.rs index 52a5d942..3544bde6 100644 --- a/graphics/src/text/editor.rs +++ b/graphics/src/text/editor.rs @@ -1,6 +1,6 @@ use crate::core::text::editor::{self, Action, Cursor}; use crate::core::text::LineHeight; -use crate::core::{Font, Pixels, Point, Size}; +use crate::core::{Font, Pixels, Point, Rectangle, Size, Vector}; use crate::text; use cosmic_text::Edit; @@ -80,8 +80,70 @@ impl editor::Editor for Editor { if cursor.line != selection.line || cursor.index != selection.index => { - // TODO - Cursor::Selection(vec![]) + let line_height = buffer.metrics().line_height; + let scroll_offset = buffer.scroll() as f32 * line_height; + + let (start, end) = if cursor < selection { + (cursor, selection) + } else { + (selection, cursor) + }; + + let visual_lines_before_start: usize = buffer + .lines + .iter() + .take(start.line) + .map(|line| { + line.layout_opt() + .as_ref() + .expect("Line layout should be cached") + .len() + }) + .sum(); + + let selected_lines = end.line - start.line + 1; + + let regions = buffer + .lines + .iter() + .skip(start.line) + .take(selected_lines) + .enumerate() + .flat_map(|(i, line)| { + highlight_line( + line, + if i == 0 { start.index } else { 0 }, + if i == selected_lines - 1 { + end.index + } else { + line.text().len() + }, + ) + }) + .enumerate() + .filter_map(|(visual_line, (x, width))| { + if width > 0.0 { + Some(Rectangle { + x, + width, + y: visual_line as f32 * line_height, + height: line_height, + }) + } else { + None + } + }) + .map(|region| { + region + + Vector::new( + 0.0, + visual_lines_before_start as f32 * line_height + + scroll_offset, + ) + }) + .collect(); + + Cursor::Selection(regions) } _ => { let lines_before_cursor: usize = buffer @@ -332,3 +394,53 @@ impl PartialEq for Weak { } } } + +fn highlight_line<'a>( + line: &'a cosmic_text::BufferLine, + from: usize, + to: usize, +) -> impl Iterator + 'a { + let layout = line + .layout_opt() + .as_ref() + .expect("Line layout should be cached"); + + layout.iter().map(move |visual_line| { + let start = visual_line + .glyphs + .first() + .map(|glyph| glyph.start) + .unwrap_or(0); + let end = visual_line + .glyphs + .last() + .map(|glyph| glyph.end) + .unwrap_or(0); + + let range = start.max(from)..end.min(to); + + if range.is_empty() { + (0.0, 0.0) + } else if range.start == start && range.end == end { + (0.0, visual_line.w) + } else { + let first_glyph = visual_line + .glyphs + .iter() + .position(|glyph| range.start <= glyph.start) + .unwrap_or(0); + + let mut glyphs = visual_line.glyphs.iter(); + + let x = + glyphs.by_ref().take(first_glyph).map(|glyph| glyph.w).sum(); + + let width: f32 = glyphs + .take_while(|glyph| range.end > glyph.start) + .map(|glyph| glyph.w) + .sum(); + + (x, width) + } + }) +} -- cgit From f4c51a96d50953d5fb6e9eb62194f226e2cbfd3c Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Wed, 13 Sep 2023 16:11:43 +0200 Subject: Introduce `Motion` concept in `core::text::editor` --- graphics/src/text/editor.rs | 106 ++++++++++++++++++++++++++++++++++---------- 1 file changed, 82 insertions(+), 24 deletions(-) (limited to 'graphics/src/text') diff --git a/graphics/src/text/editor.rs b/graphics/src/text/editor.rs index 3544bde6..747f3a80 100644 --- a/graphics/src/text/editor.rs +++ b/graphics/src/text/editor.rs @@ -1,4 +1,4 @@ -use crate::core::text::editor::{self, Action, Cursor}; +use crate::core::text::editor::{self, Action, Cursor, Motion}; use crate::core::text::LineHeight; use crate::core::{Font, Pixels, Point, Rectangle, Size, Vector}; use crate::text; @@ -76,10 +76,7 @@ impl editor::Editor for Editor { let buffer = internal.editor.buffer(); match internal.editor.select_opt() { - Some(selection) - if cursor.line != selection.line - || cursor.index != selection.index => - { + Some(selection) => { let line_height = buffer.metrics().line_height; let scroll_offset = buffer.scroll() as f32 * line_height; @@ -236,26 +233,87 @@ impl editor::Editor for Editor { let editor = &mut internal.editor; - let mut act = |action| editor.action(font_system.raw(), action); - match action { - Action::MoveLeft => act(cosmic_text::Action::Left), - Action::MoveRight => act(cosmic_text::Action::Right), - Action::MoveUp => act(cosmic_text::Action::Up), - Action::MoveDown => act(cosmic_text::Action::Down), - Action::Insert(c) => act(cosmic_text::Action::Insert(c)), - Action::Enter => act(cosmic_text::Action::Enter), - Action::Backspace => act(cosmic_text::Action::Backspace), - Action::Delete => act(cosmic_text::Action::Delete), - Action::Click(position) => act(cosmic_text::Action::Click { - x: position.x as i32, - y: position.y as i32, - }), - Action::Drag(position) => act(cosmic_text::Action::Drag { - x: position.x as i32, - y: position.y as i32, - }), - _ => todo!(), + // Motion events + Action::Move(motion) => { + if let Some(_selection) = editor.select_opt() { + editor.set_select_opt(None); + } else { + editor.action( + font_system.raw(), + match motion { + Motion::Left => cosmic_text::Action::Left, + Motion::Right => cosmic_text::Action::Right, + Motion::Up => cosmic_text::Action::Up, + Motion::Down => cosmic_text::Action::Down, + Motion::WordLeft => cosmic_text::Action::LeftWord, + Motion::WordRight => cosmic_text::Action::RightWord, + Motion::Home => cosmic_text::Action::Home, + Motion::End => cosmic_text::Action::End, + Motion::PageUp => cosmic_text::Action::PageUp, + Motion::PageDown => cosmic_text::Action::PageDown, + Motion::DocumentStart => { + cosmic_text::Action::BufferStart + } + Motion::DocumentEnd => { + cosmic_text::Action::BufferEnd + } + }, + ); + } + } + + // Selection events + Action::Select(_motion) => todo!(), + Action::SelectWord => todo!(), + Action::SelectLine => todo!(), + + // Editing events + Action::Insert(c) => { + editor + .action(font_system.raw(), cosmic_text::Action::Insert(c)); + } + Action::Enter => { + editor.action(font_system.raw(), cosmic_text::Action::Enter); + } + Action::Backspace => { + editor + .action(font_system.raw(), cosmic_text::Action::Backspace); + } + Action::Delete => { + editor.action(font_system.raw(), cosmic_text::Action::Delete); + } + + // Mouse events + Action::Click(position) => { + editor.action( + font_system.raw(), + cosmic_text::Action::Click { + x: position.x as i32, + y: position.y as i32, + }, + ); + } + Action::Drag(position) => { + editor.action( + font_system.raw(), + cosmic_text::Action::Drag { + x: position.x as i32, + y: position.y as i32, + }, + ); + + // Deselect if selection matches cursor position + if let Some(selection) = editor.select_opt() { + let cursor = editor.cursor(); + + if cursor.line == selection.line + && cursor.index == selection.index + { + editor.set_select_opt(None); + } + } + } } editor.shape_as_needed(font_system.raw()); -- cgit From f14ef7a6069cf45ae11261d7d20df6a5d7870dde Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Wed, 13 Sep 2023 16:31:56 +0200 Subject: Fix `clippy` lints --- graphics/src/text/editor.rs | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) (limited to 'graphics/src/text') diff --git a/graphics/src/text/editor.rs b/graphics/src/text/editor.rs index 747f3a80..d31ea390 100644 --- a/graphics/src/text/editor.rs +++ b/graphics/src/text/editor.rs @@ -25,7 +25,7 @@ impl Editor { } pub fn buffer(&self) -> &cosmic_text::Buffer { - &self.internal().editor.buffer() + self.internal().editor.buffer() } pub fn downgrade(&self) -> Weak { @@ -53,11 +53,11 @@ impl editor::Editor for Editor { line_height: 1.0, }); + let mut font_system = + text::font_system().write().expect("Write font system"); + buffer.set_text( - text::font_system() - .write() - .expect("Write font system") - .raw(), + font_system.raw(), text, cosmic_text::Attrs::new(), cosmic_text::Shaping::Advanced, @@ -65,6 +65,7 @@ impl editor::Editor for Editor { Editor(Some(Arc::new(Internal { editor: cosmic_text::Editor::new(buffer), + version: font_system.version(), ..Default::default() }))) } @@ -347,6 +348,14 @@ impl editor::Editor for Editor { let mut changed = false; + if font_system.version() != internal.version { + for line in internal.editor.buffer_mut().lines.iter_mut() { + line.reset(); + } + + changed = true; + } + if new_font != internal.font { for line in internal.editor.buffer_mut().lines.iter_mut() { let _ = line.set_attrs_list(cosmic_text::AttrsList::new( @@ -383,7 +392,7 @@ impl editor::Editor for Editor { } if changed { - internal.min_bounds = text::measure(&internal.editor.buffer()); + internal.min_bounds = text::measure(internal.editor.buffer()); } self.0 = Some(Arc::new(internal)); @@ -453,11 +462,11 @@ impl PartialEq for Weak { } } -fn highlight_line<'a>( - line: &'a cosmic_text::BufferLine, +fn highlight_line( + line: &cosmic_text::BufferLine, from: usize, to: usize, -) -> impl Iterator + 'a { +) -> impl Iterator + '_ { let layout = line .layout_opt() .as_ref() -- cgit From ab020383b9fd7f2cc15d145dd1a3c0870dc71d8b Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Thu, 14 Sep 2023 00:41:15 +0200 Subject: Fix scrolling offset for `Cursor::Selection` --- graphics/src/text/editor.rs | 74 +++++++++++++++++++-------------------------- 1 file changed, 31 insertions(+), 43 deletions(-) (limited to 'graphics/src/text') diff --git a/graphics/src/text/editor.rs b/graphics/src/text/editor.rs index d31ea390..c0f8d9d5 100644 --- a/graphics/src/text/editor.rs +++ b/graphics/src/text/editor.rs @@ -1,6 +1,6 @@ use crate::core::text::editor::{self, Action, Cursor, Motion}; use crate::core::text::LineHeight; -use crate::core::{Font, Pixels, Point, Rectangle, Size, Vector}; +use crate::core::{Font, Pixels, Point, Rectangle, Size}; use crate::text; use cosmic_text::Edit; @@ -78,29 +78,18 @@ impl editor::Editor for Editor { match internal.editor.select_opt() { Some(selection) => { - let line_height = buffer.metrics().line_height; - let scroll_offset = buffer.scroll() as f32 * line_height; - let (start, end) = if cursor < selection { (cursor, selection) } else { (selection, cursor) }; - let visual_lines_before_start: usize = buffer - .lines - .iter() - .take(start.line) - .map(|line| { - line.layout_opt() - .as_ref() - .expect("Line layout should be cached") - .len() - }) - .sum(); - + let line_height = buffer.metrics().line_height; let selected_lines = end.line - start.line + 1; + let visual_lines_offset = + visual_lines_offset(start.line, buffer); + let regions = buffer .lines .iter() @@ -124,37 +113,24 @@ impl editor::Editor for Editor { Some(Rectangle { x, width, - y: visual_line as f32 * line_height, + y: (visual_line as i32 + visual_lines_offset) + as f32 + * line_height, height: line_height, }) } else { None } }) - .map(|region| { - region - + Vector::new( - 0.0, - visual_lines_before_start as f32 * line_height - + scroll_offset, - ) - }) .collect(); Cursor::Selection(regions) } _ => { - let lines_before_cursor: usize = buffer - .lines - .iter() - .take(cursor.line) - .map(|line| { - line.layout_opt() - .as_ref() - .expect("Line layout should be cached") - .len() - }) - .sum(); + let line_height = buffer.metrics().line_height; + + let visual_lines_offset = + visual_lines_offset(cursor.line, buffer); let line = buffer .lines @@ -168,7 +144,7 @@ impl editor::Editor for Editor { let mut lines = layout.iter().enumerate(); - let (subline, offset) = lines + let (visual_line, offset) = lines .find_map(|(i, line)| { let start = line .glyphs @@ -208,14 +184,10 @@ impl editor::Editor for Editor { layout.last().map(|line| line.w).unwrap_or(0.0), )); - let line_height = buffer.metrics().line_height; - - let scroll_offset = buffer.scroll() as f32 * line_height; - Cursor::Caret(Point::new( offset, - (lines_before_cursor + subline) as f32 * line_height - - scroll_offset, + (visual_lines_offset + visual_line as i32) as f32 + * line_height, )) } } @@ -511,3 +483,19 @@ fn highlight_line( } }) } + +fn visual_lines_offset(line: usize, buffer: &cosmic_text::Buffer) -> i32 { + let visual_lines_before_start: usize = buffer + .lines + .iter() + .take(line) + .map(|line| { + line.layout_opt() + .as_ref() + .expect("Line layout should be cached") + .len() + }) + .sum(); + + visual_lines_before_start as i32 - buffer.scroll() +} -- cgit From e6c2db8a9312e3fe37f30f049d1fa497892f1a86 Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Thu, 14 Sep 2023 00:47:04 +0200 Subject: Fix `Cursor::Caret` position on lines that wrap on whitespace --- graphics/src/text/editor.rs | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) (limited to 'graphics/src/text') diff --git a/graphics/src/text/editor.rs b/graphics/src/text/editor.rs index c0f8d9d5..83d41c85 100644 --- a/graphics/src/text/editor.rs +++ b/graphics/src/text/editor.rs @@ -157,7 +157,7 @@ impl editor::Editor for Editor { .map(|glyph| glyph.end) .unwrap_or(0); - let is_cursor_after_start = start <= cursor.index; + let is_cursor_before_start = start > cursor.index; let is_cursor_before_end = match cursor.affinity { cosmic_text::Affinity::Before => { @@ -166,7 +166,17 @@ impl editor::Editor for Editor { cosmic_text::Affinity::After => cursor.index < end, }; - if is_cursor_after_start && is_cursor_before_end { + if is_cursor_before_start { + // Sometimes, the glyph we are looking for is right + // between lines. This can happen when a line wraps + // on a space. + // In that case, we can assume the cursor is at the + // end of the previous line. + // i is guaranteed to be > 0 because `start` is always + // 0 for the first line, so there is no way for the + // cursor to be before it. + Some((i - 1, layout[i - 1].w)) + } else if is_cursor_before_end { let offset = line .glyphs .iter() -- cgit From b24b94d82778733ddae1b824d0d7690afcec3056 Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Thu, 14 Sep 2023 14:18:49 +0200 Subject: Handle motions when a selection is present in `text::Editor` --- graphics/src/text/editor.rs | 70 ++++++++++++++++++++++++++++++--------------- 1 file changed, 47 insertions(+), 23 deletions(-) (limited to 'graphics/src/text') diff --git a/graphics/src/text/editor.rs b/graphics/src/text/editor.rs index 83d41c85..d88bcd1d 100644 --- a/graphics/src/text/editor.rs +++ b/graphics/src/text/editor.rs @@ -1,4 +1,4 @@ -use crate::core::text::editor::{self, Action, Cursor, Motion}; +use crate::core::text::editor::{self, Action, Cursor, Direction, Motion}; use crate::core::text::LineHeight; use crate::core::{Font, Pixels, Point, Rectangle, Size}; use crate::text; @@ -219,30 +219,37 @@ impl editor::Editor for Editor { match action { // Motion events Action::Move(motion) => { - if let Some(_selection) = editor.select_opt() { + if let Some(selection) = editor.select_opt() { + let cursor = editor.cursor(); + + let (left, right) = if cursor < selection { + (cursor, selection) + } else { + (selection, cursor) + }; + editor.set_select_opt(None); + + match motion { + // These motions are performed as-is even when a selection + // is present + Motion::Home + | Motion::End + | Motion::DocumentStart + | Motion::DocumentEnd => { + editor.action( + font_system.raw(), + motion_to_action(motion), + ); + } + // Other motions simply move the cursor to one end of the selection + _ => editor.set_cursor(match motion.direction() { + Direction::Left => left, + Direction::Right => right, + }), + } } else { - editor.action( - font_system.raw(), - match motion { - Motion::Left => cosmic_text::Action::Left, - Motion::Right => cosmic_text::Action::Right, - Motion::Up => cosmic_text::Action::Up, - Motion::Down => cosmic_text::Action::Down, - Motion::WordLeft => cosmic_text::Action::LeftWord, - Motion::WordRight => cosmic_text::Action::RightWord, - Motion::Home => cosmic_text::Action::Home, - Motion::End => cosmic_text::Action::End, - Motion::PageUp => cosmic_text::Action::PageUp, - Motion::PageDown => cosmic_text::Action::PageDown, - Motion::DocumentStart => { - cosmic_text::Action::BufferStart - } - Motion::DocumentEnd => { - cosmic_text::Action::BufferEnd - } - }, - ); + editor.action(font_system.raw(), motion_to_action(motion)); } } @@ -509,3 +516,20 @@ fn visual_lines_offset(line: usize, buffer: &cosmic_text::Buffer) -> i32 { visual_lines_before_start as i32 - buffer.scroll() } + +fn motion_to_action(motion: Motion) -> cosmic_text::Action { + match motion { + Motion::Left => cosmic_text::Action::Left, + Motion::Right => cosmic_text::Action::Right, + Motion::Up => cosmic_text::Action::Up, + Motion::Down => cosmic_text::Action::Down, + Motion::WordLeft => cosmic_text::Action::LeftWord, + Motion::WordRight => cosmic_text::Action::RightWord, + Motion::Home => cosmic_text::Action::Home, + Motion::End => cosmic_text::Action::End, + Motion::PageUp => cosmic_text::Action::PageUp, + Motion::PageDown => cosmic_text::Action::PageDown, + Motion::DocumentStart => cosmic_text::Action::BufferStart, + Motion::DocumentEnd => cosmic_text::Action::BufferEnd, + } +} -- cgit From edd591847599a3e47601646ce075cb5b71ea751b Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Thu, 14 Sep 2023 14:25:46 +0200 Subject: Implement motion selection in `text::Editor` --- graphics/src/text/editor.rs | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) (limited to 'graphics/src/text') diff --git a/graphics/src/text/editor.rs b/graphics/src/text/editor.rs index d88bcd1d..c6b2abd5 100644 --- a/graphics/src/text/editor.rs +++ b/graphics/src/text/editor.rs @@ -254,7 +254,26 @@ impl editor::Editor for Editor { } // Selection events - Action::Select(_motion) => todo!(), + Action::Select(motion) => { + let cursor = editor.cursor(); + + if editor.select_opt().is_none() { + editor.set_select_opt(Some(cursor)); + } + + editor.action(font_system.raw(), motion_to_action(motion)); + + // Deselect if selection matches cursor position + if let Some(selection) = editor.select_opt() { + let cursor = editor.cursor(); + + if cursor.line == selection.line + && cursor.index == selection.index + { + editor.set_select_opt(None); + } + } + } Action::SelectWord => todo!(), Action::SelectLine => todo!(), -- cgit From f7d66899f1ae087a87be5d084ec1ee9a03dd4ecc Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Thu, 14 Sep 2023 15:20:23 +0200 Subject: Implement `Action::SelectWord` in `text::Editor` --- graphics/src/text/editor.rs | 61 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 60 insertions(+), 1 deletion(-) (limited to 'graphics/src/text') diff --git a/graphics/src/text/editor.rs b/graphics/src/text/editor.rs index c6b2abd5..3fd2c4fe 100644 --- a/graphics/src/text/editor.rs +++ b/graphics/src/text/editor.rs @@ -274,7 +274,66 @@ impl editor::Editor for Editor { } } } - Action::SelectWord => todo!(), + Action::SelectWord => { + use unicode_segmentation::UnicodeSegmentation; + + let cursor = editor.cursor(); + + if let Some(line) = editor.buffer().lines.get(cursor.line) { + let (start, end) = + UnicodeSegmentation::unicode_word_indices(line.text()) + // Split words with dots + .flat_map(|(i, word)| { + word.split('.').scan(i, |current, word| { + let start = *current; + *current += word.len() + 1; + + Some((start, word)) + }) + }) + // Turn words into ranges + .map(|(i, word)| (i, i + word.len())) + // Find the word at cursor + .find(|&(start, end)| { + start <= cursor.index && cursor.index < end + }) + // Cursor is not in a word. Let's select its punctuation cluster. + .unwrap_or_else(|| { + let start = line.text()[..cursor.index] + .char_indices() + .rev() + .take_while(|(_, c)| { + c.is_ascii_punctuation() + }) + .map(|(i, _)| i) + .last() + .unwrap_or(cursor.index); + + let end = line.text()[cursor.index..] + .char_indices() + .skip_while(|(_, c)| { + c.is_ascii_punctuation() + }) + .map(|(i, _)| i + cursor.index) + .next() + .unwrap_or(cursor.index); + + (start, end) + }); + + if start != end { + editor.set_cursor(cosmic_text::Cursor { + index: start, + ..cursor + }); + + editor.set_select_opt(Some(cosmic_text::Cursor { + index: end, + ..cursor + })); + } + } + } Action::SelectLine => todo!(), // Editing events -- cgit From 8cad1d682a306071f1f03bff4e70196adc946491 Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Thu, 14 Sep 2023 15:23:20 +0200 Subject: Implement `Action::SelectLine` in `text::Editor` --- graphics/src/text/editor.rs | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) (limited to 'graphics/src/text') diff --git a/graphics/src/text/editor.rs b/graphics/src/text/editor.rs index 3fd2c4fe..8eec94c9 100644 --- a/graphics/src/text/editor.rs +++ b/graphics/src/text/editor.rs @@ -334,7 +334,24 @@ impl editor::Editor for Editor { } } } - Action::SelectLine => todo!(), + Action::SelectLine => { + let cursor = editor.cursor(); + + if let Some(line_length) = editor + .buffer() + .lines + .get(cursor.line) + .map(|line| line.text().len()) + { + editor + .set_cursor(cosmic_text::Cursor { index: 0, ..cursor }); + + editor.set_select_opt(Some(cosmic_text::Cursor { + index: line_length, + ..cursor + })); + } + } // Editing events Action::Insert(c) => { -- cgit From c7d02e24e6f8265c205a68bd97b2643d40ae30ee Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Thu, 14 Sep 2023 18:57:09 +0200 Subject: Remove `Editor::min_bounds` and use `bounds` instead --- graphics/src/text/editor.rs | 4 ---- 1 file changed, 4 deletions(-) (limited to 'graphics/src/text') diff --git a/graphics/src/text/editor.rs b/graphics/src/text/editor.rs index 8eec94c9..6d9e9bb6 100644 --- a/graphics/src/text/editor.rs +++ b/graphics/src/text/editor.rs @@ -410,10 +410,6 @@ impl editor::Editor for Editor { self.internal().bounds } - fn min_bounds(&self) -> Size { - self.internal().min_bounds - } - fn update( &mut self, new_bounds: Size, -- cgit From 3afac11784b9cedc7e6208e3bf1d0365e1f5e902 Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Thu, 14 Sep 2023 18:58:52 +0200 Subject: Remove `min_bounds` field in `graphics::text::Editor` --- graphics/src/text/editor.rs | 17 ----------------- 1 file changed, 17 deletions(-) (limited to 'graphics/src/text') diff --git a/graphics/src/text/editor.rs b/graphics/src/text/editor.rs index 6d9e9bb6..07a2d72a 100644 --- a/graphics/src/text/editor.rs +++ b/graphics/src/text/editor.rs @@ -15,7 +15,6 @@ struct Internal { editor: cosmic_text::Editor, font: Font, bounds: Size, - min_bounds: Size, version: text::Version, } @@ -426,14 +425,10 @@ impl editor::Editor for Editor { let mut font_system = text::font_system().write().expect("Write font system"); - let mut changed = false; - if font_system.version() != internal.version { for line in internal.editor.buffer_mut().lines.iter_mut() { line.reset(); } - - changed = true; } if new_font != internal.font { @@ -442,8 +437,6 @@ impl editor::Editor for Editor { text::to_attributes(new_font), )); } - - changed = true; } let metrics = internal.editor.buffer().metrics(); @@ -456,8 +449,6 @@ impl editor::Editor for Editor { font_system.raw(), cosmic_text::Metrics::new(new_size.0, new_line_height.0), ); - - changed = true; } if new_bounds != internal.bounds { @@ -468,11 +459,6 @@ impl editor::Editor for Editor { ); internal.bounds = new_bounds; - changed = true; - } - - if changed { - internal.min_bounds = text::measure(internal.editor.buffer()); } self.0 = Some(Arc::new(internal)); @@ -489,7 +475,6 @@ impl PartialEq for Internal { fn eq(&self, other: &Self) -> bool { self.font == other.font && self.bounds == other.bounds - && self.min_bounds == other.min_bounds && self.editor.buffer().metrics() == other.editor.buffer().metrics() } } @@ -505,7 +490,6 @@ impl Default for Internal { )), font: Font::default(), bounds: Size::ZERO, - min_bounds: Size::ZERO, version: text::Version::default(), } } @@ -516,7 +500,6 @@ impl fmt::Debug for Internal { f.debug_struct("Internal") .field("font", &self.font) .field("bounds", &self.bounds) - .field("min_bounds", &self.min_bounds) .finish() } } -- cgit From c6d0443627c22dcf1576303e5a426aa3622f1b7d Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Sat, 16 Sep 2023 15:27:25 +0200 Subject: Implement methods to query the contents of a `TextEditor` --- graphics/src/text/editor.rs | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) (limited to 'graphics/src/text') diff --git a/graphics/src/text/editor.rs b/graphics/src/text/editor.rs index 07a2d72a..1e375a25 100644 --- a/graphics/src/text/editor.rs +++ b/graphics/src/text/editor.rs @@ -69,6 +69,47 @@ impl editor::Editor for Editor { }))) } + fn line(&self, index: usize) -> Option<&str> { + self.buffer() + .lines + .get(index) + .map(cosmic_text::BufferLine::text) + } + + fn line_count(&self) -> usize { + self.buffer().lines.len() + } + + fn selection(&self) -> Option { + let internal = self.internal(); + + let cursor = internal.editor.cursor(); + let selection = internal.editor.select_opt()?; + + let (start, end) = if cursor < selection { + (cursor, selection) + } else { + (selection, cursor) + }; + + Some( + internal.editor.buffer().lines[start.line..=end.line] + .iter() + .enumerate() + .map(|(i, line)| { + if i == 0 { + &line.text()[start.index..] + } else if i == end.line - start.line { + &line.text()[..end.index] + } else { + line.text() + } + }) + .collect::>() + .join("\n"), + ) + } + fn cursor(&self) -> editor::Cursor { let internal = self.internal(); -- cgit From d051f21597bb333ac10183aaa3214a292e9aa365 Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Sat, 16 Sep 2023 15:40:16 +0200 Subject: Implement `Copy` and `Paste` actions for `text::Editor` --- graphics/src/text/editor.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) (limited to 'graphics/src/text') diff --git a/graphics/src/text/editor.rs b/graphics/src/text/editor.rs index 1e375a25..1890cb82 100644 --- a/graphics/src/text/editor.rs +++ b/graphics/src/text/editor.rs @@ -398,6 +398,17 @@ impl editor::Editor for Editor { editor .action(font_system.raw(), cosmic_text::Action::Insert(c)); } + Action::Paste(text) => { + editor.insert_string(&text, None); + + // TODO: Fix cosmic-text + // Cursor should be marked as moved after `insert_string`. + let cursor = editor.cursor(); + + editor + .buffer_mut() + .shape_until_cursor(font_system.raw(), cursor); + } Action::Enter => { editor.action(font_system.raw(), cosmic_text::Action::Enter); } -- cgit From c9dbccba468da683af2513535c40374da804aa60 Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Sat, 16 Sep 2023 16:27:02 +0200 Subject: Use fork of `cosmic-text` with some minor fixes --- graphics/src/text/editor.rs | 36 +----------------------------------- 1 file changed, 1 insertion(+), 35 deletions(-) (limited to 'graphics/src/text') diff --git a/graphics/src/text/editor.rs b/graphics/src/text/editor.rs index 1890cb82..a828a3bc 100644 --- a/graphics/src/text/editor.rs +++ b/graphics/src/text/editor.rs @@ -81,33 +81,7 @@ impl editor::Editor for Editor { } fn selection(&self) -> Option { - let internal = self.internal(); - - let cursor = internal.editor.cursor(); - let selection = internal.editor.select_opt()?; - - let (start, end) = if cursor < selection { - (cursor, selection) - } else { - (selection, cursor) - }; - - Some( - internal.editor.buffer().lines[start.line..=end.line] - .iter() - .enumerate() - .map(|(i, line)| { - if i == 0 { - &line.text()[start.index..] - } else if i == end.line - start.line { - &line.text()[..end.index] - } else { - line.text() - } - }) - .collect::>() - .join("\n"), - ) + self.internal().editor.copy_selection() } fn cursor(&self) -> editor::Cursor { @@ -400,14 +374,6 @@ impl editor::Editor for Editor { } Action::Paste(text) => { editor.insert_string(&text, None); - - // TODO: Fix cosmic-text - // Cursor should be marked as moved after `insert_string`. - let cursor = editor.cursor(); - - editor - .buffer_mut() - .shape_until_cursor(font_system.raw(), cursor); } Action::Enter => { editor.action(font_system.raw(), cosmic_text::Action::Enter); -- cgit From 76dc82e8e8b5201ec10f8d00d851c1decf998583 Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Sun, 17 Sep 2023 15:29:14 +0200 Subject: Draft `Highlighter` API --- graphics/src/text/editor.rs | 67 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) (limited to 'graphics/src/text') diff --git a/graphics/src/text/editor.rs b/graphics/src/text/editor.rs index a828a3bc..901b4295 100644 --- a/graphics/src/text/editor.rs +++ b/graphics/src/text/editor.rs @@ -1,4 +1,5 @@ use crate::core::text::editor::{self, Action, Cursor, Direction, Motion}; +use crate::core::text::highlighter::{self, Highlighter}; use crate::core::text::LineHeight; use crate::core::{Font, Pixels, Point, Rectangle, Size}; use crate::text; @@ -15,6 +16,7 @@ struct Internal { editor: cosmic_text::Editor, font: Font, bounds: Size, + topmost_line_changed: Option, version: text::Version, } @@ -433,6 +435,7 @@ impl editor::Editor for Editor { new_font: Font, new_size: Pixels, new_line_height: LineHeight, + new_highlighter: &mut impl Highlighter, ) { let editor = self.0.take().expect("editor should always be initialized"); @@ -479,6 +482,69 @@ impl editor::Editor for Editor { internal.bounds = new_bounds; } + if let Some(topmost_line_changed) = internal.topmost_line_changed.take() + { + new_highlighter.change_line(topmost_line_changed); + } + + self.0 = Some(Arc::new(internal)); + } + + fn highlight( + &mut self, + font: Self::Font, + highlighter: &mut H, + format_highlight: impl Fn(&H::Highlight) -> highlighter::Format, + ) { + let internal = self.internal(); + + let scroll = internal.editor.buffer().scroll(); + let visible_lines = internal.editor.buffer().visible_lines(); + let last_visible_line = (scroll + visible_lines - 1) as usize; + + let current_line = highlighter.current_line(); + + if current_line > last_visible_line { + return; + } + + let editor = + self.0.take().expect("editor should always be initialized"); + + let mut internal = Arc::try_unwrap(editor) + .expect("Editor cannot have multiple strong references"); + + let mut font_system = + text::font_system().write().expect("Write font system"); + + let attributes = text::to_attributes(font); + + for line in &mut internal.editor.buffer_mut().lines + [current_line..=last_visible_line] + { + let mut list = cosmic_text::AttrsList::new(attributes); + + for (range, highlight) in highlighter.highlight_line(line.text()) { + let format = format_highlight(&highlight); + + list.add_span( + range, + cosmic_text::Attrs { + color_opt: format.color.map(text::to_color), + ..if let Some(font) = format.font { + text::to_attributes(font) + } else { + attributes + } + }, + ); + } + + let _ = line.set_attrs_list(list); + } + + internal.editor.shape_as_needed(font_system.raw()); + self.0 = Some(Arc::new(internal)); } } @@ -508,6 +574,7 @@ impl Default for Internal { )), font: Font::default(), bounds: Size::ZERO, + topmost_line_changed: None, version: text::Version::default(), } } -- cgit From d3011992a76e83e12f74402c2ade616cdc7f1497 Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Sun, 17 Sep 2023 19:03:58 +0200 Subject: Implement basic syntax highlighting with `syntect` in `editor` example --- graphics/src/text/editor.rs | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) (limited to 'graphics/src/text') diff --git a/graphics/src/text/editor.rs b/graphics/src/text/editor.rs index 901b4295..58fcc3dc 100644 --- a/graphics/src/text/editor.rs +++ b/graphics/src/text/editor.rs @@ -447,17 +447,26 @@ impl editor::Editor for Editor { text::font_system().write().expect("Write font system"); if font_system.version() != internal.version { + log::trace!("Updating `FontSystem` of `Editor`..."); + for line in internal.editor.buffer_mut().lines.iter_mut() { line.reset(); } } if new_font != internal.font { + log::trace!("Updating font of `Editor`..."); + for line in internal.editor.buffer_mut().lines.iter_mut() { let _ = line.set_attrs_list(cosmic_text::AttrsList::new( text::to_attributes(new_font), )); } + + internal.font = new_font; + internal.topmost_line_changed = Some(0); + + internal.editor.shape_as_needed(font_system.raw()); } let metrics = internal.editor.buffer().metrics(); @@ -466,6 +475,8 @@ impl editor::Editor for Editor { if new_size.0 != metrics.font_size || new_line_height.0 != metrics.line_height { + log::trace!("Updating `Metrics` of `Editor`..."); + internal.editor.buffer_mut().set_metrics( font_system.raw(), cosmic_text::Metrics::new(new_size.0, new_line_height.0), @@ -473,6 +484,8 @@ impl editor::Editor for Editor { } if new_bounds != internal.bounds { + log::trace!("Updating size of `Editor`..."); + internal.editor.buffer_mut().set_size( font_system.raw(), new_bounds.width, @@ -484,6 +497,10 @@ impl editor::Editor for Editor { if let Some(topmost_line_changed) = internal.topmost_line_changed.take() { + log::trace!( + "Notifying highlighter of line change: {topmost_line_changed}" + ); + new_highlighter.change_line(topmost_line_changed); } @@ -497,10 +514,12 @@ impl editor::Editor for Editor { format_highlight: impl Fn(&H::Highlight) -> highlighter::Format, ) { let internal = self.internal(); + let buffer = internal.editor.buffer(); - let scroll = internal.editor.buffer().scroll(); - let visible_lines = internal.editor.buffer().visible_lines(); - let last_visible_line = (scroll + visible_lines - 1) as usize; + let scroll = buffer.scroll(); + let visible_lines = buffer.visible_lines(); + let last_visible_line = + ((scroll + visible_lines) as usize).min(buffer.lines.len()) - 1; let current_line = highlighter.current_line(); -- cgit From 23d00445ff1225b3e5ca99cb27966143cda8a2ce Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Sun, 17 Sep 2023 19:06:20 +0200 Subject: Use `saturating_sub` for `last_visible_line` in `text::Editor` --- graphics/src/text/editor.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'graphics/src/text') diff --git a/graphics/src/text/editor.rs b/graphics/src/text/editor.rs index 58fcc3dc..fbae287e 100644 --- a/graphics/src/text/editor.rs +++ b/graphics/src/text/editor.rs @@ -518,8 +518,9 @@ impl editor::Editor for Editor { let scroll = buffer.scroll(); let visible_lines = buffer.visible_lines(); - let last_visible_line = - ((scroll + visible_lines) as usize).min(buffer.lines.len()) - 1; + let last_visible_line = ((scroll + visible_lines) as usize) + .min(buffer.lines.len()) + .saturating_sub(1); let current_line = highlighter.current_line(); -- cgit From 2897986f2ded7318894a52572bec3d62754ebfaa Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Sun, 17 Sep 2023 19:27:51 +0200 Subject: Notify `Highlighter` of topmost line change --- graphics/src/text/editor.rs | 58 +++++++++++++++++++++++++++++++-------------- 1 file changed, 40 insertions(+), 18 deletions(-) (limited to 'graphics/src/text') diff --git a/graphics/src/text/editor.rs b/graphics/src/text/editor.rs index fbae287e..47c210bd 100644 --- a/graphics/src/text/editor.rs +++ b/graphics/src/text/editor.rs @@ -1,10 +1,12 @@ -use crate::core::text::editor::{self, Action, Cursor, Direction, Motion}; +use crate::core::text::editor::{ + self, Action, Cursor, Direction, Edit, Motion, +}; use crate::core::text::highlighter::{self, Highlighter}; use crate::core::text::LineHeight; use crate::core::{Font, Pixels, Point, Rectangle, Size}; use crate::text; -use cosmic_text::Edit; +use cosmic_text::Edit as _; use std::fmt; use std::sync::{self, Arc}; @@ -370,22 +372,42 @@ impl editor::Editor for Editor { } // Editing events - Action::Insert(c) => { - editor - .action(font_system.raw(), cosmic_text::Action::Insert(c)); - } - Action::Paste(text) => { - editor.insert_string(&text, None); - } - Action::Enter => { - editor.action(font_system.raw(), cosmic_text::Action::Enter); - } - Action::Backspace => { - editor - .action(font_system.raw(), cosmic_text::Action::Backspace); - } - Action::Delete => { - editor.action(font_system.raw(), cosmic_text::Action::Delete); + Action::Edit(edit) => { + match edit { + Edit::Insert(c) => { + editor.action( + font_system.raw(), + cosmic_text::Action::Insert(c), + ); + } + Edit::Paste(text) => { + editor.insert_string(&text, None); + } + Edit::Enter => { + editor.action( + font_system.raw(), + cosmic_text::Action::Enter, + ); + } + Edit::Backspace => { + editor.action( + font_system.raw(), + cosmic_text::Action::Backspace, + ); + } + Edit::Delete => { + editor.action( + font_system.raw(), + cosmic_text::Action::Delete, + ); + } + } + + let cursor = editor.cursor(); + let selection = editor.select_opt().unwrap_or(cursor); + + internal.topmost_line_changed = + Some(cursor.min(selection).line); } // Mouse events -- cgit From 86d396cf8bede8155bdd4a7d3f115a0108c67297 Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Sun, 17 Sep 2023 23:15:38 +0200 Subject: Avoid adding unnecessary spans when syntax highlighting --- graphics/src/text/editor.rs | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) (limited to 'graphics/src/text') diff --git a/graphics/src/text/editor.rs b/graphics/src/text/editor.rs index 47c210bd..95061c3c 100644 --- a/graphics/src/text/editor.rs +++ b/graphics/src/text/editor.rs @@ -569,17 +569,19 @@ impl editor::Editor for Editor { for (range, highlight) in highlighter.highlight_line(line.text()) { let format = format_highlight(&highlight); - list.add_span( - range, - cosmic_text::Attrs { - color_opt: format.color.map(text::to_color), - ..if let Some(font) = format.font { - text::to_attributes(font) - } else { - attributes - } - }, - ); + if format.color.is_some() || format.font.is_some() { + list.add_span( + range, + cosmic_text::Attrs { + color_opt: format.color.map(text::to_color), + ..if let Some(font) = format.font { + text::to_attributes(font) + } else { + attributes + } + }, + ); + } } let _ = line.set_attrs_list(list); -- cgit From d1440ceca6340d045e556eb05354c254881732f0 Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Mon, 18 Sep 2023 13:39:47 +0200 Subject: Find correct `last_visible_line` in `Editor::highlight` --- graphics/src/text/editor.rs | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) (limited to 'graphics/src/text') diff --git a/graphics/src/text/editor.rs b/graphics/src/text/editor.rs index 95061c3c..18c9b572 100644 --- a/graphics/src/text/editor.rs +++ b/graphics/src/text/editor.rs @@ -538,11 +538,27 @@ impl editor::Editor for Editor { let internal = self.internal(); let buffer = internal.editor.buffer(); - let scroll = buffer.scroll(); - let visible_lines = buffer.visible_lines(); - let last_visible_line = ((scroll + visible_lines) as usize) - .min(buffer.lines.len()) - .saturating_sub(1); + let mut window = buffer.scroll() + buffer.visible_lines(); + + let last_visible_line = buffer + .lines + .iter() + .enumerate() + .find_map(|(i, line)| { + let visible_lines = line + .layout_opt() + .as_ref() + .expect("Line layout should be cached") + .len() as i32; + + if window > visible_lines { + window -= visible_lines; + None + } else { + Some(i) + } + }) + .unwrap_or(buffer.lines.len()); let current_line = highlighter.current_line(); -- cgit From a01b123cec1b57a9100d56f567fcfbf91967b12f Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Mon, 18 Sep 2023 13:57:47 +0200 Subject: Shape as needed only in `update` during `layout` --- graphics/src/text/editor.rs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) (limited to 'graphics/src/text') diff --git a/graphics/src/text/editor.rs b/graphics/src/text/editor.rs index 18c9b572..59096e74 100644 --- a/graphics/src/text/editor.rs +++ b/graphics/src/text/editor.rs @@ -442,8 +442,6 @@ impl editor::Editor for Editor { } } - editor.shape_as_needed(font_system.raw()); - self.0 = Some(Arc::new(internal)); } @@ -487,8 +485,6 @@ impl editor::Editor for Editor { internal.font = new_font; internal.topmost_line_changed = Some(0); - - internal.editor.shape_as_needed(font_system.raw()); } let metrics = internal.editor.buffer().metrics(); @@ -526,6 +522,8 @@ impl editor::Editor for Editor { new_highlighter.change_line(topmost_line_changed); } + internal.editor.shape_as_needed(font_system.raw()); + self.0 = Some(Arc::new(internal)); } -- cgit From b5466f41ca33452fb0d4e8470856c027d3b26e39 Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Mon, 18 Sep 2023 13:58:39 +0200 Subject: Fix inconsistent `expect` messages in `text::editor` --- graphics/src/text/editor.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'graphics/src/text') diff --git a/graphics/src/text/editor.rs b/graphics/src/text/editor.rs index 59096e74..de1b998b 100644 --- a/graphics/src/text/editor.rs +++ b/graphics/src/text/editor.rs @@ -43,7 +43,7 @@ impl Editor { fn internal(&self) -> &Arc { self.0 .as_ref() - .expect("editor should always be initialized") + .expect("Editor should always be initialized") } } @@ -458,7 +458,7 @@ impl editor::Editor for Editor { new_highlighter: &mut impl Highlighter, ) { let editor = - self.0.take().expect("editor should always be initialized"); + self.0.take().expect("Editor should always be initialized"); let mut internal = Arc::try_unwrap(editor) .expect("Editor cannot have multiple strong references"); @@ -565,7 +565,7 @@ impl editor::Editor for Editor { } let editor = - self.0.take().expect("editor should always be initialized"); + self.0.take().expect("Editor should always be initialized"); let mut internal = Arc::try_unwrap(editor) .expect("Editor cannot have multiple strong references"); -- cgit From 61ef8f3249218b301d434d04c483ba70562c1df4 Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Mon, 18 Sep 2023 13:58:55 +0200 Subject: Update `version` properly when `FontSystem` changes in `text::editor` --- graphics/src/text/editor.rs | 3 +++ 1 file changed, 3 insertions(+) (limited to 'graphics/src/text') diff --git a/graphics/src/text/editor.rs b/graphics/src/text/editor.rs index de1b998b..4673fce3 100644 --- a/graphics/src/text/editor.rs +++ b/graphics/src/text/editor.rs @@ -472,6 +472,9 @@ impl editor::Editor for Editor { for line in internal.editor.buffer_mut().lines.iter_mut() { line.reset(); } + + internal.version = font_system.version(); + internal.topmost_line_changed = Some(0); } if new_font != internal.font { -- cgit From e7326f0af6f16cf2ff04fbac93bf296a044923f4 Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Mon, 18 Sep 2023 19:07:41 +0200 Subject: Flesh out the `editor` example a bit more --- graphics/src/text/editor.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) (limited to 'graphics/src/text') diff --git a/graphics/src/text/editor.rs b/graphics/src/text/editor.rs index 4673fce3..dfb91f34 100644 --- a/graphics/src/text/editor.rs +++ b/graphics/src/text/editor.rs @@ -221,6 +221,12 @@ impl editor::Editor for Editor { } } + fn cursor_position(&self) -> (usize, usize) { + let cursor = self.internal().editor.cursor(); + + (cursor.line, cursor.index) + } + fn perform(&mut self, action: Action) { let mut font_system = text::font_system().write().expect("Write font system"); @@ -559,7 +565,7 @@ impl editor::Editor for Editor { Some(i) } }) - .unwrap_or(buffer.lines.len()); + .unwrap_or(buffer.lines.len().saturating_sub(1)); let current_line = highlighter.current_line(); -- cgit From 4e757a26d0c1c58001f31cf0592131cd5ad886ad Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Tue, 19 Sep 2023 01:18:06 +0200 Subject: Implement `Scroll` action in `text::editor` --- graphics/src/text/editor.rs | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'graphics/src/text') diff --git a/graphics/src/text/editor.rs b/graphics/src/text/editor.rs index dfb91f34..a05312dc 100644 --- a/graphics/src/text/editor.rs +++ b/graphics/src/text/editor.rs @@ -446,6 +446,12 @@ impl editor::Editor for Editor { } } } + Action::Scroll { lines } => { + editor.action( + font_system.raw(), + cosmic_text::Action::Scroll { lines }, + ); + } } self.0 = Some(Arc::new(internal)); -- cgit From 625cd745f38215b1cb8f629cdc6d2fa41c9a739a Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Fri, 27 Oct 2023 05:04:14 +0200 Subject: Write documentation for the new text APIs --- graphics/src/text/cache.rs | 19 +++++++++++++++++++ graphics/src/text/editor.rs | 12 ++++++++++++ graphics/src/text/paragraph.rs | 14 ++++++++++++++ 3 files changed, 45 insertions(+) (limited to 'graphics/src/text') diff --git a/graphics/src/text/cache.rs b/graphics/src/text/cache.rs index 577c4687..b3293dd4 100644 --- a/graphics/src/text/cache.rs +++ b/graphics/src/text/cache.rs @@ -1,3 +1,4 @@ +//! Cache text. use crate::core::{Font, Size}; use crate::text; @@ -5,6 +6,7 @@ use rustc_hash::{FxHashMap, FxHashSet}; use std::collections::hash_map; use std::hash::{BuildHasher, Hash, Hasher}; +/// A store of recently used sections of text. #[allow(missing_debug_implementations)] #[derive(Default)] pub struct Cache { @@ -21,14 +23,17 @@ type HashBuilder = twox_hash::RandomXxHashBuilder64; type HashBuilder = std::hash::BuildHasherDefault; impl Cache { + /// Creates a new empty [`Cache`]. pub fn new() -> Self { Self::default() } + /// Gets the text [`Entry`] with the given [`KeyHash`]. pub fn get(&self, key: &KeyHash) -> Option<&Entry> { self.entries.get(key) } + /// Allocates a text [`Entry`] if it is not already present in the [`Cache`]. pub fn allocate( &mut self, font_system: &mut cosmic_text::FontSystem, @@ -88,6 +93,9 @@ impl Cache { (hash, self.entries.get_mut(&hash).unwrap()) } + /// Trims the [`Cache`]. + /// + /// This will clear the sections of text that have not been used since the last `trim`. pub fn trim(&mut self) { self.entries .retain(|key, _| self.recently_used.contains(key)); @@ -99,13 +107,20 @@ impl Cache { } } +/// A cache key representing a section of text. #[derive(Debug, Clone, Copy)] pub struct Key<'a> { + /// The content of the text. pub content: &'a str, + /// The size of the text. pub size: f32, + /// The line height of the text. pub line_height: f32, + /// The [`Font`] of the text. pub font: Font, + /// The bounds of the text. pub bounds: Size, + /// The shaping strategy of the text. pub shaping: text::Shaping, } @@ -123,10 +138,14 @@ impl Key<'_> { } } +/// The hash of a [`Key`]. pub type KeyHash = u64; +/// A cache entry. #[allow(missing_debug_implementations)] pub struct Entry { + /// The buffer of text, ready for drawing. pub buffer: cosmic_text::Buffer, + /// The minimum bounds of the text. pub min_bounds: Size, } diff --git a/graphics/src/text/editor.rs b/graphics/src/text/editor.rs index a05312dc..d5262ae8 100644 --- a/graphics/src/text/editor.rs +++ b/graphics/src/text/editor.rs @@ -1,3 +1,4 @@ +//! Draw and edit text. use crate::core::text::editor::{ self, Action, Cursor, Direction, Edit, Motion, }; @@ -11,6 +12,7 @@ use cosmic_text::Edit as _; use std::fmt; use std::sync::{self, Arc}; +/// A multi-line text editor. #[derive(Debug, PartialEq)] pub struct Editor(Option>); @@ -23,14 +25,21 @@ struct Internal { } impl Editor { + /// Creates a new empty [`Editor`]. pub fn new() -> Self { Self::default() } + /// Returns the buffer of the [`Editor`]. pub fn buffer(&self) -> &cosmic_text::Buffer { self.internal().editor.buffer() } + /// Creates a [`Weak`] reference to the [`Editor`]. + /// + /// This is useful to avoid cloning the [`Editor`] when + /// referential guarantees are unnecessary. For instance, + /// when creating a rendering tree. pub fn downgrade(&self) -> Weak { let editor = self.internal(); @@ -662,13 +671,16 @@ impl fmt::Debug for Internal { } } +/// A weak reference to an [`Editor`]. #[derive(Debug, Clone)] pub struct Weak { raw: sync::Weak, + /// The bounds of the [`Editor`]. pub bounds: Size, } impl Weak { + /// Tries to update the reference into an [`Editor`]. pub fn upgrade(&self) -> Option { self.raw.upgrade().map(Some).map(Editor) } diff --git a/graphics/src/text/paragraph.rs b/graphics/src/text/paragraph.rs index d0396e8e..ccfe4a61 100644 --- a/graphics/src/text/paragraph.rs +++ b/graphics/src/text/paragraph.rs @@ -1,3 +1,4 @@ +//! Draw paragraphs. use crate::core; use crate::core::alignment; use crate::core::text::{Hit, LineHeight, Shaping, Text}; @@ -7,6 +8,7 @@ use crate::text; use std::fmt; use std::sync::{self, Arc}; +/// A bunch of text. #[derive(Clone, PartialEq)] pub struct Paragraph(Option>); @@ -23,14 +25,21 @@ struct Internal { } impl Paragraph { + /// Creates a new empty [`Paragraph`]. pub fn new() -> Self { Self::default() } + /// Returns the buffer of the [`Paragraph`]. pub fn buffer(&self) -> &cosmic_text::Buffer { &self.internal().buffer } + /// Creates a [`Weak`] reference to the [`Paragraph`]. + /// + /// This is useful to avoid cloning the [`Editor`] when + /// referential guarantees are unnecessary. For instance, + /// when creating a rendering tree. pub fn downgrade(&self) -> Weak { let paragraph = self.internal(); @@ -269,15 +278,20 @@ impl Default for Internal { } } +/// A weak reference to a [`Paragraph`]. #[derive(Debug, Clone)] pub struct Weak { raw: sync::Weak, + /// The minimum bounds of the [`Paragraph`]. pub min_bounds: Size, + /// The horizontal alignment of the [`Paragraph`]. pub horizontal_alignment: alignment::Horizontal, + /// The vertical alignment of the [`Paragraph`]. pub vertical_alignment: alignment::Vertical, } impl Weak { + /// Tries to update the reference into a [`Paragraph`]. pub fn upgrade(&self) -> Option { self.raw.upgrade().map(Some).map(Paragraph) } -- cgit From 57f9024e89256ad3f99a3ab19bdc8524c1defa54 Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Fri, 27 Oct 2023 05:19:35 +0200 Subject: Fix intra-doc broken links --- graphics/src/text/paragraph.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'graphics/src/text') diff --git a/graphics/src/text/paragraph.rs b/graphics/src/text/paragraph.rs index ccfe4a61..4a08a8f4 100644 --- a/graphics/src/text/paragraph.rs +++ b/graphics/src/text/paragraph.rs @@ -37,7 +37,7 @@ impl Paragraph { /// Creates a [`Weak`] reference to the [`Paragraph`]. /// - /// This is useful to avoid cloning the [`Editor`] when + /// This is useful to avoid cloning the [`Paragraph`] when /// referential guarantees are unnecessary. For instance, /// when creating a rendering tree. pub fn downgrade(&self) -> Weak { -- cgit From 98e088e731e6fbd5b5035033ae61bda823ced988 Mon Sep 17 00:00:00 2001 From: dtzxporter Date: Tue, 12 Sep 2023 18:15:00 -0400 Subject: Migrate twox-hash -> xxhash_rust. Switch to Xxh3 for better performance. xxhash-rust is more maintained, built against `::core`, so no workaround for wasm is necessary. Switch to Xxh3 for better performance, which shows when loading/hashing image buffers. --- graphics/src/text/cache.rs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) (limited to 'graphics/src/text') diff --git a/graphics/src/text/cache.rs b/graphics/src/text/cache.rs index b3293dd4..7fb33567 100644 --- a/graphics/src/text/cache.rs +++ b/graphics/src/text/cache.rs @@ -16,11 +16,7 @@ pub struct Cache { hasher: HashBuilder, } -#[cfg(not(target_arch = "wasm32"))] -type HashBuilder = twox_hash::RandomXxHashBuilder64; - -#[cfg(target_arch = "wasm32")] -type HashBuilder = std::hash::BuildHasherDefault; +type HashBuilder = xxhash_rust::xxh3::Xxh3Builder; impl Cache { /// Creates a new empty [`Cache`]. -- cgit