dwm

Luke's build of suckless's dwm
Log | Files | Refs | README | LICENSE

dwm.c (62658B)


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