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