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