]> Pileus Git - wmpus/blob - sys-x11.c
e417e83d3a612522484bd1251b83bd2b3027331c
[wmpus] / sys-x11.c
1 /*
2  * Copyright (c) 2011, 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                 XConfigureWindow(dpy, cre->window, cre->value_mask, &(XWindowChanges){
366                         .x      = cre->x,
367                         .y      = cre->y,
368                         .width  = cre->width,
369                         .height = cre->height,
370                 });
371
372                 /* This seems necessary for, but causes flicker
373                  * there could be a better way to do this */
374                 if ((win = win_find(dpy,xe->xmaprequest.window,0)))
375                         sys_move(win, win->x, win->y, win->w, win->h);
376         }
377         else if (type == MapRequest) {
378                 printf("map_req: %d\n", type);
379                 if ((win = win_find(dpy,xe->xmaprequest.window,1))) {
380                         if (!strut_add(root, win))
381                                 wm_insert(win);
382                         else
383                                 wm_update();
384                 }
385                 XMapWindow(dpy,xe->xmaprequest.window);
386         }
387         else {
388                 printf("unknown event: %d\n", type);
389         }
390 }
391
392 static int xerror(Display *dpy, XErrorEvent *err)
393 {
394         if (err->error_code == BadWindow ||
395             (err->request_code == X_SetInputFocus     && err->error_code == BadMatch   ) ||
396             (err->request_code == X_PolyText8         && err->error_code == BadDrawable) ||
397             (err->request_code == X_PolyFillRectangle && err->error_code == BadDrawable) ||
398             (err->request_code == X_PolySegment       && err->error_code == BadDrawable) ||
399             (err->request_code == X_ConfigureWindow   && err->error_code == BadMatch   ) ||
400             (err->request_code == X_GrabButton        && err->error_code == BadAccess  ) ||
401             (err->request_code == X_GrabKey           && err->error_code == BadAccess  ) ||
402             (err->request_code == X_CopyArea          && err->error_code == BadDrawable))
403                 return 0;
404         return xerrorxlib(dpy, err);
405 }
406
407 /********************
408  * System functions *
409  ********************/
410 void sys_move(win_t *win, int x, int y, int w, int h)
411 {
412         //printf("sys_move: %p - %d,%d  %dx%d\n", win, x, y, w, h);
413         int b = 2*border;
414         win->x = x; win->y = y;
415         win->w = MAX(w,1+b); win->h = MAX(h,1+b);
416         w      = MAX(w-b,1); h      = MAX(h-b,1);
417         XMoveResizeWindow(win->sys->dpy, win->sys->xid, x, y, w, h);
418
419         /* Flush events, so moving window doesn't cause re-focus
420          * There's probably a better way to do this */
421         XEvent xe;
422         XSync(win->sys->dpy, False);
423         while (XCheckMaskEvent(win->sys->dpy, EnterWindowMask|LeaveWindowMask, &xe))
424                 printf("Skipping enter/leave event\n");
425 }
426
427 void sys_raise(win_t *win)
428 {
429         //printf("sys_raise: %p\n", win);
430         XRaiseWindow(win->sys->dpy, win->sys->xid);
431         for (list_t *cur = struts; cur; cur = cur->next)
432                 XRaiseWindow(((win_t*)cur->data)->sys->dpy,
433                              ((win_t*)cur->data)->sys->xid);
434 }
435
436 void sys_focus(win_t *win)
437 {
438         //printf("sys_focus: %p\n", win);
439
440         /* Set border on focused window */
441         static win_t *last = NULL;
442         if (last)
443                 XSetWindowBorder(last->sys->dpy, last->sys->xid, colors[CLR_UNFOCUS]);
444         XSetWindowBorder(win->sys->dpy, win->sys->xid, colors[CLR_FOCUS]);
445         XSetWindowBorderWidth(win->sys->dpy, win->sys->xid, border);
446         last = win;
447
448         /* Set actual focus */
449         XSetInputFocus(win->sys->dpy, win->sys->xid,
450                         RevertToPointerRoot, CurrentTime);
451         XSendEvent(win->sys->dpy, win->sys->xid, False, NoEventMask, &(XEvent){
452                 .type                 = ClientMessage,
453                 .xclient.window       = win->sys->xid,
454                 .xclient.message_type = atoms[WM_PROTO],
455                 .xclient.format       = 32,
456                 .xclient.data.l[0]    = atoms[WM_FOCUS],
457                 .xclient.data.l[1]    = CurrentTime,
458         });
459 }
460
461 void sys_show(win_t *win, state_t state)
462 {
463         win->sys->state = state;
464         switch (state) {
465         case ST_SHOW:
466                 printf("sys_show: show\n");
467                 XMapWindow(win->sys->dpy, win->sys->xid);
468                 XSync(win->sys->dpy, False);
469                 return;
470         case ST_FULL:
471                 printf("sys_show: full\n");
472                 XMapWindow(win->sys->dpy, win->sys->xid);
473                 return;
474         case ST_SHADE:
475                 printf("sys_show: shade\n");
476                 XMapWindow(win->sys->dpy, win->sys->xid);
477                 return;
478         case ST_ICON:
479                 printf("sys_show: icon\n");
480                 return;
481         case ST_HIDE:
482                 printf("sys_show: hide\n");
483                 XUnmapWindow(win->sys->dpy, win->sys->xid);
484                 return;
485         case ST_CLOSE:
486                 printf("sys_show: close\n");
487                 XDestroyWindow(win->sys->dpy, win->sys->xid);
488                 return;
489         }
490 }
491
492 void sys_watch(win_t *win, event_t ev, mod_t mod)
493 {
494         //printf("sys_watch: %p - %x %hhx\n", win, ev, mod);
495         XWindowAttributes attr;
496         XGetWindowAttributes(win->sys->dpy, win->sys->xid, &attr);
497         long mask = attr.your_event_mask;
498         if (EV_MOUSE0 <= ev && ev <= EV_MOUSE7)
499                 XGrabButton(win->sys->dpy, ev2xb(ev), mod2x(mod), win->sys->xid, False,
500                                 mod.up ? ButtonReleaseMask : ButtonPressMask,
501                                 GrabModeSync, GrabModeAsync, None, None);
502         else if (ev == EV_ENTER)
503                 XSelectInput(win->sys->dpy, win->sys->xid, EnterWindowMask|mask);
504         else if (ev == EV_LEAVE)
505                 XSelectInput(win->sys->dpy, win->sys->xid, LeaveWindowMask|mask);
506         else if (ev == EV_FOCUS || ev == EV_UNFOCUS)
507                 XSelectInput(win->sys->dpy, win->sys->xid, FocusChangeMask|mask);
508         else
509                 XGrabKey(win->sys->dpy, XKeysymToKeycode(win->sys->dpy, ev2xk(ev)),
510                                 mod2x(mod), win->sys->xid, True, GrabModeAsync, GrabModeAsync);
511 }
512
513 void sys_unwatch(win_t *win, event_t ev, mod_t mod)
514 {
515         if (EV_MOUSE0 <= ev && ev <= EV_MOUSE7)
516                 XUngrabButton(win->sys->dpy, ev2xb(ev), mod2x(mod), win->sys->xid);
517 }
518
519 list_t *sys_info(win_t *win)
520 {
521         /* Use global copy of screens so we can add struts */
522         if (screens == NULL) {
523                 /* Add Xinerama screens */
524                 int n = 0;
525                 XineramaScreenInfo *info = NULL;
526                 if (XineramaIsActive(win->sys->dpy))
527                         info = XineramaQueryScreens(win->sys->dpy, &n);
528                 for (int i = 0; i < n; i++) {
529                         win_t *screen = new0(win_t);
530                         screen->x = info[i].x_org;
531                         screen->y = info[i].y_org;
532                         screen->w = info[i].width;
533                         screen->h = info[i].height;
534                         screens = list_append(screens, screen);
535                 }
536         }
537         if (screens == NULL) {
538                 /* No xinerama support */
539                 win_t *screen = new0(win_t);
540                 *screen = *win;
541                 screens = list_insert(NULL, screen);
542         }
543         return screens;
544 }
545
546 win_t *sys_init(void)
547 {
548         Display *dpy;
549         Window   xid;
550
551         /* Load configuration */
552         border     = conf_get_int("main.border",     border);
553         no_capture = conf_get_int("main.no-capture", no_capture);
554
555         /* Open the display */
556         if (!(dpy = XOpenDisplay(NULL)))
557                 error("Unable to get display");
558         if (!(xid = DefaultRootWindow(dpy)))
559                 error("Unable to get root window");
560
561         /* Setup X11 data */
562         atoms[WM_PROTO]  = XInternAtom(dpy, "WM_PROTOCOLS",  False);
563         atoms[WM_FOCUS]  = XInternAtom(dpy, "WM_TAKE_FOCUS", False);
564         atoms[NET_STRUT] = XInternAtom(dpy, "_NET_WM_STRUT", False);
565
566         colors[CLR_FOCUS]   = get_color(dpy, "#a0a0ff");
567         colors[CLR_UNFOCUS] = get_color(dpy, "#101066");
568         colors[CLR_URGENT]  = get_color(dpy, "#ff0000");
569         printf("colors = #%06lx #%06lx #%06lx\n", colors[0], colors[1], colors[2]);
570
571         /* Select window management events */
572         XSelectInput(dpy, xid, SubstructureRedirectMask|SubstructureNotifyMask);
573         xerrorxlib = XSetErrorHandler(xerror);
574
575         return win_find(dpy, xid, 1);
576 }
577
578 void sys_run(win_t *root)
579 {
580         /* Add each initial window */
581         if (!no_capture) {
582                 unsigned int nkids;
583                 Window par, xid, *kids = NULL;
584                 if (XQueryTree(root->sys->dpy, root->sys->xid,
585                                         &par, &xid, &kids, &nkids)) {
586                         for(int i = 0; i < nkids; i++) {
587                                 win_t *win = win_find(root->sys->dpy, kids[i], 1);
588                                 if (win && win_viewable(win) && !strut_add(root,win))
589                                         wm_insert(win);
590                         }
591                         XFree(kids);
592                 }
593                 wm_update(); // For struts
594         }
595
596         /* Main loop */
597         running = 1;
598         while (running)
599         {
600                 XEvent xe;
601                 XNextEvent(root->sys->dpy, &xe);
602                 process_event(xe.type, &xe, root);
603         }
604 }
605
606 void sys_exit(void)
607 {
608         running = 0;
609 }
610
611 void sys_free(win_t *root)
612 {
613         XCloseDisplay(root->sys->dpy);
614         while (screens)
615                 screens = list_remove(screens, screens, 1);
616         tdestroy(cache, (void(*)(void*))win_free);
617 }