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;
52 WM_PROTO, WM_FOCUS, WM_DELETE,
53 NET_STATE, NET_FULL, NET_STRUT,
58 CLR_FOCUS, CLR_UNFOCUS, CLR_URGENT, NCOLORS
64 static Atom atoms[NATOMS];
65 static int (*xerrorxlib)(Display *, XErrorEvent *);
66 static unsigned long colors[NCOLORS];
67 static list_t *screens;
68 static list_t *struts;
70 /* Conversion functions */
71 static event_map_t ev2sym[] = {
73 {EV_RIGHT , XK_Right},
78 {EV_PAGEUP , XK_Prior},
79 {EV_PAGEDOWN, XK_Next },
95 static mod_t x2mod(unsigned int state, int up)
98 .alt = !!(state & Mod1Mask ),
99 .ctrl = !!(state & ControlMask),
100 .shift = !!(state & ShiftMask ),
101 .win = !!(state & Mod4Mask ),
106 static unsigned int mod2x(mod_t mod)
108 return (mod.alt ? Mod1Mask : 0)
109 | (mod.ctrl ? ControlMask : 0)
110 | (mod.shift ? ShiftMask : 0)
111 | (mod.win ? Mod4Mask : 0);
115 static event_t xk2ev(KeySym sym)
117 event_map_t *em = map_getr(ev2sym,sym);
118 return em ? em->ev : sym;
121 static KeySym ev2xk(event_t ev)
123 event_map_t *em = map_get(ev2sym,ev);
124 return em ? em->sym : ev;
127 static event_t xb2ev(int btn)
129 return btn + EV_MOUSE0;
132 static int ev2xb(event_t ev)
134 return ev - EV_MOUSE0;
138 static ptr_t x2ptr(XEvent *xe)
140 XKeyEvent *xke = &xe->xkey;
141 return (ptr_t){xke->x, xke->y, xke->x_root, xke->y_root};
144 static Window getfocus(win_t *root, XEvent *xe)
147 Window focus = PointerRoot;
148 if (xe->type == KeyPress || xe->type == KeyRelease)
149 XGetInputFocus(root->sys->dpy, &focus, &revert);
150 if (focus == PointerRoot)
151 focus = xe->xkey.subwindow;
153 focus = xe->xkey.window;
158 * Struts are spaces at the edges of the screen that are used by
159 * toolbars and statusbars such as dzen. */
160 static int strut_copy(win_t *to, win_t *from, int scale)
162 int left = from->sys->strut.left;
163 int right = from->sys->strut.right;
164 int top = from->sys->strut.top;
165 int bottom = from->sys->strut.bottom;
166 if (left == 0 && right == 0 && top == 0 && bottom == 0)
168 to->x += scale*(left );
169 to->y += scale*(top );
170 to->w -= scale*(left+right);
171 to->h -= scale*(top+bottom);
172 to->sys->strut.left += scale*left;
173 to->sys->strut.right += scale*right;
174 to->sys->strut.top += scale*top;
175 to->sys->strut.bottom += scale*bottom;
179 static int strut_add(win_t *root, win_t *win)
181 /* Get X11 strut data */
184 unsigned long ret_items, bytes_left;
185 unsigned char *xdata;
186 int status = XGetWindowProperty(win->sys->dpy, win->sys->xid,
187 atoms[NET_STRUT], 0L, 4L, False, XA_CARDINAL,
188 &ret_type, &ret_size, &ret_items, &bytes_left, &xdata);
189 if (status != Success || ret_size != 32 || ret_items != 4)
192 win->sys->strut.left = ((int*)xdata)[0];
193 win->sys->strut.right = ((int*)xdata)[1];
194 win->sys->strut.top = ((int*)xdata)[2];
195 win->sys->strut.bottom = ((int*)xdata)[3];
196 struts = list_insert(struts, win);
197 for (list_t *cur = screens; cur; cur = cur->next)
198 strut_copy(cur->data, win, 1);
199 return strut_copy(root, win, 1);
202 static int strut_del(win_t *root, win_t *win)
204 list_t *lwin = list_find(struts, win);
206 struts = list_remove(struts, lwin, 0);
207 for (list_t *cur = screens; cur; cur = cur->next)
208 strut_copy(cur->data, win, -1);
209 return strut_copy(root, win, -1);
212 /* Window functions */
213 static win_t *win_new(Display *dpy, Window xid)
215 XWindowAttributes attr;
216 if (XGetWindowAttributes(dpy, xid, &attr))
217 if (attr.override_redirect)
219 win_t *win = new0(win_t);
223 win->h = attr.height;
224 win->sys = new0(win_sys_t);
227 printf("win_new: %p = %p, %d (%d,%d %dx%d)\n",
229 win->x, win->y, win->w, win->h);
233 static int win_cmp(const void *_a, const void *_b)
235 const win_t *a = _a, *b = _b;
236 if (a->sys->dpy < b->sys->dpy) return -1;
237 if (a->sys->dpy > b->sys->dpy) return 1;
238 if (a->sys->xid < b->sys->xid) return -1;
239 if (a->sys->xid > b->sys->xid) return 1;
243 static win_t *win_find(Display *dpy, Window xid, int create)
247 //printf("win_find: %p, %d\n", dpy, (int)xid);
248 win_sys_t sys = {.dpy=dpy, .xid=xid};
249 win_t tmp = {.sys=&sys};
250 win_t **old = NULL, *new = NULL;
251 if ((old = tfind(&tmp, &cache, win_cmp)))
253 if (create && (new = win_new(dpy,xid)))
254 tsearch(new, &cache, win_cmp);
258 static void win_free(win_t *win)
264 static void win_remove(win_t *win)
266 tdelete(win, &cache, win_cmp);
270 static int win_viewable(win_t *win)
272 XWindowAttributes attr;
273 if (XGetWindowAttributes(win->sys->dpy, win->sys->xid, &attr))
274 return attr.map_state == IsViewable;
279 static int win_msg(win_t *win, atom_t msg)
283 if (!XGetWMProtocols(win->sys->dpy, win->sys->xid, &protos, &n))
286 while (!found && n--)
287 found = protos[n] == atoms[msg];
292 XSendEvent(win->sys->dpy, win->sys->xid, False, NoEventMask, &(XEvent){
293 .type = ClientMessage,
294 .xclient.window = win->sys->xid,
295 .xclient.message_type = atoms[WM_PROTO],
296 .xclient.format = 32,
297 .xclient.data.l[0] = atoms[msg],
298 .xclient.data.l[1] = CurrentTime,
304 static int win_full(win_t *win)
308 unsigned long ret_items, bytes_left;
309 unsigned char *xdata;
310 int status = XGetWindowProperty(win->sys->dpy, win->sys->xid,
311 atoms[NET_FULL], 0L, 1L, False, XA_ATOM,
312 &ret_type, &ret_size, &ret_items, &bytes_left, &xdata);
313 printf("is_fullscreen:\n");
314 printf("\t%d\n", status);
315 printf("\t%d\n", ret_size);
316 printf("\t%ld\n", ret_items);
317 printf("\t%p\n", xdata);
319 printf("\t%d\n", xdata[0]);
320 return status == Success && ret_size == 32 && ret_items == 1 &&
321 xdata[0] == atoms[NET_FULL];
325 /* Drawing functions */
326 static unsigned long get_color(Display *dpy, const char *name)
329 int screen = DefaultScreen(dpy);
330 Colormap cmap = DefaultColormap(dpy, screen);
331 XAllocNamedColor(dpy, cmap, name, &color, &color);
336 static void process_event(int type, XEvent *xe, win_t *root)
338 Display *dpy = root->sys->dpy;
340 //printf("event: %d\n", type);
342 /* Common data for all these events ... */
343 ptr_t ptr = {}; mod_t mod = {};
344 if (type == KeyPress || type == KeyRelease ||
345 type == ButtonPress || type == ButtonRelease ||
346 type == MotionNotify) {
347 Window xid = getfocus(root, xe);
348 if (!(win = win_find(dpy,xid,0)))
350 //printf("button-press %p\n", win);
352 mod = x2mod(xe->xkey.state, type==KeyRelease||type==ButtonRelease);
355 /* Split based on event */
356 if (type == KeyPress) {
357 while (XCheckTypedEvent(dpy, KeyPress, xe));
358 KeySym sym = XKeycodeToKeysym(dpy, xe->xkey.keycode, 0);
359 printf("got xe %c %hhx\n", xk2ev(sym), mod2int(mod));
360 wm_handle_event(win, xk2ev(sym), mod, ptr);
362 else if (type == KeyRelease) {
363 //printf("release: %d\n", type);
365 else if (type == ButtonPress) {
366 if (wm_handle_event(win, xb2ev(xe->xbutton.button), mod, ptr)) {
367 //printf("grab pointer\n");
368 XGrabPointer(dpy, xe->xbutton.root, True, PointerMotionMask|ButtonReleaseMask,
369 GrabModeAsync, GrabModeAsync, None, None, CurrentTime);
371 //printf("allow events\n");
372 XAllowEvents(win->sys->dpy, ReplayPointer, xe->xbutton.time);
375 else if (type == ButtonRelease) {
376 XUngrabPointer(dpy, CurrentTime);
377 wm_handle_event(win, xb2ev(xe->xbutton.button), mod, ptr);
379 else if (type == MotionNotify) {
380 while (XCheckTypedEvent(dpy, MotionNotify, xe));
381 wm_handle_ptr(win, ptr);
383 else if (type == EnterNotify || type == LeaveNotify) {
384 printf("%s: %d\n", type==EnterNotify?"enter":"leave", type);
385 event_t ev = type == EnterNotify ? EV_ENTER : EV_LEAVE;
386 if ((win = win_find(dpy,xe->xcrossing.window,0)))
387 wm_handle_event(win, ev, MOD(), PTR());
389 else if (type == FocusIn || type == FocusOut) {
390 //printf("focus: %d\n", type);
391 event_t ev = FocusIn ? EV_FOCUS : EV_UNFOCUS;
392 if ((win = win_find(dpy,xe->xfocus.window,0)))
393 wm_handle_event(win, ev, MOD(), PTR());
395 else if (type == ConfigureNotify) {
396 printf("configure: %d\n", type);
398 else if (type == MapNotify) {
399 printf("map: %d\n", type);
401 else if (type == UnmapNotify) {
402 if ((win = win_find(dpy,xe->xunmap.window,0)) &&
403 win->sys->state != ST_HIDE) {
404 if (!strut_del(root, win))
408 win->sys->state = ST_HIDE;
411 else if (type == DestroyNotify) {
412 //printf("destroy: %d\n", type);
413 if ((win = win_find(dpy,xe->xdestroywindow.window,0)))
416 else if (type == ConfigureRequest) {
417 XConfigureRequestEvent *cre = &xe->xconfigurerequest;
418 printf("configure_req: %d - %x, (0x%lx) %dx%d @ %d,%d\n",
419 type, (int)cre->window, cre->value_mask,
420 cre->height, cre->width, cre->x, cre->y);
421 if ((win = win_find(dpy,xe->xmaprequest.window,1))) {
422 XSendEvent(dpy, cre->window, False, StructureNotifyMask, &(XEvent){
423 .xconfigure.type = ConfigureNotify,
424 .xconfigure.display = win->sys->dpy,
425 .xconfigure.event = win->sys->xid,
426 .xconfigure.window = win->sys->xid,
427 .xconfigure.x = win->x,
428 .xconfigure.y = win->y,
429 .xconfigure.width = win->w,
430 .xconfigure.height = win->h,
431 .xconfigure.border_width = border,
433 XSync(win->sys->dpy, False);
436 else if (type == MapRequest) {
437 printf("map_req: %d\n", type);
438 if ((win = win_find(dpy,xe->xmaprequest.window,1))) {
439 XSelectInput(win->sys->dpy, win->sys->xid, PropertyChangeMask);
440 if (!strut_add(root, win))
445 XMapWindow(dpy, xe->xmaprequest.window);
447 else if (type == ClientMessage) {
448 XClientMessageEvent *cme = &xe->xclient;
449 printf("msg: %d - %ld %ld,%ld,%ld,%ld,%ld\n",
450 type, cme->message_type,
451 cme->data.l[0], cme->data.l[1], cme->data.l[2],
452 cme->data.l[3], cme->data.l[4]);
453 if ((win = win_find(dpy,cme->window,0)) &&
454 (cme->message_type == atoms[NET_STATE]) &&
455 (cme->data.l[1] == atoms[NET_FULL] ||
456 cme->data.l[2] == atoms[NET_FULL])) {
457 if (cme->data.l[0] == 1 || /* _NET_WM_STATE_ADD */
458 (cme->data.l[0] == 2 && /* _NET_WM_STATE_TOGGLE */
459 win->sys->state != ST_FULL))
460 sys_show(win, ST_FULL);
462 sys_show(win, ST_SHOW);
465 else if (type == PropertyNotify) {
466 printf("prop: %d - %d\n", type, xe->xproperty.state);
469 printf("unknown event: %d\n", type);
473 static int xerror(Display *dpy, XErrorEvent *err)
475 if (err->error_code == BadWindow ||
476 (err->request_code == X_SetInputFocus && err->error_code == BadMatch ) ||
477 (err->request_code == X_PolyText8 && err->error_code == BadDrawable) ||
478 (err->request_code == X_PolyFillRectangle && err->error_code == BadDrawable) ||
479 (err->request_code == X_PolySegment && err->error_code == BadDrawable) ||
480 (err->request_code == X_ConfigureWindow && err->error_code == BadMatch ) ||
481 (err->request_code == X_GrabButton && err->error_code == BadAccess ) ||
482 (err->request_code == X_GrabKey && err->error_code == BadAccess ) ||
483 (err->request_code == X_CopyArea && err->error_code == BadDrawable))
485 if (err->request_code == X_ChangeWindowAttributes && err->error_code == BadAccess)
486 error("Another window manager is already running");
487 return xerrorxlib(dpy, err);
490 static int xnoerror(Display *dpy, XErrorEvent *err)
496 /********************
498 ********************/
499 void sys_move(win_t *win, int x, int y, int w, int h)
501 //printf("sys_move: %p - %d,%d %dx%d\n", win, x, y, w, h);
503 win->x = x; win->y = y;
504 win->w = MAX(w,1+b); win->h = MAX(h,1+b);
505 w = MAX(w-b,1); h = MAX(h-b,1);
506 XMoveResizeWindow(win->sys->dpy, win->sys->xid, x, y, w, h);
508 /* Flush events, so moving window doesn't cause re-focus
509 * There's probably a better way to do this */
511 XSync(win->sys->dpy, False);
512 while (XCheckMaskEvent(win->sys->dpy, EnterWindowMask|LeaveWindowMask, &xe))
513 printf("Skipping enter/leave event\n");
516 void sys_raise(win_t *win)
518 //printf("sys_raise: %p\n", win);
519 XRaiseWindow(win->sys->dpy, win->sys->xid);
520 for (list_t *cur = struts; cur; cur = cur->next)
521 XRaiseWindow(((win_t*)cur->data)->sys->dpy,
522 ((win_t*)cur->data)->sys->xid);
525 void sys_focus(win_t *win)
527 printf("sys_focus: %p\n", win);
529 /* Set actual focus */
530 XSetInputFocus(win->sys->dpy, win->sys->xid,
531 RevertToPointerRoot, CurrentTime);
532 win_msg(win, WM_FOCUS);
534 /* Set border on focused window */
535 static win_t *last = NULL;
537 XSetWindowBorder(last->sys->dpy, last->sys->xid, colors[CLR_UNFOCUS]);
538 XSync(win->sys->dpy, False);
539 XSetWindowBorder(win->sys->dpy, win->sys->xid, colors[CLR_FOCUS]);
543 void sys_show(win_t *win, state_t state)
547 printf("sys_show: show\n");
548 if (win->sys->state == ST_FULL)
549 sys_move(win, win->x, win->y, win->w, win->h);
550 XSetWindowBorderWidth(win->sys->dpy, win->sys->xid, border);
551 XMapWindow(win->sys->dpy, win->sys->xid);
552 XSync(win->sys->dpy, False);
555 printf("sys_show: full\n");
556 win_t *screen = NULL;
557 for (list_t *cur = screens; cur; cur = cur->next) {
559 if (win->x >= screen->x && win->x <= screen->x+screen->w &&
560 win->y >= screen->y && win->y <= screen->y+screen->h)
563 XSetWindowBorderWidth(win->sys->dpy, win->sys->xid, 0);
564 XMapWindow(win->sys->dpy, win->sys->xid);
565 XMoveResizeWindow(win->sys->dpy, win->sys->xid,
566 screen->x - screen->sys->strut.left,
567 screen->y - screen->sys->strut.top,
568 screen->w + screen->sys->strut.left + screen->sys->strut.right,
569 screen->h + screen->sys->strut.top + screen->sys->strut.bottom);
570 XRaiseWindow(win->sys->dpy, win->sys->xid);
573 printf("sys_show: shade\n");
574 XMapWindow(win->sys->dpy, win->sys->xid);
577 printf("sys_show: icon\n");
580 printf("sys_show: hide\n");
581 XUnmapWindow(win->sys->dpy, win->sys->xid);
584 printf("sys_show: close\n");
585 if (!win_msg(win, WM_DELETE)) {
586 XGrabServer(win->sys->dpy);
587 XSetErrorHandler(xnoerror);
588 XSetCloseDownMode(win->sys->dpy, DestroyAll);
589 XKillClient(win->sys->dpy, win->sys->xid);
590 XSync(win->sys->dpy, False);
591 XSetErrorHandler(xerror);
592 XUngrabServer(win->sys->dpy);
594 XDestroyWindow(win->sys->dpy, win->sys->xid);
597 win->sys->state = state;
600 void sys_watch(win_t *win, event_t ev, mod_t mod)
602 //printf("sys_watch: %p - %x %hhx\n", win, ev, mod);
603 XWindowAttributes attr;
604 XGetWindowAttributes(win->sys->dpy, win->sys->xid, &attr);
605 long mask = attr.your_event_mask;
606 if (EV_MOUSE0 <= ev && ev <= EV_MOUSE7)
607 XGrabButton(win->sys->dpy, ev2xb(ev), mod2x(mod), win->sys->xid, False,
608 mod.up ? ButtonReleaseMask : ButtonPressMask,
609 GrabModeSync, GrabModeAsync, None, None);
610 else if (ev == EV_ENTER)
611 XSelectInput(win->sys->dpy, win->sys->xid, EnterWindowMask|mask);
612 else if (ev == EV_LEAVE)
613 XSelectInput(win->sys->dpy, win->sys->xid, LeaveWindowMask|mask);
614 else if (ev == EV_FOCUS || ev == EV_UNFOCUS)
615 XSelectInput(win->sys->dpy, win->sys->xid, FocusChangeMask|mask);
617 XGrabKey(win->sys->dpy, XKeysymToKeycode(win->sys->dpy, ev2xk(ev)),
618 mod2x(mod), win->sys->xid, True, GrabModeAsync, GrabModeAsync);
621 void sys_unwatch(win_t *win, event_t ev, mod_t mod)
623 if (EV_MOUSE0 <= ev && ev <= EV_MOUSE7)
624 XUngrabButton(win->sys->dpy, ev2xb(ev), mod2x(mod), win->sys->xid);
627 list_t *sys_info(win_t *win)
629 /* Use global copy of screens so we can add struts */
630 if (screens == NULL) {
631 /* Add Xinerama screens */
633 XineramaScreenInfo *info = NULL;
634 if (XineramaIsActive(win->sys->dpy))
635 info = XineramaQueryScreens(win->sys->dpy, &n);
636 for (int i = 0; i < n; i++) {
637 win_t *screen = new0(win_t);
638 screen->x = info[i].x_org;
639 screen->y = info[i].y_org;
640 screen->w = info[i].width;
641 screen->h = info[i].height;
642 screen->sys = new0(win_sys_t);
643 screens = list_append(screens, screen);
646 if (screens == NULL) {
647 /* No xinerama support */
648 win_t *screen = new0(win_t);
650 screens = list_insert(NULL, screen);
655 win_t *sys_init(void)
660 /* Load configuration */
661 border = conf_get_int("main.border", border);
662 no_capture = conf_get_int("main.no-capture", no_capture);
664 /* Open the display */
665 if (!(dpy = XOpenDisplay(NULL)))
666 error("Unable to get display");
667 if (!(xid = DefaultRootWindow(dpy)))
668 error("Unable to get root window");
671 atoms[WM_PROTO] = XInternAtom(dpy, "WM_PROTOCOLS", False);
672 atoms[WM_FOCUS] = XInternAtom(dpy, "WM_TAKE_FOCUS", False);
673 atoms[WM_DELETE] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
674 atoms[NET_STATE] = XInternAtom(dpy, "_NET_WM_STATE", False);
675 atoms[NET_FULL] = XInternAtom(dpy, "_NET_WM_STATE_FULLSCREEN", False);
676 atoms[NET_STRUT] = XInternAtom(dpy, "_NET_WM_STRUT", False);
678 colors[CLR_FOCUS] = get_color(dpy, "#a0a0ff");
679 colors[CLR_UNFOCUS] = get_color(dpy, "#101066");
680 colors[CLR_URGENT] = get_color(dpy, "#ff0000");
681 //printf("colors = #%06lx #%06lx #%06lx\n", colors[0], colors[1], colors[2]);
683 /* Select window management events */
684 XSelectInput(dpy, xid, SubstructureRedirectMask|SubstructureNotifyMask);
685 xerrorxlib = XSetErrorHandler(xerror);
687 return win_find(dpy, xid, 1);
690 void sys_run(win_t *root)
692 /* Add each initial window */
695 Window par, xid, *kids = NULL;
696 if (XQueryTree(root->sys->dpy, root->sys->xid,
697 &par, &xid, &kids, &nkids)) {
698 for(int i = 0; i < nkids; i++) {
699 win_t *win = win_find(root->sys->dpy, kids[i], 1);
700 if (win && win_viewable(win) && !strut_add(root,win))
705 wm_update(); // For struts
713 XNextEvent(root->sys->dpy, &xe);
714 process_event(xe.type, &xe, root);
723 void sys_free(win_t *root)
725 XCloseDisplay(root->sys->dpy);
727 win_free(screens->data);
728 screens = list_remove(screens, screens, 0);
730 tdestroy(cache, (void(*)(void*))win_free);