all repos — dwm @ b9dee2c6f172478b7a652cdf9d074ee0bd9acddc

fork of suckless dynamic window manager

dwm.c (view raw)

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