all repos — dwm @ f1719ac2de2aba270c2460807eacae137d3aeadf

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