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