2 * Copyright (c) 2011-2012, Andy Spencer <andy753421@gmail.com>
4 * Permission to use, copy, modify, and/or distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
22 #include <X11/Xproto.h>
23 #include <X11/Xatom.h>
24 #include <X11/keysym.h>
25 #include <X11/extensions/Xinerama.h>
33 static int border = 2;
34 static int no_capture = 0;
36 /* Internal structures */
41 int left, right, top, bottom;
51 WM_PROTO, WM_FOCUS, WM_DELETE,
52 NET_STATE, NET_FULL, NET_STRUT,
57 CLR_FOCUS, CLR_UNFOCUS, CLR_URGENT, NCOLORS
63 static Atom atoms[NATOMS];
64 static int (*xerrorxlib)(Display *, XErrorEvent *);
65 static unsigned long colors[NCOLORS];
66 static list_t *screens;
67 static list_t *struts;
69 /* Conversion functions */
70 static event_map_t ev2sym[] = {
72 {EV_RIGHT , XK_Right},
77 {EV_PAGEUP , XK_Prior},
78 {EV_PAGEDOWN, XK_Next },
94 static mod_t x2mod(unsigned int state, int up)
97 .alt = !!(state & Mod1Mask ),
98 .ctrl = !!(state & ControlMask),
99 .shift = !!(state & ShiftMask ),
100 .win = !!(state & Mod4Mask ),
105 static unsigned int mod2x(mod_t mod)
107 return (mod.alt ? Mod1Mask : 0)
108 | (mod.ctrl ? ControlMask : 0)
109 | (mod.shift ? ShiftMask : 0)
110 | (mod.win ? Mod4Mask : 0);
114 static event_t xk2ev(KeySym sym)
116 event_map_t *em = map_getr(ev2sym,sym);
117 return em ? em->ev : sym;
120 static KeySym ev2xk(event_t ev)
122 event_map_t *em = map_get(ev2sym,ev);
123 return em ? em->sym : ev;
126 static event_t xb2ev(int btn)
128 return btn + EV_MOUSE0;
131 static int ev2xb(event_t ev)
133 return ev - EV_MOUSE0;
137 static ptr_t x2ptr(XEvent *xe)
139 XKeyEvent *xke = &xe->xkey;
140 return (ptr_t){xke->x, xke->y, xke->x_root, xke->y_root};
143 static Window getfocus(win_t *root, XEvent *xe)
146 Window focus = PointerRoot;
147 if (xe->type == KeyPress || xe->type == KeyRelease)
148 XGetInputFocus(root->sys->dpy, &focus, &revert);
149 if (focus == PointerRoot)
150 focus = xe->xkey.subwindow;
152 focus = xe->xkey.window;
157 * Struts are spaces at the edges of the screen that are used by
158 * toolbars and statusbars such as dzen. */
159 static int strut_copy(win_t *to, win_t *from, int scale)
161 int left = from->sys->strut.left;
162 int right = from->sys->strut.right;
163 int top = from->sys->strut.top;
164 int bottom = from->sys->strut.bottom;
165 if (left == 0 && right == 0 && top == 0 && bottom == 0)
167 to->x += scale*(left );
168 to->y += scale*(top );
169 to->w -= scale*(left+right);
170 to->h -= scale*(top+bottom);
171 to->sys->strut.left += scale*left;
172 to->sys->strut.right += scale*right;
173 to->sys->strut.top += scale*top;
174 to->sys->strut.bottom += scale*bottom;
178 static int strut_add(win_t *root, win_t *win)
180 /* Get X11 strut data */
183 unsigned long ret_items, bytes_left;
184 unsigned char *xdata;
185 int status = XGetWindowProperty(win->sys->dpy, win->sys->xid,
186 atoms[NET_STRUT], 0L, 4L, False, XA_CARDINAL,
187 &ret_type, &ret_size, &ret_items, &bytes_left, &xdata);
188 if (status != Success || ret_size != 32 || ret_items != 4)
191 win->sys->strut.left = ((int*)xdata)[0];
192 win->sys->strut.right = ((int*)xdata)[1];
193 win->sys->strut.top = ((int*)xdata)[2];
194 win->sys->strut.bottom = ((int*)xdata)[3];
195 struts = list_insert(struts, win);
196 for (list_t *cur = screens; cur; cur = cur->next)
197 strut_copy(cur->data, win, 1);
198 return strut_copy(root, win, 1);
201 static int strut_del(win_t *root, win_t *win)
203 list_t *lwin = list_find(struts, win);
205 struts = list_remove(struts, lwin, 0);
206 for (list_t *cur = screens; cur; cur = cur->next)
207 strut_copy(cur->data, win, -1);
208 return strut_copy(root, win, -1);
211 /* Window functions */
212 static win_t *win_new(Display *dpy, Window xid)
214 XWindowAttributes attr;
215 if (XGetWindowAttributes(dpy, xid, &attr))
216 if (attr.override_redirect)
218 win_t *win = new0(win_t);
222 win->h = attr.height;
223 win->sys = new0(win_sys_t);
226 printf("win_new: %p = %p, %d (%d,%d %dx%d)\n",
228 win->x, win->y, win->w, win->h);
232 static int win_cmp(const void *_a, const void *_b)
234 const win_t *a = _a, *b = _b;
235 if (a->sys->dpy < b->sys->dpy) return -1;
236 if (a->sys->dpy > b->sys->dpy) return 1;
237 if (a->sys->xid < b->sys->xid) return -1;
238 if (a->sys->xid > b->sys->xid) return 1;
242 static win_t *win_find(Display *dpy, Window xid, int create)
246 //printf("win_find: %p, %d\n", dpy, (int)xid);
247 win_sys_t sys = {.dpy=dpy, .xid=xid};
248 win_t tmp = {.sys=&sys};
249 win_t **old = NULL, *new = NULL;
250 if ((old = tfind(&tmp, &cache, win_cmp)))
252 if (create && (new = win_new(dpy,xid)))
253 tsearch(new, &cache, win_cmp);
257 static void win_free(win_t *win)
263 static void win_remove(win_t *win)
265 tdelete(win, &cache, win_cmp);
269 static int win_viewable(win_t *win)
271 XWindowAttributes attr;
272 if (XGetWindowAttributes(win->sys->dpy, win->sys->xid, &attr))
273 return attr.map_state == IsViewable;
278 static int win_msg(win_t *win, atom_t msg)
282 if (!XGetWMProtocols(win->sys->dpy, win->sys->xid, &protos, &n))
285 while (!found && n--)
286 found = protos[n] == atoms[msg];
291 XSendEvent(win->sys->dpy, win->sys->xid, False, NoEventMask, &(XEvent){
292 .type = ClientMessage,
293 .xclient.window = win->sys->xid,
294 .xclient.message_type = atoms[WM_PROTO],
295 .xclient.format = 32,
296 .xclient.data.l[0] = atoms[msg],
297 .xclient.data.l[1] = CurrentTime,
302 static Atom win_prop(win_t *win, atom_t prop)
305 unsigned long nitems, bytes;
306 unsigned char *buf = NULL;
307 Atom atom, type = XA_ATOM;
308 if (XGetWindowProperty(win->sys->dpy, win->sys->xid, atoms[prop],
309 0L, sizeof(Atom), False, type, &type, &format, &nitems, &bytes, &buf) || !buf)
316 /* Drawing functions */
317 static unsigned long get_color(Display *dpy, const char *name)
320 int screen = DefaultScreen(dpy);
321 Colormap cmap = DefaultColormap(dpy, screen);
322 XAllocNamedColor(dpy, cmap, name, &color, &color);
327 static void process_event(int type, XEvent *xe, win_t *root)
329 Display *dpy = root->sys->dpy;
331 //printf("event: %d\n", type);
333 /* Common data for all these events ... */
334 ptr_t ptr = {}; mod_t mod = {};
335 if (type == KeyPress || type == KeyRelease ||
336 type == ButtonPress || type == ButtonRelease ||
337 type == MotionNotify) {
338 Window xid = getfocus(root, xe);
339 if (!(win = win_find(dpy,xid,0)))
341 //printf("button-press %p\n", win);
343 mod = x2mod(xe->xkey.state, type==KeyRelease||type==ButtonRelease);
346 /* Split based on event */
347 if (type == KeyPress) {
348 while (XCheckTypedEvent(dpy, KeyPress, xe));
349 KeySym sym = XKeycodeToKeysym(dpy, xe->xkey.keycode, 0);
350 printf("got xe %c %hhx\n", xk2ev(sym), mod2int(mod));
351 wm_handle_event(win, xk2ev(sym), mod, ptr);
353 else if (type == KeyRelease) {
354 //printf("release: %d\n", type);
356 else if (type == ButtonPress) {
357 if (wm_handle_event(win, xb2ev(xe->xbutton.button), mod, ptr)) {
358 //printf("grab pointer\n");
359 XGrabPointer(dpy, xe->xbutton.root, True, PointerMotionMask|ButtonReleaseMask,
360 GrabModeAsync, GrabModeAsync, None, None, CurrentTime);
362 //printf("allow events\n");
363 XAllowEvents(win->sys->dpy, ReplayPointer, xe->xbutton.time);
366 else if (type == ButtonRelease) {
367 XUngrabPointer(dpy, CurrentTime);
368 wm_handle_event(win, xb2ev(xe->xbutton.button), mod, ptr);
370 else if (type == MotionNotify) {
371 while (XCheckTypedEvent(dpy, MotionNotify, xe));
372 wm_handle_ptr(win, ptr);
374 else if (type == EnterNotify || type == LeaveNotify) {
375 printf("%s: %d\n", type==EnterNotify?"enter":"leave", type);
376 event_t ev = type == EnterNotify ? EV_ENTER : EV_LEAVE;
377 if ((win = win_find(dpy,xe->xcrossing.window,0)))
378 wm_handle_event(win, ev, MOD(), PTR());
380 else if (type == FocusIn || type == FocusOut) {
381 //printf("focus: %d\n", type);
382 event_t ev = FocusIn ? EV_FOCUS : EV_UNFOCUS;
383 if ((win = win_find(dpy,xe->xfocus.window,0)))
384 wm_handle_event(win, ev, MOD(), PTR());
386 else if (type == ConfigureNotify) {
387 printf("configure: %d\n", type);
389 else if (type == MapNotify) {
390 printf("map: %d\n", type);
392 else if (type == UnmapNotify) {
393 if ((win = win_find(dpy,xe->xunmap.window,0)) &&
394 win->state != ST_HIDE) {
395 if (!strut_del(root, win))
399 win->state = ST_HIDE;
402 else if (type == DestroyNotify) {
403 //printf("destroy: %d\n", type);
404 if ((win = win_find(dpy,xe->xdestroywindow.window,0)))
407 else if (type == ConfigureRequest) {
408 XConfigureRequestEvent *cre = &xe->xconfigurerequest;
409 printf("configure_req: %d - %x, (0x%lx) %dx%d @ %d,%d\n",
410 type, (int)cre->window, cre->value_mask,
411 cre->height, cre->width, cre->x, cre->y);
412 if ((win = win_find(dpy,xe->xconfigurerequest.window,1))) {
413 XSendEvent(dpy, cre->window, False, StructureNotifyMask, &(XEvent){
414 .xconfigure.type = ConfigureNotify,
415 .xconfigure.display = win->sys->dpy,
416 .xconfigure.event = win->sys->xid,
417 .xconfigure.window = win->sys->xid,
418 .xconfigure.x = win->x,
419 .xconfigure.y = win->y,
420 .xconfigure.width = win->w,
421 .xconfigure.height = win->h,
422 .xconfigure.border_width = border,
424 XSync(win->sys->dpy, False);
427 else if (type == MapRequest) {
428 printf("map_req: %d\n", type);
429 if ((win = win_find(dpy,xe->xmaprequest.window,1)) &&
430 win->state == ST_HIDE) {
431 if (win_prop(win, NET_STATE) == atoms[NET_FULL])
432 win->state = ST_FULL;
433 XSelectInput(win->sys->dpy, win->sys->xid, PropertyChangeMask);
434 if (!strut_add(root, win))
439 sys_show(win, ST_SHOW);
441 else if (type == ClientMessage) {
442 XClientMessageEvent *cme = &xe->xclient;
443 printf("msg: %d - %ld %ld,%ld,%ld,%ld,%ld\n",
444 type, cme->message_type,
445 cme->data.l[0], cme->data.l[1], cme->data.l[2],
446 cme->data.l[3], cme->data.l[4]);
447 if ((win = win_find(dpy,cme->window,0)) &&
448 (cme->message_type == atoms[NET_STATE]) &&
449 (cme->data.l[1] == atoms[NET_FULL] ||
450 cme->data.l[2] == atoms[NET_FULL])) {
451 state_t next = (cme->data.l[0] == 1 || /* _NET_WM_STATE_ADD */
452 (cme->data.l[0] == 2 && /* _NET_WM_STATE_TOGGLE */
453 win->state != ST_FULL)) ? ST_FULL : ST_SHOW;
454 wm_handle_state(win, win->state, next);
458 else if (type == PropertyNotify) {
459 printf("prop: %d - %d\n", type, xe->xproperty.state);
462 printf("unknown event: %d\n", type);
466 static int xerror(Display *dpy, XErrorEvent *err)
468 if (err->error_code == BadWindow ||
469 (err->request_code == X_SetInputFocus && err->error_code == BadMatch ) ||
470 (err->request_code == X_PolyText8 && err->error_code == BadDrawable) ||
471 (err->request_code == X_PolyFillRectangle && err->error_code == BadDrawable) ||
472 (err->request_code == X_PolySegment && err->error_code == BadDrawable) ||
473 (err->request_code == X_ConfigureWindow && err->error_code == BadMatch ) ||
474 (err->request_code == X_GrabButton && err->error_code == BadAccess ) ||
475 (err->request_code == X_GrabKey && err->error_code == BadAccess ) ||
476 (err->request_code == X_CopyArea && err->error_code == BadDrawable))
478 if (err->request_code == X_ChangeWindowAttributes && err->error_code == BadAccess)
479 error("Another window manager is already running");
480 return xerrorxlib(dpy, err);
483 static int xnoerror(Display *dpy, XErrorEvent *err)
489 /********************
491 ********************/
492 void sys_move(win_t *win, int x, int y, int w, int h)
494 //printf("sys_move: %p - %d,%d %dx%d\n", win, x, y, w, h);
496 win->x = x; win->y = y;
497 win->w = MAX(w,1+b); win->h = MAX(h,1+b);
498 w = MAX(w-b,1); h = MAX(h-b,1);
499 XMoveResizeWindow(win->sys->dpy, win->sys->xid, x, y, w, h);
501 /* Flush events, so moving window doesn't cause re-focus
502 * There's probably a better way to do this */
504 XSync(win->sys->dpy, False);
505 while (XCheckMaskEvent(win->sys->dpy, EnterWindowMask|LeaveWindowMask, &xe))
506 printf("Skipping enter/leave event\n");
509 void sys_raise(win_t *win)
511 //printf("sys_raise: %p\n", win);
512 XRaiseWindow(win->sys->dpy, win->sys->xid);
513 for (list_t *cur = struts; cur; cur = cur->next)
514 XRaiseWindow(((win_t*)cur->data)->sys->dpy,
515 ((win_t*)cur->data)->sys->xid);
518 void sys_focus(win_t *win)
520 printf("sys_focus: %p\n", win);
522 /* Set actual focus */
523 XSetInputFocus(win->sys->dpy, win->sys->xid,
524 RevertToPointerRoot, CurrentTime);
525 win_msg(win, WM_FOCUS);
527 /* Set border on focused window */
528 static win_t *last = NULL;
530 XSetWindowBorder(last->sys->dpy, last->sys->xid, colors[CLR_UNFOCUS]);
531 XSync(win->sys->dpy, False);
532 XSetWindowBorder(win->sys->dpy, win->sys->xid, colors[CLR_FOCUS]);
536 void sys_show(win_t *win, state_t state)
540 printf("sys_show: hide %p\n", win);
541 XUnmapWindow(win->sys->dpy, win->sys->xid);
544 printf("sys_show: show %p\n", win);
545 if (win->state == ST_FULL)
546 sys_move(win, win->x, win->y, win->w, win->h);
547 XSetWindowBorderWidth(win->sys->dpy, win->sys->xid, border);
548 XMapWindow(win->sys->dpy, win->sys->xid);
549 XSync(win->sys->dpy, False);
552 printf("sys_show: max %p\n", win);
553 XMapWindow(win->sys->dpy, win->sys->xid);
556 printf("sys_show: full %p\n", win);
557 win_t *screen = NULL;
558 for (list_t *cur = screens; cur; cur = cur->next) {
560 if (win->x >= screen->x && win->x <= screen->x+screen->w &&
561 win->y >= screen->y && win->y <= screen->y+screen->h)
564 XSetWindowBorderWidth(win->sys->dpy, win->sys->xid, 0);
565 XMapWindow(win->sys->dpy, win->sys->xid);
566 XMoveResizeWindow(win->sys->dpy, win->sys->xid,
567 screen->x - screen->sys->strut.left,
568 screen->y - screen->sys->strut.top,
569 screen->w + screen->sys->strut.left + screen->sys->strut.right,
570 screen->h + screen->sys->strut.top + screen->sys->strut.bottom);
571 XRaiseWindow(win->sys->dpy, win->sys->xid);
574 printf("sys_show: shade %p\n", win);
575 XMapWindow(win->sys->dpy, win->sys->xid);
578 printf("sys_show: icon %p\n", win);
581 printf("sys_show: close %p\n", win);
582 if (!win_msg(win, WM_DELETE)) {
583 XGrabServer(win->sys->dpy);
584 XSetErrorHandler(xnoerror);
585 XSetCloseDownMode(win->sys->dpy, DestroyAll);
586 XKillClient(win->sys->dpy, win->sys->xid);
587 XSync(win->sys->dpy, False);
588 XSetErrorHandler(xerror);
589 XUngrabServer(win->sys->dpy);
591 XDestroyWindow(win->sys->dpy, win->sys->xid);
597 void sys_watch(win_t *win, event_t ev, mod_t mod)
599 //printf("sys_watch: %p - %x %hhx\n", win, ev, mod);
600 XWindowAttributes attr;
601 XGetWindowAttributes(win->sys->dpy, win->sys->xid, &attr);
602 long mask = attr.your_event_mask;
603 if (EV_MOUSE0 <= ev && ev <= EV_MOUSE7)
604 XGrabButton(win->sys->dpy, ev2xb(ev), mod2x(mod), win->sys->xid, False,
605 mod.up ? ButtonReleaseMask : ButtonPressMask,
606 GrabModeSync, GrabModeAsync, None, None);
607 else if (ev == EV_ENTER)
608 XSelectInput(win->sys->dpy, win->sys->xid, EnterWindowMask|mask);
609 else if (ev == EV_LEAVE)
610 XSelectInput(win->sys->dpy, win->sys->xid, LeaveWindowMask|mask);
611 else if (ev == EV_FOCUS || ev == EV_UNFOCUS)
612 XSelectInput(win->sys->dpy, win->sys->xid, FocusChangeMask|mask);
614 XGrabKey(win->sys->dpy, XKeysymToKeycode(win->sys->dpy, ev2xk(ev)),
615 mod2x(mod), win->sys->xid, True, GrabModeAsync, GrabModeAsync);
618 void sys_unwatch(win_t *win, event_t ev, mod_t mod)
620 if (EV_MOUSE0 <= ev && ev <= EV_MOUSE7)
621 XUngrabButton(win->sys->dpy, ev2xb(ev), mod2x(mod), win->sys->xid);
624 list_t *sys_info(win_t *win)
626 /* Use global copy of screens so we can add struts */
627 if (screens == NULL) {
628 /* Add Xinerama screens */
630 XineramaScreenInfo *info = NULL;
631 if (XineramaIsActive(win->sys->dpy))
632 info = XineramaQueryScreens(win->sys->dpy, &n);
633 for (int i = 0; i < n; i++) {
634 win_t *screen = new0(win_t);
635 screen->x = info[i].x_org;
636 screen->y = info[i].y_org;
637 screen->w = info[i].width;
638 screen->h = info[i].height;
639 screen->sys = new0(win_sys_t);
640 screens = list_append(screens, screen);
643 if (screens == NULL) {
644 /* No xinerama support */
645 win_t *screen = new0(win_t);
647 screens = list_insert(NULL, screen);
652 win_t *sys_init(void)
657 /* Load configuration */
658 border = conf_get_int("main.border", border);
659 no_capture = conf_get_int("main.no-capture", no_capture);
661 /* Open the display */
662 if (!(dpy = XOpenDisplay(NULL)))
663 error("Unable to get display");
664 if (!(xid = DefaultRootWindow(dpy)))
665 error("Unable to get root window");
668 atoms[WM_PROTO] = XInternAtom(dpy, "WM_PROTOCOLS", False);
669 atoms[WM_FOCUS] = XInternAtom(dpy, "WM_TAKE_FOCUS", False);
670 atoms[WM_DELETE] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
671 atoms[NET_STATE] = XInternAtom(dpy, "_NET_WM_STATE", False);
672 atoms[NET_FULL] = XInternAtom(dpy, "_NET_WM_STATE_FULLSCREEN", False);
673 atoms[NET_STRUT] = XInternAtom(dpy, "_NET_WM_STRUT", False);
675 colors[CLR_FOCUS] = get_color(dpy, "#a0a0ff");
676 colors[CLR_UNFOCUS] = get_color(dpy, "#101066");
677 colors[CLR_URGENT] = get_color(dpy, "#ff0000");
678 //printf("colors = #%06lx #%06lx #%06lx\n", colors[0], colors[1], colors[2]);
680 /* Select window management events */
681 XSelectInput(dpy, xid, SubstructureRedirectMask|SubstructureNotifyMask);
682 xerrorxlib = XSetErrorHandler(xerror);
684 return win_find(dpy, xid, 1);
687 void sys_run(win_t *root)
689 /* Add each initial window */
692 Window par, xid, *kids = NULL;
693 if (XQueryTree(root->sys->dpy, root->sys->xid,
694 &par, &xid, &kids, &nkids)) {
695 for(int i = 0; i < nkids; i++) {
696 win_t *win = win_find(root->sys->dpy, kids[i], 1);
697 if (win && win_viewable(win) && !strut_add(root,win))
702 wm_update(); // For struts
710 XNextEvent(root->sys->dpy, &xe);
711 process_event(xe.type, &xe, root);
720 void sys_free(win_t *root)
722 XCloseDisplay(root->sys->dpy);
724 win_free(screens->data);
725 screens = list_remove(screens, screens, 0);
727 tdestroy(cache, (void(*)(void*))win_free);