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
65 static Atom atoms[NATOMS];
66 static int (*xerrorxlib)(Display *, XErrorEvent *);
67 static unsigned long colors[NCOLORS];
68 static list_t *screens;
69 static list_t *struts;
71 /* Conversion functions */
72 static event_map_t ev2sym[] = {
74 {EV_RIGHT , XK_Right},
79 {EV_PAGEUP , XK_Prior},
80 {EV_PAGEDOWN, XK_Next },
96 static mod_t x2mod(unsigned int state, int up)
99 .alt = !!(state & Mod1Mask ),
100 .ctrl = !!(state & ControlMask),
101 .shift = !!(state & ShiftMask ),
102 .win = !!(state & Mod4Mask ),
107 static unsigned int mod2x(mod_t mod)
109 return (mod.alt ? Mod1Mask : 0)
110 | (mod.ctrl ? ControlMask : 0)
111 | (mod.shift ? ShiftMask : 0)
112 | (mod.win ? Mod4Mask : 0);
116 static event_t xk2ev(KeySym sym)
118 event_map_t *em = map_getr(ev2sym,sym);
119 return em ? em->ev : sym;
122 static KeySym ev2xk(event_t ev)
124 event_map_t *em = map_get(ev2sym,ev);
125 return em ? em->sym : ev;
128 static event_t xb2ev(int btn)
130 return btn + EV_MOUSE0;
133 static int ev2xb(event_t ev)
135 return ev - EV_MOUSE0;
139 static ptr_t x2ptr(XEvent *xe)
141 XKeyEvent *xke = &xe->xkey;
142 return (ptr_t){xke->x, xke->y, xke->x_root, xke->y_root};
145 static Window getfocus(win_t *root, XEvent *xe)
148 Window focus = PointerRoot;
149 if (xe->type == KeyPress || xe->type == KeyRelease)
150 XGetInputFocus(root->sys->dpy, &focus, &revert);
151 if (focus == PointerRoot)
152 focus = xe->xkey.subwindow;
154 focus = xe->xkey.window;
159 * Struts are spaces at the edges of the screen that are used by
160 * toolbars and statusbars such as dzen. */
161 static int strut_copy(win_t *to, win_t *from, int scale)
163 int left = from->sys->strut.left;
164 int right = from->sys->strut.right;
165 int top = from->sys->strut.top;
166 int bottom = from->sys->strut.bottom;
167 if (left == 0 && right == 0 && top == 0 && bottom == 0)
169 to->x += scale*(left );
170 to->y += scale*(top );
171 to->w -= scale*(left+right);
172 to->h -= scale*(top+bottom);
173 to->sys->strut.left += scale*left;
174 to->sys->strut.right += scale*right;
175 to->sys->strut.top += scale*top;
176 to->sys->strut.bottom += scale*bottom;
180 static int strut_add(win_t *root, win_t *win)
182 /* Get X11 strut data */
185 unsigned long ret_items, bytes_left;
186 unsigned char *xdata;
187 int status = XGetWindowProperty(win->sys->dpy, win->sys->xid,
188 atoms[NET_STRUT], 0L, 4L, False, XA_CARDINAL,
189 &ret_type, &ret_size, &ret_items, &bytes_left, &xdata);
190 if (status != Success || ret_size != 32 || ret_items != 4)
193 win->sys->strut.left = ((long*)xdata)[0];
194 win->sys->strut.right = ((long*)xdata)[1];
195 win->sys->strut.top = ((long*)xdata)[2];
196 win->sys->strut.bottom = ((long*)xdata)[3];
197 struts = list_insert(struts, win);
198 for (list_t *cur = screens; cur; cur = cur->next)
199 strut_copy(cur->data, win, 1);
200 return strut_copy(root, win, 1);
203 static int strut_del(win_t *root, win_t *win)
205 list_t *lwin = list_find(struts, win);
207 struts = list_remove(struts, lwin, 0);
208 for (list_t *cur = screens; cur; cur = cur->next)
209 strut_copy(cur->data, win, -1);
210 return strut_copy(root, win, -1);
213 /* Window functions */
214 static Atom win_prop(win_t *win, atom_t prop);
215 static win_t *win_find(Display *dpy, Window xid, int create);
217 static win_t *win_new(Display *dpy, Window xid)
220 XWindowAttributes attr;
221 if (XGetWindowAttributes(dpy, xid, &attr))
222 if (attr.override_redirect)
224 win_t *win = new0(win_t);
228 win->h = attr.height;
229 win->sys = new0(win_sys_t);
232 if (win_prop(win, NET_TYPE) == atoms[NET_DIALOG])
233 win->type = TYPE_DIALOG;
234 if (XGetTransientForHint(dpy, xid, &trans))
235 win->parent = win_find(dpy, trans, 0);
236 printf("win_new: %p = %p, %d (%d,%d %dx%d) - %s\n",
238 win->x, win->y, win->w, win->h,
239 win->type ? "dialog" : "normal");
243 static int win_cmp(const void *_a, const void *_b)
245 const win_t *a = _a, *b = _b;
246 if (a->sys->dpy < b->sys->dpy) return -1;
247 if (a->sys->dpy > b->sys->dpy) return 1;
248 if (a->sys->xid < b->sys->xid) return -1;
249 if (a->sys->xid > b->sys->xid) return 1;
253 static win_t *win_find(Display *dpy, Window xid, int create)
257 //printf("win_find: %p, %d\n", dpy, (int)xid);
258 win_sys_t sys = {.dpy=dpy, .xid=xid};
259 win_t tmp = {.sys=&sys};
260 win_t **old = NULL, *new = NULL;
261 if ((old = tfind(&tmp, &cache, win_cmp)))
263 if (create && (new = win_new(dpy,xid)))
264 tsearch(new, &cache, win_cmp);
268 static void win_free(win_t *win)
274 static void win_remove(win_t *win)
276 tdelete(win, &cache, win_cmp);
280 static int win_viewable(win_t *win)
282 XWindowAttributes attr;
283 if (XGetWindowAttributes(win->sys->dpy, win->sys->xid, &attr))
284 return attr.map_state == IsViewable;
289 static int win_msg(win_t *win, atom_t msg)
293 if (!XGetWMProtocols(win->sys->dpy, win->sys->xid, &protos, &n))
296 while (!found && n--)
297 found = protos[n] == atoms[msg];
302 XSendEvent(win->sys->dpy, win->sys->xid, False, NoEventMask, &(XEvent){
303 .type = ClientMessage,
304 .xclient.window = win->sys->xid,
305 .xclient.message_type = atoms[WM_PROTO],
306 .xclient.format = 32,
307 .xclient.data.l[0] = atoms[msg],
308 .xclient.data.l[1] = CurrentTime,
313 static Atom win_prop(win_t *win, atom_t prop)
316 unsigned long nitems, bytes;
317 unsigned char *buf = NULL;
318 Atom atom, type = XA_ATOM;
319 if (XGetWindowProperty(win->sys->dpy, win->sys->xid, atoms[prop],
320 0L, sizeof(Atom), False, type, &type, &format, &nitems, &bytes, &buf) || !buf)
327 /* Drawing functions */
328 static unsigned long get_color(Display *dpy, const char *name)
331 int screen = DefaultScreen(dpy);
332 Colormap cmap = DefaultColormap(dpy, screen);
333 XAllocNamedColor(dpy, cmap, name, &color, &color);
338 static void process_event(int type, XEvent *xe, win_t *root)
340 Display *dpy = root->sys->dpy;
342 //printf("event: %d\n", type);
344 /* Common data for all these events ... */
345 ptr_t ptr = {}; mod_t mod = {};
346 if (type == KeyPress || type == KeyRelease ||
347 type == ButtonPress || type == ButtonRelease ||
348 type == MotionNotify) {
349 Window xid = getfocus(root, xe);
350 if (!(win = win_find(dpy,xid,0)))
352 //printf("button-press %p\n", win);
354 mod = x2mod(xe->xkey.state, type==KeyRelease||type==ButtonRelease);
357 /* Split based on event */
358 if (type == KeyPress) {
359 while (XCheckTypedEvent(dpy, KeyPress, xe));
360 KeySym sym = XLookupKeysym(&xe->xkey, 0);
361 printf("got xe %c %hhx\n", xk2ev(sym), mod2int(mod));
362 wm_handle_event(win, xk2ev(sym), mod, ptr);
364 else if (type == KeyRelease) {
365 //printf("release: %lx\n", xe->xkey.window);
367 else if (type == ButtonPress) {
368 if (wm_handle_event(win, xb2ev(xe->xbutton.button), mod, ptr)) {
369 //printf("grab pointer\n");
370 XGrabPointer(dpy, xe->xbutton.root, True, PointerMotionMask|ButtonReleaseMask,
371 GrabModeAsync, GrabModeAsync, None, None, CurrentTime);
373 //printf("allow events\n");
374 XAllowEvents(win->sys->dpy, ReplayPointer, xe->xbutton.time);
377 else if (type == ButtonRelease) {
378 XUngrabPointer(dpy, CurrentTime);
379 wm_handle_event(win, xb2ev(xe->xbutton.button), mod, ptr);
381 else if (type == MotionNotify) {
382 while (XCheckTypedEvent(dpy, MotionNotify, xe));
383 wm_handle_ptr(win, ptr);
385 else if (type == EnterNotify || type == LeaveNotify) {
386 printf("%s: %lx\n", type==EnterNotify?"enter":"leave",
387 xe->xcrossing.window);
388 event_t ev = type == EnterNotify ? EV_ENTER : EV_LEAVE;
389 if ((win = win_find(dpy,xe->xcrossing.window,0)))
390 wm_handle_event(win, ev, MOD(), PTR());
392 else if (type == FocusIn || type == FocusOut) {
393 //printf("focus: %lx\n", xe->xfocus.window);
394 event_t ev = FocusIn ? EV_FOCUS : EV_UNFOCUS;
395 if ((win = win_find(dpy,xe->xfocus.window,0)))
396 wm_handle_event(win, ev, MOD(), PTR());
398 else if (type == ConfigureNotify) {
399 printf("configure: %lx\n", xe->xconfigure.window);
401 else if (type == MapNotify) {
402 printf("map: %lx\n", xe->xmap.window);
404 else if (type == UnmapNotify) {
405 if ((win = win_find(dpy,xe->xunmap.window,0)) &&
406 win->state != ST_HIDE) {
407 if (!strut_del(root, win))
411 win->state = ST_HIDE;
414 else if (type == DestroyNotify) {
415 //printf("destroy: %lx\n", xe->xdestroywindow.window);
416 if ((win = win_find(dpy,xe->xdestroywindow.window,0)))
419 else if (type == ConfigureRequest) {
420 XConfigureRequestEvent *cre = &xe->xconfigurerequest;
421 printf("configure_req: %lx - (0x%lx) %dx%d @ %d,%d\n",
422 cre->window, cre->value_mask,
423 cre->height, cre->width, cre->x, cre->y);
424 if ((win = win_find(dpy,xe->xconfigurerequest.window,1))) {
425 XSendEvent(dpy, cre->window, False, StructureNotifyMask, &(XEvent){
426 .xconfigure.type = ConfigureNotify,
427 .xconfigure.display = win->sys->dpy,
428 .xconfigure.event = win->sys->xid,
429 .xconfigure.window = win->sys->xid,
430 .xconfigure.x = win->x,
431 .xconfigure.y = win->y,
432 .xconfigure.width = win->w,
433 .xconfigure.height = win->h,
434 .xconfigure.border_width = border,
436 XSync(win->sys->dpy, False);
439 else if (type == MapRequest) {
440 printf("map_req: %lx\n", xe->xmaprequest.window);
441 if ((win = win_find(dpy,xe->xmaprequest.window,1)) &&
442 win->state == ST_HIDE) {
443 win->state = ST_SHOW;
444 if (win_prop(win, NET_STATE) == atoms[NET_FULL])
445 win->state = ST_FULL;
446 XSelectInput(win->sys->dpy, win->sys->xid, PropertyChangeMask);
447 if (!strut_add(root, win))
452 sys_show(win, win->state);
454 else if (type == ClientMessage) {
455 XClientMessageEvent *cme = &xe->xclient;
456 printf("client_msg: %lx - %ld %ld,%ld,%ld,%ld,%ld\n",
457 cme->window, cme->message_type,
458 cme->data.l[0], cme->data.l[1], cme->data.l[2],
459 cme->data.l[3], cme->data.l[4]);
460 if ((win = win_find(dpy,cme->window,0)) &&
461 (cme->message_type == atoms[NET_STATE]) &&
462 (cme->data.l[1] == atoms[NET_FULL] ||
463 cme->data.l[2] == atoms[NET_FULL])) {
464 state_t next = (cme->data.l[0] == 1 || /* _NET_WM_STATE_ADD */
465 (cme->data.l[0] == 2 && /* _NET_WM_STATE_TOGGLE */
466 win->state != ST_FULL)) ? ST_FULL : ST_SHOW;
467 wm_handle_state(win, win->state, next);
471 else if (type == PropertyNotify) {
472 printf("prop: %d\n", xe->xproperty.state);
475 printf("unknown event: %d\n", type);
479 static int xerror(Display *dpy, XErrorEvent *err)
481 if (err->error_code == BadWindow ||
482 (err->request_code == X_SetInputFocus && err->error_code == BadMatch ) ||
483 (err->request_code == X_PolyText8 && err->error_code == BadDrawable) ||
484 (err->request_code == X_PolyFillRectangle && err->error_code == BadDrawable) ||
485 (err->request_code == X_PolySegment && err->error_code == BadDrawable) ||
486 (err->request_code == X_ConfigureWindow && err->error_code == BadMatch ) ||
487 (err->request_code == X_GrabButton && err->error_code == BadAccess ) ||
488 (err->request_code == X_GrabKey && err->error_code == BadAccess ) ||
489 (err->request_code == X_CopyArea && err->error_code == BadDrawable))
491 if (err->request_code == X_ChangeWindowAttributes && err->error_code == BadAccess)
492 error("Another window manager is already running");
493 return xerrorxlib(dpy, err);
496 static int xnoerror(Display *dpy, XErrorEvent *err)
502 /********************
504 ********************/
505 void sys_move(win_t *win, int x, int y, int w, int h)
507 //printf("sys_move: %p - %d,%d %dx%d\n", win, x, y, w, h);
509 win->x = x; win->y = y;
510 win->w = MAX(w,1+b); win->h = MAX(h,1+b);
511 w = MAX(w-b,1); h = MAX(h-b,1);
512 XMoveResizeWindow(win->sys->dpy, win->sys->xid, x, y, w, h);
514 /* Flush events, so moving window doesn't cause re-focus
515 * There's probably a better way to do this */
517 XSync(win->sys->dpy, False);
518 while (XCheckMaskEvent(win->sys->dpy, EnterWindowMask|LeaveWindowMask, &xe))
519 printf("Skipping enter/leave event\n");
522 void sys_raise(win_t *win)
524 //printf("sys_raise: %p\n", win);
525 XRaiseWindow(win->sys->dpy, win->sys->xid);
526 for (list_t *cur = struts; cur; cur = cur->next)
527 XRaiseWindow(((win_t*)cur->data)->sys->dpy,
528 ((win_t*)cur->data)->sys->xid);
531 void sys_focus(win_t *win)
533 printf("sys_focus: %p\n", win);
535 /* Set actual focus */
536 XSetInputFocus(win->sys->dpy, win->sys->xid,
537 RevertToPointerRoot, CurrentTime);
538 win_msg(win, WM_FOCUS);
540 /* Set border on focused window */
541 static win_t *last = NULL;
543 XSetWindowBorder(last->sys->dpy, last->sys->xid, colors[CLR_UNFOCUS]);
544 XSync(win->sys->dpy, False);
545 XSetWindowBorder(win->sys->dpy, win->sys->xid, colors[CLR_FOCUS]);
549 void sys_show(win_t *win, state_t state)
553 printf("sys_show: hide %p\n", win);
554 XUnmapWindow(win->sys->dpy, win->sys->xid);
557 printf("sys_show: show %p\n", win);
558 if (win->state == ST_FULL)
559 sys_move(win, win->x, win->y, win->w, win->h);
560 XSetWindowBorderWidth(win->sys->dpy, win->sys->xid, border);
561 XMapWindow(win->sys->dpy, win->sys->xid);
562 XSync(win->sys->dpy, False);
565 printf("sys_show: max %p\n", win);
566 XMapWindow(win->sys->dpy, win->sys->xid);
569 printf("sys_show: full %p\n", win);
570 win_t *screen = NULL;
571 for (list_t *cur = screens; cur; cur = cur->next) {
573 if (win->x >= screen->x && win->x <= screen->x+screen->w &&
574 win->y >= screen->y && win->y <= screen->y+screen->h)
577 XSetWindowBorderWidth(win->sys->dpy, win->sys->xid, 0);
578 XMapWindow(win->sys->dpy, win->sys->xid);
579 XMoveResizeWindow(win->sys->dpy, win->sys->xid,
580 screen->x - screen->sys->strut.left,
581 screen->y - screen->sys->strut.top,
582 screen->w + screen->sys->strut.left + screen->sys->strut.right,
583 screen->h + screen->sys->strut.top + screen->sys->strut.bottom);
584 XRaiseWindow(win->sys->dpy, win->sys->xid);
587 printf("sys_show: shade %p\n", win);
588 XConfigureWindow(win->sys->dpy, win->sys->xid, CWHeight,
589 &(XWindowChanges){ .height = stack });
590 XMapWindow(win->sys->dpy, win->sys->xid);
593 printf("sys_show: icon %p\n", win);
596 printf("sys_show: close %p\n", win);
597 if (!win_msg(win, WM_DELETE)) {
598 XGrabServer(win->sys->dpy);
599 XSetErrorHandler(xnoerror);
600 XSetCloseDownMode(win->sys->dpy, DestroyAll);
601 XKillClient(win->sys->dpy, win->sys->xid);
602 XSync(win->sys->dpy, False);
603 XSetErrorHandler(xerror);
604 XUngrabServer(win->sys->dpy);
606 XDestroyWindow(win->sys->dpy, win->sys->xid);
612 void sys_watch(win_t *win, event_t ev, mod_t mod)
614 //printf("sys_watch: %p - %x %hhx\n", win, ev, mod);
615 XWindowAttributes attr;
616 XGetWindowAttributes(win->sys->dpy, win->sys->xid, &attr);
617 long mask = attr.your_event_mask;
618 if (EV_MOUSE0 <= ev && ev <= EV_MOUSE7)
619 XGrabButton(win->sys->dpy, ev2xb(ev), mod2x(mod), win->sys->xid, False,
620 mod.up ? ButtonReleaseMask : ButtonPressMask,
621 GrabModeSync, GrabModeAsync, None, None);
622 else if (ev == EV_ENTER)
623 XSelectInput(win->sys->dpy, win->sys->xid, EnterWindowMask|mask);
624 else if (ev == EV_LEAVE)
625 XSelectInput(win->sys->dpy, win->sys->xid, LeaveWindowMask|mask);
626 else if (ev == EV_FOCUS || ev == EV_UNFOCUS)
627 XSelectInput(win->sys->dpy, win->sys->xid, FocusChangeMask|mask);
629 XGrabKey(win->sys->dpy, XKeysymToKeycode(win->sys->dpy, ev2xk(ev)),
630 mod2x(mod), win->sys->xid, True, GrabModeAsync, GrabModeAsync);
633 void sys_unwatch(win_t *win, event_t ev, mod_t mod)
635 if (EV_MOUSE0 <= ev && ev <= EV_MOUSE7)
636 XUngrabButton(win->sys->dpy, ev2xb(ev), mod2x(mod), win->sys->xid);
639 list_t *sys_info(win_t *win)
641 /* Use global copy of screens so we can add struts */
642 if (screens == NULL) {
643 /* Add Xinerama screens */
645 XineramaScreenInfo *info = NULL;
646 if (XineramaIsActive(win->sys->dpy))
647 info = XineramaQueryScreens(win->sys->dpy, &n);
648 for (int i = 0; i < n; i++) {
649 win_t *screen = new0(win_t);
650 screen->x = info[i].x_org;
651 screen->y = info[i].y_org;
652 screen->w = info[i].width;
653 screen->h = info[i].height;
654 screen->sys = new0(win_sys_t);
655 screens = list_append(screens, screen);
658 if (screens == NULL) {
659 /* No xinerama support */
660 win_t *screen = new0(win_t);
662 screens = list_insert(NULL, screen);
667 win_t *sys_init(void)
672 /* Load configuration */
673 stack = conf_get_int("main.stack", stack);
674 border = conf_get_int("main.border", border);
675 no_capture = conf_get_int("main.no-capture", no_capture);
677 /* Open the display */
678 if (!(dpy = XOpenDisplay(NULL)))
679 error("Unable to get display");
680 if (!(xid = DefaultRootWindow(dpy)))
681 error("Unable to get root window");
684 atoms[WM_PROTO] = XInternAtom(dpy, "WM_PROTOCOLS", False);
685 atoms[WM_FOCUS] = XInternAtom(dpy, "WM_TAKE_FOCUS", False);
686 atoms[WM_DELETE] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
687 atoms[NET_STATE] = XInternAtom(dpy, "_NET_WM_STATE", False);
688 atoms[NET_FULL] = XInternAtom(dpy, "_NET_WM_STATE_FULLSCREEN", False);
689 atoms[NET_STRUT] = XInternAtom(dpy, "_NET_WM_STRUT", False);
690 atoms[NET_TYPE] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE", False);
691 atoms[NET_DIALOG] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE_DIALOG", False);
693 colors[CLR_FOCUS] = get_color(dpy, "#a0a0ff");
694 colors[CLR_UNFOCUS] = get_color(dpy, "#101066");
695 colors[CLR_URGENT] = get_color(dpy, "#ff0000");
696 //printf("colors = #%06lx #%06lx #%06lx\n", colors[0], colors[1], colors[2]);
698 /* Select window management events */
699 XSelectInput(dpy, xid, SubstructureRedirectMask|SubstructureNotifyMask);
700 xerrorxlib = XSetErrorHandler(xerror);
702 return win_find(dpy, xid, 1);
705 void sys_run(win_t *root)
707 /* Add each initial window */
710 Window par, xid, *kids = NULL;
711 if (XQueryTree(root->sys->dpy, root->sys->xid,
712 &par, &xid, &kids, &nkids)) {
713 for(int i = 0; i < nkids; i++) {
714 win_t *win = win_find(root->sys->dpy, kids[i], 1);
715 if (win && win_viewable(win) && !strut_add(root,win))
720 wm_update(); // For struts
728 XNextEvent(root->sys->dpy, &xe);
729 process_event(xe.type, &xe, root);
738 void sys_free(win_t *root)
740 XCloseDisplay(root->sys->dpy);
742 win_free(screens->data);
743 screens = list_remove(screens, screens, 0);
745 tdestroy(cache, (void(*)(void*))win_free);