all repos — dwm @ 721b208478a907e21193a738e8c3ed3f91048c1a

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