all repos — dwm @ d1ce3eac33a636e03a1f5a887897ae8046065ff7

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