dwm

Mahdi's build of dwm
git clone git://mahdi.pw/dwm.git
Log | Files | Refs | README | LICENSE

dwm.c (67408B)


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