1
//! The Options dialog: it shows the settings, previews them live and puts them back on Cancel.
2

            
3
use super::report_chart::{echoed, pending};
4
use super::ui_config::item;
5
use crate::app::{App, CliConfig};
6
use crate::event::{Intent, apply};
7
use crate::form::{Form, FormKind};
8
use crate::modal::Modal;
9
use crate::route::RouteCtx;
10
use crate::tabs::nms_eval::ConsoleEval;
11
use crate::tabs::nms_eval::double::Sent;
12
use crate::test_support::{draw_frame, key, press};
13
use ratatui::crossterm::event::KeyCode;
14
use sqlx::types::Uuid;
15
use tvui::{ColorDepth, Role, Theme};
16

            
17
61
pub(super) fn answer_config(app: &mut App, texts: [Option<&str>; 5]) {
18
61
    let [id] = super::ui_config::reads(app)[..] else {
19
        panic!("one config read");
20
    };
21
61
    let items = texts.map(item);
22
61
    app.route_reply(id, &format!(r#"(:id {id} :value ({}))"#, items.join(" ")));
23
61
}
24

            
25
1
pub(super) fn attached_blank() -> (App, Sent) {
26
1
    let Ok(mut app) = App::new(Uuid::nil(), CliConfig::default(), ColorDepth::Rgb) else {
27
        panic!("the app builds");
28
    };
29
1
    let (eval, sent) = ConsoleEval::recording();
30
1
    app.attach_console(eval);
31
1
    (app, sent)
32
1
}
33

            
34
31
pub(super) fn attached_with(cli: CliConfig, texts: [Option<&str>; 5]) -> (App, Sent) {
35
31
    let Ok(mut app) = App::new(Uuid::nil(), cli, ColorDepth::Rgb) else {
36
        panic!("the app builds");
37
    };
38
31
    let (eval, sent) = ConsoleEval::recording();
39
31
    app.attach_console(eval);
40
31
    answer_config(&mut app, texts);
41
31
    (app, sent)
42
31
}
43

            
44
23
pub(super) fn opened(texts: [Option<&str>; 5]) -> (App, Sent) {
45
23
    let (mut app, sent) = attached_with(CliConfig::default(), texts);
46
23
    apply(&mut app, Intent::OpenOptions);
47
23
    answer_config(&mut app, texts);
48
23
    (app, sent)
49
23
}
50

            
51
31
pub(super) fn dialog(app: &App) -> &Form {
52
31
    match app.overlays.top() {
53
31
        Some(Modal::Form(form)) if form.kind == FormKind::Options => form,
54
        other => panic!("the Options dialog is not on top: {other:?}"),
55
    }
56
31
}
57

            
58
20
pub(super) fn label<'a>(app: &'a App, field: &str) -> &'a str {
59
20
    dialog(app).select_label(field).unwrap_or_default()
60
20
}
61

            
62
/// Opens the focused select, moves `steps` options with `code` and confirms.
63
22
pub(super) fn choose(app: &mut App, code: KeyCode, steps: usize) {
64
22
    press(app, key(KeyCode::Enter));
65
22
    for _ in 0..steps {
66
26
        press(app, key(code));
67
    }
68
22
    press(app, key(KeyCode::Enter));
69
22
}
70

            
71
11
pub(super) fn next_field(app: &mut App) {
72
11
    press(app, key(KeyCode::Tab));
73
11
}
74

            
75
15
pub(super) fn saves(app: &App) -> Vec<i64> {
76
15
    pending(app, |ctx| matches!(ctx, RouteCtx::OptionsSave { .. }))
77
15
}
78

            
79
const UNSET: [Option<&str>; 5] = [None; 5];
80

            
81
9
fn desktop_bg(app: &App) -> ratatui::style::Color {
82
9
    draw_frame(app, 100, 30).0[(1, 2)].bg
83
9
}
84

            
85
#[tokio::test]
86
1
async fn the_menu_opens_the_dialog_with_the_current_values() {
87
1
    let (mut app, _) = attached_with(
88
1
        CliConfig::default(),
89
1
        [Some("turbo"), None, Some("256"), Some("emacs"), None],
90
1
    );
91
1
    app.open_menu_of(crate::app::MenuId::Options);
92
1
    assert_eq!(app.menu_choice(), Some(Intent::OpenOptions));
93
1
    apply(&mut app, Intent::MenuSelect);
94
1
    assert_eq!(label(&app, "theme"), "turbo");
95
1
    assert_eq!(label(&app, "keymap"), "emacs");
96
1
    assert_eq!(label(&app, "colors"), "256");
97
3
    let labels: Vec<_> = dialog(&app).buttons().iter().map(|b| b.0).collect();
98
1
    assert_eq!(labels, ["~O~K", "~C~ancel", "A~p~ply"]);
99
1
}
100

            
101
#[tokio::test]
102
1
async fn the_dialog_shows_what_the_server_holds_now() {
103
1
    let (mut app, _) = attached_with(CliConfig::default(), UNSET);
104
1
    apply(&mut app, Intent::OpenOptions);
105
1
    assert_eq!(label(&app, "theme"), "dn");
106
1
    answer_config(&mut app, [Some("turbo"), None, None, None, None]);
107
1
    assert_eq!(label(&app, "theme"), "turbo");
108
1
}
109

            
110
#[tokio::test]
111
1
async fn an_edit_made_before_the_open_read_replies_survives_it() {
112
1
    let (mut app, _) = attached_with(CliConfig::default(), UNSET);
113
1
    apply(&mut app, Intent::OpenOptions);
114
1
    choose(&mut app, KeyCode::Down, 1);
115
1
    let turbo = Theme::preset("turbo").expect("preset");
116
1
    assert_eq!(app.theme.bg(Role::Desktop), turbo.bg(Role::Desktop));
117
1
    answer_config(&mut app, UNSET);
118
1
    assert_eq!(label(&app, "theme"), "turbo");
119
1
    assert_eq!(app.theme.bg(Role::Desktop), turbo.bg(Role::Desktop));
120
1
}
121

            
122
#[tokio::test]
123
1
async fn the_open_read_merges_what_another_session_saved_with_the_edits() {
124
1
    let (mut app, sent) = attached_with(CliConfig::default(), UNSET);
125
1
    apply(&mut app, Intent::OpenOptions);
126
1
    choose(&mut app, KeyCode::Down, 1);
127
1
    answer_config(&mut app, [None, None, None, Some("emacs"), None]);
128
1
    assert_eq!(label(&app, "theme"), "turbo");
129
1
    assert_eq!(label(&app, "keymap"), "emacs");
130
1
    assert_eq!(app.keys.indicator(), "emacs");
131
1
    for _ in 0..5 {
132
5
        press(&mut app, key(KeyCode::Tab));
133
    }
134
1
    press(&mut app, key(KeyCode::Enter));
135
1
    echoed(&mut app, &sent).await;
136
1
    let save = sent.frames().pop().unwrap_or_default();
137
1
    assert!(
138
1
        save.contains("tui-theme") && save.contains("turbo"),
139
        "{save}"
140
    );
141
1
    assert!(!save.contains("tui-keymap"), "{save}");
142
1
}
143

            
144
#[tokio::test]
145
1
async fn a_command_line_choice_is_shown_as_set_by_its_flag() {
146
1
    let cli = CliConfig {
147
1
        preset: Some("turbo".to_string()),
148
1
        depth: Some(ColorDepth::Ansi16),
149
1
        keymap: Some("vim".to_string()),
150
1
    };
151
1
    let (mut app, _) = attached_with(cli, UNSET);
152
1
    apply(&mut app, Intent::OpenOptions);
153
1
    assert_eq!(label(&app, "theme"), "turbo (set by --theme)");
154
1
    assert_eq!(label(&app, "colors"), "16 (set by --colors)");
155
1
    assert_eq!(label(&app, "keymap"), "vim (set by --keymap)");
156
1
}
157

            
158
#[tokio::test]
159
1
async fn picking_a_theme_redraws_the_whole_ui_at_once() {
160
1
    let (mut app, _) = opened(UNSET);
161
1
    let before = desktop_bg(&app);
162
1
    choose(&mut app, KeyCode::Down, 1);
163
1
    assert_eq!(label(&app, "theme"), "turbo");
164
1
    let turbo = Theme::preset("turbo").expect("preset");
165
1
    assert_eq!(app.theme.bg(Role::Desktop), turbo.bg(Role::Desktop));
166
1
    assert_ne!(desktop_bg(&app), before);
167
1
    assert_eq!(desktop_bg(&app), turbo.bg(Role::Desktop));
168
1
}
169

            
170
#[tokio::test]
171
1
async fn picking_a_colour_depth_applies_it() {
172
1
    let (mut app, _) = opened(UNSET);
173
1
    next_field(&mut app);
174
1
    next_field(&mut app);
175
1
    choose(&mut app, KeyCode::Down, 1);
176
1
    assert_eq!(label(&app, "colors"), "rgb");
177
1
    assert_eq!(app.theme.depth(), ColorDepth::Rgb);
178
1
    choose(&mut app, KeyCode::Down, 2);
179
1
    assert_eq!(label(&app, "colors"), "16");
180
1
    assert_eq!(app.theme.depth(), ColorDepth::Ansi16);
181
1
}
182

            
183
/// Changes the theme and the keymap and returns the desktop background it had before.
184
2
fn change_two(app: &mut App) -> ratatui::style::Color {
185
2
    let before = desktop_bg(app);
186
2
    choose(app, KeyCode::Down, 1);
187
2
    next_field(app);
188
2
    choose(app, KeyCode::Down, 1);
189
2
    assert_ne!(desktop_bg(app), before);
190
2
    before
191
2
}
192

            
193
2
async fn assert_put_back(app: &mut App, sent: &Sent, before: ratatui::style::Color) {
194
2
    assert!(app.overlays.is_empty());
195
2
    assert_eq!(desktop_bg(app), before);
196
2
    assert_eq!(app.keys.indicator(), "cua");
197
2
    assert!(saves(app).is_empty());
198
2
    let echoed = echoed(app, sent).await;
199
2
    assert!(!echoed.contains("config-set"), "{echoed}");
200
2
}
201

            
202
#[tokio::test]
203
1
async fn esc_puts_everything_back_and_sends_nothing() {
204
1
    let (mut app, sent) = opened(UNSET);
205
1
    let before = change_two(&mut app);
206
1
    press(&mut app, key(KeyCode::Esc));
207
1
    assert_put_back(&mut app, &sent, before).await;
208
1
}
209

            
210
#[tokio::test]
211
1
async fn the_cancel_button_puts_everything_back_and_sends_nothing() {
212
1
    let (mut app, sent) = opened(UNSET);
213
1
    let before = change_two(&mut app);
214
1
    for _ in 0..5 {
215
5
        press(&mut app, key(KeyCode::Tab));
216
    }
217
1
    assert_eq!(app.overlays.top().and_then(Modal::focused_button), Some(1));
218
1
    press(&mut app, key(KeyCode::Enter));
219
1
    assert_put_back(&mut app, &sent, before).await;
220
1
}
221

            
222
#[tokio::test]
223
1
async fn the_dialog_draws_over_the_screen() {
224
1
    let (app, _) = opened(UNSET);
225
1
    let (buffer, _) = draw_frame(&app, 100, 30);
226
3000
    let text: String = buffer.content().iter().map(|cell| cell.symbol()).collect();
227
1
    for word in [
228
1
        "Options",
229
1
        "Theme",
230
1
        "Keymap",
231
1
        "Colours",
232
1
        "Cancel",
233
1
        "Apply",
234
1
        "applies once saved",
235
1
    ] {
236
7
        assert!(text.contains(word), "{word} is not drawn");
237
1
    }
238
1
}