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