all repos — dwm @ 64674c395b89f8d9640163cdcf9c8f4e25ba0e9c

fork of suckless dynamic window manager

dwm.c (view raw)

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