all repos — dwm @ 9fa5ca353801e3537cea354103c3d5a6a53ef76a

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