Skip to main content

tui/app/
windows.rs

1//! The windows of the app and the lookups over them.
2
3use forms::FormValues;
4
5use super::App;
6use crate::draw::body_area;
7use crate::modal::Modal;
8use crate::tabs::config::ConfigTab;
9use crate::tabs::list::ListTab;
10use crate::tabs::nms::ConsoleState;
11use crate::tabs::reports::chart::TerminalEnv;
12use crate::tabs::reports::{ReportKind, ReportsTab};
13use crate::tabs::scripts::ScriptsTab;
14use crate::tabs::seq::Seq;
15use crate::tabs::ssh_keys::SshKeysTab;
16use crate::tabs::tags::TagsTab;
17use crate::tabs::templates::TemplatesTab;
18use crate::view::ViewId;
19use crate::viewer::{Source, Viewer};
20use crate::window::{Origin, Pane, Placement, View, Win, WindowId};
21use cli_core::render::schema;
22use ratatui::layout::Rect;
23use tvui::{Caps, FrameMode, FrameState, Place};
24
25/// The part of a terminal of `env` the windows sit on.
26pub(super) fn desktop_area(env: TerminalEnv) -> Rect {
27    body_area(Rect::new(0, 0, env.screen.width, env.screen.height))
28}
29
30/// A fresh view of `kind`.
31pub(super) fn new_view(kind: ViewId) -> View {
32    match kind {
33        ViewId::Accounts => View::List(
34            kind,
35            ListTab::new("(list-accounts)", &schema::ACCOUNTS).with_balance_column(),
36        ),
37        ViewId::Transactions => View::List(kind, ListTab::paged()),
38        ViewId::Commodities => View::List(
39            kind,
40            ListTab::new("(list-commodities)", &schema::COMMODITIES),
41        ),
42        ViewId::Reports => View::Reports(ReportsTab::new()),
43        ViewId::Config => View::Config(ConfigTab::new()),
44        ViewId::SshKeys => View::SshKeys(SshKeysTab::new()),
45        ViewId::Tags => View::Tags(TagsTab::new()),
46        ViewId::Templates => View::Templates(TemplatesTab::new()),
47        ViewId::Scripts => View::Scripts(ScriptsTab::new()),
48        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}
55
56impl App {
57    /// Opens `view` on top at `placement` with `number`; the only way a window appears.
58    pub(super) fn open_window(
59        &mut self,
60        view: View,
61        placement: Placement,
62        number: Option<u8>,
63    ) -> WindowId {
64        self.leave_front();
65        let id = WindowId(self.next_window);
66        self.next_window = self.next_window.saturating_add(1);
67        let ordinal = self.next_ordinal(view.kind());
68        let caps = view.caps();
69        self.windows.push(Win {
70            id,
71            view,
72            number,
73            ordinal,
74            report_seq: Seq::default(),
75        });
76        self.desktop.open(id, placement.rect, caps);
77        if placement.zoomed {
78            self.desktop.toggle_zoom(id);
79        }
80        id
81    }
82
83    /// Closes window `id`, settling what it has in flight; the only way a window goes.
84    pub(crate) fn close_window(&mut self, id: WindowId) {
85        if self.win_by(id).is_none() {
86            return;
87        }
88        if self.dragged() == Some(id) {
89            self.hold = None;
90        }
91        self.settle_window(id);
92        self.close_console_stream(id);
93        self.delete_image(id);
94        let uncovers = self.drawn_ids().contains(&id);
95        self.windows.retain(|win| win.id != id);
96        self.desktop.close(id);
97        if uncovers {
98            self.load_visible();
99        }
100    }
101
102    /// Closes the front window.
103    pub(crate) fn close_front_window(&mut self) {
104        if let Some(id) = self.front_window() {
105            self.close_window(id);
106        }
107    }
108
109    /// Brings window `id` to the front; the only way a window is raised.
110    pub(super) fn raise_window(&mut self, id: WindowId) {
111        if self.front_window() == Some(id) {
112            return;
113        }
114        self.leave_front();
115        self.desktop.raise(id);
116    }
117
118    /// Brings the rearmost window to the front.
119    pub(crate) fn next_window(&mut self) {
120        if let Some(id) = self.desktop.rearmost() {
121            self.activate_window(id);
122        }
123    }
124
125    /// Sends the front window to the back; the one behind it comes to the front.
126    pub(crate) fn prev_window(&mut self) {
127        let Some(id) = self
128            .front_window()
129            .filter(|id| self.desktop.rearmost() != Some(*id))
130        else {
131            return;
132        };
133        self.leave_front();
134        self.desktop.lower(id);
135        self.clear_status();
136        self.load_visible();
137    }
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    pub(crate) fn toggle_zoom(&mut self) {
142        let Some(id) = self.front_window() else {
143            return;
144        };
145        if self.desktop.toggle_zoom(id) {
146            self.window_resized(id);
147            self.load_visible();
148        }
149    }
150
151    /// The front-most window of `kind`, or a new one that is loaded.
152    pub(crate) fn window_or_open(&mut self, kind: ViewId) -> Origin {
153        let window = self.window_id(kind).unwrap_or_else(|| {
154            let window = self.open_new_window(new_view(kind));
155            self.load_window(window);
156            window
157        });
158        Origin { window, kind }
159    }
160
161    /// Says that there is no window of `kind`, or no window at all, to act on.
162    pub(crate) fn say_no_window(&mut self, kind: Option<ViewId>) {
163        match kind {
164            Some(kind) => self.set_status(format!("no {} window", kind.label())),
165            None => self.set_status("no window"),
166        }
167    }
168
169    /// The front window when it shows `kind`; says so otherwise.
170    pub(crate) fn front_or_say(&mut self, kind: ViewId) -> Option<WindowId> {
171        let window = self.front_window().filter(|_| self.front_is(kind));
172        if window.is_none() {
173            self.say_no_window(Some(kind));
174        }
175        window
176    }
177
178    /// Brings window `id` to the front, clears the status and loads it, as choosing it does.
179    pub(crate) fn activate_window(&mut self, id: WindowId) {
180        self.raise_window(id);
181        self.clear_status();
182        self.load_visible();
183    }
184
185    /// The windows drawn on the desktop; with no terminal geometry yet only the front one is
186    /// known to be.
187    fn drawn_ids(&self) -> Vec<WindowId> {
188        match self.terminal.env() {
189            Some(env) => {
190                let windows = self.visible_windows(desktop_area(env));
191                windows.into_iter().map(|(id, ..)| id).collect()
192            }
193            None => self.front_window().into_iter().collect(),
194        }
195    }
196
197    /// Loads every drawn window that has not been loaded.
198    pub(super) fn load_visible(&mut self) {
199        for id in self.drawn_ids() {
200            self.load_window(id);
201        }
202    }
203
204    /// Shows window `id` unless a dialog is open or awaiting its reply.
205    pub(crate) fn show_window_if_free(&mut self, id: WindowId) {
206        if self.pending_form.is_none() && self.overlays.is_empty() {
207            self.activate_window(id);
208        }
209    }
210
211    /// The window `id` and what it shows, or `None` once it is gone.
212    pub(super) fn origin_of(&self, id: WindowId) -> Option<Origin> {
213        let kind = self.window_view(id)?;
214        Some(Origin { window: id, kind })
215    }
216
217    /// The window of `origin`; says so when it has closed.
218    pub(super) fn origin_window(&mut self, origin: Origin) -> Option<WindowId> {
219        if self.window_view(origin.window).is_some() {
220            return Some(origin.window);
221        }
222        let message = match origin.kind {
223            ViewId::Viewer => "the window was closed".to_string(),
224            kind => format!("the {} window was closed", kind.label()),
225        };
226        self.set_status(message);
227        None
228    }
229
230    /// Raises the window of `origin` and makes the next dialog belong to it.
231    pub(super) fn begin_dialog(&mut self, origin: Origin) -> bool {
232        let Some(window) = self.origin_window(origin) else {
233            return false;
234        };
235        self.raise_and_load(window);
236        self.overlays.set_origin(Some(origin));
237        true
238    }
239
240    /// Raises `window` and loads it if it has not been.
241    fn raise_and_load(&mut self, window: WindowId) {
242        self.raise_window(window);
243        self.load_window(window);
244    }
245
246    /// Raises the front-most window of `kind`; says so when there is none.
247    pub(crate) fn raise_kind(&mut self, kind: ViewId) -> bool {
248        let Some(window) = self.window_id(kind) else {
249            self.say_no_window(Some(kind));
250            return false;
251        };
252        self.raise_and_load(window);
253        true
254    }
255
256    /// `begin_dialog` for the window a reply was routed to.
257    pub(super) fn begin_dialog_of(&mut self, target: Option<WindowId>) -> bool {
258        match target.and_then(|id| self.origin_of(id)) {
259            Some(origin) => self.begin_dialog(origin),
260            None => {
261                self.say_no_window(None);
262                false
263            }
264        }
265    }
266
267    /// Opens `modal` as a dialog of `origin`; `false` when its window has closed.
268    pub(super) fn open_dialog_at(&mut self, origin: Origin, modal: Modal) -> bool {
269        let opened = self.begin_dialog(origin);
270        if opened {
271            self.overlays.push(modal);
272        }
273        opened
274    }
275
276    /// Opens `modal` as a dialog of window `id`.
277    pub(super) fn open_dialog_in(&mut self, id: WindowId, modal: Modal) {
278        if let Some(origin) = self.origin_of(id) {
279            self.open_dialog_at(origin, modal);
280        }
281    }
282
283    /// Opens `modal` as a dialog of the front-most window of `kind`, or of a new one.
284    pub(crate) fn open_dialog_for(&mut self, kind: ViewId, modal: Modal) {
285        let origin = self.window_or_open(kind);
286        self.open_dialog_at(origin, modal);
287    }
288
289    /// The window the open dialog started from; says so when there is none.
290    pub(crate) fn dialog_origin(&mut self) -> Option<Origin> {
291        let origin = self.overlays.origin();
292        if origin.is_none() {
293            self.say_no_window(None);
294        }
295        origin
296    }
297
298    /// The window the open dialog belongs to; says so when it has closed or there is none.
299    pub(crate) fn dialog_window(&mut self) -> Option<WindowId> {
300        let origin = self.dialog_origin()?;
301        self.origin_window(origin)
302    }
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    fn leave_front(&mut self) {
307        if let Some(front) = self.front_window() {
308            self.delete_image(front);
309        }
310    }
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    pub(super) fn delete_image(&mut self, id: WindowId) {
315        self.queue_image_delete(id, self.terminal.env());
316    }
317
318    /// As `delete_image`; with no `env` the picture is not rebuilt, for a chart fetched again.
319    pub(super) fn queue_image_delete(&mut self, id: WindowId, env: Option<TerminalEnv>) {
320        let reports = self.win_mut::<ReportsTab>(id);
321        let image = reports.and_then(|reports| reports.chart.forget_kitty(env));
322        if let Some(image) = image {
323            self.outbound.push(tvui::kitty_delete(image));
324        }
325    }
326
327    /// The windows front to back.
328    fn front_to_back(&self) -> impl Iterator<Item = &Win> {
329        let order = self.desktop.iter_back_to_front().rev();
330        order.filter_map(|slot| self.win_by(slot.id))
331    }
332
333    /// The id of the front window.
334    #[must_use]
335    pub fn front_window(&self) -> Option<WindowId> {
336        self.desktop.front()
337    }
338
339    fn front_win(&self) -> Option<&Win> {
340        self.front_to_back().next()
341    }
342
343    /// The `T` the front window shows; user actions go through it.
344    #[must_use]
345    pub fn front<T: Pane>(&self) -> Option<&T> {
346        self.front_win().and_then(|win| T::of(&win.view))
347    }
348
349    pub fn front_mut<T: Pane>(&mut self) -> Option<&mut T> {
350        let id = self.front_window()?;
351        self.win_mut::<T>(id)
352    }
353
354    /// The `T` shown by window `id`.
355    #[must_use]
356    pub fn win<T: Pane>(&self, id: WindowId) -> Option<&T> {
357        self.win_by(id).and_then(|win| T::of(&win.view))
358    }
359
360    pub fn win_mut<T: Pane>(&mut self, id: WindowId) -> Option<&mut T> {
361        self.view_mut(id).and_then(T::of_mut)
362    }
363
364    pub(super) fn win_by(&self, id: WindowId) -> Option<&Win> {
365        self.windows.iter().find(|win| win.id == id)
366    }
367
368    pub(super) fn report_seq_of(&mut self, window: WindowId) -> Option<&mut Seq> {
369        self.win_by_mut(window).map(|win| &mut win.report_seq)
370    }
371
372    fn win_by_mut(&mut self, id: WindowId) -> Option<&mut Win> {
373        self.windows.iter_mut().find(|win| win.id == id)
374    }
375
376    pub(crate) fn view_mut(&mut self, id: WindowId) -> Option<&mut View> {
377        self.win_by_mut(id).map(|win| &mut win.view)
378    }
379
380    /// The id of the front-most window of `kind`.
381    #[must_use]
382    pub fn window_id(&self, kind: ViewId) -> Option<WindowId> {
383        let win = self.front_to_back().find(|win| win.view.kind() == kind);
384        win.map(|win| win.id)
385    }
386
387    /// The ids of every window of `kind`, front first.
388    #[must_use]
389    pub(super) fn window_ids(&self, kind: ViewId) -> Vec<WindowId> {
390        let wins = self.front_to_back();
391        wins.filter(|win| win.view.kind() == kind)
392            .map(|win| win.id)
393            .collect()
394    }
395
396    /// The kind of the front window.
397    #[must_use]
398    pub fn front_kind(&self) -> Option<ViewId> {
399        self.front_win().map(|win| win.view.kind())
400    }
401
402    #[must_use]
403    pub fn front_is(&self, kind: ViewId) -> bool {
404        self.front_kind() == Some(kind)
405    }
406
407    /// The windows to draw inside `area`, back to front, without those fully covered.
408    #[must_use]
409    pub fn visible_windows(&self, area: Rect) -> Vec<(WindowId, &View, Place)> {
410        let drawn = self.desktop.iter_back_to_front();
411        drawn
412            .filter(|slot| !self.desktop.occluded(slot.id, area))
413            .filter_map(|slot| {
414                let place = self.desktop.place_of(slot.id, area)?;
415                let win = self.win_by(slot.id)?;
416                Some((win.id, &win.view, place))
417            })
418            .collect()
419    }
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    pub fn frame_state(&self, id: WindowId) -> FrameState {
424        let mode = match (self.dragged() == Some(id), self.front_window() == Some(id)) {
425            (true, _) => FrameMode::Dragging,
426            (false, true) => FrameMode::Active,
427            (false, false) => FrameMode::Passive,
428        };
429        let slot = self.desktop.window(id);
430        FrameState {
431            mode,
432            caps: slot.map_or(Caps::ALL, |slot| slot.caps),
433            zoomed: slot.is_some_and(|slot| slot.zoomed),
434            number: self.win_by(id).and_then(|win| win.number),
435        }
436    }
437
438    /// Whether the front window is a console whose prompt has the keyboard.
439    #[must_use]
440    pub fn console_input_focused(&self) -> bool {
441        self.front::<ConsoleState>()
442            .is_some_and(|console| console.focused)
443    }
444
445    /// Gives the front console's prompt the keyboard, or takes it away.
446    pub(crate) fn set_console_focused(&mut self, focused: bool) {
447        if let Some(console) = self.front_mut::<ConsoleState>() {
448            console.focused = focused;
449        }
450    }
451
452    /// The front window's view.
453    pub fn active_view(&self) -> Option<&View> {
454        self.front_win().map(|win| &win.view)
455    }
456
457    pub fn active_view_mut(&mut self) -> Option<&mut View> {
458        let id = self.desktop.front()?;
459        self.view_mut(id)
460    }
461
462    /// The list the front window shows when it shows `kind`.
463    #[must_use]
464    pub fn front_list(&self, kind: ViewId) -> Option<&ListTab> {
465        self.front_is(kind)
466            .then(|| self.front::<ListTab>())
467            .flatten()
468    }
469
470    /// The view kind window `id` shows, or `None` once the window is gone.
471    #[must_use]
472    pub fn window_view(&self, id: WindowId) -> Option<ViewId> {
473        self.win_by(id).map(|win| win.view.kind())
474    }
475
476    /// The last report run in Reports window `window` and its values.
477    #[must_use]
478    pub fn last_report(&self, window: WindowId) -> Option<(ReportKind, FormValues)> {
479        self.win::<ReportsTab>(window)?.last().cloned()
480    }
481
482    /// Marks the Reports window that asked request `id` as waiting for it.
483    pub(crate) fn set_report_loading(&mut self, id: i64, kind: ReportKind, values: &FormValues) {
484        let Some(window) = self.pending_routes.get(&id).and_then(|route| route.target) else {
485            return;
486        };
487        if let Some(reports) = self.win_mut::<ReportsTab>(window) {
488            reports.set_loading(id, kind, values);
489        }
490    }
491
492    /// The selected row id of the front window's list, when it shows `kind`.
493    #[must_use]
494    pub fn selected_id(&self, kind: ViewId) -> Option<String> {
495        self.front_list(kind)?.selected_id().map(str::to_string)
496    }
497}