JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
removed emallocz
[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
56 /* enums */
57 enum { CurNormal, CurResize, CurMove, CurLast };        /* cursor */
58 enum { ColBorder, ColFG, ColBG, ColLast };              /* color */
59 enum { NetSupported, NetWMName, NetLast };              /* EWMH atoms */
60 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
61
62 /* typedefs */
63 typedef unsigned int uint;
64 typedef unsigned long ulong;
65 typedef struct Client Client;
66 struct Client {
67         char name[256];
68         int x, y, w, h;
69         int basew, baseh, incw, inch, maxw, maxh, minw, minh;
70         int minax, maxax, minay, maxay;
71         long flags;
72         int bw, oldbw;
73         Bool isbanned, isfixed, isfloating, isurgent;
74         uint tags;
75         Client *next;
76         Client *prev;
77         Client *snext;
78         Window win;
79 };
80
81 typedef struct {
82         int x, y, w, h;
83         ulong norm[ColLast];
84         ulong sel[ColLast];
85         Drawable drawable;
86         GC gc;
87         struct {
88                 int ascent;
89                 int descent;
90                 int height;
91                 XFontSet set;
92                 XFontStruct *xfont;
93         } font;
94 } DC; /* draw context */
95
96 typedef struct {
97         uint mod;
98         KeySym keysym;
99         void (*func)(const void *arg);
100         const void *arg;
101 } Key;
102
103 typedef struct {
104         const char *symbol;
105         void (*arrange)(void);
106         void (*updategeom)(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 ban(Client *c);
123 void buttonpress(XEvent *e);
124 void checkotherwm(void);
125 void cleanup(void);
126 void configure(Client *c);
127 void configurenotify(XEvent *e);
128 void configurerequest(XEvent *e);
129 void destroynotify(XEvent *e);
130 void detach(Client *c);
131 void detachstack(Client *c);
132 void drawbar(void);
133 void drawsquare(Bool filled, Bool empty, Bool invert, ulong col[ColLast]);
134 void drawtext(const char *text, ulong col[ColLast], Bool invert);
135 void enternotify(XEvent *e);
136 void eprint(const char *errstr, ...);
137 void expose(XEvent *e);
138 void focus(Client *c);
139 void focusin(XEvent *e);
140 void focusnext(const void *arg);
141 void focusprev(const void *arg);
142 Client *getclient(Window w);
143 ulong getcolor(const char *colstr);
144 long getstate(Window w);
145 Bool gettextprop(Window w, Atom atom, char *text, uint size);
146 void grabbuttons(Client *c, Bool focused);
147 void grabkeys(void);
148 void initfont(const char *fontstr);
149 Bool isoccupied(uint t);
150 Bool isprotodel(Client *c);
151 Bool isurgent(uint t);
152 Bool isvisible(Client *c);
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(isvisible(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(isvisible(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 && !isvisible(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 && !isvisible(c)))
632                 for(c = stack; c && !isvisible(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 && !isvisible(c); c = c->next);
667         if(!c)
668                 for(c = clients; c && !isvisible(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 && !isvisible(c); c = c->prev);
682         if(!c) {
683                 for(c = clients; c && c->next; c = c->next);
684                 for(; c && !isvisible(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 Bool
877 isvisible(Client *c) {
878         return c->tags & tagset[seltags];
879 }
880
881 void
882 keypress(XEvent *e) {
883         uint i;
884         KeySym keysym;
885         XKeyEvent *ev;
886
887         ev = &e->xkey;
888         keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
889         for(i = 0; i < LENGTH(keys); i++)
890                 if(keysym == keys[i].keysym
891                 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
892                 {
893                         if(keys[i].func)
894                                 keys[i].func(keys[i].arg);
895                 }
896 }
897
898 void
899 killclient(const void *arg) {
900         XEvent ev;
901
902         if(!sel)
903                 return;
904         if(isprotodel(sel)) {
905                 ev.type = ClientMessage;
906                 ev.xclient.window = sel->win;
907                 ev.xclient.message_type = wmatom[WMProtocols];
908                 ev.xclient.format = 32;
909                 ev.xclient.data.l[0] = wmatom[WMDelete];
910                 ev.xclient.data.l[1] = CurrentTime;
911                 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
912         }
913         else
914                 XKillClient(dpy, sel->win);
915 }
916
917 void
918 manage(Window w, XWindowAttributes *wa) {
919         Client *c, *t = NULL;
920         Status rettrans;
921         Window trans;
922         XWindowChanges wc;
923
924         if(!(c = calloc(1, sizeof(Client))))
925                 eprint("fatal: could not calloc() %u bytes\n", sizeof(Client));
926         c->win = w;
927
928         /* geometry */
929         c->x = wa->x;
930         c->y = wa->y;
931         c->w = wa->width;
932         c->h = wa->height;
933         c->oldbw = wa->border_width;
934         if(c->w == sw && c->h == sh) {
935                 c->x = sx;
936                 c->y = sy;
937                 c->bw = wa->border_width;
938         }
939         else {
940                 if(c->x + c->w + 2 * c->bw > sx + sw)
941                         c->x = sx + sw - c->w - 2 * c->bw;
942                 if(c->y + c->h + 2 * c->bw > sy + sh)
943                         c->y = sy + sh - c->h - 2 * c->bw;
944                 c->x = MAX(c->x, sx);
945                 c->y = MAX(c->y, by == 0 ? bh : sy);
946                 c->bw = borderpx;
947         }
948
949         wc.border_width = c->bw;
950         XConfigureWindow(dpy, w, CWBorderWidth, &wc);
951         XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
952         configure(c); /* propagates border_width, if size doesn't change */
953         updatesizehints(c);
954         XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
955         grabbuttons(c, False);
956         updatetitle(c);
957         if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
958                 for(t = clients; t && t->win != trans; t = t->next);
959         if(t)
960                 c->tags = t->tags;
961         else
962                 applyrules(c);
963         if(!c->isfloating)
964                 c->isfloating = (rettrans == Success) || c->isfixed;
965         attach(c);
966         attachstack(c);
967         XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
968         ban(c);
969         XMapWindow(dpy, c->win);
970         setclientstate(c, NormalState);
971         arrange();
972 }
973
974 void
975 mappingnotify(XEvent *e) {
976         XMappingEvent *ev = &e->xmapping;
977
978         XRefreshKeyboardMapping(ev);
979         if(ev->request == MappingKeyboard)
980                 grabkeys();
981 }
982
983 void
984 maprequest(XEvent *e) {
985         static XWindowAttributes wa;
986         XMapRequestEvent *ev = &e->xmaprequest;
987
988         if(!XGetWindowAttributes(dpy, ev->window, &wa))
989                 return;
990         if(wa.override_redirect)
991                 return;
992         if(!getclient(ev->window))
993                 manage(ev->window, &wa);
994 }
995
996 void
997 movemouse(Client *c) {
998         int x1, y1, ocx, ocy, di, nx, ny;
999         uint dui;
1000         Window dummy;
1001         XEvent ev;
1002
1003         ocx = nx = c->x;
1004         ocy = ny = c->y;
1005         if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1006         None, cursor[CurMove], CurrentTime) != GrabSuccess)
1007                 return;
1008         XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1009         for(;;) {
1010                 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1011                 switch (ev.type) {
1012                 case ButtonRelease:
1013                         XUngrabPointer(dpy, CurrentTime);
1014                         return;
1015                 case ConfigureRequest:
1016                 case Expose:
1017                 case MapRequest:
1018                         handler[ev.type](&ev);
1019                         break;
1020                 case MotionNotify:
1021                         XSync(dpy, False);
1022                         nx = ocx + (ev.xmotion.x - x1);
1023                         ny = ocy + (ev.xmotion.y - y1);
1024                         if(snap && nx >= wx && nx <= wx + ww
1025                                 && ny >= wy && ny <= wy + wh) {
1026                                 if(abs(wx - nx) < snap)
1027                                         nx = wx;
1028                                 else if(abs((wx + ww) - (nx + c->w + 2 * c->bw)) < snap)
1029                                         nx = wx + ww - c->w - 2 * c->bw;
1030                                 if(abs(wy - ny) < snap)
1031                                         ny = wy;
1032                                 else if(abs((wy + wh) - (ny + c->h + 2 * c->bw)) < snap)
1033                                         ny = wy + wh - c->h - 2 * c->bw;
1034                                 if(!c->isfloating && lt->arrange && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
1035                                         togglefloating(NULL);
1036                         }
1037                         if(!lt->arrange || c->isfloating)
1038                                 resize(c, nx, ny, c->w, c->h, False);
1039                         break;
1040                 }
1041         }
1042 }
1043
1044 Client *
1045 nexttiled(Client *c) {
1046         for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1047         return c;
1048 }
1049
1050 void
1051 propertynotify(XEvent *e) {
1052         Client *c;
1053         Window trans;
1054         XPropertyEvent *ev = &e->xproperty;
1055
1056         if(ev->state == PropertyDelete)
1057                 return; /* ignore */
1058         if((c = getclient(ev->window))) {
1059                 switch (ev->atom) {
1060                 default: break;
1061                 case XA_WM_TRANSIENT_FOR:
1062                         XGetTransientForHint(dpy, c->win, &trans);
1063                         if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1064                                 arrange();
1065                         break;
1066                 case XA_WM_NORMAL_HINTS:
1067                         updatesizehints(c);
1068                         break;
1069                 case XA_WM_HINTS:
1070                         updatewmhints(c);
1071                         drawbar();
1072                         break;
1073                 }
1074                 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1075                         updatetitle(c);
1076                         if(c == sel)
1077                                 drawbar();
1078                 }
1079         }
1080 }
1081
1082 void
1083 quit(const void *arg) {
1084         readin = running = False;
1085 }
1086
1087 void
1088 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1089         XWindowChanges wc;
1090
1091         if(sizehints) {
1092                 /* set minimum possible */
1093                 w = MAX(1, w);
1094                 h = MAX(1, h);
1095
1096                 /* temporarily remove base dimensions */
1097                 w -= c->basew;
1098                 h -= c->baseh;
1099
1100                 /* adjust for aspect limits */
1101                 if(c->minax != c->maxax && c->minay != c->maxay 
1102                 && c->minax > 0 && c->maxax > 0 && c->minay > 0 && c->maxay > 0) {
1103                         if(w * c->maxay > h * c->maxax)
1104                                 w = h * c->maxax / c->maxay;
1105                         else if(w * c->minay < h * c->minax)
1106                                 h = w * c->minay / c->minax;
1107                 }
1108
1109                 /* adjust for increment value */
1110                 if(c->incw)
1111                         w -= w % c->incw;
1112                 if(c->inch)
1113                         h -= h % c->inch;
1114
1115                 /* restore base dimensions */
1116                 w += c->basew;
1117                 h += c->baseh;
1118
1119                 w = MAX(w, c->minw);
1120                 h = MAX(h, c->minh);
1121                 
1122                 if (c->maxw)
1123                         w = MIN(w, c->maxw);
1124
1125                 if (c->maxh)
1126                         h = MIN(h, c->maxh);
1127         }
1128         if(w <= 0 || h <= 0)
1129                 return;
1130         if(x > sx + sw)
1131                 x = sw - w - 2 * c->bw;
1132         if(y > sy + sh)
1133                 y = sh - h - 2 * c->bw;
1134         if(x + w + 2 * c->bw < sx)
1135                 x = sx;
1136         if(y + h + 2 * c->bw < sy)
1137                 y = sy;
1138         if(c->x != x || c->y != y || c->w != w || c->h != h) {
1139                 c->x = wc.x = x;
1140                 c->y = wc.y = y;
1141                 c->w = wc.width = w;
1142                 c->h = wc.height = h;
1143                 wc.border_width = c->bw;
1144                 XConfigureWindow(dpy, c->win,
1145                                 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1146                 configure(c);
1147                 XSync(dpy, False);
1148         }
1149 }
1150
1151 void
1152 resizemouse(Client *c) {
1153         int ocx, ocy;
1154         int nw, nh;
1155         XEvent ev;
1156
1157         ocx = c->x;
1158         ocy = c->y;
1159         if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1160         None, cursor[CurResize], CurrentTime) != GrabSuccess)
1161                 return;
1162         XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1163         for(;;) {
1164                 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1165                 switch(ev.type) {
1166                 case ButtonRelease:
1167                         XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1168                                         c->w + c->bw - 1, c->h + c->bw - 1);
1169                         XUngrabPointer(dpy, CurrentTime);
1170                         while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1171                         return;
1172                 case ConfigureRequest:
1173                 case Expose:
1174                 case MapRequest:
1175                         handler[ev.type](&ev);
1176                         break;
1177                 case MotionNotify:
1178                         XSync(dpy, False);
1179                         nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1180                         nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1181
1182                         if(snap && nw >= wx && nw <= wx + ww
1183                                 && nh >= wy && nh <= wy + wh) {
1184                                 if(!c->isfloating && lt->arrange
1185                                    && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1186                                         togglefloating(NULL);
1187                         }
1188                         if(!lt->arrange || c->isfloating)
1189                                 resize(c, c->x, c->y, nw, nh, True);
1190                         break;
1191                 }
1192         }
1193 }
1194
1195 void
1196 restack(void) {
1197         Client *c;
1198         XEvent ev;
1199         XWindowChanges wc;
1200
1201         drawbar();
1202         if(!sel)
1203                 return;
1204         if(sel->isfloating || !lt->arrange)
1205                 XRaiseWindow(dpy, sel->win);
1206         if(lt->arrange) {
1207                 wc.stack_mode = Below;
1208                 wc.sibling = barwin;
1209                 for(c = stack; c; c = c->snext)
1210                         if(!c->isfloating && isvisible(c)) {
1211                                 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1212                                 wc.sibling = c->win;
1213                         }
1214         }
1215         XSync(dpy, False);
1216         while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1217 }
1218
1219 void
1220 run(void) {
1221         char *p;
1222         char sbuf[sizeof stext];
1223         fd_set rd;
1224         int r, xfd;
1225         uint len, offset;
1226         XEvent ev;
1227
1228         /* main event loop, also reads status text from stdin */
1229         XSync(dpy, False);
1230         xfd = ConnectionNumber(dpy);
1231         readin = True;
1232         offset = 0;
1233         len = sizeof stext - 1;
1234         sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1235         while(running) {
1236                 FD_ZERO(&rd);
1237                 if(readin)
1238                         FD_SET(STDIN_FILENO, &rd);
1239                 FD_SET(xfd, &rd);
1240                 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1241                         if(errno == EINTR)
1242                                 continue;
1243                         eprint("select failed\n");
1244                 }
1245                 if(FD_ISSET(STDIN_FILENO, &rd)) {
1246                         switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1247                         case -1:
1248                                 strncpy(stext, strerror(errno), len);
1249                                 readin = False;
1250                                 break;
1251                         case 0:
1252                                 strncpy(stext, "EOF", 4);
1253                                 readin = False;
1254                                 break;
1255                         default:
1256                                 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1257                                         if(*p == '\n' || *p == '\0') {
1258                                                 *p = '\0';
1259                                                 strncpy(stext, sbuf, len);
1260                                                 p += r - 1; /* p is sbuf + offset + r - 1 */
1261                                                 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1262                                                 offset = r;
1263                                                 if(r)
1264                                                         memmove(sbuf, p - r + 1, r);
1265                                                 break;
1266                                         }
1267                                 break;
1268                         }
1269                         drawbar();
1270                 }
1271                 while(XPending(dpy)) {
1272                         XNextEvent(dpy, &ev);
1273                         if(handler[ev.type])
1274                                 (handler[ev.type])(&ev); /* call handler */
1275                 }
1276         }
1277 }
1278
1279 void
1280 scan(void) {
1281         uint i, num;
1282         Window *wins, d1, d2;
1283         XWindowAttributes wa;
1284
1285         wins = NULL;
1286         if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1287                 for(i = 0; i < num; i++) {
1288                         if(!XGetWindowAttributes(dpy, wins[i], &wa)
1289                         || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1290                                 continue;
1291                         if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1292                                 manage(wins[i], &wa);
1293                 }
1294                 for(i = 0; i < num; i++) { /* now the transients */
1295                         if(!XGetWindowAttributes(dpy, wins[i], &wa))
1296                                 continue;
1297                         if(XGetTransientForHint(dpy, wins[i], &d1)
1298                         && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1299                                 manage(wins[i], &wa);
1300                 }
1301         }
1302         if(wins)
1303                 XFree(wins);
1304 }
1305
1306 void
1307 setclientstate(Client *c, long state) {
1308         long data[] = {state, None};
1309
1310         XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1311                         PropModeReplace, (unsigned char *)data, 2);
1312 }
1313
1314 /* arg > 1.0 will set mfact absolutly */
1315 void
1316 setmfact(const void *arg) {
1317         double d = *((double*) arg);
1318
1319         if(!d || lt->arrange != tile)
1320                 return;
1321         d = d < 1.0 ? d + mfact : d - 1.0;
1322         if(d < 0.1 || d > 0.9)
1323                 return;
1324         mfact = d;
1325         updatetilegeom();
1326         arrange();
1327 }
1328
1329 void
1330 setup(void) {
1331         uint i, w;
1332         XSetWindowAttributes wa;
1333
1334         /* init screen */
1335         screen = DefaultScreen(dpy);
1336         root = RootWindow(dpy, screen);
1337         initfont(FONT);
1338         sx = 0;
1339         sy = 0;
1340         sw = DisplayWidth(dpy, screen);
1341         sh = DisplayHeight(dpy, screen);
1342         bh = dc.font.height + 2;
1343         updategeom();
1344
1345         /* init atoms */
1346         wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1347         wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1348         wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1349         wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1350         netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1351         netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1352
1353         /* init cursors */
1354         wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1355         cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1356         cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1357
1358         /* init appearance */
1359         dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1360         dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1361         dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1362         dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1363         dc.sel[ColBG] = getcolor(SELBGCOLOR);
1364         dc.sel[ColFG] = getcolor(SELFGCOLOR);
1365         initfont(FONT);
1366         dc.h = bh;
1367         dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1368         dc.gc = XCreateGC(dpy, root, 0, 0);
1369         XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1370         if(!dc.font.set)
1371                 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1372
1373         /* init bar */
1374         for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1375                 w = textw(layouts[i].symbol);
1376                 blw = MAX(blw, w);
1377         }
1378
1379         wa.override_redirect = 1;
1380         wa.background_pixmap = ParentRelative;
1381         wa.event_mask = ButtonPressMask|ExposureMask;
1382
1383         barwin = XCreateWindow(dpy, root, bx, by, bw, bh, 0, DefaultDepth(dpy, screen),
1384                         CopyFromParent, DefaultVisual(dpy, screen),
1385                         CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1386         XDefineCursor(dpy, barwin, cursor[CurNormal]);
1387         XMapRaised(dpy, barwin);
1388         strcpy(stext, "dwm-"VERSION);
1389         drawbar();
1390
1391         /* EWMH support per view */
1392         XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1393                         PropModeReplace, (unsigned char *) netatom, NetLast);
1394
1395         /* select for events */
1396         wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1397                         |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1398         XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1399         XSelectInput(dpy, root, wa.event_mask);
1400
1401
1402         /* grab keys */
1403         grabkeys();
1404 }
1405
1406 void
1407 spawn(const void *arg) {
1408         static char *shell = NULL;
1409
1410         if(!shell && !(shell = getenv("SHELL")))
1411                 shell = "/bin/sh";
1412         /* The double-fork construct avoids zombie processes and keeps the code
1413          * clean from stupid signal handlers. */
1414         if(fork() == 0) {
1415                 if(fork() == 0) {
1416                         if(dpy)
1417                                 close(ConnectionNumber(dpy));
1418                         setsid();
1419                         execl(shell, shell, "-c", (char *)arg, (char *)NULL);
1420                         fprintf(stderr, "dwm: execl '%s -c %s'", shell, (char *)arg);
1421                         perror(" failed");
1422                 }
1423                 exit(0);
1424         }
1425         wait(0);
1426 }
1427
1428 void
1429 tag(const void *arg) {
1430         if(sel && *(int *)arg & TAGMASK) {
1431                 sel->tags = *(int *)arg & TAGMASK;
1432                 arrange();
1433         }
1434 }
1435
1436 uint
1437 textnw(const char *text, uint len) {
1438         XRectangle r;
1439
1440         if(dc.font.set) {
1441                 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1442                 return r.width;
1443         }
1444         return XTextWidth(dc.font.xfont, text, len);
1445 }
1446
1447 uint
1448 textw(const char *text) {
1449         return textnw(text, strlen(text)) + dc.font.height;
1450 }
1451
1452 void
1453 tile(void) {
1454         int x, y, h, w;
1455         uint i, n;
1456         Client *c;
1457
1458         for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next), n++);
1459         if(n == 0)
1460                 return;
1461
1462         /* master */
1463         c = nexttiled(clients);
1464
1465         if(n == 1)
1466                 tileresize(c, wx, wy, ww - 2 * c->bw, wh - 2 * c->bw);
1467         else
1468                 tileresize(c, mx, my, mw - 2 * c->bw, mh - 2 * c->bw);
1469
1470         if(--n == 0)
1471                 return;
1472
1473         /* tile stack */
1474         x = (tx > c->x + c->w) ? c->x + c->w + 2 * c->bw : tw;
1475         y = ty;
1476         w = (tx > c->x + c->w) ? wx + ww - x : tw;
1477         h = th / n;
1478         if(h < bh)
1479                 h = th;
1480
1481         for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1482                 if(i + 1 == n) /* remainder */
1483                         tileresize(c, x, y, w - 2 * c->bw, (ty + th) - y - 2 * c->bw);
1484                 else
1485                         tileresize(c, x, y, w - 2 * c->bw, h - 2 * c->bw);
1486                 if(h != th)
1487                         y = c->y + c->h + 2 * c->bw;
1488         }
1489 }
1490
1491 void
1492 tileresize(Client *c, int x, int y, int w, int h) {
1493         resize(c, x, y, w, h, resizehints);
1494         if(resizehints && ((c->h < bh) || (c->h > h) || (c->w < bh) || (c->w > w)))
1495                 /* client doesn't accept size constraints */
1496                 resize(c, x, y, w, h, False);
1497 }
1498
1499 void
1500 togglebar(const void *arg) {
1501         showbar = !showbar;
1502         updategeom();
1503         updatebar();
1504         arrange();
1505 }
1506
1507 void
1508 togglefloating(const void *arg) {
1509         if(!sel)
1510                 return;
1511         sel->isfloating = !sel->isfloating;
1512         if(sel->isfloating)
1513                 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1514         arrange();
1515 }
1516
1517 void
1518 togglelayout(const void *arg) {
1519         uint i;
1520
1521         if(!arg) {
1522                 if(++lt == &layouts[LENGTH(layouts)])
1523                         lt = &layouts[0];
1524         }
1525         else {
1526                 for(i = 0; i < LENGTH(layouts); i++)
1527                         if(!strcmp((char *)arg, layouts[i].symbol))
1528                                 break;
1529                 if(i == LENGTH(layouts))
1530                         return;
1531                 lt = &layouts[i];
1532         }
1533         if(sel)
1534                 arrange();
1535         else
1536                 drawbar();
1537 }
1538
1539 void
1540 toggletag(const void *arg) {
1541         if(sel && (sel->tags ^ ((*(int *)arg) & TAGMASK))) {
1542                 sel->tags ^= (*(int *)arg) & TAGMASK;
1543                 arrange();
1544         }
1545 }
1546
1547 void
1548 toggleview(const void *arg) {
1549         if((tagset[seltags] ^ ((*(int *)arg) & TAGMASK))) {
1550                 tagset[seltags] ^= (*(int *)arg) & TAGMASK;
1551                 arrange();
1552         }
1553 }
1554
1555 void
1556 unban(Client *c) {
1557         if(!c->isbanned)
1558                 return;
1559         XMoveWindow(dpy, c->win, c->x, c->y);
1560         c->isbanned = False;
1561 }
1562
1563 void
1564 unmanage(Client *c) {
1565         XWindowChanges wc;
1566
1567         wc.border_width = c->oldbw;
1568         /* The server grab construct avoids race conditions. */
1569         XGrabServer(dpy);
1570         XSetErrorHandler(xerrordummy);
1571         XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1572         detach(c);
1573         detachstack(c);
1574         if(sel == c)
1575                 focus(NULL);
1576         XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1577         setclientstate(c, WithdrawnState);
1578         free(c);
1579         XSync(dpy, False);
1580         XSetErrorHandler(xerror);
1581         XUngrabServer(dpy);
1582         arrange();
1583 }
1584
1585 void
1586 unmapnotify(XEvent *e) {
1587         Client *c;
1588         XUnmapEvent *ev = &e->xunmap;
1589
1590         if((c = getclient(ev->window)))
1591                 unmanage(c);
1592 }
1593
1594 void
1595 updatebar(void) {
1596         if(dc.drawable != 0)
1597                 XFreePixmap(dpy, dc.drawable);
1598         dc.drawable = XCreatePixmap(dpy, root, bw, bh, DefaultDepth(dpy, screen));
1599         XMoveResizeWindow(dpy, barwin, bx, by, bw, bh);
1600 }
1601
1602 void
1603 updategeom(void) {
1604         int i;
1605 #ifdef XINERAMA
1606         XineramaScreenInfo *info = NULL;
1607
1608         /* window area geometry */
1609         if(XineramaIsActive(dpy)) {
1610                 info = XineramaQueryScreens(dpy, &i);
1611                 wx = info[0].x_org;
1612                 wy = showbar && topbar ? info[0].y_org + bh : info[0].y_org;
1613                 ww = info[0].width;
1614                 wh = showbar ? info[0].height - bh : info[0].height;
1615                 XFree(info);
1616         }
1617         else
1618 #endif
1619         {
1620                 wx = sx;
1621                 wy = showbar && topbar ? sy + bh : sy;
1622                 ww = sw;
1623                 wh = showbar ? sh - bh : sh;
1624         }
1625
1626         /* bar geometry */
1627         bx = wx;
1628         by = showbar ? (topbar ? wy - bh : wy + wh) : -bh;
1629         bw = ww;
1630
1631         /* update layout geometries */
1632         for(i = 0; i < LENGTH(layouts); i++)
1633                 if(layouts[i].updategeom)
1634                         layouts[i].updategeom();
1635 }
1636
1637 void
1638 updatesizehints(Client *c) {
1639         long msize;
1640         XSizeHints size;
1641
1642         if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1643                 size.flags = PSize;
1644         c->flags = size.flags;
1645         if(c->flags & PBaseSize) {
1646                 c->basew = size.base_width;
1647                 c->baseh = size.base_height;
1648         }
1649         else if(c->flags & PMinSize) {
1650                 c->basew = size.min_width;
1651                 c->baseh = size.min_height;
1652         }
1653         else
1654                 c->basew = c->baseh = 0;
1655         if(c->flags & PResizeInc) {
1656                 c->incw = size.width_inc;
1657                 c->inch = size.height_inc;
1658         }
1659         else
1660                 c->incw = c->inch = 0;
1661         if(c->flags & PMaxSize) {
1662                 c->maxw = size.max_width;
1663                 c->maxh = size.max_height;
1664         }
1665         else
1666                 c->maxw = c->maxh = 0;
1667         if(c->flags & PMinSize) {
1668                 c->minw = size.min_width;
1669                 c->minh = size.min_height;
1670         }
1671         else if(c->flags & PBaseSize) {
1672                 c->minw = size.base_width;
1673                 c->minh = size.base_height;
1674         }
1675         else
1676                 c->minw = c->minh = 0;
1677         if(c->flags & PAspect) {
1678                 c->minax = size.min_aspect.x;
1679                 c->maxax = size.max_aspect.x;
1680                 c->minay = size.min_aspect.y;
1681                 c->maxay = size.max_aspect.y;
1682         }
1683         else
1684                 c->minax = c->maxax = c->minay = c->maxay = 0;
1685         c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1686                         && c->maxw == c->minw && c->maxh == c->minh);
1687 }
1688
1689 void
1690 updatetilegeom(void) {
1691         /* master area geometry */
1692         mx = wx;
1693         my = wy;
1694         mw = mfact * ww;
1695         mh = wh;
1696
1697         /* tile area geometry */
1698         tx = mx + mw;
1699         ty = wy;
1700         tw = ww - mw;
1701         th = wh;
1702 }
1703
1704 void
1705 updatetitle(Client *c) {
1706         if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1707                 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1708 }
1709
1710 void
1711 updatewmhints(Client *c) {
1712         XWMHints *wmh;
1713
1714         if((wmh = XGetWMHints(dpy, c->win))) {
1715                 if(c == sel)
1716                         sel->isurgent = False;
1717                 else
1718                         c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1719                 XFree(wmh);
1720         }
1721 }
1722
1723 void
1724 view(const void *arg) {
1725         if(*(int *)arg & TAGMASK) {
1726                 seltags ^= 1; /* toggle sel tagset */
1727                 tagset[seltags] = *(int *)arg & TAGMASK;
1728                 arrange();
1729         }
1730 }
1731
1732 void
1733 viewprevtag(const void *arg) {
1734         seltags ^= 1; /* toggle sel tagset */
1735         arrange();
1736 }
1737
1738 /* There's no way to check accesses to destroyed windows, thus those cases are
1739  * ignored (especially on UnmapNotify's).  Other types of errors call Xlibs
1740  * default error handler, which may call exit.  */
1741 int
1742 xerror(Display *dpy, XErrorEvent *ee) {
1743         if(ee->error_code == BadWindow
1744         || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1745         || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1746         || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1747         || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1748         || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1749         || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1750         || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1751         || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1752                 return 0;
1753         fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1754                         ee->request_code, ee->error_code);
1755         return xerrorxlib(dpy, ee); /* may call exit */
1756 }
1757
1758 int
1759 xerrordummy(Display *dpy, XErrorEvent *ee) {
1760         return 0;
1761 }
1762
1763 /* Startup Error handler to check if another window manager
1764  * is already running. */
1765 int
1766 xerrorstart(Display *dpy, XErrorEvent *ee) {
1767         otherwm = True;
1768         return -1;
1769 }
1770
1771 void
1772 zoom(const void *arg) {
1773         Client *c = sel;
1774
1775         if(!lt->arrange || sel->isfloating)
1776                 return;
1777         if(c == nexttiled(clients))
1778                 if(!c || !(c = nexttiled(c->next)))
1779                         return;
1780         detach(c);
1781         attach(c);
1782         focus(c);
1783         arrange();
1784 }
1785
1786 int
1787 main(int argc, char *argv[]) {
1788         if(argc == 2 && !strcmp("-v", argv[1]))
1789                 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1790         else if(argc != 1)
1791                 eprint("usage: dwm [-v]\n");
1792
1793         setlocale(LC_CTYPE, "");
1794         if(!(dpy = XOpenDisplay(0)))
1795                 eprint("dwm: cannot open display\n");
1796
1797         checkotherwm();
1798         setup();
1799         scan();
1800         run();
1801         cleanup();
1802
1803         XCloseDisplay(dpy);
1804         return 0;
1805 }