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