all repos — dwm @ 288cf78b180db846ef2481124f3e7a8fe66c01f2

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 TAGMASK                 ((int)((1LL << LENGTH(tags)) - 1))
  57#define TEXTW(x)                (textnw(x, strlen(x)) + dc.font.height)
  58
  59/* enums */
  60enum { CurNormal, CurResize, CurMove, CurLast };        /* cursor */
  61enum { ColBorder, ColFG, ColBG, ColLast };              /* color */
  62enum { NetSupported, NetWMName, NetLast };              /* EWMH atoms */
  63enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
  64enum { ClkTagBar, ClkLtSymbol, ClkStatusText, ClkWinTitle,
  65       ClkClientWin, ClkRootWin, ClkLast };             /* clicks */
  66
  67typedef union {
  68	int i;
  69	unsigned int ui;
  70	float f;
  71	void *v;
  72} Arg;
  73
  74typedef struct {
  75	unsigned int click;
  76	unsigned int mask;
  77	unsigned int button;
  78	void (*func)(const Arg *arg);
  79	const Arg arg;
  80} Button;
  81
  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	Window win;
  94};
  95
  96typedef struct {
  97	int x, y, w, h;
  98	unsigned long norm[ColLast];
  99	unsigned long sel[ColLast];
 100	Drawable drawable;
 101	GC gc;
 102	struct {
 103		int ascent;
 104		int descent;
 105		int height;
 106		XFontSet set;
 107		XFontStruct *xfont;
 108	} font;
 109} DC; /* draw context */
 110
 111typedef struct {
 112	unsigned int mod;
 113	KeySym keysym;
 114	void (*func)(const Arg *);
 115	const Arg arg;
 116} Key;
 117
 118typedef struct {
 119	const char *symbol;
 120	void (*arrange)(void);
 121} Layout;
 122
 123typedef struct {
 124	const char *class;
 125	const char *instance;
 126	const char *title;
 127	unsigned int tags;
 128	Bool isfloating;
 129} Rule;
 130
 131/* function declarations */
 132static void applyrules(Client *c);
 133static void arrange(void);
 134static void attach(Client *c);
 135static void attachstack(Client *c);
 136static void buttonpress(XEvent *e);
 137static void checkotherwm(void);
 138static void cleanup(void);
 139static void clearurgent(void);
 140static void configure(Client *c);
 141static void configurenotify(XEvent *e);
 142static void configurerequest(XEvent *e);
 143static void destroynotify(XEvent *e);
 144static void detach(Client *c);
 145static void detachstack(Client *c);
 146static void die(const char *errstr, ...);
 147static void drawbar(void);
 148static void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
 149static void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
 150static void enternotify(XEvent *e);
 151static void expose(XEvent *e);
 152static void focus(Client *c);
 153static void focusin(XEvent *e);
 154static void focusstack(const Arg *arg);
 155static Client *getclient(Window w);
 156static unsigned long getcolor(const char *colstr);
 157static long getstate(Window w);
 158static Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
 159static void grabbuttons(Client *c, Bool focused);
 160static void grabkeys(void);
 161static void initfont(const char *fontstr);
 162static Bool isprotodel(Client *c);
 163static void keypress(XEvent *e);
 164static void killclient(const Arg *arg);
 165static void manage(Window w, XWindowAttributes *wa);
 166static void mappingnotify(XEvent *e);
 167static void maprequest(XEvent *e);
 168static void monocle(void);
 169static void movemouse(const Arg *arg);
 170static Client *nexttiled(Client *c);
 171static void propertynotify(XEvent *e);
 172static void quit(const Arg *arg);
 173static void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
 174static void resizemouse(const Arg *arg);
 175static void restack(void);
 176static void run(void);
 177static void scan(void);
 178static void setclientstate(Client *c, long state);
 179static void setlayout(const Arg *arg);
 180static void setmfact(const Arg *arg);
 181static void setup(void);
 182static void spawn(const Arg *arg);
 183static void tag(const Arg *arg);
 184static int textnw(const char *text, unsigned int len);
 185static void tile(void);
 186static void togglebar(const Arg *arg);
 187static void togglefloating(const Arg *arg);
 188static void toggletag(const Arg *arg);
 189static void toggleview(const Arg *arg);
 190static void unmanage(Client *c);
 191static void unmapnotify(XEvent *e);
 192static void updatebar(void);
 193static void updategeom(void);
 194static void updatenumlockmask(void);
 195static void updatesizehints(Client *c);
 196static void updatetitle(Client *c);
 197static void updatewmhints(Client *c);
 198static void view(const Arg *arg);
 199static int xerror(Display *dpy, XErrorEvent *ee);
 200static int xerrordummy(Display *dpy, XErrorEvent *ee);
 201static int xerrorstart(Display *dpy, XErrorEvent *ee);
 202static void zoom(const Arg *arg);
 203
 204/* variables */
 205static char stext[256];
 206static int screen;
 207static int sx, sy, sw, sh; /* X display screen geometry x, y, width, height */ 
 208static int by, bh, blw;    /* bar geometry y, height and layout symbol width */
 209static int wx, wy, ww, wh; /* window area geometry x, y, width, height, bar excluded */
 210static unsigned int seltags = 0, sellt = 0;
 211static int (*xerrorxlib)(Display *, XErrorEvent *);
 212static unsigned int numlockmask = 0;
 213static void (*handler[LASTEvent]) (XEvent *) = {
 214	[ButtonPress] = buttonpress,
 215	[ConfigureRequest] = configurerequest,
 216	[ConfigureNotify] = configurenotify,
 217	[DestroyNotify] = destroynotify,
 218	[EnterNotify] = enternotify,
 219	[Expose] = expose,
 220	[FocusIn] = focusin,
 221	[KeyPress] = keypress,
 222	[MappingNotify] = mappingnotify,
 223	[MapRequest] = maprequest,
 224	[PropertyNotify] = propertynotify,
 225	[UnmapNotify] = unmapnotify
 226};
 227static Atom wmatom[WMLast], netatom[NetLast];
 228static Bool otherwm;
 229static Bool running = True;
 230static unsigned int tagset[] = {1, 1}; /* after start, first tag is selected */
 231static Client *clients = NULL;
 232static Client *sel = NULL;
 233static Client *stack = NULL;
 234static Cursor cursor[CurLast];
 235static Display *dpy;
 236static DC dc = {0};
 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	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	if(!c->tags)
 268		c->tags = tagset[seltags];
 269}
 270
 271void
 272arrange(void) {
 273	Client *c;
 274
 275	for(c = clients; c; c = c->next)
 276		if(ISVISIBLE(c)) {
 277			XMoveWindow(dpy, c->win, c->x, c->y);
 278			if(!lt[sellt]->arrange || c->isfloating)
 279				resize(c, c->x, c->y, c->w, c->h, True);
 280		}
 281		else {
 282			XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
 283		}
 284
 285	focus(NULL);
 286	if(lt[sellt]->arrange)
 287		lt[sellt]->arrange();
 288	restack();
 289}
 290
 291void
 292attach(Client *c) {
 293	c->next = clients;
 294	clients = c;
 295}
 296
 297void
 298attachstack(Client *c) {
 299	c->snext = stack;
 300	stack = c;
 301}
 302
 303void
 304buttonpress(XEvent *e) {
 305	unsigned int i, x, click;
 306	Arg arg = {0};
 307	Client *c;
 308	XButtonPressedEvent *ev = &e->xbutton;
 309
 310	click = ClkRootWin;
 311	if(ev->window == barwin) {
 312		i = x = 0;
 313		do x += TEXTW(tags[i]); while(ev->x >= x && ++i < LENGTH(tags));
 314		if(i < LENGTH(tags)) {
 315			click = ClkTagBar;
 316			arg.ui = 1 << i;
 317		}
 318		else if(ev->x < x + blw)
 319			click = ClkLtSymbol;
 320		else if(ev->x > wx + ww - TEXTW(stext))
 321			click = ClkStatusText;
 322		else
 323			click = ClkWinTitle;
 324	}
 325	else if((c = getclient(ev->window))) {
 326		focus(c);
 327		click = ClkClientWin;
 328	}
 329
 330	for(i = 0; i < LENGTH(buttons); i++)
 331		if(click == buttons[i].click && buttons[i].func && buttons[i].button == ev->button
 332		   && CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
 333			buttons[i].func(click == ClkTagBar ? &arg : &buttons[i].arg);
 334}
 335
 336void
 337checkotherwm(void) {
 338	otherwm = False;
 339	XSetErrorHandler(xerrorstart);
 340
 341	/* this causes an error if some other window manager is running */
 342	XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
 343	XSync(dpy, False);
 344	if(otherwm)
 345		die("dwm: another window manager is already running\n");
 346	XSetErrorHandler(NULL);
 347	xerrorxlib = 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			code = XKeysymToKeycode(dpy, keys[i].keysym);
 766			for(j = 0; j < LENGTH(modifiers); j++)
 767				XGrabKey(dpy, code, keys[i].mod | modifiers[j], root, True,
 768					 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)
 800			XFreeFont(dpy, dc.font.xfont);
 801		dc.font.xfont = NULL;
 802		if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
 803		&& !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
 804			die("error, cannot load font: '%s'\n", fontstr);
 805		dc.font.ascent = dc.font.xfont->ascent;
 806		dc.font.descent = dc.font.xfont->descent;
 807	}
 808	dc.font.height = dc.font.ascent + dc.font.descent;
 809}
 810
 811Bool
 812isprotodel(Client *c) {
 813	int i, n;
 814	Atom *protocols;
 815	Bool ret = False;
 816
 817	if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
 818		for(i = 0; !ret && i < n; i++)
 819			if(protocols[i] == wmatom[WMDelete])
 820				ret = True;
 821		XFree(protocols);
 822	}
 823	return ret;
 824}
 825
 826void
 827keypress(XEvent *e) {
 828	unsigned int i;
 829	KeySym keysym;
 830	XKeyEvent *ev;
 831
 832	ev = &e->xkey;
 833	keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
 834	for(i = 0; i < LENGTH(keys); i++)
 835		if(keysym == keys[i].keysym
 836		   && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
 837		   && keys[i].func)
 838			keys[i].func(&(keys[i].arg));
 839}
 840
 841void
 842killclient(const Arg *arg) {
 843	XEvent ev;
 844
 845	if(!sel)
 846		return;
 847	if(isprotodel(sel)) {
 848		ev.type = ClientMessage;
 849		ev.xclient.window = sel->win;
 850		ev.xclient.message_type = wmatom[WMProtocols];
 851		ev.xclient.format = 32;
 852		ev.xclient.data.l[0] = wmatom[WMDelete];
 853		ev.xclient.data.l[1] = CurrentTime;
 854		XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
 855	}
 856	else
 857		XKillClient(dpy, sel->win);
 858}
 859
 860void
 861manage(Window w, XWindowAttributes *wa) {
 862	Client *c, *t = NULL;
 863	Window trans = None;
 864	XWindowChanges wc;
 865
 866	if(!(c = calloc(1, sizeof(Client))))
 867		die("fatal: could not calloc() %u bytes\n", sizeof(Client));
 868	c->win = w;
 869
 870	/* geometry */
 871	c->x = wa->x;
 872	c->y = wa->y;
 873	c->w = wa->width;
 874	c->h = wa->height;
 875	c->oldbw = wa->border_width;
 876	if(c->w == sw && c->h == sh) {
 877		c->x = sx;
 878		c->y = sy;
 879		c->bw = 0;
 880	}
 881	else {
 882		if(c->x + c->w + 2 * c->bw > sx + sw)
 883			c->x = sx + sw - c->w - 2 * c->bw;
 884		if(c->y + c->h + 2 * c->bw > sy + sh)
 885			c->y = sy + sh - c->h - 2 * c->bw;
 886		c->x = MAX(c->x, sx);
 887		/* only fix client y-offset, if the client center might cover the bar */
 888		c->y = MAX(c->y, ((by == 0) && (c->x + (c->w / 2) >= wx) && (c->x + (c->w / 2) < wx + ww)) ? bh : sy);
 889		c->bw = borderpx;
 890	}
 891
 892	wc.border_width = c->bw;
 893	XConfigureWindow(dpy, w, CWBorderWidth, &wc);
 894	XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
 895	configure(c); /* propagates border_width, if size doesn't change */
 896	updatesizehints(c);
 897	XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
 898	grabbuttons(c, False);
 899	updatetitle(c);
 900	if(XGetTransientForHint(dpy, w, &trans))
 901		t = getclient(trans);
 902	if(t)
 903		c->tags = t->tags;
 904	else
 905		applyrules(c);
 906	if(!c->isfloating)
 907		c->isfloating = trans != None || c->isfixed;
 908	if(c->isfloating)
 909		XRaiseWindow(dpy, c->win);
 910	attach(c);
 911	attachstack(c);
 912	XMoveResizeWindow(dpy, c->win, c->x + 2 * sw, c->y, c->w, c->h); /* some windows require this */
 913	XMapWindow(dpy, c->win);
 914	setclientstate(c, NormalState);
 915	arrange();
 916}
 917
 918void
 919mappingnotify(XEvent *e) {
 920	XMappingEvent *ev = &e->xmapping;
 921
 922	XRefreshKeyboardMapping(ev);
 923	if(ev->request == MappingKeyboard)
 924		grabkeys();
 925}
 926
 927void
 928maprequest(XEvent *e) {
 929	static XWindowAttributes wa;
 930	XMapRequestEvent *ev = &e->xmaprequest;
 931
 932	if(!XGetWindowAttributes(dpy, ev->window, &wa))
 933		return;
 934	if(wa.override_redirect)
 935		return;
 936	if(!getclient(ev->window))
 937		manage(ev->window, &wa);
 938}
 939
 940void
 941monocle(void) {
 942	Client *c;
 943
 944	for(c = nexttiled(clients); c; c = nexttiled(c->next))
 945		resize(c, wx, wy, ww - 2 * c->bw, wh - 2 * c->bw, resizehints);
 946}
 947
 948void
 949movemouse(const Arg *arg) {
 950	int x, y, ocx, ocy, di, nx, ny;
 951	unsigned int dui;
 952	Client *c;
 953	Window dummy;
 954	XEvent ev;
 955
 956	if(!(c = sel))
 957		return;
 958	restack();
 959	ocx = c->x;
 960	ocy = c->y;
 961	if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
 962	None, cursor[CurMove], CurrentTime) != GrabSuccess)
 963		return;
 964	XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui);
 965	do {
 966		XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
 967		switch (ev.type) {
 968		case ConfigureRequest:
 969		case Expose:
 970		case MapRequest:
 971			handler[ev.type](&ev);
 972			break;
 973		case MotionNotify:
 974			XSync(dpy, False);
 975			nx = ocx + (ev.xmotion.x - x);
 976			ny = ocy + (ev.xmotion.y - y);
 977			if(snap && nx >= wx && nx <= wx + ww
 978			        && ny >= wy && ny <= wy + wh) {
 979				if(abs(wx - nx) < snap)
 980					nx = wx;
 981				else if(abs((wx + ww) - (nx + c->w + 2 * c->bw)) < snap)
 982					nx = wx + ww - c->w - 2 * c->bw;
 983				if(abs(wy - ny) < snap)
 984					ny = wy;
 985				else if(abs((wy + wh) - (ny + c->h + 2 * c->bw)) < snap)
 986					ny = wy + wh - c->h - 2 * c->bw;
 987				if(!c->isfloating && lt[sellt]->arrange && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
 988					togglefloating(NULL);
 989			}
 990			if(!lt[sellt]->arrange || c->isfloating)
 991				resize(c, nx, ny, c->w, c->h, False);
 992			break;
 993		}
 994	}
 995	while(ev.type != ButtonRelease);
 996	XUngrabPointer(dpy, CurrentTime);
 997}
 998
 999Client *
