all repos — dwm @ 1b62f8fa58eba3e535134912da2fa305fb7d3021

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