all repos — dwm @ 21cd59a6307ae041ed91098e06d49b3e9036cbea

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