From 6066d8277876fafa8b69e3db9ca3d1c61a7cd951 Mon Sep 17 00:00:00 2001 From: Daniel McNab <36049421+DJMcNab@users.noreply.github.com> Date: Tue, 3 Dec 2024 14:44:35 +0000 Subject: [PATCH] Update to upstream unbatched PlainEditor This is https://github.com/linebender/parley/pull/192 Follow-up with docs and line height --- Cargo.lock | 4 +- Cargo.toml | 3 +- masonry/src/text/editor.rs | 850 -------------------------------- masonry/src/text/mod.rs | 19 +- masonry/src/text/render_text.rs | 4 +- masonry/src/text/styleset.rs | 44 -- masonry/src/widget/label.rs | 8 +- masonry/src/widget/prose.rs | 2 + masonry/src/widget/text_area.rs | 138 +++--- masonry/src/widget/textbox.rs | 2 + 10 files changed, 105 insertions(+), 969 deletions(-) delete mode 100644 masonry/src/text/editor.rs delete mode 100644 masonry/src/text/styleset.rs diff --git a/Cargo.lock b/Cargo.lock index 01c15046b..1993c991a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1081,7 +1081,7 @@ dependencies = [ [[package]] name = "fontique" version = "0.2.0" -source = "git+https://github.com/linebender/parley?rev=c0d158b5d77c5726ed33fd3f2cbfcde95df374ef#c0d158b5d77c5726ed33fd3f2cbfcde95df374ef" +source = "git+https://github.com/linebender/parley?rev=dd778df2c4fcb984cd618dd0a46cc0d17970573c#dd778df2c4fcb984cd618dd0a46cc0d17970573c" dependencies = [ "core-foundation", "core-text", @@ -2510,7 +2510,7 @@ dependencies = [ [[package]] name = "parley" version = "0.2.0" -source = "git+https://github.com/linebender/parley?rev=c0d158b5d77c5726ed33fd3f2cbfcde95df374ef#c0d158b5d77c5726ed33fd3f2cbfcde95df374ef" +source = "git+https://github.com/linebender/parley?rev=dd778df2c4fcb984cd618dd0a46cc0d17970573c#dd778df2c4fcb984cd618dd0a46cc0d17970573c" dependencies = [ "accesskit", "fontique", diff --git a/Cargo.toml b/Cargo.toml index f1f6cd549..527e06abe 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -108,7 +108,8 @@ xilem_core = { version = "0.1.0", path = "xilem_core" } vello = "0.3" wgpu = "22.1.0" kurbo = "0.11.1" -parley = { git = "https://github.com/linebender/parley", rev = "c0d158b5d77c5726ed33fd3f2cbfcde95df374ef", features = [ +# https://github.com/linebender/parley/pull/192 +parley = { git = "https://github.com/linebender/parley", rev = "dd778df2c4fcb984cd618dd0a46cc0d17970573c", features = [ "accesskit", ] } peniko = "0.2.0" diff --git a/masonry/src/text/editor.rs b/masonry/src/text/editor.rs deleted file mode 100644 index eb0c33dc6..000000000 --- a/masonry/src/text/editor.rs +++ /dev/null @@ -1,850 +0,0 @@ -// Copyright 2020 the Xilem Authors and the Parley Authors -// SPDX-License-Identifier: Apache-2.0 - -// We need to be careful with contributions to this file, as we want them to get back to Parley. - -//! Import of Parley's `PlainEditor` as the version in Parley is insufficient for our needs. - -use core::{cmp::PartialEq, default::Default, fmt::Debug, ops::Range}; - -use accesskit::{Node, NodeId, TreeUpdate}; -use parley::layout::LayoutAccessibility; -use parley::{ - layout::{ - cursor::{Cursor, Selection}, - Affinity, Alignment, Layout, Line, - }, - style::Brush, - FontContext, LayoutContext, Rect, -}; -use std::{borrow::ToOwned, string::String, vec::Vec}; - -use super::styleset::StyleSet; - -/// Opaque representation of a generation. -/// -/// Obtained from [`PlainEditor::generation`]. -// Overflow handling: the generations are only compared, -// so wrapping is fine. This could only fail if exactly -// `u32::MAX` generations happen between drawing -// operations. This is implausible and so can be ignored. -#[derive(PartialEq, Eq, Default, Clone, Copy)] -pub struct Generation(u32); - -impl Generation { - /// Make it not what it currently is. - pub(crate) fn nudge(&mut self) { - self.0 = self.0.wrapping_add(1); - } -} - -/// Basic plain text editor with a single default style. -#[derive(Clone)] -pub struct PlainEditor -where - T: Brush + Clone + Debug + PartialEq + Default, -{ - default_style: StyleSet, - buffer: String, - layout: Layout, - layout_access: LayoutAccessibility, - selection: Selection, - /// Byte offsets of IME composing preedit text in the text buffer. - /// `None` if the IME is not currently composing. - compose: Option>, - width: Option, - scale: f32, - // Simple tracking of when the layout needs to be updated - // before it can be used for `Selection` calculations or - // for drawing. - // Not all operations on `PlainEditor` need to operate on a - // clean layout, and not all operations trigger a layout. - layout_dirty: bool, - // TODO: We could avoid redoing the full text layout if linebreaking or - // alignment were unchanged - // linebreak_dirty: bool, - // alignment_dirty: bool, - alignment: Alignment, - generation: Generation, -} - -impl PlainEditor -where - T: Brush, -{ - pub fn new(font_size: f32) -> Self { - Self { - default_style: StyleSet::new(font_size), - buffer: Default::default(), - layout: Default::default(), - layout_access: Default::default(), - selection: Default::default(), - compose: None, - width: None, - scale: 1.0, - layout_dirty: true, - alignment: Alignment::Start, - // We don't use the `default` value to start with, as our consumers - // will choose to use that as their initial value, but will probably need - // to redraw if they haven't already. - generation: Generation(1), - } - } -} - -/// The argument passed to the callback of [`PlainEditor::transact`], -/// on which the caller performs operations. -pub struct PlainEditorTxn<'a, T> -where - T: Brush + Clone + Debug + PartialEq + Default, -{ - editor: &'a mut PlainEditor, - font_cx: &'a mut FontContext, - layout_cx: &'a mut LayoutContext, -} - -impl PlainEditorTxn<'_, T> -where - T: Brush + Clone + Debug + PartialEq + Default, -{ - // --- MARK: Forced relayout --- - /// Insert at cursor, or replace selection. - pub fn insert_or_replace_selection(&mut self, s: &str) { - debug_assert!(!self.editor.is_composing()); - - self.editor - .replace_selection(self.font_cx, self.layout_cx, s); - } - - /// Delete the selection. - pub fn delete_selection(&mut self) { - debug_assert!(!self.editor.is_composing()); - - self.insert_or_replace_selection(""); - } - - /// Delete the selection or the next cluster (typical ‘delete’ behavior). - pub fn delete(&mut self) { - debug_assert!(!self.editor.is_composing()); - - if self.editor.selection.is_collapsed() { - // Upstream cluster range - if let Some(range) = self - .editor - .selection - .focus() - .logical_clusters(&self.editor.layout)[1] - .as_ref() - .map(|cluster| cluster.text_range()) - .and_then(|range| (!range.is_empty()).then_some(range)) - { - self.editor.buffer.replace_range(range, ""); - self.update_layout(); - } - } else { - self.delete_selection(); - } - } - - /// Delete the selection or up to the next word boundary (typical ‘ctrl + delete’ behavior). - pub fn delete_word(&mut self) { - debug_assert!(!self.editor.is_composing()); - - if self.editor.selection.is_collapsed() { - let focus = self.editor.selection.focus(); - let start = focus.index(); - let end = focus.next_logical_word(&self.editor.layout).index(); - if self.editor.text().get(start..end).is_some() { - self.editor.buffer.replace_range(start..end, ""); - self.update_layout(); - self.editor.set_selection( - Cursor::from_byte_index(&self.editor.layout, start, Affinity::Downstream) - .into(), - ); - } - } else { - self.delete_selection(); - } - } - - /// Delete the selection or the previous cluster (typical ‘backspace’ behavior). - pub fn backdelete(&mut self) { - debug_assert!(!self.editor.is_composing()); - - if self.editor.selection.is_collapsed() { - // Upstream cluster - if let Some(cluster) = self - .editor - .selection - .focus() - .logical_clusters(&self.editor.layout)[0] - .clone() - { - let range = cluster.text_range(); - let end = range.end; - let start = if cluster.is_hard_line_break() || cluster.is_emoji() { - // For newline sequences and emoji, delete the previous cluster - range.start - } else { - // Otherwise, delete the previous character - let Some((start, _)) = self - .editor - .text() - .get(..end) - .and_then(|str| str.char_indices().next_back()) - else { - return; - }; - start - }; - self.editor.buffer.replace_range(start..end, ""); - self.update_layout(); - self.editor.set_selection( - Cursor::from_byte_index(&self.editor.layout, start, Affinity::Downstream) - .into(), - ); - } - } else { - self.delete_selection(); - } - } - - /// Delete the selection or back to the previous word boundary (typical ‘ctrl + backspace’ behavior). - pub fn backdelete_word(&mut self) { - debug_assert!(!self.editor.is_composing()); - - if self.editor.selection.is_collapsed() { - let focus = self.editor.selection.focus(); - let end = focus.index(); - let start = focus.previous_logical_word(&self.editor.layout).index(); - if self.editor.text().get(start..end).is_some() { - self.editor.buffer.replace_range(start..end, ""); - self.update_layout(); - self.editor.set_selection( - Cursor::from_byte_index(&self.editor.layout, start, Affinity::Downstream) - .into(), - ); - } - } else { - self.delete_selection(); - } - } - - // --- MARK: IME --- - /// Set the IME preedit composing text. - /// - /// This starts composing. Composing is reset by calling [`PlainEditorTxn::clear_compose`]. - /// While composing, it is a logic error to call anything other than - /// [`PlainEditorTxn::set_compose`] or [`PlainEditorTxn::clear_compose`]. - /// - /// The preedit text replaces the current selection if this call starts composing. - /// - /// The selection is updated based on `cursor`, which contains the byte offsets relative to the - /// start of the preedit text. If `cursor` is `None`, the selection is collapsed to a caret in - /// front of the preedit text. - pub fn set_compose(&mut self, text: &str, cursor: Option<(usize, usize)>) { - debug_assert!(!text.is_empty()); - debug_assert!(cursor.map(|cursor| cursor.1 <= text.len()).unwrap_or(true)); - - let start = if let Some(preedit_range) = self.editor.compose.clone() { - self.editor - .buffer - .replace_range(preedit_range.clone(), text); - preedit_range.start - } else { - if self.editor.selection.is_collapsed() { - self.editor - .buffer - .insert_str(self.editor.selection.text_range().start, text); - } else { - self.editor - .buffer - .replace_range(self.editor.selection.text_range(), text); - } - self.editor.selection.text_range().start - }; - self.editor.compose = Some(start..start + text.len()); - self.update_layout(); - - if let Some(cursor) = cursor { - // Select the location indicated by the IME. - self.editor.set_selection(Selection::new( - self.editor.cursor_at(start + cursor.0), - self.editor.cursor_at(start + cursor.1), - )); - } else { - // IME indicates nothing is to be selected: collapse the selection to a - // caret just in front of the preedit. - self.editor - .set_selection(self.editor.cursor_at(start).into()); - } - } - - /// Stop IME composing. - /// - /// This removes the IME preedit text. - pub fn clear_compose(&mut self) { - if let Some(preedit_range) = self.editor.compose.clone() { - self.editor.buffer.replace_range(preedit_range.clone(), ""); - self.editor.compose = None; - self.update_layout(); - - self.editor - .set_selection(self.editor.cursor_at(preedit_range.start).into()); - } - } - - // --- MARK: Cursor Movement --- - /// Move the cursor to the cluster boundary nearest this point in the layout. - pub fn move_to_point(&mut self, x: f32, y: f32) { - debug_assert!(!self.editor.is_composing()); - - self.refresh_layout(); - self.editor - .set_selection(Selection::from_point(&self.editor.layout, x, y)); - } - - /// Move the cursor to a byte index. - /// - /// No-op if index is not a char boundary. - pub fn move_to_byte(&mut self, index: usize) { - debug_assert!(!self.editor.is_composing()); - - if self.editor.buffer.is_char_boundary(index) { - self.refresh_layout(); - self.editor - .set_selection(self.editor.cursor_at(index).into()); - } - } - - /// Move the cursor to the start of the buffer. - pub fn move_to_text_start(&mut self) { - debug_assert!(!self.editor.is_composing()); - - self.editor.set_selection(self.editor.selection.move_lines( - &self.editor.layout, - isize::MIN, - false, - )); - } - - /// Move the cursor to the start of the physical line. - pub fn move_to_line_start(&mut self) { - debug_assert!(!self.editor.is_composing()); - - self.editor - .set_selection(self.editor.selection.line_start(&self.editor.layout, false)); - } - - /// Move the cursor to the end of the buffer. - pub fn move_to_text_end(&mut self) { - debug_assert!(!self.editor.is_composing()); - - self.editor.set_selection(self.editor.selection.move_lines( - &self.editor.layout, - isize::MAX, - false, - )); - } - - /// Move the cursor to the end of the physical line. - pub fn move_to_line_end(&mut self) { - debug_assert!(!self.editor.is_composing()); - - self.editor - .set_selection(self.editor.selection.line_end(&self.editor.layout, false)); - } - - /// Move up to the closest physical cluster boundary on the previous line, preserving the horizontal position for repeated movements. - pub fn move_up(&mut self) { - debug_assert!(!self.editor.is_composing()); - - self.editor.set_selection( - self.editor - .selection - .previous_line(&self.editor.layout, false), - ); - } - - /// Move down to the closest physical cluster boundary on the next line, preserving the horizontal position for repeated movements. - pub fn move_down(&mut self) { - debug_assert!(!self.editor.is_composing()); - - self.editor - .set_selection(self.editor.selection.next_line(&self.editor.layout, false)); - } - - /// Move to the next cluster left in visual order. - pub fn move_left(&mut self) { - debug_assert!(!self.editor.is_composing()); - - self.editor.set_selection( - self.editor - .selection - .previous_visual(&self.editor.layout, false), - ); - } - - /// Move to the next cluster right in visual order. - pub fn move_right(&mut self) { - debug_assert!(!self.editor.is_composing()); - - self.editor.set_selection( - self.editor - .selection - .next_visual(&self.editor.layout, false), - ); - } - - /// Move to the next word boundary left. - pub fn move_word_left(&mut self) { - debug_assert!(!self.editor.is_composing()); - - self.editor.set_selection( - self.editor - .selection - .previous_visual_word(&self.editor.layout, false), - ); - } - - /// Move to the next word boundary right. - pub fn move_word_right(&mut self) { - debug_assert!(!self.editor.is_composing()); - - self.editor.set_selection( - self.editor - .selection - .next_visual_word(&self.editor.layout, false), - ); - } - - /// Select the whole buffer. - pub fn select_all(&mut self) { - debug_assert!(!self.editor.is_composing()); - - self.editor.set_selection( - Selection::from_byte_index(&self.editor.layout, 0_usize, Affinity::default()) - .move_lines(&self.editor.layout, isize::MAX, true), - ); - } - - /// Collapse selection into caret. - pub fn collapse_selection(&mut self) { - debug_assert!(!self.editor.is_composing()); - - self.editor.set_selection(self.editor.selection.collapse()); - } - - /// Move the selection focus point to the start of the buffer. - pub fn select_to_text_start(&mut self) { - debug_assert!(!self.editor.is_composing()); - - self.editor.set_selection(self.editor.selection.move_lines( - &self.editor.layout, - isize::MIN, - true, - )); - } - - /// Move the selection focus point to the start of the physical line. - pub fn select_to_line_start(&mut self) { - debug_assert!(!self.editor.is_composing()); - - self.editor - .set_selection(self.editor.selection.line_start(&self.editor.layout, true)); - } - - /// Move the selection focus point to the end of the buffer. - pub fn select_to_text_end(&mut self) { - debug_assert!(!self.editor.is_composing()); - - self.editor.set_selection(self.editor.selection.move_lines( - &self.editor.layout, - isize::MAX, - true, - )); - } - - /// Move the selection focus point to the end of the physical line. - pub fn select_to_line_end(&mut self) { - debug_assert!(!self.editor.is_composing()); - - self.editor - .set_selection(self.editor.selection.line_end(&self.editor.layout, true)); - } - - /// Move the selection focus point up to the nearest cluster boundary on the previous line, preserving the horizontal position for repeated movements. - pub fn select_up(&mut self) { - debug_assert!(!self.editor.is_composing()); - - self.editor.set_selection( - self.editor - .selection - .previous_line(&self.editor.layout, true), - ); - } - - /// Move the selection focus point down to the nearest cluster boundary on the next line, preserving the horizontal position for repeated movements. - pub fn select_down(&mut self) { - debug_assert!(!self.editor.is_composing()); - - self.editor - .set_selection(self.editor.selection.next_line(&self.editor.layout, true)); - } - - /// Move the selection focus point to the next cluster left in visual order. - pub fn select_left(&mut self) { - debug_assert!(!self.editor.is_composing()); - - self.editor.set_selection( - self.editor - .selection - .previous_visual(&self.editor.layout, true), - ); - } - - /// Move the selection focus point to the next cluster right in visual order. - pub fn select_right(&mut self) { - debug_assert!(!self.editor.is_composing()); - - self.editor - .set_selection(self.editor.selection.next_visual(&self.editor.layout, true)); - } - - /// Move the selection focus point to the next word boundary left. - pub fn select_word_left(&mut self) { - debug_assert!(!self.editor.is_composing()); - - self.editor.set_selection( - self.editor - .selection - .previous_visual_word(&self.editor.layout, true), - ); - } - - /// Move the selection focus point to the next word boundary right. - pub fn select_word_right(&mut self) { - debug_assert!(!self.editor.is_composing()); - - self.editor.set_selection( - self.editor - .selection - .next_visual_word(&self.editor.layout, true), - ); - } - - /// Select the word at the point. - pub fn select_word_at_point(&mut self, x: f32, y: f32) { - debug_assert!(!self.editor.is_composing()); - - self.refresh_layout(); - self.editor - .set_selection(Selection::word_from_point(&self.editor.layout, x, y)); - } - - /// Select the physical line at the point. - pub fn select_line_at_point(&mut self, x: f32, y: f32) { - debug_assert!(!self.editor.is_composing()); - - self.refresh_layout(); - let line = Selection::line_from_point(&self.editor.layout, x, y); - self.editor.set_selection(line); - } - - /// Move the selection focus point to the cluster boundary closest to point. - pub fn extend_selection_to_point(&mut self, x: f32, y: f32) { - debug_assert!(!self.editor.is_composing()); - - self.refresh_layout(); - // FIXME: This is usually the wrong way to handle selection extension for mouse moves, but not a regression. - self.editor.set_selection( - self.editor - .selection - .extend_to_point(&self.editor.layout, x, y), - ); - } - - /// Move the selection focus point to a byte index. - /// - /// No-op if index is not a char boundary. - pub fn extend_selection_to_byte(&mut self, index: usize) { - debug_assert!(!self.editor.is_composing()); - - if self.editor.buffer.is_char_boundary(index) { - self.refresh_layout(); - self.editor - .set_selection(self.editor.selection.extend(self.editor.cursor_at(index))); - } - } - - /// Select a range of byte indices - /// - /// No-op if either index is not a char boundary. - pub fn select_byte_range(&mut self, start: usize, end: usize) { - debug_assert!(!self.editor.is_composing()); - - if self.editor.buffer.is_char_boundary(start) && self.editor.buffer.is_char_boundary(end) { - self.refresh_layout(); - self.editor.set_selection(Selection::new( - self.editor.cursor_at(start), - self.editor.cursor_at(end), - )); - } - } - - pub fn select_from_accesskit(&mut self, selection: &accesskit::TextSelection) { - debug_assert!(!self.editor.is_composing()); - - self.refresh_layout(); - if let Some(selection) = Selection::from_access_selection( - selection, - &self.editor.layout, - &self.editor.layout_access, - ) { - self.editor.set_selection(selection); - } - } - - // --- MARK: Internal helpers --- - fn update_layout(&mut self) { - self.editor.update_layout(self.font_cx, self.layout_cx); - } - - fn refresh_layout(&mut self) { - self.editor.refresh_layout(self.font_cx, self.layout_cx); - } -} - -impl PlainEditor -where - T: Brush + Clone + Debug + PartialEq + Default, -{ - /// Run a series of [`PlainEditorTxn`] methods. - /// - /// This is a utility shorthand around [`transaction`](Self::transaction); - pub fn transact( - &mut self, - font_cx: &mut FontContext, - layout_cx: &mut LayoutContext, - callback: impl FnOnce(&mut PlainEditorTxn<'_, T>) -> R, - ) -> R { - let mut txn = self.transaction(font_cx, layout_cx); - callback(&mut txn) - } - - /// Run a series of [`PlainEditorTxn`] methods, updating the layout - /// if necessary. - /// - /// This is a utility shorthand to simplify methods which require the editor - /// and the provided contexts. - pub fn transaction<'txn>( - &'txn mut self, - font_cx: &'txn mut FontContext, - layout_cx: &'txn mut LayoutContext, - ) -> PlainEditorTxn<'txn, T> { - PlainEditorTxn { - editor: self, - font_cx, - layout_cx, - } - } - - /// Make a cursor at a given byte index - fn cursor_at(&self, index: usize) -> Cursor { - // TODO: Do we need to be non-dirty? - // FIXME: `Selection` should make this easier - if index >= self.buffer.len() { - Cursor::from_byte_index(&self.layout, self.buffer.len(), Affinity::Upstream) - } else { - Cursor::from_byte_index(&self.layout, index, Affinity::Downstream) - } - } - - fn replace_selection( - &mut self, - font_cx: &mut FontContext, - layout_cx: &mut LayoutContext, - s: &str, - ) { - let range = self.selection.text_range(); - let start = range.start; - if self.selection.is_collapsed() { - self.buffer.insert_str(start, s); - } else { - self.buffer.replace_range(range, s); - } - - self.update_layout(font_cx, layout_cx); - let new_index = start.saturating_add(s.len()); - let affinity = if s.ends_with("\n") { - Affinity::Downstream - } else { - Affinity::Upstream - }; - self.set_selection(Cursor::from_byte_index(&self.layout, new_index, affinity).into()); - } - - /// Update the selection, and nudge the `Generation` if something other than `h_pos` changed. - fn set_selection(&mut self, new_sel: Selection) { - if new_sel.focus() != self.selection.focus() || new_sel.anchor() != self.selection.anchor() - { - self.generation.nudge(); - } - - self.selection = new_sel; - } - - /// If the current selection is not collapsed, returns the text content of - /// that selection. - pub fn selected_text(&self) -> Option<&str> { - if !self.selection.is_collapsed() { - self.text().get(self.selection.text_range()) - } else { - None - } - } - - /// Get rectangles representing the selected portions of text. - pub fn selection_geometry(&self) -> Vec { - self.selection.geometry(&self.layout) - } - - /// Get a rectangle representing the current caret cursor position. - pub fn cursor_geometry(&self, size: f32) -> Option { - Some(self.selection.focus().geometry(&self.layout, size)) - } - - /// Get the lines from the `Layout`. - pub fn lines(&self) -> impl Iterator> + '_ + Clone { - self.layout.lines() - } - - /// Borrow the text content of the buffer. - pub fn text(&self) -> &str { - &self.buffer - } - - /// Get the current `Generation` of the layout, to decide whether to draw. - /// - /// You should store the generation the editor was at when you last drew it, and then redraw - /// when the generation is different (`Generation` is [`PartialEq`], so supports the equality `==` operation). - pub fn generation(&self) -> Generation { - self.generation - } - - /// Get the full read-only details from the layout - pub fn layout( - &mut self, - font_cx: &mut FontContext, - layout_cx: &mut LayoutContext, - ) -> &Layout { - self.refresh_layout(font_cx, layout_cx); - &self.layout - } - - /// Get the full read-only details from the layout, if valid. - pub fn get_layout(&self) -> Option<&Layout> { - if self.layout_dirty { - None - } else { - Some(&self.layout) - } - } - - /// Get the (potentially invalid) details from the layout. - pub fn layout_raw(&self) -> &Layout { - &self.layout - } - - /// Replace the whole text buffer. - pub fn set_text(&mut self, is: &str) { - self.buffer.clear(); - self.buffer.push_str(is); - self.layout_dirty = true; - } - - /// Set the width of the layout. - // TODO: If this is infinite, is the width used for alignnment the min width? - pub fn set_width(&mut self, width: Option) { - // Don't allow empty widths: - // https://github.com/linebender/parley/issues/186 - self.width = width.map(|width| if width > 10. { width } else { 10. }); - self.layout_dirty = true; - } - - /// Set the alignment of the layout. - pub fn set_alignment(&mut self, alignment: Alignment) { - self.alignment = alignment; - self.layout_dirty = true; - } - - /// Set the scale for the layout. - pub fn set_scale(&mut self, scale: f32) { - self.scale = scale; - self.layout_dirty = true; - } - - /// Set the default style for the layout. - pub fn edit_styles(&mut self) -> &mut StyleSet { - self.layout_dirty = true; - &mut self.default_style - } - - /// Update the layout if it is dirty. - fn refresh_layout(&mut self, font_cx: &mut FontContext, layout_cx: &mut LayoutContext) { - if self.layout_dirty { - self.update_layout(font_cx, layout_cx); - } - } - - /// Update the layout. - fn update_layout(&mut self, font_cx: &mut FontContext, layout_cx: &mut LayoutContext) { - let mut builder = layout_cx.ranged_builder(font_cx, &self.buffer, self.scale); - for prop in self.default_style.inner().values() { - builder.push_default(prop.to_owned()); - } - if let Some(ref preedit_range) = self.compose { - builder.push( - parley::style::StyleProperty::Underline(true), - preedit_range.clone(), - ); - } - self.layout = builder.build(&self.buffer); - self.layout.break_all_lines(self.width); - self.layout.align(self.width, self.alignment); - self.selection = self.selection.refresh(&self.layout); - self.layout_dirty = false; - self.generation.nudge(); - } - - /// Whether the editor is currently in IME composing mode. - pub fn is_composing(&self) -> bool { - self.compose.is_some() - } - - pub fn accessibility( - &mut self, - update: &mut TreeUpdate, - node: &mut Node, - next_node_id: impl FnMut() -> NodeId, - x_offset: f64, - y_offset: f64, - ) { - self.layout_access.build_nodes( - &self.buffer, - &self.layout, - update, - node, - next_node_id, - x_offset, - y_offset, - ); - if let Some(selection) = self - .selection - .to_access_selection(&self.layout, &self.layout_access) - { - node.set_text_selection(selection); - } - node.add_action(accesskit::Action::SetTextSelection); - } -} diff --git a/masonry/src/text/mod.rs b/masonry/src/text/mod.rs index 6e2377127..8ef98ed4c 100644 --- a/masonry/src/text/mod.rs +++ b/masonry/src/text/mod.rs @@ -10,11 +10,10 @@ //! //! All of these have the same set of global styling options, and can contain rich text -mod editor; +#![warn(missing_docs)] mod render_text; -mod styleset; -pub use editor::{Generation, PlainEditor, PlainEditorTxn}; +use parley::GenericFamily; pub use render_text::render_text; /// A reference counted string slice. @@ -23,9 +22,21 @@ pub use render_text::render_text; /// it cannot be mutated, but unlike `String` it can be cheaply cloned. pub type ArcStr = std::sync::Arc; +/// The Parley [`parley::Brush`] used within Masonry. +/// +/// This enables updating of brush details without performing relayouts; +/// the inner values are indexes into the `brushes` argument to [`render_text`]. #[derive(Clone, PartialEq, Default, Debug)] pub struct BrushIndex(pub usize); +/// A style property specialised for use within Masonry. pub type StyleProperty = parley::StyleProperty<'static, BrushIndex>; -pub type StyleSet = styleset::StyleSet; +/// A set of styles specialised for use within Masonry. +pub type StyleSet = parley::StyleSet; + +/// Applies the default text styles for Masonry into `styles`. +pub(crate) fn default_styles(styles: &mut StyleSet) { + styles.insert(StyleProperty::LineHeight(1.2)); + styles.insert(GenericFamily::SystemUi.into()); +} diff --git a/masonry/src/text/render_text.rs b/masonry/src/text/render_text.rs index c554aa228..748c663a0 100644 --- a/masonry/src/text/render_text.rs +++ b/masonry/src/text/render_text.rs @@ -11,12 +11,14 @@ use vello::Scene; use super::BrushIndex; /// A function that renders laid out glyphs to a [`Scene`]. +/// +/// The `BrushIndex` values of the runs are indices into `brushes`. pub fn render_text( scene: &mut Scene, transform: Affine, layout: &Layout, brushes: &[Brush], - // TODO: Should this be part of `BrushIndex`? + // TODO: Should this be part of `BrushIndex` (i.e. `brushes`)? hint: bool, ) { for line in layout.lines() { diff --git a/masonry/src/text/styleset.rs b/masonry/src/text/styleset.rs deleted file mode 100644 index ab2c237f6..000000000 --- a/masonry/src/text/styleset.rs +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2018 the Xilem Authors and the Druid Authors -// SPDX-License-Identifier: Apache-2.0 - -use std::{collections::HashMap, mem::Discriminant}; - -type StyleProperty = parley::StyleProperty<'static, Brush>; - -/// A set of Parley styles. -#[derive(Clone, Debug)] -pub struct StyleSet( - HashMap>, StyleProperty>, -); - -impl StyleSet { - pub fn new(font_size: f32) -> Self { - let mut this = Self(Default::default()); - this.insert(StyleProperty::FontSize(font_size)); - // Emulate: https://developer.mozilla.org/en-US/docs/Web/CSS/line-height#normal - // This is a more sensible default that Parley's default. - // We expect Parley to make a different choice here at some point? - this.insert(StyleProperty::LineHeight(1.2)); - this - } - - pub fn insert(&mut self, style: StyleProperty) -> Option> { - let discriminant = std::mem::discriminant(&style); - self.0.insert(discriminant, style) - } - - pub fn retain(&mut self, mut f: impl FnMut(&StyleProperty) -> bool) { - self.0.retain(|_, v| f(v)); - } - - pub fn remove( - &mut self, - property: Discriminant>, - ) -> Option> { - self.0.remove(&property) - } - - pub fn inner(&self) -> &HashMap>, StyleProperty> { - &self.0 - } -} diff --git a/masonry/src/widget/label.rs b/masonry/src/widget/label.rs index 30ab35a4e..41df90006 100644 --- a/masonry/src/widget/label.rs +++ b/masonry/src/widget/label.rs @@ -1,6 +1,8 @@ // Copyright 2019 the Xilem Authors and the Druid Authors // SPDX-License-Identifier: Apache-2.0 +#![warn(missing_docs)] + //! A label widget. use std::mem::Discriminant; @@ -14,7 +16,7 @@ use vello::kurbo::{Affine, Size}; use vello::peniko::{BlendMode, Brush}; use vello::Scene; -use crate::text::{render_text, ArcStr, BrushIndex, StyleProperty, StyleSet}; +use crate::text::{default_styles, render_text, ArcStr, BrushIndex, StyleProperty, StyleSet}; use crate::widget::WidgetMut; use crate::{ theme, AccessCtx, AccessEvent, BoxConstraints, EventCtx, LayoutCtx, PaintCtx, PointerEvent, @@ -83,11 +85,13 @@ impl Label { // This is written out fully to appease rust-analyzer; StyleProperty is imported but not recognised. /// To change the font size, use `with_style`, setting [`StyleProperty::FontSize`](parley::StyleProperty::FontSize). pub fn new(text: impl Into) -> Self { + let mut styles = StyleSet::new(theme::TEXT_SIZE_NORMAL); + default_styles(&mut styles); Self { text_layout: Layout::new(), accessibility: Default::default(), text: text.into(), - styles: StyleSet::new(theme::TEXT_SIZE_NORMAL), + styles, styles_changed: true, line_break_mode: LineBreaking::Overflow, alignment: Alignment::Start, diff --git a/masonry/src/widget/prose.rs b/masonry/src/widget/prose.rs index c43320903..66b15aa15 100644 --- a/masonry/src/widget/prose.rs +++ b/masonry/src/widget/prose.rs @@ -1,6 +1,8 @@ // Copyright 2018 the Xilem Authors and the Druid Authors // SPDX-License-Identifier: Apache-2.0 +#![warn(missing_docs)] + use accesskit::{Node, Role}; use smallvec::{smallvec, SmallVec}; use tracing::{trace_span, Span}; diff --git a/masonry/src/widget/text_area.rs b/masonry/src/widget/text_area.rs index eb3675c81..138964da3 100644 --- a/masonry/src/widget/text_area.rs +++ b/masonry/src/widget/text_area.rs @@ -1,13 +1,17 @@ // Copyright 2018 the Xilem Authors and the Druid Authors // SPDX-License-Identifier: Apache-2.0 +#![warn(missing_docs)] + use std::mem::Discriminant; use std::time::Instant; use crate::kurbo::{Affine, Point, Size}; -use crate::text::{render_text, Generation, PlainEditor}; +use crate::text::{default_styles, render_text}; use accesskit::{Node, NodeId, Role}; +use parley::editor::Generation; use parley::layout::Alignment; +use parley::PlainEditor; use smallvec::SmallVec; use tracing::{trace_span, Span}; use vello::kurbo::Vec2; @@ -131,6 +135,7 @@ impl TextArea { /// To change the font size, use `with_style`, setting [`StyleProperty::FontSize`](parley::StyleProperty::FontSize). pub fn new(text: &str) -> Self { let mut editor = PlainEditor::new(theme::TEXT_SIZE_NORMAL); + default_styles(editor.edit_styles()); editor.set_text(text); TextArea { editor, @@ -485,10 +490,10 @@ impl Widget for TextArea { let click_count = self.click_count; let cursor_pos = Point::new(state.position.x, state.position.y) - inner_origin; let (fctx, lctx) = ctx.text_contexts(); - self.editor.transact(fctx, lctx, |txn| match click_count { - 2 => txn.select_word_at_point(cursor_pos.x as f32, cursor_pos.y as f32), - 3 => txn.select_line_at_point(cursor_pos.x as f32, cursor_pos.y as f32), - _ => txn.move_to_point(cursor_pos.x as f32, cursor_pos.y as f32), + self.editor.drive(fctx, lctx, |drv| match click_count { + 2 => drv.select_word_at_point(cursor_pos.x as f32, cursor_pos.y as f32), + 3 => drv.select_line_at_point(cursor_pos.x as f32, cursor_pos.y as f32), + _ => drv.move_to_point(cursor_pos.x as f32, cursor_pos.y as f32), }); let new_generation = self.editor.generation(); @@ -504,8 +509,8 @@ impl Widget for TextArea { if !ctx.is_disabled() && ctx.has_pointer_capture() { let cursor_pos = Point::new(state.position.x, state.position.y) - inner_origin; let (fctx, lctx) = ctx.text_contexts(); - self.editor.transact(fctx, lctx, |txn| { - txn.extend_selection_to_point(cursor_pos.x as f32, cursor_pos.y as f32); + self.editor.drive(fctx, lctx, |drv| { + drv.extend_selection_to_point(cursor_pos.x as f32, cursor_pos.y as f32); }); let new_generation = self.editor.generation(); if new_generation != self.rendered_generation { @@ -547,7 +552,7 @@ impl Widget for TextArea { // if let Some(text) = self.editor.selected_text() { // let cb = ClipboardContext::new().unwrap(); // cb.set_text(text.to_owned()).ok(); - // self.editor.transact(fcx, lcx, |txn| txn.delete_selection()); + // self.editor.drive(fcx, lcx, |drv| drv.delete_selection()); // } // edited = true; } @@ -569,107 +574,107 @@ impl Widget for TextArea { // TODO: use clipboard_rs::{Clipboard, ClipboardContext}; // let cb = ClipboardContext::new().unwrap(); // let text = cb.get_text().unwrap_or_default(); - // self.editor.transact(fcx, lcx, |txn| txn.insert_or_replace_selection(&text)); + // self.editor.drive(fcx, lcx, |drv| drv.insert_or_replace_selection(&text)); // edited = true; } Key::Character(a) if action_mod && a.as_str().eq_ignore_ascii_case("a") => { - self.editor.transact(fctx, lctx, |txn| { + self.editor.drive(fctx, lctx, |drv| { if shift { - txn.collapse_selection(); + drv.collapse_selection(); } else { - txn.select_all(); + drv.select_all(); } }); } - Key::Named(NamedKey::ArrowLeft) => self.editor.transact(fctx, lctx, |txn| { + Key::Named(NamedKey::ArrowLeft) => self.editor.drive(fctx, lctx, |drv| { if action_mod { if shift { - txn.select_word_left(); + drv.select_word_left(); } else { - txn.move_word_left(); + drv.move_word_left(); } } else if shift { - txn.select_left(); + drv.select_left(); } else { - txn.move_left(); + drv.move_left(); } }), - Key::Named(NamedKey::ArrowRight) => self.editor.transact(fctx, lctx, |txn| { + Key::Named(NamedKey::ArrowRight) => self.editor.drive(fctx, lctx, |drv| { if action_mod { if shift { - txn.select_word_right(); + drv.select_word_right(); } else { - txn.move_word_right(); + drv.move_word_right(); } } else if shift { - txn.select_right(); + drv.select_right(); } else { - txn.move_right(); + drv.move_right(); } }), - Key::Named(NamedKey::ArrowUp) => self.editor.transact(fctx, lctx, |txn| { + Key::Named(NamedKey::ArrowUp) => self.editor.drive(fctx, lctx, |drv| { if shift { - txn.select_up(); + drv.select_up(); } else { - txn.move_up(); + drv.move_up(); } }), - Key::Named(NamedKey::ArrowDown) => self.editor.transact(fctx, lctx, |txn| { + Key::Named(NamedKey::ArrowDown) => self.editor.drive(fctx, lctx, |drv| { if shift { - txn.select_down(); + drv.select_down(); } else { - txn.move_down(); + drv.move_down(); } }), - Key::Named(NamedKey::Home) => self.editor.transact(fctx, lctx, |txn| { + Key::Named(NamedKey::Home) => self.editor.drive(fctx, lctx, |drv| { if action_mod { if shift { - txn.select_to_text_start(); + drv.select_to_text_start(); } else { - txn.move_to_text_start(); + drv.move_to_text_start(); } } else if shift { - txn.select_to_line_start(); + drv.select_to_line_start(); } else { - txn.move_to_line_start(); + drv.move_to_line_start(); } }), - Key::Named(NamedKey::End) => self.editor.transact(fctx, lctx, |txn| { + Key::Named(NamedKey::End) => self.editor.drive(fctx, lctx, |drv| { if action_mod { if shift { - txn.select_to_text_end(); + drv.select_to_text_end(); } else { - txn.move_to_text_end(); + drv.move_to_text_end(); } } else if shift { - txn.select_to_line_end(); + drv.select_to_line_end(); } else { - txn.move_to_line_end(); + drv.move_to_line_end(); } }), Key::Named(NamedKey::Delete) if EDITABLE => { - self.editor.transact(fctx, lctx, |txn| { + self.editor.drive(fctx, lctx, |drv| { if action_mod { - txn.delete_word(); + drv.delete_word(); } else { - txn.delete(); + drv.delete(); } }); edited = true; } Key::Named(NamedKey::Backspace) if EDITABLE => { - self.editor.transact(fctx, lctx, |txn| { + self.editor.drive(fctx, lctx, |drv| { if action_mod { - txn.backdelete_word(); + drv.backdelete_word(); } else { - txn.backdelete(); + drv.backdelete(); } }); edited = true; } Key::Named(NamedKey::Space) if EDITABLE => { self.editor - .transact(fctx, lctx, |txn| txn.insert_or_replace_selection(" ")); + .drive(fctx, lctx, |drv| drv.insert_or_replace_selection(" ")); edited = true; } Key::Named(NamedKey::Enter) => { @@ -678,7 +683,7 @@ impl Widget for TextArea { if multiline { let (fctx, lctx) = ctx.text_contexts(); self.editor - .transact(fctx, lctx, |txn| txn.insert_or_replace_selection("\n")); + .drive(fctx, lctx, |drv| drv.insert_or_replace_selection("\n")); edited = true; } else { ctx.submit_action(crate::Action::TextEntered(self.text().to_string())); @@ -693,7 +698,7 @@ impl Widget for TextArea { _ if EDITABLE => match &key_event.text { Some(text) => { self.editor - .transact(fctx, lctx, |txn| txn.insert_or_replace_selection(text)); + .drive(fctx, lctx, |drv| drv.insert_or_replace_selection(text)); edited = true; } None => { @@ -728,30 +733,30 @@ impl Widget for TextArea { let mut submit_text = None; match e { winit::event::Ime::Disabled => { - self.editor.transact(fctx, lctx, |txn| txn.clear_compose()); + self.editor.drive(fctx, lctx, |drv| drv.clear_compose()); } winit::event::Ime::Preedit(text, cursor) => { if text.is_empty() { - self.editor.transact(fctx, lctx, |txn| txn.clear_compose()); + self.editor.drive(fctx, lctx, |drv| drv.clear_compose()); } else { if !self.editor.is_composing() && self.editor.selected_text().is_some() { // The IME has started composing. Delete the current selection and // send a TextChange event with the selection removed, but without // the composing preedit text. - self.editor.transact(fctx, lctx, |txn| { - txn.delete_selection(); + self.editor.drive(fctx, lctx, |drv| { + drv.delete_selection(); }); submit_text = Some(self.text().to_string()); } self.editor - .transact(fctx, lctx, |txn| txn.set_compose(text, *cursor)); + .drive(fctx, lctx, |drv| drv.set_compose(text, *cursor)); } } winit::event::Ime::Commit(text) => { self.editor - .transact(fctx, lctx, |txn| txn.insert_or_replace_selection(text)); + .drive(fctx, lctx, |drv| drv.insert_or_replace_selection(text)); submit_text = Some(self.text().to_string()); } winit::event::Ime::Enabled => {} @@ -788,7 +793,7 @@ impl Widget for TextArea { if let Some(accesskit::ActionData::SetTextSelection(selection)) = &event.data { let (fctx, lctx) = ctx.text_contexts(); self.editor - .transact(fctx, lctx, |txn| txn.select_from_accesskit(selection)); + .drive(fctx, lctx, |drv| drv.select_from_accesskit(selection)); } } } @@ -850,14 +855,14 @@ impl Widget for TextArea { } fn paint(&mut self, ctx: &mut PaintCtx, scene: &mut Scene) { - let layout = if let Some(layout) = self.editor.get_layout() { + let layout = if let Some(layout) = self.editor.try_layout() { layout } else { debug_panic!("Widget `layout` should have happened before paint"); let (fctx, lctx) = ctx.text_contexts(); // The `layout` method takes `&mut self`, so we get borrow-checker errors if we return it from this block. - self.editor.layout(fctx, lctx); - self.editor.layout_raw() + self.editor.refresh_layout(fctx, lctx); + self.editor.try_layout().unwrap() }; let is_rtl = layout.is_rtl(); let origin = Vec2::new(self.padding.get_left(is_rtl), self.padding.top); @@ -902,15 +907,18 @@ impl Widget for TextArea { node.set_read_only(); } let (fctx, lctx) = ctx.text_contexts(); - let is_rtl = self.editor.layout(fctx, lctx).is_rtl(); + let layout = self.editor.layout(fctx, lctx); + let is_rtl = layout.is_rtl(); let origin = ctx.window_origin(); - self.editor.accessibility( - ctx.tree_update, - node, - || NodeId::from(WidgetId::next()), - origin.x + self.padding.get_left(is_rtl), - origin.y + self.padding.top, - ); + self.editor + .try_accessibility( + ctx.tree_update, + node, + || NodeId::from(WidgetId::next()), + origin.x + self.padding.get_left(is_rtl), + origin.y + self.padding.top, + ) + .expect("We just performed a layout"); } fn children_ids(&self) -> SmallVec<[WidgetId; 16]> { diff --git a/masonry/src/widget/textbox.rs b/masonry/src/widget/textbox.rs index a319494a5..d3a13630d 100644 --- a/masonry/src/widget/textbox.rs +++ b/masonry/src/widget/textbox.rs @@ -1,6 +1,8 @@ // Copyright 2018 the Xilem Authors and the Druid Authors // SPDX-License-Identifier: Apache-2.0 +#![warn(missing_docs)] + use accesskit::{Node, Role}; use smallvec::{smallvec, SmallVec}; use tracing::{trace_span, Span};