dotfiles

[void/arch] linux dotfiles
git clone git://git.mdnr.space/dotfiles
Log | Files | Refs

dwm.c (66144B)


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