1
//! The windows of the app and the lookups over them.
2

            
3
use forms::FormValues;
4

            
5
use super::App;
6
use crate::draw::body_area;
7
use crate::modal::Modal;
8
use crate::tabs::config::ConfigTab;
9
use crate::tabs::list::ListTab;
10
use crate::tabs::nms::ConsoleState;
11
use crate::tabs::reports::chart::TerminalEnv;
12
use crate::tabs::reports::{ReportKind, ReportsTab};
13
use crate::tabs::scripts::ScriptsTab;
14
use crate::tabs::seq::Seq;
15
use crate::tabs::ssh_keys::SshKeysTab;
16
use crate::tabs::tags::TagsTab;
17
use crate::tabs::templates::TemplatesTab;
18
use crate::view::ViewId;
19
use crate::viewer::{Source, Viewer};
20
use crate::window::{Origin, Pane, Placement, View, Win, WindowId};
21
use cli_core::render::schema;
22
use ratatui::layout::Rect;
23
use tvui::{Caps, FrameMode, FrameState, Place};
24

            
25
/// The part of a terminal of `env` the windows sit on.
26
1176
pub(super) fn desktop_area(env: TerminalEnv) -> Rect {
27
1176
    body_area(Rect::new(0, 0, env.screen.width, env.screen.height))
28
1176
}
29

            
30
/// A fresh view of `kind`.
31
20579
pub(super) fn new_view(kind: ViewId) -> View {
32
20579
    match kind {
33
2100
        ViewId::Accounts => View::List(
34
2100
            kind,
35
2100
            ListTab::new("(list-accounts)", &schema::ACCOUNTS).with_balance_column(),
36
2100
        ),
37
2051
        ViewId::Transactions => View::List(kind, ListTab::paged()),
38
2033
        ViewId::Commodities => View::List(
39
2033
            kind,
40
2033
            ListTab::new("(list-commodities)", &schema::COMMODITIES),
41
2033
        ),
42
2051
        ViewId::Reports => View::Reports(ReportsTab::new()),
43
2039
        ViewId::Config => View::Config(ConfigTab::new()),
44
2035
        ViewId::SshKeys => View::SshKeys(SshKeysTab::new()),
45
2120
        ViewId::Tags => View::Tags(TagsTab::new()),
46
2035
        ViewId::Templates => View::Templates(TemplatesTab::new()),
47
2037
        ViewId::Scripts => View::Scripts(ScriptsTab::new()),
48
2078
        ViewId::Console => View::Console(ConsoleState::new()),
49
        ViewId::Viewer => View::Viewer(Viewer::new(
50
            Source::Detail { id: String::new() },
51
            Vec::new(),
52
        )),
53
    }
54
20579
}
55

            
56
impl App {
57
    /// Opens `view` on top at `placement` with `number`; the only way a window appears.
58
20687
    pub(super) fn open_window(
59
20687
        &mut self,
60
20687
        view: View,
61
20687
        placement: Placement,
62
20687
        number: Option<u8>,
63
20687
    ) -> WindowId {
64
20687
        self.leave_front();
65
20687
        let id = WindowId(self.next_window);
66
20687
        self.next_window = self.next_window.saturating_add(1);
67
20687
        let ordinal = self.next_ordinal(view.kind());
68
20687
        let caps = view.caps();
69
20687
        self.windows.push(Win {
70
20687
            id,
71
20687
            view,
72
20687
            number,
73
20687
            ordinal,
74
20687
            report_seq: Seq::default(),
75
20687
        });
76
20687
        self.desktop.open(id, placement.rect, caps);
77
20687
        if placement.zoomed {
78
20598
            self.desktop.toggle_zoom(id);
79
89
        }
80
20687
        id
81
20687
    }
82

            
83
    /// Closes window `id`, settling what it has in flight; the only way a window goes.
84
686
    pub(crate) fn close_window(&mut self, id: WindowId) {
85
686
        if self.win_by(id).is_none() {
86
1
            return;
87
685
        }
88
685
        if self.dragged() == Some(id) {
89
1
            self.hold = None;
90
684
        }
91
685
        self.settle_window(id);
92
685
        self.close_console_stream(id);
93
685
        self.delete_image(id);
94
685
        let uncovers = self.drawn_ids().contains(&id);
95
4172
        self.windows.retain(|win| win.id != id);
96
685
        self.desktop.close(id);
97
685
        if uncovers {
98
183
            self.load_visible();
99
502
        }
100
686
    }
101

            
102
    /// Closes the front window.
103
110
    pub(crate) fn close_front_window(&mut self) {
104
110
        if let Some(id) = self.front_window() {
105
110
            self.close_window(id);
106
        }
107
110
    }
108

            
109
    /// Brings window `id` to the front; the only way a window is raised.
110
3342
    pub(super) fn raise_window(&mut self, id: WindowId) {
111
3342
        if self.front_window() == Some(id) {
112
530
            return;
113
2812
        }
114
2812
        self.leave_front();
115
2812
        self.desktop.raise(id);
116
3342
    }
117

            
118
    /// Brings the rearmost window to the front.
119
20
    pub(crate) fn next_window(&mut self) {
120
20
        if let Some(id) = self.desktop.rearmost() {
121
20
            self.activate_window(id);
122
        }
123
20
    }
124

            
125
    /// Sends the front window to the back; the one behind it comes to the front.
126
7
    pub(crate) fn prev_window(&mut self) {
127
7
        let Some(id) = self
128
7
            .front_window()
129
7
            .filter(|id| self.desktop.rearmost() != Some(*id))
130
        else {
131
2
            return;
132
        };
133
5
        self.leave_front();
134
5
        self.desktop.lower(id);
135
5
        self.clear_status();
136
5
        self.load_visible();
137
7
    }
138

            
139
    /// Zooms the front window to the desktop or restores it; what it uncovers is loaded and a
140
    /// chart of the new size is fetched.
141
34
    pub(crate) fn toggle_zoom(&mut self) {
142
34
        let Some(id) = self.front_window() else {
143
            return;
144
        };
145
34
        if self.desktop.toggle_zoom(id) {
146
33
            self.window_resized(id);
147
33
            self.load_visible();
148
1
        }
149
34
    }
150

            
151
    /// The front-most window of `kind`, or a new one that is loaded.
152
1042
    pub(crate) fn window_or_open(&mut self, kind: ViewId) -> Origin {
153
1042
        let window = self.window_id(kind).unwrap_or_else(|| {
154
32
            let window = self.open_new_window(new_view(kind));
155
32
            self.load_window(window);
156
32
            window
157
32
        });
158
1042
        Origin { window, kind }
159
1042
    }
160

            
161
    /// Says that there is no window of `kind`, or no window at all, to act on.
162
23
    pub(crate) fn say_no_window(&mut self, kind: Option<ViewId>) {
163
23
        match kind {
164
10
            Some(kind) => self.set_status(format!("no {} window", kind.label())),
165
13
            None => self.set_status("no window"),
166
        }
167
23
    }
168

            
169
    /// The front window when it shows `kind`; says so otherwise.
170
197
    pub(crate) fn front_or_say(&mut self, kind: ViewId) -> Option<WindowId> {
171
197
        let window = self.front_window().filter(|_| self.front_is(kind));
172
197
        if window.is_none() {
173
7
            self.say_no_window(Some(kind));
174
190
        }
175
197
        window
176
197
    }
177

            
178
    /// Brings window `id` to the front, clears the status and loads it, as choosing it does.
179
1012
    pub(crate) fn activate_window(&mut self, id: WindowId) {
180
1012
        self.raise_window(id);
181
1012
        self.clear_status();
182
1012
        self.load_visible();
183
1012
    }
184

            
185
    /// The windows drawn on the desktop; with no terminal geometry yet only the front one is
186
    /// known to be.
187
1952
    fn drawn_ids(&self) -> Vec<WindowId> {
188
1952
        match self.terminal.env() {
189
            Some(env) => {
190
655
                let windows = self.visible_windows(desktop_area(env));
191
655
                windows.into_iter().map(|(id, ..)| id).collect()
192
            }
193
1297
            None => self.front_window().into_iter().collect(),
194
        }
195
1952
    }
196

            
197
    /// Loads every drawn window that has not been loaded.
198
1267
    pub(super) fn load_visible(&mut self) {
199
1267
        for id in self.drawn_ids() {
200
1280
            self.load_window(id);
201
        }
202
1267
    }
203

            
204
    /// Shows window `id` unless a dialog is open or awaiting its reply.
205
45
    pub(crate) fn show_window_if_free(&mut self, id: WindowId) {
206
45
        if self.pending_form.is_none() && self.overlays.is_empty() {
207
42
            self.activate_window(id);
208
3
        }
209
45
    }
210

            
211
    /// The window `id` and what it shows, or `None` once it is gone.
212
88
    pub(super) fn origin_of(&self, id: WindowId) -> Option<Origin> {
213
88
        let kind = self.window_view(id)?;
214
88
        Some(Origin { window: id, kind })
215
88
    }
216

            
217
    /// The window of `origin`; says so when it has closed.
218
447
    pub(super) fn origin_window(&mut self, origin: Origin) -> Option<WindowId> {
219
447
        if self.window_view(origin.window).is_some() {
220
444
            return Some(origin.window);
221
3
        }
222
3
        let message = match origin.kind {
223
1
            ViewId::Viewer => "the window was closed".to_string(),
224
2
            kind => format!("the {} window was closed", kind.label()),
225
        };
226
3
        self.set_status(message);
227
3
        None
228
447
    }
229

            
230
    /// Raises the window of `origin` and makes the next dialog belong to it.
231
273
    pub(super) fn begin_dialog(&mut self, origin: Origin) -> bool {
232
273
        let Some(window) = self.origin_window(origin) else {
233
1
            return false;
234
        };
235
272
        self.raise_and_load(window);
236
272
        self.overlays.set_origin(Some(origin));
237
272
        true
238
273
    }
239

            
240
    /// Raises `window` and loads it if it has not been.
241
279
    fn raise_and_load(&mut self, window: WindowId) {
242
279
        self.raise_window(window);
243
279
        self.load_window(window);
244
279
    }
245

            
246
    /// Raises the front-most window of `kind`; says so when there is none.
247
8
    pub(crate) fn raise_kind(&mut self, kind: ViewId) -> bool {
248
8
        let Some(window) = self.window_id(kind) else {
249
1
            self.say_no_window(Some(kind));
250
1
            return false;
251
        };
252
7
        self.raise_and_load(window);
253
7
        true
254
8
    }
255

            
256
    /// `begin_dialog` for the window a reply was routed to.
257
62
    pub(super) fn begin_dialog_of(&mut self, target: Option<WindowId>) -> bool {
258
62
        match target.and_then(|id| self.origin_of(id)) {
259
62
            Some(origin) => self.begin_dialog(origin),
260
            None => {
261
                self.say_no_window(None);
262
                false
263
            }
264
        }
265
62
    }
266

            
267
    /// Opens `modal` as a dialog of `origin`; `false` when its window has closed.
268
211
    pub(super) fn open_dialog_at(&mut self, origin: Origin, modal: Modal) -> bool {
269
211
        let opened = self.begin_dialog(origin);
270
211
        if opened {
271
210
            self.overlays.push(modal);
272
1
        }
273
211
        opened
274
211
    }
275

            
276
    /// Opens `modal` as a dialog of window `id`.
277
23
    pub(super) fn open_dialog_in(&mut self, id: WindowId, modal: Modal) {
278
23
        if let Some(origin) = self.origin_of(id) {
279
23
            self.open_dialog_at(origin, modal);
280
        }
281
23
    }
282

            
283
    /// Opens `modal` as a dialog of the front-most window of `kind`, or of a new one.
284
107
    pub(crate) fn open_dialog_for(&mut self, kind: ViewId, modal: Modal) {
285
107
        let origin = self.window_or_open(kind);
286
107
        self.open_dialog_at(origin, modal);
287
107
    }
288

            
289
    /// The window the open dialog started from; says so when there is none.
290
160
    pub(crate) fn dialog_origin(&mut self) -> Option<Origin> {
291
160
        let origin = self.overlays.origin();
292
160
        if origin.is_none() {
293
8
            self.say_no_window(None);
294
152
        }
295
160
        origin
296
160
    }
297

            
298
    /// The window the open dialog belongs to; says so when it has closed or there is none.
299
155
    pub(crate) fn dialog_window(&mut self) -> Option<WindowId> {
300
155
        let origin = self.dialog_origin()?;
301
147
        self.origin_window(origin)
302
155
    }
303

            
304
    /// What ends when another window takes the front: the kitty image, which only the front
305
    /// window draws. A console keeps its own prompt focus.
306
23504
    fn leave_front(&mut self) {
307
23504
        if let Some(front) = self.front_window() {
308
21399
            self.delete_image(front);
309
2105
        }
310
23504
    }
311

            
312
    /// Queues the deletion of the kitty image window `id` shows, if any; the chart transmits
313
    /// again when it is next drawn.
314
22268
    pub(super) fn delete_image(&mut self, id: WindowId) {
315
22268
        self.queue_image_delete(id, self.terminal.env());
316
22268
    }
317

            
318
    /// As `delete_image`; with no `env` the picture is not rebuilt, for a chart fetched again.
319
22269
    pub(super) fn queue_image_delete(&mut self, id: WindowId, env: Option<TerminalEnv>) {
320
22269
        let reports = self.win_mut::<ReportsTab>(id);
321
22269
        let image = reports.and_then(|reports| reports.chart.forget_kitty(env));
322
22269
        if let Some(image) = image {
323
15
            self.outbound.push(tvui::kitty_delete(image));
324
22254
        }
325
22269
    }
326

            
327
    /// The windows front to back.
328
58199
    fn front_to_back(&self) -> impl Iterator<Item = &Win> {
329
58199
        let order = self.desktop.iter_back_to_front().rev();
330
90173
        order.filter_map(|slot| self.win_by(slot.id))
331
58199
    }
332

            
333
    /// The id of the front window.
334
    #[must_use]
335
71689
    pub fn front_window(&self) -> Option<WindowId> {
336
71689
        self.desktop.front()
337
71689
    }
338

            
339
51443
    fn front_win(&self) -> Option<&Win> {
340
51443
        self.front_to_back().next()
341
51443
    }
342

            
343
    /// The `T` the front window shows; user actions go through it.
344
    #[must_use]
345
46371
    pub fn front<T: Pane>(&self) -> Option<&T> {
346
46371
        self.front_win().and_then(|win| T::of(&win.view))
347
46371
    }
348

            
349
319
    pub fn front_mut<T: Pane>(&mut self) -> Option<&mut T> {
350
319
        let id = self.front_window()?;
351
319
        self.win_mut::<T>(id)
352
319
    }
353

            
354
    /// The `T` shown by window `id`.
355
    #[must_use]
356
4049
    pub fn win<T: Pane>(&self, id: WindowId) -> Option<&T> {
357
4049
        self.win_by(id).and_then(|win| T::of(&win.view))
358
4049
    }
359

            
360
25922
    pub fn win_mut<T: Pane>(&mut self, id: WindowId) -> Option<&mut T> {
361
25922
        self.view_mut(id).and_then(T::of_mut)
362
25922
    }
363

            
364
104525
    pub(super) fn win_by(&self, id: WindowId) -> Option<&Win> {
365
392403
        self.windows.iter().find(|win| win.id == id)
366
104525
    }
367

            
368
234
    pub(super) fn report_seq_of(&mut self, window: WindowId) -> Option<&mut Seq> {
369
234
        self.win_by_mut(window).map(|win| &mut win.report_seq)
370
234
    }
371

            
372
27183
    fn win_by_mut(&mut self, id: WindowId) -> Option<&mut Win> {
373
141353
        self.windows.iter_mut().find(|win| win.id == id)
374
27183
    }
375

            
376
26949
    pub(crate) fn view_mut(&mut self, id: WindowId) -> Option<&mut View> {
377
26949
        self.win_by_mut(id).map(|win| &mut win.view)
378
26949
    }
379

            
380
    /// The id of the front-most window of `kind`.
381
    #[must_use]
382
5787
    pub fn window_id(&self, kind: ViewId) -> Option<WindowId> {
383
34225
        let win = self.front_to_back().find(|win| win.view.kind() == kind);
384
5787
        win.map(|win| win.id)
385
5787
    }
386

            
387
    /// The ids of every window of `kind`, front first.
388
    #[must_use]
389
969
    pub(super) fn window_ids(&self, kind: ViewId) -> Vec<WindowId> {
390
969
        let wins = self.front_to_back();
391
5168
        wins.filter(|win| win.view.kind() == kind)
392
545
            .map(|win| win.id)
393
            .collect()
394
969
    }
395

            
396
    /// The kind of the front window.
397
    #[must_use]
398
5061
    pub fn front_kind(&self) -> Option<ViewId> {
399
5061
        self.front_win().map(|win| win.view.kind())
400
5061
    }
401

            
402
    #[must_use]
403
533
    pub fn front_is(&self, kind: ViewId) -> bool {
404
533
        self.front_kind() == Some(kind)
405
533
    }
406

            
407
    /// The windows to draw inside `area`, back to front, without those fully covered.
408
    #[must_use]
409
2311
    pub fn visible_windows(&self, area: Rect) -> Vec<(WindowId, &View, Place)> {
410
2311
        let drawn = self.desktop.iter_back_to_front();
411
2311
        drawn
412
14059
            .filter(|slot| !self.desktop.occluded(slot.id, area))
413
2235
            .filter_map(|slot| {
414
2235
                let place = self.desktop.place_of(slot.id, area)?;
415
2235
                let win = self.win_by(slot.id)?;
416
2235
                Some((win.id, &win.view, place))
417
2235
            })
418
            .collect()
419
2311
    }
420

            
421
    /// The frame of window `id`: dragging while it is moved or sized, else active when it is the front one, numbered by its own number.
422
    #[must_use]
423
1538
    pub fn frame_state(&self, id: WindowId) -> FrameState {
424
1538
        let mode = match (self.dragged() == Some(id), self.front_window() == Some(id)) {
425
59
            (true, _) => FrameMode::Dragging,
426
1299
            (false, true) => FrameMode::Active,
427
180
            (false, false) => FrameMode::Passive,
428
        };
429
1538
        let slot = self.desktop.window(id);
430
        FrameState {
431
1538
            mode,
432
1538
            caps: slot.map_or(Caps::ALL, |slot| slot.caps),
433
1538
            zoomed: slot.is_some_and(|slot| slot.zoomed),
434
1538
            number: self.win_by(id).and_then(|win| win.number),
435
        }
436
1538
    }
437

            
438
    /// Whether the front window is a console whose prompt has the keyboard.
439
    #[must_use]
440
46044
    pub fn console_input_focused(&self) -> bool {
441
46044
        self.front::<ConsoleState>()
442
1815
            .is_some_and(|console| console.focused)
443
46044
    }
444

            
445
    /// Gives the front console's prompt the keyboard, or takes it away.
446
60
    pub(crate) fn set_console_focused(&mut self, focused: bool) {
447
60
        if let Some(console) = self.front_mut::<ConsoleState>() {
448
60
            console.focused = focused;
449
        }
450
60
    }
451

            
452
    /// The front window's view.
453
11
    pub fn active_view(&self) -> Option<&View> {
454
11
        self.front_win().map(|win| &win.view)
455
11
    }
456

            
457
10
    pub fn active_view_mut(&mut self) -> Option<&mut View> {
458
10
        let id = self.desktop.front()?;
459
10
        self.view_mut(id)
460
10
    }
461

            
462
    /// The list the front window shows when it shows `kind`.
463
    #[must_use]
464
63
    pub fn front_list(&self, kind: ViewId) -> Option<&ListTab> {
465
63
        self.front_is(kind)
466
59
            .then(|| self.front::<ListTab>())
467
            .flatten()
468
63
    }
469

            
470
    /// The view kind window `id` shows, or `None` once the window is gone.
471
    #[must_use]
472
3679
    pub fn window_view(&self, id: WindowId) -> Option<ViewId> {
473
3679
        self.win_by(id).map(|win| win.view.kind())
474
3679
    }
475

            
476
    /// The last report run in Reports window `window` and its values.
477
    #[must_use]
478
36
    pub fn last_report(&self, window: WindowId) -> Option<(ReportKind, FormValues)> {
479
36
        self.win::<ReportsTab>(window)?.last().cloned()
480
36
    }
481

            
482
    /// Marks the Reports window that asked request `id` as waiting for it.
483
28
    pub(crate) fn set_report_loading(&mut self, id: i64, kind: ReportKind, values: &FormValues) {
484
28
        let Some(window) = self.pending_routes.get(&id).and_then(|route| route.target) else {
485
            return;
486
        };
487
28
        if let Some(reports) = self.win_mut::<ReportsTab>(window) {
488
28
            reports.set_loading(id, kind, values);
489
        }
490
28
    }
491

            
492
    /// The selected row id of the front window's list, when it shows `kind`.
493
    #[must_use]
494
46
    pub fn selected_id(&self, kind: ViewId) -> Option<String> {
495
46
        self.front_list(kind)?.selected_id().map(str::to_string)
496
46
    }
497
}