2 * Copyright (C) 2011 Andy Spencer <andy753421@gmail.com>
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.
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.
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/>.
23 #include <X11/Xproto.h>
24 #include <X11/Xatom.h>
25 #include <X11/keysym.h>
26 #include <X11/extensions/Xinerama.h>
36 /* Internal structures */
41 int left, right, top, bottom;
52 wm_proto, wm_focus, net_strut, natoms
56 clr_focus, clr_unfocus, clr_urgent, ncolors
61 static Atom atoms[natoms];
62 static int (*xerrorxlib)(Display *, XErrorEvent *);
63 static unsigned long colors[ncolors];
64 static list_t *screens;
66 /* Conversion functions */
67 static keymap_t key2sym[] = {
68 {key_left , XK_Left },
69 {key_right , XK_Right},
71 {key_down , XK_Down },
72 {key_home , XK_Home },
74 {key_pageup , XK_Prior},
75 {key_pagedown, XK_Next },
91 static mod_t x2mod(unsigned int state, int up)
94 .alt = !!(state & Mod1Mask ),
95 .ctrl = !!(state & ControlMask),
96 .shift = !!(state & ShiftMask ),
97 .win = !!(state & Mod4Mask ),
102 static unsigned int mod2x(mod_t mod)
104 return (mod.alt ? Mod1Mask : 0)
105 | (mod.ctrl ? ControlMask : 0)
106 | (mod.shift ? ShiftMask : 0)
107 | (mod.win ? Mod4Mask : 0);
111 static Key_t x2key(KeySym sym)
113 keymap_t *km = map_getr(key2sym,sym);
114 return km ? km->key : sym;
117 static KeySym key2x(Key_t key)
119 keymap_t *km = map_get(key2sym,key);
120 return km ? km->sym : key;
123 static Key_t x2btn(int btn)
125 return btn + key_mouse0;
128 static int btn2x(Key_t key)
130 return key - key_mouse0;
134 static ptr_t x2ptr(XEvent *_ev)
136 XKeyEvent *ev = &_ev->xkey;
137 return (ptr_t){ev->x, ev->y, ev->x_root, ev->y_root};
140 static Window getfocus(win_t *root, XEvent *event)
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;
149 focus = event->xkey.window;
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)
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)
164 to->x += scale*(left );
165 to->y += scale*(top );
166 to->w -= scale*(left+right);
167 to->h -= scale*(top+bottom);
171 static int strut_add(win_t *root, win_t *win)
173 /* Get X11 strut data */
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)
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);
193 static int strut_del(win_t *root, win_t *win)
195 for (list_t *cur = screens; cur; cur = cur->next)
196 strut_copy(cur->data, win, -1);
197 return strut_copy(root, win, -1);
200 /* Window functions */
201 static win_t *win_new(Display *dpy, Window xid)
203 XWindowAttributes attr;
204 if (XGetWindowAttributes(dpy, xid, &attr))
205 if (attr.override_redirect)
207 win_t *win = new0(win_t);
211 win->h = attr.height;
212 win->sys = new0(win_sys_t);
215 printf("win_new: %p = %p, %d (%d,%d %dx%d)\n",
217 win->x, win->y, win->w, win->h);
221 static int win_cmp(const void *_a, const void *_b)
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;
231 static win_t *win_find(Display *dpy, Window xid, int create)
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)))
241 if (create && (new = win_new(dpy,xid)))
242 tsearch(new, &cache, win_cmp);
246 static void win_remove(win_t *win)
248 tdelete(win, &cache, win_cmp);
253 static int win_viewable(win_t *win)
255 XWindowAttributes attr;
256 if (XGetWindowAttributes(win->sys->dpy, win->sys->xid, &attr))
257 return attr.map_state == IsViewable;
262 /* Drawing functions */
263 static unsigned long get_color(Display *dpy, const char *name)
266 int screen = DefaultScreen(dpy);
267 Colormap cmap = DefaultColormap(dpy, screen);
268 XAllocNamedColor(dpy, cmap, name, &color, &color);
273 static void process_event(int type, XEvent *ev, win_t *root)
275 Display *dpy = root->sys->dpy;
277 //printf("event: %d\n", type);
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)))
288 mod = x2mod(ev->xkey.state, type==KeyRelease||type==ButtonRelease);
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);
298 else if (type == KeyRelease) {
299 //printf("release: %d\n", type);
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);
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);
315 else if (type == ButtonRelease) {
316 XUngrabPointer(dpy, CurrentTime);
317 wm_handle_key(win, x2btn(ev->xbutton.button), mod, ptr);
319 else if (type == MotionNotify) {
320 while (XCheckTypedEvent(dpy, MotionNotify, ev));
321 wm_handle_ptr(win, ptr);
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());
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());
335 else if (type == ConfigureNotify) {
336 printf("configure: %d\n", type);
338 else if (type == MapNotify) {
339 printf("map: %d\n", type);
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))
348 win->sys->state = st_hide;
351 else if (type == DestroyNotify) {
352 //printf("destroy: %d\n", type);
353 if ((win = win_find(dpy,ev->xdestroywindow.window,0)))
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){
365 .height = cre->height,
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);
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))
381 XMapWindow(dpy,ev->xmaprequest.window);
384 printf("unknown event: %d\n", type);
388 static int xerror(Display *dpy, XErrorEvent *err)
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))
400 return xerrorxlib(dpy, err);
403 /********************
405 ********************/
406 void sys_move(win_t *win, int x, int y, int w, int h)
408 //printf("sys_move: %p - %d,%d %dx%d\n", win, x, y, w, h);
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);
415 /* Flush events, so moving window doesn't cause re-focus
416 * There's probably a better way to do this */
418 XSync(win->sys->dpy, False);
419 while (XCheckMaskEvent(win->sys->dpy, EnterWindowMask|LeaveWindowMask, &ev))
420 printf("Skipping enter/leave event\n");
423 void sys_raise(win_t *win)
425 //printf("sys_raise: %p\n", win);
426 XRaiseWindow(win->sys->dpy, win->sys->xid);
429 void sys_focus(win_t *win)
431 //printf("sys_focus: %p\n", win);
433 /* Set border on focused window */
434 static win_t *last = NULL;
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);
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,
454 void sys_show(win_t *win, state_t state)
456 win->sys->state = state;
459 printf("sys_show: show\n");
460 XMapWindow(win->sys->dpy, win->sys->xid);
463 printf("sys_show: full\n");
466 printf("sys_show: shade\n");
469 printf("sys_show: icon\n");
472 printf("sys_show: hide\n");
473 XUnmapWindow(win->sys->dpy, win->sys->xid);
478 void sys_watch(win_t *win, Key_t key, mod_t mod)
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);
495 XGrabKey(win->sys->dpy, XKeysymToKeycode(win->sys->dpy, key2x(key)),
496 mod2x(mod), win->sys->xid, True, GrabModeAsync, GrabModeAsync);
499 void sys_unwatch(win_t *win, Key_t key, mod_t mod)
501 if (key_mouse0 <= key && key <= key_mouse7)
502 XUngrabButton(win->sys->dpy, btn2x(key), mod2x(mod), win->sys->xid);
505 list_t *sys_info(win_t *win)
507 /* Use global copy of screens so we can add struts */
508 if (screens == NULL) {
510 XineramaScreenInfo *info = NULL;
511 if (XineramaIsActive(win->sys->dpy))
512 info = XineramaQueryScreens(win->sys->dpy, &n);
514 win_t *screen = new0(win_t);
516 return list_insert(NULL, screen);
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);
530 win_t *sys_init(void)
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");
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);
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]);
551 /* Select window management events */
552 XSelectInput(dpy, xid, SubstructureRedirectMask|SubstructureNotifyMask);
553 XSetInputFocus(dpy, None, RevertToNone, CurrentTime);
554 xerrorxlib = XSetErrorHandler(xerror);
556 return win_find(dpy, xid, 1);
559 void sys_run(win_t *root)
561 /* Add each initial window */
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))
571 wm_update(); // For struts
577 XNextEvent(root->sys->dpy, &ev);
578 process_event(ev.type, &ev, root);