all repos — dwm @ e7300e0f6f10900b50d15ea3ae8949049431e38b

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