all repos — dwm @ 1f1a1327847c3beedcbc7b57085a8deb8e8ec1f5

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