all repos — dwm @ 14d8d828abbb91db3305dfa666c8c70358d1d3c7

fork of suckless dynamic window manager

dwm.c (view raw)

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