app: cherry-pick rune's pause and sound fixes onto the checkout

Rune comes from app/vendor/rune now, a checkout of 63ad0209 on branch
ported, carrying the four commits of upstream issues 1320 (a pause while
a clip is layered holds the layer's picture and time) and 1325 (a video's
sound is read ahead of the clock and leads it). Both were written against
eb9f1104 and ported across the refactors since. The faults are the first
two and the third in docs/rune-upstream.md; the app's workarounds in
review.rs stay until the fixes arrive upstream.
This commit is contained in:
vhaudiquet committed 2026-11-22 22:16:30 +01:00
1 parent 80fef698ce
commit 5bf262b82b
3795 files changed
+663463 -28

No files matched your search

+23
View File
@@ -0,0 +1,23 @@
[package]
name = "rune-edit"
version = "0.0.1"
edition.workspace = true
license.workspace = true
description = "Single and rich text-field editing, undo history, IME composition, HTML import/export, and key events for Rune."
[dependencies]
parley = { workspace = true, features = ["std"] }
rune-core = { workspace = true }
rune-text = { workspace = true }
serde_json = { workspace = true }
unicode-segmentation = { workspace = true }
zeroize = { workspace = true }
[target.'cfg(target_arch = "wasm32")'.dependencies]
js-sys = { workspace = true }
[dev-dependencies]
rune-text = { workspace = true, features = ["embedded-fonts"] }
[lints]
workspace = true
+250
View File
@@ -0,0 +1,250 @@
//! Where the arrows move a field's caret. Left and Right go by the text's logical order while it
//! runs only left to right, and across the line as it's drawn once it holds right-to-left runs,
//! as a browser's caret moves through mixed Arabic or Hebrew and Latin; a word back and forward
//! go by the text's order; Up and Down keep the column they started in.
use parley::{Affinity, Cursor, Layout};
use rune_text::Ink;
use super::{TextEdit, next_char, prev_char};
/// Where Up and Down aim: free, or the x (device px in the field's layout) a run of them keeps,
/// so a caret passing through a shorter line (or one of the other direction) comes back to its
/// column, as a browser's does. Any other key, an edit or a press lets it go.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub(crate) enum Column {
#[default]
Free,
Kept(f32),
}
impl Column {
pub(crate) fn goal(self) -> Option<f32> {
match self {
Column::Free => None,
Column::Kept(x) => Some(x),
}
}
}
/// A word back and forward in the text's order, by Unicode's word boundaries (UAX #29), as
/// browsers and Word step: `src/util/format.ts` stops at `src`, `util` and `format.ts`, a Persian
/// word joined by a zero-width non-joiner (`می‌شود`) is one word, and punctuation and spaces
/// between words are stepped over. A pill is one word.
impl TextEdit {
pub(super) fn prev_word(&self, i: usize) -> usize {
if self.is_masked() {
return 0;
}
let mut j = i.min(self.text.len());
loop {
if let Some(start) = self.pill_before(j) {
return start;
}
let Some((start, word)) = self.segment_before(j) else { return 0 };
if !word {
// A pill is one word: stepping back over the punctuation before it stops at
// its end, and the step after that takes the pill whole.
if self.pill_before(start).is_some() {
return start;
}
j = start;
continue;
}
// A word runs back to a pill's end at most.
let pill_end = self.marks.iter().filter(|m| m.mark.is_pill() && start < m.end && m.end < j).map(|m| m.end).max();
return pill_end.unwrap_or(start);
}
}
pub(super) fn next_word(&self, i: usize) -> usize {
if self.is_masked() {
return self.text.len();
}
let len = self.text.len();
let mut j = i.min(len);
// Off macOS a word forward ends at the next word's start, past the spaces and
// punctuation after it, as Chromium's (and Windows') Ctrl+Right does; on macOS at the
// word's end.
if !cfg!(target_os = "macos") {
match self.pill_after(j) {
Some(end) => j = end,
None => {
if let Some((end, true)) = self.segment_after(j) {
j = self.clip_to_pill_start(j, end);
}
}
}
while j < len && self.pill_after(j).is_none() {
match self.segment_after(j) {
Some((end, false)) => j = end,
_ => break,
}
}
return j;
}
loop {
if let Some(end) = self.pill_after(j) {
return end;
}
let Some((end, word)) = self.segment_after(j) else { return len };
if !word {
j = end;
continue;
}
return self.clip_to_pill_start(j, end);
}
}
/// The word-boundary segment ending at byte `j` (UAX #29, within its line; a line break is a
/// segment of its own): its start, and whether it's a word (holds a letter or digit).
fn segment_before(&self, j: usize) -> Option<(usize, bool)> {
use unicode_segmentation::UnicodeSegmentation;
if j == 0 {
return None;
}
let s = &self.text;
let line = s[..j].rfind('\n').map_or(0, |k| k + 1);
if line == j {
return Some((prev_char(s, j), false));
}
let (at, seg) = s[line..j].split_word_bound_indices().next_back()?;
Some((line + at, seg.chars().any(char::is_alphanumeric)))
}
/// The word-boundary segment starting at byte `j`: its end, and whether it's a word.
fn segment_after(&self, j: usize) -> Option<(usize, bool)> {
use unicode_segmentation::UnicodeSegmentation;
let s = &self.text;
if j >= s.len() {
return None;
}
let line = s[j..].find('\n').map_or(s.len(), |k| j + k);
if line == j {
return Some((next_char(s, j), false));
}
let seg = s[j..line].split_word_bounds().next()?;
Some((j + seg.len(), seg.chars().any(char::is_alphanumeric)))
}
/// `end`, or the start of a pill between `j` and it: a word runs up to a pill at most.
fn clip_to_pill_start(&self, j: usize, end: usize) -> usize {
self.marks.iter().filter(|m| m.mark.is_pill() && j < m.start && m.start < end).map(|m| m.start).min().unwrap_or(end)
}
}
/// How the arrows move through a field's text.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum CaretMotion {
/// By character or word in the text's order (only left-to-right runs, or a hidden secret).
Logical,
/// Across the line as drawn: the text holds right-to-left runs.
Visual,
}
impl CaretMotion {
pub(super) fn of(layout: &Layout<Ink>, hidden: bool) -> CaretMotion {
let bidi = layout.is_rtl() || layout.lines().any(|line| line.runs().any(|r| r.is_rtl()));
if bidi && !hidden { CaretMotion::Visual } else { CaretMotion::Logical }
}
}
/// Which way, and how far, one arrow press moves.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Arrow {
Left,
Right,
WordLeft,
WordRight,
}
/// Seeking the caret's next place across the drawn line. A caret between two runs has two
/// places, one per affinity: the seek tries the caret's own side, then the other when that one
/// is the line's end, and stops at the first that moves.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Seek {
/// Trying the caret's place on `side`; `then`, the other side, is still to try.
Try { side: Affinity, then: Option<Affinity> },
/// It moves to this display byte, on this side.
Found(usize, Affinity),
/// Neither place moves: the caret is at the line's edge that way.
Edge,
}
/// What trying one place gave.
enum Tried {
Moved(usize, Affinity),
Stayed,
}
fn step(state: Seek, event: Tried) -> Seek {
match (state, event) {
(Seek::Try { .. }, Tried::Moved(j, side)) => Seek::Found(j, side),
(Seek::Try { then: Some(side), .. }, Tried::Stayed) => Seek::Try { side, then: None },
(Seek::Try { then: None, .. }, Tried::Stayed) => Seek::Edge,
(done, _) => done,
}
}
/// Where an arrow press lands across the drawn line.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Landing {
/// On this display byte, on this side of it (where two runs meet, the byte has a place at
/// each).
At(usize, Affinity),
/// The caret is at the line's edge that way: it leaves the line the way its paragraph runs
/// (left out of a right-to-left line goes on to the next line), or stays at the text's end.
Edge,
}
/// Where `arrow` takes a caret at display byte `at` (on `side` of it) across `text` as drawn,
/// with the direction of the paragraph it's in; `None` where it moves in the text's order (a
/// paragraph of only left-to-right runs, or a `hidden` secret). A pill's isolate marks are
/// stops of their own that leave the caret on the same byte, so it steps on past them.
pub(super) fn visual_in(text: rune_text::TextFlow<'_>, at: usize, side: Affinity, arrow: Arrow, hidden: bool) -> Option<(Landing, rune_text::Flow)> {
let p = text.piece_at(at);
if CaretMotion::of(p.layout, hidden) == CaretMotion::Logical {
return None;
}
let (mut from, mut side) = (p.shaped(at), side);
for _ in 0..4 {
match visual(p.layout, from, side, arrow) {
Landing::At(j, s) if p.content(j) == at && j != from => (from, side) = (j, s),
Landing::At(j, s) => return Some((Landing::At(p.content(j), s), p.flow)),
Landing::Edge => return Some((Landing::Edge, p.flow)),
}
}
Some((Landing::Edge, p.flow))
}
/// Whether the cluster just `right` (else left) of the caret at display byte `at` (on `side`
/// of it) is a space the text runs on into that way: in a left-to-right run to the right, in a
/// right-to-left run to the left. A word forward goes on past it off macOS.
pub(super) fn space_ahead(text: rune_text::TextFlow<'_>, at: usize, side: Affinity, right: bool) -> bool {
let p = text.piece_at(at);
let c = Cursor::from_byte_index(p.layout, p.shaped(at), side);
c.visual_clusters(p.layout)[usize::from(right)].as_ref().is_some_and(|cl| cl.is_space_or_nbsp() && cl.is_rtl() != right)
}
/// Where `arrow` takes a caret at display byte `at`, on `side` of it, across `layout` as drawn.
fn visual(layout: &Layout<Ink>, at: usize, side: Affinity, arrow: Arrow) -> Landing {
let other = match side { Affinity::Downstream => Affinity::Upstream, Affinity::Upstream => Affinity::Downstream };
let mut state = Seek::Try { side, then: Some(other) };
loop {
state = match state {
Seek::Try { side, .. } => {
let c = Cursor::from_byte_index(layout, at, side);
let to = match arrow {
Arrow::Left => c.previous_visual(layout),
Arrow::Right => c.next_visual(layout),
Arrow::WordLeft => c.previous_visual_word(layout),
Arrow::WordRight => c.next_visual_word(layout),
};
let moved = to.index() != at || to.geometry(layout, 0.0).x0 != c.geometry(layout, 0.0).x0;
step(state, if moved { Tried::Moved(to.index(), to.affinity()) } else { Tried::Stayed })
}
Seek::Found(j, s) => return Landing::At(j, s),
Seek::Edge => return Landing::Edge,
};
}
}
+72
View File
@@ -0,0 +1,72 @@
//! Ctrl+Left Shift and Ctrl+Right Shift on Windows and Linux: a field's direction, as Notepad,
//! Word and Chrome set an edit control's. Ctrl and one Shift pressed together and released with
//! no other key between them set the field left to right (Left Shift) or right to left (Right
//! Shift), every line of it, aligned to that side at once, an empty field too. Ctrl+Shift+P and
//! the other shortcuts never set it: any other key while they're held disarms it. macOS has no
//! such gesture. The runtime steps the chord on every physical key (`direction_chord`), whoever
//! takes the key, so it works in any field.
use rune_text::Flow;
use super::{KeySide, Modifier, TextEdit};
/// The direction a field's lines read in.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub(crate) enum FieldDir {
/// As its text and the element give it.
#[default]
Natural,
/// Set by Ctrl+Shift: every line, whatever its words.
Forced(Flow),
}
/// How far the Ctrl+Shift chord has gone.
#[doc(hidden)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum DirChord {
#[default]
Idle,
/// Ctrl is down, nothing else.
Ctrl,
/// Ctrl and one Shift are down, nothing else: its release sets the direction.
Armed(KeySide),
}
/// One modifier key going down or up (`ctrl` and `shift` the flags after it): the next state,
/// and the direction a release sets.
#[doc(hidden)]
pub fn step_dir_chord(state: DirChord, modifier: Modifier, pressed: bool, ctrl: bool, shift: bool) -> (DirChord, Option<Flow>) {
use Modifier::*;
match (state, modifier, pressed) {
(_, _, _) if cfg!(target_os = "macos") => (DirChord::Idle, None),
(DirChord::Idle, ControlLeft | ControlRight, true) if !shift => (DirChord::Ctrl, None),
(DirChord::Ctrl, ShiftLeft, true) if ctrl => (DirChord::Armed(KeySide::Left), None),
(DirChord::Ctrl, ShiftRight, true) if ctrl => (DirChord::Armed(KeySide::Right), None),
// Shift first, then Ctrl, arms it too.
(DirChord::Idle, ControlLeft | ControlRight, true) => (DirChord::Idle, None),
(DirChord::Armed(side), ShiftLeft | ShiftRight | ControlLeft | ControlRight, false) => {
(DirChord::Idle, Some(if side == KeySide::Left { Flow::Ltr } else { Flow::Rtl }))
}
(DirChord::Armed(_), ShiftLeft | ShiftRight | ControlLeft | ControlRight, true) => (DirChord::Idle, None),
(DirChord::Ctrl, ControlLeft | ControlRight, false) => (DirChord::Idle, None),
(s @ DirChord::Ctrl, _, _) => (s, None),
_ => (DirChord::Idle, None),
}
}
impl TextEdit {
/// The direction Ctrl+Shift set, if it set one.
#[doc(hidden)]
pub fn forced_dir(&self) -> Option<Flow> {
match self.dir {
FieldDir::Natural => None,
FieldDir::Forced(flow) => Some(flow),
}
}
/// Sets every line's direction, as Ctrl+Shift does.
#[doc(hidden)]
pub fn force_dir(&mut self, flow: Flow) {
self.dir = FieldDir::Forced(flow);
}
}
+243
View File
@@ -0,0 +1,243 @@
//! What a [`TextEdit`] draws: the display text with any preedit spliced in, and the spans,
//! links, pills and blocks mapped onto it.
use super::*;
use rune_text::Span;
impl TextEdit {
/// Map a model byte range `start..end` (in `self.text`) onto `self.display().0` byte ranges,
/// shifting or splitting around any active IME `preedit` splice.
#[doc(hidden)]
pub fn map_range_to_display(&self, start: usize, end: usize) -> Vec<(u32, u32)> {
if self.is_masked() || start >= end {
return Vec::new();
}
let s = Self::clamp_char_boundary(&self.text, start);
let e = Self::clamp_char_boundary(&self.text, end);
if s >= e {
return Vec::new();
}
let Some((p, _)) = self.preedit() else {
return vec![(s as u32, e as u32)];
};
let (a, b) = self.range();
let del_len = b - a;
let ins_len = p.len();
if e <= a {
vec![(s as u32, e as u32)]
} else if s >= b {
vec![((s - del_len + ins_len) as u32, (e - del_len + ins_len) as u32)]
} else {
let mut out = Vec::new();
if s < a {
out.push((s as u32, a as u32));
}
if e > b {
out.push(((a + ins_len) as u32, (e - del_len + ins_len) as u32));
}
out
}
}
/// Build the [`Span`]s, strikethrough ranges, [`Link`]s, and per-line [`Block`]s for
/// `self.display()` so `text_input` renders inline marks, pending IME style, and blocks.
#[doc(hidden)]
pub fn rich_display_specs(
&self,
base_style: rune_core::tok::TextStyle,
style: RichStyle,
) -> (Vec<Span>, Vec<(u32, u32, Option<Color>)>, Vec<Link>, Vec<Block>) {
if self.secure {
return (Vec::new(), Vec::new(), Vec::new(), Vec::new());
}
let mut spans: Vec<Span> = Vec::new();
let mut strikes: Vec<(u32, u32, Option<Color>)> = Vec::new();
let mut links: Vec<Link> = Vec::new();
let push_mark_span = |r_start: u32,
r_end: u32,
mark: &Mark,
spans: &mut Vec<Span>,
strikes: &mut Vec<(u32, u32, Option<Color>)>,
links: &mut Vec<Link>| {
if r_start >= r_end {
return;
}
match mark {
Mark::Bold => {
spans.push(Span {
start: r_start,
end: r_end,
weight: Some((base_style.weight + 250.0).clamp(600.0, 900.0)),
..Span::default()
});
}
Mark::Italic => {
spans.push(Span {
start: r_start,
end: r_end,
italic: true,
..Span::default()
});
}
Mark::Underline => {
spans.push(Span {
start: r_start,
end: r_end,
underline: Some(Color::TRANSPARENT),
..Span::default()
});
}
Mark::Strike => {
strikes.push((r_start, r_end, None));
}
Mark::Code => {
spans.push(Span {
start: r_start,
end: r_end,
mono: true,
color: style.code_fg,
bg: Some(style.code_bg),
bg_pad: 2.0,
..Span::default()
});
}
Mark::Link(url) => {
spans.push(Span {
start: r_start,
end: r_end,
color: Some(style.link),
underline: Some(style.link.alpha(0.65)),
..Span::default()
});
links.push(Link::new(r_start as usize..r_end as usize, url.clone()));
}
// The chip and its colours come from `display_pills`.
Mark::Pill(_) => {}
}
};
for m in &self.marks {
for (ds, de) in self.map_range_to_display(m.start, m.end) {
push_mark_span(ds, de, &m.mark, &mut spans, &mut strikes, &mut links);
}
}
// If IME preedit is active, style the preedit range with `self.active_marks()` (which
// includes any pending typing style or inherited marks at the caret).
if let Some((p, _)) = self.preedit()
&& !p.is_empty()
{
let (a, _) = self.range();
let ps = a as u32;
let pe = (a + p.len()) as u32;
for m in self.active_marks().iter().filter(|m| !m.is_pill()) {
push_mark_span(ps, pe, m, &mut spans, &mut strikes, &mut links);
}
}
// Compute display blocks per `\n`-separated line of `display().0`, and add `mono: true`
// spans for any `Block::Code` lines.
let (disp_text, _) = self.display();
let display_blocks = self.display_blocks(&disp_text);
let mut line_start = 0usize;
let mut line_idx = 0usize;
for (i, b) in disp_text.bytes().enumerate() {
if b == b'\n' {
if display_blocks.get(line_idx) == Some(&Block::Code) && line_start < i {
spans.push(Span {
start: line_start as u32,
end: i as u32,
mono: true,
color: style.code_fg,
..Span::default()
});
}
line_start = i + 1;
line_idx += 1;
}
}
if display_blocks.get(line_idx) == Some(&Block::Code) && line_start < disp_text.len() {
spans.push(Span {
start: line_start as u32,
end: disp_text.len() as u32,
mono: true,
color: style.code_fg,
..Span::default()
});
}
(spans, strikes, links, display_blocks)
}
/// Each [`Mark::Pill`]'s byte range in `self.display().0`, with its id.
#[doc(hidden)]
pub fn display_pills(&self) -> Vec<(u32, u32, &str)> {
if self.secure {
return Vec::new();
}
if self.preedit().is_none() {
let t = &self.text;
return self
.marks
.iter()
.filter_map(|m| {
let id = m.mark.pill_id()?;
let s = Self::clamp_char_boundary(t, m.start);
let e = Self::clamp_char_boundary(t, m.end);
(s < e && e - s == m.end - m.start).then_some((s as u32, e as u32, id))
})
.collect();
}
self.marks
.iter()
.filter_map(|m| {
let id = m.mark.pill_id()?;
match self.map_range_to_display(m.start, m.end)[..] {
[(s, e)] if (e - s) as usize == m.end - m.start => Some((s, e, id)),
_ => None,
}
})
.collect()
}
fn display_blocks(&self, disp_text: &str) -> Vec<Block> {
let line_count = 1 + count_newlines(disp_text.as_bytes());
if self.blocks.is_empty() {
return vec![Block::Paragraph; line_count];
}
if self.preedit().is_none() {
let mut out = self.blocks.clone();
out.resize(line_count, Block::Paragraph);
return out;
}
let (a, b) = self.range();
let line_a = self.line_of_byte(a);
let line_b = self.line_of_byte(b);
let mut out = self.blocks.clone();
if line_b > line_a && line_b < out.len() {
out.drain(line_a + 1..=line_b);
}
out.resize(line_count, out.get(line_a).copied().unwrap_or(Block::Paragraph));
out
}
/// The text to lay out: committed text with any preedit spliced in at the caret, and the
/// byte range of the preedit within it.
pub fn display(&self) -> (String, Option<(usize, usize)>) {
if self.secure {
return (self.masked_display(), None);
}
match self.preedit() {
Some((p, _)) => {
let (a, b) = self.range();
let mut s = String::with_capacity(self.text.len() + p.len());
s.push_str(&self.text[..a]);
s.push_str(p);
s.push_str(&self.text[b..]);
(s, Some((a, a + p.len())))
}
None => (self.text.clone(), None),
}
}
}
+731
View File
@@ -0,0 +1,731 @@
//! Undo and redo for a [`TextEdit`]: each step the text it changed and the selection, marks and
//! blocks either side ([`Change`]), typing runs coalesced as Chromium's editor does ([`Run`],
//! [`step`]), undo groups, and a history bounded in steps and bytes that always keeps its newest
//! step, however large (a paste of a whole file can always be undone).
use std::collections::VecDeque;
use super::*;
pub(super) const HISTORY_STEPS: usize = 128;
pub(super) const HISTORY_BYTES: usize = 1024 * 1024;
#[derive(Clone, Debug, PartialEq)]
pub(super) struct Snapshot {
text: Arc<Wiped>,
anchor: usize,
focus: usize,
marks: Vec<MarkRange>,
blocks: Vec<Block>,
soft_breaks: Vec<u32>,
}
/// Whether a [`TextEdit::undo_group`] is open, and what its one step undoes to. Never cloned
/// or compared, so cloning or comparing a [`TextEdit`] mid-group stays clean.
#[derive(Default)]
pub(super) enum Group {
#[default]
Closed,
/// Open on a field that records: the document as the group began.
Open(Snapshot),
/// Open on a secure field, which records nothing.
Unrecorded,
}
impl Group {
pub(super) fn is_open(&self) -> bool {
!matches!(self, Group::Closed)
}
}
impl Clone for Group {
fn clone(&self) -> Self {
Group::Closed
}
}
impl PartialEq for Group {
fn eq(&self, _: &Self) -> bool {
true
}
}
/// Non-content-derived edit state. Never retain a fingerprint of a secret.
#[derive(Clone, Copy, Default)]
pub(super) struct EditedTag(pub(super) bool);
impl PartialEq for EditedTag {
fn eq(&self, _: &Self) -> bool {
true
}
}
/// What an edit that replaces some bytes starts from (`TextEdit::ranged`): those bytes, where
/// they were, the text's length and the rest of the document, and what the history said of it.
pub(super) struct Ranged {
meta: Meta,
at: usize,
removed: Wiped,
len: usize,
prior: Prior,
}
/// What the history says of the document an edit starts from: whether it leads there (else it's
/// dropped), whether its newest step ends there (so typing may join it), whether that document
/// is empty, and whether its selection was a caret.
#[derive(Clone, Copy)]
struct Prior {
leads: bool,
joins: bool,
empty: bool,
collapsed: bool,
}
/// What a document holds besides its text, either side of a [`Change`].
#[derive(Clone, Debug, PartialEq)]
pub(super) struct Meta {
anchor: usize,
focus: usize,
marks: Vec<MarkRange>,
blocks: Vec<Block>,
soft_breaks: Vec<u32>,
}
impl Meta {
fn of(s: &Snapshot) -> Meta {
Meta { anchor: s.anchor, focus: s.focus, marks: s.marks.clone(), blocks: s.blocks.clone(), soft_breaks: s.soft_breaks.clone() }
}
fn bytes(&self) -> usize {
self.marks.len() * std::mem::size_of::<MarkRange>() + self.blocks.len() * std::mem::size_of::<Block>() + self.soft_breaks.len() * std::mem::size_of::<u32>()
}
}
/// One undo step: text bytes `at..at + removed.len()` of the document before it became
/// `inserted`, and what the document held besides its text before and after. Its texts are
/// shared: a field cloned for a view and edited after copies none of them.
#[derive(Clone, Debug, PartialEq)]
pub(super) struct Change {
at: usize,
removed: Arc<Wiped>,
inserted: Arc<Wiped>,
/// The text's length before and after, to tell a document the app replaced from this one.
lens: [usize; 2],
before: Meta,
after: Meta,
}
impl Change {
fn bytes(&self) -> usize {
self.removed.len() + self.inserted.len() + self.before.bytes() + self.after.bytes()
}
/// The step from `before` to `after`.
fn between(before: &Snapshot, after: &Snapshot) -> Change {
Change::to_text(before, &after.text, Meta::of(after))
}
/// The step from `before` to text `b` with `after` besides.
fn to_text(before: &Snapshot, b: &str, after: Meta) -> Change {
let a = before.text.as_str();
let (at, removed, inserted) = diff(a, b);
Change {
at,
removed: shared(&a[at..at + removed]),
inserted: shared(&b[at..at + inserted]),
lens: [a.len(), b.len()],
before: Meta::of(before),
after,
}
}
/// Whether `text` is this step's document after it (`after`) or before it: its length, and
/// the bytes the step wrote there.
fn leads_to(&self, text: &str, after: bool) -> bool {
let (len, there) = if after { (self.lens[1], &self.inserted) } else { (self.lens[0], &self.removed) };
text.len() == len && text.get(self.at..self.at + there.len()) == Some(there.as_str())
}
/// The bytes of the document between this step and `next` that joining them reads: those
/// either step touched, and any between.
fn window(&self, next: &Change) -> (usize, usize) {
(self.at.min(next.at), (self.at + self.inserted.len()).max(next.at + next.removed.len()))
}
/// `next`, from this step's document after, folded into this step: one step from this one's
/// before to `next`'s after. `mid` is that document's bytes in `self.window(&next)`.
fn join(&mut self, mid: &str, next: Change) {
let (s, e) = self.window(&next);
let at = |i: usize| i - s;
let mut removed = String::with_capacity(e - s);
removed.push_str(&mid[..at(self.at)]);
removed.push_str(&self.removed);
removed.push_str(&mid[at(self.at + self.inserted.len())..]);
let mut inserted = String::with_capacity(e - s);
inserted.push_str(&mid[..at(next.at)]);
inserted.push_str(&next.inserted);
inserted.push_str(&mid[at((next.at + next.removed.len()).min(e))..]);
(self.at, self.removed, self.inserted) = (s, Arc::new(Wiped(removed)), Arc::new(Wiped(inserted)));
(self.lens[1], self.after) = (next.lens[1], next.after);
}
}
fn shared(s: &str) -> Arc<Wiped> {
Arc::new(Wiped(s.to_owned()))
}
/// An edit's undo step into history: joined to the open step when typing may join it, else a
/// step of its own; the oldest steps go to keep the history in its bounds, never the newest.
fn push_change(history: &mut Arc<History>, rich: bool, change: Change, prior: Prior, kind: EditKind, mid: impl FnOnce(usize, usize) -> String) {
// A rich contenteditable creates its first text node here; a plain field just types.
let into_empty = rich && prior.empty;
let h = Arc::make_mut(history);
if !prior.leads {
*h = History::default();
}
h.bytes -= h.redo.iter().map(Change::bytes).sum::<usize>();
h.redo.clear();
let record = step(&mut h.run, kind, into_empty);
if record == Record::Join
&& prior.collapsed
&& prior.joins
&& h.undo.back().is_some_and(|c| c.after == change.before)
{
let last = h.undo.back_mut().unwrap();
let (s, e) = last.window(&change);
h.bytes -= last.bytes();
last.join(&mid(s, e), change);
h.bytes += last.bytes();
} else {
h.bytes += change.bytes();
h.undo.push_back(change);
}
// The newest step stays, however large: it's the way back from what was just done.
while h.undo.len() > 1 && (h.undo.len() > HISTORY_STEPS || h.bytes > HISTORY_BYTES) {
h.bytes -= h.undo.pop_front().unwrap().bytes();
}
}
/// Where `a` and `b` differ: the byte both share up to (a character boundary), and how many
/// bytes of each follow before what they share at the end.
fn diff(a: &str, b: &str) -> (usize, usize, usize) {
let (x, y) = (a.as_bytes(), b.as_bytes());
let n = x.len().min(y.len());
// In blocks first: a long document's comparison is a few memcmps.
let mut pre = 0;
while pre + 4096 <= n && x[pre..pre + 4096] == y[pre..pre + 4096] { pre += 4096; }
while pre < n && x[pre] == y[pre] { pre += 1; }
while !a.is_char_boundary(pre) { pre -= 1; }
let room = n - pre;
let mut suf = 0;
while suf + 4096 <= room && x[x.len() - suf - 4096..x.len() - suf] == y[y.len() - suf - 4096..y.len() - suf] { suf += 4096; }
while suf < room && x[x.len() - 1 - suf] == y[y.len() - 1 - suf] { suf += 1; }
while !a.is_char_boundary(x.len() - suf) || !b.is_char_boundary(y.len() - suf) { suf -= 1; }
(pre, x.len() - pre - suf, y.len() - pre - suf)
}
// Rendering clones TextEdit. Share immutable history so a view never copies the undo stack.
#[doc(hidden)]
#[derive(Clone, Debug, Default, PartialEq)]
pub struct History {
pub(super) undo: VecDeque<Change>,
pub(super) redo: Vec<Change>,
pub(super) bytes: usize,
pub(super) run: Run,
}
/// The undo step the last edit leaves open for the next to join, as a browser's editor keeps
/// its typing command open. A caret move, a pointer selection, a focus change, undo, redo and
/// any edit but typing close it. Pauses and word boundaries don't: Chromium's textarea and
/// contenteditable undo a whole typing run in one step.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(super) enum Run {
#[default]
Closed,
/// Typed text or line breaks: more join; a deletion starts a new step.
Inserting,
/// Backspace or Delete: more deletions and typed text join.
Deleting,
}
/// What an edit is, for joining it to the open undo step.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum EditKind {
/// Typed text without a line break.
Text,
/// A typed line break (Return, Shift+Return).
LineBreak,
/// Backspace or Delete over a character or a selection.
Delete,
/// A word or line deleted at once (Ctrl+Backspace, Ctrl+K): always a new step, which
/// further deletions and typing join.
DeleteRun,
/// Paste, an IME commit, a pill, formatting: a step of its own.
Other,
}
/// Where an edit's change goes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Record {
/// Into the open step.
Join,
/// Into a new step.
Push,
}
/// Steps the open run with an edit of `kind`; `into_empty` when typed text lands in a field
/// that held nothing. The first character typed into an empty field is a step of its own, as
/// in OpenCode's composer (a contenteditable whose first input closes Chromium's typing step),
/// so undoing a typed message leaves that character, then empties the field.
pub(super) fn step(run: &mut Run, kind: EditKind, into_empty: bool) -> Record {
let (record, next) = match (*run, kind) {
(_, EditKind::Other) => (Record::Push, Run::Closed),
(_, EditKind::DeleteRun) | (Run::Closed | Run::Inserting, EditKind::Delete) => (Record::Push, Run::Deleting),
(Run::Deleting, EditKind::Delete) => (Record::Join, Run::Deleting),
(Run::Closed, EditKind::Text | EditKind::LineBreak) => (Record::Push, Run::Inserting),
(Run::Inserting | Run::Deleting, EditKind::Text | EditKind::LineBreak) => (Record::Join, Run::Inserting),
};
*run = if kind == EditKind::Text && into_empty { Run::Closed } else { next };
record
}
impl TextEdit {
/// Drop the undo and redo stacks, keeping text, marks, blocks, soft breaks and the selection
/// (after loading a sent message back into a composer to edit it, say).
pub fn clear_history(&mut self) {
self.history = Arc::default();
if self.group.is_open() {
self.sync_invariants();
self.group = self.group_from_here();
}
}
/// An undo group opened on the document as it is now.
pub(super) fn group_from_here(&self) -> Group {
if self.secure { Group::Unrecorded } else { Group::Open(self.snapshot_now()) }
}
/// Edits record undo steps: not on a secure field, and not inside an undo group, whose
/// edits become one step when it closes.
fn recording(&self) -> bool {
!self.secure && !self.group.is_open()
}
/// End a typing group on a pointer selection or focus change.
pub fn break_history_group(&mut self) {
if self.history.run != Run::Closed { Arc::make_mut(&mut self.history).run = Run::Closed; }
}
pub(super) fn snapshot_now(&self) -> Snapshot {
Snapshot {
text: Arc::new(Wiped(self.text.clone())),
anchor: self.anchor,
focus: self.focus,
marks: self.marks.clone(),
blocks: self.blocks.clone(),
soft_breaks: self.soft_breaks.clone(),
}
}
pub(super) fn snapshot(&self) -> Option<Snapshot> {
self.recording().then(|| self.snapshot_now())
}
/// Text bytes `at..at + len` become `with`, and the rest of the document `meta`.
fn restore(&mut self, (at, len, with): (usize, usize, &str), meta: &Meta) {
self.text.replace_range(at..at + len, with);
self.anchor = meta.anchor;
self.focus = meta.focus;
self.marks = meta.marks.clone();
self.blocks = meta.blocks.clone();
self.soft_breaks = meta.soft_breaks.clone();
self.typing = Typing::Inherited;
self.cancel_composition();
self.sync_invariants();
}
pub(super) fn record_change(&mut self, before: Option<Snapshot>, kind: EditKind) {
let Some(before) = before.filter(|_| self.recording()) else {
return;
};
// What the edit left, read in place: copying a long document to compare it costs more
// than the edit.
let after = self.meta_now();
if before.text.as_str() == self.text && before.marks == after.marks && before.blocks == after.blocks && before.soft_breaks == after.soft_breaks {
return;
}
let change = Change::to_text(&before, &self.text, after);
let prior = self.prior(&before.text, before.anchor == before.focus);
push_change(&mut self.history, self.rich, change, prior, kind, |s, e| before.text[s..e].to_owned());
}
/// What an edit replacing text bytes `a..b` starts from, for its undo step: those bytes and
/// what the document holds besides, not the whole text.
pub(super) fn ranged(&self, a: usize, b: usize) -> Option<Ranged> {
self.recording().then(|| Ranged {
meta: self.meta_now(),
at: a,
removed: Wiped(self.text[a..b].to_owned()),
len: self.text.len(),
prior: self.prior(&self.text, self.anchor == self.focus),
})
}
/// The undo step of an edit that replaced `before`'s bytes with `inserted`, the rest of the
/// text as it was.
pub(super) fn record_ranged(&mut self, before: Option<Ranged>, inserted: &str, kind: EditKind) {
let Some(r) = before.filter(|_| self.recording()) else {
return;
};
let after = self.meta_now();
if r.removed.as_str() == inserted && r.meta.marks == after.marks && r.meta.blocks == after.blocks && r.meta.soft_breaks == after.soft_breaks {
return;
}
// The bytes the replacement really changed, as a diff of the two documents finds them.
let (x, y) = (r.removed.as_bytes(), inserted.as_bytes());
let mut p = rune_text::common_start(x, y);
while !r.removed.is_char_boundary(p) || !inserted.is_char_boundary(p) { p -= 1; }
let room = x.len().min(y.len()) - p;
let mut q = rune_text::common_end(x, y).min(room);
while !r.removed.is_char_boundary(x.len() - q) || !inserted.is_char_boundary(y.len() - q) { q -= 1; }
let change = Change {
at: r.at + p,
removed: shared(&r.removed[p..x.len() - q]),
inserted: shared(&inserted[p..y.len() - q]),
lens: [r.len, self.text.len()],
before: r.meta,
after,
};
// The document before the edit, in the bytes a join reads: this text with the
// replacement taken back.
let text = &self.text;
let (at, removed, gone) = (r.at, r.removed.as_str(), inserted.len());
let mid = |s: usize, e: usize| {
let mut out = String::with_capacity(e - s);
out.push_str(&text[s.min(at)..e.min(at)]);
out.push_str(&removed[s.clamp(at, at + removed.len()) - at..e.clamp(at, at + removed.len()) - at]);
let (s, e) = (s.max(at + removed.len()), e.max(at + removed.len()));
out.push_str(&text[s - removed.len() + gone..e - removed.len() + gone]);
out
};
push_change(&mut self.history, self.rich, change, r.prior, kind, mid);
}
fn meta_now(&self) -> Meta {
Meta { anchor: self.anchor, focus: self.focus, marks: self.marks.clone(), blocks: self.blocks.clone(), soft_breaks: self.soft_breaks.clone() }
}
/// What the history says of the document `text` an edit starts from, before it records.
fn prior(&self, text: &str, collapsed: bool) -> Prior {
let h = &self.history;
Prior {
// Public model text may have been replaced by the app: a history that doesn't lead
// to the document this edit started from is dropped.
leads: match (h.redo.last(), h.undo.back()) {
(Some(c), _) => c.leads_to(text, false),
(None, Some(c)) => c.leads_to(text, true),
(None, None) => true,
},
joins: h.undo.back().is_some_and(|c| c.leads_to(text, true)),
empty: text.is_empty(),
collapsed,
}
}
/// Run `f`, whose edits become one undo step: one undo reverts all of them and one redo
/// restores them, with the selection from before the first and after the last. Groups
/// nest and flatten into the outermost. A group that changes nothing records no step, and
/// `undo` and `redo` do nothing inside one. Typing after the group starts a new step.
///
/// Picking a mention is one step, trailing space included:
///
/// ```
/// # use rune_edit::TextEdit;
/// let mut e = TextEdit::default();
/// e.insert("hi @ag");
/// e.undo_group(|e| {
/// e.replace_with_pill(3..6, "agent:1", "@agent");
/// e.insert(" ");
/// });
/// assert_eq!(e.text, "hi @agent ");
/// e.undo();
/// assert_eq!(e.text, "hi @ag");
/// ```
pub fn undo_group<R>(&mut self, f: impl FnOnce(&mut TextEdit) -> R) -> R {
if self.group.is_open() {
return f(self);
}
self.sync_invariants();
self.break_history_group();
self.group = self.group_from_here();
struct Reset<'a>(&'a mut TextEdit);
impl Drop for Reset<'_> {
fn drop(&mut self) {
self.0.group = Group::Closed;
}
}
let g = Reset(self);
let r = f(g.0);
let before = match std::mem::take(&mut g.0.group) {
Group::Open(baseline) => Some(baseline),
Group::Closed | Group::Unrecorded => None,
};
drop(g);
self.sync_invariants();
self.break_history_group();
self.record_change(before, EditKind::Other);
r
}
/// Undo one typing group or discrete edit. Active IME composition is cancelled first.
pub fn undo(&mut self) {
if !self.recording() { return; }
self.break_history_group();
if self.preedit().is_some() { self.cancel_composition(); return; }
let h = Arc::make_mut(&mut self.history);
let Some(change) = h.undo.pop_back() else { return };
// Public model text may have been replaced by the app. Never restore stale history.
if !change.leads_to(&self.text, true) { *h = History::default(); return; }
self.restore((change.at, change.inserted.len(), &change.removed), &change.before);
Arc::make_mut(&mut self.history).redo.push(change);
}
pub fn redo(&mut self) {
if !self.recording() { return; }
self.break_history_group();
if self.preedit().is_some() { self.cancel_composition(); return; }
let h = Arc::make_mut(&mut self.history);
let Some(change) = h.redo.pop() else { return };
if !change.leads_to(&self.text, false) { *h = History::default(); return; }
self.restore((change.at, change.removed.len(), &change.inserted), &change.after);
Arc::make_mut(&mut self.history).undo.push_back(change);
}
}
/// What a stored history looks like (`TextEdit::history_json`): version 2, each step a change;
/// version 1 stored the document before and after each step, and still reads.
const HISTORY_FORMAT: u64 = 2;
impl TextEdit {
/// How many steps undo and redo hold. A change says the history moved, for an app that
/// stores it ([`TextEdit::history_json`]) only when it has.
pub fn history_len(&self) -> (usize, usize) {
(self.history.undo.len(), self.history.redo.len())
}
/// The undo and redo history as JSON, for an app to keep past a restart and give back with
/// [`TextEdit::restore_history_json`]: the document's text as it is, and the newest steps,
/// at most `max_steps` of them and about `max_bytes` of changes between them (each step the
/// text it replaced and the selection, marks and blocks either side). The newest undo step
/// is always there, however large. `None` for a secure field, which records nothing, and for
/// an empty history.
pub fn history_json(&self, max_steps: usize, max_bytes: usize) -> Option<serde_json::Value> {
if self.secure || (self.history.undo.is_empty() && self.history.redo.is_empty()) {
return None;
}
let (mut steps, mut bytes) = (0, 0);
let mut fits = |c: &Change| {
steps += 1;
bytes += c.bytes();
steps <= max_steps && bytes <= max_bytes
};
// The newest undo step first: it's the way back from what was done last.
let newest = self.history.undo.back().map(|c| { fits(c); change_json(c) });
let redo: Vec<_> = self.history.redo.iter().rev().take_while(|c| fits(c)).map(change_json).collect();
let older = self.history.undo.len().saturating_sub(1);
let mut undo: Vec<_> = self.history.undo.iter().take(older).rev().take_while(|c| fits(c)).map(change_json).collect();
undo.reverse();
undo.extend(newest);
let redo: Vec<_> = redo.into_iter().rev().collect();
Some(serde_json::json!({ "v": HISTORY_FORMAT, "d": self.text.as_str(), "undo": undo, "redo": redo }))
}
/// Takes back a history [`TextEdit::history_json`] wrote, when it leads to this document.
/// A history stored a few keystrokes before the document was (an app stores it less often
/// than the text) gets one more step, from the document it was stored with to this one, so
/// the first undo goes back to where the stored history stood. Anything that doesn't fit (a
/// step whose text or offsets aren't in its document) is left out and the field keeps no
/// history. Reads version 1 too. Returns whether it was taken.
pub fn restore_history_json(&mut self, v: &serde_json::Value) -> bool {
if self.secure || self.group.is_open() {
return false;
}
let Some((doc, mut undo, mut redo)) = (match v["v"].as_u64() {
Some(2) => read_v2(v),
Some(1) => read_v1(v),
_ => None,
}) else { return false };
if !chain_holds(&doc, &undo, &redo) {
return false;
}
self.sync_invariants();
let now = self.snapshot_now();
let same = |m: &Meta| *doc == now.text.as_str() && m.marks == now.marks && m.blocks == now.blocks && m.soft_breaks == now.soft_breaks;
let leads_here = undo.last().map(|c| &c.after).or_else(|| redo.last().map(|c| &c.before)).is_some_and(same);
if !leads_here {
let Some(last) = undo.last().map(|c| c.after.clone()) else { return false };
if *doc == now.text.as_str() {
return false;
}
redo.clear();
let stored = Snapshot { text: Arc::new(Wiped(doc.to_string())), anchor: last.anchor, focus: last.focus, marks: last.marks, blocks: last.blocks, soft_breaks: last.soft_breaks };
undo.push(Change::between(&stored, &now));
}
let mut h = History { undo: undo.into(), redo, bytes: 0, run: Run::Closed };
h.bytes = h.undo.iter().chain(h.redo.iter()).map(Change::bytes).sum();
while h.undo.len() > 1 && (h.undo.len() > HISTORY_STEPS || h.bytes > HISTORY_BYTES) {
let Some(c) = h.undo.pop_front() else { break };
h.bytes -= c.bytes();
}
self.history = Arc::new(h);
true
}
}
/// Version 2: the document as written, and each step's change.
fn read_v2(v: &serde_json::Value) -> Option<(Zeroizing<String>, Vec<Change>, Vec<Change>)> {
let doc = Zeroizing::new(v["d"].as_str()?.to_owned());
let read = |key: &str| -> Option<Vec<Change>> { v[key].as_array()?.iter().map(change_from).collect() };
Some((doc, read("undo")?, read("redo")?))
}
/// Version 1: each step the document before and after it; the document as written is the
/// newest undo step's after (or the next redo step's before).
fn read_v1(v: &serde_json::Value) -> Option<(Zeroizing<String>, Vec<Change>, Vec<Change>)> {
let read = |key: &str| -> Option<Vec<(Snapshot, Snapshot)>> {
v[key].as_array()?.iter().map(|c| Some((snapshot_from(&c["b"])?, snapshot_from(&c["a"])?))).collect()
};
let (undo, redo) = (read("undo")?, read("redo")?);
let doc = undo.last().map(|c| &c.1).or_else(|| redo.last().map(|c| &c.0))?.text.as_str().to_owned();
let change = |(b, a): &(Snapshot, Snapshot)| Change::between(b, a);
Some((Zeroizing::new(doc), undo.iter().map(change).collect(), redo.iter().map(change).collect()))
}
/// Whether `undo` leads back from `doc` step by step, and `redo` forward, every offset on a
/// character boundary of the document it's in.
fn chain_holds(doc: &str, undo: &[Change], redo: &[Change]) -> bool {
let mut text = doc.to_owned();
for c in undo.iter().rev() {
if !c.leads_to(&text, true) || !meta_holds(&c.after, &text) { return false; }
text.replace_range(c.at..c.at + c.inserted.len(), &c.removed);
if !meta_holds(&c.before, &text) { return false; }
}
text.clear();
text.push_str(doc);
for c in redo.iter().rev() {
if !c.leads_to(&text, false) || !meta_holds(&c.before, &text) { return false; }
text.replace_range(c.at..c.at + c.removed.len(), &c.inserted);
if !meta_holds(&c.after, &text) { return false; }
}
text.zeroize();
true
}
/// Whether `m`'s offsets are on character boundaries of `text`, its blocks one a line (or
/// none) and its soft breaks inside it.
fn meta_holds(m: &Meta, text: &str) -> bool {
let at = |n: usize| text.is_char_boundary(n);
let lines = text.split('\n').count();
at(m.anchor) && at(m.focus)
&& m.marks.iter().all(|r| at(r.start) && at(r.end) && r.start < r.end)
&& (m.blocks.is_empty() || m.blocks.len() == lines)
&& m.soft_breaks.iter().all(|&n| n > 0 && (n as usize) < lines)
}
fn change_json(c: &Change) -> serde_json::Value {
serde_json::json!({ "at": c.at, "r": c.removed.as_str(), "i": c.inserted.as_str(), "bl": c.lens[0], "al": c.lens[1], "b": meta_json(&c.before), "a": meta_json(&c.after) })
}
fn change_from(v: &serde_json::Value) -> Option<Change> {
let n = |k: &str| v[k].as_u64().map(|n| n as usize);
Some(Change {
at: n("at")?,
removed: shared(v["r"].as_str()?),
inserted: shared(v["i"].as_str()?),
lens: [n("bl")?, n("al")?],
before: meta_from(&v["b"])?,
after: meta_from(&v["a"])?,
})
}
fn meta_json(m: &Meta) -> serde_json::Value {
let marks: Vec<_> = m
.marks
.iter()
.map(|m| {
let kind = match &m.mark {
Mark::Bold => serde_json::json!("b"),
Mark::Italic => serde_json::json!("i"),
Mark::Underline => serde_json::json!("u"),
Mark::Strike => serde_json::json!("s"),
Mark::Code => serde_json::json!("c"),
Mark::Link(url) => serde_json::json!(["l", url]),
Mark::Pill(id) => serde_json::json!(["p", id]),
};
serde_json::json!([m.start, m.end, kind])
})
.collect();
let blocks: Vec<_> = m
.blocks
.iter()
.map(|b| match b {
Block::Paragraph => serde_json::json!("p"),
Block::Quote => serde_json::json!("q"),
Block::Code => serde_json::json!("c"),
Block::Bullet(l) => serde_json::json!(["b", l]),
Block::Numbered(l) => serde_json::json!(["n", l]),
})
.collect();
serde_json::json!({ "a": m.anchor, "f": m.focus, "m": marks, "k": blocks, "s": m.soft_breaks })
}
/// A stored document's selection, marks, blocks and soft breaks, as numbers: `meta_holds`
/// checks them against the text they're for.
fn meta_from(v: &serde_json::Value) -> Option<Meta> {
let n = |n: &serde_json::Value| n.as_u64().map(|n| n as usize);
let marks = v["m"]
.as_array()?
.iter()
.map(|m| {
let (start, end) = (n(&m[0])?, n(&m[1])?);
let mark = match (&m[2], m[2][0].as_str(), m[2][1].as_str()) {
(k, _, _) if k == "b" => Mark::Bold,
(k, _, _) if k == "i" => Mark::Italic,
(k, _, _) if k == "u" => Mark::Underline,
(k, _, _) if k == "s" => Mark::Strike,
(k, _, _) if k == "c" => Mark::Code,
(_, Some("l"), Some(url)) => Mark::Link(url.to_owned()),
(_, Some("p"), Some(id)) => Mark::Pill(id.to_owned()),
_ => return None,
};
Some(MarkRange { start, end, mark })
})
.collect::<Option<Vec<_>>>()?;
let blocks = v["k"]
.as_array()?
.iter()
.map(|b| match (b.as_str(), b[0].as_str(), b[1].as_u64()) {
(Some("p"), ..) => Some(Block::Paragraph),
(Some("q"), ..) => Some(Block::Quote),
(Some("c"), ..) => Some(Block::Code),
(_, Some("b"), Some(l)) => Some(Block::Bullet((l as u8).min(MAX_LIST_LEVEL))),
(_, Some("n"), Some(l)) => Some(Block::Numbered((l as u8).min(MAX_LIST_LEVEL))),
_ => None,
})
.collect::<Option<Vec<_>>>()?;
let soft_breaks = v["s"].as_array()?.iter().map(|n| n.as_u64().map(|n| n as u32)).collect::<Option<Vec<_>>>()?;
Some(Meta { anchor: n(&v["a"])?, focus: n(&v["f"])?, marks, blocks, soft_breaks })
}
/// A version-1 snapshot, when every offset in it is on a character boundary of its text.
fn snapshot_from(v: &serde_json::Value) -> Option<Snapshot> {
let text = v["t"].as_str()?.to_owned();
let m = meta_from(v)?;
if !meta_holds(&m, &text) { return None; }
Some(Snapshot { text: Arc::new(Wiped(text)), anchor: m.anchor, focus: m.focus, marks: m.marks, blocks: m.blocks, soft_breaks: m.soft_breaks })
}
#[cfg(test)]
#[path = "history_tests.rs"]
mod tests;
+37
View File
@@ -0,0 +1,37 @@
use super::*;
#[test]
fn a_group_opened_on_a_secure_field_records_from_when_it_turns_plain() {
let mut e = TextEdit::new("pw").secure();
e.undo_group(|e| {
e.insert("1");
assert!(matches!(e.group, Group::Unrecorded));
e.set_secure(false);
e.insert("a");
e.set_secure(false);
e.insert("b");
});
assert_eq!(e.text, "pw1ab");
e.undo();
assert_eq!(e.text, "pw1", "one step, from when the field turned plain, not moved by a second set_secure(false)");
e.undo();
assert_eq!(e.text, "pw1");
}
#[test]
fn a_group_is_closed_in_clones_and_holds_undo_until_it_closes() {
let mut e = TextEdit::new("a");
e.undo_group(|e| {
e.insert("b");
assert!(e.group.is_open() && !e.clone().group.is_open());
e.undo();
assert_eq!(e.text, "ab", "undo waits for the group to close");
e.set_secure(true);
assert!(matches!(e.group, Group::Unrecorded), "turning secure drops the baseline's text");
e.set_secure(false);
e.replace_text("c");
});
assert!(!e.group.is_open());
e.undo();
assert_eq!(e.text, "c", "replace_text in the group discards the history before it");
}
+221
View File
@@ -0,0 +1,221 @@
//! Safe HTML subset import and export for [`TextEdit`](super::TextEdit).
//!
//! Supported elements:
//! - Inline: `<b>`, `<strong>`, `<i>`, `<em>`, `<u>`, `<ins>`, `<s>`, `<del>`, `<strike>`,
//! `<a href="...">`, `<code>`, and CSS `style` attributes (`font-weight`, `font-style`,
//! `text-decoration`, `text-decoration-line`), and `<span data-pill="id">` for
//! [`Mark::Pill`].
//! - Block: `<p>`, `<div>`, `<br>`, `<ul>`, `<ol>`, `<li>`, `<blockquote>`, `<pre>`.
//! - Stripped with content: `<script>`, `<style>`, `<head>`.
//! - Unknown tags drop their wrapper and keep their text. Nothing is executed, and dangerous
//! link schemes (`javascript:`, `vbscript:`, `data:`) are rejected.
use super::Mark;
mod parse;
mod serialize;
pub(crate) use parse::parse_html;
pub(crate) use serialize::serialize_html;
#[derive(Clone, Copy, PartialEq, Eq)]
enum ListKind {
Bullet,
Numbered,
}
/// Safe URL check for `<a href="...">`: allows `http:`, `https:`, `mailto:` and `tel:`, and
/// scheme-less URLs. Browsers drop ASCII tabs and newlines anywhere in a URL and leading
/// controls and spaces, so `java\tscript:` is checked as `javascript:`; anything else with a
/// scheme (`javascript:`, `data:`, `file:`, app-specific schemes) is rejected.
fn is_safe_href(url: &str) -> bool {
let cleaned: String = url
.chars()
.filter(|c| !c.is_control() && !c.is_whitespace())
.take(64)
.map(|c| c.to_ascii_lowercase())
.collect();
if cleaned.is_empty() {
return false;
}
let scheme_len = cleaned
.find(|c: char| !(c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')))
.unwrap_or(cleaned.len());
if !cleaned[scheme_len..].starts_with(':') {
// No scheme: a relative path, `www.example.com` or `#fragment`.
return true;
}
matches!(&cleaned[..scheme_len], "http" | "https" | "mailto" | "tel")
}
/// Decodes HTML entities (`&amp;`, `&lt;`, `&gt;`, `&quot;`, `&apos;`, `&nbsp;`, `&#123;`, `&#x1F600;`).
pub(crate) fn decode_entities(input: &str) -> String {
if !input.contains('&') {
return input.to_owned();
}
let mut out = String::with_capacity(input.len());
let mut rest = input;
while let Some(amp) = rest.find('&') {
out.push_str(&rest[..amp]);
rest = &rest[amp + 1..];
// Entities are short: look for `;` in the next 33 bytes only, so a run of bare `&`s
// stays linear.
let window = &rest.as_bytes()[..rest.len().min(33)];
let Some(semi) = window.iter().position(|&b| b == b';') else {
out.push('&');
continue;
};
let entity = &rest[..semi];
if entity.is_empty() || entity.contains(char::is_whitespace) {
out.push('&');
continue;
}
let decoded = if let Some(hex) = entity.strip_prefix("#x").or_else(|| entity.strip_prefix("#X")) {
u32::from_str_radix(hex, 16).ok().and_then(char::from_u32)
} else if let Some(dec) = entity.strip_prefix('#') {
dec.parse::<u32>().ok().and_then(char::from_u32)
} else {
match entity {
"amp" | "AMP" => Some('&'),
"lt" | "LT" => Some('<'),
"gt" | "GT" => Some('>'),
"quot" | "QUOT" => Some('"'),
"apos" | "#39" => Some('\''),
"nbsp" | "NBSP" => Some('\u{00a0}'),
"copy" => Some('©'),
"mdash" => Some('—'),
"ndash" => Some('–'),
"hellip" => Some('…'),
"lsquo" => Some('‘'),
"rsquo" => Some('’'),
"ldquo" => Some('“'),
"rdquo" => Some('”'),
"bull" => Some('•'),
// Browsers decode these in an `href` too, so `javascript&colon;` is still a scheme.
"colon" => Some(':'),
"Tab" => Some('\t'),
"NewLine" => Some('\n'),
_ => None,
}
};
if let Some(ch) = decoded {
out.push(ch);
rest = &rest[semi + 1..];
} else {
out.push('&');
}
}
out.push_str(rest);
out
}
fn escape_html(s: &str, out: &mut String) {
for ch in s.chars() {
match ch {
'&' => out.push_str("&amp;"),
'<' => out.push_str("&lt;"),
'>' => out.push_str("&gt;"),
'"' => out.push_str("&quot;"),
_ => out.push(ch),
}
}
}
/// Extracts an HTML attribute's value from a tag tail (`href="..."`, `style='...'`, `href=foo`).
fn extract_attr(attrs: &str, name: &str) -> Option<String> {
let bytes = attrs.as_bytes();
let mut i = 0;
while i < bytes.len() {
while i < bytes.len() && bytes[i].is_ascii_whitespace() {
i += 1;
}
let key_start = i;
while i < bytes.len() && (bytes[i].is_ascii_alphanumeric() || matches!(bytes[i], b'-' | b'_' | b':')) {
i += 1;
}
if i == key_start {
i += 1;
continue;
}
let key = &attrs[key_start..i];
while i < bytes.len() && bytes[i].is_ascii_whitespace() {
i += 1;
}
if i >= bytes.len() || bytes[i] != b'=' {
continue;
}
i += 1;
while i < bytes.len() && bytes[i].is_ascii_whitespace() {
i += 1;
}
if i >= bytes.len() {
break;
}
let val = if bytes[i] == b'"' || bytes[i] == b'\'' {
let quote = bytes[i];
i += 1;
let val_start = i;
while i < bytes.len() && bytes[i] != quote {
i += 1;
}
let v = &attrs[val_start..i];
if i < bytes.len() {
i += 1;
}
v
} else {
let val_start = i;
while i < bytes.len() && !bytes[i].is_ascii_whitespace() && bytes[i] != b'>' && bytes[i] != b'/' {
i += 1;
}
&attrs[val_start..i]
};
if key.eq_ignore_ascii_case(name) {
return Some(decode_entities(val));
}
}
None
}
/// Parses inline CSS `style="..."` for `font-weight`, `font-style`, and `text-decoration`.
fn parse_style_marks(style: &str, add: &mut Vec<Mark>, remove: &mut Vec<Mark>) {
for decl in style.split(';') {
let Some((prop, val)) = decl.split_once(':') else { continue };
let prop = prop.trim();
let val = val.trim();
if prop.eq_ignore_ascii_case("font-weight") {
let v = val.split_whitespace().next().unwrap_or("");
if v.eq_ignore_ascii_case("bold")
|| v.eq_ignore_ascii_case("bolder")
|| v.parse::<f32>().is_ok_and(|w| w >= 600.0)
{
add.push(Mark::Bold);
} else if v.eq_ignore_ascii_case("normal")
|| v.eq_ignore_ascii_case("lighter")
|| v.parse::<f32>().is_ok_and(|w| w < 600.0)
{
remove.push(Mark::Bold);
}
} else if prop.eq_ignore_ascii_case("font-style") {
let v = val.split_whitespace().next().unwrap_or("");
if v.eq_ignore_ascii_case("italic") || v.eq_ignore_ascii_case("oblique") {
add.push(Mark::Italic);
} else if v.eq_ignore_ascii_case("normal") {
remove.push(Mark::Italic);
}
} else if prop.eq_ignore_ascii_case("text-decoration")
|| prop.eq_ignore_ascii_case("text-decoration-line")
{
for tok in val.split_whitespace() {
if tok.eq_ignore_ascii_case("underline") {
add.push(Mark::Underline);
} else if tok.eq_ignore_ascii_case("line-through") {
add.push(Mark::Strike);
} else if tok.eq_ignore_ascii_case("none") {
remove.push(Mark::Underline);
remove.push(Mark::Strike);
}
}
}
}
}
+562
View File
@@ -0,0 +1,562 @@
//! Safe HTML fragment parser into [`TextEdit`].
use super::{ListKind, decode_entities, extract_attr, is_safe_href, parse_style_marks};
use crate::{Block, MAX_LIST_LEVEL, Mark, MarkRange, TextEdit};
const MAX_DEPTH: usize = 512;
#[derive(Clone)]
struct ActiveMark {
mark: Mark,
start: usize,
}
struct TagFrame {
tag: String,
added_marks: Vec<Mark>,
suppressed_marks: Vec<Mark>,
}
pub(crate) fn parse_html(html: &str) -> TextEdit {
let mut text = String::new();
let mut marks: Vec<MarkRange> = Vec::new();
let mut blocks: Vec<Block> = vec![Block::Paragraph];
let mut soft_breaks: Vec<u32> = Vec::new();
let mut stack: Vec<TagFrame> = Vec::new();
// Open frames per tag name, so a stray closing tag never scans the whole stack.
let mut open_tags: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
let mut active_marks: Vec<ActiveMark> = Vec::new();
let mut list_stack: Vec<ListKind> = Vec::new();
let mut in_pre: usize = 0;
let mut in_quote: usize = 0;
let mut in_li: usize = 0;
// Whether the current line has been claimed by a block tag or text, whether that block is
// still open awaiting its first content, and whether text/br has been written on this line.
let mut line_has_block = false;
let mut line_open = false;
let mut line_has_content = false;
let current_default_block = |list_stack: &[ListKind], in_pre: usize, in_quote: usize, in_li: usize| -> Block {
if in_pre > 0 {
Block::Code
} else if in_li > 0 && let Some(&kind) = list_stack.last() {
let level = (list_stack.len() - 1).min(MAX_LIST_LEVEL as usize) as u8;
match kind {
ListKind::Bullet => Block::Bullet(level),
ListKind::Numbered => Block::Numbered(level),
}
} else if in_quote > 0 {
Block::Quote
} else {
Block::Paragraph
}
};
let flush_active_marks = |active: &mut [ActiveMark], marks: &mut Vec<MarkRange>, pos: usize, in_pre: usize| {
if in_pre == 0 {
for a in active.iter_mut() {
if a.start < pos {
marks.push(MarkRange {
start: a.start,
end: pos,
mark: a.mark.clone(),
});
}
a.start = pos;
}
} else {
for a in active.iter_mut() {
a.start = pos;
}
}
};
let start_new_paragraph = |text: &mut String,
blocks: &mut Vec<Block>,
active: &mut [ActiveMark],
marks: &mut Vec<MarkRange>,
line_has_block: &mut bool,
line_open: &mut bool,
line_has_content: &mut bool,
block: Block,
in_pre: usize| {
if (!*line_has_block || *line_open) && !*line_has_content {
if let Some(last) = blocks.last_mut() {
*last = block;
}
*line_has_block = true;
*line_open = true;
return;
}
let pos = text.len();
flush_active_marks(active, marks, pos, in_pre);
text.push('\n');
blocks.push(block);
let new_pos = text.len();
for a in active.iter_mut() {
a.start = new_pos;
}
*line_has_block = true;
*line_open = true;
*line_has_content = false;
};
let push_br = |text: &mut String,
blocks: &mut Vec<Block>,
soft_breaks: &mut Vec<u32>,
active: &mut [ActiveMark],
marks: &mut Vec<MarkRange>,
in_pre: usize| {
flush_active_marks(active, marks, text.len(), in_pre);
let blk = blocks.last().copied().unwrap_or(Block::Paragraph);
text.push('\n');
blocks.push(blk);
if in_pre == 0 {
soft_breaks.push((blocks.len() - 1) as u32);
}
for a in active.iter_mut() {
a.start = text.len();
}
};
// A `<br>` (text and block counts where it fell) waiting to see whether text follows it.
let mut deferred_br: Option<(usize, usize)> = None;
let mut i = 0;
let bytes = html.as_bytes();
while i < bytes.len() {
if bytes[i] == b'<' {
// Comment `<!-- ... -->`
if html[i..].starts_with("<!--") {
if let Some(end) = html[i + 4..].find("-->") {
i += 4 + end + 3;
} else {
break;
}
continue;
}
// Processing instruction or doctype `<!...>` / `<?...>`
if html[i..].starts_with("<!") || html[i..].starts_with("<?") {
if let Some(end) = html[i + 2..].find('>') {
i += 2 + end + 1;
} else {
break;
}
continue;
}
let Some(close_angle) = html[i + 1..].find('>') else {
// Unclosed `<`, treat as literal text
let decoded = decode_entities(&html[i..]);
text.push_str(&decoded);
break;
};
let raw_tag = html[i + 1..i + 1 + close_angle].trim();
i += 1 + close_angle + 1;
if raw_tag.is_empty() {
continue;
}
let is_closing = raw_tag.starts_with('/');
let body = raw_tag.trim_start_matches('/').trim_end_matches('/').trim();
let tag_end = body
.find(|c: char| c.is_whitespace() || c == '/')
.unwrap_or(body.len());
let tag = body[..tag_end].to_ascii_lowercase();
let attrs = &body[tag_end..];
let self_closing = raw_tag.ends_with('/')
|| matches!(
tag.as_str(),
"area" | "base" | "col" | "embed" | "hr" | "img" | "input" | "link" | "meta" | "source" | "track" | "wbr"
);
if !is_closing && matches!(tag.as_str(), "script" | "style" | "head") {
if !self_closing {
// Skip until matching `</tag>` (case-insensitive)
let pat = format!("</{tag}");
let mut search = i;
let mut found = None;
while search + pat.len() <= bytes.len() {
if html[search..].len() >= pat.len()
&& html.is_char_boundary(search)
&& html.is_char_boundary(search + pat.len())
&& html[search..search + pat.len()].eq_ignore_ascii_case(&pat)
{
// No `>` after this means none after any later match either.
found = html[search + pat.len()..].find('>').map(|gt| search + pat.len() + gt + 1);
break;
}
search += 1;
}
i = found.unwrap_or(bytes.len());
}
continue;
}
if !is_closing && tag == "br" {
if deferred_br == Some((text.len(), blocks.len())) {
push_br(&mut text, &mut blocks, &mut soft_breaks, &mut active_marks, &mut marks, in_pre);
line_has_block = true;
line_open = true;
}
deferred_br = None;
if in_pre > 0 {
push_br(&mut text, &mut blocks, &mut soft_breaks, &mut active_marks, &mut marks, in_pre);
line_has_content = false;
} else {
// A `<br>` only breaks the line when something follows it in the same block,
// as browsers draw it: `<p>A<br></p>` is one line, `<p><br></p>` one blank line.
deferred_br = Some((text.len(), blocks.len()));
line_has_block = true;
line_open = true;
line_has_content = true;
}
continue;
}
// Deeper nesting than any real document keeps its text but not its tags, so a flood of
// opening tags can't grow the stack without bound.
if !is_closing && !self_closing && stack.len() >= MAX_DEPTH {
continue;
}
if !is_closing {
match tag.as_str() {
"ul" => {
list_stack.push(ListKind::Bullet);
// The first item takes a line still waiting for content (`<li><ul>`), but
// never a finished one, even if it was blank (`<p></p><ul>`).
if line_has_content {
line_open = false;
}
}
"ol" => {
list_stack.push(ListKind::Numbered);
// The first item takes a line still waiting for content (`<li><ul>`), but
// never a finished one, even if it was blank (`<p></p><ul>`).
if line_has_content {
line_open = false;
}
}
"li" => {
in_li += 1;
let blk = current_default_block(&list_stack, in_pre, in_quote, in_li);
start_new_paragraph(
&mut text,
&mut blocks,
&mut active_marks,
&mut marks,
&mut line_has_block,
&mut line_open,
&mut line_has_content,
blk,
in_pre,
);
}
"blockquote" => {
in_quote += 1;
let blk = current_default_block(&list_stack, in_pre, in_quote, in_li);
start_new_paragraph(
&mut text,
&mut blocks,
&mut active_marks,
&mut marks,
&mut line_has_block,
&mut line_open,
&mut line_has_content,
blk,
in_pre,
);
}
"pre" => {
in_pre += 1;
start_new_paragraph(
&mut text,
&mut blocks,
&mut active_marks,
&mut marks,
&mut line_has_block,
&mut line_open,
&mut line_has_content,
Block::Code,
in_pre,
);
}
"p" | "div" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6" => {
let blk = current_default_block(&list_stack, in_pre, in_quote, in_li);
start_new_paragraph(
&mut text,
&mut blocks,
&mut active_marks,
&mut marks,
&mut line_has_block,
&mut line_open,
&mut line_has_content,
blk,
in_pre,
);
}
_ => {}
}
let mut to_add = Vec::new();
let mut to_suppress = Vec::new();
match tag.as_str() {
"b" | "strong" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6" => to_add.push(Mark::Bold),
"i" | "em" => to_add.push(Mark::Italic),
"u" | "ins" => to_add.push(Mark::Underline),
"s" | "del" | "strike" => to_add.push(Mark::Strike),
"code" if in_pre == 0 => to_add.push(Mark::Code),
"a" => {
if let Some(href) = extract_attr(attrs, "href")
&& is_safe_href(&href)
{
to_add.push(Mark::Link(href.trim().to_owned()));
}
}
"span" => {
if let Some(id) = extract_attr(attrs, "data-pill") {
to_add.push(Mark::Pill(id));
}
}
_ => {}
}
if let Some(style) = extract_attr(attrs, "style") {
parse_style_marks(&style, &mut to_add, &mut to_suppress);
// The element's own style wins over its tag: Google Docs wraps a whole
// paste in `<b style="font-weight:normal">`.
to_add.retain(|m| !to_suppress.iter().any(|r| r.same_kind(m)));
}
let pos = text.len();
let mut frame = TagFrame {
tag: tag.clone(),
added_marks: Vec::new(),
suppressed_marks: Vec::new(),
};
for rem in to_suppress {
if let Some(idx) = active_marks.iter().position(|a| a.mark.same_kind(&rem)) {
let popped = active_marks.remove(idx);
if in_pre == 0 && popped.start < pos {
marks.push(MarkRange {
start: popped.start,
end: pos,
mark: popped.mark.clone(),
});
}
frame.suppressed_marks.push(popped.mark);
}
}
for m in to_add {
if let Some(idx) = active_marks.iter().position(|a| a.mark.same_kind(&m)) {
if active_marks[idx].mark != m {
let old = active_marks.remove(idx);
if in_pre == 0 && old.start < pos {
marks.push(MarkRange {
start: old.start,
end: pos,
mark: old.mark.clone(),
});
}
frame.suppressed_marks.push(old.mark);
active_marks.push(ActiveMark { mark: m.clone(), start: pos });
frame.added_marks.push(m);
}
} else {
active_marks.push(ActiveMark { mark: m.clone(), start: pos });
frame.added_marks.push(m);
}
}
if !self_closing {
*open_tags.entry(tag.clone()).or_default() += 1;
stack.push(frame);
}
} else {
// Closing tag
let pos = text.len();
let open = open_tags.get(&tag).is_some_and(|&n| n > 0);
if let Some(frame_idx) = open.then(|| stack.iter().rposition(|f| f.tag == tag)).flatten() {
while stack.len() > frame_idx {
let frame = stack.pop().unwrap();
if let Some(n) = open_tags.get_mut(&frame.tag) {
*n -= 1;
}
for m in frame.added_marks.into_iter().rev() {
if let Some(idx) = active_marks.iter().rposition(|a| a.mark == m) {
let ended = active_marks.remove(idx);
if in_pre == 0 && ended.start < pos {
marks.push(MarkRange {
start: ended.start,
end: pos,
mark: ended.mark,
});
}
}
}
for sup in frame.suppressed_marks {
if !active_marks.iter().any(|a| a.mark.same_kind(&sup)) {
active_marks.push(ActiveMark { mark: sup, start: pos });
}
}
match frame.tag.as_str() {
"ul" | "ol" => {
list_stack.pop();
line_open = false;
}
"li" => {
in_li = in_li.saturating_sub(1);
line_open = false;
}
"blockquote" => {
in_quote = in_quote.saturating_sub(1);
line_open = false;
}
"pre" => {
in_pre = in_pre.saturating_sub(1);
line_open = false;
}
"p" | "div" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6" => {
line_open = false;
}
_ => {}
}
}
}
}
} else {
// Plain text node up to next `<`
let next_lt = html[i..].find('<').map_or(bytes.len(), |off| i + off);
let raw_slice = &html[i..next_lt];
i = next_lt;
let decoded = decode_entities(raw_slice);
if in_pre > 0 {
// Inside `<pre>`, preserve whitespace and split newlines into `Block::Code` paragraphs.
let mut chars = decoded.chars().peekable();
while let Some(c) = chars.next() {
if c == '\r' {
if chars.peek() == Some(&'\n') {
continue;
}
text.push('\n');
blocks.push(Block::Code);
line_has_block = true;
line_open = false;
line_has_content = false;
} else if c == '\n' {
// Ignore a single leading newline immediately after `<pre>`
if line_open && !line_has_content {
line_open = false;
continue;
}
text.push('\n');
blocks.push(Block::Code);
line_has_block = true;
line_open = false;
line_has_content = false;
} else if c == '\t' || !c.is_control() {
text.push(c);
line_has_block = true;
line_open = false;
line_has_content = true;
}
}
} else {
// Outside `<pre>`: ignore pure inter-block whitespace if we're between closed blocks and a `<` follows
if !line_open && decoded.chars().all(char::is_whitespace) && (!line_has_block || line_has_content) {
continue;
}
if line_open && !line_has_content && decoded.chars().all(char::is_whitespace) && i < bytes.len() && html[i..].starts_with('<') {
// Check if the next tag is a block child like `<p>` or `<li>` inside `<blockquote>` or `<ul>`
let rest_tag = html[i + 1..].trim_start();
let next_is_block = ["p", "div", "ul", "ol", "li", "blockquote", "pre", "h1", "h2", "h3", "h4", "h5", "h6"]
.iter()
.any(|b| {
rest_tag.len() >= b.len()
&& rest_tag.is_char_boundary(b.len())
&& rest_tag[..b.len()].eq_ignore_ascii_case(b)
&& rest_tag[b.len()..].starts_with(|c: char| c.is_whitespace() || c == '>' || c == '/')
});
if next_is_block {
continue;
}
}
if !line_open && !decoded.is_empty() && (!line_has_block || line_has_content) {
let blk = current_default_block(&list_stack, in_pre, in_quote, in_li);
if !line_has_block {
if let Some(last) = blocks.last_mut() {
*last = blk;
}
line_has_block = true;
line_open = true;
} else if !decoded.chars().all(char::is_whitespace) {
// Loose text after a closed block (`<p>A</p>B`) starts its own line.
start_new_paragraph(
&mut text,
&mut blocks,
&mut active_marks,
&mut marks,
&mut line_has_block,
&mut line_open,
&mut line_has_content,
blk,
in_pre,
);
}
}
// Collapse ASCII whitespace runs (newlines/tabs/spaces) to single spaces in HTML flow
if decoded.chars().all(char::is_whitespace) {
if deferred_br == Some((text.len(), blocks.len())) {
continue;
}
} else {
if deferred_br == Some((text.len(), blocks.len())) {
push_br(&mut text, &mut blocks, &mut soft_breaks, &mut active_marks, &mut marks, in_pre);
}
deferred_br = None;
}
let mut prev_space = text.is_empty() || text.ends_with('\n') || text.ends_with(' ');
for ch in decoded.chars() {
if ch == '\u{00a0}' {
text.push('\u{00a0}');
prev_space = false;
line_has_block = true;
line_open = true;
line_has_content = true;
} else if ch.is_whitespace() {
if !prev_space {
text.push(' ');
prev_space = true;
line_has_block = true;
line_open = true;
line_has_content = true;
}
} else if !ch.is_control() {
text.push(ch);
prev_space = false;
line_has_block = true;
line_open = true;
line_has_content = true;
}
}
}
}
}
let end_pos = text.len();
flush_active_marks(&mut active_marks, &mut marks, end_pos, in_pre);
// Strip a single trailing newline inside `<pre>` if it left an empty trailing line
if blocks.len() > 1
&& blocks.last() == Some(&Block::Code)
&& text.ends_with('\n')
&& !soft_breaks.contains(&((blocks.len() - 1) as u32))
{
text.pop();
blocks.pop();
}
let mut edit = TextEdit::from_parts(text, marks, blocks);
edit.soft_breaks = soft_breaks;
edit
}
+261
View File
@@ -0,0 +1,261 @@
//! Safe HTML serializer for a [`TextEdit`] range.
use std::ops::Range;
use rune_text::{Direction, Flow};
use super::{ListKind, escape_html};
use crate::{Block, Mark, MarkRange, TextEdit};
/// Serializes byte range `range` of `edit` to HTML.
pub(crate) fn serialize_html(edit: &TextEdit, range: Range<usize>) -> String {
let start = range.start.min(edit.text.len());
let end = range.end.min(edit.text.len()).max(start);
if start == end && edit.blocks().iter().all(|&b| b == Block::Paragraph) {
return String::new();
}
// Collect paragraphs intersecting `start..end`
let mut paras: Vec<(usize, Range<usize>, Block, bool)> = Vec::new();
for p in edit.paragraphs() {
let p_end_with_nl = if p.range.end < edit.text.len() { p.range.end + 1 } else { p.range.end };
if p.range.start <= end && p_end_with_nl >= start {
let sub_start = p.range.start.max(start);
let sub_end = p.range.end.min(end);
if sub_start <= sub_end
&& (sub_start < sub_end || start == end || (p.range.start >= start && p.range.end <= end))
{
paras.push((p.index, sub_start..sub_end, p.block, p.soft_break && p.range.start > start));
}
}
}
let dirs = block_dirs(edit, &paras);
let mut out = String::new();
let mut idx = 0;
while idx < paras.len() {
let (_, _, block, _) = paras[idx];
match block {
Block::Code => {
out.push_str("<pre");
out.push_str(dirs[idx]);
out.push_str("><code>");
let mut first = true;
while idx < paras.len() && paras[idx].2 == Block::Code {
if !first {
out.push('\n');
}
first = false;
let r = &paras[idx].1;
escape_html(&edit.text[r.clone()], &mut out);
idx += 1;
}
out.push_str("</code></pre>");
}
Block::Bullet(_) | Block::Numbered(_) => {
// Group consecutive list items and emit properly nested `<ul>` / `<ol>`
let mut open_lists: Vec<ListKind> = Vec::new();
while idx < paras.len() && paras[idx].2.is_list() {
let (_, ref r, blk, _) = paras[idx];
let (kind, level) = match blk {
Block::Bullet(l) => (ListKind::Bullet, l as usize),
Block::Numbered(l) => (ListKind::Numbered, l as usize),
_ => unreachable!(),
};
let target_depth = level + 1;
while open_lists.len() > target_depth {
match open_lists.pop().unwrap() {
ListKind::Bullet => out.push_str("</ul>"),
ListKind::Numbered => out.push_str("</ol>"),
}
}
if open_lists.len() == target_depth && open_lists.last() != Some(&kind) {
match open_lists.pop().unwrap() {
ListKind::Bullet => out.push_str("</ul>"),
ListKind::Numbered => out.push_str("</ol>"),
}
}
while open_lists.len() < target_depth {
let k = if open_lists.len() + 1 == target_depth {
kind
} else {
*open_lists.last().unwrap_or(&kind)
};
out.push_str(if k == ListKind::Bullet { "<ul" } else { "<ol" });
out.push_str(dirs[idx]);
out.push('>');
open_lists.push(k);
}
out.push_str("<li");
out.push_str(dirs[idx]);
out.push('>');
serialize_inline(edit, r.clone(), &mut out);
idx += 1;
while idx < paras.len() && paras[idx].3 && paras[idx].2 == blk {
out.push_str("<br>");
serialize_inline(edit, paras[idx].1.clone(), &mut out);
idx += 1;
}
out.push_str("</li>");
}
while let Some(k) = open_lists.pop() {
match k {
ListKind::Bullet => out.push_str("</ul>"),
ListKind::Numbered => out.push_str("</ol>"),
}
}
}
Block::Quote => {
out.push_str("<blockquote");
out.push_str(dirs[idx]);
out.push('>');
serialize_inline(edit, paras[idx].1.clone(), &mut out);
idx += 1;
while idx < paras.len() && paras[idx].3 && paras[idx].2 == Block::Quote {
out.push_str("<br>");
serialize_inline(edit, paras[idx].1.clone(), &mut out);
idx += 1;
}
out.push_str("</blockquote>");
}
Block::Paragraph => {
out.push_str("<p");
out.push_str(dirs[idx]);
out.push('>');
serialize_inline(edit, paras[idx].1.clone(), &mut out);
idx += 1;
while idx < paras.len() && paras[idx].3 && paras[idx].2 == Block::Paragraph {
out.push_str("<br>");
serialize_inline(edit, paras[idx].1.clone(), &mut out);
idx += 1;
}
out.push_str("</p>");
}
}
}
out
}
/// Each copied block's ` dir` attribute, by `paras` index: the direction the field showed it in
/// (its first strong character's, else the paragraph before it's, or the one Ctrl+Shift set),
/// and code left to right. Word, Mail and browsers then lay a right-to-left copy out as it was
/// shown. A copy with no right-to-left block has none, so it is as it always was.
fn block_dirs(edit: &TextEdit, paras: &[(usize, Range<usize>, Block, bool)]) -> Vec<&'static str> {
let forced = edit.forced_dir().map(|f| if f == Flow::Rtl { Direction::Rtl } else { Direction::Ltr });
let mut last = None;
let shown: Vec<Option<Direction>> = edit
.paragraphs()
.iter()
.map(|p| {
last = forced.or_else(|| Direction::of(&edit.text[p.range.clone()])).or(last);
last
})
.collect();
let at = |i: usize| shown.get(i).copied().flatten();
let rtl = paras.iter().any(|p| p.2 != Block::Code && at(p.0) == Some(Direction::Rtl));
paras
.iter()
.map(|p| match (p.2, at(p.0)) {
_ if !rtl => "",
(Block::Code, _) | (_, Some(Direction::Ltr)) => " dir=\"ltr\"",
(_, Some(Direction::Rtl)) => " dir=\"rtl\"",
_ => "",
})
.collect()
}
/// Serializes inline marks within `range` (a single line/paragraph slice) to HTML. A pill
/// wholly inside `range` is one `<span data-pill>` around its label's own marks, so marks
/// that cross its edges never split it; a pill cut by `range` is plain text.
fn serialize_inline(edit: &TextEdit, range: Range<usize>, out: &mut String) {
let mut at = range.start;
for m in edit.marks().iter().filter(|m| range.start <= m.start && m.end <= range.end) {
let Some(id) = m.mark.pill_id() else { continue };
serialize_marks(edit, at..m.start, out);
out.push_str("<span data-pill=\"");
escape_html(id, out);
out.push_str("\">");
serialize_marks(edit, m.range(), out);
out.push_str("</span>");
at = m.end;
}
serialize_marks(edit, at..range.end, out);
}
/// Serializes the inline marks other than pills within `range`.
fn serialize_marks(edit: &TextEdit, range: Range<usize>, out: &mut String) {
if range.is_empty() {
return;
}
let overlapping: Vec<&MarkRange> = edit
.marks()
.iter()
.filter(|m| m.start < range.end && m.end > range.start && !m.mark.is_pill())
.collect();
if overlapping.is_empty() {
escape_html(&edit.text[range], out);
return;
}
let mut bounds = vec![range.start, range.end];
for m in &overlapping {
bounds.push(m.start.clamp(range.start, range.end));
bounds.push(m.end.clamp(range.start, range.end));
}
bounds.sort_unstable();
bounds.dedup();
// `overlapping` is sorted by start (as `marks()` is): sweep it instead of rescanning.
let mut covering: Vec<&MarkRange> = Vec::new();
let mut next = 0;
for w in bounds.windows(2) {
let (a, b) = (w[0], w[1]);
if a >= b {
continue;
}
covering.retain(|m| m.end > a);
while next < overlapping.len() && overlapping[next].start <= a {
if overlapping[next].end > a {
covering.push(overlapping[next]);
}
next += 1;
}
let mut active: Vec<&Mark> = covering.iter().map(|m| &m.mark).collect();
// Canonical nesting order: Link, Bold, Italic, Underline, Strike, Code
active.sort_by_key(|m| match m {
Mark::Link(_) => 0u8,
Mark::Bold => 1,
Mark::Italic => 2,
Mark::Underline => 3,
Mark::Strike => 4,
Mark::Code => 5,
Mark::Pill(_) => 6,
});
for m in &active {
match m {
Mark::Bold => out.push_str("<strong>"),
Mark::Italic => out.push_str("<em>"),
Mark::Underline => out.push_str("<u>"),
Mark::Strike => out.push_str("<s>"),
Mark::Code => out.push_str("<code>"),
Mark::Link(url) => {
out.push_str("<a href=\"");
escape_html(url, out);
out.push_str("\">");
}
Mark::Pill(_) => {}
}
}
escape_html(&edit.text[a..b], out);
for m in active.iter().rev() {
match m {
Mark::Bold => out.push_str("</strong>"),
Mark::Italic => out.push_str("</em>"),
Mark::Underline => out.push_str("</u>"),
Mark::Strike => out.push_str("</s>"),
Mark::Code => out.push_str("</code>"),
Mark::Link(_) => out.push_str("</a>"),
Mark::Pill(_) => {}
}
}
}
}
+200
View File
@@ -0,0 +1,200 @@
//! Input method events: what the platform's input method (dead keys, CJK, the emoji picker,
//! dictation) composes, for the focused `text_input` or an app's own editor (`App::on_ime`);
//! and a field's [`Composition`], stepped by those events.
use std::ops::Range;
use zeroize::Zeroize;
use rune_core::machine::Effects;
/// One input method event. Plain typing arrives as keys (`Key::Text`); these carry what an
/// input method composed.
#[derive(Clone, Debug, PartialEq)]
pub enum Ime {
/// The composition so far (marked text), drawn at the caret and not yet part of the text,
/// with the byte range of its cursor or selection in it, and its clauses as the input
/// method splits it (a Japanese sentence's phrases, each converted on its own). Empty text
/// ends the composition. With no clauses (an input method or platform that doesn't say), a
/// cursor range that isn't empty is taken as the clause being converted.
Preedit(String, Option<(usize, usize)>, Vec<Clause>),
/// Text to insert at the caret, replacing the preedit.
Commit(String),
/// The input method takes this byte range of the text back to convert it again
/// (reconversion: Japanese 変換 on committed text, macOS ⌃⇧R): the field selects it, and
/// the composition that follows replaces it.
Select(Range<usize>),
/// The window's input method turned on for the caret that takes text (a focused
/// `text_input` or an `El::ime_cursor` surface), or off again. Informational: Rune turns it
/// on and off.
Enabled,
Disabled,
}
impl Drop for Ime {
fn drop(&mut self) {
match self {
Self::Preedit(text, ..) | Self::Commit(text) => text.zeroize(),
Self::Select(_) | Self::Enabled | Self::Disabled => {}
}
}
}
/// One clause of a composition: a byte range of the preedit, and whether it's the one being
/// converted (its candidates show; it draws with a thick underline).
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Clause {
range: Range<usize>,
target: bool,
}
impl Clause {
/// A clause over byte range `range` of the preedit, not the one being converted.
pub fn new(range: Range<usize>) -> Clause {
Clause { range, target: false }
}
/// The clause being converted.
pub fn target(mut self) -> Clause {
self.target = true;
self
}
pub fn range(&self) -> Range<usize> {
self.range.clone()
}
pub fn is_target(&self) -> bool {
self.target
}
}
/// A field's text around its selection, which the platform's input method reads to convert
/// committed text again (reconversion) and to convert with the context around the caret
/// (Windows' document feed). One paragraph, at most a KiB either side of the selection.
#[doc(hidden)]
#[derive(Clone, Debug, PartialEq)]
pub struct ImeText {
pub text: String,
/// Where `text` starts in the field's text, in bytes.
pub start: usize,
/// The selection, a byte range of `text`.
pub selection: Range<usize>,
}
impl ImeText {
/// The word (UAX #29) around byte `at` of `text`, for reconversion with no selection.
#[doc(hidden)]
pub fn word_at(&self, at: usize) -> Range<usize> {
use unicode_segmentation::UnicodeSegmentation;
self.text.split_word_bound_indices().map(|(i, w)| i..i + w.len()).find(|r| r.start <= at && at < r.end && !self.text[r.clone()].trim().is_empty())
.unwrap_or(at..at)
}
}
/// Whether a field's input method is composing: the marked text it draws at the caret, not
/// yet part of the field's text, the byte range of its cursor or selection in it, and its
/// clauses.
#[derive(Clone, Default, PartialEq, Hash)]
pub(super) enum Composition {
#[default]
Idle,
Composing { text: String, cursor: Option<(usize, usize)>, clauses: Vec<Clause> },
}
/// What steps a [`Composition`]: the input method, or the field ending it on its own.
pub(super) enum Event<'a> {
Ime(&'a Ime),
/// The field let go of the composition while it showed (it blurred, the window went
/// inactive, a click moved the caret): what it shows becomes text, as a browser's field and
/// an `NSTextView` keep it, and the platform's input method is told to drop its copy.
Finish,
/// An edit or undo replaced the text under the composition, or the field turned secure:
/// the composition goes, unwritten.
Cancel,
}
/// What a composition step asks of its field.
#[derive(Debug, PartialEq)]
pub(super) enum Effect {
/// Insert the committed text at the caret.
Commit(String),
/// Select this byte range of the text, for the input method to convert again.
Select(Range<usize>),
}
impl Composition {
pub(super) fn preedit(&self) -> Option<(&str, Option<(usize, usize)>)> {
match self {
Composition::Idle => None,
Composition::Composing { text, cursor, .. } => Some((text.as_str(), *cursor)),
}
}
/// The composition's clauses, each a byte range of the preedit, the one being converted
/// marked: the input method's, else one clause over the whole preedit with a cursor range
/// that isn't empty as the target inside it. Empty when idle.
pub(super) fn clauses(&self) -> Vec<Clause> {
match self {
Composition::Idle => Vec::new(),
Composition::Composing { clauses, .. } if !clauses.is_empty() => clauses.clone(),
Composition::Composing { text, .. } => match self.target() {
Some((a, b)) => [Clause::new(0..a), Clause::new(a..b).target(), Clause::new(b..text.len())].into_iter().filter(|c| !c.range.is_empty()).collect(),
None => vec![Clause::new(0..text.len())],
},
}
}
/// The clause being converted, a byte range of the preedit: the input method's target
/// clause, else a cursor range that isn't empty.
pub(super) fn target(&self) -> Option<(usize, usize)> {
let Composition::Composing { text, cursor, clauses } = self else { return None };
if let Some(c) = clauses.iter().find(|c| c.target && c.range.end <= text.len()) {
return Some((c.range.start, c.range.end));
}
match cursor {
Some((a, b)) if a < b && *b <= text.len() => Some((*a, *b)),
_ => None,
}
}
}
/// Steps `composition`.
pub(super) fn step(composition: &mut Composition, event: Event<'_>) -> Effects<Effect> {
let previous = std::mem::take(composition);
match (previous, event) {
(mut old, Event::Ime(Ime::Preedit(text, cursor, clauses))) => {
wipe(&mut old);
if !text.is_empty() {
// Clauses that don't fit the text or a char boundary are the platform's mistake: dropped.
let fits = |c: &Clause| c.range.start < c.range.end && c.range.end <= text.len() && text.is_char_boundary(c.range.start) && text.is_char_boundary(c.range.end);
let clauses = if clauses.iter().all(fits) { clauses.clone() } else { Vec::new() };
*composition = Composition::Composing { text: text.clone(), cursor: *cursor, clauses };
}
Effects::none()
}
(mut old, Event::Ime(Ime::Commit(text))) => {
wipe(&mut old);
Effects::one(Effect::Commit(text.clone()))
}
(Composition::Idle, Event::Ime(Ime::Select(range))) => Effects::one(Effect::Select(range.clone())),
// Mid-composition the input method converts what it already has.
(old @ Composition::Composing { .. }, Event::Ime(Ime::Select(_))) => {
*composition = old;
Effects::none()
}
(old, Event::Ime(Ime::Enabled | Ime::Disabled)) => {
*composition = old;
Effects::none()
}
(Composition::Composing { text, .. }, Event::Finish) => Effects::one(Effect::Commit(text)),
(Composition::Idle, Event::Finish) => Effects::none(),
(mut old, Event::Cancel) => {
wipe(&mut old);
Effects::none()
}
}
}
fn wipe(composition: &mut Composition) {
if let Composition::Composing { text, .. } = composition { text.zeroize(); }
}
+553
View File
@@ -0,0 +1,553 @@
//! Keys, IME and paste on a [`TextEdit`].
use parley::Layout;
use super::*;
use rune_text::{Flow, Ink, TextFlow};
impl TextEdit {
fn insert_newline(&mut self, block_for_new_line: Block, soft: bool) {
if self.secure || self.is_single_line() {
return;
}
self.sync_invariants();
let before = self.snapshot();
let (a, b) = self.range();
let inserted_marks = self.typing.take_at((self.anchor, self.focus)).unwrap_or_else(|| self.inherited_marks_at(a));
self.apply_text_and_attr_replace((a, b), "\n", &inserted_marks, Some(block_for_new_line), soft);
self.record_change(before, EditKind::LineBreak);
}
pub(super) fn set(&mut self, i: usize, extend: bool) {
// A caret moving into a pill steps over it, the way it was going.
let i = self.out_of_pill(i, i > self.focus);
self.focus = i;
if !extend {
self.anchor = i;
}
self.snap_to_pills();
self.typing = Typing::Inherited;
self.affinity = parley::Affinity::Downstream;
}
/// Moves the caret to `i` (on `side` of it, from a visual step), or collapses a selection to
/// the end the arrow points at (`right`).
fn move_h(&mut self, (i, side): (usize, parley::Affinity), extend: bool, right: bool, layout: Option<TextFlow<'_>>) {
let (a, b) = self.range();
if !extend && a != b {
let to = self.collapse_to(layout, right);
self.anchor = to;
self.focus = to;
self.affinity = parley::Affinity::Downstream;
} else {
self.set(i, extend);
if self.focus == i { self.affinity = side; }
}
self.typing = Typing::Inherited;
}
/// The end of the selection Left (`!right`) or Right collapses it to, as Notepad and Word do:
/// the end drawn further that way when both sit on one line, so Left in an Arabic line goes
/// to its logical end. Across lines, the end the arrow steps toward in the focus's paragraph.
fn collapse_to(&self, layout: Option<TextFlow<'_>>, right: bool) -> usize {
let (a, b) = self.range();
let Some(l) = layout.filter(|_| !self.is_masked()) else { return if right { b } else { a } };
let (ca, cb) = (l.caret(self.display_index(a), parley::Affinity::Downstream, 0.0), l.caret(self.display_index(b), parley::Affinity::Upstream, 0.0));
if (ca.y0 - cb.y0).abs() < 1.0 {
return if (ca.x0 <= cb.x0) != right { a } else { b };
}
let forward = right == (l.piece_at(self.display_index(self.focus)).flow == Flow::Ltr);
if forward { b } else { a }
}
/// Applies one key. `layout` is the field's layout for the current text (device px).
pub fn key(&mut self, ev: &KeyEvent, layout: Option<&Layout<Ink>>) -> EditOutcome {
self.key_in(ev, layout.map(TextFlow::Single))
}
/// [`Self::key`] with the field's layout as it draws it, one paragraph's or a by-paragraph field's.
#[doc(hidden)]
pub fn key_in(&mut self, ev: &KeyEvent, layout: Option<TextFlow<'_>>) -> EditOutcome {
let mut out = EditOutcome::default();
if matches!(ev.key, Key::Modifier { .. }) { return out; }
// Any key but Up and Down lets the column go.
let column = std::mem::take(&mut self.column);
self.sync_invariants();
let m = ev.mods;
self.normalize_hidden_selection();
if self.is_hidden_multiline() && matches!(ev.key, Key::Left | Key::Right | Key::Up | Key::Down | Key::Home | Key::End) {
self.focus = self.text.len();
self.anchor = if m.shift { 0 } else { self.focus };
return out;
}
if let Some(c) = ev.control_binding() {
let (key, line) = match c {
'a' => (Key::Left, true), 'e' => (Key::Right, true), 'b' => (Key::Left, false),
'f' => (Key::Right, false), 'p' => (Key::Up, false), 'n' => (Key::Down, false),
'd' => (Key::Delete, false), 'h' => (Key::Backspace, false),
_ => {
// Ctrl-K deletes to the end of the line, or the line break at its end.
self.break_history_group();
if self.is_hidden_multiline() && self.is_pristine() {
self.insert("");
return out;
}
let (a, b) = self.range();
let end = if a == b { self.line_edge(layout, true) } else { b };
let to = if end > a { end } else if a < self.text.len() { next_char(&self.text, a) } else { a };
if to > a { self.replace((a, to), "", EditKind::DeleteRun); }
return out;
}
};
self.column = column;
return self.key_in(&KeyEvent { key, mods: Mods { shift: m.shift, cmd: line, ..Mods::default() } }, layout);
}
if ev.is_command_chord() || ev.is_window_menu_chord() { return out; }
// Typing, deleting and line breaks join the open undo step (`history::step`); any other key closes it.
if !matches!(&ev.key, Key::Text(_) | Key::Backspace | Key::Delete | Key::Enter) { self.break_history_group(); }
// ⌘ moves to a line's edge on macOS. Elsewhere Ctrl, which also sets `cmd`, moves by
// word as Option does on macOS; `cmd` with no Ctrl (a script) keeps the line edge.
let word = m.alt || (m.ctrl && !cfg!(target_os = "macos"));
let line = m.cmd && (cfg!(target_os = "macos") || !m.ctrl);
match &ev.key {
Key::Text(s) => {
if s.chars().any(|c| !c.is_control() || (!self.is_single_line() && matches!(c, '\n' | '\r' | '\t'))) {
let s = self.sanitize(s);
if !s.is_empty() { self.replace(self.range(), &s, if s.contains(['\r', '\n']) { EditKind::LineBreak } else { EditKind::Text }); }
}
}
// A composition's Return and Escape are the input method's.
Key::Enter | Key::Escape if self.preedit().is_some() => {}
Key::Enter => {
if self.is_single_line() {
out.submit = true;
} else if self.secure {
if m.cmd || m.ctrl {
out.submit = true;
} else {
self.replace(self.range(), "\n", EditKind::LineBreak);
}
} else {
let (a, b) = self.range();
let line_idx = self.line_of_byte(a);
let blk = self.blocks.get(line_idx).copied().unwrap_or(Block::Paragraph);
let line_range = self.line_range(line_idx);
if m.shift && self.rich {
// Shift+Return: soft line break keeping the current paragraph's block.
self.insert_newline(blk, true);
} else if m.shift || m.alt {
self.insert_newline(blk, false);
} else {
match blk {
Block::Code => {
// Return on a blank last line leaves the block, as on an empty
// list item; anywhere else it inserts a newline.
if a == b && line_range.is_empty() && self.blocks.get(line_idx + 1) != Some(&Block::Code) {
self.set_block(Block::Paragraph);
} else {
self.insert_newline(Block::Code, false);
}
}
Block::Bullet(_) | Block::Numbered(_) => {
// Return in an empty list item ends the list; otherwise continues it.
if a == b && line_range.is_empty() {
self.set_block(Block::Paragraph);
} else {
self.insert_newline(blk, false);
}
}
Block::Quote => {
if a == b && line_range.is_empty() {
self.set_block(Block::Paragraph);
} else {
self.insert_newline(Block::Quote, false);
}
}
Block::Paragraph => {
out.submit = true;
}
}
}
}
}
Key::Tab => {
if !m.cmd && !m.alt && !m.ctrl && !self.secure && !self.is_single_line() {
if self.active_block() == Block::Code && !m.shift {
self.replace(self.range(), "\t", EditKind::Text);
} else if m.shift {
self.outdent_list();
} else {
self.indent_list();
}
}
}
Key::PageUp | Key::PageDown => {}
Key::Escape => out.blur = true,
Key::Backspace => {
let (a, b) = self.range();
if a != b || (self.is_hidden_multiline() && self.is_pristine()) {
self.replace(self.range(), "", EditKind::Delete);
} else {
let line_idx = self.line_of_byte(a);
let line_range = self.line_range(line_idx);
let blk = self.blocks.get(line_idx).copied().unwrap_or(Block::Paragraph);
let is_soft = self.soft_breaks.binary_search(&(line_idx as u32)).is_ok();
if !line && !word && a == line_range.start && !is_soft && blk != Block::Paragraph {
match blk {
Block::Bullet(lvl) | Block::Numbered(lvl) => {
if lvl > 0 {
self.set_block(blk.with_level(lvl - 1));
} else {
self.set_block(Block::Paragraph);
}
}
Block::Quote | Block::Code => {
if a == 0 || line_range.is_empty() {
self.set_block(Block::Paragraph);
} else {
let from = prev_backspace(&self.text, a);
self.replace((from, a), "", EditKind::Delete);
}
}
Block::Paragraph => unreachable!(),
}
} else if a > 0 {
let from = if line {
if self.is_masked() { 0 } else { self.text[..a].rfind('\n').map_or(0, |i| i + 1) }
} else if word {
self.prev_word(a)
} else {
prev_backspace(&self.text, a)
};
self.replace((from, a), "", if line || word { EditKind::DeleteRun } else { EditKind::Delete });
}
}
}
Key::Delete => {
let (a, b) = self.range();
if a != b || (self.is_hidden_multiline() && self.is_pristine()) {
self.replace(self.range(), "", EditKind::Delete);
} else if a < self.text.len() {
let to = if word { self.next_word(a) } else { next_char(&self.text, a) };
self.replace((a, to), "", if word { EditKind::DeleteRun } else { EditKind::Delete });
}
}
Key::Left if !line && let Some(to) = self.visual_step(layout, false, word) => self.move_h(to, m.shift, false, layout),
Key::Left => {
let i = if line { self.line_edge(layout, false) } else if word { self.prev_word(self.focus) } else { prev_char(&self.text, self.focus) };
self.move_h((i, parley::Affinity::Downstream), m.shift, false, layout);
}
Key::Right if !m.shift && !m.cmd && !m.alt && !m.ctrl && self.at_end_of_trailing_block() => self.leave_trailing_block(),
Key::Down if !m.shift && !m.cmd && !m.alt && !m.ctrl && self.at_end_of_trailing_block() => self.leave_trailing_block(),
Key::Right if !line && let Some(to) = self.visual_step(layout, true, word) => self.move_h(to, m.shift, true, layout),
Key::Right => {
let i = if line { self.line_edge(layout, true) } else if word { self.next_word(self.focus) } else { next_char(&self.text, self.focus) };
self.move_h((i, parley::Affinity::Downstream), m.shift, true, layout);
}
// Home and End go to the text's ends on macOS. Elsewhere they go to the line's
// edge, and with Ctrl to the text's ends.
Key::Home | Key::End => {
let end = ev.key == Key::End;
let i = if cfg!(target_os = "macos") || m.ctrl { if end { self.text.len() } else { 0 } } else { self.line_edge(layout, end) };
self.set(i, m.shift)
}
Key::Up | Key::Down => {
let down = ev.key == Key::Down;
let n = self.text.len();
// A run of Up and Down keeps the column it started in, as a browser's caret does
// through shorter lines (and lines of the other direction).
let mut kept = None;
let i = if line || self.is_masked() {
if down { n } else { 0 }
} else if let Some(l) = layout {
match l.move_line(self.display_index(self.focus), down, column.goal()) {
Some((j, x)) => {
kept = Some(x);
let j = self.model_index(j);
if j == self.focus { if down { n } else { 0 } } else { j }
}
None => n,
}
} else if down {
n
} else {
0
}
.min(n);
if m.shift {
self.focus = i;
self.snap_to_pills();
self.typing = Typing::Inherited;
} else {
self.set_caret(i);
}
self.column = kept.map_or(Column::Free, Column::Kept);
}
// Only the plain chord: with another modifier it's the app's (Ctrl+Alt+Z).
Key::Command(_) => match ev.edit_command() {
Some('z') if m.shift => self.redo(),
Some('z') => self.undo(),
Some('y') if !cfg!(target_os = "macos") => self.redo(),
Some('a') => {
self.anchor = 0;
self.focus = self.text.len();
self.typing = Typing::Inherited;
}
Some('b' | 'i' | 'u') => {
if let Some(mark) = self.format_chord(ev) {
self.toggle_mark(mark);
}
}
Some('c') if !self.secure => out.copy = Some(self.selected().to_owned()),
Some('x') if !self.secure => {
out.copy = Some(self.selected().to_owned());
self.insert("");
}
_ => {}
},
Key::Function(_) | Key::ContextMenu | Key::Insert | Key::PrintScreen | Key::ScrollLock | Key::Pause | Key::Modifier { .. } => {}
}
out
}
/// The caret is at the end of the text, in a code block or quote there that it can't move
/// out of by itself.
fn at_end_of_trailing_block(&self) -> bool {
let n = self.text.len();
!self.secure
&& !self.is_single_line()
&& self.preedit().is_none()
&& (self.anchor, self.focus) == (n, n)
&& matches!(self.blocks.last(), Some(Block::Code | Block::Quote))
}
/// Adds an empty paragraph after a trailing code block or quote and puts the caret in it:
/// one undo step.
fn leave_trailing_block(&mut self) {
self.sync_invariants();
self.break_history_group();
let before = self.snapshot();
let n = self.text.len();
self.typing = Typing::Inherited;
self.apply_text_and_attr_replace((n, n), "\n", &[], Some(Block::Paragraph), false);
self.record_change(before, EditKind::Other);
}
/// Where Left (Right when `right`) moves the caret, by a character or a `word`, when the
/// text moves visually (`CaretMotion`): across the line as it's drawn, and at the line's
/// edge on the way its paragraph runs, so Left leaves a right-to-left line forward. `None`
/// when it moves by the logical order.
fn visual_step(&self, layout: Option<TextFlow<'_>>, right: bool, word: bool) -> Option<(usize, parley::Affinity)> {
use super::caret_motion::{Arrow, Landing, visual_in};
let arrow = match (right, word) {
(false, false) => Arrow::Left,
(true, false) => Arrow::Right,
(false, true) => Arrow::WordLeft,
(true, true) => Arrow::WordRight,
};
let l = layout?;
let hidden = self.is_masked();
let (landing, flow) = visual_in(l, self.display_index(self.focus), self.affinity, arrow, hidden)?;
Some(match landing {
// Off macOS a word forward goes on past the spaces after it, as Chromium's lands at the
// next word's start: to the right where the text runs left to right (Ctrl+Right), to
// the left where it runs right to left (Ctrl+Left).
Landing::At(mut j, mut side) if word && !cfg!(target_os = "macos") => {
let step = if right { Arrow::Right } else { Arrow::Left };
while super::caret_motion::space_ahead(l, j, side, right)
&& let Some((Landing::At(k, s), _)) = visual_in(l, j, side, step, hidden)
{
(j, side) = (k, s);
}
(self.model_index(j), side)
}
Landing::At(j, side) => (self.model_index(j), side),
Landing::Edge => {
let forward = right == (flow == Flow::Ltr);
let i = match (forward, word) {
(true, false) => next_char(&self.text, self.focus),
(true, true) => self.next_word(self.focus),
(false, false) => prev_char(&self.text, self.focus),
(false, true) => self.prev_word(self.focus),
};
(i, parley::Affinity::Downstream)
}
})
}
fn line_edge(&self, layout: Option<TextFlow<'_>>, end: bool) -> usize {
if self.is_masked() {
return if end { self.text.len() } else { 0 };
}
if let Some(l) = layout {
return self.model_index(l.line_edge(self.display_index(self.focus), end));
}
if end {
self.text[self.focus..].find('\n').map_or(self.text.len(), |i| self.focus + i)
} else {
self.text[..self.focus].rfind('\n').map_or(0, |i| i + 1)
}
}
pub fn ime(&mut self, ev: &Ime) -> EditOutcome {
if self.secure { self.cancel_composition(); return EditOutcome::default(); }
self.sync_invariants();
for effect in ime::step(&mut self.composition, ime::Event::Ime(ev)) {
match effect {
ime::Effect::Commit(mut s) => {
self.commit_composed(&s);
s.zeroize();
}
// Reconversion: the composition that follows replaces the selection.
ime::Effect::Select(range) => {
let (a, b) = (Self::clamp_char_boundary(&self.text, range.start), Self::clamp_char_boundary(&self.text, range.end));
self.break_history_group();
self.set_selection(a, b);
}
}
}
EditOutcome::default()
}
/// Writes a composition's text over the selection as typing: it joins the open undo step,
/// as each Hangul syllable or kana phrase a person commits is part of what they type, the
/// way a browser's field groups them.
pub(super) fn commit_composed(&mut self, s: &str) {
let clean = self.sanitize(s);
if clean.is_empty() { return; }
let kind = if clean.contains(['\r', '\n']) { EditKind::LineBreak } else { EditKind::Text };
self.replace(self.range(), &clean, kind);
}
pub fn paste(&mut self, s: &str) -> EditOutcome {
self.normalize_hidden_selection();
let s = self.sanitize(s);
self.insert(&s);
EditOutcome::default()
}
/// Paste rich HTML (`html`) with plain-text fallback (`plain`) into `self` at the current
/// selection, recorded as a single undo step. Does not touch the OS clipboard. A plain field,
/// or HTML with no marks or blocks this model keeps, pastes `plain` instead. Pills
/// (`<span data-pill="id">`) paste as their plain labels: a field restores them only from
/// its app's own copies, and an app's paste hook can with
/// [`paste_html_with_pills`](Self::paste_html_with_pills).
pub fn paste_html(&mut self, html_str: &str, plain: &str) -> EditOutcome {
self.paste_rich(html_str, plain, false)
}
/// [`paste_html`](Self::paste_html), keeping the HTML's [`Mark::Pill`]s.
pub fn paste_html_with_pills(&mut self, html_str: &str, plain: &str) -> EditOutcome {
self.paste_rich(html_str, plain, true)
}
fn paste_rich(&mut self, html_str: &str, plain: &str, pills: bool) -> EditOutcome {
if self.secure || html_str.trim().is_empty() {
return self.paste(plain);
}
let mut frag = Self::from_html(html_str);
if !pills {
frag.marks.retain(|m| !m.mark.is_pill());
}
// HTML that only colours or lays out text (a code editor's copy) would collapse the
// plain text's whitespace for nothing.
let frag = self.keep_allowed(frag);
let unformatted = frag.marks.is_empty() && frag.blocks.iter().all(|&b| b == Block::Paragraph);
if !plain.is_empty() && (frag.text.is_empty() || unformatted) {
return self.paste(plain);
}
if !self.rich {
return self.paste(if plain.is_empty() { frag.text.as_str() } else { plain });
}
self.sync_invariants();
// A code block takes the plain text, whose whitespace HTML would have collapsed.
if !self.is_single_line() {
let (a, _) = self.range();
if self.blocks.get(self.line_of_byte(a)) == Some(&Block::Code) {
return self.paste(if plain.is_empty() { frag.text.as_str() } else { plain });
}
}
self.break_history_group();
let before = self.snapshot();
let (a, b) = self.range();
if self.is_single_line() {
// Single-line field: strip line breaks from `frag.text` while keeping inline marks.
let mut clean = String::with_capacity(frag.text.len());
let mut byte_map = vec![0usize; frag.text.len() + 1];
for (i, ch) in frag.text.char_indices() {
byte_map[i] = clean.len();
if !ch.is_control() && !matches!(ch, '\u{2028}' | '\u{2029}') {
clean.push(ch);
} else if ch == '\n' && !clean.ends_with(' ') && !clean.is_empty() {
clean.push(' ');
}
}
byte_map[frag.text.len()] = clean.len();
self.apply_text_and_attr_replace((a, b), &clean, &[], None, false);
for m in &frag.marks {
let s_idx = a + byte_map[m.start.min(frag.text.len())];
let e_idx = a + byte_map[m.end.min(frag.text.len())];
if s_idx < e_idx {
self.marks.push(MarkRange { start: s_idx, end: e_idx, mark: m.mark.clone() });
}
}
self.typing = Typing::Inherited;
self.normalize_marks();
self.record_change(before, EditKind::Other);
return EditOutcome::default();
}
// First delete `a..b` if non-empty.
if a < b {
self.apply_text_and_attr_replace((a, b), "", &[], None, false);
}
let ins_at = a;
let line_idx = self.line_of_byte(ins_at);
let line_range = self.line_range(line_idx);
let line_was_empty = line_range.is_empty();
let orig_block = self.blocks.get(line_idx).copied().unwrap_or(Block::Paragraph);
self.apply_text_and_attr_replace((ins_at, ins_at), &frag.text, &[], None, false);
// Apply `frag.blocks` and `frag.soft_breaks`.
let frag_lines = frag.blocks.len();
if frag_lines == 1 {
if line_was_empty && orig_block == Block::Paragraph && frag.blocks[0] != Block::Paragraph {
if let Some(slot) = self.blocks.get_mut(line_idx) {
*slot = frag.blocks[0];
}
}
} else if frag_lines > 1 {
if (line_was_empty || ins_at == line_range.start) && orig_block == Block::Paragraph {
if let Some(slot) = self.blocks.get_mut(line_idx) {
*slot = frag.blocks[0];
}
}
for k in 1..frag_lines {
if let Some(slot) = self.blocks.get_mut(line_idx + k) {
*slot = frag.blocks[k];
}
}
for &sb in &frag.soft_breaks {
let target = line_idx + sb as usize;
if target > 0 {
self.soft_breaks.push(target as u32);
}
}
}
// Add `frag.marks` shifted by `ins_at`.
for m in &frag.marks {
self.marks.push(MarkRange {
start: ins_at + m.start,
end: ins_at + m.end,
mark: m.mark.clone(),
});
}
self.typing = Typing::Inherited;
self.sync_invariants();
self.record_change(before, EditKind::Other);
EditOutcome::default()
}
}
+272
View File
@@ -0,0 +1,272 @@
//! Key events as the shell hands them to handlers and the focused field.
use zeroize::Zeroize;
#[doc(hidden)]
pub const PRIMARY: u8 = 1;
#[doc(hidden)]
pub const CTRL: u8 = 2;
#[doc(hidden)]
pub const ALT: u8 = 4;
#[doc(hidden)]
pub const SHIFT: u8 = 8;
#[doc(hidden)]
pub const SUPER: u8 = 16;
/// The platform whose keyboard conventions a chord resolves and draws with.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum KeyPlatform {
/// ⌘ is the primary modifier; Control is a separate key. Glyph labels: "⇧⌘T".
Mac,
/// Ctrl is the primary modifier. Word labels: "Ctrl+Shift+T", the logo key is "Win".
Windows,
/// Ctrl is the primary modifier. Word labels, the logo key is "Super". The web uses this
/// in a browser that isn't on an Apple device.
Linux,
}
impl KeyPlatform {
/// The platform this build runs on.
#[cfg(not(target_arch = "wasm32"))]
pub const fn current() -> Self {
if cfg!(any(target_os = "macos", target_os = "ios")) { return Self::Mac; }
if cfg!(target_os = "windows") { return Self::Windows; }
Self::Linux
}
/// The platform the browser runs on: `Mac` when `navigator.platform` names an Apple
/// device (as the browser's own shortcuts do), else `Linux`.
#[cfg(target_arch = "wasm32")]
pub fn current() -> Self {
static PLATFORM: std::sync::OnceLock<KeyPlatform> = std::sync::OnceLock::new();
*PLATFORM.get_or_init(|| {
let platform = js_sys::Reflect::get(&js_sys::global(), &"navigator".into())
.and_then(|navigator| js_sys::Reflect::get(&navigator, &"platform".into()))
.ok().and_then(|p| p.as_string()).unwrap_or_default();
if ["Mac", "iPod", "iPhone", "iPad"].iter().any(|apple| platform.contains(apple)) { Self::Mac } else { Self::Linux }
})
}
fn mac(self) -> bool { matches!(self, Self::Mac) }
}
/// The modifiers held with a key. `shift`, `alt`, `ctrl` and `logo` are keys; `cmd` is the
/// platform's primary shortcut modifier, reported alongside its key: ⌘ on macOS (with `logo`)
/// and Ctrl elsewhere (with `ctrl`), so Ctrl+W on Windows is `{ cmd, ctrl }`. A test of
/// `cmd && !ctrl` therefore never passes off macOS. Match shortcuts with a
/// `Chord` ("mod+w", "ctrl+tab") rather than by comparing flags.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Mods {
pub shift: bool,
/// The primary shortcut modifier: ⌘ on macOS, Ctrl elsewhere (the web reports either).
pub cmd: bool,
pub alt: bool,
/// The Control key, on every platform; off macOS `cmd` is set with it.
pub ctrl: bool,
/// The Super/Windows key (Command on macOS, where `cmd` also reports it).
pub logo: bool,
}
impl Mods {
/// Whether the platform's primary shortcut modifier is held: `cmd`.
pub fn primary(self) -> bool { self.cmd }
}
/// `bits` with the modifiers that are one key on `platform` merged: Ctrl into the primary
/// off macOS, the logo key into it on macOS.
#[doc(hidden)]
pub fn fold(bits: u8, platform: KeyPlatform) -> u8 {
let same = if platform.mac() { SUPER } else { CTRL };
if bits & same != 0 { bits & !same | PRIMARY } else { bits }
}
/// The keys `m` says are held, as chord bits for `platform`. `cmd` repeats the key this build
/// reports as primary: ⌘ (`logo`) on macOS, Ctrl elsewhere (iOS too), Ctrl or ⌘ on the web. A `Mods`
/// with `cmd` and neither key (a script, a test) holds `platform`'s primary.
#[doc(hidden)]
pub fn held(m: Mods, platform: KeyPlatform) -> u8 {
let bare = m.cmd && !m.ctrl && !m.logo;
let (ctrl, logo) = if bare || cfg!(target_arch = "wasm32") {
(m.ctrl, m.logo)
} else if cfg!(target_os = "macos") {
(m.ctrl, m.logo || m.cmd)
} else {
(m.ctrl || m.cmd, m.logo)
};
let (ctrl_bit, logo_bit) = if platform.mac() { (CTRL, PRIMARY) } else { (PRIMARY, SUPER) };
[(bare, PRIMARY), (ctrl, ctrl_bit), (logo, logo_bit), (m.alt, ALT), (m.shift, SHIFT)]
.into_iter().filter(|(on, _)| *on).fold(0, |bits, (_, bit)| bits | bit)
}
/// Whether `m` holds `platform`'s primary modifier and no other but Shift, or none at all (a
/// script's `Key::Command`): ⌘ alone on macOS, Ctrl alone elsewhere. For the edit commands a
/// text field takes (copy, paste, undo), which another modifier turns into an app's chord.
pub(crate) fn primary_alone_on(m: Mods, platform: KeyPlatform) -> bool {
matches!(held(m, platform) & !SHIFT, 0 | PRIMARY)
}
/// [`primary_alone_on`] for [`KeyPlatform::current`].
pub(crate) fn primary_alone(m: Mods) -> bool {
primary_alone_on(m, KeyPlatform::current())
}
/// A logical key. More keys may come, so a `match` needs a `_` arm.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq)]
pub enum Key {
Text(String),
Enter,
Backspace,
Delete,
Left,
Right,
Up,
Down,
Home,
End,
/// Page Up. Unclaimed, it scrolls the nearest scroll view up by most of a viewport.
/// Text fields leave it alone, as AppKit's do: the view scrolls and the caret stays.
PageUp,
/// Page Down, as `PageUp` the other way.
PageDown,
/// Insert (Help on older Mac keyboards). Text fields ignore it; apps can bind it.
Insert,
/// Print Screen (SysRq). Text fields ignore it; apps can bind it. Windows sends it only
/// on release, so its press and release arrive together.
PrintScreen,
/// Scroll Lock. Text fields ignore it; apps can bind it.
ScrollLock,
/// Pause (Break). Text fields ignore it; apps can bind it.
Pause,
Escape,
Tab,
/// Any character typed with Cmd (Ctrl off macOS), lowercased: a letter ("a", "c", "v"), a
/// digit (⌘1) or punctuation (⌘,). Off macOS, a key that types a non-ASCII character
/// arrives as the US key in its place, so Ctrl+V on a Russian layout is `Command('v')`
/// (`Tx::key_base` still says "м"). `mods` still says whether Shift, Option or Ctrl were
/// held too. Space is the exception: Cmd-Space arrives natively as `Text(" ")` with
/// `mods.cmd` (scripts send `Command(' ')`). The other native `Text` with `mods.cmd` is a
/// character typed with Left Ctrl + Left Alt on Windows, which is AltGr there ("@" on a
/// German layout's Q): it inserts, and `Chord::matches_tx` still finds "ctrl+alt+q".
/// [`KeyEvent::is_command`] matches either form.
Command(char),
/// A function key, F1 through F24. Text fields ignore it; apps can bind it.
Function(u8),
/// The Menu (Application) key. Unclaimed, it opens the focused element's context menu, as
/// Shift+F10 does: see `El::on_secondary_press`.
ContextMenu,
/// A modifier key going down (`pressed`) or up on its own, sent only where the app opts in
/// with `App::modifier_keys` (or `Runtime::set_modifier_keys`). `mods` holds the modifiers
/// after the change, as AppKit's flagsChanged does: Shift's press has `shift` set and its
/// release doesn't, unless the other Shift is still down. A held modifier never repeats.
/// Text fields, selection, focus traversal and shortcuts ignore it.
Modifier { modifier: Modifier, pressed: bool },
}
/// A modifier key, by side. Alt is Option on macOS; Super is Command on macOS and the Windows
/// key elsewhere.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Modifier {
ShiftLeft,
ShiftRight,
ControlLeft,
ControlRight,
AltLeft,
AltRight,
SuperLeft,
SuperRight,
/// Fn, or Globe on recent Mac keyboards. Other platforms rarely report it: their keyboards
/// handle Fn in firmware.
Fn,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum KeySide {
Left,
Right,
}
impl Modifier {
/// Which side of the keyboard the key is on; None for Fn.
pub fn side(self) -> Option<KeySide> {
use Modifier::*;
match self {
ShiftLeft | ControlLeft | AltLeft | SuperLeft => Some(KeySide::Left),
ShiftRight | ControlRight | AltRight | SuperRight => Some(KeySide::Right),
Fn => None,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct KeyEvent {
pub key: Key,
pub mods: Mods,
}
impl KeyEvent {
/// Whether this is Cmd (Ctrl off macOS) plus `c`, whatever else is held: `Key::Command(c)`,
/// or for `' '` the `Key::Text(" ")` a native Cmd-Space sends. Letters match either case;
/// check `mods.shift` for ⇧⌘ chords.
pub fn is_command(&self, c: char) -> bool {
let c = c.to_ascii_lowercase();
match &self.key {
Key::Command(k) => *k == c,
Key::Text(t) => c == ' ' && t == " " && self.mods.cmd,
_ => false,
}
}
/// Text typed with Cmd (macOS) or Ctrl held, such as an unclaimed Shift-Cmd-Space. It never
/// inserts, matching browsers and AppKit, but still reaches key handlers. Ctrl+Alt is AltGr
/// on Windows and Linux, so text typed with both still inserts there; Option alone types.
#[doc(hidden)]
pub fn is_command_chord(&self) -> bool {
let m = self.mods;
matches!(self.key, Key::Text(_)) && (m.cmd || m.ctrl) && (cfg!(target_os = "macos") || !m.alt)
}
/// The standard edit command this is (paste, copy, cut, select all, undo, redo, format):
/// `Key::Command(c)` with the primary modifier alone, ⌘ on macOS and Ctrl elsewhere, or
/// Shift too for ⇧⌘Z. Another modifier (Ctrl+Alt+V, ⌃⌘C, Ctrl+Shift+V) makes it an
/// app's chord, which reaches `on_key` instead.
#[doc(hidden)]
pub fn edit_command(&self) -> Option<char> {
let Key::Command(c) = self.key else { return None };
(primary_alone(self.mods) && (c == 'z' || !self.mods.shift)).then_some(c)
}
/// Alt+Space off macOS: the window menu's key. It never types a space, and on Windows opens
/// the window menu when no handler takes it. (Option+Space types on macOS.)
#[doc(hidden)]
pub fn is_window_menu_chord(&self) -> bool {
let m = self.mods;
!cfg!(target_os = "macos") && matches!(&self.key, Key::Text(t) if t == " ") && m.alt && !m.ctrl && !m.cmd && !m.logo
}
/// A macOS Control-letter text binding (Ctrl-A, Ctrl-E, Ctrl-K, …), as in every AppKit field.
#[doc(hidden)]
pub fn control_binding(&self) -> Option<char> {
let m = self.mods;
let Key::Text(s) = &self.key else { return None };
let c = s.chars().next().filter(|_| s.chars().count() == 1)?.to_ascii_lowercase();
(cfg!(target_os = "macos") && m.ctrl && !m.cmd && !m.alt && "abefpndhk".contains(c)).then_some(c)
}
}
/// The key pressed with no modifiers.
impl From<Key> for KeyEvent {
fn from(key: Key) -> Self {
KeyEvent { key, mods: Mods::default() }
}
}
impl Drop for KeyEvent {
fn drop(&mut self) {
if let Key::Text(text) = &mut self.key { text.zeroize(); }
}
}
#[cfg(test)]
#[path = "keys_tests.rs"]
mod tests;
+157
View File
@@ -0,0 +1,157 @@
use super::*;
const PLATFORMS: [KeyPlatform; 3] = [KeyPlatform::Mac, KeyPlatform::Windows, KeyPlatform::Linux];
/// Expected `[Mac, Windows, Linux]` results of `primary_alone_on` for every combination of
/// `(cmd, ctrl, logo, alt, shift)` (bit 0..4 respectively) on targets where `cmd` repeats Ctrl
/// (Windows, Linux, iOS).
const EXPECTED_OTHER: [[bool; 3]; 32] = [
[true, true, true], // 00: cmd=false ctrl=false logo=false alt=false shift=false
[true, true, true], // 01: cmd=true ctrl=false logo=false alt=false shift=false
[false, true, true], // 02: cmd=false ctrl=true logo=false alt=false shift=false
[false, true, true], // 03: cmd=true ctrl=true logo=false alt=false shift=false
[true, false, false], // 04: cmd=false ctrl=false logo=true alt=false shift=false
[false, false, false], // 05: cmd=true ctrl=false logo=true alt=false shift=false
[false, false, false], // 06: cmd=false ctrl=true logo=true alt=false shift=false
[false, false, false], // 07: cmd=true ctrl=true logo=true alt=false shift=false
[false, false, false], // 08: cmd=false ctrl=false logo=false alt=true shift=false
[false, false, false], // 09: cmd=true ctrl=false logo=false alt=true shift=false
[false, false, false], // 10: cmd=false ctrl=true logo=false alt=true shift=false
[false, false, false], // 11: cmd=true ctrl=true logo=false alt=true shift=false
[false, false, false], // 12: cmd=false ctrl=false logo=true alt=true shift=false
[false, false, false], // 13: cmd=true ctrl=false logo=true alt=true shift=false
[false, false, false], // 14: cmd=false ctrl=true logo=true alt=true shift=false
[false, false, false], // 15: cmd=true ctrl=true logo=true alt=true shift=false
[true, true, true], // 16: cmd=false ctrl=false logo=false alt=false shift=true
[true, true, true], // 17: cmd=true ctrl=false logo=false alt=false shift=true
[false, true, true], // 18: cmd=false ctrl=true logo=false alt=false shift=true
[false, true, true], // 19: cmd=true ctrl=true logo=false alt=false shift=true
[true, false, false], // 20: cmd=false ctrl=false logo=true alt=false shift=true
[false, false, false], // 21: cmd=true ctrl=false logo=true alt=false shift=true
[false, false, false], // 22: cmd=false ctrl=true logo=true alt=false shift=true
[false, false, false], // 23: cmd=true ctrl=true logo=true alt=false shift=true
[false, false, false], // 24: cmd=false ctrl=false logo=false alt=true shift=true
[false, false, false], // 25: cmd=true ctrl=false logo=false alt=true shift=true
[false, false, false], // 26: cmd=false ctrl=true logo=false alt=true shift=true
[false, false, false], // 27: cmd=true ctrl=true logo=false alt=true shift=true
[false, false, false], // 28: cmd=false ctrl=false logo=true alt=true shift=true
[false, false, false], // 29: cmd=true ctrl=false logo=true alt=true shift=true
[false, false, false], // 30: cmd=false ctrl=true logo=true alt=true shift=true
[false, false, false], // 31: cmd=true ctrl=true logo=true alt=true shift=true
];
/// Expected `[Mac, Windows, Linux]` results of `primary_alone_on` on macOS, where `cmd` repeats
/// `logo` (⌘).
const EXPECTED_MACOS: [[bool; 3]; 32] = [
[true, true, true], // 00: cmd=false ctrl=false logo=false alt=false shift=false
[true, true, true], // 01: cmd=true ctrl=false logo=false alt=false shift=false
[false, true, true], // 02: cmd=false ctrl=true logo=false alt=false shift=false
[false, false, false], // 03: cmd=true ctrl=true logo=false alt=false shift=false
[true, false, false], // 04: cmd=false ctrl=false logo=true alt=false shift=false
[true, false, false], // 05: cmd=true ctrl=false logo=true alt=false shift=false
[false, false, false], // 06: cmd=false ctrl=true logo=true alt=false shift=false
[false, false, false], // 07: cmd=true ctrl=true logo=true alt=false shift=false
[false, false, false], // 08: cmd=false ctrl=false logo=false alt=true shift=false
[false, false, false], // 09: cmd=true ctrl=false logo=false alt=true shift=false
[false, false, false], // 10: cmd=false ctrl=true logo=false alt=true shift=false
[false, false, false], // 11: cmd=true ctrl=true logo=false alt=true shift=false
[false, false, false], // 12: cmd=false ctrl=false logo=true alt=true shift=false
[false, false, false], // 13: cmd=true ctrl=false logo=true alt=true shift=false
[false, false, false], // 14: cmd=false ctrl=true logo=true alt=true shift=false
[false, false, false], // 15: cmd=true ctrl=true logo=true alt=true shift=false
[true, true, true], // 16: cmd=false ctrl=false logo=false alt=false shift=true
[true, true, true], // 17: cmd=true ctrl=false logo=false alt=false shift=true
[false, true, true], // 18: cmd=false ctrl=true logo=false alt=false shift=true
[false, false, false], // 19: cmd=true ctrl=true logo=false alt=false shift=true
[true, false, false], // 20: cmd=false ctrl=false logo=true alt=false shift=true
[true, false, false], // 21: cmd=true ctrl=false logo=true alt=false shift=true
[false, false, false], // 22: cmd=false ctrl=true logo=true alt=false shift=true
[false, false, false], // 23: cmd=true ctrl=true logo=true alt=false shift=true
[false, false, false], // 24: cmd=false ctrl=false logo=false alt=true shift=true
[false, false, false], // 25: cmd=true ctrl=false logo=false alt=true shift=true
[false, false, false], // 26: cmd=false ctrl=true logo=false alt=true shift=true
[false, false, false], // 27: cmd=true ctrl=true logo=false alt=true shift=true
[false, false, false], // 28: cmd=false ctrl=false logo=true alt=true shift=true
[false, false, false], // 29: cmd=true ctrl=false logo=true alt=true shift=true
[false, false, false], // 30: cmd=false ctrl=true logo=true alt=true shift=true
[false, false, false], // 31: cmd=true ctrl=true logo=true alt=true shift=true
];
/// Expected `[Mac, Windows, Linux]` results of `primary_alone_on` on wasm32, where `cmd` can
/// repeat either `ctrl` or `logo`.
const EXPECTED_WASM: [[bool; 3]; 32] = [
[true, true, true], // 00: cmd=false ctrl=false logo=false alt=false shift=false
[true, true, true], // 01: cmd=true ctrl=false logo=false alt=false shift=false
[false, true, true], // 02: cmd=false ctrl=true logo=false alt=false shift=false
[false, true, true], // 03: cmd=true ctrl=true logo=false alt=false shift=false
[true, false, false], // 04: cmd=false ctrl=false logo=true alt=false shift=false
[true, false, false], // 05: cmd=true ctrl=false logo=true alt=false shift=false
[false, false, false], // 06: cmd=false ctrl=true logo=true alt=false shift=false
[false, false, false], // 07: cmd=true ctrl=true logo=true alt=false shift=false
[false, false, false], // 08: cmd=false ctrl=false logo=false alt=true shift=false
[false, false, false], // 09: cmd=true ctrl=false logo=false alt=true shift=false
[false, false, false], // 10: cmd=false ctrl=true logo=false alt=true shift=false
[false, false, false], // 11: cmd=true ctrl=true logo=false alt=true shift=false
[false, false, false], // 12: cmd=false ctrl=false logo=true alt=true shift=false
[false, false, false], // 13: cmd=true ctrl=false logo=true alt=true shift=false
[false, false, false], // 14: cmd=false ctrl=true logo=true alt=true shift=false
[false, false, false], // 15: cmd=true ctrl=true logo=true alt=true shift=false
[true, true, true], // 16: cmd=false ctrl=false logo=false alt=false shift=true
[true, true, true], // 17: cmd=true ctrl=false logo=false alt=false shift=true
[false, true, true], // 18: cmd=false ctrl=true logo=false alt=false shift=true
[false, true, true], // 19: cmd=true ctrl=true logo=false alt=false shift=true
[true, false, false], // 20: cmd=false ctrl=false logo=true alt=false shift=true
[true, false, false], // 21: cmd=true ctrl=false logo=true alt=false shift=true
[false, false, false], // 22: cmd=false ctrl=true logo=true alt=false shift=true
[false, false, false], // 23: cmd=true ctrl=true logo=true alt=false shift=true
[false, false, false], // 24: cmd=false ctrl=false logo=false alt=true shift=true
[false, false, false], // 25: cmd=true ctrl=false logo=false alt=true shift=true
[false, false, false], // 26: cmd=false ctrl=true logo=false alt=true shift=true
[false, false, false], // 27: cmd=true ctrl=true logo=false alt=true shift=true
[false, false, false], // 28: cmd=false ctrl=false logo=true alt=true shift=true
[false, false, false], // 29: cmd=true ctrl=false logo=true alt=true shift=true
[false, false, false], // 30: cmd=false ctrl=true logo=true alt=true shift=true
[false, false, false], // 31: cmd=true ctrl=true logo=true alt=true shift=true
];
#[test]
fn primary_alone_matches_truth_table_for_all_modifier_combinations_and_platforms() {
let table = if cfg!(target_arch = "wasm32") {
&EXPECTED_WASM
} else if cfg!(target_os = "macos") {
&EXPECTED_MACOS
} else {
&EXPECTED_OTHER
};
for bits in 0u8..32 {
let mods = Mods {
cmd: bits & 1 != 0,
ctrl: bits & 2 != 0,
logo: bits & 4 != 0,
alt: bits & 8 != 0,
shift: bits & 16 != 0,
};
for (idx, platform) in PLATFORMS.into_iter().enumerate() {
assert_eq!(
primary_alone_on(mods, platform),
table[bits as usize][idx],
"bits={bits:02} {mods:?} on {platform:?}"
);
}
assert_eq!(
primary_alone(mods),
primary_alone_on(mods, KeyPlatform::current()),
"current() wrapper mismatch for bits={bits:02} {mods:?}"
);
}
}
#[test]
fn fold_merges_primary_alias_per_platform() {
for bits in 0u8..32 {
assert_eq!(fold(bits, KeyPlatform::Mac), if bits & SUPER != 0 { (bits & !SUPER) | PRIMARY } else { bits });
assert_eq!(fold(bits, KeyPlatform::Windows), if bits & CTRL != 0 { (bits & !CTRL) | PRIMARY } else { bits });
assert_eq!(fold(bits, KeyPlatform::Linux), if bits & CTRL != 0 { (bits & !CTRL) | PRIMARY } else { bits });
}
}
+750
View File
@@ -0,0 +1,750 @@
//! Single and rich text-field editing: the attributed model an app owns (`TextEdit`) and the
//! key/IME events the shell routes to the focused field. Movement that depends on wrapping
//! (up/down, line start/end) uses the field's current Parley layout, rebuilt by the runtime
//! before each event.
//!
//! Invariants: `anchor` and `focus` are byte offsets on char boundaries of `text`; preedit text
//! is never part of `text` until committed; inline `marks` are non-empty char-boundary byte
//! ranges sorted by start; `blocks` has one entry per `\n`-separated line of `text`.
use std::ops::Range;
use std::sync::Arc;
use zeroize::{Zeroize, Zeroizing};
use rune_core::color::Color;
use rune_text::Link;
mod caret_motion;
mod direction_keys;
mod display;
mod history;
mod html;
mod ime;
mod input;
mod keys;
mod marks;
mod model;
mod replace;
mod secure;
mod typing;
#[doc(hidden)]
pub use direction_keys::DirChord;
#[doc(hidden)]
pub use direction_keys::step_dir_chord;
#[doc(hidden)]
pub use history::History;
pub use ime::Clause;
pub use ime::Ime;
#[doc(hidden)]
pub use ime::ImeText;
#[doc(hidden)]
pub use keys::ALT;
#[doc(hidden)]
pub use keys::CTRL;
pub use keys::Key;
pub use keys::KeyEvent;
pub use keys::KeyPlatform;
pub use keys::KeySide;
pub use keys::Modifier;
pub use keys::Mods;
#[doc(hidden)]
pub use keys::PRIMARY;
#[doc(hidden)]
pub use keys::SHIFT;
#[doc(hidden)]
pub use keys::SUPER;
#[doc(hidden)]
pub use keys::fold;
#[doc(hidden)]
pub use keys::held;
pub use model::Block;
pub use model::MAX_LIST_LEVEL;
pub use model::Mark;
pub use model::MarkRange;
pub use model::ParagraphInfo;
pub use model::RichStyle;
#[doc(hidden)]
pub use secure::MULTILINE_SECURE_MASK;
#[doc(hidden)]
pub use secure::Masking;
use caret_motion::Column;
use direction_keys::FieldDir;
use history::{EditKind, EditedTag, Group};
use replace::{count_newlines, next_char, prev_backspace, prev_char};
use secure::LineMode;
use typing::Typing;
#[derive(Clone, Default, PartialEq)]
pub struct TextEdit {
/// Use `replace_text` to replace a secret without leaving its old allocation behind.
pub text: String,
pub anchor: usize,
pub focus: usize,
/// The input method's composition (`TextEdit::preedit`).
composition: ime::Composition,
pub focused: bool,
marks: Vec<MarkRange>,
blocks: Vec<Block>,
/// Line indices (`> 0`) created by `Shift+Return` (`<br>`): indented with their block,
/// without starting a new list marker or incrementing list numbering.
pub(crate) soft_breaks: Vec<u32>,
/// The style the next typed text takes: a mark toggled on an empty selection arms it.
typing: Typing,
history: Arc<History>,
/// Set inside [`TextEdit::undo_group`]: edits record nothing until the outermost group ends.
group: Group,
secure: bool,
revealed: bool,
/// Mirrors the field's `El::single_line()`; the runtime sets it before each edit.
line_mode: LineMode,
/// Formatting keys and rich paste are on (see [`TextEdit::rich`]).
rich: bool,
/// The mark kinds this field keeps, one bit per [`Mark::kind_order`]; `None` keeps all.
allowed_marks: Option<u16>,
/// The block kinds this field keeps ([`Block::kind_bit`]); `None` keeps all.
allowed_blocks: Option<u8>,
/// Whether a user has edited the value since `replace_text`.
edited_tag: EditedTag,
/// The column a run of Up and Down keeps.
column: Column,
/// Which side of `focus` the caret is drawn on where two runs of different direction meet:
/// a byte there has a place at the end of one run and at the start of the other. Arrows
/// and presses set it; anything else puts it before the byte that follows.
#[doc(hidden)]
pub affinity: parley::Affinity,
/// The direction Ctrl+Left Shift or Ctrl+Right Shift set (`direction_keys`).
dir: FieldDir,
}
impl std::fmt::Debug for TextEdit {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TextEdit").field("text", &if self.secure { "[redacted]" } else { &self.text })
.field("anchor", &self.anchor).field("focus", &self.focus).field("focused", &self.focused)
.field("marks", &self.marks).field("blocks", &self.blocks)
.field("secure", &self.secure).field("revealed", &self.revealed).finish_non_exhaustive()
}
}
/// Hashes everything a field draws: text, selection, IME composition, focus, marks, blocks and
/// whether it's secure or revealed. Pass the edit itself in a `memo` version so
/// the field redraws as the caret or rich formatting changes. A hidden secure field hashes its
/// length (single-line) or non-empty state (multi-line), not its text.
impl std::hash::Hash for TextEdit {
fn hash<H: std::hash::Hasher>(&self, h: &mut H) {
match self.masking() {
Masking::Hidden { multiline: true } => {
(!self.text.is_empty()).hash(h);
(self.anchor != self.focus).hash(h);
}
Masking::Hidden { multiline: false } => {
self.text.chars().count().hash(h);
self.anchor.hash(h);
self.focus.hash(h);
}
Masking::Plain | Masking::Shown => {
self.text.hash(h);
self.anchor.hash(h);
self.focus.hash(h);
}
}
self.composition.hash(h);
self.focused.hash(h);
self.marks.hash(h);
if !self.secure {
self.blocks.hash(h);
}
self.soft_breaks.hash(h);
self.typing.hash(h);
self.secure.hash(h);
self.revealed.hash(h);
self.is_single_line().hash(h);
self.dir.hash(h);
}
}
impl Drop for TextEdit {
fn drop(&mut self) {
wipe(&mut self.text);
self.cancel_composition();
}
}
/// Overwrites every byte `s` holds, its spare capacity too, with zeros the compiler can't leave
/// out (volatile writes and a fence, as `zeroize`), then empties it. Eight bytes a write, not
/// one: a 1.7 MB draft's copy goes in a tenth of a millisecond, where a byte at a time was most
/// of one on every frame a long draft's field was built.
#[allow(unsafe_code)]
pub(crate) fn wipe(s: &mut String) {
// SAFETY: only zeros are written, inside the allocation (`capacity` bytes from its start),
// each at an address aligned for what's written there; the length is reset to 0 after.
unsafe {
let v = s.as_mut_vec();
let (p, cap) = (v.as_mut_ptr(), v.capacity());
let head = p.align_offset(8).min(cap);
let mut i = 0;
while i < head { std::ptr::write_volatile(p.add(i), 0u8); i += 1; }
while i + 8 <= cap { std::ptr::write_volatile(p.add(i).cast::<u64>(), 0); i += 8; }
while i < cap { std::ptr::write_volatile(p.add(i), 0u8); i += 1; }
v.set_len(0);
}
std::sync::atomic::compiler_fence(std::sync::atomic::Ordering::SeqCst);
}
/// Document text kept aside (an undo step's, a snapshot's): wiped when it goes, as the field's
/// own text is.
#[doc(hidden)]
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Wiped(pub String);
impl std::ops::Deref for Wiped {
type Target = String;
fn deref(&self) -> &String {
&self.0
}
}
impl std::ops::DerefMut for Wiped {
fn deref_mut(&mut self) -> &mut String {
&mut self.0
}
}
impl Drop for Wiped {
fn drop(&mut self) {
wipe(&mut self.0);
}
}
/// What an edit asks of the host.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct EditOutcome {
pub submit: bool,
pub copy: Option<String>,
pub blur: bool,
}
impl TextEdit {
pub fn new(text: impl Into<String>) -> TextEdit {
let text = text.into();
let n = text.len();
let line_count = 1 + count_newlines(text.as_bytes());
TextEdit {
text,
anchor: n,
focus: n,
composition: ime::Composition::Idle,
focused: false,
marks: Vec::new(),
blocks: vec![Block::Paragraph; line_count],
soft_breaks: Vec::new(),
typing: Typing::Inherited,
history: Arc::default(),
group: Group::Closed,
secure: false,
revealed: false,
line_mode: LineMode::Default,
rich: false,
allowed_marks: None,
allowed_blocks: None,
edited_tag: EditedTag::default(),
column: Column::Free,
affinity: parley::Affinity::Downstream,
dir: FieldDir::Natural,
}
}
/// Construct a [`TextEdit`] from plain text, inline [`MarkRange`]s, and per-line [`Block`]s.
/// Caret starts at the end of `text`. Ranges are clamped to char boundaries and canonicalized,
/// and `blocks` is padded or truncated to match the number of `\n`-separated lines in `text`.
pub fn from_parts(text: impl Into<String>, marks: Vec<MarkRange>, blocks: Vec<Block>) -> TextEdit {
let mut edit = Self::new(text).rich();
edit.marks = marks;
edit.blocks = blocks;
edit.clamp_list_levels();
edit.sync_invariants();
edit
}
fn clamp_list_levels(&mut self) {
for b in &mut self.blocks {
*b = b.with_level(b.list_level().unwrap_or(0));
}
}
/// Rich editing: `⌘B` / `⌘I` / `⌘U` toggle marks, `Shift+Return` inserts a soft break and
/// [`paste_html`](Self::paste_html) keeps formatting. Off by default, so a plain field leaves
/// those keys to the app and pastes plain text. [`from_html`](Self::from_html) and
/// [`from_parts`](Self::from_parts) turn it on. The mark and block methods work either way.
pub fn rich(mut self) -> Self {
self.rich = true;
self
}
pub fn is_rich(&self) -> bool {
self.rich
}
/// Keep only these kinds of inline mark, for a field whose storage can't hold the rest (an
/// app that saves Markdown has no underline). A disallowed mark's shortcut (`⌘U`) goes on
/// to the app's key handlers, `toggle_mark` and `set_mark` ignore it, and paste drops it.
/// Kinds match by [`Mark::same_kind`], so any [`Mark::Link`] allows links. The field never
/// holds a disallowed mark: marks it already has, or that `set_marks` adds, are dropped.
/// Every kind is allowed by default, and [`Mark::Pill`] always is: pills are the app's own
/// tokens, not formatting.
///
/// ```ignore
/// TextEdit::new("").rich().allow_marks([Mark::Bold, Mark::Italic, Mark::Strike, Mark::Code, Mark::Link(String::new())])
/// ```
pub fn allow_marks(mut self, marks: impl IntoIterator<Item = Mark>) -> Self {
let pill = 1 << Mark::Pill(String::new()).kind_order();
self.allowed_marks = Some(marks.into_iter().fold(pill, |bits, m| bits | 1 << m.kind_order()));
self.sync_invariants();
self
}
/// Keep only these kinds of paragraph block, as [`allow_marks`](Self::allow_marks) does for
/// marks: `toggle_block` and `set_block` ignore the rest and pasted ones become paragraphs.
/// [`Block::Paragraph`] is always allowed, and list levels don't matter (`Block::Bullet(0)`
/// allows every bullet).
pub fn allow_blocks(mut self, blocks: impl IntoIterator<Item = Block>) -> Self {
self.allowed_blocks = Some(blocks.into_iter().fold(Block::Paragraph.kind_bit(), |bits, b| bits | b.kind_bit()));
self.sync_invariants();
self
}
/// Whether this field keeps marks of `mark`'s kind (see [`allow_marks`](Self::allow_marks)),
/// to hide a formatting bar's button for one it doesn't (`Mark::Link(String::new())` checks
/// links).
pub fn allows_mark(&self, mark: &Mark) -> bool {
self.allowed_marks.is_none_or(|bits| bits & 1 << mark.kind_order() != 0)
}
/// Whether this field keeps blocks of `block`'s kind (see [`allow_blocks`](Self::allow_blocks)).
pub fn allows_block(&self, block: Block) -> bool {
self.allowed_blocks.is_none_or(|bits| bits & block.kind_bit() != 0)
}
/// The mark a rich field's `⌘B`, `⌘I` or `⌘U` toggles, if this field takes that chord.
#[doc(hidden)]
pub fn format_chord(&self, ev: &KeyEvent) -> Option<Mark> {
let c = ev.edit_command()?;
if ev.mods.shift || !self.rich || self.secure {
return None;
}
let mark = match c {
'b' => Mark::Bold,
'i' => Mark::Italic,
'u' => Mark::Underline,
_ => return None,
};
self.allows_mark(&mark).then_some(mark)
}
/// `frag` without the marks and blocks this field doesn't allow.
fn keep_allowed(&self, mut frag: TextEdit) -> TextEdit {
frag.allowed_marks = self.allowed_marks;
frag.allowed_blocks = self.allowed_blocks;
frag.sync_invariants();
frag
}
/// No marks, pending style or non-paragraph blocks: draws exactly as plain text.
#[doc(hidden)]
pub fn is_plain(&self) -> bool {
self.marks.is_empty() && self.typing == Typing::Inherited && self.blocks.iter().all(|&b| b == Block::Paragraph)
}
/// Parse an HTML fragment (`<b>`, `<strong>`, `<i>`, `<em>`, `<u>`, `<s>`, `<del>`, `<strike>`,
/// `<a href>`, `<code>`, `<pre>`, `<ul>`, `<ol>`, `<li>`, `<blockquote>`, `<p>`, `<div>`, `<br>`,
/// and inline `style` for `font-weight`, `font-style`, `text-decoration`) into a [`TextEdit`].
/// Unknown tags keep their text and strip the wrapper; `<script>` and `<style>` are dropped.
pub fn from_html(html_str: &str) -> TextEdit {
html::parse_html(html_str).rich()
}
/// Serialize the entire document's text, inline marks, and paragraph blocks to safe HTML.
pub fn to_html(&self) -> String {
let e = self.synced();
html::serialize_html(&e, 0..e.text.len())
}
/// `self` with marks, blocks and caret fitted to `text`, which an app may have assigned
/// directly.
fn synced(&self) -> TextEdit {
let mut e = self.clone();
e.sync_invariants();
e
}
/// Serialize the current selection (`self.range()`) to HTML, or `""` when the selection is empty.
pub fn selected_html(&self) -> String {
let (a, b) = self.range();
if a == b || self.secure {
return String::new();
}
html::serialize_html(&self.synced(), a..b)
}
/// Inline [`MarkRange`]s on `self.text`, sorted by start byte.
pub fn marks(&self) -> &[MarkRange] {
&self.marks
}
/// Paragraph [`Block`] attributes, one per `\n`-delimited line of `self.text`.
pub fn blocks(&self) -> &[Block] {
if self.blocks.is_empty() {
&[Block::Paragraph]
} else {
&self.blocks
}
}
/// Replace the inline [`MarkRange`]s on `self.text` and canonicalize them.
pub fn set_marks(&mut self, marks: Vec<MarkRange>) {
self.marks = marks;
self.sync_invariants();
}
/// Replace the per-line [`Block`] list on `self.text`.
pub fn set_blocks(&mut self, blocks: Vec<Block>) {
self.blocks = blocks;
self.clamp_list_levels();
self.sync_invariants();
}
/// Line indices (`> 0`) created by `Shift+Return` (`<br>`) rather than a hard paragraph break.
pub fn soft_breaks(&self) -> &[u32] {
&self.soft_breaks
}
/// `self` with soft breaks before lines `lines` (indices into `\n`-delimited lines, as
/// [`soft_breaks`](Self::soft_breaks) returns them): each of those lines continues the
/// paragraph, list item or quote above it, as `Shift+Return` makes, so a draft rebuilt with
/// [`from_parts`](Self::from_parts) keeps them. Line 0 and lines past the end are dropped.
///
/// ```ignore
/// // "one" then "two" on a new line of the same bullet.
/// TextEdit::from_parts("one\ntwo", vec![], vec![Block::Bullet(0); 2]).with_soft_breaks(vec![1])
/// ```
pub fn with_soft_breaks(mut self, lines: Vec<u32>) -> Self {
self.set_soft_breaks(lines);
self
}
/// Replace the soft breaks (see [`with_soft_breaks`](Self::with_soft_breaks)). Like
/// `set_marks` and `set_blocks`, this isn't an undo step.
pub fn set_soft_breaks(&mut self, lines: Vec<u32>) {
self.soft_breaks = lines;
self.sync_invariants();
}
/// Iterate the `\n`-delimited paragraphs of `self.text` with their byte range and [`Block`].
pub fn paragraphs(&self) -> Vec<ParagraphInfo> {
let mut out = Vec::new();
let mut line_start = 0;
let mut idx = 0;
for (i, b) in self.text.bytes().enumerate() {
if b == b'\n' {
let block = self.blocks.get(idx).copied().unwrap_or(Block::Paragraph);
let soft_break = self.soft_breaks.binary_search(&(idx as u32)).is_ok();
out.push(ParagraphInfo { index: idx, range: line_start..i, block, soft_break });
line_start = i + 1;
idx += 1;
}
}
let block = self.blocks.get(idx).copied().unwrap_or(Block::Paragraph);
let soft_break = self.soft_breaks.binary_search(&(idx as u32)).is_ok();
out.push(ParagraphInfo { index: idx, range: line_start..self.text.len(), block, soft_break });
out
}
/// The input method's composition, drawn at the caret and not yet part of `text`, with the
/// byte range of its cursor or selection in it.
pub fn preedit(&self) -> Option<(&str, Option<(usize, usize)>)> {
self.composition.preedit()
}
/// An input method is composing in this field.
pub fn is_composing(&self) -> bool {
self.composition != ime::Composition::Idle
}
/// The clause the input method is converting, a byte range of the preedit, when it marks
/// one.
pub fn preedit_target(&self) -> Option<(usize, usize)> {
self.composition.target()
}
/// The composition's clauses, each a byte range of the preedit, the one being converted
/// marked (one clause over the whole preedit when the input method gives none). Empty when
/// not composing.
pub fn preedit_clauses(&self) -> Vec<Clause> {
self.composition.clauses()
}
/// The text around the selection for the platform's input method to read (reconversion,
/// document feed); none for a secret or mid-composition.
#[doc(hidden)]
pub fn ime_text(&self) -> Option<ImeText> {
if self.secure || self.is_composing() { return None; }
let (a, b) = self.range();
let t = &self.text;
let mut start = t[..a].rfind('\n').map_or(0, |i| i + 1).max(a.saturating_sub(1024));
while !t.is_char_boundary(start) { start += 1; }
let mut end = t[b..].find('\n').map_or(t.len(), |i| b + i).min(b + 1024);
while !t.is_char_boundary(end) { end -= 1; }
Some(ImeText { text: t[start..end].to_owned(), start, selection: a - start..b - start })
}
/// Ends the input method's composition without writing it, as an edit replacing the text
/// under it does.
pub fn cancel_composition(&mut self) {
let _ = ime::step(&mut self.composition, ime::Event::Cancel);
}
/// Writes what the composition shows into the text and ends it, as a field that loses
/// focus or the window mid-composition keeps it (a browser's field and an `NSTextView`
/// do). True when there was one. The runtime tells the platform's input method to drop its
/// own copy.
pub fn finish_composition(&mut self) -> bool {
if self.secure { self.cancel_composition(); return false; }
let mut finished = false;
for effect in ime::step(&mut self.composition, ime::Event::Finish) {
if let ime::Effect::Commit(mut s) = effect {
self.commit_composed(&s);
s.zeroize();
finished = true;
}
}
finished
}
#[doc(hidden)]
pub fn clear_typing_style(&mut self) {
self.typing = Typing::Inherited;
}
/// Replace the whole draft and discard its history, preserving focus and password mode.
pub fn replace_text(&mut self, text: impl Into<String>) {
let text = text.into();
wipe(&mut self.text);
let line_count = if self.secure { 0 } else { 1 + count_newlines(text.as_bytes()) };
self.text = text;
self.anchor = self.text.len();
self.focus = self.anchor;
self.marks.clear();
self.blocks = vec![Block::Paragraph; line_count];
self.soft_breaks.clear();
self.typing = Typing::Inherited;
self.cancel_composition();
self.edited_tag = EditedTag(false);
self.history = Arc::default();
if self.group.is_open() {
self.group = self.group_from_here();
}
}
/// Whether `self.text` is non-empty and still holds the value the app last set, with no user
/// edit since [`TextEdit::new`] or [`Self::replace_text`]. An empty field is never pristine.
/// Use `replace_text` for app replacements, even with the same value. Direct mutation of
/// the public `text` string cannot reset this state and does not zeroize its old allocation.
///
/// While a hidden multi-line [`secure`](Self::secure) field is pristine, the first insertion
/// replaces the entire value with the new text and the first deletion empties it, regardless
/// of caret or selection.
pub fn is_pristine(&self) -> bool {
!self.text.is_empty() && !self.edited_tag.0
}
/// Mark the current `self.text` as user-edited (`!self.is_pristine()`).
pub fn mark_edited(&mut self) {
self.edited_tag.0 = true;
}
#[doc(hidden)]
pub fn has_history(&self) -> bool { !self.history.undo.is_empty() || !self.history.redo.is_empty() }
#[doc(hidden)]
pub fn same_model(&self, other: &TextEdit) -> bool {
Arc::ptr_eq(&self.history, &other.history)
}
#[doc(hidden)]
pub fn weak_history(&self) -> std::sync::Weak<History> {
Arc::downgrade(&self.history)
}
#[doc(hidden)]
pub fn matches_history(&self, weak: &std::sync::Weak<History>) -> bool {
weak.ptr_eq(&Arc::downgrade(&self.history))
}
/// Clears the draft and its history after submission, preserving keyboard focus.
pub fn clear(&mut self) {
self.replace_text("");
}
/// The selection as ordered byte offsets, clamped to character boundaries of `text` (an app
/// may have replaced `text` without moving the caret).
pub fn range(&self) -> (usize, usize) {
let t = &self.text;
(Self::clamp_char_boundary(t, self.anchor.min(self.focus)), Self::clamp_char_boundary(t, self.anchor.max(self.focus)))
}
/// Move the caret to `byte` (clamped to a character boundary of `self.text`) and collapse the
/// selection, clearing any pending typing style.
pub fn set_caret(&mut self, byte: usize) {
let b = Self::clamp_char_boundary(&self.text, byte);
self.anchor = b;
self.focus = b;
self.snap_to_pills();
self.typing = Typing::Inherited;
self.column = Column::Free;
self.affinity = parley::Affinity::Downstream;
}
/// Set the selection `anchor` and `focus` byte indices (clamped to character boundaries of
/// `self.text`), clearing any pending typing style. A selection that ends inside a
/// [`Mark::Pill`] grows to cover it.
pub fn set_selection(&mut self, anchor: usize, focus: usize) {
self.anchor = Self::clamp_char_boundary(&self.text, anchor);
self.focus = Self::clamp_char_boundary(&self.text, focus);
self.snap_to_pills();
self.typing = Typing::Inherited;
self.column = Column::Free;
self.affinity = parley::Affinity::Downstream;
}
/// The [`Mark::Pill`]s in `self.text`, in order, with their byte ranges and ids.
pub fn pills(&self) -> impl Iterator<Item = (Range<usize>, &str)> + '_ {
let t = &self.text;
self.marks.iter().filter_map(move |m| {
let id = m.mark.pill_id()?;
(m.start < m.end && m.end <= t.len() && t.is_char_boundary(m.start) && t.is_char_boundary(m.end) && !t.as_bytes()[m.start..m.end].contains(&b'\n'))
.then(|| (m.range(), id))
})
}
/// The start of the pill that ends at or contains `j`, when `j` is past its start.
fn pill_before(&self, j: usize) -> Option<usize> {
self.marks.iter().find(|m| m.mark.is_pill() && m.start < j && j <= m.end).map(|m| m.start)
}
/// The end of the pill that starts at or contains `j`, when `j` is before its end.
fn pill_after(&self, j: usize) -> Option<usize> {
self.marks.iter().find(|m| m.mark.is_pill() && m.start <= j && j < m.end).map(|m| m.end)
}
/// Replace the selection with `label` as one [`Mark::Pill`] carrying `id`, and put the
/// caret after it: one undo step. Line breaks in `label` become spaces.
pub fn insert_pill(&mut self, id: impl Into<String>, label: &str) {
let (a, b) = self.range();
self.replace_with_pill(a..b, id, label);
}
/// Replace byte range `range` with `label` as one [`Mark::Pill`] carrying `id` (an `@query`
/// the user typed, say), and put the caret after it: one undo step. The range grows to
/// cover any pill it cuts into. Line breaks in `label` become spaces; an empty label or a
/// secure field inserts nothing.
pub fn replace_with_pill(&mut self, range: Range<usize>, id: impl Into<String>, label: &str) {
let label: String = label.chars().map(|c| if c.is_control() || matches!(c, '\u{2028}' | '\u{2029}') { ' ' } else { c }).collect();
if self.secure || label.is_empty() {
return;
}
self.sync_invariants();
self.break_history_group();
let before = self.snapshot();
let a = Self::clamp_char_boundary(&self.text, range.start.min(range.end));
let b = Self::clamp_char_boundary(&self.text, range.end.max(range.start));
let (a, b) = self.cover_pills(a, b);
self.typing = Typing::Inherited;
self.apply_text_and_attr_replace((a, b), &label, &[], None, false);
// Code blocks keep no inline marks: there the label stays plain text.
self.marks.push(MarkRange { start: a, end: a + label.len(), mark: Mark::Pill(id.into()) });
self.normalize_marks();
self.record_change(before, EditKind::Other);
}
/// The pill strictly containing byte `i` (`start < i < end`).
fn pill_around(&self, i: usize) -> Option<(usize, usize)> {
self.marks.iter().find(|m| m.mark.is_pill() && m.start < i && i < m.end).map(|m| (m.start, m.end))
}
/// `i` moved out of any pill it lands inside, to its end when `forward`, else its start.
fn out_of_pill(&self, i: usize, forward: bool) -> usize {
self.pill_around(i).map_or(i, |(s, e)| if forward { e } else { s })
}
/// `a..b` grown to cover any pill either end cuts into; an empty range inside one moves
/// to its end.
fn cover_pills(&self, a: usize, b: usize) -> (usize, usize) {
if a == b {
let i = self.out_of_pill(a, true);
return (i, i);
}
(self.out_of_pill(a, false), self.out_of_pill(b, true))
}
/// Keeps the caret off a pill's inside: a caret goes to the nearer edge, a selection grows
/// to cover the pill.
#[doc(hidden)]
pub fn snap_to_pills(&mut self) {
if !self.marks.iter().any(|m| m.mark.is_pill()) {
return;
}
if self.anchor == self.focus {
if let Some((s, e)) = self.pill_around(self.focus) {
let to = if self.focus - s < e - self.focus { s } else { e };
(self.anchor, self.focus) = (to, to);
}
} else {
let forward = self.focus > self.anchor;
self.anchor = self.out_of_pill(self.anchor, !forward);
self.focus = self.out_of_pill(self.focus, forward);
}
}
pub fn selected(&self) -> &str {
let (a, b) = self.range();
&self.text[a..b]
}
pub fn insert(&mut self, s: &str) {
self.replace(self.range(), s, EditKind::Other);
}
/// Line index (`0..line_count`) containing `byte`.
pub fn line_of_byte(&self, byte: usize) -> usize {
let clamped = byte.min(self.text.len());
count_newlines(&self.text.as_bytes()[..clamped])
}
/// Byte range (`start..end`, excluding `\n`) of 0-based `line_idx`.
pub fn line_range(&self, line_idx: usize) -> Range<usize> {
let mut cur = 0;
let mut start = 0;
for (i, b) in self.text.bytes().enumerate() {
if b == b'\n' {
if cur == line_idx {
return start..i;
}
start = i + 1;
cur += 1;
}
}
if cur == line_idx {
start..self.text.len()
} else {
self.text.len()..self.text.len()
}
}
fn clamp_char_boundary(s: &str, idx: usize) -> usize {
s.floor_char_boundary(idx)
}
}
#[cfg(test)]
mod tests;
+540
View File
@@ -0,0 +1,540 @@
//! Inline marks and paragraph blocks on a [`TextEdit`]: keeping them in step with the text,
//! toggling them, and list indentation.
use super::*;
impl TextEdit {
/// Synchronize `blocks`, `soft_breaks`, and `marks` with `self.text`.
#[doc(hidden)]
pub fn sync_invariants(&mut self) {
self.anchor = Self::clamp_char_boundary(&self.text, self.anchor);
self.focus = Self::clamp_char_boundary(&self.text, self.focus);
if self.secure {
self.marks.clear();
self.blocks.clear();
self.soft_breaks.clear();
self.typing = Typing::Inherited;
return;
}
let line_count = 1 + count_newlines(self.text.as_bytes());
if self.blocks.len() < line_count {
self.blocks.resize(line_count, Block::Paragraph);
} else if self.blocks.len() > line_count {
self.blocks.truncate(line_count);
}
if let Some(bits) = self.allowed_blocks {
for b in &mut self.blocks {
if bits & b.kind_bit() == 0 {
*b = Block::Paragraph;
}
}
}
self.soft_breaks.sort_unstable();
self.soft_breaks.dedup();
self.soft_breaks.retain(|&idx| idx > 0 && (idx as usize) < line_count);
self.normalize_marks();
self.snap_to_pills();
let anchor_line = self.line_of_byte(self.anchor);
if self.typing.at((self.anchor, self.focus)).is_none() || self.blocks.get(anchor_line) == Some(&Block::Code) {
self.typing = Typing::Inherited;
} else if let (Some(bits), Typing::Armed { marks, .. }) = (self.allowed_marks, &mut self.typing) {
marks.retain(|m| bits & 1 << m.kind_order() != 0);
}
}
pub(super) fn normalize_marks(&mut self) {
if let Some(bits) = self.allowed_marks {
self.marks.retain(|m| bits & 1 << m.mark.kind_order() != 0);
}
if self.marks.is_empty() {
return;
}
let len = self.text.len();
for m in &mut self.marks {
m.start = Self::clamp_char_boundary(&self.text, m.start);
m.end = Self::clamp_char_boundary(&self.text, m.end);
}
self.marks.retain(|m| m.start < m.end && m.end <= len);
// Strip inline marks from any `Block::Code` paragraph.
if self.blocks.contains(&Block::Code) {
let mut line_start = 0;
let mut idx = 0;
let mut code_ranges: Vec<Range<usize>> = Vec::new();
for (i, b) in self.text.bytes().enumerate() {
if b == b'\n' {
if self.blocks.get(idx) == Some(&Block::Code) {
code_ranges.push(line_start..i + 1);
}
line_start = i + 1;
idx += 1;
}
}
if self.blocks.get(idx) == Some(&Block::Code) {
code_ranges.push(line_start..len);
}
// One pass: cut each mark around the (sorted, disjoint) code ranges it overlaps.
let mut out = Vec::with_capacity(self.marks.len());
for m in self.marks.drain(..) {
let mut start = m.start;
let first = code_ranges.partition_point(|cr| cr.end <= start);
for cr in &code_ranges[first..] {
if cr.start >= m.end {
break;
}
if start < cr.start {
out.push(MarkRange { start, end: cr.start, mark: m.mark.clone() });
}
start = start.max(cr.end);
}
if start < m.end {
out.push(MarkRange { start, end: m.end, mark: m.mark });
}
}
self.marks = out;
}
// Merge overlapping or adjacent ranges of the same mark kind.
// For `Mark::Link`, later entries win over earlier overlapping links.
let mut by_kind: [Vec<MarkRange>; 7] = Default::default();
for m in self.marks.drain(..) {
if m.start < m.end {
by_kind[m.mark.kind_order() as usize].push(m);
}
}
let mut merged = Vec::new();
for (kind_idx, mut list) in by_kind.into_iter().enumerate() {
if list.is_empty() {
continue;
}
if kind_idx == 6 {
// `Mark::Pill`: whole objects on one line that never merge; the first of two
// overlapping pills wins.
list.sort_by_key(|m| (m.start, m.end));
let mut end = 0;
for m in list {
if m.start >= end && !self.text.as_bytes()[m.start..m.end].contains(&b'\n') {
end = m.end;
merged.push(m);
}
}
} else if kind_idx == 5 {
// `Mark::Link`: resolve overlaps so later links overwrite earlier ones, then merge adjacent equal URLs.
let mut bounds: Vec<(usize, usize)> = list.iter().map(|m| (m.start, m.end)).collect();
bounds.sort_unstable();
let overlapping = bounds.windows(2).any(|w| w[1].0 < w[0].1);
let mut resolved: Vec<MarkRange> = Vec::new();
if !overlapping {
resolved = std::mem::take(&mut list);
}
for link in list {
let mut next_resolved = Vec::with_capacity(resolved.len() + 1);
for old in resolved {
if old.end <= link.start || old.start >= link.end {
next_resolved.push(old);
} else {
if old.start < link.start {
next_resolved.push(MarkRange {
start: old.start,
end: link.start,
mark: old.mark.clone(),
});
}
if old.end > link.end {
next_resolved.push(MarkRange {
start: link.end,
end: old.end,
mark: old.mark,
});
}
}
}
next_resolved.push(link);
resolved = next_resolved;
}
resolved.sort_by_key(|m| (m.start, m.end));
let mut iter = resolved.into_iter();
if let Some(mut cur) = iter.next() {
for m in iter {
if m.mark == cur.mark && m.start <= cur.end {
cur.end = cur.end.max(m.end);
} else {
merged.push(cur);
cur = m;
}
}
merged.push(cur);
}
} else {
list.sort_by_key(|m| (m.start, m.end));
let mut iter = list.into_iter();
if let Some(mut cur) = iter.next() {
for m in iter {
if m.start <= cur.end {
cur.end = cur.end.max(m.end);
} else {
merged.push(cur);
cur = m;
}
}
merged.push(cur);
}
}
}
merged.sort_by_key(|m| (m.start, m.end, m.mark.kind_order()));
self.marks = merged;
}
/// Marks inherited from the character before `pos` according to AppKit rules:
/// typing inside (`m.start < pos < m.end`) or at the trailing edge (`m.start < pos == m.end`)
/// of a mark inherits it; typing at the start of a mark (`pos == m.start`) does not extend it.
pub(super) fn inherited_marks_at(&self, pos: usize) -> Vec<Mark> {
if self.marks.is_empty() {
return Vec::new();
}
let line_idx = self.line_of_byte(pos);
if self.blocks.get(line_idx) == Some(&Block::Code) {
return Vec::new();
}
let line_start = self.line_range(line_idx).start;
if pos <= line_start {
return Vec::new();
}
let mut out = Vec::new();
for m in &self.marks {
if m.start < pos && pos <= m.end && !m.mark.is_pill() && !out.iter().any(|existing: &Mark| existing.same_kind(&m.mark)) {
out.push(m.mark.clone());
}
}
out
}
/// Whether `mark` covers the entire byte range `start..end` (`start < end`).
fn range_has_mark(&self, start: usize, end: usize, mark: &Mark) -> bool {
if start >= end {
return false;
}
// Because `normalize_marks` merges contiguous ranges of the same mark, a mark covers
// the entire `start..end` iff a single `MarkRange` with `m.start <= start && end <= m.end` exists
// (for `Link("")`, any link covering each subrange, or a single link covering `start..end`).
let match_any_link = matches!(mark, Mark::Link(u) if u.is_empty());
self.marks.iter().any(|m| {
let kind_matches = if match_any_link {
matches!(m.mark, Mark::Link(_))
} else {
&m.mark == mark
};
kind_matches && m.start <= start && end <= m.end
})
}
/// Active inline marks at the caret (including pending typing style) or covering the whole
/// selection, for driving a formatting bar's pressed state.
pub fn active_marks(&self) -> Vec<Mark> {
let (a, b) = self.range();
if a == b {
let line_idx = self.line_of_byte(a);
if self.blocks.get(line_idx) == Some(&Block::Code) {
return Vec::new();
}
if let Some(p) = self.typing.at((self.anchor, self.focus)) {
return p.to_vec();
}
return self.inherited_marks_at(a);
}
let mut out = Vec::new();
for m in &self.marks {
if m.start <= a && b <= m.end && !out.iter().any(|existing: &Mark| existing == &m.mark) {
out.push(m.mark.clone());
}
}
out
}
/// Whether `mark` is active at the caret or covers the whole selection.
/// Passing `Mark::Link(String::new())` checks whether *any* link is active.
pub fn has_mark(&self, mark: &Mark) -> bool {
let match_any_link = matches!(mark, Mark::Link(u) if u.is_empty());
self.active_marks().iter().any(|m| {
if match_any_link {
matches!(m, Mark::Link(_))
} else {
m == mark
}
})
}
/// The URL of the active [`Mark::Link`] at the caret or covering the selection, if any.
pub fn active_link(&self) -> Option<&str> {
let (a, b) = self.range();
if a == b {
if let Some(p) = self.typing.at((self.anchor, self.focus)) {
return p.iter().find_map(Mark::link_url);
}
let line_idx = self.line_of_byte(a);
if self.blocks.get(line_idx) == Some(&Block::Code) || a <= self.line_range(line_idx).start {
return None;
}
return self
.marks
.iter()
.find_map(|m| (m.start < a && a <= m.end).then(|| m.mark.link_url()).flatten());
}
self.marks
.iter()
.find_map(|m| (m.start <= a && b <= m.end).then(|| m.mark.link_url()).flatten())
}
fn edit_typing_style(&mut self, pos: usize, f: impl FnOnce(&mut Vec<Mark>)) {
if self.blocks.get(self.line_of_byte(pos)) == Some(&Block::Code) {
return;
}
let mut active = self.active_marks();
f(&mut active);
self.typing = Typing::Armed { at: (self.anchor, self.focus), marks: active };
}
/// Toggle `mark` on the selection, or in the pending typing style when the selection is empty.
/// Inside a [`Block::Code`] paragraph, inline marks do not apply, nor does a mark the field
/// doesn't [allow](Self::allow_marks).
pub fn toggle_mark(&mut self, mark: Mark) {
if self.secure || !self.allows_mark(&mark) {
return;
}
self.sync_invariants();
let (a, b) = self.range();
if a == b {
if !mark.is_pill() {
self.edit_typing_style(a, |active| {
if let Some(pos) = active.iter().position(|m| m.same_kind(&mark)) {
if active[pos] == mark || matches!(mark, Mark::Link(ref u) if u.is_empty()) {
active.remove(pos);
} else {
active[pos] = mark;
}
} else {
active.push(mark);
}
});
}
return;
}
if self.range_has_mark(a, b, &mark) {
self.remove_mark(&mark);
} else {
self.set_mark(mark);
}
}
/// Apply `mark` to the current selection (or add it to pending typing style when empty).
pub fn set_mark(&mut self, mark: Mark) {
if self.secure || !self.allows_mark(&mark) {
return;
}
self.sync_invariants();
let (a, b) = self.range();
if a == b {
if !mark.is_pill() {
self.edit_typing_style(a, |active| {
if let Some(pos) = active.iter().position(|m| m.same_kind(&mark)) {
active[pos] = mark;
} else {
active.push(mark);
}
});
}
return;
}
self.break_history_group();
let before = self.snapshot();
if mark.is_pill() {
self.marks.retain(|m| !m.mark.is_pill() || m.end <= a || m.start >= b);
}
self.marks.push(MarkRange { start: a, end: b, mark });
self.typing = Typing::Inherited;
self.normalize_marks();
self.record_change(before, EditKind::Other);
}
/// Remove `mark` (matching by [`Mark::same_kind`]) from the current selection, or from pending
/// typing style when the selection is empty.
pub fn remove_mark(&mut self, mark: &Mark) {
if self.secure {
return;
}
self.sync_invariants();
let (a, b) = self.range();
if a == b {
let mut active = self.active_marks();
active.retain(|m| !m.same_kind(mark));
self.typing = Typing::Armed { at: (self.anchor, self.focus), marks: active };
return;
}
self.break_history_group();
let before = self.snapshot();
let mut out = Vec::with_capacity(self.marks.len());
for m in self.marks.drain(..) {
if !m.mark.same_kind(mark) || m.end <= a || m.start >= b {
out.push(m);
} else if m.mark.is_pill() {
// A pill goes whole: its label stays as plain text.
} else {
if m.start < a {
out.push(MarkRange { start: m.start, end: a, mark: m.mark.clone() });
}
if m.end > b {
out.push(MarkRange { start: b, end: m.end, mark: m.mark });
}
}
}
self.marks = out;
self.typing = Typing::Inherited;
self.normalize_marks();
self.record_change(before, EditKind::Other);
}
/// Apply or remove a [`Mark::Link`] on the selection (or pending style when empty).
/// Passing `None` or `Some("")` removes any link on the selection.
pub fn set_link(&mut self, url: Option<&str>) {
match url.map(str::trim).filter(|u| !u.is_empty()) {
Some(u) => self.set_mark(Mark::Link(u.to_owned())),
None => self.remove_mark(&Mark::Link(String::new())),
}
}
/// Line index range `first_line..=last_line` covered by the current selection.
fn selected_line_range(&self) -> (usize, usize) {
let (a, b) = self.range();
let first = self.line_of_byte(a);
let last = if b > a && self.text.as_bytes().get(b - 1) == Some(&b'\n') {
self.line_of_byte(b - 1)
} else {
self.line_of_byte(b)
};
(first, last.max(first))
}
/// The [`Block`] attribute of the paragraph at the caret or selection.
pub fn active_block(&self) -> Block {
let (first, _) = self.selected_line_range();
self.blocks.get(first).copied().unwrap_or(Block::Paragraph)
}
/// Alias for [`TextEdit::active_block`]: the [`Block`] attribute of the paragraph at the caret.
pub fn current_block(&self) -> Block {
self.active_block()
}
/// Whether any paragraph in the current selection is a bullet or numbered list item.
pub fn selection_in_list(&self) -> bool {
let (first, last) = self.selected_line_range();
(first..=last).any(|i| self.blocks.get(i).copied().unwrap_or(Block::Paragraph).is_list())
}
/// Set the [`Block`] attribute for all paragraphs in the current selection, unless the field
/// doesn't [allow](Self::allow_blocks) it.
pub fn set_block(&mut self, block: Block) {
if self.secure || self.is_single_line() || !self.allows_block(block) {
return;
}
let block = block.with_level(block.list_level().unwrap_or(0));
self.sync_invariants();
self.break_history_group();
let before = self.snapshot();
let (first, last) = self.selected_line_range();
for i in first..=last {
if let Some(slot) = self.blocks.get_mut(i) {
*slot = block;
}
}
if block == Block::Code {
self.typing = Typing::Inherited;
}
self.normalize_marks();
self.record_change(before, EditKind::Other);
}
/// Toggle `block` on all paragraphs in the selection: if every selected paragraph already has
/// the same block kind as `block`, resets them to [`Block::Paragraph`]; otherwise sets `block`
/// (preserving list nesting level when switching between bullet and numbered lists).
pub fn toggle_block(&mut self, block: Block) {
if self.secure || self.is_single_line() || !self.allows_block(block) {
return;
}
self.sync_invariants();
let (first, last) = self.selected_line_range();
let all_match = (first..=last).all(|i| {
self.blocks.get(i).copied().unwrap_or(Block::Paragraph).same_kind(block)
});
if all_match {
self.set_block(Block::Paragraph);
} else {
self.break_history_group();
let before = self.snapshot();
for i in first..=last {
if let Some(slot) = self.blocks.get_mut(i) {
*slot = match (slot.list_level(), block) {
(Some(lvl), Block::Bullet(0)) => Block::Bullet(lvl),
(Some(lvl), Block::Numbered(0)) => Block::Numbered(lvl),
_ => block,
};
}
}
if block == Block::Code {
self.typing = Typing::Inherited;
}
self.normalize_marks();
self.record_change(before, EditKind::Other);
}
}
/// Increase list nesting level (`Tab`) for list items in the selection, up to [`MAX_LIST_LEVEL`].
/// Returns `true` if the selection was inside a list item.
pub fn indent_list(&mut self) -> bool {
if self.secure || self.is_single_line() {
return false;
}
self.sync_invariants();
if !self.selection_in_list() {
return false;
}
self.break_history_group();
let before = self.snapshot();
let (first, last) = self.selected_line_range();
for i in first..=last {
if let Some(slot) = self.blocks.get_mut(i)
&& let Some(lvl) = slot.list_level()
{
*slot = slot.with_level((lvl + 1).min(MAX_LIST_LEVEL));
}
}
self.record_change(before, EditKind::Other);
true
}
/// Decrease list nesting level (`Shift+Tab`) for list items in the selection.
/// Returns `true` if the selection was inside a list item.
pub fn outdent_list(&mut self) -> bool {
if self.secure || self.is_single_line() {
return false;
}
self.sync_invariants();
if !self.selection_in_list() {
return false;
}
self.break_history_group();
let before = self.snapshot();
let (first, last) = self.selected_line_range();
for i in first..=last {
if let Some(slot) = self.blocks.get_mut(i)
&& let Some(lvl) = slot.list_level()
{
*slot = slot.with_level(lvl.saturating_sub(1));
}
}
self.record_change(before, EditKind::Other);
true
}
}
+129
View File
@@ -0,0 +1,129 @@
//! The rich-text model's value types: inline marks, paragraph blocks and their palette.
use std::ops::Range;
use rune_core::color::{Color, oklch, oklcha};
pub use rune_text::{Block, MAX_LIST_LEVEL};
/// An inline formatting mark stored alongside [`TextEdit::text`](super::TextEdit::text). More
/// marks may come, so a `match` needs a `_` arm.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum Mark {
Bold,
Italic,
Underline,
Strike,
Code,
Link(String),
/// An atomic inline object (an `@file` or `@agent` mention, an attachment) carrying the
/// app's id; its text is the label. The caret steps over it, deleting takes it whole, a
/// selection that touches it covers it, and typing never extends it. A field draws it as a
/// chip (`El::pill_style`, `El::pill_colors`, `El::pill_icon`). Insert one with
/// [`TextEdit::insert_pill`](super::TextEdit::insert_pill).
Pill(String),
}
impl Mark {
/// Whether `self` and `other` are the same kind of mark (`Link(_)` matches any `Link(_)`).
pub fn same_kind(&self, other: &Mark) -> bool {
match (self, other) {
(Mark::Bold, Mark::Bold)
| (Mark::Italic, Mark::Italic)
| (Mark::Underline, Mark::Underline)
| (Mark::Strike, Mark::Strike)
| (Mark::Code, Mark::Code)
| (Mark::Link(_), Mark::Link(_))
| (Mark::Pill(_), Mark::Pill(_)) => true,
_ => false,
}
}
/// The URL when `self` is [`Mark::Link`].
pub fn link_url(&self) -> Option<&str> {
match self {
Mark::Link(url) => Some(url),
_ => None,
}
}
/// The app's id when `self` is [`Mark::Pill`].
pub fn pill_id(&self) -> Option<&str> {
match self {
Mark::Pill(id) => Some(id),
_ => None,
}
}
pub(crate) fn is_pill(&self) -> bool {
matches!(self, Mark::Pill(_))
}
pub(crate) fn kind_order(&self) -> u8 {
match self {
Mark::Bold => 0,
Mark::Italic => 1,
Mark::Underline => 2,
Mark::Strike => 3,
Mark::Code => 4,
Mark::Link(_) => 5,
Mark::Pill(_) => 6,
}
}
}
/// A non-empty byte range `[start, end)` in [`TextEdit::text`](super::TextEdit::text) carrying an
/// inline [`Mark`].
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct MarkRange {
pub start: usize,
pub end: usize,
pub mark: Mark,
}
impl MarkRange {
pub fn new(range: Range<usize>, mark: Mark) -> Self {
Self { start: range.start, end: range.end, mark }
}
pub fn range(&self) -> Range<usize> {
self.start..self.end
}
}
/// A paragraph slice of [`TextEdit`](super::TextEdit), returned by
/// [`TextEdit::paragraphs`](super::TextEdit::paragraphs).
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct ParagraphInfo {
pub index: usize,
pub range: Range<usize>,
pub block: Block,
/// True when this line was split from the previous line by `Shift+Return` (`<br>`).
pub soft_break: bool,
}
/// Visual palette for rich marks and block attributes inside `text_input`.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RichStyle {
pub code_fg: Option<Color>,
pub code_bg: Color,
pub code_block_bg: Color,
pub link: Color,
pub quote_bar: Color,
pub marker: Option<Color>,
}
impl Default for RichStyle {
fn default() -> Self {
Self {
code_fg: None,
code_bg: oklcha(0.55, 0.02, 260.0, 0.16),
code_block_bg: oklcha(0.5, 0.02, 260.0, 0.12),
link: oklch(0.68, 0.16, 250.0),
quote_bar: oklcha(0.6, 0.04, 255.0, 0.45),
marker: None,
}
}
}
+286
View File
@@ -0,0 +1,286 @@
//! Core text and attribute replacement engine, grapheme stepping, and input sanitization.
use super::*;
/// The previous grapheme boundary, so a caret or backspace takes a ZWJ emoji, flag or skin
/// tone whole.
pub(crate) fn prev_char(s: &str, i: usize) -> usize {
use unicode_segmentation::UnicodeSegmentation;
s[..i].grapheme_indices(true).next_back().map_or(0, |(j, _)| j)
}
/// Where Backspace deletes back to from `i`, as Chromium's `BackspaceStateMachine` and native
/// fields do: one code point (a combining accent, a Thai or Indic vowel sign, the last jamo of
/// a decomposed syllable), so a typist fixes the last thing they typed without retyping the
/// cluster; but a CR LF and an emoji sequence (a variation selector, a skin tone, a keycap, a
/// flag's pair, a tag sequence, a ZWJ sequence of emoji) go whole.
pub(crate) fn prev_backspace(s: &str, i: usize) -> usize {
let start = prev_char(s, i);
let cluster = &s[start..i];
let emoji = cluster.chars().any(|c| matches!(c as u32, 0xFE0F | 0x20E3 | 0x1F3FB..=0x1F3FF | 0x1F1E6..=0x1F1FF | 0xE0020..=0xE007F))
|| (cluster.contains('\u{200D}') && cluster.chars().any(rune_text::is_pictographic));
if cluster == "\r\n" || emoji {
return start;
}
s[..i].char_indices().next_back().map_or(0, |(j, _)| j)
}
pub(crate) fn next_char(s: &str, i: usize) -> usize {
use unicode_segmentation::UnicodeSegmentation;
s[i..].graphemes(true).next().map_or(i, |g| i + g.len())
}
/// `\n` bytes in `s`. Counts into `u8` lanes so it vectorizes: `filter().count()` widens every
/// byte to `usize` and runs several times slower on a long field.
pub(crate) fn count_newlines(s: &[u8]) -> usize {
s.chunks(255).map(|c| c.iter().fold(0u8, |n, &b| n + (b == b'\n') as u8) as usize).sum()
}
impl TextEdit {
/// Text typed, pasted or committed into this field. Single-line fields drop control
/// characters, line breaks included (stripped, as `<input type=text>` does); multi-line
/// fields fold CRLF to LF (and multi-line secure fields also drop control characters other
/// than `\n` and `\t`). Sized up front so no partial copy of a secret is left behind by a
/// reallocation.
pub(crate) fn sanitize(&self, s: &str) -> Wiped {
let mut out = Wiped(String::with_capacity(s.len()));
if self.is_single_line() {
out.extend(s.chars().filter(|c| !c.is_control() && !matches!(c, '\u{2028}' | '\u{2029}')));
} else if self.secure {
let mut chars = s.chars().peekable();
while let Some(c) = chars.next() {
if c == '\r' {
if chars.peek() != Some(&'\n') {
out.push('\n');
}
continue;
}
if (!c.is_control() || matches!(c, '\n' | '\t')) && !matches!(c, '\u{2028}' | '\u{2029}') {
out.push(c);
}
}
} else if !s.contains('\r') {
// Most pastes: copied whole, not a character at a time.
out.push_str(s);
} else {
let mut chars = s.chars().peekable();
while let Some(c) = chars.next() {
if c == '\r' && chars.peek() == Some(&'\n') { continue; }
out.push(c);
}
}
out
}
/// Core replacement engine updating `text`, `marks`, `blocks`, and `soft_breaks` together.
pub(crate) fn apply_text_and_attr_replace(
&mut self,
(a, b): (usize, usize),
s: &str,
inserted_marks: &[Mark],
new_line_block: Option<Block>,
mark_new_lines_soft: bool,
) {
// Callers sync first; a second whole-text pass here would show on every keystroke.
self.column = Column::Free;
self.affinity = parley::Affinity::Downstream;
let del_len = b - a;
let ins_len = s.len();
if self.marks.is_empty()
&& inserted_marks.is_empty()
&& self.soft_breaks.is_empty()
&& !mark_new_lines_soft
&& new_line_block.is_none_or(|b| b == Block::Paragraph)
&& self.blocks.iter().all(|&b| b == Block::Paragraph)
{
// Plain text: no per-line passes, so a keystroke in a long plain field costs what
// it did before blocks and marks existed.
let removed = count_newlines(&self.text.as_bytes()[a..b]);
let added = count_newlines(s.as_bytes());
self.text.replace_range(a..b, s);
self.blocks.resize(self.blocks.len() + added - removed, Block::Paragraph);
self.anchor = a + ins_len;
self.focus = self.anchor;
self.cancel_composition();
return;
}
let line_a = self.line_of_byte(a);
let line_b = self.line_of_byte(b);
let line_a_range = self.line_range(line_a);
let line_b_range = self.line_range(line_b);
// Determine the surviving block for `line_a` when `a..b` merges `line_a..=line_b`.
let merged_block = if line_a < line_b
&& line_a_range.is_empty()
&& a == line_a_range.start
&& b == line_b_range.start
{
self.blocks.get(line_b).copied().unwrap_or(Block::Paragraph)
} else {
self.blocks.get(line_a).copied().unwrap_or(Block::Paragraph)
};
let merged_soft = if line_a < line_b
&& line_a_range.is_empty()
&& a == line_a_range.start
&& b == line_b_range.start
{
self.soft_breaks.binary_search(&(line_b as u32)).is_ok() && line_a > 0
} else {
self.soft_breaks.binary_search(&(line_a as u32)).is_ok()
};
let removed_lines = line_b - line_a;
let added_lines = count_newlines(s.as_bytes());
let next_line_blk = new_line_block.unwrap_or(match merged_block {
Block::Code => Block::Code,
_ => Block::Paragraph,
});
// Update `blocks` for removed and added lines.
if removed_lines > 0 {
self.blocks.drain(line_a + 1..=line_b);
}
if let Some(slot) = self.blocks.get_mut(line_a) {
*slot = merged_block;
}
if added_lines > 0 {
let insert_pos = (line_a + 1).min(self.blocks.len());
self.blocks.splice(insert_pos..insert_pos, std::iter::repeat_n(next_line_blk, added_lines));
}
// Update `soft_breaks`.
let mut next_soft = Vec::new();
for &sb in &self.soft_breaks {
let idx = sb as usize;
if idx < line_a {
next_soft.push(sb);
} else if idx > line_b {
let shifted = idx - removed_lines + added_lines;
if shifted > 0 {
next_soft.push(shifted as u32);
}
}
}
if merged_soft && line_a > 0 {
next_soft.push(line_a as u32);
}
if mark_new_lines_soft && added_lines > 0 {
for k in 1..=added_lines {
next_soft.push((line_a + k) as u32);
}
}
self.soft_breaks = next_soft;
// Shift and split existing inline marks around `a..b`.
let mut updated_marks = Vec::with_capacity(self.marks.len() + inserted_marks.len());
for m in self.marks.drain(..) {
if m.end <= a {
updated_marks.push(m);
} else if m.start >= b {
updated_marks.push(MarkRange {
start: m.start - del_len + ins_len,
end: m.end - del_len + ins_len,
mark: m.mark,
});
} else if m.mark.is_pill() {
// An edit that cuts into a pill leaves its remains as plain text.
} else {
// `m` overlaps `a..b` (or touches inside it).
if m.start < a {
updated_marks.push(MarkRange {
start: m.start,
end: a,
mark: m.mark.clone(),
});
}
if m.end > b {
updated_marks.push(MarkRange {
start: a + ins_len,
end: m.end - del_len + ins_len,
mark: m.mark,
});
}
}
}
if ins_len > 0 {
// Typed or replacing text never becomes a pill.
for im in inserted_marks.iter().filter(|m| !m.is_pill()) {
// Avoid wrapping a pure newline at the trailing edge of a mark unless inside the mark.
if s == "\n" {
let was_inside = updated_marks.iter().any(|m| m.mark == *im && m.start >= a + ins_len);
if !was_inside {
continue;
}
}
updated_marks.push(MarkRange {
start: a,
end: a + ins_len,
mark: im.clone(),
});
}
}
self.marks = updated_marks;
self.text.replace_range(a..b, s);
self.anchor = a + ins_len;
self.focus = self.anchor;
self.cancel_composition();
self.sync_invariants();
self.mark_edited();
}
pub(crate) fn replace(&mut self, (mut a, mut b): (usize, usize), s: &str, kind: EditKind) {
if self.is_hidden_multiline() && self.is_pristine() {
(a, b) = (0, self.text.len());
}
if self.secure {
let mut next = String::with_capacity(self.text.len() - (b - a) + s.len());
next.push_str(&self.text[..a]);
next.push_str(s);
next.push_str(&self.text[b..]);
self.replace_text(next);
self.anchor = a + s.len();
self.focus = self.anchor;
self.mark_edited();
return;
}
self.sync_invariants();
// Backspace or Delete next to a pill, or a selection into one, takes it whole.
let (a, b) = self.cover_pills(a, b);
if kind == EditKind::Other { self.break_history_group(); }
if &self.text[a..b] == s
&& self.typing == Typing::Inherited
&& !self.marks.iter().any(|m| m.mark.is_pill() && m.start < b && a < m.end)
{
self.anchor = a + s.len();
self.focus = self.anchor;
self.cancel_composition();
self.mark_edited();
return;
}
// Only the bytes this replaces: a keystroke in a long draft copies none of the rest.
let before = self.ranged(a, b);
let inserted_marks: Vec<Mark> = if s.is_empty() {
self.typing = Typing::Inherited;
Vec::new()
} else if let Some(p) = self.typing.take_at((self.anchor, self.focus)) {
p
} else if a < b {
// Replacing a selection inherits marks that covered the first character of the selection.
let line_idx = self.line_of_byte(a);
if self.blocks.get(line_idx) == Some(&Block::Code) {
Vec::new()
} else {
self.marks
.iter()
.filter(|m| m.start <= a && a < m.end)
.map(|m| m.mark.clone())
.collect()
}
} else {
self.inherited_marks_at(a)
};
self.apply_text_and_attr_replace((a, b), s, &inserted_marks, None, false);
self.record_ranged(before, s, kind);
}
}
+924
View File
@@ -0,0 +1,924 @@
#[test]
fn plain_edit_leaves_rich_keys_alone_and_pastes_plain_text() {
let shift_enter = KeyEvent { key: Key::Enter, mods: Mods { shift: true, ..Mods::default() } };
let mut e = TextEdit::new("hello");
e.set_selection(0, 5);
e.key(&cmd('b'), None);
e.key(&cmd('i'), None);
assert!(e.marks().is_empty() && e.is_plain());
e.set(5, false);
e.key(&shift_enter, None);
assert_eq!((e.text.as_str(), e.soft_breaks()), ("hello\n", &[][..]));
e.paste_html("<b>x</b><ul><li>y</li></ul>", "x\ny");
assert_eq!(e.text, "hello\nx\ny");
assert!(e.is_plain(), "a plain field pastes the plain text");
let mut r = TextEdit::new("hello").rich();
r.set_selection(0, 5);
r.key(&cmd('b'), None);
assert_eq!(marked(&r, &Mark::Bold), ["hello"]);
r.set(5, false);
r.key(&shift_enter, None);
assert_eq!(r.soft_breaks(), &[1]);
assert!(TextEdit::from_html("<b>a</b>").is_rich() && TextEdit::from_parts("a", vec![], vec![]).is_rich());
}
#[test]
fn direct_text_assignment_never_panics() {
let fresh = || {
let mut e = TextEdit::from_html("<ul><li><b>bold</b> <a href=\"https://a.b\">item</a></li></ul><pre><code>a\nb</code></pre><p>x<br>y</p>");
e.set(e.text.len(), false);
e
};
// The app shrinks `text` under marks, blocks, soft breaks and a caret that sit past its
// end or inside a character.
let stale = |e: &mut TextEdit| {
e.text = "é🦀".into();
e.anchor = 1;
e.focus = 3;
};
let mut e = fresh();
stale(&mut e);
let _ = (e.selected(), e.display(), e.paragraphs(), e.active_block(), e.active_marks(), e.has_mark(&Mark::Bold));
let _ = (e.to_html(), e.selected_html());
e.key(&k(Key::Left), None);
assert_invariants(&e, "after Left");
for ev in [k(Key::Text("z".into())), k(Key::Backspace), k(Key::Enter), cmd('b'), k(Key::Tab)] {
let mut e = fresh();
stale(&mut e);
e.key(&ev, None);
assert_invariants(&e, &format!("after {ev:?}"));
}
let mut e = fresh();
stale(&mut e);
e.ime(&Ime::Preedit("に".into(), None, Vec::new()));
e.ime(&Ime::Commit("日".into()));
assert_invariants(&e, "after IME");
let mut e = fresh();
stale(&mut e);
e.paste_html("<i>p</i>", "p");
assert_invariants(&e, "after paste_html");
let mut e = fresh();
stale(&mut e);
e.toggle_mark(Mark::Italic);
e.set_block(Block::Quote);
assert_invariants(&e, "after toggle_mark and set_block");
}
#[test]
fn count_newlines_matches_a_plain_count() {
for len in [0, 1, 254, 255, 256, 600, 70_000] {
let t: Vec<u8> = (0..len).map(|i| if i % 3 == 0 || i > 1000 { b'\n' } else { b'x' }).collect();
assert_eq!(count_newlines(&t), t.iter().filter(|&&b| b == b'\n').count(), "{len}");
}
}
#[test]
fn list_levels_stop_at_max_list_level() {
let mut e = TextEdit::new("a").rich();
e.set_block(Block::Bullet(0));
for _ in 0..10 { e.key(&k(Key::Tab), None); }
assert_eq!(e.blocks(), &[Block::Bullet(MAX_LIST_LEVEL)]);
e.set_block(Block::Numbered(9));
assert_eq!(e.blocks(), &[Block::Numbered(MAX_LIST_LEVEL)]);
assert_eq!(TextEdit::from_parts("a", vec![], vec![Block::Bullet(200)]).blocks(), &[Block::Bullet(MAX_LIST_LEVEL)]);
let deep = TextEdit::from_html(&format!("{}a", "<ul><li>".repeat(8)));
assert_eq!(deep.blocks().last(), Some(&Block::Bullet(MAX_LIST_LEVEL)));
}
#[test]
fn paste_html_without_formatting_keeps_the_plain_whitespace() {
// VS Code's copy: colour spans in a `white-space: pre` div.
let html = concat!(
"<meta charset='utf-8'><div style=\"color: #d4d4d4;white-space: pre;\">",
"<div><span style=\"color: #569cd6;\">fn</span><span>&nbsp;a()&nbsp;{</span></div>",
"<div><span>&nbsp; &nbsp; b</span></div><div><span>}</span></div></div>",
);
let mut e = TextEdit::new("").rich();
e.paste_html(html, "fn a() {\n b\n}");
assert_eq!(e.text, "fn a() {\n b\n}");
let mut e = TextEdit::new("").rich();
e.paste_html("<p>a <b>b</b></p>", "a b");
assert_eq!((e.text.as_str(), marked(&e, &Mark::Bold)), ("a b", vec!["b"]), "formatted HTML still wins");
}
#[test]
fn paste_html_into_a_code_block_keeps_the_plain_whitespace() {
let mut e = TextEdit::new("").rich();
e.set_block(Block::Code);
e.paste_html("<p>fn a()</p><p>b</p>", "fn a() {\n\tb\n}");
assert_eq!(e.text, "fn a() {\n\tb\n}");
assert_eq!(e.blocks(), &[Block::Code; 3]);
assert!(e.marks().is_empty());
}
#[test]
fn soft_breaks_can_be_set_on_a_rebuilt_draft() {
let mut e = TextEdit::from_parts("one\ntwo\nthree", vec![], vec![Block::Bullet(0); 3]).with_soft_breaks(vec![5, 1, 0, 1]);
assert!(!e.has_history(), "with_soft_breaks on from_parts adds no undo step");
assert_eq!(e.soft_breaks(), &[1], "line 0, duplicates and lines past the end are dropped");
assert_eq!(e.to_html().matches("<li>").count(), 2, "\"two\" continues the first bullet");
assert_invariants(&e, "with_soft_breaks");
e.set_soft_breaks(vec![2]);
assert!(!e.has_history());
assert_eq!(e.soft_breaks(), &[2]);
let round = TextEdit::from_parts(e.text.clone(), e.marks().to_vec(), e.blocks().to_vec()).with_soft_breaks(e.soft_breaks().to_vec());
assert_eq!(round.to_html(), e.to_html());
}
#[test]
fn clear_history_drops_undo_and_redo_while_keeping_formatting_and_selection() {
let mut e = TextEdit::from_parts("one\ntwo", vec![MarkRange::new(0..3, Mark::Bold)], vec![Block::Bullet(0); 2])
.with_soft_breaks(vec![1]);
e.insert("!");
e.undo();
assert!(e.has_history());
e.redo();
e.set_selection(1, 4);
e.clear_history();
assert!(!e.has_history());
e.undo();
e.redo();
assert_eq!((e.text.as_str(), e.anchor, e.focus), ("one\ntwo!", 1, 4));
assert_eq!(e.marks(), &[MarkRange::new(0..3, Mark::Bold)]);
assert_eq!(e.blocks(), &[Block::Bullet(0); 2]);
assert_eq!(e.soft_breaks(), &[1]);
}
#[test]
fn return_on_a_blank_last_line_leaves_a_code_block_in_one_undo_step() {
let mut e = TextEdit::new("").rich();
e.set_block(Block::Code);
e.key(&k(Key::Text("let x = 1;".into())), None);
e.key(&k(Key::Enter), None);
assert_eq!((e.text.as_str(), e.blocks()), ("let x = 1;\n", &[Block::Code; 2][..]));
// Composing on a blank code line and pressing Return to commit stays in the block.
// IME commits join typing; give this composition its own undo boundary.
e.break_history_group();
e.ime(&Ime::Preedit("に".into(), None, Vec::new()));
assert!(!e.key(&k(Key::Enter), None).submit);
e.ime(&Ime::Commit("日".into()));
assert_eq!((e.text.as_str(), e.blocks()), ("let x = 1;\n日", &[Block::Code; 2][..]));
undo(&mut e, false);
assert_eq!((e.text.as_str(), e.blocks()), ("let x = 1;\n", &[Block::Code; 2][..]));
let out = e.key(&k(Key::Enter), None);
assert!(!out.submit);
assert_eq!((e.text.as_str(), e.blocks()), ("let x = 1;\n", &[Block::Code, Block::Paragraph][..]), "the blank line left the block");
assert_eq!((e.anchor, e.focus), (11, 11));
undo(&mut e, false);
assert_eq!((e.text.as_str(), e.blocks()), ("let x = 1;\n", &[Block::Code; 2][..]), "leaving is one undo step");
undo(&mut e, true);
assert_eq!((e.text.as_str(), e.blocks()), ("let x = 1;\n", &[Block::Code, Block::Paragraph][..]), "redo leaves the block again");
e.key(&k(Key::Text("after".into())), None);
assert_eq!(e.blocks(), &[Block::Code, Block::Paragraph]);
assert_invariants(&e, "left code");
undo(&mut e, false);
undo(&mut e, false);
assert_eq!((e.text.as_str(), e.blocks()), ("let x = 1;\n", &[Block::Code; 2][..]));
// A blank line with more code below it is the code's own.
let mut e = TextEdit::from_parts("a\n\nb", vec![], vec![Block::Code; 3]);
e.anchor = 2;
e.focus = 2;
e.key(&k(Key::Enter), None);
assert_eq!((e.text.as_str(), e.blocks()), ("a\n\n\nb", &[Block::Code; 4][..]));
// So is a non-blank last line, and a blank line under a selection.
let mut e = TextEdit::from_parts("a\n", vec![], vec![Block::Code; 2]);
e.anchor = 0;
e.focus = 2;
e.key(&k(Key::Enter), None);
assert_eq!((e.text.as_str(), e.blocks()), ("\n", &[Block::Code; 2][..]));
}
#[test]
fn down_or_right_at_the_end_of_a_trailing_code_block_or_quote_adds_a_paragraph() {
for (block, key) in [(Block::Code, Key::Down), (Block::Code, Key::Right), (Block::Quote, Key::Down), (Block::Quote, Key::Right)] {
let mut e = TextEdit::from_parts("x\ny", vec![], vec![block; 2]);
let ctx = format!("{block:?} {key:?}");
e.anchor = 1;
e.focus = 1;
e.key(&k(key.clone()), None);
assert_eq!(e.text, "x\ny", "{ctx}: not at the end, the caret just moves");
e.anchor = 3;
e.focus = 3;
e.key(&k(key.clone()), None);
assert_eq!((e.text.as_str(), e.blocks()), ("x\ny\n", &[block, block, Block::Paragraph][..]), "{ctx}");
assert_eq!((e.anchor, e.focus), (4, 4), "{ctx}");
assert_invariants(&e, &ctx);
e.key(&k(key.clone()), None);
assert_eq!(e.text, "x\ny\n", "{ctx}: a paragraph at the end stays put");
undo(&mut e, false);
assert_eq!((e.text.as_str(), e.blocks()), ("x\ny", &[block; 2][..]), "{ctx}: one undo step");
undo(&mut e, true);
assert_eq!((e.text.as_str(), e.blocks()), ("x\ny\n", &[block, block, Block::Paragraph][..]), "{ctx}: redo restores it");
}
// Does not fire with a selection at the end, during IME, with modifiers, or in a plain field.
for key in [Key::Down, Key::Right] {
let mut e = TextEdit::from_parts("x", vec![], vec![Block::Code]);
e.set_selection(0, 1);
e.key(&k(key.clone()), None);
assert_eq!((e.text.as_str(), e.blocks()), ("x", &[Block::Code][..]), "selection ending at end");
let mut e = TextEdit::from_parts("x", vec![], vec![Block::Code]);
e.ime(&Ime::Preedit("に".into(), None, Vec::new()));
e.key(&k(key.clone()), None);
assert_eq!((e.text.as_str(), e.blocks()), ("x", &[Block::Code][..]), "during IME preedit");
let mut e = TextEdit::from_parts("x", vec![], vec![Block::Code]);
e.key(&KeyEvent { key: key.clone(), mods: Mods { shift: true, ..Mods::default() } }, None);
e.key(&KeyEvent { key: key.clone(), mods: Mods { alt: true, ..Mods::default() } }, None);
assert_eq!((e.text.as_str(), e.blocks()), ("x", &[Block::Code][..]), "modified arrow");
let mut plain = TextEdit::new("x");
plain.key(&k(key), None);
assert_eq!((plain.text.as_str(), plain.blocks()), ("x", &[Block::Paragraph][..]), "plain field");
}
}
#[test]
fn a_field_keeps_only_the_marks_and_blocks_it_allows() {
let mut e = TextEdit::from_parts("ab", vec![MarkRange { start: 0, end: 1, mark: Mark::Underline }], vec![Block::Paragraph])
.allow_marks([Mark::Bold, Mark::Strike, Mark::Code, Mark::Link(String::new())])
.allow_blocks([Block::Bullet(0), Block::Quote]);
assert!(e.marks().is_empty(), "marks it held are dropped");
assert!(e.allows_mark(&Mark::Link("https://example.com".into())) && !e.allows_mark(&Mark::Italic));
assert!(e.allows_block(Block::Bullet(3)) && e.allows_block(Block::Paragraph) && !e.allows_block(Block::Code));
e.anchor = 0;
e.focus = 2;
assert_eq!(e.format_chord(&cmd('u')), None, "⌘U is the app's");
e.key(&cmd('u'), None);
e.key(&cmd('i'), None);
e.toggle_mark(Mark::Italic);
e.set_mark(Mark::Underline);
assert!(e.marks().is_empty());
e.key(&cmd('b'), None);
assert_eq!(marked(&e, &Mark::Bold), ["ab"]);
e.toggle_block(Block::Code);
e.set_block(Block::Numbered(0));
assert_eq!(e.blocks(), &[Block::Paragraph]);
e.toggle_block(Block::Bullet(0));
assert_eq!(e.blocks(), &[Block::Bullet(0)]);
e.set_marks(vec![MarkRange { start: 0, end: 2, mark: Mark::Italic }]);
assert!(e.marks().is_empty(), "set_marks can't add one either");
e.set_blocks(vec![Block::Code]);
assert_eq!(e.blocks(), &[Block::Paragraph], "set_blocks can't add one either");
// Undo/redo of an edit recorded before allow_marks/allow_blocks was set, or a pending
// mark armed before allow_marks, cannot smuggle a disallowed mark or block back in.
let mut pre = TextEdit::new("ab").rich();
pre.set_selection(0, 2);
pre.set_mark(Mark::Underline);
pre.set_block(Block::Code);
pre.set_caret(2);
pre.insert("!");
pre.toggle_mark(Mark::Italic);
let mut pre = pre.allow_marks([Mark::Bold]).allow_blocks([Block::Quote]);
assert!(!pre.has_mark(&Mark::Italic), "pending disallowed mark is stripped");
undo(&mut pre, false);
assert!(pre.marks().is_empty() && pre.blocks() == &[Block::Paragraph], "undo filters snapshot");
undo(&mut pre, true);
assert!(pre.marks().is_empty() && pre.blocks() == &[Block::Paragraph], "redo filters snapshot");
// Pills are the app's tokens, kept whatever the allow-list says.
let mut p = TextEdit::new("hi @maya").rich().allow_marks([Mark::Bold]);
assert!(p.allows_mark(&Mark::Pill(String::new())));
p.replace_with_pill(3..8, "user:maya", "@maya");
assert_eq!(p.pills().count(), 1, "replace_with_pill works under an allow-list");
let p = p.allow_marks(Vec::<Mark>::new());
assert_eq!(p.pills().count(), 1, "an allow-list set later keeps existing pills");
let mut e = TextEdit::new("").rich().allow_marks([Mark::Bold]).allow_blocks([Block::Quote]);
e.paste_html("<ul><li><b>b</b> <i>i</i> <u>u</u></li></ul><blockquote>q</blockquote><pre>c</pre>", "");
assert_eq!(e.text, "b i u\nq\nc");
assert_eq!(e.marks().iter().map(|m| &m.mark).collect::<Vec<_>>(), [&Mark::Bold]);
assert_eq!(e.blocks(), &[Block::Paragraph, Block::Quote, Block::Paragraph]);
assert_invariants(&e, "filtered paste");
// HTML whose only formatting the field drops pastes as plain text, keeping its spacing.
let mut e = TextEdit::new("").rich().allow_marks([Mark::Bold]);
e.paste_html("<p><i>a b</i></p>", "a b");
assert_eq!(e.text, "a b");
}
#[test]
fn flatten_spans_matches_the_naive_merge_and_later_spans_win() {
use rune_core::color::Color;
use rune_text::{Span, flatten_spans};
fn naive(spans: &[Span]) -> Vec<Span> {
let mut bounds: Vec<u32> = spans.iter().filter(|s| s.start < s.end).flat_map(|s| [s.start, s.end]).collect();
bounds.sort_unstable();
bounds.dedup();
let mut out: Vec<Span> = Vec::new();
for w in bounds.windows(2) {
let mut m: Option<Span> = None;
for s in spans.iter().filter(|s| s.start < s.end && s.start <= w[0] && w[1] <= s.end) {
let m = m.get_or_insert_with(|| Span::new(w[0] as usize, w[1] as usize));
if s.weight.is_some() { m.weight = s.weight; }
if s.color.is_some() { m.color = s.color; }
if s.bg.is_some() { m.bg = s.bg; m.bg_pad = s.bg_pad; }
if s.underline.is_some() { m.underline = s.underline; }
if s.size.is_some() { m.size = s.size; }
m.mono |= s.mono;
m.italic |= s.italic;
}
if let Some(m) = m {
match out.last_mut() {
Some(last) if last.end == m.start && Span { start: m.start, end: m.end, ..last.clone() } == m => last.end = m.end,
_ => out.push(m),
}
}
}
out
}
let red = Color::WHITE;
let blue = Color::BLACK;
assert_eq!(
flatten_spans(&[Span::new(2, 5).color(blue), Span::new(0, 10).color(red)]),
[Span::new(0, 10).color(red)],
"a later span wins even where it starts first"
);
assert_eq!(
flatten_spans(&[Span::new(0, 10).color(red), Span::new(2, 5).color(blue).bold()]),
[Span::new(0, 2).color(red), Span::new(2, 5).color(blue).bold(), Span::new(5, 10).color(red)]
);
let mut seed = 7u64;
let mut next = |n: u64| { seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); (seed >> 33) % n };
for _ in 0..300 {
let spans: Vec<Span> = (0..next(12)).map(|_| {
let a = next(40) as usize;
let mut s = Span::new(a, a + next(15) as usize);
match next(5) {
0 => s = s.color(if next(2) == 0 { red } else { blue }),
1 => s = s.bold(),
2 => s = s.italic(),
3 => s = s.bg(red, next(3) as f32),
_ => s = s.mono().underline(blue),
}
s
}).collect();
assert_eq!(flatten_spans(&spans), naive(&spans), "{spans:?}");
}
}
#[test]
fn html_parsing_is_linear_on_hostile_input() {
let n = 200_000;
let cases = [
"<b>".repeat(n) + "x",
"<script>".to_owned() + &"</script".repeat(n),
"<p>".to_owned() + &"&".repeat(n * 4),
"<div><span>".repeat(n / 2) + &"</div>".repeat(n / 2),
"</b>".repeat(n),
"<ul><li>".repeat(n / 2) + "x",
"a<br>".repeat(n),
"<a href=\"".to_owned() + &"&#x6a;".repeat(n) + "\">x</a>",
];
for html in &cases {
let t = rune_core::time::now();
let e = TextEdit::from_html(html);
assert_invariants(&e, &html[..20]);
let _ = e.to_html();
// Debug builds parse these in well under a second; a quadratic path takes minutes.
assert!(t.elapsed().as_secs() < 10, "{} took {:?}", &html[..20], t.elapsed());
}
}
#[test]
fn html_links_keep_only_safe_schemes() {
for bad in [
"javascript:alert(1)", "JaVaScRiPt:alert(1)", " javascript:x", "java\tscript:x", "java\nscript:x",
"java&#x09;script:x", "&#106;avascript:x", "javascript&#58;x", "javascript&colon;x", "java&Tab;script:x",
"jav&#x0A;ascript:x", "\u{1}javascript:x", "vbscript:x", "data:text/html,x", "file:///etc/passwd",
"blob:https://a.b/x", "x-app-scheme:do",
] {
let e = TextEdit::from_html(&format!("<a href=\"{bad}\">x</a><a href='{bad}'>y</a>"));
assert!(e.marks().iter().all(|m| !matches!(m.mark, Mark::Link(_))), "{bad:?} kept: {:?}", e.marks());
assert_eq!(e.text, "xy");
}
for (good, url) in [
("https://a.b/c?d=1&amp;e=2", "https://a.b/c?d=1&e=2"),
("HTTP://A.B", "HTTP://A.B"),
("mailto:a@b.c", "mailto:a@b.c"),
("tel:+1555", "tel:+1555"),
("/relative/path", "/relative/path"),
("#frag", "#frag"),
] {
let e = TextEdit::from_html(&format!("<a href=\"{good}\">x</a>"));
assert_eq!(e.marks(), &[MarkRange::new(0..1, Mark::Link(url.into()))], "{good}");
}
let e = TextEdit::from_html("a&#0;b&#x1;c<pre>d&#0;\te</pre>");
assert_eq!(e.text, "abc\nd\te", "entities never decode to control characters");
}
#[test]
fn html_from_browsers_notes_slack_and_docs_round_trips() {
let round_trip = |e: &TextEdit, ctx: &str| {
let back = TextEdit::from_html(&e.to_html());
assert_eq!(
(&back.text, back.marks(), back.blocks(), back.soft_breaks()),
(&e.text, e.marks(), e.blocks(), e.soft_breaks()),
"{ctx} round trip"
);
assert_invariants(e, ctx);
};
let chrome = TextEdit::from_html(concat!(
"<meta charset='utf-8'><span style=\"color: rgb(0, 0, 0); font-family: Arial; font-weight: 700;\">Hello</span>",
"<span style=\"color: rgb(0, 0, 0);\"> world</span>",
));
assert_eq!(chrome.text, "Hello world");
assert_eq!(marked(&chrome, &Mark::Bold), ["Hello"]);
round_trip(&chrome, "browser");
let notes = TextEdit::from_html(concat!(
"<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n<html>\n<head>\n",
"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n",
"<style type=\"text/css\">\np.p1 {margin: 0.0px 0.0px 0.0px 0.0px}\n</style>\n</head>\n<body>\n",
"<p class=\"p1\"><b>Bold</b> text</p>\n<p class=\"p1\"><br></p>\n",
"<ul class=\"ul1\">\n<li class=\"li1\">item one</li>\n<li class=\"li1\"><i>item two</i></li>\n</ul>\n",
"</body>\n</html>\n",
));
assert_eq!(notes.text, "Bold text\n\nitem one\nitem two");
assert_eq!(notes.blocks(), &[Block::Paragraph, Block::Paragraph, Block::Bullet(0), Block::Bullet(0)]);
assert_eq!((marked(&notes, &Mark::Bold), marked(&notes, &Mark::Italic)), (vec!["Bold"], vec!["item two"]));
round_trip(&notes, "notes");
let slack = TextEdit::from_html(concat!(
"<meta charset='utf-8'><b data-stringify-type=\"bold\" style=\"color: rgb(29, 28, 29);\">bold</b>",
"<span style=\"color: rgb(29, 28, 29);\"> and </span><i data-stringify-type=\"italic\">it</i><span> </span>",
"<code data-stringify-type=\"code\" class=\"c-mrkdwn__code\">x()</code><br style=\"color: rgb(29, 28, 29);\">",
"<a target=\"_blank\" class=\"c-link\" data-stringify-link=\"https://a.b/c?d=1&amp;e=2\" ",
"href=\"https://a.b/c?d=1&amp;e=2\" rel=\"noopener noreferrer\">link</a>",
));
assert_eq!(slack.text, "bold and it x()\nlink");
assert_eq!(slack.soft_breaks(), &[1]);
assert_eq!(marked(&slack, &Mark::Code), ["x()"]);
assert_eq!(marked(&slack, &Mark::Link("https://a.b/c?d=1&e=2".into())), ["link"]);
round_trip(&slack, "slack");
let docs = TextEdit::from_html(concat!(
"<meta charset=\"utf-8\"><b style=\"font-weight:normal;\" id=\"docs-internal-guid-1\">",
"<p dir=\"ltr\" style=\"line-height:1.38;margin-top:0pt;\"><span style=\"font-size:11pt;font-weight:700;\">Bold</span>",
"<span style=\"font-size:11pt;font-weight:400;\"> plain</span></p>",
"<ul style=\"margin-top:0;\"><li dir=\"ltr\" style=\"list-style-type:disc;\"><p dir=\"ltr\" role=\"presentation\">",
"<span style=\"font-style:italic;\">item</span></p></li></ul></b>",
));
assert_eq!(docs.text, "Bold plain\nitem");
assert_eq!(docs.blocks(), &[Block::Paragraph, Block::Bullet(0)]);
assert_eq!((marked(&docs, &Mark::Bold), marked(&docs, &Mark::Italic)), (vec!["Bold"], vec!["item"]));
round_trip(&docs, "google docs");
let loose = TextEdit::from_html("<p>A</p>B<p>C<br></p>");
assert_eq!(loose.text, "A\nB\nC", "loose text gets its own line; a trailing <br> draws nothing");
round_trip(&loose, "loose");
}
#[test]
fn random_edits_keep_ranges_blocks_and_soft_breaks_consistent() {
const PIECES: [&str; 10] = ["a", "b ", "é", "🦀", "e\u{301}", "👩\u{200d}👩\u{200d}👧", "日本", "\n", "\t", " "];
for seed in 0..40u64 {
let mut state = seed.wrapping_mul(0x9e37_79b9_7f4a_7c15) | 1;
let mut next = |n: u64| { state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); (state >> 33) % n };
let mut e = TextEdit::from_html("<p>start <b>bold</b></p><ul><li>item</li></ul>");
let (mut clip, mut clip_html) = (String::new(), String::new());
for step in 0..300 {
let op = next(22);
let mods = Mods { shift: next(3) == 0, alt: next(4) == 0, ..Mods::default() };
match op {
0..=3 => { let p = PIECES[next(PIECES.len() as u64) as usize]; e.key(&k(Key::Text(p.into())), None); }
4 => { e.key(&KeyEvent { key: Key::Enter, mods }, None); }
5 => { e.key(&KeyEvent { key: Key::Backspace, mods }, None); }
6 => { e.key(&KeyEvent { key: Key::Delete, mods }, None); }
7 => { e.key(&KeyEvent { key: if next(2) == 0 { Key::Left } else { Key::Right }, mods }, None); }
8 => { e.key(&KeyEvent { key: if next(2) == 0 { Key::Home } else { Key::End }, mods }, None); }
9 => { e.key(&KeyEvent { key: Key::Tab, mods: Mods { shift: mods.shift, ..Mods::default() } }, None); }
10 => { e.key(&cmd(['b', 'i', 'u'][next(3) as usize]), None); }
11 => e.toggle_mark([Mark::Code, Mark::Strike, Mark::Link(format!("https://e.x/{}", next(3)))][next(3) as usize].clone()),
12 => {
let l = next(6) as u8;
e.set_block([Block::Paragraph, Block::Bullet(l), Block::Numbered(l), Block::Quote, Block::Code][next(5) as usize]);
}
13 => undo(&mut e, next(2) == 0),
14 => {
clip_html = e.selected_html();
if let Some(c) = e.key(&cmd(if next(2) == 0 { 'x' } else { 'c' }), None).copy { clip = c; }
}
15 => { e.paste(&clip.clone()); }
16 => { e.paste_html(&clip_html.clone(), &clip.clone()); }
17 => {
let p = PIECES[next(6) as usize];
e.ime(&Ime::Preedit(p.into(), None, Vec::new()));
if next(2) == 0 { e.ime(&Ime::Commit(p.into())); }
}
18 => { let a = next(e.text.len() as u64 + 2) as usize; let f = next(e.text.len() as u64 + 2) as usize; e.set_selection(a, f); }
19 => {
// An app writes `text` and the caret directly, then the user types.
if next(2) == 0 { let cut = next(e.text.len() as u64 + 1) as usize; let cut = TextEdit::clamp_char_boundary(&e.text, cut); e.text.truncate(cut); }
else { e.text.push_str(PIECES[next(PIECES.len() as u64) as usize]); }
e.anchor = next(e.text.len() as u64 + 3) as usize;
e.focus = e.anchor;
e.key(&k(Key::Text("z".into())), None);
}
20 => { e.key(&cmd('a'), None); }
_ => { e.key(&KeyEvent { key: if next(2) == 0 { Key::Up } else { Key::Down }, mods }, None); }
}
assert_invariants(&e, &format!("seed {seed} step {step} op {op} text {:?}", e.text));
let _ = (e.to_html(), e.display(), e.paragraphs());
}
}
}
/// `"a @x-agent b"` with the label a pill carrying `agent:x`, the caret after it.
fn with_pill() -> TextEdit {
let mut e = TextEdit::new("a b").rich();
e.set_caret(2);
e.insert_pill("agent:x", "@x-agent");
e
}
fn pills_of(e: &TextEdit) -> Vec<(Range<usize>, String)> {
e.pills().map(|(r, id)| (r, id.to_owned())).collect()
}
#[test]
fn a_pill_replaces_a_typed_query_and_lists_with_its_id() {
let mut e = TextEdit::new("").rich();
e.insert("see @ma");
let at = e.text.find('@').unwrap();
e.replace_with_pill(at..e.text.len(), "file:src/main.rs", "@main.rs\n");
assert_eq!(e.text, "see @main.rs ", "line breaks in a label become spaces");
assert_eq!(pills_of(&e), [(4..13, "file:src/main.rs".to_owned())]);
assert_eq!(e.range(), (13, 13));
e.key(&k(Key::Text("x".into())), None);
assert_eq!(pills_of(&e), [(4..13, "file:src/main.rs".to_owned())], "typing after a pill never extends it");
e.set_caret(4);
e.key(&k(Key::Text("y".into())), None);
assert_eq!((e.text.as_str(), pills_of(&e)), ("see y@main.rs x", vec![(5..14, "file:src/main.rs".to_owned())]));
let mut secure = TextEdit::new("").secure();
secure.insert_pill("a", "@a");
assert_eq!((secure.text.as_str(), secure.pills().count()), ("", 0));
}
#[test]
fn the_caret_steps_over_a_pill_in_one_move() {
let mut e = with_pill();
assert_eq!((e.text.as_str(), e.range()), ("a @x-agent b", (10, 10)));
e.key(&k(Key::Left), None);
assert_eq!(e.range(), (2, 2));
e.key(&k(Key::Left), None);
assert_eq!(e.range(), (1, 1));
e.key(&k(Key::Right), None);
e.key(&k(Key::Right), None);
assert_eq!(e.range(), (10, 10));
e.set_caret(2);
e.key(&KeyEvent { key: Key::Right, mods: Mods { alt: true, ..Mods::default() } }, None);
// On macOS a word forward stops at the pill's end; elsewhere it lands past the trailing
// space at the next word's start, still stepping over the label in one move.
let after_pill = if cfg!(target_os = "macos") { 10 } else { 11 };
assert_eq!(e.range(), (after_pill, after_pill), "a word move that stops inside the label steps over it");
e.set_caret(2);
e.key(&KeyEvent { key: Key::Right, mods: Mods { shift: true, ..Mods::default() } }, None);
assert_eq!((e.anchor, e.focus), (2, 10), "Shift+Right selects the whole pill");
e.set_caret(5);
assert_eq!(e.range(), (2, 2), "a click inside goes to the nearer edge");
e.set_caret(8);
assert_eq!(e.range(), (10, 10));
// A caret written straight into a pill moves out before the next edit.
e.anchor = 6;
e.focus = 6;
e.insert("Z");
assert_eq!((e.text.as_str(), pills_of(&e)), ("a @x-agentZ b", vec![(2..10, "agent:x".to_owned())]));
}
#[test]
fn an_undo_group_is_one_step_with_its_selection_and_nests() {
let mut e = TextEdit::new("hi @ag").rich();
e.set_caret(6);
e.undo_group(|e| {
e.replace_with_pill(3..6, "agent:1", "@agent");
e.undo_group(|e| e.insert(" "));
});
assert_eq!((e.text.as_str(), e.range(), e.pills().count()), ("hi @agent ", (10, 10), 1));
undo(&mut e, false);
assert_eq!((e.text.as_str(), e.range(), e.pills().count()), ("hi @ag", (6, 6), 0));
undo(&mut e, true);
assert_eq!((e.text.as_str(), e.range(), pills_of(&e)), ("hi @agent ", (10, 10), vec![(3..9, "agent:1".to_owned())]));
undo(&mut e, false);
assert_eq!(e.text, "hi @ag");
assert!(e.history.undo.is_empty(), "the group was a single step");
}
#[test]
fn undo_groups_keep_typing_coalescing_and_record_nothing_when_empty() {
let mut e = TextEdit::default();
e.key(&k(Key::Text("a".into())), None);
e.key(&k(Key::Text("b".into())), None);
assert_eq!(e.history.undo.len(), 1, "typing coalesces before a group");
e.undo_group(|_| {});
e.undo_group(|e| e.set_caret(0));
e.undo_group(|e| e.set_selection(0, 2));
e.undo_group(|e| {
e.set_caret(2);
e.insert("x");
e.key(&k(Key::Backspace), None);
});
assert_eq!(e.history.undo.len(), 1, "empty, caret-only and cancelling groups add no step");
e.key(&k(Key::Text("c".into())), None);
e.undo_group(|e| { e.insert("X"); e.insert("Y"); });
e.key(&k(Key::Text("d".into())), None);
assert_eq!(e.history.undo.len(), 4, "typing run breaks before and after a group");
undo(&mut e, false);
assert_eq!(e.text, "abcXY");
// An empty or caret-only group preserves the redo stack.
e.undo_group(|e| e.set_caret(0));
assert_eq!(e.history.redo.len(), 1);
undo(&mut e, false);
assert_eq!(e.text, "abc");
}
#[test]
fn undo_group_is_unwind_safe_and_interacts_with_clear_history_paste_and_soft_breaks() {
let mut e = TextEdit::new("base").rich();
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
e.undo_group(|e| {
e.insert("!");
panic!("boom");
});
})).ok();
assert!(!e.group.is_open(), "unwinding clears the active group");
e.insert("?");
assert_eq!(e.history.undo.len(), 1, "edits after a caught panic record again");
e.undo();
assert_eq!(e.text, "base!");
// Caught panic in a nested group leaves the outer group intact.
e.clear_history();
e.undo_group(|e| {
e.insert("1");
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
e.undo_group(|e| {
e.insert("2");
panic!("nested boom");
});
})).ok();
e.insert("3");
});
assert_eq!((e.text.as_str(), e.history.undo.len()), ("base!123", 1));
e.undo();
assert_eq!(e.text, "base!");
// Cloning or comparing inside a group does not leak the active group into the clone.
let mut cloned = None;
e.undo_group(|e| {
assert_eq!(*e, e.clone());
let c = e.clone();
cloned = Some(c);
});
let mut cloned = cloned.unwrap();
cloned.insert("ok");
assert_eq!(cloned.history.undo.len(), 1);
cloned.undo();
assert_eq!(cloned.text, "base!");
// clear_history and clear inside a group drop prior edits in the group.
e.undo_group(|e| {
e.insert("drop");
e.clear_history();
});
assert!(!e.has_history());
e.undo_group(|e| {
e.insert("-keep");
e.clear_history();
e.insert("-after");
});
assert_eq!(e.history.undo.len(), 1);
e.undo();
assert_eq!(e.text, "base!drop-keep");
e.undo_group(|e| e.clear());
assert_eq!((e.text.as_str(), e.has_history()), ("", false));
// Paste, soft breaks and many edits inside one group count as one step against HISTORY_STEPS.
e.undo_group(|e| {
e.paste_html("<p><b>one</b></p>", "one");
e.insert("\ntwo");
e.set_soft_breaks(vec![1]);
});
assert_eq!((e.text.as_str(), e.soft_breaks(), e.history.undo.len()), ("one\ntwo", &[1][..], 1));
e.undo();
assert_eq!((e.text.as_str(), e.soft_breaks(), e.marks().len()), ("", &[][..], 0));
e.redo();
assert_eq!((e.text.as_str(), e.soft_breaks(), e.marks().len()), ("one\ntwo", &[1][..], 1));
e.undo_group(|e| {
for _ in 0..200 {
e.insert("x");
}
});
assert_eq!(e.history.undo.len(), 2, "200 edits in one group do not evict prior steps");
}
#[test]
fn an_undo_group_leaves_ime_composition_alone() {
let mut e = TextEdit::new("x").rich();
e.set_caret(1);
e.ime(&Ime::Preedit("に".into(), None, Vec::new()));
e.undo_group(|e| e.ime(&Ime::Commit("日本".into())));
assert_eq!((e.text.as_str(), e.preedit().is_none()), ("x日本", true));
undo(&mut e, false);
assert_eq!(e.text, "x");
e.ime(&Ime::Preedit("a".into(), None, Vec::new()));
e.undo_group(|e| e.undo());
assert!(e.preedit().is_some(), "undo inside a group does nothing");
}
#[test]
fn backspace_and_delete_take_a_pill_whole_and_undo_restores_its_id() {
let mut e = with_pill();
e.key(&k(Key::Backspace), None);
assert_eq!((e.text.as_str(), e.range(), e.pills().count()), ("a b", (2, 2), 0));
undo(&mut e, false);
assert_eq!((e.text.as_str(), pills_of(&e)), ("a @x-agent b", vec![(2..10, "agent:x".to_owned())]));
e.set_caret(2);
e.key(&k(Key::Delete), None);
assert_eq!((e.text.as_str(), e.pills().count()), ("a b", 0));
undo(&mut e, false);
e.set_caret(11);
e.key(&k(Key::Backspace), None);
assert_eq!((e.text.as_str(), pills_of(&e)), ("a @x-agentb", vec![(2..10, "agent:x".to_owned())]));
e.set_caret(10);
e.key(&KeyEvent { key: Key::Backspace, mods: Mods { alt: true, ..Mods::default() } }, None);
assert_eq!((e.text.as_str(), e.pills().count()), ("a b", 0), "a word delete into a pill takes it whole");
undo(&mut e, false);
undo(&mut e, true);
undo(&mut e, false);
assert_eq!(pills_of(&e), [(2..10, "agent:x".to_owned())]);
}
#[test]
fn a_selection_into_a_pill_covers_it() {
let mut e = with_pill();
e.set_selection(0, 5);
assert_eq!((e.anchor, e.focus), (0, 10));
e.set_selection(7, 12);
assert_eq!((e.anchor, e.focus), (2, 12));
e.set_selection(11, 4);
assert_eq!((e.anchor, e.focus), (11, 2));
e.set_selection(0, 5);
e.insert("z");
assert_eq!((e.text.as_str(), e.pills().count()), ("z b", 0));
// Formatting a pill restyles its label and keeps it whole.
let mut e = with_pill();
e.set_selection(0, 6);
e.toggle_mark(Mark::Bold);
assert_eq!(pills_of(&e), [(2..10, "agent:x".to_owned())]);
assert!(e.marks().iter().any(|m| m.mark == Mark::Bold && m.range() == (0..10)));
}
#[test]
fn a_composition_never_splits_a_pill() {
let mut e = with_pill();
e.anchor = 4;
e.focus = 4;
e.ime(&Ime::Preedit("に".into(), None, Vec::new()));
let (shown, pre) = e.display();
let (pa, _) = pre.unwrap();
assert!(pa <= 2 || pa >= 10, "preedit at {pa} in {shown:?}");
assert_eq!(e.display_pills().len(), 1);
e.ime(&Ime::Commit("日本".into()));
assert_eq!(pills_of(&e).len(), 1);
assert_eq!(&e.text[pills_of(&e)[0].0.clone()], "@x-agent");
assert!(e.text == "a 日本@x-agent b" || e.text == "a @x-agent日本 b", "{}", e.text);
}
#[test]
fn pills_round_trip_through_html_and_outside_html_makes_none() {
let mut e = with_pill();
e.set_selection(0, 5);
e.toggle_mark(Mark::Italic);
e.set_selection(0, e.text.len());
let html = e.selected_html();
assert!(html.contains("<span data-pill=\"agent:x\">"), "{html}");
assert_eq!(e.selected(), "a @x-agent b", "the plain copy is the label");
let mut other = TextEdit::new("").rich();
other.paste_html_with_pills(&html, e.selected());
assert_eq!((other.text.as_str(), pills_of(&other)), ("a @x-agent b", vec![(2..10, "agent:x".to_owned())]));
let mut outside = TextEdit::new("").rich();
outside.paste_html(&html, e.selected());
assert_eq!((outside.text.as_str(), outside.pills().count()), ("a @x-agent b", 0));
assert!(outside.marks().iter().any(|m| m.mark == Mark::Italic), "the rest of the formatting stays");
// A pill split by a mark's edge still serializes as one span.
let one = TextEdit::from_html("<p><span data-pill=\"f&quot;1\">@f<b>il</b>e</span></p>");
assert_eq!(pills_of(&one), [(0..5, "f\"1".to_owned())]);
assert!(one.to_html().contains("<span data-pill=\"f&quot;1\">@f<strong>il</strong>e</span>"), "{}", one.to_html());
// A pill can't span lines.
let broken = TextEdit::from_parts("a\nb c", vec![MarkRange::new(0..3, Mark::Pill("x".into())), MarkRange::new(4..5, Mark::Pill("c".into()))], Vec::new());
assert_eq!(pills_of(&broken), [(4..5, "c".to_owned())]);
}
#[test]
fn pill_edge_cases_words_lines_bidi_and_direct_text_mutation() {
// Touching pills, punctuation after a pill, and spaces inside a pill label.
let mut e = TextEdit::new("").rich();
e.insert_pill("u:1", "@maya");
e.insert_pill("u:2", "@noah");
e.insert(", ");
e.insert_pill("u:3", "@Maya Lin");
assert_eq!(e.text, "@maya@noah, @Maya Lin");
let alt_left = KeyEvent { key: Key::Left, mods: Mods { alt: true, ..Mods::default() } };
let alt_right = KeyEvent { key: Key::Right, mods: Mods { alt: true, ..Mods::default() } };
let alt_bs = KeyEvent { key: Key::Backspace, mods: Mods { alt: true, ..Mods::default() } };
e.key(&alt_left, None);
assert_eq!(e.range(), (12, 12), "steps over @Maya Lin as one word");
e.key(&alt_left, None);
assert_eq!(e.range(), (10, 10), "stops between @noah and comma");
e.key(&alt_left, None);
assert_eq!(e.range(), (5, 5), "steps over @noah without eating @maya");
e.key(&alt_left, None);
assert_eq!(e.range(), (0, 0), "steps over @maya");
e.key(&alt_right, None);
assert_eq!(e.range(), (5, 5));
e.key(&alt_right, None);
// On macOS a word forward stops at the pill's end; elsewhere it skips trailing punctuation
// and spaces to the next pill's start.
let after_noah = if cfg!(target_os = "macos") { 10 } else { 12 };
assert_eq!(e.range(), (after_noah, after_noah));
e.key(&alt_right, None);
assert_eq!(e.range(), (21, 21), "steps over @Maya Lin as one word");
e.set_caret(10);
e.key(&alt_bs, None);
assert_eq!((e.text.as_str(), pills_of(&e)), ("@maya, @Maya Lin", vec![(0..5, "u:1".to_owned()), (7..16, "u:3".to_owned())]));
// Vertical movement and line_edge across wrapped lines ending or starting with pills.
let mut ts = rune_text::TextSystem::default();
let style = rune_core::tok::TextStyle::new(14.0, 400.0);
let mut w = TextEdit::new("hello world ").rich();
w.set_caret(w.text.len());
w.insert_pill("p:1", "@first-pill");
w.insert(" ");
w.insert_pill("p:2", "@second-pill");
w.insert(" tail");
let chips: Vec<rune_text::PillChip> = w
.display_pills()
.into_iter()
.map(|(start, end, _)| rune_text::PillChip { start, end, icon: None, bg: None, fg: None, bare: None })
.collect();
let layout = ts.layout_blocks(&w.text, &[], w.blocks(), &chips, style, 2.0, Some(220.0), parley::Alignment::Start);
assert!(layout.len() >= 3, "wrapped into {} lines", layout.len());
// Caret at end of line 0 ("hello world "), press Down onto the pill line: snaps to a pill edge on line 1, never jumps to EOF.
w.set_caret(11);
w.key(&k(Key::Down), Some(&layout));
assert!(w.focus < w.text.len(), "Down onto a pill line stays on that line: {}", w.focus);
assert!(w.pill_around(w.focus).is_none(), "caret never lands inside a pill: {}", w.focus);
// Shift+Down across a pill line covers the pill whole.
w.set_caret(0);
w.key(&KeyEvent { key: Key::Down, mods: Mods { shift: true, ..Mods::default() } }, Some(&layout));
assert!(w.pill_around(w.focus).is_none());
// IME preedit right after a pill does not bleed its underline box into the pill's chip.
let mut ime_e = with_pill();
ime_e.set_caret(10);
ime_e.ime(&Ime::Preedit("に".into(), None, Vec::new()));
let (disp, pre) = ime_e.display();
let (pa, pb) = pre.unwrap();
let p_chips: Vec<rune_text::PillChip> = ime_e
.display_pills()
.into_iter()
.map(|(start, end, _)| rune_text::PillChip { start, end, icon: None, bg: None, fg: None, bare: None })
.collect();
let ime_layout = ts.layout_blocks(&disp, &[], &[Block::Paragraph], &p_chips, style, 2.0, None, parley::Alignment::Start);
let (mut decos, mut icons) = (Vec::new(), Vec::new());
rune_text::pill_chips(&ime_layout, &p_chips, 14.0, 2.0, [0.0, 0.0], Color::BLACK, &mut decos, &mut icons);
let boxes = rune_text::range_boxes(&ime_layout, pa, pb, false);
assert_eq!(boxes.len(), 1);
assert!(boxes[0].0.x0 as f32 >= decos[0].rect[0] + decos[0].rect[2] - 0.5, "preedit box {:?} overlaps chip {:?}", boxes[0].0, decos[0].rect);
// RTL pill and mixed RTL+LTR pill chips have positive width.
for (txt, start, end) in [("דוד", 0u32, 6u32), ("שלום@maya", 8, 13), ("@e\u{0301}", 0, 4)] {
let pc = [rune_text::PillChip { start, end, icon: None, bg: None, fg: None, bare: None }];
let l = ts.layout_blocks(txt, &[], &[Block::Paragraph], &pc, style, 2.0, None, parley::Alignment::Start);
let (mut d, mut ic) = (Vec::new(), Vec::new());
rune_text::pill_chips(&l, &pc, 14.0, 2.0, [0.0, 0.0], Color::BLACK, &mut d, &mut ic);
assert_eq!(d.len(), 1, "{txt:?}");
assert!(d[0].rect[2] > 8.0, "chip for {txt:?} has width {}", d[0].rect[2]);
}
// Direct text assignment on a field holding pills never panics or exposes invalid pill ranges.
let mut direct = with_pill();
direct.text = "é".into();
assert_eq!(direct.pills().count(), 0);
assert!(direct.display_pills().is_empty());
direct.set_caret(99);
assert_eq!(direct.range(), (2, 2));
// Mark::Pill at collapsed caret does not arm pending; set_mark replaces an existing pill; plain insert strips a pill.
let mut m = with_pill();
m.set_caret(0);
m.toggle_mark(Mark::Pill("x".into()));
m.set_mark(Mark::Pill("x".into()));
assert_eq!(m.typing, Typing::Inherited);
m.set_selection(2, 10);
m.set_mark(Mark::Pill("agent:y".into()));
assert_eq!(pills_of(&m), [(2..10, "agent:y".to_owned())]);
m.set_selection(2, 10);
m.insert("@x-agent");
assert_eq!((m.text.as_str(), m.pills().count()), ("a @x-agent b", 0));
}
+173
View File
@@ -0,0 +1,173 @@
//! Password fields: the secure setting, the reveal toggle, and how a masked field maps model
//! bytes to the bullets it draws.
use super::*;
/// Fixed mask shown by a hidden multi-line secure field when non-empty, hiding both byte length
/// and line count.
#[doc(hidden)]
pub const MULTILINE_SECURE_MASK: &str = "••••••••••••";
/// Mirrors whether the bound `text_input` has `El::single_line`.
/// Before a field mounts, standalone [`TextEdit::secure`] defaults to single-line.
#[derive(Clone, Copy, Default, PartialEq, Eq)]
pub(super) enum LineMode {
#[default]
Default,
Single,
Multi,
}
/// How a field draws its text, read from its secure setting, its reveal toggle and its line
/// mode. The toggle is kept on a plain field too, so `.revealed(true).secure()` reveals in
/// either order.
#[doc(hidden)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Masking {
/// Not secure: the text as typed.
Plain,
/// Secure and revealed: the plain characters, with every other secure protection kept.
Shown,
/// Secure and hidden: one bullet per character on one line, or a fixed mask over several.
Hidden { multiline: bool },
}
impl TextEdit {
#[doc(hidden)]
pub fn masking(&self) -> Masking {
match (self.secure, self.revealed) {
(false, _) => Masking::Plain,
(true, true) => Masking::Shown,
(true, false) => Masking::Hidden { multiline: !self.is_single_line() },
}
}
/// The text draws as bullets, which caret motion treats as one word on one line.
#[doc(hidden)]
pub fn is_masked(&self) -> bool {
matches!(self.masking(), Masking::Hidden { .. })
}
/// Password editing: masked display, no undo, copy, cut or IME. All model buffers are
/// wiped on drop; secure replacements also wipe the previous allocation before freeing it.
pub fn secure(mut self) -> Self { self.set_secure(true); self }
pub fn is_secure(&self) -> bool { self.secure }
pub fn set_secure(&mut self, secure: bool) {
self.secure = secure;
if secure {
self.history = Arc::default();
if self.group.is_open() {
self.group = Group::Unrecorded;
}
self.marks.clear();
self.blocks.clear();
self.soft_breaks.clear();
self.typing = Typing::Inherited;
self.cancel_composition();
} else if let Group::Unrecorded = self.group {
// A group opened while secure starts recording from here.
self.sync_invariants();
self.group = Group::Open(self.snapshot_now());
}
}
/// Show the plain characters of a [`secure`](Self::secure) field while keeping all other
/// secure protections: no undo, copy, cut, IME or accessibility text, redacted [`Debug`],
/// and zeroized buffers.
/// Rune-owned source buffers are wiped; third-party shaping scratch used while revealed
/// is released after shaping but is not guaranteed zeroized.
pub fn revealed(mut self, revealed: bool) -> Self { self.set_revealed(revealed); self }
pub fn is_revealed(&self) -> bool { self.revealed }
pub fn set_revealed(&mut self, revealed: bool) { self.revealed = revealed; }
#[doc(hidden)]
pub fn is_single_line(&self) -> bool {
match self.line_mode {
LineMode::Default => self.secure,
LineMode::Single => true,
LineMode::Multi => false,
}
}
#[doc(hidden)]
pub fn set_single_line(&mut self, single_line: bool) {
self.line_mode = if single_line { LineMode::Single } else { LineMode::Multi };
}
/// Whether this is a multi-line secure field in hidden mode (`secure && !revealed && !single_line`).
#[doc(hidden)]
pub fn is_hidden_multiline(&self) -> bool {
self.masking() == Masking::Hidden { multiline: true }
}
/// The text a secure field draws: its mask while hidden, its characters while revealed.
pub(super) fn masked_display(&self) -> String {
match self.masking() {
Masking::Hidden { multiline: false } => "•".repeat(self.text.chars().count()),
Masking::Hidden { multiline: true } if !self.text.is_empty() => MULTILINE_SECURE_MASK.to_owned(),
Masking::Hidden { multiline: true } => String::new(),
Masking::Plain | Masking::Shown => self.text.clone(),
}
}
/// For a secure field that has started exiting: wipe the secret and keep only its mask, so
/// the field paints the same dots (no placeholder) through the exit with no plaintext.
#[doc(hidden)]
pub fn conceal(&mut self) {
if !self.secure { return; }
self.revealed = false;
let mask = self.masked_display();
self.replace_text(mask);
}
/// Map model bytes to the bullet layout's bytes and back. Each Unicode scalar gets one
/// bullet in single-line mode so UTF-8 length never changes caret/selection alignment;
/// hidden multi-line fields pin the visual caret to the end of the fixed mask and map
/// pointer hits to the end of the model.
#[doc(hidden)]
pub fn display_index(&self, byte: usize) -> usize {
match self.masking() {
Masking::Hidden { multiline: true } => if self.text.is_empty() { 0 } else { MULTILINE_SECURE_MASK.len() },
Masking::Hidden { multiline: false } => self.text[..byte.min(self.text.len())].chars().count() * '•'.len_utf8(),
Masking::Plain | Masking::Shown => byte.min(self.text.len()),
}
}
#[doc(hidden)]
pub fn model_index(&self, byte: usize) -> usize {
match self.masking() {
Masking::Hidden { multiline: true } => self.text.len(),
Masking::Hidden { multiline: false } => {
self.text.char_indices().nth(byte / '•'.len_utf8()).map_or(self.text.len(), |(i, _)| i)
}
Masking::Plain | Masking::Shown => byte.min(self.text.len()),
}
}
#[doc(hidden)]
pub fn display_selection_range(&self, a: usize, b: usize) -> (usize, usize) {
if self.is_hidden_multiline() {
if a == b || self.text.is_empty() { (0, 0) } else { (0, MULTILINE_SECURE_MASK.len()) }
} else {
(self.display_index(a), self.display_index(b))
}
}
// A fixed mask has no visible interior positions. Preserve the revealed selection until
// an edit occurs, then treat it as either the whole secret or an insertion at its end.
pub(super) fn normalize_hidden_selection(&mut self) {
if self.is_hidden_multiline() {
let selected = self.anchor != self.focus;
self.focus = self.text.len();
self.anchor = if selected { 0 } else { self.focus };
}
}
}
#[cfg(test)]
#[path = "secure_tests.rs"]
mod tests;
+41
View File
@@ -0,0 +1,41 @@
use super::*;
#[test]
fn masking_reads_the_secure_setting_the_reveal_toggle_and_the_line_mode() {
let hidden = Masking::Hidden { multiline: false };
assert_eq!(TextEdit::new("pw").masking(), Masking::Plain);
assert_eq!(TextEdit::new("pw").secure().masking(), hidden, "a field not yet mounted is single-line");
assert_eq!(TextEdit::new("pw").secure().revealed(true).masking(), Masking::Shown);
// The toggle is kept on a plain field, so builders may set it before `secure`.
let mut e = TextEdit::new("pw").revealed(true);
assert_eq!((e.masking(), e.display().0.as_str()), (Masking::Plain, "pw"));
e.set_secure(true);
assert_eq!(e.masking(), Masking::Shown);
e.set_secure(false);
e.set_secure(true);
assert_eq!(e.masking(), Masking::Shown, "turning secure off and on keeps the toggle");
e.set_revealed(false);
e.set_single_line(false);
assert_eq!(e.masking(), Masking::Hidden { multiline: true });
assert!(e.is_masked() && e.is_hidden_multiline());
e.set_single_line(true);
assert!(e.is_masked() && !e.is_hidden_multiline());
}
#[test]
fn conceal_keeps_exactly_the_mask_the_hidden_field_drew() {
for (single, text) in [(true, "hé🙂"), (false, "two\nlines"), (true, ""), (false, "")] {
let mut e = TextEdit::new(text).secure();
e.set_single_line(single);
let drawn = e.display().0;
e.set_revealed(true);
e.conceal();
assert_eq!(e.masking(), Masking::Hidden { multiline: !single });
assert_eq!((e.text.as_str(), e.display().0), (drawn.as_str(), drawn.clone()));
}
let mut plain = TextEdit::new("kept").revealed(true);
plain.conceal();
assert_eq!((plain.text.as_str(), plain.is_revealed()), ("kept", true), "a plain field has nothing to conceal");
}
+915
View File
@@ -0,0 +1,915 @@
use super::*;
use super::history::{HISTORY_BYTES, HISTORY_STEPS};
fn k(key: Key) -> KeyEvent {
KeyEvent { key, mods: Mods::default() }
}
#[test]
fn is_command_matches_any_character_and_both_forms_of_cmd_space() {
let cmd = Mods { cmd: true, ..Mods::default() };
let ev = |key, mods| KeyEvent { key, mods };
assert!(ev(Key::Command(','), cmd).is_command(','));
assert!(ev(Key::Command('1'), cmd).is_command('1'));
assert!(ev(Key::Command('k'), cmd).is_command('K'));
assert!(ev(Key::Command('z'), Mods { shift: true, ..cmd }).is_command('z'));
assert!(!ev(Key::Command('k'), cmd).is_command('j'));
assert!(ev(Key::Text(" ".into()), cmd).is_command(' '));
assert!(ev(Key::Command(' '), cmd).is_command(' '));
assert!(!ev(Key::Text(" ".into()), Mods::default()).is_command(' '));
assert!(!ev(Key::Text("k".into()), Mods::default()).is_command('k'));
}
fn undo(e: &mut TextEdit, redo: bool) {
e.key(&KeyEvent { key: Key::Command('z'), mods: Mods { cmd: true, shift: redo, ..Mods::default() } }, None);
}
#[test]
fn secure_unicode_editing_has_no_history_or_export() {
let mut e = TextEdit::new("hé🙂");
e.insert("x");
e.set_secure(true);
assert!(e.history.undo.is_empty());
assert_eq!(e.display().0, "••••");
for (model, display) in [(0, 0), (1, 3), (3, 6), (7, 9), (8, 12)] {
assert_eq!(e.display_index(model), display);
assert_eq!(e.model_index(display), model);
}
e.anchor = 1;
e.focus = 7;
for command in ['c', 'x', 'z'] {
assert!(e.key(&k(Key::Command(command)), None).copy.is_none());
assert_eq!(e.text, "hé🙂x");
}
e.paste("界");
assert_eq!((&*e.text, e.anchor, e.focus), ("h界x", 4, 4));
e.ime(&Ime::Preedit("composition".into(), None, Vec::new()));
e.ime(&Ime::Commit("commit".into()));
assert!(e.preedit().is_none());
assert_eq!(e.text, "h界x");
e.undo(); e.redo();
assert_eq!(e.text, "h界x");
assert!(e.history.undo.is_empty() && e.history.redo.is_empty());
assert!(!format!("{e:?}").contains("h界x"));
e.clear();
assert!(e.is_secure());
}
#[test]
fn secure_revealed_uses_plain_display_and_words_while_keeping_protections() {
use std::hash::{DefaultHasher, Hash, Hasher};
let hash = |e: &TextEdit| {
let mut h = DefaultHasher::new();
e.hash(&mut h);
h.finish()
};
let mut e = TextEdit::new("hé🙂 world").secure();
let hidden_hash = hash(&e);
assert!(!e.is_revealed());
assert_eq!(e.display().0, "•••••••••");
// Hidden secure fields treat the masked string as a single word.
let alt_left = KeyEvent { key: Key::Left, mods: Mods { alt: true, ..Mods::default() } };
let alt_right = KeyEvent { key: Key::Right, mods: Mods { alt: true, ..Mods::default() } };
e.set_caret(e.text.len());
e.key(&alt_left, None);
assert_eq!(e.focus, 0);
e.key(&alt_right, None);
assert_eq!(e.focus, e.text.len());
e.set_selection(1, 7);
e.set_revealed(true);
assert!(e.is_secure() && e.is_revealed());
assert_ne!(hash(&e), hidden_hash, "Hash for TextEdit must include revealed");
assert_eq!((e.anchor, e.focus), (1, 7), "toggling revealed preserves selection");
assert_eq!(e.display(), ("hé🙂 world".into(), None));
for idx in [0, 1, 3, 7, 8, 13] {
assert_eq!(e.display_index(idx), idx);
assert_eq!(e.model_index(idx), idx);
}
// Revealed secure fields step over words normally.
e.set_caret(e.text.len());
e.key(&alt_left, None);
assert_eq!(e.focus, 8);
e.key(&alt_left, None);
assert_eq!(e.focus, 0);
e.key(&alt_right, None);
// Words go by UAX #29: on macOS a word forward ends at "hé", an emoji being a word of its
// own; off macOS it lands past the space, at the next word's start.
assert_eq!(e.focus, if cfg!(target_os = "macos") { 3 } else { 8 });
// Copy, cut, undo, redo and IME remain blocked when revealed.
e.set_selection(1, 7);
for command in ['c', 'x', 'z'] {
assert!(e.key(&k(Key::Command(command)), None).copy.is_none());
assert_eq!(e.text, "hé🙂 world");
}
e.key(&k(Key::Text("!".into())), None);
assert_eq!(e.text, "h! world");
assert!(!e.has_history());
undo(&mut e, false);
e.undo();
e.redo();
assert_eq!(e.text, "h! world");
e.ime(&Ime::Preedit("comp".into(), Some((0, 4)), Vec::new()));
e.ime(&Ime::Commit("commit".into()));
assert!(e.preedit().is_none());
assert_eq!(e.text, "h! world");
let dbg = format!("{e:?}");
assert!(!dbg.contains("h! world") && !dbg.contains("world") && dbg.contains("[redacted]"));
// Toggling revealed off again preserves text and selection.
e.set_selection(2, 8);
e.set_revealed(false);
assert_eq!((&*e.text, e.anchor, e.focus), ("h! world", 2, 8));
assert_eq!(e.display().0, "••••••••");
// Conceal wipes a revealed field to bullets and clears revealed.
let mut exiting = TextEdit::new("hunter2").secure().revealed(true);
exiting.conceal();
assert!(exiting.is_secure() && !exiting.is_revealed());
assert_eq!(exiting.text, "•••••••");
assert_eq!(exiting.display().0, "•••••••");
}
#[test]
fn hidden_multiline_navigation_and_edits_have_no_invisible_interior() {
let mut e = TextEdit::new("first\nlast").secure();
e.set_single_line(false);
for key in [Key::Left, Key::Right, Key::Up, Key::Down, Key::Home, Key::End] {
e.set_caret(2);
e.key(&k(key.clone()), None);
assert_eq!(e.range(), (e.text.len(), e.text.len()));
e.key(&KeyEvent { key, mods: Mods { shift: true, ..Mods::default() } }, None);
assert_eq!(e.range(), (0, e.text.len()));
}
assert!(e.is_pristine(), "navigation keys do not clear pristine");
e.mark_edited();
e.set_caret(2);
e.key(&k(Key::Text("!".into())), None);
assert_eq!(e.text, "first\nlast!");
e.set_caret(2);
e.key(&k(Key::Backspace), None);
assert_eq!(e.text, "first\nlast");
e.key(&k(Key::Delete), None);
assert_eq!(e.text, "first\nlast");
e.set_caret(2);
e.paste("\r\nnext");
assert_eq!(e.text, "first\nlast\nnext");
e.set_selection(1, 3);
e.paste("replacement\nlines");
assert_eq!(e.text, "replacement\nlines");
e.set_revealed(true);
e.set_selection(1, 3);
e.set_revealed(false);
e.set_revealed(true);
assert_eq!(e.range(), (1, 3), "toggle without editing preserves revealed selection");
}
#[test]
fn pristine_secure_backspace_at_start_and_ime_do_not_bypass_protection() {
let mut e = TextEdit::new("fictional-secret").secure();
e.set_single_line(false);
e.set_caret(0);
e.key(&k(Key::Backspace), None);
assert!(e.text.is_empty());
assert!(!e.has_history());
e.replace_text("fictional-secret");
e.ime(&Ime::Preedit("composition".into(), None, Vec::new()));
assert!(e.preedit().is_none());
assert!(e.is_pristine());
e.ime(&Ime::Commit("commit".into()));
assert_eq!(e.text, "fictional-secret", "secure inputs reject IME commits too");
assert!(e.is_pristine());
e.paste("replacement");
assert_eq!(e.text, "replacement");
assert!(!e.is_pristine());
e.undo();
assert_eq!(e.text, "replacement");
assert!(!e.has_history());
}
#[test]
fn hidden_multiline_pristine_replace_and_delete() {
// 1. Typing while pristine replaces the whole value, regardless of caret or navigation.
let mut e = TextEdit::new("existing-fictional-key\nline-two").secure();
e.set_single_line(false);
assert!(e.is_pristine());
e.set_caret(0);
for nav in [Key::Left, Key::Right, Key::Up, Key::Down, Key::Home, Key::End] {
e.key(&k(nav), None);
}
assert!(e.is_pristine());
e.key(&k(Key::Text("a".into())), None);
assert_eq!(e.text, "a");
assert!(!e.is_pristine());
// Subsequent edits append and delete normally.
e.key(&k(Key::Text("b".into())), None);
assert_eq!(e.text, "ab");
e.paste("cd");
assert_eq!(e.text, "abcd");
e.key(&k(Key::Backspace), None);
assert_eq!(e.text, "abc");
// 2. Pasting while pristine replaces the whole value, regardless of selection.
let mut e = TextEdit::new("existing-fictional-key\nline-two").secure();
e.set_single_line(false);
e.set_selection(3, 7);
e.paste("new-key\nline-2");
assert_eq!(e.text, "new-key\nline-2");
assert!(!e.is_pristine());
e.paste("\nline-3");
assert_eq!(e.text, "new-key\nline-2\nline-3");
// 3. Deletions while pristine empty the whole value, then subsequent typing starts fresh.
let mut deletions = vec![
k(Key::Backspace),
k(Key::Delete),
KeyEvent { key: Key::Backspace, mods: Mods { cmd: true, ..Mods::default() } },
KeyEvent { key: Key::Backspace, mods: Mods { alt: true, ..Mods::default() } },
KeyEvent { key: Key::Backspace, mods: Mods { ctrl: true, cmd: !cfg!(target_os = "macos"), ..Mods::default() } },
KeyEvent { key: Key::Delete, mods: Mods { ctrl: true, cmd: !cfg!(target_os = "macos"), ..Mods::default() } },
];
// Ctrl-K is an AppKit control-letter binding on macOS only (`KeyEvent::control_binding`).
if cfg!(target_os = "macos") {
deletions.push(KeyEvent { key: Key::Text("k".into()), mods: Mods { ctrl: true, ..Mods::default() } });
}
for del in deletions {
let mut e = TextEdit::new("existing-fictional-key\nline-two").secure();
e.set_single_line(false);
e.set_caret(4);
e.key(&del, None);
assert_eq!(e.text, "", "deletion {del:?} must empty pristine hidden multiline");
assert_eq!(e.range(), (0, 0));
assert!(!e.is_pristine());
e.key(&k(Key::Text("x".into())), None);
e.key(&k(Key::Text("y".into())), None);
assert_eq!(e.text, "xy");
}
if !cfg!(target_os = "macos") {
let mut e = TextEdit::new("existing-fictional-key\nline-two").secure();
e.set_single_line(false);
e.set_caret(4);
e.key(&KeyEvent { key: Key::Text("k".into()), mods: Mods { ctrl: true, ..Mods::default() } }, None);
assert_eq!(e.text, "existing-fictional-key\nline-two", "Ctrl+K is a command chord off macOS");
assert!(e.is_pristine());
}
// 4. Toggling revealed (Show -> Hide) without editing keeps pristine; editing while revealed clears it.
let mut e = TextEdit::new("existing-fictional-key\nline-two").secure();
e.set_single_line(false);
e.set_revealed(true);
e.set_selection(2, 5);
e.set_revealed(false);
assert!(e.is_pristine(), "Show then Hide without editing keeps pristine");
e.set_caret(e.text.len());
e.paste("pasted-after-peek");
assert_eq!(e.text, "pasted-after-peek");
let mut rev = TextEdit::new("existing-fictional-key").secure().revealed(true);
rev.set_single_line(false);
rev.set_caret(rev.text.len());
rev.key(&k(Key::Text("!".into())), None);
assert_eq!(rev.text, "existing-fictional-key!", "revealed field edits normally at caret");
assert!(!rev.is_pristine());
rev.set_revealed(false);
rev.key(&k(Key::Text("?".into())), None);
assert_eq!(rev.text, "existing-fictional-key!?", "edited while revealed stays non-pristine when hidden");
// 5. App resetting via replace_text re-arms pristine, even for identical text.
rev.replace_text("reloaded-from-vault");
assert!(rev.is_pristine());
rev.key(&k(Key::Text("z".into())), None);
assert_eq!(rev.text, "z");
assert!(!rev.is_pristine());
rev.replace_text("z");
assert!(rev.is_pristine(), "same-value app replacement re-arms pristine");
rev.paste("fresh");
assert_eq!(rev.text, "fresh");
assert!(!rev.is_pristine());
// 6. Empty field is never pristine; single-line secure field never applies pristine replacement.
let mut empty = TextEdit::new("").secure();
empty.set_single_line(false);
assert!(!empty.is_pristine());
empty.key(&k(Key::Text("a".into())), None);
empty.key(&k(Key::Text("b".into())), None);
assert_eq!(empty.text, "ab");
let mut single = TextEdit::new("hunter2").secure();
single.set_single_line(true);
single.set_caret(7);
single.key(&k(Key::Text("!".into())), None);
assert_eq!(single.text, "hunter2!", "single-line secure field edits at caret");
}
#[test]
fn multiline_secure_edit_inserts_newlines_keeps_pasted_lines_and_masks_to_fixed_length() {
use std::hash::{DefaultHasher, Hash, Hasher};
let hash = |e: &TextEdit| {
let mut h = DefaultHasher::new();
e.hash(&mut h);
h.finish()
};
let mut e = TextEdit::new("").secure();
e.set_single_line(false);
assert!(!e.is_single_line() && e.is_hidden_multiline());
assert_eq!(e.display().0, "");
assert_eq!(e.display_index(0), 0);
e.paste("-----BEGIN FAKE KEY-----\r\nAAAAB3NzaC1yc2E\tline2");
assert_eq!(e.text, "-----BEGIN FAKE KEY-----\nAAAAB3NzaC1yc2E\tline2");
assert!(!e.key(&k(Key::Enter), None).submit, "plain Enter in multi-line secure field inserts a newline");
e.key(&k(Key::Text("-----END FAKE KEY-----".into())), None);
assert_eq!(
e.text,
"-----BEGIN FAKE KEY-----\nAAAAB3NzaC1yc2E\tline2\n-----END FAKE KEY-----"
);
assert!(
e.key(&KeyEvent { key: Key::Enter, mods: Mods { cmd: true, ..Mods::default() } }, None).submit,
"Cmd+Enter still submits a multi-line secure field"
);
let mut short = TextEdit::new("ten-bytes!").secure();
short.set_single_line(false);
let long_secret = (0..50)
.map(|i| format!("FAKEKEYLINE{i:02}AAAAB3NzaC1yc2EAAAADAQABAAABAQDfakebase64payloadblock0123456789ABCDEFGH=="))
.collect::<Vec<_>>()
.join("\n");
assert!(long_secret.len() >= 4096);
let mut long = TextEdit::new(long_secret).secure();
long.set_single_line(false);
assert_eq!(short.display().0, MULTILINE_SECURE_MASK);
assert_eq!(long.display().0, MULTILINE_SECURE_MASK);
assert_eq!(hash(&short), hash(&long), "hidden multi-line hash must not leak length or line count");
for offset in [0, 3, 10, 500, long.text.len()] {
assert_eq!(long.display_index(offset), MULTILINE_SECURE_MASK.len());
assert_eq!(long.model_index(offset), long.text.len());
}
assert_eq!(long.display_selection_range(5, 5), (0, 0));
assert_eq!(long.display_selection_range(2, 100), (0, MULTILINE_SECURE_MASK.len()));
// Concealing a multi-line secure field (hidden or revealed) leaves only the fixed mask.
let mut exiting_revealed = long.clone().revealed(true);
exiting_revealed.conceal();
assert!(exiting_revealed.is_secure() && !exiting_revealed.is_revealed());
assert_eq!(exiting_revealed.text, MULTILINE_SECURE_MASK);
assert_eq!(exiting_revealed.display().0, MULTILINE_SECURE_MASK);
}
/// Arrows and backspace treat a ZWJ family, a flag and a skin-toned hand as one character.
#[test]
fn caret_and_backspace_step_over_whole_emoji() {
let (family, flag, wave) = ("👨\u{200D}👩\u{200D}👧", "🇯🇵", "👋🏽");
let text = format!("a{family}{flag}{wave}");
let mut e = TextEdit::new(&text);
e.key(&k(Key::Home), None);
let mut stops = vec![e.focus];
for _ in 0..5 { e.key(&k(Key::Right), None); stops.push(e.focus); }
let ends = [0, 1, 1 + family.len(), 1 + family.len() + flag.len(), text.len(), text.len()];
assert_eq!(stops, ends);
for want in [format!("a{family}{flag}"), format!("a{family}"), "a".into()] {
e.key(&k(Key::Backspace), None);
assert_eq!(*e.text, want);
}
}
#[test]
fn history_groups_typing_and_restores_unicode_selection() {
let mut e = TextEdit::new("");
for s in ["h", "é", "🙂"] { e.key(&k(Key::Text(s.into())), None); }
undo(&mut e, false);
assert_eq!((&*e.text, e.anchor, e.focus), ("", 0, 0));
undo(&mut e, true);
assert_eq!((&*e.text, e.anchor, e.focus), ("hé🙂", 7, 7));
e.key(&k(Key::Left), None);
e.key(&KeyEvent { key: Key::Left, mods: Mods { shift: true, ..Mods::default() } }, None);
assert_eq!((e.anchor, e.focus), (3, 1));
e.paste("界\r\n日");
assert_eq!(e.text, "h界\n日🙂");
undo(&mut e, false);
assert_eq!((&*e.text, e.anchor, e.focus), ("hé🙂", 3, 1));
undo(&mut e, true);
assert_eq!((&*e.text, e.anchor, e.focus), ("h界\n日🙂", 8, 8));
undo(&mut e, false);
e.key(&k(Key::Text("a".into())), None);
undo(&mut e, true);
assert_eq!(e.text, "ha🙂", "new edit discards the redo branch");
undo(&mut e, false);
assert_eq!((&*e.text, e.anchor, e.focus), ("hé🙂", 3, 1));
}
#[test]
fn history_deletion_cut_and_ime_are_atomic() {
let mut e = TextEdit::new("hé🙂");
e.key(&k(Key::Backspace), None);
undo(&mut e, false);
assert_eq!((&*e.text, e.anchor, e.focus), ("hé🙂", 7, 7));
e.key(&k(Key::Home), None);
e.key(&k(Key::Delete), None);
undo(&mut e, false);
assert_eq!((&*e.text, e.anchor, e.focus), ("hé🙂", 0, 0));
e.anchor = 3;
e.focus = 1;
let out = e.key(&KeyEvent { key: Key::Command('x'), mods: Mods::default() }, None);
assert_eq!(out.copy.as_deref(), Some("é"));
undo(&mut e, false);
assert_eq!((e.anchor, e.focus), (3, 1));
e.ime(&Ime::Preedit("に".into(), None, Vec::new()));
e.ime(&Ime::Preedit("日本".into(), None, Vec::new()));
e.ime(&Ime::Commit("日本".into()));
assert_eq!(e.text, "h日本🙂");
undo(&mut e, false);
assert_eq!((&*e.text, e.anchor, e.focus), ("hé🙂", 3, 1));
assert!(e.preedit().is_none());
undo(&mut e, true);
assert_eq!(e.text, "h日本🙂");
e.ime(&Ime::Preedit("x".into(), None, Vec::new()));
undo(&mut e, false);
assert_eq!(e.text, "h日本🙂", "undo cancels preedit without undoing committed text");
assert!(e.preedit().is_none());
}
#[test]
fn history_is_bounded_shared_and_cleared_after_send() {
let mut e = TextEdit::new("");
for _ in 0..HISTORY_STEPS + 12 { e.paste("é"); }
let rendered = e.clone();
assert!(Arc::ptr_eq(&e.history, &rendered.history));
assert_eq!(e.history.undo.len(), HISTORY_STEPS);
for _ in 0..HISTORY_STEPS + 1 { e.undo(); }
assert_eq!(e.text, "é".repeat(12));
assert_eq!(rendered.text, "é".repeat(HISTORY_STEPS + 12));
e.paste(&"a".repeat(HISTORY_BYTES));
// Changed with undo as changes: the newest step stays however large, so a paste of a whole
// file can always be undone (older steps go to keep the history in its bytes).
assert_eq!(e.history.undo.len(), 1, "one oversized edit keeps its own step");
e.undo();
assert_eq!(e.text.len(), 24, "undoing it gives back the twelve characters before it");
e.redo();
e.focused = true;
e.clear();
e.undo();
assert!(e.focused && e.text.is_empty());
e.paste("draft");
e.text = "external".into();
e.anchor = e.text.len();
e.focus = e.anchor;
e.undo();
assert_eq!(e.text, "external", "external model replacement cannot restore stale history");
}
fn chord(s: &str, mods: Mods) -> KeyEvent { KeyEvent { key: Key::Text(s.into()), mods } }
#[test]
fn command_chords_type_nothing() {
let mut e = TextEdit::new("pw").secure();
e.key(&chord(" ", Mods { cmd: true, shift: true, logo: true, ..Mods::default() }), None);
e.key(&chord("a", Mods { ctrl: true, ..Mods::default() }), None);
assert_eq!(e.text, "pw");
let mut plain = TextEdit::new("");
plain.key(&chord(" ", Mods { cmd: true, logo: true, ..Mods::default() }), None);
plain.key(&chord("a", Mods { ctrl: true, cmd: !cfg!(target_os = "macos"), ..Mods::default() }), None);
assert_eq!(plain.text, "");
}
#[cfg(not(target_os = "macos"))]
#[test]
fn altgr_text_still_types() {
let mut e = TextEdit::new("");
e.key(&chord("€", Mods { ctrl: true, cmd: true, alt: true, ..Mods::default() }), None);
assert_eq!(e.text, "€");
}
#[test]
fn option_text_still_types() {
let mut e = TextEdit::new("").secure();
e.key(&chord("é", Mods { alt: true, ..Mods::default() }), None);
e.key(&chord("ø", Mods { alt: true, shift: true, ..Mods::default() }), None);
assert_eq!(e.text, "éø");
}
#[test]
fn paste_keeps_single_line_fields_on_one_line() {
let mut secure = TextEdit::new("").secure();
let mut single = TextEdit::new("");
single.set_single_line(true);
let mut multi = TextEdit::new("");
for e in [&mut secure, &mut single, &mut multi] { e.paste("a\tb\r\nc\u{2028}d"); }
assert_eq!(secure.text, "abcd");
assert_eq!(single.text, "abcd");
assert_eq!(multi.text, "a\tb\nc\u{2028}d");
single.ime(&Ime::Commit("x\ny".into()));
assert_eq!(single.text, "abcdxy");
}
#[test]
fn shift_enter_in_a_single_line_field_submits_without_a_line_break() {
let shift_enter = KeyEvent { key: Key::Enter, mods: Mods { shift: true, ..Mods::default() } };
let mut single = TextEdit::new("ab");
single.set_single_line(true);
let mut secure = TextEdit::new("ab").secure();
for e in [&mut single, &mut secure] {
assert!(e.key(&shift_enter, None).submit);
e.key(&k(Key::Text("\n".into())), None);
e.key(&k(Key::Text("\r\nc".into())), None);
assert_eq!(e.text, "abc");
}
}
#[cfg(target_os = "macos")]
#[test]
fn control_letters_edit_like_appkit_fields() {
let ctrl = |c: &str| KeyEvent { key: Key::Text(c.into()), mods: Mods { ctrl: true, ..Mods::default() } };
let mut e = TextEdit::new("one two\nthree");
e.set(4, false);
e.key(&ctrl("a"), None); assert_eq!(e.focus, 0);
e.key(&ctrl("e"), None); assert_eq!(e.focus, 7);
e.key(&ctrl("b"), None); e.key(&ctrl("b"), None); assert_eq!(e.focus, 5);
e.key(&ctrl("f"), None); assert_eq!(e.focus, 6);
e.key(&ctrl("h"), None); assert_eq!(e.text, "one to\nthree");
e.key(&ctrl("d"), None); assert_eq!(e.text, "one t\nthree");
e.set(0, false);
e.key(&ctrl("k"), None); assert_eq!(e.text, "\nthree");
e.key(&ctrl("k"), None); assert_eq!(e.text, "three", "at a line's end Ctrl-K joins the next line");
e.key(&ctrl("n"), None); assert_eq!(e.focus, 5);
e.key(&ctrl("x"), None); assert_eq!(e.text, "three", "other Control letters never type");
}
#[test]
fn typing_selection_and_submit() {
let mut e = TextEdit::default();
e.key(&k(Key::Text("héllo world".into())), None);
assert_eq!(e.text, "héllo world");
e.key(&KeyEvent { key: Key::Backspace, mods: Mods { alt: true, ..Mods::default() } }, None);
assert_eq!(e.text, "héllo ");
e.key(&k(Key::Left), None);
e.key(&KeyEvent { key: Key::Left, mods: Mods { shift: true, ..Mods::default() } }, None);
assert_eq!(e.selected(), "o");
e.key(&k(Key::Text("0".into())), None);
assert_eq!(e.text, "héll0 ");
e.ime(&Ime::Preedit("に".into(), None, Vec::new()));
assert_eq!(e.display().0, "héll0に ");
e.ime(&Ime::Commit("日".into()));
assert_eq!(e.text, "héll0日 ");
assert!(e.key(&k(Key::Enter), None).submit);
e.key(&KeyEvent { key: Key::Enter, mods: Mods { shift: true, ..Mods::default() } }, None);
assert!(e.text.contains('\n'));
}
#[test]
fn inline_marks_shift_split_inherit_and_respect_boundaries() {
let mut e = TextEdit::new("hello world");
// Apply bold to "hello" (0..5).
e.anchor = 0;
e.focus = 5;
e.toggle_mark(Mark::Bold);
assert!(e.has_mark(&Mark::Bold));
assert_eq!(e.marks(), &[MarkRange::new(0..5, Mark::Bold)]);
// Caret at right edge of bold (index 5): inherits Bold on typing!
e.set(5, false);
assert!(e.has_mark(&Mark::Bold));
e.key(&k(Key::Text("!".into())), None);
assert_eq!(e.text, "hello! world");
assert_eq!(e.marks(), &[MarkRange::new(0..6, Mark::Bold)]);
// Caret at index 0 (start of bold run): does NOT inherit Bold.
e.set(0, false);
assert!(!e.has_mark(&Mark::Bold));
e.key(&k(Key::Text(">".into())), None);
assert_eq!(e.text, ">hello! world");
assert_eq!(e.marks(), &[MarkRange::new(1..7, Mark::Bold)]);
// Split Bold by toggling it off on "ll" (3..5).
e.anchor = 3;
e.focus = 5;
assert!(e.has_mark(&Mark::Bold));
e.toggle_mark(Mark::Bold);
assert!(!e.has_mark(&Mark::Bold));
assert_eq!(
e.marks(),
&[MarkRange::new(1..3, Mark::Bold), MarkRange::new(5..7, Mark::Bold)]
);
// Selecting across the gap (1..7) reports Bold is not active on the whole range,
// so toggling Bold applies it to the whole selection and merges the runs.
e.anchor = 1;
e.focus = 7;
assert!(!e.has_mark(&Mark::Bold));
e.toggle_mark(Mark::Bold);
assert!(e.has_mark(&Mark::Bold));
assert_eq!(e.marks(), &[MarkRange::new(1..7, Mark::Bold)]);
// Code and Link marks do NOT inherit at the start of their run (index 8).
e.anchor = 8;
e.focus = 13; // "world"
e.toggle_mark(Mark::Code);
e.set_link(Some("https://example.com"));
// Inside "world" (index 10): both Code and Link are active and inherited.
e.set(10, false);
assert!(e.has_mark(&Mark::Code));
assert_eq!(e.active_link(), Some("https://example.com"));
// At start of link/code run (index 8): neither Code nor Link is inherited.
e.set(8, false);
assert!(!e.has_mark(&Mark::Code));
assert_eq!(e.active_link(), None);
e.key(&k(Key::Text("?".into())), None);
assert_eq!(e.text, ">hello! ?world");
assert_eq!(
e.marks(),
&[
MarkRange::new(1..7, Mark::Bold),
MarkRange::new(9..14, Mark::Code),
MarkRange::new(9..14, Mark::Link("https://example.com".into())),
]
);
}
#[test]
fn pending_typing_style_and_command_shortcuts() {
let mut e = TextEdit::new("").rich();
// Empty selection: Cmd+B sets pending Bold, Cmd+I sets pending Italic.
e.key(&KeyEvent { key: Key::Command('b'), mods: Mods { cmd: true, ..Mods::default() } }, None);
e.key(&KeyEvent { key: Key::Command('i'), mods: Mods { cmd: true, ..Mods::default() } }, None);
assert!(e.has_mark(&Mark::Bold));
assert!(e.has_mark(&Mark::Italic));
e.key(&k(Key::Text("hi".into())), None);
assert_eq!(e.text, "hi");
assert_eq!(
e.marks(),
&[MarkRange::new(0..2, Mark::Bold), MarkRange::new(0..2, Mark::Italic)]
);
// Toggle Bold off on empty selection at index 2, then type " there".
e.key(&KeyEvent { key: Key::Command('b'), mods: Mods { cmd: true, ..Mods::default() } }, None);
assert!(!e.has_mark(&Mark::Bold));
assert!(e.has_mark(&Mark::Italic));
e.key(&k(Key::Text(" there".into())), None);
assert_eq!(e.text, "hi there");
assert_eq!(
e.marks(),
&[MarkRange::new(0..2, Mark::Bold), MarkRange::new(0..8, Mark::Italic)]
);
// Moving the caret clears pending typing style.
e.toggle_mark(Mark::Underline);
assert!(e.has_mark(&Mark::Underline));
e.key(&k(Key::Left), None);
assert!(!e.has_mark(&Mark::Underline));
}
#[test]
fn unicode_emoji_cjk_and_combining_marks_across_boundaries() {
let mut e = TextEdit::new("🦀a\u{0301}日本語");
// "🦀" is 0..4, "a\u{0301}" is 4..7, "日" is 7..10, "本" is 10..13, "語" is 13..16.
e.anchor = 0;
e.focus = 4;
e.toggle_mark(Mark::Bold);
e.anchor = 4;
e.focus = 7;
e.toggle_mark(Mark::Italic);
e.anchor = 7;
e.focus = 13;
e.toggle_mark(Mark::Strike);
e.anchor = 10;
e.focus = 16;
e.toggle_mark(Mark::Underline);
// Insert CJK right at boundary between combining mark and CJK (byte 7).
e.set(7, false);
e.key(&k(Key::Text("★".into())), None); // 3 bytes, inherits Italic from 4..7
assert_eq!(e.text, "🦀a\u{0301}★日本語");
assert_eq!(
e.marks(),
&[
MarkRange::new(0..4, Mark::Bold),
MarkRange::new(4..10, Mark::Italic),
MarkRange::new(10..16, Mark::Strike),
MarkRange::new(13..19, Mark::Underline),
]
);
// Delete across boundary ("★日", bytes 7..13).
e.anchor = 7;
e.focus = 13;
e.key(&k(Key::Backspace), None);
assert_eq!(e.text, "🦀a\u{0301}本語");
assert_eq!(
e.marks(),
&[
MarkRange::new(0..4, Mark::Bold),
MarkRange::new(4..7, Mark::Italic),
MarkRange::new(7..10, Mark::Strike),
MarkRange::new(7..13, Mark::Underline),
]
);
// Round-trip through HTML preserves exact Unicode mark boundaries.
let html = e.to_html();
let rt = TextEdit::from_html(&html);
assert_eq!(rt.text, e.text);
assert_eq!(rt.marks(), e.marks());
}
#[test]
fn block_attributes_lists_quotes_code_and_keys() {
let mut e = TextEdit::new("first").rich();
e.set_block(Block::Bullet(0));
assert_eq!(e.current_block(), Block::Bullet(0));
// Return at end of non-empty list item creates a new Bullet(0) item.
e.set(5, false);
assert!(!e.key(&k(Key::Enter), None).submit);
assert_eq!(e.text, "first\n");
assert_eq!(e.blocks(), &[Block::Bullet(0), Block::Bullet(0)]);
// Tab indents the second list item to Bullet(1).
e.key(&k(Key::Tab), None);
assert_eq!(e.blocks(), &[Block::Bullet(0), Block::Bullet(1)]);
e.key(&k(Key::Text("nested".into())), None);
// Shift+Return inserts a soft break inside the same list item.
let shift_enter = KeyEvent { key: Key::Enter, mods: Mods { shift: true, ..Mods::default() } };
e.key(&shift_enter, None);
e.key(&k(Key::Text("cont".into())), None);
assert_eq!(e.soft_breaks(), &[2]);
assert_eq!(e.blocks(), &[Block::Bullet(0), Block::Bullet(1), Block::Bullet(1)]);
// Return at end of "cont" creates a new empty Bullet(1) item on line 3.
e.key(&k(Key::Enter), None);
assert_eq!(e.blocks().len(), 4);
assert_eq!(e.current_block(), Block::Bullet(1));
// Return on the empty Bullet(1) item ends the list item (converts to Paragraph) without adding a newline.
let len_before = e.text.len();
e.key(&k(Key::Enter), None);
assert_eq!(e.text.len(), len_before);
assert_eq!(e.current_block(), Block::Paragraph);
// Backspace at start of a nested list item outdents first, then exits list.
e.set_block(Block::Numbered(1));
e.key(&k(Key::Backspace), None);
assert_eq!(e.current_block(), Block::Numbered(0));
e.key(&k(Key::Backspace), None);
assert_eq!(e.current_block(), Block::Paragraph);
// Inside a Code block: Return inserts a newline, Tab inserts '\t', and inline marks do not apply.
e.set_block(Block::Code);
e.toggle_mark(Mark::Bold);
assert!(!e.has_mark(&Mark::Bold));
e.key(&k(Key::Tab), None);
e.key(&k(Key::Text("let x = 1;".into())), None);
assert!(!e.key(&k(Key::Enter), None).submit);
e.key(&k(Key::Text("let y = 2;".into())), None);
assert!(e.text.ends_with("\tlet x = 1;\nlet y = 2;"));
assert_eq!(e.current_block(), Block::Code);
assert!(e.marks().is_empty());
}
#[test]
fn undo_redo_and_ime_preserve_marks_blocks_and_spans() {
let mut e = TextEdit::new("fn main() {}");
e.anchor = 0;
e.focus = 2;
e.toggle_mark(Mark::Bold);
e.set_block(Block::Quote);
// Undo block change, then undo mark change, then redo both.
undo(&mut e, false);
assert_eq!(e.current_block(), Block::Paragraph);
assert_eq!(e.marks(), &[MarkRange::new(0..2, Mark::Bold)]);
undo(&mut e, false);
assert!(e.marks().is_empty());
undo(&mut e, true);
assert_eq!(e.marks(), &[MarkRange::new(0..2, Mark::Bold)]);
undo(&mut e, true);
assert_eq!(e.current_block(), Block::Quote);
// IME preedit with pending typing style and caller-supplied span mapping.
e.set(3, false); // right before "main"
e.toggle_mark(Mark::Italic);
// Suppose caller supplies a syntax span covering "main" (3..7 in model).
assert_eq!(e.map_range_to_display(3, 7), vec![(3, 7)]);
e.ime(&Ime::Preedit("日".into(), Some((0, 3)), Vec::new()));
// During preedit ("fn 日main() {}"), "main" in display is shifted by 3 bytes to 6..10!
assert_eq!(e.display().0, "fn 日main() {}");
assert_eq!(e.map_range_to_display(3, 7), vec![(6, 10)]);
// And the preedit itself has the pending Italic mark in rich_display_specs.
let (spans, _, _, _) = e.rich_display_specs(rune_core::tok::TextStyle::new(14.0, 400.0), RichStyle::default());
assert!(spans.iter().any(|s| s.start == 3 && s.end == 6 && s.italic));
// Commit IME preedit: Italic mark is committed on "日" (3..6).
e.ime(&Ime::Commit("日".into()));
assert_eq!(e.text, "fn 日main() {}");
assert!(e.marks().contains(&MarkRange::new(3..6, Mark::Italic)));
// Undo restores "fn main() {}" and its original marks.
undo(&mut e, false);
assert_eq!(e.text, "fn main() {}");
assert_eq!(e.marks(), &[MarkRange::new(0..2, Mark::Bold)]);
assert_eq!(e.map_range_to_display(3, 7), vec![(3, 7)]);
}
#[test]
fn html_import_export_and_paste_safe_subset() {
let html = concat!(
"<p>Hello <b>bold</b>, <strong style=\"font-style: italic\">both</strong>, ",
"<u>under</u>, <del>struck</del>, <code>inline()</code>, and ",
"<a href=\"https://opencode.ai\">link</a>",
"<a href=\"javascript:alert(1)\">bad</a></p>",
"<ul><li>first<ul><li>nested<br>soft</li></ul></li></ul>",
"<ol><li>one</li><li>two</li></ol>",
"<blockquote>quoted</blockquote>",
"<pre><code>fn add(a: i32) -&gt; i32 {\n\ta + 1\n}</code></pre>",
"<script>evil()</script><style>body{display:none}</style>",
);
let e = TextEdit::from_html(html);
assert!(!e.text.contains("evil"));
assert!(!e.text.contains("display:none"));
assert!(e.marks().iter().any(|m| m.mark == Mark::Bold));
assert!(e.marks().iter().any(|m| m.mark == Mark::Italic));
assert!(e.marks().iter().any(|m| m.mark == Mark::Underline));
assert!(e.marks().iter().any(|m| m.mark == Mark::Strike));
assert!(e.marks().iter().any(|m| m.mark == Mark::Code));
assert!(e.marks().iter().any(|m| m.mark == Mark::Link("https://opencode.ai".into())));
assert!(!e.marks().iter().any(|m| matches!(&m.mark, Mark::Link(u) if u.starts_with("javascript:"))));
assert_eq!(
e.blocks(),
&[
Block::Paragraph,
Block::Bullet(0),
Block::Bullet(1),
Block::Bullet(1),
Block::Numbered(0),
Block::Numbered(0),
Block::Quote,
Block::Code,
Block::Code,
Block::Code,
]
);
assert_eq!(e.soft_breaks(), &[3]);
// Round-trip via to_html() -> from_html().
let exported = e.to_html();
let round = TextEdit::from_html(&exported);
assert_eq!(round.text, e.text);
assert_eq!(round.marks(), e.marks());
assert_eq!(round.blocks(), e.blocks());
assert_eq!(round.soft_breaks(), e.soft_breaks());
// paste_html into an existing editor splices text, marks, and blocks cleanly.
let mut dest = TextEdit::new("prefix suffix").rich();
dest.set(7, false);
dest.paste_html("<b>rich</b> <i>paste</i>", "rich paste");
assert_eq!(dest.text, "prefix rich paste suffix");
assert_eq!(
dest.marks(),
&[
MarkRange::new(7..11, Mark::Bold),
MarkRange::new(12..17, Mark::Italic),
]
);
}
fn cmd(c: char) -> KeyEvent {
KeyEvent { key: Key::Command(c), mods: Mods { cmd: true, ..Mods::default() } }
}
/// The text under each range of `mark`.
fn marked<'a>(e: &'a TextEdit, mark: &Mark) -> Vec<&'a str> {
e.marks().iter().filter(|m| m.mark == *mark).map(|m| &e.text[m.start..m.end]).collect()
}
/// What every edit path must leave behind.
fn assert_invariants(e: &TextEdit, ctx: &str) {
let t = &e.text;
let lines = 1 + t.bytes().filter(|&b| b == b'\n').count();
assert_eq!(e.blocks().len(), lines, "{ctx}: one block per line");
assert!(e.blocks().iter().all(|b| b.list_level().is_none_or(|l| l <= MAX_LIST_LEVEL)), "{ctx}: list levels");
assert!(e.soft_breaks().windows(2).all(|w| w[0] < w[1]), "{ctx}: soft breaks sorted");
assert!(e.soft_breaks().iter().all(|&i| i > 0 && (i as usize) < lines), "{ctx}: soft breaks in range");
assert!(t.is_char_boundary(e.anchor) && t.is_char_boundary(e.focus), "{ctx}: caret on a char boundary");
let ms = e.marks();
assert!(ms.windows(2).all(|w| w[0].start <= w[1].start), "{ctx}: marks sorted");
for m in ms {
assert!(m.start < m.end && m.end <= t.len(), "{ctx}: mark {m:?} in range");
assert!(t.is_char_boundary(m.start) && t.is_char_boundary(m.end), "{ctx}: mark {m:?} on char boundaries");
for line in e.line_of_byte(m.start)..=e.line_of_byte(m.end - 1) {
assert_ne!(e.blocks()[line], Block::Code, "{ctx}: mark {m:?} reaches code line {line}");
}
}
for (i, a) in ms.iter().enumerate() {
for b in &ms[i + 1..] {
if a.mark.same_kind(&b.mark) {
assert!(b.start >= a.end, "{ctx}: same-kind marks {a:?} {b:?} overlap");
assert!(!(b.start == a.end && a.mark == b.mark), "{ctx}: equal marks {a:?} {b:?} not merged");
}
}
}
}
include!("rich_tests.rs");
+38
View File
@@ -0,0 +1,38 @@
//! The style the next text typed at the caret takes.
use super::Mark;
/// What text typed at an empty selection is marked with.
#[derive(Clone, Debug, Default, PartialEq, Hash)]
pub(super) enum Typing {
/// The marks around the caret (`TextEdit::inherited_marks_at`).
#[default]
Inherited,
/// A mark was toggled with nothing selected: text typed with the selection still at `at`
/// (`(anchor, focus)`) carries exactly `marks`. Anywhere else they're stale, since an app
/// can move the caret through the public fields without disarming them.
Armed { at: (usize, usize), marks: Vec<Mark> },
}
impl Typing {
/// The armed marks, while the selection is still where they were armed.
pub(super) fn at(&self, selection: (usize, usize)) -> Option<&[Mark]> {
match self {
Typing::Armed { at, marks } if *at == selection => Some(marks),
_ => None,
}
}
/// Disarms, returning the marks if they were armed at `selection`: typed text uses them
/// up.
pub(super) fn take_at(&mut self, selection: (usize, usize)) -> Option<Vec<Mark>> {
match std::mem::take(self) {
Typing::Armed { at, marks } if at == selection => Some(marks),
_ => None,
}
}
}
#[cfg(test)]
#[path = "typing_tests.rs"]
mod tests;
+33
View File
@@ -0,0 +1,33 @@
use super::*;
use crate::{MarkRange, TextEdit};
#[test]
fn armed_marks_count_only_at_the_selection_they_were_armed_at() {
let mut t = Typing::Armed { at: (3, 3), marks: vec![Mark::Bold] };
assert_eq!(t.at((3, 3)), Some(&[Mark::Bold][..]));
assert_eq!(t.at((4, 4)), None);
assert_eq!(Typing::Inherited.at((3, 3)), None);
assert_eq!(t.take_at((4, 4)), None);
assert_eq!(t, Typing::Inherited, "a stale style is dropped when text is typed elsewhere");
let mut t = Typing::Armed { at: (3, 3), marks: vec![Mark::Bold] };
assert_eq!(t.take_at((3, 3)), Some(vec![Mark::Bold]));
assert_eq!(t, Typing::Inherited, "typed text uses the style up");
}
#[test]
fn a_caret_moved_through_the_public_fields_and_back_still_types_the_armed_style() {
let mut e = TextEdit::new("ab").rich();
e.toggle_mark(Mark::Bold);
e.anchor = 0;
e.focus = 0;
assert!(!e.has_mark(&Mark::Bold), "armed at the end, so not at the start");
e.anchor = 2;
e.focus = 2;
e.insert("c");
assert_eq!(e.marks(), [MarkRange { start: 2, end: 3, mark: Mark::Bold }]);
e.set_caret(3);
e.toggle_mark(Mark::Italic);
e.set_caret(3);
e.insert("d");
assert_eq!(e.marks(), [MarkRange { start: 2, end: 4, mark: Mark::Bold }], "placing the caret, even where it was, disarms");
}