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