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