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;
35 static int stack = 25;
37 /* Internal structures */
42 int left, right, top, bottom;
52 WM_PROTO, WM_FOCUS, WM_DELETE,
53 NET_STATE, NET_FULL, NET_STRUT,
59 CLR_FOCUS, CLR_UNFOCUS, CLR_URGENT, NCOLORS
66 static Atom atoms[NATOMS];
67 static int (*xerrorxlib)(Display *, XErrorEvent *);
68 static unsigned long colors[NCOLORS];
69 static list_t *screens;
70 static list_t *struts;
72 /* Conversion functions */
73 static event_map_t ev2sym[] = {
75 {EV_RIGHT , XK_Right},
80 {EV_PAGEUP , XK_Prior},
81 {EV_PAGEDOWN, XK_Next },
97 static mod_t x2mod(unsigned int state, int up)
100 .alt = !!(state & Mod1Mask ),
101 .ctrl = !!(state & ControlMask),
102 .shift = !!(state & ShiftMask ),
103 .win = !!(state & Mod4Mask ),
108 static unsigned int mod2x(mod_t mod)
110 return (mod.alt ? Mod1Mask : 0)
111 | (mod.ctrl ? ControlMask : 0)
112 | (mod.shift ? ShiftMask : 0)
113 | (mod.win ? Mod4Mask : 0);
117 static event_t xk2ev(KeySym sym)
119 event_map_t *em = map_getr(ev2sym,sym);
120 return em ? em->ev : sym;
123 static KeySym ev2xk(event_t ev)
125 event_map_t *em = map_get(ev2sym,ev);
126 return em ? em->sym : ev;
129 static event_t xb2ev(int btn)
131 return btn + EV_MOUSE0;
134 static int ev2xb(event_t ev)
136 return ev - EV_MOUSE0;
140 static ptr_t x2ptr(XEvent *xe)
142 XKeyEvent *xke = &xe->xkey;
143 return (ptr_t){xke->x, xke->y, xke->x_root, xke->y_root};
146 static Window getfocus(win_t *root, XEvent *xe)
149 Window focus = PointerRoot;
150 if (xe->type == KeyPress || xe->type == KeyRelease)
151 XGetInputFocus(root->sys->dpy, &focus, &revert);
152 if (focus == PointerRoot)
153 focus = xe->xkey.subwindow;
155 focus = xe->xkey.window;
160 * Struts are spaces at the edges of the screen that are used by
161 * toolbars and statusbars such as dzen. */
162 static int strut_copy(win_t *to, win_t *from, int scale)
164 int left = from->sys->strut.left;
165 int right = from->sys->strut.right;
166 int top = from->sys->strut.top;
167 int bottom = from->sys->strut.bottom;
168 if (left == 0 && right == 0 && top == 0 && bottom == 0)
170 to->x += scale*(left );
171 to->y += scale*(top );
172 to->w -= scale*(left+right);
173 to->h -= scale*(top+bottom);
174 to->sys->strut.left += scale*left;
175 to->sys->strut.right += scale*right;
176 to->sys->strut.top += scale*top;
177 to->sys->strut.bottom += scale*bottom;
181 static int strut_add(win_t *root, win_t *win)
183 /* Get X11 strut data */
186 unsigned long ret_items, bytes_left;
187 unsigned char *xdata;
188 int status = XGetWindowProperty(win->sys->dpy, win->sys->xid,
189 atoms[NET_STRUT], 0L, 4L, False, XA_CARDINAL,
190 &ret_type, &ret_size, &ret_items, &bytes_left, &xdata);
191 if (status != Success || ret_size != 32 || ret_items != 4)
194 win->sys->strut.left = ((long*)xdata)[0];
195 win->sys->strut.right = ((long*)xdata)[1];
196 win->sys->strut.top = ((long*)xdata)[2];
197 win->sys->strut.bottom = ((long*)xdata)[3];
198 struts = list_insert(struts, win);
199 for (list_t *cur = screens; cur; cur = cur->next)
200 strut_copy(cur->data, win, 1);
201 return strut_copy(root, win, 1);
204 static int strut_del(win_t *root, win_t *win)
206 list_t *lwin = list_find(struts, win);
208 struts = list_remove(struts, lwin, 0);
209 for (list_t *cur = screens; cur; cur = cur->next)
210 strut_copy(cur->data, win, -1);
211 return strut_copy(root, win, -1);
214 /* Window functions */
215 static Atom win_prop(win_t *win, atom_t prop);
216 static win_t *win_find(Display *dpy, Window xid, int create);
218 static win_t *win_new(Display *dpy, Window xid)
221 XWindowAttributes attr;
222 if (XGetWindowAttributes(dpy, xid, &attr))
223 if (attr.override_redirect)
226 win_t *win = new0(win_t);
230 win->h = attr.height;
231 win->sys = new0(win_sys_t);
236 if (strut_add(root, win))
237 win->type = TYPE_TOOLBAR;
239 if (win_prop(win, NET_TYPE) == atoms[NET_DIALOG])
240 win->type = TYPE_DIALOG;
242 if (win_prop(win, NET_STATE) == atoms[NET_FULL])
243 win->state = ST_FULL;
245 if (XGetTransientForHint(dpy, xid, &trans))
246 win->parent = win_find(dpy, trans, 0);
248 XSelectInput(dpy, xid, PropertyChangeMask);
253 printf("win_new: %p = %p, %d (%d,%d %dx%d) - %s\n",
255 win->x, win->y, win->w, win->h,
256 win->type == TYPE_NORMAL ? "normal" :
257 win->type == TYPE_DIALOG ? "dialog" :
258 win->type == TYPE_TOOLBAR ? "normal" : "unknown");
263 static int win_cmp(const void *_a, const void *_b)
265 const win_t *a = _a, *b = _b;
266 if (a->sys->dpy < b->sys->dpy) return -1;
267 if (a->sys->dpy > b->sys->dpy) return 1;
268 if (a->sys->xid < b->sys->xid) return -1;
269 if (a->sys->xid > b->sys->xid) return 1;
273 static win_t *win_find(Display *dpy, Window xid, int create)
277 //printf("win_find: %p, %d\n", dpy, (int)xid);
278 win_sys_t sys = {.dpy=dpy, .xid=xid};
279 win_t tmp = {.sys=&sys};
280 win_t **old = NULL, *new = NULL;
281 if ((old = tfind(&tmp, &cache, win_cmp)))
283 if (create && (new = win_new(dpy,xid)))
284 tsearch(new, &cache, win_cmp);
288 static void win_free(win_t *win)
294 static void win_remove(win_t *win)
297 strut_del(root, win);
300 tdelete(win, &cache, win_cmp);
304 static int win_viewable(Display *dpy, Window xid)
306 XWindowAttributes attr;
307 if (XGetWindowAttributes(dpy, xid, &attr))
308 return attr.map_state == IsViewable;
313 static int win_msg(win_t *win, atom_t msg)
317 if (!XGetWMProtocols(win->sys->dpy, win->sys->xid, &protos, &n))
320 while (!found && n--)
321 found = protos[n] == atoms[msg];
326 XSendEvent(win->sys->dpy, win->sys->xid, False, NoEventMask, &(XEvent){
327 .type = ClientMessage,
328 .xclient.window = win->sys->xid,
329 .xclient.message_type = atoms[WM_PROTO],
330 .xclient.format = 32,
331 .xclient.data.l[0] = atoms[msg],
332 .xclient.data.l[1] = CurrentTime,
337 static Atom win_prop(win_t *win, atom_t prop)
340 unsigned long nitems, bytes;
341 unsigned char *buf = NULL;
342 Atom atom, type = XA_ATOM;
343 if (XGetWindowProperty(win->sys->dpy, win->sys->xid, atoms[prop],
344 0L, sizeof(Atom), False, type, &type, &format, &nitems, &bytes, &buf) || !buf)
351 /* Drawing functions */
352 static unsigned long get_color(Display *dpy, const char *name)
355 int screen = DefaultScreen(dpy);
356 Colormap cmap = DefaultColormap(dpy, screen);
357 XAllocNamedColor(dpy, cmap, name, &color, &color);
362 static void process_event(int type, XEvent *xe, win_t *root)
364 Display *dpy = root->sys->dpy;
366 //printf("event: %d\n", type);
368 /* Common data for all these events ... */
369 ptr_t ptr = {}; mod_t mod = {};
370 if (type == KeyPress || type == KeyRelease ||
371 type == ButtonPress || type == ButtonRelease ||
372 type == MotionNotify) {
373 Window xid = getfocus(root, xe);
374 if (!(win = win_find(dpy,xid,0)))
376 //printf("button-press %p\n", win);
378 mod = x2mod(xe->xkey.state, type==KeyRelease||type==ButtonRelease);
381 /* Split based on event */
382 if (type == KeyPress) {
383 while (XCheckTypedEvent(dpy, KeyPress, xe));
384 KeySym sym = XLookupKeysym(&xe->xkey, 0);
385 printf("got xe %c %hhx\n", xk2ev(sym), mod2int(mod));
386 wm_handle_event(win, xk2ev(sym), mod, ptr);
388 else if (type == KeyRelease) {
389 //printf("release: %lx\n", xe->xkey.window);
391 else if (type == ButtonPress) {
392 if (wm_handle_event(win, xb2ev(xe->xbutton.button), mod, ptr)) {
393 //printf("grab pointer\n");
394 XGrabPointer(dpy, xe->xbutton.root, True, PointerMotionMask|ButtonReleaseMask,
395 GrabModeAsync, GrabModeAsync, None, None, CurrentTime);
397 //printf("allow events\n");
398 XAllowEvents(win->sys->dpy, ReplayPointer, xe->xbutton.time);
401 else if (type == ButtonRelease) {
402 XUngrabPointer(dpy, CurrentTime);
403 wm_handle_event(win, xb2ev(xe->xbutton.button), mod, ptr);
405 else if (type == MotionNotify) {
406 while (XCheckTypedEvent(dpy, MotionNotify, xe));
407 wm_handle_ptr(win, ptr);
409 else if (type == EnterNotify || type == LeaveNotify) {
410 printf("%s: %lx\n", type==EnterNotify?"enter":"leave",
411 xe->xcrossing.window);
412 event_t ev = type == EnterNotify ? EV_ENTER : EV_LEAVE;
413 if ((win = win_find(dpy,xe->xcrossing.window,0)))
414 wm_handle_event(win, ev, MOD(), PTR());
416 else if (type == FocusIn || type == FocusOut) {
417 //printf("focus: %lx\n", xe->xfocus.window);
418 event_t ev = type == FocusIn ? EV_FOCUS : EV_UNFOCUS;
419 if ((win = win_find(dpy,xe->xfocus.window,0)))
420 wm_handle_event(win, ev, MOD(), PTR());
422 else if (type == ConfigureNotify) {
423 //printf("configure: %lx\n", xe->xconfigure.window);
425 else if (type == MapNotify) {
426 printf("map: %lx\n", xe->xmap.window);
428 else if (type == UnmapNotify) {
429 if ((win = win_find(dpy,xe->xunmap.window,0)) &&
430 win->state != ST_HIDE) {
431 wm_handle_state(win, win->state, ST_HIDE);
432 win->state = ST_HIDE;
435 else if (type == DestroyNotify) {
436 printf("destroy: %lx\n", xe->xdestroywindow.window);
437 if ((win = win_find(dpy,xe->xdestroywindow.window,0)))
440 else if (type == ConfigureRequest) {
441 XConfigureRequestEvent *cre = &xe->xconfigurerequest;
442 printf("configure_req: %lx - (0x%lx) %dx%d @ %d,%d\n",
443 cre->window, cre->value_mask,
444 cre->height, cre->width, cre->x, cre->y);
445 if ((win = win_find(dpy,xe->xconfigurerequest.window,1))) {
446 XSendEvent(dpy, cre->window, False, StructureNotifyMask, &(XEvent){
447 .xconfigure.type = ConfigureNotify,
448 .xconfigure.display = win->sys->dpy,
449 .xconfigure.event = win->sys->xid,
450 .xconfigure.window = win->sys->xid,
451 .xconfigure.x = win->x,
452 .xconfigure.y = win->y,
453 .xconfigure.width = win->w,
454 .xconfigure.height = win->h,
455 .xconfigure.border_width = border,
457 XSync(win->sys->dpy, False);
460 else if (type == MapRequest) {
461 printf("map_req: %lx\n", xe->xmaprequest.window);
462 win = win_find(dpy,xe->xmaprequest.window,1);
463 // fixme, for hide -> max, etc
464 if (win->state == ST_HIDE)
465 win->state = ST_SHOW;
466 sys_show(win, win->state);
468 else if (type == ClientMessage) {
469 XClientMessageEvent *cme = &xe->xclient;
470 printf("client_msg: %lx - %ld %ld,%ld,%ld,%ld,%ld\n",
471 cme->window, cme->message_type,
472 cme->data.l[0], cme->data.l[1], cme->data.l[2],
473 cme->data.l[3], cme->data.l[4]);
474 if ((win = win_find(dpy,cme->window,0)) &&
475 (cme->message_type == atoms[NET_STATE]) &&
476 (cme->data.l[1] == atoms[NET_FULL] ||
477 cme->data.l[2] == atoms[NET_FULL])) {
478 state_t next = (cme->data.l[0] == 1 || /* _NET_WM_STATE_ADD */
479 (cme->data.l[0] == 2 && /* _NET_WM_STATE_TOGGLE */
480 win->state != ST_FULL)) ? ST_FULL : ST_SHOW;
481 wm_handle_state(win, win->state, next);
485 else if (type == PropertyNotify) {
486 printf("prop: %lx - %d\n", xe->xproperty.window, xe->xproperty.state);
489 printf("unknown event: %d\n", type);
493 static int xerror(Display *dpy, XErrorEvent *err)
495 if (err->error_code == BadWindow ||
496 (err->request_code == X_SetInputFocus && err->error_code == BadMatch ) ||
497 (err->request_code == X_PolyText8 && err->error_code == BadDrawable) ||
498 (err->request_code == X_PolyFillRectangle && err->error_code == BadDrawable) ||
499 (err->request_code == X_PolySegment && err->error_code == BadDrawable) ||
500 (err->request_code == X_ConfigureWindow && err->error_code == BadMatch ) ||
501 (err->request_code == X_GrabButton && err->error_code == BadAccess ) ||
502 (err->request_code == X_GrabKey && err->error_code == BadAccess ) ||
503 (err->request_code == X_CopyArea && err->error_code == BadDrawable))
505 if (err->request_code == X_ChangeWindowAttributes && err->error_code == BadAccess)
506 error("Another window manager is already running");
507 return xerrorxlib(dpy, err);
510 static int xnoerror(Display *dpy, XErrorEvent *err)
516 /********************
518 ********************/
519 void sys_move(win_t *win, int x, int y, int w, int h)
521 //printf("sys_move: %p - %d,%d %dx%d\n", win, x, y, w, h);
523 win->x = x; win->y = y;
524 win->w = MAX(w,1+b); win->h = MAX(h,1+b);
525 w = MAX(w-b,1); h = MAX(h-b,1);
526 XMoveResizeWindow(win->sys->dpy, win->sys->xid, x, y, w, h);
528 /* Flush events, so moving window doesn't cause re-focus
529 * There's probably a better way to do this */
531 XSync(win->sys->dpy, False);
532 while (XCheckMaskEvent(win->sys->dpy, EnterWindowMask|LeaveWindowMask, &xe))
533 printf("Skipping enter/leave event\n");
536 void sys_raise(win_t *win)
538 //printf("sys_raise: %p\n", win);
539 XRaiseWindow(win->sys->dpy, win->sys->xid);
540 for (list_t *cur = struts; cur; cur = cur->next)
541 XRaiseWindow(((win_t*)cur->data)->sys->dpy,
542 ((win_t*)cur->data)->sys->xid);
545 void sys_focus(win_t *win)
547 printf("sys_focus: %p\n", win);
549 /* Set actual focus */
550 XSetInputFocus(win->sys->dpy, win->sys->xid,
551 RevertToPointerRoot, CurrentTime);
552 win_msg(win, WM_FOCUS);
554 /* Set border on focused window */
555 static win_t *last = NULL;
557 XSetWindowBorder(last->sys->dpy, last->sys->xid, colors[CLR_UNFOCUS]);
558 XSync(win->sys->dpy, False);
559 XSetWindowBorder(win->sys->dpy, win->sys->xid, colors[CLR_FOCUS]);
563 void sys_show(win_t *win, state_t state)
567 printf("sys_show: hide %p\n", win);
568 XUnmapWindow(win->sys->dpy, win->sys->xid);
571 printf("sys_show: show %p\n", win);
572 if (win->state == ST_FULL)
573 sys_move(win, win->x, win->y, win->w, win->h);
574 XSetWindowBorderWidth(win->sys->dpy, win->sys->xid, border);
575 XMapWindow(win->sys->dpy, win->sys->xid);
576 XSync(win->sys->dpy, False);
579 printf("sys_show: max %p\n", win);
580 XMapWindow(win->sys->dpy, win->sys->xid);
583 printf("sys_show: full %p\n", win);
584 win_t *screen = NULL;
585 for (list_t *cur = screens; cur; cur = cur->next) {
587 if (win->x >= screen->x && win->x <= screen->x+screen->w &&
588 win->y >= screen->y && win->y <= screen->y+screen->h)
591 XSetWindowBorderWidth(win->sys->dpy, win->sys->xid, 0);
592 XMapWindow(win->sys->dpy, win->sys->xid);
593 XMoveResizeWindow(win->sys->dpy, win->sys->xid,
594 screen->x - screen->sys->strut.left,
595 screen->y - screen->sys->strut.top,
596 screen->w + screen->sys->strut.left + screen->sys->strut.right,
597 screen->h + screen->sys->strut.top + screen->sys->strut.bottom);
598 XRaiseWindow(win->sys->dpy, win->sys->xid);
601 printf("sys_show: shade %p\n", win);
602 XConfigureWindow(win->sys->dpy, win->sys->xid, CWHeight,
603 &(XWindowChanges){ .height = stack });
604 XMapWindow(win->sys->dpy, win->sys->xid);
607 printf("sys_show: icon %p\n", win);
610 printf("sys_show: close %p\n", win);
611 if (!win_msg(win, WM_DELETE)) {
612 XGrabServer(win->sys->dpy);
613 XSetErrorHandler(xnoerror);
614 XSetCloseDownMode(win->sys->dpy, DestroyAll);
615 XKillClient(win->sys->dpy, win->sys->xid);
616 XSync(win->sys->dpy, False);
617 XSetErrorHandler(xerror);
618 XUngrabServer(win->sys->dpy);
620 XDestroyWindow(win->sys->dpy, win->sys->xid);
626 void sys_watch(win_t *win, event_t ev, mod_t mod)
628 //printf("sys_watch: %p - %x %hhx\n", win, ev, mod);
629 XWindowAttributes attr;
630 XGetWindowAttributes(win->sys->dpy, win->sys->xid, &attr);
631 long mask = attr.your_event_mask;
632 if (EV_MOUSE0 <= ev && ev <= EV_MOUSE7)
633 XGrabButton(win->sys->dpy, ev2xb(ev), mod2x(mod), win->sys->xid, False,
634 mod.up ? ButtonReleaseMask : ButtonPressMask,
635 GrabModeSync, GrabModeAsync, None, None);
636 else if (ev == EV_ENTER)
637 XSelectInput(win->sys->dpy, win->sys->xid, EnterWindowMask|mask);
638 else if (ev == EV_LEAVE)
639 XSelectInput(win->sys->dpy, win->sys->xid, LeaveWindowMask|mask);
640 else if (ev == EV_FOCUS || ev == EV_UNFOCUS)
641 XSelectInput(win->sys->dpy, win->sys->xid, FocusChangeMask|mask);
643 XGrabKey(win->sys->dpy, XKeysymToKeycode(win->sys->dpy, ev2xk(ev)),
644 mod2x(mod), win->sys->xid, True, GrabModeAsync, GrabModeAsync);
647 void sys_unwatch(win_t *win, event_t ev, mod_t mod)
649 if (EV_MOUSE0 <= ev && ev <= EV_MOUSE7)
650 XUngrabButton(win->sys->dpy, ev2xb(ev), mod2x(mod), win->sys->xid);
653 list_t *sys_info(win_t *win)
655 /* Use global copy of screens so we can add struts */
656 if (screens == NULL) {
657 /* Add Xinerama screens */
659 XineramaScreenInfo *info = NULL;
660 if (XineramaIsActive(win->sys->dpy))
661 info = XineramaQueryScreens(win->sys->dpy, &n);
662 for (int i = 0; i < n; i++) {
663 win_t *screen = new0(win_t);
664 screen->x = info[i].x_org;
665 screen->y = info[i].y_org;
666 screen->w = info[i].width;
667 screen->h = info[i].height;
668 screen->sys = new0(win_sys_t);
669 screens = list_append(screens, screen);
672 if (screens == NULL) {
673 /* No xinerama support */
674 win_t *screen = new0(win_t);
676 screens = list_insert(NULL, screen);
681 win_t *sys_init(void)
686 /* Load configuration */
687 stack = conf_get_int("main.stack", stack);
688 border = conf_get_int("main.border", border);
689 no_capture = conf_get_int("main.no-capture", no_capture);
691 /* Open the display */
692 if (!(dpy = XOpenDisplay(NULL)))
693 error("Unable to get display");
694 if (!(xid = DefaultRootWindow(dpy)))
695 error("Unable to get root window");
698 atoms[WM_PROTO] = XInternAtom(dpy, "WM_PROTOCOLS", False);
699 atoms[WM_FOCUS] = XInternAtom(dpy, "WM_TAKE_FOCUS", False);
700 atoms[WM_DELETE] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
701 atoms[NET_STATE] = XInternAtom(dpy, "_NET_WM_STATE", False);
702 atoms[NET_FULL] = XInternAtom(dpy, "_NET_WM_STATE_FULLSCREEN", False);
703 atoms[NET_STRUT] = XInternAtom(dpy, "_NET_WM_STRUT", False);
704 atoms[NET_TYPE] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE", False);
705 atoms[NET_DIALOG] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE_DIALOG", False);
707 colors[CLR_FOCUS] = get_color(dpy, "#a0a0ff");
708 colors[CLR_UNFOCUS] = get_color(dpy, "#101066");
709 colors[CLR_URGENT] = get_color(dpy, "#ff0000");
710 //printf("colors = #%06lx #%06lx #%06lx\n", colors[0], colors[1], colors[2]);
712 /* Select window management events */
713 XSelectInput(dpy, xid, SubstructureRedirectMask|SubstructureNotifyMask);
714 xerrorxlib = XSetErrorHandler(xerror);
716 return root = win_find(dpy, xid, 1);
719 void sys_run(win_t *root)
721 /* Add each initial window */
724 Window par, xid, *kids = NULL;
725 if (XQueryTree(root->sys->dpy, root->sys->xid,
726 &par, &xid, &kids, &nkids)) {
727 for(int i = 0; i < nkids; i++)
728 if (win_viewable(root->sys->dpy, kids[i]))
729 win_find(root->sys->dpy, kids[i], 1);
739 XNextEvent(root->sys->dpy, &xe);
740 process_event(xe.type, &xe, root);
749 void sys_free(win_t *root)
751 XCloseDisplay(root->sys->dpy);
753 win_free(screens->data);
754 screens = list_remove(screens, screens, 0);
756 tdestroy(cache, (void(*)(void*))win_free);