duat_core/mode/
mod.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
use core::str;

pub use crossterm::event::{KeyCode, KeyEvent, KeyModifiers as KeyMod};

pub use self::{
    commander::Command,
    helper::{Cursor, Cursors, EditHelper, Editor, Mover},
    inc_search::{ExtendFwd, ExtendRev, Fwd, IncSearcher, Rev},
    regular::Regular,
    remap::*,
    switch::*,
};
use crate::{data::RwData, ui::Ui, widgets::Widget};

mod commander;
mod helper;
mod inc_search;
mod regular;
mod remap;

mod switch {
    use std::{
        any::TypeId,
        sync::{
            Arc, LazyLock,
            atomic::{AtomicBool, Ordering},
        },
    };

    use crossterm::event::KeyEvent;
    use parking_lot::Mutex;

    use super::Mode;
    use crate::{
        context, duat_name, file_entry,
        hooks::{self, ModeSwitched},
        ui::{Ui, Window},
        widget_entry,
        widgets::{CmdLine, CmdLineMode, File, Node},
    };

    static PRINTING_IS_STOPPED: AtomicBool = AtomicBool::new(false);
    static SEND_KEY: LazyLock<Mutex<Box<dyn FnMut(KeyEvent) + Send + Sync>>> =
        LazyLock::new(|| Mutex::new(Box::new(|_| {})));
    static RESET_MODE: LazyLock<Mutex<Arc<dyn Fn() + Send + Sync>>> =
        LazyLock::new(|| Mutex::new(Arc::new(|| {})));
    static SET_MODE: Mutex<Option<Box<dyn FnOnce() + Send + Sync>>> = Mutex::new(None);

    /// Wether or not the [`Mode`] has changed
    pub fn was_set() -> Option<Box<dyn FnOnce() + Send + Sync>> {
        SET_MODE.lock().take()
    }

    /// Sets the new default mode
    ///
    /// This is the mode that will be set when [`mode::reset`] is
    /// called.
    ///
    /// [`mode::reset`]: reset
    pub fn set_default<M: Mode<U>, U: Ui>(mode: M) {
        *RESET_MODE.lock() = Arc::new(move || set_mode_fn::<M, U>(mode.clone()));
        let mut set_mode = SET_MODE.lock();
        let prev = set_mode.take();
        *set_mode = Some(Box::new(move || {
            if let Some(f) = prev {
                f()
            }
            RESET_MODE.lock()()
        }));
    }

    /// Sets the [`Mode`], switching to the appropriate [`Widget`]
    ///
    /// [`Widget`]: Mode::Widget
    pub fn set<U: Ui>(mode: impl Mode<U>) {
        let mut set_mode = SET_MODE.lock();
        let prev = set_mode.take();
        *set_mode = Some(Box::new(move || {
            if let Some(f) = prev {
                f()
            }
            set_mode_fn(mode)
        }));
    }

    /// Resets the mode to the [default]
    ///
    /// [default]: set_default
    pub fn reset() {
        *SET_MODE.lock() = Some(Box::new(|| RESET_MODE.lock()()))
    }

    /// Sets the [`CmdLineMode`]
    pub fn set_cmd<U: Ui>(mode: impl CmdLineMode<U>) {
        let Ok(cur_file) = context::cur_file::<U>() else {
            return;
        };

        if let Some(node) = cur_file.get_related_widget::<CmdLine<U>>() {
            node.try_downcast::<CmdLine<U>>()
                .unwrap()
                .write()
                .set_mode(mode);
        } else {
            let windows = context::windows::<U>().read();
            let w = context::cur_window();
            let cur_window = &windows[w];

            let mut widgets = {
                let previous = windows[..w].iter().flat_map(Window::nodes);
                let following = windows[(w + 1)..].iter().flat_map(Window::nodes);
                cur_window.nodes().chain(previous).chain(following)
            };

            if let Some(cmd_line) = widgets.find_map(|node| {
                node.data_is::<CmdLine<U>>()
                    .then(|| node.try_downcast::<CmdLine<U>>().unwrap())
            }) {
                cmd_line.write().set_mode(mode)
            }
        }
    }

