dwm

custom dwm build (upstream ~> git://dwm.suckless.org/dwm)
Log | Files | Refs | README | LICENSE

dwm.c (62435B)


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