dwm

Personal build of suckless' dwm
git clone git://git.gormless.xyz/dwm.git
Log | Files | Refs | README | LICENSE

dwm.c (57131B)


      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 dwm 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 <sys/types.h>
     32 #include <sys/wait.h>
     33 #include <X11/cursorfont.h>
     34 #include <X11/keysym.h>
     35 #include <X11/Xatom.h>
     36 #include <X11/Xlib.h>
     37 #include <X11/Xproto.h>
     38 #include <X11/Xutil.h>
     39 #ifdef XINERAMA
     40 #include <X11/extensions/Xinerama.h>
     41 #endif /* XINERAMA */
     42 #include <X11/Xft/Xft.h>
     43 #include <X11/Xlib-xcb.h>
     44 #include <xcb/res.h>
     45 #ifdef __OpenBSD__
     46 #include <sys/sysctl.h>
     47 #include <kvm.h>
     48 #endif /* __OpenBSD */
     49 
     50 #include "drw.h"
     51 #include "util.h"
     52 
     53 /* macros */
     54 #define BUTTONMASK              (ButtonPressMask|ButtonReleaseMask)
     55 #define CLEANMASK(mask)         (mask & ~(numlockmask|LockMask) & (ShiftMask|ControlMask|Mod1Mask|Mod2Mask|Mod3Mask|Mod4Mask|Mod5Mask))
     56 #define INTERSECT(x,y,w,h,m)    (MAX(0, MIN((x)+(w),(m)->wx+(m)->ww) - MAX((x),(m)->wx)) \
     57                                * MAX(0, MIN((y)+(h),(m)->wy+(m)->wh) - MAX((y),(m)->wy)))
     58 #define ISVISIBLE(C)            ((C->tags & C->mon->tagset[C->mon->seltags]))
     59 #define LENGTH(X)               (sizeof X / sizeof X[0])
     60 #define MOUSEMASK               (BUTTONMASK|PointerMotionMask)
     61 #define WIDTH(X)                ((X)->w + 2 * (X)->bw)
     62 #define HEIGHT(X)               ((X)->h + 2 * (X)->bw)
     63 #define TAGMASK                 ((1 << LENGTH(tags)) - 1)
     64 #define TEXTW(X)                (drw_fontset_getwidth(drw, (X)) + lrpad)
     65 
     66 /* enums */
     67 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
     68 enum { SchemeNorm, SchemeSel }; /* color schemes */
     69 enum { NetSupported, NetWMName, NetWMState, NetWMCheck,
     70        NetWMFullscreen, NetActiveWindow, NetWMWindowType,
     71        NetWMWindowTypeDialog, NetClientList, NetLast }; /* EWMH atoms */
     72 enum { WMProtocols, WMDelete, WMState, WMTakeFocus, WMLast }; /* default atoms */
     73 enum { ClkTagBar, ClkLtSymbol, ClkStatusText, ClkWinTitle,
     74        ClkClientWin, ClkRootWin, ClkLast }; /* clicks */
     75 
     76 typedef union {
     77 	int i;
     78 	unsigned int ui;
     79 	float f;
     80 	const void *v;
     81 } Arg;
     82 
     83 typedef struct {
     84 	unsigned int click;
     85 	unsigned int mask;
     86 	unsigned int button;
     87 	void (*func)(const Arg *arg);
     88 	const Arg arg;
     89 } Button;
     90 
     91 typedef struct Monitor Monitor;
     92 typedef struct Client Client;
     93 struct Client {
     94 	char name[256];
     95 	float mina, maxa;
     96 	int x, y, w, h;
     97 	int oldx, oldy, oldw, oldh;
     98 	int basew, baseh, incw, inch, maxw, maxh, minw, minh;
     99 	int bw, oldbw;
    100 	unsigned int tags;
    101 	int isfixed, isfloating, isurgent, neverfocus, oldstate, isfullscreen, isterminal, noswallow;
    102 	pid_t pid;
    103 	Client *next;
    104 	Client *snext;
    105 	Client *swallowing;
    106 	Monitor *mon;
    107 	Window win;
    108 };
    109 
    110 typedef struct {
    111 	unsigned int mod;
    112 	KeySym keysym;
    113 	void (*func)(const Arg *);
    114 	const Arg arg;
    115 } Key;
    116 
    117 typedef struct {
    118 	const char *symbol;
    119 	void (*arrange)(Monitor *);
    120 } Layout;
    121 
    122 struct Monitor {
    123 	char ltsymbol[16];
    124 	float mfact;
    125 	int nmaster;
    126 	int num;
    127 	int by;               /* bar geometry */
    128 	int mx, my, mw, mh;   /* screen size */
    129 	int wx, wy, ww, wh;   /* window area  */
    130 	unsigned int seltags;
    131 	unsigned int sellt;
    132 	unsigned int tagset[2];
    133 	int showbar;
    134 	int topbar;
    135 	Client *clients;
    136 	Client *sel;
    137 	Client *stack;
    138 	Monitor *next;
    139 	Window barwin;
    140 	const Layout *lt[2];
    141 };
    142 
    143 typedef struct {
    144 	const char *class;
    145 	const char *instance;
    146 	const char *title;
    147 	unsigned int tags;
    148 	int isfloating;
    149 	int isterminal;
    150 	int noswallow;
    151 	int monitor;
    152 } Rule;
    153 
    154 /* function declarations */
    155 static void applyrules(Client *c);
    156 static int applysizehints(Client *c, int *x, int *y, int *w, int *h, int interact);
    157 static void arrange(Monitor *m);
    158 static void arrangemon(Monitor *m);
    159 static void attach(Client *c);
    160 static void attachstack(Client *c);
    161 static void buttonpress(XEvent *e);
    162 static void checkotherwm(void);
    163 static void cleanup(void);
    164 static void cleanupmon(Monitor *mon);
    165 static void clientmessage(XEvent *e);
    166 static void configure(Client *c);
    167 static void configurenotify(XEvent *e);
    168 static void configurerequest(XEvent *e);
    169 static Monitor *createmon(void);
    170 static void destroynotify(XEvent *e);
    171 static void detach(Client *c);
    172 static void detachstack(Client *c);
    173 static Monitor *dirtomon(int dir);
    174 static void drawbar(Monitor *m);
    175 static void drawbars(void);
    176 static void enternotify(XEvent *e);
    177 static void expose(XEvent *e);
    178 static void focus(Client *c);
    179 static void focusin(XEvent *e);
    180 static void focusmon(const Arg *arg);
    181 static void focusstack(const Arg *arg);
    182 static Atom getatomprop(Client *c, Atom prop);
    183 static int getrootptr(int *x, int *y);
    184 static long getstate(Window w);
    185 static int gettextprop(Window w, Atom atom, char *text, unsigned int size);
    186 static void grabbuttons(Client *c, int focused);
    187 static void grabkeys(void);
    188 static void incnmaster(const Arg *arg);
    189 static void keypress(XEvent *e);
    190 static void killclient(const Arg *arg);
    191 static void manage(Window w, XWindowAttributes *wa);
    192 static void mappingnotify(XEvent *e);
    193 static void maprequest(XEvent *e);
    194 static void monocle(Monitor *m);
    195 static void motionnotify(XEvent *e);
    196 static void movemouse(const Arg *arg);
    197 static Client *nexttiled(Client *c);
    198 static void pop(Client *);
    199 static void propertynotify(XEvent *e);
    200 static void quit(const Arg *arg);
    201 static Monitor *recttomon(int x, int y, int w, int h);
    202 static void resize(Client *c, int x, int y, int w, int h, int interact);
    203 static void resizeclient(Client *c, int x, int y, int w, int h);
    204 static void resizemouse(const Arg *arg);
    205 static void restack(Monitor *m);
    206 static void run(void);
    207 static void scan(void);
    208 static int sendevent(Client *c, Atom proto);
    209 static void sendmon(Client *c, Monitor *m);
    210 static void setclientstate(Client *c, long state);
    211 static void setfocus(Client *c);
    212 static void setfullscreen(Client *c, int fullscreen);
    213 static void setlayout(const Arg *arg);
    214 static void setmfact(const Arg *arg);
    215 static void setup(void);
    216 static void seturgent(Client *c, int urg);
    217 static void showhide(Client *c);
    218 static void sigchld(int unused);
    219 static void spawn(const Arg *arg);
    220 static void tag(const Arg *arg);
    221 static void tagmon(const Arg *arg);
    222 static void tile(Monitor *);
    223 static void togglebar(const Arg *arg);
    224 static void togglefloating(const Arg *arg);
    225 static void toggletag(const Arg *arg);
    226 static void toggleview(const Arg *arg);
    227 static void unfocus(Client *c, int setfocus);
    228 static void unmanage(Client *c, int destroyed);
    229 static void unmapnotify(XEvent *e);
    230 static void updatebarpos(Monitor *m);
    231 static void updatebars(void);
    232 static void updateclientlist(void);
    233 static int updategeom(void);
    234 static void updatenumlockmask(void);
    235 static void updatesizehints(Client *c);
    236 static void updatestatus(void);
    237 static void updatetitle(Client *c);
    238 static void updatewindowtype(Client *c);
    239 static void updatewmhints(Client *c);
    240 static void view(const Arg *arg);
    241 static Client *wintoclient(Window w);
    242 static Monitor *wintomon(Window w);
    243 static int xerror(Display *dpy, XErrorEvent *ee);
    244 static int xerrordummy(Display *dpy, XErrorEvent *ee);
    245 static int xerrorstart(Display *dpy, XErrorEvent *ee);
    246 static void zoom(const Arg *arg);
    247 
    248 static pid_t getparentprocess(pid_t p);
    249 static int isdescprocess(pid_t p, pid_t c);
    250 static Client *swallowingclient(Window w);
    251 static Client *termforwin(const Client *c);
    252 static pid_t winpid(Window w);
    253 
    254 /* variables */
    255 static const char broken[] = "broken";
    256 static char stext[256];
    257 static int screen;
    258 static int sw, sh;           /* X display screen geometry width, height */
    259 static int bh, blw = 0;      /* bar geometry */
    260 static int lrpad;            /* sum of left and right padding for text */
    261 static int (*xerrorxlib)(Display *, XErrorEvent *);
    262 static unsigned int numlockmask = 0;
    263 static void (*handler[LASTEvent]) (XEvent *) = {
    264 	[ButtonPress] = buttonpress,
    265 	[ClientMessage] = clientmessage,
    266 	[ConfigureRequest] = configurerequest,
    267 	[ConfigureNotify] = configurenotify,
    268 	[DestroyNotify] = destroynotify,
    269 	[EnterNotify] = enternotify,
    270 	[Expose] = expose,
    271 	[FocusIn] = focusin,
    272 	[KeyPress] = keypress,
    273 	[MappingNotify] = mappingnotify,
    274 	[MapRequest] = maprequest,
    275 	[MotionNotify] = motionnotify,
    276 	[PropertyNotify] = propertynotify,
    277 	[UnmapNotify] = unmapnotify
    278 };
    279 static Atom wmatom[WMLast], netatom[NetLast];
    280 static int running = 1;
    281 static Cur *cursor[CurLast];
    282 static Clr **scheme;
    283 static Display *dpy;
    284 static Drw *drw;
    285 static Monitor *mons, *selmon;
    286 static Window root, wmcheckwin;
    287 
    288 static xcb_connection_t *xcon;
    289 
    290 /* configuration, allows nested code to access above variables */
    291 #include "config.h"
    292 
    293 /* compile-time check if all tags fit into an unsigned int bit array. */
    294 struct NumTags { char limitexceeded[LENGTH(tags) > 31 ? -1 : 1]; };
    295 
    296 /* function implementations */
    297 void
    298 applyrules(Client *c)
    299 {
    300 	const char *class, *instance;
    301 	unsigned int i;
    302 	const Rule *r;
    303 	Monitor *m;
    304 	XClassHint ch = { NULL, NULL };
    305 
    306 	/* rule matching */
    307 	c->isfloating = 0;
    308 	c->tags = 0;
    309 	XGetClassHint(dpy, c->win, &ch);
    310 	class    = ch.res_class ? ch.res_class : broken;
    311 	instance = ch.res_name  ? ch.res_name  : broken;
    312 
    313 	for (i = 0; i < LENGTH(rules); i++) {
    314 		r = &rules[i];
    315 		if ((!r->title || strstr(c->name, r->title))
    316 		&& (!r->class || strstr(class, r->class))
    317 		&& (!r->instance || strstr(instance, r->instance)))
    318 		{
    319 			c->isterminal = r->isterminal;
    320 			c->noswallow  = r->noswallow;
    321 			c->isfloating = r->isfloating;
    322 			c->tags |= r->tags;
    323 			for (m = mons; m && m->num != r->monitor; m = m->next);
    324 			if (m)
    325 				c->mon = m;
    326 		}
    327 	}
    328 	if (ch.res_class)
    329 		XFree(ch.res_class);
    330 	if (ch.res_name)
    331 		XFree(ch.res_name);
    332 	c->tags = c->tags & TAGMASK ? c->tags & TAGMASK : c->mon->tagset[c->mon->seltags];
    333 }
    334 
    335 int
    336 applysizehints(Client *c, int *x, int *y, int *w, int *h, int interact)
    337 {
    338 	int baseismin;
    339 	Monitor *m = c->mon;
    340 
    341 	/* set minimum possible */
    342 	*w = MAX(1, *w);
    343 	*h = MAX(1, *h);
    344 	if (interact) {
    345 		if (*x > sw)
    346 			*x = sw - WIDTH(c);
    347 		if (*y > sh)
    348 			*y = sh - HEIGHT(c);
    349 		if (*x + *w + 2 * c->bw < 0)
    350 			*x = 0;
    351 		if (*y + *h + 2 * c->bw < 0)
    352 			*y = 0;
    353 	} else {
    354 		if (*x >= m->wx + m->ww)
    355 			*x = m->wx + m->ww - WIDTH(c);
    356 		if (*y >= m->wy + m->wh)
    357 			*y = m->wy + m->wh - HEIGHT(c);
    358 		if (*x + *w + 2 * c->bw <= m->wx)
    359 			*x = m->wx;
    360 		if (*y + *h + 2 * c->bw <= m->wy)
    361 			*y = m->wy;
    362 	}
    363 	if (*h < bh)
    364 		*h = bh;
    365 	if (*w < bh)
    366 		*w = bh;
    367 	if (resizehints || c->isfloating || !c->mon->lt[c->mon->sellt]->arrange) {
    368 		/* see last two sentences in ICCCM 4.1.2.3 */
    369 		baseismin = c->basew == c->minw && c->baseh == c->minh;
    370 		if (!baseismin) { /* temporarily remove base dimensions */
    371 			*w -= c->basew;
    372 			*h -= c->baseh;
    373 		}
    374 		/* adjust for aspect limits */
    375 		if (c->mina > 0 && c->maxa > 0) {
    376 			if (c->maxa < (float)*w / *h)
    377 				*w = *h * c->maxa + 0.5;
    378 			else if (c->mina < (float)*h / *w)
    379 				*h = *w * c->mina + 0.5;
    380 		}
    381 		if (baseismin) { /* increment calculation requires this */
    382 			*w -= c->basew;
    383 			*h -= c->baseh;
    384 		}
    385 		/* adjust for increment value */
    386 		if (c->incw)
    387 			*w -= *w % c->incw;
    388 		if (c->inch)
    389 			*h -= *h % c->inch;
    390 		/* restore base dimensions */
    391 		*w = MAX(*w + c->basew, c->minw);
    392 		*h = MAX(*h + c->baseh, c->minh);
    393 		if (c->maxw)
    394 			*w = MIN(*w, c->maxw);
    395 		if (c->maxh)
    396 			*h = MIN(*h, c->maxh);
    397 	}
    398 	return *x != c->x || *y != c->y || *w != c->w || *h != c->h;
    399 }
    400 
    401 void
    402 arrange(Monitor *m)
    403 {
    404 	if (m)
    405 		showhide(m->stack);
    406 	else for (m = mons; m; m = m->next)
    407 		showhide(m->stack);
    408 	if (m) {
    409 		arrangemon(m);
    410 		restack(m);
    411 	} else for (m = mons; m; m = m->next)
    412 		arrangemon(m);
    413 }
    414 
    415 void
    416 arrangemon(Monitor *m)
    417 {
    418 	strncpy(m->ltsymbol, m->lt[m->sellt]->symbol, sizeof m->ltsymbol);
    419 	if (m->lt[m->sellt]->arrange)
    420 		m->lt[m->sellt]->arrange(m);
    421 }
    422 
    423 void
    424 attach(Client *c)
    425 {
    426 	c->next = c->mon->clients;
    427 	c->mon->clients = c;
    428 }
    429 
    430 void
    431 attachstack(Client *c)
    432 {
    433 	c->snext = c->mon->stack;
    434 	c->mon->stack = c;
    435 }
    436 
    437 void
    438 swallow(Client *p, Client *c)
    439 {
    440 
    441 	if (c->noswallow || c->isterminal)
    442 		return;
    443 	if (c->noswallow && !swallowfloating && c->isfloating)
    444 		return;
    445 
    446 	detach(c);
    447 	detachstack(c);
    448 
    449 	setclientstate(c, WithdrawnState);
    450 	XUnmapWindow(dpy, p->win);
    451 
    452 	p->swallowing = c;
    453 	c->mon = p->mon;
    454 
    455 	Window w = p->win;
    456 	p->win = c->win;
    457 	c->win = w;
    458 	updatetitle(p);
    459 	XMoveResizeWindow(dpy, p->win, p->x, p->y, p->w, p->h);
    460 	arrange(p->mon);
    461 	configure(p);
    462 	updateclientlist();
    463 }
    464 
    465 void
    466 unswallow(Client *c)
    467 {
    468 	c->win = c->swallowing->win;
    469 
    470 	free(c->swallowing);
    471 	c->swallowing = NULL;
    472 
    473 	/* unfullscreen the client */
    474 	setfullscreen(c, 0);
    475 	updatetitle(c);
    476 	arrange(c->mon);
    477 	XMapWindow(dpy, c->win);
    478 	XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
    479 	setclientstate(c, NormalState);
    480 	focus(NULL);
    481 	arrange(c->mon);
    482 }
    483 
    484 void
    485 buttonpress(XEvent *e)
    486 {
    487 	unsigned int i, x, click;
    488 	Arg arg = {0};
    489 	Client *c;
    490 	Monitor *m;
    491 	XButtonPressedEvent *ev = &e->xbutton;
    492 
    493 	click = ClkRootWin;
    494 	/* focus monitor if necessary */
    495 	if ((m = wintomon(ev->window)) && m != selmon) {
    496 		unfocus(selmon->sel, 1);
    497 		selmon = m;
    498 		focus(NULL);
    499 	}
    500 	if (ev->window == selmon->barwin) {
    501 		i = x = 0;
    502 		do
    503 			x += TEXTW(tags[i]);
    504 		while (ev->x >= x && ++i < LENGTH(tags));
    505 		if (i < LENGTH(tags)) {
    506 			click = ClkTagBar;
    507 			arg.ui = 1 << i;
    508 		} else if (ev->x < x + blw)
    509 			click = ClkLtSymbol;
    510 		else if (ev->x > selmon->ww - (int)TEXTW(stext))
    511 			click = ClkStatusText;
    512 		else
    513 			click = ClkWinTitle;
    514 	} else if ((c = wintoclient(ev->window))) {
    515 		focus(c);
    516 		restack(selmon);
    517 		XAllowEvents(dpy, ReplayPointer, CurrentTime);
    518 		click = ClkClientWin;
    519 	}
    520 	for (i = 0; i < LENGTH(buttons); i++)
    521 		if (click == buttons[i].click && buttons[i].func && buttons[i].button == ev->button
    522 		&& CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
    523 			buttons[i].func(click == ClkTagBar && buttons[i].arg.i == 0 ? &arg : &buttons[i].arg);
    524 }
    525 
    526 void
    527 checkotherwm(void)
    528 {
    529 	xerrorxlib = XSetErrorHandler(xerrorstart);
    530 	/* this causes an error if some other window manager is running */
    531 	XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
    532 	XSync(dpy, False);
    533 	XSetErrorHandler(xerror);
    534 	XSync(dpy, False);
    535 }
    536 
    537 void
    538 cleanup(void)
    539 {
    540 	Arg a = {.ui = ~0};
    541 	Layout foo = { "", NULL };
    542 	Monitor *m;
    543 	size_t i;
    544 
    545 	view(&a);
    546 	selmon->lt[selmon->sellt] = &foo;
    547 	for (m = mons; m; m = m->next)
    548 		while (m->stack)
    549 			unmanage(m->stack, 0);
    550 	XUngrabKey(dpy, AnyKey, AnyModifier, root);
    551 	while (mons)
    552 		cleanupmon(mons);
    553 	for (i = 0; i < CurLast; i++)
    554 		drw_cur_free(drw, cursor[i]);
    555 	for (i = 0; i < LENGTH(colors); i++)
    556 		free(scheme[i]);
    557 	XDestroyWindow(dpy, wmcheckwin);
    558 	drw_free(drw);
    559 	XSync(dpy, False);
    560 	XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
    561 	XDeleteProperty(dpy, root, netatom[NetActiveWindow]);
    562 }
    563 
    564 void
    565 cleanupmon(Monitor *mon)
    566 {
    567 	Monitor *m;
    568 
    569 	if (mon == mons)
    570 		mons = mons->next;
    571 	else {
    572 		for (m = mons; m && m->next != mon; m = m->next);
    573 		m->next = mon->next;
    574 	}
    575 	XUnmapWindow(dpy, mon->barwin);
    576 	XDestroyWindow(dpy, mon->barwin);
    577 	free(mon);
    578 }
    579 
    580 void
    581 clientmessage(XEvent *e)
    582 {
    583 	XClientMessageEvent *cme = &e->xclient;
    584 	Client *c = wintoclient(cme->window);
    585 
    586 	if (!c)
    587 		return;
    588 	if (cme->message_type == netatom[NetWMState]) {
    589 		if (cme->data.l[1] == netatom[NetWMFullscreen]
    590 		|| cme->data.l[2] == netatom[NetWMFullscreen])
    591 			setfullscreen(c, (cme->data.l[0] == 1 /* _NET_WM_STATE_ADD    */
    592 				|| (cme->data.l[0] == 2 /* _NET_WM_STATE_TOGGLE */ && !c->isfullscreen)));
    593 	} else if (cme->message_type == netatom[NetActiveWindow]) {
    594 		if (c != selmon->sel && !c->isurgent)
    595 			seturgent(c, 1);
    596 	}
    597 }
    598 
    599 void
    600 configure(Client *c)
    601 {
    602 	XConfigureEvent ce;
    603 
    604 	ce.type = ConfigureNotify;
    605 	ce.display = dpy;
    606 	ce.event = c->win;
    607 	ce.window = c->win;
    608 	ce.x = c->x;
    609 	ce.y = c->y;
    610 	ce.width = c->w;
    611 	ce.height = c->h;
    612 	ce.border_width = c->bw;
    613 	ce.above = None;
    614 	ce.override_redirect = False;
    615 	XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
    616 }
    617 
    618 void
    619 configurenotify(XEvent *e)
    620 {
    621 	Monitor *m;
    622 	Client *c;
    623 	XConfigureEvent *ev = &e->xconfigure;
    624 	int dirty;
    625 
    626 	/* TODO: updategeom handling sucks, needs to be simplified */
    627 	if (ev->window == root) {
    628 		dirty = (sw != ev->width || sh != ev->height);
    629 		sw = ev->width;
    630 		sh = ev->height;
    631 		if (updategeom() || dirty) {
    632 			drw_resize(drw, sw, bh);
    633 			updatebars();
    634 			for (m = mons; m; m = m->next) {
    635 				for (c = m->clients; c; c = c->next)
    636 					if (c->isfullscreen)
    637 						resizeclient(c, m->mx, m->my, m->mw, m->mh);
    638 				XMoveResizeWindow(dpy, m->barwin, m->wx, m->by, m->ww, bh);
    639 			}
    640 			focus(NULL);
    641 			arrange(NULL);
    642 		}
    643 	}
    644 }
    645 
    646 void
    647 configurerequest(XEvent *e)
    648 {
    649 	Client *c;
    650 	Monitor *m;
    651 	XConfigureRequestEvent *ev = &e->xconfigurerequest;
    652 	XWindowChanges wc;
    653 
    654 	if ((c = wintoclient(ev->window))) {
    655 		if (ev->value_mask & CWBorderWidth)
    656 			c->bw = ev->border_width;
    657 		else if (c->isfloating || !selmon->lt[selmon->sellt]->arrange) {
    658 			m = c->mon;
    659 			if (ev->value_mask & CWX) {
    660 				c->oldx = c->x;
    661 				c->x = m->mx + ev->x;
    662 			}
    663 			if (ev->value_mask & CWY) {
    664 				c->oldy = c->y;
    665 				c->y = m->my + ev->y;
    666 			}
    667 			if (ev->value_mask & CWWidth) {
    668 				c->oldw = c->w;
    669 				c->w = ev->width;
    670 			}
    671 			if (ev->value_mask & CWHeight) {
    672 				c->oldh = c->h;
    673 				c->h = ev->height;
    674 			}
    675 			if ((c->x + c->w) > m->mx + m->mw && c->isfloating)
    676 				c->x = m->mx + (m->mw / 2 - WIDTH(c) / 2); /* center in x direction */
    677 			if ((c->y + c->h) > m->my + m->mh && c->isfloating)
    678 				c->y = m->my + (m->mh / 2 - HEIGHT(c) / 2); /* center in y direction */
    679 			if ((ev->value_mask & (CWX|CWY)) && !(ev->value_mask & (CWWidth|CWHeight)))
    680 				configure(c);
    681 			if (ISVISIBLE(c))
    682 				XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
    683 		} else
    684 			configure(c);
    685 	} else {
    686 		wc.x = ev->x;
    687 		wc.y = ev->y;
    688 		wc.width = ev->width;
    689 		wc.height = ev->height;
    690 		wc.border_width = ev->border_width;
    691 		wc.sibling = ev->above;
    692 		wc.stack_mode = ev->detail;
    693 		XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
    694 	}
    695 	XSync(dpy, False);
    696 }
    697 
    698 Monitor *
    699 createmon(void)
    700 {
    701 	Monitor *m;
    702 
    703 	m = ecalloc(1, sizeof(Monitor));
    704 	m->tagset[0] = m->tagset[1] = 1;
    705 	m->mfact = mfact;
    706 	m->nmaster = nmaster;
    707 	m->showbar = showbar;
    708 	m->topbar = topbar;
    709 	m->lt[0] = &layouts[0];
    710 	m->lt[1] = &layouts[1 % LENGTH(layouts)];
    711 	strncpy(m->ltsymbol, layouts[0].symbol, sizeof m->ltsymbol);
    712 	return m;
    713 }
    714 
    715 void
    716 destroynotify(XEvent *e)
    717 {
    718 	Client *c;
    719 	XDestroyWindowEvent *ev = &e->xdestroywindow;
    720 
    721 	if ((c = wintoclient(ev->window)))
    722 		unmanage(c, 1);
    723 
    724 	else if ((c = swallowingclient(ev->window)))
    725 		unmanage(c->swallowing, 1);
    726 }
    727 
    728 void
    729 detach(Client *c)
    730 {
    731 	Client **tc;
    732 
    733 	for (tc = &c->mon->clients; *tc && *tc != c; tc = &(*tc)->next);
    734 	*tc = c->next;
    735 }
    736 
    737 void
    738 detachstack(Client *c)
    739 {
    740 	Client **tc, *t;
    741 
    742 	for (tc = &c->mon->stack; *tc && *tc != c; tc = &(*tc)->snext);
    743 	*tc = c->snext;
    744 
    745 	if (c == c->mon->sel) {
    746 		for (t = c->mon->stack; t && !ISVISIBLE(t); t = t->snext);
    747 		c->mon->sel = t;
    748 	}
    749 }
    750 
    751 Monitor *
    752 dirtomon(int dir)
    753 {
    754 	Monitor *m = NULL;
    755 
    756 	if (dir > 0) {
    757 		if (!(m = selmon->next))
    758 			m = mons;
    759 	} else if (selmon == mons)
    760 		for (m = mons; m->next; m = m->next);
    761 	else
    762 		for (m = mons; m->next != selmon; m = m->next);
    763 	return m;
    764 }
    765 
    766 void
    767 drawbar(Monitor *m)
    768 {
    769 	int x, w, tw = 0;
    770 	int boxs = drw->fonts->h / 9;
    771 	int boxw = drw->fonts->h / 6 + 2;
    772 	unsigned int i, occ = 0, urg = 0;
    773 	Client *c;
    774 
    775 	/* draw status first so it can be overdrawn by tags later */
    776 	if (m == selmon) { /* status is only drawn on selected monitor */
    777 		drw_setscheme(drw, scheme[SchemeNorm]);
    778 		tw = TEXTW(stext) - lrpad + 2; /* 2px right padding */
    779 		drw_text(drw, m->ww - tw, 0, tw, bh, 0, stext, 0);
    780 	}
    781 
    782 	for (c = m->clients; c; c = c->next) {
    783 		occ |= c->tags;
    784 		if (c->isurgent)
    785 			urg |= c->tags;
    786 	}
    787 	x = 0;
    788 	for (i = 0; i < LENGTH(tags); i++) {
    789 		w = TEXTW(tags[i]);
    790 		drw_setscheme(drw, scheme[m->tagset[m->seltags] & 1 << i ? SchemeSel : SchemeNorm]);
    791 		drw_text(drw, x, 0, w, bh, lrpad / 2, tags[i], urg & 1 << i);
    792 		if (occ & 1 << i)
    793 			drw_rect(drw, x + boxs, boxs, boxw, boxw,
    794 				m == selmon && selmon->sel && selmon->sel->tags & 1 << i,
    795 				urg & 1 << i);
    796 		x += w;
    797 	}
    798 	w = blw = TEXTW(m->ltsymbol);
    799 	drw_setscheme(drw, scheme[SchemeNorm]);
    800 	x = drw_text(drw, x, 0, w, bh, lrpad / 2, m->ltsymbol, 0);
    801 
    802 	if ((w = m->ww - tw - x) > bh) {
    803 		if (m->sel) {
    804 			drw_setscheme(drw, scheme[m == selmon ? SchemeSel : SchemeNorm]);
    805 			drw_text(drw, x, 0, w, bh, lrpad / 2, m->sel->name, 0);
    806 			if (m->sel->isfloating)
    807 				drw_rect(drw, x + boxs, boxs, boxw, boxw, m->sel->isfixed, 0);
    808 		} else {
    809 			drw_setscheme(drw, scheme[SchemeNorm]);
    810 			drw_rect(drw, x, 0, w, bh, 1, 1);
    811 		}
    812 	}
    813 	drw_map(drw, m->barwin, 0, 0, m->ww, bh);
    814 }
    815 
    816 void
    817 drawbars(void)
    818 {
    819 	Monitor *m;
    820 
    821 	for (m = mons; m; m = m->next)
    822 		drawbar(m);
    823 }
    824 
    825 void
    826 enternotify(XEvent *e)
    827 {
    828 	Client *c;
    829 	Monitor *m;
    830 	XCrossingEvent *ev = &e->xcrossing;
    831 
    832 	if ((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
    833 		return;
    834 	c = wintoclient(ev->window);
    835 	m = c ? c->mon : wintomon(ev->window);
    836 	if (m != selmon) {
    837 		unfocus(selmon->sel, 1);
    838 		selmon = m;
    839 	} else if (!c || c == selmon->sel)
    840 		return;
    841 	focus(c);
    842 }
    843 
    844 void
    845 expose(XEvent *e)
    846 {
    847 	Monitor *m;
    848 	XExposeEvent *ev = &e->xexpose;
    849 
    850 	if (ev->count == 0 && (m = wintomon(ev->window)))
    851 		drawbar(m);
    852 }
    853 
    854 void
    855 focus(Client *c)
    856 {
    857 	if (!c || !ISVISIBLE(c))
    858 		for (c = selmon->stack; c && !ISVISIBLE(c); c = c->snext);
    859 	if (selmon->sel && selmon->sel != c)
    860 		unfocus(selmon->sel, 0);
    861 	if (c) {
    862 		if (c->mon != selmon)
    863 			selmon = c->mon;
    864 		if (c->isurgent)
    865 			seturgent(c, 0);
    866 		detachstack(c);
    867 		attachstack(c);
    868 		grabbuttons(c, 1);
    869 		XSetWindowBorder(dpy, c->win, scheme[SchemeSel][ColBorder].pixel);
    870 		setfocus(c);
    871 	} else {
    872 		XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
    873 		XDeleteProperty(dpy, root, netatom[NetActiveWindow]);
    874 	}
    875 	selmon->sel = c;
    876 	drawbars();
    877 }
    878 
    879 /* there are some broken focus acquiring clients needing extra handling */
    880 void
    881 focusin(XEvent *e)
    882 {
    883 	XFocusChangeEvent *ev = &e->xfocus;
    884 
    885 	if (selmon->sel && ev->window != selmon->sel->win)
    886 		setfocus(selmon->sel);
    887 }
    888 
    889 void
    890 focusmon(const Arg *arg)
    891 {
    892 	Monitor *m;
    893 
    894 	if (!mons->next)
    895 		return;
    896 	if ((m = dirtomon(arg->i)) == selmon)
    897 		return;
    898 	unfocus(selmon->sel, 0);
    899 	selmon = m;
    900 	focus(NULL);
    901 }
    902 
    903 void
    904 focusstack(const Arg *arg)
    905 {
    906 	Client *c = NULL, *i;
    907 
    908 	if (!selmon->sel || (selmon->sel->isfullscreen && lockfullscreen))
    909 		return;
    910 	if (arg->i > 0) {
    911 		for (c = selmon->sel->next; c && !ISVISIBLE(c); c = c->next);
    912 		if (!c)
    913 			for (c = selmon->clients; c && !ISVISIBLE(c); c = c->next);
    914 	} else {
    915 		for (i = selmon->clients; i != selmon->sel; i = i->next)
    916 			if (ISVISIBLE(i))
    917 				c = i;
    918 		if (!c)
    919 			for (; i; i = i->next)
    920 				if (ISVISIBLE(i))
    921 					c = i;
    922 	}
    923 	if (c) {
    924 		focus(c);
    925 		restack(selmon);
    926 	}
    927 }
    928 
    929 Atom
    930 getatomprop(Client *c, Atom prop)
    931 {
    932 	int di;
    933 	unsigned long dl;
    934 	unsigned char *p = NULL;
    935 	Atom da, atom = None;
    936 
    937 	if (XGetWindowProperty(dpy, c->win, prop, 0L, sizeof atom, False, XA_ATOM,
    938 		&da, &di, &dl, &dl, &p) == Success && p) {
    939 		atom = *(Atom *)p;
    940 		XFree(p);
    941 	}
    942 	return atom;
    943 }
    944 
    945 int
    946 getrootptr(int *x, int *y)
    947 {
    948 	int di;
    949 	unsigned int dui;
    950 	Window dummy;
    951 
    952 	return XQueryPointer(dpy, root, &dummy, &dummy, x, y, &di, &di, &dui);
    953 }
    954 
    955 long
    956 getstate(Window w)
    957 {
    958 	int format;
    959 	long result = -1;
    960 	unsigned char *p = NULL;
    961 	unsigned long n, extra;
    962 	Atom real;
    963 
    964 	if (XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
    965 		&real, &format, &n, &extra, (unsigned char **)&p) != Success)
    966 		return -1;
    967 	if (n != 0)
    968 		result = *p;
    969 	XFree(p);
    970 	return result;
    971 }
    972 
    973 int
    974 gettextprop(Window w, Atom atom, char *text, unsigned int size)
    975 {
    976 	char **list = NULL;
    977 	int n;
    978 	XTextProperty name;
    979 
    980 	if (!text || size == 0)
    981 		return 0;
    982 	text[0] = '\0';
    983 	if (!XGetTextProperty(dpy, w, &name, atom) || !name.nitems)
    984 		return 0;
    985 	if (name.encoding == XA_STRING)
    986 		strncpy(text, (char *)name.value, size - 1);
    987 	else {
    988 		if (XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success && n > 0 && *list) {
    989 			strncpy(text, *list, size - 1);
    990 			XFreeStringList(list);
    991 		}
    992 	}
    993 	text[size - 1] = '\0';
    994 	XFree(name.value);
    995 	return 1;
    996 }
    997 
    998 void
    999 grabbuttons(Client *c, int focused)
   1000 {
   1001 	updatenumlockmask();
   1002 	{
   1003 		unsigned int i, j;
   1004 		unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
   1005 		XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
   1006 		if (!focused)
   1007 			XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
   1008 				BUTTONMASK, GrabModeSync, GrabModeSync, None, None);
   1009 		for (i = 0; i < LENGTH(buttons); i++)
   1010 			if (buttons[i].click == ClkClientWin)
   1011 				for (j = 0; j < LENGTH(modifiers); j++)
   1012 					XGrabButton(dpy, buttons[i].button,
   1013 						buttons[i].mask | modifiers[j],
   1014 						c->win, False, BUTTONMASK,
   1015 						GrabModeAsync, GrabModeSync, None, None);
   1016 	}
   1017 }
   1018 
   1019 void
   1020 grabkeys(void)
   1021 {
   1022 	updatenumlockmask();
   1023 	{
   1024 		unsigned int i, j;
   1025 		unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
   1026 		KeyCode code;
   1027 
   1028 		XUngrabKey(dpy, AnyKey, AnyModifier, root);
   1029 		for (i = 0; i < LENGTH(keys); i++)
   1030 			if ((code = XKeysymToKeycode(dpy, keys[i].keysym)))
   1031 				for (j = 0; j < LENGTH(modifiers); j++)
   1032 					XGrabKey(dpy, code, keys[i].mod | modifiers[j], root,
   1033 						True, GrabModeAsync, GrabModeAsync);
   1034 	}
   1035 }
   1036 
   1037 void
   1038 incnmaster(const Arg *arg)
   1039 {
   1040 	selmon->nmaster = MAX(selmon->nmaster + arg->i, 0);
   1041 	arrange(selmon);
   1042 }
   1043 
   1044 #ifdef XINERAMA
   1045 static int
   1046 isuniquegeom(XineramaScreenInfo *unique, size_t n, XineramaScreenInfo *info)
   1047 {
   1048 	while (n--)
   1049 		if (unique[n].x_org == info->x_org && unique[n].y_org == info->y_org
   1050 		&& unique[n].width == info->width && unique[n].height == info->height)
   1051 			return 0;
   1052 	return 1;
   1053 }
   1054 #endif /* XINERAMA */
   1055 
   1056 void
   1057 keypress(XEvent *e)
   1058 {
   1059 	unsigned int i;
   1060 	KeySym keysym;
   1061 	XKeyEvent *ev;
   1062 
   1063 	ev = &e->xkey;
   1064 	keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
   1065 	for (i = 0; i < LENGTH(keys); i++)
   1066 		if (keysym == keys[i].keysym
   1067 		&& CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
   1068 		&& keys[i].func)
   1069 			keys[i].func(&(keys[i].arg));
   1070 }
   1071 
   1072 void
   1073 killclient(const Arg *arg)
   1074 {
   1075 	if (!selmon->sel)
   1076 		return;
   1077 	if (!sendevent(selmon->sel, wmatom[WMDelete])) {
   1078 		XGrabServer(dpy);
   1079 		XSetErrorHandler(xerrordummy);
   1080 		XSetCloseDownMode(dpy, DestroyAll);
   1081 		XKillClient(dpy, selmon->sel->win);
   1082 		XSync(dpy, False);
   1083 		XSetErrorHandler(xerror);
   1084 		XUngrabServer(dpy);
   1085 	}
   1086 }
   1087 
   1088 void
   1089 manage(Window w, XWindowAttributes *wa)
   1090 {
   1091 	Client *c, *t = NULL, *term = NULL;
   1092 	Window trans = None;
   1093 	XWindowChanges wc;
   1094 
   1095 	c = ecalloc(1, sizeof(Client));
   1096 	c->win = w;
   1097 	c->pid = winpid(w);
   1098 	/* geometry */
   1099 	c->x = c->oldx = wa->x;
   1100 	c->y = c->oldy = wa->y;
   1101 	c->w = c->oldw = wa->width;
   1102 	c->h = c->oldh = wa->height;
   1103 	c->oldbw = wa->border_width;
   1104 
   1105 	updatetitle(c);
   1106 	if (XGetTransientForHint(dpy, w, &trans) && (t = wintoclient(trans))) {
   1107 		c->mon = t->mon;
   1108 		c->tags = t->tags;
   1109 	} else {
   1110 		c->mon = selmon;
   1111 		applyrules(c);
   1112 		term = termforwin(c);
   1113 	}
   1114 
   1115 	if (c->x + WIDTH(c) > c->mon->mx + c->mon->mw)
   1116 		c->x = c->mon->mx + c->mon->mw - WIDTH(c);
   1117 	if (c->y + HEIGHT(c) > c->mon->my + c->mon->mh)
   1118 		c->y = c->mon->my + c->mon->mh - HEIGHT(c);
   1119 	c->x = MAX(c->x, c->mon->mx);
   1120 	/* only fix client y-offset, if the client center might cover the bar */
   1121 	c->y = MAX(c->y, ((c->mon->by == c->mon->my) && (c->x + (c->w / 2) >= c->mon->wx)
   1122 		&& (c->x + (c->w / 2) < c->mon->wx + c->mon->ww)) ? bh : c->mon->my);
   1123 	c->bw = borderpx;
   1124 
   1125 	wc.border_width = c->bw;
   1126 	XConfigureWindow(dpy, w, CWBorderWidth, &wc);
   1127 	XSetWindowBorder(dpy, w, scheme[SchemeNorm][ColBorder].pixel);
   1128 	configure(c); /* propagates border_width, if size doesn't change */
   1129 	updatewindowtype(c);
   1130 	updatesizehints(c);
   1131 	updatewmhints(c);
   1132 	XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
   1133 	grabbuttons(c, 0);
   1134 	if (!c->isfloating)
   1135 		c->isfloating = c->oldstate = trans != None || c->isfixed;
   1136 	if (c->isfloating)
   1137 		XRaiseWindow(dpy, c->win);
   1138 	attach(c);
   1139 	attachstack(c);
   1140 	XChangeProperty(dpy, root, netatom[NetClientList], XA_WINDOW, 32, PropModeAppend,
   1141 		(unsigned char *) &(c->win), 1);
   1142 	XMoveResizeWindow(dpy, c->win, c->x + 2 * sw, c->y, c->w, c->h); /* some windows require this */
   1143 	setclientstate(c, NormalState);
   1144 	if (c->mon == selmon)
   1145 		unfocus(selmon->sel, 0);
   1146 	c->mon->sel = c;
   1147 	arrange(c->mon);
   1148 	XMapWindow(dpy, c->win);
   1149 	if (term)
   1150 		swallow(term, c);
   1151 	focus(NULL);
   1152 }
   1153 
   1154 void
   1155 mappingnotify(XEvent *e)
   1156 {
   1157 	XMappingEvent *ev = &e->xmapping;
   1158 
   1159 	XRefreshKeyboardMapping(ev);
   1160 	if (ev->request == MappingKeyboard)
   1161 		grabkeys();
   1162 }
   1163 
   1164 void
   1165 maprequest(XEvent *e)
   1166 {
   1167 	static XWindowAttributes wa;
   1168 	XMapRequestEvent *ev = &e->xmaprequest;
   1169 
   1170 	if (!XGetWindowAttributes(dpy, ev->window, &wa))
   1171 		return;
   1172 	if (wa.override_redirect)
   1173 		return;
   1174 	if (!wintoclient(ev->window))
   1175 		manage(ev->window, &wa);
   1176 }
   1177 
   1178 void
   1179 monocle(Monitor *m)
   1180 {
   1181 	unsigned int n = 0;
   1182 	Client *c;
   1183 
   1184 	for (c = m->clients; c; c = c->next)
   1185 		if (ISVISIBLE(c))
   1186 			n++;
   1187 	if (n > 0) /* override layout symbol */
   1188 		snprintf(m->ltsymbol, sizeof m->ltsymbol, "[%d]", n);
   1189 	for (c = nexttiled(m->clients); c; c = nexttiled(c->next))
   1190 		resize(c, m->wx, m->wy, m->ww - 2 * c->bw, m->wh - 2 * c->bw, 0);
   1191 }
   1192 
   1193 void
   1194 motionnotify(XEvent *e)
   1195 {
   1196 	static Monitor *mon = NULL;
   1197 	Monitor *m;
   1198 	XMotionEvent *ev = &e->xmotion;
   1199 
   1200 	if (ev->window != root)
   1201 		return;
   1202 	if ((m = recttomon(ev->x_root, ev->y_root, 1, 1)) != mon && mon) {
   1203 		unfocus(selmon->sel, 1);
   1204 		selmon = m;
   1205 		focus(NULL);
   1206 	}
   1207 	mon = m;
   1208 }
   1209 
   1210 void
   1211 movemouse(const Arg *arg)
   1212 {
   1213 	int x, y, ocx, ocy, nx, ny;
   1214 	Client *c;
   1215 	Monitor *m;
   1216 	XEvent ev;
   1217 	Time lasttime = 0;
   1218 
   1219 	if (!(c = selmon->sel))
   1220 		return;
   1221 	if (c->isfullscreen) /* no support moving fullscreen windows by mouse */
   1222 		return;
   1223 	restack(selmon);
   1224 	ocx = c->x;
   1225 	ocy = c->y;
   1226 	if (XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
   1227 		None, cursor[CurMove]->cursor, CurrentTime) != GrabSuccess)
   1228 		return;
   1229 	if (!getrootptr(&x, &y))
   1230 		return;
   1231 	do {
   1232 		XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
   1233 		switch(ev.type) {
   1234 		case ConfigureRequest:
   1235 		case Expose:
   1236 		case MapRequest:
   1237 			handler[ev.type](&ev);
   1238 			break;
   1239 		case MotionNotify:
   1240 			if ((ev.xmotion.time - lasttime) <= (1000 / 60))
   1241 				continue;
   1242 			lasttime = ev.xmotion.time;
   1243 
   1244 			nx = ocx + (ev.xmotion.x - x);
   1245 			ny = ocy + (ev.xmotion.y - y);
   1246 			if (abs(selmon->wx - nx) < snap)
   1247 				nx = selmon->wx;
   1248 			else if (abs((selmon->wx + selmon->ww) - (nx + WIDTH(c))) < snap)
   1249 				nx = selmon->wx + selmon->ww - WIDTH(c);
   1250 			if (abs(selmon->wy - ny) < snap)
   1251 				ny = selmon->wy;
   1252 			else if (abs((selmon->wy + selmon->wh) - (ny + HEIGHT(c))) < snap)
   1253 				ny = selmon->wy + selmon->wh - HEIGHT(c);
   1254 			if (!c->isfloating && selmon->lt[selmon->sellt]->arrange
   1255 			&& (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
   1256 				togglefloating(NULL);
   1257 			if (!selmon->lt[selmon->sellt]->arrange || c->isfloating)
   1258 				resize(c, nx, ny, c->w, c->h, 1);
   1259 			break;
   1260 		}
   1261 	} while (ev.type != ButtonRelease);
   1262 	XUngrabPointer(dpy, CurrentTime);
   1263 	if ((m = recttomon(c->x, c->y, c->w, c->h)) != selmon) {
   1264 		sendmon(c, m);
   1265 		selmon = m;
   1266 		focus(NULL);
   1267 	}
   1268 }
   1269 
   1270 Client *
   1271 nexttiled(Client *c)
   1272 {
   1273 	for (; c && (c->isfloating || !ISVISIBLE(c)); c = c->next);
   1274 	return c;
   1275 }
   1276 
   1277 void
   1278 pop(Client *c)
   1279 {
   1280 	detach(c);
   1281 	attach(c);
   1282 	focus(c);
   1283 	arrange(c->mon);
   1284 }
   1285 
   1286 void
   1287 propertynotify(XEvent *e)
   1288 {
   1289 	Client *c;
   1290 	Window trans;
   1291 	XPropertyEvent *ev = &e->xproperty;
   1292 
   1293 	if ((ev->window == root) && (ev->atom == XA_WM_NAME))
   1294 		updatestatus();
   1295 	else if (ev->state == PropertyDelete)
   1296 		return; /* ignore */
   1297 	else if ((c = wintoclient(ev->window))) {
   1298 		switch(ev->atom) {
   1299 		default: break;
   1300 		case XA_WM_TRANSIENT_FOR:
   1301 			if (!c->isfloating && (XGetTransientForHint(dpy, c->win, &trans)) &&
   1302 				(c->isfloating = (wintoclient(trans)) != NULL))
   1303 				arrange(c->mon);
   1304 			break;
   1305 		case XA_WM_NORMAL_HINTS:
   1306 			updatesizehints(c);
   1307 			break;
   1308 		case XA_WM_HINTS:
   1309 			updatewmhints(c);
   1310 			drawbars();
   1311 			break;
   1312 		}
   1313 		if (ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
   1314 			updatetitle(c);
   1315 			if (c == c->mon->sel)
   1316 				drawbar(c->mon);
   1317 		}
   1318 		if (ev->atom == netatom[NetWMWindowType])
   1319 			updatewindowtype(c);
   1320 	}
   1321 }
   1322 
   1323 void
   1324 quit(const Arg *arg)
   1325 {
   1326 	running = 0;
   1327 }
   1328 
   1329 Monitor *
   1330 recttomon(int x, int y, int w, int h)
   1331 {
   1332 	Monitor *m, *r = selmon;
   1333 	int a, area = 0;
   1334 
   1335 	for (m = mons; m; m = m->next)
   1336 		if ((a = INTERSECT(x, y, w, h, m)) > area) {
   1337 			area = a;
   1338 			r = m;
   1339 		}
   1340 	return r;
   1341 }
   1342 
   1343 void
   1344 resize(Client *c, int x, int y, int w, int h, int interact)
   1345 {
   1346 	if (applysizehints(c, &x, &y, &w, &h, interact))
   1347 		resizeclient(c, x, y, w, h);
   1348 }
   1349 
   1350 void
   1351 resizeclient(Client *c, int x, int y, int w, int h)
   1352 {
   1353 	XWindowChanges wc;
   1354 
   1355 	c->oldx = c->x; c->x = wc.x = x;
   1356 	c->oldy = c->y; c->y = wc.y = y;
   1357 	c->oldw = c->w; c->w = wc.width = w;
   1358 	c->oldh = c->h; c->h = wc.height = h;
   1359 	wc.border_width = c->bw;
   1360 	XConfigureWindow(dpy, c->win, CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
   1361 	configure(c);
   1362 	XSync(dpy, False);
   1363 }
   1364 
   1365 void
   1366 resizemouse(const Arg *arg)
   1367 {
   1368 	int ocx, ocy, nw, nh;
   1369 	Client *c;
   1370 	Monitor *m;
   1371 	XEvent ev;
   1372 	Time lasttime = 0;
   1373 
   1374 	if (!(c = selmon->sel))
   1375 		return;
   1376 	if (c->isfullscreen) /* no support resizing fullscreen windows by mouse */
   1377 		return;
   1378 	restack(selmon);
   1379 	ocx = c->x;
   1380 	ocy = c->y;
   1381 	if (XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
   1382 		None, cursor[CurResize]->cursor, CurrentTime) != GrabSuccess)
   1383 		return;
   1384 	XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
   1385 	do {
   1386 		XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
   1387 		switch(ev.type) {
   1388 		case ConfigureRequest:
   1389 		case Expose:
   1390 		case MapRequest:
   1391 			handler[ev.type](&ev);
   1392 			break;
   1393 		case MotionNotify:
   1394 			if ((ev.xmotion.time - lasttime) <= (1000 / 60))
   1395 				continue;
   1396 			lasttime = ev.xmotion.time;
   1397 
   1398 			nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
   1399 			nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
   1400 			if (c->mon->wx + nw >= selmon->wx && c->mon->wx + nw <= selmon->wx + selmon->ww
   1401 			&& c->mon->wy + nh >= selmon->wy && c->mon->wy + nh <= selmon->wy + selmon->wh)
   1402 			{
   1403 				if (!c->isfloating && selmon->lt[selmon->sellt]->arrange
   1404 				&& (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
   1405 					togglefloating(NULL);
   1406 			}
   1407 			if (!selmon->lt[selmon->sellt]->arrange || c->isfloating)
   1408 				resize(c, c->x, c->y, nw, nh, 1);
   1409 			break;
   1410 		}
   1411 	} while (ev.type != ButtonRelease);
   1412 	XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
   1413 	XUngrabPointer(dpy, CurrentTime);
   1414 	while (XCheckMaskEvent(dpy, EnterWindowMask, &ev));
   1415 	if ((m = recttomon(c->x, c->y, c->w, c->h)) != selmon) {
   1416 		sendmon(c, m);
   1417 		selmon = m;
   1418 		focus(NULL);
   1419 	}
   1420 }
   1421 
   1422 void
   1423 restack(Monitor *m)
   1424 {
   1425 	Client *c;
   1426 	XEvent ev;
   1427 	XWindowChanges wc;
   1428 
   1429 	drawbar(m);
   1430 	if (!m->sel)
   1431 		return;
   1432 	if (m->sel->isfloating || !m->lt[m->sellt]->arrange)
   1433 		XRaiseWindow(dpy, m->sel->win);
   1434 	if (m->lt[m->sellt]->arrange) {
   1435 		wc.stack_mode = Below;
   1436 		wc.sibling = m->barwin;
   1437 		for (c = m->stack; c; c = c->snext)
   1438 			if (!c->isfloating && ISVISIBLE(c)) {
   1439 				XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
   1440 				wc.sibling = c->win;
   1441 			}
   1442 	}
   1443 	XSync(dpy, False);
   1444 	while (XCheckMaskEvent(dpy, EnterWindowMask, &ev));
   1445 }
   1446 
   1447 void
   1448 run(void)
   1449 {
   1450 	XEvent ev;
   1451 	/* main event loop */
   1452 	XSync(dpy, False);
   1453 	while (running && !XNextEvent(dpy, &ev))
   1454 		if (handler[ev.type])
   1455 			handler[ev.type](&ev); /* call handler */
   1456 }
   1457 
   1458 void
   1459 scan(void)
   1460 {
   1461 	unsigned int i, num;
   1462 	Window d1, d2, *wins = NULL;
   1463 	XWindowAttributes wa;
   1464 
   1465 	if (XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
   1466 		for (i = 0; i < num; i++) {
   1467 			if (!XGetWindowAttributes(dpy, wins[i], &wa)
   1468 			|| wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
   1469 				continue;
   1470 			if (wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
   1471 				manage(wins[i], &wa);
   1472 		}
   1473 		for (i = 0; i < num; i++) { /* now the transients */
   1474 			if (!XGetWindowAttributes(dpy, wins[i], &wa))
   1475 				continue;
   1476 			if (XGetTransientForHint(dpy, wins[i], &d1)
   1477 			&& (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
   1478 				manage(wins[i], &wa);
   1479 		}
   1480 		if (wins)
   1481 			XFree(wins);
   1482 	}
   1483 }
   1484 
   1485 void
   1486 sendmon(Client *c, Monitor *m)
   1487 {
   1488 	if (c->mon == m)
   1489 		return;
   1490 	unfocus(c, 1);
   1491 	detach(c);
   1492 	detachstack(c);
   1493 	c->mon = m;
   1494 	c->tags = m->tagset[m->seltags]; /* assign tags of target monitor */
   1495 	attach(c);
   1496 	attachstack(c);
   1497 	focus(NULL);
   1498 	arrange(NULL);
   1499 }
   1500 
   1501 void
   1502 setclientstate(Client *c, long state)
   1503 {
   1504 	long data[] = { state, None };
   1505 
   1506 	XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
   1507 		PropModeReplace, (unsigned char *)data, 2);
   1508 }
   1509 
   1510 int
   1511 sendevent(Client *c, Atom proto)
   1512 {
   1513 	int n;
   1514 	Atom *protocols;
   1515 	int exists = 0;
   1516 	XEvent ev;
   1517 
   1518 	if (XGetWMProtocols(dpy, c->win, &protocols, &n)) {
   1519 		while (!exists && n--)
   1520 			exists = protocols[n] == proto;
   1521 		XFree(protocols);
   1522 	}
   1523 	if (exists) {
   1524 		ev.type = ClientMessage;
   1525 		ev.xclient.window = c->win;
   1526 		ev.xclient.message_type = wmatom[WMProtocols];
   1527 		ev.xclient.format = 32;
   1528 		ev.xclient.data.l[0] = proto;
   1529 		ev.xclient.data.l[1] = CurrentTime;
   1530 		XSendEvent(dpy, c->win, False, NoEventMask, &ev);
   1531 	}
   1532 	return exists;
   1533 }
   1534 
   1535 void
   1536 setfocus(Client *c)
   1537 {
   1538 	if (!c->neverfocus) {
   1539 		XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
   1540 		XChangeProperty(dpy, root, netatom[NetActiveWindow],
   1541 			XA_WINDOW, 32, PropModeReplace,
   1542 			(unsigned char *) &(c->win), 1);
   1543 	}
   1544 	sendevent(c, wmatom[WMTakeFocus]);
   1545 }
   1546 
   1547 void
   1548 setfullscreen(Client *c, int fullscreen)
   1549 {
   1550 	if (fullscreen && !c->isfullscreen) {
   1551 		XChangeProperty(dpy, c->win, netatom[NetWMState], XA_ATOM, 32,
   1552 			PropModeReplace, (unsigned char*)&netatom[NetWMFullscreen], 1);
   1553 		c->isfullscreen = 1;
   1554 		c->oldstate = c->isfloating;
   1555 		c->oldbw = c->bw;
   1556 		c->bw = 0;
   1557 		c->isfloating = 1;
   1558 		resizeclient(c, c->mon->mx, c->mon->my, c->mon->mw, c->mon->mh);
   1559 		XRaiseWindow(dpy, c->win);
   1560 	} else if (!fullscreen && c->isfullscreen){
   1561 		XChangeProperty(dpy, c->win, netatom[NetWMState], XA_ATOM, 32,
   1562 			PropModeReplace, (unsigned char*)0, 0);
   1563 		c->isfullscreen = 0;
   1564 		c->isfloating = c->oldstate;
   1565 		c->bw = c->oldbw;
   1566 		c->x = c->oldx;
   1567 		c->y = c->oldy;
   1568 		c->w = c->oldw;
   1569 		c->h = c->oldh;
   1570 		resizeclient(c, c->x, c->y, c->w, c->h);
   1571 		arrange(c->mon);
   1572 	}
   1573 }
   1574 
   1575 void
   1576 setlayout(const Arg *arg)
   1577 {
   1578 	if (!arg || !arg->v || arg->v != selmon->lt[selmon->sellt])
   1579 		selmon->sellt ^= 1;
   1580 	if (arg && arg->v)
   1581 		selmon->lt[selmon->sellt] = (Layout *)arg->v;
   1582 	strncpy(selmon->ltsymbol, selmon->lt[selmon->sellt]->symbol, sizeof selmon->ltsymbol);
   1583 	if (selmon->sel)
   1584 		arrange(selmon);
   1585 	else
   1586 		drawbar(selmon);
   1587 }
   1588 
   1589 /* arg > 1.0 will set mfact absolutely */
   1590 void
   1591 setmfact(const Arg *arg)
   1592 {
   1593 	float f;
   1594 
   1595 	if (!arg || !selmon->lt[selmon->sellt]->arrange)
   1596 		return;
   1597 	f = arg->f < 1.0 ? arg->f + selmon->mfact : arg->f - 1.0;
   1598 	if (f < 0.05 || f > 0.95)
   1599 		return;
   1600 	selmon->mfact = f;
   1601 	arrange(selmon);
   1602 }
   1603 
   1604 void
   1605 setup(void)
   1606 {
   1607 	int i;
   1608 	XSetWindowAttributes wa;
   1609 	Atom utf8string;
   1610 
   1611 	/* clean up any zombies immediately */
   1612 	sigchld(0);
   1613 
   1614 	/* init screen */
   1615 	screen = DefaultScreen(dpy);
   1616 	sw = DisplayWidth(dpy, screen);
   1617 	sh = DisplayHeight(dpy, screen);
   1618 	root = RootWindow(dpy, screen);
   1619 	drw = drw_create(dpy, screen, root, sw, sh);
   1620 	if (!drw_fontset_create(drw, fonts, LENGTH(fonts)))
   1621 		die("no fonts could be loaded.");
   1622 	lrpad = drw->fonts->h;
   1623 	bh = drw->fonts->h + 2;
   1624 	updategeom();
   1625 	/* init atoms */
   1626 	utf8string = XInternAtom(dpy, "UTF8_STRING", False);
   1627 	wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
   1628 	wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
   1629 	wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
   1630 	wmatom[WMTakeFocus] = XInternAtom(dpy, "WM_TAKE_FOCUS", False);
   1631 	netatom[NetActiveWindow] = XInternAtom(dpy, "_NET_ACTIVE_WINDOW", False);
   1632 	netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
   1633 	netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
   1634 	netatom[NetWMState] = XInternAtom(dpy, "_NET_WM_STATE", False);
   1635 	netatom[NetWMCheck] = XInternAtom(dpy, "_NET_SUPPORTING_WM_CHECK", False);
   1636 	netatom[NetWMFullscreen] = XInternAtom(dpy, "_NET_WM_STATE_FULLSCREEN", False);
   1637 	netatom[NetWMWindowType] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE", False);
   1638 	netatom[NetWMWindowTypeDialog] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE_DIALOG", False);
   1639 	netatom[NetClientList] = XInternAtom(dpy, "_NET_CLIENT_LIST", False);
   1640 	/* init cursors */
   1641 	cursor[CurNormal] = drw_cur_create(drw, XC_left_ptr);
   1642 	cursor[CurResize] = drw_cur_create(drw, XC_sizing);
   1643 	cursor[CurMove] = drw_cur_create(drw, XC_fleur);
   1644 	/* init appearance */
   1645 	scheme = ecalloc(LENGTH(colors), sizeof(Clr *));
   1646 	for (i = 0; i < LENGTH(colors); i++)
   1647 		scheme[i] = drw_scm_create(drw, colors[i], 3);
   1648 	/* init bars */
   1649 	updatebars();
   1650 	updatestatus();
   1651 	/* supporting window for NetWMCheck */
   1652 	wmcheckwin = XCreateSimpleWindow(dpy, root, 0, 0, 1, 1, 0, 0, 0);
   1653 	XChangeProperty(dpy, wmcheckwin, netatom[NetWMCheck], XA_WINDOW, 32,
   1654 		PropModeReplace, (unsigned char *) &wmcheckwin, 1);
   1655 	XChangeProperty(dpy, wmcheckwin, netatom[NetWMName], utf8string, 8,
   1656 		PropModeReplace, (unsigned char *) "dwm", 3);
   1657 	XChangeProperty(dpy, root, netatom[NetWMCheck], XA_WINDOW, 32,
   1658 		PropModeReplace, (unsigned char *) &wmcheckwin, 1);
   1659 	/* EWMH support per view */
   1660 	XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
   1661 		PropModeReplace, (unsigned char *) netatom, NetLast);
   1662 	XDeleteProperty(dpy, root, netatom[NetClientList]);
   1663 	/* select events */
   1664 	wa.cursor = cursor[CurNormal]->cursor;
   1665 	wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
   1666 		|ButtonPressMask|PointerMotionMask|EnterWindowMask
   1667 		|LeaveWindowMask|StructureNotifyMask|PropertyChangeMask;
   1668 	XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
   1669 	XSelectInput(dpy, root, wa.event_mask);
   1670 	grabkeys();
   1671 	focus(NULL);
   1672 }
   1673 
   1674 
   1675 void
   1676 seturgent(Client *c, int urg)
   1677 {
   1678 	XWMHints *wmh;
   1679 
   1680 	c->isurgent = urg;
   1681 	if (!(wmh = XGetWMHints(dpy, c->win)))
   1682 		return;
   1683 	wmh->flags = urg ? (wmh->flags | XUrgencyHint) : (wmh->flags & ~XUrgencyHint);
   1684 	XSetWMHints(dpy, c->win, wmh);
   1685 	XFree(wmh);
   1686 }
   1687 
   1688 void
   1689 showhide(Client *c)
   1690 {
   1691 	if (!c)
   1692 		return;
   1693 	if (ISVISIBLE(c)) {
   1694 		/* show clients top down */
   1695 		XMoveWindow(dpy, c->win, c->x, c->y);
   1696 		if ((!c->mon->lt[c->mon->sellt]->arrange || c->isfloating) && !c->isfullscreen)
   1697 			resize(c, c->x, c->y, c->w, c->h, 0);
   1698 		showhide(c->snext);
   1699 	} else {
   1700 		/* hide clients bottom up */
   1701 		showhide(c->snext);
   1702 		XMoveWindow(dpy, c->win, WIDTH(c) * -2, c->y);
   1703 	}
   1704 }
   1705 
   1706 void
   1707 sigchld(int unused)
   1708 {
   1709 	if (signal(SIGCHLD, sigchld) == SIG_ERR)
   1710 		die("can't install SIGCHLD handler:");
   1711 	while (0 < waitpid(-1, NULL, WNOHANG));
   1712 }
   1713 
   1714 void
   1715 spawn(const Arg *arg)
   1716 {
   1717 	if (fork() == 0) {
   1718 		if (dpy)
   1719 			close(ConnectionNumber(dpy));
   1720 		setsid();
   1721 		execvp(((char **)arg->v)[0], (char **)arg->v);
   1722 		fprintf(stderr, "dwm: execvp %s", ((char **)arg->v)[0]);
   1723 		perror(" failed");
   1724 		exit(EXIT_SUCCESS);
   1725 	}
   1726 }
   1727 
   1728 void
   1729 tag(const Arg *arg)
   1730 {
   1731 	if (selmon->sel && arg->ui & TAGMASK) {
   1732 		selmon->sel->tags = arg->ui & TAGMASK;
   1733 		focus(NULL);
   1734 		arrange(selmon);
   1735 	}
   1736 }
   1737 
   1738 void
   1739 tagmon(const Arg *arg)
   1740 {
   1741 	if (!selmon->sel || !mons->next)
   1742 		return;
   1743 	sendmon(selmon->sel, dirtomon(arg->i));
   1744 }
   1745 
   1746 void
   1747 tile(Monitor *m)
   1748 {
   1749 	unsigned int i, n, h, mw, my, ty;
   1750 	Client *c;
   1751 
   1752 	for (n = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), n++);
   1753 	if (n == 0)
   1754 		return;
   1755 
   1756 	if (n > m->nmaster)
   1757 		mw = m->nmaster ? m->ww * m->mfact : 0;
   1758 	else
   1759 		mw = m->ww;
   1760 	for (i = my = ty = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), i++)
   1761 		if (i < m->nmaster) {
   1762 			h = (m->wh - my) / (MIN(n, m->nmaster) - i);
   1763 			resize(c, m->wx, m->wy + my, mw - (2*c->bw), h - (2*c->bw), 0);
   1764 			if (my + HEIGHT(c) < m->wh)
   1765 				my += HEIGHT(c);
   1766 		} else {
   1767 			h = (m->wh - ty) / (n - i);
   1768 			resize(c, m->wx + mw, m->wy + ty, m->ww - mw - (2*c->bw), h - (2*c->bw), 0);
   1769 			if (ty + HEIGHT(c) < m->wh)
   1770 				ty += HEIGHT(c);
   1771 		}
   1772 }
   1773 
   1774 void
   1775 togglebar(const Arg *arg)
   1776 {
   1777 	selmon->showbar = !selmon->showbar;
   1778 	updatebarpos(selmon);
   1779 	XMoveResizeWindow(dpy, selmon->barwin, selmon->wx, selmon->by, selmon->ww, bh);
   1780 	arrange(selmon);
   1781 }
   1782 
   1783 void
   1784 togglefloating(const Arg *arg)
   1785 {
   1786 	if (!selmon->sel)
   1787 		return;
   1788 	if (selmon->sel->isfullscreen) /* no support for fullscreen windows */
   1789 		return;
   1790 	selmon->sel->isfloating = !selmon->sel->isfloating || selmon->sel->isfixed;
   1791 	if (selmon->sel->isfloating)
   1792 		resize(selmon->sel, selmon->sel->x, selmon->sel->y,
   1793 			selmon->sel->w, selmon->sel->h, 0);
   1794 	arrange(selmon);
   1795 }
   1796 
   1797 void
   1798 toggletag(const Arg *arg)
   1799 {
   1800 	unsigned int newtags;
   1801 
   1802 	if (!selmon->sel)
   1803 		return;
   1804 	newtags = selmon->sel->tags ^ (arg->ui & TAGMASK);
   1805 	if (newtags) {
   1806 		selmon->sel->tags = newtags;
   1807 		focus(NULL);
   1808 		arrange(selmon);
   1809 	}
   1810 }
   1811 
   1812 void
   1813 toggleview(const Arg *arg)
   1814 {
   1815 	unsigned int newtagset = selmon->tagset[selmon->seltags] ^ (arg->ui & TAGMASK);
   1816 
   1817 	if (newtagset) {
   1818 		selmon->tagset[selmon->seltags] = newtagset;
   1819 		focus(NULL);
   1820 		arrange(selmon);
   1821 	}
   1822 }
   1823 
   1824 void
   1825 unfocus(Client *c, int setfocus)
   1826 {
   1827 	if (!c)
   1828 		return;
   1829 	grabbuttons(c, 0);
   1830 	XSetWindowBorder(dpy, c->win, scheme[SchemeNorm][ColBorder].pixel);
   1831 	if (setfocus) {
   1832 		XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
   1833 		XDeleteProperty(dpy, root, netatom[NetActiveWindow]);
   1834 	}
   1835 }
   1836 
   1837 void
   1838 unmanage(Client *c, int destroyed)
   1839 {
   1840 	Monitor *m = c->mon;
   1841 	XWindowChanges wc;
   1842 
   1843 	if (c->swallowing) {
   1844 		unswallow(c);
   1845 		return;
   1846 	}
   1847 
   1848 	Client *s = swallowingclient(c->win);
   1849 	if (s) {
   1850 		free(s->swallowing);
   1851 		s->swallowing = NULL;
   1852 		arrange(m);
   1853 		focus(NULL);
   1854 		return;
   1855 	}
   1856 
   1857 	detach(c);
   1858 	detachstack(c);
   1859 	if (!destroyed) {
   1860 		wc.border_width = c->oldbw;
   1861 		XGrabServer(dpy); /* avoid race conditions */
   1862 		XSetErrorHandler(xerrordummy);
   1863 		XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
   1864 		XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
   1865 		setclientstate(c, WithdrawnState);
   1866 		XSync(dpy, False);
   1867 		XSetErrorHandler(xerror);
   1868 		XUngrabServer(dpy);
   1869 	}
   1870 	free(c);
   1871 
   1872 	if (!s) {
   1873 		arrange(m);
   1874 		focus(NULL);
   1875 		updateclientlist();
   1876 	}
   1877 }
   1878 
   1879 void
   1880 unmapnotify(XEvent *e)
   1881 {
   1882 	Client *c;
   1883 	XUnmapEvent *ev = &e->xunmap;
   1884 
   1885 	if ((c = wintoclient(ev->window))) {
   1886 		if (ev->send_event)
   1887 			setclientstate(c, WithdrawnState);
   1888 		else
   1889 			unmanage(c, 0);
   1890 	}
   1891 }
   1892 
   1893 void
   1894 updatebars(void)
   1895 {
   1896 	Monitor *m;
   1897 	XSetWindowAttributes wa = {
   1898 		.override_redirect = True,
   1899 		.background_pixmap = ParentRelative,
   1900 		.event_mask = ButtonPressMask|ExposureMask
   1901 	};
   1902 	XClassHint ch = {"dwm", "dwm"};
   1903 	for (m = mons; m; m = m->next) {
   1904 		if (m->barwin)
   1905 			continue;
   1906 		m->barwin = XCreateWindow(dpy, root, m->wx, m->by, m->ww, bh, 0, DefaultDepth(dpy, screen),
   1907 				CopyFromParent, DefaultVisual(dpy, screen),
   1908 				CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
   1909 		XDefineCursor(dpy, m->barwin, cursor[CurNormal]->cursor);
   1910 		XMapRaised(dpy, m->barwin);
   1911 		XSetClassHint(dpy, m->barwin, &ch);
   1912 	}
   1913 }
   1914 
   1915 void
   1916 updatebarpos(Monitor *m)
   1917 {
   1918 	m->wy = m->my;
   1919 	m->wh = m->mh;
   1920 	if (m->showbar) {
   1921 		m->wh -= bh;
   1922 		m->by = m->topbar ? m->wy : m->wy + m->wh;
   1923 		m->wy = m->topbar ? m->wy + bh : m->wy;
   1924 	} else
   1925 		m->by = -bh;
   1926 }
   1927 
   1928 void
   1929 updateclientlist()
   1930 {
   1931 	Client *c;
   1932 	Monitor *m;
   1933 
   1934 	XDeleteProperty(dpy, root, netatom[NetClientList]);
   1935 	for (m = mons; m; m = m->next)
   1936 		for (c = m->clients; c; c = c->next)
   1937 			XChangeProperty(dpy, root, netatom[NetClientList],
   1938 				XA_WINDOW, 32, PropModeAppend,
   1939 				(unsigned char *) &(c->win), 1);
   1940 }
   1941 
   1942 int
   1943 updategeom(void)
   1944 {
   1945 	int dirty = 0;
   1946 
   1947 #ifdef XINERAMA
   1948 	if (XineramaIsActive(dpy)) {
   1949 		int i, j, n, nn;
   1950 		Client *c;
   1951 		Monitor *m;
   1952 		XineramaScreenInfo *info = XineramaQueryScreens(dpy, &nn);
   1953 		XineramaScreenInfo *unique = NULL;
   1954 
   1955 		for (n = 0, m = mons; m; m = m->next, n++);
   1956 		/* only consider unique geometries as separate screens */
   1957 		unique = ecalloc(nn, sizeof(XineramaScreenInfo));
   1958 		for (i = 0, j = 0; i < nn; i++)
   1959 			if (isuniquegeom(unique, j, &info[i]))
   1960 				memcpy(&unique[j++], &info[i], sizeof(XineramaScreenInfo));
   1961 		XFree(info);
   1962 		nn = j;
   1963 		if (n <= nn) { /* new monitors available */
   1964 			for (i = 0; i < (nn - n); i++) {
   1965 				for (m = mons; m && m->next; m = m->next);
   1966 				if (m)
   1967 					m->next = createmon();
   1968 				else
   1969 					mons = createmon();
   1970 			}
   1971 			for (i = 0, m = mons; i < nn && m; m = m->next, i++)
   1972 				if (i >= n
   1973 				|| unique[i].x_org != m->mx || unique[i].y_org != m->my
   1974 				|| unique[i].width != m->mw || unique[i].height != m->mh)
   1975 				{
   1976 					dirty = 1;
   1977 					m->num = i;
   1978 					m->mx = m->wx = unique[i].x_org;
   1979 					m->my = m->wy = unique[i].y_org;
   1980 					m->mw = m->ww = unique[i].width;
   1981 					m->mh = m->wh = unique[i].height;
   1982 					updatebarpos(m);
   1983 				}
   1984 		} else { /* less monitors available nn < n */
   1985 			for (i = nn; i < n; i++) {
   1986 				for (m = mons; m && m->next; m = m->next);
   1987 				while ((c = m->clients)) {
   1988 					dirty = 1;
   1989 					m->clients = c->next;
   1990 					detachstack(c);
   1991 					c->mon = mons;
   1992 					attach(c);
   1993 					attachstack(c);
   1994 				}
   1995 				if (m == selmon)
   1996 					selmon = mons;
   1997 				cleanupmon(m);
   1998 			}
   1999 		}
   2000 		free(unique);
   2001 	} else
   2002 #endif /* XINERAMA */
   2003 	{ /* default monitor setup */
   2004 		if (!mons)
   2005 			mons = createmon();
   2006 		if (mons->mw != sw || mons->mh != sh) {
   2007 			dirty = 1;
   2008 			mons->mw = mons->ww = sw;
   2009 			mons->mh = mons->wh = sh;
   2010 			updatebarpos(mons);
   2011 		}
   2012 	}
   2013 	if (dirty) {
   2014 		selmon = mons;
   2015 		selmon = wintomon(root);
   2016 	}
   2017 	return dirty;
   2018 }
   2019 
   2020 void
   2021 updatenumlockmask(void)
   2022 {
   2023 	unsigned int i, j;
   2024 	XModifierKeymap *modmap;
   2025 
   2026 	numlockmask = 0;
   2027 	modmap = XGetModifierMapping(dpy);
   2028 	for (i = 0; i < 8; i++)
   2029 		for (j = 0; j < modmap->max_keypermod; j++)
   2030 			if (modmap->modifiermap[i * modmap->max_keypermod + j]
   2031 				== XKeysymToKeycode(dpy, XK_Num_Lock))
   2032 				numlockmask = (1 << i);
   2033 	XFreeModifiermap(modmap);
   2034 }
   2035 
   2036 void
   2037 updatesizehints(Client *c)
   2038 {
   2039 	long msize;
   2040 	XSizeHints size;
   2041 
   2042 	if (!XGetWMNormalHints(dpy, c->win, &size, &msize))
   2043 		/* size is uninitialized, ensure that size.flags aren't used */
   2044 		size.flags = PSize;
   2045 	if (size.flags & PBaseSize) {
   2046 		c->basew = size.base_width;
   2047 		c->baseh = size.base_height;
   2048 	} else if (size.flags & PMinSize) {
   2049 		c->basew = size.min_width;
   2050 		c->baseh = size.min_height;
   2051 	} else
   2052 		c->basew = c->baseh = 0;
   2053 	if (size.flags & PResizeInc) {
   2054 		c->incw = size.width_inc;
   2055 		c->inch = size.height_inc;
   2056 	} else
   2057 		c->incw = c->inch = 0;
   2058 	if (size.flags & PMaxSize) {
   2059 		c->maxw = size.max_width;
   2060 		c->maxh = size.max_height;
   2061 	} else
   2062 		c->maxw = c->maxh = 0;
   2063 	if (size.flags & PMinSize) {
   2064 		c->minw = size.min_width;
   2065 		c->minh = size.min_height;
   2066 	} else if (size.flags & PBaseSize) {
   2067 		c->minw = size.base_width;
   2068 		c->minh = size.base_height;
   2069 	} else
   2070 		c->minw = c->minh = 0;
   2071 	if (size.flags & PAspect) {
   2072 		c->mina = (float)size.min_aspect.y / size.min_aspect.x;
   2073 		c->maxa = (float)size.max_aspect.x / size.max_aspect.y;
   2074 	} else
   2075 		c->maxa = c->mina = 0.0;
   2076 	c->isfixed = (c->maxw && c->maxh && c->maxw == c->minw && c->maxh == c->minh);
   2077 }
   2078 
   2079 void
   2080 updatestatus(void)
   2081 {
   2082 	if (!gettextprop(root, XA_WM_NAME, stext, sizeof(stext)))
   2083 		strcpy(stext, "dwm-"VERSION);
   2084 	drawbar(selmon);
   2085 }
   2086 
   2087 void
   2088 updatetitle(Client *c)
   2089 {
   2090 	if (!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
   2091 		gettextprop(c->win, XA_WM_NAME, c->name, sizeof c->name);
   2092 	if (c->name[0] == '\0') /* hack to mark broken clients */
   2093 		strcpy(c->name, broken);
   2094 }
   2095 
   2096 void
   2097 updatewindowtype(Client *c)
   2098 {
   2099 	Atom state = getatomprop(c, netatom[NetWMState]);
   2100 	Atom wtype = getatomprop(c, netatom[NetWMWindowType]);
   2101 
   2102 	if (state == netatom[NetWMFullscreen])
   2103 		setfullscreen(c, 1);
   2104 	if (wtype == netatom[NetWMWindowTypeDialog])
   2105 		c->isfloating = 1;
   2106 }
   2107 
   2108 void
   2109 updatewmhints(Client *c)
   2110 {
   2111 	XWMHints *wmh;
   2112 
   2113 	if ((wmh = XGetWMHints(dpy, c->win))) {
   2114 		if (c == selmon->sel && wmh->flags & XUrgencyHint) {
   2115 			wmh->flags &= ~XUrgencyHint;
   2116 			XSetWMHints(dpy, c->win, wmh);
   2117 		} else
   2118 			c->isurgent = (wmh->flags & XUrgencyHint) ? 1 : 0;
   2119 		if (wmh->flags & InputHint)
   2120 			c->neverfocus = !wmh->input;
   2121 		else
   2122 			c->neverfocus = 0;
   2123 		XFree(wmh);
   2124 	}
   2125 }
   2126 
   2127 void
   2128 view(const Arg *arg)
   2129 {
   2130 	if ((arg->ui & TAGMASK) == selmon->tagset[selmon->seltags])
   2131 		return;
   2132 	selmon->seltags ^= 1; /* toggle sel tagset */
   2133 	if (arg->ui & TAGMASK)
   2134 		selmon->tagset[selmon->seltags] = arg->ui & TAGMASK;
   2135 	focus(NULL);
   2136 	arrange(selmon);
   2137 }
   2138 
   2139 pid_t
   2140 winpid(Window w)
   2141 {
   2142 
   2143 	pid_t result = 0;
   2144 
   2145 #ifdef __linux__
   2146 	xcb_res_client_id_spec_t spec = {0};
   2147 	spec.client = w;
   2148 	spec.mask = XCB_RES_CLIENT_ID_MASK_LOCAL_CLIENT_PID;
   2149 
   2150 	xcb_generic_error_t *e = NULL;
   2151 	xcb_res_query_client_ids_cookie_t c = xcb_res_query_client_ids(xcon, 1, &spec);
   2152 	xcb_res_query_client_ids_reply_t *r = xcb_res_query_client_ids_reply(xcon, c, &e);
   2153 
   2154 	if (!r)
   2155 		return (pid_t)0;
   2156 
   2157 	xcb_res_client_id_value_iterator_t i = xcb_res_query_client_ids_ids_iterator(r);
   2158 	for (; i.rem; xcb_res_client_id_value_next(&i)) {
   2159 		spec = i.data->spec;
   2160 		if (spec.mask & XCB_RES_CLIENT_ID_MASK_LOCAL_CLIENT_PID) {
   2161 			uint32_t *t = xcb_res_client_id_value_value(i.data);
   2162 			result = *t;
   2163 			break;
   2164 		}
   2165 	}
   2166 
   2167 	free(r);
   2168 
   2169 	if (result == (pid_t)-1)
   2170 		result = 0;
   2171 
   2172 #endif /* __linux__ */
   2173 
   2174 #ifdef __OpenBSD__
   2175         Atom type;
   2176         int format;
   2177         unsigned long len, bytes;
   2178         unsigned char *prop;
   2179         pid_t ret;
   2180 
   2181         if (XGetWindowProperty(dpy, w, XInternAtom(dpy, "_NET_WM_PID", 0), 0, 1, False, AnyPropertyType, &type, &format, &len, &bytes, &prop) != Success || !prop)
   2182                return 0;
   2183 
   2184         ret = *(pid_t*)prop;
   2185         XFree(prop);
   2186         result = ret;
   2187 
   2188 #endif /* __OpenBSD__ */
   2189 	return result;
   2190 }
   2191 
   2192 pid_t
   2193 getparentprocess(pid_t p)
   2194 {
   2195 	unsigned int v = 0;
   2196 
   2197 #ifdef __linux__
   2198 	FILE *f;
   2199 	char buf[256];
   2200 	snprintf(buf, sizeof(buf) - 1, "/proc/%u/stat", (unsigned)p);
   2201 
   2202 	if (!(f = fopen(buf, "r")))
   2203 		return 0;
   2204 
   2205 	fscanf(f, "%*u %*s %*c %u", &v);
   2206 	fclose(f);
   2207 #endif /* __linux__*/
   2208 
   2209 #ifdef __OpenBSD__
   2210 	int n;
   2211 	kvm_t *kd;
   2212 	struct kinfo_proc *kp;
   2213 
   2214 	kd = kvm_openfiles(NULL, NULL, NULL, KVM_NO_FILES, NULL);
   2215 	if (!kd)
   2216 		return 0;
   2217 
   2218 	kp = kvm_getprocs(kd, KERN_PROC_PID, p, sizeof(*kp), &n);
   2219 	v = kp->p_ppid;
   2220 #endif /* __OpenBSD__ */
   2221 
   2222 	return (pid_t)v;
   2223 }
   2224 
   2225 int
   2226 isdescprocess(pid_t p, pid_t c)
   2227 {
   2228 	while (p != c && c != 0)
   2229 		c = getparentprocess(c);
   2230 
   2231 	return (int)c;
   2232 }
   2233 
   2234 Client *
   2235 termforwin(const Client *w)
   2236 {
   2237 	Client *c;
   2238 	Monitor *m;
   2239 
   2240 	if (!w->pid || w->isterminal)
   2241 		return NULL;
   2242 
   2243 	for (m = mons; m; m = m->next) {
   2244 		for (c = m->clients; c; c = c->next) {
   2245 			if (c->isterminal && !c->swallowing && c->pid && isdescprocess(c->pid, w->pid))
   2246 				return c;
   2247 		}
   2248 	}
   2249 
   2250 	return NULL;
   2251 }
   2252 
   2253 Client *
   2254 swallowingclient(Window w)
   2255 {
   2256 	Client *c;
   2257 	Monitor *m;
   2258 
   2259 	for (m = mons; m; m = m->next) {
   2260 		for (c = m->clients; c; c = c->next) {
   2261 			if (c->swallowing && c->swallowing->win == w)
   2262 				return c;
   2263 		}
   2264 	}
   2265 
   2266 	return NULL;
   2267 }
   2268 
   2269 Client *
   2270 wintoclient(Window w)
   2271 {
   2272 	Client *c;
   2273 	Monitor *m;
   2274 
   2275 	for (m = mons; m; m = m->next)
   2276 		for (c = m->clients; c; c = c->next)
   2277 			if (c->win == w)
   2278 				return c;
   2279 	return NULL;
   2280 }
   2281 
   2282 Monitor *
   2283 wintomon(Window w)
   2284 {
   2285 	int x, y;
   2286 	Client *c;
   2287 	Monitor *m;
   2288 
   2289 	if (w == root && getrootptr(&x, &y))
   2290 		return recttomon(x, y, 1, 1);
   2291 	for (m = mons; m; m = m->next)
   2292 		if (w == m->barwin)
   2293 			return m;
   2294 	if ((c = wintoclient(w)))
   2295 		return c->mon;
   2296 	return selmon;
   2297 }
   2298 
   2299 /* There's no way to check accesses to destroyed windows, thus those cases are
   2300  * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
   2301  * default error handler, which may call exit. */
   2302 int
   2303 xerror(Display *dpy, XErrorEvent *ee)
   2304 {
   2305 	if (ee->error_code == BadWindow
   2306 	|| (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
   2307 	|| (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
   2308 	|| (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
   2309 	|| (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
   2310 	|| (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
   2311 	|| (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
   2312 	|| (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
   2313 	|| (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
   2314 		return 0;
   2315 	fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
   2316 		ee->request_code, ee->error_code);
   2317 	return xerrorxlib(dpy, ee); /* may call exit */
   2318 }
   2319 
   2320 int
   2321 xerrordummy(Display *dpy, XErrorEvent *ee)
   2322 {
   2323 	return 0;
   2324 }
   2325 
   2326 /* Startup Error handler to check if another window manager
   2327  * is already running. */
   2328 int
   2329 xerrorstart(Display *dpy, XErrorEvent *ee)
   2330 {
   2331 	die("dwm: another window manager is already running");
   2332 	return -1;
   2333 }
   2334 
   2335 void
   2336 zoom(const Arg *arg)
   2337 {
   2338 	Client *c = selmon->sel;
   2339 
   2340 	if (!selmon->lt[selmon->sellt]->arrange
   2341 	|| (selmon->sel && selmon->sel->isfloating))
   2342 		return;
   2343 	if (c == nexttiled(selmon->clients))
   2344 		if (!c || !(c = nexttiled(c->next)))
   2345 			return;
   2346 	pop(c);
   2347 }
   2348 
   2349 int
   2350 main(int argc, char *argv[])
   2351 {
   2352 	if (argc == 2 && !strcmp("-v", argv[1]))
   2353 		die("dwm-"VERSION);
   2354 	else if (argc != 1)
   2355 		die("usage: dwm [-v]");
   2356 	if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
   2357 		fputs("warning: no locale support\n", stderr);
   2358 	if (!(dpy = XOpenDisplay(NULL)))
   2359 		die("dwm: cannot open display");
   2360 	if (!(xcon = XGetXCBConnection(dpy)))
   2361 		die("dwm: cannot get xcb connection\n");
   2362 	checkotherwm();
   2363 	setup();
   2364 #ifdef __OpenBSD__
   2365 	if (pledge("stdio rpath proc exec ps", NULL) == -1)
   2366 		die("pledge");
   2367 #endif /* __OpenBSD__ */
   2368 	scan();
   2369 	run();
   2370 	cleanup();
   2371 	XCloseDisplay(dpy);
   2372 	return EXIT_SUCCESS;
   2373 }