dwm

Repositório dwm
git clone git://git.sivaldodavi.com/dwm.git
Log | Files | Refs | README

dwm.c (58420B)


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