rat_event/
util.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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
//!
//! Some utility functions that pop up all the time.
//!

use crate::Outcome;
use crossterm::event::{KeyModifiers, MouseButton, MouseEvent, MouseEventKind};
use ratatui::layout::{Position, Rect};
use std::cell::Cell;
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use std::time::SystemTime;

/// Which of the given rects is at the position.
pub fn item_at(areas: &[Rect], x_pos: u16, y_pos: u16) -> Option<usize> {
    for (i, r) in areas.iter().enumerate() {
        if y_pos >= r.top() && y_pos < r.bottom() && x_pos >= r.left() && x_pos < r.right() {
            return Some(i);
        }
    }
    None
}

/// Which row of the given contains the position.
/// This uses only the vertical components of the given areas.
///
/// You might want to limit calling this functions when the full
/// position is inside your target rect.
pub fn row_at(areas: &[Rect], y_pos: u16) -> Option<usize> {
    for (i, r) in areas.iter().enumerate() {
        if y_pos >= r.top() && y_pos < r.bottom() {
            return Some(i);
        }
    }
    None
}

/// Column at given position.
/// This uses only the horizontal components of the given areas.
///
/// You might want to limit calling this functions when the full
/// position is inside your target rect.
pub fn column_at(areas: &[Rect], x_pos: u16) -> Option<usize> {
    for (i, r) in areas.iter().enumerate() {
        if x_pos >= r.left() && x_pos < r.right() {
            return Some(i);
        }
    }
    None
}

/// Find a row position when dragging with the mouse. This uses positions
/// outside the given areas to estimate an invisible row that could be meant
/// by the mouse position. It uses the heuristic `1 row == 1 item` for simplicity’s
/// sake.
///
/// Rows outside the bounds are returned as Err(isize), rows inside as Ok(usize).
pub fn row_at_drag(encompassing: Rect, areas: &[Rect], y_pos: u16) -> Result<usize, isize> {
    if let Some(row) = row_at(areas, y_pos) {
        return Ok(row);
    }

    // assume row-height=1 for outside the box.
    #[allow(clippy::collapsible_else_if)]
    if y_pos < encompassing.top() {
        Err(y_pos as isize - encompassing.top() as isize)
    } else {
        if let Some(last) = areas.last() {
            Err(y_pos as isize - last.bottom() as isize + 1)
        } else {
            Err(y_pos as isize - encompassing.top() as isize)
        }
    }
}

/// Find a column position when dragging with the mouse. This uses positions
/// outside the given areas to estimate an invisible column that could be meant
/// by the mouse position. It uses the heuristic `1 column == 1 item` for simplicity’s
/// sake.
///
/// Columns outside the bounds are returned as Err(isize), rows inside as Ok(usize).
pub fn column_at_drag(encompassing: Rect, areas: &[Rect], x_pos: u16) -> Result<usize, isize> {
    if let Some(column) = column_at(areas, x_pos) {
        return Ok(column);
    }

    // change by 1 column if outside the box
    #[allow(clippy::collapsible_else_if)]
    if x_pos < encompassing.left() {
        Err(x_pos as isize - encompassing.left() as isize)
    } else {
        if let Some(last) = areas.last() {
            Err(x_pos as isize - last.right() as isize + 1)
        } else {
            Err(x_pos as isize - encompassing.left() as isize)
        }
    }
}

/// This function consumes all mouse-events in the given area,
/// except Drag events.
///
/// This should catch all events when using a popup area.
pub fn mouse_trap(event: &crossterm::event::Event, area: Rect) -> Outcome {
    match event {
        crossterm::event::Event::Mouse(MouseEvent {
            kind:
                MouseEventKind::ScrollLeft
                | MouseEventKind::ScrollRight
                | MouseEventKind::ScrollUp
                | MouseEventKind::ScrollDown
                | MouseEventKind::Down(_)
                | MouseEventKind::Up(_)
                | MouseEventKind::Moved,
            column,
            row,
            ..
        }) if area.contains(Position::new(*column, *row)) => Outcome::Unchanged,
        _ => Outcome::Continue,
    }
}

/// Click states for double click.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum Clicks {
    #[default]
    None,
    Down1(usize),
    Up1(usize),
    Down2(usize),
}

