all repos — dwm @ a3d8c05a95edbd4dad544c3373301551440c8092

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