JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
show hidden slave windows in tabs at the bottom
[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 || (c == master && selection_floating)) {
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         if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
846                 return;
847         c = wintoclient(ev->window);
848         m = c ? c->mon : wintomon(ev->window);
849         if(m != selmon) {
850                 unfocus(selmon->sel, True);
851                 selmon = m;
852         }
853         else if(!c || c == selmon->sel)
854                 return;
855         focus(c);
856 }
857
858 void
859 expose(XEvent *e) {
860         Monitor *m;
861         XExposeEvent *ev = &e->xexpose;
862
863         if(ev->count == 0 && (m = wintomon(ev->window)))
864                 drawbar(m);
865 }
866
867 void
868 focus(Client *c) {
869         if(!c || !ISVISIBLE(c))
870                 for(c = selmon->stack; c && !ISVISIBLE(c); c = c->snext);
871         /* was if(selmon->sel) */
872         if(selmon->sel && selmon->sel != c)
873                 unfocus(selmon->sel, False);
874         if(c) {
875                 if(c->mon != selmon)
876                         selmon = c->mon;
877                 if(c->isurgent)
878                         clearurgent(c);
879                 detachstack(c);
880                 attachstack(c);
881                 grabbuttons(c, True);
882                 XSetWindowBorder(dpy, c->win, scheme[SchemeSel].border->rgb);
883                 setfocus(c);
884         }
885         else {
886                 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
887                 XDeleteProperty(dpy, root, netatom[NetActiveWindow]);
888         }
889         selmon->sel = c;
890         jason_layout(selmon);
891         update_window_opacities(selmon);
892         drawbars();
893         if(c && (!root || (c->win!=root)) )
894                 window_set_opaque(c);
895 }
896
897 void
898 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
899         XFocusChangeEvent *ev = &e->xfocus;
900
901         if(selmon->sel && ev->window != selmon->sel->win)
902                 setfocus(selmon->sel);
903 }
904
905 void
906 focusmon(const Arg *arg) {
907         Monitor *m;
908
909         if(!mons->next)
910                 return;
911         if((m = dirtomon(arg->i)) == selmon)
912                 return;
913         unfocus(selmon->sel, False); /* s/True/False/ fixes input focus issues
914                                         in gedit and anjuta */
915         selmon = m;
916         focus(NULL);
917 }
918
919 void
920 focusstack(const Arg *arg) {
921         Client *c = NULL, *i;
922
923         if(!selmon->sel)
924                 return;
925         if(arg->i == 0) {
926                 for(i = selmon->clients; i != selmon->sel; i = i->next) {
927                         if(ISVISIBLE(i)) {
928                                 c = i;
929                                 break;
930                         }
931                 }
932         } else if(arg->i > 0) {
933                 for(c = selmon->sel->next; c && !ISVISIBLE(c); c = c->next);
934                 if(!c)
935                         for(c = selmon->clients; c && !ISVISIBLE(c); c = c->next);
936         }
937         else {
938                 for(i = selmon->clients; i != selmon->sel; i = i->next)
939                         if(ISVISIBLE(i))
940                                 c = i;
941                 if(!c)
942                         for(; i; i = i->next)
943                                 if(ISVISIBLE(i))
944                                         c = i;
945         }
946         if(c) {
947                 focus(c);
948                 restack(selmon);
949         }
950 }
951
952 Atom
953 getatomprop(Client *c, Atom prop) {
954         int di;
955         unsigned long dl;
956         unsigned char *p = NULL;
957         Atom da, atom = None;
958
959         if(XGetWindowProperty(dpy, c->win, prop, 0L, sizeof atom, False, XA_ATOM,
960                               &da, &di, &dl, &dl, &p) == Success && p) {
961                 atom = *(Atom *)p;
962                 XFree(p);
963         }
964         return atom;
965 }
966
967 Bool
968 getrootptr(int *x, int *y) {
969         int di;
970         unsigned int dui;
971         Window dummy;
972
973         return XQueryPointer(dpy, root, &dummy, &dummy, x, y, &di, &di, &dui);
974 }
975
976 long
977 getstate(Window w) {
978         int format;
979         long result = -1;
980         unsigned char *p = NULL;
981         unsigned long n, extra;
982         Atom real;
983
984         if(XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
985                               &real, &format, &n, &extra, (unsigned char **)&p) != Success)
986                 return -1;
987         if(n != 0)
988                 result = *p;
989         XFree(p);
990         return result;
991 }
992
993 Bool
994 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
995         char **list = NULL;
996         int n;
997         XTextProperty name;
998
999         if(!text || size == 0)
1000                 return False;
1001         text[0] = '\0';
1002         XGetTextProperty(dpy, w, &name, atom);
1003         if(!name.nitems)
1004                 return False;
1005         if(name.encoding == XA_STRING)
1006                 strncpy(text, (char *)name.value, size - 1);
1007         else {
1008                 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success && n > 0 && *list) {
1009                         strncpy(text, *list, size - 1);
1010                         XFreeStringList(list);
1011                 }
1012         }
1013         text[size - 1] = '\0';
1014         XFree(name.value);
1015         return True;
1016 }
1017
1018 void
1019 grabbuttons(Client *c, Bool focused) {
1020         updatenumlockmask();
1021         {
1022                 unsigned int i, j;
1023                 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
1024                 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1025                 if(focused) {
1026                         for(i = 0; i < LENGTH(buttons); i++)
1027                                 if(buttons[i].click == ClkClientWin)
1028                                         for(j = 0; j < LENGTH(modifiers); j++)
1029                                                 XGrabButton(dpy, buttons[i].button,
1030                                                             buttons[i].mask | modifiers[j],
1031                                                             c->win, False, BUTTONMASK,
1032                                                             GrabModeAsync, GrabModeSync, None, None);
1033                 }
1034                 else
1035                         XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
1036                                     BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
1037         }
1038 }
1039
1040 void
1041 grabkeys(void) {
1042         updatenumlockmask();
1043         {
1044                 unsigned int i, j;
1045                 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
1046                 KeyCode code;
1047
1048                 XUngrabKey(dpy, AnyKey, AnyModifier, root);
1049                 for(i = 0; i < LENGTH(keys); i++)
1050                         if((code = XKeysymToKeycode(dpy, keys[i].keysym)))
1051                                 for(j = 0; j < LENGTH(modifiers); j++)
1052                                         XGrabKey(dpy, code, keys[i].mod | modifiers[j], root,
1053                                                  True, GrabModeAsync, GrabModeAsync);
1054         }
1055 }
1056
1057 void
1058 incnmaster(const Arg *arg) {
1059         selmon->nmaster = MAX(selmon->nmaster + arg->i, 0);
1060         arrange(selmon);
1061 }
1062
1063 #ifdef XINERAMA
1064 static Bool
1065 isuniquegeom(XineramaScreenInfo *unique, size_t n, XineramaScreenInfo *info) {
1066         while(n--)
1067                 if(unique[n].x_org == info->x_org && unique[n].y_org == info->y_org
1068                 && unique[n].width == info->width && unique[n].height == info->height)
1069                         return False;
1070         return True;
1071 }
1072 #endif /* XINERAMA */
1073
1074 void
1075 keypress(XEvent *e) {
1076         unsigned int i;
1077         KeySym keysym;
1078         XKeyEvent *ev;
1079
1080         ev = &e->xkey;
1081         keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
1082         for(i = 0; i < LENGTH(keys); i++)
1083                 if(keysym == keys[i].keysym
1084                 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
1085                 && keys[i].func)
1086                         keys[i].func(&(keys[i].arg));
1087 }
1088
1089 void
1090 killclient(const Arg *arg) {
1091         if(!selmon->sel)
1092                 return;
1093         if(!sendevent(selmon->sel, wmatom[WMDelete])) {
1094                 XGrabServer(dpy);
1095                 XSetErrorHandler(xerrordummy);
1096                 XSetCloseDownMode(dpy, DestroyAll);
1097                 XKillClient(dpy, selmon->sel->win);
1098                 XSync(dpy, False);
1099                 XSetErrorHandler(xerror);
1100                 XUngrabServer(dpy);
1101         }
1102 }
1103
1104 void
1105 manage(Window w, XWindowAttributes *wa) {
1106         Client *c, *t = NULL;
1107         Window trans = None;
1108         XWindowChanges wc;
1109
1110         if(!(c = calloc(1, sizeof(Client))))
1111                 die("fatal: could not malloc() %u bytes\n", sizeof(Client));
1112         c->opacity = -1; // who knows
1113         c->win = w;
1114         updatetitle(c);
1115         if(XGetTransientForHint(dpy, w, &trans) && (t = wintoclient(trans))) {
1116                 c->mon = t->mon;
1117                 c->tags = t->tags;
1118         }
1119         else {
1120                 c->mon = selmon;
1121                 applyrules(c);
1122         }
1123         /* geometry */
1124         c->x = c->oldx = wa->x;
1125         c->y = c->oldy = wa->y;
1126         c->w = c->oldw = wa->width;
1127         c->h = c->oldh = wa->height;
1128         c->oldbw = wa->border_width;
1129
1130         if(c->x + WIDTH(c) > c->mon->mx + c->mon->mw)
1131                 c->x = c->mon->mx + c->mon->mw - WIDTH(c);
1132         if(c->y + HEIGHT(c) > c->mon->my + c->mon->mh)
1133                 c->y = c->mon->my + c->mon->mh - HEIGHT(c);
1134         c->x = MAX(c->x, c->mon->mx);
1135         /* only fix client y-offset, if the client center might cover the bar */
1136         c->y = MAX(c->y, ((c->mon->by == c->mon->my) && (c->x + (c->w / 2) >= c->mon->wx)
1137                    && (c->x + (c->w / 2) < c->mon->wx + c->mon->ww)) ? bh : c->mon->my);
1138         c->bw = borderpx;
1139
1140         wc.border_width = c->bw;
1141         XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1142         XSetWindowBorder(dpy, w, scheme[SchemeNorm].border->rgb);
1143         configure(c); /* propagates border_width, if size doesn't change */
1144         updatewindowtype(c);
1145         updatesizehints(c);
1146         updatewmhints(c);
1147         XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
1148         grabbuttons(c, False);
1149         if(!c->isfloating)
1150                 c->isfloating = c->oldstate = trans != None || c->isfixed;
1151         if(c->isfloating)
1152                 XRaiseWindow(dpy, c->win);
1153         attach(c);
1154         attachstack(c);
1155         XChangeProperty(dpy, root, netatom[NetClientList], XA_WINDOW, 32, PropModeAppend,
1156                         (unsigned char *) &(c->win), 1);
1157         XMoveResizeWindow(dpy, c->win, c->x + 2 * sw, c->y, c->w, c->h); /* some windows require this */
1158         setclientstate(c, NormalState);
1159         if (c->mon == selmon)
1160                 unfocus(selmon->sel, False);
1161         c->mon->sel = c;
1162         arrange(c->mon);
1163         XMapWindow(dpy, c->win);
1164         focus(c);
1165 }
1166
1167 void
1168 mappingnotify(XEvent *e) {
1169         XMappingEvent *ev = &e->xmapping;
1170
1171         XRefreshKeyboardMapping(ev);
1172         if(ev->request == MappingKeyboard)
1173                 grabkeys();
1174 }
1175
1176 void
1177 maprequest(XEvent *e) {
1178         static XWindowAttributes wa;
1179         XMapRequestEvent *ev = &e->xmaprequest;
1180
1181         if(!XGetWindowAttributes(dpy, ev->window, &wa))
1182                 return;
1183         if(wa.override_redirect)
1184                 return;
1185         if(!wintoclient(ev->window))
1186                 manage(ev->window, &wa);
1187 }
1188
1189 void
1190 monocle(Monitor *m) {
1191         unsigned int n = 0;
1192         Client *c;
1193
1194         for(c = m->clients; c; c = c->next)
1195                 if(ISVISIBLE(c))
1196                         n++;
1197         if(n > 0) /* override layout symbol */
1198                 snprintf(m->ltsymbol, sizeof m->ltsymbol, "[%d]", n);
1199         for(c = nexttiled(m->clients); c; c = nexttiled(c->next))
1200                 resize(c, m->wx, m->wy, m->ww - 2 * c->bw, m->wh - 2 * c->bw, False, 0);
1201 }
1202
1203 void
1204 motionnotify(XEvent *e) {
1205         static Monitor *mon = NULL;
1206         Monitor *m;
1207         XMotionEvent *ev = &e->xmotion;
1208
1209         if(ev->window != root)
1210                 return;
1211         if((m = recttomon(ev->x_root, ev->y_root, 1, 1)) != mon && mon) {
1212                 unfocus(selmon->sel, True);
1213                 selmon = m;
1214                 focus(NULL);
1215         }
1216         mon = m;
1217 }
1218
1219 void
1220 movemouse(const Arg *arg) {
1221         int x, y, ocx, ocy, nx, ny;
1222         Client *c;
1223         Monitor *m;
1224         XEvent ev;
1225         Time lasttime = 0;
1226
1227         if(!(c = selmon->sel))
1228                 return;
1229         if(c->isfullscreen) /* no support moving fullscreen windows by mouse */
1230                 return;
1231         restack(selmon);
1232         ocx = c->x;
1233         ocy = c->y;
1234         if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1235         None, cursor[CurMove]->cursor, CurrentTime) != GrabSuccess)
1236                 return;
1237         if(!getrootptr(&x, &y))
1238                 return;
1239         do {
1240                 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1241                 switch(ev.type) {
1242                 case ConfigureRequest:
1243                 case Expose:
1244                 case MapRequest:
1245                         handler[ev.type](&ev);
1246                         break;
1247                 case MotionNotify:
1248                         if ((ev.xmotion.time - lasttime) <= (1000 / 60))
1249                                 continue;
1250                         lasttime = ev.xmotion.time;
1251
1252                         nx = ocx + (ev.xmotion.x - x);
1253                         ny = ocy + (ev.xmotion.y - y);
1254                         if(nx >= selmon->wx && nx <= selmon->wx + selmon->ww
1255                         && ny >= selmon->wy && ny <= selmon->wy + selmon->wh) {
1256                                 if(abs(selmon->wx - nx) < snap)
1257                                         nx = selmon->wx;
1258                                 else if(abs((selmon->wx + selmon->ww) - (nx + WIDTH(c))) < snap)
1259                                         nx = selmon->wx + selmon->ww - WIDTH(c);
1260                                 if(abs(selmon->wy - ny) < snap)
1261                                         ny = selmon->wy;
1262                                 else if(abs((selmon->wy + selmon->wh) - (ny + HEIGHT(c))) < snap)
1263                                         ny = selmon->wy + selmon->wh - HEIGHT(c);
1264                                 if(!c->isfloating && selmon->lt[selmon->sellt]->arrange
1265                                 && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
1266                                         togglefloating(NULL);
1267                         }
1268                         if(!selmon->lt[selmon->sellt]->arrange || c->isfloating)
1269                                 resize(c, nx, ny, c->w, c->h, True, 0);
1270                         break;
1271                 }
1272         } while(ev.type != ButtonRelease);
1273         XUngrabPointer(dpy, CurrentTime);
1274         if((m = recttomon(c->x, c->y, c->w, c->h)) != selmon) {
1275                 sendmon(c, m);
1276                 selmon = m;
1277                 focus(NULL);
1278         }
1279 }
1280
1281 Client *
1282 nexttiled(Client *c) {
1283         for(; c && (c->isfloating || !ISVISIBLE(c)); c = c->next);
1284         return c;
1285 }
1286
1287 Client *
1288 nextvisible(Client *c) {
1289         for(; c && !ISVISIBLE(c); c = c->next);
1290         return c;
1291 }
1292
1293 void
1294 pop(Client *c) {
1295         detach(c);
1296         attach_as_master(c);
1297         focus(c);
1298         arrange(c->mon);
1299 }
1300
1301 void
1302 propertynotify(XEvent *e) {
1303         Client *c;
1304         Window trans;
1305         XPropertyEvent *ev = &e->xproperty;
1306
1307         if((ev->window == root) && (ev->atom == XA_WM_NAME))
1308                 updatestatus();
1309         else if(ev->state == PropertyDelete)
1310                 return; /* ignore */
1311         else if((c = wintoclient(ev->window))) {
1312                 switch(ev->atom) {
1313                 default: break;
1314                 case XA_WM_TRANSIENT_FOR:
1315                         if(!c->isfloating && (XGetTransientForHint(dpy, c->win, &trans)) &&
1316                            (c->isfloating = (wintoclient(trans)) != NULL))
1317                                 arrange(c->mon);
1318                         break;
1319                 case XA_WM_NORMAL_HINTS:
1320                         updatesizehints(c);
1321                         break;
1322                 case XA_WM_HINTS:
1323                         updatewmhints(c);
1324                         drawbars();
1325                         break;
1326                 }
1327                 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1328                         updatetitle(c);
1329                         if(c == c->mon->sel)
1330                                 drawbar(c->mon);
1331                 }
1332                 if(ev->atom == netatom[NetWMWindowType])
1333                         updatewindowtype(c);
1334         }
1335 }
1336
1337 void
1338 quit(const Arg *arg) {
1339         running = False;
1340 }
1341
1342 Monitor *
1343 recttomon(int x, int y, int w, int h) {
1344         Monitor *m, *r = selmon;
1345         int a, area = 0;
1346
1347         for(m = mons; m; m = m->next)
1348                 if((a = INTERSECT(x, y, w, h, m)) > area) {
1349                         area = a;
1350                         r = m;
1351                 }
1352         return r;
1353 }
1354
1355 void
1356 resize(Client *c, int x, int y, int w, int h, Bool interact, Client *base) {
1357         if(applysizehints(c, &x, &y, &w, &h, interact))
1358                 resizeclient(c, x, y, w, h, base);
1359 }
1360
1361 void
1362 resizeclient(Client *c, int x, int y, int w, int h, Client *base) {
1363         XWindowChanges wc;
1364         unsigned long mask = CWX|CWY|CWWidth|CWHeight|CWBorderWidth;
1365
1366         c->oldx = c->x; c->x = wc.x = x;
1367         c->oldy = c->y; c->y = wc.y = y;
1368         c->oldw = c->w; c->w = wc.width = w;
1369         c->oldh = c->h; c->h = wc.height = h;
1370         if (base) {
1371                 wc.stack_mode = Above;
1372                 wc.sibling = base->win;
1373                 mask |= CWStackMode|CWSibling;
1374         }
1375         wc.border_width = c->bw;
1376         XConfigureWindow(dpy, c->win, mask, &wc);
1377         configure(c);
1378         XSync(dpy, False);
1379 }
1380
1381 void
1382 resizemouse(const Arg *arg) {
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         if(c->isfullscreen) /* no support resizing fullscreen windows by mouse */
1392                 return;
1393         restack(selmon);
1394         ocx = c->x;
1395         ocy = c->y;
1396         if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1397                         None, cursor[CurResize]->cursor, CurrentTime) != GrabSuccess)
1398                 return;
1399         XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1400         do {
1401                 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1402                 switch(ev.type) {
1403                 case ConfigureRequest:
1404                 case Expose:
1405                 case MapRequest:
1406                         handler[ev.type](&ev);
1407                         break;
1408                 case MotionNotify:
1409                         if ((ev.xmotion.time - lasttime) <= (1000 / 60))
1410                                 continue;
1411                         lasttime = ev.xmotion.time;
1412
1413                         nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1414                         nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1415                         if(c->mon->wx + nw >= selmon->wx && c->mon->wx + nw <= selmon->wx + selmon->ww
1416                         && c->mon->wy + nh >= selmon->wy && c->mon->wy + nh <= selmon->wy + selmon->wh)
1417                         {
1418                                 if(!c->isfloating && selmon->lt[selmon->sellt]->arrange
1419                                 && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1420                                         togglefloating(NULL);
1421                         }
1422                         if(!selmon->lt[selmon->sellt]->arrange || c->isfloating)
1423                                 resize(c, c->x, c->y, nw, nh, True, 0);
1424                         break;
1425                 }
1426         } while(ev.type != ButtonRelease);
1427         XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1428         XUngrabPointer(dpy, CurrentTime);
1429         while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1430         if((m = recttomon(c->x, c->y, c->w, c->h)) != selmon) {
1431                 sendmon(c, m);
1432                 selmon = m;
1433                 focus(NULL);
1434         }
1435 }
1436
1437 void
1438 restack(Monitor *m) {
1439         Client *c;
1440         XEvent ev;
1441         XWindowChanges wc;
1442
1443         drawbar(m);
1444         if(!m->sel)
1445                 return;
1446         if(m->sel->isfloating || !m->lt[m->sellt]->arrange)
1447                 XRaiseWindow(dpy, m->sel->win);
1448         if(m->lt[m->sellt]->arrange) {
1449                 wc.stack_mode = Below;
1450                 wc.sibling = m->barwin;
1451                 for(c = m->clients; c; c = c->next)
1452                         if(!c->isfloating && ISVISIBLE(c)) {
1453                                 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1454                                 wc.sibling = c->win;
1455                                 wc.stack_mode = Above;
1456                         }
1457         }
1458         XSync(dpy, False);
1459         while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1460 }
1461
1462 void
1463 run(void) {
1464         XEvent ev;
1465         /* main event loop */
1466         XSync(dpy, False);
1467         while(running && !XNextEvent(dpy, &ev))
1468                 if(handler[ev.type])
1469                         handler[ev.type](&ev); /* call handler */
1470 }
1471
1472 void
1473 scan(void) {
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         if(c->mon == m)
1501                 return;
1502         unfocus(c, True);
1503         detachstack(c);
1504         detach(c);
1505         c->mon = m;
1506         c->tags = m->tagset[m->seltags]; /* assign tags of target monitor */
1507         attach(c);
1508         attachstack(c);
1509         focus(NULL);
1510         arrange(NULL);
1511 }
1512
1513 void
1514 setclientstate(Client *c, long state) {
1515         long data[] = { state, None };
1516
1517         XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1518                         PropModeReplace, (unsigned char *)data, 2);
1519 }
1520
1521 Bool
1522 sendevent(Client *c, Atom proto) {
1523         int n;
1524         Atom *protocols;
1525         Bool exists = False;
1526         XEvent ev;
1527
1528         if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
1529                 while(!exists && n--)
1530                         exists = protocols[n] == proto;
1531                 XFree(protocols);
1532         }
1533         if(exists) {
1534                 ev.type = ClientMessage;
1535                 ev.xclient.window = c->win;
1536                 ev.xclient.message_type = wmatom[WMProtocols];
1537                 ev.xclient.format = 32;
1538                 ev.xclient.data.l[0] = proto;
1539                 ev.xclient.data.l[1] = CurrentTime;
1540                 XSendEvent(dpy, c->win, False, NoEventMask, &ev);
1541         }
1542         return exists;
1543 }
1544
1545 void
1546 setfocus(Client *c) {
1547         if(!c->neverfocus) {
1548                 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
1549                 XChangeProperty(dpy, root, netatom[NetActiveWindow],
1550                                 XA_WINDOW, 32, PropModeReplace,
1551                                 (unsigned char *) &(c->win), 1);
1552         }
1553         sendevent(c, wmatom[WMTakeFocus]);
1554 }
1555
1556 void
1557 setfullscreen(Client *c, Bool fullscreen) {
1558         if(fullscreen) {
1559                 XChangeProperty(dpy, c->win, netatom[NetWMState], XA_ATOM, 32,
1560                                 PropModeReplace, (unsigned char*)&netatom[NetWMFullscreen], 1);
1561                 c->isfullscreen = True;
1562                 c->oldstate = c->isfloating;
1563                 c->oldbw = c->bw;
1564                 c->bw = 0;
1565                 c->isfloating = True;
1566                 resizeclient(c, c->mon->mx, c->mon->my, c->mon->mw, c->mon->mh, 0);
1567                 XRaiseWindow(dpy, c->win);
1568         }
1569         else {
1570                 XChangeProperty(dpy, c->win, netatom[NetWMState], XA_ATOM, 32,
1571                                 PropModeReplace, (unsigned char*)0, 0);
1572                 c->isfullscreen = False;
1573                 c->isfloating = c->oldstate;
1574                 c->bw = c->oldbw;
1575                 c->x = c->oldx;
1576                 c->y = c->oldy;
1577                 c->w = c->oldw;
1578                 c->h = c->oldh;
1579                 resizeclient(c, c->x, c->y, c->w, c->h, 0);
1580                 arrange(c->mon);
1581         }
1582 }
1583
1584 void
1585 setlayout(const Arg *arg) {
1586         if(!arg || !arg->v || arg->v != selmon->lt[selmon->sellt])
1587                 selmon->sellt ^= 1;
1588         if(arg && arg->v)
1589                 selmon->lt[selmon->sellt] = (Layout *)arg->v;
1590         strncpy(selmon->ltsymbol, selmon->lt[selmon->sellt]->symbol, sizeof selmon->ltsymbol);
1591         if(selmon->sel)
1592                 arrange(selmon);
1593         else
1594                 drawbar(selmon);
1595 }
1596
1597 /* arg > 1.0 will set mfact absolutly */
1598 void
1599 setmfact(const Arg *arg) {
1600         float f;
1601
1602         if(!arg || !selmon->lt[selmon->sellt]->arrange)
1603                 return;
1604         f = arg->f < 1.0 ? arg->f + selmon->mfact : arg->f - 1.0;
1605         if(f < 0.1 || f > 0.9)
1606                 return;
1607         selmon->mfact = f;
1608         arrange(selmon);
1609 }
1610
1611 void
1612 setup(void) {
1613         XSetWindowAttributes wa;
1614
1615         /* clean up any zombies immediately */
1616         sigchld(0);
1617
1618         /* init screen */
1619         screen = DefaultScreen(dpy);
1620         root = RootWindow(dpy, screen);
1621         fnt = drw_font_create(dpy, font);
1622         sw = DisplayWidth(dpy, screen);
1623         sh = DisplayHeight(dpy, screen);
1624         bh = fnt->h + 2;
1625         drw = drw_create(dpy, screen, root, sw, sh);
1626         drw_setfont(drw, fnt);
1627         updategeom();
1628         /* init atoms */
1629         wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1630         wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1631         wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1632         wmatom[WMTakeFocus] = XInternAtom(dpy, "WM_TAKE_FOCUS", False);
1633         netatom[NetActiveWindow] = XInternAtom(dpy, "_NET_ACTIVE_WINDOW", False);
1634         netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1635         netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1636         netatom[NetWMState] = XInternAtom(dpy, "_NET_WM_STATE", False);
1637         netatom[NetWMFullscreen] = XInternAtom(dpy, "_NET_WM_STATE_FULLSCREEN", False);
1638         netatom[NetWMWindowOpacity] = XInternAtom(dpy, "_NET_WM_WINDOW_OPACITY", False);
1639         netatom[NetWMWindowType] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE", False);
1640         netatom[NetWMWindowTypeDialog] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE_DIALOG", False);
1641         netatom[NetClientList] = XInternAtom(dpy, "_NET_CLIENT_LIST", False);
1642         netatom[NetSupportingWMCheck] = XInternAtom(dpy, "_NET_SUPPORTING_WM_CHECK", False);
1643         /* init cursors */
1644         cursor[CurNormal] = drw_cur_create(drw, XC_left_ptr);
1645         cursor[CurResize] = drw_cur_create(drw, XC_sizing);
1646         cursor[CurMove] = drw_cur_create(drw, XC_fleur);
1647         /* init appearance */
1648         scheme[SchemeNorm].border = drw_clr_create(drw, normbordercolor);
1649         scheme[SchemeNorm].bg = drw_clr_create(drw, normbgcolor);
1650         scheme[SchemeNorm].fg = drw_clr_create(drw, normfgcolor);
1651         scheme[SchemeSel].border = drw_clr_create(drw, selbordercolor);
1652         scheme[SchemeSel].bg = drw_clr_create(drw, selbgcolor);
1653         scheme[SchemeSel].fg = drw_clr_create(drw, selfgcolor);
1654         /* init bars */
1655         updatebars();
1656         updatestatus();
1657         /* EWMH support per view */
1658         XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1659                         PropModeReplace, (unsigned char *) netatom, NetLast);
1660         XDeleteProperty(dpy, root, netatom[NetClientList]);
1661         /* select for events */
1662         wa.cursor = cursor[CurNormal]->cursor;
1663         wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask|ButtonPressMask|PointerMotionMask
1664                         |EnterWindowMask|LeaveWindowMask|StructureNotifyMask|PropertyChangeMask;
1665         XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1666         XSelectInput(dpy, root, wa.event_mask);
1667         grabkeys();
1668         focus(NULL);
1669 }
1670
1671 void
1672 showhide(Client *c) {
1673         if(!c)
1674                 return;
1675         if(ISVISIBLE(c)) { /* show clients top down */
1676                 XMoveWindow(dpy, c->win, c->x, c->y);
1677                 if((!c->mon->lt[c->mon->sellt]->arrange || c->isfloating) && !c->isfullscreen)
1678                         resize(c, c->x, c->y, c->w, c->h, False, 0);
1679                 showhide(c->snext);
1680         }
1681         else { /* hide clients bottom up */
1682                 showhide(c->snext);
1683                 XMoveWindow(dpy, c->win, WIDTH(c) * -2, c->y);
1684         }
1685 }
1686
1687 void
1688 sigchld(int unused) {
1689         if(signal(SIGCHLD, sigchld) == SIG_ERR)
1690                 die("Can't install SIGCHLD handler");
1691         while(0 < waitpid(-1, NULL, WNOHANG));
1692 }
1693
1694 void
1695 spawn(const Arg *arg) {
1696         int tag = 0, i;
1697         if(arg->v == termcmd) {
1698                 for(i = 0; i < 32; ++i) {
1699                         if(selmon->tagset[selmon->seltags] & (1 << i)) {
1700                                 tag = i;
1701                                 break;
1702                         }
1703                 }
1704                 WORKSPACE_NUMBER[17] = workspace_numbers_str[tag][0];
1705                 WORKSPACE_NUMBER[18] = workspace_numbers_str[tag][1];
1706         }
1707         if(arg->v == dmenucmd)
1708                 dmenumon[0] = '0' + selmon->num;
1709         if(fork() == 0) {
1710                 if(dpy)
1711                         close(ConnectionNumber(dpy));
1712                 setsid();
1713                 execvp(((char **)arg->v)[0], (char **)arg->v);
1714                 fprintf(stderr, "dwm: execvp %s", ((char **)arg->v)[0]);
1715                 perror(" failed");
1716                 exit(EXIT_SUCCESS);
1717         }
1718 }
1719
1720 void
1721 tag(const Arg *arg) {
1722         if(selmon->sel && arg->ui & TAGMASK) {
1723                 selmon->sel->tags = arg->ui & TAGMASK;
1724                 focus(NULL);
1725                 arrange(selmon);
1726         }
1727 }
1728
1729 void
1730 tagmon(const Arg *arg) {
1731         if(!selmon->sel || !mons->next)
1732                 return;
1733         sendmon(selmon->sel, dirtomon(arg->i));
1734 }
1735
1736 void
1737 tile(Monitor *m) {
1738         unsigned int i, n, h, mw, my, ty;
1739         Client *c;
1740
1741         for(n = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), n++);
1742         if(n == 0)
1743                 return;
1744
1745         if(n > m->nmaster)
1746                 mw = m->nmaster ? m->ww * m->mfact : 0;
1747         else {
1748                 c = nexttiled(m->clients);
1749                 if (c && !c->screen_hog)
1750                         mw = m->ww * m->mfact;
1751                 else
1752                         mw = m->ww;
1753         }
1754         for(i = my = ty = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), i++)
1755                 if(i < m->nmaster) {
1756                         h = (m->wh - my) / (MIN(n, m->nmaster) - i);
1757                         resize(c, m->wx, m->wy + my, mw - (2*c->bw), h - (2*c->bw), False, 0);
1758                         my += HEIGHT(c);
1759                 }
1760                 else {
1761                         h = (m->wh - ty) / (n - i);
1762                         resize(c, m->wx + mw, m->wy + ty, m->ww - mw - (2*c->bw), h - (2*c->bw), False, 0);
1763                         ty += HEIGHT(c);
1764                 }
1765 }
1766
1767 void
1768 jason_layout(Monitor *m) {
1769         unsigned int i, tiled_count, mw, right_width, tabs_count, cur_tab;
1770         Client *c, *vis_slave, *base = 0;
1771
1772         for(tiled_count = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), tiled_count++);
1773         if(tiled_count == 0) {
1774                 return;
1775         }
1776
1777         c = nexttiled(m->clients);
1778         if (c == m->sel) {
1779                 // if master is selected, show first slave
1780                 vis_slave = nexttiled(c->next);
1781         } else {
1782                 vis_slave = m->sel;
1783         }
1784         if(tiled_count > 1 || (tiled_count == 1 && !c->screen_hog)) {
1785                 mw = m->ww * m->mfact;
1786         } else {
1787                 // one of these:
1788                 // * zero tiled windows
1789                 // * one tiled window that's not a screen hog
1790                 // * miltiple tiled windows
1791                 mw = m->ww;
1792         }
1793         right_width = m->ww - mw;
1794         tabs_count = tiled_count - 2;
1795         cur_tab = 0;
1796         for (i = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), i++) {
1797                 if (i == 0) {
1798                         resize(c, m->wx, m->wy, mw, m->wh, False, 0);
1799                 } else {
1800                         if (c == vis_slave) {
1801                                 resize(c, m->wx + mw, m->wy, right_width, m->wh - 30, False, base);
1802                         } else {
1803                                 // this function does not get called when focus changes
1804                                 // resize(c, m->wx + m->ww, m->wy, m->ww - mw, m->wh, False);
1805                                 resize(c, m->wx + mw + right_width * cur_tab / tabs_count, m->wy + m->wh - 20, right_width, m->wh - 30, False, base);
1806                                 cur_tab += 1;
1807                         }
1808                 }
1809                 base = c;
1810         }
1811 }
1812
1813 void
1814 togglebar(const Arg *arg) {
1815         selmon->showbar = !selmon->showbar;
1816         updatebarpos(selmon);
1817         XMoveResizeWindow(dpy, selmon->barwin, selmon->wx, selmon->by, selmon->ww, bh);
1818         arrange(selmon);
1819 }
1820
1821 void
1822 togglefloating(const Arg *arg) {
1823         if(!selmon->sel)
1824                 return;
1825         if(selmon->sel->isfullscreen) /* no support for fullscreen windows */
1826                 return;
1827         selmon->sel->isfloating = !selmon->sel->isfloating || selmon->sel->isfixed;
1828         if(selmon->sel->isfloating)
1829                 resize(selmon->sel, selmon->sel->x, selmon->sel->y,
1830                        selmon->sel->w, selmon->sel->h, False, 0);
1831         arrange(selmon);
1832 }
1833
1834 void
1835 toggletag(const Arg *arg) {
1836         unsigned int newtags;
1837
1838         if(!selmon->sel)
1839                 return;
1840         newtags = selmon->sel->tags ^ (arg->ui & TAGMASK);
1841         if(newtags) {
1842                 selmon->sel->tags = newtags;
1843                 focus(NULL);
1844                 arrange(selmon);
1845         }
1846 }
1847
1848 void
1849 toggleview(const Arg *arg) {
1850         unsigned int newtagset = selmon->tagset[selmon->seltags] ^ (arg->ui & TAGMASK);
1851
1852         if(newtagset) {
1853                 selmon->tagset[selmon->seltags] = newtagset;
1854                 focus(NULL);
1855                 arrange(selmon);
1856         }
1857 }
1858
1859 void
1860 unfocus(Client *c, Bool setfocus) {
1861         if(!c)
1862                 return;
1863         grabbuttons(c, False);
1864         XSetWindowBorder(dpy, c->win, scheme[SchemeNorm].border->rgb);
1865         if(setfocus) {
1866                 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
1867                 XDeleteProperty(dpy, root, netatom[NetActiveWindow]);
1868         }
1869 }
1870
1871 void
1872 unmanage(Client *c, Bool destroyed) {
1873         Monitor *m = c->mon;
1874         XWindowChanges wc;
1875
1876         /* The server grab construct avoids race conditions. */
1877         detachstack(c);
1878         detach(c);
1879         if(!destroyed) {
1880                 wc.border_width = c->oldbw;
1881                 XGrabServer(dpy);
1882                 XSetErrorHandler(xerrordummy);
1883                 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1884                 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1885                 setclientstate(c, WithdrawnState);
1886                 XSync(dpy, False);
1887                 XSetErrorHandler(xerror);
1888                 XUngrabServer(dpy);
1889         }
1890         free(c);
1891         focus(selmon ? selmon->sel : NULL);
1892         updateclientlist();
1893         arrange(m);
1894 }
1895
1896 void
1897 unmapnotify(XEvent *e) {
1898         Client *c;
1899         XUnmapEvent *ev = &e->xunmap;
1900
1901         if((c = wintoclient(ev->window))) {
1902                 if(ev->send_event)
1903                         setclientstate(c, WithdrawnState);
1904                 else
1905                         unmanage(c, False);
1906         }
1907 }
1908
1909 void
1910 updatebars(void) {
1911         Monitor *m;
1912         XSetWindowAttributes wa = {
1913                 .override_redirect = True,
1914                 .background_pixmap = ParentRelative,
1915                 .event_mask = ButtonPressMask|ExposureMask
1916         };
1917         for(m = mons; m; m = m->next) {
1918                 if (m->barwin)
1919                         continue;
1920                 m->barwin = XCreateWindow(dpy, root, m->wx, m->by, m->ww, bh, 0, DefaultDepth(dpy, screen),
1921                                           CopyFromParent, DefaultVisual(dpy, screen),
1922                                           CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1923                 XChangeProperty(dpy, root, netatom[NetSupportingWMCheck], XA_WINDOW, 32,
1924                                 PropModeReplace, (unsigned char *) &(m->barwin), 1);
1925                 XChangeProperty(dpy, m->barwin, netatom[NetSupportingWMCheck], XA_WINDOW, 32,
1926                                 PropModeReplace, (unsigned char *) &(m->barwin), 1);
1927                 XChangeProperty(dpy, m->barwin, netatom[NetWMName], XA_STRING, 8,
1928                                 PropModeReplace, (unsigned char *) "dwm", 3);
1929                 XDefineCursor(dpy, m->barwin, cursor[CurNormal]->cursor);
1930                 XMapRaised(dpy, m->barwin);
1931         }
1932 }
1933
1934 void
1935 updatebarpos(Monitor *m) {
1936         m->wy = m->my;
1937         m->wh = m->mh;
1938         if(m->showbar) {
1939                 m->wh -= bh;
1940                 m->by = m->topbar ? m->wy : m->wy + m->wh;
1941                 m->wy = m->topbar ? m->wy + bh : m->wy;
1942         }
1943         else
1944                 m->by = -bh;
1945 }
1946
1947 void
1948 updateclientlist() {
1949         Client *c;
1950         Monitor *m;
1951
1952         XDeleteProperty(dpy, root, netatom[NetClientList]);
1953         for(m = mons; m; m = m->next)
1954                 for(c = m->clients; c; c = c->next)
1955                         XChangeProperty(dpy, root, netatom[NetClientList],
1956                                         XA_WINDOW, 32, PropModeAppend,
1957                                         (unsigned char *) &(c->win), 1);
1958 }
1959
1960 Bool
1961 updategeom(void) {
1962         Bool dirty = False;
1963
1964 #ifdef XINERAMA
1965         if(XineramaIsActive(dpy)) {
1966                 int i, j, n, nn;
1967                 Client *c;
1968                 Monitor *m;
1969                 XineramaScreenInfo *info = XineramaQueryScreens(dpy, &nn);
1970                 XineramaScreenInfo *unique = NULL;
1971
1972                 for(n = 0, m = mons; m; m = m->next, n++);
1973                 /* only consider unique geometries as separate screens */
1974                 if(!(unique = (XineramaScreenInfo *)malloc(sizeof(XineramaScreenInfo) * nn)))
1975                         die("fatal: could not malloc() %u bytes\n", sizeof(XineramaScreenInfo) * nn);
1976                 for(i = 0, j = 0; i < nn; i++)
1977                         if(isuniquegeom(unique, j, &info[i]))
1978                                 memcpy(&unique[j++], &info[i], sizeof(XineramaScreenInfo));
1979                 XFree(info);
1980                 nn = j;
1981                 if(n <= nn) {
1982                         for(i = 0; i < (nn - n); i++) { /* new monitors available */
1983                                 for(m = mons; m && m->next; m = m->next);
1984                                 if(m)
1985                                         m->next = createmon();
1986                                 else
1987                                         mons = createmon();
1988                         }
1989                         for(i = 0, m = mons; i < nn && m; m = m->next, i++)
1990                                 if(i >= n
1991                                 || (unique[i].x_org != m->mx || unique[i].y_org != m->my
1992                                     || unique[i].width != m->mw || unique[i].height != m->mh))
1993                                 {
1994                                         dirty = True;
1995                                         m->num = i;
1996                                         m->mx = m->wx = unique[i].x_org;
1997                                         m->my = m->wy = unique[i].y_org;
1998                                         m->mw = m->ww = unique[i].width;
1999                                         m->mh = m->wh = unique[i].height;
2000                                         updatebarpos(m);
2001                                 }
2002                 }
2003                 else { /* less monitors available nn < n */
2004                         for(i = nn; i < n; i++) {
2005                                 for(m = mons; m && m->next; m = m->next);
2006                                 while(m->clients) {
2007                                         dirty = True;
2008                                         c = m->clients;
2009                                         m->clients = c->next;
2010                                         detachstack(c);
2011                                         c->mon = mons;
2012                                         attach(c);
2013                                         attachstack(c);
2014                                 }
2015                                 if(m == selmon)
2016                                         selmon = mons;
2017                                 cleanupmon(m);
2018                         }
2019                 }
2020                 free(unique);
2021         }
2022         else
2023 #endif /* XINERAMA */
2024         /* default monitor setup */
2025         {
2026                 if(!mons)
2027                         mons = createmon();
2028                 if(mons->mw != sw || mons->mh != sh) {
2029                         dirty = True;
2030                         mons->mw = mons->ww = sw;
2031                         mons->mh = mons->wh = sh;
2032                         updatebarpos(mons);
2033                 }
2034         }
2035         if(dirty) {
2036                 selmon = mons;
2037                 selmon = wintomon(root);
2038         }
2039         return dirty;
2040 }
2041
2042 void
2043 updatenumlockmask(void) {
2044         unsigned int i, j;
2045         XModifierKeymap *modmap;
2046
2047         numlockmask = 0;
2048         modmap = XGetModifierMapping(dpy);
2049         for(i = 0; i < 8; i++)
2050                 for(j = 0; j < modmap->max_keypermod; j++)
2051                         if(modmap->modifiermap[i * modmap->max_keypermod + j]
2052                            == XKeysymToKeycode(dpy, XK_Num_Lock))
2053                                 numlockmask = (1 << i);
2054         XFreeModifiermap(modmap);
2055 }
2056
2057 void
2058 updatesizehints(Client *c) {
2059         long msize;
2060         XSizeHints size;
2061
2062         if(!XGetWMNormalHints(dpy, c->win, &size, &msize))
2063                 /* size is uninitialized, ensure that size.flags aren't used */
2064                 size.flags = PSize;
2065         if(size.flags & PBaseSize) {
2066                 c->basew = size.base_width;
2067                 c->baseh = size.base_height;
2068         }
2069         else if(size.flags & PMinSize) {
2070                 c->basew = size.min_width;
2071                 c->baseh = size.min_height;
2072         }
2073         else
2074                 c->basew = c->baseh = 0;
2075         if(size.flags & PResizeInc) {
2076                 c->incw = size.width_inc;
2077                 c->inch = size.height_inc;
2078         }
2079         else
2080                 c->incw = c->inch = 0;
2081         if(size.flags & PMaxSize) {
2082                 c->maxw = size.max_width;
2083                 c->maxh = size.max_height;
2084         }
2085         else
2086                 c->maxw = c->maxh = 0;
2087         if(size.flags & PMinSize) {
2088                 c->minw = size.min_width;
2089                 c->minh = size.min_height;
2090         }
2091         else if(size.flags & PBaseSize) {
2092                 c->minw = size.base_width;
2093                 c->minh = size.base_height;
2094         }
2095         else
2096                 c->minw = c->minh = 0;
2097         if(size.flags & PAspect) {
2098                 c->mina = (float)size.min_aspect.y / size.min_aspect.x;
2099                 c->maxa = (float)size.max_aspect.x / size.max_aspect.y;
2100         }
2101         else
2102                 c->maxa = c->mina = 0.0;
2103         c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
2104                      && c->maxw == c->minw && c->maxh == c->minh);
2105 }
2106
2107 void
2108 updatetitle(Client *c) {
2109         if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
2110                 gettextprop(c->win, XA_WM_NAME, c->name, sizeof c->name);
2111         if(c->name[0] == '\0') /* hack to mark broken clients */
2112                 strcpy(c->name, broken);
2113 }
2114
2115 void
2116 updatestatus(void) {
2117         if(!gettextprop(root, XA_WM_NAME, stext, sizeof(stext)))
2118                 strcpy(stext, "dwm-"VERSION);
2119         drawbar(selmon);
2120 }
2121
2122 void
2123 updatewindowtype(Client *c) {
2124         Atom state = getatomprop(c, netatom[NetWMState]);
2125         Atom wtype = getatomprop(c, netatom[NetWMWindowType]);
2126
2127         if(state == netatom[NetWMFullscreen])
2128                 setfullscreen(c, True);
2129         if(wtype == netatom[NetWMWindowTypeDialog])
2130                 c->isfloating = True;
2131 }
2132
2133 void
2134 updatewmhints(Client *c) {
2135         XWMHints *wmh;
2136
2137         if((wmh = XGetWMHints(dpy, c->win))) {
2138                 if(c == selmon->sel && wmh->flags & XUrgencyHint) {
2139                         wmh->flags &= ~XUrgencyHint;
2140                         XSetWMHints(dpy, c->win, wmh);
2141                 }
2142                 else
2143                         c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
2144                 if(wmh->flags & InputHint)
2145                         c->neverfocus = !wmh->input;
2146                 else
2147                         c->neverfocus = False;
2148                 XFree(wmh);
2149         }
2150 }
2151
2152 void
2153 view(const Arg *arg) {
2154         if((arg->ui & TAGMASK) == selmon->tagset[selmon->seltags])
2155                 return;
2156         selmon->seltags ^= 1; /* toggle sel tagset */
2157         if(arg->ui & TAGMASK)
2158                 selmon->tagset[selmon->seltags] = arg->ui & TAGMASK;
2159         focus(NULL);
2160         arrange(selmon);
2161 }
2162
2163 Client *
2164 wintoclient(Window w) {
2165         Client *c;
2166         Monitor *m;
2167
2168         for(m = mons; m; m = m->next)
2169                 for(c = m->clients; c; c = c->next)
2170                         if(c->win == w)
2171                                 return c;
2172         return NULL;
2173 }
2174
2175 Monitor *
2176 wintomon(Window w) {
2177         int x, y;
2178         Client *c;
2179         Monitor *m;
2180
2181         if(w == root && getrootptr(&x, &y))
2182                 return recttomon(x, y, 1, 1);
2183         for(m = mons; m; m = m->next)
2184                 if(w == m->barwin)
2185                         return m;
2186         if((c = wintoclient(w)))
2187                 return c->mon;
2188         return selmon;
2189 }
2190
2191 /* There's no way to check accesses to destroyed windows, thus those cases are
2192  * ignored (especially on UnmapNotify's).  Other types of errors call Xlibs
2193  * default error handler, which may call exit.  */
2194 int
2195 xerror(Display *dpy, XErrorEvent *ee) {
2196         if(ee->error_code == BadWindow
2197         || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
2198         || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
2199         || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
2200         || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
2201         || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
2202         || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
2203         || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
2204         || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
2205                 return 0;
2206         fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
2207                         ee->request_code, ee->error_code);
2208         return xerrorxlib(dpy, ee); /* may call exit */
2209 }
2210
2211 int
2212 xerrordummy(Display *dpy, XErrorEvent *ee) {
2213         return 0;
2214 }
2215
2216 /* Startup Error handler to check if another window manager
2217  * is already running. */
2218 int
2219 xerrorstart(Display *dpy, XErrorEvent *ee) {
2220         die("dwm: another window manager is already running\n");
2221         return -1;
2222 }
2223
2224 void
2225 zoom(const Arg *arg) {
2226         Client *c = selmon->sel;
2227
2228         if(!selmon->lt[selmon->sellt]->arrange
2229         || (selmon->sel && selmon->sel->isfloating))
2230                 return;
2231         if(c == nexttiled(selmon->clients))
2232                 if(!c || !(c = nexttiled(c->next)))
2233                         return;
2234         pop(c);
2235 }
2236
2237 int
2238 main(int argc, char *argv[]) {
2239         if(argc == 2 && !strcmp("-v", argv[1]))
2240                 die("dwm-"VERSION", © 2006-2014 dwm engineers, see LICENSE for details\n");
2241         else if(argc != 1)
2242                 die("usage: dwm [-v]\n");
2243         if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
2244                 fputs("warning: no locale support\n", stderr);
2245         if(!(dpy = XOpenDisplay(NULL)))
2246                 die("dwm: cannot open display\n");
2247         checkotherwm();
2248         setup();
2249         scan();
2250         run();
2251         cleanup();
2252         XCloseDisplay(dpy);
2253         return EXIT_SUCCESS;
2254 }