Gtk 4 - grab keyboard

In preferences of my gnome shell extension I have a keyboard shortcut editor. When editing a shortcut, it needs to catch all keys, including fn/media keys. On Gtk 3 I can achieve it using Gdk.Seat.grab() on the default seat. However, I can’t find any replacement for it in Gtk/Gdk 4, and the migration guide tells to stop using grabs. So how do I catch fn/media keys?

I wonder how Gnome Settings will be ported to Gtk 4 https://gitlab.gnome.org/GNOME/gnome-control-center/-/blob/master/panels/keyboard/cc-keyboard-shortcut-editor.c#L213

If your player supports MPRIS it should receive media keys from gsd-media-keys automatically through those methods, without needing to grab.

Alternatively, if using MPD or something similar, you could configure “Custom Shortcuts” to run a command line tool such as mpc when pressing the media keys. But even that may be unnecessary, you may have better results with a bridge like mpdris2.

If I’m misunderstanding and you only need it for a shortcut editor, you likely don’t need a grab there, simply making the dialog modal will cause it to capture keyboard focus for that application.

Yes, I only need grabs for shortcut editor. Shortcuts are then handled in a shell extension using Main.wm.addKeybinding().

It’s not a media player: https://github.com/amezin/gnome-shell-extension-ddterm
And I got this feature request: https://github.com/amezin/gnome-shell-extension-ddterm/issues/33

My own keyboard has special keys like “Explorer”, “Mail”. And I need Gdk.Seat.grab() to catch them in the shortcut editor - otherwise the shell handles them, and the application (preferences dialog) gets no events at all.

You can use gdk_toplevel_inhibit_system_shortcuts on the dialog, to prevent the shell from handling those keys.

Thank you, exactly what I was looking for.

Is gdk_seat_grab(default_seat, window, GDK_SEAT_CAPABILITY_KEYBOARD, …) the correct approach on Gtk 3? Or is there something better/cleaner?

It looks like that is the way to do it, it does the same thing in Wayland GDK3: https://gitlab.gnome.org/GNOME/gtk/-/blob/e024a542b0e669cc9088edd88a098abc7e1fe5aa/gdk/wayland/gdkdevice-wayland.c#L4988

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.