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
60 static Atom atoms[natoms];
61 static int (*xerrorxlib)(Display *, XErrorEvent *);
62 static unsigned long colors[ncolors];
63 static list_t *screens;
65 /* Conversion functions */
66 static keymap_t key2sym[] = {
67 {key_left , XK_Left },
68 {key_right , XK_Right},
70 {key_down , XK_Down },
71 {key_home , XK_Home },
73 {key_pageup , XK_Prior},
74 {key_pagedown, XK_Next },
90 static mod_t x2mod(unsigned int state, int up)
93 .alt = !!(state & Mod1Mask ),
94 .ctrl = !!(state & ControlMask),
95 .shift = !!(state & ShiftMask ),
96 .win = !!(state & Mod4Mask ),
101 static unsigned int mod2x(mod_t mod)
103 return (mod.alt ? Mod1Mask : 0)
104 | (mod.ctrl ? ControlMask : 0)
105 | (mod.shift ? ShiftMask : 0)
106 | (mod.win ? Mod4Mask : 0);
110 static Key_t x2key(KeySym sym)
112 keymap_t *km = map_getr(key2sym,sym);
113 return km ? km->key : sym;
116 static KeySym key2x(Key_t key)
118 keymap_t *km = map_get(key2sym,key);
119 return km ? km->sym : key;
122 static Key_t x2btn(int btn)
124 return btn + key_mouse0;
127 static int btn2x(Key_t key)
129 return key - key_mouse0;
133 static ptr_t x2ptr(XEvent *_ev)
135 XKeyEvent *ev = &_ev->xkey;
136 return (ptr_t){ev->x, ev->y, ev->x_root, ev->y_root};
139 static Window getfocus(win_t *root, XEvent *event)
142 Window focus = PointerRoot;
143 if (event->type == KeyPress || event->type == KeyRelease)
144 XGetInputFocus(root->sys->dpy, &focus, &revert);
145 if (focus == PointerRoot)
146 focus = event->xkey.subwindow;
148 focus = event->xkey.window;
153 * Struts are spaces at the edges of the screen that are used by
154 * toolbars and statusbars such as dzen. */
155 static int strut_copy(win_t *to, win_t *from, int scale)
157 int left = from->sys->strut.left;
158 int right = from->sys->strut.right;
159 int top = from->sys->strut.top;
160 int bottom = from->sys->strut.bottom;
161 if (left == 0 && right == 0 && top == 0 && bottom == 0)
163 to->x += scale*(left );
164 to->y += scale*(top );
165 to->w -= scale*(left+right);
166 to->h -= scale*(top+bottom);
170 static int strut_add(win_t *root, win_t *win)
172 /* Get X11 strut data */
175 unsigned long ret_items, bytes_left;
176 unsigned char *xdata;
177 int status = XGetWindowProperty(win->sys->dpy, win->sys->xid,
178 atoms[net_strut], 0L, 4L, False, XA_CARDINAL,
179 &ret_type, &ret_size, &ret_items, &bytes_left, &xdata);
180 if (status != Success || ret_size != 32 || ret_items != 4)
183 win->sys->strut.left = ((int*)xdata)[0];
184 win->sys->strut.right = ((int*)xdata)[1];
185 win->sys->strut.top = ((int*)xdata)[2];
186 win->sys->strut.bottom = ((int*)xdata)[3];
187 for (list_t *cur = screens; cur; cur = cur->next)
188 strut_copy(cur->data, win, 1);
189 return strut_copy(root, win, 1);
192 static int strut_del(win_t *root, win_t *win)
194 for (list_t *cur = screens; cur; cur = cur->next)
195 strut_copy(cur->data, win, -1);
196 return strut_copy(root, win, -1);
199 /* Window functions */
200 static win_t *win_new(Display *dpy, Window xid)
202 XWindowAttributes attr;
203 if (XGetWindowAttributes(dpy, xid, &attr))
204 if (attr.override_redirect)
206 win_t *win = new0(win_t);
210 win->h = attr.height;
211 win->sys = new0(win_sys_t);
214 printf("win_new: %p = %p, %d (%d,%d %dx%d)\n",
216 win->x, win->y, win->w, win->h);
220 static int win_cmp(const void *_a, const void *_b)
222 const win_t *a = _a, *b = _b;
223 if (a->sys->dpy < b->sys->dpy) return -1;
224 if (a->sys->dpy > b->sys->dpy) return 1;
225 if (a->sys->xid < b->sys->xid) return -1;
226 if (a->sys->xid > b->sys->xid) return 1;
230 static win_t *win_find(Display *dpy, Window xid, int create)
234 //printf("win_find: %p, %d\n", dpy, (int)xid);
235 win_sys_t sys = {.dpy=dpy, .xid=xid};
236 win_t tmp = {.sys=&sys};
237 win_t **old = NULL, *new = NULL;
238 if ((old = tfind(&tmp, &cache, win_cmp)))
240 if (create && (new = win_new(dpy,xid)))
241 tsearch(new, &cache, win_cmp);
245 static void win_remove(win_t *win)
247 tdelete(win, &cache, win_cmp);
252 static int win_viewable(win_t *win)
254 XWindowAttributes attr;
255 if (XGetWindowAttributes(win->sys->dpy, win->sys->xid, &attr))
256 return attr.map_state == IsViewable;
261 /* Drawing functions */
262 static unsigned long get_color(Display *dpy, const char *name)
265 int screen = DefaultScreen(dpy);
266 Colormap cmap = DefaultColormap(dpy, screen);
267 XAllocNamedColor(dpy, cmap, name, &color, &color);
272 static void process_event(int type, XEvent *ev, win_t *root)
274 Display *dpy = root->sys->dpy;
276 //printf("event: %d\n", type);
278 /* Common data for all these events ... */
279 ptr_t ptr = {}; mod_t mod = {};
280 if (type == KeyPress || type == KeyRelease ||
281 type == ButtonPress || type == ButtonRelease ||
282 type == MotionNotify) {
283 Window xid = getfocus(root, ev);
284 if (!(win = win_find(dpy,xid,0)))
287 mod = x2mod(ev->xkey.state, type==KeyRelease||type==ButtonRelease);
290 /* Split based on event */
291 if (type == KeyPress) {
292 while (XCheckTypedEvent(dpy, KeyPress, ev));
293 KeySym sym = XKeycodeToKeysym(dpy, ev->xkey.keycode, 0);
294 printf("got key %c %hhx\n", x2key(sym), mod2int(mod));
295 wm_handle_key(win, x2key(sym), mod, ptr);
297 else if (type == KeyRelease) {
298 //printf("release: %d\n", type);
300 else if (type == ButtonPress) {
301 if (wm_handle_key(win, x2btn(ev->xbutton.button), mod, ptr))
302 XGrabPointer(dpy, ev->xbutton.root, True, PointerMotionMask|ButtonReleaseMask,
303 GrabModeAsync, GrabModeAsync, None, None, CurrentTime);
305 printf("resending event\n");
306 XSendEvent(win->sys->dpy, ev->xbutton.window, True, NoEventMask, ev);
307 XSendEvent(win->sys->dpy, ev->xbutton.window, False, NoEventMask, ev);
308 XSendEvent(win->sys->dpy, ev->xbutton.root, True, NoEventMask, ev);
309 XSendEvent(win->sys->dpy, ev->xbutton.root, False, NoEventMask, ev);
310 XSendEvent(win->sys->dpy, ev->xbutton.subwindow, True, NoEventMask, ev);
311 XSendEvent(win->sys->dpy, ev->xbutton.subwindow, False, NoEventMask, ev);
314 else if (type == ButtonRelease) {
315 XUngrabPointer(dpy, CurrentTime);
316 wm_handle_key(win, x2btn(ev->xbutton.button), mod, ptr);
318 else if (type == MotionNotify) {
319 while (XCheckTypedEvent(dpy, MotionNotify, ev));
320 wm_handle_ptr(win, ptr);
322 else if (type == EnterNotify || type == LeaveNotify) {
323 printf("enter: %d\n", type);
324 key_t key = EnterNotify ? key_enter : key_leave;
325 if ((win = win_find(dpy,ev->xcrossing.window,0)))
326 wm_handle_key(win, key, MOD(), PTR());
328 else if (type == FocusIn || type == FocusOut) {
329 //printf("focus: %d\n", type);
330 key_t key = FocusIn ? key_focus : key_unfocus;
331 if ((win = win_find(dpy,ev->xfocus.window,0)))
332 wm_handle_key(win, key, MOD(), PTR());
334 else if (type == ConfigureNotify) {
335 printf("configure: %d\n", type);
337 else if (type == MapNotify) {
338 printf("map: %d\n", type);
340 else if (type == UnmapNotify) {
341 if ((win = win_find(dpy,ev->xunmap.window,0)) &&
342 win->sys->state == st_show) {
343 if (!strut_del(root, win))
347 win->sys->state = st_hide;
350 else if (type == DestroyNotify) {
351 //printf("destroy: %d\n", type);
352 if ((win = win_find(dpy,ev->xdestroywindow.window,0)))
355 else if (type == ConfigureRequest) {
356 XConfigureRequestEvent *cre = &ev->xconfigurerequest;
357 printf("configure_req: %d - %x, (0x%lx) %dx%d @ %d,%d\n",
358 type, (int)cre->window, cre->value_mask,
359 cre->height, cre->width, cre->x, cre->y);
360 XConfigureWindow(dpy, cre->window, cre->value_mask, &(XWindowChanges){
364 .height = cre->height,
367 /* This seems necessary for, but causes flicker
368 * there could be a better way to do this */
369 if ((win = win_find(dpy,ev->xmaprequest.window,0)))
370 sys_move(win, win->x, win->y, win->w, win->h);
372 else if (type == MapRequest) {
373 printf("map_req: %d\n", type);
374 if ((win = win_find(dpy,ev->xmaprequest.window,1))) {
375 if (!strut_add(root, win))
380 XMapWindow(dpy,ev->xmaprequest.window);
383 printf("unknown event: %d\n", type);
387 static int xerror(Display *dpy, XErrorEvent *err)
389 if (err->error_code == BadWindow ||
390 (err->request_code == X_SetInputFocus && err->error_code == BadMatch ) ||
391 (err->request_code == X_PolyText8 && err->error_code == BadDrawable) ||
392 (err->request_code == X_PolyFillRectangle && err->error_code == BadDrawable) ||
393 (err->request_code == X_PolySegment && err->error_code == BadDrawable) ||
394 (err->request_code == X_ConfigureWindow && err->error_code == BadMatch ) ||
395 (err->request_code == X_GrabButton && err->error_code == BadAccess ) ||
396 (err->request_code == X_GrabKey && err->error_code == BadAccess ) ||
397 (err->request_code == X_CopyArea && err->error_code == BadDrawable))
399 return xerrorxlib(dpy, err);
402 /********************
404 ********************/
405 void sys_move(win_t *win, int x, int y, int w, int h)
407 //printf("sys_move: %p - %d,%d %dx%d\n", win, x, y, w, h);
409 win->x = x; win->y = y;
410 win->w = MAX(w,1+b); win->h = MAX(h,1+b);
411 w = MAX(w-b,1); h = MAX(h-b,1);
412 XMoveResizeWindow(win->sys->dpy, win->sys->xid, x, y, w, h);
414 /* Flush events, so moving window doesn't cause re-focus
415 * There's probably a better way to do this */
417 XSync(win->sys->dpy, False);
418 while (XCheckMaskEvent(win->sys->dpy, EnterWindowMask|LeaveWindowMask, &ev))
419 printf("Skipping enter/leave event\n");
422 void sys_raise(win_t *win)
424 //printf("sys_raise: %p\n", win);
425 XRaiseWindow(win->sys->dpy, win->sys->xid);
428 void sys_focus(win_t *win)
430 //printf("sys_focus: %p\n", win);
432 /* Set border on focused window */
433 static win_t *last = NULL;
435 XSetWindowBorder(last->sys->dpy, last->sys->xid, colors[clr_unfocus]);
436 XSetWindowBorder(win->sys->dpy, win->sys->xid, colors[clr_focus]);
437 XSetWindowBorderWidth(win->sys->dpy, win->sys->xid, BORDER);
440 /* Set actual focus */
441 XSetInputFocus(win->sys->dpy, win->sys->xid,
442 RevertToPointerRoot, CurrentTime);
443 XSendEvent(win->sys->dpy, win->sys->xid, False, NoEventMask, &(XEvent){
444 .type = ClientMessage,
445 .xclient.window = win->sys->xid,
446 .xclient.message_type = atoms[wm_proto],
447 .xclient.format = 32,
448 .xclient.data.l[0] = atoms[wm_focus],
449 .xclient.data.l[1] = CurrentTime,
453 void sys_show(win_t *win, state_t state)
455 win->sys->state = state;
458 printf("sys_show: show\n");
459 XMapWindow(win->sys->dpy, win->sys->xid);
462 printf("sys_show: full\n");
465 printf("sys_show: shade\n");
468 printf("sys_show: icon\n");
471 printf("sys_show: hide\n");
472 XUnmapWindow(win->sys->dpy, win->sys->xid);
477 void sys_watch(win_t *win, Key_t key, mod_t mod)
479 //printf("sys_watch: %p - %x %hhx\n", win, key, mod);
480 XWindowAttributes attr;
481 XGetWindowAttributes(win->sys->dpy, win->sys->xid, &attr);
482 long mask = attr.your_event_mask;
483 if (key_mouse0 <= key && key <= key_mouse7)
484 XGrabButton(win->sys->dpy, btn2x(key), mod2x(mod), win->sys->xid, False,
485 mod.up ? ButtonReleaseMask : ButtonPressMask,
486 GrabModeAsync, GrabModeAsync, None, None);
487 else if (key == key_enter)
488 XSelectInput(win->sys->dpy, win->sys->xid, EnterWindowMask|mask);
489 else if (key == key_leave)
490 XSelectInput(win->sys->dpy, win->sys->xid, LeaveWindowMask|mask);
491 else if (key == key_focus || key == key_unfocus)
492 XSelectInput(win->sys->dpy, win->sys->xid, FocusChangeMask|mask);
494 XGrabKey(win->sys->dpy, XKeysymToKeycode(win->sys->dpy, key2x(key)),
495 mod2x(mod), win->sys->xid, True, GrabModeAsync, GrabModeAsync);
498 void sys_unwatch(win_t *win, Key_t key, mod_t mod)
500 if (key_mouse0 <= key && key <= key_mouse7)
501 XUngrabButton(win->sys->dpy, btn2x(key), mod2x(mod), win->sys->xid);
504 list_t *sys_info(win_t *win)
506 /* Use global copy of screens so we can add struts */
507 if (screens == NULL) {
509 XineramaScreenInfo *info = NULL;
510 if (XineramaIsActive(win->sys->dpy))
511 info = XineramaQueryScreens(win->sys->dpy, &n);
513 win_t *screen = new0(win_t);
515 return list_insert(NULL, screen);
517 for (int i = 0; i < n; i++) {
518 win_t *screen = new0(win_t);
519 screen->x = info[i].x_org;
520 screen->y = info[i].y_org;
521 screen->w = info[i].width;
522 screen->h = info[i].height;
523 screens = list_append(screens, screen);
529 win_t *sys_init(void)
534 /* Open the display */
535 if (!(dpy = XOpenDisplay(NULL)))
536 error("Unable to get display");
537 if (!(xid = DefaultRootWindow(dpy)))
538 error("Unable to get root window");
541 atoms[wm_proto] = XInternAtom(dpy, "WM_PROTOCOLS", False);
542 atoms[wm_focus] = XInternAtom(dpy, "WM_TAKE_FOCUS", False);
543 atoms[net_strut] = XInternAtom(dpy, "_NET_WM_STRUT", False);
545 colors[clr_focus] = get_color(dpy, "#a0a0ff");
546 colors[clr_unfocus] = get_color(dpy, "#101066");
547 colors[clr_urgent] = get_color(dpy, "#ff0000");
548 printf("colors = #%06lx #%06lx #%06lx\n", colors[0], colors[1], colors[2]);
550 /* Select window management events */
551 XSelectInput(dpy, xid, SubstructureRedirectMask|SubstructureNotifyMask);
552 XSetInputFocus(dpy, None, RevertToNone, CurrentTime);
553 xerrorxlib = XSetErrorHandler(xerror);
555 return win_find(dpy, xid, 1);
558 void sys_run(win_t *root)
560 /* Add each initial window */
562 Window par, xid, *kids = NULL;
563 if (XQueryTree(root->sys->dpy, root->sys->xid,
564 &par, &xid, &kids, &nkids))
565 for(int i = 0; i < nkids; i++) {
566 win_t *win = win_find(root->sys->dpy, kids[i], 1);
567 if (win && win_viewable(win) && !strut_add(root,win))
570 wm_update(); // For struts
577 XNextEvent(root->sys->dpy, &ev);
578 process_event(ev.type, &ev, root);