Add a mode to report scroll events to programs in full detail

Mode 5523, while mouse tracking is on, makes kitty report each scroll event
as a single CSI > ... M escape code instead of as button 4-7 presses. It
carries integer deltas in v120 units or pixels, with fractions carried
over, the user's scroll multiplier as a hint, the kind of device, the
gesture phase, and flags for momentum and inverted (natural) scrolling,
and the full set of modifiers. Only the sign of the multipliers is applied.

To support this GLFW scroll events now carry the source device, the
gesture phase and whether the direction is inverted, on Wayland, X11 and
macOS. The momentum scroller now forwards the gesture end before starting
momentum and no longer reports a cancel for momentum that never began.
This commit is contained in:
Kovid Goyal 2026-11-16 09:22:53 +05:30
parent 59c8843608
commit b069fa5674
No known key found for this signature in database
GPG key ID: 06BC317B515ACE7C
15 changed files with 557 additions and 24 deletions

View file

@ -43,6 +43,117 @@ When bit 8 is set it means the event is a mouse has left the window event,
and all other bits should be ignored. The pixel position values must also
be ignored as they may not be accurate.
.. _detailed_wheel_events:
Detailed reporting of scroll wheel and touchpad events
--------------------------------------------------------
.. versionadded:: 1.0.0
Traditionally, terminals report scrolling to programs as presses of the mouse
buttons 4 to 7. This is a poor fit for modern input devices such as high
resolution wheels and touchpads, which report scrolling in fractions of a
wheel click or in pixels, have gestures that begin and end and continue scrolling
with momentum after the fingers are lifted. kitty has a mode that makes it
report scroll events with all this information instead.
The mode is private mode ``5523``. A program turns it on with
``CSI ? 5523 h`` and off with ``CSI ? 5523 l``. It can check whether the
terminal supports it with the standard DECRQM query, ``CSI ? 5523 $ p``. The
mode has an effect only while mouse tracking is turned on (one of the modes
``1000``, ``1002`` or ``1003``), as otherwise the terminal uses scroll events
itself, to scroll its scrollback. While both are on, scroll events are no
longer reported as button 4 to 7 presses. Instead, every scroll event from
the operating system is reported as a single escape code of the form::
CSI > x ; y ; dx ; dy ; unit ; source ; phase ; flags ; mods M
Spaces in the above are for clarity only. All parameters are always present.
They are:
``x ; y``
The position of the mouse pointer. This is a 1-based cell position,
unless SGR pixel mouse reporting (mode ``1016``) is on, in which case it
is the position in pixels, exactly as for other mouse events.
``dx ; dy``
The amount scrolled, as signed integers. A positive ``dy`` means scrolling
towards the end of the content, that is, the direction of the
traditional button 5 (wheel down). A positive ``dx`` means scrolling to
the right, the direction of button 7. The deltas have any natural
scrolling preference of the user already applied, see ``flags`` below.
Events that carry only a change of ``phase`` have both deltas zero.
``unit``
The unit of ``dx`` and ``dy``:
``1``
Fractions of a wheel click, with one click being ``120``. High
resolution wheels report parts of a click, for example, ``30`` for a
quarter of a click. Wheels that report only whole clicks or lines,
report multiples of ``120``.
``2``
Pixels, in the same pixel coordinate system as used for SGR pixel
mouse reporting and the ``CSI 14 t`` query. Fractions of a pixel are
accumulated by the terminal and reported in a later event, so nothing
is lost over a gesture.
This parameter can have an optional sub-parameter, the scroll multiplier
the user has configured in the terminal for this kind of scrolling, as a
positive decimal number, for example, ``1:5`` or ``2:1.5``. It is a hint
that programs can use to make their scrolling match that of the terminal,
for instance, by scrolling ``5`` lines per wheel click. Terminals are not
required to send it and programs are free to ignore it. The deltas
themselves are never scaled by the multiplier.
``source``
The kind of device the event comes from: ``0`` unknown, ``1`` a wheel,
``2`` a finger on a touchpad or trackpad, ``3`` a continuous device, for
example, a trackpoint or a knob, ``4`` a wheel tilt, that is, sideways
clicks of a wheel.
``phase``
Where the event is in a scroll gesture. ``0`` means the device has no
concept of gestures, as for wheel clicks. Otherwise, ``1`` means a
gesture began, ``2`` that it continued, ``3`` that it ended, for example,
the fingers were lifted from the touchpad, ``4`` that it was cancelled and
``5`` that a gesture may begin, for example, because the fingers are
resting on the touchpad. When ``flags`` indicates momentum, the phase
refers to the momentum scrolling rather than to the physical gesture.
``flags``
A bit field. The bit ``1`` is set when the event is momentum, also called
inertial or kinetic scrolling, that is, scrolling generated after the
fingers were lifted, which slows down over time. Programs that do their
own momentum scrolling should ignore these events. The bit ``2`` is set
when the direction of the deltas is the reverse of the physical movement
of the device, for example, because the user has turned on natural
scrolling. Programs that need the physical direction, for example, to
move a slider, can use it to undo the reversal.
``mods``
The keyboard modifiers that were pressed, encoded as in the
:ref:`keyboard protocol <modifiers>`, that is, one plus a bit field
where ``shift=1``, ``alt=2``, ``ctrl=4``, ``super=8``, ``hyper=16``,
``meta=32``, ``caps_lock=64`` and ``num_lock=128``.
More parameters may be added at the end in the future, and sub-parameters
(separated by colons) may be added to any parameter. Programs must ignore any
parameters and sub-parameters they do not recognise.
A few examples, with the escape code introducer ``CSI >`` and the final ``M``
omitted::
10;5;0;120;1:5;1;0;0;1 one click of a wheel, downwards
10;5;0;-30;1:5;1;0;0;1 a quarter click of a high resolution wheel, upwards
10;5;0;0;2:1;2;1;0;1 two fingers start a scroll on a touchpad
10;5;3;-42;2:1;2;2;0;1 the fingers move upwards by 42 pixels
10;5;0;0;2:1;2;3;0;1 the fingers are lifted
10;5;0;-35;2:1;2;1;1;1 momentum scrolling begins
10;5;0;0;2:1;2;3;1;1 momentum scrolling ends
10;5;0;120;1:5;1;0;0;5 a wheel click downwards with ctrl pressed
An escape code to move the contents of the screen into the scrollback
-------------------------------------------------------------------------------------

