all repos — dwm @ d8fad9bf7afd7438b0f3e82adf7132524bfedd0a

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, ismoved, 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 movemouse(const Arg *arg);
 172static Client *nexttiled(Client *c);
 173static void propertynotify(XEvent *e);
 174static void quit(const Arg *arg);
 175static void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
 176static void resizemouse(const Arg *arg);
 177static void restack(void);
 178static void run(void);
 179static void scan(void);
 180static void setclientstate(Client *c, long state);
 181static void setmfact(const Arg *arg);
 182static void setup(void);
 183static void spawn(const Arg *arg);
 184static void tag(const Arg *arg);
 185static int textnw(const char *text, uint len);
 186static void tile(void);
 187static void togglebar(const Arg *arg);
 188static void togglefloating(const Arg *arg);
 189static void togglelayout(const Arg *arg);
 190static void togglemax(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;
 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 ismax = False;
 229static Bool otherwm, readin;
 230static Bool running = True;
 231static uint tagset[] = {1, 1}; /* after start, first tag is selected */
 232static Client *clients = NULL;
 233static Client *sel = NULL;
 234static Client *stack = NULL;
 235static Cursor cursor[CurLast];
 236static Display *dpy;
 237static DC dc = {0};
 238static Layout *lt = NULL;
 239static Window root, barwin;
 240/* configuration, allows nested code to access above variables */
 241#include "config.h"
 242
 243/* compile-time check if all tags fit into an uint bit array. */
 244struct NumTags { char limitexceeded[sizeof(uint) * 8 < LENGTH(tags) ? -1 : 1]; };
 245
 246/* function implementations */
 247void
 248applyrules(Client *c) {
 249	uint i;
 250	Rule *r;
 251	XClassHint ch = { 0 };
 252
 253	/* rule matching */
 254	XGetClassHint(dpy, c->win, &ch);
 255	for(i = 0; i < LENGTH(rules); i++) {
 256		r = &rules[i];
 257		if((!r->title || strstr(c->name, r->title))
 258		&& (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
 259		&& (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
 260			c->isfloating = r->isfloating;
 261			c->tags |= r->tags & TAGMASK;
 262		}
 263	}
 264	if(ch.res_class)
 265		XFree(ch.res_class);
 266	if(ch.res_name)
 267		XFree(ch.res_name);
 268	if(!c->tags)
 269		c->tags = tagset[seltags];
 270}
 271
 272void
 273arrange(void) {
 274	Client *c;
 275
 276	for(c = clients; c; c = c->next)
 277		if(c->tags & tagset[seltags]) { /* is visible */
 278			if(ismax && !c->isfixed) {
 279				XMoveResizeWindow(dpy, c->win, wx, wy, ww - 2 * c->bw, wh - 2 * c->bw);
 280				c->ismoved = True;
 281			}
 282			else if(!lt->arrange || c->isfloating)
 283				resize(c, c->x, c->y, c->w, c->h, True);
 284			c->isbanned = False;
 285		}
 286		else if(!c->isbanned) {
 287			XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
 288			c->isbanned = c->ismoved = True;
 289		}
 290
 291	focus(NULL);
 292	if(lt->arrange && !ismax)
 293		lt->arrange();
 294	restack();
 295}
 296
 297void
 298attach(Client *c) {
 299	c->next = clients;
 300	clients = c;
 301}
 302
 303void
 304attachstack(Client *c) {
 305	c->snext = stack;
 306	stack = c;
 307}
 308
 309void
 310buttonpress(XEvent *e) {
 311	uint i, x, click;
 312	Client *c;
 313	XButtonPressedEvent *ev = &e->xbutton;
 314
 315	click = ClkRootWin;
 316	if(ev->window == barwin) {
 317		i = x = 0;
 318		do
 319			x += TEXTW(tags[i]);
 320		while(ev->x >= x && ++i < LENGTH(tags));
 321		if(i < LENGTH(tags))
 322			click = i;
 323		else if(ev->x < x + blw)
 324			click = ClkLtSymbol;
 325		else if(ev->x > wx + ww - TEXTW(stext))
 326			click = ClkStatusText;
 327		else
 328			click = ClkWinTitle;
 329	}
 330	else if((c = getclient(ev->window))) {
 331		focus(c);
 332		click = ClkClientWin;
 333	}
 334
 335	for(i = 0; i < LENGTH(buttons); i++)
 336		if(click == buttons[i].click && buttons[i].func && buttons[i].button == ev->button
 337		   && CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
 338			buttons[i].func(&buttons[i].arg);
 339}
 340
 341void
 342checkotherwm(void) {
 343	otherwm = False;
 344	XSetErrorHandler(xerrorstart);
 345
 346	/* this causes an error if some other window manager is running */
 347	XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
 348	XSync(dpy, False);
 349	if(otherwm)
 350		eprint("dwm: another window manager is already running\n");
 351	XSetErrorHandler(NULL);
 352	xerrorxlib = XSetErrorHandler(xerror);
 353	XSync(dpy, False);
 354}
 355
 356void
 357cleanup(void) {
 358	Arg a = {.i = ~0};
 359	Layout foo = { "", NULL };
 360
 361	close(STDIN_FILENO);
 362	view(&a);
 363	lt = &foo;
 364	while(stack)
 365		unmanage(stack);
 366	if(dc.font.set)
 367		XFreeFontSet(dpy, dc.font.set);
 368	else
 369		XFreeFont(dpy, dc.font.xfont);
 370	XUngrabKey(dpy, AnyKey, AnyModifier, root);
 371	XFreePixmap(dpy, dc.drawable);
 372	XFreeGC(dpy, dc.gc);
 373	XFreeCursor(dpy, cursor[CurNormal]);
 374	XFreeCursor(dpy, cursor[CurResize]);
 375	XFreeCursor(dpy, cursor[CurMove]);
 376	XDestroyWindow(dpy, barwin);
 377	XSync(dpy, False);
 378	XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
 379}
 380
 381void
 382configure(Client *c) {
 383	XConfigureEvent ce;
 384
 385	ce.type = ConfigureNotify;
 386	ce.display = dpy;
 387	ce.event = c->win;
 388	ce.window = c->win;
 389	ce.x = c->x;
 390	ce.y = c->y;
 391	ce.width = c->w;
 392	ce.height = c->h;
 393	ce.border_width = c->bw;
 394	ce.above = None;
 395	ce.override_redirect = False;
 396	XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
 397}
 398
 399void
 400configurenotify(XEvent *e) {
 401	XConfigureEvent *ev = &e->xconfigure;
 402
 403	if(ev->window == root && (ev->width != sw || ev->height != sh)) {
 404		sw = ev->width;
 405		sh = ev->height;
 406		updategeom();
 407		updatebar();
 408		arrange();
 409	}
 410}
 411
 412void
 413configurerequest(XEvent *e) {
 414	Client *c;
 415	XConfigureRequestEvent *ev = &e->xconfigurerequest;
 416	XWindowChanges wc;
 417
 418	if((c = getclient(ev->window))) {
 419		if(ev->value_mask & CWBorderWidth)
 420			c->bw = ev->border_width;
 421		if(ismax && !c->isbanned && !c->isfixed)
 422			XMoveResizeWindow(dpy, c->win, wx, wy, ww - 2 * c->bw, wh + 2 * c->bw);
 423		else if(c->isfloating || !lt->arrange) {
 424			if(ev->value_mask & CWX)
 425				c->x = sx + ev->x;
 426			if(ev->value_mask & CWY)
 427				c->y = sy + ev->y;
 428			if(ev->value_mask & CWWidth)
 429				c->w = ev->width;
 430			if(ev->value_mask & CWHeight)
 431				c->h = ev->height;
 432			if((c->x - sx + c->w) > sw && c->isfloating)
 433				c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
 434			if((c->y - sy + c->h) > sh && c->isfloating)
 435				c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
 436			if((ev->value_mask & (CWX|CWY))
 437			&& !(ev->value_mask & (CWWidth|CWHeight)))
 438				configure(c);
 439			if(!c->isbanned)
 440				XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
 441		}
 442		else
 443			configure(c);
 444	}
 445	else {
 446		wc.x = ev->x;
 447		wc.y = ev->y;
 448		wc.width = ev->width;
 449		wc.height = ev->height;
 450		wc.border_width = ev->border_width;
 451		wc.sibling = ev->above;
 452		wc.stack_mode = ev->detail;
 453		XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
 454	}
 455	XSync(dpy, False);
 456}
 457
 458void
 459destroynotify(XEvent *e) {
 460	Client *c;
 461	XDestroyWindowEvent *ev = &e->xdestroywindow;
 462
 463	if((c = getclient(ev->window)))
 464		unmanage(c);
 465}
 466
 467void
 468detach(Client *c) {
 469	Client *i;
 470
 471	if (c != clients) {
 472		for(i = clients; i->next != c; i = i->next);
 473		i->next = c->next;
 474	}
 475	else {
 476		clients = c->next;
 477	}
 478	c->next =  NULL;
 479}
 480
 481void
 482detachstack(Client *c) {
 483	Client **tc;
 484
 485	for(tc = &stack; *tc && *tc != c; tc = &(*tc)->snext);
 486	*tc = c->snext;
 487}
 488
 489void
 490drawbar(void) {
 491	int i, x;
 492	Client *c;
 493
 494	dc.x = 0;
 495	for(c = stack; c && c->isbanned; c = c->snext);
 496	for(i = 0; i < LENGTH(tags); i++) {
 497		dc.w = TEXTW(tags[i]);
 498		if(tagset[seltags] & 1 << i) {
 499			drawtext(tags[i], dc.sel, isurgent(i));
 500			drawsquare(c && c->tags & 1 << i, isoccupied(i), isurgent(i), dc.sel);
 501		}
 502		else {
 503			drawtext(tags[i], dc.norm, isurgent(i));
 504			drawsquare(c && c->tags & 1 << i, isoccupied(i), isurgent(i), dc.norm);
 505		}
 506		dc.x += dc.w;
 507	}
 508	if(blw > 0) {
 509		dc.w = blw;
 510		drawtext(lt->symbol, dc.norm, ismax);
 511		x = dc.x + dc.w;
 512	}
 513	else
 514		x = dc.x;
 515	dc.w = TEXTW(stext);
 516	dc.x = ww - dc.w;
 517	if(dc.x < x) {
 518		dc.x = x;
 519		dc.w = ww - x;
 520	}
 521	drawtext(stext, dc.norm, False);
 522	if((dc.w = dc.x - x) > bh) {
 523		dc.x = x;
 524		if(c) {
 525			drawtext(c->name, dc.sel, False);
 526			drawsquare(c->isfixed, c->isfloating, False, dc.sel);
 527		}
 528		else
 529			drawtext(NULL, dc.norm, False);
 530	}
 531	XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, ww, bh, 0, 0);
 532	XSync(dpy, False);
 533}
 534
 535void
 536drawsquare(Bool filled, Bool empty, Bool invert, ulong col[ColLast]) {
 537	int x;
 538	XGCValues gcv;
 539	XRectangle r = { dc.x, dc.y, dc.w, dc.h };
 540
 541	gcv.foreground = col[invert ? ColBG : ColFG];
 542	XChangeGC(dpy, dc.gc, GCForeground, &gcv);
 543	x = (dc.font.ascent + dc.font.descent + 2) / 4;
 544	r.x = dc.x + 1;
 545	r.y = dc.y + 1;
 546	if(filled) {
 547		r.width = r.height = x + 1;
 548		XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
 549	}
 550	else if(empty) {
 551		r.width = r.height = x;
 552		XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
 553	}
 554}
 555
 556void
 557drawtext(const char *text, ulong col[ColLast], Bool invert) {
 558	int i, x, y, h, len, olen;
 559	XRectangle r = { dc.x, dc.y, dc.w, dc.h };
 560	char buf[256];
 561
 562	XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
 563	XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
 564	if(!text)
 565		return;
 566	olen = strlen(text);
 567	len = MIN(olen, sizeof buf);
 568	memcpy(buf, text, len);
 569	h = dc.font.ascent + dc.font.descent;
 570	y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
 571	x = dc.x + (h / 2);
 572	/* shorten text if necessary */
 573	for(; len && (i = textnw(buf, len)) > dc.w - h; len--);
 574	if(!len)
 575		return;
 576	if(len < olen)
 577		for(i = len; i && i > len - 3; buf[--i] = '.');
 578	XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
 579	if(dc.font.set)
 580		XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
 581	else
 582		XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
 583}
 584
 585void
 586enternotify(XEvent *e) {
 587	Client *c;
 588	XCrossingEvent *ev = &e->xcrossing;
 589
 590	if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
 591		return;
 592	if((c = getclient(ev->window)))
 593		focus(c);
 594	else
 595		focus(NULL);
 596}
 597
 598void
 599eprint(const char *errstr, ...) {
 600	va_list ap;
 601
 602	va_start(ap, errstr);
 603	vfprintf(stderr, errstr, ap);
 604	va_end(ap);
 605	exit(EXIT_FAILURE);
 606}
 607
 608void
 609expose(XEvent *e) {
 610	XExposeEvent *ev = &e->xexpose;
 611
 612	if(ev->count == 0 && (ev->window == barwin))
 613		drawbar();
 614}
 615
 616void
 617focus(Client *c) {
 618	if(!c || c->isbanned)
 619		for(c = stack; c && c->isbanned; c = c->snext);
 620	if(sel && sel != c) {
 621		grabbuttons(sel, False);
 622		XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
 623	}
 624	if(c) {
 625		detachstack(c);
 626		attachstack(c);
 627		grabbuttons(c, True);
 628		XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
 629		XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
 630	}
 631	else
 632		XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
 633	sel = c;
 634	drawbar();
 635}
 636
 637void
 638focusin(XEvent *e) { /* there are some broken focus acquiring clients */
 639	XFocusChangeEvent *ev = &e->xfocus;
 640
 641	if(sel && ev->window != sel->win)
 642		XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
 643}
 644
 645void
 646focusstack(const Arg *arg) {
 647	Client *c = NULL, *i;
 648
 649	if(!sel)
 650		return;
 651	if (arg->i > 0) {
 652		for(c = sel->next; c && c->isbanned; c = c->next);
 653		if(!c)
 654			for(c = clients; c && c->isbanned; c = c->next);
 655	}
 656	else {
 657		for(i = clients; i != sel; i = i->next)
 658			if (!i->isbanned)
 659				c = i;
 660		if(!c)
 661			for(; i; i = i->next)
 662				if (!i->isbanned)
 663					c = i;
 664	}
 665	if(c) {
 666		focus(c);
 667		restack();
 668	}
 669}
 670
 671Client *
 672getclient(Window w) {
 673	Client *c;
 674
 675	for(c = clients; c && c->win != w; c = c->next);
 676	return c;
 677}
 678
 679ulong
 680getcolor(const char *colstr) {
 681	Colormap cmap = DefaultColormap(dpy, screen);
 682	XColor color;
 683
 684	if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
 685		eprint("error, cannot allocate color '%s'\n", colstr);
 686	return color.pixel;
 687}
 688
 689long
 690getstate(Window w) {
 691	int format, status;
 692	long result = -1;
 693	unsigned char *p = NULL;
 694	ulong n, extra;
 695	Atom real;
 696
 697	status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
 698			&real, &format, &n, &extra, (unsigned char **)&p);
 699	if(status != Success)
 700		return -1;
 701	if(n != 0)
 702		result = *p;
 703	XFree(p);
 704	return result;
 705}
 706
 707Bool
 708gettextprop(Window w, Atom atom, char *text, uint size) {
 709	char **list = NULL;
 710	int n;
 711	XTextProperty name;
 712
 713	if(!text || size == 0)
 714		return False;
 715	text[0] = '\0';
 716	XGetTextProperty(dpy, w, &name, atom);
 717	if(!name.nitems)
 718		return False;
 719	if(name.encoding == XA_STRING)
 720		strncpy(text, (char *)name.value, size - 1);
 721	else {
 722		if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
 723		&& n > 0 && *list) {
 724			strncpy(text, *list, size - 1);
 725			XFreeStringList(list);
 726		}
 727	}
 728	text[size - 1] = '\0';
 729	XFree(name.value);
 730	return True;
 731}
 732
 733void
 734grabbuttons(Client *c, Bool focused) {
 735	int i, j;
 736	uint buttons[]   = { Button1, Button2, Button3 };
 737	uint modifiers[] = { MODKEY, MODKEY|LockMask, MODKEY|numlockmask, MODKEY|numlockmask|LockMask };
 738
 739	XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
 740	if(focused)
 741		for(i = 0; i < LENGTH(buttons); i++)
 742			for(j = 0; j < LENGTH(modifiers); j++)
 743				XGrabButton(dpy, buttons[i], modifiers[j], c->win, False,
 744					BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
 745	else
 746		XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
 747			BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
 748}
 749
 750void
 751grabkeys(void) {
 752	uint i, j;
 753	KeyCode code;
 754	XModifierKeymap *modmap;
 755
 756	/* init modifier map */
 757	modmap = XGetModifierMapping(dpy);
 758	for(i = 0; i < 8; i++)
 759		for(j = 0; j < modmap->max_keypermod; j++) {
 760			if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
 761				numlockmask = (1 << i);
 762		}
 763	XFreeModifiermap(modmap);
 764
 765	XUngrabKey(dpy, AnyKey, AnyModifier, root);
 766	for(i = 0; i < LENGTH(keys); i++) {
 767		code = XKeysymToKeycode(dpy, keys[i].keysym);
 768		XGrabKey(dpy, code, keys[i].mod, root, True,
 769				GrabModeAsync, GrabModeAsync);
 770		XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
 771				GrabModeAsync, GrabModeAsync);
 772		XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
 773				GrabModeAsync, GrabModeAsync);
 774		XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
 775				GrabModeAsync, GrabModeAsync);
 776	}
 777}
 778
 779void
 780initfont(const char *fontstr) {
 781	char *def, **missing;
 782	int i, n;
 783
 784	missing = NULL;
 785	if(dc.font.set)
 786		XFreeFontSet(dpy, dc.font.set);
 787	dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
 788	if(missing) {
 789		while(n--)
 790			fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
 791		XFreeStringList(missing);
 792	}
 793	if(dc.font.set) {
 794		XFontSetExtents *font_extents;
 795		XFontStruct **xfonts;
 796		char **font_names;
 797		dc.font.ascent = dc.font.descent = 0;
 798		font_extents = XExtentsOfFontSet(dc.font.set);
 799		n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
 800		for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
 801			dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
 802			dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
 803			xfonts++;
 804		}
 805	}
 806	else {
 807		if(dc.font.xfont)
 808			XFreeFont(dpy, dc.font.xfont);
 809		dc.font.xfont = NULL;
 810		if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
 811		&& !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
 812			eprint("error, cannot load font: '%s'\n", fontstr);
 813		dc.font.ascent = dc.font.xfont->ascent;
 814		dc.font.descent = dc.font.xfont->descent;
 815	}
 816	dc.font.height = dc.font.ascent + dc.font.descent;
 817}
 818
 819Bool
 820isoccupied(uint t) {
 821	Client *c;
 822
 823	for(c = clients; c; c = c->next)
 824		if(c->tags & 1 << t)
 825			return True;
 826	return False;
 827}
 828
 829Bool
 830isprotodel(Client *c) {
 831	int i, n;
 832	Atom *protocols;
 833	Bool ret = False;
 834
 835	if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
 836		for(i = 0; !ret && i < n; i++)
 837			if(protocols[i] == wmatom[WMDelete])
 838				ret = True;
 839		XFree(protocols);
 840	}
 841	return ret;
 842}
 843
 844Bool
 845isurgent(uint t) {
 846	Client *c;
 847
 848	for(c = clients; c; c = c->next)
 849		if(c->isurgent && c->tags & 1 << t)
 850			return True;
 851	return False;
 852}
 853
 854void
 855keypress(XEvent *e) {
 856	uint i;
 857	KeySym keysym;
 858	XKeyEvent *ev;
 859
 860	ev = &e->xkey;
 861	keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
 862	for(i = 0; i < LENGTH(keys); i++)
 863		if(keysym == keys[i].keysym
 864		   && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
 865		   && keys[i].func)
 866			keys[i].func(&(keys[i].arg));
 867}
 868
 869void
 870killclient(const Arg *arg) {
 871	XEvent ev;
 872
 873	if(!sel)
 874		return;
 875	if(isprotodel(sel)) {
 876		ev.type = ClientMessage;
 877		ev.xclient.window = sel->win;
 878		ev.xclient.message_type = wmatom[WMProtocols];
 879		ev.xclient.format = 32;
 880		ev.xclient.data.l[0] = wmatom[WMDelete];
 881		ev.xclient.data.l[1] = CurrentTime;
 882		XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
 883	}
 884	else
 885		XKillClient(dpy, sel->win);
 886}
 887
 888void
 889manage(Window w, XWindowAttributes *wa) {
 890	Client *c, *t = NULL;
 891	Status rettrans;
 892	Window trans;
 893	XWindowChanges wc;
 894
 895	if(!(c = calloc(1, sizeof(Client))))
 896		eprint("fatal: could not calloc() %u bytes\n", sizeof(Client));
 897	c->win = w;
 898
 899	/* geometry */
 900	c->x = wa->x;
 901	c->y = wa->y;
 902	c->w = wa->width;
 903	c->h = wa->height;
 904	c->oldbw = wa->border_width;
 905	if(c->w == sw && c->h == sh) {
 906		c->x = sx;
 907		c->y = sy;
 908		c->bw = wa->border_width;
 909	}
 910	else {
 911		if(c->x + c->w + 2 * c->bw > sx + sw)
 912			c->x = sx + sw - c->w - 2 * c->bw;
 913		if(c->y + c->h + 2 * c->bw > sy + sh)
 914			c->y = sy + sh - c->h - 2 * c->bw;
 915		c->x = MAX(c->x, sx);
 916		/* only fix client y-offset, if the client center might cover the bar */
 917		c->y = MAX(c->y, ((by == 0) && (c->x + (c->w / 2) >= wx) && (c->x + (c->w / 2) < wx + ww)) ? bh : sy);
 918		c->bw = borderpx;
 919	}
 920
 921	wc.border_width = c->bw;
 922	XConfigureWindow(dpy, w, CWBorderWidth, &wc);
 923	XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
 924	configure(c); /* propagates border_width, if size doesn't change */
 925	updatesizehints(c);
 926	XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
 927	grabbuttons(c, False);
 928	updatetitle(c);
 929	if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
 930		for(t = clients; t && t->win != trans; t = t->next);
 931	if(t)
 932		c->tags = t->tags;
 933	else
 934		applyrules(c);
 935	if(!c->isfloating)
 936		c->isfloating = (rettrans == Success) || c->isfixed;
 937	if(c->isfloating)
 938		XRaiseWindow(dpy, c->win);
 939	attach(c);
 940	attachstack(c);
 941	XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
 942	XMapWindow(dpy, c->win);
 943	setclientstate(c, NormalState);
 944	arrange();
 945}
 946
 947void
 948mappingnotify(XEvent *e) {
 949	XMappingEvent *ev = &e->xmapping;
 950
 951	XRefreshKeyboardMapping(ev);
 952	if(ev->request == MappingKeyboard)
 953		grabkeys();
 954}
 955
 956void
 957maprequest(XEvent *e) {
 958	static XWindowAttributes wa;
 959	XMapRequestEvent *ev = &e->xmaprequest;
 960
 961	if(!XGetWindowAttributes(dpy, ev->window, &wa))
 962		return;
 963	if(wa.override_redirect)
 964		return;
 965	if(!getclient(ev->window))
 966		manage(ev->window, &wa);
 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->arrange && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
1012					togglefloating(NULL);
1013			}
1014			if(!lt->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 || c->isbanned); 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 || c->ismoved) {
1119		c->ismoved = False;
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->arrange
1170				   && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1171					togglefloating(NULL);
1172			}
1173			if(!lt->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(ismax || sel->isfloating || !lt->arrange)
1190		XRaiseWindow(dpy, sel->win);
1191	if(!ismax && lt->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
1299/* arg > 1.0 will set mfact absolutly */
1300void
1301setmfact(const Arg *arg) {
1302	float f;
1303
1304	if(!arg || !lt->arrange)
1305		return;
1306	f = arg->f < 1.0 ? arg->f + mfact : arg->f - 1.0;
1307	if(f < 0.1 || f > 0.9)
1308		return;
1309	mfact = f;
1310	arrange();
1311}
1312
1313void
1314setup(void) {
1315	uint i;
1316	int w;
1317	XSetWindowAttributes wa;
1318
1319	/* init screen */
1320	screen = DefaultScreen(dpy);
1321	root = RootWindow(dpy, screen);
1322	initfont(font);
1323	sx = 0;
1324	sy = 0;
1325	sw = DisplayWidth(dpy, screen);
1326	sh = DisplayHeight(dpy, screen);
1327	bh = dc.h = dc.font.height + 2;
1328	lt = layouts;
1329	updategeom();
1330
1331	/* init atoms */
1332	wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1333	wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1334	wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1335	wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1336	netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1337	netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1338
1339	/* init cursors */
1340	wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1341	cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1342	cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1343
1344	/* init appearance */
1345	dc.norm[ColBorder] = getcolor(normbordercolor);
1346	dc.norm[ColBG] = getcolor(normbgcolor);
1347	dc.norm[ColFG] = getcolor(normfgcolor);
1348	dc.sel[ColBorder] = getcolor(selbordercolor);
1349	dc.sel[ColBG] = getcolor(selbgcolor);
1350	dc.sel[ColFG] = getcolor(selfgcolor);
1351	dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1352	dc.gc = XCreateGC(dpy, root, 0, 0);
1353	XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1354	if(!dc.font.set)
1355		XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1356
1357	/* init bar */
1358	for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1359		w = TEXTW(layouts[i].symbol);
1360		blw = MAX(blw, w);
1361	}
1362
1363	wa.override_redirect = 1;
1364	wa.background_pixmap = ParentRelative;
1365	wa.event_mask = ButtonPressMask|ExposureMask;
1366
1367	barwin = XCreateWindow(dpy, root, wx, by, ww, bh, 0, DefaultDepth(dpy, screen),
1368			CopyFromParent, DefaultVisual(dpy, screen),
1369			CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1370	XDefineCursor(dpy, barwin, cursor[CurNormal]);
1371	XMapRaised(dpy, barwin);
1372	strcpy(stext, "dwm-"VERSION);
1373	drawbar();
1374
1375	/* EWMH support per view */
1376	XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1377			PropModeReplace, (unsigned char *) netatom, NetLast);
1378
1379	/* select for events */
1380	wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask|ButtonPressMask
1381			|EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1382	XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1383	XSelectInput(dpy, root, wa.event_mask);
1384
1385
1386	/* grab keys */
1387	grabkeys();
1388}
1389
1390void
1391spawn(const Arg *arg) {
1392	/* The double-fork construct avoids zombie processes and keeps the code
1393	 * clean from stupid signal handlers. */
1394	if(fork() == 0) {
1395		if(fork() == 0) {
1396			if(dpy)
1397				close(ConnectionNumber(dpy));
1398			setsid();
1399			execvp(((char **)arg->v)[0], (char **)arg->v);
1400			fprintf(stderr, "dwm: execvp %s", ((char **)arg->v)[0]);
1401			perror(" failed");
1402		}
1403		exit(0);
1404	}
1405	wait(0);
1406}
1407
1408void
1409tag(const Arg *arg) {
1410	if(sel && arg->ui & TAGMASK) {
1411		sel->tags = arg->ui & TAGMASK;
1412		arrange();
1413	}
1414}
1415
1416int
1417textnw(const char *text, uint len) {
1418	XRectangle r;
1419
1420	if(dc.font.set) {
1421		XmbTextExtents(dc.font.set, text, len, NULL, &r);
1422		return r.width;
1423	}
1424	return XTextWidth(dc.font.xfont, text, len);
1425}
1426
1427void
1428tile(void) {
1429	int x, y, h, w, mw;
1430	uint i, n;
1431	Client *c;
1432
1433	for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next), n++);
1434	if(n == 0)
1435		return;
1436
1437	/* master */
1438	c = nexttiled(clients);
1439	mw = mfact * ww;
1440	resize(c, wx, wy, (n == 1 ? ww : mw) - 2 * c->bw, wh - 2 * c->bw, resizehints);
1441
1442	if(--n == 0)
1443		return;
1444
1445	/* tile stack */
1446	x = (wx + mw > c->x + c->w) ? c->x + c->w + 2 * c->bw : wx + mw;
1447	y = wy;
1448	w = (wx + mw > c->x + c->w) ? wx + ww - x : ww - mw;
1449	h = wh / n;
1450	if(h < bh)
1451		h = wh;
1452
1453	for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1454		resize(c, x, y, w - 2 * c->bw, /* remainder */ ((i + 1 == n)
1455		       ? (wy + wh) - y : h) - 2 * c->bw, resizehints);
1456		if(h != wh)
1457			y = c->y + c->h + 2 * c->bw;
1458	}
1459}
1460
1461void
1462togglebar(const Arg *arg) {
1463	showbar = !showbar;
1464	updategeom();
1465	updatebar();
1466	arrange();
1467}
1468
1469void
1470togglefloating(const Arg *arg) {
1471	if(!sel)
1472		return;
1473	sel->isfloating = !sel->isfloating || sel->isfixed;
1474	if(sel->isfloating)
1475		resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1476	arrange();
1477}
1478
1479void
1480togglelayout(const Arg *arg) {
1481	if(arg && arg->v)
1482		lt = (Layout *)arg->v;
1483	else if(++lt == &layouts[LENGTH(layouts)])
1484		lt = &layouts[0];
1485	if(sel)
1486		arrange();
1487	else
1488		drawbar();
1489}
1490
1491void
1492togglemax(const Arg *arg) {
1493	ismax = !ismax;
1494	arrange();
1495}
1496
1497void
1498toggletag(const Arg *arg) {
1499	if(sel && (sel->tags ^= (arg->ui & TAGMASK)))
1500		arrange();
1501}
1502
1503void
1504toggleview(const Arg *arg) {
1505	if((tagset[seltags] ^= (arg->ui & TAGMASK)))
1506		arrange();
1507}
1508
1509void
1510unmanage(Client *c) {
1511	XWindowChanges wc;
1512
1513	wc.border_width = c->oldbw;
1514	/* The server grab construct avoids race conditions. */
1515	XGrabServer(dpy);
1516	XSetErrorHandler(xerrordummy);
1517	XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1518	detach(c);
1519	detachstack(c);
1520	if(sel == c)
1521		focus(NULL);
1522	XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1523	setclientstate(c, WithdrawnState);
1524	free(c);
1525	XSync(dpy, False);
1526	XSetErrorHandler(xerror);
1527	XUngrabServer(dpy);
1528	arrange();
1529}
1530
1531void
1532unmapnotify(XEvent *e) {
1533	Client *c;
1534	XUnmapEvent *ev = &e->xunmap;
1535
1536	if((c = getclient(ev->window)))
1537		unmanage(c);
1538}
1539
1540void
1541updatebar(void) {
1542	if(dc.drawable != 0)
1543		XFreePixmap(dpy, dc.drawable);
1544	dc.drawable = XCreatePixmap(dpy, root, ww, bh, DefaultDepth(dpy, screen));
1545	XMoveResizeWindow(dpy, barwin, wx, by, ww, bh);
1546}
1547
1548void
1549updategeom(void) {
1550#ifdef XINERAMA
1551	int i;
1552	XineramaScreenInfo *info = NULL;
1553
1554	/* window area geometry */
1555	if(XineramaIsActive(dpy)) {
1556		info = XineramaQueryScreens(dpy, &i);
1557		wx = info[xidx].x_org;
1558		wy = showbar && topbar ?  info[xidx].y_org + bh : info[xidx].y_org;
1559		ww = info[xidx].width;
1560		wh = showbar ? info[xidx].height - bh : info[xidx].height;
1561		XFree(info);
1562	}
1563	else
1564#endif
1565	{
1566		wx = sx;
1567		wy = showbar && topbar ? sy + bh : sy;
1568		ww = sw;
1569		wh = showbar ? sh - bh : sh;
1570	}
1571
1572	/* bar position */
1573	by = showbar ? (topbar ? wy - bh : wy + wh) : -bh;
1574}
1575
1576void
1577updatesizehints(Client *c) {
1578	long msize;
1579	XSizeHints size;
1580
1581	XGetWMNormalHints(dpy, c->win, &size, &msize);
1582	if(size.flags & PBaseSize) {
1583		c->basew = size.base_width;
1584		c->baseh = size.base_height;
1585	}
1586	else if(size.flags & PMinSize) {
1587		c->basew = size.min_width;
1588		c->baseh = size.min_height;
1589	}
1590	else
1591		c->basew = c->baseh = 0;
1592	if(size.flags & PResizeInc) {
1593		c->incw = size.width_inc;
1594		c->inch = size.height_inc;
1595	}
1596	else
1597		c->incw = c->inch = 0;
1598	if(size.flags & PMaxSize) {
1599		c->maxw = size.max_width;
1600		c->maxh = size.max_height;
1601	}
1602	else
1603		c->maxw = c->maxh = 0;
1604	if(size.flags & PMinSize) {
1605		c->minw = size.min_width;
1606		c->minh = size.min_height;
1607	}
1608	else if(size.flags & PBaseSize) {
1609		c->minw = size.base_width;
1610		c->minh = size.base_height;
1611	}
1612	else
1613		c->minw = c->minh = 0;
1614	if(size.flags & PAspect) {
1615		c->mina = (float)size.min_aspect.y / (float)size.min_aspect.x;
1616		c->maxa = (float)size.max_aspect.x / (float)size.max_aspect.y;
1617	}
1618	else
1619		c->maxa = c->mina = 0.0;
1620	c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1621			&& c->maxw == c->minw && c->maxh == c->minh);
1622}
1623
1624void
1625updatetitle(Client *c) {
1626	if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1627		gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1628}
1629
1630void
1631updatewmhints(Client *c) {
1632	XWMHints *wmh;
1633
1634	if((wmh = XGetWMHints(dpy, c->win))) {
1635		if(c == sel)
1636			sel->isurgent = False;
1637		else
1638			c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1639		XFree(wmh);
1640	}
1641}
1642
1643void
1644view(const Arg *arg) {
1645	seltags ^= 1; /* toggle sel tagset */
1646	if(arg && (arg->ui & TAGMASK))
1647		tagset[seltags] = arg->i & TAGMASK;
1648	arrange();
1649}
1650
1651/* There's no way to check accesses to destroyed windows, thus those cases are
1652 * ignored (especially on UnmapNotify's).  Other types of errors call Xlibs
1653 * default error handler, which may call exit.  */
1654int
1655xerror(Display *dpy, XErrorEvent *ee) {
1656	if(ee->error_code == BadWindow
1657	|| (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1658	|| (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1659	|| (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1660	|| (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1661	|| (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1662	|| (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1663	|| (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1664	|| (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1665		return 0;
1666	fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1667			ee->request_code, ee->error_code);
1668	return xerrorxlib(dpy, ee); /* may call exit */
1669}
1670
1671int
1672xerrordummy(Display *dpy, XErrorEvent *ee) {
1673	return 0;
1674}
1675
1676/* Startup Error handler to check if another window manager
1677 * is already running. */
1678int
1679xerrorstart(Display *dpy, XErrorEvent *ee) {
1680	otherwm = True;
1681	return -1;
1682}
1683
1684void
1685zoom(const Arg *arg) {
1686	Client *c = sel;
1687
1688	if(ismax || !lt->arrange || (sel && sel->isfloating))
1689		return;
1690	if(c == nexttiled(clients))
1691		if(!c || !(c = nexttiled(c->next)))
1692			return;
1693	detach(c);
1694	attach(c);
1695	focus(c);
1696	arrange();
1697}
1698
1699int
1700main(int argc, char *argv[]) {
1701	if(argc == 2 && !strcmp("-v", argv[1]))
1702		eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1703	else if(argc != 1)
1704		eprint("usage: dwm [-v]\n");
1705
1706	setlocale(LC_CTYPE, "");
1707	if(!(dpy = XOpenDisplay(0)))
1708		eprint("dwm: cannot open display\n");
1709
1710	checkotherwm();
1711	setup();
1712	scan();
1713	run();
1714	cleanup();
1715
1716	XCloseDisplay(dpy);
1717	return 0;
1718}