]> Pileus Git - wmpus/blob - sys-x11.c
Add fullscreen support
[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 #if 0
213 static int is_fullscreen(win_t *win)
214 {
215         Atom ret_type;
216         int ret_size;
217         unsigned long ret_items, bytes_left;
218         unsigned char *xdata;
219         int status = XGetWindowProperty(win->sys->dpy, win->sys->xid,
220                         atoms[NET_FULL], 0L, 1L, False, XA_ATOM,
221                         &ret_type, &ret_size, &ret_items, &bytes_left, &xdata);
222         printf("is_fullscreen:\n");
223         printf("\t%d\n", status);
224         printf("\t%d\n", ret_size);
225         printf("\t%ld\n", ret_items);
226         printf("\t%p\n", xdata);
227         if (xdata)
228         printf("\t%d\n", xdata[0]);
229         return status == Success && ret_size == 32 && ret_items == 1 &&
230                 xdata[0] == atoms[NET_FULL];
231 }
232 #endif
233
234 /* Window functions */
235 static win_t *win_new(Display *dpy, Window xid)
236 {
237         XWindowAttributes attr;
238         if (XGetWindowAttributes(dpy, xid, &attr))
239                 if (attr.override_redirect)
240                         return NULL;
241         win_t *win    = new0(win_t);
242         win->x        = attr.x;
243         win->y        = attr.y;
244         win->w        = attr.width;
245         win->h        = attr.height;
246         win->sys      = new0(win_sys_t);
247         win->sys->dpy = dpy;
248         win->sys->xid = xid;
249         printf("win_new: %p = %p, %d (%d,%d %dx%d)\n",
250                         win, dpy, (int)xid,
251                         win->x, win->y, win->w, win->h);
252         return win;
253 }
254
255 static int win_cmp(const void *_a, const void *_b)
256 {
257         const win_t *a = _a, *b = _b;
258         if (a->sys->dpy < b->sys->dpy) return -1;
259         if (a->sys->dpy > b->sys->dpy) return  1;
260         if (a->sys->xid < b->sys->xid) return -1;
261         if (a->sys->xid > b->sys->xid) return  1;
262         return 0;
263 }
264
265 static win_t *win_find(Display *dpy, Window xid, int create)
266 {
267         if (!dpy || !xid)
268                 return NULL;
269         //printf("win_find: %p, %d\n", dpy, (int)xid);
270         win_sys_t sys = {.dpy=dpy, .xid=xid};
271         win_t     tmp = {.sys=&sys};
272         win_t **old = NULL, *new = NULL;
273         if ((old = tfind(&tmp, &cache, win_cmp)))
274                 return *old;
275         if (create && (new = win_new(dpy,xid)))
276                 tsearch(new, &cache, win_cmp);
277         return new;
278 }
279
280 static void win_free(win_t *win)
281 {
282         free(win->sys);
283         free(win);
284 }
285
286 static void win_remove(win_t *win)
287 {
288         tdelete(win, &cache, win_cmp);
289         win_free(win);
290 }
291
292 static int win_viewable(win_t *win)
293 {
294         XWindowAttributes attr;
295         if (XGetWindowAttributes(win->sys->dpy, win->sys->xid, &attr))
296                 return attr.map_state == IsViewable;
297         else
298                 return True;
299 }
300
301 /* Drawing functions */
302 static unsigned long get_color(Display *dpy, const char *name)
303 {
304         XColor color;
305         int screen = DefaultScreen(dpy);
306         Colormap cmap = DefaultColormap(dpy, screen);
307         XAllocNamedColor(dpy, cmap, name, &color, &color);
308         return color.pixel;
309 }
310
311 /* Callbacks */
312 static void process_event(int type, XEvent *xe, win_t *root)
313 {
314         Display  *dpy = root->sys->dpy;
315         win_t *win = NULL;
316         //printf("event: %d\n", type);
317
318         /* Common data for all these events ... */
319         ptr_t ptr = {}; mod_t mod = {};
320         if (type == KeyPress    || type == KeyRelease    ||
321             type == ButtonPress || type == ButtonRelease ||
322             type == MotionNotify) {
323                 Window xid = getfocus(root, xe);
324                 if (!(win = win_find(dpy,xid,0)))
325                         return;
326                 ptr = x2ptr(xe);
327                 mod = x2mod(xe->xkey.state, type==KeyRelease||type==ButtonRelease);
328         }
329
330         /* Split based on event */
331         if (type == KeyPress) {
332                 while (XCheckTypedEvent(dpy, KeyPress, xe));
333                 KeySym sym = XKeycodeToKeysym(dpy, xe->xkey.keycode, 0);
334                 printf("got xe %c %hhx\n", xk2ev(sym), mod2int(mod));
335                 wm_handle_event(win, xk2ev(sym), mod, ptr);
336         }
337         else if (type == KeyRelease) {
338                 //printf("release: %d\n", type);
339         }
340         else if (type == ButtonPress) {
341                 if (wm_handle_event(win, xb2ev(xe->xbutton.button), mod, ptr))
342                         XGrabPointer(dpy, xe->xbutton.root, True, PointerMotionMask|ButtonReleaseMask,
343                                         GrabModeAsync, GrabModeAsync, None, None, CurrentTime);
344                 else
345                         XAllowEvents(win->sys->dpy, ReplayPointer, CurrentTime);
346         }
347         else if (type == ButtonRelease) {
348                 XUngrabPointer(dpy, CurrentTime);
349                 wm_handle_event(win, xb2ev(xe->xbutton.button), mod, ptr);
350         }
351         else if (type == MotionNotify) {
352                 while (XCheckTypedEvent(dpy, MotionNotify, xe));
353                 wm_handle_ptr(win, ptr);
354         }
355         else if (type == EnterNotify || type == LeaveNotify) {
356                 printf("%s: %d\n", type==EnterNotify?"enter":"leave", type);
357                 event_t ev = EnterNotify ? EV_ENTER : EV_LEAVE;
358                 if ((win = win_find(dpy,xe->xcrossing.window,0)))
359                         wm_handle_event(win, ev, MOD(), PTR());
360         }
361         else if (type == FocusIn || type == FocusOut) {
362                 //printf("focus: %d\n", type);
363                 event_t ev = FocusIn ? EV_FOCUS : EV_UNFOCUS;
364                 if ((win = win_find(dpy,xe->xfocus.window,0)))
365                         wm_handle_event(win, ev, MOD(), PTR());
366         }
367         else if (type == ConfigureNotify) {
368                 printf("configure: %d\n", type);
369         }
370         else if (type == MapNotify) {
371                 printf("map: %d\n", type);
372         }
373         else if (type == UnmapNotify) {
374                 if ((win = win_find(dpy,xe->xunmap.window,0)) &&
375                      win->sys->state != ST_HIDE) {
376                         if (!strut_del(root, win))
377                                 wm_remove(win);
378                         else
379                                 wm_update();
380                         win->sys->state = ST_HIDE;
381                 }
382         }
383         else if (type == DestroyNotify) {
384                 //printf("destroy: %d\n", type);
385                 if ((win = win_find(dpy,xe->xdestroywindow.window,0)))
386                         win_remove(win);
387         }
388         else if (type == ConfigureRequest) {
389                 XConfigureRequestEvent *cre = &xe->xconfigurerequest;
390                 printf("configure_req: %d - %x, (0x%lx) %dx%d @ %d,%d\n",
391                                 type, (int)cre->window, cre->value_mask,
392                                 cre->height, cre->width, cre->x, cre->y);
393                 if ((win = win_find(dpy,xe->xmaprequest.window,1))) {
394                         XSendEvent(dpy, cre->window, False, StructureNotifyMask, &(XEvent){
395                                 .xconfigure.type              = ConfigureNotify,
396                                 .xconfigure.display           = win->sys->dpy,
397                                 .xconfigure.event             = win->sys->xid,
398                                 .xconfigure.window            = win->sys->xid,
399                                 .xconfigure.x                 = win->x,
400                                 .xconfigure.y                 = win->y,
401                                 .xconfigure.width             = win->w,
402                                 .xconfigure.height            = win->h,
403                                 .xconfigure.border_width      = border,
404                         });
405                         XSync(win->sys->dpy, False);
406                 }
407         }
408         else if (type == MapRequest) {
409                 printf("map_req: %d\n", type);
410                 if ((win = win_find(dpy,xe->xmaprequest.window,1))) {
411                         XSelectInput(win->sys->dpy, win->sys->xid, PropertyChangeMask);
412                         if (!strut_add(root, win))
413                                 wm_insert(win);
414                         else
415                                 wm_update();
416                 }
417                 XMapWindow(dpy, xe->xmaprequest.window);
418         }
419         else if (type == ClientMessage) {
420                 printf("msg: %d\n", type);
421                 XClientMessageEvent *cme = &xe->xclient;
422                 if ((win = win_find(dpy,cme->window,0))     &&
423                     (cme->message_type == atoms[NET_STATE]) &&
424                     (cme->data.l[1] == atoms[NET_FULL] ||
425                      cme->data.l[2] == atoms[NET_FULL])) {
426                         if (cme->data.l[0] == 1 || /* _NET_WM_STATE_ADD    */
427                            (cme->data.l[0] == 2 && /* _NET_WM_STATE_TOGGLE */
428                             win->sys->state != ST_FULL))
429                                 sys_show(win, ST_FULL);
430                         else
431                                 sys_show(win, ST_SHOW);
432                 }
433         }
434         else if (type == PropertyNotify) {
435                 printf("prop: %d\n", type);
436         }
437         else {
438                 printf("unknown event: %d\n", type);
439         }
440 }
441
442 static int xerror(Display *dpy, XErrorEvent *err)
443 {
444         if (err->error_code == BadWindow ||
445             (err->request_code == X_SetInputFocus     && err->error_code == BadMatch   ) ||
446             (err->request_code == X_PolyText8         && err->error_code == BadDrawable) ||
447             (err->request_code == X_PolyFillRectangle && err->error_code == BadDrawable) ||
448             (err->request_code == X_PolySegment       && err->error_code == BadDrawable) ||
449             (err->request_code == X_ConfigureWindow   && err->error_code == BadMatch   ) ||
450             (err->request_code == X_GrabButton        && err->error_code == BadAccess  ) ||
451             (err->request_code == X_GrabKey           && err->error_code == BadAccess  ) ||
452             (err->request_code == X_CopyArea          && err->error_code == BadDrawable))
453                 return 0;
454         if (err->request_code == X_ChangeWindowAttributes && err->error_code == BadAccess)
455                 error("Another window manager is already running");
456         return xerrorxlib(dpy, err);
457 }
458
459 /********************
460  * System functions *
461  ********************/
462 void sys_move(win_t *win, int x, int y, int w, int h)
463 {
464         //printf("sys_move: %p - %d,%d  %dx%d\n", win, x, y, w, h);
465         int b = 2*border;
466         win->x = x; win->y = y;
467         win->w = MAX(w,1+b); win->h = MAX(h,1+b);
468         w      = MAX(w-b,1); h      = MAX(h-b,1);
469         XMoveResizeWindow(win->sys->dpy, win->sys->xid, x, y, w, h);
470
471         /* Flush events, so moving window doesn't cause re-focus
472          * There's probably a better way to do this */
473         XEvent xe;
474         XSync(win->sys->dpy, False);
475         while (XCheckMaskEvent(win->sys->dpy, EnterWindowMask|LeaveWindowMask, &xe))
476                 printf("Skipping enter/leave event\n");
477 }
478
479 void sys_raise(win_t *win)
480 {
481         //printf("sys_raise: %p\n", win);
482         XRaiseWindow(win->sys->dpy, win->sys->xid);
483         for (list_t *cur = struts; cur; cur = cur->next)
484                 XRaiseWindow(((win_t*)cur->data)->sys->dpy,
485                              ((win_t*)cur->data)->sys->xid);
486 }
487
488 void sys_focus(win_t *win)
489 {
490         printf("sys_focus: %p\n", win);
491
492         /* Set actual focus */
493         XSetInputFocus(win->sys->dpy, win->sys->xid,
494                         RevertToPointerRoot, CurrentTime);
495         XSendEvent(win->sys->dpy, win->sys->xid, False, NoEventMask, &(XEvent){
496                 .type                 = ClientMessage,
497                 .xclient.window       = win->sys->xid,
498                 .xclient.message_type = atoms[WM_PROTO],
499                 .xclient.format       = 32,
500                 .xclient.data.l[0]    = atoms[WM_FOCUS],
501                 .xclient.data.l[1]    = CurrentTime,
502         });
503
504         /* Set border on focused window */
505         static win_t *last = NULL;
506         if (last)
507                 XSetWindowBorder(last->sys->dpy, last->sys->xid, colors[CLR_UNFOCUS]);
508         XSync(win->sys->dpy, False);
509         XSetWindowBorder(win->sys->dpy, win->sys->xid, colors[CLR_FOCUS]);
510         last = win;
511 }
512
513 void sys_show(win_t *win, state_t state)
514 {
515         /* Restore from fullscreen */
516         switch (state) {
517         case ST_SHOW:
518                 printf("sys_show: show\n");
519                 if (win->sys->state == ST_FULL)
520                         sys_move(win, win->x, win->y, win->w, win->h);
521                 XSetWindowBorderWidth(win->sys->dpy, win->sys->xid, border);
522                 XMapWindow(win->sys->dpy, win->sys->xid);
523                 XSync(win->sys->dpy, False);
524                 break;
525         case ST_FULL:
526                 printf("sys_show: full\n");
527                 win_t *screen = NULL;
528                 for (list_t *cur = screens; cur; cur = cur->next) {
529                         screen = cur->data;
530                         if (win->x >= screen->x && win->x <= screen->x+screen->w &&
531                             win->y >= screen->y && win->y <= screen->y+screen->h)
532                                 break;
533                 }
534                 XSetWindowBorderWidth(win->sys->dpy, win->sys->xid, 0);
535                 XMapWindow(win->sys->dpy, win->sys->xid);
536                 XMoveResizeWindow(win->sys->dpy, win->sys->xid,
537                         screen->x - screen->sys->strut.left,
538                         screen->y - screen->sys->strut.top,
539                         screen->w + screen->sys->strut.left + screen->sys->strut.right,
540                         screen->h + screen->sys->strut.top  + screen->sys->strut.bottom);
541                 XRaiseWindow(win->sys->dpy, win->sys->xid);
542                 break;
543         case ST_SHADE:
544                 printf("sys_show: shade\n");
545                 XMapWindow(win->sys->dpy, win->sys->xid);
546                 break;
547         case ST_ICON:
548                 printf("sys_show: icon\n");
549                 break;
550         case ST_HIDE:
551                 printf("sys_show: hide\n");
552                 XUnmapWindow(win->sys->dpy, win->sys->xid);
553                 break;
554         case ST_CLOSE:
555                 printf("sys_show: close\n");
556                 XDestroyWindow(win->sys->dpy, win->sys->xid);
557                 break;
558         }
559         win->sys->state = state;
560 }
561
562 void sys_watch(win_t *win, event_t ev, mod_t mod)
563 {
564         //printf("sys_watch: %p - %x %hhx\n", win, ev, mod);
565         XWindowAttributes attr;
566         XGetWindowAttributes(win->sys->dpy, win->sys->xid, &attr);
567         long mask = attr.your_event_mask;
568         if (EV_MOUSE0 <= ev && ev <= EV_MOUSE7)
569                 XGrabButton(win->sys->dpy, ev2xb(ev), mod2x(mod), win->sys->xid, False,
570                                 mod.up ? ButtonReleaseMask : ButtonPressMask,
571                                 GrabModeSync, GrabModeAsync, None, None);
572         else if (ev == EV_ENTER)
573                 XSelectInput(win->sys->dpy, win->sys->xid, EnterWindowMask|mask);
574         else if (ev == EV_LEAVE)
575                 XSelectInput(win->sys->dpy, win->sys->xid, LeaveWindowMask|mask);
576         else if (ev == EV_FOCUS || ev == EV_UNFOCUS)
577                 XSelectInput(win->sys->dpy, win->sys->xid, FocusChangeMask|mask);
578         else
579                 XGrabKey(win->sys->dpy, XKeysymToKeycode(win->sys->dpy, ev2xk(ev)),
580                                 mod2x(mod), win->sys->xid, True, GrabModeAsync, GrabModeAsync);
581 }
582
583 void sys_unwatch(win_t *win, event_t ev, mod_t mod)
584 {
585         if (EV_MOUSE0 <= ev && ev <= EV_MOUSE7)
586                 XUngrabButton(win->sys->dpy, ev2xb(ev), mod2x(mod), win->sys->xid);
587 }
588
589 list_t *sys_info(win_t *win)
590 {
591         /* Use global copy of screens so we can add struts */
592         if (screens == NULL) {
593                 /* Add Xinerama screens */
594                 int n = 0;
595                 XineramaScreenInfo *info = NULL;
596                 if (XineramaIsActive(win->sys->dpy))
597                         info = XineramaQueryScreens(win->sys->dpy, &n);
598                 for (int i = 0; i < n; i++) {
599                         win_t *screen = new0(win_t);
600                         screen->x = info[i].x_org;
601                         screen->y = info[i].y_org;
602                         screen->w = info[i].width;
603                         screen->h = info[i].height;
604                         screen->sys = new0(win_sys_t);
605                         screens = list_append(screens, screen);
606                 }
607         }
608         if (screens == NULL) {
609                 /* No xinerama support */
610                 win_t *screen = new0(win_t);
611                 *screen = *win;
612                 screens = list_insert(NULL, screen);
613         }
614         return screens;
615 }
616
617 win_t *sys_init(void)
618 {
619         Display *dpy;
620         Window   xid;
621
622         /* Load configuration */
623         border     = conf_get_int("main.border",     border);
624         no_capture = conf_get_int("main.no-capture", no_capture);
625
626         /* Open the display */
627         if (!(dpy = XOpenDisplay(NULL)))
628                 error("Unable to get display");
629         if (!(xid = DefaultRootWindow(dpy)))
630                 error("Unable to get root window");
631
632         /* Setup X11 data */
633         atoms[WM_PROTO]  = XInternAtom(dpy, "WM_PROTOCOLS",  False);
634         atoms[WM_FOCUS]  = XInternAtom(dpy, "WM_TAKE_FOCUS", False);
635         atoms[NET_STATE] = XInternAtom(dpy, "_NET_WM_STATE", False);
636         atoms[NET_FULL]  = XInternAtom(dpy, "_NET_WM_STATE_FULLSCREEN", False);
637         atoms[NET_STRUT] = XInternAtom(dpy, "_NET_WM_STRUT", False);
638
639         colors[CLR_FOCUS]   = get_color(dpy, "#a0a0ff");
640         colors[CLR_UNFOCUS] = get_color(dpy, "#101066");
641         colors[CLR_URGENT]  = get_color(dpy, "#ff0000");
642         //printf("colors = #%06lx #%06lx #%06lx\n", colors[0], colors[1], colors[2]);
643
644         /* Select window management events */
645         XSelectInput(dpy, xid, SubstructureRedirectMask|SubstructureNotifyMask);
646         xerrorxlib = XSetErrorHandler(xerror);
647
648         return win_find(dpy, xid, 1);
649 }
650
651 void sys_run(win_t *root)
652 {
653         /* Add each initial window */
654         if (!no_capture) {
655                 unsigned int nkids;
656                 Window par, xid, *kids = NULL;
657                 if (XQueryTree(root->sys->dpy, root->sys->xid,
658                                         &par, &xid, &kids, &nkids)) {
659                         for(int i = 0; i < nkids; i++) {
660                                 win_t *win = win_find(root->sys->dpy, kids[i], 1);
661                                 if (win && win_viewable(win) && !strut_add(root,win))
662                                         wm_insert(win);
663                         }
664                         XFree(kids);
665                 }
666                 wm_update(); // For struts
667         }
668
669         /* Main loop */
670         running = 1;
671         while (running)
672         {
673                 XEvent xe;
674                 XNextEvent(root->sys->dpy, &xe);
675                 process_event(xe.type, &xe, root);
676         }
677 }
678
679 void sys_exit(void)
680 {
681         running = 0;
682 }
683
684 void sys_free(win_t *root)
685 {
686         XCloseDisplay(root->sys->dpy);
687         while (screens) {
688                 win_free(screens->data);
689                 screens = list_remove(screens, screens, 0);
690         }
691         tdestroy(cache, (void(*)(void*))win_free);
692 }