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