all repos — dwm @ 5d2385b636d496645be4c703f04a365c637379c5

fork of suckless dynamic window manager

dwm.c (view raw)

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