Skip to content
This repository has been archived by the owner on Oct 22, 2019. It is now read-only.

Commit

Permalink
Calculate relative 'y' position for mouse event (#11)
Browse files Browse the repository at this point in the history
  • Loading branch information
TimonPost authored Oct 21, 2019
1 parent 6d045a8 commit b56a273
Showing 1 changed file with 12 additions and 8 deletions.
20 changes: 12 additions & 8 deletions src/input/windows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ use winapi::um::{

use crossterm_winapi::{
ButtonState, Console, ConsoleMode, EventFlags, Handle, InputEventType, KeyEventRecord,
MouseEvent,
MouseEvent, ScreenBuffer,
};
use lazy_static::lazy_static;

Expand Down Expand Up @@ -390,7 +390,7 @@ fn read_input_events() -> Result<(u32, Vec<InputEvent>)> {
}

fn handle_mouse_event(mouse_event: MouseEvent) -> Result<Option<InputEvent>> {
if let Some(event) = parse_mouse_event_record(&mouse_event) {
if let Ok(Some(event)) = parse_mouse_event_record(&mouse_event) {
return Ok(Some(InputEvent::Mouse(event)));
}
Ok(None)
Expand Down Expand Up @@ -530,19 +530,23 @@ fn parse_key_event_record(key_event: &KeyEventRecord) -> Option<KeyEvent> {
}
}

fn parse_mouse_event_record(event: &MouseEvent) -> Option<crate::MouseEvent> {
fn parse_mouse_event_record(event: &MouseEvent) -> Result<Option<crate::MouseEvent>> {
// NOTE (@imdaveho): xterm emulation takes the digits of the coords and passes them
// individually as bytes into a buffer; the below cxbs and cybs replicates that and
// mimicks the behavior; additionally, in xterm, mouse move is only handled when a
// mouse button is held down (ie. mouse drag)

// Windows returns (0, 0) for upper/left
let window_size = ScreenBuffer::current()?.info()?.terminal_window();

let xpos = event.mouse_position.x;
let ypos = event.mouse_position.y;
let mut ypos = event.mouse_position.y;

// The 'y' position of a mouse event is not relative to the window but absolute to screen buffer.
// This means that when the mouse cursor is at the top left it will be x: 0, y: 2295 (e.g. y = number of cells counting from the absolute buffer height) instead of relative x: 0, y: 0 to the window.

// TODO (@imdaveho): check if linux only provides coords for visible terminal window vs the total buffer
ypos = ypos - window_size.top;

match event.event_flags {
Ok(match event.event_flags {
EventFlags::PressOrRelease => {
// Single click
match event.button_state {
Expand Down Expand Up @@ -604,5 +608,5 @@ fn parse_mouse_event_record(event: &MouseEvent) -> Option<crate::MouseEvent> {
EventFlags::DoubleClick => None, // NOTE (@imdaveho): double click not supported by unix terminals
EventFlags::MouseHwheeled => None, // NOTE (@imdaveho): horizontal scroll not supported by unix terminals
// TODO: Handle Ctrl + Mouse, Alt + Mouse, etc.
}
})
}

0 comments on commit b56a273

Please sign in to comment.