dwm

dynamic window manager
git clone https://git.parazyd.org/dwm
Log | Files | Refs | README | LICENSE

dwm.c (71014B)


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