summaryrefslogtreecommitdiffstats
path: root/src/app/widgets.rs
blob: 7ef2f4dd6fc62fecf0a50984713a52069ecf9b67 (plain)
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
use std::{fmt::Debug, time::Instant};

use crossterm::event::{KeyEvent, MouseEvent};
use enum_dispatch::enum_dispatch;
use tui::{backend::Backend, layout::Rect, Frame};

use crate::{
    app::event::{ComponentEventResult, SelectionAction},
    canvas::Painter,
    options::layout_options::LayoutRule,
};

mod tui_stuff;

pub mod base;
pub use base::*;

pub mod dialogs;
pub use dialogs::*;

pub mod bottom_widgets;
pub use bottom_widgets::*;

use self::tui_stuff::BlockBuilder;

use super::data_farmer::DataCollection;

/// A trait for things that are drawn with state.
#[enum_dispatch]
#[allow(unused_variables)]
pub trait Component {
    /// Handles a [`KeyEvent`].
    ///
    /// Defaults to returning [`ComponentEventResult::Unhandled`], indicating the component does not handle this event.
    fn handle_key_event(&mut self, event: KeyEvent) -> ComponentEventResult {
        ComponentEventResult::Unhandled
    }

    /// Handles a [`MouseEvent`].
    ///
    /// Defaults to returning [`ComponentEventResult::Unhandled`], indicating the component does not handle this event.
    fn handle_mouse_event(&mut self, event: MouseEvent) -> ComponentEventResult {
        ComponentEventResult::Unhandled
    }

    /// Returns a [`Component`]'s bounding box.  Note that these are defined in *global*, *absolute*
    /// coordinates.
    fn bounds(&self) -> Rect;

    /// Updates a [`Component`]'s bounding box to `new_bounds`.
    fn set_bounds(&mut self, new_bounds: Rect);

    /// Returns a [`Component`]'s bounding box, *including the border*. Defaults to just returning the normal bounds.
    ///   Note that these are defined in *global*, *absolute* coordinates.
    fn border_bounds(&self) -> Rect {
        self.bounds()
    }

    /// Updates a [`Component`]'s bounding box to `new_bounds`.  Defaults to just setting the normal bounds.
    fn set_border_bounds(&mut self, new_bounds: Rect) {
        self.set_bounds(new_bounds);
    }

    /// Returns whether a [`MouseEvent`] intersects a [`Component`]'s bounds.
    fn does_bounds_intersect_mouse(&self, event: &MouseEvent) -> bool {
        let x = event.column;
        let y = event.row;
        let bounds = self.bounds();

        does_bound_intersect_coordinate(x, y, bounds)
    }

    /// Returns whether a [`MouseEvent`] intersects a [`Component`]'s bounds, including any borders, if there are.
    fn does_border_intersect_mouse(&self, event: &MouseEvent) -> bool {
        let x = event.column;
        let y = event.row;
        let bounds = self.border_bounds();

        does_bound_intersect_coordinate(x, y, bounds)
    }
}

pub fn does_bound_intersect_coordinate(x: u16, y: u16, bounds: Rect) -> bool {
    x >= bounds.left() && x < bounds.right() && y >= bounds.top() && y < bounds.bottom()
}

/// A trait for actual fully-fledged widgets to be displayed in bottom.
#[enum_dispatch]
#[allow(unused_variables)]
pub trait Widget {
    /// Handles what to do when trying to respond to a widget selection movement to the left.
    /// Defaults to just moving to the next-possible widget in that direction.
    fn handle_widget_selection_left(&mut self) -> SelectionAction {
        SelectionAction::NotHandled
    }

    /// Handles what to do when trying to respond to a widget selection movement to the right.
    /// Defaults to just moving to the next-possible widget in that direction.
    fn handle_widget_selection_right(&mut self) -> SelectionAction {
        SelectionAction::NotHandled
    }

    /// Handles what to do when trying to respond to a widget selection movement upward.
    /// Defaults to just moving to the next-possible widget in that direction.
    fn handle_widget_selection_up(&mut self) -> SelectionAction {
        SelectionAction::NotHandled
    }

    /// Handles what to do when trying to respond to a widget selection movement downward.
    /// Defaults to just moving to the next-possible widget in that direction.
    fn handle_widget_selection_down(&mut self) -> SelectionAction {
        SelectionAction::NotHandled
    }

    /// Returns a [`Widget`]'s "pretty" display name.
    fn get_pretty_name(&self) -> &'static str;

