dwm

dynamic window manager - with my changes
git clone https://pi.duncano.de/git/dwm.git

dwm.c (55404B)


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