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