rat_widget/
button.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
//!
//! Button widget.
//!
//! Render:
//! ```rust ignore
//! Button::new("Button")
//!      .styles(THEME.button_style()) //
//!      .render(b_area_1, frame.buffer_mut(), &mut state.button1);
//! ```
//!
//! Event handling:
//! ```rust ignore
//! match state.button1.handle(event, Regular) {
//!     ButtonOutcome::Pressed => {
//!         data.p1 += 1;
//!         Outcome::Changed
//!     }
//!     r => r.into(),
//! }
//! ```
//!

use crate::_private::NonExhaustive;
use crate::button::event::ButtonOutcome;
use crate::util::{block_size, revert_style};
use rat_event::util::{have_keyboard_enhancement, MouseFlags};
use rat_event::{ct_event, ConsumedEvent, HandleEvent, MouseOnly, Regular};
use rat_focus::{FocusBuilder, FocusFlag, HasFocus};
use rat_reloc::{relocate_area, RelocatableState};
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::prelude::BlockExt;
use ratatui::style::Style;
use ratatui::text::Text;
#[cfg(feature = "unstable-widget-ref")]
use ratatui::widgets::StatefulWidgetRef;
use ratatui::widgets::{Block, StatefulWidget, Widget};
use std::thread;
use std::time::Duration;

/// Button widget.
#[derive(Debug, Default, Clone)]
pub struct Button<'a> {
    text: Text<'a>,
    style: Style,
    focus_style: Option<Style>,
    hover_style: Option<Style>,
    armed_style: Option<Style>,
    armed_delay: Option<Duration>,
    block: Option<Block<'a>>,
}

/// Composite style.
#[derive(Debug, Clone)]
pub struct ButtonStyle {
    /// Base style
    pub style: Style,
    /// Focused style
    pub focus: Option<Style>,
    /// Armed style
    pub armed: Option<Style>,
    /// Hover style
    pub hover: Option<Style>,
    /// Button border
    pub block: Option<Block<'static>>,
    /// Some terminals repaint too fast to see the click.
    /// This adds some delay when the button state goes from
    /// armed to clicked.
    pub armed_delay: Option<Duration>,

    pub non_exhaustive: NonExhaustive,
}

/// State & event-handling.
#[derive(Debug)]
pub struct ButtonState {
    /// Complete area
    /// __readonly__. renewed for each render.
    pub area: Rect,
    /// Area inside the block.
    /// __readonly__. renewed for each render.
    pub inner: Rect,

    /// Hover is enabled?
    pub hover_enabled: bool,
    /// Button has been clicked but not released yet.
    /// __used for mouse interaction__
    pub armed: bool,
    /// Some terminals repaint too fast to see the click.
    /// This adds some delay when the button state goes from
    /// armed to clicked.
    ///
    /// Default is 50ms.
    pub armed_delay: Option<Duration>,

    /// Current focus state.
    /// __read+write__
    pub focus: FocusFlag,

    pub mouse: MouseFlags,

    pub non_exhaustive: NonExhaustive,
}

impl Default for ButtonStyle {
    fn default() -> Self {
        Self {
            style: Default::default(),
            focus: None,
            armed: None,
            hover: None,
            block: None,
            armed_delay: None,
            non_exhaustive: NonExhaustive,
        }
    }
}

impl<'a> Button<'a> {
    pub fn new(text: impl Into<Text<'a>>) -> Self {
        Self::default().text(text)
    }

    /// Set all styles.
    #[inline]
    pub fn styles_opt(self, styles: Option<ButtonStyle>) -> Self {
        if let Some(styles) = styles {
            self.styles(styles)
        } else {
            self
        }
    }

    /// Set all styles.
    #[inline]
    pub fn styles(mut self, styles: ButtonStyle) -> Self {
        self.style = styles.style;
        if styles.focus.is_some() {
            self.focus_style = styles.focus;
        }
        if styles.armed.is_some() {
            self.armed_style = styles.armed;
        }
        if styles.armed_delay.is_some() {
            self.armed_delay = styles.armed_delay;
        }
        if styles.hover.is_some() {
            self.hover_style = styles.hover;
        }
        if let Some(block) = styles.block {
            self.block = Some(block);
        }
        self.block = self.block.map(|v| v.style(self.style));
        self
    }

    /// Set the base-style.
    #[inline]
    pub fn style(mut self, style: impl Into<Style>) -> Self {
        self.style = style.into();
        self
    }

    /// Style when focused.
    #[inline]
    pub fn focus_style(mut self, style: impl Into<Style>) -> Self {
        self.focus_style = Some(style.into());
        self
    }

    /// Style when clicked but not released.
    #[inline]
    pub fn armed_style(mut self, style: impl Into<Style>) -> Self {
        self.armed_style = Some(style.into());
        self
    }

    /// Some terminals repaint too fast to see the click.
    /// This adds some delay when the button state goes from
    /// armed to clicked.
    pub fn armed_delay(mut self, delay: Duration) -> Self {
        self.armed_delay = Some(delay);
        self
    }

