all repos — dwm @ a6a216f28cbc49afaace269c2662382a351fda24

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