Mouse input
uncurses can report mouse activity as ordinary events: clicks, motion, and the scroll wheel. You opt in, and after that the pointer shows up in the same event stream as the keyboard, in cell coordinates or, on terminals that support it, pixels.
Turning it on
MouseTracking is a bitflags set of optional extras layered on basic button
tracking: MouseTracking::MOTION adds pointer movement with no button held, and
MouseTracking::PIXELS asks for pixel-accurate coordinates. An empty set
(MouseTracking::empty()) is basic tracking with no extras.
To start tracking at initialization, set ProgramOptions::mouse during construction:
use uncurses::program::{MouseTracking, Program, ProgramOptions};
use uncurses::terminal::Terminal;
let mut program = Program::with_options(
Terminal::stdio(),
ProgramOptions {
mouse: Some(MouseTracking::MOTION),
..ProgramOptions::default()
},
)?;
program.init()?;To turn it on and off during a session, call enable_mouse with the flags you
want, and disable_mouse to stop:
program.enable_mouse(MouseTracking::MOTION)?; // motion on, pixels off
// ... later, to stop tracking:
program.disable_mouse()?;Either way, the program does not gate mouse setup on detected capabilities. It
always requests 1000 + 1002 tracking and 1006 SGR encoding; MOTION also asks
for 1003, and PIXELS also asks for 1016. Terminals ignore unsupported modes,
so a terminal that cannot report pixels keeps reporting cells.
Reading mouse events
Mouse activity arrives as four event kinds, each carrying a position, button,
and modifiers. A mouse event’s x and y are plain u16, so build a
Position from them and work in the layout types from there.
use uncurses::event::{Event, MouseButton};
use uncurses::layout::Position;
let ev = program.read_event()?;
match ev {
Event::MouseClick(m) => {
let at = Position::new(m.x, m.y); // use m.button to inspect the button
}
Event::MouseRelease(m) => {
let at = Position::new(m.x, m.y); // the button came back up
}
Event::MouseMove(m) => {
// Motion while a button is held always arrives; buttonless hover
// motion only when you asked for `MouseTracking::MOTION`.
let at = Position::new(m.x, m.y);
}
Event::MouseWheel(m) => match m.button {
MouseButton::WheelUp => {}
MouseButton::WheelDown => {}
_ => {}
},
_ => {}
}Positions are 0-based: (0, 0) is the top-left cell, x is the column and y
is the row.
Hit testing
There is no widget tree, so “did they click the button” is a Rect containment
check. Track the Rect you drew each clickable thing into, then test the event
position against it.
use uncurses::event::Event;
use uncurses::layout::Rect;
let button = Rect::new(10, 4, 14, 3); // x, y, width, height
if let Event::MouseClick(m) = event {
if button.contains((m.x, m.y)) {
// the click landed on the button
}
}Rect::contains takes anything that converts into a Position. A Position is
From<(u16, u16)>, so the tuple form works directly.
Pixel mode
When you ask for MouseTracking::PIXELS, a capable terminal reports the pointer
in pixel offsets instead of cells, which is what you want for sub-cell precision
like dragging a graphic. Two things change, and the program helps with both.
First, find out whether you are actually getting pixels. init() does not probe
the terminal, so ask for capabilities when you need this answer. The
terminal may not support the request, in which case you quietly keep getting
cells. Once the record has the replies, it tells you which mode you got:
use uncurses::ansi::mode::Mode;
use uncurses::program::Probe;
use std::io::Write;
let mut probe = Probe::new(program.env());
probe.modes.push(Mode::MOUSE_SGR_PIXEL);
let mut caps = probe.query_capabilities(program.screen_mut(), true)?;
program.screen_mut().flush()?;
// In the collection loop, pass identified replies to caps.record(&event).
// After the application ends collection:
let pixel_mode = caps.supports(Mode::MOUSE_SGR_PIXEL);Second, when pixel_mode is true, a mouse event’s x and y are pixels, not
columns and rows. To convert them, you need the window size in pixels. Ask for
it with program.request_window_pixel_size()?, and keep the
Event::WindowPixelSize reply in your own state. Then
mouse_pixel_to_cell scales
a pixel Mouse across the grid.
This current-source fragment stores the text-area pixel dimensions:
use uncurses::event::{Event, mouse_pixel_to_cell};
use uncurses::layout::Position;
match event {
Event::WindowPixelSize(size) => window_pixels = Some(size.into()),
Event::MouseClick(m) => {
let m = match (pixel_mode, window_pixels) {
(true, Some((pw, ph))) => {
let grid = program.screen().size();
mouse_pixel_to_cell(m, pw, ph, grid.width, grid.height)
}
_ => m, // already in cells, or the size is not known yet
};
let at = Position::new(m.x, m.y);
}
_ => {}
}The scale uses the full grid, so a fractional cell width does not add up to
an error across the row. On the alt screen, the screen size is the terminal
size. Inline, pass the terminal size from program.get_window_size()?.
To estimate one cell’s pixel size, call
program.get_window_size()?.estimated_cell_pixel_size(). The estimate divides
the window’s pixel dimensions by its grid dimensions. It returns None when
any dimension is unknown or zero, and it can be smaller than the real cell size
when the terminal adds padding. Use program.request_cell_pixel_size()? to ask
the terminal for a direct cell-size report.
See examples/examples/mouse.rs for a live readout of motion, buttons, and
wheel ticks.
Clicks in inline mode
When you render inline rather than on the alternate screen, the surface starts partway down the terminal, but the terminal still reports clicks in whole-screen coordinates. To hit test against your surface you need to know where its top-left cell physically sits.
Call program.request_origin()? to move the cursor to the surface’s top-left
cell and request its position.
The reply arrives as Event::CursorPosition, and it holds the origin.
Pass its position to program.set_origin. Then read it with
program.origin(), or map a whole-screen Mouse straight into surface-local
coordinates with program.mouse_to_origin.
A cursor position reply carries no request ID, so your loop must know which
request it answers. Replies arrive in request order. Count the origin requests
that wait for a reply, and give the next CursorPosition to set_origin while
that count is above zero. Keep origin requests separate from other cursor
requests, including the capability width probe, so the count matches the right
reply. A report on row 1 also spells modified F3. The key arrives just before
the report, so drop F3 while the count is above zero. A real modified F3 can
have the same bytes, so this can drop that key while the request waits.
use uncurses::event::{Event, KeyCode};
program.request_origin()?;
let mut origin_requests = 1usize;
match event {
Event::KeyPress(key) if origin_requests > 0 && key.code == KeyCode::F(3) => {}
Event::CursorPosition { position, .. } if origin_requests > 0 => {
origin_requests -= 1;
program.set_origin(position);
}
Event::MouseClick(m) => {
let local = program.mouse_to_origin(m); // relative to the surface's top-left
// hit test `local.x` / `local.y` against your layout
}
_ => {}
}On the alternate screen the origin is always (0, 0), so mouse_to_origin is a
no-op there and the same hit-testing code works in both modes.
request_origin performs no I/O there, so count requests only for an inline
surface.
Request the origin once after enable_mouse, then again after each resize or
resume, because either can move the surface:
Event::Resize(_) => {
program.autoresize()?;
program.request_origin()?;
origin_requests += 1;
}See examples/examples/calculator.rs for a mouse-driven, inline calculator that
maps clicks onto its keypad this way.
