all repos — dwm @ c2784e4a38f2305a444abaaf77f39219bd9f56e5

fork of suckless dynamic window manager

dwm.c (view raw)

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