all repos — dwm @ aa2395b6a81475b44dd74618fb7f0b40305e10bb

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 border, oldborder;
  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, 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(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 = 0;
 326		for(i = 0; i < LENGTH(tags); i++) {
 327			x += textw(tags[i]);
 328			if(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->border;
 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		setgeom(NULL);
 428}
 429
 430void
 431configurerequest(XEvent *e) {
 432	Client *c;
 433	XConfigureRequestEvent *ev = &e->xconfigurerequest;
 434	XWindowChanges wc;
 435
 436	if((c = getclient(ev->window))) {
 437		if(ev->value_mask & CWBorderWidth)
 438			c->border = ev->border_width;
 439		if(c->isfixed || c->isfloating || lt->isfloating) {
 440			if(ev->value_mask & CWX)
 441				c->x = sx + ev->x;
 442			if(ev->value_mask & CWY)
 443				c->y = sy + ev->y;
 444			if(ev->value_mask & CWWidth)
 445				c->w = ev->width;
 446			if(ev->value_mask & CWHeight)
 447				c->h = ev->height;
 448			if((c->x - sx + c->w) > sw && c->isfloating)
 449				c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
 450			if((c->y - sy + c->h) > sh && c->isfloating)
 451				c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
 452			if((ev->value_mask & (CWX|CWY))
 453			&& !(ev->value_mask & (CWWidth|CWHeight)))
 454				configure(c);
 455			if(isvisible(c))
 456				XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
 457		}
 458		else
 459			configure(c);
 460	}
 461	else {
 462		wc.x = ev->x;
 463		wc.y = ev->y;
 464		wc.width = ev->width;
 465		wc.height = ev->height;
 466		wc.border_width = ev->border_width;
 467		wc.sibling = ev->above;
 468		wc.stack_mode = ev->detail;
 469		XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
 470	}
 471	XSync(dpy, False);
 472}
 473
 474unsigned int
 475counttiled(void) {
 476	unsigned int n;
 477	Client *c;
 478
 479	for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next), n++);
 480	return n;
 481}
 482
 483void
 484destroynotify(XEvent *e) {
 485	Client *c;
 486	XDestroyWindowEvent *ev = &e->xdestroywindow;
 487
 488	if((c = getclient(ev->window)))
 489		unmanage(c);
 490}
 491
 492void
 493detach(Client *c) {
 494	if(c->prev)
 495		c->prev->next = c->next;
 496	if(c->next)
 497		c->next->prev = c->prev;
 498	if(c == clients)
 499		clients = c->next;
 500	c->next = c->prev = NULL;
 501}
 502
 503void
 504detachstack(Client *c) {
 505	Client **tc;
 506
 507	for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
 508	*tc = c->snext;
 509}
 510
 511void
 512drawbar(void) {
 513	int i, x;
 514	Client *c;
 515
 516	dc.x = 0;
 517	for(c = stack; c && !isvisible(c); c = c->snext);
 518	for(i = 0; i < LENGTH(tags); i++) {
 519		dc.w = textw(tags[i]);
 520		if(seltags[i]) {
 521			drawtext(tags[i], dc.sel, isurgent(i));
 522			drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.sel);
 523		}
 524		else {
 525			drawtext(tags[i], dc.norm, isurgent(i));
 526			drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.norm);
 527		}
 528		dc.x += dc.w;
 529	}
 530	dc.w = blw;
 531	drawtext(lt->symbol, dc.norm, False);
 532	x = dc.x + dc.w;
 533	dc.w = textw(stext);
 534	dc.x = bw - dc.w;
 535	if(dc.x < x) {
 536		dc.x = x;
 537		dc.w = bw - x;
 538	}
 539	drawtext(stext, dc.norm, False);
 540	if((dc.w = dc.x - x) > bh) {
 541		dc.x = x;
 542		if(c) {
 543			drawtext(c->name, dc.sel, False);
 544			drawsquare(False, c->isfloating, False, dc.sel);
 545		}
 546		else
 547			drawtext(NULL, dc.norm, False);
 548	}
 549	XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, bw, bh, 0, 0);
 550	XSync(dpy, False);
 551}
 552
 553void
 554drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
 555	int x;
 556	XGCValues gcv;
 557	XRectangle r = { dc.x, dc.y, dc.w, dc.h };
 558
 559	gcv.foreground = col[invert ? ColBG : ColFG];
 560	XChangeGC(dpy, dc.gc, GCForeground, &gcv);
 561	x = (dc.font.ascent + dc.font.descent + 2) / 4;
 562	r.x = dc.x + 1;
 563	r.y = dc.y + 1;
 564	if(filled) {
 565		r.width = r.height = x + 1;
 566		XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
 567	}
 568	else if(empty) {
 569		r.width = r.height = x;
 570		XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
 571	}
 572}
 573
 574void
 575drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
 576	int x, y, w, h;
 577	unsigned int len, olen;
 578	XRectangle r = { dc.x, dc.y, dc.w, dc.h };
 579
 580	XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
 581	XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
 582	if(!text)
 583		return;
 584	w = 0;
 585	olen = len = strlen(text);
 586	if(len >= sizeof buf)
 587		len = sizeof buf - 1;
 588	memcpy(buf, text, len);
 589	buf[len] = 0;
 590	h = dc.font.ascent + dc.font.descent;
 591	y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
 592	x = dc.x + (h / 2);
 593	/* shorten text if necessary */
 594	while(len && (w = textnw(buf, len)) > dc.w - h)
 595		buf[--len] = 0;
 596	if(len < olen) {
 597		if(len > 1)
 598			buf[len - 1] = '.';
 599		if(len > 2)
 600			buf[len - 2] = '.';
 601		if(len > 3)
 602			buf[len - 3] = '.';
 603	}
 604	if(w > dc.w)
 605		return; /* too long */
 606	XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
 607	if(dc.font.set)
 608		XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
 609	else
 610		XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
 611}
 612
 613void *
 614emallocz(unsigned int size) {
 615	void *res = calloc(1, size);
 616
 617	if(!res)
 618		eprint("fatal: could not malloc() %u bytes\n", size);
 619	return res;
 620}
 621
 622void
 623enternotify(XEvent *e) {
 624	Client *c;
 625	XCrossingEvent *ev = &e->xcrossing;
 626
 627	if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
 628		return;
 629	if((c = getclient(ev->window)))
 630		focus(c);
 631	else
 632		focus(NULL);
 633}
 634
 635void
 636eprint(const char *errstr, ...) {
 637	va_list ap;
 638
 639	va_start(ap, errstr);
 640	vfprintf(stderr, errstr, ap);
 641	va_end(ap);
 642	exit(EXIT_FAILURE);
 643}
 644
 645void
 646expose(XEvent *e) {
 647	XExposeEvent *ev = &e->xexpose;
 648
 649	if(ev->count == 0 && (ev->window == barwin))
 650		drawbar();
 651}
 652
 653void
 654floating(void) { /* default floating layout */
 655	Client *c;
 656
 657	for(c = clients; c; c = c->next)
 658		if(isvisible(c))
 659			resize(c, c->x, c->y, c->w, c->h, True);
 660}
 661
 662void
 663focus(Client *c) {
 664	if(!c || (c && !isvisible(c)))
 665		for(c = stack; c && !isvisible(c); c = c->snext);
 666	if(sel && sel != c) {
 667		grabbuttons(sel, False);
 668		XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
 669	}
 670	if(c) {
 671		detachstack(c);
 672		attachstack(c);
 673		grabbuttons(c, True);
 674	}
 675	sel = c;
 676	if(c) {
 677		XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
 678		XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
 679	}
 680	else
 681		XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
 682	drawbar();
 683}
 684
 685void
 686focusin(XEvent *e) { /* there are some broken focus acquiring clients */
 687	XFocusChangeEvent *ev = &e->xfocus;
 688
 689	if(sel && ev->window != sel->win)
 690		XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
 691}
 692
 693void
 694focusnext(const char *arg) {
 695	Client *c;
 696
 697	if(!sel)
 698		return;
 699	for(c = sel->next; c && !isvisible(c); c = c->next);
 700	if(!c)
 701		for(c = clients; c && !isvisible(c); c = c->next);
 702	if(c) {
 703		focus(c);
 704		restack();
 705	}
 706}
 707
 708void
 709focusprev(const char *arg) {
 710	Client *c;
 711
 712	if(!sel)
 713		return;
 714	for(c = sel->prev; c && !isvisible(c); c = c->prev);
 715	if(!c) {
 716		for(c = clients; c && c->next; c = c->next);
 717		for(; c && !isvisible(c); c = c->prev);
 718	}
 719	if(c) {
 720		focus(c);
 721		restack();
 722	}
 723}
 724
 725Client *
 726getclient(Window w) {
 727	Client *c;
 728
 729	for(c = clients; c && c->win != w; c = c->next);
 730	return c;
 731}
 732
 733unsigned long
 734getcolor(const char *colstr) {
 735	Colormap cmap = DefaultColormap(dpy, screen);
 736	XColor color;
 737
 738	if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
 739		eprint("error, cannot allocate color '%s'\n", colstr);
 740	return color.pixel;
 741}
 742
 743long
 744getstate(Window w) {
 745	int format, status;
 746	long result = -1;
 747	unsigned char *p = NULL;
 748	unsigned long n, extra;
 749	Atom real;
 750
 751	status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
 752			&real, &format, &n, &extra, (unsigned char **)&p);
 753	if(status != Success)
 754		return -1;
 755	if(n != 0)
 756		result = *p;
 757	XFree(p);
 758	return result;
 759}
 760
 761Bool
 762gettextprop(Window w, Atom atom, char *text, unsigned int size) {
 763	char **list = NULL;
 764	int n;
 765	XTextProperty name;
 766
 767	if(!text || size == 0)
 768		return False;
 769	text[0] = '\0';
 770	XGetTextProperty(dpy, w, &name, atom);
 771	if(!name.nitems)
 772		return False;
 773	if(name.encoding == XA_STRING)
 774		strncpy(text, (char *)name.value, size - 1);
 775	else {
 776		if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
 777		&& n > 0 && *list) {
 778			strncpy(text, *list, size - 1);
 779			XFreeStringList(list);
 780		}
 781	}
 782	text[size - 1] = '\0';
 783	XFree(name.value);
 784	return True;
 785}
 786
 787void
 788grabbuttons(Client *c, Bool focused) {
 789	XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
 790
 791	if(focused) {
 792		XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
 793				GrabModeAsync, GrabModeSync, None, None);
 794		XGrabButton(dpy, Button1, MODKEY|LockMask, c->win, False, BUTTONMASK,
 795				GrabModeAsync, GrabModeSync, None, None);
 796		XGrabButton(dpy, Button1, MODKEY|numlockmask, c->win, False, BUTTONMASK,
 797				GrabModeAsync, GrabModeSync, None, None);
 798		XGrabButton(dpy, Button1, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
 799				GrabModeAsync, GrabModeSync, None, None);
 800
 801		XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
 802				GrabModeAsync, GrabModeSync, None, None);
 803		XGrabButton(dpy, Button2, MODKEY|LockMask, c->win, False, BUTTONMASK,
 804				GrabModeAsync, GrabModeSync, None, None);
 805		XGrabButton(dpy, Button2, MODKEY|numlockmask, c->win, False, BUTTONMASK,
 806				GrabModeAsync, GrabModeSync, None, None);
 807		XGrabButton(dpy, Button2, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
 808				GrabModeAsync, GrabModeSync, None, None);
 809
 810		XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
 811				GrabModeAsync, GrabModeSync, None, None);
 812		XGrabButton(dpy, Button3, MODKEY|LockMask, c->win, False, BUTTONMASK,
 813				GrabModeAsync, GrabModeSync, None, None);
 814		XGrabButton(dpy, Button3, MODKEY|numlockmask, c->win, False, BUTTONMASK,
 815				GrabModeAsync, GrabModeSync, None, None);
 816		XGrabButton(dpy, Button3, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
 817				GrabModeAsync, GrabModeSync, None, None);
 818	}
 819	else
 820		XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
 821				GrabModeAsync, GrabModeSync, None, None);
 822}
 823
 824void
 825grabkeys(void)  {
 826	unsigned int i, j;
 827	KeyCode code;
 828	XModifierKeymap *modmap;
 829
 830	/* init modifier map */
 831	modmap = XGetModifierMapping(dpy);
 832	for(i = 0; i < 8; i++)
 833		for(j = 0; j < modmap->max_keypermod; j++) {
 834			if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
 835				numlockmask = (1 << i);
 836		}
 837	XFreeModifiermap(modmap);
 838
 839	XUngrabKey(dpy, AnyKey, AnyModifier, root);
 840	for(i = 0; i < LENGTH(keys); i++) {
 841		code = XKeysymToKeycode(dpy, keys[i].keysym);
 842		XGrabKey(dpy, code, keys[i].mod, root, True,
 843				GrabModeAsync, GrabModeAsync);
 844		XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
 845				GrabModeAsync, GrabModeAsync);
 846		XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
 847				GrabModeAsync, GrabModeAsync);
 848		XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
 849				GrabModeAsync, GrabModeAsync);
 850	}
 851}
 852
 853unsigned int
 854idxoftag(const char *t) {
 855	unsigned int i;
 856
 857	for(i = 0; (i < LENGTH(tags)) && (tags[i] != t); i++);
 858	return (i < LENGTH(tags)) ? i : 0;
 859}
 860
 861void
 862initfont(const char *fontstr) {
 863	char *def, **missing;
 864	int i, n;
 865
 866	missing = NULL;
 867	if(dc.font.set)
 868		XFreeFontSet(dpy, dc.font.set);
 869	dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
 870	if(missing) {
 871		while(n--)
 872			fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
 873		XFreeStringList(missing);
 874	}
 875	if(dc.font.set) {
 876		XFontSetExtents *font_extents;
 877		XFontStruct **xfonts;
 878		char **font_names;
 879		dc.font.ascent = dc.font.descent = 0;
 880		font_extents = XExtentsOfFontSet(dc.font.set);
 881		n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
 882		for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
 883			if(dc.font.ascent < (*xfonts)->ascent)
 884				dc.font.ascent = (*xfonts)->ascent;
 885			if(dc.font.descent < (*xfonts)->descent)
 886				dc.font.descent = (*xfonts)->descent;
 887			xfonts++;
 888		}
 889	}
 890	else {
 891		if(dc.font.xfont)
 892			XFreeFont(dpy, dc.font.xfont);
 893		dc.font.xfont = NULL;
 894		if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
 895		&& !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
 896			eprint("error, cannot load font: '%s'\n", fontstr);
 897		dc.font.ascent = dc.font.xfont->ascent;
 898		dc.font.descent = dc.font.xfont->descent;
 899	}
 900	dc.font.height = dc.font.ascent + dc.font.descent;
 901}
 902
 903Bool
 904isoccupied(unsigned int t) {
 905	Client *c;
 906
 907	for(c = clients; c; c = c->next)
 908		if(c->tags[t])
 909			return True;
 910	return False;
 911}
 912
 913Bool
 914isprotodel(Client *c) {
 915	int i, n;
 916	Atom *protocols;
 917	Bool ret = False;
 918
 919	if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
 920		for(i = 0; !ret && i < n; i++)
 921			if(protocols[i] == wmatom[WMDelete])
 922				ret = True;
 923		XFree(protocols);
 924	}
 925	return ret;
 926}
 927
 928Bool
 929isurgent(unsigned int t) {
 930	Client *c;
 931
 932	for(c = clients; c; c = c->next)
 933		if(c->isurgent && c->tags[t])
 934			return True;
 935	return False;
 936}
 937
 938Bool
 939isvisible(Client *c) {
 940	unsigned int i;
 941
 942	for(i = 0; i < LENGTH(tags); i++)
 943		if(c->tags[i] && seltags[i])
 944			return True;
 945	return False;
 946}
 947
 948void
 949keypress(XEvent *e) {
 950	unsigned int i;
 951	KeySym keysym;
 952	XKeyEvent *ev;
 953
 954	ev = &e->xkey;
 955	keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
 956	for(i = 0; i < LENGTH(keys); i++)
 957		if(keysym == keys[i].keysym
 958		&& CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
 959		{
 960			if(keys[i].func)
 961				keys[i].func(keys[i].arg);
 962		}
 963}
 964
 965void
 966killclient(const char *arg) {
 967	XEvent ev;
 968
 969	if(!sel)
 970		return;
 971	if(isprotodel(sel)) {
 972		ev.type = ClientMessage;
 973		ev.xclient.window = sel->win;
 974		ev.xclient.message_type = wmatom[WMProtocols];
 975		ev.xclient.format = 32;
 976		ev.xclient.data.l[0] = wmatom[WMDelete];
 977		ev.xclient.data.l[1] = CurrentTime;
 978		XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
 979	}
 980	else
 981		XKillClient(dpy, sel->win);
 982}
 983
 984void
 985manage(Window w, XWindowAttributes *wa) {
 986	Client *c, *t = NULL;
 987	Status rettrans;
 988	Window trans;
 989	XWindowChanges wc;
 990
 991	c = emallocz(sizeof(Client));
 992	c->tags = emallocz(TAGSZ);
 993	c->win = w;
 994
 995	/* geometry */
 996	c->x = wa->x;
 997	c->y = wa->y;
 998	c->w = wa->width;
 999	c->h = wa->height;
1000	c->oldborder = wa->border_width;
1001	if(c->w == sw && c->h == sh) {
1002		c->x = sx;
1003		c->y = sy;
1004		c->border = wa->border_width;
1005	}
1006	else {
1007		if(c->x + c->w + 2 * c->border > wx + ww)
1008			c->x = wx + ww - c->w - 2 * c->border;
1009		if(c->y + c->h + 2 * c->border > wy + wh)
1010			c->y = wy + wh - c->h - 2 * c->border;
1011		if(c->x < wx)
1012			c->x = wx;
1013		if(c->y < wy)
1014			c->y = wy;
1015		c->border = BORDERPX;
1016	}
1017
1018	wc.border_width = c->border;
1019	XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1020	XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1021	configure(c); /* propagates border_width, if size doesn't change */
1022	updatesizehints(c);
1023	XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
1024	grabbuttons(c, False);
1025	updatetitle(c);
1026	if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
1027		for(t = clients; t && t->win != trans; t = t->next);
1028	if(t)
1029		memcpy(c->tags, t->tags, TAGSZ);
1030	else
1031		applyrules(c);
1032	if(!c->isfloating)
1033		c->isfloating = (rettrans == Success) || c->isfixed;
1034	attach(c);
1035	attachstack(c);
1036	XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
1037	ban(c);
1038	XMapWindow(dpy, c->win);
1039	setclientstate(c, NormalState);
1040	arrange();
1041}
1042
1043void
1044mappingnotify(XEvent *e) {
1045	XMappingEvent *ev = &e->xmapping;
1046
1047	XRefreshKeyboardMapping(ev);
1048	if(ev->request == MappingKeyboard)
1049		grabkeys();
1050}
1051
1052void
1053maprequest(XEvent *e) {
1054	static XWindowAttributes wa;
1055	XMapRequestEvent *ev = &e->xmaprequest;
1056
1057	if(!XGetWindowAttributes(dpy, ev->window, &wa))
1058		return;
1059	if(wa.override_redirect)
1060		return;
1061	if(!getclient(ev->window))
1062		manage(ev->window, &wa);
1063}
1064
1065void
1066monocle(void) {
1067	Client *c;
1068
1069	for(c = clients; c; c = c->next)
1070		if(isvisible(c))
1071			resize(c, mox, moy, mow, moh, RESIZEHINTS);
1072}
1073
1074void
1075movemouse(Client *c) {
1076	int x1, y1, ocx, ocy, di, nx, ny;
1077	unsigned int dui;
1078	Window dummy;
1079	XEvent ev;
1080
1081	ocx = nx = c->x;
1082	ocy = ny = c->y;
1083	if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1084			None, cursor[CurMove], CurrentTime) != GrabSuccess)
1085		return;
1086	XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1087	for(;;) {
1088		XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1089		switch (ev.type) {
1090		case ButtonRelease:
1091			XUngrabPointer(dpy, CurrentTime);
1092			return;
1093		case ConfigureRequest:
1094		case Expose:
1095		case MapRequest:
1096			handler[ev.type](&ev);
1097			break;
1098		case MotionNotify:
1099			XSync(dpy, False);
1100			nx = ocx + (ev.xmotion.x - x1);
1101			ny = ocy + (ev.xmotion.y - y1);
1102			if(abs(wx - nx) < SNAP)
1103				nx = wx;
1104			else if(abs((wx + ww) - (nx + c->w + 2 * c->border)) < SNAP)
1105				nx = wx + ww - c->w - 2 * c->border;
1106			if(abs(wy - ny) < SNAP)
1107				ny = wy;
1108			else if(abs((wy + wh) - (ny + c->h + 2 * c->border)) < SNAP)
1109				ny = wy + wh - c->h - 2 * c->border;
1110			if(!c->isfloating && !lt->isfloating && (abs(nx - c->x) > SNAP || abs(ny - c->y) > SNAP))
1111				togglefloating(NULL);
1112			if((lt->isfloating) || c->isfloating)
1113				resize(c, nx, ny, c->w, c->h, False);
1114			break;
1115		}
1116	}
1117}
1118
1119Client *
1120nexttiled(Client *c) {
1121	for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1122	return c;
1123}
1124
1125void
1126propertynotify(XEvent *e) {
1127	Client *c;
1128	Window trans;
1129	XPropertyEvent *ev = &e->xproperty;
1130
1131	if(ev->state == PropertyDelete)
1132		return; /* ignore */
1133	if((c = getclient(ev->window))) {
1134		switch (ev->atom) {
1135		default: break;
1136		case XA_WM_TRANSIENT_FOR:
1137			XGetTransientForHint(dpy, c->win, &trans);
1138			if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1139				arrange();
1140			break;
1141		case XA_WM_NORMAL_HINTS:
1142			updatesizehints(c);
1143			break;
1144		case XA_WM_HINTS:
1145			updatewmhints(c);
1146			drawbar();
1147			break;
1148		}
1149		if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1150			updatetitle(c);
1151			if(c == sel)
1152				drawbar();
1153		}
1154	}
1155}
1156
1157void
1158quit(const char *arg) {
1159	readin = running = False;
1160}
1161
1162void
1163reapply(const char *arg) {
1164	static Bool zerotags[LENGTH(tags)] = { 0 };
1165	Client *c;
1166
1167	for(c = clients; c; c = c->next) {
1168		memcpy(c->tags, zerotags, sizeof zerotags);
1169		applyrules(c);
1170	}
1171	arrange();
1172}
1173
1174void
1175resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1176	XWindowChanges wc;
1177
1178	if(sizehints) {
1179		/* set minimum possible */
1180		if (w < 1)
1181			w = 1;
1182		if (h < 1)
1183			h = 1;
1184
1185		/* temporarily remove base dimensions */
1186		w -= c->basew;
1187		h -= c->baseh;
1188
1189		/* adjust for aspect limits */
1190		if (c->minay > 0 && c->maxay > 0 && c->minax > 0 && c->maxax > 0) {
1191			if (w * c->maxay > h * c->maxax)
1192				w = h * c->maxax / c->maxay;
1193			else if (w * c->minay < h * c->minax)
1194				h = w * c->minay / c->minax;
1195		}
1196
1197		/* adjust for increment value */
1198		if(c->incw)
1199			w -= w % c->incw;
1200		if(c->inch)
1201			h -= h % c->inch;
1202
1203		/* restore base dimensions */
1204		w += c->basew;
1205		h += c->baseh;
1206
1207		if(c->minw > 0 && w < c->minw)
1208			w = c->minw;
1209		if(c->minh > 0 && h < c->minh)
1210			h = c->minh;
1211		if(c->maxw > 0 && w > c->maxw)
1212			w = c->maxw;
1213		if(c->maxh > 0 && h > c->maxh)
1214			h = c->maxh;
1215	}
1216	if(w <= 0 || h <= 0)
1217		return;
1218	if(x > sx + sw)
1219		x = sw - w - 2 * c->border;
1220	if(y > sy + sh)
1221		y = sh - h - 2 * c->border;
1222	if(x + w + 2 * c->border < sx)
1223		x = sx;
1224	if(y + h + 2 * c->border < sy)
1225		y = sy;
1226	if(c->x != x || c->y != y || c->w != w || c->h != h) {
1227		c->x = wc.x = x;
1228		c->y = wc.y = y;
1229		c->w = wc.width = w;
1230		c->h = wc.height = h;
1231		wc.border_width = c->border;
1232		XConfigureWindow(dpy, c->win,
1233				CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1234		configure(c);
1235		XSync(dpy, False);
1236	}
1237}
1238
1239void
1240resizemouse(Client *c) {
1241	int ocx, ocy;
1242	int nw, nh;
1243	XEvent ev;
1244
1245	ocx = c->x;
1246	ocy = c->y;
1247	if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1248			None, cursor[CurResize], CurrentTime) != GrabSuccess)
1249		return;
1250	XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
1251	for(;;) {
1252		XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1253		switch(ev.type) {
1254		case ButtonRelease:
1255			XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1256					c->w + c->border - 1, c->h + c->border - 1);
1257			XUngrabPointer(dpy, CurrentTime);
1258			while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1259			return;
1260		case ConfigureRequest:
1261		case Expose:
1262		case MapRequest:
1263			handler[ev.type](&ev);
1264			break;
1265		case MotionNotify:
1266			XSync(dpy, False);
1267			if((nw = ev.xmotion.x - ocx - 2 * c->border + 1) <= 0)
1268				nw = 1;
1269			if((nh = ev.xmotion.y - ocy - 2 * c->border + 1) <= 0)
1270				nh = 1;
1271			if(!c->isfloating && !lt->isfloating && (abs(nw - c->w) > SNAP || abs(nh - c->h) > SNAP))
1272				togglefloating(NULL);
1273			if((lt->isfloating) || c->isfloating)
1274				resize(c, c->x, c->y, nw, nh, True);
1275			break;
1276		}
1277	}
1278}
1279
1280void
1281restack(void) {
1282	Client *c;
1283	XEvent ev;
1284	XWindowChanges wc;
1285
1286	drawbar();
1287	if(!sel)
1288		return;
1289	if(sel->isfloating || lt->isfloating)
1290		XRaiseWindow(dpy, sel->win);
1291	if(!lt->isfloating) {
1292		wc.stack_mode = Below;
1293		wc.sibling = barwin;
1294		if(!sel->isfloating) {
1295			XConfigureWindow(dpy, sel->win, CWSibling|CWStackMode, &wc);
1296			wc.sibling = sel->win;
1297		}
1298		for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
1299			if(c == sel)
1300				continue;
1301			XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1302			wc.sibling = c->win;
1303		}
1304	}
1305	XSync(dpy, False);
1306	while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1307}
1308
1309void
1310run(void) {
1311	char *p;
1312	char sbuf[sizeof stext];
1313	fd_set rd;
1314	int r, xfd;
1315	unsigned int len, offset;
1316	XEvent ev;
1317
1318	/* main event loop, also reads status text from stdin */
1319	XSync(dpy, False);
1320	xfd = ConnectionNumber(dpy);
1321	readin = True;
1322	offset = 0;
1323	len = sizeof stext - 1;
1324	sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1325	while(running) {
1326		FD_ZERO(&rd);
1327		if(readin)
1328			FD_SET(STDIN_FILENO, &rd);
1329		FD_SET(xfd, &rd);
1330		if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1331			if(errno == EINTR)
1332				continue;
1333			eprint("select failed\n");
1334		}
1335		if(FD_ISSET(STDIN_FILENO, &rd)) {
1336			switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1337			case -1:
1338				strncpy(stext, strerror(errno), len);
1339				readin = False;
1340				break;
1341			case 0:
1342				strncpy(stext, "EOF", 4);
1343				readin = False;
1344				break;
1345			default:
1346				for(p = sbuf + offset; r > 0; p++, r--, offset++)
1347					if(*p == '\n' || *p == '\0') {
1348						*p = '\0';
1349						strncpy(stext, sbuf, len);
1350						p += r - 1; /* p is sbuf + offset + r - 1 */
1351						for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1352						offset = r;
1353						if(r)
1354							memmove(sbuf, p - r + 1, r);
1355						break;
1356					}
1357				break;
1358			}
1359			drawbar();
1360		}
1361		while(XPending(dpy)) {
1362			XNextEvent(dpy, &ev);
1363			if(handler[ev.type])
1364				(handler[ev.type])(&ev); /* call handler */
1365		}
1366	}
1367}
1368
1369void
1370scan(void) {
1371	unsigned int i, num;
1372	Window *wins, d1, d2;
1373	XWindowAttributes wa;
1374
1375	wins = NULL;
1376	if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1377		for(i = 0; i < num; i++) {
1378			if(!XGetWindowAttributes(dpy, wins[i], &wa)
1379					|| wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1380				continue;
1381			if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1382				manage(wins[i], &wa);
1383		}
1384		for(i = 0; i < num; i++) { /* now the transients */
1385			if(!XGetWindowAttributes(dpy, wins[i], &wa))
1386				continue;
1387			if(XGetTransientForHint(dpy, wins[i], &d1)
1388					&& (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1389				manage(wins[i], &wa);
1390		}
1391	}
1392	if(wins)
1393		XFree(wins);
1394}
1395
1396void
1397setclientstate(Client *c, long state) {
1398	long data[] = {state, None};
1399
1400	XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1401			PropModeReplace, (unsigned char *)data, 2);
1402}
1403
1404void
1405setgeom(const char *arg) {
1406	unsigned int i;
1407
1408	for(i = 0; arg && i < LENGTH(geoms); i++)
1409		if(!strcmp(geoms[i].symbol, arg))
1410			break;
1411	if(i == LENGTH(geoms))
1412		return;
1413	geom = &geoms[i];
1414	geom->apply();
1415	updatebarpos();
1416	arrange();
1417}
1418
1419void
1420setlayout(const char *arg) {
1421	static Layout *revert = 0;
1422	unsigned int i;
1423
1424	if(!arg)
1425		return;
1426	for(i = 0; i < LENGTH(layouts); i++)
1427		if(!strcmp(arg, layouts[i].symbol))
1428			break;
1429	if(i == LENGTH(layouts))
1430		return;
1431	if(revert && &layouts[i] == lt)
1432		lt = revert;
1433	else {
1434		revert = lt;
1435		lt = &layouts[i];
1436	}
1437	if(sel)
1438		arrange();
1439	else
1440		drawbar();
1441}
1442
1443void
1444setup(void) {
1445	unsigned int i;
1446	XSetWindowAttributes wa;
1447
1448	/* init screen */
1449	screen = DefaultScreen(dpy);
1450	root = RootWindow(dpy, screen);
1451	initfont(FONT);
1452
1453	/* apply default geometry */
1454	sx = 0;
1455	sy = 0;
1456	sw = DisplayWidth(dpy, screen);
1457	sh = DisplayHeight(dpy, screen);
1458	bh = dc.font.height + 2;
1459	geom = &geoms[0];
1460	geom->apply();
1461
1462	/* init atoms */
1463	wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1464	wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1465	wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1466	wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1467	netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1468	netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1469
1470	/* init cursors */
1471	wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1472	cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1473	cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1474
1475	/* init appearance */
1476	dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1477	dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1478	dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1479	dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1480	dc.sel[ColBG] = getcolor(SELBGCOLOR);
1481	dc.sel[ColFG] = getcolor(SELFGCOLOR);
1482	initfont(FONT);
1483	dc.h = bh;
1484	dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1485	dc.gc = XCreateGC(dpy, root, 0, 0);
1486	XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1487	if(!dc.font.set)
1488		XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1489
1490	/* init tags */
1491	seltags = emallocz(TAGSZ);
1492	prevtags = emallocz(TAGSZ);
1493	seltags[0] = prevtags[0] = True;
1494
1495	/* init layouts */
1496	lt = &layouts[0];
1497
1498	/* init bar */
1499	for(blw = i = 0; i < LENGTH(layouts); i++) {
1500		i = textw(layouts[i].symbol);
1501		if(i > blw)
1502			blw = i;
1503	}
1504
1505	wa.override_redirect = 1;
1506	wa.background_pixmap = ParentRelative;
1507	wa.event_mask = ButtonPressMask|ExposureMask;
1508
1509	barwin = XCreateWindow(dpy, root, bx, by, bw, bh, 0, DefaultDepth(dpy, screen),
1510				CopyFromParent, DefaultVisual(dpy, screen),
1511				CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1512	XDefineCursor(dpy, barwin, cursor[CurNormal]);
1513	XMapRaised(dpy, barwin);
1514	strcpy(stext, "dwm-"VERSION);
1515	drawbar();
1516
1517	/* EWMH support per view */
1518	XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1519			PropModeReplace, (unsigned char *) netatom, NetLast);
1520
1521	/* select for events */
1522	wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1523			|EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1524	XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1525	XSelectInput(dpy, root, wa.event_mask);
1526
1527
1528	/* grab keys */
1529	grabkeys();
1530}
1531
1532void
1533spawn(const char *arg) {
1534	static char *shell = NULL;
1535
1536	if(!shell && !(shell = getenv("SHELL")))
1537		shell = "/bin/sh";
1538	if(!arg)
1539		return;
1540	/* The double-fork construct avoids zombie processes and keeps the code
1541	 * clean from stupid signal handlers. */
1542	if(fork() == 0) {
1543		if(fork() == 0) {
1544			if(dpy)
1545				close(ConnectionNumber(dpy));
1546			setsid();
1547			execl(shell, shell, "-c", arg, (char *)NULL);
1548			fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1549			perror(" failed");
1550		}
1551		exit(0);
1552	}
1553	wait(0);
1554}
1555
1556void
1557tag(const char *arg) {
1558	unsigned int i;
1559
1560	if(!sel)
1561		return;
1562	for(i = 0; i < LENGTH(tags); i++)
1563		sel->tags[i] = (NULL == arg);
1564	sel->tags[idxoftag(arg)] = True;
1565	arrange();
1566}
1567
1568unsigned int
1569textnw(const char *text, unsigned int len) {
1570	XRectangle r;
1571
1572	if(dc.font.set) {
1573		XmbTextExtents(dc.font.set, text, len, NULL, &r);
1574		return r.width;
1575	}
1576	return XTextWidth(dc.font.xfont, text, len);
1577}
1578
1579unsigned int
1580textw(const char *text) {
1581	return textnw(text, strlen(text)) + dc.font.height;
1582}
1583
1584void
1585tileh(void) {
1586	int x, w;
1587	unsigned int i, n = counttiled();
1588	Client *c;
1589
1590	if(n == 0)
1591		return;
1592	c = tilemaster(n);
1593	if(--n == 0)
1594		return;
1595
1596	x = tx;
1597	w = tw / n;
1598	if(w < bh)
1599		w = tw;
1600
1601	for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1602		if(i + 1 == n) /* remainder */
1603			tileresize(c, x, ty, (tx + tw) - x - 2 * c->border, th - 2 * c->border);
1604		else
1605			tileresize(c, x, ty, w - 2 * c->border, th - 2 * c->border);
1606		if(w != tw)
1607			x = c->x + c->w + 2 * c->border;
1608	}
1609}
1610
1611Client *
1612tilemaster(unsigned int n) {
1613	Client *c = nexttiled(clients);
1614
1615	if(n == 1)
1616		tileresize(c, mox, moy, mow - 2 * c->border, moh - 2 * c->border);
1617	else
1618		tileresize(c, mx, my, mw - 2 * c->border, mh - 2 * c->border);
1619	return c;
1620}
1621
1622void
1623tileresize(Client *c, int x, int y, int w, int h) {
1624	resize(c, x, y, w, h, RESIZEHINTS);
1625	if((RESIZEHINTS) && ((c->h < bh) || (c->h > h) || (c->w < bh) || (c->w > w)))
1626		/* client doesn't accept size constraints */
1627		resize(c, x, y, w, h, False);
1628}
1629
1630void
1631tilev(void) {
1632	int y, h;
1633	unsigned int i, n = counttiled();
1634	Client *c;
1635
1636	if(n == 0)
1637		return;
1638	c = tilemaster(n);
1639	if(--n == 0)
1640		return;
1641
1642	y = ty;
1643	h = th / n;
1644	if(h < bh)
1645		h = th;
1646
1647	for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1648		if(i + 1 == n) /* remainder */
1649			tileresize(c, tx, y, tw - 2 * c->border, (ty + th) - y - 2 * c->border);
1650		else
1651			tileresize(c, tx, y, tw - 2 * c->border, h - 2 * c->border);
1652		if(h != th)
1653			y = c->y + c->h + 2 * c->border;
1654	}
1655}
1656
1657void
1658togglefloating(const char *arg) {
1659	if(!sel)
1660		return;
1661	sel->isfloating = !sel->isfloating;
1662	if(sel->isfloating)
1663		resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1664	arrange();
1665}
1666
1667void
1668toggletag(const char *arg) {
1669	unsigned int i, j;
1670
1671	if(!sel)
1672		return;
1673	i = idxoftag(arg);
1674	sel->tags[i] = !sel->tags[i];
1675	for(j = 0; j < LENGTH(tags) && !sel->tags[j]; j++);
1676	if(j == LENGTH(tags))
1677		sel->tags[i] = True; /* at least one tag must be enabled */
1678	arrange();
1679}
1680
1681void
1682toggleview(const char *arg) {
1683	unsigned int i, j;
1684
1685	i = idxoftag(arg);
1686	seltags[i] = !seltags[i];
1687	for(j = 0; j < LENGTH(tags) && !seltags[j]; j++);
1688	if(j == LENGTH(tags))
1689		seltags[i] = True; /* at least one tag must be viewed */
1690	arrange();
1691}
1692
1693void
1694unban(Client *c) {
1695	if(!c->isbanned)
1696		return;
1697	XMoveWindow(dpy, c->win, c->x, c->y);
1698	c->isbanned = False;
1699}
1700
1701void
1702unmanage(Client *c) {
1703	XWindowChanges wc;
1704
1705	wc.border_width = c->oldborder;
1706	/* The server grab construct avoids race conditions. */
1707	XGrabServer(dpy);
1708	XSetErrorHandler(xerrordummy);
1709	XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1710	detach(c);
1711	detachstack(c);
1712	if(sel == c)
1713		focus(NULL);
1714	XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1715	setclientstate(c, WithdrawnState);
1716	free(c->tags);
1717	free(c);
1718	XSync(dpy, False);
1719	XSetErrorHandler(xerror);
1720	XUngrabServer(dpy);
1721	arrange();
1722}
1723
1724void
1725unmapnotify(XEvent *e) {
1726	Client *c;
1727	XUnmapEvent *ev = &e->xunmap;
1728
1729	if((c = getclient(ev->window)))
1730		unmanage(c);
1731}
1732
1733void
1734updatebarpos(void) {
1735
1736	if(dc.drawable != 0)
1737		XFreePixmap(dpy, dc.drawable);
1738	dc.drawable = XCreatePixmap(dpy, root, bw, bh, DefaultDepth(dpy, screen));
1739	XMoveResizeWindow(dpy, barwin, bx, by, bw, bh);
1740}
1741
1742void
1743updatesizehints(Client *c) {
1744	long msize;
1745	XSizeHints size;
1746
1747	if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1748		size.flags = PSize;
1749	c->flags = size.flags;
1750	if(c->flags & PBaseSize) {
1751		c->basew = size.base_width;
1752		c->baseh = size.base_height;
1753	}
1754	else if(c->flags & PMinSize) {
1755		c->basew = size.min_width;
1756		c->baseh = size.min_height;
1757	}
1758	else
1759		c->basew = c->baseh = 0;
1760	if(c->flags & PResizeInc) {
1761		c->incw = size.width_inc;
1762		c->inch = size.height_inc;
1763	}
1764	else
1765		c->incw = c->inch = 0;
1766	if(c->flags & PMaxSize) {
1767		c->maxw = size.max_width;
1768		c->maxh = size.max_height;
1769	}
1770	else
1771		c->maxw = c->maxh = 0;
1772	if(c->flags & PMinSize) {
1773		c->minw = size.min_width;
1774		c->minh = size.min_height;
1775	}
1776	else if(c->flags & PBaseSize) {
1777		c->minw = size.base_width;
1778		c->minh = size.base_height;
1779	}
1780	else
1781		c->minw = c->minh = 0;
1782	if(c->flags & PAspect) {
1783		c->minax = size.min_aspect.x;
1784		c->maxax = size.max_aspect.x;
1785		c->minay = size.min_aspect.y;
1786		c->maxay = size.max_aspect.y;
1787	}
1788	else
1789		c->minax = c->maxax = c->minay = c->maxay = 0;
1790	c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1791			&& c->maxw == c->minw && c->maxh == c->minh);
1792}
1793
1794void
1795updatetitle(Client *c) {
1796	if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1797		gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1798}
1799
1800void
1801updatewmhints(Client *c) {
1802	XWMHints *wmh;
1803
1804	if((wmh = XGetWMHints(dpy, c->win))) {
1805		if(c == sel)
1806			sel->isurgent = False;
1807		else
1808			c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1809		XFree(wmh);
1810	}
1811}
1812
1813
1814void
1815view(const char *arg) {
1816	unsigned int i;
1817
1818	for(i = 0; i < LENGTH(tags); i++)
1819		tmp[i] = (NULL == arg);
1820	tmp[idxoftag(arg)] = True;
1821
1822	if(memcmp(seltags, tmp, TAGSZ) != 0) {
1823		memcpy(prevtags, seltags, TAGSZ);
1824		memcpy(seltags, tmp, TAGSZ);
1825		arrange();
1826	}
1827}
1828
1829void
1830viewprevtag(const char *arg) {
1831
1832	memcpy(tmp, seltags, TAGSZ);
1833	memcpy(seltags, prevtags, TAGSZ);
1834	memcpy(prevtags, tmp, TAGSZ);
1835	arrange();
1836}
1837
1838/* There's no way to check accesses to destroyed windows, thus those cases are
1839 * ignored (especially on UnmapNotify's).  Other types of errors call Xlibs
1840 * default error handler, which may call exit.  */
1841int
1842xerror(Display *dpy, XErrorEvent *ee) {
1843	if(ee->error_code == BadWindow
1844	|| (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1845	|| (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1846	|| (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1847	|| (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1848	|| (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1849	|| (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1850	|| (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1851		return 0;
1852	fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1853		ee->request_code, ee->error_code);
1854	return xerrorxlib(dpy, ee); /* may call exit */
1855}
1856
1857int
1858xerrordummy(Display *dpy, XErrorEvent *ee) {
1859	return 0;
1860}
1861
1862/* Startup Error handler to check if another window manager
1863 * is already running. */
1864int
1865xerrorstart(Display *dpy, XErrorEvent *ee) {
1866	otherwm = True;
1867	return -1;
1868}
1869
1870void
1871zoom(const char *arg) {
1872	Client *c = sel;
1873
1874	if(!sel || lt->isfloating || sel->isfloating)
1875		return;
1876	if(c == nexttiled(clients))
1877		if(!(c = nexttiled(c->next)))
1878			return;
1879	detach(c);
1880	attach(c);
1881	focus(c);
1882	arrange();
1883}
1884
1885int
1886main(int argc, char *argv[]) {
1887	if(argc == 2 && !strcmp("-v", argv[1]))
1888		eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1889	else if(argc != 1)
1890		eprint("usage: dwm [-v]\n");
1891
1892	setlocale(LC_CTYPE, "");
1893	if(!(dpy = XOpenDisplay(0)))
1894		eprint("dwm: cannot open display\n");
1895
1896	checkotherwm();
1897	setup();
1898	scan();
1899	run();
1900	cleanup();
1901
1902	XCloseDisplay(dpy);
1903	return 0;
1904}