all repos — dwm @ 191cb9ce283090c48f17c9518a9b6a553085c8e4

fork of suckless dynamic window manager

dwm.c (view raw)

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