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