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