mod history;
use std::cell::Cell;
use std::fmt;
use std::rc::Rc;
use iced::advanced::layout::{self, Layout};
use iced::advanced::widget::{Operation, Tree, Widget, tree};
use iced::advanced::{Clipboard, Shell, input_method, overlay, renderer};
use iced::keyboard::{self, Key, Modifiers, key::Named};
use iced::widget::text_input::{self, Value};
use iced::{Element, Event, Length, Rectangle, Renderer, Size, Theme, Vector, mouse};
use crate::keys::{self, Chord, Keymap};
pub(crate) use history::{Edit, History, Restore};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Shortcut {
Undo,
Redo,
DeleteWordBackward,
DeleteWordForward,
EscapeUnfocus,
}
impl Shortcut {
const fn bit(self) -> u8 {
1 << self as u8
}
}
impl keys::Action for Shortcut {
const ALL: &'static [Self] = &[
Shortcut::Undo,
Shortcut::Redo,
Shortcut::DeleteWordBackward,
Shortcut::DeleteWordForward,
Shortcut::EscapeUnfocus,
];
fn defaults() -> Keymap<Self> {
default_keymap()
}
fn name(self) -> &'static str {
match self {
Shortcut::Undo => "Undo",
Shortcut::Redo => "Redo",
Shortcut::DeleteWordBackward => "Delete word backward",
Shortcut::DeleteWordForward => "Delete word forward",
Shortcut::EscapeUnfocus => "Unfocus",
}
}
fn description(self) -> &'static str {
match self {
Shortcut::Undo => "Undoes the last word typed, deletion, paste or cut.",
Shortcut::Redo => "Redoes what undo took back.",
Shortcut::DeleteWordBackward => {
"Deletes back to the start of the word, or the selection if there is one."
}
Shortcut::DeleteWordForward => {
"Deletes forward to the end of the word, or the selection if there is one."
}
Shortcut::EscapeUnfocus => {
"Removes focus from the field without closing a dialog around it."
}
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct Shortcuts(u8);
impl Shortcuts {
pub fn all() -> Self {
<Shortcut as keys::Action>::ALL
.iter()
.fold(Self::none(), |set, shortcut| set.with(*shortcut))
}
pub const fn none() -> Self {
Self(0)
}
pub const fn with(self, shortcut: Shortcut) -> Self {
Self(self.0 | shortcut.bit())
}
pub const fn without(self, shortcut: Shortcut) -> Self {
Self(self.0 & !shortcut.bit())
}
pub const fn contains(self, shortcut: Shortcut) -> bool {
self.0 & shortcut.bit() != 0
}
pub const fn is_empty(self) -> bool {
self.0 == 0
}
pub fn iter(self) -> impl Iterator<Item = Shortcut> {
<Shortcut as keys::Action>::ALL
.iter()
.copied()
.filter(move |shortcut| self.contains(*shortcut))
}
fn has_history(self) -> bool {
self.contains(Shortcut::Undo) || self.contains(Shortcut::Redo)
}
}
impl Default for Shortcuts {
fn default() -> Self {
Self::all()
}
}
impl fmt::Debug for Shortcuts {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_set().entries(self.iter()).finish()
}
}
impl FromIterator<Shortcut> for Shortcuts {
fn from_iter<I: IntoIterator<Item = Shortcut>>(shortcuts: I) -> Self {
shortcuts
.into_iter()
.fold(Self::none(), |set, shortcut| set.with(shortcut))
}
}
pub fn default_keymap() -> Keymap<Shortcut> {
Keymap::new()
.bind(Chord::character('z').command(), Shortcut::Undo)
.bind(Chord::character('z').command().shift(), Shortcut::Redo)
.bind(Chord::character('y').command(), Shortcut::Redo)
.bind(word(Named::Backspace), Shortcut::DeleteWordBackward)
.bind(word(Named::Delete), Shortcut::DeleteWordForward)
.bind(Chord::named(Named::Escape), Shortcut::EscapeUnfocus)
}
fn word(key: Named) -> Chord {
let chord = Chord::named(key);
if cfg!(target_os = "macos") {
chord.alt()
} else {
chord.ctrl()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Direction {
Backward,
Forward,
}
pub(crate) trait Field<Message> {
fn text(&self) -> String;
fn is_focused(&self, tree: &Tree) -> bool;
fn has_selection(&self, tree: &Tree) -> bool;
fn restore(&self, tree: &mut Tree, restore: Restore, shell: &mut Shell<'_, Message>);
fn delete_word(
&self,
tree: &mut Tree,
direction: Direction,
shell: &mut Shell<'_, Message>,
) -> bool;
fn unfocus(&self, tree: &mut Tree);
}
pub(crate) struct Editing<'a, Message, F> {
content: Element<'a, Message>,
field: F,
keymap: Keymap<Shortcut>,
shortcuts: Shortcuts,
edited: Rc<Cell<bool>>,
}
impl<'a, Message, F> Editing<'a, Message, F> {
pub fn new(
content: impl Into<Element<'a, Message>>,
field: F,
keymap: Keymap<Shortcut>,
shortcuts: Shortcuts,
edited: Rc<Cell<bool>>,
) -> Self {
Self {
content: content.into(),
field,
keymap,
shortcuts,
edited,
}
}
}
pub(crate) fn resolve(
keymap: &Keymap<Shortcut>,
key: &Key,
physical_key: keyboard::key::Physical,
modifiers: Modifiers,
) -> Option<Shortcut> {
keymap.resolve(key, modifiers).or_else(|| {
let latin = key.to_latin(physical_key)?;
keymap.resolve(&Key::Character(latin.to_string().into()), modifiers)
})
}
pub(crate) fn without_shortcut_text(event: &Event) -> Option<Event> {
let Event::Keyboard(keyboard::Event::KeyPressed {
key,
modified_key,
physical_key,
location,
modifiers,
repeat,
text: Some(text),
}) = event
else {
return None;
};
if !modifiers.command() || modifiers.alt() || text.chars().any(char::is_control) {
return None;
}
Some(Event::Keyboard(keyboard::Event::KeyPressed {
key: key.clone(),
modified_key: modified_key.clone(),
physical_key: *physical_key,
location: *location,
modifiers: *modifiers,
repeat: *repeat,
text: None,
}))
}
fn moves_caret(event: &Event) -> bool {
!matches!(event, Event::Keyboard(keyboard::Event::KeyReleased { .. }))
}
pub(crate) fn classify(event: &Event) -> Edit {
match event {
Event::Keyboard(keyboard::Event::KeyPressed {
key,
modifiers,
text,
..
}) => match key.as_ref() {
Key::Named(Named::Enter) => Edit::Insert("\n".into()),
Key::Named(Named::Backspace | Named::Delete)
if !modifiers.control() && !modifiers.alt() && !modifiers.logo() =>
{
Edit::Delete
}
_ => match text {
Some(text) if !text.chars().any(char::is_control) => Edit::Insert(text.to_string()),
_ => Edit::Other,
},
},
Event::InputMethod(input_method::Event::Commit(text)) => Edit::Insert(text.clone()),
_ => Edit::Other,
}
}
impl<Message, F: Field<Message>> Widget<Message, Theme, Renderer> for Editing<'_, Message, F> {
fn tag(&self) -> tree::Tag {
tree::Tag::of::<History>()
}
fn state(&self) -> tree::State {
tree::State::new(History::default())
}
fn children(&self) -> Vec<Tree> {
vec![Tree::new(&self.content)]
}
fn diff(&self, tree: &mut Tree) {
tree.diff_children(std::slice::from_ref(&self.content));
let history = tree.state.downcast_mut::<History>();
if self.shortcuts.has_history() {
history.settle(|| self.field.text());
} else {
*history = History::default();
}
}
fn size(&self) -> Size<Length> {
self.content.as_widget().size()
}
fn size_hint(&self) -> Size<Length> {
self.content.as_widget().size_hint()
}
fn layout(
&mut self,
tree: &mut Tree,
renderer: &Renderer,
limits: &layout::Limits,
) -> layout::Node {
self.content
.as_widget_mut()
.layout(&mut tree.children[0], renderer, limits)
}
fn draw(
&self,
tree: &Tree,
renderer: &mut Renderer,
theme: &Theme,
style: &renderer::Style,
layout: Layout<'_>,
cursor: mouse::Cursor,
viewport: &Rectangle,
) {
self.content.as_widget().draw(
&tree.children[0],
renderer,
theme,
style,
layout,
cursor,
viewport,
);
}
fn operate(
&mut self,
tree: &mut Tree,
layout: Layout<'_>,
renderer: &Renderer,
operation: &mut dyn Operation,
) {
self.content
.as_widget_mut()
.operate(&mut tree.children[0], layout, renderer, operation);
}
fn update(
&mut self,
tree: &mut Tree,
event: &Event,
layout: Layout<'_>,
cursor: mouse::Cursor,
renderer: &Renderer,
clipboard: &mut dyn Clipboard,
shell: &mut Shell<'_, Message>,
viewport: &Rectangle,
) {
let focused = self.field.is_focused(&tree.children[0]);
if focused
&& !shell.is_event_captured()
&& let Event::Keyboard(keyboard::Event::KeyPressed {
key,
physical_key,
modifiers,
..
}) = event
&& let Some(shortcut) = resolve(&self.keymap, key, *physical_key, *modifiers)
{
if self.shortcuts.contains(shortcut) {
self.perform(tree, shortcut, shell);
shell.capture_event();
}
return;
}
let stripped = focused.then(|| without_shortcut_text(event)).flatten();
let event = stripped.as_ref().unwrap_or(event);
let replacing = focused && self.field.has_selection(&tree.children[0]);
let captured = shell.is_event_captured();
self.edited.set(false);
self.content.as_widget_mut().update(
&mut tree.children[0],
event,
layout,
cursor,
renderer,
clipboard,
shell,
viewport,
);
if !self.shortcuts.has_history() {
return;
}
let history = tree.state.downcast_mut::<History>();
if self.edited.replace(false) {
history.record(classify(event), replacing, || self.field.text());
} else if !captured && shell.is_event_captured() && moves_caret(event) {
history.interrupt();
}
}
fn mouse_interaction(
&self,
tree: &Tree,
layout: Layout<'_>,
cursor: mouse::Cursor,
viewport: &Rectangle,
renderer: &Renderer,
) -> mouse::Interaction {
self.content.as_widget().mouse_interaction(
&tree.children[0],
layout,
cursor,
viewport,
renderer,
)
}
fn overlay<'b>(
&'b mut self,
tree: &'b mut Tree,
layout: Layout<'b>,
renderer: &Renderer,
viewport: &Rectangle,
translation: Vector,
) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
self.content.as_widget_mut().overlay(
&mut tree.children[0],
layout,
renderer,
viewport,
translation,
)
}
}
impl<Message, F: Field<Message>> Editing<'_, Message, F> {
fn perform(&self, tree: &mut Tree, shortcut: Shortcut, shell: &mut Shell<'_, Message>) {
let (state, children) = (&mut tree.state, &mut tree.children);
let history = state.downcast_mut::<History>();
let Some(child) = children.first_mut() else {
return;
};
let direction = match shortcut {
Shortcut::Undo | Shortcut::Redo => {
let text = self.field.text();
let restore = if shortcut == Shortcut::Undo {
history.undo(text)
} else {
history.redo(text)
};
if let Some(restore) = restore {
self.field.restore(child, restore, shell);
}
return;
}
Shortcut::EscapeUnfocus => {
self.field.unfocus(child);
history.interrupt();
shell.request_redraw();
return;
}
Shortcut::DeleteWordBackward => Direction::Backward,
Shortcut::DeleteWordForward => Direction::Forward,
};
if self.field.delete_word(child, direction, shell) && self.shortcuts.has_history() {
history.record(Edit::Other, true, || self.field.text());
}
}
}
impl<'a, Message: 'a, F: Field<Message> + 'a> From<Editing<'a, Message, F>>
for Element<'a, Message>
{
fn from(editing: Editing<'a, Message, F>) -> Self {
Element::new(editing)
}
}
type InputState = text_input::State<<Renderer as iced::advanced::text::Renderer>::Paragraph>;
pub(crate) struct Input<'a, Message> {
value: String,
secure: bool,
on_input: Rc<dyn Fn(String) -> Message + 'a>,
}
impl<'a, Message> Input<'a, Message> {
pub fn new(value: &str, secure: bool, on_input: Rc<dyn Fn(String) -> Message + 'a>) -> Self {
Self {
value: value.to_owned(),
secure,
on_input,
}
}
}
fn input_state(tree: &Tree) -> Option<&InputState> {
match &tree.state {
tree::State::Some(state) => state.downcast_ref::<InputState>(),
tree::State::None => None,
}
}
fn input_state_mut(tree: &mut Tree) -> Option<&mut InputState> {
match &mut tree.state {
tree::State::Some(state) => state.downcast_mut::<InputState>(),
tree::State::None => None,
}
}
impl<Message> Field<Message> for Input<'_, Message> {
fn text(&self) -> String {
self.value.clone()
}
fn is_focused(&self, tree: &Tree) -> bool {
input_state(tree).is_some_and(InputState::is_focused)
}
fn has_selection(&self, tree: &Tree) -> bool {
input_state(tree)
.is_some_and(|state| state.cursor().selection(&Value::new(&self.value)).is_some())
}
fn restore(&self, tree: &mut Tree, restore: Restore, shell: &mut Shell<'_, Message>) {
let caret = restore
.text
.get(..restore.caret)
.map_or(0, |head| Value::new(head).len());
shell.publish((self.on_input)(restore.text));
if let Some(state) = input_state_mut(tree) {
state.move_cursor_to(caret);
}
}
fn delete_word(
&self,
tree: &mut Tree,
direction: Direction,
shell: &mut Shell<'_, Message>,
) -> bool {
let Some(state) = input_state_mut(tree) else {
return false;
};
let value = Value::new(&self.value);
let (start, end) = state
.cursor()
.selection(&value)
.unwrap_or_else(|| word_range(&value, caret(state, &value), direction, self.secure));
if start == end {
return false;
}
let kept = format!(
"{}{}",
value.select(0, start),
value.select(end, value.len())
);
shell.publish((self.on_input)(kept));
state.move_cursor_to(start);
true
}
fn unfocus(&self, tree: &mut Tree) {
if let Some(state) = input_state_mut(tree) {
state.unfocus();
}
}
}
fn caret(state: &InputState, value: &Value) -> usize {
match state.cursor().state(value) {
text_input::cursor::State::Index(index) => index,
text_input::cursor::State::Selection { end, .. } => end,
}
}
fn word_range(value: &Value, caret: usize, direction: Direction, secure: bool) -> (usize, usize) {
match (direction, secure) {
(Direction::Backward, true) => (0, caret),
(Direction::Backward, false) => (value.previous_start_of_word(caret), caret),
(Direction::Forward, true) => (caret, value.len()),
(Direction::Forward, false) => (caret, value.next_end_of_word(caret)),
}
}
#[cfg(test)]
mod tests {
use super::*;
use iced::keyboard::key::{NativeCode, Physical};
fn press(chord: &str) -> Option<Shortcut> {
let chord: Chord = chord.parse().ok()?;
default_keymap().resolve(chord.key(), chord.modifiers())
}
fn key_press(key: Key, modifiers: Modifiers, text: Option<&str>) -> Event {
Event::Keyboard(keyboard::Event::KeyPressed {
key: key.clone(),
modified_key: key,
physical_key: Physical::Unidentified(NativeCode::Unidentified),
location: keyboard::Location::Standard,
modifiers,
repeat: false,
text: text.map(Into::into),
})
}
#[test]
fn default_keymap_binds_undo_redo_and_word_deletion() {
assert_eq!(press("Mod+Z"), Some(Shortcut::Undo));
assert_eq!(press("Mod+Shift+Z"), Some(Shortcut::Redo));
assert_eq!(press("Mod+Y"), Some(Shortcut::Redo));
let word = if cfg!(target_os = "macos") {
"Alt"
} else {
"Ctrl"
};
assert_eq!(
press(&format!("{word}+Backspace")),
Some(Shortcut::DeleteWordBackward)
);
assert_eq!(
press(&format!("{word}+Delete")),
Some(Shortcut::DeleteWordForward)
);
assert_eq!(press("Escape"), Some(Shortcut::EscapeUnfocus));
assert_eq!(press("Z"), None);
assert_eq!(press("Backspace"), None);
}
#[test]
fn every_shortcut_has_a_default_chord() {
let keymap = default_keymap();
for shortcut in <Shortcut as keys::Action>::ALL {
assert!(!keymap.chords(shortcut).is_empty(), "{shortcut:?}");
}
}
#[test]
fn shortcut_sets() {
let all = Shortcuts::all();
assert_eq!(Shortcuts::default(), all);
assert_eq!(all.iter().count(), <Shortcut as keys::Action>::ALL.len());
assert!(Shortcuts::none().is_empty());
assert_eq!(Shortcuts::none().iter().count(), 0);
let no_undo = all.without(Shortcut::Undo);
assert!(!no_undo.contains(Shortcut::Undo));
assert!(no_undo.contains(Shortcut::Redo));
assert_eq!(no_undo.with(Shortcut::Undo), all);
assert_eq!(all.without(Shortcut::Undo).without(Shortcut::Undo), no_undo);
let picked: Shortcuts = [Shortcut::EscapeUnfocus].into_iter().collect();
assert_eq!(picked, Shortcuts::none().with(Shortcut::EscapeUnfocus));
assert!(!picked.has_history());
assert!(Shortcuts::none().with(Shortcut::Redo).has_history());
assert_eq!(format!("{picked:?}"), "{EscapeUnfocus}");
}
#[test]
fn keymap_overrides_and_unbinding() {
let keymap = default_keymap()
.unbind_action(&Shortcut::Redo)
.bind(Chord::named(Named::F4), Shortcut::Redo);
let physical = Physical::Unidentified(NativeCode::Unidentified);
let y = Key::Character("y".into());
assert_eq!(resolve(&keymap, &y, physical, Modifiers::COMMAND), None);
assert_eq!(
resolve(
&keymap,
&Key::Named(Named::F4),
physical,
Modifiers::empty()
),
Some(Shortcut::Redo)
);
assert_eq!(
resolve(&Keymap::new(), &y, physical, Modifiers::COMMAND),
None
);
}
#[test]
fn shift_with_a_capital_letter_still_matches() {
let physical = Physical::Unidentified(NativeCode::Unidentified);
let z = Key::Character("Z".into());
assert_eq!(
resolve(
&default_keymap(),
&z,
physical,
Modifiers::COMMAND | Modifiers::SHIFT
),
Some(Shortcut::Redo)
);
}
#[test]
fn letters_match_by_their_latin_key_on_other_layouts() {
let physical = Physical::Code(keyboard::key::Code::KeyZ);
let cyrillic = Key::Character("я".into());
assert_eq!(
resolve(&default_keymap(), &cyrillic, physical, Modifiers::COMMAND),
Some(Shortcut::Undo)
);
}
#[test]
fn classify_groups_typing_and_deletion() {
let a = Key::Character("a".into());
assert_eq!(
classify(&key_press(a.clone(), Modifiers::empty(), Some("a"))),
Edit::Insert("a".into())
);
assert_eq!(
classify(&key_press(a, Modifiers::CTRL, Some("\u{1}"))),
Edit::Other
);
assert_eq!(
classify(&key_press(
Key::Named(Named::Enter),
Modifiers::empty(),
Some("\r")
)),
Edit::Insert("\n".into())
);
assert_eq!(
classify(&key_press(
Key::Named(Named::Backspace),
Modifiers::empty(),
None
)),
Edit::Delete
);
assert_eq!(
classify(&key_press(
Key::Named(Named::Backspace),
Modifiers::CTRL,
None
)),
Edit::Other
);
assert_eq!(
classify(&Event::InputMethod(input_method::Event::Commit(
"word".into()
))),
Edit::Insert("word".into())
);
}
#[test]
fn shortcut_text_is_dropped_but_altgr_and_plain_typing_keep_it() {
let one = Key::Character("1".into());
let Some(Event::Keyboard(keyboard::Event::KeyPressed { text, .. })) =
without_shortcut_text(&key_press(one.clone(), Modifiers::COMMAND, Some("1")))
else {
panic!("Ctrl+1 loses its text");
};
assert_eq!(text, None);
assert_eq!(
without_shortcut_text(&key_press(
Key::Character("@".into()),
Modifiers::CTRL | Modifiers::ALT,
Some("@")
)),
None
);
assert_eq!(
without_shortcut_text(&key_press(one, Modifiers::empty(), Some("1"))),
None
);
}
#[test]
fn word_ranges_follow_the_caret() {
let value = Value::new("one two");
assert_eq!(word_range(&value, 7, Direction::Backward, false), (4, 7));
assert_eq!(word_range(&value, 0, Direction::Forward, false), (0, 3));
assert_eq!(word_range(&value, 7, Direction::Backward, true), (0, 7));
assert_eq!(word_range(&value, 2, Direction::Forward, true), (2, 7));
}
}