use std::time::Duration;
use crate::{Error, Result};
use libghostty_vt::{
Terminal,
paste,
selection::{
FormatOptions,
gesture::{DragEvent, Geometry, Gesture, PressEvent, ReleaseEvent},
},
terminal::{Mode, Point, PointCoordinate},
};
const REPEAT_INTERVAL: Duration = Duration::from_millis(400);
const REPEAT_DISTANCE: f64 = 4.0;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) struct Cell {
pub(crate) x: u16,
pub(crate) y: u16,
}
pub(crate) struct Pointer {
gesture: Gesture<'static>,
press: PressEvent<'static>,
drag: DragEvent<'static>,
release: ReleaseEvent<'static>,
pub(crate) dragging: bool,
}
impl Pointer {
pub(crate) fn new() -> Result<Self> {
Ok(Self {
gesture: Gesture::new()
.map_err(|error| Error::context("failed to create a selection gesture", error))?,
press: PressEvent::new()
.map_err(|error| Error::context("failed to create a press event", error))?,
drag: DragEvent::new()
.map_err(|error| Error::context("failed to create a drag event", error))?,
release: ReleaseEvent::new()
.map_err(|error| Error::context("failed to create a release event", error))?,
dragging: false,
})
}
pub(crate) fn press(
&mut self,
terminal: &Terminal<'_, '_>,
cell: Cell,
at: (f32, f32),
now: Duration,
) -> Result<()> {
let grid_ref = grid_ref_at(terminal, cell)?;
self.press
.set_position(f64::from(at.0), f64::from(at.1))
.and_then(|event| event.set_time(now))
.and_then(|event| event.set_repeat_interval(REPEAT_INTERVAL))
.and_then(|event| event.set_repeat_distance(REPEAT_DISTANCE))
.map_err(|error| Error::context("failed to describe the press", error))?;
let selection = self
.press
.apply(&mut self.gesture, terminal, grid_ref)
.map_err(|error| Error::context("failed to apply the press", error))?;
terminal
.set_selection(selection.as_ref())
.map_err(|error| Error::context("failed to set the selection", error))?;
self.dragging = true;
Ok(())
}
pub(crate) fn drag(
&mut self,
terminal: &Terminal<'_, '_>,
cell: Cell,
at: (f32, f32),
geometry: Geometry,
rectangle: bool,
) -> Result<()> {
let grid_ref = grid_ref_at(terminal, cell)?;
self.drag
.set_position(f64::from(at.0), f64::from(at.1))
.and_then(|event| event.set_rectangle(rectangle))
.map_err(|error| Error::context("failed to describe the drag", error))?;
let selection = self
.drag
.apply(&mut self.gesture, terminal, grid_ref, geometry)
.map_err(|error| Error::context("failed to apply the drag", error))?;
if let Some(selection) = selection {
terminal
.set_selection(Some(&selection))
.map_err(|error| Error::context("failed to set the selection", error))?;
}
Ok(())
}
pub(crate) fn release(&mut self, terminal: &Terminal<'_, '_>) -> Result<()> {
self.dragging = false;
self.release
.apply(&mut self.gesture, terminal, None)
.map_err(|error| Error::context("failed to apply the release", error))
}
pub(crate) fn dragged(&self, terminal: &Terminal<'_, '_>) -> bool {
self.gesture.dragged(terminal).unwrap_or(false)
}
}
fn grid_ref_at<'t>(
terminal: &'t Terminal<'_, '_>,
cell: Cell,
) -> Result<libghostty_vt::screen::GridRef<'t>> {
terminal
.grid_ref(Point::Viewport(PointCoordinate {
x: cell.x,
y: u32::from(cell.y),
}))
.map_err(|error| Error::context("failed to read the cell under the pointer", error))
}
pub(crate) fn selected_text(terminal: &Terminal<'_, '_>) -> Option<String> {
let options = FormatOptions::new().with_unwrap(true).with_trim(true);
let bytes = terminal.format_selection_alloc(None, options).ok()??;
String::from_utf8(bytes.to_vec()).ok()
}
pub(crate) fn encode_paste(terminal: &Terminal<'_, '_>, text: &str) -> Result<Vec<u8>> {
let bracketed = terminal.mode(Mode::BRACKETED_PASTE).unwrap_or(false);
let mut data = text.as_bytes().to_vec();
let mut out = vec![0u8; data.len() + 16];
match paste::encode(&mut data, bracketed, &mut out) {
Ok(written) => {
out.truncate(written);
Ok(out)
}
Err(libghostty_vt::error::Error::OutOfSpace { required }) => {
let mut data = text.as_bytes().to_vec();
let mut out = vec![0u8; required.max(text.len() * 2 + 64)];
let written = paste::encode(&mut data, bracketed, &mut out)
.map_err(|error| Error::context("failed to encode the paste", error))?;
out.truncate(written);
Ok(out)
}
Err(error) => Err(Error::context("failed to encode the paste", error)),
}
}
pub(crate) fn geometry(cols: u16, cell_width: f32, padding_left: f32, height: f32) -> Geometry {
Geometry {
columns: u32::from(cols).max(1),
cell_width: (cell_width.round() as u32).max(1),
padding_left: padding_left.round().max(0.0) as u32,
screen_height: (height.round() as u32).max(1),
}
}
#[cfg(test)]
mod tests {
use super::*;
use libghostty_vt::TerminalOptions;
const CELL_WIDTH: f32 = 8.0;
const CELL_HEIGHT: f32 = 16.0;
fn terminal_showing(text: &str) -> Terminal<'static, 'static> {
let mut terminal = Terminal::new(TerminalOptions {
cols: 40,
rows: 5,
max_scrollback: 100,
})
.expect("expected a terminal");
terminal.vt_write(text.as_bytes());
terminal
}
fn at(cell: Cell, across: f32) -> (f32, f32) {
(
f32::from(cell.x) * CELL_WIDTH + CELL_WIDTH * across,
f32::from(cell.y) * CELL_HEIGHT + CELL_HEIGHT / 2.0,
)
}
fn cell(x: u16, y: u16) -> Cell {
Cell { x, y }
}
fn drag_across(terminal: &Terminal<'_, '_>, from: Cell, to: Cell) -> Pointer {
let forward = (to.y, to.x) >= (from.y, from.x);
let (from_at, to_at) = if forward {
(at(from, 0.25), at(to, 0.75))
} else {
(at(from, 0.75), at(to, 0.25))
};
let mut pointer = Pointer::new().expect("expected a gesture");
pointer
.press(terminal, from, from_at, Duration::from_secs(1))
.expect("expected the press to land");
pointer
.drag(
terminal,
to,
to_at,
geometry(40, CELL_WIDTH, 0.0, CELL_HEIGHT * 5.0),
false,
)
.expect("expected the drag to land");
pointer.release(terminal).expect("expected the release");
pointer
}
#[test]
fn dragging_across_a_line_selects_what_the_pointer_swept() {
let terminal = terminal_showing("hello world");
drag_across(&terminal, cell(0, 0), cell(4, 0));
assert_eq!(selected_text(&terminal).as_deref(), Some("hello"));
}
#[test]
fn a_selection_can_run_backwards_and_over_more_than_one_row() {
let terminal = terminal_showing("first line\r\nsecond line");
drag_across(&terminal, cell(5, 1), cell(0, 0));
let selected = selected_text(&terminal).expect("expected a selection");
assert!(selected.starts_with("first line"), "got {selected:?}");
assert!(
selected.contains("second"),
"a selection that started below has to reach back over the row break, got {selected:?}"
);
}
#[test]
fn a_click_that_never_moved_selects_nothing() {
let terminal = terminal_showing("hello world");
drag_across(&terminal, cell(0, 0), cell(4, 0));
assert!(selected_text(&terminal).is_some(), "something is selected");
let mut pointer = Pointer::new().expect("expected a gesture");
pointer
.press(&terminal, cell(2, 0), at(cell(2, 0), 0.5), Duration::from_secs(2))
.expect("expected the press to land");
assert!(!pointer.dragged(&terminal), "the pointer never moved");
pointer.release(&terminal).expect("expected the release");
assert_eq!(selected_text(&terminal), None, "the click cleared it");
}
#[test]
fn a_drag_is_recognised_as_one() {
let terminal = terminal_showing("hello world");
let pointer = drag_across(&terminal, cell(0, 0), cell(4, 0));
assert!(pointer.dragged(&terminal), "the pointer swept four cells");
assert!(!pointer.dragging, "and the release ended the gesture");
}
#[test]
fn nothing_selected_means_nothing_to_copy() {
let terminal = terminal_showing("hello world");
assert_eq!(selected_text(&terminal), None);
}
#[test]
fn paste_is_bracketed_only_when_the_program_asked_for_it() {
let plain = terminal_showing("");
let encoded = encode_paste(&plain, "one\ntwo").expect("expected an encoding");
assert_eq!(encoded, b"one\rtwo");
let bracketed = terminal_showing("\x1b[?2004h");
let encoded = encode_paste(&bracketed, "one\ntwo").expect("expected an encoding");
assert_eq!(encoded, b"\x1b[200~one\ntwo\x1b[201~");
}
#[test]
fn a_long_paste_is_not_truncated() {
let terminal = terminal_showing("");
let long = "x".repeat(9_000);
let encoded = encode_paste(&terminal, &long).expect("expected an encoding");
assert_eq!(encoded.len(), long.len());
}
}