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