all repos — dwm @ d456617f0eb93df0ec8eb81ff6e04ca988c09c60

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