all repos — dwm @ a6d23fb61c26126685ed8e19a7cb94189bbbd566

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