all repos — dwm @ 31da0b7525f4a6f98fb5b3258da86d04387a0382

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 */
  62enum { ClkLtSymbol = 64, ClkStatusText, ClkWinTitle,
  63       ClkClientWin, ClkRootWin, ClkLast };             /* clicks */
  64
  65/* typedefs */
  66typedef unsigned int uint;
  67typedef unsigned long ulong;
  68
  69typedef union {
  70	int i;
  71	uint ui;
  72	float f;
  73	void *v;
  74} Arg;
  75
  76typedef struct {
  77	uint click;
  78	uint mask;
  79	uint button;
  80	void (*func)(const Arg *arg);
  81	const Arg arg;
  82} Button;
  83
  84typedef struct Client Client;
  85struct Client {
  86	char name[256];
  87	float mina, maxa;
  88	int x, y, w, h;
  89	int basew, baseh, incw, inch, maxw, maxh, minw, minh;
  90	int bw, oldbw;
  91	uint tags;
  92	Bool isbanned, isfixed, isfloating, isurgent;
  93	Client *next;
  94	Client *snext;
  95	Window win;
  96};
  97
  98typedef struct {
  99	int x, y, w, h;
 100	ulong norm[ColLast];
 101	ulong sel[ColLast];
 102	Drawable drawable;
 103	GC gc;
 104	struct {
 105		int ascent;
 106		int descent;
 107		int height;
 108		XFontSet set;
 109		XFontStruct *xfont;
 110	} font;
 111} DC; /* draw context */
 112
 113typedef struct {
 114	uint mod;
 115	KeySym keysym;
 116	void (*func)(const Arg *);
 117	const Arg arg;
 118} Key;
 119
 120typedef struct {
 121	const char *symbol;
 122	void (*arrange)(void);
 123} Layout;
 124
 125typedef struct {
 126	const char *class;
 127	const char *instance;
 128	const char *title;
 129	uint tags;
 130	Bool isfloating;
 131} Rule;
 132
 133/* function declarations */
 134static void applyrules(Client *c);
 135static void arrange(void);
 136static void attach(Client *c);
 137static void attachstack(Client *c);
 138static void buttonpress(XEvent *e);
 139static void checkotherwm(void);
 140static void cleanup(void);
 141static void configure(Client *c);
 142static void configurenotify(XEvent *e);
 143static void configurerequest(XEvent *e);
 144static void destroynotify(XEvent *e);
 145static void detach(Client *c);
 146static void detachstack(Client *c);
 147static void drawbar(void);
 148static void drawsquare(Bool filled, Bool empty, Bool invert, ulong col[ColLast]);
 149static void drawtext(const char *text, ulong col[ColLast], Bool invert);
 150static void enternotify(XEvent *e);
 151static void eprint(const char *errstr, ...);
 152static void expose(XEvent *e);
 153static void focus(Client *c);
 154static void focusin(XEvent *e);
 155static void focusstack(const Arg *arg);
 156static Client *getclient(Window w);
 157static ulong getcolor(const char *colstr);
 158static long getstate(Window w);
 159static Bool gettextprop(Window w, Atom atom, char *text, uint size);
 160static void grabbuttons(Client *c, Bool focused);
 161static void grabkeys(void);
 162static void initfont(const char *fontstr);
 163static Bool isoccupied(uint t);
 164static Bool isprotodel(Client *c);
 165static Bool isurgent(uint t);
 166static void keypress(XEvent *e);
 167static void killclient(const Arg *arg);
 168static void manage(Window w, XWindowAttributes *wa);
 169static void mappingnotify(XEvent *e);
 170static void maprequest(XEvent *e);
 171static void monocle(void);
 172static void movemouse(const Arg *arg);
 173static Client *nexttiled(Client *c);
 174static void propertynotify(XEvent *e);
 175static void quit(const Arg *arg);
 176static void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
 177static void resizemouse(const Arg *arg);
 178static void restack(void);
 179static void run(void);
 180static void scan(void);
 181static void setclientstate(Client *c, long state);
 182static void setlayout(const Arg *arg);
 183static void setmfact(const Arg *arg);
 184static void setup(void);
 185static void spawn(const Arg *arg);
 186static void tag(const Arg *arg);
 187static int textnw(const char *text, uint len);
 188static void tile(void);
 189static void togglebar(const Arg *arg);
 190static void togglefloating(const Arg *arg);
 191static void toggletag(const Arg *arg);
 192static void toggleview(const Arg *arg);
 193static void unmanage(Client *c);
 194static void unmapnotify(XEvent *e);
 195static void updatebar(void);
 196static void updategeom(void);
 197static void updatesizehints(Client *c);
 198static void updatetitle(Client *c);
 199static void updatewmhints(Client *c);
 200static void view(const Arg *arg);
 201static int xerror(Display *dpy, XErrorEvent *ee);
 202static int xerrordummy(Display *dpy, XErrorEvent *ee);
 203static int xerrorstart(Display *dpy, XErrorEvent *ee);
 204static void zoom(const Arg *arg);
 205
 206/* variables */
 207static char stext[256];
 208static int screen, sx, sy, sw, sh;
 209static int by, bh, blw, wx, wy, ww, wh;
 210static uint seltags = 0, sellt = 0;
 211static int (*xerrorxlib)(Display *, XErrorEvent *);
 212static uint numlockmask = 0;
 213static void (*handler[LASTEvent]) (XEvent *) = {
 214	[ButtonPress] = buttonpress,
 215	[ConfigureRequest] = configurerequest,
 216	[ConfigureNotify] = configurenotify,
 217	[DestroyNotify] = destroynotify,
 218	[EnterNotify] = enternotify,
 219	[Expose] = expose,
 220	[FocusIn] = focusin,
 221	[KeyPress] = keypress,
 222	[MappingNotify] = mappingnotify,
 223	[MapRequest] = maprequest,
 224	[PropertyNotify] = propertynotify,
 225	[UnmapNotify] = unmapnotify
 226};
 227static Atom wmatom[WMLast], netatom[NetLast];
 228static Bool otherwm, readin;
 229static Bool running = True;
 230static uint tagset[] = {1, 1}; /* after start, first tag is selected */
 231static Client *clients = NULL;
 232static Client *sel = NULL;
 233static Client *stack = NULL;
 234static Cursor cursor[CurLast];
 235static Display *dpy;
 236static DC dc = {0};
 237static Layout *lt[] = { NULL, NULL };
 238static Window root, barwin;
 239/* configuration, allows nested code to access above variables */
 240#include "config.h"
 241
 242/* compile-time check if all tags fit into an uint bit array. */
 243struct NumTags { char limitexceeded[sizeof(uint) * 8 < LENGTH(tags) ? -1 : 1]; };
 244
 245/* function implementations */
 246void
 247applyrules(Client *c) {
 248	uint i;
 249	Rule *r;
 250	XClassHint ch = { 0 };
 251
 252	/* rule matching */
 253	XGetClassHint(dpy, c->win, &ch);
 254	for(i = 0; i < LENGTH(rules); i++) {
 255		r = &rules[i];
 256		if((!r->title || strstr(c->name, r->title))
 257		&& (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
 258		&& (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
 259			c->isfloating = r->isfloating;
 260			c->tags |= r->tags & TAGMASK;
 261		}
 262	}
 263	if(ch.res_class)
 264		XFree(ch.res_class);
 265	if(ch.res_name)
 266		XFree(ch.res_name);
 267	if(!c->tags)
 268		c->tags = tagset[seltags];
 269}
 270
 271void
 272arrange(void) {
 273	Client *c;
 274
 275	for(c = clients; c; c = c->next)
 276		if(c->tags & tagset[seltags]) { /* is visible */
 277			if(!lt[sellt]->arrange || c->isfloating)
 278				resize(c, c->x, c->y, c->w, c->h, True);
 279			c->isbanned = False;
 280		}
 281		else if(!c->isbanned) {
 282			XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
 283			c->isbanned = True;
 284		}
 285
 286	focus(NULL);
 287	if(lt[sellt]->arrange)
 288		lt[sellt]->arrange();
 289	restack();
 290}
 291
 292void
 293attach(Client *c) {
 294	c->next = clients;
 295	clients = c;
 296}
 297
 298void
 299attachstack(Client *c) {
 300	c->snext = stack;
 301	stack = c;
 302}
 303
 304void
 305buttonpress(XEvent *e) {
 306	uint i, x, click;
 307	Client *c;
 308	XButtonPressedEvent *ev = &e->xbutton;
 309
 310	click = ClkRootWin;
 311	if(ev->window == barwin) {
 312		i = x = 0;
 313		do
 314			x += TEXTW(tags[i]);
 315		while(ev->x >= x && ++i < LENGTH(tags));
 316		if(i < LENGTH(tags))
 317			click = i;
 318		else if(ev->x < x + blw)
 319			click = ClkLtSymbol;
 320		else if(ev->x > wx + ww - TEXTW(stext))
 321			click = ClkStatusText;
 322		else
 323			click = ClkWinTitle;
 324	}
 325	else if((c = getclient(ev->window))) {
 326		focus(c);
 327		click = ClkClientWin;
 328	}
 329
 330	for(i = 0; i < LENGTH(buttons); i++)
 331		if(click == buttons[i].click && buttons[i].func && buttons[i].button == ev->button
 332		   && CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
 333			buttons[i].func(&buttons[i].arg);
 334}
 335
 336void
 337checkotherwm(void) {
 338	otherwm = False;
 339	XSetErrorHandler(xerrorstart);
 340
 341	/* this causes an error if some other window manager is running */
 342	XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
 343	XSync(dpy, False);
 344	if(otherwm)
 345		eprint("dwm: another window manager is already running\n");
 346	XSetErrorHandler(NULL);
 347	xerrorxlib = XSetErrorHandler(xerror);
 348	XSync(dpy, False);
 349}
 350
 351void
 352cleanup(void) {
 353	Arg a = {.i = ~0};
 354	Layout foo = { "", NULL };
 355
 356	close(STDIN_FILENO);
 357	view(&a);
 358	lt[sellt] = &foo;
 359	while(stack)
 360		unmanage(stack);
 361	if(dc.font.set)
 362		XFreeFontSet(dpy, dc.font.set);
 363	else
 364		XFreeFont(dpy, dc.font.xfont);
 365	XUngrabKey(dpy, AnyKey, AnyModifier, root);
 366	XFreePixmap(dpy, dc.drawable);
 367	XFreeGC(dpy, dc.gc);
 368	XFreeCursor(dpy, cursor[CurNormal]);
 369	XFreeCursor(dpy, cursor[CurResize]);
 370	XFreeCursor(dpy, cursor[CurMove]);
 371	XDestroyWindow(dpy, barwin);
 372	XSync(dpy, False);
 373	XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
 374}
 375
 376void
 377configure(Client *c) {
 378	XConfigureEvent ce;
 379
 380	ce.type = ConfigureNotify;
 381	ce.display = dpy;
 382	ce.event = c->win;
 383	ce.window = c->win;
 384	ce.x = c->x;
 385	ce.y = c->y;
 386	ce.width = c->w;
 387	ce.height = c->h;
 388	ce.border_width = c->bw;
 389	ce.above = None;
 390	ce.override_redirect = False;
 391	XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
 392}
 393
 394void
 395configurenotify(XEvent *e) {
 396	XConfigureEvent *ev = &e->xconfigure;
 397
 398	if(ev->window == root && (ev->width != sw || ev->height != sh)) {
 399		sw = ev->width;
 400		sh = ev->height;
 401		updategeom();
 402		updatebar();
 403		arrange();
 404	}
 405}
 406
 407void
 408configurerequest(XEvent *e) {
 409	Client *c;
 410	XConfigureRequestEvent *ev = &e->xconfigurerequest;
 411	XWindowChanges wc;
 412
 413	if((c = getclient(ev->window))) {
 414		if(ev->value_mask & CWBorderWidth)
 415			c->bw = ev->border_width;
 416		else if(c->isfloating || !lt[sellt]->arrange) {
 417			if(ev->value_mask & CWX)
 418				c->x = sx + ev->x;
 419			if(ev->value_mask & CWY)
 420				c->y = sy + ev->y;
 421			if(ev->value_mask & CWWidth)
 422				c->w = ev->width;
 423			if(ev->value_mask & CWHeight)
 424				c->h = ev->height;
 425			if((c->x - sx + c->w) > sw && c->isfloating)
 426				c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
 427			if((c->y - sy + c->h) > sh && c->isfloating)
 428				c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
 429			if((ev->value_mask & (CWX|CWY))
 430			&& !(ev->value_mask & (CWWidth|CWHeight)))
 431				configure(c);
 432			if(!c->isbanned)
 433				XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
 434		}
 435		else
 436			configure(c);
 437	}
 438	else {
 439		wc.x = ev->x;
 440		wc.y = ev->y;
 441		wc.width = ev->width;
 442		wc.height = ev->height;
 443		wc.border_width = ev->border_width;
 444		wc.sibling = ev->above;
 445		wc.stack_mode = ev->detail;
 446		XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
 447	}
 448	XSync(dpy, False);
 449}
 450
 451void
 452destroynotify(XEvent *e) {
 453	Client *c;
 454	XDestroyWindowEvent *ev = &e->xdestroywindow;
 455
 456	if((c = getclient(ev->window)))
 457		unmanage(c);
 458}
 459
 460void
 461detach(Client *c) {
 462	Client *i;
 463
 464	if (c != clients) {
 465		for(i = clients; i->next != c; i = i->next);
 466		i->next = c->next;
 467	}
 468	else {
 469		clients = c->next;
 470	}
 471	c->next =  NULL;
 472}
 473
 474void
 475detachstack(Client *c) {
 476	Client **tc;
 477
 478	for(tc = &stack; *tc && *tc != c; tc = &(*tc)->snext);
 479	*tc = c->snext;
 480}
 481
 482void
 483drawbar(void) {
 484	int i, x;
 485	Client *c;
 486
 487	dc.x = 0;
 488	for(c = stack; c && c->isbanned; c = c->snext);
 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(c && c->tags & 1 << i, isoccupied(i), isurgent(i), dc.sel);
 494		}
 495		else {
 496			drawtext(tags[i], dc.norm, isurgent(i));
 497			drawsquare(c && c->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(c) {
 518			drawtext(c->name, dc.sel, False);
 519			drawsquare(c->isfixed, c->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 || c->isbanned)
 612		for(c = stack; c && c->isbanned; 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 && c->isbanned; c = c->next);
 646		if(!c)
 647			for(c = clients; c && c->isbanned; c = c->next);
 648	}
 649	else {
 650		for(i = clients; i != sel; i = i->next)
 651			if (!i->isbanned)
 652				c = i;
 653		if(!c)
 654			for(; i; i = i->next)
 655				if (!i->isbanned)
 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	int i, j;
 729	uint buttons[]   = { Button1, Button2, Button3 };
 730	uint modifiers[] = { MODKEY, MODKEY|LockMask, MODKEY|numlockmask, MODKEY|numlockmask|LockMask };
 731
 732	XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
 733	if(focused)
 734		for(i = 0; i < LENGTH(buttons); i++)
 735			for(j = 0; j < LENGTH(modifiers); j++)
 736				XGrabButton(dpy, buttons[i], modifiers[j], c->win, False,
 737					BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
 738	else
 739		XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
 740			BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
 741}
 742
 743void
 744grabkeys(void) {
 745	uint i, j;
 746	KeyCode code;
 747	XModifierKeymap *modmap;
 748
 749	/* init modifier map */
 750	modmap = XGetModifierMapping(dpy);
 751	for(i = 0; i < 8; i++)
 752		for(j = 0; j < modmap->max_keypermod; j++) {
 753			if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
 754				numlockmask = (1 << i);
 755		}
 756	XFreeModifiermap(modmap);
 757
 758	XUngrabKey(dpy, AnyKey, AnyModifier, root);
 759	for(i = 0; i < LENGTH(keys); i++) {
 760		code = XKeysymToKeycode(dpy, keys[i].keysym);
 761		XGrabKey(dpy, code, keys[i].mod, root, True,
 762				GrabModeAsync, GrabModeAsync);
 763		XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
 764				GrabModeAsync, GrabModeAsync);
 765		XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
 766				GrabModeAsync, GrabModeAsync);
 767		XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
 768				GrabModeAsync, GrabModeAsync);
 769	}
 770}
 771
 772void
 773initfont(const char *fontstr) {
 774	char *def, **missing;
 775	int i, n;
 776
 777	missing = NULL;
 778	if(dc.font.set)
 779		XFreeFontSet(dpy, dc.font.set);
 780	dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
 781	if(missing) {
 782		while(n--)
 783			fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
 784		XFreeStringList(missing);
 785	}
 786	if(dc.font.set) {
 787		XFontSetExtents *font_extents;
 788		XFontStruct **xfonts;
 789		char **font_names;
 790		dc.font.ascent = dc.font.descent = 0;
 791		font_extents = XExtentsOfFontSet(dc.font.set);
 792		n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
 793		for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
 794			dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
 795			dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
 796			xfonts++;
 797		}
 798	}
 799	else {
 800		if(dc.font.xfont)
 801			XFreeFont(dpy, dc.font.xfont);
 802		dc.font.xfont = NULL;
 803		if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
 804		&& !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
 805			eprint("error, cannot load font: '%s'\n", fontstr);
 806		dc.font.ascent = dc.font.xfont->ascent;
 807		dc.font.descent = dc.font.xfont->descent;
 808	}
 809	dc.font.height = dc.font.ascent + dc.font.descent;
 810}
 811
 812Bool
 813isoccupied(uint t) {
 814	Client *c;
 815
 816	for(c = clients; c; c = c->next)
 817		if(c->tags & 1 << t)
 818			return True;
 819	return False;
 820}
 821
 822Bool
 823isprotodel(Client *c) {
 824	int i, n;
 825	Atom *protocols;
 826	Bool ret = False;
 827
 828	if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
 829		for(i = 0; !ret && i < n; i++)
 830			if(protocols[i] == wmatom[WMDelete])
 831				ret = True;
 832		XFree(protocols);
 833	}
 834	return ret;
 835}
 836
 837Bool
 838isurgent(uint t) {
 839	Client *c;
 840
 841	for(c = clients; c; c = c->next)
 842		if(c->isurgent && c->tags & 1 << t)
 843			return True;
 844	return False;
 845}
 846
 847void
 848keypress(XEvent *e) {
 849	uint i;
 850	KeySym keysym;
 851	XKeyEvent *ev;
 852
 853	ev = &e->xkey;
 854	keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
 855	for(i = 0; i < LENGTH(keys); i++)
 856		if(keysym == keys[i].keysym
 857		   && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
 858		   && keys[i].func)
 859			keys[i].func(&(keys[i].arg));
 860}
 861
 862void
 863killclient(const Arg *arg) {
 864	XEvent ev;
 865
 866	if(!sel)
 867		return;
 868	if(isprotodel(sel)) {
 869		ev.type = ClientMessage;
 870		ev.xclient.window = sel->win;
 871		ev.xclient.message_type = wmatom[WMProtocols];
 872		ev.xclient.format = 32;
 873		ev.xclient.data.l[0] = wmatom[WMDelete];
 874		ev.xclient.data.l[1] = CurrentTime;
 875		XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
 876	}
 877	else
 878		XKillClient(dpy, sel->win);
 879}
 880
 881void
 882manage(Window w, XWindowAttributes *wa) {
 883	Client *c, *t = NULL;
 884	Status rettrans;
 885	Window trans;
 886	XWindowChanges wc;
 887
 888	if(!(c = calloc(1, sizeof(Client))))
 889		eprint("fatal: could not calloc() %u bytes\n", sizeof(Client));
 890	c->win = w;
 891
 892	/* geometry */
 893	c->x = wa->x;
 894	c->y = wa->y;
 895	c->w = wa->width;
 896	c->h = wa->height;
 897	c->oldbw = wa->border_width;
 898	if(c->w == sw && c->h == sh) {
 899		c->x = sx;
 900		c->y = sy;
 901		c->bw = wa->border_width;
 902	}
 903	else {
 904		if(c->x + c->w + 2 * c->bw > sx + sw)
 905			c->x = sx + sw - c->w - 2 * c->bw;
 906		if(c->y + c->h + 2 * c->bw > sy + sh)
 907			c->y = sy + sh - c->h - 2 * c->bw;
 908		c->x = MAX(c->x, sx);
 909		/* only fix client y-offset, if the client center might cover the bar */
 910		c->y = MAX(c->y, ((by == 0) && (c->x + (c->w / 2) >= wx) && (c->x + (c->w / 2) < wx + ww)) ? bh : sy);
 911		c->bw = borderpx;
 912	}
 913
 914	wc.border_width = c->bw;
 915	XConfigureWindow(dpy, w, CWBorderWidth, &wc);
 916	XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
 917	configure(c); /* propagates border_width, if size doesn't change */
 918	updatesizehints(c);
 919	XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
 920	grabbuttons(c, False);
 921	updatetitle(c);
 922	if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
 923		for(t = clients; t && t->win != trans; t = t->next);
 924	if(t)
 925		c->tags = t->tags;
 926	else
 927		applyrules(c);
 928	if(!c->isfloating)
 929		c->isfloating = (rettrans == Success) || c->isfixed;
 930	if(c->isfloating)
 931		XRaiseWindow(dpy, c->win);
 932	attach(c);
 933	attachstack(c);
 934	XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
 935	XMapWindow(dpy, c->win);
 936	setclientstate(c, NormalState);
 937	arrange();
 938}
 939
 940void
 941mappingnotify(XEvent *e) {
 942	XMappingEvent *ev = &e->xmapping;
 943
 944	XRefreshKeyboardMapping(ev);
 945	if(ev->request == MappingKeyboard)
 946		grabkeys();
 947}
 948
 949void
 950maprequest(XEvent *e) {
 951	static XWindowAttributes wa;
 952	XMapRequestEvent *ev = &e->xmaprequest;
 953
 954	if(!XGetWindowAttributes(dpy, ev->window, &wa))
 955		return;
 956	if(wa.override_redirect)
 957		return;
 958	if(!getclient(ev->window))
 959		manage(ev->window, &wa);
 960}
 961
 962void
 963monocle(void) {
 964	Client *c;
 965
 966	for(c = nexttiled(clients); c; c = nexttiled(c->next))
 967		resize(c, wx, wy, ww, wh, resizehints);
 968}
 969
 970void
 971movemouse(const Arg *arg) {
 972	int x1, y1, ocx, ocy, di, nx, ny;
 973	uint dui;
 974	Client *c;
 975	Window dummy;
 976	XEvent ev;
 977
 978	if(!(c = sel))
 979		return;
 980	restack();
 981	ocx = nx = c->x;
 982	ocy = ny = c->y;
 983	if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
 984	None, cursor[CurMove], CurrentTime) != GrabSuccess)
 985		return;
 986	XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
 987	for(;;) {
 988		XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
 989		switch (ev.type) {
 990		case ButtonRelease:
 991			XUngrabPointer(dpy, CurrentTime);
 992			return;
 993		case ConfigureRequest:
 994		case Expose:
 995		case MapRequest:
 996			handler[ev.type](&ev);
 997			break;
 998		case MotionNotify:
 999			XSync(dpy, False);
1000			nx = ocx + (ev.xmotion.x - x1);
1001			ny = ocy + (ev.xmotion.y - y1);
1002			if(snap && nx >= wx && nx <= wx + ww
1003			        && ny >= wy && ny <= wy + wh) {
1004				if(abs(wx - nx) < snap)
1005					nx = wx;
1006				else if(abs((wx + ww) - (nx + c->w + 2 * c->bw)) < snap)
1007					nx = wx + ww - c->w - 2 * c->bw;
1008				if(abs(wy - ny) < snap)
1009					ny = wy;
1010				else if(abs((wy + wh) - (ny + c->h + 2 * c->bw)) < snap)
1011					ny = wy + wh - c->h - 2 * c->bw;
1012				if(!c->isfloating && lt[sellt]->arrange && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
1013					togglefloating(NULL);
1014			}
1015			if(!lt[sellt]->arrange || c->isfloating)
1016				resize(c, nx, ny, c->w, c->h, False);
1017			break;
1018		}
1019	}
1020}
1021
1022Client *
1023nexttiled(Client *c) {
1024	for(; c && (c->isfloating || c->isbanned); c = c->next);
1025	return c;
1026}
1027
1028void
1029propertynotify(XEvent *e) {
1030	Client *c;
1031	Window trans;
1032	XPropertyEvent *ev = &e->xproperty;
1033
1034	if(ev->state == PropertyDelete)
1035		return; /* ignore */
1036	if((c = getclient(ev->window))) {
1037		switch (ev->atom) {
1038		default: break;
1039		case XA_WM_TRANSIENT_FOR:
1040			XGetTransientForHint(dpy, c->win, &trans);
1041			if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1042				arrange();
1043			break;
1044		case XA_WM_NORMAL_HINTS:
1045			updatesizehints(c);
1046			break;
1047		case XA_WM_HINTS:
1048			updatewmhints(c);
1049			drawbar();
1050			break;
1051		}
1052		if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1053			updatetitle(c);
1054			if(c == sel)
1055				drawbar();
1056		}
1057	}
1058}
1059
1060void
1061quit(const Arg *arg) {
1062	readin = running = False;
1063}
1064
1065void
1066resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1067	XWindowChanges wc;
1068
1069	if(sizehints) {
1070		/* set minimum possible */
1071		w = MAX(1, w);
1072		h = MAX(1, h);
1073
1074		/* temporarily remove base dimensions */
1075		w -= c->basew;
1076		h -= c->baseh;
1077
1078		/* adjust for aspect limits */
1079		if(c->mina > 0 && c->maxa > 0) {
1080			if(c->maxa < (float) w/h)
1081				w = h * c->maxa;
1082			else if(c->mina > (float) h/w)
1083				h = w * c->mina;
1084		}
1085
1086		/* adjust for increment value */
1087		if(c->incw)
1088			w -= w % c->incw;
1089		if(c->inch)
1090			h -= h % c->inch;
1091
1092		/* restore base dimensions */
1093		w += c->basew;
1094		h += c->baseh;
1095
1096		w = MAX(w, c->minw);
1097		h = MAX(h, c->minh);
1098
1099		if(c->maxw)
1100			w = MIN(w, c->maxw);
1101
1102		if(c->maxh)
1103			h = MIN(h, c->maxh);
1104	}
1105	if(w <= 0 || h <= 0)
1106		return;
1107	if(x > sx + sw)
1108		x = sw - w - 2 * c->bw;
1109	if(y > sy + sh)
1110		y = sh - h - 2 * c->bw;
1111	if(x + w + 2 * c->bw < sx)
1112		x = sx;
1113	if(y + h + 2 * c->bw < sy)
1114		y = sy;
1115	if(h < bh)
1116		h = bh;
1117	if(w < bh)
1118		w = bh;
1119	if(c->x != x || c->y != y || c->w != w || c->h != h) {
1120		c->x = wc.x = x;
1121		c->y = wc.y = y;
1122		c->w = wc.width = w;
1123		c->h = wc.height = h;
1124		wc.border_width = c->bw;
1125		XConfigureWindow(dpy, c->win,
1126				CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1127		configure(c);
1128		XSync(dpy, False);
1129	}
1130}
1131
1132void
1133resizemouse(const Arg *arg) {
1134	int ocx, ocy;
1135	int nw, nh;
1136	Client *c;
1137	XEvent ev;
1138
1139	if(!(c = sel))
1140		return;
1141	restack();
1142	ocx = c->x;
1143	ocy = c->y;
1144	if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1145	None, cursor[CurResize], CurrentTime) != GrabSuccess)
1146		return;
1147	XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1148	for(;;) {
1149		XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1150		switch(ev.type) {
1151		case ButtonRelease:
1152			XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1153					c->w + c->bw - 1, c->h + c->bw - 1);
1154			XUngrabPointer(dpy, CurrentTime);
1155			while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1156			return;
1157		case ConfigureRequest:
1158		case Expose:
1159		case MapRequest:
1160			handler[ev.type](&ev);
1161			break;
1162		case MotionNotify:
1163			XSync(dpy, False);
1164			nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1165			nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1166
1167			if(snap && nw >= wx && nw <= wx + ww
1168			        && nh >= wy && nh <= wy + wh) {
1169				if(!c->isfloating && lt[sellt]->arrange
1170				   && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1171					togglefloating(NULL);
1172			}
1173			if(!lt[sellt]->arrange || c->isfloating)
1174				resize(c, c->x, c->y, nw, nh, True);
1175			break;
1176		}
1177	}
1178}
1179
1180void
1181restack(void) {
1182	Client *c;
1183	XEvent ev;
1184	XWindowChanges wc;
1185
1186	drawbar();
1187	if(!sel)
1188		return;
1189	if(sel->isfloating || !lt[sellt]->arrange)
1190		XRaiseWindow(dpy, sel->win);
1191	if(lt[sellt]->arrange) {
1192		wc.stack_mode = Below;
1193		wc.sibling = barwin;
1194		for(c = stack; c; c = c->snext)
1195			if(!c->isfloating && !c->isbanned) {
1196				XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1197				wc.sibling = c->win;
1198			}
1199	}
1200	XSync(dpy, False);
1201	while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1202}
1203
1204void
1205run(void) {
1206	char *p;
1207	char sbuf[sizeof stext];
1208	fd_set rd;
1209	int r, xfd;
1210	uint len, offset;
1211	XEvent ev;
1212
1213	/* main event loop, also reads status text from stdin */
1214	XSync(dpy, False);
1215	xfd = ConnectionNumber(dpy);
1216	readin = True;
1217	offset = 0;
1218	len = sizeof stext - 1;
1219	sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1220	while(running) {
1221		FD_ZERO(&rd);
1222		if(readin)
1223			FD_SET(STDIN_FILENO, &rd);
1224		FD_SET(xfd, &rd);
1225		if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1226			if(errno == EINTR)
1227				continue;
1228			eprint("select failed\n");
1229		}
1230		if(FD_ISSET(STDIN_FILENO, &rd)) {
1231			switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1232			case -1:
1233				strncpy(stext, strerror(errno), len);
1234				readin = False;
1235				break;
1236			case 0:
1237				strncpy(stext, "EOF", 4);
1238				readin = False;
1239				break;
1240			default:
1241				for(p = sbuf + offset; r > 0; p++, r--, offset++)
1242					if(*p == '\n' || *p == '\0') {
1243						*p = '\0';
1244						strncpy(stext, sbuf, len);
1245						p += r - 1; /* p is sbuf + offset + r - 1 */
1246						for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1247						offset = r;
1248						if(r)
1249							memmove(sbuf, p - r + 1, r);
1250						break;
1251					}
1252				break;
1253			}
1254			drawbar();
1255		}
1256		while(XPending(dpy)) {
1257			XNextEvent(dpy, &ev);
1258			if(handler[ev.type])
1259				(handler[ev.type])(&ev); /* call handler */
1260		}
1261	}
1262}
1263
1264void
1265scan(void) {
1266	uint i, num;
1267	Window *wins, d1, d2;
1268	XWindowAttributes wa;
1269
1270	wins = NULL;
1271	if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1272		for(i = 0; i < num; i++) {
1273			if(!XGetWindowAttributes(dpy, wins[i], &wa)
1274			|| wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1275				continue;
1276			if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1277				manage(wins[i], &wa);
1278		}
1279		for(i = 0; i < num; i++) { /* now the transients */
1280			if(!XGetWindowAttributes(dpy, wins[i], &wa))
1281				continue;
1282			if(XGetTransientForHint(dpy, wins[i], &d1)
1283			&& (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1284				manage(wins[i], &wa);
1285		}
1286	}
1287	if(wins)
1288		XFree(wins);
1289}
1290
1291void
1292setclientstate(Client *c, long state) {
1293	long data[] = {state, None};
1294
1295	XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1296			PropModeReplace, (unsigned char *)data, 2);
1297}
1298
1299void
1300setlayout(const Arg *arg) {
1301	sellt ^= 1;
1302	if(arg && arg->v && arg->v != lt[sellt])
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	XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1525	setclientstate(c, WithdrawnState);
1526	free(c);
1527	XSync(dpy, False);
1528	XSetErrorHandler(xerror);
1529	XUngrabServer(dpy);
1530	arrange();
1531}
1532
1533void
1534unmapnotify(XEvent *e) {
1535	Client *c;
1536	XUnmapEvent *ev = &e->xunmap;
1537
1538	if((c = getclient(ev->window)))
1539		unmanage(c);
1540}
1541
1542void
1543updatebar(void) {
1544	if(dc.drawable != 0)
1545		XFreePixmap(dpy, dc.drawable);
1546	dc.drawable = XCreatePixmap(dpy, root, ww, bh, DefaultDepth(dpy, screen));
1547	XMoveResizeWindow(dpy, barwin, wx, by, ww, bh);
1548}
1549
1550void
1551updategeom(void) {
1552#ifdef XINERAMA
1553	int i;
1554	XineramaScreenInfo *info = NULL;
1555
1556	/* window area geometry */
1557	if(XineramaIsActive(dpy)) {
1558		info = XineramaQueryScreens(dpy, &i);
1559		wx = info[xidx].x_org;
1560		wy = showbar && topbar ?  info[xidx].y_org + bh : info[xidx].y_org;
1561		ww = info[xidx].width;
1562		wh = showbar ? info[xidx].height - bh : info[xidx].height;
1563		XFree(info);
1564	}
1565	else
1566#endif
1567	{
1568		wx = sx;
1569		wy = showbar && topbar ? sy + bh : sy;
1570		ww = sw;
1571		wh = showbar ? sh - bh : sh;
1572	}
1573
1574	/* bar position */
1575	by = showbar ? (topbar ? wy - bh : wy + wh) : -bh;
1576}
1577
1578void
1579updatesizehints(Client *c) {
1580	long msize;
1581	XSizeHints size;
1582
1583	XGetWMNormalHints(dpy, c->win, &size, &msize);
1584	if(size.flags & PBaseSize) {
1585		c->basew = size.base_width;
1586		c->baseh = size.base_height;
1587	}
1588	else if(size.flags & PMinSize) {
1589		c->basew = size.min_width;
1590		c->baseh = size.min_height;
1591	}
1592	else
1593		c->basew = c->baseh = 0;
1594	if(size.flags & PResizeInc) {
1595		c->incw = size.width_inc;
1596		c->inch = size.height_inc;
1597	}
1598	else
1599		c->incw = c->inch = 0;
1600	if(size.flags & PMaxSize) {
1601		c->maxw = size.max_width;
1602		c->maxh = size.max_height;
1603	}
1604	else
1605		c->maxw = c->maxh = 0;
1606	if(size.flags & PMinSize) {
1607		c->minw = size.min_width;
1608		c->minh = size.min_height;
1609	}
1610	else if(size.flags & PBaseSize) {
1611		c->minw = size.base_width;
1612		c->minh = size.base_height;
1613	}
1614	else
1615		c->minw = c->minh = 0;
1616	if(size.flags & PAspect) {
1617		c->mina = (float)size.min_aspect.y / (float)size.min_aspect.x;
1618		c->maxa = (float)size.max_aspect.x / (float)size.max_aspect.y;
1619	}
1620	else
1621		c->maxa = c->mina = 0.0;
1622	c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1623			&& c->maxw == c->minw && c->maxh == c->minh);
1624}
1625
1626void
1627updatetitle(Client *c) {
1628	if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1629		gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1630}
1631
1632void
1633updatewmhints(Client *c) {
1634	XWMHints *wmh;
1635
1636	if((wmh = XGetWMHints(dpy, c->win))) {
1637		if(c == sel)
1638			sel->isurgent = False;
1639		else
1640			c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1641		XFree(wmh);
1642	}
1643}
1644
1645void
1646view(const Arg *arg) {
1647	seltags ^= 1; /* toggle sel tagset */
1648	if(arg && (arg->ui & TAGMASK))
1649		tagset[seltags] = arg->i & TAGMASK;
1650	arrange();
1651}
1652
1653/* There's no way to check accesses to destroyed windows, thus those cases are
1654 * ignored (especially on UnmapNotify's).  Other types of errors call Xlibs
1655 * default error handler, which may call exit.  */
1656int
1657xerror(Display *dpy, XErrorEvent *ee) {
1658	if(ee->error_code == BadWindow
1659	|| (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1660	|| (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1661	|| (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1662	|| (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1663	|| (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1664	|| (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1665	|| (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1666	|| (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1667		return 0;
1668	fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1669			ee->request_code, ee->error_code);
1670	return xerrorxlib(dpy, ee); /* may call exit */
1671}
1672
1673int
1674xerrordummy(Display *dpy, XErrorEvent *ee) {
1675	return 0;
1676}
1677
1678/* Startup Error handler to check if another window manager
1679 * is already running. */
1680int
1681xerrorstart(Display *dpy, XErrorEvent *ee) {
1682	otherwm = True;
1683	return -1;
1684}
1685
1686void
1687zoom(const Arg *arg) {
1688	Client *c = sel;
1689
1690	if(!lt[sellt]->arrange || lt[sellt]->arrange == monocle || (sel && sel->isfloating))
1691		return;
1692	if(c == nexttiled(clients))
1693		if(!c || !(c = nexttiled(c->next)))
1694			return;
1695	detach(c);
1696	attach(c);
1697	focus(c);
1698	arrange();
1699}
1700
1701int
1702main(int argc, char *argv[]) {
1703	if(argc == 2 && !strcmp("-v", argv[1]))
1704		eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1705	else if(argc != 1)
1706		eprint("usage: dwm [-v]\n");
1707
1708	setlocale(LC_CTYPE, "");
1709	if(!(dpy = XOpenDisplay(0)))
1710		eprint("dwm: cannot open display\n");
1711
1712	checkotherwm();
1713	setup();
1714	scan();
1715	run();
1716	cleanup();
1717
1718	XCloseDisplay(dpy);
1719	return 0;
1720}