I'm trying to get the current keyboard modifiers state through gnome GDK or GTK library in aim to implement an accessibility gnome shell extension that shows that state.
I know how to get thier state using xlib, but there is not full binding for gnome gjs.
The code below get only the initial state. It does not update state.
/*
* compiling: gcc `pkg-config --cflags gdk-3.0` -o gdk_mod gdk_mod.c `pkg-config --libs gdk-3.0`
*/
#include <gdk/gdk.h>
int main (int argc, char **argv) {
gdk_init(&argc, &argv);
GdkDisplay * disp;
disp = gdk_display_open(NULL);
if (disp!=NULL) g_printf("display connected!\n");
GdkKeymap * kmap;
kmap = gdk_keymap_get_for_display(disp);
guint state;
state = gdk_keymap_get_modifier_state(kmap);
g_printf("mod state: %x\n", state);
while (1) {
g_usleep(1000000);
//kmap = gdk_keymap_get_for_display(disp);
state = gdk_keymap_get_modifier_state(kmap);
g_printf("mod state: %x\n", state);
}
}
Here an example output with CAPS lock active then inactive but no change:
$ ./gdk_mod
display found!
mod state: 2
mod state: 2
mod state: 2
mod state: 2
mod state: 2
^C
Currently using Kubuntu 15.04.
What's wrong with my code?
Indeed, I need an event loop as andlabs said in his comment. His suggestion to use GTK
gtk_init()
>k_main()
works perfectly.I could also use GDK with GLib GMainLoop.
References:
You are going to need to run the GTK+ event loop for this to work. The event loop is part of GLib's main loop. When you call
gtk_main()
, this main loop is run. I don't know if it polls for events or has events pushed to it, but it won't ask for the keyboard state on the fly like you were trying to do.The easiest way to set up GDK is to do it via GTK+ by using
gtk_init()
andgtk_main()
. You can use GDK on its own, but I don't know how. You seemed to have figured it out, which works.And instead of calling
g_usleep()
, which just blocks your program, you can hook a periodic timeout into the main loop. This is done withg_timeout_add()
. The function that you pass tog_timeout_add()
returns a Boolean value that decides whether the timer should be stopped or not, so you don't have to worry about rescheduling your function, as GLib will do that for you.