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