-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsuperkb.c
632 lines (500 loc) · 17.7 KB
/
superkb.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
/*
* superkb.c
*
* Copyright (C) 2006, Octavio Alvarez Piza.
* License: GNU General Public License v2.
*
*/
/* Superkb: This modules does all the key and event handling magic. */
#include <X11/Xlib.h>
#include <X11/XKBlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <assert.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <sys/time.h>
#include "superkb.h"
#include "globals.h"
#include "debug.h"
#include "timeval.h"
long unsigned int keygrab1_serial = -1;
long unsigned int keygrab2_serial = -1;
int superkey1_grabfail = 0;
int superkey2_grabfail = 0;
void (*__Action)(KeyCode keycode, unsigned int state);
/* Start PRESSED KEYS STACK */
typedef struct pressed_keys_element {
int keycode;
int state;
} pressed_key_t;
pressed_key_t *pressed_keys = NULL;
int pressed_keys_n = 0;
void remove_from_pressed_key_stack(int keycode, int state)
{
int x;
int y;
for (x = pressed_keys_n-1; x >=0; x--) {
assert(pressed_keys != NULL);
if (pressed_keys[x].keycode == keycode &&
pressed_keys[x].state == state) {
/* Item to be removed found. */
for (y = x; y < pressed_keys_n-1; y++) {
pressed_keys[y].keycode = pressed_keys[y+1].keycode;
pressed_keys[y].state = pressed_keys[y+1].state;
}
list_rmv_element(pressed_keys, pressed_keys_n, pressed_key_t);
}
}
}
void push_into_pressed_key_stack(int keycode, int state)
{
list_add_element(pressed_keys, pressed_keys_n, pressed_key_t);
assert(pressed_keys != NULL);
pressed_keys[pressed_keys_n-1].keycode = keycode;
pressed_keys[pressed_keys_n-1].state = state;
}
void clear_pressed_key_stack() {
if (pressed_keys != NULL) {
free (pressed_keys);
pressed_keys = NULL;
}
pressed_keys_n = 0;
}
/* End PRESSED KEYS STACK */
/* This function is the same as XNextEvent but a timeout can be
* specified in "to". It's supposed to accept NULL for no timeout
* as the function works like a wrapper for select().
*
* It works by select()ing on XConnectionNumber(display) to wait either
* for incoming traffic or timeout. If the former is found, return the
* next event.
*
* RETURNS == 0 ? Timed out before getting an event.
* RETURNS < 0 ? Error. Useful to get EINTR. Return set to -errno.
* RETURNS > 0 ? Event catched.
*/
int
XNextEventWithTimeout(Display * display, XEvent * event_return,
struct timeval *to)
{
fd_set fd;
int r;
XFlush(display);
if (QLength(display) > 0) {
XNextEvent(display, event_return);
return 1;
}
FD_ZERO(&fd);
FD_SET(XConnectionNumber(display), &fd);
do {
r = select(FD_SETSIZE, &fd, NULL, NULL, to);
} while(r == -1 && errno == EINTR);
if (r == -1) {
/* Some error other than EINTR. */
return -errno;
}
if (r == 0) {
/* Timeout */
return r;
}
XNextEvent(display, event_return);
return 1;
}
enum to_index {
TO_CONFIG = 0,
TO_DRAWKB = 1
};
#define to_n 2
struct timeval to[to_n];
int saved_key1_autorepeat_mode = 0;
int saved_key2_autorepeat_mode = 0;
void superkb_restore_auto_repeat(superkb_p this) {
XKeyboardControl xkbc;
if (this->key1) {
xkbc.key = this->key1;
xkbc.auto_repeat_mode = saved_key1_autorepeat_mode;
XChangeKeyboardControl(this->dpy, KBAutoRepeatMode | KBKey, &xkbc);
}
if (this->key2) {
xkbc.key = this->key2;
xkbc.auto_repeat_mode = saved_key2_autorepeat_mode;
XChangeKeyboardControl(this->dpy, KBAutoRepeatMode | KBKey, &xkbc);
}
}
int display_generic_x_error(Display *dpy, XErrorEvent *xerrev) {
char buf[80];
XGetErrorText(dpy, xerrev->error_code, (char *) buf, sizeof (buf)-1);
fprintf(stderr, "X Error of failed request: %s\n", buf);
XGetErrorDatabaseText(dpy, "Xproto", "XError", "Unknown error", (char *) &buf, sizeof (buf)-1);
fprintf(stderr, " Major opcode of failed request: %d (%s)\n", xerrev->request_code, buf);
fprintf(stderr, " Serial number of failed request: %d\n", xerrev->minor_code);
fprintf(stderr, " Current serial number in output stream: %ld\n", xerrev->serial);
abort();
}
int xerror_handler(Display *dpy, XErrorEvent *xerrev) {
if (xerrev->serial == keygrab1_serial) {
superkey1_grabfail = 1;
} else if (xerrev->serial == keygrab2_serial) {
superkey2_grabfail = 1;
} else {
display_generic_x_error(dpy, xerrev);
}
return 0;
}
void one_superkey_used_friendly_warning(int number, const char *keyname) {
const char *ordinal = "A";
if (number == 1)
ordinal = "Your first";
if (number == 2)
ordinal = "Your second";
fprintf(stderr,
"WARNING: %s configured Super key (%s) is already in\n"
" use by another program (usually Compiz). You may continue using Superkb\n"
" using your second Super key. You may want to try the following to avoid\n"
" this error:\n"
" * Load Superkb before the conflicting program by loading it right\n"
" at startup. (Under GNOME, use System > Startup Applications.)\n"
" * Unload or kill the conflicting program.\n"
" * Clear the configuration for the first Super key by adding\n"
" \"SUPERKEY%d_CODE 0\" in your $HOME/.superkbrc.)\n"
"\n", ordinal, keyname, number
);
}
int key_is_pressed (Display *dpy, KeyCode keycode)
{
char key_buffer [32];
XQueryKeymap(dpy, key_buffer);
return ( (key_buffer[keycode >> 3] >> (keycode & 0x07)) & 0x01 );
}
void superkb_start(superkb_p this)
{
XSynchronize(this->dpy, True);
XSetErrorHandler(xerror_handler);
/* Solicitar los eventos */
if (this->key1 != 0) {
keygrab1_serial = NextRequest(this->dpy);
XGrabKey(this->dpy, this->key1, AnyModifier, this->rootwin, True,
GrabModeAsync, GrabModeAsync);
}
if (this->key2 != 0) {
keygrab2_serial = NextRequest(this->dpy);
XGrabKey(this->dpy, this->key2, AnyModifier, this->rootwin, True,
GrabModeAsync, GrabModeAsync);
}
XSynchronize(this->dpy, False);
XSetErrorHandler(NULL);
int t1 = (this->key1 != 0);
int f1 = superkey1_grabfail;
int t2 = (this->key2 != 0);
int f2 = superkey2_grabfail;
if ((t1 && f1 && t2 && f2) || (t1 && f1 && !t2) || (t2 && f2 && !t1)) {
fprintf(stderr,
"ERROR: Some other program (usually Compiz or another Superkb) is already\n"
" using your Super keys. You may want to try either of the following:\n"
" * Load Superkb before the conflicting program by loading it right\n"
" at startup. (Under GNOME, use System > Startup Applications.)\n"
" * Unload or kill the conflicting program.\n"
" * Try a different set of Super keys. (Remember that Superkb supports\n"
" two Super keys; if you don't use the second one you must clear it\n"
" using \"SUPERKEY2_CODE 0\" in your $HOME/.superkbrc.)\n"
"\n"
);
abort();
}
if (t1 && t2 && !f1 && f2) {
one_superkey_used_friendly_warning(1, XKeysymToString(XkbKeycodeToKeysym(this->dpy, this->key1, 0, 0)));
}
if (t1 && t2 && f1 && !f2) {
one_superkey_used_friendly_warning(2, XKeysymToString(XkbKeycodeToKeysym(this->dpy, this->key2, 0, 0)));
}
XKeyboardState xkbs;
int x;
/* Save autorepeat previous state. Then turn off. */
XGetKeyboardControl(this->dpy, &xkbs);
saved_key1_autorepeat_mode = (xkbs.auto_repeats[(int) (this->key1/8)] & (1 << (this->key1 % 8))) > 0;
XGetKeyboardControl(this->dpy, &xkbs);
saved_key2_autorepeat_mode = (xkbs.auto_repeats[(int) (this->key2/8)] & (1 << (this->key2 % 8))) > 0;
/* FIXME: Autorepeat must be restored on end */
XKeyboardControl xkbc;
if (this->key1) {
xkbc.key = this->key1;
xkbc.auto_repeat_mode = AutoRepeatModeOff;
XChangeKeyboardControl(this->dpy, KBAutoRepeatMode | KBKey, &xkbc);
}
if (this->key2) {
xkbc.key = this->key2;
xkbc.auto_repeat_mode = AutoRepeatModeOff;
XChangeKeyboardControl(this->dpy, KBAutoRepeatMode | KBKey, &xkbc);
}
int ignore_release = 0;
int saved_autorepeat_mode = 0;
/* Counter, in case user presses both Supers and releases only one. */
int super_was_active = 0;
debug (2, "[ar] super_was_active has been initialized to %d.\n", super_was_active);
/* Initialize timeouts to be inactive. */
timerclear(&to[TO_DRAWKB]);
timerclear(&to[TO_CONFIG]);
(*this->welcome_message)();
fprintf(stderr,
"\n\n"
"Superkb is now running!\n"
"\n"
"Press and hold any of your configured Super keys to start using it.\n"
"\n"
);
while (1) {
struct timeval hold_start;
struct timeval hold_end;
XEvent ev;
int XNEWT_ret = 0;
int i;
int to_reason = 0;
int super_replay = 0;
XEvent event_save_for_replay;
Window event_saved_window = 0xFFFFFFFFL;
memset(&ev, 0, sizeof(ev));
/* Decide wether to use XNextEvent or my own XNextEventWithTimeout
* and do accordingly. If WithTimeout was used, substract the
* time actually elapsed to the set timeout. */
for (i = 0; i < to_n; i++) {
if (timerisset(&to[i])) {
to_reason = i;
break;
}
}
if (i == to_n) {
debug (4, "[xn] Calling XNextEventWithTimeout(this->dpy, &ev, NULL)\n");
XNEWT_ret = XNextEventWithTimeout(this->dpy, &ev, NULL);
} else {
gettimeofday(&hold_start, NULL);
for (i = to_reason + 1; i < to_n; i++) {
if (timerisset(&to[i])) {
if (timercmp(&to[i], &to[to_reason], <))
to_reason = i;
}
}
/* Man pages say that Linux select() modifies timeout where
* other implementations don't. We oughta save timeout and restore
* it after select().
*/
struct timeval timeout_save;
memcpy(&timeout_save, &to[to_reason], sizeof(struct timeval));
/* I hope select() takes proper care of negative timeouts.
* It happens sometimes.
*/
if (to[to_reason].tv_sec >= 0 &&
to[to_reason].tv_usec >= 0) {
debug (4, "[xn] Calling XNextEventWithTimeout(this->dpy, &ev, &to[to_reason]) to_reason = %d\n", to_reason);
XNEWT_ret = XNextEventWithTimeout(this->dpy, &ev, &to[to_reason]);
}
/* Restore. */
memcpy(&to[to_reason], &timeout_save, sizeof(struct timeval));
gettimeofday(&hold_end, NULL);
struct timeval hold_time;
/* Update all timers */
timersub(&hold_end, &hold_start, &hold_time);
for (i = 0; i < to_n; i++) {
if (timerisset(&to[i])) {
timersub(&to[i], &hold_time, &to[i]);
}
}
}
if (XNEWT_ret == -EINTR)
break;
if (XNEWT_ret == 0) {
/* Timed out */
if (to_reason == TO_CONFIG) {
debug(9, "[kc] Placeholder: key config window should pop up here.\n");
timerclear(&to[TO_CONFIG]);
ignore_release = 1;
int squashed_state = ev.xkey.state & this->state_mask;
remove_from_pressed_key_stack(ev.xkey.keycode, squashed_state);
}
if (to_reason == TO_DRAWKB) {
super_replay = 0;
timerclear(&to[TO_DRAWKB]);
/* Map Window. */
if (this->kbwin.map)
this->kbwin.map(this->dpy);
}
} else if (ev.xany.window != this->rootwin) {
this->kbwin.event(this->dpy, ev);
} else if (ev.xkey.keycode == this->key1
|| ev.xkey.keycode == this->key2) {
if (ev.type == KeyPress) {
ignore_release = 0;
debug(1, "[sk] Super key has been pressed, code: %d, name: %s.\n", ev.xkey.keycode,
XKeysymToString(XkbKeycodeToKeysym(this->dpy, ev.xkey.keycode, 0, 0)));
if (super_was_active++) {
super_replay = 0;
debug(2, "[sa] super_was_active increased to %d, not taking action.\n", super_was_active);
continue;
}
debug(2, "[sa] super_was_active increased to %d, taking action.\n", super_was_active);
super_replay = this->superkey_replay;
memcpy(&event_save_for_replay, &ev, sizeof(XEvent));
int revert_to_return;
XGetInputFocus(this->dpy, &event_saved_window, &revert_to_return);
XKeyboardState xkbs;
/* Save autorepeat previous state. Then turn off. */
XGetKeyboardControl(this->dpy, &xkbs);
saved_autorepeat_mode = xkbs.global_auto_repeat;
debug(1, "[ar] AutoRepeat state has been saved: %d.\n", saved_autorepeat_mode);
XKeyboardControl xkbc;
xkbc.auto_repeat_mode = AutoRepeatModeOff;
XChangeKeyboardControl(this->dpy, KBAutoRepeatMode, &xkbc);
debug(1, "[ar] AutoRepeat state has been turned off.\n");
/* Grab the keyboard. */
XGrabKeyboard(this->dpy, this->rootwin, False, GrabModeAsync,
GrabModeAsync, CurrentTime);
if (this->drawkb_delay > 0) {
to[TO_DRAWKB].tv_sec = (int) this->drawkb_delay;
to[TO_DRAWKB].tv_usec = (int) ((this->drawkb_delay - to[TO_DRAWKB].tv_sec) * 1000000);
} else {
/* Map Window. */
this->kbwin.map(this->dpy);
}
} else if (ev.type == KeyRelease) {
debug(1, "[sk] Super key has been released, code: %d, name: %s.\n", ev.xkey.keycode,
XKeysymToString(XkbKeycodeToKeysym(this->dpy, ev.xkey.keycode, 0, 0)));
if (--super_was_active) {
debug(2, "[sa] super_was_active decreased to %d, ignoring release.\n", super_was_active);
continue;
}
debug(2, "[sa] super_was_active decreased to %d, taking action.\n", super_was_active);
timerclear(&to[TO_DRAWKB]);
timerclear(&to[TO_CONFIG]);
if (super_replay && event_saved_window != 0xFFFFFFFFL) {
/* Since Xlib only supports Replaying a key before getting the next keyboard event,
* we can't really use XAllowEvents() to replay the Super key in case the user
* asked to. So we try XSendEvent() with the Press from the saved event on KeyPress,
* and the Release we are currently using.
*/
event_save_for_replay.xkey.window = event_saved_window;
ev.xkey.window = event_saved_window;
event_save_for_replay.xkey.subwindow = 0;
ev.xkey.subwindow = 0;
XSendEvent(this->dpy, event_saved_window, 1, KeyPressMask, &event_save_for_replay);
XSendEvent(this->dpy, event_saved_window, 1, KeyReleaseMask, &ev);
XSync(this->dpy, True);
debug(1, "[sr] Super key has been replayed\n");
}
/* Restore saved_autorepeat_mode. */
XKeyboardControl xkbc;
/*xkbc.auto_repeat_mode = saved_autorepeat_mode; */
xkbc.auto_repeat_mode = AutoRepeatModeOn;
XChangeKeyboardControl(this->dpy, KBAutoRepeatMode, &xkbc);
debug(1, "[ar] AutoRepeat has been restored to: %d\n", saved_autorepeat_mode);
XUngrabKeyboard(this->dpy, CurrentTime);
this->kbwin.unmap(this->dpy);
for (x = 0; x < pressed_keys_n; x++) {
__Action(pressed_keys[x].keycode, pressed_keys[x].state);
debug(1, "[ac] Due to Super key release, executed action for key code = %d, name: %s\n", pressed_keys[x].keycode,
XKeysymToString(XkbKeycodeToKeysym
(this->dpy, pressed_keys[x].keycode, 0, 0)));
}
clear_pressed_key_stack();
debug(1, "---------------------------------------------\n");
}
} else if (ev.type == KeyPress) {
debug(1, "[kp] A non-Super key was pressed.\n");
super_replay = 0;
to[TO_CONFIG].tv_sec = 3;
to[TO_CONFIG].tv_usec = 0;
debug(2, "[kp] TO_CONFIG timer set to 3 s.\n");
int squashed_state = ev.xkey.state & this->state_mask;
push_into_pressed_key_stack(ev.xkey.keycode, squashed_state);
assert(pressed_keys != NULL);
debug(2, "[kp] Pushed key and state to stack: %d, %d\n", ev.xkey.keycode, squashed_state);
} else if ((ev.type == KeyRelease && !ignore_release &&
super_was_active > 0)) {
/* User might have asked for binding configuration, so ignore key
* release. That's what ignore_release is for.
*/
timerclear(&to[TO_CONFIG]);
int squashed_state = ev.xkey.state & this->state_mask;
if ( key_is_pressed (this->dpy, ev.xkey.keycode) ) {
/* Verifies that the key is indeed pressed and not just a
* KeyRelease generated X's AutoRepeat.
*/
remove_from_pressed_key_stack(ev.xkey.keycode, squashed_state);
continue;
}
__Action(ev.xkey.keycode, squashed_state);
debug(1, "[ac] Due to bound key release, executed action for key code = %d, name: %s\n", ev.xkey.keycode,
XKeysymToString(XkbKeycodeToKeysym
(this->dpy, ev.xkey.keycode, 0, 0)));
debug(2, " ... and because super_was_active value was > 0: %d\n", super_was_active);
remove_from_pressed_key_stack(ev.xkey.keycode, squashed_state);
debug(2, "[kp] Removed key and state to stack: %d, %d\n", ev.xkey.keycode, squashed_state);
} else {
/* According to manual, this should not be necessary. */
/* XAllowEvents(this->dpy, ReplayKeyboard, CurrentTime); */
}
}
}
void superkb_kbwin_set(superkb_p this,
int (*superkb_kbwin_init) (Display *),
void (*superkb_kbwin_map) (Display *),
void (*superkb_kbwin_unmap) (Display *),
void (*superkb_kbwin_event) (Display *, XEvent ev))
{
if (superkb_kbwin_init != NULL) {
this->kbwin.init = superkb_kbwin_init;
}
if (superkb_kbwin_map != NULL) {
this->kbwin.map = superkb_kbwin_map;
}
if (superkb_kbwin_unmap != NULL) {
this->kbwin.unmap = superkb_kbwin_unmap;
}
if (superkb_kbwin_event != NULL) {
this->kbwin.event = superkb_kbwin_event;
}
}
int
superkb_init(superkb_p this,
Display *display,
const char *kblayout, KeyCode key1, KeyCode key2,
double drawkb_delay,
void (*f)(KeyCode keycode, unsigned int state),
int superkey_replay,
int superkey_release_cancels,
int states_mask, void (*welcome_message)())
{
__Action = f;
this->dpy = display;
int r;
this->drawkb_delay = drawkb_delay;
this->superkey_replay = superkey_replay;
this->superkey_release_cancels = superkey_release_cancels;
this->state_mask = states_mask;
/* FIXME: Validate parameters. */
/* Set configuration values. Parameters should be already validated. */
strcpy(this->kblayout, kblayout);
this->key1 = key1;
this->key2 = key2;
this->rootwin = DefaultRootWindow(this->dpy);
this->dpy = display;
this->welcome_message = welcome_message;
/* Create the keyboard window. */
r = this->kbwin.init(this->dpy);
if (r == EXIT_FAILURE) {
perror("superkb: superkb_init(): kbwin.init() failed");
return EXIT_FAILURE;
}
XFlush(this->dpy);
return 0;
}
superkb_p superkb_create(void) {
superkb_p this = malloc(sizeof(superkb_t));
if (this == NULL) {
perror("superkb: superkb_create(): malloc() failed");
return NULL;
}
memset (this, 0, sizeof(superkb_t));
return this;
}