Lines
98.75 %
Functions
42.59 %
Branches
100 %
//! What a dialog draws on: the frame, or a copy of the screen it may hang off.
use ratatui::Frame;
use ratatui::buffer::Buffer;
use ratatui::layout::{Position, Rect};
use ratatui::widgets::{StatefulWidget, Widget};
use tvui::{Place, copy_visible};
use crate::hits::Hits;
/// A copy of the screen made wide enough for a dialog that hangs off its right and bottom, and
/// shifted right by the columns the dialog hangs off the left.
pub(crate) struct Offscreen {
buf: Buffer,
shift: u16,
host: Rect,
cursor: Option<Position>,
}
impl Offscreen {
/// The cells a popup may open in.
pub(crate) fn area(&self) -> Rect {
Rect {
x: self.host.x + self.shift,
..self.host
pub(crate) fn buffer_mut(&mut self) -> &mut Buffer {
&mut self.buf
pub(crate) fn set_cursor_position(&mut self, position: Position) {
self.cursor = Some(position);
pub(crate) fn render_widget<W: Widget>(&mut self, widget: W, area: Rect) {
widget.render(area, &mut self.buf);
pub(crate) fn render_stateful_widget<W: StatefulWidget>(
&mut self,
widget: W,
area: Rect,
state: &mut W::State,
) {
widget.render(area, &mut self.buf, state);
fn cells(value: i32) -> u16 {
u16::try_from(value.max(0)).unwrap_or(u16::MAX)
/// Draws a dialog at `place`, which may hang off the left, right and bottom of `host`: `draw` gets
/// the canvas, the full-size rect of the dialog on it and the hits to fill. What `host` shows of the
/// canvas goes back to the frame, and so do the hits and the cursor if it is on a visible cell.
pub(crate) fn draw_placed(
frame: &mut Frame,
place: Place,
hits: &mut Hits,
draw: impl FnOnce(&mut Offscreen, Rect, &mut Hits),
let screen = frame.area();
let shift = cells(-place.x);
let wide = cells(i32::from(shift) + place.x + i32::from(place.width));
let tall = cells(place.y + i32::from(place.height));
let size = Rect::new(
0,
screen.right().saturating_add(shift).max(wide),
screen.bottom().max(tall),
);
let mut canvas = Offscreen {
buf: Buffer::empty(size),
shift,
host,
cursor: None,
};
for position in screen.positions() {
let (Some(from), Some(to)) = (
frame.buffer_mut().cell(position),
canvas.buf.cell_mut((position.x + shift, position.y)),
) else {
continue;
to.clone_from(from);
let area = Rect::new(
cells(place.x + i32::from(shift)),
cells(place.y),
place.width,
place.height,
let mut local = Hits::default();
draw(&mut canvas, area, &mut local);
let whole = Place {
x: -i32::from(shift),
y: 0,
width: size.width,
height: size.height,
copy_visible(&canvas.buf, whole, host, frame.buffer_mut());
hits.extend_shifted(local, shift, host);
let shown = canvas
.cursor
.and_then(|at| at.x.checked_sub(shift).map(|x| Position::new(x, at.y)))
.filter(|at| host.contains(*at));
if let Some(at) = shown {
frame.set_cursor_position(at);