View file

@ -1439,6 +1439,21 @@ is_modifier_pressed(NSUInteger flags, NSUInteger target_mask, NSUInteger other_m
case NSEventPhaseMayBegin: ev.momentum_type = GLFW_MOMENTUM_PHASE_MAY_BEGIN; break;
case NSEventPhaseNone: break;
}
switch ([event phase]) {
case NSEventPhaseBegan: ev.phase = GLFW_SCROLL_PHASE_BEGAN; break;
case NSEventPhaseStationary:
case NSEventPhaseChanged: ev.phase = GLFW_SCROLL_PHASE_CHANGED; break;
case NSEventPhaseEnded: ev.phase = GLFW_SCROLL_PHASE_ENDED; break;
case NSEventPhaseCancelled: ev.phase = GLFW_SCROLL_PHASE_CANCELLED; break;
case NSEventPhaseMayBegin: ev.phase = GLFW_SCROLL_PHASE_MAY_BEGIN; break;
case NSEventPhaseNone: break;
}
// Only gesture based devices, trackpads and the Magic Mouse, have phases.
// Precise deltas without phases come from devices such as high resolution
// wheels that macOS does not identify.
if (ev.phase != GLFW_SCROLL_PHASE_NONE || ev.momentum_type != GLFW_NO_MOMENTUM_DATA) ev.source = GLFW_SCROLL_SOURCE_FINGER;
else ev.source = [event hasPreciseScrollingDeltas] ? GLFW_SCROLL_SOURCE_UNKNOWN : GLFW_SCROLL_SOURCE_WHEEL;
ev.direction_inverted = [event isDirectionInvertedFromDevice];
_glfwInputScroll(window, &ev);
}

32
glfw/glfw3.h vendored
View file

