#[cfg(test)]
mod tests;
use crcbl_core::input::{KeyCode, Modifiers};
use unicode_segmentation::UnicodeSegmentation;
use crate::font::cluster;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Motion {
Left,
Right,
WordLeft,
WordRight,
Home,
End,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Edit {
Insert(String),
Move {
motion: Motion,
select: bool,
},
Backspace,
Delete,
BackspaceWord,
DeleteWord,
SelectAll,
Copy,
Cut,
Paste,
}
impl Edit {
pub const SHORTCUT: Modifiers = Modifiers::CTRL.union(Modifiers::SUPER);
pub const WORD: Modifiers = Modifiers::CTRL.union(Modifiers::ALT);
#[must_use]
pub fn for_key(key: KeyCode, modifiers: Modifiers) -> Option<Self> {
let select = modifiers.contains(Modifiers::SHIFT);
let arrow = |by_char, by_word, to_end| {
let motion = if modifiers.contains(Modifiers::SUPER) {
to_end
} else if modifiers.intersects(Self::WORD) {
by_word
} else {
by_char
};
Some(Self::Move { motion, select })
};
let shortcut = modifiers.intersects(Self::SHORTCUT) && !modifiers.contains(Modifiers::ALT);
let word = modifiers.intersects(Self::WORD);
match key {
KeyCode::ArrowLeft => arrow(Motion::Left, Motion::WordLeft, Motion::Home),
KeyCode::ArrowRight => arrow(Motion::Right, Motion::WordRight, Motion::End),
KeyCode::Home => Some(Self::Move {
motion: Motion::Home,
select,
}),
KeyCode::End => Some(Self::Move {
motion: Motion::End,
select,
}),
KeyCode::Backspace if word => Some(Self::BackspaceWord),
KeyCode::Delete if word => Some(Self::DeleteWord),
KeyCode::Backspace => Some(Self::Backspace),
KeyCode::Delete => Some(Self::Delete),
KeyCode::KeyA if shortcut => Some(Self::SelectAll),
KeyCode::KeyC if shortcut => Some(Self::Copy),
KeyCode::KeyX if shortcut => Some(Self::Cut),
KeyCode::KeyV if shortcut => Some(Self::Paste),
_ => None,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ClipboardOp {
Offer(String),
Read,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Applied {
pub text: bool,
pub caret: bool,
pub clipboard: Option<ClipboardOp>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct LineEdit {
text: String,
caret: usize,
anchor: usize,
}
impl LineEdit {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn text(&self) -> &str {
&self.text
}
#[must_use]
pub const fn caret(&self) -> usize {
self.caret
}
#[must_use]
pub const fn anchor(&self) -> usize {
self.anchor
}
#[must_use]
pub fn selection(&self) -> core::ops::Range<usize> {
self.caret.min(self.anchor)..self.caret.max(self.anchor)
}
#[must_use]
pub fn selected_text(&self) -> &str {
let range = self.selection();
&self.text[byte_of(&self.text, range.start)..byte_of(&self.text, range.end)]
}
#[must_use]
pub fn len(&self) -> usize {
self.text.chars().count()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.text.is_empty()
}
pub fn set_text(&mut self, text: &str) {
self.clear();
self.insert(text);
}
pub fn sync(&mut self, text: &str) -> bool {
if self.text == text {
return false;
}
text.clone_into(&mut self.text);
let stops = self.stops();
self.caret = snap_back(&stops, self.caret);
self.anchor = snap_back(&stops, self.anchor);
true
}
pub fn clear(&mut self) {
self.text.clear();
self.caret = 0;
self.anchor = 0;
}
pub fn place(&mut self, at: usize, select: bool) -> bool {
let at = snap_back(&self.stops(), at);
let before = (self.caret, self.anchor);
self.caret = at;
if !select {
self.anchor = at;
}
before != (self.caret, self.anchor)
}
pub fn select(&mut self, range: core::ops::Range<usize>) -> bool {
let stops = self.stops();
let before = (self.caret, self.anchor);
self.anchor = snap_back(&stops, range.start);
self.caret = snap_on(&stops, range.end);
before != (self.caret, self.anchor)
}
pub fn insert(&mut self, text: &str) -> bool {
let mut kept = text.chars().filter(|c| !c.is_control()).peekable();
if kept.peek().is_none() {
return false;
}
self.delete_selection();
let mut at = byte_of(&self.text, self.caret);
for c in kept {
self.text.insert(at, c);
at += c.len_utf8();
self.caret += 1;
}
self.caret = snap_on(&self.stops(), self.caret);
self.anchor = self.caret;
true
}
pub fn backspace(&mut self) -> bool {
if self.delete_selection() {
return true;
}
if self.caret == 0 {
return false;
}
let start = previous_stop(&self.stops(), self.caret);
self.remove(start..self.caret);
self.caret = start;
self.anchor = start;
true
}
pub fn delete(&mut self) -> bool {
if self.delete_selection() {
return true;
}
if self.caret == self.len() {
return false;
}
let end = next_stop(&self.stops(), self.caret);
self.remove(self.caret..end);
true
}
fn delete_to(&mut self, motion: Motion) -> bool {
if self.delete_selection() {
return true;
}
self.move_caret(motion, true);
self.delete_selection()
}
pub fn move_caret(&mut self, motion: Motion, select: bool) -> bool {
let before = (self.caret, self.anchor);
let range = self.selection();
let collapsing = !select && !range.is_empty();
let from = match motion {
Motion::Left | Motion::WordLeft if collapsing => range.start,
Motion::Right | Motion::WordRight if collapsing => range.end,
_ => self.caret,
};
let chars: Vec<char> = self.text.chars().collect();
let stops = self.stops();
let to = match motion {
Motion::Left if collapsing => from,
Motion::Right if collapsing => from,
Motion::Left => previous_stop(&stops, from),
Motion::Right => next_stop(&stops, from),
Motion::WordLeft => snap_back(&stops, word_left(&chars, from)),
Motion::WordRight => snap_on(&stops, word_right(&chars, from)),
Motion::Home => 0,
Motion::End => chars.len(),
};
self.caret = to;
if !select {
self.anchor = to;
}
before != (self.caret, self.anchor)
}
pub fn apply(&mut self, edit: &Edit) -> Applied {
let before = (self.caret, self.anchor);
let mut applied = Applied::default();
match edit {
Edit::Insert(text) => applied.text = self.insert(text),
Edit::Move { motion, select } => {
self.move_caret(*motion, *select);
}
Edit::Backspace => applied.text = self.backspace(),
Edit::Delete => applied.text = self.delete(),
Edit::BackspaceWord => applied.text = self.delete_to(Motion::WordLeft),
Edit::DeleteWord => applied.text = self.delete_to(Motion::WordRight),
Edit::SelectAll => {
self.select(0..self.len());
}
Edit::Copy | Edit::Cut => {
if !self.selection().is_empty() {
applied.clipboard = Some(ClipboardOp::Offer(self.selected_text().to_owned()));
if *edit == Edit::Cut {
applied.text = self.delete_selection();
}
}
}
Edit::Paste => applied.clipboard = Some(ClipboardOp::Read),
}
applied.caret = before != (self.caret, self.anchor);
applied
}
fn delete_selection(&mut self) -> bool {
let range = self.selection();
if range.is_empty() {
return false;
}
self.remove(range.clone());
self.caret = range.start;
self.anchor = range.start;
true
}
fn remove(&mut self, range: core::ops::Range<usize>) {
let start = byte_of(&self.text, range.start);
let end = byte_of(&self.text, range.end);
self.text.replace_range(start..end, "");
}
fn stops(&self) -> Vec<usize> {
cluster::caret_stops(&self.text)
}
}
fn snap_back(stops: &[usize], at: usize) -> usize {
stops[stops.partition_point(|&stop| stop <= at) - 1]
}
fn snap_on(stops: &[usize], at: usize) -> usize {
let end = stops.len() - 1;
stops[stops.partition_point(|&stop| stop < at).min(end)]
}
fn previous_stop(stops: &[usize], at: usize) -> usize {
stops[stops.partition_point(|&stop| stop < at).saturating_sub(1)]
}
fn next_stop(stops: &[usize], at: usize) -> usize {
let end = stops.len() - 1;
stops[stops.partition_point(|&stop| stop <= at).min(end)]
}
#[must_use]
pub fn byte_of(text: &str, count: usize) -> usize {
text.char_indices()
.nth(count)
.map_or(text.len(), |(at, _)| at)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Class {
Space,
Word,
Other,
}
fn classes(chars: &[char]) -> Vec<Class> {
let text: String = chars.iter().collect();
let mut classes = Vec::with_capacity(chars.len());
for word in text.split_word_bounds() {
let class = if word.chars().any(|c| c.is_alphanumeric() || c == '_') {
Class::Word
} else if word.chars().all(char::is_whitespace) {
Class::Space
} else {
Class::Other
};
classes.extend(core::iter::repeat_n(class, word.chars().count()));
}
classes
}
#[must_use]
pub fn word_left(chars: &[char], from: usize) -> usize {
let classes = classes(chars);
let mut at = from.min(chars.len());
while at > 0 && classes[at - 1] == Class::Space {
at -= 1;
}
if let Some(&run) = at.checked_sub(1).and_then(|before| classes.get(before)) {
while at > 0 && classes[at - 1] == run {
at -= 1;
}
}
at
}
#[must_use]
pub fn word_right(chars: &[char], from: usize) -> usize {
let classes = classes(chars);
let mut at = from.min(chars.len());
while at < chars.len() && classes[at] == Class::Space {
at += 1;
}
if let Some(&run) = classes.get(at) {
while at < chars.len() && classes[at] == run {
at += 1;
}
}
at
}
#[must_use]
pub fn run_at(chars: &[char], index: usize) -> core::ops::Range<usize> {
let Some(last) = chars.len().checked_sub(1) else {
return 0..0;
};
let classes = classes(chars);
let index = index.min(last);
let run = classes[index];
let mut start = index;
while start > 0 && classes[start - 1] == run {
start -= 1;
}
let mut end = index + 1;
while end < chars.len() && classes[end] == run {
end += 1;
}
start..end
}