mouse xpos/ypos can be negative or larger than window size

When calculating the viewport point, we need to consider this. We clamp
the possible values to [0, width/height - 1]. Fixes #1.
This commit is contained in:
Mitchell Hashimoto
2022-08-06 16:05:32 -07:00
parent 109e2a67ab
commit 1da5ca0a7f

View File

@ -777,12 +777,25 @@ fn cursorPosCallback(
} }
fn posToViewport(self: Window, xpos: f64, ypos: f64) terminal.point.Viewport { fn posToViewport(self: Window, xpos: f64, ypos: f64) terminal.point.Viewport {
// Convert the mouse position to the viewport x/y // xpos and ypos can be negative if while dragging, the user moves the
const cell_width = @floatCast(f64, self.grid.cell_size.width); // mouse off the window. Likewise, they can be larger than our window
const cell_height = @floatCast(f64, self.grid.cell_size.height); // width if the user drags out of the window positively.
return .{ return .{
.x = @floatToInt(usize, xpos / cell_width), .x = if (xpos < 0) 0 else x: {
.y = @floatToInt(usize, ypos / cell_height), // Our cell is the mouse divided by cell width
const cell_width = @floatCast(f64, self.grid.cell_size.width);
const x = @floatToInt(usize, xpos / cell_width);
// Can be off the screen if the user drags it out, so max
// it out on our available columns
break :x @minimum(x, self.terminal.cols - 1);
},
.y = if (ypos < 0) 0 else y: {
const cell_height = @floatCast(f64, self.grid.cell_size.height);
const y = @floatToInt(usize, ypos / cell_height);
break :y @minimum(y, self.terminal.rows - 1);
},
}; };
} }