all repos — dwm @ a9e145fe6d8af4848e6706131ac41e99003cd997

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