all repos — dwm @ 9086f98068693d22321be2bdc6779e7be7e751c7

fork of suckless dynamic window manager

dwm.c (view raw)

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