all repos — dwm @ f22d047d4139ef889e95aabd0103e11357193e5a

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