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