all repos — dwm @ 103fb58a445bc849acdd32c694f013846ab863ee

fork of suckless dynamic window manager

dwm.c (view raw)

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