all repos — dwm @ 858251de46c50498b261b312f2df03531dd9923c

fork of suckless dynamic window manager

dwm.c (view raw)

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