all repos — dwm @ c19d4b2930379d0b966a1f082f9db2f3011bea76

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