all repos — dwm @ 62d3caa9990e4fd936850341095da4dd1bf4c846

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