all repos — dwm @ 1c80c05587e0f9fc23fb774aa2ef3b297fc8f6d8

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