@ -460,6 +460,33 @@ typedef enum GLFWOffsetType {
GLFW_SCROLL_OFFEST_HIGHRES = 2,
} GLFWOffsetType;
// The kind of device a scroll event comes from
typedef enum GLFWScrollSource {
GLFW_SCROLL_SOURCE_UNKNOWN = 0,
// A wheel, with or without high resolution
GLFW_SCROLL_SOURCE_WHEEL = 1,
// Fingers on a touchpad or trackpad
GLFW_SCROLL_SOURCE_FINGER = 2,
// A continuous device without a physical end of gesture, such as a trackpoint
GLFW_SCROLL_SOURCE_CONTINUOUS = 3,
// Sideways clicks of a wheel
GLFW_SCROLL_SOURCE_WHEEL_TILT = 4,
} GLFWScrollSource;
// Where an event is in a physical scroll gesture. Momentum events, generated
// after the gesture ends, have their phase in momentum_type instead.
typedef enum GLFWScrollPhase {
// The device has no concept of gestures, such as wheel clicks
GLFW_SCROLL_PHASE_NONE = 0,
GLFW_SCROLL_PHASE_BEGAN = 1,
GLFW_SCROLL_PHASE_CHANGED = 2,
// The gesture ended, for example, the fingers were lifted
GLFW_SCROLL_PHASE_ENDED = 3,
GLFW_SCROLL_PHASE_CANCELLED = 4,
// A gesture may begin, for example, the fingers rest on the trackpad
GLFW_SCROLL_PHASE_MAY_BEGIN = 5,
} GLFWScrollPhase;
typedef struct GLFWScrollEvent {
double x_offset, y_offset; // offsets are scaled by the window scale for HIGHRES
struct {
@ -468,6 +495,11 @@ typedef struct GLFWScrollEvent {
GLFWMomentumType momentum_type;
GLFWOffsetType offset_type;
int keyboard_modifiers;
GLFWScrollSource source;
GLFWScrollPhase phase;
// true if the offsets are reversed relative to the physical movement of
// the device, for example, because natural scrolling is enabled
bool direction_inverted;
} GLFWScrollEvent;
// Touch events are reported only for direct touch devices, i.e. touchscreens,

View file

@ -34,6 +34,7 @@ typedef struct MomentumScroller {
double x, y;
} velocity;
int keyboard_modifiers;
bool direction_inverted;
struct {
monotonic_t start, duration;
struct {
@ -71,7 +72,15 @@ cancel_existing_scroll(bool reset_velocity) {
}
if (s.state == MOMENTUM_IN_PROGRESS) {
_GLFWwindow *w = _glfwWindowForId(s.window_id);
if (w) _glfwInputScroll(w, &(GLFWScrollEvent){.momentum_type = GLFW_MOMENTUM_PHASE_CANCELED, .keyboard_modifiers = s.keyboard_modifiers});
if (w)
_glfwInputScroll(
w,
&(GLFWScrollEvent){
.momentum_type = GLFW_MOMENTUM_PHASE_CANCELED,
.offset_type = GLFW_SCROLL_OFFEST_HIGHRES,
.source = GLFW_SCROLL_SOURCE_FINGER,
.direction_inverted = s.direction_inverted,
.keyboard_modifiers = s.keyboard_modifiers});
}
s.window_id = 0;
s.keyboard_modifiers = 0;
@ -152,6 +161,8 @@ static void
send_momentum_event(bool is_start) {
_GLFWwindow *w = _glfwWindowForId(s.window_id);
if (!w || w != _glfwFocusedWindow()) {
// Momentum that never began is not reported as cancelled
if (is_start) s.state = NONE;
cancel_existing_scroll(true);
return;
}
@ -174,6 +185,8 @@ send_momentum_event(bool is_start) {
.unscaled.y = s.velocity.y,
.x_offset = s.scale * s.velocity.x,
.y_offset = s.scale * s.velocity.y,
.source = GLFW_SCROLL_SOURCE_FINGER,
.direction_inverted = s.direction_inverted,
.keyboard_modifiers = s.keyboard_modifiers};
_glfwInputScroll(w, &e);
}
@ -207,7 +220,8 @@ handle_scroll_event(_GLFWwindow *w, const GLFWScrollEvent *ev, bool stopped, boo
return;
}
if (!is_finger_based || ev->offset_type != GLFW_SCROLL_OFFEST_HIGHRES || !glfw_is_momentum_scroll_enabled()) {
if (ev->x_offset != 0 || ev->y_offset != 0) _glfwInputScroll(w, ev);
// Events without offsets are sent only for the gesture phase they carry
if (ev->x_offset != 0 || ev->y_offset != 0 || ev->phase != GLFW_SCROLL_PHASE_NONE) _glfwInputScroll(w, ev);
return;
}
if (s.state == PHYSICAL_EVENT_IN_PROGRESS) {
@ -233,6 +247,7 @@ handle_scroll_event(_GLFWwindow *w, const GLFWScrollEvent *ev, bool stopped, boo
}
s.window_id = w->id;
s.keyboard_modifiers = ev->keyboard_modifiers;
s.direction_inverted = ev->direction_inverted;
if (ev->offset_type == GLFW_SCROLL_OFFEST_HIGHRES) {
if (!is_synthetic_momentum_start_event) add_sample(ev->unscaled.x, ev->unscaled.y, now);
if (stopped) s.state = is_suitable_for_momentum() ? MOMENTUM_IN_PROGRESS : NONE;
@ -240,8 +255,11 @@ handle_scroll_event(_GLFWwindow *w, const GLFWScrollEvent *ev, bool stopped, boo
} else {
s.state = stopped ? NONE : PHYSICAL_EVENT_IN_PROGRESS;
}
if (s.state == MOMENTUM_IN_PROGRESS) start_momentum_scroll(now);
else _glfwInputScroll(w, ev);
if (s.state == MOMENTUM_IN_PROGRESS) {
// Report the end of the physical gesture before the momentum begins
if (ev->phase != GLFW_SCROLL_PHASE_NONE) _glfwInputScroll(w, ev);
start_momentum_scroll(now);
} else _glfwInputScroll(w, ev);
}
void
@ -272,6 +290,7 @@ glfwFeedMomentumScroller(GLFWwindow *handle, double dx, double dy, int keyboard_
.x_offset = dx * (xscale > 0 ? xscale : 1),
.y_offset = dy * (yscale > 0 ? yscale : 1),
.keyboard_modifiers = keyboard_modifiers,
.source = GLFW_SCROLL_SOURCE_FINGER,
};
handle_scroll_event(w, &ev, stopped, true, timestamp > 0 ? timestamp : monotonic(), false);
}

46
glfw/wl_init.c vendored
View file

@ -115,6 +115,18 @@ pointerHandleLeave(void *data UNUSED, struct wl_pointer *pointer UNUSED, uint32_
if (!window) return;
_glfw.wl.serial = serial;
_glfw.wl.pointerFocus = NULL;
if (window->wl.scroll_gesture_in_progress) {
// The end of the gesture will not be delivered to this window
window->wl.scroll_gesture_in_progress = false;
_glfwInputScroll(
window,
&(GLFWScrollEvent){
.phase = GLFW_SCROLL_PHASE_CANCELLED,
.source = window->wl.prev_frame_scroll_source,
.offset_type = window->wl.prev_frame_offset_type,
.direction_inverted = window->wl.prev_frame_direction_inverted,
.keyboard_modifiers = _glfw.wl.xkb.states.modifiers});
}
if (window->wl.surface == surface) {
window->wl.hovered = false;
_glfwInputCursorEnter(window, false);
@ -247,12 +259,36 @@ pointer_handle_frame(void *data UNUSED, struct wl_pointer *pointer UNUSED) {
}
bool stopped = info.y_stop_received || info.x_stop_received;
if (!found && stopped) ev.offset_type = window->wl.prev_frame_offset_type;
if (info.source_received) {
switch (info.source_type) {
case WL_POINTER_AXIS_SOURCE_WHEEL: ev.source = GLFW_SCROLL_SOURCE_WHEEL; break;
case WL_POINTER_AXIS_SOURCE_FINGER: ev.source = GLFW_SCROLL_SOURCE_FINGER; break;
case WL_POINTER_AXIS_SOURCE_CONTINUOUS: ev.source = GLFW_SCROLL_SOURCE_CONTINUOUS; break;
case WL_POINTER_AXIS_SOURCE_WHEEL_TILT: ev.source = GLFW_SCROLL_SOURCE_WHEEL_TILT; break;
default: ev.source = GLFW_SCROLL_SOURCE_UNKNOWN; break;
}
} else if (!found) ev.source = window->wl.prev_frame_scroll_source;
ev.direction_inverted = info.direction_inverted_received ? info.direction_inverted : window->wl.prev_frame_direction_inverted;
// Only finger and continuous sources send axis_stop, so only they have gestures
if (ev.source == GLFW_SCROLL_SOURCE_FINGER || ev.source == GLFW_SCROLL_SOURCE_CONTINUOUS) {
if (stopped) {
ev.phase = GLFW_SCROLL_PHASE_ENDED;
window->wl.scroll_gesture_in_progress = false;
} else if (found) {
ev.phase = window->wl.scroll_gesture_in_progress ? GLFW_SCROLL_PHASE_CHANGED : GLFW_SCROLL_PHASE_BEGAN;
window->wl.scroll_gesture_in_progress = true;
}
}
ev.unscaled.x *= -1;
const double scale = ev.offset_type == GLFW_SCROLL_OFFEST_HIGHRES ? _glfwWaylandWindowScale(window) : 1;
ev.x_offset = scale * ev.unscaled.x;
ev.y_offset = scale * ev.unscaled.y;
glfw_handle_scroll_event_for_momentum(window, &ev, stopped, info.source_type == WL_POINTER_AXIS_SOURCE_FINGER);
if (found) window->wl.prev_frame_offset_type = ev.offset_type;
if (found || info.source_received) {
if (found) window->wl.prev_frame_offset_type = ev.offset_type;
window->wl.prev_frame_scroll_source = ev.source;
window->wl.prev_frame_direction_inverted = ev.direction_inverted;
}
/* clear pointer_curr_axis_info for next frame */
memset(&info, 0, sizeof(info));
}
@ -262,6 +298,7 @@ pointer_handle_axis_source(void *data UNUSED, struct wl_pointer *pointer UNUSED,
_GLFWwindow *window = _glfw.wl.pointerFocus;
if (!window) return;
info.source_type = source;
info.source_received = true;
}
static void
@ -292,7 +329,12 @@ pointer_handle_axis_value120(void *data UNUSED, struct wl_pointer *pointer UNUSE
}
static void
pointer_handle_axis_relative_direction(void *data UNUSED, struct wl_pointer *pointer UNUSED, uint32_t axis UNUSED, uint32_t axis_relative_direction UNUSED) {}
pointer_handle_axis_relative_direction(void *data UNUSED, struct wl_pointer *pointer UNUSED, uint32_t axis UNUSED, uint32_t axis_relative_direction) {
_GLFWwindow *window = _glfw.wl.pointerFocus;
if (!window) return;
info.direction_inverted_received = true;
if (axis_relative_direction == WL_POINTER_AXIS_RELATIVE_DIRECTION_INVERTED) info.direction_inverted = true;
}
#undef info
static const struct wl_pointer_listener pointerListener = {

5
glfw/wl_platform.h vendored
View file

@ -207,11 +207,14 @@ typedef struct _GLFWwindowWayland {
} discrete, continuous;
/* Event timestamp in nanoseconds */
bool x_stop_received, y_stop_received;
bool x_stop_received, y_stop_received, source_received, direction_inverted_received, direction_inverted;
uint32_t source_type;
monotonic_t x_start_time, x_stop_time, y_stop_time, y_start_time;
} pointer_curr_axis_info;
GLFWOffsetType prev_frame_offset_type;
// Axis state that compositors need not repeat in every frame of a gesture
GLFWScrollSource prev_frame_scroll_source;
bool prev_frame_direction_inverted, scroll_gesture_in_progress;
_GLFWcursor *currentCursor;
double cursorPosX, cursorPosY, allCursorPosX, allCursorPosY;

54
glfw/x11_window.c vendored
View file

@ -67,6 +67,7 @@ x11_scroll_stop_timer_callback(unsigned long long timer_id UNUSED, void *data UN
x11_momentum_scroll_state.last_event.x_offset = 0;
x11_momentum_scroll_state.last_event.unscaled.x = 0;
x11_momentum_scroll_state.last_event.unscaled.y = 0;
x11_momentum_scroll_state.last_event.phase = GLFW_SCROLL_PHASE_ENDED;
glfw_handle_scroll_event_for_momentum(w, &x11_momentum_scroll_state.last_event, true, true);
} else {
// Window no longer exists, cancel any ongoing momentum
@ -83,6 +84,25 @@ x11_cancel_momentum_scroll_timer(void) {
x11_momentum_scroll_state.window_id = 0;
}
// XInput has no end of gesture events, so a gesture is considered to end when
// no scroll events arrive for a while. If something other than scrolling
// happens before that, the gesture is cancelled instead.
static void
x11_cancel_scroll_gesture(void) {
if (!x11_momentum_scroll_state.timer_id) return;
_GLFWwindow *w = _glfwWindowForId(x11_momentum_scroll_state.window_id);
GLFWScrollEvent ev = x11_momentum_scroll_state.last_event;
x11_cancel_momentum_scroll_timer();
if (w) {
ev.x_offset = 0;
ev.y_offset = 0;
ev.unscaled.x = 0;
ev.unscaled.y = 0;
ev.phase = GLFW_SCROLL_PHASE_CANCELLED;
_glfwInputScroll(w, &ev);
}
}
// Additional mouse button names for XButtonEvent
#define Button6 6
#define Button7 7
@ -1528,10 +1548,16 @@ handle_xi_motion_event(_GLFWwindow *window, XIDeviceEvent *de) {
.y_offset = yOffset * (type == GLFW_SCROLL_OFFEST_HIGHRES ? _glfw.x11.contentScaleY : 1),
.unscaled = {.x = xOffset, .y = yOffset},
.offset_type = type,
.source = d->is_finger_based ? GLFW_SCROLL_SOURCE_FINGER
: (type == GLFW_SCROLL_OFFEST_HIGHRES ? GLFW_SCROLL_SOURCE_UNKNOWN : GLFW_SCROLL_SOURCE_WHEEL),
};
// For high-resolution, finger-based scrolling, use timer-based momentum scrolling
if (d->is_finger_based && type == GLFW_SCROLL_OFFEST_HIGHRES && glfw_is_momentum_scroll_enabled()) {
// For high-resolution, finger-based scrolling, use a timer to detect
// the end of the gesture, for gesture phases and momentum scrolling
if (d->is_finger_based && type == GLFW_SCROLL_OFFEST_HIGHRES) {
const bool gesture_in_progress = x11_momentum_scroll_state.timer_id && x11_momentum_scroll_state.window_id == window->id;
if (!gesture_in_progress) x11_cancel_scroll_gesture();
ev.phase = gesture_in_progress ? GLFW_SCROLL_PHASE_CHANGED : GLFW_SCROLL_PHASE_BEGAN;
// Reset the timer on each scroll event
x11_cancel_momentum_scroll_timer();
@ -1553,7 +1579,7 @@ handle_xi_motion_event(_GLFWwindow *window, XIDeviceEvent *de) {
}
if (scroll_valuator_found) _glfw.x11.xi.last_smooth_scroll_time = de->time;
else {
x11_cancel_momentum_scroll_timer();
x11_cancel_scroll_gesture();
glfw_cancel_momentum_scroll();
handle_mouse_move_event(window, (int)de->event_x, (int)de->event_y);
}
@ -2062,7 +2088,7 @@ processEvent(XEvent *event) {
case KeyPress: {
UPDATE_KEYMAP_IF_NEEDED;
x11_cancel_momentum_scroll_timer();
x11_cancel_scroll_gesture();
glfw_cancel_momentum_scroll();
glfw_xkb_handle_key_event(window, &_glfw.x11.xkb, event->xkey.keycode, GLFW_PRESS);
return;
@ -2070,7 +2096,7 @@ processEvent(XEvent *event) {
case KeyRelease: {
UPDATE_KEYMAP_IF_NEEDED;
x11_cancel_momentum_scroll_timer();
x11_cancel_scroll_gesture();
glfw_cancel_momentum_scroll();
if (!_glfw.x11.xkb.detectable) {
// HACK: Key repeat events will arrive as KeyRelease/KeyPress
@ -2105,8 +2131,8 @@ processEvent(XEvent *event) {
case ButtonPress: {
const int mods = translateState(event->xbutton.state);
#define cancel_momentum() \
x11_cancel_momentum_scroll_timer(); \
#define cancel_momentum() \
x11_cancel_scroll_gesture(); \
glfw_cancel_momentum_scroll()
if (event->xbutton.button == Button1) {
@ -2126,16 +2152,20 @@ processEvent(XEvent *event) {
// such as from XTEST (x11vnc, xdotool) are handled normally.
else if (event->xbutton.button == Button4) {
if (!isEmulatedScrollButton(&event->xbutton))
_glfwInputScroll(window, &(GLFWScrollEvent){.keyboard_modifiers = mods, .y_offset = 1, .unscaled.y = 1});
_glfwInputScroll(
window, &(GLFWScrollEvent){.keyboard_modifiers = mods, .source = GLFW_SCROLL_SOURCE_WHEEL, .y_offset = 1, .unscaled.y = 1});
} else if (event->xbutton.button == Button5) {
if (!isEmulatedScrollButton(&event->xbutton))
_glfwInputScroll(window, &(GLFWScrollEvent){.keyboard_modifiers = mods, .y_offset = -1, .unscaled.y = -1});
_glfwInputScroll(
window, &(GLFWScrollEvent){.keyboard_modifiers = mods, .source = GLFW_SCROLL_SOURCE_WHEEL, .y_offset = -1, .unscaled.y = -1});
} else if (event->xbutton.button == Button6) {
if (!isEmulatedScrollButton(&event->xbutton))
_glfwInputScroll(window, &(GLFWScrollEvent){.keyboard_modifiers = mods, .x_offset = 1, .unscaled.x = 1});
_glfwInputScroll(
window, &(GLFWScrollEvent){.keyboard_modifiers = mods, .source = GLFW_SCROLL_SOURCE_WHEEL, .x_offset = 1, .unscaled.x = 1});
} else if (event->xbutton.button == Button7) {
if (!isEmulatedScrollButton(&event->xbutton))
_glfwInputScroll(window, &(GLFWScrollEvent){.keyboard_modifiers = mods, .x_offset = -1, .unscaled.x = -1});
_glfwInputScroll(
window, &(GLFWScrollEvent){.keyboard_modifiers = mods, .source = GLFW_SCROLL_SOURCE_WHEEL, .x_offset = -1, .unscaled.x = -1});
}
else {
@ -2209,7 +2239,7 @@ processEvent(XEvent *event) {
handle_drag_motion(root_x, root_y, event->xmotion.time);
}
x11_cancel_momentum_scroll_timer();
x11_cancel_scroll_gesture();
glfw_cancel_momentum_scroll();
handle_mouse_move_event(window, event->xmotion.x, event->xmotion.y);
return;

View file

@ -1161,6 +1161,7 @@ class Screen:
in_bracketed_paste_mode: bool
in_band_resize_notification: bool
paste_events: bool
wheel_events: bool
color_preference_notification: bool
cursor_visible: bool
scrolled_by: int

32
kitty/glfw-wrapper.h generated
View file

@ -296,6 +296,33 @@ typedef enum GLFWOffsetType {
GLFW_SCROLL_OFFEST_HIGHRES = 2,
} GLFWOffsetType;
// The kind of device a scroll event comes from
typedef enum GLFWScrollSource {
GLFW_SCROLL_SOURCE_UNKNOWN = 0,
// A wheel, with or without high resolution
GLFW_SCROLL_SOURCE_WHEEL = 1,
// Fingers on a touchpad or trackpad
GLFW_SCROLL_SOURCE_FINGER = 2,
// A continuous device without a physical end of gesture, such as a trackpoint
GLFW_SCROLL_SOURCE_CONTINUOUS = 3,
// Sideways clicks of a wheel
GLFW_SCROLL_SOURCE_WHEEL_TILT = 4,
} GLFWScrollSource;
// Where an event is in a physical scroll gesture. Momentum events, generated
// after the gesture ends, have their phase in momentum_type instead.
typedef enum GLFWScrollPhase {
// The device has no concept of gestures, such as wheel clicks
GLFW_SCROLL_PHASE_NONE = 0,
GLFW_SCROLL_PHASE_BEGAN = 1,
GLFW_SCROLL_PHASE_CHANGED = 2,
// The gesture ended, for example, the fingers were lifted
GLFW_SCROLL_PHASE_ENDED = 3,
GLFW_SCROLL_PHASE_CANCELLED = 4,
// A gesture may begin, for example, the fingers rest on the trackpad
GLFW_SCROLL_PHASE_MAY_BEGIN = 5,
} GLFWScrollPhase;
typedef struct GLFWScrollEvent {
double x_offset, y_offset; // offsets are scaled by the window scale for HIGHRES
struct {
@ -304,6 +331,11 @@ typedef struct GLFWScrollEvent {
GLFWMomentumType momentum_type;
GLFWOffsetType offset_type;
int keyboard_modifiers;
GLFWScrollSource source;
GLFWScrollPhase phase;
// true if the offsets are reversed relative to the physical movement of
// the device, for example, because natural scrolling is enabled
bool direction_inverted;
} GLFWScrollEvent;
// Touch events are reported only for direct touch devices, i.e. touchscreens,

View file

@ -97,5 +97,8 @@
// Paste events mode https://rockorager.dev/misc/bracketed-paste-mime/
#define PASTE_EVENTS (5522 << 5)
// Detailed reporting of scroll wheel and touchpad events, see the misc-protocol docs
#define WHEEL_EVENTS (5523 << 5)
// Handle Ctrl-C/Ctrl-Z mode
#define HANDLE_TERMIOS_SIGNALS (19997 << 5)

View file

@ -69,7 +69,7 @@ encode_button(unsigned int button) {
}
}
static char mouse_event_buf[64];
static char mouse_event_buf[128];
static int
encode_mouse_event_impl(const MousePosition *mpos, int mouse_tracking_protocol, int button, MouseAction action, int mods) {
@ -1864,6 +1864,158 @@ scroll_phase(GLFWMomentumType t) {
}
// Detailed wheel event reporting {{{
// See the section on detailed wheel events in docs/misc-protocol.rst
typedef enum WheelEventUnit { WHEEL_UNIT_V120 = 1, WHEEL_UNIT_PIXELS = 2 } WheelEventUnit;
enum { WHEEL_FLAG_MOMENTUM = 1, WHEEL_FLAG_INVERTED = 2 };
static unsigned
wheel_event_phase(const GLFWScrollEvent *ev) {
switch (ev->momentum_type) {
case GLFW_NO_MOMENTUM_DATA: break;
case GLFW_MOMENTUM_PHASE_BEGAN: return 1;
case GLFW_MOMENTUM_PHASE_STATIONARY:
case GLFW_MOMENTUM_PHASE_ACTIVE: return 2;
case GLFW_MOMENTUM_PHASE_ENDED: return 3;
case GLFW_MOMENTUM_PHASE_CANCELED: return 4;
case GLFW_MOMENTUM_PHASE_MAY_BEGIN: return 5;
}
switch (ev->phase) {
case GLFW_SCROLL_PHASE_NONE: return 0;
case GLFW_SCROLL_PHASE_BEGAN: return 1;
case GLFW_SCROLL_PHASE_CHANGED: return 2;
case GLFW_SCROLL_PHASE_ENDED: return 3;
case GLFW_SCROLL_PHASE_CANCELLED: return 4;
case GLFW_SCROLL_PHASE_MAY_BEGIN: return 5;
}
return 0;
}
static unsigned
wheel_event_source(GLFWScrollSource s) {
switch (s) {
case GLFW_SCROLL_SOURCE_UNKNOWN: return 0;
case GLFW_SCROLL_SOURCE_WHEEL: return 1;
case GLFW_SCROLL_SOURCE_FINGER: return 2;
case GLFW_SCROLL_SOURCE_CONTINUOUS: return 3;
case GLFW_SCROLL_SOURCE_WHEEL_TILT: return 4;
}
return 0;
}
// Formats a positive number as a short decimal, without an exponent or
// trailing zeros, as needed by the escape code
static void
format_wheel_multiplier(double val, char *buf, size_t sz) {
if (!isfinite(val) || val < 0) val = 0;
int n = snprintf(buf, sz, "%.3f", val);
if (n <= 0 || (size_t)n >= sz) {
snprintf(buf, sz, "1");
return;
}
while (n > 1 && buf[n - 1] == '0') buf[--n] = 0;
if (n > 1 && buf[n - 1] == '.') buf[--n] = 0;
}
// Adds delta to the unreported remainder and returns the whole part of the
// sum, keeping the fraction in remainder. A remainder from the opposite
// direction is discarded, as it would otherwise cancel part of the new delta.
static int
take_whole_wheel_delta(double delta, double *remainder) {
if (delta * *remainder < 0) *remainder = 0;
const double total = *remainder + delta;
const double whole = trunc(total);
*remainder = total - whole;
if (whole > INT_MAX) return INT_MAX;
if (whole < -INT_MAX) return -INT_MAX;
return (int)whole;
}
// Reports a scroll event to the program in the detailed wheel event format.
// Returns the number of bytes written to mouse_event_buf or zero if nothing
// is to be reported.
static int
encode_wheel_event(OSWindow *osw, Window *w, const GLFWScrollEvent *ev) {
Screen *screen = w->render_data.screen;
// GLFW offsets are positive upwards and leftwards, while the escape code
// uses positive downwards and rightwards
double dx = -ev->x_offset, dy = -ev->y_offset, multiplier;
WheelEventUnit unit;
switch (ev->offset_type) {
case GLFW_SCROLL_OFFEST_HIGHRES:
unit = WHEEL_UNIT_PIXELS;
multiplier = OPT(touch_scroll_multiplier);
break;
case GLFW_SCROLL_OFFSET_LINES:
dx *= 120;
dy *= 120;
/* fallthrough */
case GLFW_SCROLL_OFFEST_V120:
default:
unit = WHEEL_UNIT_V120;
multiplier = OPT(wheel_scroll_multiplier);
break;
}
unsigned flags = ev->direction_inverted ? WHEEL_FLAG_INVERTED : 0;
// Only the sign of the multiplier is applied to the deltas, the
// magnitude is sent as a hint
if (multiplier < 0) {
dx = -dx;
dy = -dy;
flags ^= WHEEL_FLAG_INVERTED;
}
if (ev->momentum_type != GLFW_NO_MOMENTUM_DATA) flags |= WHEEL_FLAG_MOMENTUM;
const unsigned phase = wheel_event_phase(ev);
if (osw->scroll.reported_window_id != w->id || osw->scroll.reported_unit != (int)unit || phase == 1) {
osw->scroll.reported_remainder_x = 0;
osw->scroll.reported_remainder_y = 0;
osw->scroll.reported_window_id = w->id;
osw->scroll.reported_unit = unit;
}
const int idx = take_whole_wheel_delta(dx, &osw->scroll.reported_remainder_x);
const int idy = take_whole_wheel_delta(dy, &osw->scroll.reported_remainder_y);
// An event that neither scrolls a whole unit nor changes the phase has
// nothing to report, its fraction is reported with a later event
if (!idx && !idy && (phase == 0 || phase == 2)) return 0;
int x = w->mouse_pos.cell_x + 1, y = w->mouse_pos.cell_y + 1;
if (screen->modes.mouse_tracking_protocol == SGR_PIXEL_PROTOCOL) {
x = (int)round(w->mouse_pos.global_x);
y = (int)round(w->mouse_pos.global_y);
}
char mult[32];
format_wheel_multiplier(fabs(multiplier), mult, sizeof(mult));
const unsigned mods = 1 + ((unsigned)ev->keyboard_modifiers & 0xff);
const int n = snprintf(
mouse_event_buf,
sizeof(mouse_event_buf),
">%d;%d;%d;%d;%d:%s;%u;%u;%u;%uM",
x,
y,
idx,
idy,
unit,
mult,
wheel_event_source(ev->source),
phase,
flags,
mods);
if (n <= 0 || (size_t)n >= sizeof(mouse_event_buf)) {
log_error("Detailed wheel event too long to encode");
return 0;
}
return n;
}
static bool
report_wheel_event(OSWindow *osw, Window *w, const GLFWScrollEvent *ev) {
Screen *screen = w->render_data.screen;
if (!screen->modes.mWHEEL_EVENTS || screen->modes.mouse_tracking_mode == NO_TRACKING) return false;
if (encode_wheel_event(osw, w, ev) > 0) write_escape_code_to_child(screen, ESC_CSI, mouse_event_buf);
return true;
}
// }}}
static inline bool
pixel_scroll_enabled_for_screen(const Screen *screen) {
return OPT(pixel_scroll) && screen->linebuf == screen->main_linebuf;
@ -1909,6 +2061,7 @@ scroll_event_in_window(OSWindow *osw, Window *w, const GLFWScrollEvent *ev, unsi
if (ev->momentum_type == GLFW_MOMENTUM_PHASE_ENDED || ev->momentum_type == GLFW_MOMENTUM_PHASE_CANCELED) osw->scroll.mapped_gesture = false;
return;
}
if (report_wheel_event(osw, w, ev)) return;
finish_scroll_animation(screen);
if (ev->y_offset != 0.0) {
if (screen->modes.mouse_tracking_mode == NO_TRACKING && pixel_scroll_enabled_for_screen(screen) &&
@ -2256,8 +2409,20 @@ static PyObject *
send_mock_scroll_event_to_window(PyObject *self UNUSED, PyObject *args) {
PyObject *capsule;
GLFWScrollEvent ev = {0};
int offset_type, momentum_type = GLFW_NO_MOMENTUM_DATA;
if (!PyArg_ParseTuple(args, "O!iddi|i", &PyCapsule_Type, &capsule, &offset_type, &ev.x_offset, &ev.y_offset, &ev.keyboard_modifiers, &momentum_type))
int offset_type, momentum_type = GLFW_NO_MOMENTUM_DATA, source = GLFW_SCROLL_SOURCE_UNKNOWN, phase = GLFW_SCROLL_PHASE_NONE, inverted = 0;
if (!PyArg_ParseTuple(
args,
"O!iddi|iiip",
&PyCapsule_Type,
&capsule,
&offset_type,
&ev.x_offset,
&ev.y_offset,
&ev.keyboard_modifiers,
&momentum_type,
&source,
&phase,
&inverted))
return NULL;
Window *w = PyCapsule_GetPointer(capsule, "Window");
if (!w) return NULL;
@ -2265,6 +2430,9 @@ send_mock_scroll_event_to_window(PyObject *self UNUSED, PyObject *args) {
static OSWindow osw = {0};
ev.offset_type = offset_type;
ev.momentum_type = momentum_type;
ev.source = source;
ev.phase = phase;
ev.direction_inverted = inverted;
ev.unscaled.x = ev.x_offset;
ev.unscaled.y = ev.y_offset;
scroll_event_in_window(&osw, w, &ev, w->render_data.screen->cell_size.width, w->render_data.screen->cell_size.height);

View file

@ -2521,6 +2521,7 @@ set_mode_from_const(Screen *self, unsigned int mode, bool val) {
switch (mode) {
SIMPLE_MODE(LNM)
SIMPLE_MODE(PASTE_EVENTS)
SIMPLE_MODE(WHEEL_EVENTS)
SIMPLE_MODE(IRM)
SIMPLE_MODE(DECARM)
SIMPLE_MODE(BRACKETED_PASTE)
@ -3190,6 +3191,7 @@ copy_specific_mode(Screen *self, unsigned int mode, const ScreenModes *src, Scre
SIMPLE_MODE(FOCUS_TRACKING)
SIMPLE_MODE(COLOR_PREFERENCE_NOTIFICATION)
SIMPLE_MODE(PASTE_EVENTS)
SIMPLE_MODE(WHEEL_EVENTS)
SIMPLE_MODE(INBAND_RESIZE_NOTIFICATION)
SIMPLE_MODE(VISIBILITY_REPORTS)
SIMPLE_MODE(DECCKM)
@ -3237,6 +3239,7 @@ copy_specific_modes(Screen *self, const ScreenModes *src, ScreenModes *dest) {
copy_specific_mode(self, INBAND_RESIZE_NOTIFICATION, src, dest);
copy_specific_mode(self, VISIBILITY_REPORTS, src, dest);
copy_specific_mode(self, PASTE_EVENTS, src, dest);
copy_specific_mode(self, WHEEL_EVENTS, src, dest);
copy_specific_mode(self, DECCKM, src, dest);
copy_specific_mode(self, DECTCEM, src, dest);
copy_specific_mode(self, DECAWM, src, dest);
@ -3873,6 +3876,7 @@ report_mode_status(Screen *self, unsigned int which, bool private) {
KNOWN_MODE(VISIBILITY_REPORTS);
KNOWN_MODE(INBAND_RESIZE_NOTIFICATION);
KNOWN_MODE(PASTE_EVENTS);
KNOWN_MODE(WHEEL_EVENTS);
#undef KNOWN_MODE
case ALTERNATE_SCREEN: ans = self->linebuf == self->alt_linebuf ? 1 : 2; break;
case MOUSE_BUTTON_TRACKING: ans = self->modes.mouse_tracking_mode == BUTTON_MODE ? 1 : 2; break;
@ -6534,6 +6538,7 @@ MODE_GETSET(focus_tracking_enabled, FOCUS_TRACKING)
MODE_GETSET(color_preference_notification, COLOR_PREFERENCE_NOTIFICATION)
MODE_GETSET(in_band_resize_notification, INBAND_RESIZE_NOTIFICATION)
MODE_GETSET(paste_events, PASTE_EVENTS)
MODE_GETSET(wheel_events, WHEEL_EVENTS)
MODE_GETSET(auto_repeat_enabled, DECARM)
MODE_GETSET(cursor_visible, DECTCEM)
MODE_GETSET(cursor_key_mode, DECCKM)
@ -8233,7 +8238,7 @@ static PyMethodDef methods[] = {
static PyGetSetDef getsetters[] = {
GETSET(in_bracketed_paste_mode) GETSET(color_preference_notification) GETSET(auto_repeat_enabled) GETSET(focus_tracking_enabled)
GETSET(in_band_resize_notification) GETSET(paste_events) GETSET(cursor_visible) GETSET(cursor_key_mode) GETSET(disable_ligatures)
GETSET(in_band_resize_notification) GETSET(paste_events) GETSET(wheel_events) GETSET(cursor_visible) GETSET(cursor_key_mode) GETSET(disable_ligatures)
GETSET(render_unfocused_cursor){NULL} /* Sentinel */
};

View file

@ -25,7 +25,7 @@ typedef struct DnDCommand {
typedef struct {
bool mLNM, mIRM, mDECTCEM, mDECSCNM, mDECOM, mDECAWM, mDECCOLM, mDECARM, mDECCKM, mCOLOR_PREFERENCE_NOTIFICATION, mBRACKETED_PASTE, mFOCUS_TRACKING,
mDECSACE, mHANDLE_TERMIOS_SIGNALS, mINBAND_RESIZE_NOTIFICATION, mPASTE_EVENTS, mVISIBILITY_REPORTS;
mDECSACE, mHANDLE_TERMIOS_SIGNALS, mINBAND_RESIZE_NOTIFICATION, mPASTE_EVENTS, mVISIBILITY_REPORTS, mWHEEL_EVENTS;
MouseTrackingMode mouse_tracking_mode;
MouseTrackingProtocol mouse_tracking_protocol;
} ScreenModes;

View file

@ -682,6 +682,11 @@ typedef struct OSWindow {
int mapped_modifiers;
monotonic_t mapped_last_event_at;
bool mapped_gesture, mapped_grabbed;
// Detailed wheel event reporting: the fractions of the reported
// deltas not yet sent and the window and unit they belong to
double reported_remainder_x, reported_remainder_y;
id_type reported_window_id;
int reported_unit;
} scroll;
ShaderAnimEventMask shader_anim_event_registry;
id_type last_bell_window_id; // ID of the most recent window that received a bell event

View file

@ -677,6 +677,73 @@ class TestMouse(BaseTest):
self.ae(steps(LINES, [1.0, 0.1]), [-1, -1])
self.ae(steps(V120, [120.0, 240.0]), [-1, -2])
def test_wheel_events(self):
LINES, V120, HIGHRES = 0, 1, 2 # GLFWOffsetType
MOMENTUM_BEGAN, MOMENTUM_ACTIVE, MOMENTUM_ENDED = 1, 3, 4 # GLFWMomentumType
WHEEL, FINGER = 1, 2 # GLFWScrollSource
BEGAN, CHANGED, ENDED = 1, 2, 3 # GLFWScrollPhase
s = self.create_screen(lines=5, scrollback=50)
self.set_options({'pixel_scroll': False, 'wheel_scroll_multiplier': 5.0, 'touch_scroll_multiplier': 1.5})
w = create_mock_window(s)
def scroll(y=0.0, x=0.0, offset_type=LINES, mods=0, momentum=0, source=0, phase=0, inverted=False):
s.callbacks.wtcbuf = b''
send_mock_scroll_event_to_window(w, offset_type, float(x), float(y), mods, momentum, source, phase, inverted)
return s.callbacks.wtcbuf.decode()
def ae(expected, **kw):
self.ae(scroll(**kw), ''.join(f'\x1b[>1;1;{e}M' for e in expected))
# Without mouse tracking the mode has no effect and the scrollback scrolls
parse_bytes(s, b'\x1b[?5523h')
self.assertTrue(s.wheel_events)
ae([], y=1)
parse_bytes(s, b'\x1b[?1000h')
# Wheels report whole clicks as 120, positive is downwards, the
# multiplier is only a hint and the deltas are not repeated
ae(['0;-360;1:5;1;0;0;1'], y=3, source=WHEEL)
ae(['0;120;1:5;1;0;0;1'], y=-1, source=WHEEL)
# Horizontal scrolling, positive is rightwards
ae(['-120;0;1:5;1;0;0;1'], x=1, source=WHEEL)
# High resolution wheels
ae(['0;30;1:5;0;0;0;1'], y=-30, offset_type=V120)
# Modifiers use the keyboard protocol encoding
ae(['0;120;1:5;0;0;0;7'], y=-1, mods=GLFW_MOD_CONTROL | GLFW_MOD_ALT)
ae(['0;120;1:5;0;0;0;65'], y=-1, mods=GLFW_MOD_CAPS_LOCK)
# A touchpad gesture with fractional pixels, which are accumulated
ae(['0;0;2:1.5;2;1;0;1'], y=0, offset_type=HIGHRES, source=FINGER, phase=BEGAN)
ae(['3;-2;2:1.5;2;2;0;1'], x=-3.5, y=2.5, offset_type=HIGHRES, source=FINGER, phase=CHANGED)
ae(['1;-1;2:1.5;2;2;0;1'], x=-0.5, y=0.5, offset_type=HIGHRES, source=FINGER, phase=CHANGED)
# Less than a pixel in the same phase has nothing to report
ae([], y=0.25, offset_type=HIGHRES, source=FINGER, phase=CHANGED)
ae(['0;-1;2:1.5;2;2;0;1'], y=0.75, offset_type=HIGHRES, source=FINGER, phase=CHANGED)
# A change of phase is always reported
ae(['0;0;2:1.5;2;3;0;1'], offset_type=HIGHRES, source=FINGER, phase=ENDED)
# Momentum
ae(['0;-10;2:1.5;2;1;1;1'], y=10, offset_type=HIGHRES, source=FINGER, momentum=MOMENTUM_BEGAN)
ae(['0;-5;2:1.5;2;2;1;1'], y=5, offset_type=HIGHRES, source=FINGER, momentum=MOMENTUM_ACTIVE)
ae(['0;0;2:1.5;2;3;1;1'], offset_type=HIGHRES, source=FINGER, momentum=MOMENTUM_ENDED)
# Natural scrolling
ae(['0;-10;2:1.5;2;1;2;1'], y=10, offset_type=HIGHRES, source=FINGER, phase=BEGAN, inverted=True)
# A negative multiplier reverses the deltas and the inverted flag
self.set_options({'pixel_scroll': False, 'wheel_scroll_multiplier': -2.25})
ae(['0;-120;1:2.25;1;0;2;1'], y=-1, source=WHEEL)
ae(['0;-120;1:2.25;1;0;0;1'], y=-1, source=WHEEL, inverted=True)
# SGR pixel mode reports the position in pixels
parse_bytes(s, b'\x1b[?1016h')
self.ae(scroll(y=-1, source=WHEEL), '\x1b[>0;0;0;-120;1:2.25;1;0;2;1M')
# Turning the mode off restores legacy reporting
parse_bytes(s, b'\x1b[?1016l\x1b[?1006h\x1b[?5523l')
self.assertFalse(s.wheel_events)
self.ae(scroll(y=-1, source=WHEEL), '\x1b[<64;1;1M')
# DECRQM
s.callbacks.wtcbuf = b''
parse_bytes(s, b'\x1b[?5523$p')
self.ae(s.callbacks.wtcbuf, b'\x1b[?5523;2$y')
s.callbacks.wtcbuf = b''
parse_bytes(s, b'\x1b[?5523h\x1b[?5523$p')
self.ae(s.callbacks.wtcbuf, b'\x1b[?5523;1$y')
def test_mapped_scroll(self):
from kitty.config import load_config