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