    /// Style for hover over the button.
    pub fn hover_style(mut self, style: impl Into<Style>) -> Self {
        self.hover_style = Some(style.into());
        self
    }

    /// Button text.
    #[inline]
    pub fn text(mut self, text: impl Into<Text<'a>>) -> Self {
        self.text = text.into().centered();
        self
    }

    /// Left align button text.
    pub fn left_aligned(mut self) -> Self {
        self.text = self.text.left_aligned();
        self
    }

    /// Right align button text.
    pub fn right_aligned(mut self) -> Self {
        self.text = self.text.right_aligned();
        self
    }

    /// Block.
    #[inline]
    pub fn block(mut self, block: Block<'a>) -> Self {
        self.block = Some(block);
        self.block = self.block.map(|v| v.style(self.style));
        self
    }

    /// Inherent width.
    pub fn width(&self) -> u16 {
        self.text.width() as u16 + block_size(&self.block).width
    }

    /// Inherent height.
    pub fn height(&self) -> u16 {
        self.text.height() as u16 + block_size(&self.block).height
    }
}

#[cfg(feature = "unstable-widget-ref")]
impl<'a> StatefulWidgetRef for Button<'a> {
    type State = ButtonState;

    fn render_ref(&self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
        render_ref(self, area, buf, state);
    }
}

impl StatefulWidget for Button<'_> {
    type State = ButtonState;

    fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
        render_ref(&self, area, buf, state);
    }
}

fn render_ref(widget: &Button<'_>, area: Rect, buf: &mut Buffer, state: &mut ButtonState) {
    state.area = area;
    state.inner = widget.block.inner_if_some(area);
    state.armed_delay = widget.armed_delay;
    state.hover_enabled = widget.hover_style.is_some();

    let style = widget.style;
    let focus_style = if let Some(focus_style) = widget.focus_style {
        focus_style
    } else {
        revert_style(style)
    };
    let armed_style = if let Some(armed_style) = widget.armed_style {
        armed_style
    } else {
        if state.is_focused() {
            revert_style(focus_style)
        } else {
            revert_style(style)
        }
    };

    if widget.block.is_some() {
        widget.block.render(area, buf);
    } else {
        buf.set_style(area, style);
    }

    if state.mouse.hover.get() && widget.hover_style.is_some() {
        buf.set_style(state.inner, widget.hover_style.expect("style"))
    } else if state.is_focused() {
        buf.set_style(state.inner, focus_style);
    }

    if state.armed {
        let armed_area = Rect::new(
            state.inner.x + 1,
            state.inner.y,
            state.inner.width.saturating_sub(2),
            state.inner.height,
        );
        buf.set_style(armed_area, style.patch(armed_style));
    }

    let h = widget.text.height() as u16;
    let r = state.inner.height.saturating_sub(h) / 2;
    let area = Rect::new(state.inner.x, state.inner.y + r, state.inner.width, h);
    (&widget.text).render(area, buf);
}

impl Clone for ButtonState {
    fn clone(&self) -> Self {
        Self {
            area: self.area,
            inner: self.inner,
            hover_enabled: false,
            armed: self.armed,
            armed_delay: self.armed_delay,
            focus: FocusFlag::named(self.focus.name()),
            mouse: Default::default(),
            non_exhaustive: NonExhaustive,
        }
    }
}

impl Default for ButtonState {
    fn default() -> Self {
        Self {
            area: Default::default(),
            inner: Default::default(),
            hover_enabled: false,
            armed: false,
            armed_delay: None,
            focus: Default::default(),
            mouse: Default::default(),
            non_exhaustive: NonExhaustive,
        }
    }
}

impl ButtonState {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn named(name: &str) -> Self {
        Self {
            focus: FocusFlag::named(name),
            ..Default::default()
        }
    }
}

impl HasFocus for ButtonState {
    fn build(&self, builder: &mut FocusBuilder) {
        builder.leaf_widget(self);
    }

    #[inline]
    fn focus(&self) -> FocusFlag {
        self.focus.clone()
    }

    #[inline]
    fn area(&self) -> Rect {
        self.area
    }
}

impl RelocatableState for ButtonState {
    fn relocate(&mut self, shift: (i16, i16), clip: Rect) {
        self.area = relocate_area(self.area, shift, clip);
        self.inner = relocate_area(self.inner, shift, clip);
    }
}

pub(crate) mod event {
    use rat_event::{ConsumedEvent, Outcome};

    /// Result value for event-handling.
    ///
    /// Adds `Pressed` to the general Outcome.
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub enum ButtonOutcome {
        /// The given event was not handled at all.
        Continue,
        /// The event was handled, no repaint necessary.
        Unchanged,
        /// The event was handled, repaint necessary.
        Changed,
        /// Button has been pressed.
        Pressed,
    }

    impl ConsumedEvent for ButtonOutcome {
        fn is_consumed(&self) -> bool {
            *self != ButtonOutcome::Continue
        }
    }

