dwm

my customized branch of dwm
git clone git://git.jakekoroman.com/dwm
Log | Files | Refs | README | LICENSE

dwm.c (58321B)


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