all repos — dwm @ 7bc272a4e4f463c673d12144b3a202db2345e7de

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