1000nexttiled(Client *c) {
1001	for(; c && (c->isfloating || !ISVISIBLE(c)); c = c->next);
1002	return c;
1003}
1004
1005void
1006propertynotify(XEvent *e) {
1007	Client *c;
1008	Window trans;
1009	XPropertyEvent *ev = &e->xproperty;
1010
1011	if(ev->state == PropertyDelete)
1012		return; /* ignore */
1013	if((c = getclient(ev->window))) {
1014		switch (ev->atom) {
1015		default: break;
1016		case XA_WM_TRANSIENT_FOR:
1017			XGetTransientForHint(dpy, c->win, &trans);
1018			if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1019				arrange();
1020			break;
1021		case XA_WM_NORMAL_HINTS:
1022			updatesizehints(c);
1023			break;
1024		case XA_WM_HINTS:
1025			updatewmhints(c);
1026			drawbar();
1027			break;
1028		}
1029		if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1030			updatetitle(c);
1031			if(c == sel)
1032				drawbar();
1033		}
1034	}
1035}
1036
1037void
1038quit(const Arg *arg) {
1039	readin = running = False;
1040}
1041
1042void
1043resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1044	XWindowChanges wc;
1045
1046	if(sizehints) {
1047		/* see last two sentences in ICCCM 4.1.2.3 */
1048		Bool baseismin = c->basew == c->minw && c->baseh == c->minh;
1049
1050		/* set minimum possible */
1051		w = MAX(1, w);
1052		h = MAX(1, h);
1053
1054		if(!baseismin) { /* temporarily remove base dimensions */
1055			w -= c->basew;
1056			h -= c->baseh;
1057		}
1058
1059		/* adjust for aspect limits */
1060		if(c->mina > 0 && c->maxa > 0) {
1061			if(c->maxa < (float)(w / h))
1062				w = h * c->maxa;
1063			else if(c->mina < (float)(h / w))
1064				h = w * c->mina;
1065		}
1066
1067		if(baseismin) { /* increment calculation requires this */
1068			w -= c->basew;
1069			h -= c->baseh;
1070		}
1071
1072		/* adjust for increment value */
1073		if(c->incw)
1074			w -= w % c->incw;
1075		if(c->inch)
1076			h -= h % c->inch;
1077
1078		/* restore base dimensions */
1079		w += c->basew;
1080		h += c->baseh;
1081
1082		w = MAX(w, c->minw);
1083		h = MAX(h, c->minh);
1084
1085		if(c->maxw)
1086			w = MIN(w, c->maxw);
1087
1088		if(c->maxh)
1089			h = MIN(h, c->maxh);
1090	}
1091	if(w <= 0 || h <= 0)
1092		return;
1093	if(x > sx + sw)
1094		x = sw - w - 2 * c->bw;
1095	if(y > sy + sh)
1096		y = sh - h - 2 * c->bw;
1097	if(x + w + 2 * c->bw < sx)
1098		x = sx;
1099	if(y + h + 2 * c->bw < sy)
1100		y = sy;
1101	if(h < bh)
1102		h = bh;
1103	if(w < bh)
1104		w = bh;
1105	if(c->x != x || c->y != y || c->w != w || c->h != h) {
1106		c->x = wc.x = x;
1107		c->y = wc.y = y;
1108		c->w = wc.width = w;
1109		c->h = wc.height = h;
1110		wc.border_width = c->bw;
1111		XConfigureWindow(dpy, c->win,
1112				CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1113		configure(c);
1114		XSync(dpy, False);
1115	}
1116}
1117
1118void
1119resizemouse(const Arg *arg) {
1120	int ocx, ocy;
1121	int nw, nh;
1122	Client *c;
1123	XEvent ev;
1124
1125	if(!(c = sel))
1126		return;
1127	restack();
1128	ocx = c->x;
1129	ocy = c->y;
1130	if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1131	None, cursor[CurResize], CurrentTime) != GrabSuccess)
1132		return;
1133	XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1134	do {
1135		XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1136		switch(ev.type) {
1137		case ConfigureRequest:
1138		case Expose:
1139		case MapRequest:
1140			handler[ev.type](&ev);
1141			break;
1142		case MotionNotify:
1143			XSync(dpy, False);
1144			nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1145			nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1146
1147			if(snap && nw >= wx && nw <= wx + ww
1148			        && nh >= wy && nh <= wy + wh) {
1149				if(!c->isfloating && lt[sellt]->arrange
1150				   && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1151					togglefloating(NULL);
1152			}
1153			if(!lt[sellt]->arrange || c->isfloating)
1154				resize(c, c->x, c->y, nw, nh, True);
1155			break;
1156		}
1157	}
1158	while(ev.type != ButtonRelease);
1159	XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1160	XUngrabPointer(dpy, CurrentTime);
1161	while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1162}
1163
1164void
1165restack(void) {
1166	Client *c;
1167	XEvent ev;
1168	XWindowChanges wc;
1169
1170	drawbar();
1171	if(!sel)
1172		return;
1173	if(sel->isfloating || !lt[sellt]->arrange)
1174		XRaiseWindow(dpy, sel->win);
1175	if(lt[sellt]->arrange) {
1176		wc.stack_mode = Below;
1177		wc.sibling = barwin;
1178		for(c = stack; c; c = c->snext)
1179			if(!c->isfloating && ISVISIBLE(c)) {
1180				XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1181				wc.sibling = c->win;
1182			}
1183	}
1184	XSync(dpy, False);
1185	while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1186}
1187
1188void
1189run(void) {
1190	char *p;
1191	char sbuf[sizeof stext];
1192	fd_set rd;
1193	int r, xfd;
1194	unsigned int len, offset;
1195	XEvent ev;
1196
1197	/* main event loop, also reads status text from stdin */
1198	XSync(dpy, False);
1199	xfd = ConnectionNumber(dpy);
1200	offset = 0;
1201	len = sizeof stext - 1;
1202	sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1203	while(running) {
1204		FD_ZERO(&rd);
1205		if(readin)
1206			FD_SET(STDIN_FILENO, &rd);
1207		FD_SET(xfd, &rd);
1208		if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1209			if(errno == EINTR)
1210				continue;
1211			die("select failed\n");
1212		}
1213		if(FD_ISSET(STDIN_FILENO, &rd)) {
1214			switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1215			case -1:
1216				strncpy(stext, strerror(errno), len);
1217				readin = False;
1218				break;
1219			case 0:
1220				strncpy(stext, "EOF", 4);
1221				readin = False;
1222				break;
1223			default:
1224				for(p = sbuf + offset; r > 0; p++, r--, offset++)
1225					if(*p == '\n' || *p == '\0') {
1226						*p = '\0';
1227						strncpy(stext, sbuf, len);
1228						p += r - 1; /* p is sbuf + offset + r - 1 */
1229						for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1230						offset = r;
1231						if(r)
1232							memmove(sbuf, p - r + 1, r);
1233						break;
1234					}
1235				break;
1236			}
1237			drawbar();
1238		}
1239		while(XPending(dpy)) {
1240			XNextEvent(dpy, &ev);
1241			if(handler[ev.type])
1242				(handler[ev.type])(&ev); /* call handler */
1243		}
1244	}
1245}
1246
1247void
1248scan(void) {
1249	unsigned int i, num;
1250	Window d1, d2, *wins = NULL;
1251	XWindowAttributes wa;
1252
1253	if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1254		for(i = 0; i < num; i++) {
1255			if(!XGetWindowAttributes(dpy, wins[i], &wa)
1256			|| wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1257				continue;
1258			if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1259				manage(wins[i], &wa);
1260		}
1261		for(i = 0; i < num; i++) { /* now the transients */
1262			if(!XGetWindowAttributes(dpy, wins[i], &wa))
1263				continue;
1264			if(XGetTransientForHint(dpy, wins[i], &d1)
1265			&& (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1266				manage(wins[i], &wa);
1267		}
1268		if(wins)
1269			XFree(wins);
1270	}
1271}
1272
1273void
1274setclientstate(Client *c, long state) {
1275	long data[] = {state, None};
1276
1277	XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1278			PropModeReplace, (unsigned char *)data, 2);
1279}
1280
1281void
1282setlayout(const Arg *arg) {
1283	if(!arg || !arg->v || arg->v != lt[sellt])
1284		sellt ^= 1;
1285	if(arg && arg->v)
1286		lt[sellt] = (Layout *)arg->v;
1287	if(sel)
1288		arrange();
1289	else
1290		drawbar();
1291}
1292
1293/* arg > 1.0 will set mfact absolutly */
1294void
1295setmfact(const Arg *arg) {
1296	float f;
1297
1298	if(!arg || !lt[sellt]->arrange)
1299		return;
1300	f = arg->f < 1.0 ? arg->f + mfact : arg->f - 1.0;
1301	if(f < 0.1 || f > 0.9)
1302		return;
1303	mfact = f;
1304	arrange();
1305}
1306
1307void
1308setup(void) {
1309	unsigned int i;
1310	int w;
1311	XSetWindowAttributes wa;
1312
1313	/* init screen */
1314	screen = DefaultScreen(dpy);
1315	root = RootWindow(dpy, screen);
1316	initfont(font);
1317	sx = 0;
1318	sy = 0;
1319	sw = DisplayWidth(dpy, screen);
1320	sh = DisplayHeight(dpy, screen);
1321	bh = dc.h = dc.font.height + 2;
1322	lt[0] = &layouts[0];
1323	lt[1] = &layouts[1 % LENGTH(layouts)];
1324	updategeom();
1325
1326	/* init atoms */
1327	wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1328	wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1329	wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1330	wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1331	netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1332	netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1333
1334	/* init cursors */
1335	wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1336	cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1337	cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1338
1339	/* init appearance */
1340	dc.norm[ColBorder] = getcolor(normbordercolor);
1341	dc.norm[ColBG] = getcolor(normbgcolor);
1342	dc.norm[ColFG] = getcolor(normfgcolor);
1343	dc.sel[ColBorder] = getcolor(selbordercolor);
1344	dc.sel[ColBG] = getcolor(selbgcolor);
1345	dc.sel[ColFG] = getcolor(selfgcolor);
1346	dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1347	dc.gc = XCreateGC(dpy, root, 0, 0);
1348	XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1349	if(!dc.font.set)
1350		XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1351
1352	/* init bar */
1353	for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1354		w = TEXTW(layouts[i].symbol);
1355		blw = MAX(blw, w);
1356	}
1357
1358	wa.override_redirect = 1;
1359	wa.background_pixmap = ParentRelative;
1360	wa.event_mask = ButtonPressMask|ExposureMask;
1361
1362	barwin = XCreateWindow(dpy, root, wx, by, ww, bh, 0, DefaultDepth(dpy, screen),
1363			CopyFromParent, DefaultVisual(dpy, screen),
1364			CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1365	XDefineCursor(dpy, barwin, cursor[CurNormal]);
1366	XMapRaised(dpy, barwin);
1367	strcpy(stext, "dwm-"VERSION);
1368	drawbar();
1369
1370	/* EWMH support per view */
1371	XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1372			PropModeReplace, (unsigned char *) netatom, NetLast);
1373
1374	/* select for events */
1375	wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask|ButtonPressMask
1376			|EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1377	XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1378	XSelectInput(dpy, root, wa.event_mask);
1379
1380	grabkeys();
1381}
1382
1383void
1384spawn(const Arg *arg) {
1385	/* The double-fork construct avoids zombie processes and keeps the code
1386	 * clean from stupid signal handlers. */
1387	if(fork() == 0) {
1388		if(fork() == 0) {
1389			if(dpy)
1390				close(ConnectionNumber(dpy));
1391			setsid();
1392			execvp(((char **)arg->v)[0], (char **)arg->v);
1393			fprintf(stderr, "dwm: execvp %s", ((char **)arg->v)[0]);
1394			perror(" failed");
1395		}
1396		exit(0);
1397	}
1398	wait(0);
1399}
1400
1401void
1402tag(const Arg *arg) {
1403	if(sel && arg->ui & TAGMASK) {
1404		sel->tags = arg->ui & TAGMASK;
1405		arrange();
1406	}
1407}
1408
1409int
1410textnw(const char *text, unsigned int len) {
1411	XRectangle r;
1412
1413	if(dc.font.set) {
1414		XmbTextExtents(dc.font.set, text, len, NULL, &r);
1415		return r.width;
1416	}
1417	return XTextWidth(dc.font.xfont, text, len);
1418}
1419
1420void
1421tile(void) {
1422	int x, y, h, w, mw;
1423	unsigned int i, n;
1424	Client *c;
1425
1426	for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next), n++);
1427	if(n == 0)
1428		return;
1429
1430	/* master */
1431	c = nexttiled(clients);
1432	mw = mfact * ww;
1433	resize(c, wx, wy, (n == 1 ? ww : mw) - 2 * c->bw, wh - 2 * c->bw, resizehints);
1434
1435	if(--n == 0)
1436		return;
1437
1438	/* tile stack */
1439	x = (wx + mw > c->x + c->w) ? c->x + c->w + 2 * c->bw : wx + mw;
1440	y = wy;
1441	w = (wx + mw > c->x + c->w) ? wx + ww - x : ww - mw;
1442	h = wh / n;
1443	if(h < bh)
1444		h = wh;
1445
1446	for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1447		resize(c, x, y, w - 2 * c->bw, /* remainder */ ((i + 1 == n)
1448		       ? (wy + wh) - y : h) - 2 * c->bw, resizehints);
1449		if(h != wh)
1450			y = c->y + c->h + 2 * c->bw;
1451	}
1452}
1453
1454void
1455togglebar(const Arg *arg) {
1456	showbar = !showbar;
1457	updategeom();
1458	updatebar();
1459	arrange();
1460}
1461
1462void
1463togglefloating(const Arg *arg) {
1464	if(!sel)
1465		return;
1466	sel->isfloating = !sel->isfloating || sel->isfixed;
1467	if(sel->isfloating)
1468		resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1469	arrange();
1470}
1471
1472void
1473toggletag(const Arg *arg) {
1474	unsigned int mask;
1475
1476	if (!sel)
1477		return;
1478	
1479	mask = sel->tags ^ (arg->ui & TAGMASK);
1480	if(sel && mask) {
1481		sel->tags = mask;
1482		arrange();
1483	}
1484}
1485
1486void
1487toggleview(const Arg *arg) {
1488	unsigned int mask = tagset[seltags] ^ (arg->ui & TAGMASK);
1489
1490	if(mask) {
1491		tagset[seltags] = mask;
1492		clearurgent();
1493		arrange();
1494	}
1495}
1496
1497void
1498unmanage(Client *c) {
1499	XWindowChanges wc;
1500
1501	wc.border_width = c->oldbw;
1502	/* The server grab construct avoids race conditions. */
1503	XGrabServer(dpy);
1504	XSetErrorHandler(xerrordummy);
1505	XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1506	detach(c);
1507	detachstack(c);
1508	if(sel == c)
1509		focus(NULL);
1510	XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1511	setclientstate(c, WithdrawnState);
1512	free(c);
1513	XSync(dpy, False);
1514	XSetErrorHandler(xerror);
1515	XUngrabServer(dpy);
1516	arrange();
1517}
1518
1519void
1520unmapnotify(XEvent *e) {
1521	Client *c;
1522	XUnmapEvent *ev = &e->xunmap;
1523
1524	if((c = getclient(ev->window)))
1525		unmanage(c);
1526}
1527
1528void
1529updatebar(void) {
1530	if(dc.drawable != 0)
1531		XFreePixmap(dpy, dc.drawable);
1532	dc.drawable = XCreatePixmap(dpy, root, ww, bh, DefaultDepth(dpy, screen));
1533	XMoveResizeWindow(dpy, barwin, wx, by, ww, bh);
1534}
1535
1536void
1537updategeom(void) {
1538#ifdef XINERAMA
1539	int n, i = 0;
1540	XineramaScreenInfo *info = NULL;
1541
1542	/* window area geometry */
1543	if(XineramaIsActive(dpy) && (info = XineramaQueryScreens(dpy, &n))) { 
1544		if(n > 1) {
1545			int di, x, y;
1546			unsigned int dui;
1547			Window dummy;
1548			if(XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui))
1549				for(i = 0; i < n; i++)
1550					if(INRECT(x, y, info[i].x_org, info[i].y_org, info[i].width, info[i].height))
1551						break;
1552		}
1553		wx = info[i].x_org;
1554		wy = showbar && topbar ?  info[i].y_org + bh : info[i].y_org;
1555		ww = info[i].width;
1556		wh = showbar ? info[i].height - bh : info[i].height;
1557		XFree(info);
1558	}
1559	else
1560#endif
1561	{
1562		wx = sx;
1563		wy = showbar && topbar ? sy + bh : sy;
1564		ww = sw;
1565		wh = showbar ? sh - bh : sh;
1566	}
1567
1568	/* bar position */
1569	by = showbar ? (topbar ? wy - bh : wy + wh) : -bh;
1570}
1571
1572void
1573updatenumlockmask(void) {
1574	unsigned int i, j;
1575	XModifierKeymap *modmap;
1576
1577	numlockmask = 0;
1578	modmap = XGetModifierMapping(dpy);
1579	for(i = 0; i < 8; i++)
1580		for(j = 0; j < modmap->max_keypermod; j++)
1581			if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
1582				numlockmask = (1 << i);
1583	XFreeModifiermap(modmap);
1584}
1585
1586void
1587updatesizehints(Client *c) {
1588	long msize;
1589	XSizeHints size;
1590
1591	XGetWMNormalHints(dpy, c->win, &size, &msize);
1592	if(size.flags & PBaseSize) {
1593		c->basew = size.base_width;
1594		c->baseh = size.base_height;
1595	}
1596	else if(size.flags & PMinSize) {
1597		c->basew = size.min_width;
1598		c->baseh = size.min_height;
1599	}
1600	else
1601		c->basew = c->baseh = 0;
1602	if(size.flags & PResizeInc) {
1603		c->incw = size.width_inc;
1604		c->inch = size.height_inc;
1605	}
1606	else
1607		c->incw = c->inch = 0;
1608	if(size.flags & PMaxSize) {
1609		c->maxw = size.max_width;
1610		c->maxh = size.max_height;
1611	}
1612	else
1613		c->maxw = c->maxh = 0;
1614	if(size.flags & PMinSize) {
1615		c->minw = size.min_width;
1616		c->minh = size.min_height;
1617	}
1618	else if(size.flags & PBaseSize) {
1619		c->minw = size.base_width;
1620		c->minh = size.base_height;
1621	}
1622	else
1623		c->minw = c->minh = 0;
1624	if(size.flags & PAspect) {
1625		c->mina = (float)size.min_aspect.y / (float)size.min_aspect.x;
1626		c->maxa = (float)size.max_aspect.x / (float)size.max_aspect.y;
1627	}
1628	else
1629		c->maxa = c->mina = 0.0;
1630	c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1631			&& c->maxw == c->minw && c->maxh == c->minh);
1632}
1633
1634void
1635updatetitle(Client *c) {
1636	if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1637		gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1638}
1639
1640void
1641updatewmhints(Client *c) {
1642	XWMHints *wmh;
1643
1644	if((wmh = XGetWMHints(dpy, c->win))) {
1645		if(ISVISIBLE(c) && wmh->flags & XUrgencyHint) {
1646			wmh->flags &= ~XUrgencyHint;
1647			XSetWMHints(dpy, c->win, wmh);
1648		}
1649		else
1650			c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1651
1652		XFree(wmh);
1653	}
1654}
1655
1656void
1657view(const Arg *arg) {
1658	if((arg->ui & TAGMASK) == tagset[seltags])
1659		return;
1660	seltags ^= 1; /* toggle sel tagset */
1661	if(arg->ui & TAGMASK)
1662		tagset[seltags] = arg->ui & TAGMASK;
1663	clearurgent();
1664	arrange();
1665}
1666
1667/* There's no way to check accesses to destroyed windows, thus those cases are
1668 * ignored (especially on UnmapNotify's).  Other types of errors call Xlibs
1669 * default error handler, which may call exit.  */
1670int
1671xerror(Display *dpy, XErrorEvent *ee) {
1672	if(ee->error_code == BadWindow
1673	|| (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1674	|| (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1675	|| (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1676	|| (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1677	|| (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1678	|| (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1679	|| (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1680	|| (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1681		return 0;
1682	fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1683			ee->request_code, ee->error_code);
1684	return xerrorxlib(dpy, ee); /* may call exit */
1685}
1686
1687int
1688xerrordummy(Display *dpy, XErrorEvent *ee) {
1689	return 0;
1690}
1691
1692/* Startup Error handler to check if another window manager
1693 * is already running. */
1694int
1695xerrorstart(Display *dpy, XErrorEvent *ee) {
1696	otherwm = True;
1697	return -1;
1698}
1699
1700void
1701zoom(const Arg *arg) {
1702	Client *c = sel;
1703
1704	if(!lt[sellt]->arrange || lt[sellt]->arrange == monocle || (sel && sel->isfloating))
1705		return;
1706	if(c == nexttiled(clients))
1707		if(!c || !(c = nexttiled(c->next)))
1708			return;
1709	detach(c);
1710	attach(c);
1711	focus(c);
1712	arrange();
1713}
1714
1715int
1716main(int argc, char *argv[]) {
1717	if(argc == 2 && !strcmp("-v", argv[1]))
1718		die("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1719	else if(argc != 1)
1720		die("usage: dwm [-v]\n");
1721
1722	if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
1723		fprintf(stderr, "warning: no locale support\n");
1724
1725	if(!(dpy = XOpenDisplay(0)))
1726		die("dwm: cannot open display\n");
1727
1728	checkotherwm();
1729	setup();
1730	scan();
1731	run();
1732	cleanup();
1733
1734	XCloseDisplay(dpy);
1735	return 0;
1736}