all repos — dwm @ c094ed24735b8bac3c6c7773c76e608cdf3f3354

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