]> Pileus Git - wmpus/blob - sys-x11.c
Add floating layer
[wmpus] / sys-x11.c
1 /*
2  * Copyright (C) 2011 Andy Spencer <andy753421@gmail.com>
3  * 
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  * 
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  * 
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <search.h>
21
22 #include <X11/Xlib.h>
23 #include <X11/Xproto.h>
24 #include <X11/Xatom.h>
25 #include <X11/keysym.h>
26 #include <X11/extensions/Xinerama.h>
27
28 #include "util.h"
29 #include "sys.h"
30 #include "wm.h"
31
32 #ifndef BORDER
33 #define BORDER 2
34 #endif
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         Key_t key;
48         int   sym;
49 } keymap_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 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_remove(win_t *win)
247 {
248         tdelete(win, &cache, win_cmp);
249         free(win->sys);
250         free(win);
251 }
252
253 static int win_viewable(win_t *win)
254 {
255         XWindowAttributes attr;
256         if (XGetWindowAttributes(win->sys->dpy, win->sys->xid, &attr))
257                 return attr.map_state == IsViewable;
258         else
259                 return True;
260 }
261
262 /* Drawing functions */
263 static unsigned long get_color(Display *dpy, const char *name)
264 {
265         XColor color;
266         int screen = DefaultScreen(dpy);
267         Colormap cmap = DefaultColormap(dpy, screen);
268         XAllocNamedColor(dpy, cmap, name, &color, &color);
269         return color.pixel;
270 }
271
272 /* Callbacks */
273 static void process_event(int type, XEvent *ev, win_t *root)
274 {
275         Display  *dpy = root->sys->dpy;
276         win_t *win = NULL;
277         //printf("event: %d\n", type);
278
279         /* Common data for all these events ... */
280         ptr_t ptr; mod_t mod;
281         if (type == KeyPress    || type == KeyRelease    ||
282             type == ButtonPress || type == ButtonRelease ||
283             type == MotionNotify) {
284                 Window xid = getfocus(root, ev);
285                 if (!(win = win_find(dpy,xid,0)))
286                         return;
287                 ptr = x2ptr(ev);
288                 mod = x2mod(ev->xkey.state, type==KeyRelease||type==ButtonRelease);
289         }
290
291         /* Split based on event */
292         if (type == KeyPress) {
293                 while (XCheckTypedEvent(dpy, KeyPress, ev));
294                 KeySym sym = XKeycodeToKeysym(dpy, ev->xkey.keycode, 0);
295                 printf("got key %c %hhx\n", x2key(sym), mod2int(mod));
296                 wm_handle_key(win, x2key(sym), mod, ptr);
297         }
298         else if (type == KeyRelease) {
299                 //printf("release: %d\n", type);
300         }
301         else if (type == ButtonPress) {
302                 if (wm_handle_key(win, x2btn(ev->xbutton.button), mod, ptr))
303                         XGrabPointer(dpy, ev->xbutton.root, True, PointerMotionMask|ButtonReleaseMask,
304                                         GrabModeAsync, GrabModeAsync, None, None, CurrentTime);
305                 else {
306                         printf("resending event\n");
307                         XSendEvent(win->sys->dpy, ev->xbutton.window,    True,  NoEventMask, ev);
308                         XSendEvent(win->sys->dpy, ev->xbutton.window,    False, NoEventMask, ev);
309                         XSendEvent(win->sys->dpy, ev->xbutton.root,      True,  NoEventMask, ev);
310                         XSendEvent(win->sys->dpy, ev->xbutton.root,      False, NoEventMask, ev);
311                         XSendEvent(win->sys->dpy, ev->xbutton.subwindow, True,  NoEventMask, ev);
312                         XSendEvent(win->sys->dpy, ev->xbutton.subwindow, False, NoEventMask, ev);
313                 }
314         }
315         else if (type == ButtonRelease) {
316                 XUngrabPointer(dpy, CurrentTime);
317                 wm_handle_key(win, x2btn(ev->xbutton.button), mod, ptr);
318         }
319         else if (type == MotionNotify) {
320                 while (XCheckTypedEvent(dpy, MotionNotify, ev));
321                 wm_handle_ptr(win, ptr);
322         }
323         else if (type == EnterNotify || type == LeaveNotify) {
324                 printf("enter: %d\n", type);
325                 key_t key = EnterNotify ? key_enter : key_leave;
326                 if ((win = win_find(dpy,ev->xcrossing.window,0)))
327                         wm_handle_key(win, key, MOD(), PTR());
328         }
329         else if (type == FocusIn || type == FocusOut) {
330                 //printf("focus: %d\n", type);
331                 key_t key = FocusIn ? key_focus : key_unfocus;
332                 if ((win = win_find(dpy,ev->xfocus.window,0)))
333                         wm_handle_key(win, key, MOD(), PTR());
334         }
335         else if (type == ConfigureNotify) {
336                 printf("configure: %d\n", type);
337         }
338         else if (type == MapNotify) {
339                 printf("map: %d\n", type);
340         }
341         else if (type == UnmapNotify) {
342                 if ((win = win_find(dpy,ev->xunmap.window,0)) &&
343                      win->sys->state == st_show) {
344                         if (!strut_del(root, win))
345                                 wm_remove(win);
346                         else
347                                 wm_update();
348                         win->sys->state = st_hide;
349                 }
350         }
351         else if (type == DestroyNotify) {
352                 //printf("destroy: %d\n", type);
353                 if ((win = win_find(dpy,ev->xdestroywindow.window,0)))
354                         win_remove(win);
355         }
356         else if (type == ConfigureRequest) {
357                 XConfigureRequestEvent *cre = &ev->xconfigurerequest;
358                 printf("configure_req: %d - %x, (0x%lx) %dx%d @ %d,%d\n",
359                                 type, (int)cre->window, cre->value_mask,
360                                 cre->height, cre->width, cre->x, cre->y);
361                 XConfigureWindow(dpy, cre->window, cre->value_mask, &(XWindowChanges){
362                         .x      = cre->x,
363                         .y      = cre->y,
364                         .width  = cre->width,
365                         .height = cre->height,
366                 });
367
368                 /* This seems necessary for, but causes flicker
369                  * there could be a better way to do this */
370                 if ((win = win_find(dpy,ev->xmaprequest.window,0)))
371                         sys_move(win, win->x, win->y, win->w, win->h);
372         }
373         else if (type == MapRequest) {
374                 printf("map_req: %d\n", type);
375                 if ((win = win_find(dpy,ev->xmaprequest.window,1))) {
376                         if (!strut_add(root, win))
377                                 wm_insert(win);
378                         else
379                                 wm_update();
380                 }
381                 XMapWindow(dpy,ev->xmaprequest.window);
382         }
383         else {
384                 printf("unknown event: %d\n", type);
385         }
386 }
387
388 static int xerror(Display *dpy, XErrorEvent *err)
389 {
390         if (err->error_code == BadWindow ||
391             (err->request_code == X_SetInputFocus     && err->error_code == BadMatch   ) ||
392             (err->request_code == X_PolyText8         && err->error_code == BadDrawable) ||
393             (err->request_code == X_PolyFillRectangle && err->error_code == BadDrawable) ||
394             (err->request_code == X_PolySegment       && err->error_code == BadDrawable) ||
395             (err->request_code == X_ConfigureWindow   && err->error_code == BadMatch   ) ||
396             (err->request_code == X_GrabButton        && err->error_code == BadAccess  ) ||
397             (err->request_code == X_GrabKey           && err->error_code == BadAccess  ) ||
398             (err->request_code == X_CopyArea          && err->error_code == BadDrawable))
399                 return 0;
400         return xerrorxlib(dpy, err);
401 }
402
403 /********************
404  * System functions *
405  ********************/
406 void sys_move(win_t *win, int x, int y, int w, int h)
407 {
408         //printf("sys_move: %p - %d,%d  %dx%d\n", win, x, y, w, h);
409         int b = 2*BORDER;
410         win->x = x; win->y = y;
411         win->w = MAX(w,1+b); win->h = MAX(h,1+b);
412         w      = MAX(w-b,1); h      = MAX(h-b,1);
413         XMoveResizeWindow(win->sys->dpy, win->sys->xid, x, y, w, h);
414
415         /* Flush events, so moving window doesn't cause re-focus
416          * There's probably a better way to do this */
417         XEvent ev;
418         XSync(win->sys->dpy, False);
419         while (XCheckMaskEvent(win->sys->dpy, EnterWindowMask|LeaveWindowMask, &ev))
420                 printf("Skipping enter/leave event\n");
421 }
422
423 void sys_raise(win_t *win)
424 {
425         //printf("sys_raise: %p\n", win);
426         XRaiseWindow(win->sys->dpy, win->sys->xid);
427 }
428
429 void sys_focus(win_t *win)
430 {
431         //printf("sys_focus: %p\n", win);
432
433         /* Set border on focused window */
434         static win_t *last = NULL;
435         if (last)
436                 XSetWindowBorder(last->sys->dpy, last->sys->xid, colors[clr_unfocus]);
437         XSetWindowBorder(win->sys->dpy, win->sys->xid, colors[clr_focus]);
438         XSetWindowBorderWidth(win->sys->dpy, win->sys->xid, BORDER);
439         last = win;
440
441         /* Set actual focus */
442         XSetInputFocus(win->sys->dpy, win->sys->xid,
443                         RevertToPointerRoot, CurrentTime);
444         XSendEvent(win->sys->dpy, win->sys->xid, False, NoEventMask, &(XEvent){
445                 .type                 = ClientMessage,
446                 .xclient.window       = win->sys->xid,
447                 .xclient.message_type = atoms[wm_proto],
448                 .xclient.format       = 32,
449                 .xclient.data.l[0]    = atoms[wm_focus],
450                 .xclient.data.l[1]    = CurrentTime,
451         });
452 }
453
454 void sys_show(win_t *win, state_t state)
455 {
456         win->sys->state = state;
457         switch (state) {
458         case st_show:
459                 printf("sys_show: show\n");
460                 XMapWindow(win->sys->dpy, win->sys->xid);
461                 return;
462         case st_full:
463                 printf("sys_show: full\n");
464                 return;
465         case st_shade:
466                 printf("sys_show: shade\n");
467                 return;
468         case st_icon:
469                 printf("sys_show: icon\n");
470                 return;
471         case st_hide:
472                 printf("sys_show: hide\n");
473                 XUnmapWindow(win->sys->dpy, win->sys->xid);
474                 return;
475         }
476 }
477
478 void sys_watch(win_t *win, Key_t key, mod_t mod)
479 {
480         //printf("sys_watch: %p - %x %hhx\n", win, key, mod);
481         XWindowAttributes attr;
482         XGetWindowAttributes(win->sys->dpy, win->sys->xid, &attr);
483         long mask = attr.your_event_mask;
484         if (key_mouse0 <= key && key <= key_mouse7)
485                 XGrabButton(win->sys->dpy, btn2x(key), mod2x(mod), win->sys->xid, False,
486                                 mod.up ? ButtonReleaseMask : ButtonPressMask,
487                                 GrabModeAsync, GrabModeAsync, None, None);
488         else if (key == key_enter)
489                 XSelectInput(win->sys->dpy, win->sys->xid, EnterWindowMask|mask);
490         else if (key == key_leave)
491                 XSelectInput(win->sys->dpy, win->sys->xid, LeaveWindowMask|mask);
492         else if (key == key_focus || key == key_unfocus)
493                 XSelectInput(win->sys->dpy, win->sys->xid, FocusChangeMask|mask);
494         else
495                 XGrabKey(win->sys->dpy, XKeysymToKeycode(win->sys->dpy, key2x(key)),
496                                 mod2x(mod), win->sys->xid, True, GrabModeAsync, GrabModeAsync);
497 }
498
499 void sys_unwatch(win_t *win, Key_t key, mod_t mod)
500 {
501         if (key_mouse0 <= key && key <= key_mouse7)
502                 XUngrabButton(win->sys->dpy, btn2x(key), mod2x(mod), win->sys->xid);
503 }
504
505 list_t *sys_info(win_t *win)
506 {
507         /* Use global copy of screens so we can add struts */
508         if (screens == NULL) {
509                 int n;
510                 XineramaScreenInfo *info = NULL;
511                 if (XineramaIsActive(win->sys->dpy))
512                         info = XineramaQueryScreens(win->sys->dpy, &n);
513                 if (!info) {
514                         win_t *screen = new0(win_t);
515                         *screen = *win;
516                         return list_insert(NULL, screen);
517                 }
518                 for (int i = 0; i < n; i++) {
519                         win_t *screen = new0(win_t);
520                         screen->x = info[i].x_org;
521                         screen->y = info[i].y_org;
522                         screen->w = info[i].width;
523                         screen->h = info[i].height;
524                         screens = list_append(screens, screen);
525                 }
526         }
527         return screens;
528 }
529
530 win_t *sys_init(void)
531 {
532         Display *dpy;
533         Window   xid;
534
535         /* Open the display */
536         if (!(dpy = XOpenDisplay(NULL)))
537                 error("Unable to get display");
538         if (!(xid = DefaultRootWindow(dpy)))
539                 error("Unable to get root window");
540
541         /* Setup X11 data */
542         atoms[wm_proto]  = XInternAtom(dpy, "WM_PROTOCOLS",  False);
543         atoms[wm_focus]  = XInternAtom(dpy, "WM_TAKE_FOCUS", False);
544         atoms[net_strut] = XInternAtom(dpy, "_NET_WM_STRUT", False);
545
546         colors[clr_focus]   = get_color(dpy, "#a0a0ff");
547         colors[clr_unfocus] = get_color(dpy, "#101066");
548         colors[clr_urgent]  = get_color(dpy, "#ff0000");
549         printf("colors = #%06lx #%06lx #%06lx\n", colors[0], colors[1], colors[2]);
550
551         /* Select window management events */
552         XSelectInput(dpy, xid, SubstructureRedirectMask|SubstructureNotifyMask);
553         XSetInputFocus(dpy, None, RevertToNone, CurrentTime);
554         xerrorxlib = XSetErrorHandler(xerror);
555
556         return win_find(dpy, xid, 1);
557 }
558
559 void sys_run(win_t *root)
560 {
561         /* Add each initial window */
562         unsigned int nkids;
563         Window par, xid, *kids = NULL;
564         if (XQueryTree(root->sys->dpy, root->sys->xid,
565                                 &par, &xid, &kids, &nkids))
566                 for(int i = 0; i < nkids; i++) {
567                         win_t *win = win_find(root->sys->dpy, kids[i], 1);
568                         if (win && win_viewable(win) && !strut_add(root,win))
569                                 wm_insert(win);
570                 }
571         wm_update(); // For struts
572
573         /* Main loop */
574         for(;;)
575         {
576                 XEvent ev;
577                 XNextEvent(root->sys->dpy, &ev);
578                 process_event(ev.type, &ev, root);
579         }
580 }