dwm

dynamic window manager
git clone git://git.suckless.org/dwm
Log | Files | Refs | README | LICENSE

dwm.c (53768B)


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