From e6561b633721c987806f7118c5916668caea14b8 Mon Sep 17 00:00:00 2001 From: Zhizhen He Date: Fri, 23 Oct 2026 03:21:17 +0800 Subject: [PATCH 1/2] Respect mouse mappings for link hover feedback Follow configured mouse actions for the hand pointer and hover underline, and refresh both on modifier changes without requiring mouse movement. Cover URL detection, hyperlink highlighting, configuration variants, and link dragging with focused regression tests. --- docs/changelog.rst | 5 +++ kitty/config.py | 20 +++++++++++- kitty/glfw.c | 6 +++- kitty/mouse.c | 36 ++++++++++++++------- kitty/options/definition.py | 5 +++ kitty/state.c | 10 +++++- kitty/state.h | 2 ++ kitty_tests/mouse.py | 61 ++++++++++++++++++++++++++++++++++- kitty_tests/selection_drag.py | 3 +- 9 files changed, 131 insertions(+), 17 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index b177f54a2..5bf3c34a7 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -234,6 +234,11 @@ Detailed list of changes - Remote control: Fix a crash when using damaged images with :code:`set-window-logo` or :code:`set-background-image` (:pull:`10715`) +- Show the hand pointer and hover highlighting over links only when the pressed + modifiers match a configured mouse action for opening the link. Update both + immediately when modifiers are pressed or released, even without moving the + mouse. + - Transfer kitten: When receiving files, replace existing symbolic and hard links at the destination instead of overwriting the files they point to. Files are now written to a temporary file and renamed into place, so an diff --git a/kitty/config.py b/kitty/config.py index 4e8444872..04a47e1d5 100644 --- a/kitty/config.py +++ b/kitty/config.py @@ -12,7 +12,7 @@ from .conf.utils import BadLine, parse_config_base from .conf.utils import load_config as _load_config from .constants import cache_dir, defconf from .options.types import Options, defaults, option_names -from .options.utils import KeyboardMode, KeyboardModeMap, KeyDefinition, MouseMap, MouseMapping, build_action_aliases +from .options.utils import KeyboardMode, KeyboardModeMap, KeyDefinition, MapType, MouseMap, MouseMapping, build_action_aliases from .typing_compat import TypedDict from .utils import log_error @@ -143,6 +143,24 @@ def finalize_mouse_mappings(opts: Options, accumulate_bad_lines: list[BadLine] | opts.mousemap = mousemap +def mouse_url_modifiers(opts: Options) -> tuple[int, int]: + from .fast_data_types import GLFW_MOUSE_BUTTON_LAST + from .keys import mod_mask + + modifiers = [0, 0] + for event, definition in opts.mousemap.items(): + if not 0 <= event.button <= GLFW_MOUSE_BUTTON_LAST or event.mods & ~mod_mask: + continue + try: + actions = opts.alias_map.resolve_aliases(definition, MapType.MOUSE_MAP) + except Exception as err: + log_error(f'Ignoring mouse_map with invalid action: {definition}. Error: {err}') + continue + if any(a.func in ('mouse_click_url', 'mouse_click_url_or_select') or (a.func == 'mouse_handle_click' and 'link' in a.args) for a in actions): + modifiers[event.grabbed] |= 1 << event.mods + return modifiers[0], modifiers[1] + + def parse_config( lines: Iterable[str], accumulate_bad_lines: list[BadLine] | None = None, diff --git a/kitty/glfw.c b/kitty/glfw.c index 43897bba7..edad0dd4a 100644 --- a/kitty/glfw.c +++ b/kitty/glfw.c @@ -601,11 +601,15 @@ key_callback(GLFWwindow *w, GLFWkeyevent *ev) { #ifndef __APPLE__ if (key_modifier != -1) update_modifier_state_on_modifier_key_event(ev, key_modifier, is_left); #endif + const int old_mods = global_state.mods_at_last_key_or_button_event; global_state.mods_at_last_key_or_button_event = ev->mods; global_state.callback_os_window->cursor_blink_zero_time = monotonic(); global_state.callback_os_window->user_is_idle = false; global_state.callback_os_window->shader_anim_event_registry |= (1u << SHADER_ANIM_EVENT_USER_ACTIVITY); - if (is_window_ready_for_callbacks() && !ev->fake_event_on_focus_change) on_key_input(ev); + if (is_window_ready_for_callbacks()) { + if ((old_mods ^ ev->mods) & ~GLFW_LOCK_MASK) update_mouse_pointer_shape(); + if (!ev->fake_event_on_focus_change) on_key_input(ev); + } global_state.callback_os_window = NULL; request_tick_callback(); } diff --git a/kitty/mouse.c b/kitty/mouse.c index 2466c4feb..4835bfa35 100644 --- a/kitty/mouse.c +++ b/kitty/mouse.c @@ -19,6 +19,8 @@ extern PyTypeObject Screen_Type; static MouseShape mouse_cursor_shape = TEXT_POINTER; typedef enum MouseActions { PRESS, RELEASE, DRAG, MOVE, LEAVE } MouseAction; #define debug debug_input +#define MOUSE_MAPPING_MODS_MASK (GLFW_MOD_SHIFT | GLFW_MOD_ALT | GLFW_MOD_CONTROL | GLFW_MOD_SUPER | GLFW_MOD_HYPER | GLFW_MOD_META) +static_assert(MOUSE_MAPPING_MODS_MASK < 64, "mouse mapping modifiers must fit in a uint64_t bitmap"); static void finish_scroll_animation(Screen *screen) { @@ -432,18 +434,23 @@ handle_mouse_movement_in_kitty(Window *w, int button, bool mouse_cell_changed) { } static void -detect_url(Screen *screen, unsigned int x, unsigned int y) { +detect_url(Screen *screen, unsigned int x, unsigned int y, int modifiers) { int hid = screen_detect_url(screen, x, y); zero_at_ptr(&screen->current_hyperlink_under_mouse); + set_mouse_cursor_for_screen(screen); if (hid != 0) { - mouse_cursor_shape = POINTER_POINTER; + if (OPT(url_mappings)[screen->modes.mouse_tracking_mode != NO_TRACKING] & (1ull << (modifiers & MOUSE_MAPPING_MODS_MASK))) { + mouse_cursor_shape = POINTER_POINTER; + } else { + screen_mark_url(screen, 0, 0, 0, 0); + } screen->current_hyperlink_under_mouse.has_detected_url = hid < 0; if (hid > 0) { screen->current_hyperlink_under_mouse.id = (hyperlink_id_type)hid; screen->current_hyperlink_under_mouse.x = x; screen->current_hyperlink_under_mouse.y = y; } - } else set_mouse_cursor_for_screen(screen); + } } static bool @@ -721,7 +728,7 @@ HANDLER(handle_move_event) { return; } Screen *screen = w->render_data.screen; - if (OPT(detect_urls)) detect_url(screen, w->mouse_pos.cell_x, w->mouse_pos.cell_y); + if (OPT(detect_urls)) detect_url(screen, w->mouse_pos.cell_x, w->mouse_pos.cell_y, modifiers); if (should_handle_in_kitty(w, screen, button)) { handle_mouse_movement_in_kitty(w, button, mouse_cell_changed | cell_half_changed); } else { @@ -798,7 +805,8 @@ add_press(Window *w, int button, int modifiers) { bool mouse_open_url(Window *w) { Screen *screen = w->render_data.screen; - detect_url(screen, w->mouse_pos.cell_x, w->mouse_pos.cell_y); + // Opening a URL must work even when hover highlighting is disabled. + screen_detect_url(screen, w->mouse_pos.cell_x, w->mouse_pos.cell_y); return screen_open_url(screen, "open_url"); } @@ -1168,6 +1176,9 @@ focus_in_event(void) { void update_mouse_pointer_shape(void) { + if (global_state.redirect_mouse_handling || global_state.active_drag_in_window || global_state.tracked_drag_in_window || + global_state.tab_being_dragged.id || global_state.window_being_dragged.id || global_state.active_drag_resize) + return; mouse_cursor_shape = TEXT_POINTER; MouseRegion r = mouse_region(false, true); if (r.in_tab_bar) { @@ -1180,6 +1191,10 @@ update_mouse_pointer_shape(void) { } else if (r.window->render_data.screen) { screen_mark_url(r.window->render_data.screen, 0, 0, 0, 0); set_mouse_cursor_for_screen(r.window->render_data.screen); + bool mouse_cell_changed, cell_half_changed; + if (OPT(detect_urls) && set_mouse_position(r.window, &mouse_cell_changed, &cell_half_changed)) { + detect_url(r.window->render_data.screen, r.window->mouse_pos.cell_x, r.window->mouse_pos.cell_y, global_state.mods_at_last_key_or_button_event); + } } } set_mouse_cursor(mouse_cursor_shape); @@ -1595,9 +1610,6 @@ mapped_scroll_steps(GLFWOffsetType offset_type, double offset, double *pending, // Bit i of wheel_mappings[button - MOUSE_WHEEL_UP][grabbed] is set when the wheel is mapped // with the modifiers i, so that unmapped scrolling never calls into Python. -#define WHEEL_MAPPING_MODS_MASK (GLFW_MOD_SHIFT | GLFW_MOD_ALT | GLFW_MOD_CONTROL | GLFW_MOD_SUPER | GLFW_MOD_HYPER | GLFW_MOD_META) -static_assert(WHEEL_MAPPING_MODS_MASK < 64, "wheel mapping modifiers must fit in a uint64_t bitmap"); - bool set_wheel_mappings(PyObject *py_opts, Options *opts) { memset(opts->wheel_mappings, 0, sizeof(opts->wheel_mappings)); @@ -1618,7 +1630,7 @@ set_wheel_mappings(PyObject *py_opts, Options *opts) { const long button = PyLong_AsLong(PyTuple_GET_ITEM(key, 0)), mods = PyLong_AsLong(PyTuple_GET_ITEM(key, 1)); if (PyErr_Occurred()) return false; // modifiers outside the mask are stripped from events, so such a mapping can never match - if (button < MOUSE_WHEEL_UP || button > MOUSE_WHEEL_RIGHT || (mods & ~WHEEL_MAPPING_MODS_MASK)) continue; + if (button < MOUSE_WHEEL_UP || button > MOUSE_WHEEL_RIGHT || (mods & ~MOUSE_MAPPING_MODS_MASK)) continue; const int grabbed = PyObject_IsTrue(PyTuple_GET_ITEM(key, 3)); if (grabbed < 0) return false; opts->wheel_mappings[button - MOUSE_WHEEL_UP][grabbed] |= 1ull << mods; @@ -1746,7 +1758,7 @@ scroll_event_in_window(OSWindow *osw, Window *w, const GLFWScrollEvent *ev, unsi } if (ev->momentum_type == GLFW_NO_MOMENTUM_DATA) { const bool grabbed = screen->modes.mouse_tracking_mode != NO_TRACKING; - const int mods = ev->keyboard_modifiers & WHEEL_MAPPING_MODS_MASK; + const int mods = ev->keyboard_modifiers & MOUSE_MAPPING_MODS_MASK; if (dispatch_mapped_scroll(osw, w, ev, mods, grabbed)) osw->scroll.mapped_gesture = true; else if (osw->scroll.mapped_gesture) { osw->scroll.mapped_gesture = continues_mapped_gesture(osw, w, ev, mods, grabbed); @@ -1937,7 +1949,7 @@ send_mock_mouse_event_to_window(PyObject *self UNUSED, PyObject *args) { if (button == -2) do_drag_scroll(w, true); else if (button == -3) do_drag_scroll(w, false); else { - if (OPT(detect_urls)) detect_url(w->render_data.screen, x, y); + if (OPT(detect_urls)) detect_url(w->render_data.screen, x, y, modifiers); handle_mouse_movement_in_kitty(w, last_button_pressed, mouse_cell_changed); handle_potential_drag(w, last_button_pressed); } @@ -1954,7 +1966,7 @@ send_mock_mouse_event_to_window(PyObject *self UNUSED, PyObject *args) { } } } - Py_RETURN_NONE; + return PyLong_FromLong(mouse_cursor_shape); } static PyObject * diff --git a/kitty/options/definition.py b/kitty/options/definition.py index 2305ca7c7..f695c6d81 100644 --- a/kitty/options/definition.py +++ b/kitty/options/definition.py @@ -1226,6 +1226,11 @@ Mouse buttons can be mapped to perform arbitrary actions. The syntax is: mouse_map button-name event-type modes action +The mouse pointer changes to a hand and links are highlighted on hover only when +the current keyboard modifiers and grabbed/ungrabbed mode match a mouse mapping +that opens the link. Both update when modifiers are pressed or released, even +if the mouse does not move. + Where :code:`button-name` is one of :code:`left`, :code:`middle`, :code:`right`, :code:`b1` ... :code:`b8`, :code:`wheel_up`, :code:`wheel_down`, :code:`wheel_left`, :code:`wheel_right` with added keyboard modifiers. For example: :code:`ctrl+shift+left` refers to holding the diff --git a/kitty/state.c b/kitty/state.c index da1b97dc3..222a36b4a 100644 --- a/kitty/state.c +++ b/kitty/state.c @@ -382,7 +382,7 @@ initialize_window(Window *w, PyObject *title, bool init_gpu_resources) { if (PyErr_Occurred()) PyErr_Print(); } if (init_gpu_resources) create_gpu_resources_for_window(w); - else { w->render_data.vao_idx = -1; } + else { w->render_data.vao_idx = w->window_title_render_data.vao_idx = -1; } } static id_type @@ -1148,6 +1148,14 @@ PYWRAP1(set_options) { global_state.debug_font_fallback = debug_font_fallback ? true : false; if (!convert_opts_from_python_opts(opts, &global_state.opts)) return NULL; if (!set_wheel_mappings(opts, &global_state.opts)) return NULL; + RAII_PyObject(config, PyImport_ImportModule("kitty.config")); + if (!config) return NULL; + RAII_PyObject(url_modifiers, PyObject_CallMethod(config, "mouse_url_modifiers", "O", opts)); + if (!url_modifiers) return NULL; + for (size_t i = 0; i < arraysz(global_state.opts.url_mappings); i++) { + global_state.opts.url_mappings[i] = PyLong_AsUnsignedLongLong(PyTuple_GET_ITEM(url_modifiers, i)); + if (PyErr_Occurred()) return NULL; + } if (!set_vertical_tab_bar_padding(opts, &global_state.opts)) return NULL; push_modifier_remap_to_glfw(); Py_XDECREF(global_state.options_object); diff --git a/kitty/state.h b/kitty/state.h index cef0655ab..977d2728b 100644 --- a/kitty/state.h +++ b/kitty/state.h @@ -134,6 +134,8 @@ typedef struct Options { // wheel with the modifiers i, button is 0 for wheel_up, 1 for wheel_down, // 2 for wheel_left and 3 for wheel_right uint64_t wheel_mappings[4][2]; + // Bit i is set when a mouse button opens the hovered URL with modifiers i. + uint64_t url_mappings[2]; // ungrabbed, grabbed bool window_alert_on_bell; bool macos_dock_badge_on_bell; bool debug_keyboard; diff --git a/kitty_tests/mouse.py b/kitty_tests/mouse.py index c3439a3eb..a3358c2e7 100644 --- a/kitty_tests/mouse.py +++ b/kitty_tests/mouse.py @@ -4,8 +4,10 @@ from functools import partial from time import sleep +from kitty.config import load_config from kitty.fast_data_types import ( GLFW_MOD_ALT, + GLFW_MOD_CAPS_LOCK, GLFW_MOD_CONTROL, GLFW_MOD_SHIFT, GLFW_MOUSE_BUTTON_LEFT, @@ -34,10 +36,67 @@ def send_mouse_event( ): ix = int(x) in_left_half_of_cell = x - ix < 0.5 - send_mock_mouse_event_to_window(window, button, modifiers, is_release, ix, y, clear_click_queue, in_left_half_of_cell, pixel_x, pixel_y) + return send_mock_mouse_event_to_window(window, button, modifiers, is_release, ix, y, clear_click_queue, in_left_half_of_cell, pixel_x, pixel_y) class TestMouse(BaseTest): + def test_link_hover_modifiers(self): + s = self.create_screen(cols=60) + s.draw('https://example.invalid/') + parse_bytes(s, b'\r\n\x1b]8;;https://example.invalid/\x1b\\hyperlink\x1b]8;;\x1b\\\r\nsrc/file.py:42') + w = create_mock_window(s) + hover = partial(send_mouse_event, w, x=2) + normal_shape = send_mouse_event(w, x=50) + link_shape = hover() + self.assertNotEqual(normal_shape, link_shape) + + def configure(*lines): + set_options(load_config(overrides=('clear_all_mouse_actions yes', 'detect_url_regex [[:alnum:]_./-]+:[0-9]+', *lines))) + + def check(mods, clickable, y=0): + self.ae(hover(modifiers=mods, y=y), link_shape if clickable else normal_shape) + expected = ('https://example.invalid/', 'hyperlink', 'src/file.py:42')[y] if clickable else '' + self.ae(''.join(s.text_for_marked_url()), expected) + # The renderer uses bit 1 of the selection buffer for URL underlines. + self.ae(sum(bool(cell & 2) for cell in s.current_selections()), len(expected)) + + mods = GLFW_MOD_CONTROL | GLFW_MOD_SHIFT + configure('mouse_map ctrl+shift+left release grabbed,ungrabbed mouse_handle_click link') + for y in (0, 1, 2): + for held, clickable in ( + (0, False), + (GLFW_MOD_CONTROL, False), + (mods, True), + (mods | GLFW_MOD_ALT, False), + (mods | GLFW_MOD_CAPS_LOCK, True), + (0, False), + ): + # Repeated events in the same cell must respond to modifier changes. + check(held, clickable, y) + + configure('mouse_map left click ungrabbed mouse_handle_click selection link prompt') + check(0, True) + check(mods, False) + parse_bytes(s, b'\x1b[?1000h') + normal_shape = send_mouse_event(w, x=50) + check(0, False) + configure('mouse_map alt+left release grabbed mouse_click_url') + check(GLFW_MOD_ALT, True) + check(0, False) + parse_bytes(s, b'\x1b[?1000l') + normal_shape = send_mouse_event(w, x=50) + check(GLFW_MOD_ALT, False) + + configure('action_alias follow_link mouse_handle_click link', 'mouse_map alt+left release ungrabbed follow_link') + check(GLFW_MOD_ALT, True) + check(0, False) + configure('mouse_map left click ungrabbed combine : mouse_handle_click link : discard_event') + check(0, True) + configure('mouse_map left click ungrabbed mouse_click_url_or_select') + check(0, True) + configure('mouse_map left click ungrabbed mouse_click_url', 'mouse_map left click ungrabbed') + check(0, False) + def test_mouse_selection(self): s = self.create_screen(options=dict(rectangle_select_modifiers=GLFW_MOD_ALT | GLFW_MOD_CONTROL)) w = create_mock_window(s) diff --git a/kitty_tests/selection_drag.py b/kitty_tests/selection_drag.py index 7d026b185..bab38757f 100644 --- a/kitty_tests/selection_drag.py +++ b/kitty_tests/selection_drag.py @@ -130,7 +130,7 @@ class TestSelectionDrag(BaseTest): self.ae(drags, ['alpha']) def test_selection_drag_links(self): - s, ev, drags = self.drag_screen() + s, ev, drags = self.drag_screen('mouse_map left click ungrabbed') s.draw('https://example.com') urls = [] s.callbacks.drag_url = lambda url, hyperlink_id: urls.append(url) @@ -142,6 +142,7 @@ class TestSelectionDrag(BaseTest): self.ae(urls, []) s.clear_selection() ev(x=10) + self.assertNotIn(2, s.current_selections()) ev(LEFT, x=10, clear_click_queue=True) ev(x=11) self.ae(urls, ['https://example.com']) From 4e9ff82c77c0b23563c092c23a588140ddaa67c9 Mon Sep 17 00:00:00 2001 From: Zhizhen He Date: Fri, 23 Oct 2026 12:59:35 +0800 Subject: [PATCH 2/2] Fix link hover regressions identified in review Refresh hover feedback only in the hovered pane when modifier changes alter whether a single-click link action matches. Preserve resize and drag cursors and keep OSC 22 pointer updates independent of modifier handling. Compute link modifier masks while finalizing mouse mappings, clarify the documentation, and cover the reported regressions with mock pointer events. --- docs/changelog.rst | 10 ++-- kitty/config.py | 18 +++----- kitty/glfw.c | 5 +- kitty/mouse.c | 91 +++++++++++++++++++++++++++++++++---- kitty/options/definition.py | 13 +++--- kitty/options/types.py | 3 +- kitty/options/utils.py | 1 + kitty/state.c | 15 +++--- kitty/state.h | 1 + kitty_tests/mouse.py | 62 +++++++++++++++++++++++++ 10 files changed, 180 insertions(+), 39 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 5bf3c34a7..948a12044 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -234,11 +234,6 @@ Detailed list of changes - Remote control: Fix a crash when using damaged images with :code:`set-window-logo` or :code:`set-background-image` (:pull:`10715`) -- Show the hand pointer and hover highlighting over links only when the pressed - modifiers match a configured mouse action for opening the link. Update both - immediately when modifiers are pressed or released, even without moving the - mouse. - - Transfer kitten: When receiving files, replace existing symbolic and hard links at the destination instead of overwriting the files they point to. Files are now written to a temporary file and renamed into place, so an @@ -251,6 +246,11 @@ Detailed list of changes status bars, file trees, etc. Create them with :code:`launch --type=window-dock` or :code:`launch --type=tab-dock`, see :ref:`docks` +- Show the hand pointer and hover highlighting over links only when the pressed + modifiers match a configured mouse action for opening the link with a single + click. Update both immediately when modifiers are pressed or released, even + without moving the mouse. + - A new option :opt:`restore_session_after_logout` to save the state of every kitty instance, including the scrollback of every window, when logging out, restarting or shutting down the computer and restore it the next time diff --git a/kitty/config.py b/kitty/config.py index 04a47e1d5..67b39f263 100644 --- a/kitty/config.py +++ b/kitty/config.py @@ -121,6 +121,9 @@ def finalize_keys(opts: Options, accumulate_bad_lines: list[BadLine] | None = No def finalize_mouse_mappings(opts: Options, accumulate_bad_lines: list[BadLine] | None = None) -> None: + from .fast_data_types import GLFW_MOUSE_BUTTON_LAST + from .keys import mod_mask + defns: list[MouseMapping] = [] for d in opts.mouse_map: if d is None: # clear_all_mouse_actions @@ -141,15 +144,9 @@ def finalize_mouse_mappings(opts: Options, accumulate_bad_lines: list[BadLine] | else: mousemap.pop(defn.trigger, None) opts.mousemap = mousemap - - -def mouse_url_modifiers(opts: Options) -> tuple[int, int]: - from .fast_data_types import GLFW_MOUSE_BUTTON_LAST - from .keys import mod_mask - - modifiers = [0, 0] - for event, definition in opts.mousemap.items(): - if not 0 <= event.button <= GLFW_MOUSE_BUTTON_LAST or event.mods & ~mod_mask: + opts.url_mappings = {False: 0, True: 0} + for event, definition in mousemap.items(): + if not 0 <= event.button <= GLFW_MOUSE_BUTTON_LAST or event.mods & ~mod_mask or event.repeat_count not in (-2, -1, 1): continue try: actions = opts.alias_map.resolve_aliases(definition, MapType.MOUSE_MAP) @@ -157,8 +154,7 @@ def mouse_url_modifiers(opts: Options) -> tuple[int, int]: log_error(f'Ignoring mouse_map with invalid action: {definition}. Error: {err}') continue if any(a.func in ('mouse_click_url', 'mouse_click_url_or_select') or (a.func == 'mouse_handle_click' and 'link' in a.args) for a in actions): - modifiers[event.grabbed] |= 1 << event.mods - return modifiers[0], modifiers[1] + opts.url_mappings[event.grabbed] |= 1 << event.mods def parse_config( diff --git a/kitty/glfw.c b/kitty/glfw.c index edad0dd4a..8cbe4cd9a 100644 --- a/kitty/glfw.c +++ b/kitty/glfw.c @@ -607,7 +607,7 @@ key_callback(GLFWwindow *w, GLFWkeyevent *ev) { global_state.callback_os_window->user_is_idle = false; global_state.callback_os_window->shader_anim_event_registry |= (1u << SHADER_ANIM_EVENT_USER_ACTIVITY); if (is_window_ready_for_callbacks()) { - if ((old_mods ^ ev->mods) & ~GLFW_LOCK_MASK) update_mouse_pointer_shape(); + update_link_hover_for_modifiers(old_mods, ev->mods); if (!ev->fake_event_on_focus_change) on_key_input(ev); } global_state.callback_os_window = NULL; @@ -1615,7 +1615,8 @@ set_glfw_mouse_pointer_shape_in_window(GLFWwindow *w, MouseShape type) { void set_mouse_cursor(MouseShape type) { - if (global_state.callback_os_window) { + // Headless mock OS windows have no native cursor. + if (global_state.callback_os_window && global_state.callback_os_window->handle) { GLFWwindow *w = (GLFWwindow *)global_state.callback_os_window->handle; set_glfw_mouse_pointer_shape_in_window(w, type); } diff --git a/kitty/mouse.c b/kitty/mouse.c index 4835bfa35..80e812ce7 100644 --- a/kitty/mouse.c +++ b/kitty/mouse.c @@ -1176,9 +1176,6 @@ focus_in_event(void) { void update_mouse_pointer_shape(void) { - if (global_state.redirect_mouse_handling || global_state.active_drag_in_window || global_state.tracked_drag_in_window || - global_state.tab_being_dragged.id || global_state.window_being_dragged.id || global_state.active_drag_resize) - return; mouse_cursor_shape = TEXT_POINTER; MouseRegion r = mouse_region(false, true); if (r.in_tab_bar) { @@ -1189,12 +1186,7 @@ update_mouse_pointer_shape(void) { if (handle_scrollbar_mouse(r.window, -1, MOVE, 0)) { mouse_cursor_shape = scrollbar_drag_mouse_cursor; } else if (r.window->render_data.screen) { - screen_mark_url(r.window->render_data.screen, 0, 0, 0, 0); set_mouse_cursor_for_screen(r.window->render_data.screen); - bool mouse_cell_changed, cell_half_changed; - if (OPT(detect_urls) && set_mouse_position(r.window, &mouse_cell_changed, &cell_half_changed)) { - detect_url(r.window->render_data.screen, r.window->mouse_pos.cell_x, r.window->mouse_pos.cell_y, global_state.mods_at_last_key_or_button_event); - } } } set_mouse_cursor(mouse_cursor_shape); @@ -1206,6 +1198,30 @@ leave_event(int modifiers) { set_currently_hovered_window(0, modifiers, false); } +bool +update_link_hover_for_modifiers(int old_mods, int new_mods) { + old_mods &= MOUSE_MAPPING_MODS_MASK; + new_mods &= MOUSE_MAPPING_MODS_MASK; + OSWindow *osw = global_state.callback_os_window; + if (old_mods == new_mods || !OPT(detect_urls) || !osw || !osw->num_tabs || !global_state.mouse_hover_in_window || global_state.redirect_mouse_handling || + global_state.active_drag_in_window || global_state.tracked_drag_in_window || global_state.tab_being_dragged.id || + global_state.window_being_dragged.id || global_state.active_drag_resize) + return false; + Tab *tab = osw->tabs + osw->active_tab; + for (unsigned i = 0; i < tab->num_windows; i++) { + Window *w = tab->windows + i; + if (w->id != global_state.mouse_hover_in_window) continue; + Screen *screen = w->render_data.screen; + if (!w->visible || !screen || w->scrollbar.is_hovering || w->scrollbar.is_dragging) return false; + const uint64_t mappings = OPT(url_mappings)[screen->modes.mouse_tracking_mode != NO_TRACKING]; + if (((mappings >> old_mods) & 1) == ((mappings >> new_mods) & 1)) return false; + detect_url(screen, w->mouse_pos.cell_x, w->mouse_pos.cell_y, new_mods); + set_mouse_cursor(mouse_cursor_shape); + return true; + } + return false; +} + void enter_event(int modifiers, bool cursor_moved) { #ifdef __APPLE__ @@ -1969,6 +1985,64 @@ send_mock_mouse_event_to_window(PyObject *self UNUSED, PyObject *args) { return PyLong_FromLong(mouse_cursor_shape); } +static PyObject * +update_mock_pointer(PyObject *self UNUSED, PyObject *args) { + PyObject *capsule; + int old_mods, new_mods, inside = 1; + unsigned drag = 0, border = 0; + const char *pointer_shape = NULL; + if (!PyArg_ParseTuple(args, "O!ii|pIIs", &PyCapsule_Type, &capsule, &old_mods, &new_mods, &inside, &drag, &border, &pointer_shape)) return NULL; + Window *w = PyCapsule_GetPointer(capsule, "Window"); + if (!w) return NULL; + Screen *screen = w->render_data.screen; + GlobalState saved = global_state; + MouseShape saved_shape = mouse_cursor_shape; + Window windows[] = {*w, *w}; + windows[1].id++; + windows[0].render_data.geometry = (WindowGeometry){.right = screen->columns * 10, .bottom = screen->lines * 20}; + windows[1].render_data.geometry = windows[0].render_data.geometry; + BorderRect rect = {.border_type = (int)w->id, .horizontal = border == 2}; + rect.px.left = (unsigned)w->mouse_pos.global_x; + rect.px.right = rect.px.left + 1; + rect.px.top = (unsigned)w->mouse_pos.global_y; + rect.px.bottom = rect.px.top + 1; + Tab tab = {.windows = windows, .num_windows = border ? 2 : 1}; + tab.border_rects.rect_buf = ▭ + tab.border_rects.num_border_rects = border ? 1 : 0; + struct { + FONTS_DATA_HEAD + } fonts = {.logical_dpi_x = 72, .logical_dpi_y = 72, .fcm = {.cell_width = 10, .cell_height = 20}}; + OSWindow osw = { + .tabs = &tab, + .num_tabs = 1, + .has_too_few_tabs = true, + .fonts_data = (FONTS_DATA_HANDLE)&fonts, + .viewport_width = screen->columns * 10, + .viewport_height = screen->lines * 20, + .mouse_x = w->mouse_pos.global_x, + .mouse_y = w->mouse_pos.global_y}; + global_state.callback_os_window = &osw; + global_state.mouse_hover_in_window = global_state.active_drag_in_window = global_state.tracked_drag_in_window = global_state.active_drag_resize = 0; + global_state.tab_being_dragged.id = global_state.window_being_dragged.id = 0; + global_state.redirect_mouse_handling = false; + global_state.mods_at_last_key_or_button_event = old_mods; + mouse_event(-1, old_mods, -1); + if (!inside) leave_event(old_mods); + if (drag == 1) global_state.active_drag_in_window = w->id; + else if (drag == 2) global_state.tracked_drag_in_window = w->id; + global_state.mods_at_last_key_or_button_event = new_mods; + bool updated = false; + if (pointer_shape) { + RAII_PyObject(ret, PyObject_CallMethod((PyObject *)screen, "change_pointer_shape", "ss", "=", pointer_shape)); + if (ret) update_mouse_pointer_shape(); + } else updated = update_link_hover_for_modifiers(old_mods, new_mods); + MouseShape result = mouse_cursor_shape; + global_state = saved; + mouse_cursor_shape = saved_shape; + if (PyErr_Occurred()) return NULL; + return Py_BuildValue("(iO)", result, updated ? Py_True : Py_False); +} + static PyObject * test_scale_scroll(PyObject *self UNUSED, PyObject *args) { PyObject *values; @@ -2043,6 +2117,7 @@ static PyMethodDef module_methods[] = { METHODB(test_scale_scroll, METH_VARARGS), METHODB(test_mapped_scroll_steps, METH_VARARGS), METHODB(send_mock_mouse_event_to_window, METH_VARARGS), + METHODB(update_mock_pointer, METH_VARARGS), METHODB(send_mock_scroll_event_to_window, METH_VARARGS), METHODB(mock_mouse_selection, METH_VARARGS), {NULL, NULL, 0, NULL} /* Sentinel */ diff --git a/kitty/options/definition.py b/kitty/options/definition.py index f695c6d81..fde432e1c 100644 --- a/kitty/options/definition.py +++ b/kitty/options/definition.py @@ -17,7 +17,7 @@ definition = Definition( {'keyboard_modes': 'KeyboardModeMap', 'alias_map': 'AliasMap'}, ['KeyDefinition', 'KeyMapOptions', 'kitty.fast_data_types.SingleKey'], ), - Action('mouse_map', 'parse_mouse_map', {'mousemap': 'MouseMap'}, ['MouseMapping']), + Action('mouse_map', 'parse_mouse_map', {'mousemap': 'MouseMap', 'url_mappings': 'URLMappings'}, ['MouseMapping']), has_color_table=True, ) definition.add_deprecation('deprecated_hide_window_decorations_aliases', 'x11_hide_window_decorations', 'macos_hide_titlebar') @@ -1226,11 +1226,6 @@ Mouse buttons can be mapped to perform arbitrary actions. The syntax is: mouse_map button-name event-type modes action -The mouse pointer changes to a hand and links are highlighted on hover only when -the current keyboard modifiers and grabbed/ungrabbed mode match a mouse mapping -that opens the link. Both update when modifiers are pressed or released, even -if the mouse does not move. - Where :code:`button-name` is one of :code:`left`, :code:`middle`, :code:`right`, :code:`b1` ... :code:`b8`, :code:`wheel_up`, :code:`wheel_down`, :code:`wheel_left`, :code:`wheel_right` with added keyboard modifiers. For example: :code:`ctrl+shift+left` refers to holding the @@ -1275,6 +1270,12 @@ grabbed by the program running in the terminal, or not. The values are mouse events. Note that the click and double click events have a delay of :opt:`click_interval` to disambiguate from double and triple presses. +The mouse pointer changes to a hand and links are highlighted on hover only when +the current keyboard modifiers and grabbed/ungrabbed mode match a mouse mapping +that opens the link on a single :code:`press`, :code:`release` or :code:`click`. +Both update when modifiers are pressed or released, even if the mouse does not +move. Mappings that require a double or triple click do not enable hover feedback. + You can run kitty with the :option:`kitty --debug-input` command line option to see mouse events. See the builtin actions below to get a sense of what is possible. diff --git a/kitty/options/types.py b/kitty/options/types.py index 4d7f5cdca..3718efcbd 100644 --- a/kitty/options/types.py +++ b/kitty/options/types.py @@ -12,7 +12,7 @@ from kitty.fonts import FontSpec import kitty.fonts from kitty.options.utils import ( AliasMap, KeyDefinition, KeyFallbackType, KeyMapOptions, KeyboardModeMap, MouseHideWait, MouseMap, - MouseMapping, NotifyOnCmdFinish, TabBarMarginHeight + MouseMapping, NotifyOnCmdFinish, TabBarMarginHeight, URLMappings ) import kitty.options.utils from kitty.types import FloatEdges @@ -762,6 +762,7 @@ class Options: alias_map: AliasMap = AliasMap() mouse_map: list[kitty.options.utils.MouseMapping] = [] mousemap: MouseMap = {} + url_mappings: URLMappings = {} color_table: "array[int]" = array("L", ( 0x000000, 0xcc0403, 0x19cb00, 0xcecb00, 0x0d73cc, 0xcb1ed1, 0x0dcdcd, 0xdddddd, 0x767676, 0xf2201f, 0x23fd00, 0xfffd00, 0x1a8fff, 0xfd28ff, 0x14ffff, 0xffffff, diff --git a/kitty/options/utils.py b/kitty/options/utils.py index 60b41be5f..a286edf49 100644 --- a/kitty/options/utils.py +++ b/kitty/options/utils.py @@ -47,6 +47,7 @@ from kitty.utils import expandvars, log_error, resolve_abs_or_config_path, shlex KeyMap = dict[SingleKey, list['KeyDefinition']] MouseMap = dict[MouseEvent, str] +URLMappings = dict[bool, int] KeySequence = tuple[SingleKey, ...] MINIMUM_FONT_SIZE = 4 # Zooming is limited to a multiple of the configured font size, or to this diff --git a/kitty/state.c b/kitty/state.c index 222a36b4a..3fd06de0e 100644 --- a/kitty/state.c +++ b/kitty/state.c @@ -382,7 +382,11 @@ initialize_window(Window *w, PyObject *title, bool init_gpu_resources) { if (PyErr_Occurred()) PyErr_Print(); } if (init_gpu_resources) create_gpu_resources_for_window(w); - else { w->render_data.vao_idx = w->window_title_render_data.vao_idx = -1; } + else { + // Mock windows have no graphics context. Neither VAO may be deleted when + // the mock window is destroyed by the mouse regression tests. + w->render_data.vao_idx = w->window_title_render_data.vao_idx = -1; + } } static id_type @@ -1148,12 +1152,11 @@ PYWRAP1(set_options) { global_state.debug_font_fallback = debug_font_fallback ? true : false; if (!convert_opts_from_python_opts(opts, &global_state.opts)) return NULL; if (!set_wheel_mappings(opts, &global_state.opts)) return NULL; - RAII_PyObject(config, PyImport_ImportModule("kitty.config")); - if (!config) return NULL; - RAII_PyObject(url_modifiers, PyObject_CallMethod(config, "mouse_url_modifiers", "O", opts)); - if (!url_modifiers) return NULL; + RAII_PyObject(url_mappings, PyObject_GetAttrString(opts, "url_mappings")); + if (!url_mappings) return NULL; for (size_t i = 0; i < arraysz(global_state.opts.url_mappings); i++) { - global_state.opts.url_mappings[i] = PyLong_AsUnsignedLongLong(PyTuple_GET_ITEM(url_modifiers, i)); + PyObject *mask = PyDict_GetItem(url_mappings, i ? Py_True : Py_False); + global_state.opts.url_mappings[i] = mask ? PyLong_AsUnsignedLongLong(mask) : 0; if (PyErr_Occurred()) return NULL; } if (!set_vertical_tab_bar_padding(opts, &global_state.opts)) return NULL; diff --git a/kitty/state.h b/kitty/state.h index 977d2728b..cd5060fa7 100644 --- a/kitty/state.h +++ b/kitty/state.h @@ -851,6 +851,7 @@ void update_menu_bar_title(PyObject *title UNUSED); void change_live_resize_state(OSWindow *, bool); bool render_os_window(OSWindow *w, monotonic_t now, bool scan_for_animated_images); void update_mouse_pointer_shape(void); +bool update_link_hover_for_modifiers(int old_mods, int new_mods); void adjust_window_size_for_csd(OSWindow *w, int width, int height, int *adjusted_width, int *adjusted_height); void dispatch_buffered_keys(Window *w); void free_buffered_keys(Window *w); diff --git a/kitty_tests/mouse.py b/kitty_tests/mouse.py index a3358c2e7..1335b258e 100644 --- a/kitty_tests/mouse.py +++ b/kitty_tests/mouse.py @@ -10,6 +10,7 @@ from kitty.fast_data_types import ( GLFW_MOD_CAPS_LOCK, GLFW_MOD_CONTROL, GLFW_MOD_SHIFT, + GLFW_MOD_SUPER, GLFW_MOUSE_BUTTON_LEFT, GLFW_MOUSE_BUTTON_RIGHT, MOUSE_SELECTION_WORD_AND_LINE_FROM_POINT, @@ -18,6 +19,7 @@ from kitty.fast_data_types import ( send_mock_mouse_event_to_window, send_mock_scroll_event_to_window, set_options, + update_mock_pointer, ) from .base import BaseTest, parse_bytes @@ -97,6 +99,66 @@ class TestMouse(BaseTest): configure('mouse_map left click ungrabbed mouse_click_url', 'mouse_map left click ungrabbed') check(0, False) + for event in ('press', 'release', 'click'): + configure(f'mouse_map cmd+left {event} ungrabbed mouse_handle_click link') + check(GLFW_MOD_SUPER, True) + check(0, False) + for event in ('doublepress', 'triplepress', 'doubleclick'): + configure(f'mouse_map left {event} ungrabbed mouse_click_url') + check(0, False) + + def test_link_hover_key_events(self): + s = self.create_screen(cols=60) + s.draw('https://example.invalid/') + w = create_mock_window(s) + link_shape = send_mouse_event(w, x=2) + mods = GLFW_MOD_CONTROL | GLFW_MOD_SHIFT + set_options( + load_config( + overrides=( + 'clear_all_mouse_actions yes', + 'mouse_map ctrl+shift+left release grabbed,ungrabbed mouse_handle_click link', + 'mouse_map cmd+left release grabbed,ungrabbed mouse_handle_click link', + ) + ) + ) + for tracking in (False, True): + parse_bytes(s, b'\x1b[?1000h' if tracking else b'\x1b[?1000l') + normal_shape = send_mouse_event(w, x=50) + send_mouse_event(w, x=2) + for held in (mods, GLFW_MOD_SUPER): + for old, new, highlighted in ((0, held, True), (held, 0, False)): + self.ae(update_mock_pointer(w, old, new), (link_shape if highlighted else normal_shape, True)) + self.ae(bool(''.join(s.text_for_marked_url())), highlighted) + self.ae(update_mock_pointer(w, 0, held, False)[1], False) + self.ae(''.join(s.text_for_marked_url()), '') + for old, new in ((0, GLFW_MOD_SHIFT), (mods, GLFW_MOD_SUPER), (mods, mods | GLFW_MOD_CAPS_LOCK)): + self.ae(update_mock_pointer(w, old, new)[1], False) + for drag in (1, 2): + self.ae(update_mock_pointer(w, 0, mods, True, drag)[1], False) + + def test_link_hover_preserves_border_cursor(self): + s = self.create_screen(cols=60) + s.draw('https://example.invalid/') + w = create_mock_window(s) + send_mouse_event(w, x=2) + mods = GLFW_MOD_CONTROL | GLFW_MOD_SHIFT + for border in (1, 2): + shape, updated = update_mock_pointer(w, 0, 0, True, 0, border) + self.ae(updated, False) + self.ae(update_mock_pointer(w, 0, mods, True, 0, border), (shape, False)) + + def test_pointer_shape_during_mouse_drag(self): + s = self.create_screen(cols=60) + parse_bytes(s, b'\x1b[?1000h') + w = create_mock_window(s) + for drag in (1, 2): + for name in ('grabbing', 'ew-resize'): + s.change_pointer_shape('=', name) + expected = send_mouse_event(w, x=2) + s.change_pointer_shape('=', 'text') + self.ae(update_mock_pointer(w, 0, 0, True, drag, 0, name)[0], expected) + def test_mouse_selection(self): s = self.create_screen(options=dict(rectangle_select_modifiers=GLFW_MOD_ALT | GLFW_MOD_CONTROL)) w = create_mock_window(s)