/// Some state for mouse interactions.
///
/// This helps with double-click and mouse drag recognition.
/// Add this to your widget state.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct MouseFlags {
    /// Timestamp for double click
    pub time: Cell<Option<SystemTime>>,
    /// Flag for the first down.
    pub click: Cell<Clicks>,
    /// Drag enabled.
    pub drag: Cell<bool>,
    /// Hover detect.
    pub hover: Cell<bool>,
}

impl MouseFlags {
    /// Returns column/row extracted from the Mouse-Event.
    pub fn pos_of(&self, event: &MouseEvent) -> (u16, u16) {
        (event.column, event.row)
    }

    /// Which of the given rects is at the position.
    pub fn item_at(&self, areas: &[Rect], x_pos: u16, y_pos: u16) -> Option<usize> {
        item_at(areas, x_pos, y_pos)
    }

    /// Which row of the given contains the position.
    /// This uses only the vertical components of the given areas.
    ///
    /// You might want to limit calling this functions when the full
    /// position is inside your target rect.
    pub fn row_at(&self, areas: &[Rect], y_pos: u16) -> Option<usize> {
        row_at(areas, y_pos)
    }

    /// Column at given position.
    /// This uses only the horizontal components of the given areas.
    ///
    /// You might want to limit calling this functions when the full
    /// position is inside your target rect.
    pub fn column_at(&self, areas: &[Rect], x_pos: u16) -> Option<usize> {
        column_at(areas, x_pos)
    }

    /// Find a row position when dragging with the mouse. This uses positions
    /// outside the given areas to estimate an invisible row that could be meant
    /// by the mouse position. It uses the heuristic `1 row == 1 item` for simplicity’s
    /// sake.
    ///
    /// Rows outside the bounds are returned as Err(isize), rows inside as Ok(usize).
    pub fn row_at_drag(
        &self,
        encompassing: Rect,
        areas: &[Rect],
        y_pos: u16,
    ) -> Result<usize, isize> {
        row_at_drag(encompassing, areas, y_pos)
    }

    /// Find a column position when dragging with the mouse. This uses positions
    /// outside the given areas to estimate an invisible column that could be meant
    /// by the mouse position. It uses the heuristic `1 column == 1 item` for simplicity’s
    /// sake.
    ///
    /// Columns outside the bounds are returned as Err(isize), rows inside as Ok(usize).
    pub fn column_at_drag(
        &self,
        encompassing: Rect,
        areas: &[Rect],
        x_pos: u16,
    ) -> Result<usize, isize> {
        column_at_drag(encompassing, areas, x_pos)
    }

    /// Checks if this is a hover event for the widget.
    pub fn hover(&self, area: Rect, event: &MouseEvent) -> bool {
        match event {
            MouseEvent {
                kind: MouseEventKind::Moved,
                column,
                row,
                modifiers: KeyModifiers::NONE,
            } => {
                let old_hover = self.hover.get();
                if area.contains((*column, *row).into()) {
                    self.hover.set(true);
                } else {
                    self.hover.set(false);
                }
                old_hover != self.hover.get()
            }
            _ => false,
        }
    }

    /// Checks if this is a drag event for the widget.
    ///
    /// It makes sense to allow drag events outside the given area, if the
    /// drag has been started with a click to the given area.
    ///
    /// This can be integrated in the event-match with a guard:
    ///
    /// ```rust ignore
    /// match event {
    ///         Event::Mouse(m) if state.mouse.drag(state.area, m) => {
    ///             // ...
    ///             Outcome::Changed
    ///         }
    /// }
    /// ```
    pub fn drag(&self, area: Rect, event: &MouseEvent) -> bool {
        self.drag2(area, event, KeyModifiers::NONE)
    }

