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