dwm

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

dwm.c (67377B)


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