]> Pileus Git - wmpus/blob - sys-x11.c
Only grab mouse click on unfocused windows
[wmpus] / sys-x11.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <search.h>
4
5 #include <X11/Xlib.h>
6 #include <X11/Xproto.h>
7 #include <X11/Xatom.h>
8 #include <X11/keysym.h>
9
10 #include "util.h"
11 #include "sys.h"
12 #include "wm.h"
13
14 /* Internal structures */
15 struct win_sys {
16         Window   xid;
17         Display *dpy;
18         struct {
19                 int left, right, top, bottom;
20         } strut;
21 };
22
23 typedef struct {
24         Key_t key;
25         int   sym;
26 } keymap_t;
27
28 typedef enum {
29         wm_proto, wm_focus, net_strut, natoms
30 } atom_t;
31
32 /* Global data */
33 static void *win_cache = NULL;
34 static Atom atoms[natoms];
35 static int (*xerrorxlib)(Display *, XErrorEvent *);
36
37 /* Conversion functions */
38 static keymap_t key2sym[] = {
39         {key_left    , XK_Left },
40         {key_right   , XK_Right},
41         {key_up      , XK_Up   },
42         {key_down    , XK_Down },
43         {key_home    , XK_Home },
44         {key_end     , XK_End  },
45         {key_pageup  , XK_Prior},
46         {key_pagedown, XK_Next },
47         {key_f1      , XK_F1   },
48         {key_f2      , XK_F2   },
49         {key_f3      , XK_F3   },
50         {key_f4      , XK_F4   },
51         {key_f5      , XK_F5   },
52         {key_f6      , XK_F6   },
53         {key_f7      , XK_F7   },
54         {key_f8      , XK_F8   },
55         {key_f9      , XK_F9   },
56         {key_f10     , XK_F10  },
57         {key_f11     , XK_F11  },
58         {key_f12     , XK_F12  },
59 };
60
61 /* - Modifiers */
62 static mod_t x2mod(unsigned int state, int up)
63 {
64         return (mod_t){
65                .alt   = !!(state & Mod1Mask   ),
66                .ctrl  = !!(state & ControlMask),
67                .shift = !!(state & ShiftMask  ),
68                .win   = !!(state & Mod4Mask   ),
69                .up    = up,
70         };
71 }
72
73 static unsigned int mod2x(mod_t mod)
74 {
75         return (mod.alt   ? Mod1Mask    : 0)
76              | (mod.ctrl  ? ControlMask : 0)
77              | (mod.shift ? ShiftMask   : 0)
78              | (mod.win   ? Mod4Mask    : 0);
79 }
80
81 /* - Keycodes */
82 static Key_t x2key(KeySym sym)
83 {
84         keymap_t *km = map_getr(key2sym,sym);
85         return km ? km->key : sym;
86 }
87
88 static KeySym key2x(Key_t key)
89 {
90         keymap_t *km = map_get(key2sym,key);
91         return km ? km->sym : key;
92 }
93
94 static Key_t x2btn(int btn)
95 {
96         return btn + key_mouse0;
97 }
98
99 static int btn2x(Key_t key)
100 {
101         return key - key_mouse0;
102 }
103
104 /* - Pointers */
105 static ptr_t x2ptr(XEvent *_ev)
106 {
107         XKeyEvent *ev = &_ev->xkey;
108         return (ptr_t){ev->x, ev->y, ev->x_root, ev->y_root};
109 }
110
111 static Window getfocus(win_t *root, XEvent *event)
112 {
113         int revert;
114         Window focus = PointerRoot;
115         if (event->type == KeyPress || event->type == KeyRelease)
116                 XGetInputFocus(root->sys->dpy, &focus, &revert);
117         if (focus == PointerRoot)
118                 focus = event->xkey.subwindow;
119         if (focus == None)
120                 focus = event->xkey.window;
121         return focus;
122 }
123
124 /* Helpers */
125 static int add_strut(win_t *root, win_t *win)
126 {
127         /* Get X11 strut data */
128         Atom ret_type;
129         int ret_size;
130         unsigned long ret_items, bytes_left;
131         unsigned char *xdata;
132         int status = XGetWindowProperty(win->sys->dpy, win->sys->xid,
133                         atoms[net_strut], 0L, 4L, False, XA_CARDINAL,
134                         &ret_type, &ret_size, &ret_items, &bytes_left, &xdata);
135         if (status != Success || ret_size != 32 || ret_items != 4)
136                 return 0;
137
138         int left   = ((int*)xdata)[0];
139         int right  = ((int*)xdata)[1];
140         int top    = ((int*)xdata)[2];
141         int bottom = ((int*)xdata)[3];
142         if (left == 0 && right == 0 && top == 0 && bottom == 0)
143                 return 0;
144
145         win->sys->strut.left   = left;
146         win->sys->strut.right  = right;
147         win->sys->strut.top    = top;
148         win->sys->strut.bottom = bottom;
149         root->x += left;
150         root->y += top;
151         root->w -= left+right;
152         root->h -= top+bottom;
153         return 1;
154 }
155
156 static int del_strut(win_t *root, win_t *win)
157 {
158         int left   = win->sys->strut.left;
159         int right  = win->sys->strut.right;
160         int top    = win->sys->strut.top;
161         int bottom = win->sys->strut.bottom;
162         if (left == 0 && right == 0 && top == 0 && bottom == 0)
163                 return 0;
164
165         root->x -= left;
166         root->y -= top;
167         root->w += left+right;
168         root->h += top+bottom;
169         return 1;
170 }
171
172 /* Window functions */
173 static win_t *win_new(Display *dpy, Window xid)
174 {
175         XWindowAttributes attr;
176         if (XGetWindowAttributes(dpy, xid, &attr))
177                 if (attr.override_redirect)
178                         return NULL;
179         win_t *win    = new0(win_t);
180         win->x        = attr.x;
181         win->y        = attr.y;
182         win->w        = attr.width;
183         win->h        = attr.height;
184         win->sys      = new0(win_sys_t);
185         win->sys->dpy = dpy;
186         win->sys->xid = xid;
187         printf("%p = %p, %d\n", win, dpy, (int)xid);
188         return win;
189 }
190
191 static int win_cmp(const void *_a, const void *_b)
192 {
193         const win_t *a = _a, *b = _b;
194         if (a->sys->dpy < b->sys->dpy) return -1;
195         if (a->sys->dpy > b->sys->dpy) return  1;
196         if (a->sys->xid < b->sys->xid) return -1;
197         if (a->sys->xid > b->sys->xid) return  1;
198         return 0;
199 }
200
201 static win_t *win_find(Display *dpy, Window xid, int create)
202 {
203         if (!dpy || !xid)
204                 return NULL;
205         //printf("win_find: %p, %d\n", dpy, (int)xid);
206         win_sys_t sys = {.dpy=dpy, .xid=xid};
207         win_t     tmp = {.sys=&sys};
208         win_t **old = NULL, *new = NULL;
209         if ((old = tfind(&tmp, &win_cache, win_cmp)))
210                 return *old;
211         if (create && (new = win_new(dpy,xid)))
212                 tsearch(new, &win_cache, win_cmp);
213         return new;
214 }
215
216 static void win_remove(win_t *win)
217 {
218         tdelete(win, &win_cache, win_cmp);
219         free(win->sys);
220         free(win);
221 }
222
223 static int win_viewable(win_t *win)
224 {
225         XWindowAttributes attr;
226         if (XGetWindowAttributes(win->sys->dpy, win->sys->xid, &attr))
227                 return attr.map_state == IsViewable;
228         else
229                 return True;
230 }
231
232 /* Callbacks */
233 static void process_event(int type, XEvent *ev, win_t *root)
234 {
235         Display  *dpy = root->sys->dpy;
236         win_t *win = NULL;
237         printf("event: %d\n", type);
238
239         /* Common data for all these events ... */
240         ptr_t ptr; mod_t mod;
241         if (type == KeyPress    || type == KeyRelease    ||
242             type == ButtonPress || type == ButtonRelease ||
243             type == MotionNotify) {
244                 Window xid = getfocus(root, ev);
245                 if (!(win = win_find(dpy,xid,0)))
246                         return;
247                 ptr = x2ptr(ev);
248                 mod = x2mod(ev->xkey.state, type==KeyRelease||type==ButtonRelease);
249         }
250
251         /* Split based on event */
252         if (type == KeyPress) {
253                 while (XCheckTypedEvent(dpy, KeyPress, ev));
254                 KeySym sym = XKeycodeToKeysym(dpy, ev->xkey.keycode, 0);
255                 wm_handle_key(win, x2key(sym), mod, ptr);
256         }
257         else if (type == KeyRelease) {
258                 //printf("release: %d\n", type);
259         }
260         else if (type == ButtonPress) {
261                 if (wm_handle_key(win, x2btn(ev->xbutton.button), mod, ptr))
262                         XGrabPointer(dpy, ev->xbutton.root, True, PointerMotionMask|ButtonReleaseMask,
263                                         GrabModeAsync, GrabModeAsync, None, None, CurrentTime);
264                 else {
265                         printf("resending event\n");
266                         XSendEvent(win->sys->dpy, ev->xbutton.window,    True,  NoEventMask, ev);
267                         XSendEvent(win->sys->dpy, ev->xbutton.window,    False, NoEventMask, ev);
268                         XSendEvent(win->sys->dpy, ev->xbutton.root,      True,  NoEventMask, ev);
269                         XSendEvent(win->sys->dpy, ev->xbutton.root,      False, NoEventMask, ev);
270                         XSendEvent(win->sys->dpy, ev->xbutton.subwindow, True,  NoEventMask, ev);
271                         XSendEvent(win->sys->dpy, ev->xbutton.subwindow, False, NoEventMask, ev);
272                 }
273         }
274         else if (type == ButtonRelease) {
275                 XUngrabPointer(dpy, CurrentTime);
276                 wm_handle_key(win, x2btn(ev->xbutton.button), mod, ptr);
277         }
278         else if (type == MotionNotify) {
279                 while (XCheckTypedEvent(dpy, MotionNotify, ev));
280                 wm_handle_ptr(win, ptr);
281         }
282         else if (type == EnterNotify || type == LeaveNotify) {
283                 printf("enter: %d\n", type);
284                 key_t key = EnterNotify ? key_enter : key_leave;
285                 if ((win = win_find(dpy,ev->xcrossing.window,0)))
286                         wm_handle_key(win, key, MOD(), PTR());
287         }
288         else if (type == FocusIn || type == FocusOut) {
289                 printf("focus: %d\n", type);
290                 key_t key = FocusIn ? key_focus : key_unfocus;
291                 if ((win = win_find(dpy,ev->xfocus.window,0)))
292                         wm_handle_key(win, key, MOD(), PTR());
293         }
294         else if (type == ConfigureNotify) {
295                 printf("configure: %d\n", type);
296         }
297         else if (type == MapNotify) {
298                 printf("map: %d\n", type);
299         }
300         else if (type == UnmapNotify) {
301                 //printf("unmap: %d\n", type);
302                 if ((win = win_find(dpy,ev->xunmap.window,0))) {
303                         if (!del_strut(root, win))
304                                 wm_remove(win);
305                         else
306                                 wm_update();
307                         win_remove(win);
308                 }
309         }
310         else if (type == ConfigureRequest) {
311                 XConfigureRequestEvent *cre = &ev->xconfigurerequest;
312                 printf("configure_req: %d - %x, (0x%lx) %dx%d @ %d,%d\n",
313                                 type, (int)cre->window, cre->value_mask,
314                                 cre->height, cre->width, cre->x, cre->y);
315                 XConfigureWindow(dpy, cre->window, cre->value_mask, &(XWindowChanges){
316                         .x      = cre->x,
317                         .y      = cre->y,
318                         .width  = cre->width,
319                         .height = cre->height,
320                 });
321
322                 /* This seems necessasairy for, but causes flicker
323                  * there could be a better way to do this */
324                 if ((win = win_find(dpy,ev->xmaprequest.window,0)))
325                         sys_move(win, win->x, win->y, win->w, win->h);
326         }
327         else if (type == MapRequest) {
328                 printf("map_req: %d\n", type);
329                 if ((win = win_find(dpy,ev->xmaprequest.window,1))) {
330                         if (!add_strut(root, win))
331                                 wm_insert(win);
332                         else
333                                 wm_update();
334                 }
335                 XMapWindow(dpy,ev->xmaprequest.window);
336         }
337         else {
338                 printf("unknown event: %d\n", type);
339         }
340 }
341
342 static int xerror(Display *dpy, XErrorEvent *err)
343 {
344         if (err->error_code == BadWindow ||
345             (err->request_code == X_SetInputFocus     && err->error_code == BadMatch   ) ||
346             (err->request_code == X_PolyText8         && err->error_code == BadDrawable) ||
347             (err->request_code == X_PolyFillRectangle && err->error_code == BadDrawable) ||
348             (err->request_code == X_PolySegment       && err->error_code == BadDrawable) ||
349             (err->request_code == X_ConfigureWindow   && err->error_code == BadMatch   ) ||
350             (err->request_code == X_GrabButton        && err->error_code == BadAccess  ) ||
351             (err->request_code == X_GrabKey           && err->error_code == BadAccess  ) ||
352             (err->request_code == X_CopyArea          && err->error_code == BadDrawable))
353                 return 0;
354         return xerrorxlib(dpy, err);
355 }
356
357 /*****************
358  * Sys functions *
359  *****************/
360 void sys_move(win_t *win, int x, int y, int w, int h)
361 {
362         //printf("sys_move: %p - %d,%d  %dx%d\n", win, x, y, w, h);
363         win->x = MAX(x,0); win->y = MAX(y,0);
364         win->w = MAX(w,1); win->h = MAX(h,1);
365         XMoveResizeWindow(win->sys->dpy, win->sys->xid,
366                         win->x, win->y, win->w, win->h);
367
368         /* Flush events, so moving window doesn't cuase re-focus
369          * There's probably a better way to do this */
370         XEvent ev;
371         XSync(win->sys->dpy, False);
372         while (XCheckMaskEvent(win->sys->dpy, EnterWindowMask|LeaveWindowMask, &ev))
373                 printf("Skipping enter/leave event\n");
374 }
375
376 void sys_raise(win_t *win)
377 {
378         //printf("sys_raise: %p\n", win);
379         XRaiseWindow(win->sys->dpy, win->sys->xid);
380 }
381
382 void sys_focus(win_t *win)
383 {
384         printf("sys_focus: %p\n", win);
385         XSetInputFocus(win->sys->dpy, win->sys->xid,
386                         RevertToPointerRoot, CurrentTime);
387         XSendEvent(win->sys->dpy, win->sys->xid, False, NoEventMask, &(XEvent){
388                 .type                 = ClientMessage,
389                 .xclient.window       = win->sys->xid,
390                 .xclient.message_type = atoms[wm_proto],
391                 .xclient.format       = 32,
392                 .xclient.data.l[0]    = atoms[wm_focus],
393                 .xclient.data.l[1]    = CurrentTime,
394         });
395 }
396
397 void sys_watch(win_t *win, Key_t key, mod_t mod)
398 {
399         //printf("sys_watch: %p - %x %hhx\n", win, key, mod);
400         XWindowAttributes attr;
401         XGetWindowAttributes(win->sys->dpy, win->sys->xid, &attr);
402         long mask = attr.your_event_mask;
403         if (key_mouse0 <= key && key <= key_mouse7)
404                 XGrabButton(win->sys->dpy, btn2x(key), mod2x(mod), win->sys->xid, False,
405                                 mod.up ? ButtonReleaseMask : ButtonPressMask,
406                                 GrabModeAsync, GrabModeAsync, None, None);
407         else if (key == key_enter)
408                 XSelectInput(win->sys->dpy, win->sys->xid, EnterWindowMask|mask);
409         else if (key == key_leave)
410                 XSelectInput(win->sys->dpy, win->sys->xid, LeaveWindowMask|mask);
411         else if (key == key_focus || key == key_unfocus)
412                 XSelectInput(win->sys->dpy, win->sys->xid, FocusChangeMask|mask);
413         else
414                 XGrabKey(win->sys->dpy, XKeysymToKeycode(win->sys->dpy, key2x(key)),
415                                 mod2x(mod), win->sys->xid, True, GrabModeAsync, GrabModeAsync);
416 }
417
418 void sys_unwatch(win_t *win, Key_t key, mod_t mod)
419 {
420         if (key_mouse0 <= key && key <= key_mouse7)
421                 XUngrabButton(win->sys->dpy, btn2x(key), mod2x(mod), win->sys->xid);
422 }
423
424 win_t *sys_init(void)
425 {
426         Display *dpy;
427         Window   xid;
428         if (!(dpy = XOpenDisplay(NULL)))
429                 error("Unable to get display");
430         if (!(xid = DefaultRootWindow(dpy)))
431                 error("Unable to get root window");
432         atoms[wm_proto]  = XInternAtom(dpy, "WM_PROTOCOLS",  False);
433         atoms[wm_focus]  = XInternAtom(dpy, "WM_TAKE_FOCUS", False);
434         atoms[net_strut] = XInternAtom(dpy, "_NET_WM_STRUT", False);
435         XSelectInput(dpy, xid, SubstructureRedirectMask|SubstructureNotifyMask);
436         XSetInputFocus(dpy, None, RevertToNone, CurrentTime);
437         xerrorxlib = XSetErrorHandler(xerror);
438         return win_find(dpy, xid, 1);
439 }
440
441 void sys_run(win_t *root)
442 {
443         /* Add each initial window */
444         unsigned int nkids;
445         Window par, xid, *kids = NULL;
446         if (XQueryTree(root->sys->dpy, root->sys->xid,
447                                 &par, &xid, &kids, &nkids))
448                 for(int i = 0; i < nkids; i++) {
449                         win_t *win = win_find(root->sys->dpy, kids[i], 1);
450                         if (win && win_viewable(win) && !add_strut(root,win))
451                                 wm_insert(win);
452                 }
453         wm_update(); // For struts
454
455         /* Main loop */
456         for(;;)
457         {
458                 XEvent ev;
459                 XNextEvent(root->sys->dpy, &ev);
460                 process_event(ev.type, &ev, root);
461         }
462 }