]> Pileus Git - wmpus/blob - sys-x11.c
Remove border width for toolbars
[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                         int border_width = (win->type == TYPE_TOOLBAR ? 0 : border);
463                         XSendEvent(dpy, cre->window, False, StructureNotifyMask, &(XEvent){
464                                 .xconfigure.type         = ConfigureNotify,
465                                 .xconfigure.display      = win->sys->dpy,
466                                 .xconfigure.event        = win->sys->xid,
467                                 .xconfigure.window       = win->sys->xid,
468                                 .xconfigure.x            = win->x,
469                                 .xconfigure.y            = win->y,
470                                 .xconfigure.width        = win->w,
471                                 .xconfigure.height       = win->h,
472                                 .xconfigure.border_width = border_width,
473                         });
474                         XSync(win->sys->dpy, False);
475                 }
476         }
477         else if (type == MapRequest) {
478                 printf("map_req: %lx\n", xe->xmaprequest.window);
479                 win = win_find(dpy,xe->xmaprequest.window,1);
480                 // fixme, for hide -> max, etc
481                 if (win->state == ST_HIDE) {
482                         wm_handle_state(win, win->state, ST_SHOW);
483                         win->state = ST_SHOW;
484                 }
485                 sys_show(win, win->state);
486         }
487         else if (type == ClientMessage) {
488                 XClientMessageEvent *cme = &xe->xclient;
489                 printf("client_msg: %lx - %ld %ld,%ld,%ld,%ld,%ld\n",
490                                 cme->window, cme->message_type,
491                                 cme->data.l[0], cme->data.l[1], cme->data.l[2],
492                                 cme->data.l[3], cme->data.l[4]);
493                 if ((win = win_find(dpy,cme->window,0))     &&
494                     (cme->message_type == atoms[NET_STATE]) &&
495                     (cme->data.l[1] == atoms[NET_FULL] ||
496                      cme->data.l[2] == atoms[NET_FULL])) {
497                         state_t next = (cme->data.l[0] == 1 || /* _NET_WM_STATE_ADD    */
498                                        (cme->data.l[0] == 2 && /* _NET_WM_STATE_TOGGLE */
499                                         win->state != ST_FULL)) ? ST_FULL : ST_SHOW;
500                         wm_handle_state(win, win->state, next);
501                         sys_show(win, next);
502                 }
503         }
504         else if (type == PropertyNotify) {
505                 printf("prop: %lx - %d\n", xe->xproperty.window, xe->xproperty.state);
506         }
507         else {
508                 printf("unknown event: %d\n", type);
509         }
510 }
511
512 static int xerror(Display *dpy, XErrorEvent *err)
513 {
514         if (err->error_code == BadWindow ||
515             (err->request_code == X_SetInputFocus     && err->error_code == BadMatch   ) ||
516             (err->request_code == X_PolyText8         && err->error_code == BadDrawable) ||
517             (err->request_code == X_PolyFillRectangle && err->error_code == BadDrawable) ||
518             (err->request_code == X_PolySegment       && err->error_code == BadDrawable) ||
519             (err->request_code == X_ConfigureWindow   && err->error_code == BadMatch   ) ||
520             (err->request_code == X_GrabButton        && err->error_code == BadAccess  ) ||
521             (err->request_code == X_GrabKey           && err->error_code == BadAccess  ) ||
522             (err->request_code == X_CopyArea          && err->error_code == BadDrawable))
523                 return 0;
524         if (err->request_code == X_ChangeWindowAttributes && err->error_code == BadAccess)
525                 error("Another window manager is already running");
526         return xerrorxlib(dpy, err);
527 }
528
529 static int xnoerror(Display *dpy, XErrorEvent *err)
530 {
531         return 0;
532 }
533
534
535 /********************
536  * System functions *
537  ********************/
538 void sys_move(win_t *win, int x, int y, int w, int h)
539 {
540         //printf("sys_move: %p - %d,%d  %dx%d\n", win, x, y, w, h);
541         int b = 2*border;
542         win->x = x; win->y = y;
543         win->w = MAX(w,1+b); win->h = MAX(h,1+b);
544         w      = MAX(w-b,1); h      = MAX(h-b,1);
545         XConfigureWindow(win->sys->dpy, win->sys->xid, CWX|CWY|CWWidth|CWHeight,
546                 &(XWindowChanges) { .x=x, .y=y, .width=w, .height=h });
547         XMoveResizeWindow(win->sys->dpy, win->sys->xid, x, y, w, h);
548
549         /* Flush events, so moving window doesn't cause re-focus
550          * There's probably a better way to do this */
551         XEvent xe;
552         XSync(win->sys->dpy, False);
553         while (XCheckMaskEvent(win->sys->dpy, EnterWindowMask|LeaveWindowMask, &xe))
554                 printf("Skipping enter/leave event\n");
555 }
556
557 void sys_raise(win_t *win)
558 {
559         //printf("sys_raise: %p\n", win);
560         XRaiseWindow(win->sys->dpy, win->sys->xid);
561         for (list_t *cur = struts; cur; cur = cur->next)
562                 XRaiseWindow(((win_t*)cur->data)->sys->dpy,
563                              ((win_t*)cur->data)->sys->xid);
564 }
565
566 void sys_focus(win_t *win)
567 {
568         //printf("sys_focus: %p\n", win);
569
570         /* Set actual focus */
571         XSetInputFocus(win->sys->dpy, win->sys->xid,
572                         RevertToPointerRoot, CurrentTime);
573         //win_msg(win, WM_FOCUS);
574
575         /* Set border on focused window */
576         if (last)
577                 XSetWindowBorder(last->sys->dpy, last->sys->xid, colors[CLR_UNFOCUS]);
578         XSync(win->sys->dpy, False);
579         XSetWindowBorder(win->sys->dpy, win->sys->xid, colors[CLR_FOCUS]);
580         last = win;
581 }
582
583 void sys_show(win_t *win, state_t state)
584 {
585         //if (win->state == state)
586         //      return;
587
588         /* Debug */
589         printf("sys_show: %p: %s -> %s\n", win,
590                         state_map[win->state], state_map[state]);
591
592         /* Find screen */
593         win_t *screen = NULL;
594         if (state == ST_FULL || state == ST_MAX) {
595                 for (list_t *cur = screens; cur; cur = cur->next) {
596                         screen = cur->data;
597                         if (win->x >= screen->x && win->x <= screen->x+screen->w &&
598                             win->y >= screen->y && win->y <= screen->y+screen->h)
599                                 break;
600                 }
601         }
602
603         /* Update properties */
604         if (state == ST_FULL)
605                 XChangeProperty(win->sys->dpy, win->sys->xid, atoms[NET_STATE], XA_ATOM, 32,
606                                 PropModeReplace, (unsigned char*)&atoms[NET_FULL], 1);
607         else if (state != ST_FULL)
608                 XChangeProperty(win->sys->dpy, win->sys->xid, atoms[NET_STATE], XA_ATOM, 32,
609                                 PropModeReplace, (unsigned char*)0, 0);
610
611         /* Update border */
612         if (win->type == TYPE_TOOLBAR || state == ST_FULL)
613                 XSetWindowBorderWidth(win->sys->dpy, win->sys->xid, 0);
614         else if (state == ST_SHOW || state == ST_MAX || state == ST_SHADE)
615                 XSetWindowBorderWidth(win->sys->dpy, win->sys->xid, border);
616
617         /* Map/Unmap window */
618         if (state == ST_SHOW || state == ST_FULL || state == ST_MAX || state == ST_SHADE)
619                 XMapWindow(win->sys->dpy, win->sys->xid);
620         else if (state == ST_HIDE)
621                 XUnmapWindow(win->sys->dpy, win->sys->xid);
622
623         /* Resize windows */
624         if (state == ST_SHOW) {
625                 sys_move(win, win->x, win->y, win->w, win->h);
626         } else if (state == ST_MAX) {
627                 sys_move(win, screen->x, screen->y, screen->w, screen->h);
628         } else if (state == ST_FULL) {
629                 XWindowChanges wc = {
630                         .x      = screen->x - screen->sys->strut.left ,
631                         .y      = screen->y - screen->sys->strut.top ,
632                         .width  = screen->w + screen->sys->strut.left + screen->sys->strut.right,
633                         .height = screen->h + screen->sys->strut.top  + screen->sys->strut.bottom
634                 };
635                 win->x = wc.x;     win->y = wc.y;
636                 win->w = wc.width; win->h = wc.height;
637                 XConfigureWindow(win->sys->dpy, win->sys->xid, CWX|CWY|CWWidth|CWHeight, &wc);
638                 XMoveResizeWindow(win->sys->dpy, win->sys->xid, wc.x, wc.y, wc.width, wc.height);
639         } else if (state == ST_SHADE) {
640                 XConfigureWindow(win->sys->dpy, win->sys->xid, CWHeight,
641                         &(XWindowChanges) { .height = stack });
642         }
643
644         /* Raise window */
645         if (state == ST_FULL || state == ST_MAX)
646                 XRaiseWindow(win->sys->dpy, win->sys->xid);
647
648         /* Close windows */
649         if (state == ST_CLOSE) {
650                 if (!win_msg(win, WM_DELETE)) {
651                         XGrabServer(win->sys->dpy);
652                         XSetErrorHandler(xnoerror);
653                         XSetCloseDownMode(win->sys->dpy, DestroyAll);
654                         XKillClient(win->sys->dpy, win->sys->xid);
655                         XSync(win->sys->dpy, False);
656                         XSetErrorHandler(xerror);
657                         XUngrabServer(win->sys->dpy);
658                 }
659         }
660
661         /* Update state */
662         win->state = state;
663 }
664
665 void sys_watch(win_t *win, event_t ev, mod_t mod)
666 {
667         //printf("sys_watch: %p - %x %hhx\n", win, ev, mod);
668         XWindowAttributes attr;
669         XGetWindowAttributes(win->sys->dpy, win->sys->xid, &attr);
670         long mask = attr.your_event_mask;
671         if (EV_MOUSE0 <= ev && ev <= EV_MOUSE7)
672                 XGrabButton(win->sys->dpy, ev2xb(ev), mod2x(mod), win->sys->xid, False,
673                                 mod.up ? ButtonReleaseMask : ButtonPressMask,
674                                 GrabModeSync, GrabModeAsync, None, None);
675         else if (ev == EV_ENTER)
676                 XSelectInput(win->sys->dpy, win->sys->xid, EnterWindowMask|mask);
677         else if (ev == EV_LEAVE)
678                 XSelectInput(win->sys->dpy, win->sys->xid, LeaveWindowMask|mask);
679         else if (ev == EV_FOCUS || ev == EV_UNFOCUS)
680                 XSelectInput(win->sys->dpy, win->sys->xid, FocusChangeMask|mask);
681         else
682                 XGrabKey(win->sys->dpy, XKeysymToKeycode(win->sys->dpy, ev2xk(ev)),
683                                 mod2x(mod), win->sys->xid, True, GrabModeAsync, GrabModeAsync);
684 }
685
686 void sys_unwatch(win_t *win, event_t ev, mod_t mod)
687 {
688         if (EV_MOUSE0 <= ev && ev <= EV_MOUSE7)
689                 XUngrabButton(win->sys->dpy, ev2xb(ev), mod2x(mod), win->sys->xid);
690 }
691
692 list_t *sys_info(win_t *win)
693 {
694         /* Use global copy of screens so we can add struts */
695         if (screens == NULL) {
696                 /* Add Xinerama screens */
697                 int n = 0;
698                 XineramaScreenInfo *info = NULL;
699                 if (XineramaIsActive(win->sys->dpy))
700                         info = XineramaQueryScreens(win->sys->dpy, &n);
701                 for (int i = 0; i < n; i++) {
702                         win_t *screen = new0(win_t);
703                         screen->x = info[i].x_org;
704                         screen->y = info[i].y_org;
705                         screen->w = info[i].width;
706                         screen->h = info[i].height;
707                         screen->sys = new0(win_sys_t);
708                         screens = list_append(screens, screen);
709                 }
710         }
711         if (screens == NULL) {
712                 /* No xinerama support */
713                 win_t *screen = new0(win_t);
714                 *screen = *win;
715                 screens = list_insert(NULL, screen);
716         }
717         return screens;
718 }
719
720 win_t *sys_init(void)
721 {
722         Display *dpy;
723         Window   xid;
724
725         /* Load configuration */
726         stack      = conf_get_int("main.stack",      stack);
727         border     = conf_get_int("main.border",     border);
728         no_capture = conf_get_int("main.no-capture", no_capture);
729
730         /* Open the display */
731         if (!(dpy = XOpenDisplay(NULL)))
732                 error("Unable to get display");
733         if (!(xid = DefaultRootWindow(dpy)))
734                 error("Unable to get root window");
735
736         /* Setup X11 data */
737         atoms[WM_PROTO]    = XInternAtom(dpy, "WM_PROTOCOLS",               False);
738         atoms[WM_FOCUS]    = XInternAtom(dpy, "WM_TAKE_FOCUS",              False);
739         atoms[WM_DELETE]   = XInternAtom(dpy, "WM_DELETE_WINDOW",           False);
740         atoms[NET_STATE]   = XInternAtom(dpy, "_NET_WM_STATE",              False);
741         atoms[NET_FULL]    = XInternAtom(dpy, "_NET_WM_STATE_FULLSCREEN",   False);
742         atoms[NET_STRUT]   = XInternAtom(dpy, "_NET_WM_STRUT",              False);
743         atoms[NET_TYPE]    = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE",        False);
744         atoms[NET_DIALOG]  = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE_DIALOG", False);
745
746         colors[CLR_FOCUS]   = get_color(dpy, "#a0a0ff");
747         colors[CLR_UNFOCUS] = get_color(dpy, "#101066");
748         colors[CLR_URGENT]  = get_color(dpy, "#ff0000");
749         //printf("colors = #%06lx #%06lx #%06lx\n", colors[0], colors[1], colors[2]);
750
751         /* Select window management events */
752         XSelectInput(dpy, xid, SubstructureRedirectMask|SubstructureNotifyMask);
753         xerrorxlib = XSetErrorHandler(xerror);
754
755         return root = win_find(dpy, xid, 1);
756 }
757
758 void sys_run(win_t *root)
759 {
760         /* Add each initial window */
761         if (!no_capture) {
762                 unsigned int nkids;
763                 Window par, xid, *kids = NULL;
764                 if (XQueryTree(root->sys->dpy, root->sys->xid,
765                                         &par, &xid, &kids, &nkids)) {
766                         for(int i = 0; i < nkids; i++)
767                                 if (win_viewable(root->sys->dpy, kids[i]))
768                                         win_find(root->sys->dpy, kids[i], 1);
769                         XFree(kids);
770                 }
771         }
772
773         /* Main loop */
774         running = 1;
775         while (running)
776         {
777                 XEvent xe;
778                 XNextEvent(root->sys->dpy, &xe);
779                 process_event(xe.type, &xe, root);
780         }
781 }
782
783 void sys_exit(void)
784 {
785         running = 0;
786 }
787
788 void sys_free(win_t *root)
789 {
790         XCloseDisplay(root->sys->dpy);
791         while (screens) {
792                 win_free(screens->data);
793                 screens = list_remove(screens, screens, 0);
794         }
795         tdestroy(cache, (void(*)(void*))win_free);
796 }