all repos — dwm @ 01022b95d65612462972bdd009896ba6fdd3063a

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