    /// Checks if this is a drag event for the widget.
    ///
    /// It makes sense to allow drag events outside the given area, if the
    /// drag has been started with a click to the given area.
    ///
    /// This function handles that case.
    pub fn drag2(&self, area: Rect, event: &MouseEvent, filter: KeyModifiers) -> bool {
        match event {
            MouseEvent {
                kind: MouseEventKind::Down(MouseButton::Left),
                column,
                row,
                modifiers,
            } if *modifiers == filter => {
                if area.contains((*column, *row).into()) {
                    self.drag.set(true);
                } else {
                    self.drag.set(false);
                }
            }
            MouseEvent {
                kind: MouseEventKind::Drag(MouseButton::Left),
                modifiers,
                ..
            } if *modifiers == filter => {
                if self.drag.get() {
                    return true;
                }
            }
            MouseEvent {
                kind: MouseEventKind::Up(MouseButton::Left) | MouseEventKind::Moved,
                ..
            } => {
                self.drag.set(false);
            }

            _ => {}
        }

        false
    }

    /// Checks for double-click events.
    ///
    /// This can be integrated in the event-match with a guard:
    ///
    /// ```rust ignore
    /// match event {
    ///         Event::Mouse(m) if state.mouse.doubleclick(state.area, m) => {
    ///             state.flip = !state.flip;
    ///             Outcome::Changed
    ///         }
    /// }
    /// ```
    ///
    pub fn doubleclick(&self, area: Rect, event: &MouseEvent) -> bool {
        self.doubleclick2(area, event, KeyModifiers::NONE)
    }

    /// Checks for double-click events.
    /// This one can have an extra KeyModifiers.
    ///
    /// This can be integrated in the event-match with a guard:
    ///
    /// ```rust ignore
    /// match event {
    ///         Event::Mouse(m) if state.mouse.doubleclick(state.area, m) => {
    ///             state.flip = !state.flip;
    ///             Outcome::Changed
    ///         }
    /// }
    /// ```
    ///
    pub fn doubleclick2(&self, area: Rect, event: &MouseEvent, filter: KeyModifiers) -> bool {
        match event {
            MouseEvent {
                kind: MouseEventKind::Down(MouseButton::Left),
                column,
                row,
                modifiers,
            } if *modifiers == filter => 'f: {
                if area.contains((*column, *row).into()) {
                    match self.click.get() {
                        Clicks::Up1(_) => {
                            if let Some(time) = self.time.get() {
                                if time.elapsed().unwrap_or_default().as_millis() as u32
                                    > double_click_timeout()
                                {
                                    self.time.set(Some(SystemTime::now()));
                                    self.click.set(Clicks::Down1(0));
                                    break 'f false;
                                }
                            }
                            self.click.set(Clicks::Down2(0));
                        }
                        _ => {
                            self.time.set(Some(SystemTime::now()));
                            self.click.set(Clicks::Down1(0));
                        }
                    }
                    break 'f false;
                } else {
                    self.time.set(None);
                    self.click.set(Clicks::None);
                    break 'f false;
                }
            }
            MouseEvent {
                kind: MouseEventKind::Up(MouseButton::Left),
                column,
                row,
                modifiers,
            } if *modifiers == filter => 'f: {
                if area.contains((*column, *row).into()) {
                    match self.click.get() {
                        Clicks::Down1(_) => {
                            self.click.set(Clicks::Up1(0));
                            break 'f false;
                        }
                        Clicks::Up1(_) => {
                            self.click.set(Clicks::None);
                            break 'f true;
                        }
                        Clicks::Down2(_) => {
                            self.click.set(Clicks::None);
                            break 'f true;
                        }
                        _ => {
                            self.click.set(Clicks::None);
                            break 'f false;
                        }
                    }
                } else {
                    self.click.set(Clicks::None);
                    break 'f false;
                }
            }
            _ => false,
        }
    }
}

/// Some state for mouse interactions with multiple areas.
///
/// This helps with double-click and mouse drag recognition.
/// Add this to your widget state.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct MouseFlagsN {
    /// Timestamp for double click
    pub time: Cell<Option<SystemTime>>,
    /// Flag for the first down.
    pub click: Cell<Clicks>,
    /// Drag enabled.
    pub drag: Cell<Option<usize>>,
    /// Hover detect.
    pub hover: Cell<Option<usize>>,
}

impl MouseFlagsN {
    /// Returns column/row extracted from the Mouse-Event.
    pub fn pos_of(&self, event: &MouseEvent) -> (u16, u16) {
        (event.column, event.row)
    }

    /// Which of the given rects is at the position.
    pub fn item_at(&self, areas: &[Rect], x_pos: u16, y_pos: u16) -> Option<usize> {
        item_at(areas, x_pos, y_pos)
    }

