all repos — dwm @ a2bc5cd9a2f999cb46575d5c07c9f95edadd9031

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