all repos — dwm @ 59107755c8ba155501662f3230b1e5725f282c37

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 setlayout(const char *arg);
 164void setup(void);
 165void spawn(const char *arg);
 166void tag(const char *arg);
 167unsigned int textnw(const char *text, unsigned int len);
 168unsigned int textw(const char *text);
 169void tileh(void);
 170void tilehstack(unsigned int n);
 171unsigned int tilemaster(void);
 172void tilev(void);
 173void tilevstack(unsigned int n);
 174void togglefloating(const char *arg);
 175void toggletag(const char *arg);
 176void toggleview(const char *arg);
 177void unban(Client *c);
 178void unmanage(Client *c);
 179void unmapnotify(XEvent *e);
 180void updatesizehints(Client *c);
 181void updatetitle(Client *c);
 182void updatewmhints(Client *c);
 183void view(const char *arg);
 184void viewprevtag(const char *arg);	/* views previous selected tags */
 185int xerror(Display *dpy, XErrorEvent *ee);
 186int xerrordummy(Display *dpy, XErrorEvent *ee);
 187int xerrorstart(Display *dpy, XErrorEvent *ee);
 188void zoom(const char *arg);
 189
 190/* variables */
 191char stext[256], buf[256];
 192int screen, sx, sy, sw, sh;
 193int (*xerrorxlib)(Display *, XErrorEvent *);
 194int bx, by, bw, bh, blw, mx, my, mw, mh, mox, moy, mow, moh, tx, ty, tw, th, wx, wy, ww, wh;
 195unsigned int numlockmask = 0;
 196void (*handler[LASTEvent]) (XEvent *) = {
 197	[ButtonPress] = buttonpress,
 198	[ConfigureRequest] = configurerequest,
 199	[ConfigureNotify] = configurenotify,
 200	[DestroyNotify] = destroynotify,
 201	[EnterNotify] = enternotify,
 202	[Expose] = expose,
 203	[FocusIn] = focusin,
 204	[KeyPress] = keypress,
 205	[MappingNotify] = mappingnotify,
 206	[MapRequest] = maprequest,
 207	[PropertyNotify] = propertynotify,
 208	[UnmapNotify] = unmapnotify
 209};
 210Atom wmatom[WMLast], netatom[NetLast];
 211Bool otherwm, readin;
 212Bool running = True;
 213Bool *prevtags;
 214Bool *seltags;
 215Client *clients = NULL;
 216Client *sel = NULL;
 217Client *stack = NULL;
 218Cursor cursor[CurLast];
 219Display *dpy;
 220DC dc = {0};
 221Layout *lt = NULL;
 222Window root, barwin;
 223
 224/* configuration, allows nested code to access above variables */
 225#include "config.h"
 226#define TAGSZ (LENGTH(tags) * sizeof(Bool))
 227static Bool tmp[LENGTH(tags)];
 228
 229/* function implementations */
 230
 231void
 232applyrules(Client *c) {
 233	unsigned int i;
 234	Bool matched = False;
 235	Rule *r;
 236	XClassHint ch = { 0 };
 237
 238	/* rule matching */
 239	XGetClassHint(dpy, c->win, &ch);
 240	for(i = 0; i < LENGTH(rules); i++) {
 241		r = &rules[i];
 242		if(strstr(c->name, r->prop)
 243		|| (ch.res_class && strstr(ch.res_class, r->prop))
 244		|| (ch.res_name && strstr(ch.res_name, r->prop)))
 245		{
 246			c->isfloating = r->isfloating;
 247			if(r->tag) {
 248				c->tags[idxoftag(r->tag)] = True;
 249				matched = True;
 250			}
 251		}
 252	}
 253	if(ch.res_class)
 254		XFree(ch.res_class);
 255	if(ch.res_name)
 256		XFree(ch.res_name);
 257	if(!matched)
 258		memcpy(c->tags, seltags, TAGSZ);
 259}
 260
 261void
 262arrange(void) {
 263	Client *c;
 264
 265	for(c = clients; c; c = c->next)
 266		if(isvisible(c))
 267			unban(c);
 268		else
 269			ban(c);
 270
 271	focus(NULL);
 272	lt->arrange();
 273	restack();
 274}
 275
 276void
 277attach(Client *c) {
 278	if(clients)
 279		clients->prev = c;
 280	c->next = clients;
 281	clients = c;
 282}
 283
 284void
 285attachstack(Client *c) {
 286	c->snext = stack;
 287	stack = c;
 288}
 289
 290void
 291ban(Client *c) {
 292	if(c->isbanned)
 293		return;
 294	XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
 295	c->isbanned = True;
 296}
 297
 298void
 299buttonpress(XEvent *e) {
 300	unsigned int i, x;
 301	Client *c;
 302	XButtonPressedEvent *ev = &e->xbutton;
 303
 304	if(ev->window == barwin) {
 305		x = 0;
 306		for(i = 0; i < LENGTH(tags); i++) {
 307			x += textw(tags[i]);
 308			if(ev->x < x) {
 309				if(ev->button == Button1) {
 310					if(ev->state & MODKEY)
 311						tag(tags[i]);
 312					else
 313						view(tags[i]);
 314				}
 315				else if(ev->button == Button3) {
 316					if(ev->state & MODKEY)
 317						toggletag(tags[i]);
 318					else
 319						toggleview(tags[i]);
 320				}
 321				return;
 322			}
 323		}
 324	}
 325	else if((c = getclient(ev->window))) {
 326		focus(c);
 327		if(CLEANMASK(ev->state) != MODKEY)
 328			return;
 329		if(ev->button == Button1) {
 330			restack();
 331			movemouse(c);
 332		}
 333		else if(ev->button == Button2) {
 334			if((floating != lt->arrange) && c->isfloating)
 335				togglefloating(NULL);
 336			else
 337				zoom(NULL);
 338		}
 339		else if(ev->button == Button3 && !c->isfixed) {
 340			restack();
 341			resizemouse(c);
 342		}
 343	}
 344}
 345
 346void
 347checkotherwm(void) {
 348	otherwm = False;
 349	XSetErrorHandler(xerrorstart);
 350
 351	/* this causes an error if some other window manager is running */
 352	XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
 353	XSync(dpy, False);
 354	if(otherwm)
 355		eprint("dwm: another window manager is already running\n");
 356	XSync(dpy, False);
 357	XSetErrorHandler(NULL);
 358	xerrorxlib = XSetErrorHandler(xerror);
 359	XSync(dpy, False);
 360}
 361
 362void
 363cleanup(void) {
 364	close(STDIN_FILENO);
 365	while(stack) {
 366		unban(stack);
 367		unmanage(stack);
 368	}
 369	if(dc.font.set)
 370		XFreeFontSet(dpy, dc.font.set);
 371	else
 372		XFreeFont(dpy, dc.font.xfont);
 373	XUngrabKey(dpy, AnyKey, AnyModifier, root);
 374	XFreePixmap(dpy, dc.drawable);
 375	XFreeGC(dpy, dc.gc);
 376	XFreeCursor(dpy, cursor[CurNormal]);
 377	XFreeCursor(dpy, cursor[CurResize]);
 378	XFreeCursor(dpy, cursor[CurMove]);
 379	XDestroyWindow(dpy, barwin);
 380	XSync(dpy, False);
 381	XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
 382}
 383
 384void
 385configure(Client *c) {
 386	XConfigureEvent ce;
 387
 388	ce.type = ConfigureNotify;
 389	ce.display = dpy;
 390	ce.event = c->win;
 391	ce.window = c->win;
 392	ce.x = c->x;
 393	ce.y = c->y;
 394	ce.width = c->w;
 395	ce.height = c->h;
 396	ce.border_width = c->border;
 397	ce.above = None;
 398	ce.override_redirect = False;
 399	XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
 400}
 401
 402void
 403configurenotify(XEvent *e) {
 404	XConfigureEvent *ev = &e->xconfigure;
 405
 406	if(ev->window == root && (ev->width != sw || ev->height != sh)) {
 407		sw = ev->width;
 408		sh = ev->height;
 409		XFreePixmap(dpy, dc.drawable);
 410		dc.drawable = XCreatePixmap(dpy, root, bw, bh, DefaultDepth(dpy, screen));
 411		XMoveResizeWindow(dpy, barwin, bx, by, bw, bh);
 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
1382setlayout(const char *arg) {
1383	static Layout *revert = 0;
1384	unsigned int i;
1385
1386	if(!arg)
1387		return;
1388	for(i = 0; i < LENGTH(layouts); i++)
1389		if(!strcmp(arg, layouts[i].symbol))
1390			break;
1391	if(i == LENGTH(layouts))
1392		return;
1393	if(revert && &layouts[i] == lt)
1394		lt = revert;
1395	else {
1396		revert = lt;
1397		lt = &layouts[i];
1398	}
1399	if(sel)
1400		arrange();
1401	else
1402		drawbar();
1403}
1404
1405void
1406setup(void) {
1407	unsigned int i;
1408	XSetWindowAttributes wa;
1409
1410	/* init screen */
1411	screen = DefaultScreen(dpy);
1412	root = RootWindow(dpy, screen);
1413	sx = 0;
1414	sy = 0;
1415	sw = DisplayWidth(dpy, screen);
1416	sh = DisplayHeight(dpy, screen);
1417
1418	/* init atoms */
1419	wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1420	wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1421	wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1422	wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1423	netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1424	netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1425
1426	/* init cursors */
1427	wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1428	cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1429	cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1430
1431	/* init appearance */
1432	dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1433	dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1434	dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1435	dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1436	dc.sel[ColBG] = getcolor(SELBGCOLOR);
1437	dc.sel[ColFG] = getcolor(SELFGCOLOR);
1438	initfont(FONT);
1439	dc.h = bh = dc.font.height + 2;
1440	dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1441	dc.gc = XCreateGC(dpy, root, 0, 0);
1442	XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1443	if(!dc.font.set)
1444		XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1445
1446	/* init tags */
1447	seltags = emallocz(TAGSZ);
1448	prevtags = emallocz(TAGSZ);
1449	seltags[0] = prevtags[0] = True;
1450
1451	/* init layouts */
1452	lt = &layouts[0];
1453
1454	/* bar position */
1455	bx = BX; by = BY; bw = BW;
1456
1457	/* window area */
1458	wx = WX; wy = WY; ww = WW; wh = WH;
1459
1460	/* master area */
1461	mx = MX; my = MY; mw = MW; mh = MH;
1462
1463	/* tile area */
1464	tx = TX; ty = TY; tw = TW; th = TH;
1465
1466	/* monocle area */
1467	mox = MOX; moy = MOY; mow = MOW; moh = MOH;
1468
1469	/* init bar */
1470	for(blw = i = 0; i < LENGTH(layouts); i++) {
1471		i = textw(layouts[i].symbol);
1472		if(i > blw)
1473			blw = i;
1474	}
1475
1476	wa.override_redirect = 1;
1477	wa.background_pixmap = ParentRelative;
1478	wa.event_mask = ButtonPressMask|ExposureMask;
1479
1480	barwin = XCreateWindow(dpy, root, bx, by, bw, bh, 0, DefaultDepth(dpy, screen),
1481				CopyFromParent, DefaultVisual(dpy, screen),
1482				CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1483	XDefineCursor(dpy, barwin, cursor[CurNormal]);
1484	XMapRaised(dpy, barwin);
1485	strcpy(stext, "dwm-"VERSION);
1486	drawbar();
1487
1488	/* EWMH support per view */
1489	XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1490			PropModeReplace, (unsigned char *) netatom, NetLast);
1491
1492	/* select for events */
1493	wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1494			|EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1495	XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1496	XSelectInput(dpy, root, wa.event_mask);
1497
1498
1499	/* grab keys */
1500	grabkeys();
1501}
1502
1503void
1504spawn(const char *arg) {
1505	static char *shell = NULL;
1506
1507	if(!shell && !(shell = getenv("SHELL")))
1508		shell = "/bin/sh";
1509	if(!arg)
1510		return;
1511	/* The double-fork construct avoids zombie processes and keeps the code
1512	 * clean from stupid signal handlers. */
1513	if(fork() == 0) {
1514		if(fork() == 0) {
1515			if(dpy)
1516				close(ConnectionNumber(dpy));
1517			setsid();
1518			execl(shell, shell, "-c", arg, (char *)NULL);
1519			fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1520			perror(" failed");
1521		}
1522		exit(0);
1523	}
1524	wait(0);
1525}
1526
1527void
1528tag(const char *arg) {
1529	unsigned int i;
1530
1531	if(!sel)
1532		return;
1533	for(i = 0; i < LENGTH(tags); i++)
1534		sel->tags[i] = (NULL == arg);
1535	sel->tags[idxoftag(arg)] = True;
1536	arrange();
1537}
1538
1539unsigned int
1540textnw(const char *text, unsigned int len) {
1541	XRectangle r;
1542
1543	if(dc.font.set) {
1544		XmbTextExtents(dc.font.set, text, len, NULL, &r);
1545		return r.width;
1546	}
1547	return XTextWidth(dc.font.xfont, text, len);
1548}
1549
1550unsigned int
1551textw(const char *text) {
1552	return textnw(text, strlen(text)) + dc.font.height;
1553}
1554
1555void
1556tileresize(Client *c, int x, int y, int w, int h) {
1557	resize(c, x, y, w, h, RESIZEHINTS);
1558	if((RESIZEHINTS) && ((c->h < bh) || (c->h > h) || (c->w < bh) || (c->w > w)))
1559		/* client doesn't accept size constraints */
1560		resize(c, x, y, w, h, False);
1561}
1562
1563void
1564tileh(void) {
1565	tilehstack(tilemaster());
1566}
1567
1568void
1569tilehstack(unsigned int n) {
1570	int i, x, w;
1571	Client *c;
1572
1573	if(n == 0)
1574		return;
1575
1576	x = tx;
1577	w = tw / n;
1578	if(w < bh)
1579		w = tw;
1580
1581	for(i = 0, c = nexttiled(clients); c; c = nexttiled(c->next), i++)
1582		if(i > 0) {
1583			if(i > 1 && i == n) /* remainder */
1584				tileresize(c, x, ty, (tx + tw) - x - 2 * c->border,
1585				              th - 2 * c->border);
1586			else
1587				tileresize(c, x, ty, w - 2 * c->border,
1588				              th - 2 * c->border);
1589			if(w != tw)
1590				x = c->x + c->w + 2 * c->border;
1591		}
1592}
1593
1594unsigned int
1595tilemaster(void) {
1596	unsigned int n;
1597	Client *c, *mc;
1598
1599	for(n = 0, mc = c = nexttiled(clients); c; c = nexttiled(c->next))
1600		n++;
1601	if(n == 0)
1602		return 0;
1603	if(n == 1)
1604		tileresize(mc, mox, moy, mow - 2 * mc->border, moh - 2 * mc->border);
1605	else
1606		tileresize(mc, mx, my, mw - 2 * mc->border, mh - 2 * mc->border);
1607	return n - 1;
1608}
1609
1610void
1611tilev(void) {
1612	tilevstack(tilemaster());
1613}
1614
1615void
1616tilevstack(unsigned int n) {
1617	int i, y, h;
1618	Client *c;
1619
1620	if(n == 0)
1621		return;
1622
1623	y = ty;
1624	h = th / n;
1625	if(h < bh)
1626		h = th;
1627
1628	for(i = 0, c = nexttiled(clients); c; c = nexttiled(c->next), i++)
1629		if(i > 0) {
1630			if(i > 1 && i == n) /* remainder */
1631				tileresize(c, tx, y, tw - 2 * c->border,
1632				              (ty + th) - y - 2 * c->border);
1633			else
1634				tileresize(c, tx, y, tw - 2 * c->border,
1635				              h - 2 * c->border);
1636			if(h != th)
1637				y = c->y + c->h + 2 * c->border;
1638		}
1639}
1640
1641void
1642togglefloating(const char *arg) {
1643	if(!sel)
1644		return;
1645	sel->isfloating = !sel->isfloating;
1646	if(sel->isfloating)
1647		resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1648	arrange();
1649}
1650
1651void
1652toggletag(const char *arg) {
1653	unsigned int i, j;
1654
1655	if(!sel)
1656		return;
1657	i = idxoftag(arg);
1658	sel->tags[i] = !sel->tags[i];
1659	for(j = 0; j < LENGTH(tags) && !sel->tags[j]; j++);
1660	if(j == LENGTH(tags))
1661		sel->tags[i] = True; /* at least one tag must be enabled */
1662	arrange();
1663}
1664
1665void
1666toggleview(const char *arg) {
1667	unsigned int i, j;
1668
1669	i = idxoftag(arg);
1670	seltags[i] = !seltags[i];
1671	for(j = 0; j < LENGTH(tags) && !seltags[j]; j++);
1672	if(j == LENGTH(tags))
1673		seltags[i] = True; /* at least one tag must be viewed */
1674	arrange();
1675}
1676
1677void
1678unban(Client *c) {
1679	if(!c->isbanned)
1680		return;
1681	XMoveWindow(dpy, c->win, c->x, c->y);
1682	c->isbanned = False;
1683}
1684
1685void
1686unmanage(Client *c) {
1687	XWindowChanges wc;
1688
1689	wc.border_width = c->oldborder;
1690	/* The server grab construct avoids race conditions. */
1691	XGrabServer(dpy);
1692	XSetErrorHandler(xerrordummy);
1693	XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1694	detach(c);
1695	detachstack(c);
1696	if(sel == c)
1697		focus(NULL);
1698	XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1699	setclientstate(c, WithdrawnState);
1700	free(c->tags);
1701	free(c);
1702	XSync(dpy, False);
1703	XSetErrorHandler(xerror);
1704	XUngrabServer(dpy);
1705	arrange();
1706}
1707
1708void
1709unmapnotify(XEvent *e) {
1710	Client *c;
1711	XUnmapEvent *ev = &e->xunmap;
1712
1713	if((c = getclient(ev->window)))
1714		unmanage(c);
1715}
1716
1717void
1718updatesizehints(Client *c) {
1719	long msize;
1720	XSizeHints size;
1721
1722	if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1723		size.flags = PSize;
1724	c->flags = size.flags;
1725	if(c->flags & PBaseSize) {
1726		c->basew = size.base_width;
1727		c->baseh = size.base_height;
1728	}
1729	else if(c->flags & PMinSize) {
1730		c->basew = size.min_width;
1731		c->baseh = size.min_height;
1732	}
1733	else
1734		c->basew = c->baseh = 0;
1735	if(c->flags & PResizeInc) {
1736		c->incw = size.width_inc;
1737		c->inch = size.height_inc;
1738	}
1739	else
1740		c->incw = c->inch = 0;
1741	if(c->flags & PMaxSize) {
1742		c->maxw = size.max_width;
1743		c->maxh = size.max_height;
1744	}
1745	else
1746		c->maxw = c->maxh = 0;
1747	if(c->flags & PMinSize) {
1748		c->minw = size.min_width;
1749		c->minh = size.min_height;
1750	}
1751	else if(c->flags & PBaseSize) {
1752		c->minw = size.base_width;
1753		c->minh = size.base_height;
1754	}
1755	else
1756		c->minw = c->minh = 0;
1757	if(c->flags & PAspect) {
1758		c->minax = size.min_aspect.x;
1759		c->maxax = size.max_aspect.x;
1760		c->minay = size.min_aspect.y;
1761		c->maxay = size.max_aspect.y;
1762	}
1763	else
1764		c->minax = c->maxax = c->minay = c->maxay = 0;
1765	c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1766			&& c->maxw == c->minw && c->maxh == c->minh);
1767}
1768
1769void
1770updatetitle(Client *c) {
1771	if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1772		gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1773}
1774
1775void
1776updatewmhints(Client *c) {
1777	XWMHints *wmh;
1778
1779	if((wmh = XGetWMHints(dpy, c->win))) {
1780		if(c == sel)
1781			sel->isurgent = False;
1782		else
1783			c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1784		XFree(wmh);
1785	}
1786}
1787
1788
1789void
1790view(const char *arg) {
1791	unsigned int i;
1792
1793	for(i = 0; i < LENGTH(tags); i++)
1794		tmp[i] = (NULL == arg);
1795	tmp[idxoftag(arg)] = True;
1796
1797	if(memcmp(seltags, tmp, TAGSZ) != 0) {
1798		memcpy(prevtags, seltags, TAGSZ);
1799		memcpy(seltags, tmp, TAGSZ);
1800		arrange();
1801	}
1802}
1803
1804void
1805viewprevtag(const char *arg) {
1806
1807	memcpy(tmp, seltags, TAGSZ);
1808	memcpy(seltags, prevtags, TAGSZ);
1809	memcpy(prevtags, tmp, TAGSZ);
1810	arrange();
1811}
1812
1813/* There's no way to check accesses to destroyed windows, thus those cases are
1814 * ignored (especially on UnmapNotify's).  Other types of errors call Xlibs
1815 * default error handler, which may call exit.  */
1816int
1817xerror(Display *dpy, XErrorEvent *ee) {
1818	if(ee->error_code == BadWindow
1819	|| (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1820	|| (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1821	|| (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1822	|| (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1823	|| (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1824	|| (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1825	|| (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1826		return 0;
1827	fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1828		ee->request_code, ee->error_code);
1829	return xerrorxlib(dpy, ee); /* may call exit */
1830}
1831
1832int
1833xerrordummy(Display *dpy, XErrorEvent *ee) {
1834	return 0;
1835}
1836
1837/* Startup Error handler to check if another window manager
1838 * is already running. */
1839int
1840xerrorstart(Display *dpy, XErrorEvent *ee) {
1841	otherwm = True;
1842	return -1;
1843}
1844
1845void
1846zoom(const char *arg) {
1847	Client *c = sel;
1848
1849	if(!sel || lt->isfloating || sel->isfloating)
1850		return;
1851	if(c == nexttiled(clients))
1852		if(!(c = nexttiled(c->next)))
1853			return;
1854	detach(c);
1855	attach(c);
1856	focus(c);
1857	arrange();
1858}
1859
1860int
1861main(int argc, char *argv[]) {
1862	if(argc == 2 && !strcmp("-v", argv[1]))
1863		eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1864	else if(argc != 1)
1865		eprint("usage: dwm [-v]\n");
1866
1867	setlocale(LC_CTYPE, "");
1868	if(!(dpy = XOpenDisplay(0)))
1869		eprint("dwm: cannot open display\n");
1870
1871	checkotherwm();
1872	setup();
1873	scan();
1874	run();
1875	cleanup();
1876
1877	XCloseDisplay(dpy);
1878	return 0;
1879}