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