]> Pileus Git - wmpus/blob - sys-x11.c
1e35845db4403b101442366696f394f4dbfec301
[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
251         printf("win_new: win=%p x11=(%p,%d) state=%x pos=(%d,%d %dx%d) type=%s\n",
252                         win, dpy, (int)xid, win->state,
253                         win->x, win->y, win->w, win->h,
254                         win->type == TYPE_NORMAL  ? "normal"  :
255                         win->type == TYPE_DIALOG  ? "dialog"  :
256                         win->type == TYPE_TOOLBAR ? "toolbar" : "unknown");
257
258         if (root)
259                 wm_insert(win);
260
261         return win;
262 }
263
264 static int win_cmp(const void *_a, const void *_b)
265 {
266         const win_t *a = _a, *b = _b;
267         if (a->sys->dpy < b->sys->dpy) return -1;
268         if (a->sys->dpy > b->sys->dpy) return  1;
269         if (a->sys->xid < b->sys->xid) return -1;
270         if (a->sys->xid > b->sys->xid) return  1;
271         return 0;
272 }
273
274 static win_t *win_find(Display *dpy, Window xid, int create)
275 {
276         if (!dpy || !xid)
277                 return NULL;
278         //printf("win_find: %p, %d\n", dpy, (int)xid);
279         win_sys_t sys = {.dpy=dpy, .xid=xid};
280         win_t     tmp = {.sys=&sys};
281         win_t **old = NULL, *new = NULL;
282         if ((old = tfind(&tmp, &cache, win_cmp)))
283                 return *old;
284         if (create && (new = win_new(dpy,xid)))
285                 tsearch(new, &cache, win_cmp);
286         return new;
287 }
288
289 static void win_free(win_t *win)
290 {
291         free(win->sys);
292         free(win);
293 }
294
295 static void win_remove(win_t *win)
296 {
297         if (win != root) {
298                 strut_del(root, win);
299                 wm_remove(win);
300         }
301         tdelete(win, &cache, win_cmp);
302         win_free(win);
303 }
304
305 static int win_viewable(Display *dpy, Window xid)
306 {
307         XWindowAttributes attr;
308         if (XGetWindowAttributes(dpy, xid, &attr))
309                 return attr.map_state == IsViewable;
310         else
311                 return True;
312 }
313
314 static int win_msg(win_t *win, atom_t msg)
315 {
316         int n, found = 0;
317         Atom *protos;
318         if (!XGetWMProtocols(win->sys->dpy, win->sys->xid, &protos, &n))
319                 return 0;
320
321         while (!found && n--)
322                 found = protos[n] == atoms[msg];
323         XFree(protos);
324         if (!found)
325                 return 0;
326
327         XSendEvent(win->sys->dpy, win->sys->xid, False, NoEventMask, &(XEvent){
328                 .type                 = ClientMessage,
329                 .xclient.window       = win->sys->xid,
330                 .xclient.message_type = atoms[WM_PROTO],
331                 .xclient.format       = 32,
332                 .xclient.data.l[0]    = atoms[msg],
333                 .xclient.data.l[1]    = CurrentTime,
334         });
335         return 1;
336 }
337
338 static Atom win_prop(win_t *win, atom_t prop)
339 {
340         int format;
341         unsigned long nitems, bytes;
342         unsigned char *buf = NULL;
343         Atom atom, type = XA_ATOM;
344         if (XGetWindowProperty(win->sys->dpy, win->sys->xid, atoms[prop],
345                         0L, sizeof(Atom), False, type, &type, &format, &nitems, &bytes, &buf) || !buf)
346                 return 0;
347         atom = *(Atom *)buf;
348         XFree(buf);
349         return atom;
350 }
351
352 /* Drawing functions */
353 static unsigned long get_color(Display *dpy, const char *name)
354 {
355         XColor color;
356         int screen = DefaultScreen(dpy);
357         Colormap cmap = DefaultColormap(dpy, screen);
358         XAllocNamedColor(dpy, cmap, name, &color, &color);
359         return color.pixel;
360 }
361
362 /* Callbacks */
363 static void process_event(int type, XEvent *xe, win_t *root)
364 {
365         Display  *dpy = root->sys->dpy;
366         win_t *win = NULL;
367         //printf("event: %d\n", type);
368
369         /* Common data for all these events ... */
370         ptr_t ptr = {}; mod_t mod = {};
371         if (type == KeyPress    || type == KeyRelease    ||
372             type == ButtonPress || type == ButtonRelease ||
373             type == MotionNotify) {
374                 Window xid = getfocus(root, xe);
375                 if (!(win = win_find(dpy,xid,0)))
376                         return;
377                 //printf("button-press %p\n", win);
378                 ptr = x2ptr(xe);
379                 mod = x2mod(xe->xkey.state, type==KeyRelease||type==ButtonRelease);
380         }
381
382         /* Split based on event */
383         if (type == KeyPress) {
384                 while (XCheckTypedEvent(dpy, KeyPress, xe));
385                 KeySym sym = XLookupKeysym(&xe->xkey, 0);
386                 //printf("got xe %c %hhx\n", xk2ev(sym), mod2int(mod));
387                 wm_handle_event(win, xk2ev(sym), mod, ptr);
388         }
389         else if (type == KeyRelease) {
390                 //printf("release: %lx\n", xe->xkey.window);
391         }
392         else if (type == ButtonPress) {
393                 if (wm_handle_event(win, xb2ev(xe->xbutton.button), mod, ptr)) {
394                         //printf("grab pointer\n");
395                         XGrabPointer(dpy, xe->xbutton.root, True, PointerMotionMask|ButtonReleaseMask,
396                                         GrabModeAsync, GrabModeAsync, None, None, CurrentTime);
397                 } else {
398                         //printf("allow events\n");
399                         XAllowEvents(win->sys->dpy, ReplayPointer, xe->xbutton.time);
400                 }
401         }
402         else if (type == ButtonRelease) {
403                 XUngrabPointer(dpy, CurrentTime);
404                 wm_handle_event(win, xb2ev(xe->xbutton.button), mod, ptr);
405         }
406         else if (type == MotionNotify) {
407                 while (XCheckTypedEvent(dpy, MotionNotify, xe));
408                 wm_handle_ptr(win, ptr);
409         }
410         else if (type == EnterNotify || type == LeaveNotify) {
411                 printf("%s: %lx\n", type==EnterNotify?"enter":"leave",
412                                 xe->xcrossing.window);
413                 event_t ev = type == EnterNotify ? EV_ENTER : EV_LEAVE;
414                 if ((win = win_find(dpy,xe->xcrossing.window,0)))
415                         wm_handle_event(win, ev, MOD(), PTR());
416         }
417         else if (type == FocusIn || type == FocusOut) {
418                 //printf("focus: %lx\n", xe->xfocus.window);
419                 event_t ev = type == FocusIn ? EV_FOCUS : EV_UNFOCUS;
420                 if ((win = win_find(dpy,xe->xfocus.window,0)))
421                         wm_handle_event(win, ev, MOD(), PTR());
422         }
423         else if (type == ConfigureNotify) {
424                 //printf("configure: %lx\n", xe->xconfigure.window);
425         }
426         else if (type == MapNotify) {
427                 printf("map: %lx\n", xe->xmap.window);
428         }
429         else if (type == UnmapNotify) {
430                 if ((win = win_find(dpy,xe->xunmap.window,0)) &&
431                      win->state != ST_HIDE) {
432                         printf("unmap: %lx\n", xe->xunmap.window);
433                         wm_handle_state(win, win->state, ST_HIDE);
434                         win->state = ST_HIDE;
435                 }
436         }
437         else if (type == DestroyNotify) {
438                 printf("destroy: %lx\n", xe->xdestroywindow.window);
439                 if ((win = win_find(dpy,xe->xdestroywindow.window,0)))
440                         win_remove(win);
441         }
442         else if (type == ConfigureRequest) {
443                 XConfigureRequestEvent *cre = &xe->xconfigurerequest;
444                 printf("configure_req: %lx - (0x%lx) %dx%d @ %d,%d\n",
445                                 cre->window, cre->value_mask,
446                                 cre->height, cre->width, cre->x, cre->y);
447                 if ((win = win_find(dpy,xe->xconfigurerequest.window,1))) {
448                         XSendEvent(dpy, cre->window, False, StructureNotifyMask, &(XEvent){
449                                 .xconfigure.type              = ConfigureNotify,
450                                 .xconfigure.display           = win->sys->dpy,
451                                 .xconfigure.event             = win->sys->xid,
452                                 .xconfigure.window            = win->sys->xid,
453                                 .xconfigure.x                 = win->x,
454                                 .xconfigure.y                 = win->y,
455                                 .xconfigure.width             = win->w,
456                                 .xconfigure.height            = win->h,
457                                 .xconfigure.border_width      = border,
458                         });
459                         XSync(win->sys->dpy, False);
460                 }
461         }
462         else if (type == MapRequest) {
463                 printf("map_req: %lx\n", xe->xmaprequest.window);
464                 win = win_find(dpy,xe->xmaprequest.window,1);
465                 // fixme, for hide -> max, etc
466                 if (win->state == ST_HIDE)
467                         win->state = ST_SHOW;
468                 sys_show(win, win->state);
469         }
470         else if (type == ClientMessage) {
471                 XClientMessageEvent *cme = &xe->xclient;
472                 printf("client_msg: %lx - %ld %ld,%ld,%ld,%ld,%ld\n",
473                                 cme->window, cme->message_type,
474                                 cme->data.l[0], cme->data.l[1], cme->data.l[2],
475                                 cme->data.l[3], cme->data.l[4]);
476                 if ((win = win_find(dpy,cme->window,0))     &&
477                     (cme->message_type == atoms[NET_STATE]) &&
478                     (cme->data.l[1] == atoms[NET_FULL] ||
479                      cme->data.l[2] == atoms[NET_FULL])) {
480                         state_t next = (cme->data.l[0] == 1 || /* _NET_WM_STATE_ADD    */
481                                        (cme->data.l[0] == 2 && /* _NET_WM_STATE_TOGGLE */
482                                         win->state != ST_FULL)) ? ST_FULL : ST_SHOW;
483                         printf("client_msg: fullscreen %x -> %x", win->state, next);
484                         wm_handle_state(win, win->state, next);
485                         sys_show(win, next);
486                 }
487         }
488         else if (type == PropertyNotify) {
489                 printf("prop: %lx - %d\n", xe->xproperty.window, xe->xproperty.state);
490         }
491         else {
492                 printf("unknown event: %d\n", type);
493         }
494 }
495
496 static int xerror(Display *dpy, XErrorEvent *err)
497 {
498         if (err->error_code == BadWindow ||
499             (err->request_code == X_SetInputFocus     && err->error_code == BadMatch   ) ||
500             (err->request_code == X_PolyText8         && err->error_code == BadDrawable) ||
501             (err->request_code == X_PolyFillRectangle && err->error_code == BadDrawable) ||
502             (err->request_code == X_PolySegment       && err->error_code == BadDrawable) ||
503             (err->request_code == X_ConfigureWindow   && err->error_code == BadMatch   ) ||
504             (err->request_code == X_GrabButton        && err->error_code == BadAccess  ) ||
505             (err->request_code == X_GrabKey           && err->error_code == BadAccess  ) ||
506             (err->request_code == X_CopyArea          && err->error_code == BadDrawable))
507                 return 0;
508         if (err->request_code == X_ChangeWindowAttributes && err->error_code == BadAccess)
509                 error("Another window manager is already running");
510         return xerrorxlib(dpy, err);
511 }
512
513 static int xnoerror(Display *dpy, XErrorEvent *err)
514 {
515         return 0;
516 }
517
518
519 /********************
520  * System functions *
521  ********************/
522 void sys_move(win_t *win, int x, int y, int w, int h)
523 {
524         //printf("sys_move: %p - %d,%d  %dx%d\n", win, x, y, w, h);
525         int b = 2*border;
526         win->x = x; win->y = y;
527         win->w = MAX(w,1+b); win->h = MAX(h,1+b);
528         w      = MAX(w-b,1); h      = MAX(h-b,1);
529         XMoveResizeWindow(win->sys->dpy, win->sys->xid, x, y, w, h);
530
531         /* Flush events, so moving window doesn't cause re-focus
532          * There's probably a better way to do this */
533         XEvent xe;
534         XSync(win->sys->dpy, False);
535         while (XCheckMaskEvent(win->sys->dpy, EnterWindowMask|LeaveWindowMask, &xe))
536                 printf("Skipping enter/leave event\n");
537 }
538
539 void sys_raise(win_t *win)
540 {
541         //printf("sys_raise: %p\n", win);
542         XRaiseWindow(win->sys->dpy, win->sys->xid);
543         for (list_t *cur = struts; cur; cur = cur->next)
544                 XRaiseWindow(((win_t*)cur->data)->sys->dpy,
545                              ((win_t*)cur->data)->sys->xid);
546 }
547
548 void sys_focus(win_t *win)
549 {
550         //printf("sys_focus: %p\n", win);
551
552         /* Set actual focus */
553         XSetInputFocus(win->sys->dpy, win->sys->xid,
554                         RevertToPointerRoot, CurrentTime);
555         win_msg(win, WM_FOCUS);
556
557         /* Set border on focused window */
558         static win_t *last = NULL;
559         if (last)
560                 XSetWindowBorder(last->sys->dpy, last->sys->xid, colors[CLR_UNFOCUS]);
561         XSync(win->sys->dpy, False);
562         XSetWindowBorder(win->sys->dpy, win->sys->xid, colors[CLR_FOCUS]);
563         last = win;
564 }
565
566 void sys_show(win_t *win, state_t state)
567 {
568         switch (state) {
569         case ST_HIDE:
570                 printf("sys_show: hide %p\n", win);
571                 XUnmapWindow(win->sys->dpy, win->sys->xid);
572                 break;
573         case ST_SHOW:
574                 printf("sys_show: show %p\n", win);
575                 if (win->state == ST_FULL)
576                         sys_move(win, win->x, win->y, win->w, win->h);
577                 XSetWindowBorderWidth(win->sys->dpy, win->sys->xid, border);
578                 XMapWindow(win->sys->dpy, win->sys->xid);
579                 XSync(win->sys->dpy, False);
580                 break;
581         case ST_MAX:
582                 printf("sys_show: max %p\n", win);
583                 XMapWindow(win->sys->dpy, win->sys->xid);
584                 break;
585         case ST_FULL:
586                 printf("sys_show: full %p\n", win);
587                 win_t *screen = NULL;
588                 for (list_t *cur = screens; cur; cur = cur->next) {
589                         screen = cur->data;
590                         if (win->x >= screen->x && win->x <= screen->x+screen->w &&
591                             win->y >= screen->y && win->y <= screen->y+screen->h)
592                                 break;
593                 }
594                 XSetWindowBorderWidth(win->sys->dpy, win->sys->xid, 0);
595                 XMapWindow(win->sys->dpy, win->sys->xid);
596                 XMoveResizeWindow(win->sys->dpy, win->sys->xid,
597                         screen->x - screen->sys->strut.left,
598                         screen->y - screen->sys->strut.top,
599                         screen->w + screen->sys->strut.left + screen->sys->strut.right,
600                         screen->h + screen->sys->strut.top  + screen->sys->strut.bottom);
601                 XRaiseWindow(win->sys->dpy, win->sys->xid);
602                 break;
603         case ST_SHADE:
604                 printf("sys_show: shade %p\n", win);
605                 XConfigureWindow(win->sys->dpy, win->sys->xid, CWHeight,
606                                 &(XWindowChanges){ .height = stack });
607                 XMapWindow(win->sys->dpy, win->sys->xid);
608                 break;
609         case ST_ICON:
610                 printf("sys_show: icon %p\n", win);
611                 break;
612         case ST_CLOSE:
613                 printf("sys_show: close %p\n", win);
614                 if (!win_msg(win, WM_DELETE)) {
615                         XGrabServer(win->sys->dpy);
616                         XSetErrorHandler(xnoerror);
617                         XSetCloseDownMode(win->sys->dpy, DestroyAll);
618                         XKillClient(win->sys->dpy, win->sys->xid);
619                         XSync(win->sys->dpy, False);
620                         XSetErrorHandler(xerror);
621                         XUngrabServer(win->sys->dpy);
622                 }
623                 XDestroyWindow(win->sys->dpy, win->sys->xid);
624                 break;
625         }
626         win->state = state;
627 }
628
629 void sys_watch(win_t *win, event_t ev, mod_t mod)
630 {
631         //printf("sys_watch: %p - %x %hhx\n", win, ev, mod);
632         XWindowAttributes attr;
633         XGetWindowAttributes(win->sys->dpy, win->sys->xid, &attr);
634         long mask = attr.your_event_mask;
635         if (EV_MOUSE0 <= ev && ev <= EV_MOUSE7)
636                 XGrabButton(win->sys->dpy, ev2xb(ev), mod2x(mod), win->sys->xid, False,
637                                 mod.up ? ButtonReleaseMask : ButtonPressMask,
638                                 GrabModeSync, GrabModeAsync, None, None);
639         else if (ev == EV_ENTER)
640                 XSelectInput(win->sys->dpy, win->sys->xid, EnterWindowMask|mask);
641         else if (ev == EV_LEAVE)
642                 XSelectInput(win->sys->dpy, win->sys->xid, LeaveWindowMask|mask);
643         else if (ev == EV_FOCUS || ev == EV_UNFOCUS)
644                 XSelectInput(win->sys->dpy, win->sys->xid, FocusChangeMask|mask);
645         else
646                 XGrabKey(win->sys->dpy, XKeysymToKeycode(win->sys->dpy, ev2xk(ev)),
647                                 mod2x(mod), win->sys->xid, True, GrabModeAsync, GrabModeAsync);
648 }
649
650 void sys_unwatch(win_t *win, event_t ev, mod_t mod)
651 {
652         if (EV_MOUSE0 <= ev && ev <= EV_MOUSE7)
653                 XUngrabButton(win->sys->dpy, ev2xb(ev), mod2x(mod), win->sys->xid);
654 }
655
656 list_t *sys_info(win_t *win)
657 {
658         /* Use global copy of screens so we can add struts */
659         if (screens == NULL) {
660                 /* Add Xinerama screens */
661                 int n = 0;
662                 XineramaScreenInfo *info = NULL;
663                 if (XineramaIsActive(win->sys->dpy))
664                         info = XineramaQueryScreens(win->sys->dpy, &n);
665                 for (int i = 0; i < n; i++) {
666                         win_t *screen = new0(win_t);
667                         screen->x = info[i].x_org;
668                         screen->y = info[i].y_org;
669                         screen->w = info[i].width;
670                         screen->h = info[i].height;
671                         screen->sys = new0(win_sys_t);
672                         screens = list_append(screens, screen);
673                 }
674         }
675         if (screens == NULL) {
676                 /* No xinerama support */
677                 win_t *screen = new0(win_t);
678                 *screen = *win;
679                 screens = list_insert(NULL, screen);
680         }
681         return screens;
682 }
683
684 win_t *sys_init(void)
685 {
686         Display *dpy;
687         Window   xid;
688
689         /* Load configuration */
690         stack      = conf_get_int("main.stack",      stack);
691         border     = conf_get_int("main.border",     border);
692         no_capture = conf_get_int("main.no-capture", no_capture);
693
694         /* Open the display */
695         if (!(dpy = XOpenDisplay(NULL)))
696                 error("Unable to get display");
697         if (!(xid = DefaultRootWindow(dpy)))
698                 error("Unable to get root window");
699
700         /* Setup X11 data */
701         atoms[WM_PROTO]    = XInternAtom(dpy, "WM_PROTOCOLS",               False);
702         atoms[WM_FOCUS]    = XInternAtom(dpy, "WM_TAKE_FOCUS",              False);
703         atoms[WM_DELETE]   = XInternAtom(dpy, "WM_DELETE_WINDOW",           False);
704         atoms[NET_STATE]   = XInternAtom(dpy, "_NET_WM_STATE",              False);
705         atoms[NET_FULL]    = XInternAtom(dpy, "_NET_WM_STATE_FULLSCREEN",   False);
706         atoms[NET_STRUT]   = XInternAtom(dpy, "_NET_WM_STRUT",              False);
707         atoms[NET_TYPE]    = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE",        False);
708         atoms[NET_DIALOG]  = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE_DIALOG", False);
709
710         colors[CLR_FOCUS]   = get_color(dpy, "#a0a0ff");
711         colors[CLR_UNFOCUS] = get_color(dpy, "#101066");
712         colors[CLR_URGENT]  = get_color(dpy, "#ff0000");
713         //printf("colors = #%06lx #%06lx #%06lx\n", colors[0], colors[1], colors[2]);
714
715         /* Select window management events */
716         XSelectInput(dpy, xid, SubstructureRedirectMask|SubstructureNotifyMask);
717         xerrorxlib = XSetErrorHandler(xerror);
718
719         return root = win_find(dpy, xid, 1);
720 }
721
722 void sys_run(win_t *root)
723 {
724         /* Add each initial window */
725         if (!no_capture) {
726                 unsigned int nkids;
727                 Window par, xid, *kids = NULL;
728                 if (XQueryTree(root->sys->dpy, root->sys->xid,
729                                         &par, &xid, &kids, &nkids)) {
730                         for(int i = 0; i < nkids; i++)
731                                 if (win_viewable(root->sys->dpy, kids[i]))
732                                         win_find(root->sys->dpy, kids[i], 1);
733                         XFree(kids);
734                 }
735         }
736
737         /* Main loop */
738         running = 1;
739         while (running)
740         {
741                 XEvent xe;
742                 XNextEvent(root->sys->dpy, &xe);
743                 process_event(xe.type, &xe, root);
744         }
745 }
746
747 void sys_exit(void)
748 {
749         running = 0;
750 }
751
752 void sys_free(win_t *root)
753 {
754         XCloseDisplay(root->sys->dpy);
755         while (screens) {
756                 win_free(screens->data);
757                 screens = list_remove(screens, screens, 0);
758         }
759         tdestroy(cache, (void(*)(void*))win_free);
760 }