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