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