Skip to main content

tui/
draw.rs

1//! Ratatui rendering. The draw layer is a pure function of
2//! [`crate::app::App`]: take a `Frame` and an `App`, render the current
3//! visual state. No I/O of its own; I/O is the transport's job.
4
5mod canvas;
6mod filter_builder;
7mod form;
8mod menu;
9mod messages;
10mod modal;
11mod status_tail;
12
13use std::rc::Rc;
14
15use crate::app::App;
16use crate::event::Intent;
17use crate::hits::{Hits, Target};
18use crate::keymap;
19use crate::view::{DrawCtx, Tab};
20use canvas::Offscreen;
21use ratatui::Frame;
22use ratatui::buffer::Buffer;
23use ratatui::layout::{Alignment, Constraint, Direction, Layout, Rect};
24use ratatui::widgets::Paragraph;
25use status_tail::status_tail;
26
27use tvui::{
28    Dialog, FrameMode, FrameState, Role, StatusBar, close_area, copy_visible, grow_area, zoom_area,
29};
30
31/// The columns between the hints and the status tail.
32const TAIL_GAP: usize = 3;
33
34fn screen_rows(area: Rect) -> Rc<[Rect]> {
35    Layout::default()
36        .direction(Direction::Vertical)
37        .constraints([
38            Constraint::Length(1),
39            Constraint::Min(1),
40            Constraint::Length(1),
41        ])
42        .split(area)
43}
44
45/// The area between the menu bar and the status line.
46#[must_use]
47pub fn body_area(screen: Rect) -> Rect {
48    screen_rows(screen)[1]
49}
50
51/// Draws `app`, recording in `hits` every area a click can land on, bottom to top.
52pub fn draw(frame: &mut Frame, app: &App, hits: &mut Hits) {
53    let area = frame.area();
54    let chunks = screen_rows(area);
55
56    draw_body(frame, chunks[1], app, hits);
57    let hints = draw_status(frame, chunks[2], app);
58    menu::draw_menu(frame, chunks[0], app, hits);
59
60    for layer in app.overlays.layers() {
61        hits.push(area, Target::Block);
62        let mut lower = Hits::default();
63        let layer_hits = if layer.top { &mut *hits } else { &mut lower };
64        modal::draw_modal(frame, area, layer, app, layer_hits);
65    }
66    if let Some(pending) = &app.pending_form {
67        hits.push(area, Target::Block);
68        modal::draw_pending(frame, area, pending, app);
69    }
70    if app.menu.is_none() {
71        for (rect, intent) in hints {
72            hits.push(rect, Target::Hint(intent));
73        }
74    }
75}
76
77fn draw_body(frame: &mut Frame, area: Rect, app: &App, hits: &mut Hits) {
78    tvui::render_background(area, frame.buffer_mut(), &app.theme);
79    let covered = !app.overlays.is_empty() || app.pending_form.is_some();
80    let front = app.front_window();
81    for (id, view, place) in app.visible_windows(area) {
82        let state = app.frame_state(id);
83        let mut local = Hits::default();
84        local.push(place.local(), Target::Block);
85        let mut ctx = DrawCtx {
86            is_active: app.console_input_focused() && front == Some(id),
87            frame: match (state.mode, covered) {
88                (FrameMode::Active, true) => FrameState {
89                    mode: FrameMode::Passive,
90                    ..state
91                },
92                _ => state,
93            },
94            title: view.framed_title(&app.window_suffix(id)),
95            theme: &app.theme,
96            hits: &mut local,
97        };
98        let mut window = Buffer::empty(place.local());
99        view.draw(&mut window, place.local(), &mut ctx);
100        copy_visible(&window, place, place.visible_in(area), frame.buffer_mut());
101        push_frame_hits(&mut local, place.local(), state);
102        hits.extend_shown(local, Some(id), place, area);
103    }
104}
105
106/// The frame's own areas, over whatever the view drew: its icons and the whole top row.
107fn push_frame_hits(local: &mut Hits, area: Rect, state: FrameState) {
108    local.push(Rect { height: 1, ..area }, Target::Title);
109    for (rect, target) in [
110        (close_area(area, state), Target::Close),
111        (zoom_area(area, state), Target::Zoom),
112        (grow_area(area, state), Target::Grow),
113    ] {
114        if let Some(rect) = rect {
115            local.push(rect, target);
116        }
117    }
118}
119
120/// Draws the status line and returns the area of each hint, to record over any modal: the
121/// status line stays live under one.
122fn draw_status(frame: &mut Frame, area: Rect, app: &App) -> Vec<(Rect, Intent)> {
123    let style = app.theme.style(Role::Status);
124    if app.cmdline.active {
125        let buf = app.cmdline.editor.buffer();
126        let text = match app.cmdline.completions.is_empty() {
127            true => format!(":{buf}"),
128            false => format!(":{}  [{}]", buf, app.cmdline.completions.join("  ")),
129        };
130        frame.render_widget(Paragraph::new(text).style(style), area);
131        return Vec::new();
132    }
133    let indicator = format!("[{}]", app.keys.indicator());
134    if !app.status.is_empty() {
135        let text = format!("{indicator} {}", app.status);
136        frame.render_widget(Paragraph::new(text).style(style), area);
137        return Vec::new();
138    }
139    if app.front_window().is_none() && app.overlays.is_empty() && app.menu.is_none() {
140        let text = format!("{indicator} {}", empty_desktop_hint(app));
141        frame.render_widget(Paragraph::new(text).style(style), area);
142        return Vec::new();
143    }
144    let hinted = keymap::hinted(app);
145    let hints: Vec<_> = hinted.iter().map(keymap::Hint::pair).collect();
146    let bar = StatusBar::new(&app.theme, &hints);
147    let tail = status_tail(app.user_id, &indicator);
148    let tail_width = u16::try_from(tail.chars().count() + TAIL_GAP).unwrap_or(u16::MAX);
149    let width = area.width.saturating_sub(tail_width);
150    let end = Rect {
151        x: area.x.saturating_add(width),
152        width: area.width.saturating_sub(width),
153        ..area
154    };
155    let bar_area = Rect { width, ..area };
156    let areas: Vec<_> = StatusBar::item_areas(bar_area, &hints)
157        .into_iter()
158        .map(|(index, rect)| (rect, hinted[index].intent))
159        .collect();
160    frame.render_widget(bar, bar_area);
161    let text = Paragraph::new(tail)
162        .style(style)
163        .alignment(Alignment::Right);
164    frame.render_widget(text, end);
165    areas
166}
167
168/// What the status line says while the desktop is empty: the keys of the menu and of the views.
169fn empty_desktop_hint(app: &App) -> String {
170    let keys = keymap::here(app);
171    let views = [Tab::ALL.first(), Tab::ALL.last()].map(|tab| {
172        let tab = tab.copied()?;
173        keys.key(Intent::SelectTab(tab))
174    });
175    let parts = [
176        keys.key(Intent::OpenMenu)
177            .map(|menu| format!("{menu} menu")),
178        match views {
179            [Some(first), Some(last)] => Some(format!("{first}\u{2013}{last} open a view")),
180            _ => None,
181        },
182    ];
183    parts
184        .into_iter()
185        .flatten()
186        .collect::<Vec<_>>()
187        .join(" \u{b7} ")
188}
189
190fn draw_panel(
191    frame: &mut Offscreen,
192    area: Rect,
193    dialog: Dialog<'_>,
194    (body, at): (Paragraph<'_>, Rect),
195) {
196    frame.render_widget(dialog, area);
197    frame.render_widget(body, at);
198}
199
200#[cfg(test)]
201mod bar_hits_tests;
202#[cfg(test)]
203mod button_tests;
204#[cfg(test)]
205mod form_hits_tests;
206#[cfg(test)]
207mod frame_tests;
208#[cfg(test)]
209mod hits_tests;
210#[cfg(test)]
211mod layers_tests;
212#[cfg(test)]
213pub(crate) mod pending_form_tests;
214#[cfg(test)]
215mod placed_tests;
216#[cfg(test)]
217mod tests;
218#[cfg(test)]
219mod window_hits_tests;