all repos — dwm @ d26b60b43eb24b70b75c5fb2ec9b6f2558ca8bc2

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