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