suckless

my personal suckless patches and customisation (dwm, st, dmenu).
Log | Files | Refs | README

dwm.c.orig (53963B)


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