1
//! The per-user theme keys `tui-theme`, `tui-theme-overrides` and `tui-colors`, and the five-key read.
2

            
3
use super::report_chart::{echoed, pending};
4
use crate::app::ui_config::READ;
5
use crate::app::{App, CliConfig};
6
use crate::draw::draw;
7
use crate::route::RouteCtx;
8
use crate::tabs::nms_eval::ConsoleEval;
9
use crate::test_support::dn_theme;
10
use ratatui::Terminal;
11
use ratatui::backend::TestBackend;
12
use ratatui::style::Color;
13
use rpc::{ScriptCtx, Session};
14
use server::lossless::seed;
15
use sqlx::PgPool;
16
use sqlx::types::Uuid;
17
use tvui::{ColorDepth, Role, Theme};
18

            
19
21
pub(super) fn attached() -> App {
20
21
    let mut app = crate::test_support::app();
21
21
    app.attach_console(ConsoleEval::recording().0);
22
21
    app
23
21
}
24

            
25
90
pub(super) fn reads(app: &App) -> Vec<i64> {
26
94
    pending(app, |ctx| matches!(ctx, RouteCtx::UiConfig { .. }))
27
90
}
28

            
29
439
pub(super) fn item(text: Option<&str>) -> String {
30
439
    match text {
31
43
        Some(text) => format!(r#""(:config-value \"{text}\")""#),
32
396
        None => r#""(:config-value nil)""#.to_string(),
33
    }
34
439
}
35

            
36
/// The reply to a read: the theme triple, then the keymap pair left unset.
37
11
fn wire(id: i64, items: [String; 3]) -> String {
38
11
    let unset = [item(None), item(None)];
39
11
    let items: Vec<_> = items.into_iter().chain(unset).collect();
40
11
    format!(r#"(:id {id} :value ({}))"#, items.join(" "))
41
11
}
42

            
43
/// Answers the one read with the preset, override and colour values.
44
8
fn answer(app: &mut App, [preset, overrides, colors]: [Option<&str>; 3]) {
45
8
    let [id] = reads(app)[..] else {
46
        panic!("one config read");
47
    };
48
8
    let items = [preset, overrides, colors].map(item);
49
8
    app.route_reply(id, &wire(id, items));
50
8
}
51

            
52
4
fn preset(name: &str) -> Theme {
53
4
    Theme::preset(name).expect("preset")
54
4
}
55

            
56
#[tokio::test]
57
1
async fn attaching_the_console_asks_for_the_five_keys_in_one_request() {
58
1
    let mut app = crate::test_support::app();
59
1
    let (eval, sent) = ConsoleEval::recording();
60
1
    app.attach_console(eval);
61
1
    assert_eq!(reads(&app).len(), 1);
62
1
    let echoed = echoed(&mut app, &sent).await;
63
1
    let keys = [
64
1
        "tui-theme",
65
1
        "tui-theme-overrides",
66
1
        "tui-colors",
67
1
        "tui-keymap",
68
1
        "tui-keymap-overrides",
69
1
    ];
70
1
    for key in keys {
71
5
        assert!(
72
5
            echoed.contains(&format!(r#"(get-config "{key}")"#)),
73
1
            "{echoed}"
74
1
        );
75
1
    }
76
1
}
77

            
78
#[tokio::test]
79
1
async fn the_replies_choose_preset_overrides_and_depth() {
80
1
    let mut app = attached();
81
1
    answer(
82
1
        &mut app,
83
1
        [Some("turbo"), Some("status = white on red"), Some("16")],
84
1
    );
85
1
    assert_eq!(app.theme.depth(), ColorDepth::Ansi16);
86
1
    let panel = app.theme.style(Role::Panel);
87
1
    assert_eq!(panel.fg, Some(Color::LightYellow));
88
1
    assert_eq!(panel.bg, Some(Color::Blue));
89

            
90
1
    let mut terminal = Terminal::new(TestBackend::new(80, 24)).expect("test terminal");
91
1
    terminal
92
1
        .draw(|frame| draw(frame, &app, &mut crate::hits::Hits::default()))
93
1
        .expect("draw");
94
1
    let cell = &terminal.backend().buffer()[(79, 23)];
95
1
    assert_eq!(cell.bg, Color::Red);
96
1
    assert_eq!(cell.fg, Color::White);
97
1
}
98

            
99
#[tokio::test]
100
1
async fn missing_keys_keep_the_defaults() {
101
1
    let mut app = attached();
102
1
    answer(&mut app, [None, None, None]);
103
1
    assert_eq!(app.theme.style(Role::Panel), dn_theme().style(Role::Panel));
104
1
    assert!(app.status.is_empty(), "{}", app.status);
105
1
}
106

            
107
#[tokio::test]
108
1
async fn auto_depth_is_the_depth_the_app_started_with() {
109
1
    let Ok(mut app) = App::new(Uuid::nil(), CliConfig::default(), ColorDepth::Indexed256) else {
110
        panic!("the default theme builds");
111
    };
112
1
    app.attach_console(ConsoleEval::recording().0);
113
1
    answer(&mut app, [None, None, Some("auto")]);
114
1
    assert_eq!(app.theme.depth(), ColorDepth::Indexed256);
115
1
}
116

            
117
#[tokio::test]
118
1
async fn command_line_choices_beat_the_config() {
119
1
    let cli = CliConfig {
120
1
        preset: Some("dn".to_string()),
121
1
        depth: Some(ColorDepth::Rgb),
122
1
        ..CliConfig::default()
123
1
    };
124
1
    let Ok(mut app) = App::new(Uuid::nil(), cli, ColorDepth::Ansi16) else {
125
        panic!("the command-line theme builds");
126
    };
127
1
    app.attach_console(ConsoleEval::recording().0);
128
1
    answer(&mut app, [Some("turbo"), None, Some("16")]);
129
1
    assert_eq!(app.theme.depth(), ColorDepth::Rgb);
130
1
    assert_eq!(
131
1
        app.theme.style(Role::Panel),
132
1
        preset("dn").style(Role::Panel)
133
1
    );
134
1
}
135

            
136
#[tokio::test]
137
1
async fn a_bad_override_keeps_the_preset_and_depth_and_shows_the_error() {
138
1
    let mut app = attached();
139
1
    answer(
140
1
        &mut app,
141
1
        [Some("turbo"), Some("status = pink on red"), Some("16")],
142
1
    );
143
1
    assert_eq!(app.status, "theme: line 1: unknown colour `pink`");
144
1
    assert_eq!(app.theme.depth(), ColorDepth::Ansi16);
145
1
    let turbo = preset("turbo").with_depth(ColorDepth::Ansi16);
146
1
    assert_eq!(app.theme.style(Role::Panel), turbo.style(Role::Panel));
147
1
    assert_eq!(app.theme.style(Role::Status), turbo.style(Role::Status));
148
1
}
149

            
150
#[tokio::test]
151
1
async fn an_unknown_preset_or_depth_shows_the_error() {
152
1
    let mut app = attached();
153
1
    answer(&mut app, [Some("bogus"), None, None]);
154
1
    assert_eq!(
155
1
        app.status,
156
1
        "theme: unknown preset `bogus`; known: dn, turbo"
157
    );
158

            
159
1
    let mut app = attached();
160
1
    answer(&mut app, [Some("turbo"), None, Some("8")]);
161
1
    assert_eq!(
162
1
        app.status,
163
1
        "theme: unknown colour depth `8`; known: rgb, 256, 16, auto"
164
    );
165
1
    assert_eq!(app.theme.depth(), dn_theme().depth());
166
1
    assert_eq!(
167
1
        app.theme.style(Role::Panel),
168
1
        preset("turbo").style(Role::Panel)
169
1
    );
170
1
}
171

            
172
#[tokio::test]
173
1
async fn a_bad_depth_in_config_is_ignored_when_the_command_line_sets_one() {
174
1
    let cli = CliConfig {
175
1
        depth: Some(ColorDepth::Ansi16),
176
1
        ..CliConfig::default()
177
1
    };
178
1
    let Ok(mut app) = App::new(Uuid::nil(), cli, ColorDepth::Rgb) else {
179
        panic!("the command-line theme builds");
180
    };
181
1
    app.attach_echo();
182
1
    app.read_ui_config();
183
1
    answer(&mut app, [None, None, Some("8")]);
184
1
    assert!(app.status.is_empty(), "{}", app.status);
185
1
    assert_eq!(app.theme.depth(), ColorDepth::Ansi16);
186
1
}
187

            
188
#[test]
189
1
fn a_bad_command_line_preset_is_an_error() {
190
1
    let cli = CliConfig {
191
1
        preset: Some("bogus".to_string()),
192
1
        ..CliConfig::default()
193
1
    };
194
1
    let built = App::new(Uuid::nil(), cli, ColorDepth::Rgb);
195
1
    assert_eq!(
196
1
        built.err().as_deref(),
197
1
        Some("unknown preset `bogus`; known: dn, turbo")
198
    );
199
1
}
200

            
201
#[tokio::test]
202
1
async fn a_stale_reply_is_ignored() {
203
1
    let mut app = attached();
204
1
    app.read_ui_config();
205
1
    let [old, new] = reads(&app)[..] else {
206
        panic!("two config reads");
207
    };
208
1
    let turbo = [Some("turbo"), None, None].map(item);
209
1
    app.route_reply(old, &wire(old, turbo));
210
1
    assert_eq!(app.theme.style(Role::Panel), dn_theme().style(Role::Panel));
211
1
    assert!(app.status.is_empty(), "{}", app.status);
212
1
    let current = [Some("turbo"), None, Some("16")].map(item);
213
1
    app.route_reply(new, &wire(new, current));
214
1
    assert_eq!(app.theme.depth(), ColorDepth::Ansi16);
215
1
}
216

            
217
#[tokio::test]
218
1
async fn a_read_error_is_shown_and_keeps_the_theme() {
219
1
    let mut app = attached();
220
1
    let [id] = reads(&app)[..] else {
221
        panic!("one config read");
222
    };
223
1
    app.route_reply(
224
1
        id,
225
1
        &format!(r#"(:id {id} :error (:code eval :message "boom"))"#),
226
1
    );
227
1
    assert_eq!(app.status, "config: wire error from server: [eval] boom");
228
1
    assert_eq!(app.theme.style(Role::Panel), dn_theme().style(Role::Panel));
229
1
}
230

            
231
#[tokio::test]
232
1
async fn a_non_text_value_is_shown_not_taken_as_unset() {
233
1
    let mut app = attached();
234
1
    let [id] = reads(&app)[..] else {
235
        panic!("one config read");
236
    };
237
1
    let items = [
238
1
        item(None),
239
1
        r#""(:config-value #u8(1 2))""#.to_string(),
240
1
        item(None),
241
1
    ];
242
1
    app.route_reply(id, &wire(id, items));
243
1
    assert_eq!(app.status, "config: the config value is not text");
244
1
}
245

            
246
#[sqlx::test(migrator = "server::db::MIGRATOR")]
247
async fn a_real_session_answers_the_config_read(pool: PgPool) -> anyhow::Result<()> {
248
    let _guard = server::db::install_test_pool(pool.clone());
249
    let fixture = seed(&pool).await?;
250
    let mut session = Session::new(ScriptCtx::new(fixture.user))?;
251
    let set = r#"(:id 1 :form (set-config "tui-theme" "turbo"))"#;
252
    session.handle_form(set).await;
253
    let set = r#"(:id 1 :form (set-config "tui-colors" "16"))"#;
254
    session.handle_form(set).await;
255
    let mut app = attached();
256
    let [id] = reads(&app)[..] else {
257
        anyhow::bail!("one config read");
258
    };
259
    let wire = session
260
        .handle_form(&format!("(:id {id} :form {READ})"))
261
        .await;
262
    app.route_reply(id, &wire);
263
    assert!(app.status.is_empty(), "{}", app.status);
264
    assert_eq!(app.theme.depth(), ColorDepth::Ansi16);
265
    assert_eq!(
266
        app.theme.style(Role::Panel).bg,
267
        preset("turbo")
268
            .with_depth(ColorDepth::Ansi16)
269
            .style(Role::Panel)
270
            .bg
271
    );
272
    Ok(())
273
}