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