    /// Which row of the given contains the position.
    /// This uses only the vertical components of the given areas.
    ///
    /// You might want to limit calling this functions when the full
    /// position is inside your target rect.
    pub fn row_at(&self, areas: &[Rect], y_pos: u16) -> Option<usize> {
        row_at(areas, y_pos)
    }

    /// Column at given position.
    /// This uses only the horizontal components of the given areas.
    ///
    /// You might want to limit calling this functions when the full
    /// position is inside your target rect.
    pub fn column_at(&self, areas: &[Rect], x_pos: u16) -> Option<usize> {
        column_at(areas, x_pos)
    }

    /// Find a row position when dragging with the mouse. This uses positions
    /// outside the given areas to estimate an invisible row that could be meant
    /// by the mouse position. It uses the heuristic `1 row == 1 item` for simplicity’s
    /// sake.
    ///
    /// Rows outside the bounds are returned as Err(isize), rows inside as Ok(usize).
    pub fn row_at_drag(
        &self,
        encompassing: Rect,
        areas: &[Rect],
        y_pos: u16,
    ) -> Result<usize, isize> {
        row_at_drag(encompassing, areas, y_pos)
    }

    /// Find a column position when dragging with the mouse. This uses positions
    /// outside the given areas to estimate an invisible column that could be meant
    /// by the mouse position. It uses the heuristic `1 column == 1 item` for simplicity’s
    /// sake.
    ///
    /// Columns outside the bounds are returned as Err(isize), rows inside as Ok(usize).
    pub fn column_at_drag(
        &self,
        encompassing: Rect,
        areas: &[Rect],
        x_pos: u16,
    ) -> Result<usize, isize> {
        column_at_drag(encompassing, areas, x_pos)
    }

    /// Checks if this is a hover event for the widget.
    pub fn hover(&self, areas: &[Rect], event: &MouseEvent) -> bool {
        match event {
            MouseEvent {
                kind: MouseEventKind::Moved,
                column,
                row,
                modifiers: KeyModifiers::NONE,
            } => {
                let old_hover = self.hover.get();
                if let Some(n) = self.item_at(areas, *column, *row) {
                    self.hover.set(Some(n));
                } else {
                    self.hover.set(None);
                }
                old_hover != self.hover.get()
            }
            _ => false,
        }
    }

    /// Checks if this is a drag event for the widget.
    ///
    /// It makes sense to allow drag events outside the given area, if the
    /// drag has been started with a click to the given area.
    ///
    /// This function handles that case.
    pub fn drag(&self, areas: &[Rect], event: &MouseEvent) -> bool {
        self.drag2(areas, event, KeyModifiers::NONE)
    }

    /// Checks if this is a drag event for the widget.
    ///
    /// It makes sense to allow drag events outside the given area, if the
    /// drag has been started with a click to the given area.
    ///
    /// This function handles that case.
    pub fn drag2(&self, areas: &[Rect], event: &MouseEvent, filter: KeyModifiers) -> bool {
        match event {
            MouseEvent {
                kind: MouseEventKind::Down(MouseButton::Left),
                column,
                row,
                modifiers,
            } if *modifiers == filter => {
                self.drag.set(None);
                for (n, area) in areas.iter().enumerate() {
                    if area.contains((*column, *row).into()) {
                        self.drag.set(Some(n));
                    }
                }
            }
            MouseEvent {
                kind: MouseEventKind::Drag(MouseButton::Left),
                modifiers,
                ..
            } if *modifiers == filter => {
                if self.drag.get().is_some() {
                    return true;
                }
            }
            MouseEvent {
                kind: MouseEventKind::Up(MouseButton::Left) | MouseEventKind::Moved,
                ..
            } => {
                self.drag.set(None);
            }

            _ => {}
        }

        false
    }

    /// Checks for double-click events.
    ///
    /// This can be integrated in the event-match with a guard:
    ///
    /// ```rust ignore
    /// match event {
    ///         Event::Mouse(m) if state.mouse.doubleclick(state.area, m) => {
    ///             state.flip = !state.flip;
    ///             Outcome::Changed
    ///         }
    /// }
    /// ```
    ///
    pub fn doubleclick(&self, areas: &[Rect], event: &MouseEvent) -> bool {
        self.doubleclick2(areas, event, KeyModifiers::NONE)
    }

