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