dwm

Personal build of dwm
Log | Files | Refs | README | LICENSE

dwm.c (70398B)


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