all repos — dwm @ c82db690cc0c4624dad4dc6ae899020799ec84db

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