all repos — dwm @ db5db8806f4bbb26bb1259f7ea42d7a826517bbb

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