dwm

dwm fork
git clone git://git.rr3.xyz/dwm
Log | Files | Refs | README | LICENSE

dwm.c (53956B)


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