dwm

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README | LICENSE

dwm.c (58836B)


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