dwm

My fork of https://dwm.suckless.org/
git clone https://git.inz.fi/dwm/
Log | Files | Refs | README | LICENSE

dwm.c (70689B)


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