Blob


1 /*
2 * Copyright (c) 2020 Omar Polo <op@omarpolo.com>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include "star-platinum.h"
19 #include <err.h>
20 #include <signal.h>
21 #include <stdarg.h>
22 #include <stdio.h>
23 #include <string.h>
24 #include <unistd.h>
26 #include <X11/XKBlib.h>
27 #include <X11/Xutil.h>
29 #ifndef __OpenBSD__
30 # define pledge(a, b) 0
31 #endif
33 extern FILE *yyin;
34 char *fname;
36 extern int yylineno;
37 int yyparse(void);
39 struct group *config;
40 int goterror = 0;
42 Display *d;
44 int ignored_modifiers[] = {
45 0, /* no modifiers */
46 LockMask, /* caps lock */
47 Mod2Mask, /* num lock */
48 Mod3Mask, /* scroll lock */
49 Mod5Mask, /* ? */
50 };
52 #define IGNORE_MODIFIERS (LockMask | Mod2Mask | Mod3Mask | Mod5Mask)
54 __attribute__((__format__ (__printf__, 1, 2)))
55 void
56 yyerror(const char *fmt, ...)
57 {
58 va_list ap;
59 size_t l;
61 va_start(ap, fmt);
63 goterror = 1;
64 fprintf(stderr, "%s:%d ", fname, yylineno);
65 vfprintf(stderr, fmt, ap);
67 l = strlen(fmt);
68 if (l > 0 && fmt[l-1] != '\n')
69 fprintf(stderr, "\n");
71 va_end(ap);
72 }
74 char *
75 find_config()
76 {
77 char *home, *xdg, *t;
78 int free_xdg = 0;
80 home = getenv("HOME");
81 xdg = getenv("XDG_CONFIG_HOME");
83 if (home == NULL && xdg == NULL)
84 return NULL;
86 /* file in home directory >>>>>> XDG shit */
87 if (home != NULL) {
88 if (asprintf(&t, "%s/.star-platinum.conf", home) == -1)
89 return NULL;
90 if (access(t, R_OK) == 0)
91 return t;
93 free(t);
94 /* continue to search */
95 }
97 /* sanitize XDG_CONFIG_HOME */
98 if (xdg == NULL) {
99 free_xdg = 1;
100 if (asprintf(&xdg, "%s/.config", home) == -1)
101 return NULL;
104 if (asprintf(&t, "%s/star-platinum.conf", xdg) == -1)
105 goto err;
107 if (access(t, R_OK) == 0)
108 return t;
109 free(t);
111 err:
112 if (free_xdg)
113 free(xdg);
115 return NULL;
118 int
119 main(int argc, char **argv)
121 int status = 0, dump_config = 0, conftest = 0, ch;
122 struct group *g;
123 struct rule *r;
124 XEvent e;
125 Window root;
127 signal(SIGCHLD, SIG_IGN); /* don't allow zombies */
129 fname = NULL;
130 while ((ch = getopt(argc, argv, "c:dn")) != -1) {
131 switch (ch) {
132 case 'c':
133 free(fname);
134 if ((fname = strdup(optarg)) == NULL)
135 err(1, "strdup");
136 break;
138 case 'd':
139 dump_config = 1;
140 break;
142 case 'n':
143 conftest = 1;
144 break;
146 default:
147 fprintf(stderr, "USAGE: %s [-dn] [-c conf]\n", *argv);
148 return 1;
152 if (fname == NULL) {
153 if ((fname = find_config()) == NULL)
154 errx(1, "can't find a configuration file");
157 if ((yyin = fopen(fname, "r")) == NULL)
158 err(1, "cannot open %s", fname);
159 yyparse();
160 fclose(yyin);
162 free(fname);
163 fname = NULL;
165 if (goterror)
166 return 1;
168 if (dump_config)
169 printgroup(config);
171 if (conftest) {
172 recfree_group(config);
173 return 0;
176 if ((d = XOpenDisplay(NULL)) == NULL) {
177 recfree_group(config);
178 return 1;
181 XSetErrorHandler(&error_handler);
183 root = DefaultRootWindow(d);
185 /* grab all the keys */
186 for (g = config; g != NULL; g = g->next)
187 for (r = g->rules; r != NULL; r = r->next)
188 grabkey(r->key);
190 XSelectInput(d, root, KeyPressMask);
191 XFlush(d);
193 pledge("stdio proc exec", NULL);
195 while (1) {
196 XNextEvent(d, &e);
197 switch (e.type) {
198 case KeyRelease:
199 case KeyPress:
200 process_event(config, (XKeyEvent*)&e);
201 break;
203 default:
204 printf("Unknown event %d\n", e.type);
205 break;
209 XCloseDisplay(d);
210 recfree_group(config);
211 return status;
215 /* xlib */
217 int
218 error_handler(Display *d, XErrorEvent *e)
220 fprintf(stderr, "Xlib error %d\n", e->type);
221 return 1;
224 /* TODO: it should grab ALL POSSIBLE COMBINATIONS of `ignored_modifiers`! */
225 void
226 grabkey(struct key k)
228 static size_t len = sizeof(ignored_modifiers)/sizeof(int);
229 size_t i;
230 Window root;
232 root = DefaultRootWindow(d);
234 /* printf("Grabbing "); printkey(k); printf("\n"); */
235 for (i = 0; i < len; ++i) {
236 XGrabKey(d, XKeysymToKeycode(d, k.key),
237 k.modifier | ignored_modifiers[i],
238 root, False, GrabModeAsync, GrabModeAsync);
242 KeySym
243 keycode_to_keysym(unsigned int kc)
245 /* group 0 (?). shift level is 0 because we don't want it*/
246 return XkbKeycodeToKeysym(d, kc, 0, 0);
249 Window
250 focused_window()
252 Window w;
253 int revert_to;
255 /* one can use (at least) three way to obtain the current
256 * focused window using xlib:
258 * - XQueryTree : you traverse tre tree until you find the
259 * window
261 * - looking at _NET_ACTIVE_WINDOW in the root window, but
262 * depedns on the window manager to set it
264 * - using XGetInputFocus
266 * I don't know the pro/cons of these, but XGetInputFocus
267 * seems the easiest.
268 */
269 XGetInputFocus(d, &w, &revert_to);
270 return w;
273 void
274 send_fake(Window w, struct key k, XKeyEvent *original)
276 XKeyEvent e;
278 /*
279 * this needs to be hijacked. original->window is the root
280 * window (since we grabbed the key there) and we want to
281 * deliver the key to another window.
282 */
283 e.window = w;
285 /* this is the fake key */
286 e.keycode = XKeysymToKeycode(d, k.key);
287 e.state = k.modifier;
289 /* the rest is just copying fields from the original event */
290 e.type = original->type;
291 e.display = original->display;
292 e.root = original->root;
293 e.subwindow = original->subwindow;
294 e.time = original->time;
295 e.same_screen = original->same_screen;
296 e.x = original->x;
297 e.y = original->y;
298 e.x_root = original->x_root;
299 e.y_root = original->y_root;
301 XSendEvent(d, w, True, KeyPressMask, (XEvent*)&e);
302 XFlush(d);
305 int
306 window_match_class(Window w, const char *class)
308 XClassHint ch;
309 int matched;
311 if (!XGetClassHint(d, w, &ch)) {
312 fprintf(stderr, "XGetClassHint failed\n");
313 return 0;
316 matched = !strcmp(ch.res_class, class);
318 XFree(ch.res_name);
319 XFree(ch.res_class);
321 return matched;
325 /* action */
327 void
328 do_action(struct action a, Window focused, XKeyEvent *original)
330 switch (a.type) {
331 case AFAKE:
332 send_fake(focused, a.send_key, original);
333 break;
335 case ASPECIAL:
336 switch (a.special) {
337 case ATOGGLE:
338 case AACTIVATE:
339 case ADEACTIVATE:
340 printf("TODO\n");
341 break;
343 case AIGNORE:
344 break;
346 default:
347 /* unreachable */
348 abort();
350 break;
352 case AEXEC: {
353 pid_t p;
354 const char *sh;
356 switch (p = fork()) {
357 case -1:
358 err(1, "fork");
360 case 0:
361 if ((sh = getenv("SHELL")) == NULL)
362 sh = "/bin/sh";
363 printf("before exec'ing %s -c '%s'\n", sh, a.str);
364 execlp(sh, sh, "-c", a.str, NULL);
365 err(1, "execlp");
368 break;
371 default:
372 /* unreachable */
373 abort();
377 void
378 free_action(struct action a)
380 if (a.type == AEXEC)
381 free(a.str);
385 /* match */
387 struct match *
388 new_match(int prop, char *s)
390 struct match *m;
392 if ((m = calloc(1, sizeof(*m))) == NULL)
393 err(1, "calloc");
394 m->prop = prop;
395 m->str = s;
396 return m;
399 void
400 recfree_match(struct match *m)
402 struct match *mt;
404 if (m == NULL)
405 return;
407 mt = m->next;
408 free(m->str);
409 free(m);
410 recfree_match(mt);
413 int
414 match_window(struct match *m, Window w)
416 switch (m->prop) {
417 case MANY:
418 return 1;
420 case MCLASS:
421 return window_match_class(w, m->str);
422 break;
424 default:
425 /* unreachable */
426 abort();
431 /* rule */
433 struct rule *
434 new_rule(struct key k, struct action a)
436 struct rule *r;
438 if ((r = calloc(1, sizeof(*r))) == NULL)
439 err(1, "calloc");
440 memcpy(&r->key, &k, sizeof(k));
441 memcpy(&r->action, &a, sizeof(a));
442 return r;
445 void
446 recfree_rule(struct rule *r)
448 struct rule *rt;
450 if (r == NULL)
451 return;
453 rt = r->next;
454 free(r);
455 recfree_rule(rt);
458 int
459 rule_matched(struct rule *r, struct key k)
461 unsigned int m;
463 m = k.modifier;
464 m &= ~IGNORE_MODIFIERS; /* clear ignored modifiers */
466 return r->key.modifier == m
467 && r->key.key == k.key;
471 /* group */
473 struct group *
474 new_group(struct match *matches, struct rule *rules)
476 struct group *g;
478 if ((g = calloc(1, sizeof(*g))) == NULL)
479 err(1, "calloc");
480 g->matches = matches;
481 g->rules = rules;
482 return g;
485 void
486 recfree_group(struct group *g)
488 struct group *gt;
490 if (g == NULL)
491 return;
493 gt = g->next;
494 recfree_match(g->matches);
495 recfree_rule(g->rules);
496 free(g);
497 recfree_group(gt);
500 void
501 process_event(struct group *g, XKeyEvent *e)
503 Window focused;
504 struct rule *r;
505 struct key pressed = {
506 .modifier = e->state,
507 .key = keycode_to_keysym(e->keycode),
508 };
510 focused = focused_window();
512 for (; g != NULL; g = g->next) {
513 if (!group_match(g, focused))
514 continue;
516 for (r = g->rules; r != NULL; r = r->next) {
517 if (rule_matched(r, pressed)) {
518 do_action(r->action, focused, e);
519 return;
524 send_fake(focused, pressed, e);
527 int
528 group_match(struct group *g, Window w)
530 struct match *m;
532 for (m = g->matches; m != NULL; m = m->next)
533 if (match_window(m, w))
534 return 1;
535 return 0;
539 /* debug/dump stuff */
541 void
542 printkey(struct key k)
544 if (k.modifier & ControlMask)
545 printf("C-");
546 if (k.modifier & ShiftMask)
547 printf("S-");
548 if (k.modifier & Mod1Mask)
549 printf("M-");
550 if (k.modifier & Mod4Mask)
551 printf("s-");
553 printf("%s", XKeysymToString(k.key));
556 void
557 printaction(struct action a)
559 switch (a.type) {
560 case ASPECIAL:
561 switch (a.special) {
562 case ATOGGLE: printf("toggle"); break;
563 case AACTIVATE: printf("activate"); break;
564 case ADEACTIVATE: printf("deactivate"); break;
565 case AIGNORE: printf("ignore"); break;
566 default: abort(); /* unreachable */
568 break;
570 case AFAKE:
571 printf("send key ");
572 printkey(a.send_key);
573 break;
575 case AEXEC:
576 printf("exec %s", a.str);
577 break;
579 default:
580 /* unreachable */
581 abort();
585 void
586 printmatch(struct match *m)
588 if (m == NULL) {
589 printf("(null)");
590 return;
592 printf("match ");
593 switch (m->prop) {
594 case MANY:
595 printf("all");
596 break;
597 case MCLASS:
598 printf("class %s", m->str);
599 break;
600 default:
601 /* unreachable */
602 abort();
605 if (m->next == NULL)
606 printf("\n");
607 else {
608 printf(" ; ");
609 printmatch(m->next);
613 void
614 printrule(struct rule *r)
616 if (r == NULL) {
617 printf("(null)");
618 return;
620 printf("on ");
621 printkey(r->key);
622 printf(" do ");
623 printaction(r->action);
624 printf("\n");
626 if (r->next != NULL)
627 printrule(r->next);
630 void
631 printgroup(struct group *g)
633 if (g == NULL) {
634 printf("(null)");
635 return;
637 printmatch(g->matches);
638 printf("\n");
639 printrule(g->rules);
640 printf("\n\n");
642 if (g->next != NULL)
643 printgroup(g->next);