birdwm

birdwm - mrgrouse's daily driver fork of suckless' dwm. Contains many patches and is currently loosely maintained.
Log | Files | Refs | README | LICENSE

birdwm.c (72122B)


      1 /* See LICENSE file for copyright and license details.
      2  *
      3  * dynamic window manager is designed like any other X client as well. It is
      4  * driven through handling X events. In contrast to other X clients, a window
      5  * manager selects for SubstructureRedirectMask on the root window, to receive
      6  * events about window (dis-)appearance. Only one X connection at a time is
      7  * allowed to select for this event mask.
      8  *
      9  * The event handlers of birdwm are organized in an array which is accessed
     10  * whenever a new event has been fetched. This allows event dispatching
     11  * in O(1) time.
     12  *
     13  * Each child of the root window is called a client, except windows which have
     14  * set the override_redirect flag. Clients are organized in a linked client
     15  * list on each monitor, the focus history is remembered through a stack list
     16  * on each monitor. Each client contains a bit array to indicate the tags of a
     17  * client.
     18  *
     19  * Keys and tagging rules are organized as arrays and defined in config.h.
     20  *
     21  * To understand everything else, start reading main().
     22  */
     23 #include <errno.h>
     24 #include <locale.h>
     25 #include <signal.h>
     26 #include <stdarg.h>
     27 #include <stdio.h>
     28 #include <stdlib.h>
     29 #include <string.h>
     30 #include <unistd.h>
     31 #include <limits.h>
     32 #include <stdint.h>
     33 #include <sys/types.h>
     34 #include <sys/wait.h>
     35 #include <X11/cursorfont.h>
     36 #include <X11/keysym.h>
     37 #include <X11/Xatom.h>
     38 #include <X11/Xlib.h>
     39 #include <X11/Xproto.h>
     40 #include <X11/Xresource.h>
     41 #include <X11/Xutil.h>
     42 #ifdef XINERAMA
     43 #include <X11/extensions/Xinerama.h>
     44 #endif /* XINERAMA */
     45 #include <X11/Xft/Xft.h>
     46 
     47 #include "drw.h"
     48 #include "util.h"
     49 
     50 /* macros */
     51 #define BUTTONMASK              (ButtonPressMask|ButtonReleaseMask)
     52 #define CLEANMASK(mask)         (mask & ~(numlockmask|LockMask) & (ShiftMask|ControlMask|Mod1Mask|Mod2Mask|Mod3Mask|Mod4Mask|Mod5Mask))
     53 #define INTERSECT(x,y,w,h,m)    (MAX(0, MIN((x)+(w),(m)->wx+(m)->ww) - MAX((x),(m)->wx)) \
     54                                * MAX(0, MIN((y)+(h),(m)->wy+(m)->wh) - MAX((y),(m)->wy)))
     55 #define ISVISIBLE(C)            ((C->tags & C->mon->tagset[C->mon->seltags]))
     56 #define MOUSEMASK               (BUTTONMASK|PointerMotionMask)
     57 #define WIDTH(X)                ((X)->w + 2 * (X)->bw + gappx)
     58 #define HEIGHT(X)               ((X)->h + 2 * (X)->bw + gappx)
     59 #define TAGMASK                 ((1 << LENGTH(tags)) - 1)
     60 #define TEXTW(X)                (drw_fontset_getwidth(drw, (X)) + lrpad)
     61 #define XRDB_LOAD_COLOR(R,V)    if (XrmGetResource(xrdb, R, NULL, &type, &value) == True) { \
     62                                   if (value.addr != NULL && strnlen(value.addr, 8) == 7 && value.addr[0] == '#') { \
     63                                     int i = 1; \
     64                                     for (; i <= 6; i++) { \
     65                                       if (value.addr[i] < 48) break; \
     66                                       if (value.addr[i] > 57 && value.addr[i] < 65) break; \
     67                                       if (value.addr[i] > 70 && value.addr[i] < 97) break; \
     68                                       if (value.addr[i] > 102) break; \
     69                                     } \
     70                                     if (i == 7) { \
     71                                       strncpy(V, value.addr, 7); \
     72                                       V[7] = '\0'; \
     73                                     } \
     74                                   } \
     75                                 }
     76 
     77 #define SYSTEM_TRAY_REQUEST_DOCK    0
     78 /* XEMBED messages */
     79 #define XEMBED_EMBEDDED_NOTIFY      0
     80 #define XEMBED_WINDOW_ACTIVATE      1
     81 #define XEMBED_FOCUS_IN             4
     82 #define XEMBED_MODALITY_ON         10
     83 #define XEMBED_MAPPED              (1 << 0)
     84 #define XEMBED_WINDOW_ACTIVATE      1
     85 #define XEMBED_WINDOW_DEACTIVATE    2
     86 #define VERSION_MAJOR               0
     87 #define VERSION_MINOR               0
     88 #define XEMBED_EMBEDDED_VERSION (VERSION_MAJOR << 16) | VERSION_MINOR
     89 
     90 /* enums */
     91 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
     92 enum { SchemeNorm, SchemeSel }; /* color schemes */
     93 enum { NetSupported, NetWMName, NetWMIcon, NetWMState, NetWMCheck,
     94        NetSystemTray, NetSystemTrayOP, NetSystemTrayOrientation, NetSystemTrayOrientationHorz,
     95        NetWMFullscreen, NetActiveWindow, NetWMWindowType,
     96        NetWMWindowTypeDialog, NetClientList, NetLast }; /* EWMH atoms */
     97 enum { Manager, Xembed, XembedInfo, XLast }; /* Xembed atoms */
     98 enum { WMProtocols, WMDelete, WMState, WMTakeFocus, WMLast }; /* default atoms */
     99 enum { ClkTagBar, ClkLtSymbol, ClkStatusText, ClkWinTitle,
    100        ClkClientWin, ClkRootWin, ClkLast }; /* clicks */
    101 
    102 typedef union {
    103 	int i;
    104 	unsigned int ui;
    105 	float f;
    106 	const void *v;
    107 } Arg;
    108 
    109 typedef struct {
    110 	unsigned int click;
    111 	unsigned int mask;
    112 	unsigned int button;
    113 	void (*func)(const Arg *arg);
    114 	const Arg arg;
    115 } Button;
    116 
    117 typedef struct Monitor Monitor;
    118 typedef struct Client Client;
    119 struct Client {
    120 	char name[256];
    121 	float mina, maxa;
    122 	int x, y, w, h;
    123 	int oldx, oldy, oldw, oldh;
    124 	int basew, baseh, incw, inch, maxw, maxh, minw, minh, hintsvalid;
    125 	int bw, oldbw;
    126 	unsigned int tags;
    127 	int isfixed, isfloating, isurgent, neverfocus, oldstate, isfullscreen;
    128 	unsigned int icw, ich; Picture icon;
    129 	Client *next;
    130 	Client *snext;
    131 	Monitor *mon;
    132 	Window win;
    133 };
    134 
    135 typedef struct {
    136 	unsigned int mod;
    137 	KeySym keysym;
    138 	void (*func)(const Arg *);
    139 	const Arg arg;
    140 } Key;
    141 
    142 typedef struct {
    143 	const char *symbol;
    144 	void (*arrange)(Monitor *);
    145 } Layout;
    146 
    147 struct Monitor {
    148 	char ltsymbol[16];
    149 	float mfact;
    150 	int nmaster;
    151 	int num;
    152 	int by;               /* bar geometry */
    153 	int mx, my, mw, mh;   /* screen size */
    154 	int wx, wy, ww, wh;   /* window area  */
    155 	unsigned int seltags;
    156 	unsigned int sellt;
    157 	unsigned int tagset[2];
    158 	int showbar;
    159 	int topbar;
    160 	Client *clients;
    161 	Client *sel;
    162 	Client *stack;
    163 	Monitor *next;
    164 	Window barwin;
    165 	const Layout *lt[2];
    166 };
    167 
    168 typedef struct {
    169 	const char *class;
    170 	const char *instance;
    171 	const char *title;
    172 	unsigned int tags;
    173 	int isfloating;
    174 	int monitor;
    175 } Rule;
    176 
    177 typedef struct Systray   Systray;
    178 struct Systray {
    179 	Window win;
    180 	Client *icons;
    181 };
    182 
    183 /* function declarations */
    184 static void applyrules(Client *c);
    185 static int applysizehints(Client *c, int *x, int *y, int *w, int *h, int interact);
    186 static void arrange(Monitor *m);
    187 static void arrangemon(Monitor *m);
    188 static void attach(Client *c);
    189 static void attachstack(Client *c);
    190 static void buttonpress(XEvent *e);
    191 static void checkotherwm(void);
    192 static void cleanup(void);
    193 static void cleanupmon(Monitor *mon);
    194 static void clientmessage(XEvent *e);
    195 static void configure(Client *c);
    196 static void configurenotify(XEvent *e);
    197 static void configurerequest(XEvent *e);
    198 static Monitor *createmon(void);
    199 static void destroynotify(XEvent *e);
    200 static void detach(Client *c);
    201 static void detachstack(Client *c);
    202 static Monitor *dirtomon(int dir);
    203 static void drawbar(Monitor *m);
    204 static void drawbars(void);
    205 static void enternotify(XEvent *e);
    206 static void expose(XEvent *e);
    207 static void focus(Client *c);
    208 static void focusin(XEvent *e);
    209 static void focusmon(const Arg *arg);
    210 static void focusstack(const Arg *arg);
    211 static Atom getatomprop(Client *c, Atom prop);
    212 static Picture geticonprop(Window w, unsigned int *icw, unsigned int *ich);
    213 static int getrootptr(int *x, int *y);
    214 static long getstate(Window w);
    215 static unsigned int getsystraywidth();
    216 static int gettextprop(Window w, Atom atom, char *text, unsigned int size);
    217 static void grabbuttons(Client *c, int focused);
    218 static void grabkeys(void);
    219 static void incnmaster(const Arg *arg);
    220 static void keypress(XEvent *e);
    221 static void killclient(const Arg *arg);
    222 static void loadxrdb(void);
    223 static void manage(Window w, XWindowAttributes *wa);
    224 static void mappingnotify(XEvent *e);
    225 static void maprequest(XEvent *e);
    226 static void monocle(Monitor *m);
    227 static void motionnotify(XEvent *e);
    228 static void movemouse(const Arg *arg);
    229 static Client *nexttiled(Client *c);
    230 static void pop(Client *c);
    231 static void propertynotify(XEvent *e);
    232 static void quit(const Arg *arg);
    233 static Monitor *recttomon(int x, int y, int w, int h);
    234 static void removesystrayicon(Client *i);
    235 static void resize(Client *c, int x, int y, int w, int h, int interact);
    236 static void resizebarwin(Monitor *m);
    237 static void resizeclient(Client *c, int x, int y, int w, int h);
    238 static void resizemouse(const Arg *arg);
    239 static void resizerequest(XEvent *e);
    240 static void restack(Monitor *m);
    241 static void run(void);
    242 static void scan(void);
    243 static int sendevent(Window w, Atom proto, int m, long d0, long d1, long d2, long d3, long d4);
    244 static void sendmon(Client *c, Monitor *m);
    245 static void setclientstate(Client *c, long state);
    246 static void setfocus(Client *c);
    247 static void setfullscreen(Client *c, int fullscreen);
    248 static void setlayout(const Arg *arg);
    249 static void setmfact(const Arg *arg);
    250 static void setup(void);
    251 static void seturgent(Client *c, int urg);
    252 static void showhide(Client *c);
    253 static void spawn(const Arg *arg);
    254 static Monitor *systraytomon(Monitor *m);
    255 static void tag(const Arg *arg);
    256 static void tagmon(const Arg *arg);
    257 static void tile(Monitor *m);
    258 static void togglebar(const Arg *arg);
    259 static void togglefloating(const Arg *arg);
    260 static void togglescratch(const Arg *arg);
    261 static void toggletag(const Arg *arg);
    262 static void toggleview(const Arg *arg);
    263 static void freeicon(Client *c);
    264 static void unfocus(Client *c, int setfocus);
    265 static void unmanage(Client *c, int destroyed);
    266 static void unmapnotify(XEvent *e);
    267 static void updatebarpos(Monitor *m);
    268 static void updatebars(void);
    269 static void updateclientlist(void);
    270 static int updategeom(void);
    271 static void updatenumlockmask(void);
    272 static void updatesizehints(Client *c);
    273 static void updatestatus(void);
    274 static void updatesystray(void);
    275 static void updatesystrayicongeom(Client *i, int w, int h);
    276 static void updatesystrayiconstate(Client *i, XPropertyEvent *ev);
    277 static void updatetitle(Client *c);
    278 static void updateicon(Client *c);
    279 static void updatewindowtype(Client *c);
    280 static void updatewmhints(Client *c);
    281 static void view(const Arg *arg);
    282 static Client *wintoclient(Window w);
    283 static Monitor *wintomon(Window w);
    284 static Client *wintosystrayicon(Window w);
    285 static int xerror(Display *dpy, XErrorEvent *ee);
    286 static int xerrordummy(Display *dpy, XErrorEvent *ee);
    287 static int xerrorstart(Display *dpy, XErrorEvent *ee);
    288 static void xrdb(const Arg *arg);
    289 static void zoom(const Arg *arg);
    290 static void autostart_exec(void);
    291 
    292 /* variables */
    293 static Systray *systray = NULL;
    294 static const char broken[] = "broken";
    295 static char stext[256];
    296 static int screen;
    297 static int sw, sh;           /* X display screen geometry width, height */
    298 static int bh;               /* bar height */
    299 static int lrpad;            /* sum of left and right padding for text */
    300 static int vp;               /* vertical padding for bar */
    301 static int sp;               /* side padding for bar */
    302 static int (*xerrorxlib)(Display *, XErrorEvent *);
    303 static unsigned int numlockmask = 0;
    304 static void (*handler[LASTEvent]) (XEvent *) = {
    305 	[ButtonPress] = buttonpress,
    306 	[ClientMessage] = clientmessage,
    307 	[ConfigureRequest] = configurerequest,
    308 	[ConfigureNotify] = configurenotify,
    309 	[DestroyNotify] = destroynotify,
    310 	[EnterNotify] = enternotify,
    311 	[Expose] = expose,
    312 	[FocusIn] = focusin,
    313 	[KeyPress] = keypress,
    314 	[MappingNotify] = mappingnotify,
    315 	[MapRequest] = maprequest,
    316 	[MotionNotify] = motionnotify,
    317 	[PropertyNotify] = propertynotify,
    318 	[ResizeRequest] = resizerequest,
    319 	[UnmapNotify] = unmapnotify
    320 };
    321 static Atom wmatom[WMLast], netatom[NetLast], xatom[XLast];
    322 static int running = 1;
    323 static Cur *cursor[CurLast];
    324 static Clr **scheme;
    325 static Display *dpy;
    326 static Drw *drw;
    327 static Monitor *mons, *selmon;
    328 static Window root, wmcheckwin;
    329 
    330 /* configuration, allows nested code to access above variables */
    331 #include "config.h"
    332 
    333 static unsigned int scratchtag = 1 << LENGTH(tags);
    334 
    335 /* compile-time check if all tags fit into an unsigned int bit array. */
    336 struct NumTags { char limitexceeded[LENGTH(tags) > 31 ? -1 : 1]; };
    337 
    338 /* birdwm will keep pid's of processes from autostart array and kill them at quit */
    339 static pid_t *autostart_pids;
    340 static size_t autostart_len;
    341 
    342 /* execute command from autostart array */
    343 static void
    344 autostart_exec() {
    345 	const char *const *p;
    346 	size_t i = 0;
    347 
    348 	/* count entries */
    349 	for (p = autostart; *p; autostart_len++, p++)
    350 		while (*++p);
    351 
    352 	autostart_pids = malloc(autostart_len * sizeof(pid_t));
    353 	for (p = autostart; *p; i++, p++) {
    354 		if ((autostart_pids[i] = fork()) == 0) {
    355 			setsid();
    356 			execvp(*p, (char *const *)p);
    357 			fprintf(stderr, "birdwm: execvp %s\n", *p);
    358 			perror(" failed");
    359 			_exit(EXIT_FAILURE);
    360 		}
    361 		/* skip arguments */
    362 		while (*++p);
    363 	}
    364 }
    365 
    366 
    367 
    368 /* function implementations */
    369 void
    370 applyrules(Client *c)
    371 {
    372 	const char *class, *instance;
    373 	unsigned int i;
    374 	const Rule *r;
    375 	Monitor *m;
    376 	XClassHint ch = { NULL, NULL };
    377 
    378 	/* rule matching */
    379 	c->isfloating = 0;
    380 	c->tags = 0;
    381 	XGetClassHint(dpy, c->win, &ch);
    382 	class    = ch.res_class ? ch.res_class : broken;
    383 	instance = ch.res_name  ? ch.res_name  : broken;
    384 
    385 	for (i = 0; i < LENGTH(rules); i++) {
    386 		r = &rules[i];
    387 		if ((!r->title || strstr(c->name, r->title))
    388 		&& (!r->class || strstr(class, r->class))
    389 		&& (!r->instance || strstr(instance, r->instance)))
    390 		{
    391 			c->isfloating = r->isfloating;
    392 			c->tags |= r->tags;
    393 			for (m = mons; m && m->num != r->monitor; m = m->next);
    394 			if (m)
    395 				c->mon = m;
    396 		}
    397 	}
    398 	if (ch.res_class)
    399 		XFree(ch.res_class);
    400 	if (ch.res_name)
    401 		XFree(ch.res_name);
    402 	c->tags = c->tags & TAGMASK ? c->tags & TAGMASK : c->mon->tagset[c->mon->seltags];
    403 }
    404 
    405 int
    406 applysizehints(Client *c, int *x, int *y, int *w, int *h, int interact)
    407 {
    408 	int baseismin;
    409 	Monitor *m = c->mon;
    410 
    411 	/* set minimum possible */
    412 	*w = MAX(1, *w);
    413 	*h = MAX(1, *h);
    414 	if (interact) {
    415 		if (*x > sw)
    416 			*x = sw - WIDTH(c);
    417 		if (*y > sh)
    418 			*y = sh - HEIGHT(c);
    419 		if (*x + *w + 2 * c->bw < 0)
    420 			*x = 0;
    421 		if (*y + *h + 2 * c->bw < 0)
    422 			*y = 0;
    423 	} else {
    424 		if (*x >= m->wx + m->ww)
    425 			*x = m->wx + m->ww - WIDTH(c);
    426 		if (*y >= m->wy + m->wh)
    427 			*y = m->wy + m->wh - HEIGHT(c);
    428 		if (*x + *w + 2 * c->bw <= m->wx)
    429 			*x = m->wx;
    430 		if (*y + *h + 2 * c->bw <= m->wy)
    431 			*y = m->wy;
    432 	}
    433 	if (*h < bh)
    434 		*h = bh;
    435 	if (*w < bh)
    436 		*w = bh;
    437 	if (resizehints || c->isfloating || !c->mon->lt[c->mon->sellt]->arrange) {
    438 		if (!c->hintsvalid)
    439 			updatesizehints(c);
    440 		/* see last two sentences in ICCCM 4.1.2.3 */
    441 		baseismin = c->basew == c->minw && c->baseh == c->minh;
    442 		if (!baseismin) { /* temporarily remove base dimensions */
    443 			*w -= c->basew;
    444 			*h -= c->baseh;
    445 		}
    446 		/* adjust for aspect limits */
    447 		if (c->mina > 0 && c->maxa > 0) {
    448 			if (c->maxa < (float)*w / *h)
    449 				*w = *h * c->maxa + 0.5;
    450 			else if (c->mina < (float)*h / *w)
    451 				*h = *w * c->mina + 0.5;
    452 		}
    453 		if (baseismin) { /* increment calculation requires this */
    454 			*w -= c->basew;
    455 			*h -= c->baseh;
    456 		}
    457 		/* adjust for increment value */
    458 		if (c->incw)
    459 			*w -= *w % c->incw;
    460 		if (c->inch)
    461 			*h -= *h % c->inch;
    462 		/* restore base dimensions */
    463 		*w = MAX(*w + c->basew, c->minw);
    464 		*h = MAX(*h + c->baseh, c->minh);
    465 		if (c->maxw)
    466 			*w = MIN(*w, c->maxw);
    467 		if (c->maxh)
    468 			*h = MIN(*h, c->maxh);
    469 	}
    470 	return *x != c->x || *y != c->y || *w != c->w || *h != c->h;
    471 }
    472 
    473 void
    474 arrange(Monitor *m)
    475 {
    476 	if (m)
    477 		showhide(m->stack);
    478 	else for (m = mons; m; m = m->next)
    479 		showhide(m->stack);
    480 	if (m) {
    481 		arrangemon(m);
    482 		restack(m);
    483 	} else for (m = mons; m; m = m->next)
    484 		arrangemon(m);
    485 }
    486 
    487 void
    488 arrangemon(Monitor *m)
    489 {
    490 	strncpy(m->ltsymbol, m->lt[m->sellt]->symbol, sizeof m->ltsymbol);
    491 	if (m->lt[m->sellt]->arrange)
    492 		m->lt[m->sellt]->arrange(m);
    493 }
    494 
    495 void
    496 attach(Client *c)
    497 {
    498 	c->next = c->mon->clients;
    499 	c->mon->clients = c;
    500 }
    501 
    502 void
    503 attachstack(Client *c)
    504 {
    505 	c->snext = c->mon->stack;
    506 	c->mon->stack = c;
    507 }
    508 
    509 void
    510 buttonpress(XEvent *e)
    511 {
    512 	unsigned int i, x, click;
    513 	Arg arg = {0};
    514 	Client *c;
    515 	Monitor *m;
    516 	XButtonPressedEvent *ev = &e->xbutton;
    517 
    518 	click = ClkRootWin;
    519 	/* focus monitor if necessary */
    520 	if ((m = wintomon(ev->window)) && m != selmon) {
    521 		unfocus(selmon->sel, 1);
    522 		selmon = m;
    523 		focus(NULL);
    524 	}
    525 	if (ev->window == selmon->barwin) {
    526 		i = x = 0;
    527 		do
    528 			x += TEXTW(tags[i]);
    529 		while (ev->x >= x && ++i < LENGTH(tags));
    530 		if (i < LENGTH(tags)) {
    531 			click = ClkTagBar;
    532 			arg.ui = 1 << i;
    533 		} else if (ev->x < x + TEXTW(selmon->ltsymbol))
    534 			click = ClkLtSymbol;
    535 		else if (ev->x > selmon->ww - (int)TEXTW(stext) - getsystraywidth())
    536 			click = ClkStatusText;
    537 		else
    538 			click = ClkWinTitle;
    539 	} else if ((c = wintoclient(ev->window))) {
    540 		focus(c);
    541 		restack(selmon);
    542 		XAllowEvents(dpy, ReplayPointer, CurrentTime);
    543 		click = ClkClientWin;
    544 	}
    545 	for (i = 0; i < LENGTH(buttons); i++)
    546 		if (click == buttons[i].click && buttons[i].func && buttons[i].button == ev->button
    547 		&& CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
    548 			buttons[i].func(click == ClkTagBar && buttons[i].arg.i == 0 ? &arg : &buttons[i].arg);
    549 }
    550 
    551 void
    552 checkotherwm(void)
    553 {
    554 	xerrorxlib = XSetErrorHandler(xerrorstart);
    555 	/* this causes an error if some other window manager is running */
    556 	XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
    557 	XSync(dpy, False);
    558 	XSetErrorHandler(xerror);
    559 	XSync(dpy, False);
    560 }
    561 
    562 void
    563 cleanup(void)
    564 {
    565 	Arg a = {.ui = ~0};
    566 	Layout foo = { "", NULL };
    567 	Monitor *m;
    568 	size_t i;
    569 
    570 	view(&a);
    571 	selmon->lt[selmon->sellt] = &foo;
    572 	for (m = mons; m; m = m->next)
    573 		while (m->stack)
    574 			unmanage(m->stack, 0);
    575 	XUngrabKey(dpy, AnyKey, AnyModifier, root);
    576 	while (mons)
    577 		cleanupmon(mons);
    578 
    579 	if (showsystray) {
    580 		XUnmapWindow(dpy, systray->win);
    581 		XDestroyWindow(dpy, systray->win);
    582 		free(systray);
    583 	}
    584 
    585 	for (i = 0; i < CurLast; i++)
    586 		drw_cur_free(drw, cursor[i]);
    587 	for (i = 0; i < LENGTH(colors); i++)
    588 		free(scheme[i]);
    589 	free(scheme);
    590 	XDestroyWindow(dpy, wmcheckwin);
    591 	drw_free(drw);
    592 	XSync(dpy, False);
    593 	XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
    594 	XDeleteProperty(dpy, root, netatom[NetActiveWindow]);
    595 }
    596 
    597 void
    598 cleanupmon(Monitor *mon)
    599 {
    600 	Monitor *m;
    601 
    602 	if (mon == mons)
    603 		mons = mons->next;
    604 	else {
    605 		for (m = mons; m && m->next != mon; m = m->next);
    606 		m->next = mon->next;
    607 	}
    608 	XUnmapWindow(dpy, mon->barwin);
    609 	XDestroyWindow(dpy, mon->barwin);
    610 	free(mon);
    611 }
    612 
    613 void
    614 clientmessage(XEvent *e)
    615 {
    616 	XWindowAttributes wa;
    617 	XSetWindowAttributes swa;
    618 	XClientMessageEvent *cme = &e->xclient;
    619 	Client *c = wintoclient(cme->window);
    620 
    621 	if (showsystray && cme->window == systray->win && cme->message_type == netatom[NetSystemTrayOP]) {
    622 		/* add systray icons */
    623 		if (cme->data.l[1] == SYSTEM_TRAY_REQUEST_DOCK) {
    624 			if (!(c = (Client *)calloc(1, sizeof(Client))))
    625 				die("fatal: could not malloc() %u bytes\n", sizeof(Client));
    626 			if (!(c->win = cme->data.l[2])) {
    627 				free(c);
    628 				return;
    629 			}
    630 			c->mon = selmon;
    631 			c->next = systray->icons;
    632 			systray->icons = c;
    633 			if (!XGetWindowAttributes(dpy, c->win, &wa)) {
    634 				/* use sane defaults */
    635 				wa.width = bh;
    636 				wa.height = bh;
    637 				wa.border_width = 0;
    638 			}
    639 			c->x = c->oldx = c->y = c->oldy = 0;
    640 			c->w = c->oldw = wa.width;
    641 			c->h = c->oldh = wa.height;
    642 			c->oldbw = wa.border_width;
    643 			c->bw = 0;
    644 			c->isfloating = True;
    645 			/* reuse tags field as mapped status */
    646 			c->tags = 1;
    647 			updatesizehints(c);
    648 			updatesystrayicongeom(c, wa.width, wa.height);
    649 			XAddToSaveSet(dpy, c->win);
    650 			XSelectInput(dpy, c->win, StructureNotifyMask | PropertyChangeMask | ResizeRedirectMask);
    651 			XReparentWindow(dpy, c->win, systray->win, 0, 0);
    652 			/* use parents background color */
    653 			swa.background_pixel  = scheme[SchemeNorm][ColBg].pixel;
    654 			XChangeWindowAttributes(dpy, c->win, CWBackPixel, &swa);
    655 			sendevent(c->win, netatom[Xembed], StructureNotifyMask, CurrentTime, XEMBED_EMBEDDED_NOTIFY, 0 , systray->win, XEMBED_EMBEDDED_VERSION);
    656 			/* FIXME not sure if I have to send these events, too */
    657 			sendevent(c->win, netatom[Xembed], StructureNotifyMask, CurrentTime, XEMBED_FOCUS_IN, 0 , systray->win, XEMBED_EMBEDDED_VERSION);
    658 			sendevent(c->win, netatom[Xembed], StructureNotifyMask, CurrentTime, XEMBED_WINDOW_ACTIVATE, 0 , systray->win, XEMBED_EMBEDDED_VERSION);
    659 			sendevent(c->win, netatom[Xembed], StructureNotifyMask, CurrentTime, XEMBED_MODALITY_ON, 0 , systray->win, XEMBED_EMBEDDED_VERSION);
    660 			XSync(dpy, False);
    661 			resizebarwin(selmon);
    662 			updatesystray();
    663 			setclientstate(c, NormalState);
    664 		}
    665 		return;
    666 	}
    667 
    668 	if (!c)
    669 		return;
    670 	if (cme->message_type == netatom[NetWMState]) {
    671 		if (cme->data.l[1] == netatom[NetWMFullscreen]
    672 		|| cme->data.l[2] == netatom[NetWMFullscreen])
    673 			setfullscreen(c, (cme->data.l[0] == 1 /* _NET_WM_STATE_ADD    */
    674 				|| (cme->data.l[0] == 2 /* _NET_WM_STATE_TOGGLE */ && !c->isfullscreen)));
    675 	} else if (cme->message_type == netatom[NetActiveWindow]) {
    676 		if (c != selmon->sel && !c->isurgent)
    677 			seturgent(c, 1);
    678 	}
    679 }
    680 
    681 void
    682 configure(Client *c)
    683 {
    684 	XConfigureEvent ce;
    685 
    686 	ce.type = ConfigureNotify;
    687 	ce.display = dpy;
    688 	ce.event = c->win;
    689 	ce.window = c->win;
    690 	ce.x = c->x;
    691 	ce.y = c->y;
    692 	ce.width = c->w;
    693 	ce.height = c->h;
    694 	ce.border_width = c->bw;
    695 	ce.above = None;
    696 	ce.override_redirect = False;
    697 	XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
    698 }
    699 
    700 void
    701 configurenotify(XEvent *e)
    702 {
    703 	Monitor *m;
    704 	Client *c;
    705 	XConfigureEvent *ev = &e->xconfigure;
    706 	int dirty;
    707 
    708 	/* TODO: updategeom handling sucks, needs to be simplified */
    709 	if (ev->window == root) {
    710 		dirty = (sw != ev->width || sh != ev->height);
    711 		sw = ev->width;
    712 		sh = ev->height;
    713 		if (updategeom() || dirty) {
    714 			drw_resize(drw, sw, bh);
    715 			updatebars();
    716 			for (m = mons; m; m = m->next) {
    717 				for (c = m->clients; c; c = c->next)
    718 					if (c->isfullscreen)
    719 						resizeclient(c, m->mx, m->my, m->mw, m->mh);
    720 				//XMoveResizeWindow(dpy, m->barwin, m->wx + sp, m->by + vp, m->ww -  2 * sp, bh);
    721 				resizebarwin(m);
    722 			}
    723 			focus(NULL);
    724 			arrange(NULL);
    725 		}
    726 	}
    727 }
    728 
    729 void
    730 configurerequest(XEvent *e)
    731 {
    732 	Client *c;
    733 	Monitor *m;
    734 	XConfigureRequestEvent *ev = &e->xconfigurerequest;
    735 	XWindowChanges wc;
    736 
    737 	if ((c = wintoclient(ev->window))) {
    738 		if (ev->value_mask & CWBorderWidth)
    739 			c->bw = ev->border_width;
    740 		else if (c->isfloating || !selmon->lt[selmon->sellt]->arrange) {
    741 			m = c->mon;
    742 			if (ev->value_mask & CWX) {
    743 				c->oldx = c->x;
    744 				c->x = m->mx + ev->x;
    745 			}
    746 			if (ev->value_mask & CWY) {
    747 				c->oldy = c->y;
    748 				c->y = m->my + ev->y;
    749 			}
    750 			if (ev->value_mask & CWWidth) {
    751 				c->oldw = c->w;
    752 				c->w = ev->width;
    753 			}
    754 			if (ev->value_mask & CWHeight) {
    755 				c->oldh = c->h;
    756 				c->h = ev->height;
    757 			}
    758 			if ((c->x + c->w) > m->mx + m->mw && c->isfloating)
    759 				c->x = m->mx + (m->mw / 2 - WIDTH(c) / 2); /* center in x direction */
    760 			if ((c->y + c->h) > m->my + m->mh && c->isfloating)
    761 				c->y = m->my + (m->mh / 2 - HEIGHT(c) / 2); /* center in y direction */
    762 			if ((ev->value_mask & (CWX|CWY)) && !(ev->value_mask & (CWWidth|CWHeight)))
    763 				configure(c);
    764 			if (ISVISIBLE(c))
    765 				XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
    766 		} else
    767 			configure(c);
    768 	} else {
    769 		wc.x = ev->x;
    770 		wc.y = ev->y;
    771 		wc.width = ev->width;
    772 		wc.height = ev->height;
    773 		wc.border_width = ev->border_width;
    774 		wc.sibling = ev->above;
    775 		wc.stack_mode = ev->detail;
    776 		XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
    777 	}
    778 	XSync(dpy, False);
    779 }
    780 
    781 Monitor *
    782 createmon(void)
    783 {
    784 	Monitor *m;
    785 
    786 	m = ecalloc(1, sizeof(Monitor));
    787 	m->tagset[0] = m->tagset[1] = 1;
    788 	m->mfact = mfact;
    789 	m->nmaster = nmaster;
    790 	m->showbar = showbar;
    791 	m->topbar = topbar;
    792 	m->lt[0] = &layouts[0];
    793 	m->lt[1] = &layouts[1 % LENGTH(layouts)];
    794 	strncpy(m->ltsymbol, layouts[0].symbol, sizeof m->ltsymbol);
    795 	return m;
    796 }
    797 
    798 void
    799 destroynotify(XEvent *e)
    800 {
    801 	Client *c;
    802 	XDestroyWindowEvent *ev = &e->xdestroywindow;
    803 
    804 	if ((c = wintoclient(ev->window)))
    805 		unmanage(c, 1);
    806 	else if ((c = wintosystrayicon(ev->window))) {
    807 		removesystrayicon(c);
    808 		resizebarwin(selmon);
    809 		updatesystray();
    810 	}
    811 }
    812 
    813 void
    814 detach(Client *c)
    815 {
    816 	Client **tc;
    817 
    818 	for (tc = &c->mon->clients; *tc && *tc != c; tc = &(*tc)->next);
    819 	*tc = c->next;
    820 }
    821 
    822 void
    823 detachstack(Client *c)
    824 {
    825 	Client **tc, *t;
    826 
    827 	for (tc = &c->mon->stack; *tc && *tc != c; tc = &(*tc)->snext);
    828 	*tc = c->snext;
    829 
    830 	if (c == c->mon->sel) {
    831 		for (t = c->mon->stack; t && !ISVISIBLE(t); t = t->snext);
    832 		c->mon->sel = t;
    833 	}
    834 }
    835 
    836 Monitor *
    837 dirtomon(int dir)
    838 {
    839 	Monitor *m = NULL;
    840 
    841 	if (dir > 0) {
    842 		if (!(m = selmon->next))
    843 			m = mons;
    844 	} else if (selmon == mons)
    845 		for (m = mons; m->next; m = m->next);
    846 	else
    847 		for (m = mons; m->next != selmon; m = m->next);
    848 	return m;
    849 }
    850 
    851 void
    852 drawbar(Monitor *m)
    853 {
    854 	int x, w, tw = 0, stw = 0;
    855 	int boxs = drw->fonts->h / 9;
    856 	int boxw = drw->fonts->h / 6 + 2;
    857 	unsigned int i, occ = 0, urg = 0;
    858 	Client *c;
    859 
    860 	if (!m->showbar)
    861 		return;
    862 
    863 	if (showsystray && m == systraytomon(m) && !systrayonleft)
    864 		stw = getsystraywidth();
    865 
    866 	/* draw status first so it can be overdrawn by tags later */
    867 	if (m == selmon) { /* status is only drawn on selected monitor */
    868 		drw_setscheme(drw, scheme[SchemeNorm]);
    869 		tw = TEXTW(stext) - lrpad / 2 + 2; /* 2px right padding */
    870 		drw_text(drw, m->ww - tw - stw - 2 * sp, 0, sw, bh, lrpad / 2 - 2, stext, 1);
    871 	}
    872 
    873 	resizebarwin(m);
    874 	for (c = m->clients; c; c = c->next) {
    875 		occ |= c->tags;
    876 		if (c->isurgent)
    877 			urg |= c->tags;
    878 	}
    879 	x = 0;
    880 	for (i = 0; i < LENGTH(tags); i++) {
    881 		w = TEXTW(tags[i]);
    882 		drw_setscheme(drw, scheme[m->tagset[m->seltags] & 1 << i ? SchemeSel : SchemeNorm]);
    883 		drw_text(drw, x, 0, w, bh, lrpad / 2, tags[i], urg & 1 << i);
    884 		if (occ & 1 << i)
    885 			drw_rect(drw, x + boxs, boxs, boxw, boxw,
    886 				m == selmon && selmon->sel && selmon->sel->tags & 1 << i,
    887 				urg & 1 << i);
    888 		x += w;
    889 	}
    890 	w = TEXTW(m->ltsymbol);
    891 	drw_setscheme(drw, scheme[SchemeNorm]);
    892 	x = drw_text(drw, x, 0, w, bh, lrpad / 2, m->ltsymbol, 0);
    893 
    894 	if ((w = m->ww - tw - stw - x) > bh) {
    895 		if (m->sel) {
    896 			drw_setscheme(drw, scheme[m == selmon ? SchemeSel : SchemeNorm]);
    897 			drw_text(drw, x, 0, w - 2 * sp, bh, lrpad / 2 + (m->sel->icon ? m->sel->icw + ICONSPACING : 0), m->sel->name, 0);
    898 			if (m->sel->icon) drw_pic(drw, x + lrpad / 2, (bh -m->sel->ich) / 2, m->sel->icw, m->sel->ich, m->sel->icon);
    899 			if (m->sel->isfloating)
    900 				drw_rect(drw, x + boxs, boxs, boxw, boxw, m->sel->isfixed, 0);
    901 		} else {
    902 			drw_setscheme(drw, scheme[SchemeNorm]);
    903 			drw_rect(drw, x, 0, w - 2 * sp, bh, 1, 1);
    904 		}
    905 	}
    906 	drw_map(drw, m->barwin, 0, 0, m->ww - stw, bh);
    907 }
    908 
    909 void
    910 drawbars(void)
    911 {
    912 	Monitor *m;
    913 
    914 	for (m = mons; m; m = m->next)
    915 		drawbar(m);
    916 }
    917 
    918 void
    919 enternotify(XEvent *e)
    920 {
    921 	Client *c;
    922 	Monitor *m;
    923 	XCrossingEvent *ev = &e->xcrossing;
    924 
    925 	if ((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
    926 		return;
    927 	c = wintoclient(ev->window);
    928 	m = c ? c->mon : wintomon(ev->window);
    929 	if (m != selmon) {
    930 		unfocus(selmon->sel, 1);
    931 		selmon = m;
    932 	} else if (!c || c == selmon->sel)
    933 		return;
    934 	focus(c);
    935 }
    936 
    937 void
    938 expose(XEvent *e)
    939 {
    940 	Monitor *m;
    941 	XExposeEvent *ev = &e->xexpose;
    942 
    943 	if (ev->count == 0 && (m = wintomon(ev->window))) {
    944 		drawbar(m);
    945 		if (m == selmon)
    946 			updatesystray();
    947 	}
    948 }
    949 
    950 void
    951 focus(Client *c)
    952 {
    953 	if (!c || !ISVISIBLE(c))
    954 		for (c = selmon->stack; c && !ISVISIBLE(c); c = c->snext);
    955 	if (selmon->sel && selmon->sel != c)
    956 		unfocus(selmon->sel, 0);
    957 	if (c) {
    958 		if (c->mon != selmon)
    959 			selmon = c->mon;
    960 		if (c->isurgent)
    961 			seturgent(c, 0);
    962 		detachstack(c);
    963 		attachstack(c);
    964 		grabbuttons(c, 1);
    965 		XSetWindowBorder(dpy, c->win, scheme[SchemeSel][ColBorder].pixel);
    966 		setfocus(c);
    967 	} else {
    968 		XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
    969 		XDeleteProperty(dpy, root, netatom[NetActiveWindow]);
    970 	}
    971 	selmon->sel = c;
    972 	drawbars();
    973 }
    974 
    975 /* there are some broken focus acquiring clients needing extra handling */
    976 void
    977 focusin(XEvent *e)
    978 {
    979 	XFocusChangeEvent *ev = &e->xfocus;
    980 
    981 	if (selmon->sel && ev->window != selmon->sel->win)
    982 		setfocus(selmon->sel);
    983 }
    984 
    985 void
    986 focusmon(const Arg *arg)
    987 {
    988 	Monitor *m;
    989 
    990 	if (!mons->next)
    991 		return;
    992 	if ((m = dirtomon(arg->i)) == selmon)
    993 		return;
    994 	unfocus(selmon->sel, 0);
    995 	selmon = m;
    996 	focus(NULL);
    997 }
    998 
    999 void
   1000 focusstack(const Arg *arg)
   1001 {
   1002 	Client *c = NULL, *i;
   1003 
   1004 	if (!selmon->sel || (selmon->sel->isfullscreen && lockfullscreen))
   1005 		return;
   1006 	if (arg->i > 0) {
   1007 		for (c = selmon->sel->next; c && !ISVISIBLE(c); c = c->next);
   1008 		if (!c)
   1009 			for (c = selmon->clients; c && !ISVISIBLE(c); c = c->next);
   1010 	} else {
   1011 		for (i = selmon->clients; i != selmon->sel; i = i->next)
   1012 			if (ISVISIBLE(i))
   1013 				c = i;
   1014 		if (!c)
   1015 			for (; i; i = i->next)
   1016 				if (ISVISIBLE(i))
   1017 					c = i;
   1018 	}
   1019 	if (c) {
   1020 		focus(c);
   1021 		restack(selmon);
   1022 	}
   1023 }
   1024 
   1025 Atom
   1026 getatomprop(Client *c, Atom prop)
   1027 {
   1028 	int di;
   1029 	unsigned long dl;
   1030 	unsigned char *p = NULL;
   1031 	Atom da, atom = None;
   1032 
   1033 	/* FIXME getatomprop should return the number of items and a pointer to
   1034 	 * the stored data instead of this workaround */
   1035 	Atom req = XA_ATOM;
   1036 	if (prop == xatom[XembedInfo])
   1037 		req = xatom[XembedInfo];
   1038 
   1039 	if (XGetWindowProperty(dpy, c->win, prop, 0L, sizeof atom, False, req,
   1040 		&da, &di, &dl, &dl, &p) == Success && p) {
   1041 		atom = *(Atom *)p;
   1042 		if (da == xatom[XembedInfo] && dl == 2)
   1043 			atom = ((Atom *)p)[1];
   1044 		XFree(p);
   1045 	}
   1046 	return atom;
   1047 }
   1048 
   1049 unsigned int
   1050 getsystraywidth()
   1051 {
   1052 	unsigned int w = 0;
   1053 	Client *i;
   1054 	if(showsystray)
   1055 		for(i = systray->icons; i; w += i->w + systrayspacing, i = i->next) ;
   1056 	return w ? w + systrayspacing : 1;
   1057 }
   1058 
   1059 static uint32_t prealpha(uint32_t p) {
   1060 	uint8_t a = p >> 24u;
   1061 	uint32_t rb = (a * (p & 0xFF00FFu)) >> 8u;
   1062 	uint32_t g = (a * (p & 0x00FF00u)) >> 8u;
   1063 	return (rb & 0xFF00FFu) | (g & 0x00FF00u) | (a << 24u);
   1064 }
   1065 
   1066 Picture
   1067 geticonprop(Window win, unsigned int *picw, unsigned int *pich)
   1068 {
   1069 	int format;
   1070 	unsigned long n, extra, *p = NULL;
   1071 	Atom real;
   1072 
   1073 	if (XGetWindowProperty(dpy, win, netatom[NetWMIcon], 0L, LONG_MAX, False, AnyPropertyType, 
   1074 						   &real, &format, &n, &extra, (unsigned char **)&p) != Success)
   1075 		return None; 
   1076 	if (n == 0 || format != 32) { XFree(p); return None; }
   1077 
   1078 	unsigned long *bstp = NULL;
   1079 	uint32_t w, h, sz;
   1080 	{
   1081 		unsigned long *i; const unsigned long *end = p + n;
   1082 		uint32_t bstd = UINT32_MAX, d, m;
   1083 		for (i = p; i < end - 1; i += sz) {
   1084 			if ((w = *i++) >= 16384 || (h = *i++) >= 16384) { XFree(p); return None; }
   1085 			if ((sz = w * h) > end - i) break;
   1086 			if ((m = w > h ? w : h) >= ICONSIZE && (d = m - ICONSIZE) < bstd) { bstd = d; bstp = i; }
   1087 		}
   1088 		if (!bstp) {
   1089 			for (i = p; i < end - 1; i += sz) {
   1090 				if ((w = *i++) >= 16384 || (h = *i++) >= 16384) { XFree(p); return None; }
   1091 				if ((sz = w * h) > end - i) break;
   1092 				if ((d = ICONSIZE - (w > h ? w : h)) < bstd) { bstd = d; bstp = i; }
   1093 			}
   1094 		}
   1095 		if (!bstp) { XFree(p); return None; }
   1096 	}
   1097 
   1098 	if ((w = *(bstp - 2)) == 0 || (h = *(bstp - 1)) == 0) { XFree(p); return None; }
   1099 
   1100 	uint32_t icw, ich;
   1101 	if (w <= h) {
   1102 		ich = ICONSIZE; icw = w * ICONSIZE / h;
   1103 		if (icw == 0) icw = 1;
   1104 	}
   1105 	else {
   1106 		icw = ICONSIZE; ich = h * ICONSIZE / w;
   1107 		if (ich == 0) ich = 1;
   1108 	}
   1109 	*picw = icw; *pich = ich;
   1110 
   1111 	uint32_t i, *bstp32 = (uint32_t *)bstp;
   1112 	for (sz = w * h, i = 0; i < sz; ++i) bstp32[i] = prealpha(bstp[i]);
   1113 
   1114 	Picture ret = drw_picture_create_resized(drw, (char *)bstp, w, h, icw, ich);
   1115 	XFree(p);
   1116 
   1117 	return ret;
   1118 }
   1119 
   1120 int
   1121 getrootptr(int *x, int *y)
   1122 {
   1123 	int di;
   1124 	unsigned int dui;
   1125 	Window dummy;
   1126 
   1127 	return XQueryPointer(dpy, root, &dummy, &dummy, x, y, &di, &di, &dui);
   1128 }
   1129 
   1130 long
   1131 getstate(Window w)
   1132 {
   1133 	int format;
   1134 	long result = -1;
   1135 	unsigned char *p = NULL;
   1136 	unsigned long n, extra;
   1137 	Atom real;
   1138 
   1139 	if (XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
   1140 		&real, &format, &n, &extra, (unsigned char **)&p) != Success)
   1141 		return -1;
   1142 	if (n != 0)
   1143 		result = *p;
   1144 	XFree(p);
   1145 	return result;
   1146 }
   1147 
   1148 int
   1149 gettextprop(Window w, Atom atom, char *text, unsigned int size)
   1150 {
   1151 	char **list = NULL;
   1152 	int n;
   1153 	XTextProperty name;
   1154 
   1155 	if (!text || size == 0)
   1156 		return 0;
   1157 	text[0] = '\0';
   1158 	if (!XGetTextProperty(dpy, w, &name, atom) || !name.nitems)
   1159 		return 0;
   1160 	if (name.encoding == XA_STRING) {
   1161 		strncpy(text, (char *)name.value, size - 1);
   1162 	} else if (XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success && n > 0 && *list) {
   1163 		strncpy(text, *list, size - 1);
   1164 		XFreeStringList(list);
   1165 	}
   1166 	text[size - 1] = '\0';
   1167 	XFree(name.value);
   1168 	return 1;
   1169 }
   1170 
   1171 void
   1172 grabbuttons(Client *c, int focused)
   1173 {
   1174 	updatenumlockmask();
   1175 	{
   1176 		unsigned int i, j;
   1177 		unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
   1178 		XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
   1179 		if (!focused)
   1180 			XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
   1181 				BUTTONMASK, GrabModeSync, GrabModeSync, None, None);
   1182 		for (i = 0; i < LENGTH(buttons); i++)
   1183 			if (buttons[i].click == ClkClientWin)
   1184 				for (j = 0; j < LENGTH(modifiers); j++)
   1185 					XGrabButton(dpy, buttons[i].button,
   1186 						buttons[i].mask | modifiers[j],
   1187 						c->win, False, BUTTONMASK,
   1188 						GrabModeAsync, GrabModeSync, None, None);
   1189 	}
   1190 }
   1191 
   1192 void
   1193 grabkeys(void)
   1194 {
   1195 	updatenumlockmask();
   1196 	{
   1197 		unsigned int i, j, k;
   1198 		unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
   1199 		int start, end, skip;
   1200 		KeySym *syms;
   1201 
   1202 		XUngrabKey(dpy, AnyKey, AnyModifier, root);
   1203 		XDisplayKeycodes(dpy, &start, &end);
   1204 		syms = XGetKeyboardMapping(dpy, start, end - start + 1, &skip);
   1205 		if (!syms)
   1206 			return;
   1207 		for (k = start; k <= end; k++)
   1208 			for (i = 0; i < LENGTH(keys); i++)
   1209 				/* skip modifier codes, we do that ourselves */
   1210 				if (keys[i].keysym == syms[(k - start) * skip])
   1211 					for (j = 0; j < LENGTH(modifiers); j++)
   1212 						XGrabKey(dpy, k,
   1213 							 keys[i].mod | modifiers[j],
   1214 							 root, True,
   1215 							 GrabModeAsync, GrabModeAsync);
   1216 		XFree(syms);
   1217 	}
   1218 }
   1219 
   1220 void
   1221 incnmaster(const Arg *arg)
   1222 {
   1223 	selmon->nmaster = MAX(selmon->nmaster + arg->i, 0);
   1224 	arrange(selmon);
   1225 }
   1226 
   1227 #ifdef XINERAMA
   1228 static int
   1229 isuniquegeom(XineramaScreenInfo *unique, size_t n, XineramaScreenInfo *info)
   1230 {
   1231 	while (n--)
   1232 		if (unique[n].x_org == info->x_org && unique[n].y_org == info->y_org
   1233 		&& unique[n].width == info->width && unique[n].height == info->height)
   1234 			return 0;
   1235 	return 1;
   1236 }
   1237 #endif /* XINERAMA */
   1238 
   1239 void
   1240 keypress(XEvent *e)
   1241 {
   1242 	unsigned int i;
   1243 	KeySym keysym;
   1244 	XKeyEvent *ev;
   1245 
   1246 	ev = &e->xkey;
   1247 	keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
   1248 	for (i = 0; i < LENGTH(keys); i++)
   1249 		if (keysym == keys[i].keysym
   1250 		&& CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
   1251 		&& keys[i].func)
   1252 			keys[i].func(&(keys[i].arg));
   1253 }
   1254 
   1255 void
   1256 killclient(const Arg *arg)
   1257 {
   1258 	if (!selmon->sel)
   1259 		return;
   1260 
   1261 	if (!sendevent(selmon->sel->win, wmatom[WMDelete], NoEventMask, wmatom[WMDelete], CurrentTime, 0 , 0, 0)) {
   1262 		XGrabServer(dpy);
   1263 		XSetErrorHandler(xerrordummy);
   1264 		XSetCloseDownMode(dpy, DestroyAll);
   1265 		XKillClient(dpy, selmon->sel->win);
   1266 		XSync(dpy, False);
   1267 		XSetErrorHandler(xerror);
   1268 		XUngrabServer(dpy);
   1269 	}
   1270 }
   1271 
   1272 void
   1273 loadxrdb()
   1274 {
   1275   Display *display;
   1276   char * resm;
   1277   XrmDatabase xrdb;
   1278   char *type;
   1279   XrmValue value;
   1280 
   1281   display = XOpenDisplay(NULL);
   1282 
   1283   if (display != NULL) {
   1284     resm = XResourceManagerString(display);
   1285 
   1286     if (resm != NULL) {
   1287       xrdb = XrmGetStringDatabase(resm);
   1288 
   1289       if (xrdb != NULL) {
   1290         XRDB_LOAD_COLOR("birdwm.normbordercolor", normbordercolor);
   1291         XRDB_LOAD_COLOR("birdwm.normbgcolor", normbgcolor);
   1292         XRDB_LOAD_COLOR("birdwm.normfgcolor", normfgcolor);
   1293         XRDB_LOAD_COLOR("birdwm.selbordercolor", selbordercolor);
   1294         XRDB_LOAD_COLOR("birdwm.selbgcolor", selbgcolor);
   1295         XRDB_LOAD_COLOR("birdwm.selfgcolor", selfgcolor);
   1296       }
   1297     }
   1298   }
   1299 
   1300   XCloseDisplay(display);
   1301 }
   1302 
   1303 void
   1304 manage(Window w, XWindowAttributes *wa)
   1305 {
   1306 	Client *c, *t = NULL;
   1307 	Window trans = None;
   1308 	XWindowChanges wc;
   1309 
   1310 	c = ecalloc(1, sizeof(Client));
   1311 	c->win = w;
   1312 	/* geometry */
   1313 	c->x = c->oldx = wa->x;
   1314 	c->y = c->oldy = wa->y;
   1315 	c->w = c->oldw = wa->width;
   1316 	c->h = c->oldh = wa->height;
   1317 	c->oldbw = wa->border_width;
   1318 
   1319 	updateicon(c);
   1320 	updatetitle(c);
   1321 	if (XGetTransientForHint(dpy, w, &trans) && (t = wintoclient(trans))) {
   1322 		c->mon = t->mon;
   1323 		c->tags = t->tags;
   1324 	} else {
   1325 		c->mon = selmon;
   1326 		applyrules(c);
   1327 	}
   1328 
   1329 	if (c->x + WIDTH(c) > c->mon->wx + c->mon->ww)
   1330 		c->x = c->mon->wx + c->mon->ww - WIDTH(c);
   1331 	if (c->y + HEIGHT(c) > c->mon->wy + c->mon->wh)
   1332 		c->y = c->mon->wy + c->mon->wh - HEIGHT(c);
   1333 	c->x = MAX(c->x, c->mon->wx);
   1334 	c->y = MAX(c->y, c->mon->wy);
   1335 	c->bw = borderpx;
   1336 
   1337 	selmon->tagset[selmon->seltags] &= ~scratchtag;
   1338 	if (!strcmp(c->name, scratchpadname)) {
   1339 		c->mon->tagset[c->mon->seltags] |= c->tags = scratchtag;
   1340 		c->isfloating = True;
   1341 		c->x = c->mon->wx + (c->mon->ww / 2 - WIDTH(c) / 2);
   1342 		c->y = c->mon->wy + (c->mon->wh / 2 - HEIGHT(c) / 2);
   1343 	}
   1344 
   1345 	wc.border_width = c->bw;
   1346 	XConfigureWindow(dpy, w, CWBorderWidth, &wc);
   1347 	XSetWindowBorder(dpy, w, scheme[SchemeNorm][ColBorder].pixel);
   1348 	configure(c); /* propagates border_width, if size doesn't change */
   1349 	updatewindowtype(c);
   1350 	updatesizehints(c);
   1351 	updatewmhints(c);
   1352 	XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
   1353 	grabbuttons(c, 0);
   1354 	if (!c->isfloating)
   1355 		c->isfloating = c->oldstate = trans != None || c->isfixed;
   1356 	if (c->isfloating)
   1357 		XRaiseWindow(dpy, c->win);
   1358 	attach(c);
   1359 	attachstack(c);
   1360 	XChangeProperty(dpy, root, netatom[NetClientList], XA_WINDOW, 32, PropModeAppend,
   1361 		(unsigned char *) &(c->win), 1);
   1362 	XMoveResizeWindow(dpy, c->win, c->x + 2 * sw, c->y, c->w, c->h); /* some windows require this */
   1363 	setclientstate(c, NormalState);
   1364 	if (c->mon == selmon)
   1365 		unfocus(selmon->sel, 0);
   1366 	c->mon->sel = c;
   1367 	arrange(c->mon);
   1368 	XMapWindow(dpy, c->win);
   1369 	focus(NULL);
   1370 }
   1371 
   1372 void
   1373 mappingnotify(XEvent *e)
   1374 {
   1375 	XMappingEvent *ev = &e->xmapping;
   1376 
   1377 	XRefreshKeyboardMapping(ev);
   1378 	if (ev->request == MappingKeyboard)
   1379 		grabkeys();
   1380 }
   1381 
   1382 void
   1383 maprequest(XEvent *e)
   1384 {
   1385 	static XWindowAttributes wa;
   1386 	XMapRequestEvent *ev = &e->xmaprequest;
   1387 
   1388 	Client *i;
   1389 	if ((i = wintosystrayicon(ev->window))) {
   1390 		sendevent(i->win, netatom[Xembed], StructureNotifyMask, CurrentTime, XEMBED_WINDOW_ACTIVATE, 0, systray->win, XEMBED_EMBEDDED_VERSION);
   1391 		resizebarwin(selmon);
   1392 		updatesystray();
   1393 	}
   1394 
   1395 	if (!XGetWindowAttributes(dpy, ev->window, &wa) || wa.override_redirect)
   1396 		return;
   1397 	if (!wintoclient(ev->window))
   1398 		manage(ev->window, &wa);
   1399 }
   1400 
   1401 void
   1402 monocle(Monitor *m)
   1403 {
   1404 	unsigned int n = 0;
   1405 	Client *c;
   1406 
   1407 	for (c = m->clients; c; c = c->next)
   1408 		if (ISVISIBLE(c))
   1409 			n++;
   1410 	if (n > 0) /* override layout symbol */
   1411 		snprintf(m->ltsymbol, sizeof m->ltsymbol, "[%d]", n);
   1412 	for (c = nexttiled(m->clients); c; c = nexttiled(c->next))
   1413 		resize(c, m->wx, m->wy, m->ww - 2 * c->bw, m->wh - 2 * c->bw, 0);
   1414 }
   1415 
   1416 void
   1417 motionnotify(XEvent *e)
   1418 {
   1419 	static Monitor *mon = NULL;
   1420 	Monitor *m;
   1421 	XMotionEvent *ev = &e->xmotion;
   1422 
   1423 	if (ev->window != root)
   1424 		return;
   1425 	if ((m = recttomon(ev->x_root, ev->y_root, 1, 1)) != mon && mon) {
   1426 		unfocus(selmon->sel, 1);
   1427 		selmon = m;
   1428 		focus(NULL);
   1429 	}
   1430 	mon = m;
   1431 }
   1432 
   1433 void
   1434 movemouse(const Arg *arg)
   1435 {
   1436 	int x, y, ocx, ocy, nx, ny;
   1437 	Client *c;
   1438 	Monitor *m;
   1439 	XEvent ev;
   1440 	Time lasttime = 0;
   1441 
   1442 	if (!(c = selmon->sel))
   1443 		return;
   1444 	if (c->isfullscreen) /* no support moving fullscreen windows by mouse */
   1445 		return;
   1446 	restack(selmon);
   1447 	ocx = c->x;
   1448 	ocy = c->y;
   1449 	if (XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
   1450 		None, cursor[CurMove]->cursor, CurrentTime) != GrabSuccess)
   1451 		return;
   1452 	if (!getrootptr(&x, &y))
   1453 		return;
   1454 	do {
   1455 		XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
   1456 		switch(ev.type) {
   1457 		case ConfigureRequest:
   1458 		case Expose:
   1459 		case MapRequest:
   1460 			handler[ev.type](&ev);
   1461 			break;
   1462 		case MotionNotify:
   1463 			if ((ev.xmotion.time - lasttime) <= (1000 / 60))
   1464 				continue;
   1465 			lasttime = ev.xmotion.time;
   1466 
   1467 			nx = ocx + (ev.xmotion.x - x);
   1468 			ny = ocy + (ev.xmotion.y - y);
   1469 			if (abs(selmon->wx - nx) < snap)
   1470 				nx = selmon->wx;
   1471 			else if (abs((selmon->wx + selmon->ww) - (nx + WIDTH(c))) < snap)
   1472 				nx = selmon->wx + selmon->ww - WIDTH(c);
   1473 			if (abs(selmon->wy - ny) < snap)
   1474 				ny = selmon->wy;
   1475 			else if (abs((selmon->wy + selmon->wh) - (ny + HEIGHT(c))) < snap)
   1476 				ny = selmon->wy + selmon->wh - HEIGHT(c);
   1477 			if (!c->isfloating && selmon->lt[selmon->sellt]->arrange
   1478 			&& (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
   1479 				togglefloating(NULL);
   1480 			if (!selmon->lt[selmon->sellt]->arrange || c->isfloating)
   1481 				resize(c, nx, ny, c->w, c->h, 1);
   1482 			break;
   1483 		}
   1484 	} while (ev.type != ButtonRelease);
   1485 	XUngrabPointer(dpy, CurrentTime);
   1486 	if ((m = recttomon(c->x, c->y, c->w, c->h)) != selmon) {
   1487 		sendmon(c, m);
   1488 		selmon = m;
   1489 		focus(NULL);
   1490 	}
   1491 }
   1492 
   1493 Client *
   1494 nexttiled(Client *c)
   1495 {
   1496 	for (; c && (c->isfloating || !ISVISIBLE(c)); c = c->next);
   1497 	return c;
   1498 }
   1499 
   1500 void
   1501 pop(Client *c)
   1502 {
   1503 	detach(c);
   1504 	attach(c);
   1505 	focus(c);
   1506 	arrange(c->mon);
   1507 }
   1508 
   1509 void
   1510 propertynotify(XEvent *e)
   1511 {
   1512 	Client *c;
   1513 	Window trans;
   1514 	XPropertyEvent *ev = &e->xproperty;
   1515 
   1516 	if ((c = wintosystrayicon(ev->window))) {
   1517 		if (ev->atom == XA_WM_NORMAL_HINTS) {
   1518 			updatesizehints(c);
   1519 			updatesystrayicongeom(c, c->w, c->h);
   1520 		}
   1521 		else
   1522 			updatesystrayiconstate(c, ev);
   1523 		resizebarwin(selmon);
   1524 		updatesystray();
   1525 	}
   1526 
   1527 	if ((ev->window == root) && (ev->atom == XA_WM_NAME))
   1528 		updatestatus();
   1529 	else if (ev->state == PropertyDelete)
   1530 		return; /* ignore */
   1531 	else if ((c = wintoclient(ev->window))) {
   1532 		switch(ev->atom) {
   1533 		default: break;
   1534 		case XA_WM_TRANSIENT_FOR:
   1535 			if (!c->isfloating && (XGetTransientForHint(dpy, c->win, &trans)) &&
   1536 				(c->isfloating = (wintoclient(trans)) != NULL))
   1537 				arrange(c->mon);
   1538 			break;
   1539 		case XA_WM_NORMAL_HINTS:
   1540 			c->hintsvalid = 0;
   1541 			break;
   1542 		case XA_WM_HINTS:
   1543 			updatewmhints(c);
   1544 			drawbars();
   1545 			break;
   1546 		}
   1547 		if (ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
   1548 			updatetitle(c);
   1549 			if (c == c->mon->sel)
   1550 				drawbar(c->mon);
   1551 		}
   1552 		else if (ev->atom == netatom[NetWMIcon]) {
   1553 			updateicon(c);
   1554 			if (c == c->mon->sel)
   1555 				drawbar(c->mon);
   1556 		}
   1557 		if (ev->atom == netatom[NetWMWindowType])
   1558 			updatewindowtype(c);
   1559 	}
   1560 }
   1561 
   1562 void
   1563 quit(const Arg *arg)
   1564 {
   1565 	size_t i;
   1566 
   1567 	/* kill child processes */
   1568 	for (i = 0; i < autostart_len; i++) {
   1569 		if (0 < autostart_pids[i]) {
   1570 			kill(autostart_pids[i], SIGTERM);
   1571 			waitpid(autostart_pids[i], NULL, 0);
   1572 		}
   1573 	}
   1574 
   1575 	running = 0;
   1576 }
   1577 
   1578 Monitor *
   1579 recttomon(int x, int y, int w, int h)
   1580 {
   1581 	Monitor *m, *r = selmon;
   1582 	int a, area = 0;
   1583 
   1584 	for (m = mons; m; m = m->next)
   1585 		if ((a = INTERSECT(x, y, w, h, m)) > area) {
   1586 			area = a;
   1587 			r = m;
   1588 		}
   1589 	return r;
   1590 }
   1591 
   1592 void
   1593 removesystrayicon(Client *i)
   1594 {
   1595 	Client **ii;
   1596 
   1597 	if (!showsystray || !i)
   1598 		return;
   1599 	for (ii = &systray->icons; *ii && *ii != i; ii = &(*ii)->next);
   1600 	if (ii)
   1601 		*ii = i->next;
   1602 	free(i);
   1603 }
   1604 
   1605 void
   1606 resize(Client *c, int x, int y, int w, int h, int interact)
   1607 {
   1608 	if (applysizehints(c, &x, &y, &w, &h, interact))
   1609 		resizeclient(c, x, y, w, h);
   1610 }
   1611 
   1612 void
   1613 resizebarwin(Monitor *m) {
   1614 	unsigned int w = m->ww;
   1615 	if (showsystray && m == systraytomon(m) && !systrayonleft)
   1616 		w -= getsystraywidth();
   1617 	XMoveResizeWindow(dpy, m->barwin, m->wx + sp, m->by + vp, w - 2 * sp, bh);
   1618 }
   1619 
   1620 void
   1621 resizeclient(Client *c, int x, int y, int w, int h)
   1622 {
   1623 	XWindowChanges wc;
   1624 	unsigned int n;
   1625 	unsigned int gapoffset;
   1626 	unsigned int gapincr;
   1627 	Client *nbc;
   1628 
   1629 	wc.border_width = c->bw;
   1630 
   1631 	/* Get number of clients for the client's monitor */
   1632 	for (n = 0, nbc = nexttiled(c->mon->clients); nbc; nbc = nexttiled(nbc->next), n++);
   1633 
   1634 	/* Do nothing if layout is floating */
   1635 	if (c->isfloating || c->mon->lt[c->mon->sellt]->arrange == NULL) {
   1636 		gapincr = gapoffset = 0;
   1637 	} else {
   1638 		/* Remove border and gap if layout is monocle or only one client */
   1639 		//if (c->mon->lt[c->mon->sellt]->arrange == monocle || n == 1) {
   1640 		if (c->mon->lt[c->mon->sellt]->arrange == monocle) { /* this edit is for no-gaps only monocle mode */
   1641 			gapoffset = 0;
   1642 			gapincr = -2 * borderpx;
   1643 			wc.border_width = 0;
   1644 		} else {
   1645 			gapoffset = gappx;
   1646 			gapincr = 2 * gappx;
   1647 		}
   1648 	}
   1649 
   1650 	c->oldx = c->x; c->x = wc.x = x + gapoffset;
   1651 	c->oldy = c->y; c->y = wc.y = y + gapoffset;
   1652 	c->oldw = c->w; c->w = wc.width = w - gapincr;
   1653 	c->oldh = c->h; c->h = wc.height = h - gapincr;
   1654 
   1655 	XConfigureWindow(dpy, c->win, CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
   1656 	configure(c);
   1657 	XSync(dpy, False);
   1658 }
   1659 
   1660 void
   1661 resizerequest(XEvent *e)
   1662 {
   1663 	XResizeRequestEvent *ev = &e->xresizerequest;
   1664 	Client *i;
   1665 
   1666 	if ((i = wintosystrayicon(ev->window))) {
   1667 		updatesystrayicongeom(i, ev->width, ev->height);
   1668 		resizebarwin(selmon);
   1669 		updatesystray();
   1670 	}
   1671 }
   1672 
   1673 void
   1674 resizemouse(const Arg *arg)
   1675 {
   1676 	int ocx, ocy, nw, nh;
   1677 	Client *c;
   1678 	Monitor *m;
   1679 	XEvent ev;
   1680 	Time lasttime = 0;
   1681 
   1682 	if (!(c = selmon->sel))
   1683 		return;
   1684 	if (c->isfullscreen) /* no support resizing fullscreen windows by mouse */
   1685 		return;
   1686 	restack(selmon);
   1687 	ocx = c->x;
   1688 	ocy = c->y;
   1689 	if (XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
   1690 		None, cursor[CurResize]->cursor, CurrentTime) != GrabSuccess)
   1691 		return;
   1692 	XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
   1693 	do {
   1694 		XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
   1695 		switch(ev.type) {
   1696 		case ConfigureRequest:
   1697 		case Expose:
   1698 		case MapRequest:
   1699 			handler[ev.type](&ev);
   1700 			break;
   1701 		case MotionNotify:
   1702 			if ((ev.xmotion.time - lasttime) <= (1000 / 60))
   1703 				continue;
   1704 			lasttime = ev.xmotion.time;
   1705 
   1706 			nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
   1707 			nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
   1708 			if (c->mon->wx + nw >= selmon->wx && c->mon->wx + nw <= selmon->wx + selmon->ww
   1709 			&& c->mon->wy + nh >= selmon->wy && c->mon->wy + nh <= selmon->wy + selmon->wh)
   1710 			{
   1711 				if (!c->isfloating && selmon->lt[selmon->sellt]->arrange
   1712 				&& (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
   1713 					togglefloating(NULL);
   1714 			}
   1715 			if (!selmon->lt[selmon->sellt]->arrange || c->isfloating)
   1716 				resize(c, c->x, c->y, nw, nh, 1);
   1717 			break;
   1718 		}
   1719 	} while (ev.type != ButtonRelease);
   1720 	XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
   1721 	XUngrabPointer(dpy, CurrentTime);
   1722 	while (XCheckMaskEvent(dpy, EnterWindowMask, &ev));
   1723 	if ((m = recttomon(c->x, c->y, c->w, c->h)) != selmon) {
   1724 		sendmon(c, m);
   1725 		selmon = m;
   1726 		focus(NULL);
   1727 	}
   1728 }
   1729 
   1730 void
   1731 restack(Monitor *m)
   1732 {
   1733 	Client *c;
   1734 	XEvent ev;
   1735 	XWindowChanges wc;
   1736 
   1737 	drawbar(m);
   1738 	if (!m->sel)
   1739 		return;
   1740 	if (m->sel->isfloating || !m->lt[m->sellt]->arrange)
   1741 		XRaiseWindow(dpy, m->sel->win);
   1742 	if (m->lt[m->sellt]->arrange) {
   1743 		wc.stack_mode = Below;
   1744 		wc.sibling = m->barwin;
   1745 		for (c = m->stack; c; c = c->snext)
   1746 			if (!c->isfloating && ISVISIBLE(c)) {
   1747 				XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
   1748 				wc.sibling = c->win;
   1749 			}
   1750 	}
   1751 	XSync(dpy, False);
   1752 	while (XCheckMaskEvent(dpy, EnterWindowMask, &ev));
   1753 }
   1754 
   1755 void
   1756 run(void)
   1757 {
   1758 	XEvent ev;
   1759 	/* main event loop */
   1760 	XSync(dpy, False);
   1761 	while (running && !XNextEvent(dpy, &ev))
   1762 		if (handler[ev.type])
   1763 			handler[ev.type](&ev); /* call handler */
   1764 }
   1765 
   1766 void
   1767 scan(void)
   1768 {
   1769 	unsigned int i, num;
   1770 	Window d1, d2, *wins = NULL;
   1771 	XWindowAttributes wa;
   1772 
   1773 	if (XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
   1774 		for (i = 0; i < num; i++) {
   1775 			if (!XGetWindowAttributes(dpy, wins[i], &wa)
   1776 			|| wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
   1777 				continue;
   1778 			if (wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
   1779 				manage(wins[i], &wa);
   1780 		}
   1781 		for (i = 0; i < num; i++) { /* now the transients */
   1782 			if (!XGetWindowAttributes(dpy, wins[i], &wa))
   1783 				continue;
   1784 			if (XGetTransientForHint(dpy, wins[i], &d1)
   1785 			&& (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
   1786 				manage(wins[i], &wa);
   1787 		}
   1788 		if (wins)
   1789 			XFree(wins);
   1790 	}
   1791 }
   1792 
   1793 void
   1794 sendmon(Client *c, Monitor *m)
   1795 {
   1796 	if (c->mon == m)
   1797 		return;
   1798 	unfocus(c, 1);
   1799 	detach(c);
   1800 	detachstack(c);
   1801 	c->mon = m;
   1802 	c->tags = m->tagset[m->seltags]; /* assign tags of target monitor */
   1803 	attach(c);
   1804 	attachstack(c);
   1805 	focus(NULL);
   1806 	arrange(NULL);
   1807 }
   1808 
   1809 void
   1810 setclientstate(Client *c, long state)
   1811 {
   1812 	long data[] = { state, None };
   1813 
   1814 	XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
   1815 		PropModeReplace, (unsigned char *)data, 2);
   1816 }
   1817 
   1818 int
   1819 sendevent(Window w, Atom proto, int mask, long d0, long d1, long d2, long d3, long d4)
   1820 {
   1821 	int n;
   1822 	Atom *protocols, mt;
   1823 	int exists = 0;
   1824 	XEvent ev;
   1825 
   1826 	if (proto == wmatom[WMTakeFocus] || proto == wmatom[WMDelete]) {
   1827 		mt = wmatom[WMProtocols];
   1828 		if (XGetWMProtocols(dpy, w, &protocols, &n)) {
   1829 			while (!exists && n--)
   1830 				exists = protocols[n] == proto;
   1831 			XFree(protocols);
   1832 		}
   1833 	}
   1834 	else {
   1835 		exists = True;
   1836 		mt = proto;
   1837 	}
   1838 
   1839 	if (exists) {
   1840 		ev.type = ClientMessage;
   1841 		ev.xclient.window = w;
   1842 		ev.xclient.message_type = mt;
   1843 		ev.xclient.format = 32;
   1844 		ev.xclient.data.l[0] = d0;
   1845 		ev.xclient.data.l[1] = d1;
   1846 		ev.xclient.data.l[2] = d2;
   1847 		ev.xclient.data.l[3] = d3;
   1848 		ev.xclient.data.l[4] = d4;
   1849 		XSendEvent(dpy, w, False, mask, &ev);
   1850 	}
   1851 	return exists;
   1852 }
   1853 
   1854 void
   1855 setfocus(Client *c)
   1856 {
   1857 	if (!c->neverfocus) {
   1858 		XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
   1859 		XChangeProperty(dpy, root, netatom[NetActiveWindow],
   1860 			XA_WINDOW, 32, PropModeReplace,
   1861 			(unsigned char *) &(c->win), 1);
   1862 	}
   1863 	sendevent(c->win, wmatom[WMTakeFocus], NoEventMask, wmatom[WMTakeFocus], CurrentTime, 0, 0, 0);
   1864 }
   1865 
   1866 void
   1867 setfullscreen(Client *c, int fullscreen)
   1868 {
   1869 	if (fullscreen && !c->isfullscreen) {
   1870 		XChangeProperty(dpy, c->win, netatom[NetWMState], XA_ATOM, 32,
   1871 			PropModeReplace, (unsigned char*)&netatom[NetWMFullscreen], 1);
   1872 		c->isfullscreen = 1;
   1873 		c->oldstate = c->isfloating;
   1874 		c->oldbw = c->bw;
   1875 		c->bw = 0;
   1876 		c->isfloating = 1;
   1877 		resizeclient(c, c->mon->mx, c->mon->my, c->mon->mw, c->mon->mh);
   1878 		XRaiseWindow(dpy, c->win);
   1879 	} else if (!fullscreen && c->isfullscreen){
   1880 		XChangeProperty(dpy, c->win, netatom[NetWMState], XA_ATOM, 32,
   1881 			PropModeReplace, (unsigned char*)0, 0);
   1882 		c->isfullscreen = 0;
   1883 		c->isfloating = c->oldstate;
   1884 		c->bw = c->oldbw;
   1885 		c->x = c->oldx;
   1886 		c->y = c->oldy;
   1887 		c->w = c->oldw;
   1888 		c->h = c->oldh;
   1889 		resizeclient(c, c->x, c->y, c->w, c->h);
   1890 		arrange(c->mon);
   1891 	}
   1892 }
   1893 
   1894 void
   1895 setlayout(const Arg *arg)
   1896 {
   1897 	if (!arg || !arg->v || arg->v != selmon->lt[selmon->sellt])
   1898 		selmon->sellt ^= 1;
   1899 	if (arg && arg->v)
   1900 		selmon->lt[selmon->sellt] = (Layout *)arg->v;
   1901 	strncpy(selmon->ltsymbol, selmon->lt[selmon->sellt]->symbol, sizeof selmon->ltsymbol);
   1902 	if (selmon->sel)
   1903 		arrange(selmon);
   1904 	else
   1905 		drawbar(selmon);
   1906 }
   1907 
   1908 /* arg > 1.0 will set mfact absolutely */
   1909 void
   1910 setmfact(const Arg *arg)
   1911 {
   1912 	float f;
   1913 
   1914 	if (!arg || !selmon->lt[selmon->sellt]->arrange)
   1915 		return;
   1916 	f = arg->f < 1.0 ? arg->f + selmon->mfact : arg->f - 1.0;
   1917 	if (f < 0.05 || f > 0.95)
   1918 		return;
   1919 	selmon->mfact = f;
   1920 	arrange(selmon);
   1921 }
   1922 
   1923 void
   1924 setup(void)
   1925 {
   1926 	int i;
   1927 	XSetWindowAttributes wa;
   1928 	Atom utf8string;
   1929 	struct sigaction sa;
   1930 	pid_t pid;
   1931 
   1932 	/* do not transform children into zombies when they terminate */
   1933 	sigemptyset(&sa.sa_mask);
   1934 	sa.sa_flags = SA_NOCLDSTOP | SA_NOCLDWAIT | SA_RESTART;
   1935 	sa.sa_handler = SIG_IGN;
   1936 	sigaction(SIGCHLD, &sa, NULL);
   1937 
   1938 	/* clean up any zombies (inherited from .xinitrc etc) immediately */
   1939 	while (0 < (pid = waitpid(-1, NULL, WNOHANG))) {
   1940 		pid_t *p, *lim;
   1941 
   1942 		if (!(p = autostart_pids))
   1943 			continue;
   1944 		lim = &p[autostart_len];
   1945 
   1946 		for (; p < lim; p++) {
   1947 			if (*p == pid) {
   1948 				*p = -1;
   1949 				break;
   1950 			}
   1951 		}
   1952 
   1953 	}
   1954 
   1955 	/* init screen */
   1956 	screen = DefaultScreen(dpy);
   1957 	sw = DisplayWidth(dpy, screen);
   1958 	sh = DisplayHeight(dpy, screen);
   1959 	root = RootWindow(dpy, screen);
   1960 	drw = drw_create(dpy, screen, root, sw, sh);
   1961 	if (!drw_fontset_create(drw, fonts, LENGTH(fonts)))
   1962 		die("no fonts could be loaded.");
   1963 	lrpad = drw->fonts->h;
   1964 	bh = drw->fonts->h + 2;
   1965 	updategeom();
   1966 	sp = sidepad;
   1967 	vp = (topbar == 1) ? vertpad : - vertpad;
   1968 
   1969 	/* init atoms */
   1970 	utf8string = XInternAtom(dpy, "UTF8_STRING", False);
   1971 	wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
   1972 	wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
   1973 	wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
   1974 	wmatom[WMTakeFocus] = XInternAtom(dpy, "WM_TAKE_FOCUS", False);
   1975 	netatom[NetActiveWindow] = XInternAtom(dpy, "_NET_ACTIVE_WINDOW", False);
   1976 	netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
   1977 	netatom[NetSystemTray] = XInternAtom(dpy, "_NET_SYSTEM_TRAY_S0", False);
   1978 	netatom[NetSystemTrayOP] = XInternAtom(dpy, "_NET_SYSTEM_TRAY_OPCODE", False);
   1979 	netatom[NetSystemTrayOrientation] = XInternAtom(dpy, "_NET_SYSTEM_TRAY_ORIENTATION", False);
   1980 	netatom[NetSystemTrayOrientationHorz] = XInternAtom(dpy, "_NET_SYSTEM_TRAY_ORIENTATION_HORZ", False);
   1981 	netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
   1982 	netatom[NetWMIcon] = XInternAtom(dpy, "_NET_WM_ICON", False);
   1983 	netatom[NetWMState] = XInternAtom(dpy, "_NET_WM_STATE", False);
   1984 	netatom[NetWMCheck] = XInternAtom(dpy, "_NET_SUPPORTING_WM_CHECK", False);
   1985 	netatom[NetWMFullscreen] = XInternAtom(dpy, "_NET_WM_STATE_FULLSCREEN", False);
   1986 	netatom[NetWMWindowType] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE", False);
   1987 	netatom[NetWMWindowTypeDialog] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE_DIALOG", False);
   1988 	netatom[NetClientList] = XInternAtom(dpy, "_NET_CLIENT_LIST", False);
   1989 	xatom[Manager] = XInternAtom(dpy, "MANAGER", False);
   1990 	xatom[Xembed] = XInternAtom(dpy, "_XEMBED", False);
   1991 	xatom[XembedInfo] = XInternAtom(dpy, "_XEMBED_INFO", False);
   1992 	/* init cursors */
   1993 	cursor[CurNormal] = drw_cur_create(drw, XC_left_ptr);
   1994 	cursor[CurResize] = drw_cur_create(drw, XC_sizing);
   1995 	cursor[CurMove] = drw_cur_create(drw, XC_fleur);
   1996 	/* init appearance */
   1997 	scheme = ecalloc(LENGTH(colors), sizeof(Clr *));
   1998 	for (i = 0; i < LENGTH(colors); i++)
   1999 		scheme[i] = drw_scm_create(drw, colors[i], 3);
   2000 	/* init system tray */
   2001 	updatesystray();
   2002 
   2003 	/* init bars */
   2004 	updatebars();
   2005 	updatestatus();
   2006 	updatebarpos(selmon);
   2007 	/* supporting window for NetWMCheck */
   2008 	wmcheckwin = XCreateSimpleWindow(dpy, root, 0, 0, 1, 1, 0, 0, 0);
   2009 	XChangeProperty(dpy, wmcheckwin, netatom[NetWMCheck], XA_WINDOW, 32,
   2010 		PropModeReplace, (unsigned char *) &wmcheckwin, 1);
   2011 	XChangeProperty(dpy, wmcheckwin, netatom[NetWMName], utf8string, 8,
   2012 		PropModeReplace, (unsigned char *) "birdwm", 3);
   2013 	XChangeProperty(dpy, root, netatom[NetWMCheck], XA_WINDOW, 32,
   2014 		PropModeReplace, (unsigned char *) &wmcheckwin, 1);
   2015 	/* EWMH support per view */
   2016 	XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
   2017 		PropModeReplace, (unsigned char *) netatom, NetLast);
   2018 	XDeleteProperty(dpy, root, netatom[NetClientList]);
   2019 	/* select events */
   2020 	wa.cursor = cursor[CurNormal]->cursor;
   2021 	wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
   2022 		|ButtonPressMask|PointerMotionMask|EnterWindowMask
   2023 		|LeaveWindowMask|StructureNotifyMask|PropertyChangeMask;
   2024 	XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
   2025 	XSelectInput(dpy, root, wa.event_mask);
   2026 	grabkeys();
   2027 	focus(NULL);
   2028 }
   2029 
   2030 void
   2031 seturgent(Client *c, int urg)
   2032 {
   2033 	XWMHints *wmh;
   2034 
   2035 	c->isurgent = urg;
   2036 	if (!(wmh = XGetWMHints(dpy, c->win)))
   2037 		return;
   2038 	wmh->flags = urg ? (wmh->flags | XUrgencyHint) : (wmh->flags & ~XUrgencyHint);
   2039 	XSetWMHints(dpy, c->win, wmh);
   2040 	XFree(wmh);
   2041 }
   2042 
   2043 void
   2044 showhide(Client *c)
   2045 {
   2046 	if (!c)
   2047 		return;
   2048 	if (ISVISIBLE(c)) {
   2049 		/* show clients top down */
   2050 		XMoveWindow(dpy, c->win, c->x, c->y);
   2051 		if ((!c->mon->lt[c->mon->sellt]->arrange || c->isfloating) && !c->isfullscreen)
   2052 			resize(c, c->x, c->y, c->w, c->h, 0);
   2053 		showhide(c->snext);
   2054 	} else {
   2055 		/* hide clients bottom up */
   2056 		showhide(c->snext);
   2057 		XMoveWindow(dpy, c->win, WIDTH(c) * -2, c->y);
   2058 	}
   2059 }
   2060 
   2061 void
   2062 spawn(const Arg *arg)
   2063 {
   2064 	struct sigaction sa;
   2065 
   2066 	if (arg->v == dmenucmd)
   2067 		dmenumon[0] = '0' + selmon->num;
   2068 	selmon->tagset[selmon->seltags] &= ~scratchtag;
   2069 	if (fork() == 0) {
   2070 		if (dpy)
   2071 			close(ConnectionNumber(dpy));
   2072 		setsid();
   2073 
   2074 		sigemptyset(&sa.sa_mask);
   2075 		sa.sa_flags = 0;
   2076 		sa.sa_handler = SIG_DFL;
   2077 		sigaction(SIGCHLD, &sa, NULL);
   2078 
   2079 		execvp(((char **)arg->v)[0], (char **)arg->v);
   2080 		die("birdwm: execvp '%s' failed:", ((char **)arg->v)[0]);
   2081 	}
   2082 }
   2083 
   2084 void
   2085 tag(const Arg *arg)
   2086 {
   2087 	if (selmon->sel && arg->ui & TAGMASK) {
   2088 		selmon->sel->tags = arg->ui & TAGMASK;
   2089 		focus(NULL);
   2090 		arrange(selmon);
   2091 	}
   2092 }
   2093 
   2094 void
   2095 tagmon(const Arg *arg)
   2096 {
   2097 	if (!selmon->sel || !mons->next)
   2098 		return;
   2099 	sendmon(selmon->sel, dirtomon(arg->i));
   2100 }
   2101 
   2102 void
   2103 tile(Monitor *m)
   2104 {
   2105 	unsigned int i, n, h, mw, my, ty;
   2106 	Client *c;
   2107 
   2108 	for (n = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), n++);
   2109 	if (n == 0)
   2110 		return;
   2111 
   2112 	if (n > m->nmaster)
   2113 		mw = m->nmaster ? m->ww * m->mfact : 0;
   2114 	else
   2115 		mw = m->ww;
   2116 	for (i = my = ty = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), i++)
   2117 		if (i < m->nmaster) {
   2118 			h = (m->wh - my) / (MIN(n, m->nmaster) - i);
   2119 			resize(c, m->wx, m->wy + my, mw - (2*c->bw) + (n > 1 ? gappx : 0), h - (2*c->bw), 0);
   2120 			if (my + HEIGHT(c) < m->wh)
   2121 				my += HEIGHT(c);
   2122 		} else {
   2123 			h = (m->wh - ty) / (n - i);
   2124 			resize(c, m->wx + mw, m->wy + ty, m->ww - mw - (2*c->bw), h - (2*c->bw), 0);
   2125 			if (ty + HEIGHT(c) < m->wh)
   2126 				ty += HEIGHT(c);
   2127 		}
   2128 }
   2129 
   2130 void
   2131 togglebar(const Arg *arg)
   2132 {
   2133 	selmon->showbar = !selmon->showbar;
   2134 	updatebarpos(selmon);
   2135 	//XMoveResizeWindow(dpy, selmon->barwin, selmon->wx + sp, selmon->by + vp, selmon->ww - 2 * sp, bh);
   2136 	resizebarwin(selmon);
   2137 	if (showsystray) {
   2138 		XWindowChanges wc;
   2139 		if (!selmon->showbar)
   2140 			wc.y = -bh;
   2141 		else if (selmon->showbar) {
   2142 			wc.y = 0;
   2143 			if (!selmon->topbar)
   2144 				wc.y = selmon->mh - bh;
   2145 		}
   2146 		XConfigureWindow(dpy, systray->win, CWY, &wc);
   2147 	}
   2148 	arrange(selmon);
   2149 }
   2150 
   2151 void
   2152 togglefloating(const Arg *arg)
   2153 {
   2154 	if (!selmon->sel)
   2155 		return;
   2156 	if (selmon->sel->isfullscreen) /* no support for fullscreen windows */
   2157 		return;
   2158 	selmon->sel->isfloating = !selmon->sel->isfloating || selmon->sel->isfixed;
   2159 	if (selmon->sel->isfloating)
   2160 		resize(selmon->sel, selmon->sel->x, selmon->sel->y,
   2161 			selmon->sel->w, selmon->sel->h, 0);
   2162 	arrange(selmon);
   2163 }
   2164 
   2165 void
   2166 togglescratch(const Arg *arg)
   2167 {
   2168 	Client *c;
   2169 	unsigned int found = 0;
   2170 
   2171 	for (c = selmon->clients; c && !(found = c->tags & scratchtag); c = c->next);
   2172 	if (found) {
   2173 		unsigned int newtagset = selmon->tagset[selmon->seltags] ^ scratchtag;
   2174 		if (newtagset) {
   2175 			selmon->tagset[selmon->seltags] = newtagset;
   2176 			focus(NULL);
   2177 			arrange(selmon);
   2178 		}
   2179 		if (ISVISIBLE(c)) {
   2180 			focus(c);
   2181 			restack(selmon);
   2182 		}
   2183 	} else
   2184 		spawn(arg);
   2185 }
   2186 
   2187 void
   2188 toggletag(const Arg *arg)
   2189 {
   2190 	unsigned int newtags;
   2191 
   2192 	if (!selmon->sel)
   2193 		return;
   2194 	newtags = selmon->sel->tags ^ (arg->ui & TAGMASK);
   2195 	if (newtags) {
   2196 		selmon->sel->tags = newtags;
   2197 		focus(NULL);
   2198 		arrange(selmon);
   2199 	}
   2200 }
   2201 
   2202 void
   2203 toggleview(const Arg *arg)
   2204 {
   2205 	unsigned int newtagset = selmon->tagset[selmon->seltags] ^ (arg->ui & TAGMASK);
   2206 
   2207 	if (newtagset) {
   2208 		selmon->tagset[selmon->seltags] = newtagset;
   2209 		focus(NULL);
   2210 		arrange(selmon);
   2211 	}
   2212 }
   2213 
   2214 void
   2215 freeicon(Client *c)
   2216 {
   2217 	if (c->icon) {
   2218 		XRenderFreePicture(dpy, c->icon);
   2219 		c->icon = None;
   2220 	}
   2221 }
   2222 
   2223 void
   2224 unfocus(Client *c, int setfocus)
   2225 {
   2226 	if (!c)
   2227 		return;
   2228 	grabbuttons(c, 0);
   2229 	XSetWindowBorder(dpy, c->win, scheme[SchemeNorm][ColBorder].pixel);
   2230 	if (setfocus) {
   2231 		XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
   2232 		XDeleteProperty(dpy, root, netatom[NetActiveWindow]);
   2233 	}
   2234 }
   2235 
   2236 void
   2237 unmanage(Client *c, int destroyed)
   2238 {
   2239 	Monitor *m = c->mon;
   2240 	XWindowChanges wc;
   2241 
   2242 	detach(c);
   2243 	detachstack(c);
   2244 	freeicon(c);
   2245 	if (!destroyed) {
   2246 		wc.border_width = c->oldbw;
   2247 		XGrabServer(dpy); /* avoid race conditions */
   2248 		XSetErrorHandler(xerrordummy);
   2249 		XSelectInput(dpy, c->win, NoEventMask);
   2250 		XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
   2251 		XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
   2252 		setclientstate(c, WithdrawnState);
   2253 		XSync(dpy, False);
   2254 		XSetErrorHandler(xerror);
   2255 		XUngrabServer(dpy);
   2256 	}
   2257 	free(c);
   2258 	focus(NULL);
   2259 	updateclientlist();
   2260 	arrange(m);
   2261 }
   2262 
   2263 void
   2264 unmapnotify(XEvent *e)
   2265 {
   2266 	Client *c;
   2267 	XUnmapEvent *ev = &e->xunmap;
   2268 
   2269 	if ((c = wintoclient(ev->window))) {
   2270 		if (ev->send_event)
   2271 			setclientstate(c, WithdrawnState);
   2272 		else
   2273 			unmanage(c, 0);
   2274 	}
   2275 	else if ((c = wintosystrayicon(ev->window))) {
   2276 		/* KLUDGE! sometimes icons occasionally unmap their windows, but do
   2277 		 * _not_ destroy them. We map those windows back */
   2278 		XMapRaised(dpy, c->win);
   2279 		updatesystray();
   2280 	}
   2281 }
   2282 
   2283 void
   2284 updatebars(void)
   2285 {
   2286 	unsigned int w;
   2287 	Monitor *m;
   2288 	XSetWindowAttributes wa = {
   2289 		.override_redirect = True,
   2290 		.background_pixmap = ParentRelative,
   2291 		.event_mask = ButtonPressMask|ExposureMask
   2292 	};
   2293 	XClassHint ch = {"birdwm", "birdwm"};
   2294 	for (m = mons; m; m = m->next) {
   2295 		if (m->barwin)
   2296 			continue;
   2297 		//m->barwin = XCreateWindow(dpy, root, m->wx + sp, m->by + vp, m->ww - 2 * sp, bh, 0, DefaultDepth(dpy, screen),
   2298 		w = m->ww;
   2299 		if (showsystray && m == systraytomon(m))
   2300 			w -= getsystraywidth();
   2301 		m->barwin = XCreateWindow(dpy, root, m->wx + sp, m ->by + vp, w - 2 * sp, bh, 0, DefaultDepth(dpy, screen),
   2302 				CopyFromParent, DefaultVisual(dpy, screen),
   2303 				CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
   2304 		XDefineCursor(dpy, m->barwin, cursor[CurNormal]->cursor);
   2305 		if (showsystray && m == systraytomon(m))
   2306 			XMapRaised(dpy, systray->win);
   2307 		XMapRaised(dpy, m->barwin);
   2308 		XSetClassHint(dpy, m->barwin, &ch);
   2309 	}
   2310 }
   2311 
   2312 void
   2313 updatebarpos(Monitor *m)
   2314 {
   2315 	m->wy = m->my;
   2316 	m->wh = m->mh;
   2317 	if (m->showbar) {
   2318 		m->wh = m->wh - vertpad - bh;
   2319 		m->by = m->topbar ? m->wy : m->wy + m->wh + vertpad;
   2320 		m->wy = m->topbar ? m->wy + bh + vp : m->wy;
   2321 	} else
   2322 		m->by = -bh - vp;
   2323 }
   2324 
   2325 void
   2326 updateclientlist(void)
   2327 {
   2328 	Client *c;
   2329 	Monitor *m;
   2330 
   2331 	XDeleteProperty(dpy, root, netatom[NetClientList]);
   2332 	for (m = mons; m; m = m->next)
   2333 		for (c = m->clients; c; c = c->next)
   2334 			XChangeProperty(dpy, root, netatom[NetClientList],
   2335 				XA_WINDOW, 32, PropModeAppend,
   2336 				(unsigned char *) &(c->win), 1);
   2337 }
   2338 
   2339 int
   2340 updategeom(void)
   2341 {
   2342 	int dirty = 0;
   2343 
   2344 #ifdef XINERAMA
   2345 	if (XineramaIsActive(dpy)) {
   2346 		int i, j, n, nn;
   2347 		Client *c;
   2348 		Monitor *m;
   2349 		XineramaScreenInfo *info = XineramaQueryScreens(dpy, &nn);
   2350 		XineramaScreenInfo *unique = NULL;
   2351 
   2352 		for (n = 0, m = mons; m; m = m->next, n++);
   2353 		/* only consider unique geometries as separate screens */
   2354 		unique = ecalloc(nn, sizeof(XineramaScreenInfo));
   2355 		for (i = 0, j = 0; i < nn; i++)
   2356 			if (isuniquegeom(unique, j, &info[i]))
   2357 				memcpy(&unique[j++], &info[i], sizeof(XineramaScreenInfo));
   2358 		XFree(info);
   2359 		nn = j;
   2360 
   2361 		/* new monitors if nn > n */
   2362 		for (i = n; i < nn; i++) {
   2363 			for (m = mons; m && m->next; m = m->next);
   2364 			if (m)
   2365 				m->next = createmon();
   2366 			else
   2367 				mons = createmon();
   2368 		}
   2369 		for (i = 0, m = mons; i < nn && m; m = m->next, i++)
   2370 			if (i >= n
   2371 			|| unique[i].x_org != m->mx || unique[i].y_org != m->my
   2372 			|| unique[i].width != m->mw || unique[i].height != m->mh)
   2373 			{
   2374 				dirty = 1;
   2375 				m->num = i;
   2376 				m->mx = m->wx = unique[i].x_org;
   2377 				m->my = m->wy = unique[i].y_org;
   2378 				m->mw = m->ww = unique[i].width;
   2379 				m->mh = m->wh = unique[i].height;
   2380 				updatebarpos(m);
   2381 			}
   2382 		/* removed monitors if n > nn */
   2383 		for (i = nn; i < n; i++) {
   2384 			for (m = mons; m && m->next; m = m->next);
   2385 			while ((c = m->clients)) {
   2386 				dirty = 1;
   2387 				m->clients = c->next;
   2388 				detachstack(c);
   2389 				c->mon = mons;
   2390 				attach(c);
   2391 				attachstack(c);
   2392 			}
   2393 			if (m == selmon)
   2394 				selmon = mons;
   2395 			cleanupmon(m);
   2396 		}
   2397 		free(unique);
   2398 	} else
   2399 #endif /* XINERAMA */
   2400 	{ /* default monitor setup */
   2401 		if (!mons)
   2402 			mons = createmon();
   2403 		if (mons->mw != sw || mons->mh != sh) {
   2404 			dirty = 1;
   2405 			mons->mw = mons->ww = sw;
   2406 			mons->mh = mons->wh = sh;
   2407 			updatebarpos(mons);
   2408 		}
   2409 	}
   2410 	if (dirty) {
   2411 		selmon = mons;
   2412 		selmon = wintomon(root);
   2413 	}
   2414 	return dirty;
   2415 }
   2416 
   2417 void
   2418 updatenumlockmask(void)
   2419 {
   2420 	unsigned int i, j;
   2421 	XModifierKeymap *modmap;
   2422 
   2423 	numlockmask = 0;
   2424 	modmap = XGetModifierMapping(dpy);
   2425 	for (i = 0; i < 8; i++)
   2426 		for (j = 0; j < modmap->max_keypermod; j++)
   2427 			if (modmap->modifiermap[i * modmap->max_keypermod + j]
   2428 				== XKeysymToKeycode(dpy, XK_Num_Lock))
   2429 				numlockmask = (1 << i);
   2430 	XFreeModifiermap(modmap);
   2431 }
   2432 
   2433 void
   2434 updatesizehints(Client *c)
   2435 {
   2436 	long msize;
   2437 	XSizeHints size;
   2438 
   2439 	if (!XGetWMNormalHints(dpy, c->win, &size, &msize))
   2440 		/* size is uninitialized, ensure that size.flags aren't used */
   2441 		size.flags = PSize;
   2442 	if (size.flags & PBaseSize) {
   2443 		c->basew = size.base_width;
   2444 		c->baseh = size.base_height;
   2445 	} else if (size.flags & PMinSize) {
   2446 		c->basew = size.min_width;
   2447 		c->baseh = size.min_height;
   2448 	} else
   2449 		c->basew = c->baseh = 0;
   2450 	if (size.flags & PResizeInc) {
   2451 		c->incw = size.width_inc;
   2452 		c->inch = size.height_inc;
   2453 	} else
   2454 		c->incw = c->inch = 0;
   2455 	if (size.flags & PMaxSize) {
   2456 		c->maxw = size.max_width;
   2457 		c->maxh = size.max_height;
   2458 	} else
   2459 		c->maxw = c->maxh = 0;
   2460 	if (size.flags & PMinSize) {
   2461 		c->minw = size.min_width;
   2462 		c->minh = size.min_height;
   2463 	} else if (size.flags & PBaseSize) {
   2464 		c->minw = size.base_width;
   2465 		c->minh = size.base_height;
   2466 	} else
   2467 		c->minw = c->minh = 0;
   2468 	if (size.flags & PAspect) {
   2469 		c->mina = (float)size.min_aspect.y / size.min_aspect.x;
   2470 		c->maxa = (float)size.max_aspect.x / size.max_aspect.y;
   2471 	} else
   2472 		c->maxa = c->mina = 0.0;
   2473 	c->isfixed = (c->maxw && c->maxh && c->maxw == c->minw && c->maxh == c->minh);
   2474 	c->hintsvalid = 1;
   2475 }
   2476 
   2477 void
   2478 updatestatus(void)
   2479 {
   2480 	if (!gettextprop(root, XA_WM_NAME, stext, sizeof(stext)))
   2481 		strcpy(stext, "birdwm-"VERSION);
   2482 	drawbar(selmon);
   2483 	updatesystray();
   2484 }
   2485 
   2486 
   2487 void
   2488 updatesystrayicongeom(Client *i, int w, int h)
   2489 {
   2490 	if (i) {
   2491 		i->h = bh;
   2492 		if (w == h)
   2493 			i->w = bh;
   2494 		else if (h == bh)
   2495 			i->w = w;
   2496 		else
   2497 			i->w = (int) ((float)bh * ((float)w / (float)h));
   2498 		applysizehints(i, &(i->x), &(i->y), &(i->w), &(i->h), False);
   2499 		/* force icons into the systray dimensions if they don't want to */
   2500 		if (i->h > bh) {
   2501 			if (i->w == i->h)
   2502 				i->w = bh;
   2503 			else
   2504 				i->w = (int) ((float)bh * ((float)i->w / (float)i->h));
   2505 			i->h = bh;
   2506 		}
   2507 	}
   2508 }
   2509 
   2510 void
   2511 updatesystrayiconstate(Client *i, XPropertyEvent *ev)
   2512 {
   2513 	long flags;
   2514 	int code = 0;
   2515 
   2516 	if (!showsystray || !i || ev->atom != xatom[XembedInfo] ||
   2517 			!(flags = getatomprop(i, xatom[XembedInfo])))
   2518 		return;
   2519 
   2520 	if (flags & XEMBED_MAPPED && !i->tags) {
   2521 		i->tags = 1;
   2522 		code = XEMBED_WINDOW_ACTIVATE;
   2523 		XMapRaised(dpy, i->win);
   2524 		setclientstate(i, NormalState);
   2525 	}
   2526 	else if (!(flags & XEMBED_MAPPED) && i->tags) {
   2527 		i->tags = 0;
   2528 		code = XEMBED_WINDOW_DEACTIVATE;
   2529 		XUnmapWindow(dpy, i->win);
   2530 		setclientstate(i, WithdrawnState);
   2531 	}
   2532 	else
   2533 		return;
   2534 	sendevent(i->win, xatom[Xembed], StructureNotifyMask, CurrentTime, code, 0,
   2535 			systray->win, XEMBED_EMBEDDED_VERSION);
   2536 }
   2537 
   2538 void
   2539 updatesystray(void)
   2540 {
   2541 	XSetWindowAttributes wa;
   2542 	XWindowChanges wc;
   2543 	Client *i;
   2544 	Monitor *m = systraytomon(NULL);
   2545 	unsigned int x = m->mx + m->mw - vp;
   2546 	unsigned int y = m->by + sp;
   2547 	unsigned int sw = TEXTW(stext) - lrpad + systrayspacing;
   2548 	unsigned int w = 1;
   2549 
   2550 	if (!showsystray)
   2551 		return;
   2552 	if (systrayonleft)
   2553 		x -= sw + lrpad / 2;
   2554 	if (!systray) {
   2555 		/* init systray */
   2556 		if (!(systray = (Systray *)calloc(1, sizeof(Systray))))
   2557 			die("fatal: could not malloc() %u bytes\n", sizeof(Systray));
   2558 		systray->win = XCreateSimpleWindow(dpy, root, x, y, w, bh, 0, 0, scheme[SchemeSel][ColBg].pixel);
   2559 		wa.event_mask        = ButtonPressMask | ExposureMask;
   2560 		wa.override_redirect = True;
   2561 		wa.background_pixel  = scheme[SchemeNorm][ColBg].pixel;
   2562 		XSelectInput(dpy, systray->win, SubstructureNotifyMask);
   2563 		XChangeProperty(dpy, systray->win, netatom[NetSystemTrayOrientation], XA_CARDINAL, 32,
   2564 				PropModeReplace, (unsigned char *)&netatom[NetSystemTrayOrientationHorz], 1);
   2565 		XChangeWindowAttributes(dpy, systray->win, CWEventMask|CWOverrideRedirect|CWBackPixel, &wa);
   2566 		XMapRaised(dpy, systray->win);
   2567 		XSetSelectionOwner(dpy, netatom[NetSystemTray], systray->win, CurrentTime);
   2568 		if (XGetSelectionOwner(dpy, netatom[NetSystemTray]) == systray->win) {
   2569 			sendevent(root, xatom[Manager], StructureNotifyMask, CurrentTime, netatom[NetSystemTray], systray->win, 0, 0);
   2570 			XSync(dpy, False);
   2571 		}
   2572 		else {
   2573 			fprintf(stderr, "birdwm: unable to obtain system tray.\n");
   2574 			free(systray);
   2575 			systray = NULL;
   2576 			return;
   2577 		}
   2578 	}
   2579 	for (w = 0, i = systray->icons; i; i = i->next) {
   2580 		/* make sure the background color stays the same */
   2581 		wa.background_pixel  = scheme[SchemeNorm][ColBg].pixel;
   2582 		XChangeWindowAttributes(dpy, i->win, CWBackPixel, &wa);
   2583 		XMapRaised(dpy, i->win);
   2584 		w += systrayspacing;
   2585 		i->x = w;
   2586 		XMoveResizeWindow(dpy, i->win, i->x, y - sp, i->w, i->h);
   2587 		w += i->w;
   2588 		if (i->mon != m)
   2589 			i->mon = m;
   2590 	}
   2591 	w = w ? w + systrayspacing : 1;
   2592 	x -= w;
   2593 	XMoveResizeWindow(dpy, systray->win, x, y, w, bh);
   2594 	wc.x = x; wc.y = y; wc.width = w; wc.height = bh;
   2595 	wc.stack_mode = Above; wc.sibling = m->barwin;
   2596 	XConfigureWindow(dpy, systray->win, CWX|CWY|CWWidth|CWHeight|CWSibling|CWStackMode, &wc);
   2597 	XMapWindow(dpy, systray->win);
   2598 	XMapSubwindows(dpy, systray->win);
   2599 	/* redraw background */
   2600 	XSetForeground(dpy, drw->gc, scheme[SchemeNorm][ColBg].pixel);
   2601 	XFillRectangle(dpy, systray->win, drw->gc, 0, 0, w, bh);
   2602 	XSync(dpy, False);
   2603 }
   2604 
   2605 void
   2606 updatetitle(Client *c)
   2607 {
   2608 	if (!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
   2609 		gettextprop(c->win, XA_WM_NAME, c->name, sizeof c->name);
   2610 	if (c->name[0] == '\0') /* hack to mark broken clients */
   2611 		strcpy(c->name, broken);
   2612 }
   2613 
   2614 void
   2615 updateicon(Client *c)
   2616 {
   2617 	freeicon(c);
   2618 	c->icon = geticonprop(c->win, &c->icw, &c->ich);
   2619 }
   2620 
   2621 void
   2622 updatewindowtype(Client *c)
   2623 {
   2624 	Atom state = getatomprop(c, netatom[NetWMState]);
   2625 	Atom wtype = getatomprop(c, netatom[NetWMWindowType]);
   2626 
   2627 	if (state == netatom[NetWMFullscreen])
   2628 		setfullscreen(c, 1);
   2629 	if (wtype == netatom[NetWMWindowTypeDialog])
   2630 		c->isfloating = 1;
   2631 }
   2632 
   2633 void
   2634 updatewmhints(Client *c)
   2635 {
   2636 	XWMHints *wmh;
   2637 
   2638 	if ((wmh = XGetWMHints(dpy, c->win))) {
   2639 		if (c == selmon->sel && wmh->flags & XUrgencyHint) {
   2640 			wmh->flags &= ~XUrgencyHint;
   2641 			XSetWMHints(dpy, c->win, wmh);
   2642 		} else
   2643 			c->isurgent = (wmh->flags & XUrgencyHint) ? 1 : 0;
   2644 		if (wmh->flags & InputHint)
   2645 			c->neverfocus = !wmh->input;
   2646 		else
   2647 			c->neverfocus = 0;
   2648 		XFree(wmh);
   2649 	}
   2650 }
   2651 
   2652 void
   2653 view(const Arg *arg)
   2654 {
   2655 	if ((arg->ui & TAGMASK) == selmon->tagset[selmon->seltags])
   2656 		return;
   2657 	selmon->seltags ^= 1; /* toggle sel tagset */
   2658 	if (arg->ui & TAGMASK)
   2659 		selmon->tagset[selmon->seltags] = arg->ui & TAGMASK;
   2660 	focus(NULL);
   2661 	arrange(selmon);
   2662 }
   2663 
   2664 Client *
   2665 wintoclient(Window w)
   2666 {
   2667 	Client *c;
   2668 	Monitor *m;
   2669 
   2670 	for (m = mons; m; m = m->next)
   2671 		for (c = m->clients; c; c = c->next)
   2672 			if (c->win == w)
   2673 				return c;
   2674 	return NULL;
   2675 }
   2676 
   2677 Client *
   2678 wintosystrayicon(Window w) {
   2679 	Client *i = NULL;
   2680 
   2681 	if (!showsystray || !w)
   2682 		return i;
   2683 	for (i = systray->icons; i && i->win != w; i = i->next) ;
   2684 	return i;
   2685 }
   2686 
   2687 Monitor *
   2688 wintomon(Window w)
   2689 {
   2690 	int x, y;
   2691 	Client *c;
   2692 	Monitor *m;
   2693 
   2694 	if (w == root && getrootptr(&x, &y))
   2695 		return recttomon(x, y, 1, 1);
   2696 	for (m = mons; m; m = m->next)
   2697 		if (w == m->barwin)
   2698 			return m;
   2699 	if ((c = wintoclient(w)))
   2700 		return c->mon;
   2701 	return selmon;
   2702 }
   2703 
   2704 /* There's no way to check accesses to destroyed windows, thus those cases are
   2705  * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
   2706  * default error handler, which may call exit. */
   2707 int
   2708 xerror(Display *dpy, XErrorEvent *ee)
   2709 {
   2710 	if (ee->error_code == BadWindow
   2711 	|| (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
   2712 	|| (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
   2713 	|| (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
   2714 	|| (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
   2715 	|| (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
   2716 	|| (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
   2717 	|| (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
   2718 	|| (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
   2719 		return 0;
   2720 	fprintf(stderr, "birdwm: fatal error: request code=%d, error code=%d\n",
   2721 		ee->request_code, ee->error_code);
   2722 	return xerrorxlib(dpy, ee); /* may call exit */
   2723 }
   2724 
   2725 int
   2726 xerrordummy(Display *dpy, XErrorEvent *ee)
   2727 {
   2728 	return 0;
   2729 }
   2730 
   2731 /* Startup Error handler to check if another window manager
   2732  * is already running. */
   2733 int
   2734 xerrorstart(Display *dpy, XErrorEvent *ee)
   2735 {
   2736 	die("birdwm: another window manager is already running");
   2737 	return -1;
   2738 }
   2739 
   2740 Monitor *
   2741 systraytomon(Monitor *m) {
   2742 	Monitor *t;
   2743 	int i, n;
   2744 	if(!systraypinning) {
   2745 		if(!m)
   2746 			return selmon;
   2747 		return m == selmon ? m : NULL;
   2748 	}
   2749 	for(n = 1, t = mons; t && t->next; n++, t = t->next) ;
   2750 	for(i = 1, t = mons; t && t->next && i < systraypinning; i++, t = t->next) ;
   2751 	if(systraypinningfailfirst && n < systraypinning)
   2752 		return mons;
   2753 	return t;
   2754 }
   2755 
   2756 void
   2757 xrdb(const Arg *arg)
   2758 {
   2759   loadxrdb();
   2760   int i;
   2761   for (i = 0; i < LENGTH(colors); i++)
   2762                 scheme[i] = drw_scm_create(drw, colors[i], 3);
   2763   focus(NULL);
   2764   arrange(NULL);
   2765 }
   2766 
   2767 void
   2768 zoom(const Arg *arg)
   2769 {
   2770 	Client *c = selmon->sel;
   2771 
   2772 	if (!selmon->lt[selmon->sellt]->arrange || !c || c->isfloating)
   2773 		return;
   2774 	if (c == nexttiled(selmon->clients) && !(c = nexttiled(c->next)))
   2775 		return;
   2776 	pop(c);
   2777 }
   2778 
   2779 int
   2780 main(int argc, char *argv[])
   2781 {
   2782 	if (argc == 2 && !strcmp("-v", argv[1]))
   2783 		die("birdwm-"VERSION);
   2784 	else if (argc != 1)
   2785 		die("usage: birdwm [-v]");
   2786 	if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
   2787 		fputs("warning: no locale support\n", stderr);
   2788 	if (!(dpy = XOpenDisplay(NULL)))
   2789 		die("birdwm: cannot open display");
   2790 	checkotherwm();
   2791 	autostart_exec();
   2792         XrmInitialize();
   2793         loadxrdb();
   2794 	setup();
   2795 #ifdef __OpenBSD__
   2796 	if (pledge("stdio rpath proc exec", NULL) == -1)
   2797 		die("pledge");
   2798 #endif /* __OpenBSD__ */
   2799 	scan();
   2800 	run();
   2801 	cleanup();
   2802 	XCloseDisplay(dpy);
   2803 	return EXIT_SUCCESS;
   2804 }
   2805