all repos — dwm @ 59aa02a0750ebc82dbcb30897bbf427391edffa0

fork of suckless dynamic window manager

dwm.c (view raw)

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