all repos — dwm @ da1b3fa4379acc7431eaee1331e755ef5335011b

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