dwm

Fork of dwm, the best tiling window manager
git clone git://git.laack.co/dwm.git
Log | Files | Refs | README | LICENSE

dwm.c (53532B)


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