dwm

I use bspwm now
Log | Files | Refs | README | LICENSE

dwm.c (66980B)


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