all repos — dwm @ d5893f55bec202e5dbb5ca4ef1f205cec5eb22c6

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