]> Pileus Git - wmpus/blob - sys-x11.c
2079ca5679c20f520284063601d4455dc7cbc727
[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                         wm_handle_state(win, win->state, ST_SHOW);
468                         win->state = ST_SHOW;
469                 }
470                 sys_show(win, win->state);
471         }
472         else if (type == ClientMessage) {
473                 XClientMessageEvent *cme = &xe->xclient;
474                 printf("client_msg: %lx - %ld %ld,%ld,%ld,%ld,%ld\n",
475                                 cme->window, cme->message_type,
476                                 cme->data.l[0], cme->data.l[1], cme->data.l[2],
477                                 cme->data.l[3], cme->data.l[4]);
478                 if ((win = win_find(dpy,cme->window,0))     &&
479                     (cme->message_type == atoms[NET_STATE]) &&
480                     (cme->data.l[1] == atoms[NET_FULL] ||
481                      cme->data.l[2] == atoms[NET_FULL])) {
482                         state_t next = (cme->data.l[0] == 1 || /* _NET_WM_STATE_ADD    */
483                                        (cme->data.l[0] == 2 && /* _NET_WM_STATE_TOGGLE */
484                                         win->state != ST_FULL)) ? ST_FULL : ST_SHOW;
485                         printf("client_msg: fullscreen %x -> %x", win->state, next);
486                         wm_handle_state(win, win->state, next);
487                         sys_show(win, next);
488                 }
489         }
490         else if (type == PropertyNotify) {
491                 printf("prop: %lx - %d\n", xe->xproperty.window, xe->xproperty.state);
492         }
493         else {
494                 printf("unknown event: %d\n", type);
495         }
496 }
497
498 static int xerror(Display *dpy, XErrorEvent *err)
499 {
500         if (err->error_code == BadWindow ||
501             (err->request_code == X_SetInputFocus     && err->error_code == BadMatch   ) ||
502             (err->request_code == X_PolyText8         && err->error_code == BadDrawable) ||
503             (err->request_code == X_PolyFillRectangle && err->error_code == BadDrawable) ||
504             (err->request_code == X_PolySegment       && err->error_code == BadDrawable) ||
505             (err->request_code == X_ConfigureWindow   && err->error_code == BadMatch   ) ||
506             (err->request_code == X_GrabButton        && err->error_code == BadAccess  ) ||
507             (err->request_code == X_GrabKey           && err->error_code == BadAccess  ) ||
508             (err->request_code == X_CopyArea          && err->error_code == BadDrawable))
509                 return 0;
510         if (err->request_code == X_ChangeWindowAttributes && err->error_code == BadAccess)
511                 error("Another window manager is already running");
512         return xerrorxlib(dpy, err);
513 }
514
515 static int xnoerror(Display *dpy, XErrorEvent *err)
516 {
517         return 0;
518 }
519
520
521 /********************
522  * System functions *
523  ********************/
524 void sys_move(win_t *win, int x, int y, int w, int h)
525 {
526         //printf("sys_move: %p - %d,%d  %dx%d\n", win, x, y, w, h);
527         int b = 2*border;
528         win->x = x; win->y = y;
529         win->w = MAX(w,1+b); win->h = MAX(h,1+b);
530         w      = MAX(w-b,1); h      = MAX(h-b,1);
531         XMoveResizeWindow(win->sys->dpy, win->sys->xid, x, y, w, h);
532
533         /* Flush events, so moving window doesn't cause re-focus
534          * There's probably a better way to do this */
535         XEvent xe;
536         XSync(win->sys->dpy, False);
537         while (XCheckMaskEvent(win->sys->dpy, EnterWindowMask|LeaveWindowMask, &xe))
538                 printf("Skipping enter/leave event\n");
539 }
540
541 void sys_raise(win_t *win)
542 {
543         //printf("sys_raise: %p\n", win);
544         XRaiseWindow(win->sys->dpy, win->sys->xid);
545         for (list_t *cur = struts; cur; cur = cur->next)
546                 XRaiseWindow(((win_t*)cur->data)->sys->dpy,
547                              ((win_t*)cur->data)->sys->xid);
548 }
549
550 void sys_focus(win_t *win)
551 {
552         //printf("sys_focus: %p\n", win);
553
554         /* Set actual focus */
555         XSetInputFocus(win->sys->dpy, win->sys->xid,
556                         RevertToPointerRoot, CurrentTime);
557         win_msg(win, WM_FOCUS);
558
559         /* Set border on focused window */
560         static win_t *last = NULL;
561         if (last)
562                 XSetWindowBorder(last->sys->dpy, last->sys->xid, colors[CLR_UNFOCUS]);
563         XSync(win->sys->dpy, False);
564         XSetWindowBorder(win->sys->dpy, win->sys->xid, colors[CLR_FOCUS]);
565         last = win;
566 }
567
568 void sys_show(win_t *win, state_t state)
569 {
570         switch (state) {
571         case ST_HIDE:
572                 printf("sys_show: hide %p\n", win);
573                 XUnmapWindow(win->sys->dpy, win->sys->xid);
574                 break;
575         case ST_SHOW:
576                 printf("sys_show: show %p\n", win);
577                 if (win->state == ST_FULL)
578                         sys_move(win, win->x, win->y, win->w, win->h);
579                 XSetWindowBorderWidth(win->sys->dpy, win->sys->xid, border);
580                 XMapWindow(win->sys->dpy, win->sys->xid);
581                 XSync(win->sys->dpy, False);
582                 break;
583         case ST_MAX:
584                 printf("sys_show: max %p\n", win);
585                 XMapWindow(win->sys->dpy, win->sys->xid);
586                 break;
587         case ST_FULL:
588                 printf("sys_show: full %p\n", win);
589                 win_t *screen = NULL;
590                 for (list_t *cur = screens; cur; cur = cur->next) {
591                         screen = cur->data;
592                         if (win->x >= screen->x && win->x <= screen->x+screen->w &&
593                             win->y >= screen->y && win->y <= screen->y+screen->h)
594                                 break;
595                 }
596                 XSetWindowBorderWidth(win->sys->dpy, win->sys->xid, 0);
597                 XMapWindow(win->sys->dpy, win->sys->xid);
598                 XConfigureWindow(win->sys->dpy, win->sys->xid,
599                         CWX|CWY|CWWidth|CWHeight, &(XWindowChanges) {
600                                 .x      = win->x,
601                                 .y      = win->y,
602                                 .width  = win->w,
603                                 .height = win->h,
604                 });
605                 XMoveResizeWindow(win->sys->dpy, win->sys->xid,
606                         screen->x - screen->sys->strut.left,
607                         screen->y - screen->sys->strut.top,
608                         screen->w + screen->sys->strut.left + screen->sys->strut.right,
609                         screen->h + screen->sys->strut.top  + screen->sys->strut.bottom);
610                 XRaiseWindow(win->sys->dpy, win->sys->xid);
611                 break;
612         case ST_SHADE:
613                 printf("sys_show: shade %p\n", win);
614                 XConfigureWindow(win->sys->dpy, win->sys->xid, CWHeight,
615                                 &(XWindowChanges){ .height = stack });
616                 XMapWindow(win->sys->dpy, win->sys->xid);
617                 break;
618         case ST_ICON:
619                 printf("sys_show: icon %p\n", win);
620                 break;
621         case ST_CLOSE:
622                 printf("sys_show: close %p\n", win);
623                 if (!win_msg(win, WM_DELETE)) {
624                         XGrabServer(win->sys->dpy);
625                         XSetErrorHandler(xnoerror);
626                         XSetCloseDownMode(win->sys->dpy, DestroyAll);
627                         XKillClient(win->sys->dpy, win->sys->xid);
628                         XSync(win->sys->dpy, False);
629                         XSetErrorHandler(xerror);
630                         XUngrabServer(win->sys->dpy);
631                 }
632                 XDestroyWindow(win->sys->dpy, win->sys->xid);
633                 break;
634         }
635         win->state = state;
636 }
637
638 void sys_watch(win_t *win, event_t ev, mod_t mod)
639 {
640         //printf("sys_watch: %p - %x %hhx\n", win, ev, mod);
641         XWindowAttributes attr;
642         XGetWindowAttributes(win->sys->dpy, win->sys->xid, &attr);
643         long mask = attr.your_event_mask;
644         if (EV_MOUSE0 <= ev && ev <= EV_MOUSE7)
645                 XGrabButton(win->sys->dpy, ev2xb(ev), mod2x(mod), win->sys->xid, False,
646                                 mod.up ? ButtonReleaseMask : ButtonPressMask,
647                                 GrabModeSync, GrabModeAsync, None, None);
648         else if (ev == EV_ENTER)
649                 XSelectInput(win->sys->dpy, win->sys->xid, EnterWindowMask|mask);
650         else if (ev == EV_LEAVE)
651                 XSelectInput(win->sys->dpy, win->sys->xid, LeaveWindowMask|mask);
652         else if (ev == EV_FOCUS || ev == EV_UNFOCUS)
653                 XSelectInput(win->sys->dpy, win->sys->xid, FocusChangeMask|mask);
654         else
655                 XGrabKey(win->sys->dpy, XKeysymToKeycode(win->sys->dpy, ev2xk(ev)),
656                                 mod2x(mod), win->sys->xid, True, GrabModeAsync, GrabModeAsync);
657 }
658
659 void sys_unwatch(win_t *win, event_t ev, mod_t mod)
660 {
661         if (EV_MOUSE0 <= ev && ev <= EV_MOUSE7)
662                 XUngrabButton(win->sys->dpy, ev2xb(ev), mod2x(mod), win->sys->xid);
663 }
664
665 list_t *sys_info(win_t *win)
666 {
667         /* Use global copy of screens so we can add struts */
668         if (screens == NULL) {
669                 /* Add Xinerama screens */
670                 int n = 0;
671                 XineramaScreenInfo *info = NULL;
672                 if (XineramaIsActive(win->sys->dpy))
673                         info = XineramaQueryScreens(win->sys->dpy, &n);
674                 for (int i = 0; i < n; i++) {
675                         win_t *screen = new0(win_t);
676                         screen->x = info[i].x_org;
677                         screen->y = info[i].y_org;
678                         screen->w = info[i].width;
679                         screen->h = info[i].height;
680                         screen->sys = new0(win_sys_t);
681                         screens = list_append(screens, screen);
682                 }
683         }
684         if (screens == NULL) {
685                 /* No xinerama support */
686                 win_t *screen = new0(win_t);
687                 *screen = *win;
688                 screens = list_insert(NULL, screen);
689         }
690         return screens;
691 }
692
693 win_t *sys_init(void)
694 {
695         Display *dpy;
696         Window   xid;
697
698         /* Load configuration */
699         stack      = conf_get_int("main.stack",      stack);
700         border     = conf_get_int("main.border",     border);
701         no_capture = conf_get_int("main.no-capture", no_capture);
702
703         /* Open the display */
704         if (!(dpy = XOpenDisplay(NULL)))
705                 error("Unable to get display");
706         if (!(xid = DefaultRootWindow(dpy)))
707                 error("Unable to get root window");
708
709         /* Setup X11 data */
710         atoms[WM_PROTO]    = XInternAtom(dpy, "WM_PROTOCOLS",               False);
711         atoms[WM_FOCUS]    = XInternAtom(dpy, "WM_TAKE_FOCUS",              False);
712         atoms[WM_DELETE]   = XInternAtom(dpy, "WM_DELETE_WINDOW",           False);
713         atoms[NET_STATE]   = XInternAtom(dpy, "_NET_WM_STATE",              False);
714         atoms[NET_FULL]    = XInternAtom(dpy, "_NET_WM_STATE_FULLSCREEN",   False);
715         atoms[NET_STRUT]   = XInternAtom(dpy, "_NET_WM_STRUT",              False);
716         atoms[NET_TYPE]    = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE",        False);
717         atoms[NET_DIALOG]  = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE_DIALOG", False);
718
719         colors[CLR_FOCUS]   = get_color(dpy, "#a0a0ff");
720         colors[CLR_UNFOCUS] = get_color(dpy, "#101066");
721         colors[CLR_URGENT]  = get_color(dpy, "#ff0000");
722         //printf("colors = #%06lx #%06lx #%06lx\n", colors[0], colors[1], colors[2]);
723
724         /* Select window management events */
725         XSelectInput(dpy, xid, SubstructureRedirectMask|SubstructureNotifyMask);
726         xerrorxlib = XSetErrorHandler(xerror);
727
728         return root = win_find(dpy, xid, 1);
729 }
730
731 void sys_run(win_t *root)
732 {
733         /* Add each initial window */
734         if (!no_capture) {
735                 unsigned int nkids;
736                 Window par, xid, *kids = NULL;
737                 if (XQueryTree(root->sys->dpy, root->sys->xid,
738                                         &par, &xid, &kids, &nkids)) {
739                         for(int i = 0; i < nkids; i++)
740                                 if (win_viewable(root->sys->dpy, kids[i]))
741                                         win_find(root->sys->dpy, kids[i], 1);
742                         XFree(kids);
743                 }
744         }
745
746         /* Main loop */
747         running = 1;
748         while (running)
749         {
750                 XEvent xe;
751                 XNextEvent(root->sys->dpy, &xe);
752                 process_event(xe.type, &xe, root);
753         }
754 }
755
756 void sys_exit(void)
757 {
758         running = 0;
759 }
760
761 void sys_free(win_t *root)
762 {
763         XCloseDisplay(root->sys->dpy);
764         while (screens) {
765                 win_free(screens->data);
766                 screens = list_remove(screens, screens, 0);
767         }
768         tdestroy(cache, (void(*)(void*))win_free);
769 }