all repos — dwm @ 3a79b82721a4772e1c92acf5f3be41eaf0dc28d2

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