forked from jordansissel/keynav
-
Notifications
You must be signed in to change notification settings - Fork 0
/
keynav.c
2130 lines (1799 loc) · 55.6 KB
/
keynav.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
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* keynav - Keyboard navigation tool.
*
* XXX: Merge 'wininfo' and 'wininfo_history'. The latest history entry is the
* same as wininfo, so use that instead.
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <X11/Xlib.h>
#include <X11/XKBlib.h>
#include <X11/Xresource.h>
#include <X11/Xutil.h>
#include <X11/keysym.h>
#include <X11/extensions/shape.h>
#include <X11/extensions/Xinerama.h>
#include <X11/extensions/Xrandr.h>
#include <glib.h>
#include <cairo-xlib.h>
#ifdef PROFILE_THINGS
#include <time.h>
#endif
#include <xdo.h>
#include "keynav_version.h"
#ifndef GLOBAL_CONFIG_FILE
#define GLOBAL_CONFIG_FILE "/etc/keynavrc"
#endif /* GLOBAL_CONFIG_FILE */
extern char **environ;
char **g_argv;
#define ISACTIVE (appstate.active)
#define ISDRAGGING (appstate.dragging)
struct appstate {
int active;
int dragging;
int need_draw;
int need_moveresize;
enum { record_getkey, record_ing, record_off } recording;
int playback;
int grid_nav; /* 1 if grid nav is active */
enum { GRID_NAV_COL, GRID_NAV_ROW } grid_nav_state;
enum { GRID_LABEL_NONE, GRID_LABEL_AA } grid_label;
int grid_nav_col;
int grid_nav_row;
};
typedef enum { HANDLE_CONTINUE, HANDLE_STOP } handler_info_t;
typedef struct recording {
int keycode;
GPtrArray *commands;
} recording_t;
GPtrArray *recordings;
recording_t *active_recording = NULL;
char *recordings_filename = NULL;
typedef struct wininfo {
int x;
int y;
int w;
int h;
int grid_rows;
int grid_cols;
int border_thickness;
int center_cut_size;
int curviewport;
} wininfo_t;
typedef struct mouseinfo {
int x;
int y;
} mouseinfo_t;
typedef struct viewport {
int x;
int y;
int w;
int h;
int screen_num;
Screen *screen;
Window root;
} viewport_t;
static wininfo_t wininfo;
static mouseinfo_t mouseinfo;
static viewport_t *viewports;
static int nviewports = 0;
static int xinerama = 0;
static int daemonize = 0;
static int is_daemon = False;
static Display *dpy;
static Window zone;
XRectangle *clip_rectangles = NULL;
int nclip_rectangles = 0;
static GC canvas_gc;
static Pixmap canvas;
static cairo_surface_t *canvas_surface;
static cairo_t *canvas_cairo;
static Pixmap shape;
static cairo_surface_t *shape_surface;
static cairo_t *shape_cairo;
static xdo_t *xdo;
static struct appstate appstate = {
.active = 0,
.dragging = 0,
.recording = record_off,
.grid_nav = 0,
};
static int drag_button = 0;
static char drag_modkeys[128];
/* history tracking */
#define WININFO_MAXHIST (100)
static wininfo_t wininfo_history[WININFO_MAXHIST]; /* XXX: is 100 enough? */
static int wininfo_history_cursor = 0;
void defaults();
void cmd_cell_select(char *args);
void cmd_click(char *args);
void cmd_cursorzoom(char *args);
void cmd_cut_down(char *args);
void cmd_cut_left(char *args);
void cmd_cut_right(char *args);
void cmd_cut_up(char *args);
void cmd_daemonize(char *args);
void cmd_doubleclick(char *args);
void cmd_drag(char *args);
void cmd_end(char *args);
void cmd_toggle_start(char *args);
void cmd_grid(char *args);
void cmd_grid_nav(char *args);
void cmd_history_back(char *args);
void cmd_loadconfig(char *args);
void cmd_move_down(char *args);
void cmd_move_left(char *args);
void cmd_move_right(char *args);
void cmd_move_up(char *args);
void cmd_quit(char *args);
void cmd_record(char *args);
void cmd_playback(char *args);
void cmd_restart(char *args);
void cmd_shell(char *args);
void cmd_start(char *args);
void cmd_warp(char *args);
void cmd_windowzoom(char *args);
void update();
void correct_overflow();
void handle_keypress(XKeyEvent *e);
void handle_commands(char *commands);
void parse_config();
int parse_config_line(char *line);
void save_history_point();
void restore_history_point(int moves_ago);
void cell_select(int x, int y);
handler_info_t handle_recording(XKeyEvent *e);
handler_info_t handle_gridnav(XKeyEvent *e);
void query_screens();
void query_screen_xinerama();
void query_screen_normal();
int viewport_sort(const void *a, const void *b);
int query_current_screen();
int query_current_screen_xinerama();
int query_current_screen_normal();
void viewport_left();
void viewport_right();
int pointinrect(int px, int py, int rx, int ry, int rw, int rh);
int percent_of(int num, char *args, float default_val);
void sigchld(int sig);
void sighup(int sig);
void restart();
void recordings_save(const char *filename);
void parse_recordings(const char *filename);
void openpixel(Display *dpy, Window zone, mouseinfo_t *mouseinfo);
void closepixel(Display *dpy, Window zone, mouseinfo_t *mouseinfo);
typedef struct dispatch {
char *command;
void (*func)(char *args);
} dispatch_t;
dispatch_t dispatch[] = {
"cut-up", cmd_cut_up,
"cut-down", cmd_cut_down,
"cut-left", cmd_cut_left,
"cut-right", cmd_cut_right,
"move-up", cmd_move_up,
"move-down", cmd_move_down,
"move-left", cmd_move_left,
"move-right", cmd_move_right,
"cursorzoom", cmd_cursorzoom,
"windowzoom", cmd_windowzoom,
// Grid commands
"grid", cmd_grid,
"grid-nav", cmd_grid_nav,
"cell-select", cmd_cell_select,
// Mouse activity
"warp", cmd_warp,
"click", cmd_click,
"doubleclick", cmd_doubleclick,
"drag", cmd_drag,
// Other commands.
"loadconfig", cmd_loadconfig,
"daemonize", cmd_daemonize,
"sh", cmd_shell,
"start", cmd_start,
"end", cmd_end,
"toggle-start", cmd_toggle_start,
"history-back", cmd_history_back,
"quit", cmd_quit,
"restart", cmd_restart,
"record", cmd_record,
"playback", cmd_playback,
NULL, NULL,
};
typedef struct keybinding {
char *commands;
int keycode;
int mods;
} keybinding_t;
GPtrArray *keybindings = NULL;
typedef struct startkey {
int keycode;
int mods;
} startkey_t;
GPtrArray *startkeys = NULL;
int parse_keycode(char *keyseq) {
char *tokctx;
char *strptr;
char *tok;
char *last_tok;
char *dup;
int keycode = 0;
int keysym = 0;
strptr = dup = strdup(keyseq);
//printf("finding keycode for %s\n", keyseq);
while ((tok = strtok_r(strptr, "+", &tokctx)) != NULL) {
last_tok = tok;
strptr = NULL;
}
keysym = XStringToKeysym(last_tok);
if (keysym == NoSymbol) {
fprintf(stderr, "No keysym found for '%s' in sequence '%s'\n",
last_tok, keyseq);
/* At this point, we'll be returning 0 for keycode */
} else {
/* Valid keysym */
keycode = XKeysymToKeycode(dpy, keysym);
if (keycode == 0) {
fprintf(stderr, "Unable to lookup keycode for %s\n", last_tok);
}
}
free(dup);
return keycode;
}
int parse_mods(char *keyseq) {
char *tokctx;
char *strptr;
char *tok;
char *last_tok;
char *dup;
GPtrArray *mods;
int modmask = 0;
mods = g_ptr_array_new();
strptr = dup = strdup(keyseq);
while ((tok = strtok_r(strptr, "+", &tokctx)) != NULL) {
strptr = NULL;
g_ptr_array_add(mods, tok);
}
int i = 0;
/* Use all but the last token as modifiers */
const char **symbol_map = xdo_get_symbol_map();
for (i = 0; i < mods->len; i++) {
KeySym keysym = 0;
int j = 0;
const char *mod = g_ptr_array_index(mods, i);
for (j = 0; symbol_map[j] != NULL; j+=2) {
if (!strcasecmp(mod, symbol_map[j])) {
mod = symbol_map[j + 1];
}
}
keysym = XStringToKeysym(mod);
//printf("%s => %d\n", mod, keysym);
if ((keysym == XK_Shift_L) || (keysym == XK_Shift_R))
modmask |= ShiftMask;
if ((keysym == XK_Control_L) || (keysym == XK_Control_R))
modmask |= ControlMask;
if ((keysym == XK_Alt_L) || (keysym == XK_Alt_R))
modmask |= Mod1Mask;
if ((keysym == XK_Super_L) || (keysym == XK_Super_R)
|| (keysym == XK_Hyper_L) || (keysym == XK_Hyper_R))
modmask |= Mod4Mask;
if (!strcasecmp(mod, "mod1"))
modmask |= Mod1Mask;
// See masking of state in handle_keypress
if (!strcasecmp(mod, "mod2"))
printf("Error in configuration: keynav does not support mod2 modifier, but other modifiers are supported.");
if (!strcasecmp(mod, "mod3"))
modmask |= Mod3Mask;
if (!strcasecmp(mod, "mod4"))
modmask |= Mod4Mask;
if (!strcasecmp(mod, "mod5"))
modmask |= Mod5Mask;
/* 'xmodmap' will output the current modN:KeySym mappings */
}
free(dup);
g_ptr_array_free(mods, FALSE);
return modmask;
}
void addbinding(int keycode, int mods, char *commands) {
int i;
// Check if we already have a binding for this, if so, override it.
for (i = 0; i < keybindings->len; i++) {
keybinding_t *kbt = g_ptr_array_index(keybindings, i);
if (kbt->keycode == keycode && kbt->mods == mods) {
free(kbt->commands);
kbt->commands = strdup(commands);
return;
}
}
keybinding_t *keybinding = NULL;
keybinding = calloc(sizeof(keybinding_t), 1);
keybinding->commands = strdup(commands);
keybinding->keycode = keycode;
keybinding->mods = mods;
g_ptr_array_add(keybindings, keybinding);
if (!strncmp(commands, "start", 5) || !strncmp(commands, "toggle-start", 12)) {
int i = 0;
startkey_t *startkey = calloc(sizeof(startkey_t), 1);
startkey->keycode = keycode;
startkey->mods = mods;
g_ptr_array_add(startkeys, startkey);
/* Grab on all screen root windows */
for (i = 0; i < ScreenCount(dpy); i++) {
Window root = RootWindow(dpy, i);
XGrabKey(dpy, keycode, mods, root, False, GrabModeAsync, GrabModeAsync);
XGrabKey(dpy, keycode, mods | LockMask, root, False, GrabModeAsync, GrabModeAsync);
XGrabKey(dpy, keycode, mods | Mod2Mask, root, False, GrabModeAsync, GrabModeAsync);
XGrabKey(dpy, keycode, mods | LockMask | Mod2Mask, root, False, GrabModeAsync, GrabModeAsync);
}
}
if (!strncmp(commands, "record", 6)) {
char *path = commands + 6;
char *newrecordingpath;
while (isspace(*path))
path++;
/* If args is nonempty, try to use it as the file to store recordings in */
if (path != NULL && path[0] != '\0') {
/* Handle ~/ swapping in for actual homedir */
if (!strncmp(path, "~/", 2)) {
asprintf(&newrecordingpath, "%s/%s", getenv("HOME"), path + 2);
} else {
newrecordingpath = strdup(path);
}
/* Fail if we try to set the record file to another name than we set
* previously */
if (recordings_filename != NULL
&& strcmp(recordings_filename, newrecordingpath)) {
free(newrecordingpath);
fprintf(stderr,
"Recordings file already set to '%s', you tried to\n"
"set it to '%s'. Keeping original value.\n",
recordings_filename, path);
} else {
recordings_filename = newrecordingpath;
parse_recordings(recordings_filename);
}
}
} /* special config handling for 'record' */
}
void parse_config_file(const char* file) {
FILE *fp = NULL;
#define LINEBUF_SIZE 512
char line[LINEBUF_SIZE];
int lineno = 0;
if (file[0] == '~') {
const char *homedir = getenv("HOME");
if (homedir != NULL) {
char *rcfile = NULL;
asprintf(&rcfile, "%s/%s", homedir, file + 1 /* skip first char '~' */);
parse_config_file(rcfile);
free(rcfile);
return;
} else {
fprintf(stderr,
"No HOME set in environment. Can't expand '%s' (fatal error)\n",
file);
/* This is fatal. */
exit(EXIT_FAILURE);
}
} /* if file[0] == '~' */
fp = fopen(file, "r");
/* Silently ignore file read errors */
if (fp == NULL) {
//fprintf(stderr, "Error trying to open file for read '%s'\n", file);
//perror("Error");
return;
}
/* fopen succeeded */
while (fgets(line, LINEBUF_SIZE, fp) != NULL) {
lineno++;
/* Kill the newline */
while (line[strlen(line) - 1] == '\n' ||
line[strlen(line) - 1] == '\r')
*(line + strlen(line) - 1) = '\0';
if (parse_config_line(line) != 0) {
fprintf(stderr, "Error with config %s:%d: %s\n", file, lineno, line);
}
}
fclose(fp);
}
void parse_config() {
char *homedir;
keybindings = g_ptr_array_new();
startkeys = g_ptr_array_new();
recordings = g_ptr_array_new();
defaults();
parse_config_file(GLOBAL_CONFIG_FILE);
parse_config_file("~/.keynavrc");
// support XDG Base Directory
char *config_home = getenv("XDG_CONFIG_HOME");
char *user_config_file;
if (config_home &&
asprintf(&user_config_file, "%s/keynav/keynavrc", config_home) != -1) {
parse_config_file(user_config_file);
free(user_config_file);
} else {
// standard default if XDG_CONFIG_HOME is not set
parse_config_file("~/.config/keynav/keynavrc");
}
}
void defaults() {
char *tmp;
int i;
char *default_config[] = {
"clear",
"ctrl+semicolon start",
"Escape end",
"ctrl+bracketleft end", /* for vi people who use ^[ */
"q record ~/.keynav_macros",
"shift+at playback",
"a history-back",
"h cut-left",
"j cut-down",
"k cut-up",
"l cut-right",
"shift+h move-left",
"shift+j move-down",
"shift+k move-up",
"shift+l move-right",
"space warp,click 1,end",
"Return warp,click 1,end",
"semicolon warp,end",
"w warp",
"t windowzoom",
"c cursorzoom 300 300",
"e end",
"1 click 1",
"2 click 2",
"3 click 3",
"ctrl+h cut-left",
"ctrl+j cut-down",
"ctrl+k cut-up",
"ctrl+l cut-right",
"y cut-left,cut-up",
"u cut-right,cut-up",
"b cut-left,cut-down",
"n cut-right,cut-down",
"shift+y move-left,move-up",
"shift+u move-right,move-up",
"shift+b move-left,move-down",
"shift+n move-right,move-down",
"ctrl+y cut-left,cut-up",
"ctrl+u cut-right,cut-up",
"ctrl+b cut-left,cut-down",
"ctrl+n cut-right,cut-down",
NULL,
};
for (i = 0; default_config[i]; i++) {
tmp = strdup(default_config[i]);
if (parse_config_line(tmp) != 0) {
fprintf(stderr, "Error with default config line %d: %s\n", i + 1, tmp);
}
free(tmp);
}
}
int parse_config_line(char *orig_line) {
/* syntax:
* keysequence cmd1,cmd2,cmd3
*
* ex:
* ctrl+semicolon start
* space warp
* semicolon warp,click
*/
char *line = strdup(orig_line);
char *tokctx;
char *keyseq;
int keycode, mods;
int i, j;
char *comment;
/* Ignore everything after a '#' */
comment = strchr(line, '#');
if (comment != NULL)
*comment = '\0';
/* Ignore leading whitespace */
while (isspace(*line))
line++;
/* Ignore empty lines */
if (*line == '\n' || *line == '\0')
return 0;
tokctx = line;
keyseq = strdup(strtok_r(line, " ", &tokctx));
/* A special config option that will clear all keybindings */
if (strcmp(keyseq, "clear") == 0) {
/* TODO(sissel): Make this a cmd_clear function */
/* Reset keybindings */
g_ptr_array_free(keybindings, TRUE);
keybindings = g_ptr_array_new();
/* ungrab keybindings associated with start */
if (startkeys->len > 0) {
for (i = 0; i < ScreenCount(dpy); i++) {
Window root = RootWindow(dpy, i);
for (j = 0; j < startkeys->len; j++) {
startkey_t *sk = g_ptr_array_index(startkeys, j);
XUngrabKey(dpy, sk->keycode, sk->mods, root);
XUngrabKey(dpy, sk->keycode, sk->mods | LockMask, root);
XUngrabKey(dpy, sk->keycode, sk->mods | Mod2Mask, root);
XUngrabKey(dpy, sk->keycode, sk->mods | LockMask | Mod2Mask, root);
}
}
g_ptr_array_free(startkeys, TRUE);
startkeys = g_ptr_array_new();
}
} else if (strcmp(keyseq, "daemonize") == 0) {
handle_commands(keyseq);
} else if (strcmp(keyseq, "loadconfig") == 0) {
handle_commands(keyseq);
} else {
keycode = parse_keycode(keyseq);
if (keycode == 0) {
fprintf(stderr, "Problem parsing keysequence '%s'\n", keyseq);
return 1;
}
mods = parse_mods(keyseq);
/* FreeBSD sets 'tokctx' to NULL at end of string.
* glibc sets 'tokctx' to the next character (the '\0')
* Reported by Richard Kolkovich */
if (tokctx == NULL || *tokctx == '\0') {
fprintf(stderr, "Incomplete configuration line. Missing commands: '%s'\n", line);
return 1;
}
addbinding(keycode, mods, tokctx /* the remainder of the line */);
}
free(keyseq);
free(line);
return 0;
}
int percent_of(int num, char *args, float default_val) {
static float precision = 100000.0;
float pct = 0.0;
int value = 0;
/* Parse a float. If this fails, assume the default value */
if (sscanf(args, "%f", &pct) <= 0)
pct = default_val;
/* > 1, then it's not a percent, it's an absolute value. */
if (pct > 1.0)
return (int)pct;
value = (int)((num * (pct * precision)) / precision);
return value;
}
void updatecliprects(wininfo_t *info, XRectangle **rectangles, int *nrects) {
int rects = (info->grid_cols + 1) + (info->grid_rows + 1) /* grid lines */
+ (info->grid_cols * info->grid_rows); /* grid text boxes */
if (rects != nclip_rectangles) {
nclip_rectangles = rects;
clip_rectangles = realloc(clip_rectangles, nclip_rectangles * sizeof(XRectangle));
}
}
void updategrid(Window win, struct wininfo *info, int apply_clip, int draw) {
double w = info->w;
double h = info->h;
double cell_width;
double cell_height;
int i;
int rect = 0;
if (apply_clip) {
updatecliprects(info, &clip_rectangles, &nclip_rectangles);
memset(clip_rectangles, 0, nclip_rectangles * sizeof(XRectangle));
}
#ifdef PROFILE_THINGS
struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start);
#endif
if (w <= 4 || h <= 4) {
cairo_new_path(canvas_cairo);
cairo_fill(canvas_cairo);
return;
}
//printf("updategrid: clip:%d, draw:%d\n", apply_clip, draw);
if (draw) {
cairo_new_path(canvas_cairo);
cairo_set_source_rgb(canvas_cairo, 1, 1, 1);
cairo_rectangle(canvas_cairo, 0, 0, w, h);
cairo_set_line_width(canvas_cairo, wininfo.border_thickness);
cairo_fill(canvas_cairo);
}
cell_width = (w / info->grid_cols);
cell_height = (h / info->grid_rows);
int x_total_offset = 0;
/* clip vertically */
for (i = 0; i <= info->grid_cols; i++) {
int x_off = 0;
if (i > 0) {
x_off = -info->border_thickness / 2;
}
if (i == info->grid_cols) {
x_total_offset = info->w - 1;
}
int x_w_off = 0;
if (i == 0 || i == info->grid_cols) {
x_w_off = info->border_thickness / 2;
}
cairo_move_to(canvas_cairo, x_total_offset + 1, 0);
cairo_line_to(canvas_cairo, x_total_offset + 1, info->h);
clip_rectangles[rect].x = x_total_offset + x_off;
clip_rectangles[rect].y = 0;
clip_rectangles[rect].width = info->border_thickness - x_w_off;
clip_rectangles[rect].height = info->h;
rect++;
x_total_offset += cell_width;
}
int y_total_offset = 0;
/* clip horizontally */
for (i = 0; i <= info->grid_rows; i++) {
int y_off = 0;
if (i > 0) {
y_off = -info->border_thickness / 2;
}
if (i == info->grid_rows) {
y_total_offset = info->h - 1;
}
int y_w_off = 0;
if (i == 0 || i == info->grid_rows) {
y_w_off = info->border_thickness / 2;
}
cairo_move_to(canvas_cairo, 0, y_total_offset + 1);
cairo_line_to(canvas_cairo, info->w, y_total_offset + 1);
clip_rectangles[rect].x = 0;
clip_rectangles[rect].y = y_total_offset + y_off;
clip_rectangles[rect].width = info->w;
clip_rectangles[rect].height = info->border_thickness - y_w_off;
rect++;
y_total_offset += cell_height;
}
cairo_path_t *path = cairo_copy_path(canvas_cairo);
#ifdef PROFILE_THINGS
clock_gettime(CLOCK_MONOTONIC, &end);
printf("updategrid pathbuild time: %ld.%09ld\n",
end.tv_sec - start.tv_sec,
end.tv_nsec - start.tv_nsec);
clock_gettime(CLOCK_MONOTONIC, &start);
#endif
if (draw) {
cairo_set_source_rgba(canvas_cairo, 0, 0, 0, 1.0);
cairo_set_line_width(canvas_cairo, 1);
cairo_stroke(canvas_cairo);
#ifdef PROFILE_THINGS
XSync(dpy, False);
clock_gettime(CLOCK_MONOTONIC, &end);
printf("updategrid draw time: %ld.%09ld\n",
end.tv_sec - start.tv_sec,
end.tv_nsec - start.tv_nsec);
clock_gettime(CLOCK_MONOTONIC, &start);
#endif
} /* if draw */
cairo_path_destroy(path);
}
void updategridtext(Window win, struct wininfo *info, int apply_clip, int draw) {
double w = info->w;
double h = info->h;
double cell_width;
double cell_height;
double x_off, y_off;
int row, col;
int rect = (info->grid_cols + 1 + info->grid_rows + 1); /* start at end of grid lines */
x_off = info->border_thickness / 2;
y_off = info->border_thickness / 2;
cairo_text_extents_t te;
#define FONTSIZE 18
if (draw) {
cairo_new_path(canvas_cairo);
cairo_select_font_face(canvas_cairo, "Courier", CAIRO_FONT_SLANT_NORMAL,
CAIRO_FONT_WEIGHT_BOLD);
cairo_set_font_size(canvas_cairo, FONTSIZE);
cairo_text_extents(canvas_cairo, "AA", &te);
}
w -= info->border_thickness;
h -= info->border_thickness;
cell_width = (w / info->grid_cols);
cell_height = (h / info->grid_rows);
h++;
w++;
//printf("bearing: %f,%f\n", te.x_bearing, te.y_bearing);
//printf("size: %f,%f\n", te.width, te.height);
char label[3] = "AA";
int row_selected = 0;
for (col = 0; col < info->grid_cols; col++) {
label[0] = 'A';
for (row = 0; row < info->grid_rows; row++) {
int rectwidth = te.width + 25;
int rectheight = te.height + 8;
int xpos = cell_width * col + x_off + (cell_width / 2);
int ypos = cell_height * row + y_off + (cell_height / 2);
row_selected = (appstate.grid_nav && appstate.grid_nav_row == row
&& appstate.grid_nav_state == GRID_NAV_COL);
//printf("Grid: %c%c\n", label[0], label[1]);
/* If the current column is the one selected by grid nav, use
* a different color */
//printf("Grid geom: %fx%f @ %d,%d\n",
//xpos - rectwidth / 2 + te.x_bearing / 2,
//ypos - rectheight / 2 + te.y_bearing / 2,
//rectwidth, rectheight);
cairo_rectangle(canvas_cairo,
xpos - rectwidth / 2 + te.x_bearing / 2,
ypos - rectheight / 2 + te.y_bearing / 2,
rectwidth, rectheight);
if (draw) {
cairo_path_t *pathcopy;
pathcopy = cairo_copy_path(canvas_cairo);
cairo_set_line_width(shape_cairo, 2);
if (row_selected) {
cairo_set_source_rgb(canvas_cairo, 0, .3, .3);
} else {
cairo_set_source_rgb(canvas_cairo, 0, .2, 0);
}
cairo_fill(canvas_cairo);
cairo_append_path(canvas_cairo, pathcopy);
cairo_set_source_rgb(canvas_cairo, .8, .8, 0);
cairo_stroke(canvas_cairo);
cairo_path_destroy(pathcopy);
if (row_selected) {
cairo_set_source_rgb(canvas_cairo, 1, 1, 1);
} else {
cairo_set_source_rgb(canvas_cairo, .8, .8, .8);
}
cairo_fill(canvas_cairo);
cairo_move_to(canvas_cairo, xpos - te.width / 2, ypos);
cairo_show_text(canvas_cairo, label);
}
if (apply_clip) {
clip_rectangles[rect].x = xpos - rectwidth / 2 + te.x_bearing / 2;
clip_rectangles[rect].y = ypos - rectheight / 2 + te.y_bearing / 2;
clip_rectangles[rect].width = rectwidth + 1;
clip_rectangles[rect].height = rectheight + 1;
rect++;
}
label[0]++;
}
label[1]++;
} /* Draw rectangles and text */
} /* void updategridtext */
void grab_keyboard() {
int grabstate;
int grabtries = 0;
/* This loop is to work around the following scenario:
* xbindkeys invokes XGrabKeyboard when you press a bound keystroke and
* doesn't Ungrab until you release a key.
* Example: (xbindkey '(Control semicolon) "keynav 'start, grid 2x2'")
* This will only invoke XUngrabKeyboard when you release 'semicolon'
*
* The problem is that keynav would be launched as soon as the keydown
* event 'control + semicolon' occurs, but we could only get the grab on
* the release.
*
* This sleepyloop will keep trying to grab the keyboard until it succeeds.
*
* Reported by Colin Shea
*/
grabstate = XGrabKeyboard(dpy, viewports[wininfo.curviewport].root, False,
GrabModeAsync, GrabModeAsync, CurrentTime);
while (grabstate != GrabSuccess) {
usleep(10000); /* sleep for 10ms */
grabstate = XGrabKeyboard(dpy, viewports[wininfo.curviewport].root, False,
GrabModeAsync, GrabModeAsync, CurrentTime);
grabtries += 1;
if (grabtries >= 20) {
fprintf(stderr, "XGrabKeyboard failed %d times, giving up...\n",
grabtries);
/* Returning from here will result in the appstate.active still
* being false. */
return;
}
}
//printf("Got grab!\n");
}
void cmd_start(char *args) {
XSetWindowAttributes winattr;
int i;
int screen;
screen = query_current_screen();
wininfo.curviewport = screen;
appstate.grid_nav_row = -1;
appstate.grid_nav_col = -1;
wininfo.x = viewports[wininfo.curviewport].x;
wininfo.y = viewports[wininfo.curviewport].y;
wininfo.w = viewports[wininfo.curviewport].w;
wininfo.h = viewports[wininfo.curviewport].h;
grab_keyboard();
/* Default start with 4 cells, 2x2 */
wininfo.grid_rows = 2;
wininfo.grid_cols = 2;
wininfo.border_thickness = 3;
wininfo.center_cut_size = 3;
if (ISACTIVE)
return;
int depth;
appstate.active = True;
appstate.need_draw = 1;
appstate.need_moveresize = 1;
if (zone == 0) { /* Create our window for the first time */
viewport_t *viewport = &(viewports[wininfo.curviewport]);
depth = viewports[wininfo.curviewport].screen->root_depth;
wininfo_history_cursor = 0;
zone = XCreateSimpleWindow(dpy, viewport->root,
wininfo.x, wininfo.y, wininfo.w, wininfo.h, 0, 0, 0);
xdo_set_window_class(xdo, zone, "keynav", "keynav");
canvas_gc = XCreateGC(dpy, zone, 0, NULL);
canvas = XCreatePixmap(dpy, zone, viewport->w, viewport->h,
viewport->screen->root_depth);
canvas_surface = cairo_xlib_surface_create(dpy, canvas,
viewport->screen->root_visual,
viewport->w, viewport->h);
canvas_cairo = cairo_create(canvas_surface);
cairo_set_antialias(canvas_cairo, CAIRO_ANTIALIAS_NONE);
cairo_set_line_cap(canvas_cairo, CAIRO_LINE_CAP_SQUARE);
shape = XCreatePixmap(dpy, zone, viewport->w, viewport->h, 1);
shape_surface = cairo_xlib_surface_create_for_bitmap(dpy, shape,
viewport->screen,
viewport->w,
viewport->h);
shape_cairo = cairo_create(shape_surface);
cairo_set_line_width(shape_cairo, wininfo.border_thickness);
cairo_set_antialias(canvas_cairo, CAIRO_ANTIALIAS_NONE);
cairo_set_line_cap(shape_cairo, CAIRO_LINE_CAP_SQUARE);
/* Tell the window manager not to manage us */
winattr.override_redirect = 1;
XChangeWindowAttributes(dpy, zone, CWOverrideRedirect, &winattr);
XSelectInput(dpy, zone, StructureNotifyMask | ExposureMask
| PointerMotionMask | LeaveWindowMask );
} /* if zone == 0 */
}
void cmd_end(char *args) {
if (!ISACTIVE)
return;
/* kill drag state too */
if (ISDRAGGING)
cmd_drag(NULL);
/* Stop recording if we're in that mode */