all repos — dwm @ 3aabc08ede9c6496720124be8ee34c8b39735239

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