1 /* See LICENSE file for copyright and license details. */
10 #include <sys/select.h>
12 #include <X11/cursorfont.h>
13 #include <X11/keysym.h>
14 #include <X11/Xatom.h>
15 #include <X11/Xproto.h>
16 #include <X11/Xutil.h>
19 #define BUTTONMASK (ButtonPressMask | ButtonReleaseMask)
20 #define CLEANMASK(mask) (mask & ~(numlockmask | LockMask))
21 #define MOUSEMASK (BUTTONMASK | PointerMotionMask)
24 enum { BarTop, BarBot, BarOff }; /* bar position */
25 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
26 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
27 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
28 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
31 typedef struct Client Client;
35 int rx, ry, rw, rh; /* revert geometry */
36 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
37 int minax, maxax, minay, maxay;
39 unsigned int border, oldborder;
40 Bool isbanned, isfixed, ismax, isfloating;
50 unsigned long norm[ColLast];
51 unsigned long sel[ColLast];
61 } DC; /* draw context */
66 void (*func)(const char *arg);
72 void (*arrange)(void);
87 static void eprint(const char *errstr, ...);
88 static void *emallocz(unsigned int size);
89 static void spawn(const char *arg);
90 static void drawsquare(Bool filled, Bool empty, unsigned long col[ColLast]);
91 static unsigned long initcolor(const char *colstr);
92 static void initfont(const char *fontstr);
93 static Bool isoccupied(unsigned int t);
94 static unsigned int textnw(const char *text, unsigned int len);
95 static void drawtext(const char *text, unsigned long col[ColLast]);
96 static void drawbar(void);
97 static void initstyle(void);
98 static void initbar(void);
99 static unsigned int textw(const char *text);
100 static void togglebar(const char *arg);
101 static void updatebarpos(void);
102 static void attachstack(Client *c);
103 static void detachstack(Client *c);
104 static void grabbuttons(Client *c, Bool focused);
105 static Bool isprotodel(Client *c);
106 static void setclientstate(Client *c, long state);
107 static int xerrordummy(Display *dsply, XErrorEvent *ee);
108 static void ban(Client *c);
109 static void configure(Client *c);
110 static void killclient(const char *arg);
111 static void manage(Window w, XWindowAttributes *wa);
112 static void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
113 static void unban(Client *c);
114 static void unmanage(Client *c);
115 static void updatesizehints(Client *c);
116 static void updatetitle(Client *c);
117 static Client *getclient(Window w);
118 static void movemouse(Client *c);
119 static void resizemouse(Client *c);
120 static void buttonpress(XEvent *e);
121 static void configurerequest(XEvent *e);
122 static void configurenotify(XEvent *e);
123 static void destroynotify(XEvent *e);
124 static void enternotify(XEvent *e);
125 static void expose(XEvent *e);
126 static void keypress(XEvent *e);
127 static void leavenotify(XEvent *e);
128 static void mappingnotify(XEvent *e);
129 static void maprequest(XEvent *e);
130 static void propertynotify(XEvent *e);
131 static void unmapnotify(XEvent *e);
132 static void grabkeys(void);
133 static unsigned int idxoftag(const char *tag);
134 static void floating(void); /* default floating layout */
135 static void applyrules(Client *c);
136 static void compileregs(void);
137 static void focusnext(const char *arg);
138 static void focusprev(const char *arg);
139 static void initlayouts(void);
140 static Bool isfloating(void);
141 static Bool isvisible(Client *c);
142 static void restack(void);
143 static void setlayout(const char *arg);
144 static void tag(const char *arg);
145 static void togglefloating(const char *arg);
146 static void togglemax(const char *arg);
147 static void toggletag(const char *arg);
148 static void toggleview(const char *arg);
149 static void view(const char *arg);
150 static void cleanup(void);
151 static long getstate(Window w);
152 static void scan(void);
153 static void setup(void);
154 static int xerrorstart(Display *dsply, XErrorEvent *ee);
155 static Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
156 static void quit(const char *arg);
157 static int xerror(Display *dpy, XErrorEvent *ee);
158 static void arrange(void);
159 static void attach(Client *c);
160 static void detach(Client *c);
161 static void focus(Client *c);
162 static Bool isarrange(void (*func)());
163 static Client *nexttiled(Client *c);
164 static void setmwfact(const char *arg);
165 static void tile(void);
166 static void zoom(const char *arg);
171 static char stext[256];
172 static double mwfact = MWFACT;
173 static int screen, sx, sy, sw, sh, wax, way, waw, wah;
174 static int (*xerrorxlib)(Display *, XErrorEvent *);
175 static unsigned int bh;
176 static unsigned int blw = 0;
177 static unsigned int bpos = BARPOS;
178 static unsigned int ltidx = 0; /* default */
179 static unsigned int nlayouts = 0;
180 static unsigned int nrules = 0;
181 static unsigned int ntags;
182 static unsigned int numlockmask = 0;
183 static void (*handler[LASTEvent]) (XEvent *) = {
184 [ButtonPress] = buttonpress,
185 [ConfigureRequest] = configurerequest,
186 [ConfigureNotify] = configurenotify,
187 [DestroyNotify] = destroynotify,
188 [EnterNotify] = enternotify,
189 [LeaveNotify] = leavenotify,
191 [KeyPress] = keypress,
192 [MappingNotify] = mappingnotify,
193 [MapRequest] = maprequest,
194 [PropertyNotify] = propertynotify,
195 [UnmapNotify] = unmapnotify
197 static Atom wmatom[WMLast], netatom[NetLast];
198 static Bool otherwm, readin;
199 static Bool running = True;
200 static Bool *seltags;
201 static Bool selscreen = True;
202 static Client *clients = NULL;
203 static Client *sel = NULL;
204 static Client *stack = NULL;
205 static Cursor cursor[CurLast];
208 static Window barwin, root;
209 static Regs *regs = NULL;
212 eprint(const char *errstr, ...) {
215 va_start(ap, errstr);
216 vfprintf(stderr, errstr, ap);
222 emallocz(unsigned int size) {
223 void *res = calloc(1, size);
226 eprint("fatal: could not malloc() %u bytes\n", size);
231 spawn(const char *arg) {
232 static char *shell = NULL;
234 if(!shell && !(shell = getenv("SHELL")))
238 /* The double-fork construct avoids zombie processes and keeps the code
239 * clean from stupid signal handlers. */
243 close(ConnectionNumber(dpy));
245 execl(shell, shell, "-c", arg, (char *)NULL);
246 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
255 drawsquare(Bool filled, Bool empty, unsigned long col[ColLast]) {
258 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
260 gcv.foreground = col[ColFG];
261 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
262 x = (dc.font.ascent + dc.font.descent + 2) / 4;
266 r.width = r.height = x + 1;
267 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
270 r.width = r.height = x;
271 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
276 initcolor(const char *colstr) {
277 Colormap cmap = DefaultColormap(dpy, screen);
280 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
281 eprint("error, cannot allocate color '%s'\n", colstr);
286 initfont(const char *fontstr) {
287 char *def, **missing;
292 XFreeFontSet(dpy, dc.font.set);
293 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
296 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
297 XFreeStringList(missing);
300 XFontSetExtents *font_extents;
301 XFontStruct **xfonts;
303 dc.font.ascent = dc.font.descent = 0;
304 font_extents = XExtentsOfFontSet(dc.font.set);
305 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
306 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
307 if(dc.font.ascent < (*xfonts)->ascent)
308 dc.font.ascent = (*xfonts)->ascent;
309 if(dc.font.descent < (*xfonts)->descent)
310 dc.font.descent = (*xfonts)->descent;
316 XFreeFont(dpy, dc.font.xfont);
317 dc.font.xfont = NULL;
318 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
319 || !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
320 eprint("error, cannot load font: '%s'\n", fontstr);
321 dc.font.ascent = dc.font.xfont->ascent;
322 dc.font.descent = dc.font.xfont->descent;
324 dc.font.height = dc.font.ascent + dc.font.descent;
328 isoccupied(unsigned int t) {
331 for(c = clients; c; c = c->next)
338 textnw(const char *text, unsigned int len) {
342 XmbTextExtents(dc.font.set, text, len, NULL, &r);
345 return XTextWidth(dc.font.xfont, text, len);
349 drawtext(const char *text, unsigned long col[ColLast]) {
351 static char buf[256];
352 unsigned int len, olen;
353 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
355 XSetForeground(dpy, dc.gc, col[ColBG]);
356 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
360 olen = len = strlen(text);
361 if(len >= sizeof buf)
362 len = sizeof buf - 1;
363 memcpy(buf, text, len);
365 h = dc.font.ascent + dc.font.descent;
366 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
368 /* shorten text if necessary */
369 while(len && (w = textnw(buf, len)) > dc.w - h)
380 return; /* too long */
381 XSetForeground(dpy, dc.gc, col[ColFG]);
383 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
385 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
393 for(i = 0; i < ntags; i++) {
394 dc.w = textw(tags[i]);
396 drawtext(tags[i], dc.sel);
397 drawsquare(sel && sel->tags[i], isoccupied(i), dc.sel);
400 drawtext(tags[i], dc.norm);
401 drawsquare(sel && sel->tags[i], isoccupied(i), dc.norm);
406 drawtext(layouts[ltidx].symbol, dc.norm);
414 drawtext(stext, dc.norm);
415 if((dc.w = dc.x - x) > bh) {
418 drawtext(sel->name, dc.sel);
419 drawsquare(sel->ismax, sel->isfloating, dc.sel);
422 drawtext(NULL, dc.norm);
424 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, sw, bh, 0, 0);
430 dc.norm[ColBorder] = initcolor(NORMBORDERCOLOR);
431 dc.norm[ColBG] = initcolor(NORMBGCOLOR);
432 dc.norm[ColFG] = initcolor(NORMFGCOLOR);
433 dc.sel[ColBorder] = initcolor(SELBORDERCOLOR);
434 dc.sel[ColBG] = initcolor(SELBGCOLOR);
435 dc.sel[ColFG] = initcolor(SELFGCOLOR);
437 dc.h = bh = dc.font.height + 2;
442 XSetWindowAttributes wa;
444 wa.override_redirect = 1;
445 wa.background_pixmap = ParentRelative;
446 wa.event_mask = ButtonPressMask | ExposureMask;
447 barwin = XCreateWindow(dpy, root, sx, sy, sw, bh, 0,
448 DefaultDepth(dpy, screen), CopyFromParent, DefaultVisual(dpy, screen),
449 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
450 XDefineCursor(dpy, barwin, cursor[CurNormal]);
452 XMapRaised(dpy, barwin);
453 strcpy(stext, "dwm-"VERSION);
454 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
455 dc.gc = XCreateGC(dpy, root, 0, 0);
456 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
458 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
462 textw(const char *text) {
463 return textnw(text, strlen(text)) + dc.font.height;
467 togglebar(const char *arg) {
469 bpos = (BARPOS == BarOff) ? BarTop : BARPOS;
488 XMoveWindow(dpy, barwin, sx, sy);
492 XMoveWindow(dpy, barwin, sx, sy + wah);
495 XMoveWindow(dpy, barwin, sx, sy - bh);
499 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
503 attachstack(Client *c) {
509 detachstack(Client *c) {
512 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
517 grabbuttons(Client *c, Bool focused) {
518 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
521 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
522 GrabModeAsync, GrabModeSync, None, None);
523 XGrabButton(dpy, Button1, MODKEY | LockMask, c->win, False, BUTTONMASK,
524 GrabModeAsync, GrabModeSync, None, None);
525 XGrabButton(dpy, Button1, MODKEY | numlockmask, c->win, False, BUTTONMASK,
526 GrabModeAsync, GrabModeSync, None, None);
527 XGrabButton(dpy, Button1, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
528 GrabModeAsync, GrabModeSync, None, None);
530 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
531 GrabModeAsync, GrabModeSync, None, None);
532 XGrabButton(dpy, Button2, MODKEY | LockMask, c->win, False, BUTTONMASK,
533 GrabModeAsync, GrabModeSync, None, None);
534 XGrabButton(dpy, Button2, MODKEY | numlockmask, c->win, False, BUTTONMASK,
535 GrabModeAsync, GrabModeSync, None, None);
536 XGrabButton(dpy, Button2, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
537 GrabModeAsync, GrabModeSync, None, None);
539 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
540 GrabModeAsync, GrabModeSync, None, None);
541 XGrabButton(dpy, Button3, MODKEY | LockMask, c->win, False, BUTTONMASK,
542 GrabModeAsync, GrabModeSync, None, None);
543 XGrabButton(dpy, Button3, MODKEY | numlockmask, c->win, False, BUTTONMASK,
544 GrabModeAsync, GrabModeSync, None, None);
545 XGrabButton(dpy, Button3, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
546 GrabModeAsync, GrabModeSync, None, None);
549 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
550 GrabModeAsync, GrabModeSync, None, None);
554 isprotodel(Client *c) {
559 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
560 for(i = 0; !ret && i < n; i++)
561 if(protocols[i] == wmatom[WMDelete])
569 setclientstate(Client *c, long state) {
570 long data[] = {state, None};
572 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
573 PropModeReplace, (unsigned char *)data, 2);
577 xerrordummy(Display *dsply, XErrorEvent *ee) {
585 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
590 configure(Client *c) {
593 ce.type = ConfigureNotify;
601 ce.border_width = c->border;
603 ce.override_redirect = False;
604 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
608 killclient(const char *arg) {
613 if(isprotodel(sel)) {
614 ev.type = ClientMessage;
615 ev.xclient.window = sel->win;
616 ev.xclient.message_type = wmatom[WMProtocols];
617 ev.xclient.format = 32;
618 ev.xclient.data.l[0] = wmatom[WMDelete];
619 ev.xclient.data.l[1] = CurrentTime;
620 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
623 XKillClient(dpy, sel->win);
627 manage(Window w, XWindowAttributes *wa) {
629 Client *c, *t = NULL;
634 c = emallocz(sizeof(Client));
635 c->tags = emallocz(ntags * sizeof(Bool));
641 c->oldborder = wa->border_width;
642 if(c->w == sw && c->h == sh) {
645 c->border = wa->border_width;
648 if(c->x + c->w + 2 * c->border > wax + waw)
649 c->x = wax + waw - c->w - 2 * c->border;
650 if(c->y + c->h + 2 * c->border > way + wah)
651 c->y = way + wah - c->h - 2 * c->border;
656 c->border = BORDERPX;
658 wc.border_width = c->border;
659 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
660 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
661 configure(c); /* propagates border_width, if size doesn't change */
664 StructureNotifyMask | PropertyChangeMask | EnterWindowMask);
665 grabbuttons(c, False);
667 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
668 for(t = clients; t && t->win != trans; t = t->next);
670 for(i = 0; i < ntags; i++)
671 c->tags[i] = t->tags[i];
674 c->isfloating = (rettrans == Success) || c->isfixed;
677 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
679 XMapWindow(dpy, c->win);
680 setclientstate(c, NormalState);
685 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
686 double dx, dy, max, min, ratio;
690 if(c->minay > 0 && c->maxay > 0 && (h - c->baseh) > 0 && (w - c->basew) > 0) {
691 dx = (double)(w - c->basew);
692 dy = (double)(h - c->baseh);
693 min = (double)(c->minax) / (double)(c->minay);
694 max = (double)(c->maxax) / (double)(c->maxay);
696 if(max > 0 && min > 0 && ratio > 0) {
698 dy = (dx * min + dy) / (min * min + 1);
700 w = (int)dx + c->basew;
701 h = (int)dy + c->baseh;
703 else if(ratio > max) {
704 dy = (dx * min + dy) / (max * max + 1);
706 w = (int)dx + c->basew;
707 h = (int)dy + c->baseh;
711 if(c->minw && w < c->minw)
713 if(c->minh && h < c->minh)
715 if(c->maxw && w > c->maxw)
717 if(c->maxh && h > c->maxh)
720 w -= (w - c->basew) % c->incw;
722 h -= (h - c->baseh) % c->inch;
726 /* offscreen appearance fixes */
728 x = sw - w - 2 * c->border;
730 y = sh - h - 2 * c->border;
731 if(x + w + 2 * c->border < sx)
733 if(y + h + 2 * c->border < sy)
735 if(c->x != x || c->y != y || c->w != w || c->h != h) {
739 c->h = wc.height = h;
740 wc.border_width = c->border;
741 XConfigureWindow(dpy, c->win, CWX | CWY | CWWidth | CWHeight | CWBorderWidth, &wc);
751 XMoveWindow(dpy, c->win, c->x, c->y);
756 unmanage(Client *c) {
759 wc.border_width = c->oldborder;
760 /* The server grab construct avoids race conditions. */
762 XSetErrorHandler(xerrordummy);
763 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
768 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
769 setclientstate(c, WithdrawnState);
773 XSetErrorHandler(xerror);
779 updatesizehints(Client *c) {
783 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
785 c->flags = size.flags;
786 if(c->flags & PBaseSize) {
787 c->basew = size.base_width;
788 c->baseh = size.base_height;
790 else if(c->flags & PMinSize) {
791 c->basew = size.min_width;
792 c->baseh = size.min_height;
795 c->basew = c->baseh = 0;
796 if(c->flags & PResizeInc) {
797 c->incw = size.width_inc;
798 c->inch = size.height_inc;
801 c->incw = c->inch = 0;
802 if(c->flags & PMaxSize) {
803 c->maxw = size.max_width;
804 c->maxh = size.max_height;
807 c->maxw = c->maxh = 0;
808 if(c->flags & PMinSize) {
809 c->minw = size.min_width;
810 c->minh = size.min_height;
812 else if(c->flags & PBaseSize) {
813 c->minw = size.base_width;
814 c->minh = size.base_height;
817 c->minw = c->minh = 0;
818 if(c->flags & PAspect) {
819 c->minax = size.min_aspect.x;
820 c->maxax = size.max_aspect.x;
821 c->minay = size.min_aspect.y;
822 c->maxay = size.max_aspect.y;
825 c->minax = c->maxax = c->minay = c->maxay = 0;
826 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
827 && c->maxw == c->minw && c->maxh == c->minh);
831 updatetitle(Client *c) {
832 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
833 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
837 getclient(Window w) {
840 for(c = clients; c && c->win != w; c = c->next);
845 movemouse(Client *c) {
846 int x1, y1, ocx, ocy, di, nx, ny;
853 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
854 None, cursor[CurMove], CurrentTime) != GrabSuccess)
857 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
859 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask, &ev);
862 XUngrabPointer(dpy, CurrentTime);
864 case ConfigureRequest:
867 handler[ev.type](&ev);
871 nx = ocx + (ev.xmotion.x - x1);
872 ny = ocy + (ev.xmotion.y - y1);
873 if(abs(wax + nx) < SNAP)
875 else if(abs((wax + waw) - (nx + c->w + 2 * c->border)) < SNAP)
876 nx = wax + waw - c->w - 2 * c->border;
877 if(abs(way - ny) < SNAP)
879 else if(abs((way + wah) - (ny + c->h + 2 * c->border)) < SNAP)
880 ny = way + wah - c->h - 2 * c->border;
881 resize(c, nx, ny, c->w, c->h, False);
888 resizemouse(Client *c) {
895 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
896 None, cursor[CurResize], CurrentTime) != GrabSuccess)
899 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
901 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask , &ev);
904 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
905 c->w + c->border - 1, c->h + c->border - 1);
906 XUngrabPointer(dpy, CurrentTime);
907 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
909 case ConfigureRequest:
912 handler[ev.type](&ev);
916 if((nw = ev.xmotion.x - ocx - 2 * c->border + 1) <= 0)
918 if((nh = ev.xmotion.y - ocy - 2 * c->border + 1) <= 0)
920 resize(c, c->x, c->y, nw, nh, True);
927 buttonpress(XEvent *e) {
930 XButtonPressedEvent *ev = &e->xbutton;
932 if(barwin == ev->window) {
934 for(i = 0; i < ntags; i++) {
937 if(ev->button == Button1) {
938 if(ev->state & MODKEY)
943 else if(ev->button == Button3) {
944 if(ev->state & MODKEY)
952 if((ev->x < x + blw) && ev->button == Button1)
955 else if((c = getclient(ev->window))) {
957 if(CLEANMASK(ev->state) != MODKEY)
959 if(ev->button == Button1 && (isfloating() || c->isfloating)) {
963 else if(ev->button == Button2)
965 else if(ev->button == Button3
966 && (isfloating() || c->isfloating) && !c->isfixed)
975 configurerequest(XEvent *e) {
977 XConfigureRequestEvent *ev = &e->xconfigurerequest;
980 if((c = getclient(ev->window))) {
982 if(ev->value_mask & CWBorderWidth)
983 c->border = ev->border_width;
984 if(c->isfixed || c->isfloating || isfloating()) {
985 if(ev->value_mask & CWX)
987 if(ev->value_mask & CWY)
989 if(ev->value_mask & CWWidth)
991 if(ev->value_mask & CWHeight)
993 if((c->x + c->w) > sw && c->isfloating)
994 c->x = sw / 2 - c->w / 2; /* center in x direction */
995 if((c->y + c->h) > sh && c->isfloating)
996 c->y = sh / 2 - c->h / 2; /* center in y direction */
997 if((ev->value_mask & (CWX | CWY))
998 && !(ev->value_mask & (CWWidth | CWHeight)))
1001 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
1009 wc.width = ev->width;
1010 wc.height = ev->height;
1011 wc.border_width = ev->border_width;
1012 wc.sibling = ev->above;
1013 wc.stack_mode = ev->detail;
1014 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
1020 configurenotify(XEvent *e) {
1021 XConfigureEvent *ev = &e->xconfigure;
1023 if (ev->window == root && (ev->width != sw || ev->height != sh)) {
1026 XFreePixmap(dpy, dc.drawable);
1027 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
1028 XResizeWindow(dpy, barwin, sw, bh);
1035 destroynotify(XEvent *e) {
1037 XDestroyWindowEvent *ev = &e->xdestroywindow;
1039 if((c = getclient(ev->window)))
1044 enternotify(XEvent *e) {
1046 XCrossingEvent *ev = &e->xcrossing;
1048 if(ev->mode != NotifyNormal || ev->detail == NotifyInferior)
1050 if((c = getclient(ev->window)))
1052 else if(ev->window == root) {
1060 XExposeEvent *ev = &e->xexpose;
1062 if(ev->count == 0) {
1063 if(barwin == ev->window)
1069 keypress(XEvent *e) {
1071 unsigned int len = sizeof keys / sizeof keys[0];
1074 XKeyEvent *ev = &e->xkey;
1076 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
1077 for(i = 0; i < len; i++)
1078 if(keysym == keys[i].keysym
1079 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
1082 keys[i].func(keys[i].arg);
1087 leavenotify(XEvent *e) {
1088 XCrossingEvent *ev = &e->xcrossing;
1090 if((ev->window == root) && !ev->same_screen) {
1097 mappingnotify(XEvent *e) {
1098 XMappingEvent *ev = &e->xmapping;
1100 XRefreshKeyboardMapping(ev);
1101 if(ev->request == MappingKeyboard)
1106 maprequest(XEvent *e) {
1107 static XWindowAttributes wa;
1108 XMapRequestEvent *ev = &e->xmaprequest;
1110 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1112 if(wa.override_redirect)
1114 if(!getclient(ev->window))
1115 manage(ev->window, &wa);
1119 propertynotify(XEvent *e) {
1122 XPropertyEvent *ev = &e->xproperty;
1124 if(ev->state == PropertyDelete)
1125 return; /* ignore */
1126 if((c = getclient(ev->window))) {
1129 case XA_WM_TRANSIENT_FOR:
1130 XGetTransientForHint(dpy, c->win, &trans);
1131 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1134 case XA_WM_NORMAL_HINTS:
1138 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1147 unmapnotify(XEvent *e) {
1149 XUnmapEvent *ev = &e->xunmap;
1151 if((c = getclient(ev->window)))
1158 unsigned int len = sizeof keys / sizeof keys[0];
1162 XUngrabKey(dpy, AnyKey, AnyModifier, root);
1163 for(i = 0; i < len; i++) {
1164 code = XKeysymToKeycode(dpy, keys[i].keysym);
1165 XGrabKey(dpy, code, keys[i].mod, root, True,
1166 GrabModeAsync, GrabModeAsync);
1167 XGrabKey(dpy, code, keys[i].mod | LockMask, root, True,
1168 GrabModeAsync, GrabModeAsync);
1169 XGrabKey(dpy, code, keys[i].mod | numlockmask, root, True,
1170 GrabModeAsync, GrabModeAsync);
1171 XGrabKey(dpy, code, keys[i].mod | numlockmask | LockMask, root, True,
1172 GrabModeAsync, GrabModeAsync);
1177 idxoftag(const char *tag) {
1180 for(i = 0; i < ntags; i++)
1187 floating(void) { /* default floating layout */
1190 for(c = clients; c; c = c->next)
1192 resize(c, c->x, c->y, c->w, c->h, True);
1196 applyrules(Client *c) {
1197 static char buf[512];
1200 Bool matched = False;
1201 XClassHint ch = { 0 };
1204 XGetClassHint(dpy, c->win, &ch);
1205 snprintf(buf, sizeof buf, "%s:%s:%s",
1206 ch.res_class ? ch.res_class : "",
1207 ch.res_name ? ch.res_name : "", c->name);
1208 for(i = 0; i < nrules; i++)
1209 if(regs[i].propregex && !regexec(regs[i].propregex, buf, 1, &tmp, 0)) {
1210 c->isfloating = rules[i].isfloating;
1211 for(j = 0; regs[i].tagregex && j < ntags; j++) {
1212 if(!regexec(regs[i].tagregex, tags[j], 1, &tmp, 0)) {
1219 XFree(ch.res_class);
1223 for(i = 0; i < ntags; i++)
1224 c->tags[i] = seltags[i];
1234 nrules = sizeof rules / sizeof rules[0];
1235 regs = emallocz(nrules * sizeof(Regs));
1236 for(i = 0; i < nrules; i++) {
1238 reg = emallocz(sizeof(regex_t));
1239 if(regcomp(reg, rules[i].prop, REG_EXTENDED))
1242 regs[i].propregex = reg;
1245 reg = emallocz(sizeof(regex_t));
1246 if(regcomp(reg, rules[i].tags, REG_EXTENDED))
1249 regs[i].tagregex = reg;
1255 focusnext(const char *arg) {
1260 for(c = sel->next; c && !isvisible(c); c = c->next);
1262 for(c = clients; c && !isvisible(c); c = c->next);
1270 focusprev(const char *arg) {
1275 for(c = sel->prev; c && !isvisible(c); c = c->prev);
1277 for(c = clients; c && c->next; c = c->next);
1278 for(; c && !isvisible(c); c = c->prev);
1290 nlayouts = sizeof layouts / sizeof layouts[0];
1291 for(blw = i = 0; i < nlayouts; i++) {
1292 w = textw(layouts[i].symbol);
1300 return layouts[ltidx].arrange == floating;
1304 isvisible(Client *c) {
1307 for(i = 0; i < ntags; i++)
1308 if(c->tags[i] && seltags[i])
1322 if(sel->isfloating || isfloating())
1323 XRaiseWindow(dpy, sel->win);
1325 wc.stack_mode = Below;
1326 wc.sibling = barwin;
1327 if(!sel->isfloating) {
1328 XConfigureWindow(dpy, sel->win, CWSibling | CWStackMode, &wc);
1329 wc.sibling = sel->win;
1331 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
1334 XConfigureWindow(dpy, c->win, CWSibling | CWStackMode, &wc);
1335 wc.sibling = c->win;
1339 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1343 setlayout(const char *arg) {
1347 if(++ltidx == nlayouts)
1351 for(i = 0; i < nlayouts; i++)
1352 if(!strcmp(arg, layouts[i].symbol))
1365 tag(const char *arg) {
1370 for(i = 0; i < ntags; i++)
1371 sel->tags[i] = arg == NULL;
1373 if(i >= 0 && i < ntags)
1374 sel->tags[i] = True;
1379 togglefloating(const char *arg) {
1382 sel->isfloating = !sel->isfloating;
1384 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1389 togglemax(const char *arg) {
1392 if(!sel || (!isfloating() && !sel->isfloating) || sel->isfixed)
1394 if((sel->ismax = !sel->ismax)) {
1399 resize(sel, wax, way, waw - 2 * sel->border, wah - 2 * sel->border, True);
1402 resize(sel, sel->rx, sel->ry, sel->rw, sel->rh, True);
1404 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1408 toggletag(const char *arg) {
1414 sel->tags[i] = !sel->tags[i];
1415 for(j = 0; j < ntags && !sel->tags[j]; j++);
1417 sel->tags[i] = True;
1422 toggleview(const char *arg) {
1426 seltags[i] = !seltags[i];
1427 for(j = 0; j < ntags && !seltags[j]; j++);
1429 seltags[i] = True; /* cannot toggle last view */
1434 view(const char *arg) {
1437 for(i = 0; i < ntags; i++)
1438 seltags[i] = arg == NULL;
1440 if(i >= 0 && i < ntags)
1447 close(STDIN_FILENO);
1453 XFreeFontSet(dpy, dc.font.set);
1455 XFreeFont(dpy, dc.font.xfont);
1456 XUngrabKey(dpy, AnyKey, AnyModifier, root);
1457 XFreePixmap(dpy, dc.drawable);
1458 XFreeGC(dpy, dc.gc);
1459 XDestroyWindow(dpy, barwin);
1460 XFreeCursor(dpy, cursor[CurNormal]);
1461 XFreeCursor(dpy, cursor[CurResize]);
1462 XFreeCursor(dpy, cursor[CurMove]);
1463 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
1469 getstate(Window w) {
1472 unsigned char *p = NULL;
1473 unsigned long n, extra;
1476 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
1477 &real, &format, &n, &extra, (unsigned char **)&p);
1478 if(status != Success)
1488 unsigned int i, num;
1489 Window *wins, d1, d2;
1490 XWindowAttributes wa;
1493 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1494 for(i = 0; i < num; i++) {
1495 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1496 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1498 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1499 manage(wins[i], &wa);
1501 for(i = 0; i < num; i++) { /* now the transients */
1502 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1504 if(XGetTransientForHint(dpy, wins[i], &d1)
1505 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1506 manage(wins[i], &wa);
1518 XModifierKeymap *modmap;
1519 XSetWindowAttributes wa;
1522 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1523 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1524 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1525 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1526 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1527 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1528 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1529 PropModeReplace, (unsigned char *) netatom, NetLast);
1531 cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1532 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1533 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1534 /* init modifier map */
1535 modmap = XGetModifierMapping(dpy);
1536 for (i = 0; i < 8; i++)
1537 for (j = 0; j < modmap->max_keypermod; j++) {
1538 if(modmap->modifiermap[i * modmap->max_keypermod + j]
1539 == XKeysymToKeycode(dpy, XK_Num_Lock))
1540 numlockmask = (1 << i);
1542 XFreeModifiermap(modmap);
1543 /* select for events */
1544 wa.event_mask = SubstructureRedirectMask | SubstructureNotifyMask
1545 | EnterWindowMask | LeaveWindowMask | StructureNotifyMask;
1546 wa.cursor = cursor[CurNormal];
1547 XChangeWindowAttributes(dpy, root, CWEventMask | CWCursor, &wa);
1548 XSelectInput(dpy, root, wa.event_mask);
1551 for(ntags = 0; tags[ntags]; ntags++);
1552 seltags = emallocz(sizeof(Bool) * ntags);
1556 sw = DisplayWidth(dpy, screen);
1557 sh = DisplayHeight(dpy, screen);
1561 /* multihead support */
1562 selscreen = XQueryPointer(dpy, root, &w, &w, &i, &i, &i, &i, &mask);
1566 * Startup Error handler to check if another window manager
1567 * is already running.
1570 xerrorstart(Display *dsply, XErrorEvent *ee) {
1576 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
1581 if(!text || size == 0)
1584 XGetTextProperty(dpy, w, &name, atom);
1587 if(name.encoding == XA_STRING)
1588 strncpy(text, (char *)name.value, size - 1);
1590 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
1593 strncpy(text, *list, size - 1);
1594 XFreeStringList(list);
1597 text[size - 1] = '\0';
1603 quit(const char *arg) {
1604 readin = running = False;
1607 /* There's no way to check accesses to destroyed windows, thus those cases are
1608 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1609 * default error handler, which may call exit.
1612 xerror(Display *dpy, XErrorEvent *ee) {
1613 if(ee->error_code == BadWindow
1614 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1615 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1616 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1617 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1618 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1619 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1620 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1622 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1623 ee->request_code, ee->error_code);
1624 return xerrorxlib(dpy, ee); /* may call exit */
1631 for(c = clients; c; c = c->next)
1636 layouts[ltidx].arrange();
1652 c->prev->next = c->next;
1654 c->next->prev = c->prev;
1657 c->next = c->prev = NULL;
1662 if((!c && selscreen) || (c && !isvisible(c)))
1663 for(c = stack; c && !isvisible(c); c = c->snext);
1664 if(sel && sel != c) {
1665 grabbuttons(sel, False);
1666 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
1671 grabbuttons(c, True);
1678 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
1679 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
1682 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
1686 isarrange(void (*func)())
1688 return func == layouts[ltidx].arrange;
1692 nexttiled(Client *c) {
1693 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1698 setmwfact(const char *arg) {
1701 if(!isarrange(tile))
1703 /* arg handling, manipulate mwfact */
1706 else if(1 == sscanf(arg, "%lf", &delta)) {
1707 if(arg[0] != '+' && arg[0] != '-')
1713 else if(mwfact > 0.9)
1721 unsigned int i, n, nx, ny, nw, nh, mw, th;
1724 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next))
1728 mw = (n == 1) ? waw : mwfact * waw;
1729 th = (n > 1) ? wah / (n - 1) : 0;
1730 if(n > 1 && th < bh)
1735 for(i = 0, c = nexttiled(clients); c; c = nexttiled(c->next), i++) {
1737 if(i == 0) { /* master */
1738 nw = mw - 2 * c->border;
1739 nh = wah - 2 * c->border;
1741 else { /* tile window */
1746 nw = waw - mw - 2 * c->border;
1747 if(i + 1 == n) /* remainder */
1748 nh = (way + wah) - ny - 2 * c->border;
1750 nh = th - 2 * c->border;
1752 resize(c, nx, ny, nw, nh, RESIZEHINTS);
1753 if(n > 1 && th != wah)
1754 ny += nh + 2 * c->border;
1759 zoom(const char *arg) {
1762 if(!sel || !isarrange(tile) || sel->isfloating)
1764 if((c = sel) == nexttiled(clients))
1765 if(!(c = nexttiled(c->next)))
1774 main(int argc, char *argv[]) {
1780 if(argc == 2 && !strcmp("-v", argv[1]))
1781 eprint("dwm-"VERSION", © 2006-2007 A. R. Garbe, S. van Dijk, J. Salmi, P. Hruby, S. Nagy\n");
1783 eprint("usage: dwm [-v]\n");
1784 setlocale(LC_CTYPE, "");
1785 if(!(dpy = XOpenDisplay(0)))
1786 eprint("dwm: cannot open display\n");
1787 xfd = ConnectionNumber(dpy);
1788 screen = DefaultScreen(dpy);
1789 root = RootWindow(dpy, screen);
1791 XSetErrorHandler(xerrorstart);
1792 /* this causes an error if some other window manager is running */
1793 XSelectInput(dpy, root, SubstructureRedirectMask);
1796 eprint("dwm: another window manager is already running\n");
1799 XSetErrorHandler(NULL);
1800 xerrorxlib = XSetErrorHandler(xerror);
1806 /* main event loop, also reads status text from stdin */
1812 FD_SET(STDIN_FILENO, &rd);
1814 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1817 eprint("select failed\n");
1819 if(FD_ISSET(STDIN_FILENO, &rd)) {
1820 switch(r = read(STDIN_FILENO, stext, sizeof stext - 1)) {
1822 strncpy(stext, strerror(errno), sizeof stext - 1);
1823 stext[sizeof stext - 1] = '\0';
1827 strncpy(stext, "EOF", 4);
1831 for(stext[r] = '\0', p = stext + strlen(stext) - 1; p >= stext && *p == '\n'; *p-- = '\0');
1832 for(; p >= stext && *p != '\n'; --p);
1834 strncpy(stext, p + 1, sizeof stext);
1838 while(XPending(dpy)) {
1839 XNextEvent(dpy, &ev);
1840 if(handler[ev.type])
1841 (handler[ev.type])(&ev); /* call handler */