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, NET_STRUT, NATOMS
56 CLR_FOCUS, CLR_UNFOCUS, CLR_URGENT, NCOLORS
62 static Atom atoms[NATOMS];
63 static int (*xerrorxlib)(Display *, XErrorEvent *);
64 static unsigned long colors[NCOLORS];
65 static list_t *screens;
66 static list_t *struts;
68 /* Conversion functions */
69 static event_map_t ev2sym[] = {
71 {EV_RIGHT , XK_Right},
76 {EV_PAGEUP , XK_Prior},
77 {EV_PAGEDOWN, XK_Next },
93 static mod_t x2mod(unsigned int state, int up)
96 .alt = !!(state & Mod1Mask ),
97 .ctrl = !!(state & ControlMask),
98 .shift = !!(state & ShiftMask ),
99 .win = !!(state & Mod4Mask ),
104 static unsigned int mod2x(mod_t mod)
106 return (mod.alt ? Mod1Mask : 0)
107 | (mod.ctrl ? ControlMask : 0)
108 | (mod.shift ? ShiftMask : 0)
109 | (mod.win ? Mod4Mask : 0);
113 static event_t xk2ev(KeySym sym)
115 event_map_t *em = map_getr(ev2sym,sym);
116 return em ? em->ev : sym;
119 static KeySym ev2xk(event_t ev)
121 event_map_t *em = map_get(ev2sym,ev);
122 return em ? em->sym : ev;
125 static event_t xb2ev(int btn)
127 return btn + EV_MOUSE0;
130 static int ev2xb(event_t ev)
132 return ev - EV_MOUSE0;
136 static ptr_t x2ptr(XEvent *xe)
138 XKeyEvent *xke = &xe->xkey;
139 return (ptr_t){xke->x, xke->y, xke->x_root, xke->y_root};
142 static Window getfocus(win_t *root, XEvent *xe)
145 Window focus = PointerRoot;
146 if (xe->type == KeyPress || xe->type == KeyRelease)
147 XGetInputFocus(root->sys->dpy, &focus, &revert);
148 if (focus == PointerRoot)
149 focus = xe->xkey.subwindow;
151 focus = xe->xkey.window;
156 * Struts are spaces at the edges of the screen that are used by
157 * toolbars and statusbars such as dzen. */
158 static int strut_copy(win_t *to, win_t *from, int scale)
160 int left = from->sys->strut.left;
161 int right = from->sys->strut.right;
162 int top = from->sys->strut.top;
163 int bottom = from->sys->strut.bottom;
164 if (left == 0 && right == 0 && top == 0 && bottom == 0)
166 to->x += scale*(left );
167 to->y += scale*(top );
168 to->w -= scale*(left+right);
169 to->h -= scale*(top+bottom);
173 static int strut_add(win_t *root, win_t *win)
175 /* Get X11 strut data */
178 unsigned long ret_items, bytes_left;
179 unsigned char *xdata;
180 int status = XGetWindowProperty(win->sys->dpy, win->sys->xid,
181 atoms[NET_STRUT], 0L, 4L, False, XA_CARDINAL,
182 &ret_type, &ret_size, &ret_items, &bytes_left, &xdata);
183 if (status != Success || ret_size != 32 || ret_items != 4)
186 win->sys->strut.left = ((int*)xdata)[0];
187 win->sys->strut.right = ((int*)xdata)[1];
188 win->sys->strut.top = ((int*)xdata)[2];
189 win->sys->strut.bottom = ((int*)xdata)[3];
190 struts = list_insert(struts, win);
191 for (list_t *cur = screens; cur; cur = cur->next)
192 strut_copy(cur->data, win, 1);
193 return strut_copy(root, win, 1);
196 static int strut_del(win_t *root, win_t *win)
198 list_t *lwin = list_find(struts, win);
200 struts = list_remove(struts, lwin, 0);
201 for (list_t *cur = screens; cur; cur = cur->next)
202 strut_copy(cur->data, win, -1);
203 return strut_copy(root, win, -1);
206 /* Window functions */
207 static win_t *win_new(Display *dpy, Window xid)
209 XWindowAttributes attr;
210 if (XGetWindowAttributes(dpy, xid, &attr))
211 if (attr.override_redirect)
213 win_t *win = new0(win_t);
217 win->h = attr.height;
218 win->sys = new0(win_sys_t);
221 printf("win_new: %p = %p, %d (%d,%d %dx%d)\n",
223 win->x, win->y, win->w, win->h);
227 static int win_cmp(const void *_a, const void *_b)
229 const win_t *a = _a, *b = _b;
230 if (a->sys->dpy < b->sys->dpy) return -1;
231 if (a->sys->dpy > b->sys->dpy) return 1;
232 if (a->sys->xid < b->sys->xid) return -1;
233 if (a->sys->xid > b->sys->xid) return 1;
237 static win_t *win_find(Display *dpy, Window xid, int create)
241 //printf("win_find: %p, %d\n", dpy, (int)xid);
242 win_sys_t sys = {.dpy=dpy, .xid=xid};
243 win_t tmp = {.sys=&sys};
244 win_t **old = NULL, *new = NULL;
245 if ((old = tfind(&tmp, &cache, win_cmp)))
247 if (create && (new = win_new(dpy,xid)))
248 tsearch(new, &cache, win_cmp);
252 static void win_free(win_t *win)
258 static void win_remove(win_t *win)
260 tdelete(win, &cache, win_cmp);
264 static int win_viewable(win_t *win)
266 XWindowAttributes attr;
267 if (XGetWindowAttributes(win->sys->dpy, win->sys->xid, &attr))
268 return attr.map_state == IsViewable;
273 /* Drawing functions */
274 static unsigned long get_color(Display *dpy, const char *name)
277 int screen = DefaultScreen(dpy);
278 Colormap cmap = DefaultColormap(dpy, screen);
279 XAllocNamedColor(dpy, cmap, name, &color, &color);
284 static void process_event(int type, XEvent *xe, win_t *root)
286 Display *dpy = root->sys->dpy;
288 //printf("event: %d\n", type);
290 /* Common data for all these events ... */
291 ptr_t ptr = {}; mod_t mod = {};
292 if (type == KeyPress || type == KeyRelease ||
293 type == ButtonPress || type == ButtonRelease ||
294 type == MotionNotify) {
295 Window xid = getfocus(root, xe);
296 if (!(win = win_find(dpy,xid,0)))
299 mod = x2mod(xe->xkey.state, type==KeyRelease||type==ButtonRelease);
302 /* Split based on event */
303 if (type == KeyPress) {
304 while (XCheckTypedEvent(dpy, KeyPress, xe));
305 KeySym sym = XKeycodeToKeysym(dpy, xe->xkey.keycode, 0);
306 printf("got xe %c %hhx\n", xk2ev(sym), mod2int(mod));
307 wm_handle_event(win, xk2ev(sym), mod, ptr);
309 else if (type == KeyRelease) {
310 //printf("release: %d\n", type);
312 else if (type == ButtonPress) {
313 if (wm_handle_event(win, xb2ev(xe->xbutton.button), mod, ptr))
314 XGrabPointer(dpy, xe->xbutton.root, True, PointerMotionMask|ButtonReleaseMask,
315 GrabModeAsync, GrabModeAsync, None, None, CurrentTime);
317 XAllowEvents(win->sys->dpy, ReplayPointer, CurrentTime);
319 else if (type == ButtonRelease) {
320 XUngrabPointer(dpy, CurrentTime);
321 wm_handle_event(win, xb2ev(xe->xbutton.button), mod, ptr);
323 else if (type == MotionNotify) {
324 while (XCheckTypedEvent(dpy, MotionNotify, xe));
325 wm_handle_ptr(win, ptr);
327 else if (type == EnterNotify || type == LeaveNotify) {
328 printf("%s: %d\n", type==EnterNotify?"enter":"leave", type);
329 event_t ev = EnterNotify ? EV_ENTER : EV_LEAVE;
330 if ((win = win_find(dpy,xe->xcrossing.window,0)))
331 wm_handle_event(win, ev, MOD(), PTR());
333 else if (type == FocusIn || type == FocusOut) {
334 //printf("focus: %d\n", type);
335 event_t ev = FocusIn ? EV_FOCUS : EV_UNFOCUS;
336 if ((win = win_find(dpy,xe->xfocus.window,0)))
337 wm_handle_event(win, ev, MOD(), PTR());
339 else if (type == ConfigureNotify) {
340 printf("configure: %d\n", type);
342 else if (type == MapNotify) {
343 printf("map: %d\n", type);
345 else if (type == UnmapNotify) {
346 if ((win = win_find(dpy,xe->xunmap.window,0)) &&
347 win->sys->state != ST_HIDE) {
348 if (!strut_del(root, win))
352 win->sys->state = ST_HIDE;
355 else if (type == DestroyNotify) {
356 //printf("destroy: %d\n", type);
357 if ((win = win_find(dpy,xe->xdestroywindow.window,0)))
360 else if (type == ConfigureRequest) {
361 XConfigureRequestEvent *cre = &xe->xconfigurerequest;
362 printf("configure_req: %d - %x, (0x%lx) %dx%d @ %d,%d\n",
363 type, (int)cre->window, cre->value_mask,
364 cre->height, cre->width, cre->x, cre->y);
365 if ((win = win_find(dpy,xe->xmaprequest.window,1))) {
366 XSendEvent(dpy, cre->window, False, StructureNotifyMask, &(XEvent){
367 .xconfigure.type = ConfigureNotify,
368 .xconfigure.display = win->sys->dpy,
369 .xconfigure.event = win->sys->xid,
370 .xconfigure.window = win->sys->xid,
371 .xconfigure.x = win->x,
372 .xconfigure.y = win->y,
373 .xconfigure.width = win->w,
374 .xconfigure.height = win->h,
376 XSync(win->sys->dpy, False);
379 else if (type == MapRequest) {
380 printf("map_req: %d\n", type);
381 if ((win = win_find(dpy,xe->xmaprequest.window,1))) {
382 if (!strut_add(root, win))
387 XMapWindow(dpy, xe->xmaprequest.window);
390 printf("unknown event: %d\n", type);
394 static int xerror(Display *dpy, XErrorEvent *err)
396 if (err->error_code == BadWindow ||
397 (err->request_code == X_SetInputFocus && err->error_code == BadMatch ) ||
398 (err->request_code == X_PolyText8 && err->error_code == BadDrawable) ||
399 (err->request_code == X_PolyFillRectangle && err->error_code == BadDrawable) ||
400 (err->request_code == X_PolySegment && err->error_code == BadDrawable) ||
401 (err->request_code == X_ConfigureWindow && err->error_code == BadMatch ) ||
402 (err->request_code == X_GrabButton && err->error_code == BadAccess ) ||
403 (err->request_code == X_GrabKey && err->error_code == BadAccess ) ||
404 (err->request_code == X_CopyArea && err->error_code == BadDrawable))
406 return xerrorxlib(dpy, err);
409 /********************
411 ********************/
412 void sys_move(win_t *win, int x, int y, int w, int h)
414 //printf("sys_move: %p - %d,%d %dx%d\n", win, x, y, w, h);
416 win->x = x; win->y = y;
417 win->w = MAX(w,1+b); win->h = MAX(h,1+b);
418 w = MAX(w-b,1); h = MAX(h-b,1);
419 XMoveResizeWindow(win->sys->dpy, win->sys->xid, x, y, w, h);
421 /* Flush events, so moving window doesn't cause re-focus
422 * There's probably a better way to do this */
424 XSync(win->sys->dpy, False);
425 while (XCheckMaskEvent(win->sys->dpy, EnterWindowMask|LeaveWindowMask, &xe))
426 printf("Skipping enter/leave event\n");
429 void sys_raise(win_t *win)
431 //printf("sys_raise: %p\n", win);
432 XRaiseWindow(win->sys->dpy, win->sys->xid);
433 for (list_t *cur = struts; cur; cur = cur->next)
434 XRaiseWindow(((win_t*)cur->data)->sys->dpy,
435 ((win_t*)cur->data)->sys->xid);
438 void sys_focus(win_t *win)
440 //printf("sys_focus: %p\n", win);
442 /* Set border on focused window */
443 static win_t *last = NULL;
445 XSetWindowBorder(last->sys->dpy, last->sys->xid, colors[CLR_UNFOCUS]);
446 XSetWindowBorder(win->sys->dpy, win->sys->xid, colors[CLR_FOCUS]);
447 XSetWindowBorderWidth(win->sys->dpy, win->sys->xid, border);
450 /* Set actual focus */
451 XSetInputFocus(win->sys->dpy, win->sys->xid,
452 RevertToPointerRoot, CurrentTime);
453 XSendEvent(win->sys->dpy, win->sys->xid, False, NoEventMask, &(XEvent){
454 .type = ClientMessage,
455 .xclient.window = win->sys->xid,
456 .xclient.message_type = atoms[WM_PROTO],
457 .xclient.format = 32,
458 .xclient.data.l[0] = atoms[WM_FOCUS],
459 .xclient.data.l[1] = CurrentTime,
463 void sys_show(win_t *win, state_t state)
465 win->sys->state = state;
468 printf("sys_show: show\n");
469 XMapWindow(win->sys->dpy, win->sys->xid);
470 XSync(win->sys->dpy, False);
473 printf("sys_show: full\n");
474 XMapWindow(win->sys->dpy, win->sys->xid);
477 printf("sys_show: shade\n");
478 XMapWindow(win->sys->dpy, win->sys->xid);
481 printf("sys_show: icon\n");
484 printf("sys_show: hide\n");
485 XUnmapWindow(win->sys->dpy, win->sys->xid);
488 printf("sys_show: close\n");
489 XDestroyWindow(win->sys->dpy, win->sys->xid);
494 void sys_watch(win_t *win, event_t ev, mod_t mod)
496 //printf("sys_watch: %p - %x %hhx\n", win, ev, mod);
497 XWindowAttributes attr;
498 XGetWindowAttributes(win->sys->dpy, win->sys->xid, &attr);
499 long mask = attr.your_event_mask;
500 if (EV_MOUSE0 <= ev && ev <= EV_MOUSE7)
501 XGrabButton(win->sys->dpy, ev2xb(ev), mod2x(mod), win->sys->xid, False,
502 mod.up ? ButtonReleaseMask : ButtonPressMask,
503 GrabModeSync, GrabModeAsync, None, None);
504 else if (ev == EV_ENTER)
505 XSelectInput(win->sys->dpy, win->sys->xid, EnterWindowMask|mask);
506 else if (ev == EV_LEAVE)
507 XSelectInput(win->sys->dpy, win->sys->xid, LeaveWindowMask|mask);
508 else if (ev == EV_FOCUS || ev == EV_UNFOCUS)
509 XSelectInput(win->sys->dpy, win->sys->xid, FocusChangeMask|mask);
511 XGrabKey(win->sys->dpy, XKeysymToKeycode(win->sys->dpy, ev2xk(ev)),
512 mod2x(mod), win->sys->xid, True, GrabModeAsync, GrabModeAsync);
515 void sys_unwatch(win_t *win, event_t ev, mod_t mod)
517 if (EV_MOUSE0 <= ev && ev <= EV_MOUSE7)
518 XUngrabButton(win->sys->dpy, ev2xb(ev), mod2x(mod), win->sys->xid);
521 list_t *sys_info(win_t *win)
523 /* Use global copy of screens so we can add struts */
524 if (screens == NULL) {
525 /* Add Xinerama screens */
527 XineramaScreenInfo *info = NULL;
528 if (XineramaIsActive(win->sys->dpy))
529 info = XineramaQueryScreens(win->sys->dpy, &n);
530 for (int i = 0; i < n; i++) {
531 win_t *screen = new0(win_t);
532 screen->x = info[i].x_org;
533 screen->y = info[i].y_org;
534 screen->w = info[i].width;
535 screen->h = info[i].height;
536 screens = list_append(screens, screen);
539 if (screens == NULL) {
540 /* No xinerama support */
541 win_t *screen = new0(win_t);
543 screens = list_insert(NULL, screen);
548 win_t *sys_init(void)
553 /* Load configuration */
554 border = conf_get_int("main.border", border);
555 no_capture = conf_get_int("main.no-capture", no_capture);
557 /* Open the display */
558 if (!(dpy = XOpenDisplay(NULL)))
559 error("Unable to get display");
560 if (!(xid = DefaultRootWindow(dpy)))
561 error("Unable to get root window");
564 atoms[WM_PROTO] = XInternAtom(dpy, "WM_PROTOCOLS", False);
565 atoms[WM_FOCUS] = XInternAtom(dpy, "WM_TAKE_FOCUS", False);
566 atoms[NET_STRUT] = XInternAtom(dpy, "_NET_WM_STRUT", False);
568 colors[CLR_FOCUS] = get_color(dpy, "#a0a0ff");
569 colors[CLR_UNFOCUS] = get_color(dpy, "#101066");
570 colors[CLR_URGENT] = get_color(dpy, "#ff0000");
571 printf("colors = #%06lx #%06lx #%06lx\n", colors[0], colors[1], colors[2]);
573 /* Select window management events */
574 XSelectInput(dpy, xid, SubstructureRedirectMask|SubstructureNotifyMask);
575 xerrorxlib = XSetErrorHandler(xerror);
577 return win_find(dpy, xid, 1);
580 void sys_run(win_t *root)
582 /* Add each initial window */
585 Window par, xid, *kids = NULL;
586 if (XQueryTree(root->sys->dpy, root->sys->xid,
587 &par, &xid, &kids, &nkids)) {
588 for(int i = 0; i < nkids; i++) {
589 win_t *win = win_find(root->sys->dpy, kids[i], 1);
590 if (win && win_viewable(win) && !strut_add(root,win))
595 wm_update(); // For struts
603 XNextEvent(root->sys->dpy, &xe);
604 process_event(xe.type, &xe, root);
613 void sys_free(win_t *root)
615 XCloseDisplay(root->sys->dpy);
617 screens = list_remove(screens, screens, 1);
618 tdestroy(cache, (void(*)(void*))win_free);