dwm

my build of dwm
git clone git://git.hanetzok.net/dwm
Log | Files | Refs | README | LICENSE

dwm.c (64240B)


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