]> Pileus Git - wmpus/blob - sys-x11.c
Fix showing struts
[wmpus] / sys-x11.c
1 /*
2  * Copyright (c) 2011-2012, 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 };
44
45 typedef struct {
46         event_t ev;
47         int     sym;
48 } event_map_t;
49
50 typedef enum {
51         WM_PROTO, WM_FOCUS, WM_DELETE,
52         NET_STATE, NET_FULL, NET_STRUT,
53         NET_TYPE, NET_DIALOG,
54         NATOMS
55 } atom_t;
56
57 typedef enum {
58         CLR_FOCUS, CLR_UNFOCUS, CLR_URGENT, NCOLORS
59 } color_t;
60
61 /* Global data */
62 static int   running;
63 static void *cache;
64 static Atom atoms[NATOMS];
65 static int (*xerrorxlib)(Display *, XErrorEvent *);
66 static unsigned long colors[NCOLORS];
67 static list_t *screens;
68 static list_t *struts;
69
70 /* Conversion functions */
71 static event_map_t ev2sym[] = {
72         {EV_LEFT    , XK_Left },
73         {EV_RIGHT   , XK_Right},
74         {EV_UP      , XK_Up   },
75         {EV_DOWN    , XK_Down },
76         {EV_HOME    , XK_Home },
77         {EV_END     , XK_End  },
78         {EV_PAGEUP  , XK_Prior},
79         {EV_PAGEDOWN, XK_Next },
80         {EV_F1      , XK_F1   },
81         {EV_F2      , XK_F2   },
82         {EV_F3      , XK_F3   },
83         {EV_F4      , XK_F4   },
84         {EV_F5      , XK_F5   },
85         {EV_F6      , XK_F6   },
86         {EV_F7      , XK_F7   },
87         {EV_F8      , XK_F8   },
88         {EV_F9      , XK_F9   },
89         {EV_F10     , XK_F10  },
90         {EV_F11     , XK_F11  },
91         {EV_F12     , XK_F12  },
92 };
93
94 /* - Modifiers */
95 static mod_t x2mod(unsigned int state, int up)
96 {
97         return (mod_t){
98                .alt   = !!(state & Mod1Mask   ),
99                .ctrl  = !!(state & ControlMask),
100                .shift = !!(state & ShiftMask  ),
101                .win   = !!(state & Mod4Mask   ),
102                .up    = up,
103         };
104 }
105
106 static unsigned int mod2x(mod_t mod)
107 {
108         return (mod.alt   ? Mod1Mask    : 0)
109              | (mod.ctrl  ? ControlMask : 0)
110              | (mod.shift ? ShiftMask   : 0)
111              | (mod.win   ? Mod4Mask    : 0);
112 }
113
114 /* - Keycodes */
115 static event_t xk2ev(KeySym sym)
116 {
117         event_map_t *em = map_getr(ev2sym,sym);
118         return em ? em->ev : sym;
119 }
120
121 static KeySym ev2xk(event_t ev)
122 {
123         event_map_t *em = map_get(ev2sym,ev);
124         return em ? em->sym : ev;
125 }
126
127 static event_t xb2ev(int btn)
128 {
129         return btn + EV_MOUSE0;
130 }
131
132 static int ev2xb(event_t ev)
133 {
134         return ev - EV_MOUSE0;
135 }
136
137 /* - Pointers */
138 static ptr_t x2ptr(XEvent *xe)
139 {
140         XKeyEvent *xke = &xe->xkey;
141         return (ptr_t){xke->x, xke->y, xke->x_root, xke->y_root};
142 }
143
144 static Window getfocus(win_t *root, XEvent *xe)
145 {
146         int revert;
147         Window focus = PointerRoot;
148         if (xe->type == KeyPress || xe->type == KeyRelease)
149                 XGetInputFocus(root->sys->dpy, &focus, &revert);
150         if (focus == PointerRoot)
151                 focus = xe->xkey.subwindow;
152         if (focus == None)
153                 focus = xe->xkey.window;
154         return focus;
155 }
156
157 /* Strut functions
158  *   Struts are spaces at the edges of the screen that are used by
159  *   toolbars and statusbars such as dzen. */
160 static int strut_copy(win_t *to, win_t *from, int scale)
161 {
162         int left   = from->sys->strut.left;
163         int right  = from->sys->strut.right;
164         int top    = from->sys->strut.top;
165         int bottom = from->sys->strut.bottom;
166         if (left == 0 && right == 0 && top == 0 && bottom == 0)
167                 return 0;
168         to->x += scale*(left      );
169         to->y += scale*(top       );
170         to->w -= scale*(left+right);
171         to->h -= scale*(top+bottom);
172         to->sys->strut.left   += scale*left;
173         to->sys->strut.right  += scale*right;
174         to->sys->strut.top    += scale*top;
175         to->sys->strut.bottom += scale*bottom;
176         return 1;
177 }
178
179 static int strut_add(win_t *root, win_t *win)
180 {
181         /* Get X11 strut data */
182         Atom ret_type;
183         int ret_size;
184         unsigned long ret_items, bytes_left;
185         unsigned char *xdata;
186         int status = XGetWindowProperty(win->sys->dpy, win->sys->xid,
187                         atoms[NET_STRUT], 0L, 4L, False, XA_CARDINAL,
188                         &ret_type, &ret_size, &ret_items, &bytes_left, &xdata);
189         if (status != Success || ret_size != 32 || ret_items != 4)
190                 return 0;
191
192         win->sys->strut.left   = ((int*)xdata)[0];
193         win->sys->strut.right  = ((int*)xdata)[1];
194         win->sys->strut.top    = ((int*)xdata)[2];
195         win->sys->strut.bottom = ((int*)xdata)[3];
196         struts = list_insert(struts, win);
197         for (list_t *cur = screens; cur; cur = cur->next)
198                 strut_copy(cur->data, win, 1);
199         return strut_copy(root, win, 1);
200 }
201
202 static int strut_del(win_t *root, win_t *win)
203 {
204         list_t *lwin = list_find(struts, win);
205         if (lwin)
206                 struts = list_remove(struts, lwin, 0);
207         for (list_t *cur = screens; cur; cur = cur->next)
208                 strut_copy(cur->data, win, -1);
209         return strut_copy(root, win, -1);
210 }
211
212 /* Window functions */
213 static Atom win_prop(win_t *win, atom_t prop);
214 static win_t *win_find(Display *dpy, Window xid, int create);
215
216 static win_t *win_new(Display *dpy, Window xid)
217 {
218         Window trans;
219         XWindowAttributes attr;
220         if (XGetWindowAttributes(dpy, xid, &attr))
221                 if (attr.override_redirect)
222                         return NULL;
223         win_t *win    = new0(win_t);
224         win->x        = attr.x;
225         win->y        = attr.y;
226         win->w        = attr.width;
227         win->h        = attr.height;
228         win->sys      = new0(win_sys_t);
229         win->sys->dpy = dpy;
230         win->sys->xid = xid;
231         if (win_prop(win, NET_TYPE) == atoms[NET_DIALOG])
232                 win->type = TYPE_DIALOG;
233         if (XGetTransientForHint(dpy, xid, &trans))
234                 win->parent = win_find(dpy, trans, 0);
235         printf("win_new: %p = %p, %d (%d,%d %dx%d) - %s\n",
236                         win, dpy, (int)xid,
237                         win->x, win->y, win->w, win->h,
238                         win->type ? "dialog" : "normal");
239         return win;
240 }
241
242 static int win_cmp(const void *_a, const void *_b)
243 {
244         const win_t *a = _a, *b = _b;
245         if (a->sys->dpy < b->sys->dpy) return -1;
246         if (a->sys->dpy > b->sys->dpy) return  1;
247         if (a->sys->xid < b->sys->xid) return -1;
248         if (a->sys->xid > b->sys->xid) return  1;
249         return 0;
250 }
251
252 static win_t *win_find(Display *dpy, Window xid, int create)
253 {
254         if (!dpy || !xid)
255                 return NULL;
256         //printf("win_find: %p, %d\n", dpy, (int)xid);
257         win_sys_t sys = {.dpy=dpy, .xid=xid};
258         win_t     tmp = {.sys=&sys};
259         win_t **old = NULL, *new = NULL;
260         if ((old = tfind(&tmp, &cache, win_cmp)))
261                 return *old;
262         if (create && (new = win_new(dpy,xid)))
263                 tsearch(new, &cache, win_cmp);
264         return new;
265 }
266
267 static void win_free(win_t *win)
268 {
269         free(win->sys);
270         free(win);
271 }
272
273 static void win_remove(win_t *win)
274 {
275         tdelete(win, &cache, win_cmp);
276         win_free(win);
277 }
278
279 static int win_viewable(win_t *win)
280 {
281         XWindowAttributes attr;
282         if (XGetWindowAttributes(win->sys->dpy, win->sys->xid, &attr))
283                 return attr.map_state == IsViewable;
284         else
285                 return True;
286 }
287
288 static int win_msg(win_t *win, atom_t msg)
289 {
290         int n, found = 0;
291         Atom *protos;
292         if (!XGetWMProtocols(win->sys->dpy, win->sys->xid, &protos, &n))
293                 return 0;
294
295         while (!found && n--)
296                 found = protos[n] == atoms[msg];
297         XFree(protos);
298         if (!found)
299                 return 0;
300
301         XSendEvent(win->sys->dpy, win->sys->xid, False, NoEventMask, &(XEvent){
302                 .type                 = ClientMessage,
303                 .xclient.window       = win->sys->xid,
304                 .xclient.message_type = atoms[WM_PROTO],
305                 .xclient.format       = 32,
306                 .xclient.data.l[0]    = atoms[msg],
307                 .xclient.data.l[1]    = CurrentTime,
308         });
309         return 1;
310 }
311
312 static Atom win_prop(win_t *win, atom_t prop)
313 {
314         int format;
315         unsigned long nitems, bytes;
316         unsigned char *buf = NULL;
317         Atom atom, type = XA_ATOM;
318         if (XGetWindowProperty(win->sys->dpy, win->sys->xid, atoms[prop],
319                         0L, sizeof(Atom), False, type, &type, &format, &nitems, &bytes, &buf) || !buf)
320                 return 0;
321         atom = *(Atom *)buf;
322         XFree(buf);
323         return atom;
324 }
325
326 /* Drawing functions */
327 static unsigned long get_color(Display *dpy, const char *name)
328 {
329         XColor color;
330         int screen = DefaultScreen(dpy);
331         Colormap cmap = DefaultColormap(dpy, screen);
332         XAllocNamedColor(dpy, cmap, name, &color, &color);
333         return color.pixel;
334 }
335
336 /* Callbacks */
337 static void process_event(int type, XEvent *xe, win_t *root)
338 {
339         Display  *dpy = root->sys->dpy;
340         win_t *win = NULL;
341         //printf("event: %d\n", type);
342
343         /* Common data for all these events ... */
344         ptr_t ptr = {}; mod_t mod = {};
345         if (type == KeyPress    || type == KeyRelease    ||
346             type == ButtonPress || type == ButtonRelease ||
347             type == MotionNotify) {
348                 Window xid = getfocus(root, xe);
349                 if (!(win = win_find(dpy,xid,0)))
350                         return;
351                 //printf("button-press %p\n", win);
352                 ptr = x2ptr(xe);
353                 mod = x2mod(xe->xkey.state, type==KeyRelease||type==ButtonRelease);
354         }
355
356         /* Split based on event */
357         if (type == KeyPress) {
358                 while (XCheckTypedEvent(dpy, KeyPress, xe));
359                 KeySym sym = XKeycodeToKeysym(dpy, xe->xkey.keycode, 0);
360                 printf("got xe %c %hhx\n", xk2ev(sym), mod2int(mod));
361                 wm_handle_event(win, xk2ev(sym), mod, ptr);
362         }
363         else if (type == KeyRelease) {
364                 //printf("release: %d\n", type);
365         }
366         else if (type == ButtonPress) {
367                 if (wm_handle_event(win, xb2ev(xe->xbutton.button), mod, ptr)) {
368                         //printf("grab pointer\n");
369                         XGrabPointer(dpy, xe->xbutton.root, True, PointerMotionMask|ButtonReleaseMask,
370                                         GrabModeAsync, GrabModeAsync, None, None, CurrentTime);
371                 } else {
372                         //printf("allow events\n");
373                         XAllowEvents(win->sys->dpy, ReplayPointer, xe->xbutton.time);
374                 }
375         }
376         else if (type == ButtonRelease) {
377                 XUngrabPointer(dpy, CurrentTime);
378                 wm_handle_event(win, xb2ev(xe->xbutton.button), mod, ptr);
379         }
380         else if (type == MotionNotify) {
381                 while (XCheckTypedEvent(dpy, MotionNotify, xe));
382                 wm_handle_ptr(win, ptr);
383         }
384         else if (type == EnterNotify || type == LeaveNotify) {
385                 printf("%s: %d\n", type==EnterNotify?"enter":"leave", type);
386                 event_t ev = type == EnterNotify ? EV_ENTER : EV_LEAVE;
387                 if ((win = win_find(dpy,xe->xcrossing.window,0)))
388                         wm_handle_event(win, ev, MOD(), PTR());
389         }
390         else if (type == FocusIn || type == FocusOut) {
391                 //printf("focus: %d\n", type);
392                 event_t ev = FocusIn ? EV_FOCUS : EV_UNFOCUS;
393                 if ((win = win_find(dpy,xe->xfocus.window,0)))
394                         wm_handle_event(win, ev, MOD(), PTR());
395         }
396         else if (type == ConfigureNotify) {
397                 printf("configure: %d\n", type);
398         }
399         else if (type == MapNotify) {
400                 printf("map: %d\n", type);
401         }
402         else if (type == UnmapNotify) {
403                 if ((win = win_find(dpy,xe->xunmap.window,0)) &&
404                      win->state != ST_HIDE) {
405                         if (!strut_del(root, win))
406                                 wm_remove(win);
407                         else
408                                 wm_update();
409                         win->state = ST_HIDE;
410                 }
411         }
412         else if (type == DestroyNotify) {
413                 //printf("destroy: %d\n", type);
414                 if ((win = win_find(dpy,xe->xdestroywindow.window,0)))
415                         win_remove(win);
416         }
417         else if (type == ConfigureRequest) {
418                 XConfigureRequestEvent *cre = &xe->xconfigurerequest;
419                 printf("configure_req: %d - %x, (0x%lx) %dx%d @ %d,%d\n",
420                                 type, (int)cre->window, cre->value_mask,
421                                 cre->height, cre->width, cre->x, cre->y);
422                 if ((win = win_find(dpy,xe->xconfigurerequest.window,1))) {
423                         XSendEvent(dpy, cre->window, False, StructureNotifyMask, &(XEvent){
424                                 .xconfigure.type              = ConfigureNotify,
425                                 .xconfigure.display           = win->sys->dpy,
426                                 .xconfigure.event             = win->sys->xid,
427                                 .xconfigure.window            = win->sys->xid,
428                                 .xconfigure.x                 = win->x,
429                                 .xconfigure.y                 = win->y,
430                                 .xconfigure.width             = win->w,
431                                 .xconfigure.height            = win->h,
432                                 .xconfigure.border_width      = border,
433                         });
434                         XSync(win->sys->dpy, False);
435                 }
436         }
437         else if (type == MapRequest) {
438                 printf("map_req: %d\n", type);
439                 if ((win = win_find(dpy,xe->xmaprequest.window,1)) &&
440                      win->state == ST_HIDE) {
441                         win->state = ST_SHOW;
442                         if (win_prop(win, NET_STATE) == atoms[NET_FULL])
443                                 win->state = ST_FULL;
444                         XSelectInput(win->sys->dpy, win->sys->xid, PropertyChangeMask);
445                         if (!strut_add(root, win))
446                                 wm_insert(win);
447                         else
448                                 wm_update();
449                 }
450                 sys_show(win, win->state);
451         }
452         else if (type == ClientMessage) {
453                 XClientMessageEvent *cme = &xe->xclient;
454                 printf("msg: %d - %ld %ld,%ld,%ld,%ld,%ld\n",
455                                 type, cme->message_type,
456                                 cme->data.l[0], cme->data.l[1], cme->data.l[2],
457                                 cme->data.l[3], cme->data.l[4]);
458                 if ((win = win_find(dpy,cme->window,0))     &&
459                     (cme->message_type == atoms[NET_STATE]) &&
460                     (cme->data.l[1] == atoms[NET_FULL] ||
461                      cme->data.l[2] == atoms[NET_FULL])) {
462                         state_t next = (cme->data.l[0] == 1 || /* _NET_WM_STATE_ADD    */
463                                        (cme->data.l[0] == 2 && /* _NET_WM_STATE_TOGGLE */
464                                         win->state != ST_FULL)) ? ST_FULL : ST_SHOW;
465                         wm_handle_state(win, win->state, next);
466                         sys_show(win, next);
467                 }
468         }
469         else if (type == PropertyNotify) {
470                 printf("prop: %d - %d\n", type, xe->xproperty.state);
471         }
472         else {
473                 printf("unknown event: %d\n", type);
474         }
475 }
476
477 static int xerror(Display *dpy, XErrorEvent *err)
478 {
479         if (err->error_code == BadWindow ||
480             (err->request_code == X_SetInputFocus     && err->error_code == BadMatch   ) ||
481             (err->request_code == X_PolyText8         && err->error_code == BadDrawable) ||
482             (err->request_code == X_PolyFillRectangle && err->error_code == BadDrawable) ||
483             (err->request_code == X_PolySegment       && err->error_code == BadDrawable) ||
484             (err->request_code == X_ConfigureWindow   && err->error_code == BadMatch   ) ||
485             (err->request_code == X_GrabButton        && err->error_code == BadAccess  ) ||
486             (err->request_code == X_GrabKey           && err->error_code == BadAccess  ) ||
487             (err->request_code == X_CopyArea          && err->error_code == BadDrawable))
488                 return 0;
489         if (err->request_code == X_ChangeWindowAttributes && err->error_code == BadAccess)
490                 error("Another window manager is already running");
491         return xerrorxlib(dpy, err);
492 }
493
494 static int xnoerror(Display *dpy, XErrorEvent *err)
495 {
496         return 0;
497 }
498
499
500 /********************
501  * System functions *
502  ********************/
503 void sys_move(win_t *win, int x, int y, int w, int h)
504 {
505         //printf("sys_move: %p - %d,%d  %dx%d\n", win, x, y, w, h);
506         int b = 2*border;
507         win->x = x; win->y = y;
508         win->w = MAX(w,1+b); win->h = MAX(h,1+b);
509         w      = MAX(w-b,1); h      = MAX(h-b,1);
510         XMoveResizeWindow(win->sys->dpy, win->sys->xid, x, y, w, h);
511
512         /* Flush events, so moving window doesn't cause re-focus
513          * There's probably a better way to do this */
514         XEvent xe;
515         XSync(win->sys->dpy, False);
516         while (XCheckMaskEvent(win->sys->dpy, EnterWindowMask|LeaveWindowMask, &xe))
517                 printf("Skipping enter/leave event\n");
518 }
519
520 void sys_raise(win_t *win)
521 {
522         //printf("sys_raise: %p\n", win);
523         XRaiseWindow(win->sys->dpy, win->sys->xid);
524         for (list_t *cur = struts; cur; cur = cur->next)
525                 XRaiseWindow(((win_t*)cur->data)->sys->dpy,
526                              ((win_t*)cur->data)->sys->xid);
527 }
528
529 void sys_focus(win_t *win)
530 {
531         printf("sys_focus: %p\n", win);
532
533         /* Set actual focus */
534         XSetInputFocus(win->sys->dpy, win->sys->xid,
535                         RevertToPointerRoot, CurrentTime);
536         win_msg(win, WM_FOCUS);
537
538         /* Set border on focused window */
539         static win_t *last = NULL;
540         if (last)
541                 XSetWindowBorder(last->sys->dpy, last->sys->xid, colors[CLR_UNFOCUS]);
542         XSync(win->sys->dpy, False);
543         XSetWindowBorder(win->sys->dpy, win->sys->xid, colors[CLR_FOCUS]);
544         last = win;
545 }
546
547 void sys_show(win_t *win, state_t state)
548 {
549         switch (state) {
550         case ST_HIDE:
551                 printf("sys_show: hide %p\n", win);
552                 XUnmapWindow(win->sys->dpy, win->sys->xid);
553                 break;
554         case ST_SHOW:
555                 printf("sys_show: show %p\n", win);
556                 if (win->state == ST_FULL)
557                         sys_move(win, win->x, win->y, win->w, win->h);
558                 XSetWindowBorderWidth(win->sys->dpy, win->sys->xid, border);
559                 XMapWindow(win->sys->dpy, win->sys->xid);
560                 XSync(win->sys->dpy, False);
561                 break;
562         case ST_MAX:
563                 printf("sys_show: max %p\n", win);
564                 XMapWindow(win->sys->dpy, win->sys->xid);
565                 break;
566         case ST_FULL:
567                 printf("sys_show: full %p\n", win);
568                 win_t *screen = NULL;
569                 for (list_t *cur = screens; cur; cur = cur->next) {
570                         screen = cur->data;
571                         if (win->x >= screen->x && win->x <= screen->x+screen->w &&
572                             win->y >= screen->y && win->y <= screen->y+screen->h)
573                                 break;
574                 }
575                 XSetWindowBorderWidth(win->sys->dpy, win->sys->xid, 0);
576                 XMapWindow(win->sys->dpy, win->sys->xid);
577                 XMoveResizeWindow(win->sys->dpy, win->sys->xid,
578                         screen->x - screen->sys->strut.left,
579                         screen->y - screen->sys->strut.top,
580                         screen->w + screen->sys->strut.left + screen->sys->strut.right,
581                         screen->h + screen->sys->strut.top  + screen->sys->strut.bottom);
582                 XRaiseWindow(win->sys->dpy, win->sys->xid);
583                 break;
584         case ST_SHADE:
585                 printf("sys_show: shade %p\n", win);
586                 XMapWindow(win->sys->dpy, win->sys->xid);
587                 break;
588         case ST_ICON:
589                 printf("sys_show: icon %p\n", win);
590                 break;
591         case ST_CLOSE:
592                 printf("sys_show: close %p\n", win);
593                 if (!win_msg(win, WM_DELETE)) {
594                         XGrabServer(win->sys->dpy);
595                         XSetErrorHandler(xnoerror);
596                         XSetCloseDownMode(win->sys->dpy, DestroyAll);
597                         XKillClient(win->sys->dpy, win->sys->xid);
598                         XSync(win->sys->dpy, False);
599                         XSetErrorHandler(xerror);
600                         XUngrabServer(win->sys->dpy);
601                 }
602                 XDestroyWindow(win->sys->dpy, win->sys->xid);
603                 break;
604         }
605         win->state = state;
606 }
607
608 void sys_watch(win_t *win, event_t ev, mod_t mod)
609 {
610         //printf("sys_watch: %p - %x %hhx\n", win, ev, mod);
611         XWindowAttributes attr;
612         XGetWindowAttributes(win->sys->dpy, win->sys->xid, &attr);
613         long mask = attr.your_event_mask;
614         if (EV_MOUSE0 <= ev && ev <= EV_MOUSE7)
615                 XGrabButton(win->sys->dpy, ev2xb(ev), mod2x(mod), win->sys->xid, False,
616                                 mod.up ? ButtonReleaseMask : ButtonPressMask,
617                                 GrabModeSync, GrabModeAsync, None, None);
618         else if (ev == EV_ENTER)
619                 XSelectInput(win->sys->dpy, win->sys->xid, EnterWindowMask|mask);
620         else if (ev == EV_LEAVE)
621                 XSelectInput(win->sys->dpy, win->sys->xid, LeaveWindowMask|mask);
622         else if (ev == EV_FOCUS || ev == EV_UNFOCUS)
623                 XSelectInput(win->sys->dpy, win->sys->xid, FocusChangeMask|mask);
624         else
625                 XGrabKey(win->sys->dpy, XKeysymToKeycode(win->sys->dpy, ev2xk(ev)),
626                                 mod2x(mod), win->sys->xid, True, GrabModeAsync, GrabModeAsync);
627 }
628
629 void sys_unwatch(win_t *win, event_t ev, mod_t mod)
630 {
631         if (EV_MOUSE0 <= ev && ev <= EV_MOUSE7)
632                 XUngrabButton(win->sys->dpy, ev2xb(ev), mod2x(mod), win->sys->xid);
633 }
634
635 list_t *sys_info(win_t *win)
636 {
637         /* Use global copy of screens so we can add struts */
638         if (screens == NULL) {
639                 /* Add Xinerama screens */
640                 int n = 0;
641                 XineramaScreenInfo *info = NULL;
642                 if (XineramaIsActive(win->sys->dpy))
643                         info = XineramaQueryScreens(win->sys->dpy, &n);
644                 for (int i = 0; i < n; i++) {
645                         win_t *screen = new0(win_t);
646                         screen->x = info[i].x_org;
647                         screen->y = info[i].y_org;
648                         screen->w = info[i].width;
649                         screen->h = info[i].height;
650                         screen->sys = new0(win_sys_t);
651                         screens = list_append(screens, screen);
652                 }
653         }
654         if (screens == NULL) {
655                 /* No xinerama support */
656                 win_t *screen = new0(win_t);
657                 *screen = *win;
658                 screens = list_insert(NULL, screen);
659         }
660         return screens;
661 }
662
663 win_t *sys_init(void)
664 {
665         Display *dpy;
666         Window   xid;
667
668         /* Load configuration */
669         border     = conf_get_int("main.border",     border);
670         no_capture = conf_get_int("main.no-capture", no_capture);
671
672         /* Open the display */
673         if (!(dpy = XOpenDisplay(NULL)))
674                 error("Unable to get display");
675         if (!(xid = DefaultRootWindow(dpy)))
676                 error("Unable to get root window");
677
678         /* Setup X11 data */
679         atoms[WM_PROTO]    = XInternAtom(dpy, "WM_PROTOCOLS",               False);
680         atoms[WM_FOCUS]    = XInternAtom(dpy, "WM_TAKE_FOCUS",              False);
681         atoms[WM_DELETE]   = XInternAtom(dpy, "WM_DELETE_WINDOW",           False);
682         atoms[NET_STATE]   = XInternAtom(dpy, "_NET_WM_STATE",              False);
683         atoms[NET_FULL]    = XInternAtom(dpy, "_NET_WM_STATE_FULLSCREEN",   False);
684         atoms[NET_STRUT]   = XInternAtom(dpy, "_NET_WM_STRUT",              False);
685         atoms[NET_TYPE]    = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE",        False);
686         atoms[NET_DIALOG]  = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE_DIALOG", False);
687
688         colors[CLR_FOCUS]   = get_color(dpy, "#a0a0ff");
689         colors[CLR_UNFOCUS] = get_color(dpy, "#101066");
690         colors[CLR_URGENT]  = get_color(dpy, "#ff0000");
691         //printf("colors = #%06lx #%06lx #%06lx\n", colors[0], colors[1], colors[2]);
692
693         /* Select window management events */
694         XSelectInput(dpy, xid, SubstructureRedirectMask|SubstructureNotifyMask);
695         xerrorxlib = XSetErrorHandler(xerror);
696
697         return win_find(dpy, xid, 1);
698 }
699
700 void sys_run(win_t *root)
701 {
702         /* Add each initial window */
703         if (!no_capture) {
704                 unsigned int nkids;
705                 Window par, xid, *kids = NULL;
706                 if (XQueryTree(root->sys->dpy, root->sys->xid,
707                                         &par, &xid, &kids, &nkids)) {
708                         for(int i = 0; i < nkids; i++) {
709                                 win_t *win = win_find(root->sys->dpy, kids[i], 1);
710                                 if (win && win_viewable(win) && !strut_add(root,win))
711                                         wm_insert(win);
712                         }
713                         XFree(kids);
714                 }
715                 wm_update(); // For struts
716         }
717
718         /* Main loop */
719         running = 1;
720         while (running)
721         {
722                 XEvent xe;
723                 XNextEvent(root->sys->dpy, &xe);
724                 process_event(xe.type, &xe, root);
725         }
726 }
727
728 void sys_exit(void)
729 {
730         running = 0;
731 }
732
733 void sys_free(win_t *root)
734 {
735         XCloseDisplay(root->sys->dpy);
736         while (screens) {
737                 win_free(screens->data);
738                 screens = list_remove(screens, screens, 0);
739         }
740         tdestroy(cache, (void(*)(void*))win_free);
741 }