duat_core/mode/mod.rs
1//! [`Mode`]s that handle user input
2//!
3//! Each [`Mode`] controls a specifig type of [`Widget`], and
4//! switching [`Mode`]s is how one sets the current [`Widget`]. For
5//! example, the [`Standard`] (like most [`Mode`]s), controls the
6//! [`File`] [`Widget`]. So when you switch to that [`Mode`], you
7//! return to the active [`File`] if you were focused on another
8//! [`Widget`].
9//!
10//! Other than the [`File`] the main [`Widget`] that is controled by
11//! [`Mode`]s is the [`PromptLine`]. It is an example of a [`Widget`]
12//! that has many [`Mode`]s implemented for it. Chief of which is
13//! [`RunCommands`], but there is also [`IncSearch`] and
14//! [`PipeSelections`], and the creation of more [`Mode`]s for the
15//! [`PromptLine`] is very much encouraged.
16//!
17//! [`Standard`]: docs.rs/duat-utils/latest/duat_utils/modes/struct.Standard.html
18//! [`PromptLine`]: docs.rs/duat-utils/latest/duat_utils/widgets/struct.PromptLine.html
19//! [`RunCommands`]: docs.rs/duat-utils/latest/duat_utils/modes/struct.RunCommands.html
20//! [`IncSearch`]: docs.rs/duat-utils/latest/duat_utils/modes/struct.IncSearch.html
21//! [`PipeSelections`]: docs.rs/duat-utils/latest/duat_utils/modes/struct.PipeSelections.html
22use core::str;
23use std::sync::atomic::{AtomicBool, Ordering};
24
25pub use crossterm::event::{KeyCode, KeyEvent};
26
27/// Key modifiers, like Shift, Alt, Super, Shift + Alt, etc
28pub type KeyMod = crossterm::event::KeyModifiers;
29
30pub use self::{
31 cursor::{Cursor, Cursors, PointOrPoints, Selection, Selections, VPoint},
32 remap::*,
33 switch::*,
34};
35use crate::{
36 context::Handle,
37 data::Pass,
38 file::File,
39 ui::{Ui, Widget},
40};
41
42mod cursor;
43mod remap;
44mod switch;
45
46/// A blank [`Mode`], intended for plugin authors to use
47///
48/// This [`Mode`] just resets to the default [`File`] [`Mode`], no
49/// matter what key is pressed. It is instead used for mapping keys to
50/// other [`Mode`]s in a common place:
51///
52/// ```rust
53/// # use duat_core::doc_duat as duat;
54/// # mod plugin0{
55/// # use duat_core::prelude::*;
56/// # #[derive(Clone, Copy, Debug)]
57/// # pub struct PluginMode0;
58/// # impl<U: Ui> Mode<U> for PluginMode0 {
59/// # type Widget = File<U>;
60/// # fn send_key(&mut self, _: &mut Pass, _: KeyEvent, _: Handle<Self::Widget, U>) {}
61/// # }
62/// # }
63/// # mod plugin1 {
64/// # use duat_core::prelude::*;
65/// # #[derive(Clone, Copy, Debug)]
66/// # pub struct PluginMode1;
67/// # impl<U: Ui> Mode<U> for PluginMode1 {
68/// # type Widget = File<U>;
69/// # fn send_key(&mut self, _: &mut Pass, _: KeyEvent, _: Handle<Self::Widget, U>) {}
70/// # }
71/// # }
72/// # mod kak {
73/// # use duat_core::prelude::*;
74/// # #[derive(Clone, Copy, Debug)]
75/// # pub struct Normal;
76/// # impl<U: Ui> Mode<U> for Normal {
77/// # type Widget = File<U>;
78/// # fn send_key(&mut self, _: &mut Pass, _: KeyEvent, _: Handle<Self::Widget, U>) {}
79/// # }
80/// # }
81/// setup_duat!(setup);
82/// use duat::prelude::*;
83/// use plugin0::*;
84/// use plugin1::*;
85///
86/// fn setup() {
87/// map::<User>("0", PluginMode0);
88/// map::<User>("1", PluginMode1);
89/// map::<kak::Normal>(" ", User);
90/// }
91/// ```
92///
93/// This way, there is a common "hub" for mappings, which plugins can
94/// use in order to map their own [`Mode`]s without interfering with
95/// the user's mapping.
96#[derive(Clone, Copy, Debug)]
97pub struct User;
98
99impl<U: Ui> Mode<U> for User {
100 type Widget = File<U>;
101
102 fn send_key(&mut self, _: &mut Pass, _: KeyEvent, _: Handle<Self::Widget, U>) {
103 reset::<File<U>, U>();
104 }
105}
106
107/// Wether the reverse modifier should be [alt] as opposed to [shift]
108///
109/// [shift]: KeyMod::SHIFT
110/// [alt]: KeyMod::ALT
111static ALT_IS_REFERSE: AtomicBool = AtomicBool::new(false);
112
113/// Wether [alt] should be the reverse [modifier], instead of [shift]
114///
115/// On most editing models, the key that reverses actions (mostly
116/// searching), is the [shift] key, (like `shift + n` to go to the
117/// previouse match). In other situations though, that may not be the
118/// case, like with [`duat-kak`], where that key is [alt] (for
119/// consistency reasons).
120///
121/// Changing this key via [`set_alt_is_reverse`] does not cause any
122/// internal changes in [`duat-core`] or [`duat-utils`]. It is only
123/// meant to serve as a general setting for plugins to follow.
124///
125/// [modifier]: KeyMod
126/// [shift]: KeyMod::SHIFT
127/// [alt]: KeyMod::ALT
128/// [`duat-kak`]: docs.rs/duat-kak/latest/duat_kak
129/// [`duat-core`]: docs.rs/duat-core/latest/duat_core
130/// [`duat-utils`]: docs.rs/duat-utils/latest/duat_utils
131pub fn alt_is_reverse() -> bool {
132 ALT_IS_REFERSE.load(Ordering::Relaxed)
133}
134
135/// Sets wether [alt] should be the reverse [modifier], instead of
136/// [shift]
137///
138/// On most editing models, the key that reverses actions (mostly
139/// searching), is the [shift] key, (like `shift + n` to go to the
140/// previouse match). In other situations though, that may not be the
141/// case, like with [`duat-kak`], where that key is [alt] (for
142/// consistency reasons).
143///
144/// The value of this setting can be retrieved with
145/// [`alt_is_reverse`].
146///
147/// [modifier]: KeyMod
148/// [shift]: KeyMod::SHIFT
149/// [alt]: KeyMod::ALT
150/// [`duat-kak`]: docs.rs/duat-kak/latest/duat_kak
151/// [`duat-core`]: docs.rs/duat-core/latest/duat_core
152/// [`duat-utils`]: docs.rs/duat-utils/latest/duat_utils
153pub fn set_alt_is_reverse(value: bool) -> bool {
154 ALT_IS_REFERSE.swap(value, Ordering::Relaxed)
155}
156
157/// A mode for a [`Widget`]
158///
159/// [`Mode`]s are the way that Duat decides how keys are going to
160/// modify widgets.
161///
162/// For this example, I will create a `Menu` widget. This example
163/// doesn't make use of the [`Cursor`] methods from the [`Handle`].
164/// Those are methods that modify [`Selection`]s, and can use them to
165/// modify the [`Text`] in a declarative fashion. For an example with
166/// [`Cursor`]s, see the documentation for [`Handle`]s.
167///
168/// First, the [`Widget`] itself:
169///
170/// ```rust
171/// # use duat_core::text::Text;
172/// #[derive(Default)]
173/// struct Menu {
174/// text: Text,
175/// selected_entry: usize,
176/// active_etry: Option<usize>,
177/// }
178/// ```
179/// In this widget, the entries will be selectable via a [`Mode`], by
180/// pressing the up and down keys. Let's say that said menu has five
181/// entries, and one of them can be active at a time:
182///
183/// ```rust
184/// # #![feature(let_chains)]
185/// # use duat_core::prelude::*;
186/// # struct Menu {
187/// # text: Text,
188/// # selected_entry: usize,
189/// # active_entry: Option<usize>,
190/// # }
191/// impl Menu {
192/// pub fn shift_selection(&mut self, shift: i32) {
193/// let selected = self.selected_entry as i32 + shift;
194/// self.selected_entry = if selected < 0 {
195/// 4
196/// } else if selected > 4 {
197/// 0
198/// } else {
199/// selected as usize
200/// };
201/// }
202///
203/// pub fn toggle(&mut self) {
204/// self.active_entry = match self.active_entry {
205/// Some(entry) if entry == self.selected_entry => None,
206/// Some(_) | None => Some(self.selected_entry),
207/// };
208/// }
209///
210/// fn build_text(&mut self) {
211/// let mut builder = Text::builder();
212/// builder.push(AlignCenter);
213///
214/// for i in 0..5 {
215/// if let Some(active) = self.active_entry
216/// && active == i
217/// {
218/// if self.selected_entry == i {
219/// builder.push(form::id_of!("MenuSelActive"))
220/// } else {
221/// builder.push(form::id_of!("MenuActive"))
222/// }
223/// } else if self.selected_entry == i {
224/// builder.push(form::id_of!("MenuSelected"))
225/// }
226///
227/// builder.push(txt!("Entry {i}"));
228/// }
229///
230/// self.text = builder.build();
231/// }
232/// }
233/// ```
234///
235/// By making `shift_selection` and `toggle` `pub`, I can allow an end
236/// user to create their own [`Mode`] for this widget.
237///
238/// Now I'll implement [`Widget`]:
239///
240/// ```rust
241/// # #[derive(Default)]
242/// # struct Menu {
243/// # text: Text,
244/// # selected_entry: usize,
245/// # active_entry: Option<usize>,
246/// # }
247/// # impl Menu {
248/// # fn build_text(&mut self) { todo!(); }
249/// # }
250/// use std::marker::PhantomData;
251///
252/// use duat_core::prelude::*;
253///
254/// struct MenuCfg<U>(PhantomData<U>);
255///
256/// impl<U: Ui> WidgetCfg<U> for MenuCfg<U> {
257/// type Widget = Menu;
258///
259/// fn build(self, _: &mut Pass, _: Option<FileHandle<U>>) -> (Menu, PushSpecs) {
260/// let mut widget = Menu::default();
261/// widget.build_text();
262///
263/// let specs = PushSpecs::left().with_hor_len(10.0).with_ver_len(5.0);
264///
265/// (widget, specs)
266/// }
267/// }
268///
269/// impl<U: Ui> Widget<U> for Menu {
270/// type Cfg = MenuCfg<U>;
271///
272/// fn update(_: &mut Pass, handle: Handle<Self, U>) {}
273///
274/// fn needs_update(&self) -> bool {
275/// false
276/// }
277///
278/// fn text(&self) -> &Text {
279/// &self.text
280/// }
281///
282/// fn text_mut(&mut self) -> &mut Text {
283/// &mut self.text
284/// }
285///
286/// fn cfg() -> Self::Cfg {
287/// MenuCfg(PhantomData)
288/// }
289///
290/// fn once() -> Result<(), Text> {
291/// form::set_weak("menu.active", Form::blue());
292/// form::set_weak("menu.selected", "accent");
293/// form::set_weak("menu.selected.active", "menu.selected");
294/// Ok(())
295/// }
296/// }
297/// ```
298///
299/// One thing that you'll notice is the definition of
300/// [`Widget::needs_update`]. It can always return `false` because the
301/// `Menu` only needs to update after keys are sent, and sent keys
302/// automatically trigger [`Widget::update`].
303///
304/// Now, let's take a look at some [`Widget`] methods that are used
305/// when the [`Widget`] is supposed to be handled by [`Mode`]s. Those
306/// are the [`on_focus`] and [`on_unfocus`] methods:
307///
308/// ```rust
309/// # use std::marker::PhantomData;
310/// # use duat_core::prelude::*;
311/// # #[derive(Default)]
312/// # struct Menu {
313/// # text: Text,
314/// # selected_entry: usize,
315/// # active_entry: Option<usize>,
316/// # }
317/// # struct MenuCfg<U>(PhantomData<U>);
318/// # impl<U: Ui> WidgetCfg<U> for MenuCfg<U> {
319/// # type Widget = Menu;
320/// # fn build(self, _: &mut Pass, _: Option<FileHandle<U>>) -> (Menu, PushSpecs) { todo!() }
321/// # }
322/// impl<U: Ui> Widget<U> for Menu {
323/// # type Cfg = MenuCfg<U>;
324/// # fn cfg() -> Self::Cfg { todo!() }
325/// # fn text(&self) -> &Text { todo!() }
326/// # fn text_mut(&mut self) -> &mut Text { todo!() }
327/// # fn once() -> Result<(), Text> { Ok(()) }
328/// # fn update(_: &mut Pass, _: Handle<Self, U>) {}
329/// # fn needs_update(&self) -> bool { todo!(); }
330/// // ...
331/// fn on_focus(_: &mut Pass, handle: Handle<Self, U>) {
332/// handle.set_mask("inactive");
333/// }
334///
335/// fn on_unfocus(_: &mut Pass, handle: Handle<Self, U>) {
336/// handle.set_mask("inactive");
337/// }
338/// }
339/// ```
340///
341/// These methods can do work when the wiget is focused or unfocused.
342///
343/// In this case, I chose to replace the [`Form`]s with "inactive"
344/// variants, to visually show when the widget is not active. Also,
345/// the usage of [`form::set_weak`] means that if an end user used
346/// [`form::set`] on one of these [`Form`]s, that will be prioritized.
347///
348/// Do also note that [`on_focus`] and [`on_unfocus`] are optional
349/// methods, since a [`Widget`] doesn't necessarily need to change on
350/// focus/unfocus.
351///
352/// Now, all that is left to do is the `MenuInput` [`Mode`]. We just
353/// need to create an empty struct and call the methods of the `Menu`:
354///
355/// ```rust
356/// # use std::marker::PhantomData;
357/// # use duat_core::prelude::*;
358/// # #[derive(Default)]
359/// # struct Menu {
360/// # text: Text,
361/// # selected_entry: usize,
362/// # active_entry: Option<usize>,
363/// # }
364/// # impl Menu {
365/// # pub fn shift_selection(&mut self, shift: i32) {}
366/// # pub fn toggle(&mut self) {}
367/// # fn build_text(&mut self) {}
368/// # }
369/// # struct MenuCfg<U>(PhantomData<U>);
370/// # impl<U: Ui> WidgetCfg<U> for MenuCfg<U> {
371/// # type Widget = Menu;
372/// # fn build(self, _: &mut Pass, _: Option<FileHandle<U>>) -> (Menu, PushSpecs) { todo!() }
373/// # }
374/// # impl<U: Ui> Widget<U> for Menu {
375/// # type Cfg = MenuCfg<U>;
376/// # fn cfg() -> Self::Cfg { todo!() }
377/// # fn text(&self) -> &Text { todo!() }
378/// # fn text_mut(&mut self) -> &mut Text { todo!() }
379/// # fn once() -> Result<(), Text> { Ok(()) }
380/// # fn update(_: &mut Pass, _: Handle<Self, U>) {}
381/// # fn needs_update(&self) -> bool { todo!(); }
382/// # }
383/// #[derive(Clone)]
384/// struct MenuInput;
385///
386/// impl<U: Ui> Mode<U> for MenuInput {
387/// type Widget = Menu;
388///
389/// fn send_key(&mut self, pa: &mut Pass, key: KeyEvent, handle: Handle<Self::Widget, U>) {
390/// use KeyCode::*;
391///
392/// handle.write(pa, |menu, _| {
393/// match key {
394/// key!(Down) => menu.shift_selection(1),
395/// key!(Up) => menu.shift_selection(-1),
396/// key!(Enter | Tab | Char(' ')) => menu.toggle(),
397/// _ => {}
398/// }
399/// });
400/// }
401/// }
402/// ```
403/// Notice the [`key!`] macro. This macro is useful for pattern
404/// matching [`KeyEvent`]s on [`Mode`]s.
405///
406/// [`Cursor`]: crate::mode::Cursor
407/// [`print`]: Widget::print
408/// [`on_focus`]: Widget::on_focus
409/// [`on_unfocus`]: Widget::on_unfocus
410/// [resizing]: crate::ui::RawArea::constrain_ver
411/// [`Form`]: crate::form::Form
412/// [`duat-kak`]: https://docs.rs/duat-kak/latest/duat_kak/index.html
413/// [`form::set_weak`]: crate::form::set_weak
414/// [`form::set`]: crate::form::set
415/// [Kakoune]: https://github.com/mawww/kakoune
416/// [`Text`]: crate::Text
417/// [`&mut Selections`]: Selections
418#[allow(unused_variables)]
419pub trait Mode<U: Ui>: Sized + Clone + 'static {
420 /// The [`Widget`] that this [`Mode`] controls
421 type Widget: Widget<U>;
422
423 /// Sends a [`KeyEvent`] to this [`Mode`]
424 fn send_key(&mut self, pa: &mut Pass, key: KeyEvent, handle: Handle<Self::Widget, U>);
425
426 /// A function to trigger after switching to this [`Mode`]
427 ///
428 /// This can be some initial setup, like adding [`Tag`]s to the
429 /// [`Text`] in order to show some important visual help for that
430 /// specific [`Mode`].
431 ///
432 /// [`Tag`]: crate::text::Tag
433 /// [`Text`]: crate::text::Text
434 fn on_switch(&mut self, pa: &mut Pass, handle: Handle<Self::Widget, U>) {}
435
436 /// A function to trigger before switching off this [`Mode`]
437 ///
438 /// This can be some final cleanup like removing the [`Text`]
439 /// entirely, for example.
440 ///
441 /// You might think "Wait, can't I just do these things before
442 /// calling [`mode::set`] or [`mode::reset`]?". Yeah, you could,
443 /// but these functions can fail, so you would do cleanup without
444 /// actually leaving the [`Mode`]. [`before_exit`] _only_ triggers
445 /// if the switch was actually successful.
446 ///
447 /// [`Text`]: crate::text::Text
448 /// [`mode::set`]: set
449 /// [`mode::reset`]: reset
450 /// [`before_exit`]: Mode::before_exit
451 fn before_exit(&mut self, pa: &mut Pass, handle: Handle<Self::Widget, U>) {}
452
453 /// DO NOT IMPLEMENT THIS FUNCTION, IT IS MEANT FOR `&str` ONLY
454 #[doc(hidden)]
455 fn just_keys(&self) -> Option<&str> {
456 None
457 }
458}
459
460// This implementation exists only to allow &strs to be passed to
461// remaps.
462impl<U: Ui> Mode<U> for &'static str {
463 // Doesn't matter
464 type Widget = File<U>;
465
466 fn send_key(&mut self, _: &mut Pass, _: KeyEvent, _: Handle<Self::Widget, U>) {
467 unreachable!("&strs are only meant to be sent as AsGives, turning into keys");
468 }
469
470 fn just_keys(&self) -> Option<&str> {
471 Some(self)
472 }
473}
474
475/// This is a macro for matching keys in patterns:
476///
477/// Use this for quickly matching a [`KeyEvent`], probably inside an
478/// [`Mode`]:
479///
480/// ```rust
481/// # use duat_core::mode::{KeyEvent, KeyCode, KeyMod, key};
482/// # fn test(key: KeyEvent) {
483/// if let key!(KeyCode::Char('o'), KeyMod::NONE) = key { /* Code */ }
484/// // as opposed to
485/// if let KeyEvent {
486/// code: KeyCode::Char('c'),
487/// modifiers: KeyMod::NONE,
488/// ..
489/// } = key
490/// { /* Code */ }
491/// # }
492/// ```
493///
494/// You can also assign while matching:
495///
496/// ```rust
497/// # use duat_core::mode::{KeyEvent, KeyCode, KeyMod, key};
498/// # fn test(key: KeyEvent) {
499/// if let key!(code, KeyMod::SHIFT | KeyMod::ALT) = key { /* Code */ }
500/// // as opposed to
501/// if let KeyEvent {
502/// code,
503/// modifiers: KeyMod::SHIFT | KeyMod::ALT,
504/// ..
505/// } = key
506/// { /* Code */ }
507/// # }
508/// ```
509pub macro key {
510 ($code:pat) => {
511 KeyEvent { code: $code, modifiers: KeyMod::NONE, .. }
512 },
513
514 ($code:pat, $modifiers:pat) => {
515 KeyEvent { code: $code, modifiers: $modifiers, .. }
516 }
517}
518
519/// Return the length of a strin in chars
520#[allow(dead_code)]
521#[doc(hidden)]
522pub const fn len_chars(s: &str) -> usize {
523 let mut i = 0;
524 let b = s.as_bytes();
525 let mut nchars = 0;
526 while i < b.len() {
527 if crate::text::utf8_char_width(b[i]) > 0 {
528 nchars += 1;
529 }
530 i += 1;
531 }
532 nchars
533}
534
535/// Maps each [`char`] in an `&str` to a [`KeyEvent`]
536#[allow(dead_code)]
537#[doc(hidden)]
538pub fn key_events<const LEN: usize>(str: &str, modif: KeyMod) -> [KeyEvent; LEN] {
539 let mut events = [KeyEvent::new(KeyCode::Esc, KeyMod::NONE); LEN];
540
541 for (event, char) in events.iter_mut().zip(str.chars()) {
542 *event = KeyEvent::new(KeyCode::Char(char), modif)
543 }
544
545 events
546}