dwm-noxz

[fork] suckless dwm - personal fork
git clone git://git.noxz.tech/dwm-noxz
Log | Files | Refs | README | LICENSE

dwm.c (64333B)


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