all repos — dwm @ 0b5c14cf593c82b85570c45beac553dfce2f9689

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