all repos — dwm @ 4380db468aa81f73e3a31f434bc5bd4a2fe35bf0

fork of suckless dynamic window manager

dwm.c (view raw)

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