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