    /// Switches to the file with the given name
    pub fn reset_switch_to<U: Ui>(name: impl std::fmt::Display) {
        let windows = context::windows::<U>().read();
        let name = name.to_string();
        match file_entry(&windows, &name) {
            Ok((_, node)) => {
                let node = node.clone();
                *SET_MODE.lock() = Some(Box::new(move || {
                    switch_widget(node);
                    RESET_MODE.lock().clone()()
                }));
            }
            Err(err) => context::notify(err),
        }
    }

    /// Wether or not printing has been stopped
    ///
    /// This is done when sending multiple keys at the same time
    pub(crate) fn is_printing_stopped() -> bool {
        PRINTING_IS_STOPPED.load(Ordering::Acquire)
    }

    /// Stop printing
    pub(super) fn stop_printing() {
        PRINTING_IS_STOPPED.store(true, Ordering::Release);
    }

    /// Resume printing
    pub(super) fn resume_printing() {
        PRINTING_IS_STOPPED.store(false, Ordering::Release);
    }

    /// Switches to a certain widget
    pub(super) fn switch_widget<U: Ui>(node: Node<U>) {
        if let Ok(widget) = context::cur_widget::<U>() {
            widget.node().on_unfocus();
        }

        context::set_cur(node.as_file(), node.clone());

        node.on_focus();
    }

    /// Sends the [`KeyEvent`] to the active [`Mode`]
    pub(super) fn send_key_to(key: KeyEvent) {
        SEND_KEY.lock()(key);
    }

    /// Inner function that sends [`KeyEvent`]s
    fn send_key_fn<U: Ui>(mode: &mut impl Mode<U>, key: KeyEvent) {
        let Ok(widget) = context::cur_widget::<U>() else {
            return;
        };

        widget.mutate_data_as(|widget, area, cursors| {
            let mut c = cursors.write();
            mode.send_key(key, widget, area, &mut c)
        });
    }

    /// Inner function that sets [`Mode`]s
    fn set_mode_fn<M: Mode<U>, U: Ui>(mut mode: M) {
        // If we are on the correct widget, no switch is needed.
        if context::cur_widget::<U>().unwrap().type_id() != TypeId::of::<M::Widget>() {
            let windows = context::windows().read();
            let w = context::cur_window();
            let entry = if TypeId::of::<M::Widget>() == TypeId::of::<File>() {
                let name = context::cur_file::<U>().unwrap().name();
                file_entry(&windows, &name)
            } else {
                widget_entry::<M::Widget, U>(&windows, w)
            };

            match entry {
                Ok((_, node)) => switch_widget(node.clone()),
                Err(err) => {
                    context::notify(err);
                    return;
                }
            };
        }

        let widget = context::cur_widget::<U>().unwrap();
        widget.mutate_data_as::<M::Widget, ()>(|w, a, c| {
            let mut c = c.write();
            mode.on_switch(w, a, &mut c);
        });

        crate::mode::set_send_key::<M, U>();

        context::mode_name().mutate(|mode| {
            let new_mode = duat_name::<M>();
            hooks::trigger::<ModeSwitched>((mode, new_mode));
            *mode = new_mode;
        });

        *SEND_KEY.lock() = Box::new(move |key| send_key_fn::<U>(&mut mode, key));
    }
}

