dwm

dynamic window manager
git clone git://git.yotsev.xyz/dwm.git
Log | Files | Refs | README | LICENSE

dwm.c (57345B)


      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, SchemeStatus, SchemeTagsSel, SchemeTagsNorm, SchemeInfoSel, SchemeInfoNorm }; /* 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[SchemeStatus]);
    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 ? SchemeTagsSel : SchemeTagsNorm]);
    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[SchemeTagsNorm]);
    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 ? SchemeInfoSel : SchemeInfoNorm]);
    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[SchemeInfoNorm]);
    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)
    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 	c->x = c->mon->mx + (c->mon->mw - WIDTH(c)) / 2;
   1133 	c->y = c->mon->my + (c->mon->mh - HEIGHT(c)) / 2;
   1134 	XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
   1135 	grabbuttons(c, 0);
   1136 	if (!c->isfloating)
   1137 		c->isfloating = c->oldstate = trans != None || c->isfixed;
   1138 	if (c->isfloating)
   1139 		XRaiseWindow(dpy, c->win);
   1140 	attach(c);
   1141 	attachstack(c);
   1142 	XChangeProperty(dpy, root, netatom[NetClientList], XA_WINDOW, 32, PropModeAppend,
   1143 		(unsigned char *) &(c->win), 1);
   1144 	XMoveResizeWindow(dpy, c->win, c->x + 2 * sw, c->y, c->w, c->h); /* some windows require this */
   1145 	setclientstate(c, NormalState);
   1146 	if (c->mon == selmon)
   1147 		unfocus(selmon->sel, 0);
   1148 	c->mon->sel = c;
   1149 	arrange(c->mon);
   1150 	XMapWindow(dpy, c->win);
   1151 	if (term)
   1152 		swallow(term, c);
   1153 	focus(NULL);
   1154 }
   1155 
   1156 void
   1157 mappingnotify(XEvent *e)
   1158 {
   1159 	XMappingEvent *ev = &e->xmapping;
   1160 
   1161 	XRefreshKeyboardMapping(ev);
   1162 	if (ev->request == MappingKeyboard)
   1163 		grabkeys();
   1164 }
   1165 
   1166 void
   1167 maprequest(XEvent *e)
   1168 {
   1169 	static XWindowAttributes wa;
   1170 	XMapRequestEvent *ev = &e->xmaprequest;
   1171 
   1172 	if (!XGetWindowAttributes(dpy, ev->window, &wa))
   1173 		return;
   1174 	if (wa.override_redirect)
   1175 		return;
   1176 	if (!wintoclient(ev->window))
   1177 		manage(ev->window, &wa);
   1178 }
   1179 
   1180 void
   1181 monocle(Monitor *m)
   1182 {
   1183 	unsigned int n = 0;
   1184 	Client *c;
   1185 
   1186 	for (c = m->clients; c; c = c->next)
   1187 		if (ISVISIBLE(c))
   1188 			n++;
   1189 	if (n > 0) /* override layout symbol */
   1190 		snprintf(m->ltsymbol, sizeof m->ltsymbol, "[%d]", n);
   1191 	for (c = nexttiled(m->clients); c; c = nexttiled(c->next))
   1192 		resize(c, m->wx, m->wy, m->ww - 2 * c->bw, m->wh - 2 * c->bw, 0);
   1193 }
   1194 
   1195 void
   1196 motionnotify(XEvent *e)
   1197 {
   1198 	static Monitor *mon = NULL;
   1199 	Monitor *m;
   1200 	XMotionEvent *ev = &e->xmotion;
   1201 
   1202 	if (ev->window != root)
   1203 		return;
   1204 	if ((m = recttomon(ev->x_root, ev->y_root, 1, 1)) != mon && mon) {
   1205 		unfocus(selmon->sel, 1);
   1206 		selmon = m;
   1207 		focus(NULL);
   1208 	}
   1209 	mon = m;
   1210 }
   1211 
   1212 void
   1213 movemouse(const Arg *arg)
   1214 {
   1215 	int x, y, ocx, ocy, nx, ny;
   1216 	Client *c;
   1217 	Monitor *m;
   1218 	XEvent ev;
   1219 	Time lasttime = 0;
   1220 
   1221 	if (!(c = selmon->sel))
   1222 		return;
   1223 	if (c->isfullscreen) /* no support moving fullscreen windows by mouse */
   1224 		return;
   1225 	restack(selmon);
   1226 	ocx = c->x;
   1227 	ocy = c->y;
   1228 	if (XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
   1229 		None, cursor[CurMove]->cursor, CurrentTime) != GrabSuccess)
   1230 		return;
   1231 	if (!getrootptr(&x, &y))
   1232 		return;
   1233 	do {
   1234 		XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
   1235 		switch(ev.type) {
   1236 		case ConfigureRequest:
   1237 		case Expose:
   1238 		case MapRequest:
   1239 			handler[ev.type](&ev);
   1240 			break;
   1241 		case MotionNotify:
   1242 			if ((ev.xmotion.time - lasttime) <= (1000 / 60))
   1243 				continue;
   1244 			lasttime = ev.xmotion.time;
   1245 
   1246 			nx = ocx + (ev.xmotion.x - x);
   1247 			ny = ocy + (ev.xmotion.y - y);
   1248 			if (abs(selmon->wx - nx) < snap)
   1249 				nx = selmon->wx;
   1250 			else if (abs((selmon->wx + selmon->ww) - (nx + WIDTH(c))) < snap)
   1251 				nx = selmon->wx + selmon->ww - WIDTH(c);
   1252 			if (abs(selmon->wy - ny) < snap)
   1253 				ny = selmon->wy;
   1254 			else if (abs((selmon->wy + selmon->wh) - (ny + HEIGHT(c))) < snap)
   1255 				ny = selmon->wy + selmon->wh - HEIGHT(c);
   1256 			if (!c->isfloating && selmon->lt[selmon->sellt]->arrange
   1257 			&& (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
   1258 				togglefloating(NULL);
   1259 			if (!selmon->lt[selmon->sellt]->arrange || c->isfloating)
   1260 				resize(c, nx, ny, c->w, c->h, 1);
   1261 			break;
   1262 		}
   1263 	} while (ev.type != ButtonRelease);
   1264 	XUngrabPointer(dpy, CurrentTime);
   1265 	if ((m = recttomon(c->x, c->y, c->w, c->h)) != selmon) {
   1266 		sendmon(c, m);
   1267 		selmon = m;
   1268 		focus(NULL);
   1269 	}
   1270 }
   1271 
   1272 Client *
   1273 nexttiled(Client *c)
   1274 {
   1275 	for (; c && (c->isfloating || !ISVISIBLE(c)); c = c->next);
   1276 	return c;
   1277 }
   1278 
   1279 void
   1280 pop(Client *c)
   1281 {
   1282 	detach(c);
   1283 	attach(c);
   1284 	focus(c);
   1285 	arrange(c->mon);
   1286 }
   1287 
   1288 void
   1289 propertynotify(XEvent *e)
   1290 {
   1291 	Client *c;
   1292 	Window trans;
   1293 	XPropertyEvent *ev = &e->xproperty;
   1294 
   1295 	if ((ev->window == root) && (ev->atom == XA_WM_NAME))
   1296 		updatestatus();
   1297 	else if (ev->state == PropertyDelete)
   1298 		return; /* ignore */
   1299 	else if ((c = wintoclient(ev->window))) {
   1300 		switch(ev->atom) {
   1301 		default: break;
   1302 		case XA_WM_TRANSIENT_FOR:
   1303 			if (!c->isfloating && (XGetTransientForHint(dpy, c->win, &trans)) &&
   1304 				(c->isfloating = (wintoclient(trans)) != NULL))
   1305 				arrange(c->mon);
   1306 			break;
   1307 		case XA_WM_NORMAL_HINTS:
   1308 			updatesizehints(c);
   1309 			break;
   1310 		case XA_WM_HINTS:
   1311 			updatewmhints(c);
   1312 			drawbars();
   1313 			break;
   1314 		}
   1315 		if (ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
   1316 			updatetitle(c);
   1317 			if (c == c->mon->sel)
   1318 				drawbar(c->mon);
   1319 		}
   1320 		if (ev->atom == netatom[NetWMWindowType])
   1321 			updatewindowtype(c);
   1322 	}
   1323 }
   1324 
   1325 void
   1326 quit(const Arg *arg)
   1327 {
   1328 	running = 0;
   1329 }
   1330 
   1331 Monitor *
   1332 recttomon(int x, int y, int w, int h)
   1333 {
   1334 	Monitor *m, *r = selmon;
   1335 	int a, area = 0;
   1336 
   1337 	for (m = mons; m; m = m->next)
   1338 		if ((a = INTERSECT(x, y, w, h, m)) > area) {
   1339 			area = a;
   1340 			r = m;
   1341 		}
   1342 	return r;
   1343 }
   1344 
   1345 void
   1346 resize(Client *c, int x, int y, int w, int h, int interact)
   1347 {
   1348 	if (applysizehints(c, &x, &y, &w, &h, interact))
   1349 		resizeclient(c, x, y, w, h);
   1350 }
   1351 
   1352 void
   1353 resizeclient(Client *c, int x, int y, int w, int h)
   1354 {
   1355 	XWindowChanges wc;
   1356 
   1357 	c->oldx = c->x; c->x = wc.x = x;
   1358 	c->oldy = c->y; c->y = wc.y = y;
   1359 	c->oldw = c->w; c->w = wc.width = w;
   1360 	c->oldh = c->h; c->h = wc.height = h;
   1361 	wc.border_width = c->bw;
   1362 	XConfigureWindow(dpy, c->win, CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
   1363 	configure(c);
   1364 	XSync(dpy, False);
   1365 }
   1366 
   1367 void
   1368 resizemouse(const Arg *arg)
   1369 {
   1370 	int ocx, ocy, nw, nh;
   1371 	Client *c;
   1372 	Monitor *m;
   1373 	XEvent ev;
   1374 	Time lasttime = 0;
   1375 
   1376 	if (!(c = selmon->sel))
   1377 		return;
   1378 	if (c->isfullscreen) /* no support resizing fullscreen windows by mouse */
   1379 		return;
   1380 	restack(selmon);
   1381 	ocx = c->x;
   1382 	ocy = c->y;
   1383 	if (XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
   1384 		None, cursor[CurResize]->cursor, CurrentTime) != GrabSuccess)
   1385 		return;
   1386 	XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
   1387 	do {
   1388 		XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
   1389 		switch(ev.type) {
   1390 		case ConfigureRequest:
   1391 		case Expose:
   1392 		case MapRequest:
   1393 			handler[ev.type](&ev);
   1394 			break;
   1395 		case MotionNotify:
   1396 			if ((ev.xmotion.time - lasttime) <= (1000 / 60))
   1397 				continue;
   1398 			lasttime = ev.xmotion.time;
   1399 
   1400 			nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
   1401 			nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
   1402 			if (c->mon->wx + nw >= selmon->wx && c->mon->wx + nw <= selmon->wx + selmon->ww
   1403 			&& c->mon->wy + nh >= selmon->wy && c->mon->wy + nh <= selmon->wy + selmon->wh)
   1404 			{
   1405 				if (!c->isfloating && selmon->lt[selmon->sellt]->arrange
   1406 				&& (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
   1407 					togglefloating(NULL);
   1408 			}
   1409 			if (!selmon->lt[selmon->sellt]->arrange || c->isfloating)
   1410 				resize(c, c->x, c->y, nw, nh, 1);
   1411 			break;
   1412 		}
   1413 	} while (ev.type != ButtonRelease);
   1414 	XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
   1415 	XUngrabPointer(dpy, CurrentTime);
   1416 	while (XCheckMaskEvent(dpy, EnterWindowMask, &ev));
   1417 	if ((m = recttomon(c->x, c->y, c->w, c->h)) != selmon) {
   1418 		sendmon(c, m);
   1419 		selmon = m;
   1420 		focus(NULL);
   1421 	}
   1422 }
   1423 
   1424 void
   1425 restack(Monitor *m)
   1426 {
   1427 	Client *c;
   1428 	XEvent ev;
   1429 	XWindowChanges wc;
   1430 
   1431 	drawbar(m);
   1432 	if (!m->sel)
   1433 		return;
   1434 	if (m->sel->isfloating || !m->lt[m->sellt]->arrange)
   1435 		XRaiseWindow(dpy, m->sel->win);
   1436 	if (m->lt[m->sellt]->arrange) {
   1437 		wc.stack_mode = Below;
   1438 		wc.sibling = m->barwin;
   1439 		for (c = m->stack; c; c = c->snext)
   1440 			if (!c->isfloating && ISVISIBLE(c)) {
   1441 				XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
   1442 				wc.sibling = c->win;
   1443 			}
   1444 	}
   1445 	XSync(dpy, False);
   1446 	while (XCheckMaskEvent(dpy, EnterWindowMask, &ev));
   1447 }
   1448 
   1449 void
   1450 run(void)
   1451 {
   1452 	XEvent ev;
   1453 	/* main event loop */
   1454 	XSync(dpy, False);
   1455 	while (running && !XNextEvent(dpy, &ev))
   1456 		if (handler[ev.type])
   1457 			handler[ev.type](&ev); /* call handler */
   1458 }
   1459 
   1460 void
   1461 scan(void)
   1462 {
   1463 	unsigned int i, num;
   1464 	Window d1, d2, *wins = NULL;
   1465 	XWindowAttributes wa;
   1466 
   1467 	if (XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
   1468 		for (i = 0; i < num; i++) {
   1469 			if (!XGetWindowAttributes(dpy, wins[i], &wa)
   1470 			|| wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
   1471 				continue;
   1472 			if (wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
   1473 				manage(wins[i], &wa);
   1474 		}
   1475 		for (i = 0; i < num; i++) { /* now the transients */
   1476 			if (!XGetWindowAttributes(dpy, wins[i], &wa))
   1477 				continue;
   1478 			if (XGetTransientForHint(dpy, wins[i], &d1)
   1479 			&& (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
   1480 				manage(wins[i], &wa);
   1481 		}
   1482 		if (wins)
   1483 			XFree(wins);
   1484 	}
   1485 }
   1486 
   1487 void
   1488 sendmon(Client *c, Monitor *m)
   1489 {
   1490 	if (c->mon == m)
   1491 		return;
   1492 	unfocus(c, 1);
   1493 	detach(c);
   1494 	detachstack(c);
   1495 	c->mon = m;
   1496 	c->tags = m->tagset[m->seltags]; /* assign tags of target monitor */
   1497 	attach(c);
   1498 	attachstack(c);
   1499 	focus(NULL);
   1500 	arrange(NULL);
   1501 }
   1502 
   1503 void
   1504 setclientstate(Client *c, long state)
   1505 {
   1506 	long data[] = { state, None };
   1507 
   1508 	XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
   1509 		PropModeReplace, (unsigned char *)data, 2);
   1510 }
   1511 
   1512 int
   1513 sendevent(Client *c, Atom proto)
   1514 {
   1515 	int n;
   1516 	Atom *protocols;
   1517 	int exists = 0;
   1518 	XEvent ev;
   1519 
   1520 	if (XGetWMProtocols(dpy, c->win, &protocols, &n)) {
   1521 		while (!exists && n--)
   1522 			exists = protocols[n] == proto;
   1523 		XFree(protocols);
   1524 	}
   1525 	if (exists) {
   1526 		ev.type = ClientMessage;
   1527 		ev.xclient.window = c->win;
   1528 		ev.xclient.message_type = wmatom[WMProtocols];
   1529 		ev.xclient.format = 32;
   1530 		ev.xclient.data.l[0] = proto;
   1531 		ev.xclient.data.l[1] = CurrentTime;
   1532 		XSendEvent(dpy, c->win, False, NoEventMask, &ev);
   1533 	}
   1534 	return exists;
   1535 }
   1536 
   1537 void
   1538 setfocus(Client *c)
   1539 {
   1540 	if (!c->neverfocus) {
   1541 		XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
   1542 		XChangeProperty(dpy, root, netatom[NetActiveWindow],
   1543 			XA_WINDOW, 32, PropModeReplace,
   1544 			(unsigned char *) &(c->win), 1);
   1545 	}
   1546 	sendevent(c, wmatom[WMTakeFocus]);
   1547 }
   1548 
   1549 void
   1550 setfullscreen(Client *c, int fullscreen)
   1551 {
   1552 	if (fullscreen && !c->isfullscreen) {
   1553 		XChangeProperty(dpy, c->win, netatom[NetWMState], XA_ATOM, 32,
   1554 			PropModeReplace, (unsigned char*)&netatom[NetWMFullscreen], 1);
   1555 		c->isfullscreen = 1;
   1556 		c->oldstate = c->isfloating;
   1557 		c->oldbw = c->bw;
   1558 		c->bw = 0;
   1559 		c->isfloating = 1;
   1560 		resizeclient(c, c->mon->mx, c->mon->my, c->mon->mw, c->mon->mh);
   1561 		XRaiseWindow(dpy, c->win);
   1562 	} else if (!fullscreen && c->isfullscreen){
   1563 		XChangeProperty(dpy, c->win, netatom[NetWMState], XA_ATOM, 32,
   1564 			PropModeReplace, (unsigned char*)0, 0);
   1565 		c->isfullscreen = 0;
   1566 		c->isfloating = c->oldstate;
   1567 		c->bw = c->oldbw;
   1568 		c->x = c->oldx;
   1569 		c->y = c->oldy;
   1570 		c->w = c->oldw;
   1571 		c->h = c->oldh;
   1572 		resizeclient(c, c->x, c->y, c->w, c->h);
   1573 		arrange(c->mon);
   1574 	}
   1575 }
   1576 
   1577 void
   1578 setlayout(const Arg *arg)
   1579 {
   1580 	if (!arg || !arg->v || arg->v != selmon->lt[selmon->sellt])
   1581 		selmon->sellt ^= 1;
   1582 	if (arg && arg->v)
   1583 		selmon->lt[selmon->sellt] = (Layout *)arg->v;
   1584 	strncpy(selmon->ltsymbol, selmon->lt[selmon->sellt]->symbol, sizeof selmon->ltsymbol);
   1585 	if (selmon->sel)
   1586 		arrange(selmon);
   1587 	else
   1588 		drawbar(selmon);
   1589 }
   1590 
   1591 /* arg > 1.0 will set mfact absolutely */
   1592 void
   1593 setmfact(const Arg *arg)
   1594 {
   1595 	float f;
   1596 
   1597 	if (!arg || !selmon->lt[selmon->sellt]->arrange)
   1598 		return;
   1599 	f = arg->f < 1.0 ? arg->f + selmon->mfact : arg->f - 1.0;
   1600 	if (f < 0.05 || f > 0.95)
   1601 		return;
   1602 	selmon->mfact = f;
   1603 	arrange(selmon);
   1604 }
   1605 
   1606 void
   1607 setup(void)
   1608 {
   1609 	int i;
   1610 	XSetWindowAttributes wa;
   1611 	Atom utf8string;
   1612 
   1613 	/* clean up any zombies immediately */
   1614 	sigchld(0);
   1615 
   1616 	/* init screen */
   1617 	screen = DefaultScreen(dpy);
   1618 	sw = DisplayWidth(dpy, screen);
   1619 	sh = DisplayHeight(dpy, screen);
   1620 	root = RootWindow(dpy, screen);
   1621 	drw = drw_create(dpy, screen, root, sw, sh);
   1622 	if (!drw_fontset_create(drw, fonts, LENGTH(fonts)))
   1623 		die("no fonts could be loaded.");
   1624 	lrpad = drw->fonts->h;
   1625 	bh = drw->fonts->h + 2;
   1626 	updategeom();
   1627 	/* init atoms */
   1628 	utf8string = XInternAtom(dpy, "UTF8_STRING", False);
   1629 	wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
   1630 	wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
   1631 	wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
   1632 	wmatom[WMTakeFocus] = XInternAtom(dpy, "WM_TAKE_FOCUS", False);
   1633 	netatom[NetActiveWindow] = XInternAtom(dpy, "_NET_ACTIVE_WINDOW", False);
   1634 	netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
   1635 	netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
   1636 	netatom[NetWMState] = XInternAtom(dpy, "_NET_WM_STATE", False);
   1637 	netatom[NetWMCheck] = XInternAtom(dpy, "_NET_SUPPORTING_WM_CHECK", False);
   1638 	netatom[NetWMFullscreen] = XInternAtom(dpy, "_NET_WM_STATE_FULLSCREEN", False);
   1639 	netatom[NetWMWindowType] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE", False);
   1640 	netatom[NetWMWindowTypeDialog] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE_DIALOG", False);
   1641 	netatom[NetClientList] = XInternAtom(dpy, "_NET_CLIENT_LIST", False);
   1642 	/* init cursors */
   1643 	cursor[CurNormal] = drw_cur_create(drw, XC_left_ptr);
   1644 	cursor[CurResize] = drw_cur_create(drw, XC_sizing);
   1645 	cursor[CurMove] = drw_cur_create(drw, XC_fleur);
   1646 	/* init appearance */
   1647 	scheme = ecalloc(LENGTH(colors), sizeof(Clr *));
   1648 	for (i = 0; i < LENGTH(colors); i++)
   1649 		scheme[i] = drw_scm_create(drw, colors[i], 3);
   1650 	/* init bars */
   1651 	updatebars();
   1652 	updatestatus();
   1653 	/* supporting window for NetWMCheck */
   1654 	wmcheckwin = XCreateSimpleWindow(dpy, root, 0, 0, 1, 1, 0, 0, 0);
   1655 	XChangeProperty(dpy, wmcheckwin, netatom[NetWMCheck], XA_WINDOW, 32,
   1656 		PropModeReplace, (unsigned char *) &wmcheckwin, 1);
   1657 	XChangeProperty(dpy, wmcheckwin, netatom[NetWMName], utf8string, 8,
   1658 		PropModeReplace, (unsigned char *) "dwm", 3);
   1659 	XChangeProperty(dpy, root, netatom[NetWMCheck], XA_WINDOW, 32,
   1660 		PropModeReplace, (unsigned char *) &wmcheckwin, 1);
   1661 	/* EWMH support per view */
   1662 	XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
   1663 		PropModeReplace, (unsigned char *) netatom, NetLast);
   1664 	XDeleteProperty(dpy, root, netatom[NetClientList]);
   1665 	/* select events */
   1666 	wa.cursor = cursor[CurNormal]->cursor;
   1667 	wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
   1668 		|ButtonPressMask|PointerMotionMask|EnterWindowMask
   1669 		|LeaveWindowMask|StructureNotifyMask|PropertyChangeMask;
   1670 	XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
   1671 	XSelectInput(dpy, root, wa.event_mask);
   1672 	grabkeys();
   1673 	focus(NULL);
   1674 }
   1675 
   1676 
   1677 void
   1678 seturgent(Client *c, int urg)
   1679 {
   1680 	XWMHints *wmh;
   1681 
   1682 	c->isurgent = urg;
   1683 	if (!(wmh = XGetWMHints(dpy, c->win)))
   1684 		return;
   1685 	wmh->flags = urg ? (wmh->flags | XUrgencyHint) : (wmh->flags & ~XUrgencyHint);
   1686 	XSetWMHints(dpy, c->win, wmh);
   1687 	XFree(wmh);
   1688 }
   1689 
   1690 void
   1691 showhide(Client *c)
   1692 {
   1693 	if (!c)
   1694 		return;
   1695 	if (ISVISIBLE(c)) {
   1696 		/* show clients top down */
   1697 		XMoveWindow(dpy, c->win, c->x, c->y);
   1698 		if ((!c->mon->lt[c->mon->sellt]->arrange || c->isfloating) && !c->isfullscreen)
   1699 			resize(c, c->x, c->y, c->w, c->h, 0);
   1700 		showhide(c->snext);
   1701 	} else {
   1702 		/* hide clients bottom up */
   1703 		showhide(c->snext);
   1704 		XMoveWindow(dpy, c->win, WIDTH(c) * -2, c->y);
   1705 	}
   1706 }
   1707 
   1708 void
   1709 sigchld(int unused)
   1710 {
   1711 	if (signal(SIGCHLD, sigchld) == SIG_ERR)
   1712 		die("can't install SIGCHLD handler:");
   1713 	while (0 < waitpid(-1, NULL, WNOHANG));
   1714 }
   1715 
   1716 void
   1717 spawn(const Arg *arg)
   1718 {
   1719 	if (arg->v == dmenucmd)
   1720 		dmenumon[0] = '0' + selmon->num;
   1721 	if (fork() == 0) {
   1722 		if (dpy)
   1723 			close(ConnectionNumber(dpy));
   1724 		setsid();
   1725 		execvp(((char **)arg->v)[0], (char **)arg->v);
   1726 		fprintf(stderr, "dwm: execvp %s", ((char **)arg->v)[0]);
   1727 		perror(" failed");
   1728 		exit(EXIT_SUCCESS);
   1729 	}
   1730 }
   1731 
   1732 void
   1733 tag(const Arg *arg)
   1734 {
   1735 	if (selmon->sel && arg->ui & TAGMASK) {
   1736 		selmon->sel->tags = arg->ui & TAGMASK;
   1737 		focus(NULL);
   1738 		arrange(selmon);
   1739 	}
   1740 }
   1741 
   1742 void
   1743 tagmon(const Arg *arg)
   1744 {
   1745 	if (!selmon->sel || !mons->next)
   1746 		return;
   1747 	sendmon(selmon->sel, dirtomon(arg->i));
   1748 }
   1749 
   1750 void
   1751 tile(Monitor *m)
   1752 {
   1753 	unsigned int i, n, h, mw, my, ty;
   1754 	Client *c;
   1755 
   1756 	for (n = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), n++);
   1757 	if (n == 0)
   1758 		return;
   1759 
   1760 	if (n > m->nmaster)
   1761 		mw = m->nmaster ? m->ww * m->mfact : 0;
   1762 	else
   1763 		mw = m->ww;
   1764 	for (i = my = ty = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), i++)
   1765 		if (i < m->nmaster) {
   1766 			h = (m->wh - my) / (MIN(n, m->nmaster) - i);
   1767 			resize(c, m->wx, m->wy + my, mw - (2*c->bw), h - (2*c->bw), 0);
   1768 			if (my + HEIGHT(c) < m->wh)
   1769 				my += HEIGHT(c);
   1770 		} else {
   1771 			h = (m->wh - ty) / (n - i);
   1772 			resize(c, m->wx + mw, m->wy + ty, m->ww - mw - (2*c->bw), h - (2*c->bw), 0);
   1773 			if (ty + HEIGHT(c) < m->wh)
   1774 				ty += HEIGHT(c);
   1775 		}
   1776 }
   1777 
   1778 void
   1779 togglebar(const Arg *arg)
   1780 {
   1781 	selmon->showbar = !selmon->showbar;
   1782 	updatebarpos(selmon);
   1783 	XMoveResizeWindow(dpy, selmon->barwin, selmon->wx, selmon->by, selmon->ww, bh);
   1784 	arrange(selmon);
   1785 }
   1786 
   1787 void
   1788 togglefloating(const Arg *arg)
   1789 {
   1790 	if (!selmon->sel)
   1791 		return;
   1792 	if (selmon->sel->isfullscreen) /* no support for fullscreen windows */
   1793 		return;
   1794 	selmon->sel->isfloating = !selmon->sel->isfloating || selmon->sel->isfixed;
   1795 	if (selmon->sel->isfloating)
   1796 		resize(selmon->sel, selmon->sel->x, selmon->sel->y,
   1797 			selmon->sel->w, selmon->sel->h, 0);
   1798 	arrange(selmon);
   1799 }
   1800 
   1801 void
   1802 toggletag(const Arg *arg)
   1803 {
   1804 	unsigned int newtags;
   1805 
   1806 	if (!selmon->sel)
   1807 		return;
   1808 	newtags = selmon->sel->tags ^ (arg->ui & TAGMASK);
   1809 	if (newtags) {
   1810 		selmon->sel->tags = newtags;
   1811 		focus(NULL);
   1812 		arrange(selmon);
   1813 	}
   1814 }
   1815 
   1816 void
   1817 toggleview(const Arg *arg)
   1818 {
   1819 	unsigned int newtagset = selmon->tagset[selmon->seltags] ^ (arg->ui & TAGMASK);
   1820 
   1821 	if (newtagset) {
   1822 		selmon->tagset[selmon->seltags] = newtagset;
   1823 		focus(NULL);
   1824 		arrange(selmon);
   1825 	}
   1826 }
   1827 
   1828 void
   1829 unfocus(Client *c, int setfocus)
   1830 {
   1831 	if (!c)
   1832 		return;
   1833 	grabbuttons(c, 0);
   1834 	XSetWindowBorder(dpy, c->win, scheme[SchemeNorm][ColBorder].pixel);
   1835 	if (setfocus) {
   1836 		XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
   1837 		XDeleteProperty(dpy, root, netatom[NetActiveWindow]);
   1838 	}
   1839 }
   1840 
   1841 void
   1842 unmanage(Client *c, int destroyed)
   1843 {
   1844 	Monitor *m = c->mon;
   1845 	XWindowChanges wc;
   1846 
   1847 	if (c->swallowing) {
   1848 		unswallow(c);
   1849 		return;
   1850 	}
   1851 
   1852 	Client *s = swallowingclient(c->win);
   1853 	if (s) {
   1854 		free(s->swallowing);
   1855 		s->swallowing = NULL;
   1856 		arrange(m);
   1857 		focus(NULL);
   1858 		return;
   1859 	}
   1860 
   1861 	detach(c);
   1862 	detachstack(c);
   1863 	if (!destroyed) {
   1864 		wc.border_width = c->oldbw;
   1865 		XGrabServer(dpy); /* avoid race conditions */
   1866 		XSetErrorHandler(xerrordummy);
   1867 		XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
   1868 		XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
   1869 		setclientstate(c, WithdrawnState);
   1870 		XSync(dpy, False);
   1871 		XSetErrorHandler(xerror);
   1872 		XUngrabServer(dpy);
   1873 	}
   1874 	free(c);
   1875 
   1876 	if (!s) {
   1877 		arrange(m);
   1878 		focus(NULL);
   1879 		updateclientlist();
   1880 	}
   1881 }
   1882 
   1883 void
   1884 unmapnotify(XEvent *e)
   1885 {
   1886 	Client *c;
   1887 	XUnmapEvent *ev = &e->xunmap;
   1888 
   1889 	if ((c = wintoclient(ev->window))) {
   1890 		if (ev->send_event)
   1891 			setclientstate(c, WithdrawnState);
   1892 		else
   1893 			unmanage(c, 0);
   1894 	}
   1895 }
   1896 
   1897 void
   1898 updatebars(void)
   1899 {
   1900 	Monitor *m;
   1901 	XSetWindowAttributes wa = {
   1902 		.override_redirect = True,
   1903 		.background_pixmap = ParentRelative,
   1904 		.event_mask = ButtonPressMask|ExposureMask
   1905 	};
   1906 	XClassHint ch = {"dwm", "dwm"};
   1907 	for (m = mons; m; m = m->next) {
   1908 		if (m->barwin)
   1909 			continue;
   1910 		m->barwin = XCreateWindow(dpy, root, m->wx, m->by, m->ww, bh, 0, DefaultDepth(dpy, screen),
   1911 				CopyFromParent, DefaultVisual(dpy, screen),
   1912 				CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
   1913 		XDefineCursor(dpy, m->barwin, cursor[CurNormal]->cursor);
   1914 		XMapRaised(dpy, m->barwin);
   1915 		XSetClassHint(dpy, m->barwin, &ch);
   1916 	}
   1917 }
   1918 
   1919 void
   1920 updatebarpos(Monitor *m)
   1921 {
   1922 	m->wy = m->my;
   1923 	m->wh = m->mh;
   1924 	if (m->showbar) {
   1925 		m->wh -= bh;
   1926 		m->by = m->topbar ? m->wy : m->wy + m->wh;
   1927 		m->wy = m->topbar ? m->wy + bh : m->wy;
   1928 	} else
   1929 		m->by = -bh;
   1930 }
   1931 
   1932 void
   1933 updateclientlist()
   1934 {
   1935 	Client *c;
   1936 	Monitor *m;
   1937 
   1938 	XDeleteProperty(dpy, root, netatom[NetClientList]);
   1939 	for (m = mons; m; m = m->next)
   1940 		for (c = m->clients; c; c = c->next)
   1941 			XChangeProperty(dpy, root, netatom[NetClientList],
   1942 				XA_WINDOW, 32, PropModeAppend,
   1943 				(unsigned char *) &(c->win), 1);
   1944 }
   1945 
   1946 int
   1947 updategeom(void)
   1948 {
   1949 	int dirty = 0;
   1950 
   1951 #ifdef XINERAMA
   1952 	if (XineramaIsActive(dpy)) {
   1953 		int i, j, n, nn;
   1954 		Client *c;
   1955 		Monitor *m;
   1956 		XineramaScreenInfo *info = XineramaQueryScreens(dpy, &nn);
   1957 		XineramaScreenInfo *unique = NULL;
   1958 
   1959 		for (n = 0, m = mons; m; m = m->next, n++);
   1960 		/* only consider unique geometries as separate screens */
   1961 		unique = ecalloc(nn, sizeof(XineramaScreenInfo));
   1962 		for (i = 0, j = 0; i < nn; i++)
   1963 			if (isuniquegeom(unique, j, &info[i]))
   1964 				memcpy(&unique[j++], &info[i], sizeof(XineramaScreenInfo));
   1965 		XFree(info);
   1966 		nn = j;
   1967 		if (n <= nn) { /* new monitors available */
   1968 			for (i = 0; i < (nn - n); i++) {
   1969 				for (m = mons; m && m->next; m = m->next);
   1970 				if (m)
   1971 					m->next = createmon();
   1972 				else
   1973 					mons = createmon();
   1974 			}
   1975 			for (i = 0, m = mons; i < nn && m; m = m->next, i++)
   1976 				if (i >= n
   1977 				|| unique[i].x_org != m->mx || unique[i].y_org != m->my
   1978 				|| unique[i].width != m->mw || unique[i].height != m->mh)
   1979 				{
   1980 					dirty = 1;
   1981 					m->num = i;
   1982 					m->mx = m->wx = unique[i].x_org;
   1983 					m->my = m->wy = unique[i].y_org;
   1984 					m->mw = m->ww = unique[i].width;
   1985 					m->mh = m->wh = unique[i].height;
   1986 					updatebarpos(m);
   1987 				}
   1988 		} else { /* less monitors available nn < n */
   1989 			for (i = nn; i < n; i++) {
   1990 				for (m = mons; m && m->next; m = m->next);
   1991 				while ((c = m->clients)) {
   1992 					dirty = 1;
   1993 					m->clients = c->next;
   1994 					detachstack(c);
   1995 					c->mon = mons;
   1996 					attach(c);
   1997 					attachstack(c);
   1998 				}
   1999 				if (m == selmon)
   2000 					selmon = mons;
   2001 				cleanupmon(m);
   2002 			}
   2003 		}
   2004 		free(unique);
   2005 	} else
   2006 #endif /* XINERAMA */
   2007 	{ /* default monitor setup */
   2008 		if (!mons)
   2009 			mons = createmon();
   2010 		if (mons->mw != sw || mons->mh != sh) {
   2011 			dirty = 1;
   2012 			mons->mw = mons->ww = sw;
   2013 			mons->mh = mons->wh = sh;
   2014 			updatebarpos(mons);
   2015 		}
   2016 	}
   2017 	if (dirty) {
   2018 		selmon = mons;
   2019 		selmon = wintomon(root);
   2020 	}
   2021 	return dirty;
   2022 }
   2023 
   2024 void
   2025 updatenumlockmask(void)
   2026 {
   2027 	unsigned int i, j;
   2028 	XModifierKeymap *modmap;
   2029 
   2030 	numlockmask = 0;
   2031 	modmap = XGetModifierMapping(dpy);
   2032 	for (i = 0; i < 8; i++)
   2033 		for (j = 0; j < modmap->max_keypermod; j++)
   2034 			if (modmap->modifiermap[i * modmap->max_keypermod + j]
   2035 				== XKeysymToKeycode(dpy, XK_Num_Lock))
   2036 				numlockmask = (1 << i);
   2037 	XFreeModifiermap(modmap);
   2038 }
   2039 
   2040 void
   2041 updatesizehints(Client *c)
   2042 {
   2043 	long msize;
   2044 	XSizeHints size;
   2045 
   2046 	if (!XGetWMNormalHints(dpy, c->win, &size, &msize))
   2047 		/* size is uninitialized, ensure that size.flags aren't used */
   2048 		size.flags = PSize;
   2049 	if (size.flags & PBaseSize) {
   2050 		c->basew = size.base_width;
   2051 		c->baseh = size.base_height;
   2052 	} else if (size.flags & PMinSize) {
   2053 		c->basew = size.min_width;
   2054 		c->baseh = size.min_height;
   2055 	} else
   2056 		c->basew = c->baseh = 0;
   2057 	if (size.flags & PResizeInc) {
   2058 		c->incw = size.width_inc;
   2059 		c->inch = size.height_inc;
   2060 	} else
   2061 		c->incw = c->inch = 0;
   2062 	if (size.flags & PMaxSize) {
   2063 		c->maxw = size.max_width;
   2064 		c->maxh = size.max_height;
   2065 	} else
   2066 		c->maxw = c->maxh = 0;
   2067 	if (size.flags & PMinSize) {
   2068 		c->minw = size.min_width;
   2069 		c->minh = size.min_height;
   2070 	} else if (size.flags & PBaseSize) {
   2071 		c->minw = size.base_width;
   2072 		c->minh = size.base_height;
   2073 	} else
   2074 		c->minw = c->minh = 0;
   2075 	if (size.flags & PAspect) {
   2076 		c->mina = (float)size.min_aspect.y / size.min_aspect.x;
   2077 		c->maxa = (float)size.max_aspect.x / size.max_aspect.y;
   2078 	} else
   2079 		c->maxa = c->mina = 0.0;
   2080 	c->isfixed = (c->maxw && c->maxh && c->maxw == c->minw && c->maxh == c->minh);
   2081 }
   2082 
   2083 void
   2084 updatestatus(void)
   2085 {
   2086 	if (!gettextprop(root, XA_WM_NAME, stext, sizeof(stext)))
   2087 		strcpy(stext, "dwm-"VERSION);
   2088 	drawbar(selmon);
   2089 }
   2090 
   2091 void
   2092 updatetitle(Client *c)
   2093 {
   2094 	if (!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
   2095 		gettextprop(c->win, XA_WM_NAME, c->name, sizeof c->name);
   2096 	if (c->name[0] == '\0') /* hack to mark broken clients */
   2097 		strcpy(c->name, broken);
   2098 }
   2099 
   2100 void
   2101 updatewindowtype(Client *c)
   2102 {
   2103 	Atom state = getatomprop(c, netatom[NetWMState]);
   2104 	Atom wtype = getatomprop(c, netatom[NetWMWindowType]);
   2105 
   2106 	if (state == netatom[NetWMFullscreen])
   2107 		setfullscreen(c, 1);
   2108 	if (wtype == netatom[NetWMWindowTypeDialog])
   2109 		c->isfloating = 1;
   2110 }
   2111 
   2112 void
   2113 updatewmhints(Client *c)
   2114 {
   2115 	XWMHints *wmh;
   2116 
   2117 	if ((wmh = XGetWMHints(dpy, c->win))) {
   2118 		if (c == selmon->sel && wmh->flags & XUrgencyHint) {
   2119 			wmh->flags &= ~XUrgencyHint;
   2120 			XSetWMHints(dpy, c->win, wmh);
   2121 		} else
   2122 			c->isurgent = (wmh->flags & XUrgencyHint) ? 1 : 0;
   2123 		if (wmh->flags & InputHint)
   2124 			c->neverfocus = !wmh->input;
   2125 		else
   2126 			c->neverfocus = 0;
   2127 		XFree(wmh);
   2128 	}
   2129 }
   2130 
   2131 void
   2132 view(const Arg *arg)
   2133 {
   2134 	if ((arg->ui & TAGMASK) == selmon->tagset[selmon->seltags])
   2135 		return;
   2136 	selmon->seltags ^= 1; /* toggle sel tagset */
   2137 	if (arg->ui & TAGMASK)
   2138 		selmon->tagset[selmon->seltags] = arg->ui & TAGMASK;
   2139 	focus(NULL);
   2140 	arrange(selmon);
   2141 }
   2142 
   2143 pid_t
   2144 winpid(Window w)
   2145 {
   2146 
   2147 	pid_t result = 0;
   2148 
   2149 #ifdef __linux__
   2150 	xcb_res_client_id_spec_t spec = {0};
   2151 	spec.client = w;
   2152 	spec.mask = XCB_RES_CLIENT_ID_MASK_LOCAL_CLIENT_PID;
   2153 
   2154 	xcb_generic_error_t *e = NULL;
   2155 	xcb_res_query_client_ids_cookie_t c = xcb_res_query_client_ids(xcon, 1, &spec);
   2156 	xcb_res_query_client_ids_reply_t *r = xcb_res_query_client_ids_reply(xcon, c, &e);
   2157 
   2158 	if (!r)
   2159 		return (pid_t)0;
   2160 
   2161 	xcb_res_client_id_value_iterator_t i = xcb_res_query_client_ids_ids_iterator(r);
   2162 	for (; i.rem; xcb_res_client_id_value_next(&i)) {
   2163 		spec = i.data->spec;
   2164 		if (spec.mask & XCB_RES_CLIENT_ID_MASK_LOCAL_CLIENT_PID) {
   2165 			uint32_t *t = xcb_res_client_id_value_value(i.data);
   2166 			result = *t;
   2167 			break;
   2168 		}
   2169 	}
   2170 
   2171 	free(r);
   2172 
   2173 	if (result == (pid_t)-1)
   2174 		result = 0;
   2175 
   2176 #endif /* __linux__ */
   2177 
   2178 #ifdef __OpenBSD__
   2179         Atom type;
   2180         int format;
   2181         unsigned long len, bytes;
   2182         unsigned char *prop;
   2183         pid_t ret;
   2184 
   2185         if (XGetWindowProperty(dpy, w, XInternAtom(dpy, "_NET_WM_PID", 0), 0, 1, False, AnyPropertyType, &type, &format, &len, &bytes, &prop) != Success || !prop)
   2186                return 0;
   2187 
   2188         ret = *(pid_t*)prop;
   2189         XFree(prop);
   2190         result = ret;
   2191 
   2192 #endif /* __OpenBSD__ */
   2193 	return result;
   2194 }
   2195 
   2196 pid_t
   2197 getparentprocess(pid_t p)
   2198 {
   2199 	unsigned int v = 0;
   2200 
   2201 #ifdef __linux__
   2202 	FILE *f;
   2203 	char buf[256];
   2204 	snprintf(buf, sizeof(buf) - 1, "/proc/%u/stat", (unsigned)p);
   2205 
   2206 	if (!(f = fopen(buf, "r")))
   2207 		return 0;
   2208 
   2209 	fscanf(f, "%*u %*s %*c %u", &v);
   2210 	fclose(f);
   2211 #endif /* __linux__*/
   2212 
   2213 #ifdef __OpenBSD__
   2214 	int n;
   2215 	kvm_t *kd;
   2216 	struct kinfo_proc *kp;
   2217 
   2218 	kd = kvm_openfiles(NULL, NULL, NULL, KVM_NO_FILES, NULL);
   2219 	if (!kd)
   2220 		return 0;
   2221 
   2222 	kp = kvm_getprocs(kd, KERN_PROC_PID, p, sizeof(*kp), &n);
   2223 	v = kp->p_ppid;
   2224 #endif /* __OpenBSD__ */
   2225 
   2226 	return (pid_t)v;
   2227 }
   2228 
   2229 int
   2230 isdescprocess(pid_t p, pid_t c)
   2231 {
   2232 	while (p != c && c != 0)
   2233 		c = getparentprocess(c);
   2234 
   2235 	return (int)c;
   2236 }
   2237 
   2238 Client *
   2239 termforwin(const Client *w)
   2240 {
   2241 	Client *c;
   2242 	Monitor *m;
   2243 
   2244 	if (!w->pid || w->isterminal)
   2245 		return NULL;
   2246 
   2247 	for (m = mons; m; m = m->next) {
   2248 		for (c = m->clients; c; c = c->next) {
   2249 			if (c->isterminal && !c->swallowing && c->pid && isdescprocess(c->pid, w->pid))
   2250 				return c;
   2251 		}
   2252 	}
   2253 
   2254 	return NULL;
   2255 }
   2256 
   2257 Client *
   2258 swallowingclient(Window w)
   2259 {
   2260 	Client *c;
   2261 	Monitor *m;
   2262 
   2263 	for (m = mons; m; m = m->next) {
   2264 		for (c = m->clients; c; c = c->next) {
   2265 			if (c->swallowing && c->swallowing->win == w)
   2266 				return c;
   2267 		}
   2268 	}
   2269 
   2270 	return NULL;
   2271 }
   2272 
   2273 Client *
   2274 wintoclient(Window w)
   2275 {
   2276 	Client *c;
   2277 	Monitor *m;
   2278 
   2279 	for (m = mons; m; m = m->next)
   2280 		for (c = m->clients; c; c = c->next)
   2281 			if (c->win == w)
   2282 				return c;
   2283 	return NULL;
   2284 }
   2285 
   2286 Monitor *
   2287 wintomon(Window w)
   2288 {
   2289 	int x, y;
   2290 	Client *c;
   2291 	Monitor *m;
   2292 
   2293 	if (w == root && getrootptr(&x, &y))
   2294 		return recttomon(x, y, 1, 1);
   2295 	for (m = mons; m; m = m->next)
   2296 		if (w == m->barwin)
   2297 			return m;
   2298 	if ((c = wintoclient(w)))
   2299 		return c->mon;
   2300 	return selmon;
   2301 }
   2302 
   2303 /* There's no way to check accesses to destroyed windows, thus those cases are
   2304  * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
   2305  * default error handler, which may call exit. */
   2306 int
   2307 xerror(Display *dpy, XErrorEvent *ee)
   2308 {
   2309 	if (ee->error_code == BadWindow
   2310 	|| (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
   2311 	|| (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
   2312 	|| (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
   2313 	|| (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
   2314 	|| (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
   2315 	|| (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
   2316 	|| (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
   2317 	|| (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
   2318 		return 0;
   2319 	fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
   2320 		ee->request_code, ee->error_code);
   2321 	return xerrorxlib(dpy, ee); /* may call exit */
   2322 }
   2323 
   2324 int
   2325 xerrordummy(Display *dpy, XErrorEvent *ee)
   2326 {
   2327 	return 0;
   2328 }
   2329 
   2330 /* Startup Error handler to check if another window manager
   2331  * is already running. */
   2332 int
   2333 xerrorstart(Display *dpy, XErrorEvent *ee)
   2334 {
   2335 	die("dwm: another window manager is already running");
   2336 	return -1;
   2337 }
   2338 
   2339 void
   2340 zoom(const Arg *arg)
   2341 {
   2342 	Client *c = selmon->sel;
   2343 
   2344 	if (!selmon->lt[selmon->sellt]->arrange
   2345 	|| (selmon->sel && selmon->sel->isfloating))
   2346 		return;
   2347 	if (c == nexttiled(selmon->clients))
   2348 		if (!c || !(c = nexttiled(c->next)))
   2349 			return;
   2350 	pop(c);
   2351 }
   2352 
   2353 int
   2354 main(int argc, char *argv[])
   2355 {
   2356 	if (argc == 2 && !strcmp("-v", argv[1]))
   2357 		die("dwm-"VERSION);
   2358 	else if (argc != 1)
   2359 		die("usage: dwm [-v]");
   2360 	if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
   2361 		fputs("warning: no locale support\n", stderr);
   2362 	if (!(dpy = XOpenDisplay(NULL)))
   2363 		die("dwm: cannot open display");
   2364 	if (!(xcon = XGetXCBConnection(dpy)))
   2365 		die("dwm: cannot get xcb connection\n");
   2366 	checkotherwm();
   2367 	setup();
   2368 #ifdef __OpenBSD__
   2369 	if (pledge("stdio rpath proc exec ps", NULL) == -1)
   2370 		die("pledge");
   2371 #endif /* __OpenBSD__ */
   2372 	scan();
   2373 	run();
   2374 	cleanup();
   2375 	XCloseDisplay(dpy);
   2376 	return EXIT_SUCCESS;
   2377 }