dwm

personal fork of dwm (rnpnr branch)
git clone anongit@rnpnr.xyz:dwm.git
Log | Files | Refs | Feed | README | LICENSE

dwm.c (55549B)


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