all repos — dwm @ 2f4835a98a9905c36ce3008d0076c1ea905464a3

fork of suckless dynamic window manager

dwm.c (view raw)

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