all repos — dwm @ c86ed46a1bbba0635a76d05ebeb839c7fec7f7fc

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