dwm

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

dwm.c (55640B)


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