JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
replaced isvisible with a macro
[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  * Calls to fetch an X event from the event queue are blocking.  Due reading
10  * status text from standard input, a select()-driven main loop has been
11  * implemented which selects for reads on the X connection and STDIN_FILENO to
12  * handle all data smoothly. The event handlers of dwm are organized in an
13  * array which is accessed whenever a new event has been fetched. This allows
14  * event dispatching in O(1) time.
15  *
16  * Each child of the root window is called a client, except windows which have
17  * set the override_redirect flag.  Clients are organized in a global
18  * doubly-linked client list, the focus history is remembered through a global
19  * stack list. Each client contains an array of Bools of the same size as the
20  * global tags array to indicate the tags of a client.
21  *
22  * Keys and tagging rules are organized as arrays and defined in config.h.
23  *
24  * To understand everything else, start reading main().
25  */
26 #include <errno.h>
27 #include <locale.h>
28 #include <stdarg.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <unistd.h>
33 #include <sys/select.h>
34 #include <sys/types.h>
35 #include <sys/wait.h>
36 #include <X11/cursorfont.h>
37 #include <X11/keysym.h>
38 #include <X11/Xatom.h>
39 #include <X11/Xlib.h>
40 #include <X11/Xproto.h>
41 #include <X11/Xutil.h>
42 #ifdef XINERAMA
43 #include <X11/extensions/Xinerama.h>
44 #endif
45
46 /* macros */
47 #define MAX(a, b)       ((a) > (b) ? (a) : (b))
48 #define MIN(a, b)       ((a) < (b) ? (a) : (b))
49 #define BUTTONMASK      (ButtonPressMask|ButtonReleaseMask)
50 #define CLEANMASK(mask) (mask & ~(numlockmask|LockMask))
51 #define LENGTH(x)       (sizeof x / sizeof x[0])
52 #define MAXTAGLEN       16
53 #define MOUSEMASK       (BUTTONMASK|PointerMotionMask)
54 #define TAGMASK         ((int)((1LL << LENGTH(tags)) - 1))
55 #define VISIBLE(x)      ((x)->tags & tagset[seltags])
56
57 /* enums */
58 enum { CurNormal, CurResize, CurMove, CurLast };        /* cursor */
59 enum { ColBorder, ColFG, ColBG, ColLast };              /* color */
60 enum { NetSupported, NetWMName, NetLast };              /* EWMH atoms */
61 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
62
63 /* typedefs */
64 typedef unsigned int uint;
65 typedef unsigned long ulong;
66 typedef struct Client Client;
67 struct Client {
68         char name[256];
69         int x, y, w, h;
70         int basew, baseh, incw, inch, maxw, maxh, minw, minh;
71         int minax, maxax, minay, maxay;
72         long flags;
73         int bw, oldbw;
74         Bool isbanned, isfixed, isfloating, isurgent;
75         uint tags;
76         Client *next;
77         Client *prev;
78         Client *snext;
79         Window win;
80 };
81
82 typedef struct {
83         int x, y, w, h;
84         ulong norm[ColLast];
85         ulong sel[ColLast];
86         Drawable drawable;
87         GC gc;
88         struct {
89                 int ascent;
90                 int descent;
91                 int height;
92                 XFontSet set;
93                 XFontStruct *xfont;
94         } font;
95 } DC; /* draw context */
96
97 typedef struct {
98         uint mod;
99         KeySym keysym;
100         void (*func)(const void *arg);
101         const void *arg;
102 } Key;
103
104 typedef struct {
105         const char *symbol;
106         void (*arrange)(void);
107         void (*updategeom)(void);
108 } Layout;
109
110 typedef struct {
111         const char *class;
112         const char *instance;
113         const char *title;
114         uint tags;
115         Bool isfloating;
116 } Rule;
117
118 /* function declarations */
119 void applyrules(Client *c);
120 void arrange(void);
121 void attach(Client *c);
122 void attachstack(Client *c);
123 void ban(Client *c);
124 void buttonpress(XEvent *e);
125 void checkotherwm(void);
126 void cleanup(void);
127 void configure(Client *c);
128 void configurenotify(XEvent *e);
129 void configurerequest(XEvent *e);
130 void destroynotify(XEvent *e);
131 void detach(Client *c);
132 void detachstack(Client *c);
133 void drawbar(void);
134 void drawsquare(Bool filled, Bool empty, Bool invert, ulong col[ColLast]);
135 void drawtext(const char *text, ulong col[ColLast], Bool invert);
136 void enternotify(XEvent *e);
137 void eprint(const char *errstr, ...);
138 void expose(XEvent *e);
139 void focus(Client *c);
140 void focusin(XEvent *e);
141 void focusnext(const void *arg);
142 void focusprev(const void *arg);
143 Client *getclient(Window w);
144 ulong getcolor(const char *colstr);
145 long getstate(Window w);
146 Bool gettextprop(Window w, Atom atom, char *text, uint size);
147 void grabbuttons(Client *c, Bool focused);
148 void grabkeys(void);
149 void initfont(const char *fontstr);
150 Bool isoccupied(uint t);
151 Bool isprotodel(Client *c);
152 Bool isurgent(uint t);
153 void keypress(XEvent *e);
154 void killclient(const void *arg);
155 void manage(Window w, XWindowAttributes *wa);
156 void mappingnotify(XEvent *e);
157 void maprequest(XEvent *e);
158 void movemouse(Client *c);
159 Client *nexttiled(Client *c);
160 void propertynotify(XEvent *e);
161 void quit(const void *arg);
162 void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
163 void resizemouse(Client *c);
164 void restack(void);
165 void run(void);
166 void scan(void);
167 void setclientstate(Client *c, long state);
168 void setmfact(const void *arg);
169 void setup(void);
170 void spawn(const void *arg);
171 void tag(const void *arg);
172 uint textnw(const char *text, uint len);
173 uint textw(const char *text);
174 void tile(void);
175 void tileresize(Client *c, int x, int y, int w, int h);
176 void togglebar(const void *arg);
177 void togglefloating(const void *arg);
178 void togglelayout(const void *arg);
179 void toggletag(const void *arg);
180 void toggleview(const void *arg);
181 void unban(Client *c);
182 void unmanage(Client *c);
183 void unmapnotify(XEvent *e);
184 void updatebar(void);
185 void updategeom(void);
186 void updatesizehints(Client *c);
187 void updatetilegeom(void);
188 void updatetitle(Client *c);
189 void updatewmhints(Client *c);
190 void view(const void *arg);
191 void viewprevtag(const void *arg);
192 int xerror(Display *dpy, XErrorEvent *ee);
193 int xerrordummy(Display *dpy, XErrorEvent *ee);
194 int xerrorstart(Display *dpy, XErrorEvent *ee);
195 void zoom(const void *arg);
196
197 /* variables */
198 char stext[256];
199 int screen, sx, sy, sw, sh;
200 int bx, by, bw, bh, blw, wx, wy, ww, wh;
201 int mx, my, mw, mh, tx, ty, tw, th;
202 uint seltags = 0;
203 int (*xerrorxlib)(Display *, XErrorEvent *);
204 uint numlockmask = 0;
205 void (*handler[LASTEvent]) (XEvent *) = {
206         [ButtonPress] = buttonpress,
207         [ConfigureRequest] = configurerequest,
208         [ConfigureNotify] = configurenotify,
209         [DestroyNotify] = destroynotify,
210         [EnterNotify] = enternotify,
211         [Expose] = expose,
212         [FocusIn] = focusin,
213         [KeyPress] = keypress,
214         [MappingNotify] = mappingnotify,
215         [MapRequest] = maprequest,
216         [PropertyNotify] = propertynotify,
217         [UnmapNotify] = unmapnotify
218 };
219 Atom wmatom[WMLast], netatom[NetLast];
220 Bool otherwm, readin;
221 Bool running = True;
222 uint tagset[] = {1, 1}; /* after start, first tag is selected */
223 Client *clients = NULL;
224 Client *sel = NULL;
225 Client *stack = NULL;
226 Cursor cursor[CurLast];
227 Display *dpy;
228 DC dc = {0};
229 Layout layouts[];
230 Layout *lt = layouts;
231 Window root, barwin;
232
233 /* configuration, allows nested code to access above variables */
234 #include "config.h"
235
236 /* compile-time check if all tags fit into an uint bit array. */
237 struct NumTags { char limitexceeded[sizeof(uint) * 8 < LENGTH(tags) ? -1 : 1]; };
238
239 /* function implementations */
240 void
241 applyrules(Client *c) {
242         uint i;
243         Rule *r;
244         XClassHint ch = { 0 };
245
246         /* rule matching */
247         XGetClassHint(dpy, c->win, &ch);
248         for(i = 0; i < LENGTH(rules); i++) {
249                 r = &rules[i];
250                 if((!r->title || strstr(c->name, r->title))
251                 && (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
252                 && (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
253                         c->isfloating = r->isfloating;
254                         c->tags |= r->tags & TAGMASK;
255                 }
256         }
257         if(ch.res_class)
258                 XFree(ch.res_class);
259         if(ch.res_name)
260                 XFree(ch.res_name);
261         if(!c->tags)
262                 c->tags = tagset[seltags];
263 }
264
265 void
266 arrange(void) {
267         Client *c;
268
269         for(c = clients; c; c = c->next)
270                 if(VISIBLE(c)) {
271                         unban(c);
272                         if(!lt->arrange || c->isfloating)
273                                 resize(c, c->x, c->y, c->w, c->h, True);
274                 }
275                 else
276                         ban(c);
277
278         focus(NULL);
279         if(lt->arrange)
280                 lt->arrange();
281         restack();
282 }
283
284 void
285 attach(Client *c) {
286         if(clients)
287                 clients->prev = c;
288         c->next = clients;
289         clients = c;
290 }
291
292 void
293 attachstack(Client *c) {
294         c->snext = stack;
295         stack = c;
296 }
297
298 void
299 ban(Client *c) {
300         if(c->isbanned)
301                 return;
302         XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
303         c->isbanned = True;
304 }
305
306 void
307 buttonpress(XEvent *e) {
308         uint i, x, mask;
309         Client *c;
310         XButtonPressedEvent *ev = &e->xbutton;
311
312         if(ev->window == barwin) {
313                 x = 0;
314                 for(i = 0; i < LENGTH(tags); i++) {
315                         x += textw(tags[i]);
316                         if(ev->x < x) {
317                                 mask = 1 << i;
318                                 if(ev->button == Button1) {
319                                         if(ev->state & MODKEY)
320                                                 tag(&mask);
321                                         else
322                                                 view(&mask);
323                                 }
324                                 else if(ev->button == Button3) {
325                                         if(ev->state & MODKEY)
326                                                 toggletag(&mask);
327                                         else
328                                                 toggleview(&mask);
329                                 }
330                                 return;
331                         }
332                 }
333                 if((ev->x < x + blw) && ev->button == Button1) 
334                         togglelayout(NULL);
335         }
336         else if((c = getclient(ev->window))) {
337                 focus(c);
338                 if(CLEANMASK(ev->state) != MODKEY)
339                         return;
340                 if(ev->button == Button1) {
341                         restack();
342                         movemouse(c);
343                 }
344                 else if(ev->button == Button2)
345                         togglefloating(NULL);
346                 else if(ev->button == Button3 && !c->isfixed) {
347                         restack();
348                         resizemouse(c);
349                 }
350         }
351 }
352
353 void
354 checkotherwm(void) {
355         otherwm = False;
356         XSetErrorHandler(xerrorstart);
357
358         /* this causes an error if some other window manager is running */
359         XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
360         XSync(dpy, False);
361         if(otherwm)
362                 eprint("dwm: another window manager is already running\n");
363         XSync(dpy, False);
364         XSetErrorHandler(NULL);
365         xerrorxlib = XSetErrorHandler(xerror);
366         XSync(dpy, False);
367 }
368
369 void
370 cleanup(void) {
371         close(STDIN_FILENO);
372         while(stack) {
373                 unban(stack);
374                 unmanage(stack);
375         }
376         if(dc.font.set)
377                 XFreeFontSet(dpy, dc.font.set);
378         else
379                 XFreeFont(dpy, dc.font.xfont);
380         XUngrabKey(dpy, AnyKey, AnyModifier, root);
381         XFreePixmap(dpy, dc.drawable);
382         XFreeGC(dpy, dc.gc);
383         XFreeCursor(dpy, cursor[CurNormal]);
384         XFreeCursor(dpy, cursor[CurResize]);
385         XFreeCursor(dpy, cursor[CurMove]);
386         XDestroyWindow(dpy, barwin);
387         XSync(dpy, False);
388         XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
389 }
390
391 void
392 configure(Client *c) {
393         XConfigureEvent ce;
394
395         ce.type = ConfigureNotify;
396         ce.display = dpy;
397         ce.event = c->win;
398         ce.window = c->win;
399         ce.x = c->x;
400         ce.y = c->y;
401         ce.width = c->w;
402         ce.height = c->h;
403         ce.border_width = c->bw;
404         ce.above = None;
405         ce.override_redirect = False;
406         XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
407 }
408
409 void
410 configurenotify(XEvent *e) {
411         XConfigureEvent *ev = &e->xconfigure;
412
413         if(ev->window == root && (ev->width != sw || ev->height != sh)) {
414                 sw = ev->width;
415                 sh = ev->height;
416                 updategeom();
417                 updatebar();
418                 arrange();
419         }
420 }
421
422 void
423 configurerequest(XEvent *e) {
424         Client *c;
425         XConfigureRequestEvent *ev = &e->xconfigurerequest;
426         XWindowChanges wc;
427
428         if((c = getclient(ev->window))) {
429                 if(ev->value_mask & CWBorderWidth)
430                         c->bw = ev->border_width;
431                 if(c->isfixed || c->isfloating || !lt->arrange) {
432                         if(ev->value_mask & CWX)
433                                 c->x = sx + ev->x;
434                         if(ev->value_mask & CWY)
435                                 c->y = sy + ev->y;
436                         if(ev->value_mask & CWWidth)
437                                 c->w = ev->width;
438                         if(ev->value_mask & CWHeight)
439                                 c->h = ev->height;
440                         if((c->x - sx + c->w) > sw && c->isfloating)
441                                 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
442                         if((c->y - sy + c->h) > sh && c->isfloating)
443                                 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
444                         if((ev->value_mask & (CWX|CWY))
445                         && !(ev->value_mask & (CWWidth|CWHeight)))
446                                 configure(c);
447                         if(VISIBLE(c))
448                                 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
449                 }
450                 else
451                         configure(c);
452         }
453         else {
454                 wc.x = ev->x;
455                 wc.y = ev->y;
456                 wc.width = ev->width;
457                 wc.height = ev->height;
458                 wc.border_width = ev->border_width;
459                 wc.sibling = ev->above;
460                 wc.stack_mode = ev->detail;
461                 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
462         }
463         XSync(dpy, False);
464 }
465
466 void
467 destroynotify(XEvent *e) {
468         Client *c;
469         XDestroyWindowEvent *ev = &e->xdestroywindow;
470
471         if((c = getclient(ev->window)))
472                 unmanage(c);
473 }
474
475 void
476 detach(Client *c) {
477         if(c->prev)
478                 c->prev->next = c->next;
479         if(c->next)
480                 c->next->prev = c->prev;
481         if(c == clients)
482                 clients = c->next;
483         c->next = c->prev = NULL;
484 }
485
486 void
487 detachstack(Client *c) {
488         Client **tc;
489
490         for(tc = &stack; *tc && *tc != c; tc = &(*tc)->snext);
491         *tc = c->snext;
492 }
493
494 void
495 drawbar(void) {
496         int i, x;
497         Client *c;
498
499         dc.x = 0;
500         for(c = stack; c && !VISIBLE(c); c = c->snext);
501         for(i = 0; i < LENGTH(tags); i++) {
502                 dc.w = textw(tags[i]);
503                 if(tagset[seltags] & 1 << i) {
504                         drawtext(tags[i], dc.sel, isurgent(i));
505                         drawsquare(c && c->tags & 1 << i, isoccupied(i), isurgent(i), dc.sel);
506                 }
507                 else {
508                         drawtext(tags[i], dc.norm, isurgent(i));
509                         drawsquare(c && c->tags & 1 << i, isoccupied(i), isurgent(i), dc.norm);
510                 }
511                 dc.x += dc.w;
512         }
513         if(blw > 0) {
514                 dc.w = blw;
515                 drawtext(lt->symbol, dc.norm, False);
516                 x = dc.x + dc.w;
517         }
518         else
519                 x = dc.x;
520         dc.w = textw(stext);
521         dc.x = bw - dc.w;
522         if(dc.x < x) {
523                 dc.x = x;
524                 dc.w = bw - x;
525         }
526         drawtext(stext, dc.norm, False);
527         if((dc.w = dc.x - x) > bh) {
528                 dc.x = x;
529                 if(c) {
530                         drawtext(c->name, dc.sel, False);
531                         drawsquare(False, c->isfloating, False, dc.sel);
532                 }
533                 else
534                         drawtext(NULL, dc.norm, False);
535         }
536         XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, bw, bh, 0, 0);
537         XSync(dpy, False);
538 }
539
540 void
541 drawsquare(Bool filled, Bool empty, Bool invert, ulong col[ColLast]) {
542         int x;
543         XGCValues gcv;
544         XRectangle r = { dc.x, dc.y, dc.w, dc.h };
545
546         gcv.foreground = col[invert ? ColBG : ColFG];
547         XChangeGC(dpy, dc.gc, GCForeground, &gcv);
548         x = (dc.font.ascent + dc.font.descent + 2) / 4;
549         r.x = dc.x + 1;
550         r.y = dc.y + 1;
551         if(filled) {
552                 r.width = r.height = x + 1;
553                 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
554         }
555         else if(empty) {
556                 r.width = r.height = x;
557                 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
558         }
559 }
560
561 void
562 drawtext(const char *text, ulong col[ColLast], Bool invert) {
563         int x, y, w, h;
564         uint len, olen;
565         XRectangle r = { dc.x, dc.y, dc.w, dc.h };
566         char buf[256];
567
568         XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
569         XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
570         if(!text)
571                 return;
572         olen = strlen(text);
573         len = MIN(olen, sizeof buf);
574         memcpy(buf, text, len);
575         w = 0;
576         h = dc.font.ascent + dc.font.descent;
577         y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
578         x = dc.x + (h / 2);
579         /* shorten text if necessary */
580         for(; len && (w = textnw(buf, len)) > dc.w - h; len--);
581         if(!len)
582                 return;
583         if(len < olen) {
584                 if(len > 1)
585                         buf[len - 1] = '.';
586                 if(len > 2)
587                         buf[len - 2] = '.';
588                 if(len > 3)
589                         buf[len - 3] = '.';
590         }
591         XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
592         if(dc.font.set)
593                 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
594         else
595                 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
596 }
597
598 void
599 enternotify(XEvent *e) {
600         Client *c;
601         XCrossingEvent *ev = &e->xcrossing;
602
603         if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
604                 return;
605         if((c = getclient(ev->window)))
606                 focus(c);
607         else
608                 focus(NULL);
609 }
610
611 void
612 eprint(const char *errstr, ...) {
613         va_list ap;
614
615         va_start(ap, errstr);
616         vfprintf(stderr, errstr, ap);
617         va_end(ap);
618         exit(EXIT_FAILURE);
619 }
620
621 void
622 expose(XEvent *e) {
623         XExposeEvent *ev = &e->xexpose;
624
625         if(ev->count == 0 && (ev->window == barwin))
626                 drawbar();
627 }
628
629 void
630 focus(Client *c) {
631         if(!c || (c && !VISIBLE(c)))
632                 for(c = stack; c && !VISIBLE(c); c = c->snext);
633         if(sel && sel != c) {
634                 grabbuttons(sel, False);
635                 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
636         }
637         if(c) {
638                 detachstack(c);
639                 attachstack(c);
640                 grabbuttons(c, True);
641         }
642         sel = c;
643         if(c) {
644                 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
645                 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
646         }
647         else
648                 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
649         drawbar();
650 }
651
652 void
653 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
654         XFocusChangeEvent *ev = &e->xfocus;
655
656         if(sel && ev->window != sel->win)
657                 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
658 }
659
660 void
661 focusnext(const void *arg) {
662         Client *c;
663
664         if(!sel)
665                 return;
666         for(c = sel->next; c && !VISIBLE(c); c = c->next);
667         if(!c)
668                 for(c = clients; c && !VISIBLE(c); c = c->next);
669         if(c) {
670                 focus(c);
671                 restack();
672         }
673 }
674
675 void
676 focusprev(const void *arg) {
677         Client *c;
678
679         if(!sel)
680                 return;
681         for(c = sel->prev; c && !VISIBLE(c); c = c->prev);
682         if(!c) {
683                 for(c = clients; c && c->next; c = c->next);
684                 for(; c && !VISIBLE(c); c = c->prev);
685         }
686         if(c) {
687                 focus(c);
688                 restack();
689         }
690 }
691
692 Client *
693 getclient(Window w) {
694         Client *c;
695
696         for(c = clients; c && c->win != w; c = c->next);
697         return c;
698 }
699
700 ulong
701 getcolor(const char *colstr) {
702         Colormap cmap = DefaultColormap(dpy, screen);
703         XColor color;
704
705         if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
706                 eprint("error, cannot allocate color '%s'\n", colstr);
707         return color.pixel;
708 }
709
710 long
711 getstate(Window w) {
712         int format, status;
713         long result = -1;
714         unsigned char *p = NULL;
715         ulong n, extra;
716         Atom real;
717
718         status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
719                         &real, &format, &n, &extra, (unsigned char **)&p);
720         if(status != Success)
721                 return -1;
722         if(n != 0)
723                 result = *p;
724         XFree(p);
725         return result;
726 }
727
728 Bool
729 gettextprop(Window w, Atom atom, char *text, uint size) {
730         char **list = NULL;
731         int n;
732         XTextProperty name;
733
734         if(!text || size == 0)
735                 return False;
736         text[0] = '\0';
737         XGetTextProperty(dpy, w, &name, atom);
738         if(!name.nitems)
739                 return False;
740         if(name.encoding == XA_STRING)
741                 strncpy(text, (char *)name.value, size - 1);
742         else {
743                 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
744                 && n > 0 && *list) {
745                         strncpy(text, *list, size - 1);
746                         XFreeStringList(list);
747                 }
748         }
749         text[size - 1] = '\0';
750         XFree(name.value);
751         return True;
752 }
753
754 void
755 grabbuttons(Client *c, Bool focused) {
756         int i, j;
757         uint buttons[]   = { Button1, Button2, Button3 };
758         uint modifiers[] = { MODKEY, MODKEY|LockMask, MODKEY|numlockmask,
759                                 MODKEY|numlockmask|LockMask} ;
760
761         XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
762         if(focused)
763                 for(i = 0; i < LENGTH(buttons); i++)
764                         for(j = 0; j < LENGTH(modifiers); j++)
765                                 XGrabButton(dpy, buttons[i], modifiers[j], c->win, False,
766                                         BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
767         else
768                 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
769                         BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
770 }
771
772 void
773 grabkeys(void) {
774         uint i, j;
775         KeyCode code;
776         XModifierKeymap *modmap;
777
778         /* init modifier map */
779         modmap = XGetModifierMapping(dpy);
780         for(i = 0; i < 8; i++)
781                 for(j = 0; j < modmap->max_keypermod; j++) {
782                         if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
783                                 numlockmask = (1 << i);
784                 }
785         XFreeModifiermap(modmap);
786
787         XUngrabKey(dpy, AnyKey, AnyModifier, root);
788         for(i = 0; i < LENGTH(keys); i++) {
789                 code = XKeysymToKeycode(dpy, keys[i].keysym);
790                 XGrabKey(dpy, code, keys[i].mod, root, True,
791                                 GrabModeAsync, GrabModeAsync);
792                 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
793                                 GrabModeAsync, GrabModeAsync);
794                 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
795                                 GrabModeAsync, GrabModeAsync);
796                 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
797                                 GrabModeAsync, GrabModeAsync);
798         }
799 }
800
801 void
802 initfont(const char *fontstr) {
803         char *def, **missing;
804         int i, n;
805
806         missing = NULL;
807         if(dc.font.set)
808                 XFreeFontSet(dpy, dc.font.set);
809         dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
810         if(missing) {
811                 while(n--)
812                         fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
813                 XFreeStringList(missing);
814         }
815         if(dc.font.set) {
816                 XFontSetExtents *font_extents;
817                 XFontStruct **xfonts;
818                 char **font_names;
819                 dc.font.ascent = dc.font.descent = 0;
820                 font_extents = XExtentsOfFontSet(dc.font.set);
821                 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
822                 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
823                         dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
824                         dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
825                         xfonts++;
826                 }
827         }
828         else {
829                 if(dc.font.xfont)
830                         XFreeFont(dpy, dc.font.xfont);
831                 dc.font.xfont = NULL;
832                 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
833                 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
834                         eprint("error, cannot load font: '%s'\n", fontstr);
835                 dc.font.ascent = dc.font.xfont->ascent;
836                 dc.font.descent = dc.font.xfont->descent;
837         }
838         dc.font.height = dc.font.ascent + dc.font.descent;
839 }
840
841 Bool
842 isoccupied(uint t) {
843         Client *c;
844
845         for(c = clients; c; c = c->next)
846                 if(c->tags & 1 << t)
847                         return True;
848         return False;
849 }
850
851 Bool
852 isprotodel(Client *c) {
853         int i, n;
854         Atom *protocols;
855         Bool ret = False;
856
857         if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
858                 for(i = 0; !ret && i < n; i++)
859                         if(protocols[i] == wmatom[WMDelete])
860                                 ret = True;
861                 XFree(protocols);
862         }
863         return ret;
864 }
865
866 Bool
867 isurgent(uint t) {
868         Client *c;
869
870         for(c = clients; c; c = c->next)
871                 if(c->isurgent && c->tags & 1 << t)
872                         return True;
873         return False;
874 }
875
876 void
877 keypress(XEvent *e) {
878         uint i;
879         KeySym keysym;
880         XKeyEvent *ev;
881
882         ev = &e->xkey;
883         keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
884         for(i = 0; i < LENGTH(keys); i++)
885                 if(keysym == keys[i].keysym
886                 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
887                 {
888                         if(keys[i].func)
889                                 keys[i].func(keys[i].arg);
890                 }
891 }
892
893 void
894 killclient(const void *arg) {
895         XEvent ev;
896
897         if(!sel)
898                 return;
899         if(isprotodel(sel)) {
900                 ev.type = ClientMessage;
901                 ev.xclient.window = sel->win;
902                 ev.xclient.message_type = wmatom[WMProtocols];
903                 ev.xclient.format = 32;
904                 ev.xclient.data.l[0] = wmatom[WMDelete];
905                 ev.xclient.data.l[1] = CurrentTime;
906                 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
907         }
908         else
909                 XKillClient(dpy, sel->win);
910 }
911
912 void
913 manage(Window w, XWindowAttributes *wa) {
914         Client *c, *t = NULL;
915         Status rettrans;
916         Window trans;
917         XWindowChanges wc;
918
919         if(!(c = calloc(1, sizeof(Client))))
920                 eprint("fatal: could not calloc() %u bytes\n", sizeof(Client));
921         c->win = w;
922
923         /* geometry */
924         c->x = wa->x;
925         c->y = wa->y;
926         c->w = wa->width;
927         c->h = wa->height;
928         c->oldbw = wa->border_width;
929         if(c->w == sw && c->h == sh) {
930                 c->x = sx;
931                 c->y = sy;
932                 c->bw = wa->border_width;
933         }
934         else {
935                 if(c->x + c->w + 2 * c->bw > sx + sw)
936                         c->x = sx + sw - c->w - 2 * c->bw;
937                 if(c->y + c->h + 2 * c->bw > sy + sh)
938                         c->y = sy + sh - c->h - 2 * c->bw;
939                 c->x = MAX(c->x, sx);
940                 c->y = MAX(c->y, by == 0 ? bh : sy);
941                 c->bw = borderpx;
942         }
943
944         wc.border_width = c->bw;
945         XConfigureWindow(dpy, w, CWBorderWidth, &wc);
946         XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
947         configure(c); /* propagates border_width, if size doesn't change */
948         updatesizehints(c);
949         XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
950         grabbuttons(c, False);
951         updatetitle(c);
952         if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
953                 for(t = clients; t && t->win != trans; t = t->next);
954         if(t)
955                 c->tags = t->tags;
956         else
957                 applyrules(c);
958         if(!c->isfloating)
959                 c->isfloating = (rettrans == Success) || c->isfixed;
960         attach(c);
961         attachstack(c);
962         XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
963         ban(c);
964         XMapWindow(dpy, c->win);
965         setclientstate(c, NormalState);
966         arrange();
967 }
968
969 void
970 mappingnotify(XEvent *e) {
971         XMappingEvent *ev = &e->xmapping;
972
973         XRefreshKeyboardMapping(ev);
974         if(ev->request == MappingKeyboard)
975                 grabkeys();
976 }
977
978 void
979 maprequest(XEvent *e) {
980         static XWindowAttributes wa;
981         XMapRequestEvent *ev = &e->xmaprequest;
982
983         if(!XGetWindowAttributes(dpy, ev->window, &wa))
984                 return;
985         if(wa.override_redirect)
986                 return;
987         if(!getclient(ev->window))
988                 manage(ev->window, &wa);
989 }
990
991 void
992 movemouse(Client *c) {
993         int x1, y1, ocx, ocy, di, nx, ny;
994         uint dui;
995         Window dummy;
996         XEvent ev;
997
998         ocx = nx = c->x;
999         ocy = ny = c->y;
1000         if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1001         None, cursor[CurMove], CurrentTime) != GrabSuccess)
1002                 return;
1003         XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1004         for(;;) {
1005                 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1006                 switch (ev.type) {
1007                 case ButtonRelease:
1008                         XUngrabPointer(dpy, CurrentTime);
1009                         return;
1010                 case ConfigureRequest:
1011                 case Expose:
1012                 case MapRequest:
1013                         handler[ev.type](&ev);
1014                         break;
1015                 case MotionNotify:
1016                         XSync(dpy, False);
1017                         nx = ocx + (ev.xmotion.x - x1);
1018                         ny = ocy + (ev.xmotion.y - y1);
1019                         if(snap && nx >= wx && nx <= wx + ww
1020                                 && ny >= wy && ny <= wy + wh) {
1021                                 if(abs(wx - nx) < snap)
1022                                         nx = wx;
1023                                 else if(abs((wx + ww) - (nx + c->w + 2 * c->bw)) < snap)
1024                                         nx = wx + ww - c->w - 2 * c->bw;
1025                                 if(abs(wy - ny) < snap)
1026                                         ny = wy;
1027                                 else if(abs((wy + wh) - (ny + c->h + 2 * c->bw)) < snap)
1028                                         ny = wy + wh - c->h - 2 * c->bw;
1029                                 if(!c->isfloating && lt->arrange && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
1030                                         togglefloating(NULL);
1031                         }
1032                         if(!lt->arrange || c->isfloating)
1033                                 resize(c, nx, ny, c->w, c->h, False);
1034                         break;
1035                 }
1036         }
1037 }
1038
1039 Client *
1040 nexttiled(Client *c) {
1041         for(; c && (c->isfloating || !VISIBLE(c)); c = c->next);
1042         return c;
1043 }
1044
1045 void
1046 propertynotify(XEvent *e) {
1047         Client *c;
1048         Window trans;
1049         XPropertyEvent *ev = &e->xproperty;
1050
1051         if(ev->state == PropertyDelete)
1052                 return; /* ignore */
1053         if((c = getclient(ev->window))) {
1054                 switch (ev->atom) {
1055                 default: break;
1056                 case XA_WM_TRANSIENT_FOR:
1057                         XGetTransientForHint(dpy, c->win, &trans);
1058                         if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1059                                 arrange();
1060                         break;
1061                 case XA_WM_NORMAL_HINTS:
1062                         updatesizehints(c);
1063                         break;
1064                 case XA_WM_HINTS:
1065                         updatewmhints(c);
1066                         drawbar();
1067                         break;
1068                 }
1069                 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1070                         updatetitle(c);
1071                         if(c == sel)
1072                                 drawbar();
1073                 }
1074         }
1075 }
1076
1077 void
1078 quit(const void *arg) {
1079         readin = running = False;
1080 }
1081
1082 void
1083 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1084         XWindowChanges wc;
1085
1086         if(sizehints) {
1087                 /* set minimum possible */
1088                 w = MAX(1, w);
1089                 h = MAX(1, h);
1090
1091                 /* temporarily remove base dimensions */
1092                 w -= c->basew;
1093                 h -= c->baseh;
1094
1095                 /* adjust for aspect limits */
1096                 if(c->minax != c->maxax && c->minay != c->maxay 
1097                 && c->minax > 0 && c->maxax > 0 && c->minay > 0 && c->maxay > 0) {
1098                         if(w * c->maxay > h * c->maxax)
1099                                 w = h * c->maxax / c->maxay;
1100                         else if(w * c->minay < h * c->minax)
1101                                 h = w * c->minay / c->minax;
1102                 }
1103
1104                 /* adjust for increment value */
1105                 if(c->incw)
1106                         w -= w % c->incw;
1107                 if(c->inch)
1108                         h -= h % c->inch;
1109
1110                 /* restore base dimensions */
1111                 w += c->basew;
1112                 h += c->baseh;
1113
1114                 w = MAX(w, c->minw);
1115                 h = MAX(h, c->minh);
1116                 
1117                 if (c->maxw)
1118                         w = MIN(w, c->maxw);
1119
1120                 if (c->maxh)
1121                         h = MIN(h, c->maxh);
1122         }
1123         if(w <= 0 || h <= 0)
1124                 return;
1125         if(x > sx + sw)
1126                 x = sw - w - 2 * c->bw;
1127         if(y > sy + sh)
1128                 y = sh - h - 2 * c->bw;
1129         if(x + w + 2 * c->bw < sx)
1130                 x = sx;
1131         if(y + h + 2 * c->bw < sy)
1132                 y = sy;
1133         if(c->x != x || c->y != y || c->w != w || c->h != h) {
1134                 c->x = wc.x = x;
1135                 c->y = wc.y = y;
1136                 c->w = wc.width = w;
1137                 c->h = wc.height = h;
1138                 wc.border_width = c->bw;
1139                 XConfigureWindow(dpy, c->win,
1140                                 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1141                 configure(c);
1142                 XSync(dpy, False);
1143         }
1144 }
1145
1146 void
1147 resizemouse(Client *c) {
1148         int ocx, ocy;
1149         int nw, nh;
1150         XEvent ev;
1151
1152         ocx = c->x;
1153         ocy = c->y;
1154         if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1155         None, cursor[CurResize], CurrentTime) != GrabSuccess)
1156                 return;
1157         XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1158         for(;;) {
1159                 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1160                 switch(ev.type) {
1161                 case ButtonRelease:
1162                         XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1163                                         c->w + c->bw - 1, c->h + c->bw - 1);
1164                         XUngrabPointer(dpy, CurrentTime);
1165                         while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1166                         return;
1167                 case ConfigureRequest:
1168                 case Expose:
1169                 case MapRequest:
1170                         handler[ev.type](&ev);
1171                         break;
1172                 case MotionNotify:
1173                         XSync(dpy, False);
1174                         nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1175                         nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1176
1177                         if(snap && nw >= wx && nw <= wx + ww
1178                                 && nh >= wy && nh <= wy + wh) {
1179                                 if(!c->isfloating && lt->arrange
1180                                    && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1181                                         togglefloating(NULL);
1182                         }
1183                         if(!lt->arrange || c->isfloating)
1184                                 resize(c, c->x, c->y, nw, nh, True);
1185                         break;
1186                 }
1187         }
1188 }
1189
1190 void
1191 restack(void) {
1192         Client *c;
1193         XEvent ev;
1194         XWindowChanges wc;
1195
1196         drawbar();
1197         if(!sel)
1198                 return;
1199         if(sel->isfloating || !lt->arrange)
1200                 XRaiseWindow(dpy, sel->win);
1201         if(lt->arrange) {
1202                 wc.stack_mode = Below;
1203                 wc.sibling = barwin;
1204                 for(c = stack; c; c = c->snext)
1205                         if(!c->isfloating && VISIBLE(c)) {
1206                                 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1207                                 wc.sibling = c->win;
1208                         }
1209         }
1210         XSync(dpy, False);
1211         while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1212 }
1213
1214 void
1215 run(void) {
1216         char *p;
1217         char sbuf[sizeof stext];
1218         fd_set rd;
1219         int r, xfd;
1220         uint len, offset;
1221         XEvent ev;
1222
1223         /* main event loop, also reads status text from stdin */
1224         XSync(dpy, False);
1225         xfd = ConnectionNumber(dpy);
1226         readin = True;
1227         offset = 0;
1228         len = sizeof stext - 1;
1229         sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1230         while(running) {
1231                 FD_ZERO(&rd);
1232                 if(readin)
1233                         FD_SET(STDIN_FILENO, &rd);
1234                 FD_SET(xfd, &rd);
1235                 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1236                         if(errno == EINTR)
1237                                 continue;
1238                         eprint("select failed\n");
1239                 }
1240                 if(FD_ISSET(STDIN_FILENO, &rd)) {
1241                         switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1242                         case -1:
1243                                 strncpy(stext, strerror(errno), len);
1244                                 readin = False;
1245                                 break;
1246                         case 0:
1247                                 strncpy(stext, "EOF", 4);
1248                                 readin = False;
1249                                 break;
1250                         default:
1251                                 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1252                                         if(*p == '\n' || *p == '\0') {
1253                                                 *p = '\0';
1254                                                 strncpy(stext, sbuf, len);
1255                                                 p += r - 1; /* p is sbuf + offset + r - 1 */
1256                                                 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1257                                                 offset = r;
1258                                                 if(r)
1259                                                         memmove(sbuf, p - r + 1, r);
1260                                                 break;
1261                                         }
1262                                 break;
1263                         }
1264                         drawbar();
1265                 }
1266                 while(XPending(dpy)) {
1267                         XNextEvent(dpy, &ev);
1268                         if(handler[ev.type])
1269                                 (handler[ev.type])(&ev); /* call handler */
1270                 }
1271         }
1272 }
1273
1274 void
1275 scan(void) {
1276         uint i, num;
1277         Window *wins, d1, d2;
1278         XWindowAttributes wa;
1279
1280         wins = NULL;
1281         if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1282                 for(i = 0; i < num; i++) {
1283                         if(!XGetWindowAttributes(dpy, wins[i], &wa)
1284                         || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1285                                 continue;
1286                         if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1287                                 manage(wins[i], &wa);
1288                 }
1289                 for(i = 0; i < num; i++) { /* now the transients */
1290                         if(!XGetWindowAttributes(dpy, wins[i], &wa))
1291                                 continue;
1292                         if(XGetTransientForHint(dpy, wins[i], &d1)
1293                         && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1294                                 manage(wins[i], &wa);
1295                 }
1296         }
1297         if(wins)
1298                 XFree(wins);
1299 }
1300
1301 void
1302 setclientstate(Client *c, long state) {
1303         long data[] = {state, None};
1304
1305         XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1306                         PropModeReplace, (unsigned char *)data, 2);
1307 }
1308
1309 /* arg > 1.0 will set mfact absolutly */
1310 void
1311 setmfact(const void *arg) {
1312         double d = *((double*) arg);
1313
1314         if(!d || lt->arrange != tile)
1315                 return;
1316         d = d < 1.0 ? d + mfact : d - 1.0;
1317         if(d < 0.1 || d > 0.9)
1318                 return;
1319         mfact = d;
1320         updatetilegeom();
1321         arrange();
1322 }
1323
1324 void
1325 setup(void) {
1326         uint i, w;
1327         XSetWindowAttributes wa;
1328
1329         /* init screen */
1330         screen = DefaultScreen(dpy);
1331         root = RootWindow(dpy, screen);
1332         initfont(FONT);
1333         sx = 0;
1334         sy = 0;
1335         sw = DisplayWidth(dpy, screen);
1336         sh = DisplayHeight(dpy, screen);
1337         bh = dc.font.height + 2;
1338         updategeom();
1339
1340         /* init atoms */
1341         wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1342         wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1343         wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1344         wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1345         netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1346         netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1347
1348         /* init cursors */
1349         wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1350         cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1351         cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1352
1353         /* init appearance */
1354         dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1355         dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1356         dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1357         dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1358         dc.sel[ColBG] = getcolor(SELBGCOLOR);
1359         dc.sel[ColFG] = getcolor(SELFGCOLOR);
1360         initfont(FONT);
1361         dc.h = bh;
1362         dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1363         dc.gc = XCreateGC(dpy, root, 0, 0);
1364         XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1365         if(!dc.font.set)
1366                 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1367
1368         /* init bar */
1369         for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1370                 w = textw(layouts[i].symbol);
1371                 blw = MAX(blw, w);
1372         }
1373
1374         wa.override_redirect = 1;
1375         wa.background_pixmap = ParentRelative;
1376         wa.event_mask = ButtonPressMask|ExposureMask;
1377
1378         barwin = XCreateWindow(dpy, root, bx, by, bw, bh, 0, DefaultDepth(dpy, screen),
1379                         CopyFromParent, DefaultVisual(dpy, screen),
1380                         CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1381         XDefineCursor(dpy, barwin, cursor[CurNormal]);
1382         XMapRaised(dpy, barwin);
1383         strcpy(stext, "dwm-"VERSION);
1384         drawbar();
1385
1386         /* EWMH support per view */
1387         XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1388                         PropModeReplace, (unsigned char *) netatom, NetLast);
1389
1390         /* select for events */
1391         wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1392                         |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1393         XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1394         XSelectInput(dpy, root, wa.event_mask);
1395
1396
1397         /* grab keys */
1398         grabkeys();
1399 }
1400
1401 void
1402 spawn(const void *arg) {
1403         static char *shell = NULL;
1404
1405         if(!shell && !(shell = getenv("SHELL")))
1406                 shell = "/bin/sh";
1407         /* The double-fork construct avoids zombie processes and keeps the code
1408          * clean from stupid signal handlers. */
1409         if(fork() == 0) {
1410                 if(fork() == 0) {
1411                         if(dpy)
1412                                 close(ConnectionNumber(dpy));
1413                         setsid();
1414                         execl(shell, shell, "-c", (char *)arg, (char *)NULL);
1415                         fprintf(stderr, "dwm: execl '%s -c %s'", shell, (char *)arg);
1416                         perror(" failed");
1417                 }
1418                 exit(0);
1419         }
1420         wait(0);
1421 }
1422
1423 void
1424 tag(const void *arg) {
1425         if(sel && *(int *)arg & TAGMASK) {
1426                 sel->tags = *(int *)arg & TAGMASK;
1427                 arrange();
1428         }
1429 }
1430
1431 uint
1432 textnw(const char *text, uint len) {
1433         XRectangle r;
1434
1435         if(dc.font.set) {
1436                 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1437                 return r.width;
1438         }
1439         return XTextWidth(dc.font.xfont, text, len);
1440 }
1441
1442 uint
1443 textw(const char *text) {
1444         return textnw(text, strlen(text)) + dc.font.height;
1445 }
1446
1447 void
1448 tile(void) {
1449         int x, y, h, w;
1450         uint i, n;
1451         Client *c;
1452
1453         for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next), n++);
1454         if(n == 0)
1455                 return;
1456
1457         /* master */
1458         c = nexttiled(clients);
1459
1460         if(n == 1)
1461                 tileresize(c, wx, wy, ww - 2 * c->bw, wh - 2 * c->bw);
1462         else
1463                 tileresize(c, mx, my, mw - 2 * c->bw, mh - 2 * c->bw);
1464
1465         if(--n == 0)
1466                 return;
1467
1468         /* tile stack */
1469         x = (tx > c->x + c->w) ? c->x + c->w + 2 * c->bw : tw;
1470         y = ty;
1471         w = (tx > c->x + c->w) ? wx + ww - x : tw;
1472         h = th / n;
1473         if(h < bh)
1474                 h = th;
1475
1476         for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1477                 if(i + 1 == n) /* remainder */
1478                         tileresize(c, x, y, w - 2 * c->bw, (ty + th) - y - 2 * c->bw);
1479                 else
1480                         tileresize(c, x, y, w - 2 * c->bw, h - 2 * c->bw);
1481                 if(h != th)
1482                         y = c->y + c->h + 2 * c->bw;
1483         }
1484 }
1485
1486 void
1487 tileresize(Client *c, int x, int y, int w, int h) {
1488         resize(c, x, y, w, h, resizehints);
1489         if(resizehints && ((c->h < bh) || (c->h > h) || (c->w < bh) || (c->w > w)))
1490                 /* client doesn't accept size constraints */
1491                 resize(c, x, y, w, h, False);
1492 }
1493
1494 void
1495 togglebar(const void *arg) {
1496         showbar = !showbar;
1497         updategeom();
1498         updatebar();
1499         arrange();
1500 }
1501
1502 void
1503 togglefloating(const void *arg) {
1504         if(!sel)
1505                 return;
1506         sel->isfloating = !sel->isfloating;
1507         if(sel->isfloating)
1508                 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1509         arrange();
1510 }
1511
1512 void
1513 togglelayout(const void *arg) {
1514         uint i;
1515
1516         if(!arg) {
1517                 if(++lt == &layouts[LENGTH(layouts)])
1518                         lt = &layouts[0];
1519         }
1520         else {
1521                 for(i = 0; i < LENGTH(layouts); i++)
1522                         if(!strcmp((char *)arg, layouts[i].symbol))
1523                                 break;
1524                 if(i == LENGTH(layouts))
1525                         return;
1526                 lt = &layouts[i];
1527         }
1528         if(sel)
1529                 arrange();
1530         else
1531                 drawbar();
1532 }
1533
1534 void
1535 toggletag(const void *arg) {
1536         if(sel && (sel->tags ^ ((*(int *)arg) & TAGMASK))) {
1537                 sel->tags ^= (*(int *)arg) & TAGMASK;
1538                 arrange();
1539         }
1540 }
1541
1542 void
1543 toggleview(const void *arg) {
1544         if((tagset[seltags] ^ ((*(int *)arg) & TAGMASK))) {
1545                 tagset[seltags] ^= (*(int *)arg) & TAGMASK;
1546                 arrange();
1547         }
1548 }
1549
1550 void
1551 unban(Client *c) {
1552         if(!c->isbanned)
1553                 return;
1554         XMoveWindow(dpy, c->win, c->x, c->y);
1555         c->isbanned = False;
1556 }
1557
1558 void
1559 unmanage(Client *c) {
1560         XWindowChanges wc;
1561
1562         wc.border_width = c->oldbw;
1563         /* The server grab construct avoids race conditions. */
1564         XGrabServer(dpy);
1565         XSetErrorHandler(xerrordummy);
1566         XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1567         detach(c);
1568         detachstack(c);
1569         if(sel == c)
1570                 focus(NULL);
1571         XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1572         setclientstate(c, WithdrawnState);
1573         free(c);
1574         XSync(dpy, False);
1575         XSetErrorHandler(xerror);
1576         XUngrabServer(dpy);
1577         arrange();
1578 }
1579
1580 void
1581 unmapnotify(XEvent *e) {
1582         Client *c;
1583         XUnmapEvent *ev = &e->xunmap;
1584
1585         if((c = getclient(ev->window)))
1586                 unmanage(c);
1587 }
1588
1589 void
1590 updatebar(void) {
1591         if(dc.drawable != 0)
1592                 XFreePixmap(dpy, dc.drawable);
1593         dc.drawable = XCreatePixmap(dpy, root, bw, bh, DefaultDepth(dpy, screen));
1594         XMoveResizeWindow(dpy, barwin, bx, by, bw, bh);
1595 }
1596
1597 void
1598 updategeom(void) {
1599         int i;
1600 #ifdef XINERAMA
1601         XineramaScreenInfo *info = NULL;
1602
1603         /* window area geometry */
1604         if(XineramaIsActive(dpy)) {
1605                 info = XineramaQueryScreens(dpy, &i);
1606                 wx = info[0].x_org;
1607                 wy = showbar && topbar ? info[0].y_org + bh : info[0].y_org;
1608                 ww = info[0].width;
1609                 wh = showbar ? info[0].height - bh : info[0].height;
1610                 XFree(info);
1611         }
1612         else
1613 #endif
1614         {
1615                 wx = sx;
1616                 wy = showbar && topbar ? sy + bh : sy;
1617                 ww = sw;
1618                 wh = showbar ? sh - bh : sh;
1619         }
1620
1621         /* bar geometry */
1622         bx = wx;
1623         by = showbar ? (topbar ? wy - bh : wy + wh) : -bh;
1624         bw = ww;
1625
1626         /* update layout geometries */
1627         for(i = 0; i < LENGTH(layouts); i++)
1628                 if(layouts[i].updategeom)
1629                         layouts[i].updategeom();
1630 }
1631
1632 void
1633 updatesizehints(Client *c) {
1634         long msize;
1635         XSizeHints size;
1636
1637         if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1638                 size.flags = PSize;
1639         c->flags = size.flags;
1640         if(c->flags & PBaseSize) {
1641                 c->basew = size.base_width;
1642                 c->baseh = size.base_height;
1643         }
1644         else if(c->flags & PMinSize) {
1645                 c->basew = size.min_width;
1646                 c->baseh = size.min_height;
1647         }
1648         else
1649                 c->basew = c->baseh = 0;
1650         if(c->flags & PResizeInc) {
1651                 c->incw = size.width_inc;
1652                 c->inch = size.height_inc;
1653         }
1654         else
1655                 c->incw = c->inch = 0;
1656         if(c->flags & PMaxSize) {
1657                 c->maxw = size.max_width;
1658                 c->maxh = size.max_height;
1659         }
1660         else
1661                 c->maxw = c->maxh = 0;
1662         if(c->flags & PMinSize) {
1663                 c->minw = size.min_width;
1664                 c->minh = size.min_height;
1665         }
1666         else if(c->flags & PBaseSize) {
1667                 c->minw = size.base_width;
1668                 c->minh = size.base_height;
1669         }
1670         else
1671                 c->minw = c->minh = 0;
1672         if(c->flags & PAspect) {
1673                 c->minax = size.min_aspect.x;
1674                 c->maxax = size.max_aspect.x;
1675                 c->minay = size.min_aspect.y;
1676                 c->maxay = size.max_aspect.y;
1677         }
1678         else
1679                 c->minax = c->maxax = c->minay = c->maxay = 0;
1680         c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1681                         && c->maxw == c->minw && c->maxh == c->minh);
1682 }
1683
1684 void
1685 updatetilegeom(void) {
1686         /* master area geometry */
1687         mx = wx;
1688         my = wy;
1689         mw = mfact * ww;
1690         mh = wh;
1691
1692         /* tile area geometry */
1693         tx = mx + mw;
1694         ty = wy;
1695         tw = ww - mw;
1696         th = wh;
1697 }
1698
1699 void
1700 updatetitle(Client *c) {
1701         if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1702                 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1703 }
1704
1705 void
1706 updatewmhints(Client *c) {
1707         XWMHints *wmh;
1708
1709         if((wmh = XGetWMHints(dpy, c->win))) {
1710                 if(c == sel)
1711                         sel->isurgent = False;
1712                 else
1713                         c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1714                 XFree(wmh);
1715         }
1716 }
1717
1718 void
1719 view(const void *arg) {
1720         if(*(int *)arg & TAGMASK) {
1721                 seltags ^= 1; /* toggle sel tagset */
1722                 tagset[seltags] = *(int *)arg & TAGMASK;
1723                 arrange();
1724         }
1725 }
1726
1727 void
1728 viewprevtag(const void *arg) {
1729         seltags ^= 1; /* toggle sel tagset */
1730         arrange();
1731 }
1732
1733 /* There's no way to check accesses to destroyed windows, thus those cases are
1734  * ignored (especially on UnmapNotify's).  Other types of errors call Xlibs
1735  * default error handler, which may call exit.  */
1736 int
1737 xerror(Display *dpy, XErrorEvent *ee) {
1738         if(ee->error_code == BadWindow
1739         || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1740         || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1741         || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1742         || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1743         || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1744         || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1745         || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1746         || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1747                 return 0;
1748         fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1749                         ee->request_code, ee->error_code);
1750         return xerrorxlib(dpy, ee); /* may call exit */
1751 }
1752
1753 int
1754 xerrordummy(Display *dpy, XErrorEvent *ee) {
1755         return 0;
1756 }
1757
1758 /* Startup Error handler to check if another window manager
1759  * is already running. */
1760 int
1761 xerrorstart(Display *dpy, XErrorEvent *ee) {
1762         otherwm = True;
1763         return -1;
1764 }
1765
1766 void
1767 zoom(const void *arg) {
1768         Client *c = sel;
1769
1770         if(!lt->arrange || sel->isfloating)
1771                 return;
1772         if(c == nexttiled(clients))
1773                 if(!c || !(c = nexttiled(c->next)))
1774                         return;
1775         detach(c);
1776         attach(c);
1777         focus(c);
1778         arrange();
1779 }
1780
1781 int
1782 main(int argc, char *argv[]) {
1783         if(argc == 2 && !strcmp("-v", argv[1]))
1784                 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1785         else if(argc != 1)
1786                 eprint("usage: dwm [-v]\n");
1787
1788         setlocale(LC_CTYPE, "");
1789         if(!(dpy = XOpenDisplay(0)))
1790                 eprint("dwm: cannot open display\n");
1791
1792         checkotherwm();
1793         setup();
1794         scan();
1795         run();
1796         cleanup();
1797
1798         XCloseDisplay(dpy);
1799         return 0;
1800 }