2 * Copyright (c) 2011, 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
21 #include <X11/Xproto.h>
22 #include <X11/Xatom.h>
23 #include <X11/keysym.h>
24 #include <X11/extensions/Xinerama.h>
34 /* Internal structures */
39 int left, right, top, bottom;
50 wm_proto, wm_focus, net_strut, natoms
54 clr_focus, clr_unfocus, clr_urgent, ncolors
59 static Atom atoms[natoms];
60 static int (*xerrorxlib)(Display *, XErrorEvent *);
61 static unsigned long colors[ncolors];
62 static list_t *screens;
64 /* Conversion functions */
65 static keymap_t key2sym[] = {
66 {key_left , XK_Left },
67 {key_right , XK_Right},
69 {key_down , XK_Down },
70 {key_home , XK_Home },
72 {key_pageup , XK_Prior},
73 {key_pagedown, XK_Next },
89 static mod_t x2mod(unsigned int state, int up)
92 .alt = !!(state & Mod1Mask ),
93 .ctrl = !!(state & ControlMask),
94 .shift = !!(state & ShiftMask ),
95 .win = !!(state & Mod4Mask ),
100 static unsigned int mod2x(mod_t mod)
102 return (mod.alt ? Mod1Mask : 0)
103 | (mod.ctrl ? ControlMask : 0)
104 | (mod.shift ? ShiftMask : 0)
105 | (mod.win ? Mod4Mask : 0);
109 static Key_t x2key(KeySym sym)
111 keymap_t *km = map_getr(key2sym,sym);
112 return km ? km->key : sym;
115 static KeySym key2x(Key_t key)
117 keymap_t *km = map_get(key2sym,key);
118 return km ? km->sym : key;
121 static Key_t x2btn(int btn)
123 return btn + key_mouse0;
126 static int btn2x(Key_t key)
128 return key - key_mouse0;
132 static ptr_t x2ptr(XEvent *_ev)
134 XKeyEvent *ev = &_ev->xkey;
135 return (ptr_t){ev->x, ev->y, ev->x_root, ev->y_root};
138 static Window getfocus(win_t *root, XEvent *event)
141 Window focus = PointerRoot;
142 if (event->type == KeyPress || event->type == KeyRelease)
143 XGetInputFocus(root->sys->dpy, &focus, &revert);
144 if (focus == PointerRoot)
145 focus = event->xkey.subwindow;
147 focus = event->xkey.window;
152 * Struts are spaces at the edges of the screen that are used by
153 * toolbars and statusbars such as dzen. */
154 static int strut_copy(win_t *to, win_t *from, int scale)
156 int left = from->sys->strut.left;
157 int right = from->sys->strut.right;
158 int top = from->sys->strut.top;
159 int bottom = from->sys->strut.bottom;
160 if (left == 0 && right == 0 && top == 0 && bottom == 0)
162 to->x += scale*(left );
163 to->y += scale*(top );
164 to->w -= scale*(left+right);
165 to->h -= scale*(top+bottom);
169 static int strut_add(win_t *root, win_t *win)
171 /* Get X11 strut data */
174 unsigned long ret_items, bytes_left;
175 unsigned char *xdata;
176 int status = XGetWindowProperty(win->sys->dpy, win->sys->xid,
177 atoms[net_strut], 0L, 4L, False, XA_CARDINAL,
178 &ret_type, &ret_size, &ret_items, &bytes_left, &xdata);
179 if (status != Success || ret_size != 32 || ret_items != 4)
182 win->sys->strut.left = ((int*)xdata)[0];
183 win->sys->strut.right = ((int*)xdata)[1];
184 win->sys->strut.top = ((int*)xdata)[2];
185 win->sys->strut.bottom = ((int*)xdata)[3];
186 for (list_t *cur = screens; cur; cur = cur->next)
187 strut_copy(cur->data, win, 1);
188 return strut_copy(root, win, 1);
191 static int strut_del(win_t *root, win_t *win)
193 for (list_t *cur = screens; cur; cur = cur->next)
194 strut_copy(cur->data, win, -1);
195 return strut_copy(root, win, -1);
198 /* Window functions */
199 static win_t *win_new(Display *dpy, Window xid)
201 XWindowAttributes attr;
202 if (XGetWindowAttributes(dpy, xid, &attr))
203 if (attr.override_redirect)
205 win_t *win = new0(win_t);
209 win->h = attr.height;
210 win->sys = new0(win_sys_t);
213 printf("win_new: %p = %p, %d (%d,%d %dx%d)\n",
215 win->x, win->y, win->w, win->h);
219 static int win_cmp(const void *_a, const void *_b)
221 const win_t *a = _a, *b = _b;
222 if (a->sys->dpy < b->sys->dpy) return -1;
223 if (a->sys->dpy > b->sys->dpy) return 1;
224 if (a->sys->xid < b->sys->xid) return -1;
225 if (a->sys->xid > b->sys->xid) return 1;
229 static win_t *win_find(Display *dpy, Window xid, int create)
233 //printf("win_find: %p, %d\n", dpy, (int)xid);
234 win_sys_t sys = {.dpy=dpy, .xid=xid};
235 win_t tmp = {.sys=&sys};
236 win_t **old = NULL, *new = NULL;
237 if ((old = tfind(&tmp, &cache, win_cmp)))
239 if (create && (new = win_new(dpy,xid)))
240 tsearch(new, &cache, win_cmp);
244 static void win_remove(win_t *win)
246 tdelete(win, &cache, win_cmp);
251 static int win_viewable(win_t *win)
253 XWindowAttributes attr;
254 if (XGetWindowAttributes(win->sys->dpy, win->sys->xid, &attr))
255 return attr.map_state == IsViewable;
260 /* Drawing functions */
261 static unsigned long get_color(Display *dpy, const char *name)
264 int screen = DefaultScreen(dpy);
265 Colormap cmap = DefaultColormap(dpy, screen);
266 XAllocNamedColor(dpy, cmap, name, &color, &color);
271 static void process_event(int type, XEvent *ev, win_t *root)
273 Display *dpy = root->sys->dpy;
275 //printf("event: %d\n", type);
277 /* Common data for all these events ... */
278 ptr_t ptr; mod_t mod;
279 if (type == KeyPress || type == KeyRelease ||
280 type == ButtonPress || type == ButtonRelease ||
281 type == MotionNotify) {
282 Window xid = getfocus(root, ev);
283 if (!(win = win_find(dpy,xid,0)))
286 mod = x2mod(ev->xkey.state, type==KeyRelease||type==ButtonRelease);
289 /* Split based on event */
290 if (type == KeyPress) {
291 while (XCheckTypedEvent(dpy, KeyPress, ev));
292 KeySym sym = XKeycodeToKeysym(dpy, ev->xkey.keycode, 0);
293 printf("got key %c %hhx\n", x2key(sym), mod2int(mod));
294 wm_handle_key(win, x2key(sym), mod, ptr);
296 else if (type == KeyRelease) {
297 //printf("release: %d\n", type);
299 else if (type == ButtonPress) {
300 if (wm_handle_key(win, x2btn(ev->xbutton.button), mod, ptr))
301 XGrabPointer(dpy, ev->xbutton.root, True, PointerMotionMask|ButtonReleaseMask,
302 GrabModeAsync, GrabModeAsync, None, None, CurrentTime);
304 printf("resending event\n");
305 XSendEvent(win->sys->dpy, ev->xbutton.window, True, NoEventMask, ev);
306 XSendEvent(win->sys->dpy, ev->xbutton.window, False, NoEventMask, ev);
307 XSendEvent(win->sys->dpy, ev->xbutton.root, True, NoEventMask, ev);
308 XSendEvent(win->sys->dpy, ev->xbutton.root, False, NoEventMask, ev);
309 XSendEvent(win->sys->dpy, ev->xbutton.subwindow, True, NoEventMask, ev);
310 XSendEvent(win->sys->dpy, ev->xbutton.subwindow, False, NoEventMask, ev);
313 else if (type == ButtonRelease) {
314 XUngrabPointer(dpy, CurrentTime);
315 wm_handle_key(win, x2btn(ev->xbutton.button), mod, ptr);
317 else if (type == MotionNotify) {
318 while (XCheckTypedEvent(dpy, MotionNotify, ev));
319 wm_handle_ptr(win, ptr);
321 else if (type == EnterNotify || type == LeaveNotify) {
322 printf("enter: %d\n", type);
323 key_t key = EnterNotify ? key_enter : key_leave;
324 if ((win = win_find(dpy,ev->xcrossing.window,0)))
325 wm_handle_key(win, key, MOD(), PTR());
327 else if (type == FocusIn || type == FocusOut) {
328 //printf("focus: %d\n", type);
329 key_t key = FocusIn ? key_focus : key_unfocus;
330 if ((win = win_find(dpy,ev->xfocus.window,0)))
331 wm_handle_key(win, key, MOD(), PTR());
333 else if (type == ConfigureNotify) {
334 printf("configure: %d\n", type);
336 else if (type == MapNotify) {
337 printf("map: %d\n", type);
339 else if (type == UnmapNotify) {
340 if ((win = win_find(dpy,ev->xunmap.window,0)) &&
341 win->sys->state == st_show) {
342 if (!strut_del(root, win))
346 win->sys->state = st_hide;
349 else if (type == DestroyNotify) {
350 //printf("destroy: %d\n", type);
351 if ((win = win_find(dpy,ev->xdestroywindow.window,0)))
354 else if (type == ConfigureRequest) {
355 XConfigureRequestEvent *cre = &ev->xconfigurerequest;
356 printf("configure_req: %d - %x, (0x%lx) %dx%d @ %d,%d\n",
357 type, (int)cre->window, cre->value_mask,
358 cre->height, cre->width, cre->x, cre->y);
359 XConfigureWindow(dpy, cre->window, cre->value_mask, &(XWindowChanges){
363 .height = cre->height,
366 /* This seems necessary for, but causes flicker
367 * there could be a better way to do this */
368 if ((win = win_find(dpy,ev->xmaprequest.window,0)))
369 sys_move(win, win->x, win->y, win->w, win->h);
371 else if (type == MapRequest) {
372 printf("map_req: %d\n", type);
373 if ((win = win_find(dpy,ev->xmaprequest.window,1))) {
374 if (!strut_add(root, win))
379 XMapWindow(dpy,ev->xmaprequest.window);
382 printf("unknown event: %d\n", type);
386 static int xerror(Display *dpy, XErrorEvent *err)
388 if (err->error_code == BadWindow ||
389 (err->request_code == X_SetInputFocus && err->error_code == BadMatch ) ||
390 (err->request_code == X_PolyText8 && err->error_code == BadDrawable) ||
391 (err->request_code == X_PolyFillRectangle && err->error_code == BadDrawable) ||
392 (err->request_code == X_PolySegment && err->error_code == BadDrawable) ||
393 (err->request_code == X_ConfigureWindow && err->error_code == BadMatch ) ||
394 (err->request_code == X_GrabButton && err->error_code == BadAccess ) ||
395 (err->request_code == X_GrabKey && err->error_code == BadAccess ) ||
396 (err->request_code == X_CopyArea && err->error_code == BadDrawable))
398 return xerrorxlib(dpy, err);
401 /********************
403 ********************/
404 void sys_move(win_t *win, int x, int y, int w, int h)
406 //printf("sys_move: %p - %d,%d %dx%d\n", win, x, y, w, h);
408 win->x = x; win->y = y;
409 win->w = MAX(w,1+b); win->h = MAX(h,1+b);
410 w = MAX(w-b,1); h = MAX(h-b,1);
411 XMoveResizeWindow(win->sys->dpy, win->sys->xid, x, y, w, h);
413 /* Flush events, so moving window doesn't cause re-focus
414 * There's probably a better way to do this */
416 XSync(win->sys->dpy, False);
417 while (XCheckMaskEvent(win->sys->dpy, EnterWindowMask|LeaveWindowMask, &ev))
418 printf("Skipping enter/leave event\n");
421 void sys_raise(win_t *win)
423 //printf("sys_raise: %p\n", win);
424 XRaiseWindow(win->sys->dpy, win->sys->xid);
427 void sys_focus(win_t *win)
429 //printf("sys_focus: %p\n", win);
431 /* Set border on focused window */
432 static win_t *last = NULL;
434 XSetWindowBorder(last->sys->dpy, last->sys->xid, colors[clr_unfocus]);
435 XSetWindowBorder(win->sys->dpy, win->sys->xid, colors[clr_focus]);
436 XSetWindowBorderWidth(win->sys->dpy, win->sys->xid, BORDER);
439 /* Set actual focus */
440 XSetInputFocus(win->sys->dpy, win->sys->xid,
441 RevertToPointerRoot, CurrentTime);
442 XSendEvent(win->sys->dpy, win->sys->xid, False, NoEventMask, &(XEvent){
443 .type = ClientMessage,
444 .xclient.window = win->sys->xid,
445 .xclient.message_type = atoms[wm_proto],
446 .xclient.format = 32,
447 .xclient.data.l[0] = atoms[wm_focus],
448 .xclient.data.l[1] = CurrentTime,
452 void sys_show(win_t *win, state_t state)
454 win->sys->state = state;
457 printf("sys_show: show\n");
458 XMapWindow(win->sys->dpy, win->sys->xid);
461 printf("sys_show: full\n");
464 printf("sys_show: shade\n");
467 printf("sys_show: icon\n");
470 printf("sys_show: hide\n");
471 XUnmapWindow(win->sys->dpy, win->sys->xid);
476 void sys_watch(win_t *win, Key_t key, mod_t mod)
478 //printf("sys_watch: %p - %x %hhx\n", win, key, mod);
479 XWindowAttributes attr;
480 XGetWindowAttributes(win->sys->dpy, win->sys->xid, &attr);
481 long mask = attr.your_event_mask;
482 if (key_mouse0 <= key && key <= key_mouse7)
483 XGrabButton(win->sys->dpy, btn2x(key), mod2x(mod), win->sys->xid, False,
484 mod.up ? ButtonReleaseMask : ButtonPressMask,
485 GrabModeAsync, GrabModeAsync, None, None);
486 else if (key == key_enter)
487 XSelectInput(win->sys->dpy, win->sys->xid, EnterWindowMask|mask);
488 else if (key == key_leave)
489 XSelectInput(win->sys->dpy, win->sys->xid, LeaveWindowMask|mask);
490 else if (key == key_focus || key == key_unfocus)
491 XSelectInput(win->sys->dpy, win->sys->xid, FocusChangeMask|mask);
493 XGrabKey(win->sys->dpy, XKeysymToKeycode(win->sys->dpy, key2x(key)),
494 mod2x(mod), win->sys->xid, True, GrabModeAsync, GrabModeAsync);
497 void sys_unwatch(win_t *win, Key_t key, mod_t mod)
499 if (key_mouse0 <= key && key <= key_mouse7)
500 XUngrabButton(win->sys->dpy, btn2x(key), mod2x(mod), win->sys->xid);
503 list_t *sys_info(win_t *win)
505 /* Use global copy of screens so we can add struts */
506 if (screens == NULL) {
508 XineramaScreenInfo *info = NULL;
509 if (XineramaIsActive(win->sys->dpy))
510 info = XineramaQueryScreens(win->sys->dpy, &n);
512 win_t *screen = new0(win_t);
514 return list_insert(NULL, screen);
516 for (int i = 0; i < n; i++) {
517 win_t *screen = new0(win_t);
518 screen->x = info[i].x_org;
519 screen->y = info[i].y_org;
520 screen->w = info[i].width;
521 screen->h = info[i].height;
522 screens = list_append(screens, screen);
528 win_t *sys_init(void)
533 /* Open the display */
534 if (!(dpy = XOpenDisplay(NULL)))
535 error("Unable to get display");
536 if (!(xid = DefaultRootWindow(dpy)))
537 error("Unable to get root window");
540 atoms[wm_proto] = XInternAtom(dpy, "WM_PROTOCOLS", False);
541 atoms[wm_focus] = XInternAtom(dpy, "WM_TAKE_FOCUS", False);
542 atoms[net_strut] = XInternAtom(dpy, "_NET_WM_STRUT", False);
544 colors[clr_focus] = get_color(dpy, "#a0a0ff");
545 colors[clr_unfocus] = get_color(dpy, "#101066");
546 colors[clr_urgent] = get_color(dpy, "#ff0000");
547 printf("colors = #%06lx #%06lx #%06lx\n", colors[0], colors[1], colors[2]);
549 /* Select window management events */
550 XSelectInput(dpy, xid, SubstructureRedirectMask|SubstructureNotifyMask);
551 XSetInputFocus(dpy, None, RevertToNone, CurrentTime);
552 xerrorxlib = XSetErrorHandler(xerror);
554 return win_find(dpy, xid, 1);
557 void sys_run(win_t *root)
559 /* Add each initial window */
561 Window par, xid, *kids = NULL;
562 if (XQueryTree(root->sys->dpy, root->sys->xid,
563 &par, &xid, &kids, &nkids))
564 for(int i = 0; i < nkids; i++) {
565 win_t *win = win_find(root->sys->dpy, kids[i], 1);
566 if (win && win_viewable(win) && !strut_add(root,win))
569 wm_update(); // For struts
575 XNextEvent(root->sys->dpy, &ev);
576 process_event(ev.type, &ev, root);