dwm-noxz

[fork] suckless dwm - personal fork
git clone https://noxz.tech/git/dwm-noxz.git
dwm-noxz

dwm.c
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 <ctype.h>
24#include <errno.h>
25#include <fcntl.h>
26#include <locale.h>
27#include <signal.h>
28#include <stdarg.h>
29#include <stdio.h>
30#include <stdlib.h>
31#include <string.h>
32#include <unistd.h>
33#include <poll.h>
34#include <sys/select.h>
35#include <sys/types.h>
36#include <sys/wait.h>
37#include <X11/cursorfont.h>
38#include <X11/keysym.h>
39#include <X11/Xatom.h>
40#include <X11/Xlib.h>
41#include <X11/Xproto.h>
42#include <X11/Xutil.h>
43#include <X11/Xresource.h>
44#ifdef XINERAMA
45#include <X11/extensions/Xinerama.h>
46#endif /* XINERAMA */
47#include <X11/Xft/Xft.h>
48
49#include "drw.h"
50#include "util.h"
51
52/* macros */
53#define BUTTONMASK              (ButtonPressMask|ButtonReleaseMask)
54#define CLEANMASK(mask)         (mask & ~(numlockmask|LockMask) & (ShiftMask|ControlMask|Mod1Mask|Mod2Mask|Mod3Mask|Mod4Mask|Mod5Mask))
55#define INTERSECT(x,y,w,h,m)    (MAX(0, MIN((x)+(w),(m)->wx+(m)->ww) - MAX((x),(m)->wx)) \
56                               * MAX(0, MIN((y)+(h),(m)->wy+(m)->wh) - MAX((y),(m)->wy)))
57#define ISVISIBLE(C)            ((C->tags & C->mon->tagset[C->mon->seltags]) || C->issticky)
58#define LENGTH(X)               (sizeof X / sizeof X[0])
59#define MOUSEMASK               (BUTTONMASK|PointerMotionMask)
60#define WIDTH(X)                ((X)->w + 2 * (X)->bw)
61#define HEIGHT(X)               ((X)->h + 2 * (X)->bw)
62#define TAGMASK                 ((1 << LENGTH(tags)) - 1)
63#define TEXTW(X)                (drw_fontset_getwidth(drw, (X)) + lrpad)
64
65/* enums */
66enum { DispUi, DispCmdLine }; /* dispatch types */
67enum { LayoutGrid, LayoutMonocle, LayoutFloating }; /* layouts, first is default */
68enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
69enum { SchemeNorm, SchemeSel, SchemeTagsNorm, SchemeTagsIncl, SchemeTagsSel,
70       SchemeLayout, SchemeTitleNorm, SchemeTitleSel, SchemeWMIcon,
71       SchemeStatusNorm, SchemeStatusNotify }; /* color schemes */
72enum { NetSupported, NetWMName, NetWMState, NetWMCheck,
73       NetWMFullscreen, NetActiveWindow, NetWMWindowType,
74       NetWMWindowTypeDialog, NetClientList, NetClientInfo, NetTagState, NetLast }; /* EWMH atoms */
75enum { WMProtocols, WMDelete, WMState, WMTakeFocus, WMLast }; /* default atoms */
76enum { ClkTagBar, ClkLtSymbol, ClkStatusText, ClkWinTitle,
77       ClkClientWin, ClkRootWin, ClkLast, ClkWMIcon }; /* clicks */
78
79typedef union {
80	int i;
81	unsigned int ui;
82	float f;
83	const void *v;
84} Arg;
85
86typedef struct {
87	unsigned int click;
88	unsigned int mask;
89	unsigned int button;
90	void (*func)(const Arg *arg);
91	const Arg arg;
92} Button;
93
94typedef struct Pertag Pertag;
95typedef struct Monitor Monitor;
96typedef struct Client Client;
97struct Client {
98	char name[512];
99	float mina, maxa;
100	int x, y, w, h;
101	int oldx, oldy, oldw, oldh;
102	int basew, baseh, incw, inch, maxw, maxh, minw, minh;
103	int bw, oldbw;
104	unsigned int tags;
105	int isfixed, isfloating, isurgent, neverfocus, oldstate, isfullscreen, issticky;
106	Client *next;
107	Client *snext;
108	Monitor *mon;
109	Window win;
110};
111
112typedef struct {
113	void (*arrange)(Monitor *);
114	int *icon;
115	int vectlength;
116} Layout;
117
118struct Monitor {
119	int nmaster;
120	int num;
121	int by;               /* bar geometry */
122	int mx, my, mw, mh;   /* screen size */
123	int wx, wy, ww, wh;   /* window area  */
124	int gap;
125	unsigned int seltags;
126	unsigned int sellt;
127	unsigned int tagset[2];
128	int showbar;
129	int topbar;
130	Client *clients;
131	Client *sel;
132	Client *stack;
133	Monitor *next;
134	Window barwin;
135	const Layout *lt[2];
136	Pertag *pertag;
137};
138
139/* Xresources preferences */
140enum resource_type {
141	STRING = 0,
142	INTEGER = 1,
143	FLOAT = 2
144};
145
146typedef struct {
147	char *name;
148	enum resource_type type;
149	void *dst;
150} ResourcePref;
151
152typedef struct {
153	const char *name;
154	void (*func)(const Arg *arg);
155	const Arg arg;
156} Command;
157
158/* function declarations */
159static int applysizehints(Client *c, int *x, int *y, int *w, int *h, int *bw, int interact);
160static void arrange(Monitor *m);
161static void arrangemon(Monitor *m);
162static void attach(Client *c);
163static void attachabove(Client *c);
164static void attachstack(Client *c);
165static void buttonpress(XEvent *e);
166static void checkotherwm(void);
167static void cleanup(void);
168static void cleanupmon(Monitor *mon);
169static void clientmessage(XEvent *e);
170static void configure(Client *c);
171static void configurenotify(XEvent *e);
172static void configurerequest(XEvent *e);
173static Monitor *createmon(void);
174static void destroynotify(XEvent *e);
175static void detach(Client *c);
176static void detachstack(Client *c);
177static Monitor *dirtomon(int dir);
178static char *strmbtok(char *, const char *);
179static void strsplit(char *, char ***, const char *);
180static void dispatchline(const char*, int, void (*)(const Arg*), const Arg*);
181static void dispatchcmd(void);
182static void drawbar(Monitor *m);
183static void drawbars(void);
184static void drawicon(int scheme_type, int *icon, int size, int offset);
185static void enqueue(Client *c);
186static void enqueuestack(Client *c);
187static Bool evpredicate();
188static void expose(XEvent *e);
189static void focus(Client *c);
190static void focusin(XEvent *e);
191static void focusmon(const Arg *arg);
192static void focusstack(const Arg *arg);
193static Atom getatomprop(Client *c, Atom prop);
194static void getgap(Monitor *m, unsigned int n, unsigned int *g, unsigned int r, unsigned int c);
195static int getrootptr(int *x, int *y);
196static long getstate(Window w);
197static int gettextprop(Window w, Atom atom, char *text, unsigned int size);
198static void grabbuttons(Client *c, int focused);
199static void incgaps(const Arg *arg);
200static void incnmaster(const Arg *arg);
201static void killclient(const Arg *arg);
202static void loadxresources(void);
203static void loadstate(int atom_type, Window win, Client *c);
204static void manage(Window w, XWindowAttributes *wa);
205static void maprequest(XEvent *e);
206static void monocle(Monitor *m);
207static void movemouse(const Arg *arg);
208static Client *nextinstack(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, int bw, int interact);
214static void resizeclient(Client *c, int x, int y, int w, int h, int bw);
215static void resizemouse(const Arg *arg);
216static void resourceload(XrmDatabase db, char *name, enum resource_type rtype, void *dst);
217static void restack(Monitor *m);
218static void movestack(const Arg *arg);
219static void rotatestack(const Arg *arg);
220static void run(void);
221static void scan(void);
222static int sendevent(Client *c, Atom proto);
223static void sendmon(Client *c, Monitor *m);
224static void setclientstate(Client *c, long state);
225static void setclienttagprop(Client *c);
226static void setfocus(Client *c);
227static void setfullscreen(Client *c, int fullscreen);
228static void setlayout(const Arg *arg);
229static void setstatus(const Arg *arg);
230static void settagstate(void);
231static void togglelayout(const Arg *arg);
232static void rotatelayout(const Arg *arg);
233static void setup(void);
234static void seturgent(Client *c, int urg);
235static void showhide(Client *c);
236static void sigchld(int unused);
237static void spawn(const Arg *arg);
238static void tag(const Arg *arg);
239static void tagmon(const Arg *arg);
240static void nrowgrid(Monitor *);
241static void togglebar(const Arg *arg);
242static void togglefloating(const Arg *arg);
243static void togglegaps(const Arg *arg);
244static void togglesticky(const Arg *arg);
245static void toggletag(const Arg *arg);
246static void toggleview(const Arg *arg);
247static void unfocus(Client *c, int setfocus);
248static void unmanage(Client *c, int destroyed);
249static void unmapnotify(XEvent *e);
250static void updatebarpos(Monitor *m);
251static void updatebars(void);
252static void updateclientlist(void);
253static int updategeom(void);
254static void updatenumlockmask(void);
255static void updatesizehints(Client *c);
256static void updatetitle(Client *c);
257static void updatewindowtype(Client *c);
258static void updatewmhints(Client *c);
259static void view(const Arg *arg);
260static Client *wintoclient(Window w);
261static Monitor *wintomon(Window w);
262static int xerror(Display *dpy, XErrorEvent *ee);
263static int xerrordummy(Display *dpy, XErrorEvent *ee);
264static int xerrorstart(Display *dpy, XErrorEvent *ee);
265static void zoom(const Arg *arg);
266
267/* variables */
268static const char broken[] = "broken";
269static char stext[256] = "";
270static int screen;
271static int sw, sh;           /* X display screen geometry width, height */
272static int bh, blw = 0;      /* bar geometry */
273static int lrpad;            /* sum of left and right padding for text */
274static int (*xerrorxlib)(Display *, XErrorEvent *);
275static unsigned int numlockmask = 0;
276static void (*handler[LASTEvent]) (XEvent *) = {
277	[ButtonPress] = buttonpress,
278	[ClientMessage] = clientmessage,
279	[ConfigureRequest] = configurerequest,
280	[ConfigureNotify] = configurenotify,
281	[DestroyNotify] = destroynotify,
282	[Expose] = expose,
283	[FocusIn] = focusin,
284	[MapRequest] = maprequest,
285	[PropertyNotify] = propertynotify,
286	[UnmapNotify] = unmapnotify
287};
288static Atom wmatom[WMLast], netatom[NetLast];
289static int running = 1;
290static Cur *cursor[CurLast];
291static Clr **scheme;
292static Display *dpy;
293static Drw *drw;
294static Monitor *mons, *selmon;
295static Window root, wmcheckwin;
296static int fifofd;
297
298/* configuration, allows nested code to access above variables */
299#include "config.h"
300
301unsigned int tagw[LENGTH(tags)];
302
303struct Pertag {
304	unsigned int curtag, prevtag; /* current and previous tag */
305	int nmasters[LENGTH(tags) + 1]; /* number of windows in master area */
306	unsigned int sellts[LENGTH(tags) + 1]; /* selected layouts */
307	const Layout *ltidxs[LENGTH(tags) + 1][2]; /* matrix of tags and layouts indexes  */
308	int showbars[LENGTH(tags) + 1]; /* display bar for the current tag */
309	int enablegaps[LENGTH(tags) + 1];
310	int gaps[LENGTH(tags) + 1];
311};
312
313/* compile-time check if all tags fit into an unsigned int bit array. */
314struct NumTags { char limitexceeded[LENGTH(tags) > 31 ? -1 : 1]; };
315
316/* function implementations */
317int
318applysizehints(Client *c, int *x, int *y, int *w, int *h, int *bw, int interact)
319{
320	int baseismin;
321	Monitor *m = c->mon;
322
323	/* set minimum possible */
324	*w = MAX(1, *w);
325	*h = MAX(1, *h);
326	if (interact) {
327		if (*x > sw)
328			*x = sw - WIDTH(c);
329		if (*y > sh)
330			*y = sh - HEIGHT(c);
331		if (*x + *w + 2 * *bw < 0)
332			*x = 0;
333		if (*y + *h + 2 * *bw < 0)
334			*y = 0;
335	} else {
336		if (*x >= m->wx + m->ww)
337			*x = m->wx + m->ww - WIDTH(c);
338		if (*y >= m->wy + m->wh)
339			*y = m->wy + m->wh - HEIGHT(c);
340		if (*x + *w + 2 * *bw <= m->wx)
341			*x = m->wx;
342		if (*y + *h + 2 * *bw <= m->wy)
343			*y = m->wy;
344	}
345	if (*h < bh)
346		*h = bh;
347	if (*w < bh)
348		*w = bh;
349	if (resizehints || c->isfloating || !c->mon->lt[c->mon->sellt]->arrange) {
350		/* see last two sentences in ICCCM 4.1.2.3 */
351		baseismin = c->basew == c->minw && c->baseh == c->minh;
352		if (!baseismin) { /* temporarily remove base dimensions */
353			*w -= c->basew;
354			*h -= c->baseh;
355		}
356		/* adjust for aspect limits */
357		if (c->mina > 0 && c->maxa > 0) {
358			if (c->maxa < (float)*w / *h)
359				*w = *h * c->maxa + 0.5;
360			else if (c->mina < (float)*h / *w)
361				*h = *w * c->mina + 0.5;
362		}
363		if (baseismin) { /* increment calculation requires this */
364			*w -= c->basew;
365			*h -= c->baseh;
366		}
367		/* adjust for increment value */
368		if (c->incw)
369			*w -= *w % c->incw;
370		if (c->inch)
371			*h -= *h % c->inch;
372		/* restore base dimensions */
373		*w = MAX(*w + c->basew, c->minw);
374		*h = MAX(*h + c->baseh, c->minh);
375		if (c->maxw)
376			*w = MIN(*w, c->maxw);
377		if (c->maxh)
378			*h = MIN(*h, c->maxh);
379	}
380	return *x != c->x || *y != c->y || *w != c->w || *h != c->h || *bw != c->bw;
381}
382
383void
384arrange(Monitor *m)
385{
386	if (m)
387		showhide(m->stack);
388	else for (m = mons; m; m = m->next)
389		showhide(m->stack);
390	if (m) {
391		arrangemon(m);
392		restack(m);
393	} else for (m = mons; m; m = m->next)
394		arrangemon(m);
395}
396
397void
398arrangemon(Monitor *m)
399{
400	Client *c;
401
402	if (m->lt[m->sellt]->arrange)
403		m->lt[m->sellt]->arrange(m);
404	else
405		for (c = selmon->clients; c; c = c->next)
406			if (ISVISIBLE(c) && c->bw == 0)
407				resize(c, c->x, c->y, c->w - 2*borderpx, c->h - 2*borderpx, borderpx, 0);
408}
409
410void
411attach(Client *c)
412{
413	c->next = c->mon->clients;
414	c->mon->clients = c;
415}
416
417void
418attachabove(Client *c)
419{
420	if (c->mon->sel == NULL || c->mon->sel == c->mon->clients || c->mon->sel->isfloating) {
421		attach(c);
422		return;
423	}
424	
425	Client *at;
426	for (at = c->mon->clients; at->next != c->mon->sel; at = at->next);
427	c->next = at->next;
428	at->next = c;
429}
430
431void
432attachstack(Client *c)
433{
434	c->snext = c->mon->stack;
435	c->mon->stack = c;
436}
437
438void
439buttonpress(XEvent *e)
440{
441	unsigned int i, x, click, occ = 0;
442	Arg arg = {0};
443	Client *c;
444	Monitor *m;
445	XButtonPressedEvent *ev = &e->xbutton;
446
447	click = ClkRootWin;
448	/* focus monitor if necessary */
449	if ((m = wintomon(ev->window)) && m != selmon
450	    && (focusonwheel || (ev->button != Button4 && ev->button != Button5))) {
451		unfocus(selmon->sel, 1);
452		selmon = m;
453		focus(NULL);
454	}
455	if (ev->window == selmon->barwin) {
456		i = x = 0;
457		for (c = m->clients; c; c = c->next)
458			occ |= c->tags == 255 ? 0 : c->tags;
459		do {
460			/* do not reserve space for vacant tags */
461			if (!(occ & 1 << i || m->tagset[m->seltags] & 1 << i))
462				continue;
463			x += tagw[i];
464		} while (ev->x >= x && ++i < LENGTH(tags));
465		if (i < LENGTH(tags)) {
466			click = ClkTagBar;
467			arg.ui = 1 << i;
468		} else if (ev->x < x + blw)
469			click = ClkLtSymbol;
470		else if (ev->x > selmon->ww - i_basewidth)
471			click = ClkWMIcon;
472		else if (ev->x > selmon->ww - (int)TEXTW(stext))
473			click = ClkStatusText;
474		else
475			click = ClkWinTitle;
476	} else if ((c = wintoclient(ev->window))) {
477		if (focusonwheel || (ev->button != Button4 && ev->button != Button5))
478			focus(c);
479		XAllowEvents(dpy, ReplayPointer, CurrentTime);
480		click = ClkClientWin;
481	}
482	for (i = 0; i < LENGTH(buttons); i++)
483		if (click == buttons[i].click && buttons[i].func && buttons[i].button == ev->button
484		&& CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
485			buttons[i].func(click == ClkTagBar && buttons[i].arg.i == 0 ? &arg : &buttons[i].arg);
486}
487
488void
489checkotherwm(void)
490{
491	xerrorxlib = XSetErrorHandler(xerrorstart);
492	/* this causes an error if some other window manager is running */
493	XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
494	XSync(dpy, False);
495	XSetErrorHandler(xerror);
496	XSync(dpy, False);
497}
498
499void
500cleanup(void)
501{
502	Arg a = {.ui = ~0};
503	Layout foo = { NULL };
504	Monitor *m;
505	size_t i;
506
507	view(&a);
508	selmon->lt[selmon->sellt] = &foo;
509	for (m = mons; m; m = m->next)
510		while (m->stack)
511			unmanage(m->stack, 0);
512	XUngrabKey(dpy, AnyKey, AnyModifier, root);
513	while (mons)
514		cleanupmon(mons);
515	for (i = 0; i < CurLast; i++)
516		drw_cur_free(drw, cursor[i]);
517	for (i = 0; i < LENGTH(colors); i++)
518		free(scheme[i]);
519	XDestroyWindow(dpy, wmcheckwin);
520	drw_free(drw);
521	XSync(dpy, False);
522	XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
523	XDeleteProperty(dpy, root, netatom[NetActiveWindow]);
524	close(fifofd);
525}
526
527void
528cleanupmon(Monitor *mon)
529{
530	Monitor *m;
531
532	if (mon == mons)
533		mons = mons->next;
534	else {
535		for (m = mons; m && m->next != mon; m = m->next);
536		m->next = mon->next;
537	}
538	XUnmapWindow(dpy, mon->barwin);
539	XDestroyWindow(dpy, mon->barwin);
540	free(mon);
541}
542
543void
544clientmessage(XEvent *e)
545{
546	XClientMessageEvent *cme = &e->xclient;
547	Client *c = wintoclient(cme->window);
548
549	if (!c)
550		return;
551	if (cme->message_type == netatom[NetWMState]) {
552		if (cme->data.l[1] == netatom[NetWMFullscreen]
553		|| cme->data.l[2] == netatom[NetWMFullscreen])
554			setfullscreen(c, (cme->data.l[0] == 1 /* _NET_WM_STATE_ADD    */
555				|| (cme->data.l[0] == 2 /* _NET_WM_STATE_TOGGLE */ && !c->isfullscreen)));
556	} else if (cme->message_type == netatom[NetActiveWindow]) {
557		if (c != selmon->sel && !c->isurgent)
558			seturgent(c, 1);
559	}
560}
561
562void
563configure(Client *c)
564{
565	XConfigureEvent ce;
566
567	ce.type = ConfigureNotify;
568	ce.display = dpy;
569	ce.event = c->win;
570	ce.window = c->win;
571	ce.x = c->x;
572	ce.y = c->y;
573	ce.width = c->w;
574	ce.height = c->h;
575	ce.border_width = c->bw;
576	ce.above = None;
577	ce.override_redirect = False;
578	XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
579}
580
581void
582configurenotify(XEvent *e)
583{
584	Monitor *m;
585	Client *c;
586	XConfigureEvent *ev = &e->xconfigure;
587	int dirty;
588
589	/* TODO: updategeom handling sucks, needs to be simplified */
590	if (ev->window == root) {
591		dirty = (sw != ev->width || sh != ev->height);
592		sw = ev->width;
593		sh = ev->height;
594		if (updategeom() || dirty) {
595			drw_resize(drw, sw, bh);
596			updatebars();
597			for (m = mons; m; m = m->next) {
598				for (c = m->clients; c; c = c->next)
599					if (c->isfullscreen)
600						resizeclient(c, m->mx, m->my, m->mw, m->mh, 0);
601				XMoveResizeWindow(dpy, m->barwin, m->wx, m->by, m->ww, bh);
602			}
603			focus(NULL);
604			arrange(NULL);
605		}
606	}
607}
608
609void
610configurerequest(XEvent *e)
611{
612	Client *c;
613	Monitor *m;
614	XConfigureRequestEvent *ev = &e->xconfigurerequest;
615	XWindowChanges wc;
616
617	if ((c = wintoclient(ev->window))) {
618		if (ev->value_mask & CWBorderWidth)
619			c->bw = ev->border_width;
620		else if (c->isfloating || !selmon->lt[selmon->sellt]->arrange) {
621			m = c->mon;
622			if (ev->value_mask & CWX) {
623				c->oldx = c->x;
624				c->x = m->mx + ev->x;
625			}
626			if (ev->value_mask & CWY) {
627				c->oldy = c->y;
628				c->y = m->my + ev->y;
629			}
630			if (ev->value_mask & CWWidth) {
631				c->oldw = c->w;
632				c->w = ev->width;
633			}
634			if (ev->value_mask & CWHeight) {
635				c->oldh = c->h;
636				c->h = ev->height;
637			}
638			if ((c->x + c->w) > m->mx + m->mw && c->isfloating)
639				c->x = m->mx + (m->mw / 2 - WIDTH(c) / 2); /* center in x direction */
640			if ((c->y + c->h) > m->my + m->mh && c->isfloating)
641				c->y = m->my + (m->mh / 2 - HEIGHT(c) / 2); /* center in y direction */
642			if ((ev->value_mask & (CWX|CWY)) && !(ev->value_mask & (CWWidth|CWHeight)))
643				configure(c);
644			if (ISVISIBLE(c))
645				XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
646		} else
647			configure(c);
648	} else {
649		wc.x = ev->x;
650		wc.y = ev->y;
651		wc.width = ev->width;
652		wc.height = ev->height;
653		wc.border_width = ev->border_width;
654		wc.sibling = ev->above;
655		wc.stack_mode = ev->detail;
656		XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
657	}
658	XSync(dpy, False);
659}
660
661Monitor *
662createmon(void)
663{
664	Monitor *m;
665	unsigned int i;
666
667	m = ecalloc(1, sizeof(Monitor));
668	m->tagset[0] = m->tagset[1] = 1;
669	m->nmaster = nmaster;
670	m->showbar = showbar;
671	m->topbar = topbar;
672	m->gap = gap;
673	m->lt[0] = &layouts[0];
674	m->lt[1] = &layouts[1 % LENGTH(layouts)];
675	m->pertag = ecalloc(1, sizeof(Pertag));
676	m->pertag->curtag = m->pertag->prevtag = 1;
677	for (i = 0; i <= LENGTH(tags); i++) {
678		m->pertag->nmasters[i] = m->nmaster;
679
680		m->pertag->ltidxs[i][0] = m->lt[0];
681		m->pertag->ltidxs[i][1] = m->lt[1];
682		m->pertag->sellts[i] = m->sellt;
683		m->pertag->enablegaps[i] = 1;
684		m->pertag->gaps[i] = gap;
685
686		m->pertag->showbars[i] = m->showbar;
687	}
688	return m;
689}
690
691void
692destroynotify(XEvent *e)
693{
694	Client *c;
695	XDestroyWindowEvent *ev = &e->xdestroywindow;
696
697	if ((c = wintoclient(ev->window)))
698		unmanage(c, 1);
699}
700
701void
702detach(Client *c)
703{
704	Client **tc;
705
706	for (tc = &c->mon->clients; *tc && *tc != c; tc = &(*tc)->next);
707	*tc = c->next;
708}
709
710void
711detachstack(Client *c)
712{
713	Client **tc, *t;
714
715	for (tc = &c->mon->stack; *tc && *tc != c; tc = &(*tc)->snext);
716	*tc = c->snext;
717
718	if (c == c->mon->sel) {
719		for (t = c->mon->stack; t && !ISVISIBLE(t); t = t->snext);
720		c->mon->sel = t;
721	}
722}
723
724Monitor *
725dirtomon(int dir)
726{
727	Monitor *m = NULL;
728
729	if (dir > 0) {
730		if (!(m = selmon->next))
731			m = mons;
732	} else if (selmon == mons)
733		for (m = mons; m->next; m = m->next);
734	else
735		for (m = mons; m->next != selmon; m = m->next);
736	return m;
737}
738
739char *
740strmbtok(char *str, const char *toks)
741{
742	static char *tok = NULL;
743	char *lead = NULL;
744	Bool block = False;
745
746	if (str != NULL)
747		tok = lead = str;
748	else if (*(lead = tok) == '\0')
749		lead = NULL;
750
751	while (*tok != '\0') {
752		if (block && '\"' == *tok) {
753			block = False;
754		} else if (!block && '\"' == *tok) {
755			block = True;
756		} else if (!block && strchr(toks, *tok) != NULL) {
757			*tok = '\0';
758			tok++;
759			break;
760		}
761		tok++;
762	}
763	return lead;
764}
765
766void
767strsplit(char *str, char ***arr, const char *toks)
768{
769	char *p = strmbtok(str, toks);
770	int len = 0;
771
772	while (p) {
773		if ((*arr = realloc(*arr, sizeof (char*) * ++len)) == NULL)
774			die("realloc: failed\n");
775		(*arr)[len - 1] = p;
776		p = strmbtok(NULL, toks);
777	}
778
779	if ((*arr = realloc(*arr, sizeof (char*) * (len + 1))) == NULL)
780		die("realloc: failed\n");
781	(*arr)[len] = 0;
782}
783
784void
785dispatchline(const char *c, int n, void (*func)(const Arg *), const Arg *arg)
786{
787	char *line = NULL;
788	char **arr = NULL;
789	int len = strlen(c) - n;
790	Arg a;
791
792	if (len < 0)
793		return;
794
795	line = malloc(len + 1);
796
797	strcpy(line, c + n);
798	strsplit(line, &arr, " ");
799
800	switch (arg->i) {
801	case DispUi:
802		if (sscanf(arr[0], "%d", &a.i))
803			a.ui = 1 << a.i;
804	break;
805	case DispCmdLine:
806		a.v = (const char **)arr;
807	break;
808	}
809
810	func(&a);
811
812	free(line);
813	free(arr);
814}
815
816void
817dispatchcmd(void)
818{
819	char buf[BUFSIZ];
820	char *ptr, *line, *next;
821	ssize_t n, m;
822	int i;
823
824	if ((n = read(fifofd, buf, sizeof(buf) - 1)) == -1)
825		return;
826
827	buf[n] = '\0';
828	line = buf;
829
830	/* read each line as a single command */
831	while (line) {
832		next = strchr(line, '\n');
833		if (next)
834			*next = '\0';
835		for (i = 0; i < LENGTH(commands); i++) {
836			m = MAX(strlen(line), strlen(commands[i].name));
837			n = (((ptr = strstr(commands[i].name, "...")))
838				? ptr - commands[i].name
839				: m
840			);
841			if (strncmp(commands[i].name, line, n) == 0) {
842				if (n != m)
843					dispatchline(line, n, commands[i].func, &commands[i].arg);
844				else
845					commands[i].func(&commands[i].arg);
846				break;
847			}
848		}
849		if (next)
850			*next = '\n';
851		line = next ? next + 1 : NULL;
852	}
853
854	/* make sure fifo is empty */
855	while (errno != EWOULDBLOCK)
856		read(fifofd, buf, sizeof(buf) - 1);
857}
858
859void
860drawbar(Monitor *m)
861{
862	int x, w, tw = 0;
863	int tlpad;
864	unsigned int i, j, occ = 0, urg = 0;
865	char *ts = stext;
866	char *tp = stext;
867	int tx = 0;
868	char ctmp;
869	Client *c;
870	char taglabel[64];
871	char *masterclientontag[LENGTH(tags)];
872
873	/* draw status first so it can be overdrawn by tags later */
874	if (m == selmon) { /* status is only drawn on selected monitor */
875		drw_setscheme(drw, scheme[SchemeStatusNorm]);
876		/* get string width excluding color scheme references */
877		while (1) {
878			if ((unsigned int)*ts > LENGTH(colors)) { ts++; continue ; }
879			ctmp = *ts;
880			*ts = '\0';
881			tw += TEXTW(tp) -lrpad;
882			if (ctmp == '\0') { break; }
883			*ts = ctmp;
884			tp = ++ts;
885		}
886		tx = -i_basewidth;
887		ts = stext;
888		tp = stext;
889		while (1) {
890			if ((unsigned int)*ts > LENGTH(colors)) { ts++; continue ; }
891			ctmp = *ts;
892			*ts = '\0';
893			drw_text(drw, m->ww - tw + tx, 0, tw - tx, bh, 0, tp, 0);
894			tx += TEXTW(tp) -lrpad;
895			if (ctmp == '\0') { break; }
896			drw_setscheme(drw, scheme[(unsigned int)(ctmp-1)]);
897			*ts = ctmp;
898			tp = ++ts;
899		}
900		tw += i_basewidth;
901	}
902
903	/* draw wm icon */
904	drawicon(SchemeWMIcon, i_wmicon, LENGTH(i_wmicon), m->ww - i_basewidth);
905
906	for (i = 0; i < LENGTH(tags); i++)
907		masterclientontag[i] = NULL;
908
909	for (c = m->clients; c; c = c->next) {
910		occ |= c->tags == 255 ? 0 : c->tags;
911		if (c->isurgent)
912			urg |= c->tags;
913		for (i = 0; i < LENGTH(tags); i++)
914			if (!masterclientontag[i] && c->tags & (1 << i)) {
915				XClassHint ch = { NULL, NULL };
916				XGetClassHint(dpy, c->win, &ch);
917				if (!(masterclientontag[i] = ch.res_class))
918					continue;
919				/* to lower */
920				for(j = 0; masterclientontag[i][j]; j++)
921					masterclientontag[i][j] = tolower(masterclientontag[i][j]);
922			}
923	}
924
925	for (i = x = 0; i < LENGTH(tags); i++) {
926		/* do not draw vacant tags */
927		if (!(occ & 1 << i || m->tagset[m->seltags] & 1 << i))
928			continue;
929		if (masterclientontag[i])
930			snprintf(taglabel, 64, ptagf, tags[i], masterclientontag[i]);
931		else
932			snprintf(taglabel, 64, etagf, tags[i]);
933		masterclientontag[i] = taglabel;
934		tagw[i] = w = TEXTW(masterclientontag[i]);
935		drw_setscheme(drw,
936			scheme[m->tagset[m->seltags] & 1 << i ? SchemeTagsSel                   /* selected tag */
937			: selmon && selmon->sel && selmon->sel->tags & 1 << i ? SchemeTagsIncl  /* client in tag */
938			: SchemeTagsNorm]);
939		drw_text(drw, x, 0, w, bh, lrpad / 2, masterclientontag[i], urg & 1 << i);
940		if (m->tagset[m->seltags] & 1 << i)
941			drw_rect(drw, x + ulinepad, bh - ulinestroke - ulinevoffset, w - (ulinepad * 2), ulinestroke, 1, ColBorder);
942		x += w;
943	}
944
945	/* draw layout icon */
946	drawicon(SchemeLayout, m->lt[selmon->sellt]->icon, m->lt[selmon->sellt]->vectlength, x);
947	x += blw = i_basewidth;
948
949	if ((w = m->ww - tw - x) > bh) {
950		if (m->sel) {
951			drw_setscheme(drw, scheme[m == selmon ? SchemeTitleSel : SchemeTitleNorm]);
952			tlpad = (m->ww - ((int)TEXTW(m->sel->name) - lrpad)) / 2 - x;
953			if (TEXTW(m->sel->name) + tlpad > (m->ww - tw - x))
954				drw_text(drw, x, 0, w, bh, lrpad / 2, m->sel->name, 0);
955			else
956				drw_text(drw, x, 0, w, bh, tlpad, m->sel->name, 0);
957		} else {
958			drw_setscheme(drw, scheme[SchemeTitleNorm]);
959			drw_rect(drw, x, 0, w, bh, 1, ColBg);
960		}
961	}
962	drw_map(drw, m->barwin, 0, 0, m->ww, bh);
963}
964
965void
966drawbars(void)
967{
968	Monitor *m;
969
970	for (m = mons; m; m = m->next)
971		drawbar(m);
972}
973
974void
975drawicon(int scheme_type, int *icon, int size, int offset)
976{
977	int i, x, y;
978	if (size == 0 || size % 4 != 0)
979		return;
980
981	for (i = x = y = 0; i < size;
982	     x = MAX(x, icon[i + 0] + icon[i + 2]),
983	     y = MAX(y, icon[i + 1] + icon[i + 3]), i+=4);
984	x = (i_basewidth - x) / 2 + offset;
985	y = (bh - y) / 2;
986
987	drw_setscheme(drw, scheme[scheme_type]);
988
989	/* draw icon */
990	drw_rect(drw, offset, 0, i_basewidth, bh, 1, ColBg);
991	for (i = 0; i < size; i+=4)
992		drw_rect(drw, x + icon[i], y + icon[i+1], icon[i+2], icon[i+3], 1, ColFg);
993}
994
995void
996enqueue(Client *c)
997{
998	Client *l;
999	for (l = c->mon->clients; l && l->next; l = l->next);
1000	if (l) {
1001		l->next = c;
1002		c->next = NULL;
1003	}
1004}
1005
1006void
1007enqueuestack(Client *c)
1008{
1009	Client *l;
1010	for (l = c->mon->stack; l && l->snext; l = l->snext);
1011	if (l) {
1012		l->snext = c;
1013		c->snext = NULL;
1014	}
1015}
1016
1017Bool
1018evpredicate()
1019{
1020	return True;
1021}
1022
1023void
1024expose(XEvent *e)
1025{
1026	Monitor *m;
1027	XExposeEvent *ev = &e->xexpose;
1028
1029	if (ev->count == 0 && (m = wintomon(ev->window)))
1030		drawbar(m);
1031}
1032
1033void
1034focus(Client *c)
1035{
1036	XWindowChanges wc;
1037
1038	if (!c || !ISVISIBLE(c))
1039		for (c = selmon->stack; c && !ISVISIBLE(c); c = c->snext);
1040	if (selmon->sel && selmon->sel != c)
1041		unfocus(selmon->sel, 0);
1042	if (c) {
1043		if (c->mon != selmon)
1044			selmon = c->mon;
1045		if (c->isurgent)
1046			seturgent(c, 0);
1047		detachstack(c);
1048		attachstack(c);
1049		grabbuttons(c, 1);
1050		if (c->isfloating)
1051			XSetWindowBorder(dpy, c->win, scheme[SchemeSel][ColFloat].pixel);
1052		else {
1053			wc.sibling = selmon->barwin;
1054			wc.stack_mode = Below;
1055			XConfigureWindow(dpy, c->win, CWSibling | CWStackMode, &wc);
1056			XSetWindowBorder(dpy, c->win, scheme[SchemeSel][ColBorder].pixel);
1057		}
1058		setfocus(c);
1059	} else {
1060		XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
1061		XDeleteProperty(dpy, root, netatom[NetActiveWindow]);
1062	}
1063	selmon->sel = c;
1064	drawbars();
1065}
1066
1067/* there are some broken focus acquiring clients needing extra handling */
1068void
1069focusin(XEvent *e)
1070{
1071	XFocusChangeEvent *ev = &e->xfocus;
1072
1073	if (selmon->sel && ev->window != selmon->sel->win)
1074		setfocus(selmon->sel);
1075}
1076
1077void
1078focusmon(const Arg *arg)
1079{
1080	Monitor *m;
1081
1082	if (!mons->next)
1083		return;
1084	if ((m = dirtomon(arg->i)) == selmon)
1085		return;
1086	unfocus(selmon->sel, 0);
1087	selmon = m;
1088	focus(NULL);
1089}
1090
1091void
1092focusstack(const Arg *arg)
1093{
1094	Client *c = NULL, *i;
1095
1096	if (!selmon->sel)
1097		return;
1098	if (arg->i > 0) {
1099		for (c = selmon->sel->next; c && !ISVISIBLE(c); c = c->next);
1100		if (!c)
1101			for (c = selmon->clients; c && !ISVISIBLE(c); c = c->next);
1102	} else {
1103		for (i = selmon->clients; i != selmon->sel; i = i->next)
1104			if (ISVISIBLE(i))
1105				c = i;
1106		if (!c)
1107			for (; i; i = i->next)
1108				if (ISVISIBLE(i))
1109					c = i;
1110	}
1111	if (c) {
1112		focus(c);
1113		restack(selmon);
1114	}
1115}
1116
1117Atom
1118getatomprop(Client *c, Atom prop)
1119{
1120	int di;
1121	unsigned long dl;
1122	unsigned char *p = NULL;
1123	Atom da, atom = None;
1124
1125	if (XGetWindowProperty(dpy, c->win, prop, 0L, sizeof atom, False, XA_ATOM,
1126		&da, &di, &dl, &dl, &p) == Success && p) {
1127		atom = *(Atom *)p;
1128		XFree(p);
1129	}
1130	return atom;
1131}
1132
1133int
1134getrootptr(int *x, int *y)
1135{
1136	int di;
1137	unsigned int dui;
1138	Window dummy;
1139
1140	return XQueryPointer(dpy, root, &dummy, &dummy, x, y, &di, &di, &dui);
1141}
1142
1143long
1144getstate(Window w)
1145{
1146	int format;
1147	long result = -1;
1148	unsigned char *p = NULL;
1149	unsigned long n, extra;
1150	Atom real;
1151
1152	if (XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
1153		&real, &format, &n, &extra, (unsigned char **)&p) != Success)
1154		return -1;
1155	if (n != 0)
1156		result = *p;
1157	XFree(p);
1158	return result;
1159}
1160
1161int
1162gettextprop(Window w, Atom atom, char *text, unsigned int size)
1163{
1164	char **list = NULL;
1165	int n;
1166	XTextProperty name;
1167
1168	if (!text || size == 0)
1169		return 0;
1170	text[0] = '\0';
1171	if (!XGetTextProperty(dpy, w, &name, atom) || !name.nitems)
1172		return 0;
1173	if (name.encoding == XA_STRING)
1174		strncpy(text, (char *)name.value, size - 1);
1175	else {
1176		if (XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success && n > 0 && *list) {
1177			strncpy(text, *list, size - 1);
1178			XFreeStringList(list);
1179		}
1180	}
1181	text[size - 1] = '\0';
1182	XFree(name.value);
1183	return 1;
1184}
1185
1186void
1187grabbuttons(Client *c, int focused)
1188{
1189	updatenumlockmask();
1190	{
1191		unsigned int i, j;
1192		unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
1193		XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1194		if (!focused)
1195			XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
1196				BUTTONMASK, GrabModeSync, GrabModeSync, None, None);
1197		for (i = 0; i < LENGTH(buttons); i++)
1198			if (buttons[i].click == ClkClientWin)
1199				for (j = 0; j < LENGTH(modifiers); j++)
1200					XGrabButton(dpy, buttons[i].button,
1201						buttons[i].mask | modifiers[j],
1202						c->win, False, BUTTONMASK,
1203						GrabModeAsync, GrabModeSync, None, None);
1204	}
1205}
1206
1207void
1208incgaps(const Arg *arg)
1209{
1210	selmon->gap = selmon->pertag->gaps[selmon->pertag->curtag] = MAX(selmon->gap + arg->i, 0);
1211	arrange(selmon);
1212}
1213
1214void
1215incnmaster(const Arg *arg)
1216{
1217	selmon->nmaster = selmon->pertag->nmasters[selmon->pertag->curtag] = MAX(selmon->nmaster + arg->i, 1);
1218	arrange(selmon);
1219}
1220
1221#ifdef XINERAMA
1222static int
1223isuniquegeom(XineramaScreenInfo *unique, size_t n, XineramaScreenInfo *info)
1224{
1225	while (n--)
1226		if (unique[n].x_org == info->x_org && unique[n].y_org == info->y_org
1227		&& unique[n].width == info->width && unique[n].height == info->height)
1228			return 0;
1229	return 1;
1230}
1231#endif /* XINERAMA */
1232
1233void
1234killclient(const Arg *arg)
1235{
1236	if (!selmon->sel)
1237		return;
1238	if (!sendevent(selmon->sel, wmatom[WMDelete])) {
1239		XGrabServer(dpy);
1240		XSetErrorHandler(xerrordummy);
1241		XSetCloseDownMode(dpy, DestroyAll);
1242		XKillClient(dpy, selmon->sel->win);
1243		XSync(dpy, False);
1244		XSetErrorHandler(xerror);
1245		XUngrabServer(dpy);
1246	}
1247}
1248
1249void
1250loadxresources(void)
1251{
1252	Display *display;
1253	char *resm;
1254	XrmDatabase db;
1255	ResourcePref *p;
1256
1257	display = XOpenDisplay(NULL);
1258	resm = XResourceManagerString(display);
1259	if (!resm)
1260		return;
1261
1262	db = XrmGetStringDatabase(resm);
1263	for (p = resources; p < resources + LENGTH(resources); p++)
1264		resourceload(db, p->name, p->type, p->dst);
1265	XCloseDisplay(display);
1266}
1267
1268void
1269loadstate(int atom_type, Window win, Client *c)
1270{
1271	int format;
1272	unsigned long *data, n, extra, length = (
1273		atom_type == NetClientInfo ? 2L
1274		: atom_type == NetTagState ? 1L
1275		: 0L);
1276	Monitor *m;
1277	Atom atom, req_type = (
1278		atom_type == NetClientInfo ? XA_CARDINAL
1279		: atom_type == NetTagState ? XA_INTEGER
1280		: AnyPropertyType);
1281
1282	if (XGetWindowProperty(dpy, win, netatom[atom_type], 0L, length, False, req_type, &atom, &format, &n, &extra, (unsigned char **)&data) == Success) {
1283		if (atom_type == NetClientInfo && n == 2) {
1284			c->tags = *data;
1285			for (m = mons; m; m = m->next)
1286				if (m->num == *(data+1) && (c->mon = m) == m)
1287					break;
1288		} else if (atom_type == NetTagState && n == 1) {
1289			selmon->tagset[selmon->seltags] = (unsigned int)*data;
1290		}
1291	}
1292	if (n > 0) /* clean up */
1293		XFree(data);
1294}
1295
1296void
1297manage(Window w, XWindowAttributes *wa)
1298{
1299	Client *c, *t = NULL;
1300	Window trans = None;
1301	XWindowChanges wc;
1302
1303	c = ecalloc(1, sizeof(Client));
1304	c->win = w;
1305	/* geometry */
1306	c->x = c->oldx = wa->x;
1307	c->y = c->oldy = wa->y;
1308	c->w = c->oldw = wa->width;
1309	c->h = c->oldh = wa->height;
1310	c->oldbw = wa->border_width;
1311
1312	updatetitle(c);
1313	if (XGetTransientForHint(dpy, w, &trans) && (t = wintoclient(trans))) {
1314		c->mon = t->mon;
1315		c->tags = t->tags;
1316	} else {
1317		c->mon = selmon;
1318		c->isfloating = 0;
1319		c->tags = c->tags & TAGMASK ? c->tags & TAGMASK
1320			: c->mon->tagset[c->mon->seltags]
1321			? c->mon->tagset[c->mon->seltags]
1322			: 1;
1323	}
1324
1325	if (c->x + WIDTH(c) > c->mon->mx + c->mon->mw)
1326		c->x = c->mon->mx + c->mon->mw - WIDTH(c);
1327	if (c->y + HEIGHT(c) > c->mon->my + c->mon->mh)
1328		c->y = c->mon->my + c->mon->mh - HEIGHT(c);
1329	c->x = MAX(c->x, c->mon->mx);
1330	/* only fix client y-offset, if the client center might cover the bar */
1331	c->y = MAX(c->y, ((c->mon->by == c->mon->my) && (c->x + (c->w / 2) >= c->mon->wx)
1332		&& (c->x + (c->w / 2) < c->mon->wx + c->mon->ww)) ? bh : c->mon->my);
1333	c->bw = borderpx;
1334
1335	wc.border_width = c->bw;
1336	XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1337	if (c->isfloating)
1338		XSetWindowBorder(dpy, w, scheme[SchemeNorm][ColFloat].pixel);
1339	else
1340		XSetWindowBorder(dpy, w, scheme[SchemeNorm][ColBorder].pixel);
1341	configure(c); /* propagates border_width, if size doesn't change */
1342	updatewindowtype(c);
1343	updatesizehints(c);
1344	updatewmhints(c);
1345	loadstate(NetClientInfo, c->win, c);
1346	setclienttagprop(c);
1347
1348	XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
1349	grabbuttons(c, 0);
1350	if (!c->isfloating)
1351		c->isfloating = c->oldstate = trans != None || c->isfixed;
1352	if (c->isfloating)
1353		XRaiseWindow(dpy, c->win);
1354	if (c->isfloating)
1355		XSetWindowBorder(dpy, w, scheme[SchemeNorm][ColFloat].pixel);
1356	attachabove(c);
1357	attachstack(c);
1358	XChangeProperty(dpy, root, netatom[NetClientList], XA_WINDOW, 32, PropModeAppend,
1359		(unsigned char *) &(c->win), 1);
1360	XMoveResizeWindow(dpy, c->win, c->x + 2 * sw, c->y, c->w, c->h); /* some windows require this */
1361	setclientstate(c, NormalState);
1362	if (c->mon == selmon)
1363		unfocus(selmon->sel, 0);
1364	c->mon->sel = c;
1365	arrange(c->mon);
1366	XMapWindow(dpy, c->win);
1367	focus(NULL);
1368}
1369
1370void
1371maprequest(XEvent *e)
1372{
1373	static XWindowAttributes wa;
1374	XMapRequestEvent *ev = &e->xmaprequest;
1375
1376	if (!XGetWindowAttributes(dpy, ev->window, &wa))
1377		return;
1378	if (wa.override_redirect)
1379		return;
1380	if (!wintoclient(ev->window))
1381		manage(ev->window, &wa);
1382}
1383
1384void
1385monocle(Monitor *m)
1386{
1387	Client *c;
1388	for (c = nextinstack(m->clients); c; c = nextinstack(c->next))
1389		resize(c, m->wx, m->wy, m->ww, m->wh, 0, 0);
1390}
1391
1392void
1393movemouse(const Arg *arg)
1394{
1395	int x, y, ocx, ocy, nx, ny;
1396	Client *c;
1397	Monitor *m;
1398	XEvent ev;
1399	Time lasttime = 0;
1400
1401	if (!(c = selmon->sel))
1402		return;
1403	if (c->isfullscreen) /* no support moving fullscreen windows by mouse */
1404		return;
1405	restack(selmon);
1406	ocx = c->x;
1407	ocy = c->y;
1408	if (XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1409		None, cursor[CurMove]->cursor, CurrentTime) != GrabSuccess)
1410		return;
1411	if (!getrootptr(&x, &y))
1412		return;
1413	do {
1414		XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1415		switch(ev.type) {
1416		case ConfigureRequest:
1417		case Expose:
1418		case MapRequest:
1419			handler[ev.type](&ev);
1420			break;
1421		case MotionNotify:
1422			if ((ev.xmotion.time - lasttime) <= (1000 / 60))
1423				continue;
1424			lasttime = ev.xmotion.time;
1425
1426			nx = ocx + (ev.xmotion.x - x);
1427			ny = ocy + (ev.xmotion.y - y);
1428			if (abs(selmon->wx - nx) < snap)
1429				nx = selmon->wx;
1430			else if (abs((selmon->wx + selmon->ww) - (nx + WIDTH(c))) < snap)
1431				nx = selmon->wx + selmon->ww - WIDTH(c);
1432			if (abs(selmon->wy - ny) < snap)
1433				ny = selmon->wy;
1434			else if (abs((selmon->wy + selmon->wh) - (ny + HEIGHT(c))) < snap)
1435				ny = selmon->wy + selmon->wh - HEIGHT(c);
1436			if (!c->isfloating && selmon->lt[selmon->sellt]->arrange
1437			&& (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
1438				togglefloating(NULL);
1439			if (!selmon->lt[selmon->sellt]->arrange || c->isfloating)
1440				resize(c, nx, ny, c->w, c->h, c->bw, 1);
1441			break;
1442		}
1443	} while (ev.type != ButtonRelease);
1444	XUngrabPointer(dpy, CurrentTime);
1445	if ((m = recttomon(c->x, c->y, c->w, c->h)) != selmon) {
1446		sendmon(c, m);
1447		selmon = m;
1448		focus(NULL);
1449	}
1450}
1451
1452Client *
1453nextinstack(Client *c)
1454{
1455	for (; c && (c->isfloating || !ISVISIBLE(c)); c = c->next);
1456	return c;
1457}
1458
1459void
1460pop(Client *c)
1461{
1462	detach(c);
1463	attach(c);
1464	focus(c);
1465	arrange(c->mon);
1466}
1467
1468void
1469propertynotify(XEvent *e)
1470{
1471	Client *c;
1472	Window trans;
1473	XPropertyEvent *ev = &e->xproperty;
1474
1475	if (ev->state == PropertyDelete)
1476		return; /* ignore */
1477	else if ((c = wintoclient(ev->window))) {
1478		switch(ev->atom) {
1479		default: break;
1480		case XA_WM_TRANSIENT_FOR:
1481			if (!c->isfloating && (XGetTransientForHint(dpy, c->win, &trans)) &&
1482				(c->isfloating = (wintoclient(trans)) != NULL))
1483				arrange(c->mon);
1484			break;
1485		case XA_WM_NORMAL_HINTS:
1486			updatesizehints(c);
1487			break;
1488		case XA_WM_HINTS:
1489			updatewmhints(c);
1490			drawbars();
1491			break;
1492		}
1493		if (ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1494			updatetitle(c);
1495			if (c == c->mon->sel)
1496				drawbar(c->mon);
1497		}
1498		if (ev->atom == netatom[NetWMWindowType])
1499			updatewindowtype(c);
1500	}
1501}
1502
1503void
1504quit(const Arg *arg)
1505{
1506	running = 0;
1507}
1508
1509Monitor *
1510recttomon(int x, int y, int w, int h)
1511{
1512	Monitor *m, *r = selmon;
1513	int a, area = 0;
1514
1515	for (m = mons; m; m = m->next)
1516		if ((a = INTERSECT(x, y, w, h, m)) > area) {
1517			area = a;
1518			r = m;
1519		}
1520	return r;
1521}
1522
1523void
1524resize(Client *c, int x, int y, int w, int h, int bw, int interact)
1525{
1526	if (applysizehints(c, &x, &y, &w, &h, &bw, interact))
1527		resizeclient(c, x, y, w, h, bw);
1528}
1529
1530void
1531resizeclient(Client *c, int x, int y, int w, int h, int bw)
1532{
1533	XWindowChanges wc;
1534
1535	c->oldx = c->x; c->x = wc.x = x;
1536	c->oldy = c->y; c->y = wc.y = y;
1537	c->oldw = c->w; c->w = wc.width = w;
1538	c->oldh = c->h; c->h = wc.height = h;
1539	c->oldbw = c->bw; c->bw = wc.border_width = bw;
1540	if (((nextinstack(c->mon->clients) == c && !nextinstack(c->next))
1541		|| &monocle == c->mon->lt[c->mon->sellt]->arrange)
1542		&& !c->isfullscreen
1543		&& !c->isfloating
1544		&& !c->mon->pertag->enablegaps[c->mon->pertag->curtag]) {
1545			c->w = wc.width += c->bw * 2;
1546			c->h = wc.height += c->bw * 2;
1547			wc.border_width = 0;
1548	}
1549	XConfigureWindow(dpy, c->win, CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1550	configure(c);
1551	XSync(dpy, False);
1552}
1553
1554void
1555resizemouse(const Arg *arg)
1556{
1557	int ocx, ocy, nw, nh;
1558	Client *c;
1559	Monitor *m;
1560	XEvent ev;
1561	Time lasttime = 0;
1562
1563	if (!(c = selmon->sel))
1564		return;
1565	if (c->isfullscreen) /* no support resizing fullscreen windows by mouse */
1566		return;
1567	restack(selmon);
1568	ocx = c->x;
1569	ocy = c->y;
1570	if (XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1571		None, cursor[CurResize]->cursor, CurrentTime) != GrabSuccess)
1572		return;
1573	XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1574	do {
1575		XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1576		switch(ev.type) {
1577		case ConfigureRequest:
1578		case Expose:
1579		case MapRequest:
1580			handler[ev.type](&ev);
1581			break;
1582		case MotionNotify:
1583			if ((ev.xmotion.time - lasttime) <= (1000 / 60))
1584				continue;
1585			lasttime = ev.xmotion.time;
1586
1587			nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1588			nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1589			if (c->mon->wx + nw >= selmon->wx && c->mon->wx + nw <= selmon->wx + selmon->ww
1590			&& c->mon->wy + nh >= selmon->wy && c->mon->wy + nh <= selmon->wy + selmon->wh)
1591			{
1592				if (!c->isfloating && selmon->lt[selmon->sellt]->arrange
1593				&& (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1594					togglefloating(NULL);
1595			}
1596			if (!selmon->lt[selmon->sellt]->arrange || c->isfloating)
1597				resize(c, c->x, c->y, nw, nh, c->bw, 1);
1598			break;
1599		}
1600	} while (ev.type != ButtonRelease);
1601	XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1602	XUngrabPointer(dpy, CurrentTime);
1603	while (XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1604	if ((m = recttomon(c->x, c->y, c->w, c->h)) != selmon) {
1605		sendmon(c, m);
1606		selmon = m;
1607		focus(NULL);
1608	}
1609}
1610
1611void
1612restack(Monitor *m)
1613{
1614	Client *c;
1615	XEvent ev;
1616	XWindowChanges wc;
1617
1618	drawbar(m);
1619	if (!m->sel)
1620		return;
1621	if (m->sel->isfloating || !m->lt[m->sellt]->arrange)
1622		XRaiseWindow(dpy, m->sel->win);
1623	if (m->lt[m->sellt]->arrange) {
1624		wc.stack_mode = Below;
1625		wc.sibling = m->barwin;
1626		for (c = m->stack; c; c = c->snext)
1627			if (!c->isfloating && ISVISIBLE(c)) {
1628				XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1629				wc.sibling = c->win;
1630			}
1631	}
1632	XSync(dpy, False);
1633	while (XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1634}
1635
1636void
1637movestack(const Arg *arg)
1638{
1639	Client *c = NULL, *p = NULL, *pc = NULL, *i;
1640
1641	if(arg->i > 0) {
1642		/* find the client after selmon->sel */
1643		for(c = selmon->sel->next; c && (!ISVISIBLE(c) || c->isfloating); c = c->next);
1644		if(!c)
1645			for(c = selmon->clients; c && (!ISVISIBLE(c) || c->isfloating); c = c->next);
1646
1647	}
1648	else {
1649		/* find the client before selmon->sel */
1650		for(i = selmon->clients; i != selmon->sel; i = i->next)
1651			if(ISVISIBLE(i) && !i->isfloating)
1652				c = i;
1653		if(!c)
1654			for(; i; i = i->next)
1655				if(ISVISIBLE(i) && !i->isfloating)
1656					c = i;
1657	}
1658	/* find the client before selmon->sel and c */
1659	for(i = selmon->clients; i && (!p || !pc); i = i->next) {
1660		if(i->next == selmon->sel)
1661			p = i;
1662		if(i->next == c)
1663			pc = i;
1664	}
1665
1666	/* swap c and selmon->sel selmon->clients in the selmon->clients list */
1667	if(c && c != selmon->sel) {
1668		Client *temp = selmon->sel->next==c?selmon->sel:selmon->sel->next;
1669		selmon->sel->next = c->next==selmon->sel?c:c->next;
1670		c->next = temp;
1671
1672		if(p && p != c)
1673			p->next = c;
1674		if(pc && pc != selmon->sel)
1675			pc->next = selmon->sel;
1676
1677		if(selmon->sel == selmon->clients)
1678			selmon->clients = c;
1679		else if(c == selmon->clients)
1680			selmon->clients = selmon->sel;
1681
1682		arrange(selmon);
1683	}
1684}
1685
1686void
1687rotatestack(const Arg *arg)
1688{
1689	Client *c = NULL, *f;
1690
1691	if (!selmon->sel)
1692		return;
1693	f = selmon->sel;
1694	if (arg->i > 0) {
1695		for (c = nextinstack(selmon->clients); c && nextinstack(c->next); c = nextinstack(c->next));
1696		if (c){
1697			detach(c);
1698			attach(c);
1699			detachstack(c);
1700			attachstack(c);
1701		}
1702	} else {
1703		if ((c = nextinstack(selmon->clients))){
1704			detach(c);
1705			enqueue(c);
1706			detachstack(c);
1707			enqueuestack(c);
1708		}
1709	}
1710	if (c){
1711		arrange(selmon);
1712		//unfocus(f, 1);
1713		focus(f);
1714		restack(selmon);
1715	}
1716}
1717
1718void
1719run(void)
1720{
1721	XEvent ev;
1722	struct pollfd fds[2] = {
1723		{ .events = POLLIN },
1724		{ .fd = fifofd, .events = POLLIN }
1725	};
1726	/* main event loop */
1727	XSync(dpy, False);
1728	fds[0].fd = ConnectionNumber(dpy);
1729	while (running) {
1730		(void)poll(fds, 1[&fds] - fds, -1);
1731		if (fds[1].revents & POLLIN)
1732			 dispatchcmd();
1733		if (fds[0].revents & POLLIN)
1734			while (XCheckIfEvent(dpy, &ev, evpredicate, NULL))
1735				if (handler[ev.type])
1736					handler[ev.type](&ev); /* call handler */
1737	}
1738}
1739
1740void
1741scan(void)
1742{
1743	unsigned int i, num;
1744	Window d1, d2, *wins = NULL;
1745	XWindowAttributes wa;
1746
1747	if (XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1748		for (i = 0; i < num; i++) {
1749			if (!XGetWindowAttributes(dpy, wins[i], &wa)
1750			|| wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1751				continue;
1752			if (wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1753				manage(wins[i], &wa);
1754		}
1755		for (i = 0; i < num; i++) { /* now the transients */
1756			if (!XGetWindowAttributes(dpy, wins[i], &wa))
1757				continue;
1758			if (XGetTransientForHint(dpy, wins[i], &d1)
1759			&& (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1760				manage(wins[i], &wa);
1761		}
1762		if (wins)
1763			XFree(wins);
1764	}
1765}
1766
1767void
1768sendmon(Client *c, Monitor *m)
1769{
1770	if (c->mon == m)
1771		return;
1772	unfocus(c, 1);
1773	detach(c);
1774	detachstack(c);
1775	c->mon = m;
1776	c->tags = (m->tagset[m->seltags] ? m->tagset[m->seltags] : 1);
1777	attachabove(c);
1778	attachstack(c);
1779	setclienttagprop(c);
1780	focus(NULL);
1781	arrange(NULL);
1782}
1783
1784void
1785setclientstate(Client *c, long state)
1786{
1787	long data[] = { state, None };
1788
1789	XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1790		PropModeReplace, (unsigned char *)data, 2);
1791}
1792
1793void
1794setclienttagprop(Client *c)
1795{
1796	long data[] = { (long) c->tags, (long) c->mon->num };
1797	XChangeProperty(dpy, c->win, netatom[NetClientInfo], XA_CARDINAL, 32,
1798			PropModeReplace, (unsigned char *) data, 2);
1799}
1800
1801int
1802sendevent(Client *c, Atom proto)
1803{
1804	int n;
1805	Atom *protocols;
1806	int exists = 0;
1807	XEvent ev;
1808
1809	if (XGetWMProtocols(dpy, c->win, &protocols, &n)) {
1810		while (!exists && n--)
1811			exists = protocols[n] == proto;
1812		XFree(protocols);
1813	}
1814	if (exists) {
1815		ev.type = ClientMessage;
1816		ev.xclient.window = c->win;
1817		ev.xclient.message_type = wmatom[WMProtocols];
1818		ev.xclient.format = 32;
1819		ev.xclient.data.l[0] = proto;
1820		ev.xclient.data.l[1] = CurrentTime;
1821		XSendEvent(dpy, c->win, False, NoEventMask, &ev);
1822	}
1823	return exists;
1824}
1825
1826void
1827setfocus(Client *c)
1828{
1829	if (!c->neverfocus) {
1830		XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
1831		XChangeProperty(dpy, root, netatom[NetActiveWindow],
1832			XA_WINDOW, 32, PropModeReplace,
1833			(unsigned char *) &(c->win), 1);
1834	}
1835	sendevent(c, wmatom[WMTakeFocus]);
1836}
1837
1838void
1839setfullscreen(Client *c, int fullscreen)
1840{
1841	if (fullscreen && !c->isfullscreen) {
1842		XChangeProperty(dpy, c->win, netatom[NetWMState], XA_ATOM, 32,
1843			PropModeReplace, (unsigned char*)&netatom[NetWMFullscreen], 1);
1844		c->isfullscreen = 1;
1845		c->oldstate = c->isfloating;
1846		c->isfloating = 1;
1847		resizeclient(c, c->mon->mx, c->mon->my, c->mon->mw, c->mon->mh, 0);
1848		XRaiseWindow(dpy, c->win);
1849	} else if (!fullscreen && c->isfullscreen){
1850		XChangeProperty(dpy, c->win, netatom[NetWMState], XA_ATOM, 32,
1851			PropModeReplace, (unsigned char*)0, 0);
1852		c->isfullscreen = 0;
1853		c->isfloating = c->oldstate;
1854		c->x = c->oldx;
1855		c->y = c->oldy;
1856		c->w = c->oldw;
1857		c->h = c->oldh;
1858		c->bw = c->oldbw;
1859		resizeclient(c, c->x, c->y, c->w, c->h, c->bw);
1860		arrange(c->mon);
1861	}
1862}
1863
1864void
1865setlayout(const Arg *arg)
1866{
1867	if (!arg || !arg->v || arg->v != selmon->lt[selmon->sellt])
1868		selmon->sellt = selmon->pertag->sellts[selmon->pertag->curtag] ^= 1;
1869	if (arg && arg->v)
1870		selmon->lt[selmon->sellt] = selmon->pertag->ltidxs[selmon->pertag->curtag][selmon->sellt] = (Layout *)arg->v;
1871	if (selmon->sel)
1872		arrange(selmon);
1873	else
1874		drawbar(selmon);
1875}
1876
1877void
1878settagstate(void)
1879{
1880	if (running) {
1881		long data[] = { (long)selmon->tagset[selmon->seltags] };
1882		XChangeProperty(dpy, root, netatom[NetTagState], XA_INTEGER, 32, PropModeReplace, (unsigned char *) data, 1);
1883	}
1884}
1885
1886void
1887togglelayout(const Arg *arg)
1888{
1889	if (selmon->pertag->ltidxs[selmon->pertag->curtag][selmon->sellt] != (Layout *)arg->v)
1890		setlayout(arg);
1891	else
1892		setlayout(0);
1893}
1894
1895void
1896rotatelayout(const Arg *arg)
1897{
1898	int i,
1899		idx = -1,
1900		max = LENGTH(layouts);
1901
1902	if (!arg || !arg->i || arg->i == 0)
1903		return;
1904
1905	for (i = 0; i < max && idx == -1; i++) {
1906		if (selmon->lt[selmon->sellt] == &layouts[i])
1907			idx = i;
1908	}
1909
1910	if (idx == -1)
1911		return;
1912
1913	if (arg->i < 0 && idx-- == 0)
1914		idx = max - 1;
1915
1916	if (arg->i > 0 && idx++ == max - 1)
1917		idx = 0;
1918
1919	selmon->pertag->ltidxs[selmon->pertag->curtag][selmon->sellt] = &layouts[idx];
1920	selmon->lt[selmon->sellt] = selmon->pertag->ltidxs[selmon->pertag->curtag][selmon->sellt];
1921	if (selmon->sel)
1922		arrange(selmon);
1923	else
1924		drawbar(selmon);
1925}
1926
1927void
1928setup(void)
1929{
1930	int i;
1931	XSetWindowAttributes wa;
1932	Atom utf8string;
1933
1934	/* clean up any zombies immediately */
1935	sigchld(0);
1936
1937	/* init screen */
1938	screen = DefaultScreen(dpy);
1939	sw = DisplayWidth(dpy, screen);
1940	sh = DisplayHeight(dpy, screen);
1941	root = RootWindow(dpy, screen);
1942	drw = drw_create(dpy, screen, root, sw, sh);
1943	if (!drw_fontset_create(drw, fonts, LENGTH(fonts)))
1944		die("no fonts could be loaded.");
1945	lrpad = drw->fonts->h + 4;
1946	bh = drw->fonts->h + 2 + 4;
1947	updategeom();
1948	/* init atoms */
1949	utf8string = XInternAtom(dpy, "UTF8_STRING", False);
1950	wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1951	wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1952	wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1953	wmatom[WMTakeFocus] = XInternAtom(dpy, "WM_TAKE_FOCUS", False);
1954	netatom[NetActiveWindow] = XInternAtom(dpy, "_NET_ACTIVE_WINDOW", False);
1955	netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1956	netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1957	netatom[NetWMState] = XInternAtom(dpy, "_NET_WM_STATE", False);
1958	netatom[NetWMCheck] = XInternAtom(dpy, "_NET_SUPPORTING_WM_CHECK", False);
1959	netatom[NetWMFullscreen] = XInternAtom(dpy, "_NET_WM_STATE_FULLSCREEN", False);
1960	netatom[NetWMWindowType] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE", False);
1961	netatom[NetWMWindowTypeDialog] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE_DIALOG", False);
1962	netatom[NetClientList] = XInternAtom(dpy, "_NET_CLIENT_LIST", False);
1963	netatom[NetClientInfo] = XInternAtom(dpy, "_NET_CLIENT_INFO", False);
1964	netatom[NetTagState] = XInternAtom(dpy, "_NET_TAG_STATE", False);
1965	/* init cursors */
1966	cursor[CurNormal] = drw_cur_create(drw, XC_left_ptr);
1967	cursor[CurResize] = drw_cur_create(drw, XC_sizing);
1968	cursor[CurMove] = drw_cur_create(drw, XC_fleur);
1969	/* init appearance */
1970	scheme = ecalloc(LENGTH(colors), sizeof(Clr *));
1971	for (i = 0; i < LENGTH(colors); i++)
1972		scheme[i] = drw_scm_create(drw, colors[i], 4);
1973	/* init bars */
1974	updatebars();
1975	/* supporting window for NetWMCheck */
1976	wmcheckwin = XCreateSimpleWindow(dpy, root, 0, 0, 1, 1, 0, 0, 0);
1977	XChangeProperty(dpy, wmcheckwin, netatom[NetWMCheck], XA_WINDOW, 32,
1978		PropModeReplace, (unsigned char *) &wmcheckwin, 1);
1979	XChangeProperty(dpy, wmcheckwin, netatom[NetWMName], utf8string, 8,
1980		PropModeReplace, (unsigned char *) "dwm", 3);
1981	XChangeProperty(dpy, root, netatom[NetWMCheck], XA_WINDOW, 32,
1982		PropModeReplace, (unsigned char *) &wmcheckwin, 1);
1983	/* EWMH support per view */
1984	XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1985		PropModeReplace, (unsigned char *) netatom, NetLast);
1986	XDeleteProperty(dpy, root, netatom[NetClientList]);
1987	XDeleteProperty(dpy, root, netatom[NetClientInfo]);
1988	/* select events */
1989	wa.cursor = cursor[CurNormal]->cursor;
1990	wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1991		|ButtonPressMask|PointerMotionMask|EnterWindowMask
1992		|LeaveWindowMask|StructureNotifyMask|PropertyChangeMask;
1993	XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1994	XSelectInput(dpy, root, wa.event_mask);
1995	focus(NULL);
1996
1997	/* load tag state */
1998	loadstate(NetTagState, root, NULL);
1999
2000	/* fifo */
2001	mkfifo(dwmfifo, 0600);
2002	fifofd = open(dwmfifo, O_RDWR | O_CLOEXEC | O_NONBLOCK);
2003	if (fifofd < 0)
2004		die("Failed to open() DWM fifo %s:", dwmfifo);
2005}
2006
2007void
2008seturgent(Client *c, int urg)
2009{
2010	XWMHints *wmh;
2011
2012	c->isurgent = urg;
2013	if (!(wmh = XGetWMHints(dpy, c->win)))
2014		return;
2015	wmh->flags = urg ? (wmh->flags | XUrgencyHint) : (wmh->flags & ~XUrgencyHint);
2016	XSetWMHints(dpy, c->win, wmh);
2017	XFree(wmh);
2018}
2019
2020void
2021showhide(Client *c)
2022{
2023	if (!c)
2024		return;
2025	if (ISVISIBLE(c)) {
2026		/* show clients top down */
2027		XMoveWindow(dpy, c->win, c->x, c->y);
2028		if ((!c->mon->lt[c->mon->sellt]->arrange || c->isfloating) && !c->isfullscreen)
2029			resize(c, c->x, c->y, c->w, c->h, c->bw, 0);
2030		showhide(c->snext);
2031	} else {
2032		/* hide clients bottom up */
2033		showhide(c->snext);
2034		XMoveWindow(dpy, c->win, WIDTH(c) * -2, c->y);
2035	}
2036}
2037
2038void
2039sigchld(int unused)
2040{
2041	if (signal(SIGCHLD, sigchld) == SIG_ERR)
2042		die("can't install SIGCHLD handler:");
2043	while (0 < waitpid(-1, NULL, WNOHANG));
2044}
2045
2046void
2047spawn(const Arg *arg)
2048{
2049	if (fork() == 0) {
2050		if (dpy)
2051			close(ConnectionNumber(dpy));
2052		setsid();
2053		execvp(((char **)arg->v)[0], (char **)arg->v);
2054		fprintf(stderr, "dwm: execvp %s", ((char **)arg->v)[0]);
2055		perror(" failed");
2056		exit(EXIT_SUCCESS);
2057	}
2058}
2059
2060void
2061setstatus(const Arg *arg)
2062{
2063	char *buff = NULL;
2064	int len = 0;
2065	int i, c = 0;
2066
2067	for (i = 0; ((char **)arg->v)[i]; i++, c++)
2068		len += 1 + strlen(((char **)arg->v)[i]);
2069
2070	if (len == 0)
2071		return;
2072
2073	buff = calloc(len + 1, sizeof(char));
2074
2075	for (i = 0; ((char **)arg->v)[i]; i++) {
2076		strcat(buff, ((char **)arg->v)[i]);
2077		strcat(buff, " "); /* also add space to end for padding */
2078	}
2079
2080	strcpy(stext, buff);
2081	drawbar(selmon);
2082
2083	free(buff);
2084}
2085
2086void
2087tag(const Arg *arg)
2088{
2089	if (selmon->sel && arg->ui & TAGMASK) {
2090		selmon->sel->tags = arg->ui & TAGMASK;
2091		setclienttagprop(selmon->sel);
2092		focus(NULL);
2093		arrange(selmon);
2094		if (viewontag)
2095			view(arg);
2096	}
2097}
2098
2099void
2100tagmon(const Arg *arg)
2101{
2102	if (!selmon->sel || !mons->next)
2103		return;
2104	sendmon(selmon->sel, dirtomon(arg->i));
2105}
2106
2107void
2108getgap(Monitor *m, unsigned int n, unsigned int *g, unsigned int r, unsigned int c)
2109{
2110	/* check if gaps are to large */
2111	if (m->gap > m->wh / (r + 1))
2112		m->gap = m->wh / (r + 1);
2113	if (m->gap > m->ww / (c + 1))
2114		m->gap = m->ww / (c + 1);
2115
2116	/* set gap if used */
2117	*g = (m->pertag->enablegaps[m->pertag->curtag] && n > 0) ? m->gap : 0;
2118}
2119
2120void
2121nrowgrid(Monitor *m)
2122{
2123	unsigned int n, ri = 0, ci = 0;             /* counters */
2124	unsigned int cx, cy, cw, ch, cg;            /* client geometry */
2125	unsigned int uw = 0, uh = 0, uc = 0;        /* utilization trackers */
2126	unsigned int bw = borderpx;
2127	unsigned int cols, rows;
2128	Bool gaps;
2129	Client *c;
2130
2131	for (n = 0, c = nextinstack(m->clients); c; c = nextinstack(c->next), n++);
2132	if (n == 0)
2133		return;
2134
2135	/* calculate rows and cols, never allow empty rows */
2136	/* handle bounds for nmaster */
2137	rows = m->nmaster = m->pertag->nmasters[m->pertag->curtag] = MAX(MIN(m->nmaster, n), 1);
2138	if (n < rows)
2139		rows = n;
2140	cols = n / rows;
2141
2142	getgap(m, n, &cg, rows, cols);
2143	gaps = cg && m->pertag->enablegaps[m->pertag->curtag];
2144
2145	/* hide border when single client without gaps */
2146	if (n == 1 && !gaps)
2147		bw = 0;
2148
2149	/* define first row */
2150	uc = cols;
2151	cy = m->wy + cg + (gaps ? 0 : bw);
2152	ch = (m->wh - 2*cg - (cg * (rows - 1))) / rows;
2153	uw = gaps ? 0 : bw;
2154	uh = ch + cg + (gaps ? 0 : bw);
2155
2156	for (c = nextinstack(m->clients); c; c = nextinstack(c->next), ci++) {
2157		if (ci == cols) {
2158			ci = 0;
2159			ri++;
2160
2161			/* next row */
2162			cols = (n - uc) / (rows - ri);
2163			uc += cols;
2164			cy = m->wy + uh + cg;
2165			ch = ((m->wh - 2*cg) - uh - (cg * (rows - ri - 1))) / (rows - ri);
2166			uw = gaps ? 0 : bw;
2167			uh += ch + cg;
2168		}
2169
2170		cx = m->wx + uw + cg;
2171		cw = ((m->ww - 2*cg) - uw - (cg * (cols - ci - 1))) / (cols - ci);
2172		uw += cw + cg;
2173
2174		if (gaps)
2175			resize(c, cx, cy, cw - (2*bw), ch - (2*bw), bw, 0);
2176		else
2177			resize(c, cx - bw, cy - bw, cw - bw, ch - (rows == 1 ? 2 : 1)*bw, bw, 0);
2178	}
2179}
2180
2181void
2182togglebar(const Arg *arg)
2183{
2184	selmon->showbar = selmon->pertag->showbars[selmon->pertag->curtag] = !selmon->showbar;
2185	updatebarpos(selmon);
2186	XMoveResizeWindow(dpy, selmon->barwin, selmon->wx, selmon->by, selmon->ww, bh);
2187	arrange(selmon);
2188}
2189
2190void
2191togglefloating(const Arg *arg)
2192{
2193	if (!selmon->sel)
2194		return;
2195	if (selmon->sel->isfullscreen) /* no support for fullscreen windows */
2196		return;
2197	selmon->sel->isfloating = !selmon->sel->isfloating || selmon->sel->isfixed;
2198	if (selmon->sel->isfloating)
2199		XSetWindowBorder(dpy, selmon->sel->win, scheme[SchemeSel][ColFloat].pixel);
2200	else
2201		XSetWindowBorder(dpy, selmon->sel->win, scheme[SchemeSel][ColBorder].pixel);
2202	if (selmon->sel->isfloating)
2203		resize(selmon->sel, selmon->sel->x, selmon->sel->y,
2204		    selmon->sel->w - 2 * (borderpx - selmon->sel->bw),
2205		    selmon->sel->h - 2 * (borderpx - selmon->sel->bw),
2206		    borderpx, 0);
2207	arrange(selmon);
2208}
2209
2210void
2211togglegaps(const Arg *arg)
2212{
2213	selmon->pertag->enablegaps[selmon->pertag->curtag] = !selmon->pertag->enablegaps[selmon->pertag->curtag];
2214	arrange(selmon);
2215}
2216
2217void
2218togglesticky(const Arg *arg)
2219{
2220	if (!selmon->sel)
2221		return;
2222	selmon->sel->issticky = !selmon->sel->issticky;
2223	arrange(selmon);
2224}
2225
2226void
2227toggletag(const Arg *arg)
2228{
2229	unsigned int newtags;
2230
2231	if (!selmon->sel)
2232		return;
2233	newtags = selmon->sel->tags ^ (arg->ui & TAGMASK);
2234	if (newtags) {
2235		selmon->sel->tags = newtags;
2236		setclienttagprop(selmon->sel);
2237		focus(NULL);
2238		arrange(selmon);
2239	}
2240}
2241
2242void
2243toggleview(const Arg *arg)
2244{
2245	unsigned int newtagset = selmon->tagset[selmon->seltags] ^ (arg->ui & TAGMASK);
2246	int i;
2247
2248	if (newtagset) {
2249		if (newtagset == ~0) {
2250			selmon->pertag->prevtag = selmon->pertag->curtag;
2251			selmon->pertag->curtag = 0;
2252		}
2253		/* test if the user did not select the same tag */
2254		if (!(newtagset & 1 << (selmon->pertag->curtag - 1))) {
2255			selmon->pertag->prevtag = selmon->pertag->curtag;
2256			for (i = 0; !(newtagset & 1 << i); i++);
2257			selmon->pertag->curtag = i + 1;
2258		}
2259		selmon->tagset[selmon->seltags] = newtagset;
2260
2261		/* apply settings for this view */
2262		selmon->gap = selmon->pertag->gaps[selmon->pertag->curtag];
2263		selmon->nmaster = selmon->pertag->nmasters[selmon->pertag->curtag];
2264		selmon->sellt = selmon->pertag->sellts[selmon->pertag->curtag];
2265		selmon->lt[selmon->sellt] = selmon->pertag->ltidxs[selmon->pertag->curtag][selmon->sellt];
2266		selmon->lt[selmon->sellt ^ 1] = selmon->pertag->ltidxs[selmon->pertag->curtag][selmon->sellt^1];
2267		focus(NULL);
2268		arrange(selmon);
2269	} else {
2270		selmon->tagset[selmon->seltags] = newtagset;
2271		focus(NULL);
2272		arrange(selmon);
2273	}
2274
2275	settagstate();
2276}
2277
2278void
2279unfocus(Client *c, int setfocus)
2280{
2281	if (!c)
2282		return;
2283	grabbuttons(c, 0);
2284	XSetWindowBorder(dpy, c->win, scheme[SchemeNorm][ColBorder].pixel);
2285	if (setfocus) {
2286		XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
2287		XDeleteProperty(dpy, root, netatom[NetActiveWindow]);
2288	}
2289}
2290
2291void
2292unmanage(Client *c, int destroyed)
2293{
2294	Monitor *m = c->mon;
2295	XWindowChanges wc;
2296
2297	detach(c);
2298	detachstack(c);
2299	if (!destroyed) {
2300		wc.border_width = c->oldbw;
2301		XGrabServer(dpy); /* avoid race conditions */
2302		XSetErrorHandler(xerrordummy);
2303		XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
2304		XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
2305		setclientstate(c, WithdrawnState);
2306		XSync(dpy, False);
2307		XSetErrorHandler(xerror);
2308		XUngrabServer(dpy);
2309	}
2310	free(c);
2311	focus(NULL);
2312	updateclientlist();
2313	arrange(m);
2314}
2315
2316void
2317unmapnotify(XEvent *e)
2318{
2319	Client *c;
2320	XUnmapEvent *ev = &e->xunmap;
2321
2322	if ((c = wintoclient(ev->window))) {
2323		if (ev->send_event)
2324			setclientstate(c, WithdrawnState);
2325		else
2326			unmanage(c, 0);
2327	}
2328}
2329
2330void
2331updatebars(void)
2332{
2333	Monitor *m;
2334	XSetWindowAttributes wa = {
2335		.override_redirect = True,
2336		.background_pixmap = ParentRelative,
2337		.event_mask = ButtonPressMask|ExposureMask
2338	};
2339	XClassHint ch = {"dwm", "dwm"};
2340	for (m = mons; m; m = m->next) {
2341		if (m->barwin)
2342			continue;
2343		m->barwin = XCreateWindow(dpy, root, m->wx, m->by, m->ww, bh, 0, DefaultDepth(dpy, screen),
2344				CopyFromParent, DefaultVisual(dpy, screen),
2345				CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
2346		XDefineCursor(dpy, m->barwin, cursor[CurNormal]->cursor);
2347		XMapRaised(dpy, m->barwin);
2348		XSetClassHint(dpy, m->barwin, &ch);
2349	}
2350}
2351
2352void
2353updatebarpos(Monitor *m)
2354{
2355	m->wy = m->my;
2356	m->wh = m->mh;
2357	if (m->showbar) {
2358		m->wh -= bh;
2359		m->by = m->topbar ? m->wy : m->wy + m->wh;
2360		m->wy = m->topbar ? m->wy + bh : m->wy;
2361	} else
2362		m->by = -bh;
2363}
2364
2365void
2366updateclientlist()
2367{
2368	Client *c;
2369	Monitor *m;
2370
2371	XDeleteProperty(dpy, root, netatom[NetClientList]);
2372	for (m = mons; m; m = m->next)
2373		for (c = m->clients; c; c = c->next)
2374			XChangeProperty(dpy, root, netatom[NetClientList],
2375				XA_WINDOW, 32, PropModeAppend,
2376				(unsigned char *) &(c->win), 1);
2377}
2378
2379int
2380updategeom(void)
2381{
2382	int dirty = 0;
2383
2384#ifdef XINERAMA
2385	if (XineramaIsActive(dpy)) {
2386		int i, j, n, nn;
2387		Client *c;
2388		Monitor *m;
2389		XineramaScreenInfo *info = XineramaQueryScreens(dpy, &nn);
2390		XineramaScreenInfo *unique = NULL;
2391
2392		for (n = 0, m = mons; m; m = m->next, n++);
2393		/* only consider unique geometries as separate screens */
2394		unique = ecalloc(nn, sizeof(XineramaScreenInfo));
2395		for (i = 0, j = 0; i < nn; i++)
2396			if (isuniquegeom(unique, j, &info[i]))
2397				memcpy(&unique[j++], &info[i], sizeof(XineramaScreenInfo));
2398		XFree(info);
2399		nn = j;
2400		if (n <= nn) { /* new monitors available */
2401			for (i = 0; i < (nn - n); i++) {
2402				for (m = mons; m && m->next; m = m->next);
2403				if (m)
2404					m->next = createmon();
2405				else
2406					mons = createmon();
2407			}
2408			for (i = 0, m = mons; i < nn && m; m = m->next, i++)
2409				if (i >= n
2410				|| unique[i].x_org != m->mx || unique[i].y_org != m->my
2411				|| unique[i].width != m->mw || unique[i].height != m->mh)
2412				{
2413					dirty = 1;
2414					m->num = i;
2415					m->mx = m->wx = unique[i].x_org;
2416					m->my = m->wy = unique[i].y_org;
2417					m->mw = m->ww = unique[i].width;
2418					m->mh = m->wh = unique[i].height;
2419					updatebarpos(m);
2420				}
2421		} else { /* less monitors available nn < n */
2422			for (i = nn; i < n; i++) {
2423				for (m = mons; m && m->next; m = m->next);
2424				while ((c = m->clients)) {
2425					dirty = 1;
2426					m->clients = c->next;
2427					detachstack(c);
2428					c->mon = mons;
2429					attach(c);
2430					attachstack(c);
2431				}
2432				if (m == selmon)
2433					selmon = mons;
2434				cleanupmon(m);
2435			}
2436		}
2437		free(unique);
2438	} else
2439#endif /* XINERAMA */
2440	{ /* default monitor setup */
2441		if (!mons)
2442			mons = createmon();
2443		if (mons->mw != sw || mons->mh != sh) {
2444			dirty = 1;
2445			mons->mw = mons->ww = sw;
2446			mons->mh = mons->wh = sh;
2447			updatebarpos(mons);
2448		}
2449	}
2450	if (dirty) {
2451		selmon = mons;
2452		selmon = wintomon(root);
2453	}
2454	return dirty;
2455}
2456
2457void
2458updatenumlockmask(void)
2459{
2460	unsigned int i, j;
2461	XModifierKeymap *modmap;
2462
2463	numlockmask = 0;
2464	modmap = XGetModifierMapping(dpy);
2465	for (i = 0; i < 8; i++)
2466		for (j = 0; j < modmap->max_keypermod; j++)
2467			if (modmap->modifiermap[i * modmap->max_keypermod + j]
2468				== XKeysymToKeycode(dpy, XK_Num_Lock))
2469				numlockmask = (1 << i);
2470	XFreeModifiermap(modmap);
2471}
2472
2473void
2474updatesizehints(Client *c)
2475{
2476	long msize;
2477	XSizeHints size;
2478
2479	if (!XGetWMNormalHints(dpy, c->win, &size, &msize))
2480		/* size is uninitialized, ensure that size.flags aren't used */
2481		size.flags = PSize;
2482	if (size.flags & PBaseSize) {
2483		c->basew = size.base_width;
2484		c->baseh = size.base_height;
2485	} else if (size.flags & PMinSize) {
2486		c->basew = size.min_width;
2487		c->baseh = size.min_height;
2488	} else
2489		c->basew = c->baseh = 0;
2490	if (size.flags & PResizeInc) {
2491		c->incw = size.width_inc;
2492		c->inch = size.height_inc;
2493	} else
2494		c->incw = c->inch = 0;
2495	if (size.flags & PMaxSize) {
2496		c->maxw = size.max_width;
2497		c->maxh = size.max_height;
2498	} else
2499		c->maxw = c->maxh = 0;
2500	if (size.flags & PMinSize) {
2501		c->minw = size.min_width;
2502		c->minh = size.min_height;
2503	} else if (size.flags & PBaseSize) {
2504		c->minw = size.base_width;
2505		c->minh = size.base_height;
2506	} else
2507		c->minw = c->minh = 0;
2508	if (size.flags & PAspect) {
2509		c->mina = (float)size.min_aspect.y / size.min_aspect.x;
2510		c->maxa = (float)size.max_aspect.x / size.max_aspect.y;
2511	} else
2512		c->maxa = c->mina = 0.0;
2513	c->isfixed = (c->maxw && c->maxh && c->maxw == c->minw && c->maxh == c->minh);
2514}
2515
2516void
2517updatetitle(Client *c)
2518{
2519	if (!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
2520		gettextprop(c->win, XA_WM_NAME, c->name, sizeof c->name);
2521	if (c->name[0] == '\0') /* hack to mark broken clients */
2522		strcpy(c->name, broken);
2523}
2524
2525void
2526updatewindowtype(Client *c)
2527{
2528	Atom state = getatomprop(c, netatom[NetWMState]);
2529	Atom wtype = getatomprop(c, netatom[NetWMWindowType]);
2530
2531	if (state == netatom[NetWMFullscreen])
2532		setfullscreen(c, 1);
2533	if (wtype == netatom[NetWMWindowTypeDialog])
2534		c->isfloating = 1;
2535}
2536
2537void
2538updatewmhints(Client *c)
2539{
2540	XWMHints *wmh;
2541
2542	if ((wmh = XGetWMHints(dpy, c->win))) {
2543		if (c == selmon->sel && wmh->flags & XUrgencyHint) {
2544			wmh->flags &= ~XUrgencyHint;
2545			XSetWMHints(dpy, c->win, wmh);
2546		} else
2547			c->isurgent = (wmh->flags & XUrgencyHint) ? 1 : 0;
2548		if (wmh->flags & InputHint)
2549			c->neverfocus = !wmh->input;
2550		else
2551			c->neverfocus = 0;
2552		XFree(wmh);
2553	}
2554}
2555
2556void
2557view(const Arg *arg)
2558{
2559	int i;
2560	unsigned int tmptag;
2561
2562	if (arg->ui && (arg->ui & TAGMASK) == selmon->tagset[selmon->seltags])
2563		return;
2564	selmon->seltags ^= 1; /* toggle sel tagset */
2565	if (arg->ui & TAGMASK) {
2566		selmon->tagset[selmon->seltags] = arg->ui & TAGMASK;
2567		selmon->pertag->prevtag = selmon->pertag->curtag;
2568
2569		if (arg->ui == ~0)
2570			selmon->pertag->curtag = 0;
2571		else {
2572			for (i = 0; !(arg->ui & 1 << i); i++) ;
2573			selmon->pertag->curtag = i + 1;
2574		}
2575	} else {
2576		tmptag = selmon->pertag->prevtag;
2577		selmon->pertag->prevtag = selmon->pertag->curtag;
2578		selmon->pertag->curtag = tmptag;
2579	}
2580
2581	selmon->gap = selmon->pertag->gaps[selmon->pertag->curtag];
2582	selmon->nmaster = selmon->pertag->nmasters[selmon->pertag->curtag];
2583	selmon->sellt = selmon->pertag->sellts[selmon->pertag->curtag];
2584	selmon->lt[selmon->sellt] = selmon->pertag->ltidxs[selmon->pertag->curtag][selmon->sellt];
2585	selmon->lt[selmon->sellt^1] = selmon->pertag->ltidxs[selmon->pertag->curtag][selmon->sellt^1];
2586
2587	if (selmon->showbar != selmon->pertag->showbars[selmon->pertag->curtag])
2588		togglebar(NULL);
2589	focus(NULL);
2590	arrange(selmon);
2591
2592	settagstate();
2593}
2594
2595Client *
2596wintoclient(Window w)
2597{
2598	Client *c;
2599	Monitor *m;
2600
2601	for (m = mons; m; m = m->next)
2602		for (c = m->clients; c; c = c->next)
2603			if (c->win == w)
2604				return c;
2605	return NULL;
2606}
2607
2608Monitor *
2609wintomon(Window w)
2610{
2611	int x, y;
2612	Client *c;
2613	Monitor *m;
2614
2615	if (w == root && getrootptr(&x, &y))
2616		return recttomon(x, y, 1, 1);
2617	for (m = mons; m; m = m->next)
2618		if (w == m->barwin)
2619			return m;
2620	if ((c = wintoclient(w)))
2621		return c->mon;
2622	return selmon;
2623}
2624
2625/* There's no way to check accesses to destroyed windows, thus those cases are
2626 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
2627 * default error handler, which may call exit. */
2628int
2629xerror(Display *dpy, XErrorEvent *ee)
2630{
2631	if (ee->error_code == BadWindow
2632	|| (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
2633	|| (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
2634	|| (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
2635	|| (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
2636	|| (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
2637	|| (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
2638	|| (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
2639	|| (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
2640		return 0;
2641	fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
2642		ee->request_code, ee->error_code);
2643	return xerrorxlib(dpy, ee); /* may call exit */
2644}
2645
2646int
2647xerrordummy(Display *dpy, XErrorEvent *ee)
2648{
2649	return 0;
2650}
2651
2652/* Startup Error handler to check if another window manager
2653 * is already running. */
2654int
2655xerrorstart(Display *dpy, XErrorEvent *ee)
2656{
2657	die("dwm: another window manager is already running");
2658	return -1;
2659}
2660
2661void
2662zoom(const Arg *arg)
2663{
2664	Client *c = selmon->sel;
2665
2666	if (!selmon->lt[selmon->sellt]->arrange
2667	|| (selmon->sel && selmon->sel->isfloating))
2668		return;
2669	if (c == nextinstack(selmon->clients))
2670		if (!c || !(c = nextinstack(c->next)))
2671			return;
2672	pop(c);
2673}
2674
2675void
2676resourceload(XrmDatabase db, char *name, enum resource_type rtype, void *dst)
2677{
2678	char *sdst = NULL;
2679	int *idst = NULL;
2680	float *fdst = NULL;
2681
2682	sdst = dst;
2683	idst = dst;
2684	fdst = dst;
2685
2686	char fullname[256];
2687	char *type;
2688	XrmValue ret;
2689
2690	snprintf(fullname, sizeof(fullname), "%s.%s", "dwm", name);
2691	fullname[sizeof(fullname) - 1] = '\0';
2692
2693	XrmGetResource(db, fullname, "*", &type, &ret);
2694	if (!(ret.addr == NULL || strncmp("String", type, 64)))
2695	{
2696		switch (rtype) {
2697		case STRING:
2698			strcpy(sdst, ret.addr);
2699			break;
2700		case INTEGER:
2701			*idst = strtoul(ret.addr, NULL, 10);
2702			break;
2703		case FLOAT:
2704			*fdst = strtof(ret.addr, NULL);
2705			break;
2706		}
2707	}
2708}
2709
2710int
2711main(int argc, char *argv[])
2712{
2713	if (argc == 2 && !strcmp("-v", argv[1]))
2714		die("dwm-"VERSION);
2715	else if (argc != 1)
2716		die("usage: dwm [-v]");
2717	if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
2718		fputs("warning: no locale support\n", stderr);
2719	if (!(dpy = XOpenDisplay(NULL)))
2720		die("dwm: cannot open display");
2721	checkotherwm();
2722	XrmInitialize();
2723	loadxresources();
2724	setup();
2725#ifdef __OpenBSD__
2726	if (pledge("stdio rpath proc exec", NULL) == -1)
2727		die("pledge");
2728#endif /* __OpenBSD__ */
2729	scan();
2730	run();
2731	cleanup();
2732	XCloseDisplay(dpy);
2733	return EXIT_SUCCESS;
2734}