1
use crate::app::{App, CliConfig};
2
use crate::hits::Hits;
3
use crate::keymap::{Hint, Keys, handle_key};
4
use crate::modal::Modal;
5
use crate::tabs::config::ConfigTab;
6
use crate::tabs::list::ListTab;
7
use crate::tabs::nms::ConsoleState;
8
use crate::tabs::reports::ReportsTab;
9
use crate::tabs::scripts::ScriptsTab;
10
use crate::tabs::ssh_keys::SshKeysTab;
11
use crate::tabs::tags::TagsTab;
12
use crate::tabs::templates::TemplatesTab;
13
use crate::view::{DrawCtx, ViewId};
14
use crate::widgets::grid::{Grid, GridLine, Item};
15
use crate::window::{Origin, Pane};
16
use ratatui::Terminal;
17
use ratatui::backend::TestBackend;
18
use ratatui::buffer::Buffer;
19
use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
20
use sqlx::types::Uuid;
21
use tvui::{ColorDepth, Theme};
22

            
23
/// The status bar items of `app` as key and label.
24
49
pub(crate) fn hint_pairs(app: &App) -> Vec<(String, String)> {
25
49
    crate::keymap::hinted(app).iter().map(Hint::pair).collect()
26
49
}
27

            
28
/// Draws `app` once on a `width` by `height` terminal, so the windows record their views.
29
5
pub(crate) fn draw_once(app: &App, width: u16, height: u16) {
30
5
    draw_frame(app, width, height);
31
5
}
32

            
33
/// Draws `app` once and returns the screen and the areas the frame recorded.
34
691
pub(crate) fn draw_frame(app: &App, width: u16, height: u16) -> (Buffer, Hits) {
35
691
    let mut terminal = Terminal::new(TestBackend::new(width, height)).expect("test terminal");
36
691
    let mut hits = Hits::default();
37
691
    terminal
38
691
        .draw(|frame| crate::draw::draw(frame, app, &mut hits))
39
691
        .expect("the frame draws");
40
691
    (terminal.backend().buffer().clone(), hits)
41
691
}
42

            
43
/// Draws `app` on a `width` by `height` terminal and keeps the areas for the mouse.
44
569
pub(crate) fn draw_into(app: &mut App, width: u16, height: u16) {
45
569
    app.hits = draw_frame(app, width, height).1;
46
569
}
47

            
48
/// Draws `app` on an 80 by 24 terminal and keeps the areas for the mouse.
49
487
pub(crate) fn redraw(app: &mut App) {
50
487
    draw_into(app, 80, 24);
51
487
}
52

            
53
/// The area the last frame drew for `target`; the test fails when it was not drawn.
54
338
pub(crate) fn area_of(app: &App, target: crate::hits::Target) -> ratatui::layout::Rect {
55
5257
    match app.hits.entries().iter().find(|(_, t)| *t == target) {
56
338
        Some((rect, _)) => *rect,
57
        None => panic!("{target:?} was not drawn"),
58
    }
59
338
}
60

            
61
/// The items of cell line `line` of `grid`.
62
19
pub(crate) fn cells<'a>(grid: &'a Grid<'a>, line: usize) -> &'a [Item<'a>] {
63
19
    match grid.lines.get(line) {
64
19
        Some(GridLine::Cells { items, .. }) => items,
65
        _ => &[],
66
    }
67
19
}
68

            
69
/// How many conversion arrows cell line `line` of `grid` has.
70
9
pub(crate) fn arrows(grid: &Grid<'_>, line: usize) -> usize {
71
9
    cells(grid, line)
72
9
        .iter()
73
90
        .filter(|item| item.text == "\u{2192}")
74
        .count()
75
9
}
76

            
77
1508
pub(crate) fn dn_theme() -> Theme {
78
1508
    Theme::preset(tvui::DEFAULT_PRESET).expect("the dn preset parses")
79
1508
}
80

            
81
74
pub(crate) fn draw_ctx<'a>(theme: &'a Theme, hits: &'a mut Hits) -> DrawCtx<'a> {
82
74
    DrawCtx {
83
74
        is_active: false,
84
74
        frame: tvui::FrameState {
85
74
            mode: tvui::FrameMode::Active,
86
74
            ..tvui::FrameState::default()
87
74
        },
88
74
        title: String::new(),
89
74
        theme,
90
74
        hits,
91
74
    }
92
74
}
93

            
94
/// An app on an empty desktop, as it starts.
95
2041
pub(crate) fn empty_app_for(user_id: Uuid) -> App {
96
2041
    match App::new(user_id, CliConfig::default(), ColorDepth::Rgb) {
97
2041
        Ok(app) => app,
98
        Err(err) => panic!("the default theme builds: {err}"),
99
    }
100
2041
}
101

            
102
12
pub(crate) fn empty_app() -> App {
103
12
    empty_app_for(Uuid::new_v4())
104
12
}
105

            
106
/// An app with a window of every view.
107
2029
pub(crate) fn app_for(user_id: Uuid) -> App {
108
2029
    let mut app = empty_app_for(user_id);
109
2029
    app.open_every_view();
110
2029
    app
111
2029
}
112

            
113
1995
pub(crate) fn app() -> App {
114
1995
    app_for(Uuid::new_v4())
115
1995
}
116

            
117
344
pub(crate) fn app_with_preset(name: &str) -> App {
118
344
    let mut app = app();
119
344
    app.keys = match Keys::preset(name) {
120
344
        Ok(keys) => keys,
121
        Err(err) => panic!("the {name} preset parses: {err}"),
122
    };
123
344
    app
124
344
}
125

            
126
126
pub(crate) fn emacs_app() -> App {
127
126
    app_with_preset("emacs")
128
126
}
129

            
130
132
pub(crate) fn vim_app() -> App {
131
132
    app_with_preset("vim")
132
132
}
133

            
134
2613
pub(crate) fn key(code: KeyCode) -> KeyEvent {
135
2613
    KeyEvent::new(code, KeyModifiers::NONE)
136
2613
}
137

            
138
170
pub(crate) fn ctrl(code: KeyCode) -> KeyEvent {
139
170
    KeyEvent::new(code, KeyModifiers::CONTROL)
140
170
}
141

            
142
99
pub(crate) fn alt(code: KeyCode) -> KeyEvent {
143
99
    KeyEvent::new(code, KeyModifiers::ALT)
144
99
}
145

            
146
/// Translate then apply, the way the runtime handles a key event.
147
2960
pub(crate) fn press(app: &mut App, event: KeyEvent) {
148
2960
    handle_key(app, event);
149
2960
    app.flush_key_press();
150
2960
}
151

            
152
macro_rules! test_panes {
153
    ($($get:ident $(, $get_mut:ident)?: $ty:ty = $kind:expr;)*) => {
154
        impl App {
155
            $(
156
338
                pub(crate) fn $get(&self) -> &$ty {
157
338
                    self.recent::<$ty>($kind).expect(stringify!($ty))
158
338
                }
159

            
160
                $(
161
305
                    pub(crate) fn $get_mut(&mut self) -> &mut $ty {
162
305
                        self.recent_mut::<$ty>($kind).expect(stringify!($ty))
163
305
                    }
164
                )?
165
            )*
166
        }
167
    };
168
}
169

            
170
test_panes! {
171
    reports, reports_mut: ReportsTab = ViewId::Reports;
172
    config, config_mut: ConfigTab = ViewId::Config;
173
    ssh_keys: SshKeysTab = ViewId::SshKeys;
174
    tags: TagsTab = ViewId::Tags;
175
    templates: TemplatesTab = ViewId::Templates;
176
    scripts, scripts_mut: ScriptsTab = ViewId::Scripts;
177
    console, console_mut: ConsoleState = ViewId::Console;
178
}
179

            
180
/// The title of the front window, which must be a viewer.
181
6
pub(crate) fn viewer_title(app: &App) -> String {
182
6
    match app.front::<crate::viewer::Viewer>() {
183
6
        Some(viewer) => viewer.title(),
184
        None => panic!("the front window is not a viewer"),
185
    }
186
6
}
187

            
188
/// Whether a Help window is the front window.
189
11
pub(crate) fn help_open(app: &App) -> bool {
190
11
    app.front::<crate::viewer::Viewer>()
191
11
        .is_some_and(|viewer| matches!(viewer.source, crate::viewer::Source::Help { .. }))
192
11
}
193

            
194
/// Pushes a read-only draft dialog, for what only the `modal-view` scope does.
195
11
pub(crate) fn open_draft(app: &mut App) {
196
660
    let lines = (0..60).map(|n| format!("line {n}")).collect();
197
11
    app.overlays
198
11
        .push(Modal::Draft(crate::modal::Draft::new(lines)));
199
11
}
200

            
201
/// Pushes a confirmation, the generic modal fixture.
202
19
pub(crate) fn open_overlay(app: &mut App) {
203
19
    let modal = Modal::confirm("Sure?", crate::modal::ConfirmAction::DiscardForm);
204
19
    app.overlays.push(modal);
205
19
}
206

            
207
impl App {
208
    /// Opens `modal` as a dialog of the front window, without loading it.
209
123
    pub(crate) fn open_dialog_on_front(&mut self, modal: Modal) {
210
123
        let window = self.front_window();
211
123
        let origin = window.and_then(|window| {
212
123
            let kind = self.window_view(window)?;
213
123
            Some(Origin { window, kind })
214
123
        });
215
123
        self.overlays.set_origin(origin);
216
123
        self.overlays.push(modal);
217
123
    }
218

            
219
    /// The `T` of the front-most window of `kind`.
220
654
    fn recent<T: Pane>(&self, kind: ViewId) -> Option<&T> {
221
654
        self.win::<T>(self.window_id(kind)?)
222
654
    }
223

            
224
575
    fn recent_mut<T: Pane>(&mut self, kind: ViewId) -> Option<&mut T> {
225
575
        let id = self.window_id(kind)?;
226
575
        self.win_mut::<T>(id)
227
575
    }
228

            
229
171
    pub(crate) fn accounts(&self) -> &ListTab {
230
171
        self.recent(ViewId::Accounts).expect("Accounts")
231
171
    }
232

            
233
194
    pub(crate) fn accounts_mut(&mut self) -> &mut ListTab {
234
194
        self.recent_mut(ViewId::Accounts).expect("Accounts")
235
194
    }
236

            
237
140
    pub(crate) fn transactions(&self) -> &ListTab {
238
140
        self.recent(ViewId::Transactions).expect("Transactions")
239
140
    }
240

            
241
63
    pub(crate) fn transactions_mut(&mut self) -> &mut ListTab {
242
63
        self.recent_mut(ViewId::Transactions).expect("Transactions")
243
63
    }
244

            
245
5
    pub(crate) fn commodities(&self) -> &ListTab {
246
5
        self.recent(ViewId::Commodities).expect("Commodities")
247
5
    }
248

            
249
13
    pub(crate) fn commodities_mut(&mut self) -> &mut ListTab {
250
13
        self.recent_mut(ViewId::Commodities).expect("Commodities")
251
13
    }
252
}
253

            
254
/// The cells of a `place` that sits at a non-negative origin.
255
72
pub fn flat(place: tvui::Place) -> ratatui::layout::Rect {
256
144
    let cell = |value: i32| u16::try_from(value).unwrap_or_default();
257
72
    ratatui::layout::Rect::new(cell(place.x), cell(place.y), place.width, place.height)
258
72
}