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