dwm

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

dwm.c (76406B)


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