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