dwm

My patch set and modifications to dwm
git clone git://git.ethandl.dev/dwm
Log | Files | Refs | README | LICENSE

dwm.c (52861B)


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