all repos — dwm @ 9a4d07d9de31c7bf3fba83c66d1a09d63848adfc

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