/// A mode for a [`Widget`]
///
/// Input methods are the way that Duat decides how keys are going to
/// modify widgets.
///
/// In principle, there are two types of `Mode`, the ones which use
/// [`Cursors`], and the ones which don't. In [`Mode::send_key`], you
/// receive an [`&mut Cursors`], and if you're not using cursors, you
/// should run [`Cursors::clear`], in order to make sure there are no
/// cursors.
///
/// If a [`Mode`] has cursors, it _must_ use the [`EditHelper`] struct
/// in order to modify of the widget's [`Text`].
///
/// If your widget/mode combo is not based on cursors. You get
/// more freedom to modify things as you wish, but you should refrain
/// from using [`Cursor`]s in order to prevent bugs.
///
/// For this example, I will create a `Menu` widget, which is not
/// supposed to have [`Cursor`]s. For an example with [`Cursor`]s, see
/// [`EditHelper`]:
///
/// ```rust
/// # use duat_core::text::Text;
/// #[derive(Default)]
/// struct Menu {
///     text: Text,
///     selected_entry: usize,
///     active_etry: Option<usize>,
/// }
/// ```
/// In this widget, I will create a menu whose entries can be selected
/// by an [`Mode`].
///
/// Let's say that said menu has five entries, and one of them can be
/// active at a time:
///
/// ```rust
/// # #![feature(let_chains)]
/// # use duat_core::text::{Text, text, AlignCenter};
/// # struct Menu {
/// #     text: Text,
/// #     selected_entry: usize,
/// #     active_entry: Option<usize>,
/// # }
/// impl Menu {
///     pub fn shift_selection(&mut self, shift: i32) {
///         let selected = self.selected_entry as i32 + shift;
///         self.selected_entry = if selected < 0 {
///             4
///         } else if selected > 4 {
///             0
///         } else {
///             selected as usize
///         };
///     }
///
///     pub fn toggle(&mut self) {
///         self.active_entry = match self.active_entry {
///             Some(entry) if entry == self.selected_entry => None,
///             Some(_) | None => Some(self.selected_entry),
///         };
///     }
///
///     fn build_text(&mut self) {
///         let mut builder = Text::builder();
///         text!(builder, AlignCenter);
///
///         for i in 0..5 {
///             if let Some(active) = self.active_entry
///                 && active == i
///             {
///                 if self.selected_entry == i {
///                     text!(builder, [MenuSelActive])
///                 } else {
///                     text!(builder, [MenuActive])
///                 }
///             } else if self.selected_entry == i {
///                 text!(builder, [MenuSelected]);
///             } else {
///                 text!(builder, [MenuInactive]);
///             }
///
///             text!(builder, "Entry " i);
///         }
///
///         self.text = builder.finish();
///     }
/// }
/// ```
///
/// By making `shift_selection` and `toggle` `pub`, I can allow an end
/// user to create their own [`Mode`] for this widget.
///
/// Let's say that I have created an [`Mode`] `MenuInput` for
/// the `Menu`. This mode is actually the one that is documented on
/// the documentation entry for [`Mode`], you can check it out next,
/// to see how that was handled.
///
/// Now I'll implement [`Widget`]:
///
/// ```rust
/// # use std::marker::PhantomData;
/// # use duat_core::{
/// #     data::RwData, mode::{Mode, KeyEvent}, forms::{self, Form},
/// #     text::{text, Text}, ui::{PushSpecs, Ui}, widgets::{Widget, WidgetCfg},
/// # };
/// # #[derive(Default)]
/// # struct Menu {
/// #     text: Text,
/// #     selected_entry: usize,
/// #     active_entry: Option<usize>,
/// # }
/// # impl Menu {
/// #     fn build_text(&mut self) {
/// #         todo!();
/// #     }
/// # }
/// struct MenuCfg<U>(PhantomData<U>);
///
/// impl<U: Ui> WidgetCfg<U> for MenuCfg<U> {
///     type Widget = Menu;
///
///     fn build(self, on_file: bool) -> (Menu, impl Fn() -> bool + 'static, PushSpecs) {
///         let checker = || false;
///
///         let mut widget = Menu::default();
///         widget.build_text();
///
///         let specs = PushSpecs::left().with_hor_len(10.0).with_ver_len(5.0);
///
///         (widget, checker, specs)
///     }
/// }
///
/// impl<U: Ui> Widget<U> for Menu {
///     type Cfg = MenuCfg<U>;
///
///     fn cfg() -> Self::Cfg {
///         MenuCfg(PhantomData)
///     }
///
///     fn text(&self) -> &Text {
///         &self.text
///     }
///   
///     fn text_mut(&mut self) -> &mut Text {
///         &mut self.text
///     }
///
///     fn once() {
///         forms::set_weak("MenuInactive", "Inactive");
///         forms::set_weak("MenuSelected", "Inactive");
///         forms::set_weak("MenuActive", Form::blue());
///         forms::set_weak("MenuSelActive", Form::blue());
///     }
/// }
/// ```
///
/// We can use `let checker = || false` here, since active [`Widget`]s
/// get automatically updated whenever they are focused or a key is
/// sent.
///
/// Now, let's take a look at some [`Widget`] methods that are unique
/// to widgets that can take mode. Those are the [`on_focus`] and
/// [`on_unfocus`] methods:
///
/// ```rust
/// # use std::marker::PhantomData;
/// # use duat_core::{
/// #     data::RwData, forms::{self, Form}, text::{text, Text}, ui::{PushSpecs, Ui},
/// #     widgets::{Widget, WidgetCfg},
/// # };
/// # #[derive(Default)]
/// # struct Menu {
/// #     text: Text,
/// #     selected_entry: usize,
/// #     active_entry: Option<usize>,
/// # }
/// # struct MenuCfg<U>(PhantomData<U>);
/// # impl<U: Ui> WidgetCfg<U> for MenuCfg<U> {
/// #     type Widget = Menu;
/// #     fn build(self, on_file: bool) -> (Menu, impl Fn() -> bool + 'static, PushSpecs) {
/// #         (Menu::default(), || false, PushSpecs::left())
/// #     }
/// # }
/// impl<U: Ui> Widget<U> for Menu {
/// #     type Cfg = MenuCfg<U>;
/// #     fn cfg() -> Self::Cfg {
/// #         MenuCfg(PhantomData)
/// #     }
/// #     fn text(&self) -> &Text {
/// #         &self.text
/// #     }
/// #     fn once() {}
/// #     fn text_mut(&mut self) -> &mut Text {
/// #         &mut self.text
/// #     }
///     // ...
///     fn on_focus(&mut self, _area: &U::Area) {
///         forms::set_weak("MenuInactive", "Default");
///         forms::set_weak("MenuSelected", Form::new().on_grey());
///         forms::set_weak("MenuSelActive", Form::blue().on_grey());
///     }
///
///     fn on_unfocus(&mut self, _area: &U::Area) {
///         forms::set_weak("MenuInactive", "Inactive");
///         forms::set_weak("MenuSelected", "Inactive");
///         forms::set_weak("MenuSelActive", Form::blue());
///     }
/// }
/// ```
///
/// These methods can do work when the wiget is focused or unfocused.
///
/// In this case, I chose to replace the [`Form`]s with "inactive"
/// variants, to visually show when the widget is not active.
///
/// Do also note that [`on_focus`] and [`on_unfocus`] are optional
/// methods, since a change on focus is not always necessary.
///
/// Now, all that is left to do is  the `MenuInput` [`Mode`]. We just
/// need to create an empty struct and call the methods of the `Menu`:
///
/// ```rust
/// # #![feature(let_chains)]
/// # use std::marker::PhantomData;
/// # use duat_core::{
/// #     data::RwData, mode::{key, Cursors, Mode, KeyCode, KeyEvent}, forms::{self, Form},
/// #     text::{text, Text}, ui::{PushSpecs, Ui}, widgets::{Widget, WidgetCfg},
/// # };
/// # #[derive(Default)]
/// # struct Menu {
/// #     text: Text,
/// #     selected_entry: usize,
/// #     active_entry: Option<usize>,
/// # }
/// # impl Menu {
/// #     pub fn shift_selection(&mut self, shift: i32) {}
/// #     pub fn toggle(&mut self) {}
/// #     fn build_text(&mut self) {}
/// # }
/// # struct MenuCfg<U>(PhantomData<U>);
/// # impl<U: Ui> WidgetCfg<U> for MenuCfg<U> {
/// #     type Widget = Menu;
/// #     fn build(self, on_file: bool) -> (Menu, impl Fn() -> bool + 'static, PushSpecs) {
/// #         (Menu::default(), || false, PushSpecs::left())
/// #     }
/// # }
/// # impl<U: Ui> Widget<U> for Menu {
/// #     type Cfg = MenuCfg<U>;
/// #     fn cfg() -> Self::Cfg {
/// #         MenuCfg(PhantomData)
/// #     }
/// #     fn text(&self) -> &Text {
/// #         &self.text
/// #     }
/// #     fn once() {}
/// #     fn text_mut(&mut self) -> &mut Text {
/// #         &mut self.text
/// #     }
/// # }
/// #[derive(Clone)]
/// struct MenuInput;
///
/// impl<U: Ui> Mode<U> for MenuInput {
///     type Widget = Menu;
///
///     fn send_key(
///         &mut self,
///         key: KeyEvent,
///         widget: &RwData<Menu>,
///         area: &U::Area,
///         cursors: &mut Cursors,
///     ) {
///         cursors.clear();
///         use KeyCode::*;
///         let mut menu = widget.write();
///         
///         match key {
///             key!(Down) => menu.shift_selection(1),
///             key!(Up) => menu.shift_selection(-1),
///             key!(Enter | Tab | Char(' ')) => menu.toggle(),
///             _ => {}
///         }
///     }
/// }
/// ```
/// Notice the [`key!`] macro. This macro is useful for pattern
/// matching [`KeyEvent`]s on [`Mode`]s.
///
/// [`Cursor`]: crate::mode::Cursor
/// [`print`]: Widget::print
/// [`on_focus`]: Widget::on_focus
/// [`on_unfocus`]: Widget::on_unfocus
/// [resizing]: Area::constrain_ver
/// [`Form`]: crate::forms::Form
/// [default]: default::KeyMap
/// [`duat-kak`]: https://docs.rs/duat-kak/latest/duat_kak/index.html
/// [Kakoune]: https://github.com/mawww/kakoune
/// [`Text`]: crate::Text
/// [`&mut Cursors`]: Cursors
pub trait Mode<U: Ui>: Sized + Clone + Send + Sync + 'static {
    type Widget: Widget<U>;

    /// Sends a [`KeyEvent`] to this [`Mode`]
    fn send_key(
        &mut self,
        key: KeyEvent,
        widget: &RwData<Self::Widget>,
        area: &U::Area,
        cursors: &mut Cursors,
    );

    /// A function to trigger when switching to this [`Mode`]
    ///
    /// This can be some initial setup, like adding [`Tag`]s to the
    /// [`Text`] in order to show some important visual help for that
    /// specific [`Mode`].
    ///
    /// [`Tag`]: crate::text::Tag
    /// [`Text`]: crate::text::Text
    #[allow(unused)]
    fn on_switch(&mut self, widget: &RwData<Self::Widget>, area: &U::Area, cursors: &mut Cursors) {}
}

