dwm.c (67113B) - raw


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