dwm

my customized dwm build
git clone git://git.hanetzok.net/dwm
Log | Files | Refs | README | LICENSE

dwm.c (76070B)


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