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