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