all repos — dwm @ e5a1e77351bb4538a1a475739a00dcb41aa35701

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