all repos — dwm @ 1e20a0f78a580ebf4ad521d0e074125bb0a7d4b8

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