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