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, int pressed)
276 XKeyEvent e;
278 e.type = pressed ? KeyPress : KeyRelease;
280 e.display = d;
281 e.window = w;
282 e.root = DefaultRootWindow(d);
283 e.subwindow = None;
284 e.time = CurrentTime;
286 /* TODO: fix these */
287 e.x = 1;
288 e.y = 1;
289 e.x_root = 1;
290 e.y_root = 1;
292 e.same_screen = True;
293 e.keycode = XKeysymToKeycode(d, k.key);
294 e.state = k.modifier;
296 XSendEvent(d, w, True, KeyPressMask, (XEvent*)&e);
297 XFlush(d);
300 int
301 window_match_class(Window w, const char *class)
303 XClassHint ch;
304 int matched;
306 if (!XGetClassHint(d, w, &ch)) {
307 fprintf(stderr, "XGetClassHint failed\n");
308 return 0;
311 matched = !strcmp(ch.res_class, class);
313 XFree(ch.res_name);
314 XFree(ch.res_class);
316 return matched;
320 /* action */
322 void
323 do_action(struct action a, Window focused, int pressed)
325 switch (a.type) {
326 case AFAKE:
327 send_fake(focused, a.send_key, pressed);
328 break;
330 case ASPECIAL:
331 switch (a.special) {
332 case ATOGGLE:
333 case AACTIVATE:
334 case ADEACTIVATE:
335 printf("TODO\n");
336 break;
338 case AIGNORE:
339 break;
341 default:
342 /* unreachable */
343 abort();
345 break;
347 case AEXEC: {
348 pid_t p;
349 const char *sh;
351 switch (p = fork()) {
352 case -1:
353 err(1, "fork");
355 case 0:
356 if ((sh = getenv("SHELL")) == NULL)
357 sh = "/bin/sh";
358 printf("before exec'ing %s -c '%s'\n", sh, a.str);
359 execlp(sh, sh, "-c", a.str, NULL);
360 err(1, "execlp");
363 break;
366 default:
367 /* unreachable */
368 abort();
372 void
373 free_action(struct action a)
375 if (a.type == AEXEC)
376 free(a.str);
380 /* match */
382 struct match *
383 new_match(int prop, char *s)
385 struct match *m;
387 if ((m = calloc(1, sizeof(*m))) == NULL)
388 err(1, "calloc");
389 m->prop = prop;
390 m->str = s;
391 return m;
394 void
395 recfree_match(struct match *m)
397 struct match *mt;
399 if (m == NULL)
400 return;
402 mt = m->next;
403 free(m->str);
404 free(m);
405 recfree_match(mt);
408 int
409 match_window(struct match *m, Window w)
411 switch (m->prop) {
412 case MANY:
413 return 1;
415 case MCLASS:
416 return window_match_class(w, m->str);
417 break;
419 default:
420 /* unreachable */
421 abort();
426 /* rule */
428 struct rule *
429 new_rule(struct key k, struct action a)
431 struct rule *r;
433 if ((r = calloc(1, sizeof(*r))) == NULL)
434 err(1, "calloc");
435 memcpy(&r->key, &k, sizeof(k));
436 memcpy(&r->action, &a, sizeof(a));
437 return r;
440 void
441 recfree_rule(struct rule *r)
443 struct rule *rt;
445 if (r == NULL)
446 return;
448 rt = r->next;
449 free(r);
450 recfree_rule(rt);
453 int
454 rule_matched(struct rule *r, struct key k)
456 unsigned int m;
458 m = k.modifier;
459 m &= ~IGNORE_MODIFIERS; /* clear ignored modifiers */
461 return r->key.modifier == m
462 && r->key.key == k.key;
466 /* group */
468 struct group *
469 new_group(struct match *matches, struct rule *rules)
471 struct group *g;
473 if ((g = calloc(1, sizeof(*g))) == NULL)
474 err(1, "calloc");
475 g->matches = matches;
476 g->rules = rules;
477 return g;
480 void
481 recfree_group(struct group *g)
483 struct group *gt;
485 if (g == NULL)
486 return;
488 gt = g->next;
489 recfree_match(g->matches);
490 recfree_rule(g->rules);
491 free(g);
492 recfree_group(gt);
495 void
496 process_event(struct group *g, XKeyEvent *e)
498 Window focused;
499 struct rule *r;
500 struct key pressed = {
501 .modifier = e->state,
502 .key = keycode_to_keysym(e->keycode),
503 };
505 focused = focused_window();
507 for (; g != NULL; g = g->next) {
508 if (!group_match(g, focused))
509 continue;
511 for (r = g->rules; r != NULL; r = r->next) {
512 if (rule_matched(r, pressed)) {
513 do_action(r->action, focused, e->type == KeyPress);
514 return;
519 send_fake(focused, pressed, e->type == KeyPress);
522 int
523 group_match(struct group *g, Window w)
525 struct match *m;
527 for (m = g->matches; m != NULL; m = m->next)
528 if (match_window(m, w))
529 return 1;
530 return 0;
534 /* debug/dump stuff */
536 void
537 printkey(struct key k)
539 if (k.modifier & ControlMask)
540 printf("C-");
541 if (k.modifier & ShiftMask)
542 printf("S-");
543 if (k.modifier & Mod1Mask)
544 printf("M-");
545 if (k.modifier & Mod4Mask)
546 printf("s-");
548 printf("%s", XKeysymToString(k.key));
551 void
552 printaction(struct action a)
554 switch (a.type) {
555 case ASPECIAL:
556 switch (a.special) {
557 case ATOGGLE: printf("toggle"); break;
558 case AACTIVATE: printf("activate"); break;
559 case ADEACTIVATE: printf("deactivate"); break;
560 case AIGNORE: printf("ignore"); break;
561 default: abort(); /* unreachable */
563 break;
565 case AFAKE:
566 printf("send key ");
567 printkey(a.send_key);
568 break;
570 case AEXEC:
571 printf("exec %s", a.str);
572 break;
574 default:
575 /* unreachable */
576 abort();
580 void
581 printmatch(struct match *m)
583 if (m == NULL) {
584 printf("(null)");
585 return;
587 printf("match ");
588 switch (m->prop) {
589 case MANY:
590 printf("all");
591 break;
592 case MCLASS:
593 printf("class %s", m->str);
594 break;
595 default:
596 /* unreachable */
597 abort();
600 if (m->next == NULL)
601 printf("\n");
602 else {
603 printf(" ; ");
604 printmatch(m->next);
608 void
609 printrule(struct rule *r)
611 if (r == NULL) {
612 printf("(null)");
613 return;
615 printf("on ");
616 printkey(r->key);
617 printf(" do ");
618 printaction(r->action);
619 printf("\n");
621 if (r->next != NULL)
622 printrule(r->next);
625 void
626 printgroup(struct group *g)
628 if (g == NULL) {
629 printf("(null)");
630 return;
632 printmatch(g->matches);
633 printf("\n");
634 printrule(g->rules);
635 printf("\n\n");
637 if (g->next != NULL)
638 printgroup(g->next);