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 XConfigureWindow(dpy, cre->window, cre->value_mask, &(XWindowChanges){
369 .height = cre->height,
372 /* This seems necessary for, but causes flicker
373 * there could be a better way to do this */
374 if ((win = win_find(dpy,xe->xmaprequest.window,0)))
375 sys_move(win, win->x, win->y, win->w, win->h);
377 else if (type == MapRequest) {
378 printf("map_req: %d\n", type);
379 if ((win = win_find(dpy,xe->xmaprequest.window,1))) {
380 if (!strut_add(root, win))
385 XMapWindow(dpy,xe->xmaprequest.window);
388 printf("unknown event: %d\n", type);
392 static int xerror(Display *dpy, XErrorEvent *err)
394 if (err->error_code == BadWindow ||
395 (err->request_code == X_SetInputFocus && err->error_code == BadMatch ) ||
396 (err->request_code == X_PolyText8 && err->error_code == BadDrawable) ||
397 (err->request_code == X_PolyFillRectangle && err->error_code == BadDrawable) ||
398 (err->request_code == X_PolySegment && err->error_code == BadDrawable) ||
399 (err->request_code == X_ConfigureWindow && err->error_code == BadMatch ) ||
400 (err->request_code == X_GrabButton && err->error_code == BadAccess ) ||
401 (err->request_code == X_GrabKey && err->error_code == BadAccess ) ||
402 (err->request_code == X_CopyArea && err->error_code == BadDrawable))
404 return xerrorxlib(dpy, err);
407 /********************
409 ********************/
410 void sys_move(win_t *win, int x, int y, int w, int h)
412 //printf("sys_move: %p - %d,%d %dx%d\n", win, x, y, w, h);
414 win->x = x; win->y = y;
415 win->w = MAX(w,1+b); win->h = MAX(h,1+b);
416 w = MAX(w-b,1); h = MAX(h-b,1);
417 XMoveResizeWindow(win->sys->dpy, win->sys->xid, x, y, w, h);
419 /* Flush events, so moving window doesn't cause re-focus
420 * There's probably a better way to do this */
422 XSync(win->sys->dpy, False);
423 while (XCheckMaskEvent(win->sys->dpy, EnterWindowMask|LeaveWindowMask, &xe))
424 printf("Skipping enter/leave event\n");
427 void sys_raise(win_t *win)
429 //printf("sys_raise: %p\n", win);
430 XRaiseWindow(win->sys->dpy, win->sys->xid);
431 for (list_t *cur = struts; cur; cur = cur->next)
432 XRaiseWindow(((win_t*)cur->data)->sys->dpy,
433 ((win_t*)cur->data)->sys->xid);
436 void sys_focus(win_t *win)
438 //printf("sys_focus: %p\n", win);
440 /* Set border on focused window */
441 static win_t *last = NULL;
443 XSetWindowBorder(last->sys->dpy, last->sys->xid, colors[CLR_UNFOCUS]);
444 XSetWindowBorder(win->sys->dpy, win->sys->xid, colors[CLR_FOCUS]);
445 XSetWindowBorderWidth(win->sys->dpy, win->sys->xid, border);
448 /* Set actual focus */
449 XSetInputFocus(win->sys->dpy, win->sys->xid,
450 RevertToPointerRoot, CurrentTime);
451 XSendEvent(win->sys->dpy, win->sys->xid, False, NoEventMask, &(XEvent){
452 .type = ClientMessage,
453 .xclient.window = win->sys->xid,
454 .xclient.message_type = atoms[WM_PROTO],
455 .xclient.format = 32,
456 .xclient.data.l[0] = atoms[WM_FOCUS],
457 .xclient.data.l[1] = CurrentTime,
461 void sys_show(win_t *win, state_t state)
463 win->sys->state = state;
466 printf("sys_show: show\n");
467 XMapWindow(win->sys->dpy, win->sys->xid);
468 XSync(win->sys->dpy, False);
471 printf("sys_show: full\n");
472 XMapWindow(win->sys->dpy, win->sys->xid);
475 printf("sys_show: shade\n");
476 XMapWindow(win->sys->dpy, win->sys->xid);
479 printf("sys_show: icon\n");
482 printf("sys_show: hide\n");
483 XUnmapWindow(win->sys->dpy, win->sys->xid);
486 printf("sys_show: close\n");
487 XDestroyWindow(win->sys->dpy, win->sys->xid);
492 void sys_watch(win_t *win, event_t ev, mod_t mod)
494 //printf("sys_watch: %p - %x %hhx\n", win, ev, mod);
495 XWindowAttributes attr;
496 XGetWindowAttributes(win->sys->dpy, win->sys->xid, &attr);
497 long mask = attr.your_event_mask;
498 if (EV_MOUSE0 <= ev && ev <= EV_MOUSE7)
499 XGrabButton(win->sys->dpy, ev2xb(ev), mod2x(mod), win->sys->xid, False,
500 mod.up ? ButtonReleaseMask : ButtonPressMask,
501 GrabModeSync, GrabModeAsync, None, None);
502 else if (ev == EV_ENTER)
503 XSelectInput(win->sys->dpy, win->sys->xid, EnterWindowMask|mask);
504 else if (ev == EV_LEAVE)
505 XSelectInput(win->sys->dpy, win->sys->xid, LeaveWindowMask|mask);
506 else if (ev == EV_FOCUS || ev == EV_UNFOCUS)
507 XSelectInput(win->sys->dpy, win->sys->xid, FocusChangeMask|mask);
509 XGrabKey(win->sys->dpy, XKeysymToKeycode(win->sys->dpy, ev2xk(ev)),
510 mod2x(mod), win->sys->xid, True, GrabModeAsync, GrabModeAsync);
513 void sys_unwatch(win_t *win, event_t ev, mod_t mod)
515 if (EV_MOUSE0 <= ev && ev <= EV_MOUSE7)
516 XUngrabButton(win->sys->dpy, ev2xb(ev), mod2x(mod), win->sys->xid);
519 list_t *sys_info(win_t *win)
521 /* Use global copy of screens so we can add struts */
522 if (screens == NULL) {
523 /* Add Xinerama screens */
525 XineramaScreenInfo *info = NULL;
526 if (XineramaIsActive(win->sys->dpy))
527 info = XineramaQueryScreens(win->sys->dpy, &n);
528 for (int i = 0; i < n; i++) {
529 win_t *screen = new0(win_t);
530 screen->x = info[i].x_org;
531 screen->y = info[i].y_org;
532 screen->w = info[i].width;
533 screen->h = info[i].height;
534 screens = list_append(screens, screen);
537 if (screens == NULL) {
538 /* No xinerama support */
539 win_t *screen = new0(win_t);
541 screens = list_insert(NULL, screen);
546 win_t *sys_init(void)
551 /* Load configuration */
552 border = conf_get_int("main.border", border);
553 no_capture = conf_get_int("main.no-capture", no_capture);
555 /* Open the display */
556 if (!(dpy = XOpenDisplay(NULL)))
557 error("Unable to get display");
558 if (!(xid = DefaultRootWindow(dpy)))
559 error("Unable to get root window");
562 atoms[WM_PROTO] = XInternAtom(dpy, "WM_PROTOCOLS", False);
563 atoms[WM_FOCUS] = XInternAtom(dpy, "WM_TAKE_FOCUS", False);
564 atoms[NET_STRUT] = XInternAtom(dpy, "_NET_WM_STRUT", False);
566 colors[CLR_FOCUS] = get_color(dpy, "#a0a0ff");
567 colors[CLR_UNFOCUS] = get_color(dpy, "#101066");
568 colors[CLR_URGENT] = get_color(dpy, "#ff0000");
569 printf("colors = #%06lx #%06lx #%06lx\n", colors[0], colors[1], colors[2]);
571 /* Select window management events */
572 XSelectInput(dpy, xid, SubstructureRedirectMask|SubstructureNotifyMask);
573 xerrorxlib = XSetErrorHandler(xerror);
575 return win_find(dpy, xid, 1);
578 void sys_run(win_t *root)
580 /* Add each initial window */
583 Window par, xid, *kids = NULL;
584 if (XQueryTree(root->sys->dpy, root->sys->xid,
585 &par, &xid, &kids, &nkids)) {
586 for(int i = 0; i < nkids; i++) {
587 win_t *win = win_find(root->sys->dpy, kids[i], 1);
588 if (win && win_viewable(win) && !strut_add(root,win))
593 wm_update(); // For struts
601 XNextEvent(root->sys->dpy, &xe);
602 process_event(xe.type, &xe, root);
611 void sys_free(win_t *root)
613 XCloseDisplay(root->sys->dpy);
615 screens = list_remove(screens, screens, 1);
616 tdestroy(cache, (void(*)(void*))win_free);