/// This is a macro for matching keys in patterns:
///
/// Use this for quickly matching a [`KeyEvent`], probably inside an
/// [`Mode`]:
///
/// ```rust
/// # use duat_core::mode::{KeyEvent, KeyCode, KeyMod, key};
/// # fn test(key: KeyEvent) {
/// if let key!(KeyCode::Char('o'), KeyMod::NONE) = key { /* Code */ }
/// // as opposed to
/// if let KeyEvent {
///     code: KeyCode::Char('c'),
///     modifiers: KeyMod::NONE,
///     ..
/// } = key
/// { /* Code */ }
/// # }
/// ```
///
/// You can also assign while matching:
///
/// ```rust
/// # use duat_core::mode::{KeyEvent, KeyCode, KeyMod, key};
/// # fn test(key: KeyEvent) {
/// if let key!(code, KeyMod::SHIFT | KeyMod::ALT) = key { /* Code */ }
/// // as opposed to
/// if let KeyEvent {
///     code,
///     modifiers: KeyMod::SHIFT | KeyMod::ALT,
///     ..
/// } = key
/// { /* Code */ }
/// # }
/// ```
pub macro key {
    ($code:pat) => {
        KeyEvent { code: $code, modifiers: KeyMod::NONE, .. }
    },

    ($code:pat, $modifiers:pat) => {
        KeyEvent { code: $code, modifiers: $modifiers, .. }
    }
}

/// Return the lenght of a strin in chars
#[allow(dead_code)]
#[doc(hidden)]
pub const fn len_chars(s: &str) -> usize {
    let mut i = 0;
    let b = s.as_bytes();
    let mut nchars = 0;
    while i < b.len() {
        if crate::text::utf8_char_width(b[i]) > 0 {
            nchars += 1;
        }
        i += 1;
    }
    nchars
}

/// Maps each [`char`] in an `&str` to a [`KeyEvent`]
#[allow(dead_code)]
#[doc(hidden)]
pub fn key_events<const LEN: usize>(str: &str, modif: KeyMod) -> [KeyEvent; LEN] {
    let mut events = [KeyEvent::new(KeyCode::Esc, KeyMod::NONE); LEN];

    for (event, char) in events.iter_mut().zip(str.chars()) {
        *event = KeyEvent::new(KeyCode::Char(char), modif)
    }

    events
}