dwm

X window manager from suckless utilities
git clone git://git.thepablogq.xyz/dwm
Log | Files | Refs | README | LICENSE

dwm.c (61047B)


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