sistema_progs

Programas para customizar o meu entorno de traballo nos meus equipos persoais
Log | Files | Refs

dwm.c.orig (69753B)


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