dwm

[archived] [fork] dynamic window manager
git clone https://hhvn.uk/dwm
git clone git://hhvn.uk/dwm
Log | Files | Refs | README | LICENSE

dwm.c (53864B)


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