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