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