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