    /// Checks for double-click events.
    /// This one can have an extra KeyModifiers.
    ///
    /// This can be integrated in the event-match with a guard:
    ///
    /// ```rust ignore
    /// match event {
    ///         Event::Mouse(m) if state.mouse.doubleclick(state.area, m) => {
    ///             state.flip = !state.flip;
    ///             Outcome::Changed
    ///         }
    /// }
    /// ```
    ///
    pub fn doubleclick2(&self, areas: &[Rect], event: &MouseEvent, filter: KeyModifiers) -> bool {
        match event {
            MouseEvent {
                kind: MouseEventKind::Down(MouseButton::Left),
                column,
                row,
                modifiers,
            } if *modifiers == filter => 'f: {
                for (n, area) in areas.iter().enumerate() {
                    if area.contains((*column, *row).into()) {
                        match self.click.get() {
                            Clicks::Up1(v) => {
                                if let Some(time) = self.time.get() {
                                    if time.elapsed().unwrap_or_default().as_millis() as u32
                                        > double_click_timeout()
                                    {
                                        self.time.set(Some(SystemTime::now()));
                                        self.click.set(Clicks::Down1(n));
                                        break 'f false;
                                    }
                                }
                                if n == v {
                                    self.click.set(Clicks::Down2(n));
                                } else {
                                    self.click.set(Clicks::None);
                                }
                            }
                            _ => {
                                self.time.set(Some(SystemTime::now()));
                                self.click.set(Clicks::Down1(n));
                            }
                        }
                        break 'f false;
                    }
                }
                self.time.set(None);
                self.click.set(Clicks::None);
                false
            }
            MouseEvent {
                kind: MouseEventKind::Up(MouseButton::Left),
                column,
                row,
                modifiers,
            } if *modifiers == filter => 'f: {
                for (n, area) in areas.iter().enumerate() {
                    if area.contains((*column, *row).into()) {
                        match self.click.get() {
                            Clicks::Down1(v) => {
                                if n == v {
                                    self.click.set(Clicks::Up1(v));
                                } else {
                                    self.click.set(Clicks::None);
                                }
                            }
                            Clicks::Up1(v) => {
                                if n == v {
                                    self.click.set(Clicks::None);
                                    break 'f true;
                                } else {
                                    self.click.set(Clicks::None);
                                }
                            }
                            Clicks::Down2(v) => {
                                if n == v {
                                    self.click.set(Clicks::None);
                                    break 'f true;
                                } else {
                                    self.click.set(Clicks::None);
                                }
                            }
                            _ => {
                                self.click.set(Clicks::None);
                            }
                        }
                        break 'f false;
                    }
                }
                self.click.set(Clicks::None);
                false
            }
            _ => false,
        }
    }
}

static DOUBLE_CLICK: AtomicU32 = AtomicU32::new(250);

/// Sets the global double click time-out between consecutive clicks.
/// In milliseconds.
pub fn set_double_click_timeout(timeout: u32) {
    DOUBLE_CLICK.store(timeout, Ordering::Release);
}

/// The global double click time-out between consecutive clicks.
/// In milliseconds.
pub fn double_click_timeout() -> u32 {
    DOUBLE_CLICK.load(Ordering::Acquire)
}

static ENHANCED_KEYS: AtomicBool = AtomicBool::new(false);

/// Are enhanced keys available?
/// Only then Release and Repeat keys are available.
///
/// This flag is set during startup of the application when
/// configuring the terminal.
pub fn have_keyboard_enhancement() -> bool {
    ENHANCED_KEYS.load(Ordering::Acquire)
}

/// Set the flag for enhanced keys.
///
/// For windows + crossterm this can always be set true.
///
/// For unix this needs to activate the enhancements with PushKeyboardEnhancementFlags,
/// and it still needs to query supports_keyboard_enhancement().
/// If you enable REPORT_ALL_KEYS_AS_ESCAPE_CODES you need REPORT_ALTERNATE_KEYS to,
/// otherwise shift+key will not return something useful.
///
pub fn set_have_keyboard_enhancement(have: bool) {
    ENHANCED_KEYS.store(have, Ordering::Release);
}