]> Pileus Git - wmpus/blob - sys-x11.c
Use config for sys-x11 and wm-wmii
[wmpus] / sys-x11.c
1 /*
2  * Copyright (c) 2011, Andy Spencer <andy753421@gmail.com>
3  *
4  * Permission to use, copy, modify, and/or 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  */
15
16 #define _GNU_SOURCE
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <search.h>
20
21 #include <X11/Xlib.h>
22 #include <X11/Xproto.h>
23 #include <X11/Xatom.h>
24 #include <X11/keysym.h>
25 #include <X11/extensions/Xinerama.h>
26
27 #include "util.h"
28 #include "conf.h"
29 #include "sys.h"
30 #include "wm.h"
31
32 /* Configuration */
33 static int BORDER     = 2;
34 static int NO_CAPTURE = 0;
35
36 /* Internal structures */
37 struct win_sys {
38         Window   xid;
39         Display *dpy;
40         struct {
41                 int left, right, top, bottom;
42         } strut;
43         state_t  state;
44 };
45
46 typedef struct {
47         Key_t key;
48         int   sym;
49 } keymap_t;
50
51 typedef enum {
52         wm_proto, wm_focus, net_strut, natoms
53 } atom_t;
54
55 typedef enum {
56         clr_focus, clr_unfocus, clr_urgent, ncolors
57 } color_t;
58
59 /* Global data */
60 static int   running;
61 static void *cache;
62 static Atom atoms[natoms];
63 static int (*xerrorxlib)(Display *, XErrorEvent *);
64 static unsigned long colors[ncolors];
65 static list_t *screens;
66
67 /* Conversion functions */
68 static keymap_t key2sym[] = {
69         {key_left    , XK_Left },
70         {key_right   , XK_Right},
71         {key_up      , XK_Up   },
72         {key_down    , XK_Down },
73         {key_home    , XK_Home },
74         {key_end     , XK_End  },
75         {key_pageup  , XK_Prior},
76         {key_pagedown, XK_Next },
77         {key_f1      , XK_F1   },
78         {key_f2      , XK_F2   },
79         {key_f3      , XK_F3   },
80         {key_f4      , XK_F4   },
81         {key_f5      , XK_F5   },
82         {key_f6      , XK_F6   },
83         {key_f7      , XK_F7   },
84         {key_f8      , XK_F8   },
85         {key_f9      , XK_F9   },
86         {key_f10     , XK_F10  },
87         {key_f11     , XK_F11  },
88         {key_f12     , XK_F12  },
89 };
90
91 /* - Modifiers */
92 static mod_t x2mod(unsigned int state, int up)
93 {
94         return (mod_t){
95                .alt   = !!(state & Mod1Mask   ),
96                .ctrl  = !!(state & ControlMask),
97                .shift = !!(state & ShiftMask  ),
98                .win   = !!(state & Mod4Mask   ),
99                .up    = up,
100         };
101 }
102
103 static unsigned int mod2x(mod_t mod)
104 {
105         return (mod.alt   ? Mod1Mask    : 0)
106              | (mod.ctrl  ? ControlMask : 0)
107              | (mod.shift ? ShiftMask   : 0)
108              | (mod.win   ? Mod4Mask    : 0);
109 }
110
111 /* - Keycodes */
112 static Key_t x2key(KeySym sym)
113 {
114         keymap_t *km = map_getr(key2sym,sym);
115         return km ? km->key : sym;
116 }
117
118 static KeySym key2x(Key_t key)
119 {
120         keymap_t *km = map_get(key2sym,key);
121         return km ? km->sym : key;
122 }
123
124 static Key_t x2btn(int btn)
125 {
126         return btn + key_mouse0;
127 }
128
129 static int btn2x(Key_t key)
130 {
131         return key - key_mouse0;
132 }
133
134 /* - Pointers */
135 static ptr_t x2ptr(XEvent *_ev)
136 {
137         XKeyEvent *ev = &_ev->xkey;
138         return (ptr_t){ev->x, ev->y, ev->x_root, ev->y_root};
139 }
140
141 static Window getfocus(win_t *root, XEvent *event)
142 {
143         int revert;
144         Window focus = PointerRoot;
145         if (event->type == KeyPress || event->type == KeyRelease)
146                 XGetInputFocus(root->sys->dpy, &focus, &revert);
147         if (focus == PointerRoot)
148                 focus = event->xkey.subwindow;
149         if (focus == None)
150                 focus = event->xkey.window;
151         return focus;
152 }
153
154 /* Strut functions
155  *   Struts are spaces at the edges of the screen that are used by
156  *   toolbars and statusbars such as dzen. */
157 static int strut_copy(win_t *to, win_t *from, int scale)
158 {
159         int left   = from->sys->strut.left;
160         int right  = from->sys->strut.right;
161         int top    = from->sys->strut.top;
162         int bottom = from->sys->strut.bottom;
163         if (left == 0 && right == 0 && top == 0 && bottom == 0)
164                 return 0;
165         to->x += scale*(left      );
166         to->y += scale*(top       );
167         to->w -= scale*(left+right);
168         to->h -= scale*(top+bottom);
169         return 1;
170 }
171
172 static int strut_add(win_t *root, win_t *win)
173 {
174         /* Get X11 strut data */
175         Atom ret_type;
176         int ret_size;
177         unsigned long ret_items, bytes_left;
178         unsigned char *xdata;
179         int status = XGetWindowProperty(win->sys->dpy, win->sys->xid,
180                         atoms[net_strut], 0L, 4L, False, XA_CARDINAL,
181                         &ret_type, &ret_size, &ret_items, &bytes_left, &xdata);
182         if (status != Success || ret_size != 32 || ret_items != 4)
183                 return 0;
184
185         win->sys->strut.left   = ((int*)xdata)[0];
186         win->sys->strut.right  = ((int*)xdata)[1];
187         win->sys->strut.top    = ((int*)xdata)[2];
188         win->sys->strut.bottom = ((int*)xdata)[3];
189         for (list_t *cur = screens; cur; cur = cur->next)
190                 strut_copy(cur->data, win, 1);
191         return strut_copy(root, win, 1);
192 }
193
194 static int strut_del(win_t *root, win_t *win)
195 {
196         for (list_t *cur = screens; cur; cur = cur->next)
197                 strut_copy(cur->data, win, -1);
198         return strut_copy(root, win, -1);
199 }
200
201 /* Window functions */
202 static win_t *win_new(Display *dpy, Window xid)
203 {
204         XWindowAttributes attr;
205         if (XGetWindowAttributes(dpy, xid, &attr))
206                 if (attr.override_redirect)
207                         return NULL;
208         win_t *win    = new0(win_t);
209         win->x        = attr.x;
210         win->y        = attr.y;
211         win->w        = attr.width;
212         win->h        = attr.height;
213         win->sys      = new0(win_sys_t);
214         win->sys->dpy = dpy;
215         win->sys->xid = xid;
216         printf("win_new: %p = %p, %d (%d,%d %dx%d)\n",
217                         win, dpy, (int)xid,
218                         win->x, win->y, win->w, win->h);
219         return win;
220 }
221
222 static int win_cmp(const void *_a, const void *_b)
223 {
224         const win_t *a = _a, *b = _b;
225         if (a->sys->dpy < b->sys->dpy) return -1;
226         if (a->sys->dpy > b->sys->dpy) return  1;
227         if (a->sys->xid < b->sys->xid) return -1;
228         if (a->sys->xid > b->sys->xid) return  1;
229         return 0;
230 }
231
232 static win_t *win_find(Display *dpy, Window xid, int create)
233 {
234         if (!dpy || !xid)
235                 return NULL;
236         //printf("win_find: %p, %d\n", dpy, (int)xid);
237         win_sys_t sys = {.dpy=dpy, .xid=xid};
238         win_t     tmp = {.sys=&sys};
239         win_t **old = NULL, *new = NULL;
240         if ((old = tfind(&tmp, &cache, win_cmp)))
241                 return *old;
242         if (create && (new = win_new(dpy,xid)))
243                 tsearch(new, &cache, win_cmp);
244         return new;
245 }
246
247 static void win_free(win_t *win)
248 {
249         free(win->sys);
250         free(win);
251 }
252
253 static void win_remove(win_t *win)
254 {
255         tdelete(win, &cache, win_cmp);
256         win_free(win);
257 }
258
259 static int win_viewable(win_t *win)
260 {
261         XWindowAttributes attr;
262         if (XGetWindowAttributes(win->sys->dpy, win->sys->xid, &attr))
263                 return attr.map_state == IsViewable;
264         else
265                 return True;
266 }
267
268 /* Drawing functions */
269 static unsigned long get_color(Display *dpy, const char *name)
270 {
271         XColor color;
272         int screen = DefaultScreen(dpy);
273         Colormap cmap = DefaultColormap(dpy, screen);
274         XAllocNamedColor(dpy, cmap, name, &color, &color);
275         return color.pixel;
276 }
277
278 /* Callbacks */
279 static void process_event(int type, XEvent *ev, win_t *root)
280 {
281         Display  *dpy = root->sys->dpy;
282         win_t *win = NULL;
283         //printf("event: %d\n", type);
284
285         /* Common data for all these events ... */
286         ptr_t ptr = {}; mod_t mod = {};
287         if (type == KeyPress    || type == KeyRelease    ||
288             type == ButtonPress || type == ButtonRelease ||
289             type == MotionNotify) {
290                 Window xid = getfocus(root, ev);
291                 if (!(win = win_find(dpy,xid,0)))
292                         return;
293                 ptr = x2ptr(ev);
294                 mod = x2mod(ev->xkey.state, type==KeyRelease||type==ButtonRelease);
295         }
296
297         /* Split based on event */
298         if (type == KeyPress) {
299                 while (XCheckTypedEvent(dpy, KeyPress, ev));
300                 KeySym sym = XKeycodeToKeysym(dpy, ev->xkey.keycode, 0);
301                 printf("got key %c %hhx\n", x2key(sym), mod2int(mod));
302                 wm_handle_key(win, x2key(sym), mod, ptr);
303         }
304         else if (type == KeyRelease) {
305                 //printf("release: %d\n", type);
306         }
307         else if (type == ButtonPress) {
308                 if (wm_handle_key(win, x2btn(ev->xbutton.button), mod, ptr))
309                         XGrabPointer(dpy, ev->xbutton.root, True, PointerMotionMask|ButtonReleaseMask,
310                                         GrabModeAsync, GrabModeAsync, None, None, CurrentTime);
311                 else {
312                         printf("resending event\n");
313                         XSendEvent(win->sys->dpy, ev->xbutton.window,    True,  NoEventMask, ev);
314                         XSendEvent(win->sys->dpy, ev->xbutton.window,    False, NoEventMask, ev);
315                         XSendEvent(win->sys->dpy, ev->xbutton.root,      True,  NoEventMask, ev);
316                         XSendEvent(win->sys->dpy, ev->xbutton.root,      False, NoEventMask, ev);
317                         XSendEvent(win->sys->dpy, ev->xbutton.subwindow, True,  NoEventMask, ev);
318                         XSendEvent(win->sys->dpy, ev->xbutton.subwindow, False, NoEventMask, ev);
319                 }
320         }
321         else if (type == ButtonRelease) {
322                 XUngrabPointer(dpy, CurrentTime);
323                 wm_handle_key(win, x2btn(ev->xbutton.button), mod, ptr);
324         }
325         else if (type == MotionNotify) {
326                 while (XCheckTypedEvent(dpy, MotionNotify, ev));
327                 wm_handle_ptr(win, ptr);
328         }
329         else if (type == EnterNotify || type == LeaveNotify) {
330                 printf("enter: %d\n", type);
331                 key_t key = EnterNotify ? key_enter : key_leave;
332                 if ((win = win_find(dpy,ev->xcrossing.window,0)))
333                         wm_handle_key(win, key, MOD(), PTR());
334         }
335         else if (type == FocusIn || type == FocusOut) {
336                 //printf("focus: %d\n", type);
337                 key_t key = FocusIn ? key_focus : key_unfocus;
338                 if ((win = win_find(dpy,ev->xfocus.window,0)))
339                         wm_handle_key(win, key, MOD(), PTR());
340         }
341         else if (type == ConfigureNotify) {
342                 printf("configure: %d\n", type);
343         }
344         else if (type == MapNotify) {
345                 printf("map: %d\n", type);
346         }
347         else if (type == UnmapNotify) {
348                 if ((win = win_find(dpy,ev->xunmap.window,0)) &&
349                      win->sys->state == st_show) {
350                         if (!strut_del(root, win))
351                                 wm_remove(win);
352                         else
353                                 wm_update();
354                         win->sys->state = st_hide;
355                 }
356         }
357         else if (type == DestroyNotify) {
358                 //printf("destroy: %d\n", type);
359                 if ((win = win_find(dpy,ev->xdestroywindow.window,0)))
360                         win_remove(win);
361         }
362         else if (type == ConfigureRequest) {
363                 XConfigureRequestEvent *cre = &ev->xconfigurerequest;
364                 printf("configure_req: %d - %x, (0x%lx) %dx%d @ %d,%d\n",
365                                 type, (int)cre->window, cre->value_mask,
366                                 cre->height, cre->width, cre->x, cre->y);
367                 XConfigureWindow(dpy, cre->window, cre->value_mask, &(XWindowChanges){
368                         .x      = cre->x,
369                         .y      = cre->y,
370                         .width  = cre->width,
371                         .height = cre->height,
372                 });
373
374                 /* This seems necessary for, but causes flicker
375                  * there could be a better way to do this */
376                 if ((win = win_find(dpy,ev->xmaprequest.window,0)))
377                         sys_move(win, win->x, win->y, win->w, win->h);
378         }
379         else if (type == MapRequest) {
380                 printf("map_req: %d\n", type);
381                 if ((win = win_find(dpy,ev->xmaprequest.window,1))) {
382                         if (!strut_add(root, win))
383                                 wm_insert(win);
384                         else
385                                 wm_update();
386                 }
387                 XMapWindow(dpy,ev->xmaprequest.window);
388         }
389         else {
390                 printf("unknown event: %d\n", type);
391         }
392 }
393
394 static int xerror(Display *dpy, XErrorEvent *err)
395 {
396         if (err->error_code == BadWindow ||
397             (err->request_code == X_SetInputFocus     && err->error_code == BadMatch   ) ||
398             (err->request_code == X_PolyText8         && err->error_code == BadDrawable) ||
399             (err->request_code == X_PolyFillRectangle && err->error_code == BadDrawable) ||
400             (err->request_code == X_PolySegment       && err->error_code == BadDrawable) ||
401             (err->request_code == X_ConfigureWindow   && err->error_code == BadMatch   ) ||
402             (err->request_code == X_GrabButton        && err->error_code == BadAccess  ) ||
403             (err->request_code == X_GrabKey           && err->error_code == BadAccess  ) ||
404             (err->request_code == X_CopyArea          && err->error_code == BadDrawable))
405                 return 0;
406         return xerrorxlib(dpy, err);
407 }
408
409 /********************
410  * System functions *
411  ********************/
412 void sys_move(win_t *win, int x, int y, int w, int h)
413 {
414         //printf("sys_move: %p - %d,%d  %dx%d\n", win, x, y, w, h);
415         int b = 2*BORDER;
416         win->x = x; win->y = y;
417         win->w = MAX(w,1+b); win->h = MAX(h,1+b);
418         w      = MAX(w-b,1); h      = MAX(h-b,1);
419         XMoveResizeWindow(win->sys->dpy, win->sys->xid, x, y, w, h);
420
421         /* Flush events, so moving window doesn't cause re-focus
422          * There's probably a better way to do this */
423         XEvent ev;
424         XSync(win->sys->dpy, False);
425         while (XCheckMaskEvent(win->sys->dpy, EnterWindowMask|LeaveWindowMask, &ev))
426                 printf("Skipping enter/leave event\n");
427 }
428
429 void sys_raise(win_t *win)
430 {
431         //printf("sys_raise: %p\n", win);
432         XRaiseWindow(win->sys->dpy, win->sys->xid);
433 }
434
435 void sys_focus(win_t *win)
436 {
437         //printf("sys_focus: %p\n", win);
438
439         /* Set border on focused window */
440         static win_t *last = NULL;
441         if (last)
442                 XSetWindowBorder(last->sys->dpy, last->sys->xid, colors[clr_unfocus]);
443         XSetWindowBorder(win->sys->dpy, win->sys->xid, colors[clr_focus]);
444         XSetWindowBorderWidth(win->sys->dpy, win->sys->xid, BORDER);
445         last = win;
446
447         /* Set actual focus */
448         XSetInputFocus(win->sys->dpy, win->sys->xid,
449                         RevertToPointerRoot, CurrentTime);
450         XSendEvent(win->sys->dpy, win->sys->xid, False, NoEventMask, &(XEvent){
451                 .type                 = ClientMessage,
452                 .xclient.window       = win->sys->xid,
453                 .xclient.message_type = atoms[wm_proto],
454                 .xclient.format       = 32,
455                 .xclient.data.l[0]    = atoms[wm_focus],
456                 .xclient.data.l[1]    = CurrentTime,
457         });
458 }
459
460 void sys_show(win_t *win, state_t state)
461 {
462         win->sys->state = state;
463         switch (state) {
464         case st_show:
465                 printf("sys_show: show\n");
466                 XMapWindow(win->sys->dpy, win->sys->xid);
467                 XSync(win->sys->dpy, False);
468                 return;
469         case st_full:
470                 printf("sys_show: full\n");
471                 return;
472         case st_shade:
473                 printf("sys_show: shade\n");
474                 return;
475         case st_icon:
476                 printf("sys_show: icon\n");
477                 return;
478         case st_hide:
479                 printf("sys_show: hide\n");
480                 XUnmapWindow(win->sys->dpy, win->sys->xid);
481                 return;
482         }
483 }
484
485 void sys_watch(win_t *win, Key_t key, mod_t mod)
486 {
487         //printf("sys_watch: %p - %x %hhx\n", win, key, mod);
488         XWindowAttributes attr;
489         XGetWindowAttributes(win->sys->dpy, win->sys->xid, &attr);
490         long mask = attr.your_event_mask;
491         if (key_mouse0 <= key && key <= key_mouse7)
492                 XGrabButton(win->sys->dpy, btn2x(key), mod2x(mod), win->sys->xid, False,
493                                 mod.up ? ButtonReleaseMask : ButtonPressMask,
494                                 GrabModeAsync, GrabModeAsync, None, None);
495         else if (key == key_enter)
496                 XSelectInput(win->sys->dpy, win->sys->xid, EnterWindowMask|mask);
497         else if (key == key_leave)
498                 XSelectInput(win->sys->dpy, win->sys->xid, LeaveWindowMask|mask);
499         else if (key == key_focus || key == key_unfocus)
500                 XSelectInput(win->sys->dpy, win->sys->xid, FocusChangeMask|mask);
501         else
502                 XGrabKey(win->sys->dpy, XKeysymToKeycode(win->sys->dpy, key2x(key)),
503                                 mod2x(mod), win->sys->xid, True, GrabModeAsync, GrabModeAsync);
504 }
505
506 void sys_unwatch(win_t *win, Key_t key, mod_t mod)
507 {
508         if (key_mouse0 <= key && key <= key_mouse7)
509                 XUngrabButton(win->sys->dpy, btn2x(key), mod2x(mod), win->sys->xid);
510 }
511
512 list_t *sys_info(win_t *win)
513 {
514         /* Use global copy of screens so we can add struts */
515         if (screens == NULL) {
516                 /* Add Xinerama screens */
517                 int n = 0;
518                 XineramaScreenInfo *info = NULL;
519                 if (XineramaIsActive(win->sys->dpy))
520                         info = XineramaQueryScreens(win->sys->dpy, &n);
521                 for (int i = 0; i < n; i++) {
522                         win_t *screen = new0(win_t);
523                         screen->x = info[i].x_org;
524                         screen->y = info[i].y_org;
525                         screen->w = info[i].width;
526                         screen->h = info[i].height;
527                         screens = list_append(screens, screen);
528                 }
529         }
530         if (screens == NULL) {
531                 /* No xinerama support */
532                 win_t *screen = new0(win_t);
533                 *screen = *win;
534                 screens = list_insert(NULL, screen);
535         }
536         return screens;
537 }
538
539 win_t *sys_init(void)
540 {
541         Display *dpy;
542         Window   xid;
543
544         /* Load configuration */
545         BORDER     = conf_get_int("main.border",     BORDER);
546         NO_CAPTURE = conf_get_int("main.no-capture", NO_CAPTURE);
547
548         /* Open the display */
549         if (!(dpy = XOpenDisplay(NULL)))
550                 error("Unable to get display");
551         if (!(xid = DefaultRootWindow(dpy)))
552                 error("Unable to get root window");
553
554         /* Setup X11 data */
555         atoms[wm_proto]  = XInternAtom(dpy, "WM_PROTOCOLS",  False);
556         atoms[wm_focus]  = XInternAtom(dpy, "WM_TAKE_FOCUS", False);
557         atoms[net_strut] = XInternAtom(dpy, "_NET_WM_STRUT", False);
558
559         colors[clr_focus]   = get_color(dpy, "#a0a0ff");
560         colors[clr_unfocus] = get_color(dpy, "#101066");
561         colors[clr_urgent]  = get_color(dpy, "#ff0000");
562         printf("colors = #%06lx #%06lx #%06lx\n", colors[0], colors[1], colors[2]);
563
564         /* Select window management events */
565         XSelectInput(dpy, xid, SubstructureRedirectMask|SubstructureNotifyMask);
566         XSetInputFocus(dpy, None, RevertToNone, CurrentTime);
567         xerrorxlib = XSetErrorHandler(xerror);
568
569         return win_find(dpy, xid, 1);
570 }
571
572 void sys_run(win_t *root)
573 {
574         /* Add each initial window */
575         if (!NO_CAPTURE) {
576                 unsigned int nkids;
577                 Window par, xid, *kids = NULL;
578                 if (XQueryTree(root->sys->dpy, root->sys->xid,
579                                         &par, &xid, &kids, &nkids)) {
580                         for(int i = 0; i < nkids; i++) {
581                                 win_t *win = win_find(root->sys->dpy, kids[i], 1);
582                                 if (win && win_viewable(win) && !strut_add(root,win))
583                                         wm_insert(win);
584                         }
585                         XFree(kids);
586                 }
587                 wm_update(); // For struts
588         }
589
590         /* Main loop */
591         running = 1;
592         while (running)
593         {
594                 XEvent ev;
595                 XNextEvent(root->sys->dpy, &ev);
596                 process_event(ev.type, &ev, root);
597         }
598 }
599
600 void sys_exit(void)
601 {
602         running = 0;
603 }
604
605 void sys_free(win_t *root)
606 {
607         XCloseDisplay(root->sys->dpy);
608         while (screens)
609                 screens = list_remove(screens, screens, 1);
610         tdestroy(cache, (void(*)(void*))win_free);
611 }