dwm

fork of dwm
git clone git://popovic.xyz/dwm.git
Log | Files | Refs | README | LICENSE

dwm.c.orig (62392B)


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