Lines
100 %
Functions
Branches
//! Per-channel TUI state: keystroke decoder, input sender and the PTY
//! geometry the client announced.
use crate::key_decoder::SharedDecoder;
use tokio::sync::mpsc::Sender;
use tokio::sync::watch;
use tui::transport::{DEFAULT_CELL_PIXELS, RawEvent};
/// Largest terminal a client may announce; the render buffers scale with it.
const MAX_COLS: u16 = 500;
const MAX_ROWS: u16 = 200;
/// Largest pixel size of one cell; a client-announced size above it is not believed,
/// because images are sized as cells times this.
const MAX_CELL_PIXELS: u16 = 128;
/// Pulls a client-announced cell count into `1..=max`.
fn clamp_cells(cells: u32, max: u16) -> u16 {
u16::try_from(cells.clamp(1, u32::from(max))).unwrap_or(max)
}
/// Terminal size in cells and pixels as the client last reported it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Geometry {
pub cols: u16,
pub rows: u16,
pix_width: u32,
pix_height: u32,
impl Default for Geometry {
fn default() -> Self {
Self {
cols: 80,
rows: 24,
pix_width: 0,
pix_height: 0,
impl Geometry {
fn new(cols: u32, rows: u32, pix_width: u32, pix_height: u32) -> Self {
cols: clamp_cells(cols, MAX_COLS),
rows: clamp_cells(rows, MAX_ROWS),
pix_width,
pix_height,
/// The window's pixel size as the client reported it; 0 when it did not.
#[must_use]
pub fn pixels(self) -> (u32, u32) {
(self.pix_width, self.pix_height)
/// Pixel size of one cell; an unknown (0) or implausible dimension gets the 10x20 fallback.
pub fn cell_pixels(self) -> (u16, u16) {
let cell = |pixels: u32, cells: u16, fallback: u16| {
pixels
.checked_div(u32::from(cells))
.and_then(|size| u16::try_from(size).ok())
.filter(|size| (1..=MAX_CELL_PIXELS).contains(size))
.unwrap_or(fallback)
};
(
cell(self.pix_width, self.cols, DEFAULT_CELL_PIXELS.0),
cell(self.pix_height, self.rows, DEFAULT_CELL_PIXELS.1),
)
/// Created in `pty_request`, completed in `shell_request`, dropped in
/// `channel_close`.
pub struct TuiChannelState {
pub decoder: SharedDecoder,
pub input_tx: Option<Sender<RawEvent>>,
pub term: Option<String>,
geometry: watch::Sender<Geometry>,
impl TuiChannelState {
pub fn new(term: &str, cols: u32, rows: u32, pix_width: u32, pix_height: u32) -> Self {
let geometry = Geometry::new(cols, rows, pix_width, pix_height);
decoder: SharedDecoder::default(),
input_tx: None,
term: Some(term.to_string()),
geometry: watch::channel(geometry).0,
pub fn geometry(&self) -> Geometry {
*self.geometry.borrow()
pub fn subscribe(&self) -> watch::Receiver<Geometry> {
self.geometry.subscribe()
pub fn resize(&self, cols: u32, rows: u32, pix_width: u32, pix_height: u32) -> Geometry {
let resized = Geometry::new(cols, rows, pix_width, pix_height);
self.geometry.send_replace(resized);
resized