dwm

my dwm config in tx branch
git clone git://shroom.party/dwm.git
Log | Files | Refs | README | LICENSE

dwm.c (55945B)


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