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