all repos — dwm @ 9449ea3e002990372383835b85ed18ceaf75e400

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