]> Pileus Git - wmpus/blob - sys-x11.c
072216b76ca54c45550ae37be72c719e1d6a5aee
[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 #include <stdio.h>
17 #include <stdlib.h>
18 #include <search.h>
19
20 #include <X11/Xlib.h>
21 #include <X11/Xproto.h>
22 #include <X11/Xatom.h>
23 #include <X11/keysym.h>
24 #include <X11/extensions/Xinerama.h>
25
26 #include "util.h"
27 #include "sys.h"
28 #include "wm.h"
29
30 #ifndef BORDER
31 #define BORDER 2
32 #endif
33
34 /* Internal structures */
35 struct win_sys {
36         Window   xid;
37         Display *dpy;
38         struct {
39                 int left, right, top, bottom;
40         } strut;
41         state_t  state;
42 };
43
44 typedef struct {
45         Key_t key;
46         int   sym;
47 } keymap_t;
48
49 typedef enum {
50         wm_proto, wm_focus, net_strut, natoms
51 } atom_t;
52
53 typedef enum {
54         clr_focus, clr_unfocus, clr_urgent, ncolors
55 } color_t;
56
57 /* Global data */
58 static void *cache;
59 static Atom atoms[natoms];
60 static int (*xerrorxlib)(Display *, XErrorEvent *);
61 static unsigned long colors[ncolors];
62 static list_t *screens;
63
64 /* Conversion functions */
65 static keymap_t key2sym[] = {
66         {key_left    , XK_Left },
67         {key_right   , XK_Right},
68         {key_up      , XK_Up   },
69         {key_down    , XK_Down },
70         {key_home    , XK_Home },
71         {key_end     , XK_End  },
72         {key_pageup  , XK_Prior},
73         {key_pagedown, XK_Next },
74         {key_f1      , XK_F1   },
75         {key_f2      , XK_F2   },
76         {key_f3      , XK_F3   },
77         {key_f4      , XK_F4   },
78         {key_f5      , XK_F5   },
79         {key_f6      , XK_F6   },
80         {key_f7      , XK_F7   },
81         {key_f8      , XK_F8   },
82         {key_f9      , XK_F9   },
83         {key_f10     , XK_F10  },
84         {key_f11     , XK_F11  },
85         {key_f12     , XK_F12  },
86 };
87
88 /* - Modifiers */
89 static mod_t x2mod(unsigned int state, int up)
90 {
91         return (mod_t){
92                .alt   = !!(state & Mod1Mask   ),
93                .ctrl  = !!(state & ControlMask),
94                .shift = !!(state & ShiftMask  ),
95                .win   = !!(state & Mod4Mask   ),
96                .up    = up,
97         };
98 }
99
100 static unsigned int mod2x(mod_t mod)
101 {
102         return (mod.alt   ? Mod1Mask    : 0)
103              | (mod.ctrl  ? ControlMask : 0)
104              | (mod.shift ? ShiftMask   : 0)
105              | (mod.win   ? Mod4Mask    : 0);
106 }
107
108 /* - Keycodes */
109 static Key_t x2key(KeySym sym)
110 {
111         keymap_t *km = map_getr(key2sym,sym);
112         return km ? km->key : sym;
113 }
114
115 static KeySym key2x(Key_t key)
116 {
117         keymap_t *km = map_get(key2sym,key);
118         return km ? km->sym : key;
119 }
120
121 static Key_t x2btn(int btn)
122 {
123         return btn + key_mouse0;
124 }
125
126 static int btn2x(Key_t key)
127 {
128         return key - key_mouse0;
129 }
130
131 /* - Pointers */
132 static ptr_t x2ptr(XEvent *_ev)
133 {
134         XKeyEvent *ev = &_ev->xkey;
135         return (ptr_t){ev->x, ev->y, ev->x_root, ev->y_root};
136 }
137
138 static Window getfocus(win_t *root, XEvent *event)
139 {
140         int revert;
141         Window focus = PointerRoot;
142         if (event->type == KeyPress || event->type == KeyRelease)
143                 XGetInputFocus(root->sys->dpy, &focus, &revert);
144         if (focus == PointerRoot)
145                 focus = event->xkey.subwindow;
146         if (focus == None)
147                 focus = event->xkey.window;
148         return focus;
149 }
150
151 /* Strut functions
152  *   Struts are spaces at the edges of the screen that are used by
153  *   toolbars and statusbars such as dzen. */
154 static int strut_copy(win_t *to, win_t *from, int scale)
155 {
156         int left   = from->sys->strut.left;
157         int right  = from->sys->strut.right;
158         int top    = from->sys->strut.top;
159         int bottom = from->sys->strut.bottom;
160         if (left == 0 && right == 0 && top == 0 && bottom == 0)
161                 return 0;
162         to->x += scale*(left      );
163         to->y += scale*(top       );
164         to->w -= scale*(left+right);
165         to->h -= scale*(top+bottom);
166         return 1;
167 }
168
169 static int strut_add(win_t *root, win_t *win)
170 {
171         /* Get X11 strut data */
172         Atom ret_type;
173         int ret_size;
174         unsigned long ret_items, bytes_left;
175         unsigned char *xdata;
176         int status = XGetWindowProperty(win->sys->dpy, win->sys->xid,
177                         atoms[net_strut], 0L, 4L, False, XA_CARDINAL,
178                         &ret_type, &ret_size, &ret_items, &bytes_left, &xdata);
179         if (status != Success || ret_size != 32 || ret_items != 4)
180                 return 0;
181
182         win->sys->strut.left   = ((int*)xdata)[0];
183         win->sys->strut.right  = ((int*)xdata)[1];
184         win->sys->strut.top    = ((int*)xdata)[2];
185         win->sys->strut.bottom = ((int*)xdata)[3];
186         for (list_t *cur = screens; cur; cur = cur->next)
187                 strut_copy(cur->data, win, 1);
188         return strut_copy(root, win, 1);
189 }
190
191 static int strut_del(win_t *root, win_t *win)
192 {
193         for (list_t *cur = screens; cur; cur = cur->next)
194                 strut_copy(cur->data, win, -1);
195         return strut_copy(root, win, -1);
196 }
197
198 /* Window functions */
199 static win_t *win_new(Display *dpy, Window xid)
200 {
201         XWindowAttributes attr;
202         if (XGetWindowAttributes(dpy, xid, &attr))
203                 if (attr.override_redirect)
204                         return NULL;
205         win_t *win    = new0(win_t);
206         win->x        = attr.x;
207         win->y        = attr.y;
208         win->w        = attr.width;
209         win->h        = attr.height;
210         win->sys      = new0(win_sys_t);
211         win->sys->dpy = dpy;
212         win->sys->xid = xid;
213         printf("win_new: %p = %p, %d (%d,%d %dx%d)\n",
214                         win, dpy, (int)xid,
215                         win->x, win->y, win->w, win->h);
216         return win;
217 }
218
219 static int win_cmp(const void *_a, const void *_b)
220 {
221         const win_t *a = _a, *b = _b;
222         if (a->sys->dpy < b->sys->dpy) return -1;
223         if (a->sys->dpy > b->sys->dpy) return  1;
224         if (a->sys->xid < b->sys->xid) return -1;
225         if (a->sys->xid > b->sys->xid) return  1;
226         return 0;
227 }
228
229 static win_t *win_find(Display *dpy, Window xid, int create)
230 {
231         if (!dpy || !xid)
232                 return NULL;
233         //printf("win_find: %p, %d\n", dpy, (int)xid);
234         win_sys_t sys = {.dpy=dpy, .xid=xid};
235         win_t     tmp = {.sys=&sys};
236         win_t **old = NULL, *new = NULL;
237         if ((old = tfind(&tmp, &cache, win_cmp)))
238                 return *old;
239         if (create && (new = win_new(dpy,xid)))
240                 tsearch(new, &cache, win_cmp);
241         return new;
242 }
243
244 static void win_remove(win_t *win)
245 {
246         tdelete(win, &cache, win_cmp);
247         free(win->sys);
248         free(win);
249 }
250
251 static int win_viewable(win_t *win)
252 {
253         XWindowAttributes attr;
254         if (XGetWindowAttributes(win->sys->dpy, win->sys->xid, &attr))
255                 return attr.map_state == IsViewable;
256         else
257                 return True;
258 }
259
260 /* Drawing functions */
261 static unsigned long get_color(Display *dpy, const char *name)
262 {
263         XColor color;
264         int screen = DefaultScreen(dpy);
265         Colormap cmap = DefaultColormap(dpy, screen);
266         XAllocNamedColor(dpy, cmap, name, &color, &color);
267         return color.pixel;
268 }
269
270 /* Callbacks */
271 static void process_event(int type, XEvent *ev, win_t *root)
272 {
273         Display  *dpy = root->sys->dpy;
274         win_t *win = NULL;
275         //printf("event: %d\n", type);
276
277         /* Common data for all these events ... */
278         ptr_t ptr = {}; mod_t mod = {};
279         if (type == KeyPress    || type == KeyRelease    ||
280             type == ButtonPress || type == ButtonRelease ||
281             type == MotionNotify) {
282                 Window xid = getfocus(root, ev);
283                 if (!(win = win_find(dpy,xid,0)))
284                         return;
285                 ptr = x2ptr(ev);
286                 mod = x2mod(ev->xkey.state, type==KeyRelease||type==ButtonRelease);
287         }
288
289         /* Split based on event */
290         if (type == KeyPress) {
291                 while (XCheckTypedEvent(dpy, KeyPress, ev));
292                 KeySym sym = XKeycodeToKeysym(dpy, ev->xkey.keycode, 0);
293                 printf("got key %c %hhx\n", x2key(sym), mod2int(mod));
294                 wm_handle_key(win, x2key(sym), mod, ptr);
295         }
296         else if (type == KeyRelease) {
297                 //printf("release: %d\n", type);
298         }
299         else if (type == ButtonPress) {
300                 if (wm_handle_key(win, x2btn(ev->xbutton.button), mod, ptr))
301                         XGrabPointer(dpy, ev->xbutton.root, True, PointerMotionMask|ButtonReleaseMask,
302                                         GrabModeAsync, GrabModeAsync, None, None, CurrentTime);
303                 else {
304                         printf("resending event\n");
305                         XSendEvent(win->sys->dpy, ev->xbutton.window,    True,  NoEventMask, ev);
306                         XSendEvent(win->sys->dpy, ev->xbutton.window,    False, NoEventMask, ev);
307                         XSendEvent(win->sys->dpy, ev->xbutton.root,      True,  NoEventMask, ev);
308                         XSendEvent(win->sys->dpy, ev->xbutton.root,      False, NoEventMask, ev);
309                         XSendEvent(win->sys->dpy, ev->xbutton.subwindow, True,  NoEventMask, ev);
310                         XSendEvent(win->sys->dpy, ev->xbutton.subwindow, False, NoEventMask, ev);
311                 }
312         }
313         else if (type == ButtonRelease) {
314                 XUngrabPointer(dpy, CurrentTime);
315                 wm_handle_key(win, x2btn(ev->xbutton.button), mod, ptr);
316         }
317         else if (type == MotionNotify) {
318                 while (XCheckTypedEvent(dpy, MotionNotify, ev));
319                 wm_handle_ptr(win, ptr);
320         }
321         else if (type == EnterNotify || type == LeaveNotify) {
322                 printf("enter: %d\n", type);
323                 key_t key = EnterNotify ? key_enter : key_leave;
324                 if ((win = win_find(dpy,ev->xcrossing.window,0)))
325                         wm_handle_key(win, key, MOD(), PTR());
326         }
327         else if (type == FocusIn || type == FocusOut) {
328                 //printf("focus: %d\n", type);
329                 key_t key = FocusIn ? key_focus : key_unfocus;
330                 if ((win = win_find(dpy,ev->xfocus.window,0)))
331                         wm_handle_key(win, key, MOD(), PTR());
332         }
333         else if (type == ConfigureNotify) {
334                 printf("configure: %d\n", type);
335         }
336         else if (type == MapNotify) {
337                 printf("map: %d\n", type);
338         }
339         else if (type == UnmapNotify) {
340                 if ((win = win_find(dpy,ev->xunmap.window,0)) &&
341                      win->sys->state == st_show) {
342                         if (!strut_del(root, win))
343                                 wm_remove(win);
344                         else
345                                 wm_update();
346                         win->sys->state = st_hide;
347                 }
348         }
349         else if (type == DestroyNotify) {
350                 //printf("destroy: %d\n", type);
351                 if ((win = win_find(dpy,ev->xdestroywindow.window,0)))
352                         win_remove(win);
353         }
354         else if (type == ConfigureRequest) {
355                 XConfigureRequestEvent *cre = &ev->xconfigurerequest;
356                 printf("configure_req: %d - %x, (0x%lx) %dx%d @ %d,%d\n",
357                                 type, (int)cre->window, cre->value_mask,
358                                 cre->height, cre->width, cre->x, cre->y);
359                 XConfigureWindow(dpy, cre->window, cre->value_mask, &(XWindowChanges){
360                         .x      = cre->x,
361                         .y      = cre->y,
362                         .width  = cre->width,
363                         .height = cre->height,
364                 });
365
366                 /* This seems necessary for, but causes flicker
367                  * there could be a better way to do this */
368                 if ((win = win_find(dpy,ev->xmaprequest.window,0)))
369                         sys_move(win, win->x, win->y, win->w, win->h);
370         }
371         else if (type == MapRequest) {
372                 printf("map_req: %d\n", type);
373                 if ((win = win_find(dpy,ev->xmaprequest.window,1))) {
374                         if (!strut_add(root, win))
375                                 wm_insert(win);
376                         else
377                                 wm_update();
378                 }
379                 XMapWindow(dpy,ev->xmaprequest.window);
380         }
381         else {
382                 printf("unknown event: %d\n", type);
383         }
384 }
385
386 static int xerror(Display *dpy, XErrorEvent *err)
387 {
388         if (err->error_code == BadWindow ||
389             (err->request_code == X_SetInputFocus     && err->error_code == BadMatch   ) ||
390             (err->request_code == X_PolyText8         && err->error_code == BadDrawable) ||
391             (err->request_code == X_PolyFillRectangle && err->error_code == BadDrawable) ||
392             (err->request_code == X_PolySegment       && err->error_code == BadDrawable) ||
393             (err->request_code == X_ConfigureWindow   && err->error_code == BadMatch   ) ||
394             (err->request_code == X_GrabButton        && err->error_code == BadAccess  ) ||
395             (err->request_code == X_GrabKey           && err->error_code == BadAccess  ) ||
396             (err->request_code == X_CopyArea          && err->error_code == BadDrawable))
397                 return 0;
398         return xerrorxlib(dpy, err);
399 }
400
401 /********************
402  * System functions *
403  ********************/
404 void sys_move(win_t *win, int x, int y, int w, int h)
405 {
406         //printf("sys_move: %p - %d,%d  %dx%d\n", win, x, y, w, h);
407         int b = 2*BORDER;
408         win->x = x; win->y = y;
409         win->w = MAX(w,1+b); win->h = MAX(h,1+b);
410         w      = MAX(w-b,1); h      = MAX(h-b,1);
411         XMoveResizeWindow(win->sys->dpy, win->sys->xid, x, y, w, h);
412
413         /* Flush events, so moving window doesn't cause re-focus
414          * There's probably a better way to do this */
415         XEvent ev;
416         XSync(win->sys->dpy, False);
417         while (XCheckMaskEvent(win->sys->dpy, EnterWindowMask|LeaveWindowMask, &ev))
418                 printf("Skipping enter/leave event\n");
419 }
420
421 void sys_raise(win_t *win)
422 {
423         //printf("sys_raise: %p\n", win);
424         XRaiseWindow(win->sys->dpy, win->sys->xid);
425 }
426
427 void sys_focus(win_t *win)
428 {
429         //printf("sys_focus: %p\n", win);
430
431         /* Set border on focused window */
432         static win_t *last = NULL;
433         if (last)
434                 XSetWindowBorder(last->sys->dpy, last->sys->xid, colors[clr_unfocus]);
435         XSetWindowBorder(win->sys->dpy, win->sys->xid, colors[clr_focus]);
436         XSetWindowBorderWidth(win->sys->dpy, win->sys->xid, BORDER);
437         last = win;
438
439         /* Set actual focus */
440         XSetInputFocus(win->sys->dpy, win->sys->xid,
441                         RevertToPointerRoot, CurrentTime);
442         XSendEvent(win->sys->dpy, win->sys->xid, False, NoEventMask, &(XEvent){
443                 .type                 = ClientMessage,
444                 .xclient.window       = win->sys->xid,
445                 .xclient.message_type = atoms[wm_proto],
446                 .xclient.format       = 32,
447                 .xclient.data.l[0]    = atoms[wm_focus],
448                 .xclient.data.l[1]    = CurrentTime,
449         });
450 }
451
452 void sys_show(win_t *win, state_t state)
453 {
454         win->sys->state = state;
455         switch (state) {
456         case st_show:
457                 printf("sys_show: show\n");
458                 XMapWindow(win->sys->dpy, win->sys->xid);
459                 return;
460         case st_full:
461                 printf("sys_show: full\n");
462                 return;
463         case st_shade:
464                 printf("sys_show: shade\n");
465                 return;
466         case st_icon:
467                 printf("sys_show: icon\n");
468                 return;
469         case st_hide:
470                 printf("sys_show: hide\n");
471                 XUnmapWindow(win->sys->dpy, win->sys->xid);
472                 return;
473         }
474 }
475
476 void sys_watch(win_t *win, Key_t key, mod_t mod)
477 {
478         //printf("sys_watch: %p - %x %hhx\n", win, key, mod);
479         XWindowAttributes attr;
480         XGetWindowAttributes(win->sys->dpy, win->sys->xid, &attr);
481         long mask = attr.your_event_mask;
482         if (key_mouse0 <= key && key <= key_mouse7)
483                 XGrabButton(win->sys->dpy, btn2x(key), mod2x(mod), win->sys->xid, False,
484                                 mod.up ? ButtonReleaseMask : ButtonPressMask,
485                                 GrabModeAsync, GrabModeAsync, None, None);
486         else if (key == key_enter)
487                 XSelectInput(win->sys->dpy, win->sys->xid, EnterWindowMask|mask);
488         else if (key == key_leave)
489                 XSelectInput(win->sys->dpy, win->sys->xid, LeaveWindowMask|mask);
490         else if (key == key_focus || key == key_unfocus)
491                 XSelectInput(win->sys->dpy, win->sys->xid, FocusChangeMask|mask);
492         else
493                 XGrabKey(win->sys->dpy, XKeysymToKeycode(win->sys->dpy, key2x(key)),
494                                 mod2x(mod), win->sys->xid, True, GrabModeAsync, GrabModeAsync);
495 }
496
497 void sys_unwatch(win_t *win, Key_t key, mod_t mod)
498 {
499         if (key_mouse0 <= key && key <= key_mouse7)
500                 XUngrabButton(win->sys->dpy, btn2x(key), mod2x(mod), win->sys->xid);
501 }
502
503 list_t *sys_info(win_t *win)
504 {
505         /* Use global copy of screens so we can add struts */
506         if (screens == NULL) {
507                 int n;
508                 XineramaScreenInfo *info = NULL;
509                 if (XineramaIsActive(win->sys->dpy))
510                         info = XineramaQueryScreens(win->sys->dpy, &n);
511                 if (!info) {
512                         win_t *screen = new0(win_t);
513                         *screen = *win;
514                         return list_insert(NULL, screen);
515                 }
516                 for (int i = 0; i < n; i++) {
517                         win_t *screen = new0(win_t);
518                         screen->x = info[i].x_org;
519                         screen->y = info[i].y_org;
520                         screen->w = info[i].width;
521                         screen->h = info[i].height;
522                         screens = list_append(screens, screen);
523                 }
524         }
525         return screens;
526 }
527
528 win_t *sys_init(void)
529 {
530         Display *dpy;
531         Window   xid;
532
533         /* Open the display */
534         if (!(dpy = XOpenDisplay(NULL)))
535                 error("Unable to get display");
536         if (!(xid = DefaultRootWindow(dpy)))
537                 error("Unable to get root window");
538
539         /* Setup X11 data */
540         atoms[wm_proto]  = XInternAtom(dpy, "WM_PROTOCOLS",  False);
541         atoms[wm_focus]  = XInternAtom(dpy, "WM_TAKE_FOCUS", False);
542         atoms[net_strut] = XInternAtom(dpy, "_NET_WM_STRUT", False);
543
544         colors[clr_focus]   = get_color(dpy, "#a0a0ff");
545         colors[clr_unfocus] = get_color(dpy, "#101066");
546         colors[clr_urgent]  = get_color(dpy, "#ff0000");
547         printf("colors = #%06lx #%06lx #%06lx\n", colors[0], colors[1], colors[2]);
548
549         /* Select window management events */
550         XSelectInput(dpy, xid, SubstructureRedirectMask|SubstructureNotifyMask);
551         XSetInputFocus(dpy, None, RevertToNone, CurrentTime);
552         xerrorxlib = XSetErrorHandler(xerror);
553
554         return win_find(dpy, xid, 1);
555 }
556
557 void sys_run(win_t *root)
558 {
559         /* Add each initial window */
560         unsigned int nkids;
561         Window par, xid, *kids = NULL;
562         if (XQueryTree(root->sys->dpy, root->sys->xid,
563                                 &par, &xid, &kids, &nkids))
564                 for(int i = 0; i < nkids; i++) {
565                         win_t *win = win_find(root->sys->dpy, kids[i], 1);
566                         if (win && win_viewable(win) && !strut_add(root,win))
567                                 wm_insert(win);
568                 }
569         wm_update(); // For struts
570
571         /* Main loop */
572         for(;;)
573         {
574                 XEvent ev;
575                 XNextEvent(root->sys->dpy, &ev);
576                 process_event(ev.type, &ev, root);
577         }
578 }