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