all repos — dwm @ 5fa559dbfc6238a911c210ae4124586c6886df23

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