all repos — dwm @ 5e408d8ff65c8609898ad792cdeeac443f28be7a

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