all repos — dwm @ 913333f51840d942bdde891eb2fb3c7f66b83db1

fork of suckless dynamic window manager

dwm.c (view raw)

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