all repos — dwm @ 9463d5354bc57d0c0086b7328196d7af60ed706d

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