    impl From<ButtonOutcome> for Outcome {
        fn from(value: ButtonOutcome) -> Self {
            match value {
                ButtonOutcome::Continue => Outcome::Continue,
                ButtonOutcome::Unchanged => Outcome::Unchanged,
                ButtonOutcome::Changed => Outcome::Changed,
                ButtonOutcome::Pressed => Outcome::Changed,
            }
        }
    }
}

impl HandleEvent<crossterm::event::Event, Regular, ButtonOutcome> for ButtonState {
    fn handle(&mut self, event: &crossterm::event::Event, _keymap: Regular) -> ButtonOutcome {
        let r = if self.is_focused() {
            // Release keys may not be available.
            if have_keyboard_enhancement() {
                match event {
                    ct_event!(keycode press Enter) | ct_event!(key press ' ') => {
                        self.armed = true;
                        ButtonOutcome::Changed
                    }
                    ct_event!(keycode release Enter) | ct_event!(key release ' ') => {
                        if self.armed {
                            if let Some(delay) = self.armed_delay {
                                thread::sleep(delay);
                            }
                            self.armed = false;
                            ButtonOutcome::Pressed
                        } else {
                            // single key release happen more often than not.
                            ButtonOutcome::Unchanged
                        }
                    }
                    _ => ButtonOutcome::Continue,
                }
            } else {
                match event {
                    ct_event!(keycode press Enter) | ct_event!(key press ' ') => {
                        ButtonOutcome::Pressed
                    }
                    _ => ButtonOutcome::Continue,
                }
            }
        } else {
            ButtonOutcome::Continue
        };

        if r == ButtonOutcome::Continue {
            HandleEvent::handle(self, event, MouseOnly)
        } else {
            r
        }
    }
}

impl HandleEvent<crossterm::event::Event, MouseOnly, ButtonOutcome> for ButtonState {
    fn handle(&mut self, event: &crossterm::event::Event, _keymap: MouseOnly) -> ButtonOutcome {
        match event {
            ct_event!(mouse down Left for column, row) => {
                if self.area.contains((*column, *row).into()) {
                    self.armed = true;
                    ButtonOutcome::Changed
                } else {
                    ButtonOutcome::Continue
                }
            }
            ct_event!(mouse up Left for column, row) => {
                if self.area.contains((*column, *row).into()) {
                    if self.armed {
                        self.armed = false;
                        ButtonOutcome::Pressed
                    } else {
                        ButtonOutcome::Continue
                    }
                } else {
                    if self.armed {
                        self.armed = false;
                        ButtonOutcome::Changed
                    } else {
                        ButtonOutcome::Continue
                    }
                }
            }
            ct_event!(mouse any for m) if self.mouse.hover(self.area, m) => ButtonOutcome::Changed,
            _ => ButtonOutcome::Continue,
        }
    }
}

/// Check event-handling for this hot-key and do Regular key-events otherwise.
impl HandleEvent<crossterm::event::Event, crossterm::event::KeyEvent, ButtonOutcome>
    for ButtonState
{
    fn handle(
        &mut self,
        event: &crossterm::event::Event,
        hotkey: crossterm::event::KeyEvent,
    ) -> ButtonOutcome {
        use crossterm::event::Event;

        let r = match event {
            Event::Key(key) => {
                // Release keys may not be available.
                if have_keyboard_enhancement() {
                    if hotkey.code == key.code && hotkey.modifiers == key.modifiers {
                        if key.kind == crossterm::event::KeyEventKind::Press {
                            self.armed = true;
                            ButtonOutcome::Changed
                        } else if key.kind == crossterm::event::KeyEventKind::Release {
                            if self.armed {
                                if let Some(delay) = self.armed_delay {
                                    thread::sleep(delay);
                                }
                                self.armed = false;
                                ButtonOutcome::Pressed
                            } else {
                                // single key release happen more often than not.
                                ButtonOutcome::Unchanged
                            }
                        } else {
                            ButtonOutcome::Continue
                        }
                    } else {
                        ButtonOutcome::Continue
                    }
                } else {
                    if hotkey.code == key.code && hotkey.modifiers == key.modifiers {
                        if key.kind == crossterm::event::KeyEventKind::Press {
                            ButtonOutcome::Pressed
                        } else {
                            ButtonOutcome::Continue
                        }
                    } else {
                        ButtonOutcome::Continue
                    }
                }
            }
            _ => ButtonOutcome::Continue,
        };

        r.or_else(|| self.handle(event, Regular))
    }
}

/// Handle all events.
/// Text events are only processed if focus is true.
/// Mouse events are processed if they are in range.
pub fn handle_events(
    state: &mut ButtonState,
    focus: bool,
    event: &crossterm::event::Event,
) -> ButtonOutcome {
    state.focus.set(focus);
    HandleEvent::handle(state, event, Regular)
}

/// Handle only mouse-events.
pub fn handle_mouse_events(
    state: &mut ButtonState,
    event: &crossterm::event::Event,
) -> ButtonOutcome {
    HandleEvent::handle(state, event, MouseOnly)
}