]> Pileus Git - wmpus/blob - sys-x11.c
Fix struts with multi-monitors
[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 #ifndef BORDER
16 #define BORDER 2
17 #endif
18
19 /* Internal structures */
20 struct win_sys {
21         Window   xid;
22         Display *dpy;
23         struct {
24                 int left, right, top, bottom;
25         } strut;
26         state_t  state;
27 };
28
29 typedef struct {
30         Key_t key;
31         int   sym;
32 } keymap_t;
33
34 typedef enum {
35         wm_proto, wm_focus, net_strut, natoms
36 } atom_t;
37
38 typedef enum {
39         clr_focus, clr_unfocus, clr_urgent, ncolors
40 } color_t;
41
42 /* Global data */
43 static void *cache;
44 static Atom atoms[natoms];
45 static int (*xerrorxlib)(Display *, XErrorEvent *);
46 static unsigned long colors[ncolors];
47 static list_t *screens;
48
49 /* Conversion functions */
50 static keymap_t key2sym[] = {
51         {key_left    , XK_Left },
52         {key_right   , XK_Right},
53         {key_up      , XK_Up   },
54         {key_down    , XK_Down },
55         {key_home    , XK_Home },
56         {key_end     , XK_End  },
57         {key_pageup  , XK_Prior},
58         {key_pagedown, XK_Next },
59         {key_f1      , XK_F1   },
60         {key_f2      , XK_F2   },
61         {key_f3      , XK_F3   },
62         {key_f4      , XK_F4   },
63         {key_f5      , XK_F5   },
64         {key_f6      , XK_F6   },
65         {key_f7      , XK_F7   },
66         {key_f8      , XK_F8   },
67         {key_f9      , XK_F9   },
68         {key_f10     , XK_F10  },
69         {key_f11     , XK_F11  },
70         {key_f12     , XK_F12  },
71 };
72
73 /* - Modifiers */
74 static mod_t x2mod(unsigned int state, int up)
75 {
76         return (mod_t){
77                .alt   = !!(state & Mod1Mask   ),
78                .ctrl  = !!(state & ControlMask),
79                .shift = !!(state & ShiftMask  ),
80                .win   = !!(state & Mod4Mask   ),
81                .up    = up,
82         };
83 }
84
85 static unsigned int mod2x(mod_t mod)
86 {
87         return (mod.alt   ? Mod1Mask    : 0)
88              | (mod.ctrl  ? ControlMask : 0)
89              | (mod.shift ? ShiftMask   : 0)
90              | (mod.win   ? Mod4Mask    : 0);
91 }
92
93 /* - Keycodes */
94 static Key_t x2key(KeySym sym)
95 {
96         keymap_t *km = map_getr(key2sym,sym);
97         return km ? km->key : sym;
98 }
99
100 static KeySym key2x(Key_t key)
101 {
102         keymap_t *km = map_get(key2sym,key);
103         return km ? km->sym : key;
104 }
105
106 static Key_t x2btn(int btn)
107 {
108         return btn + key_mouse0;
109 }
110
111 static int btn2x(Key_t key)
112 {
113         return key - key_mouse0;
114 }
115
116 /* - Pointers */
117 static ptr_t x2ptr(XEvent *_ev)
118 {
119         XKeyEvent *ev = &_ev->xkey;
120         return (ptr_t){ev->x, ev->y, ev->x_root, ev->y_root};
121 }
122
123 static Window getfocus(win_t *root, XEvent *event)
124 {
125         int revert;
126         Window focus = PointerRoot;
127         if (event->type == KeyPress || event->type == KeyRelease)
128                 XGetInputFocus(root->sys->dpy, &focus, &revert);
129         if (focus == PointerRoot)
130                 focus = event->xkey.subwindow;
131         if (focus == None)
132                 focus = event->xkey.window;
133         return focus;
134 }
135
136 /* Helpers */
137 static int copy_strut(win_t *to, win_t *from, int scale)
138 {
139         int left   = from->sys->strut.left;
140         int right  = from->sys->strut.right;
141         int top    = from->sys->strut.top;
142         int bottom = from->sys->strut.bottom;
143         if (left == 0 && right == 0 && top == 0 && bottom == 0)
144                 return 0;
145         to->x += scale*(left      );
146         to->y += scale*(top       );
147         to->w -= scale*(left+right);
148         to->h -= scale*(top+bottom);
149         return 1;
150 }
151
152 static int add_strut(win_t *root, win_t *win)
153 {
154         /* Get X11 strut data */
155         Atom ret_type;
156         int ret_size;
157         unsigned long ret_items, bytes_left;
158         unsigned char *xdata;
159         int status = XGetWindowProperty(win->sys->dpy, win->sys->xid,
160                         atoms[net_strut], 0L, 4L, False, XA_CARDINAL,
161                         &ret_type, &ret_size, &ret_items, &bytes_left, &xdata);
162         if (status != Success || ret_size != 32 || ret_items != 4)
163                 return 0;
164
165         win->sys->strut.left   = ((int*)xdata)[0];
166         win->sys->strut.right  = ((int*)xdata)[1];
167         win->sys->strut.top    = ((int*)xdata)[2];
168         win->sys->strut.bottom = ((int*)xdata)[3];
169         for (list_t *cur = screens; cur; cur = cur->next)
170                 copy_strut(cur->data, win, 1);
171         return copy_strut(root, win, 1);
172 }
173
174 static int del_strut(win_t *root, win_t *win)
175 {
176         for (list_t *cur = screens; cur; cur = cur->next)
177                 copy_strut(cur->data, win, -1);
178         return copy_strut(root, win, -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         /* Use global copy of screens so we can add struts */
489         if (screens == NULL) {
490                 int n;
491                 XineramaScreenInfo *info = NULL;
492                 if (XineramaIsActive(win->sys->dpy))
493                         info = XineramaQueryScreens(win->sys->dpy, &n);
494                 if (!info) {
495                         win_t *screen = new0(win_t);
496                         *screen = *win;
497                         return list_insert(NULL, screen);
498                 }
499                 for (int i = 0; i < n; i++) {
500                         win_t *screen = new0(win_t);
501                         screen->x = info[i].x_org;
502                         screen->y = info[i].y_org;
503                         screen->w = info[i].width;
504                         screen->h = info[i].height;
505                         screens = list_append(screens, screen);
506                 }
507         }
508         return screens;
509 }
510
511 win_t *sys_init(void)
512 {
513         Display *dpy;
514         Window   xid;
515
516         /* Open the display */
517         if (!(dpy = XOpenDisplay(NULL)))
518                 error("Unable to get display");
519         if (!(xid = DefaultRootWindow(dpy)))
520                 error("Unable to get root window");
521
522         /* Setup X11 data */
523         atoms[wm_proto]  = XInternAtom(dpy, "WM_PROTOCOLS",  False);
524         atoms[wm_focus]  = XInternAtom(dpy, "WM_TAKE_FOCUS", False);
525         atoms[net_strut] = XInternAtom(dpy, "_NET_WM_STRUT", False);
526
527         colors[clr_focus]   = get_color(dpy, "#a0a0ff");
528         colors[clr_unfocus] = get_color(dpy, "#101066");
529         colors[clr_urgent]  = get_color(dpy, "#ff0000");
530         printf("colors = #%06lx #%06lx #%06lx\n", colors[0], colors[1], colors[2]);
531
532         /* Selec Window Managmenet events */
533         XSelectInput(dpy, xid, SubstructureRedirectMask|SubstructureNotifyMask);
534         XSetInputFocus(dpy, None, RevertToNone, CurrentTime);
535         xerrorxlib = XSetErrorHandler(xerror);
536
537         return win_find(dpy, xid, 1);
538 }
539
540 void sys_run(win_t *root)
541 {
542         /* Add each initial window */
543         unsigned int nkids;
544         Window par, xid, *kids = NULL;
545         if (XQueryTree(root->sys->dpy, root->sys->xid,
546                                 &par, &xid, &kids, &nkids))
547                 for(int i = 0; i < nkids; i++) {
548                         win_t *win = win_find(root->sys->dpy, kids[i], 1);
549                         if (win && win_viewable(win) && !add_strut(root,win))
550                                 wm_insert(win);
551                 }
552         wm_update(); // For struts
553
554         /* Main loop */
555         for(;;)
556         {
557                 XEvent ev;
558                 XNextEvent(root->sys->dpy, &ev);
559                 process_event(ev.type, &ev, root);
560         }
561 }