dwm

my customized branch of dwm
git clone git://git.jakekoroman.com/dwm
Log | Files | Refs | README | LICENSE

dwm.c (61926B)


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