    /// Returns a new [`BlockBuilder`], which can become a [`tui::widgets::Block`] if [`BlockBuilder::build`] is called.
    /// The default implementation builds a [`Block`] that has all 4 borders with no selection or expansion.
    fn block(&self) -> BlockBuilder {
        BlockBuilder::new(self.get_pretty_name())
    }

    /// Draws a [`Widget`]. The default implementation draws nothing.
    fn draw<B: Backend>(
        &mut self, painter: &Painter, f: &mut Frame<'_, B>, area: Rect, selected: bool,
        expanded: bool,
    ) {
    }

    /// How a [`Widget`] updates its internal data that'll be displayed. Called after every data harvest.
    /// The default implementation does nothing with the data.
    fn update_data(&mut self, data_collection: &DataCollection) {}

    /// Returns the desired width from the [`Widget`].
    fn width(&self) -> LayoutRule;

    /// Returns the desired height from the [`Widget`].
    fn height(&self) -> LayoutRule;

    /// Returns whether this [`Widget`] can be expanded. The default implementation returns `true`.
    fn expandable(&self) -> bool {
        true
    }

    /// Returns whether this [`Widget`] can be selected. The default implementation returns [`SelectableType::Selectable`].
    fn selectable_type(&self) -> SelectableType {
        SelectableType::Selectable
    }

    /// Resets state in a [`Widget`]; used when a reset signal is given. The default implementation does nothing.
    fn reset(&mut self) {}
}

/// Whether a widget can be selected, not selected, or redirected upon selection.
pub enum SelectableType {
    Selectable,
    Unselectable,
}

/// The "main" widgets that are used by bottom to display information!
#[allow(clippy::large_enum_variant)]
#[enum_dispatch(Component, Widget)]
pub enum TmpBottomWidget {
    MemGraph,
    TempTable,
    DiskTable,
    CpuGraph,
    NetGraph,
    OldNetGraph,
    ProcessManager,
    BatteryTable,
    BasicCpu,
    BasicMem,
    BasicNet,
    Carousel,
    Empty,
}

impl Debug for TmpBottomWidget {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::MemGraph(_) => write!(f, "MemGraph"),
            Self::TempTable(_) => write!(f, "TempTable"),
            Self::DiskTable(_) => write!(f, "DiskTable"),
            Self::CpuGraph(_) => write!(f, "CpuGraph"),
            Self::NetGraph(_) => write!(f, "NetGraph"),
            Self::OldNetGraph(_) => write!(f, "OldNetGraph"),
            Self::ProcessManager(_) => write!(f, "ProcessManager"),
            Self::BatteryTable(_) => write!(f, "BatteryTable"),
            Self::BasicCpu(_) => write!(f, "BasicCpu"),
            Self::BasicMem(_) => write!(f, "BasicMem"),
            Self::BasicNet(_) => write!(f, "BasicNet"),
            Self::Carousel(_) => write!(f, "Carousel"),
            Self::Empty(_) => write!(f, "Empty"),
        }
    }
}

/// The states a dialog can be in. Consists of either:
/// - [`DialogState::Hidden`] - the dialog is currently not showing.
/// - [`DialogState::Shown`] - the dialog is showing.
#[derive(Debug)]
pub enum DialogState<D: Default + Component> {
    Hidden,
    Shown(D),
}

impl<D> Default for DialogState<D>
where
    D: Default + Component,
{
    fn default() -> Self {
        DialogState::Hidden
    }
}

impl<D> DialogState<D>
where
    D: Default + Component,
{
    pub fn is_showing(&self) -> bool {
        matches!(self, DialogState::Shown(_))
    }

    pub fn hide(&mut self) {
        *self = DialogState::Hidden;
    }

    pub fn show(&mut self) {
        *self = DialogState::Shown(D::default());
    }
}

// ----- FIXME: Delete the old stuff below -----

#[derive(PartialEq)]
pub enum KillSignal {
    Cancel,
    Kill(usize),
}

impl Default for KillSignal {
    #[cfg(target_family = "unix")]
    fn default() -> Self {
        KillSignal::Kill(15)
    }
    #[cfg(target_os = "windows")]
    fn default() -> Self {
        KillSignal::Kill(1)
    }
}

#[derive(Default)]
pub struct AppDeleteDialogState {
    pub is_showing_dd: bool,
    pub selected_signal: KillSignal,
    /// tl x, tl y, br x, br y, index/signal
    pub button_positions: Vec<(u16, u16, u16, u16, usize)>,
    pub keyboard_signal_select: usize,
    pub last_number_press: Option<Instant>,
    pub scroll_pos: usize,
}