all repos — dwm @ 3da24539976b4474862415606f641d0f69336729

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