How to handle keyboard events in gnome shell extensions?

时光总嘲笑我的痴心妄想 提交于 2019-12-03 22:17:36

I came across this snippet in gcampax's gtk-js-app template some time ago, which may be related to what you're doing:

// Due to limitations of gobject-introspection wrt GdkEvent and GdkEventKey,
// this needs to be a signal handler
this.connect('key-press-event', Lang.bind(this, this._handleKeyPress));

and

_handleKeyPress: function(self, event) {
    return this.main_search_bar.handle_event(event);
},

I haven't had a need to use keyboard events yet, and this is Gtk in GJS, but the same limitation may be affecting gnome-shell extensions.

UPDATE

I've been doing some keybinding stuff lately, and if attaching a signal handler to the global object is working, you can do something like this:

global.display.connect("key-press-event", (widget, event, user_data) => {
    let [success, keyval] = event.get_keyval(); // integer
    let keyname = Gdk.keyval_name(keyval); // string keyname

    if (keyname === "Control_L") {
        // Dialog code or eg. this.keys_array.push("<Ctrl>");
    }
});

There's also some Shell keybinding code here and some shell-global documentation here that might give you more clues. Wish I could help more but I'm wrestling my own GJS atm ;)

ADDENDUM

There is a good answer here with an example class with informative logging, as well as a speculative explanation. I've also found this functionality is exposed over DBus which might be more convenient in some cases:

Bus Name: org.gnome.Shell -> Path: /org/gnome/Shell -> Interface: org.gnome.Shell

Relevant Methods:

  • GrabAccelerator(String accelerator, UInt32 flags) -> (UInt32 action)
  • UngrabAccelerator(UInt32 action) -> (Boolean success)

Signal:

  • AcceleratorActivate(UInt32, Dict of {String, Variant})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!