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
22 #include <X11/Xproto.h>
23 #include <X11/Xatom.h>
24 #include <X11/keysym.h>
25 #include <X11/extensions/Xinerama.h>
35 /* Internal structures */
40 int left, right, top, bottom;
51 wm_proto, wm_focus, net_strut, natoms
55 clr_focus, clr_unfocus, clr_urgent, ncolors
61 static Atom atoms[natoms];
62 static int (*xerrorxlib)(Display *, XErrorEvent *);
63 static unsigned long colors[ncolors];
64 static list_t *screens;
66 /* Conversion functions */
67 static keymap_t key2sym[] = {
68 {key_left , XK_Left },
69 {key_right , XK_Right},
71 {key_down , XK_Down },
72 {key_home , XK_Home },
74 {key_pageup , XK_Prior},
75 {key_pagedown, XK_Next },
91 static mod_t x2mod(unsigned int state, int up)
94 .alt = !!(state & Mod1Mask ),
95 .ctrl = !!(state & ControlMask),
96 .shift = !!(state & ShiftMask ),
97 .win = !!(state & Mod4Mask ),
102 static unsigned int mod2x(mod_t mod)
104 return (mod.alt ? Mod1Mask : 0)
105 | (mod.ctrl ? ControlMask : 0)
106 | (mod.shift ? ShiftMask : 0)
107 | (mod.win ? Mod4Mask : 0);
111 static Key_t x2key(KeySym sym)
113 keymap_t *km = map_getr(key2sym,sym);
114 return km ? km->key : sym;
117 static KeySym key2x(Key_t key)
119 keymap_t *km = map_get(key2sym,key);
120 return km ? km->sym : key;
123 static Key_t x2btn(int btn)
125 return btn + key_mouse0;
128 static int btn2x(Key_t key)
130 return key - key_mouse0;
134 static ptr_t x2ptr(XEvent *_ev)
136 XKeyEvent *ev = &_ev->xkey;
137 return (ptr_t){ev->x, ev->y, ev->x_root, ev->y_root};
140 static Window getfocus(win_t *root, XEvent *event)
143 Window focus = PointerRoot;
144 if (event->type == KeyPress || event->type == KeyRelease)
145 XGetInputFocus(root->sys->dpy, &focus, &revert);
146 if (focus == PointerRoot)
147 focus = event->xkey.subwindow;
149 focus = event->xkey.window;
154 * Struts are spaces at the edges of the screen that are used by
155 * toolbars and statusbars such as dzen. */
156 static int strut_copy(win_t *to, win_t *from, int scale)
158 int left = from->sys->strut.left;
159 int right = from->sys->strut.right;
160 int top = from->sys->strut.top;
161 int bottom = from->sys->strut.bottom;
162 if (left == 0 && right == 0 && top == 0 && bottom == 0)
164 to->x += scale*(left );
165 to->y += scale*(top );
166 to->w -= scale*(left+right);
167 to->h -= scale*(top+bottom);
171 static int strut_add(win_t *root, win_t *win)
173 /* Get X11 strut data */
176 unsigned long ret_items, bytes_left;
177 unsigned char *xdata;
178 int status = XGetWindowProperty(win->sys->dpy, win->sys->xid,
179 atoms[net_strut], 0L, 4L, False, XA_CARDINAL,
180 &ret_type, &ret_size, &ret_items, &bytes_left, &xdata);
181 if (status != Success || ret_size != 32 || ret_items != 4)
184 win->sys->strut.left = ((int*)xdata)[0];
185 win->sys->strut.right = ((int*)xdata)[1];
186 win->sys->strut.top = ((int*)xdata)[2];
187 win->sys->strut.bottom = ((int*)xdata)[3];
188 for (list_t *cur = screens; cur; cur = cur->next)
189 strut_copy(cur->data, win, 1);
190 return strut_copy(root, win, 1);
193 static int strut_del(win_t *root, win_t *win)
195 for (list_t *cur = screens; cur; cur = cur->next)
196 strut_copy(cur->data, win, -1);
197 return strut_copy(root, win, -1);
200 /* Window functions */
201 static win_t *win_new(Display *dpy, Window xid)
203 XWindowAttributes attr;
204 if (XGetWindowAttributes(dpy, xid, &attr))
205 if (attr.override_redirect)
207 win_t *win = new0(win_t);
211 win->h = attr.height;
212 win->sys = new0(win_sys_t);
215 printf("win_new: %p = %p, %d (%d,%d %dx%d)\n",
217 win->x, win->y, win->w, win->h);
221 static int win_cmp(const void *_a, const void *_b)
223 const win_t *a = _a, *b = _b;
224 if (a->sys->dpy < b->sys->dpy) return -1;
225 if (a->sys->dpy > b->sys->dpy) return 1;
226 if (a->sys->xid < b->sys->xid) return -1;
227 if (a->sys->xid > b->sys->xid) return 1;
231 static win_t *win_find(Display *dpy, Window xid, int create)
235 //printf("win_find: %p, %d\n", dpy, (int)xid);
236 win_sys_t sys = {.dpy=dpy, .xid=xid};
237 win_t tmp = {.sys=&sys};
238 win_t **old = NULL, *new = NULL;
239 if ((old = tfind(&tmp, &cache, win_cmp)))
241 if (create && (new = win_new(dpy,xid)))
242 tsearch(new, &cache, win_cmp);
246 static void win_free(win_t *win)
252 static void win_remove(win_t *win)
254 tdelete(win, &cache, win_cmp);
258 static int win_viewable(win_t *win)
260 XWindowAttributes attr;
261 if (XGetWindowAttributes(win->sys->dpy, win->sys->xid, &attr))
262 return attr.map_state == IsViewable;
267 /* Drawing functions */
268 static unsigned long get_color(Display *dpy, const char *name)
271 int screen = DefaultScreen(dpy);
272 Colormap cmap = DefaultColormap(dpy, screen);
273 XAllocNamedColor(dpy, cmap, name, &color, &color);
278 static void process_event(int type, XEvent *ev, win_t *root)
280 Display *dpy = root->sys->dpy;
282 //printf("event: %d\n", type);
284 /* Common data for all these events ... */
285 ptr_t ptr = {}; mod_t mod = {};
286 if (type == KeyPress || type == KeyRelease ||
287 type == ButtonPress || type == ButtonRelease ||
288 type == MotionNotify) {
289 Window xid = getfocus(root, ev);
290 if (!(win = win_find(dpy,xid,0)))
293 mod = x2mod(ev->xkey.state, type==KeyRelease||type==ButtonRelease);
296 /* Split based on event */
297 if (type == KeyPress) {
298 while (XCheckTypedEvent(dpy, KeyPress, ev));
299 KeySym sym = XKeycodeToKeysym(dpy, ev->xkey.keycode, 0);
300 printf("got key %c %hhx\n", x2key(sym), mod2int(mod));
301 wm_handle_key(win, x2key(sym), mod, ptr);
303 else if (type == KeyRelease) {
304 //printf("release: %d\n", type);
306 else if (type == ButtonPress) {
307 if (wm_handle_key(win, x2btn(ev->xbutton.button), mod, ptr))
308 XGrabPointer(dpy, ev->xbutton.root, True, PointerMotionMask|ButtonReleaseMask,
309 GrabModeAsync, GrabModeAsync, None, None, CurrentTime);
311 printf("resending event\n");
312 XSendEvent(win->sys->dpy, ev->xbutton.window, True, NoEventMask, ev);
313 XSendEvent(win->sys->dpy, ev->xbutton.window, False, NoEventMask, ev);
314 XSendEvent(win->sys->dpy, ev->xbutton.root, True, NoEventMask, ev);
315 XSendEvent(win->sys->dpy, ev->xbutton.root, False, NoEventMask, ev);
316 XSendEvent(win->sys->dpy, ev->xbutton.subwindow, True, NoEventMask, ev);
317 XSendEvent(win->sys->dpy, ev->xbutton.subwindow, False, NoEventMask, ev);
320 else if (type == ButtonRelease) {
321 XUngrabPointer(dpy, CurrentTime);
322 wm_handle_key(win, x2btn(ev->xbutton.button), mod, ptr);
324 else if (type == MotionNotify) {
325 while (XCheckTypedEvent(dpy, MotionNotify, ev));
326 wm_handle_ptr(win, ptr);
328 else if (type == EnterNotify || type == LeaveNotify) {
329 printf("enter: %d\n", type);
330 key_t key = EnterNotify ? key_enter : key_leave;
331 if ((win = win_find(dpy,ev->xcrossing.window,0)))
332 wm_handle_key(win, key, MOD(), PTR());
334 else if (type == FocusIn || type == FocusOut) {
335 //printf("focus: %d\n", type);
336 key_t key = FocusIn ? key_focus : key_unfocus;
337 if ((win = win_find(dpy,ev->xfocus.window,0)))
338 wm_handle_key(win, key, MOD(), PTR());
340 else if (type == ConfigureNotify) {
341 printf("configure: %d\n", type);
343 else if (type == MapNotify) {
344 printf("map: %d\n", type);
346 else if (type == UnmapNotify) {
347 if ((win = win_find(dpy,ev->xunmap.window,0)) &&
348 win->sys->state == st_show) {
349 if (!strut_del(root, win))
353 win->sys->state = st_hide;
356 else if (type == DestroyNotify) {
357 //printf("destroy: %d\n", type);
358 if ((win = win_find(dpy,ev->xdestroywindow.window,0)))
361 else if (type == ConfigureRequest) {
362 XConfigureRequestEvent *cre = &ev->xconfigurerequest;
363 printf("configure_req: %d - %x, (0x%lx) %dx%d @ %d,%d\n",
364 type, (int)cre->window, cre->value_mask,
365 cre->height, cre->width, cre->x, cre->y);
366 XConfigureWindow(dpy, cre->window, cre->value_mask, &(XWindowChanges){
370 .height = cre->height,
373 /* This seems necessary for, but causes flicker
374 * there could be a better way to do this */
375 if ((win = win_find(dpy,ev->xmaprequest.window,0)))
376 sys_move(win, win->x, win->y, win->w, win->h);
378 else if (type == MapRequest) {
379 printf("map_req: %d\n", type);
380 if ((win = win_find(dpy,ev->xmaprequest.window,1))) {
381 if (!strut_add(root, win))
386 XMapWindow(dpy,ev->xmaprequest.window);
389 printf("unknown event: %d\n", type);
393 static int xerror(Display *dpy, XErrorEvent *err)
395 if (err->error_code == BadWindow ||
396 (err->request_code == X_SetInputFocus && err->error_code == BadMatch ) ||
397 (err->request_code == X_PolyText8 && err->error_code == BadDrawable) ||
398 (err->request_code == X_PolyFillRectangle && err->error_code == BadDrawable) ||
399 (err->request_code == X_PolySegment && err->error_code == BadDrawable) ||
400 (err->request_code == X_ConfigureWindow && err->error_code == BadMatch ) ||
401 (err->request_code == X_GrabButton && err->error_code == BadAccess ) ||
402 (err->request_code == X_GrabKey && err->error_code == BadAccess ) ||
403 (err->request_code == X_CopyArea && err->error_code == BadDrawable))
405 return xerrorxlib(dpy, err);
408 /********************
410 ********************/
411 void sys_move(win_t *win, int x, int y, int w, int h)
413 //printf("sys_move: %p - %d,%d %dx%d\n", win, x, y, w, h);
415 win->x = x; win->y = y;
416 win->w = MAX(w,1+b); win->h = MAX(h,1+b);
417 w = MAX(w-b,1); h = MAX(h-b,1);
418 XMoveResizeWindow(win->sys->dpy, win->sys->xid, x, y, w, h);
420 /* Flush events, so moving window doesn't cause re-focus
421 * There's probably a better way to do this */
423 XSync(win->sys->dpy, False);
424 while (XCheckMaskEvent(win->sys->dpy, EnterWindowMask|LeaveWindowMask, &ev))
425 printf("Skipping enter/leave event\n");
428 void sys_raise(win_t *win)
430 //printf("sys_raise: %p\n", win);
431 XRaiseWindow(win->sys->dpy, win->sys->xid);
434 void sys_focus(win_t *win)
436 //printf("sys_focus: %p\n", win);
438 /* Set border on focused window */
439 static win_t *last = NULL;
441 XSetWindowBorder(last->sys->dpy, last->sys->xid, colors[clr_unfocus]);
442 XSetWindowBorder(win->sys->dpy, win->sys->xid, colors[clr_focus]);
443 XSetWindowBorderWidth(win->sys->dpy, win->sys->xid, BORDER);
446 /* Set actual focus */
447 XSetInputFocus(win->sys->dpy, win->sys->xid,
448 RevertToPointerRoot, CurrentTime);
449 XSendEvent(win->sys->dpy, win->sys->xid, False, NoEventMask, &(XEvent){
450 .type = ClientMessage,
451 .xclient.window = win->sys->xid,
452 .xclient.message_type = atoms[wm_proto],
453 .xclient.format = 32,
454 .xclient.data.l[0] = atoms[wm_focus],
455 .xclient.data.l[1] = CurrentTime,
459 void sys_show(win_t *win, state_t state)
461 win->sys->state = state;
464 printf("sys_show: show\n");
465 XMapWindow(win->sys->dpy, win->sys->xid);
466 XSync(win->sys->dpy, False);
469 printf("sys_show: full\n");
472 printf("sys_show: shade\n");
475 printf("sys_show: icon\n");
478 printf("sys_show: hide\n");
479 XUnmapWindow(win->sys->dpy, win->sys->xid);
484 void sys_watch(win_t *win, Key_t key, mod_t mod)
486 //printf("sys_watch: %p - %x %hhx\n", win, key, mod);
487 XWindowAttributes attr;
488 XGetWindowAttributes(win->sys->dpy, win->sys->xid, &attr);
489 long mask = attr.your_event_mask;
490 if (key_mouse0 <= key && key <= key_mouse7)
491 XGrabButton(win->sys->dpy, btn2x(key), mod2x(mod), win->sys->xid, False,
492 mod.up ? ButtonReleaseMask : ButtonPressMask,
493 GrabModeAsync, GrabModeAsync, None, None);
494 else if (key == key_enter)
495 XSelectInput(win->sys->dpy, win->sys->xid, EnterWindowMask|mask);
496 else if (key == key_leave)
497 XSelectInput(win->sys->dpy, win->sys->xid, LeaveWindowMask|mask);
498 else if (key == key_focus || key == key_unfocus)
499 XSelectInput(win->sys->dpy, win->sys->xid, FocusChangeMask|mask);
501 XGrabKey(win->sys->dpy, XKeysymToKeycode(win->sys->dpy, key2x(key)),
502 mod2x(mod), win->sys->xid, True, GrabModeAsync, GrabModeAsync);
505 void sys_unwatch(win_t *win, Key_t key, mod_t mod)
507 if (key_mouse0 <= key && key <= key_mouse7)
508 XUngrabButton(win->sys->dpy, btn2x(key), mod2x(mod), win->sys->xid);
511 list_t *sys_info(win_t *win)
513 /* Use global copy of screens so we can add struts */
514 if (screens == NULL) {
515 /* Add Xinerama screens */
517 XineramaScreenInfo *info = NULL;
518 if (XineramaIsActive(win->sys->dpy))
519 info = XineramaQueryScreens(win->sys->dpy, &n);
520 for (int i = 0; i < n; i++) {
521 win_t *screen = new0(win_t);
522 screen->x = info[i].x_org;
523 screen->y = info[i].y_org;
524 screen->w = info[i].width;
525 screen->h = info[i].height;
526 screens = list_append(screens, screen);
529 if (screens == NULL) {
530 /* No xinerama support */
531 win_t *screen = new0(win_t);
533 screens = list_insert(NULL, screen);
538 win_t *sys_init(void)
543 /* Open the display */
544 if (!(dpy = XOpenDisplay(NULL)))
545 error("Unable to get display");
546 if (!(xid = DefaultRootWindow(dpy)))
547 error("Unable to get root window");
550 atoms[wm_proto] = XInternAtom(dpy, "WM_PROTOCOLS", False);
551 atoms[wm_focus] = XInternAtom(dpy, "WM_TAKE_FOCUS", False);
552 atoms[net_strut] = XInternAtom(dpy, "_NET_WM_STRUT", False);
554 colors[clr_focus] = get_color(dpy, "#a0a0ff");
555 colors[clr_unfocus] = get_color(dpy, "#101066");
556 colors[clr_urgent] = get_color(dpy, "#ff0000");
557 printf("colors = #%06lx #%06lx #%06lx\n", colors[0], colors[1], colors[2]);
559 /* Select window management events */
560 XSelectInput(dpy, xid, SubstructureRedirectMask|SubstructureNotifyMask);
561 XSetInputFocus(dpy, None, RevertToNone, CurrentTime);
562 xerrorxlib = XSetErrorHandler(xerror);
564 return win_find(dpy, xid, 1);
567 void sys_run(win_t *root)
569 /* Add each initial window */
571 Window par, xid, *kids = NULL;
572 if (XQueryTree(root->sys->dpy, root->sys->xid,
573 &par, &xid, &kids, &nkids)) {
574 for(int i = 0; i < nkids; i++) {
575 win_t *win = win_find(root->sys->dpy, kids[i], 1);
576 if (win && win_viewable(win) && !strut_add(root,win))
581 wm_update(); // For struts
588 XNextEvent(root->sys->dpy, &ev);
589 process_event(ev.type, &ev, root);
598 void sys_free(win_t *root)
600 XCloseDisplay(root->sys->dpy);
602 screens = list_remove(screens, screens, 1);
603 tdestroy(cache, (void(*)(void*))win_free);