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 unsigned int idxoftag(const char *tag);
133 static void floating(void); /* default floating layout */
134 static void applyrules(Client *c);
135 static void compileregs(void);
136 static void focusnext(const char *arg);
137 static void focusprev(const char *arg);
138 static void initlayouts(void);
139 static Bool isfloating(void);
140 static Bool isvisible(Client *c);
141 static void restack(void);
142 static void setlayout(const char *arg);
143 static void tag(const char *arg);
144 static void togglefloating(const char *arg);
145 static void togglemax(const char *arg);
146 static void toggletag(const char *arg);
147 static void toggleview(const char *arg);
148 static void view(const char *arg);
149 static void cleanup(void);
150 static long getstate(Window w);
151 static void scan(void);
152 static void setup(void);
153 static int xerrorstart(Display *dsply, XErrorEvent *ee);
154 static Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
155 static void quit(const char *arg);
156 static int xerror(Display *dpy, XErrorEvent *ee);
157 static void arrange(void);
158 static void attach(Client *c);
159 static void detach(Client *c);
160 static void focus(Client *c);
161 static Bool isarrange(void (*func)());
162 static Client *nexttiled(Client *c);
163 static void setmwfact(const char *arg);
164 static void tile(void);
165 static void zoom(const char *arg);
170 static char stext[256];
171 static double mwfact = MWFACT;
172 static int screen, sx, sy, sw, sh, wax, way, waw, wah;
173 static int (*xerrorxlib)(Display *, XErrorEvent *);
174 static unsigned int bh;
175 static unsigned int blw = 0;
176 static unsigned int bpos = BARPOS;
177 static unsigned int ltidx = 0; /* default */
178 static unsigned int nlayouts = 0;
179 static unsigned int nrules = 0;
180 static unsigned int ntags;
181 static unsigned int numlockmask = 0;
182 static void (*handler[LASTEvent]) (XEvent *) = {
183 [ButtonPress] = buttonpress,
184 [ConfigureRequest] = configurerequest,
185 [ConfigureNotify] = configurenotify,
186 [DestroyNotify] = destroynotify,
187 [EnterNotify] = enternotify,
188 [LeaveNotify] = leavenotify,
190 [KeyPress] = keypress,
191 [MappingNotify] = mappingnotify,
192 [MapRequest] = maprequest,
193 [PropertyNotify] = propertynotify,
194 [UnmapNotify] = unmapnotify
196 static Atom wmatom[WMLast], netatom[NetLast];
197 static Bool otherwm, readin;
198 static Bool running = True;
199 static Bool *seltags;
200 static Bool selscreen = True;
201 static Client *clients = NULL;
202 static Client *sel = NULL;
203 static Client *stack = NULL;
204 static Cursor cursor[CurLast];
207 static Window barwin, root;
208 static Regs *regs = NULL;
211 eprint(const char *errstr, ...) {
214 va_start(ap, errstr);
215 vfprintf(stderr, errstr, ap);
221 emallocz(unsigned int size) {
222 void *res = calloc(1, size);
225 eprint("fatal: could not malloc() %u bytes\n", size);
230 spawn(const char *arg) {
231 static char *shell = NULL;
233 if(!shell && !(shell = getenv("SHELL")))
237 /* The double-fork construct avoids zombie processes and keeps the code
238 * clean from stupid signal handlers. */
242 close(ConnectionNumber(dpy));
244 execl(shell, shell, "-c", arg, (char *)NULL);
245 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
254 drawsquare(Bool filled, Bool empty, unsigned long col[ColLast]) {
257 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
259 gcv.foreground = col[ColFG];
260 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
261 x = (dc.font.ascent + dc.font.descent + 2) / 4;
265 r.width = r.height = x + 1;
266 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
269 r.width = r.height = x;
270 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
275 initcolor(const char *colstr) {
276 Colormap cmap = DefaultColormap(dpy, screen);
279 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
280 eprint("error, cannot allocate color '%s'\n", colstr);
285 initfont(const char *fontstr) {
286 char *def, **missing;
291 XFreeFontSet(dpy, dc.font.set);
292 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
295 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
296 XFreeStringList(missing);
299 XFontSetExtents *font_extents;
300 XFontStruct **xfonts;
302 dc.font.ascent = dc.font.descent = 0;
303 font_extents = XExtentsOfFontSet(dc.font.set);
304 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
305 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
306 if(dc.font.ascent < (*xfonts)->ascent)
307 dc.font.ascent = (*xfonts)->ascent;
308 if(dc.font.descent < (*xfonts)->descent)
309 dc.font.descent = (*xfonts)->descent;
315 XFreeFont(dpy, dc.font.xfont);
316 dc.font.xfont = NULL;
317 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
318 || !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
319 eprint("error, cannot load font: '%s'\n", fontstr);
320 dc.font.ascent = dc.font.xfont->ascent;
321 dc.font.descent = dc.font.xfont->descent;
323 dc.font.height = dc.font.ascent + dc.font.descent;
327 isoccupied(unsigned int t) {
330 for(c = clients; c; c = c->next)
337 textnw(const char *text, unsigned int len) {
341 XmbTextExtents(dc.font.set, text, len, NULL, &r);
344 return XTextWidth(dc.font.xfont, text, len);
348 drawtext(const char *text, unsigned long col[ColLast]) {
350 static char buf[256];
351 unsigned int len, olen;
352 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
354 XSetForeground(dpy, dc.gc, col[ColBG]);
355 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
359 olen = len = strlen(text);
360 if(len >= sizeof buf)
361 len = sizeof buf - 1;
362 memcpy(buf, text, len);
364 h = dc.font.ascent + dc.font.descent;
365 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
367 /* shorten text if necessary */
368 while(len && (w = textnw(buf, len)) > dc.w - h)
379 return; /* too long */
380 XSetForeground(dpy, dc.gc, col[ColFG]);
382 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
384 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
392 for(i = 0; i < ntags; i++) {
393 dc.w = textw(tags[i]);
395 drawtext(tags[i], dc.sel);
396 drawsquare(sel && sel->tags[i], isoccupied(i), dc.sel);
399 drawtext(tags[i], dc.norm);
400 drawsquare(sel && sel->tags[i], isoccupied(i), dc.norm);
405 drawtext(layouts[ltidx].symbol, dc.norm);
413 drawtext(stext, dc.norm);
414 if((dc.w = dc.x - x) > bh) {
417 drawtext(sel->name, dc.sel);
418 drawsquare(sel->ismax, sel->isfloating, dc.sel);
421 drawtext(NULL, dc.norm);
423 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, sw, bh, 0, 0);
429 dc.norm[ColBorder] = initcolor(NORMBORDERCOLOR);
430 dc.norm[ColBG] = initcolor(NORMBGCOLOR);
431 dc.norm[ColFG] = initcolor(NORMFGCOLOR);
432 dc.sel[ColBorder] = initcolor(SELBORDERCOLOR);
433 dc.sel[ColBG] = initcolor(SELBGCOLOR);
434 dc.sel[ColFG] = initcolor(SELFGCOLOR);
436 dc.h = bh = dc.font.height + 2;
441 XSetWindowAttributes wa;
443 wa.override_redirect = 1;
444 wa.background_pixmap = ParentRelative;
445 wa.event_mask = ButtonPressMask | ExposureMask;
446 barwin = XCreateWindow(dpy, root, sx, sy, sw, bh, 0,
447 DefaultDepth(dpy, screen), CopyFromParent, DefaultVisual(dpy, screen),
448 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
449 XDefineCursor(dpy, barwin, cursor[CurNormal]);
451 XMapRaised(dpy, barwin);
452 strcpy(stext, "dwm-"VERSION);
453 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
454 dc.gc = XCreateGC(dpy, root, 0, 0);
455 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
457 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
461 textw(const char *text) {
462 return textnw(text, strlen(text)) + dc.font.height;
466 togglebar(const char *arg) {
468 bpos = (BARPOS == BarOff) ? BarTop : BARPOS;
487 XMoveWindow(dpy, barwin, sx, sy);
491 XMoveWindow(dpy, barwin, sx, sy + wah);
494 XMoveWindow(dpy, barwin, sx, sy - bh);
498 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
502 attachstack(Client *c) {
508 detachstack(Client *c) {
511 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
516 grabbuttons(Client *c, Bool focused) {
517 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
520 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
521 GrabModeAsync, GrabModeSync, None, None);
522 XGrabButton(dpy, Button1, MODKEY | LockMask, c->win, False, BUTTONMASK,
523 GrabModeAsync, GrabModeSync, None, None);
524 XGrabButton(dpy, Button1, MODKEY | numlockmask, c->win, False, BUTTONMASK,
525 GrabModeAsync, GrabModeSync, None, None);
526 XGrabButton(dpy, Button1, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
527 GrabModeAsync, GrabModeSync, None, None);
529 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
530 GrabModeAsync, GrabModeSync, None, None);
531 XGrabButton(dpy, Button2, MODKEY | LockMask, c->win, False, BUTTONMASK,
532 GrabModeAsync, GrabModeSync, None, None);
533 XGrabButton(dpy, Button2, MODKEY | numlockmask, c->win, False, BUTTONMASK,
534 GrabModeAsync, GrabModeSync, None, None);
535 XGrabButton(dpy, Button2, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
536 GrabModeAsync, GrabModeSync, None, None);
538 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
539 GrabModeAsync, GrabModeSync, None, None);
540 XGrabButton(dpy, Button3, MODKEY | LockMask, c->win, False, BUTTONMASK,
541 GrabModeAsync, GrabModeSync, None, None);
542 XGrabButton(dpy, Button3, MODKEY | numlockmask, c->win, False, BUTTONMASK,
543 GrabModeAsync, GrabModeSync, None, None);
544 XGrabButton(dpy, Button3, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
545 GrabModeAsync, GrabModeSync, None, None);
548 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
549 GrabModeAsync, GrabModeSync, None, None);
553 isprotodel(Client *c) {
558 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
559 for(i = 0; !ret && i < n; i++)
560 if(protocols[i] == wmatom[WMDelete])
568 setclientstate(Client *c, long state) {
569 long data[] = {state, None};
571 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
572 PropModeReplace, (unsigned char *)data, 2);
576 xerrordummy(Display *dsply, XErrorEvent *ee) {
584 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
589 configure(Client *c) {
592 ce.type = ConfigureNotify;
600 ce.border_width = c->border;
602 ce.override_redirect = False;
603 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
607 killclient(const char *arg) {
612 if(isprotodel(sel)) {
613 ev.type = ClientMessage;
614 ev.xclient.window = sel->win;
615 ev.xclient.message_type = wmatom[WMProtocols];
616 ev.xclient.format = 32;
617 ev.xclient.data.l[0] = wmatom[WMDelete];
618 ev.xclient.data.l[1] = CurrentTime;
619 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
622 XKillClient(dpy, sel->win);
626 manage(Window w, XWindowAttributes *wa) {
628 Client *c, *t = NULL;
633 c = emallocz(sizeof(Client));
634 c->tags = emallocz(ntags * sizeof(Bool));
640 c->oldborder = wa->border_width;
641 if(c->w == sw && c->h == sh) {
644 c->border = wa->border_width;
647 if(c->x + c->w + 2 * c->border > wax + waw)
648 c->x = wax + waw - c->w - 2 * c->border;
649 if(c->y + c->h + 2 * c->border > way + wah)
650 c->y = way + wah - c->h - 2 * c->border;
655 c->border = BORDERPX;
657 wc.border_width = c->border;
658 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
659 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
660 configure(c); /* propagates border_width, if size doesn't change */
663 StructureNotifyMask | PropertyChangeMask | EnterWindowMask);
664 grabbuttons(c, False);
666 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
667 for(t = clients; t && t->win != trans; t = t->next);
669 for(i = 0; i < ntags; i++)
670 c->tags[i] = t->tags[i];
673 c->isfloating = (rettrans == Success) || c->isfixed;
676 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
678 XMapWindow(dpy, c->win);
679 setclientstate(c, NormalState);
684 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
685 double dx, dy, max, min, ratio;
689 if(c->minay > 0 && c->maxay > 0 && (h - c->baseh) > 0 && (w - c->basew) > 0) {
690 dx = (double)(w - c->basew);
691 dy = (double)(h - c->baseh);
692 min = (double)(c->minax) / (double)(c->minay);
693 max = (double)(c->maxax) / (double)(c->maxay);
695 if(max > 0 && min > 0 && ratio > 0) {
697 dy = (dx * min + dy) / (min * min + 1);
699 w = (int)dx + c->basew;
700 h = (int)dy + c->baseh;
702 else if(ratio > max) {
703 dy = (dx * min + dy) / (max * max + 1);
705 w = (int)dx + c->basew;
706 h = (int)dy + c->baseh;
710 if(c->minw && w < c->minw)
712 if(c->minh && h < c->minh)
714 if(c->maxw && w > c->maxw)
716 if(c->maxh && h > c->maxh)
719 w -= (w - c->basew) % c->incw;
721 h -= (h - c->baseh) % c->inch;
725 /* offscreen appearance fixes */
727 x = sw - w - 2 * c->border;
729 y = sh - h - 2 * c->border;
730 if(x + w + 2 * c->border < sx)
732 if(y + h + 2 * c->border < sy)
734 if(c->x != x || c->y != y || c->w != w || c->h != h) {
738 c->h = wc.height = h;
739 wc.border_width = c->border;
740 XConfigureWindow(dpy, c->win, CWX | CWY | CWWidth | CWHeight | CWBorderWidth, &wc);
750 XMoveWindow(dpy, c->win, c->x, c->y);
755 unmanage(Client *c) {
758 wc.border_width = c->oldborder;
759 /* The server grab construct avoids race conditions. */
761 XSetErrorHandler(xerrordummy);
762 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
767 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
768 setclientstate(c, WithdrawnState);
772 XSetErrorHandler(xerror);
778 updatesizehints(Client *c) {
782 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
784 c->flags = size.flags;
785 if(c->flags & PBaseSize) {
786 c->basew = size.base_width;
787 c->baseh = size.base_height;
789 else if(c->flags & PMinSize) {
790 c->basew = size.min_width;
791 c->baseh = size.min_height;
794 c->basew = c->baseh = 0;
795 if(c->flags & PResizeInc) {
796 c->incw = size.width_inc;
797 c->inch = size.height_inc;
800 c->incw = c->inch = 0;
801 if(c->flags & PMaxSize) {
802 c->maxw = size.max_width;
803 c->maxh = size.max_height;
806 c->maxw = c->maxh = 0;
807 if(c->flags & PMinSize) {
808 c->minw = size.min_width;
809 c->minh = size.min_height;
811 else if(c->flags & PBaseSize) {
812 c->minw = size.base_width;
813 c->minh = size.base_height;
816 c->minw = c->minh = 0;
817 if(c->flags & PAspect) {
818 c->minax = size.min_aspect.x;
819 c->maxax = size.max_aspect.x;
820 c->minay = size.min_aspect.y;
821 c->maxay = size.max_aspect.y;
824 c->minax = c->maxax = c->minay = c->maxay = 0;
825 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
826 && c->maxw == c->minw && c->maxh == c->minh);
830 updatetitle(Client *c) {
831 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
832 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
836 getclient(Window w) {
839 for(c = clients; c && c->win != w; c = c->next);
844 movemouse(Client *c) {
845 int x1, y1, ocx, ocy, di, nx, ny;
852 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
853 None, cursor[CurMove], CurrentTime) != GrabSuccess)
856 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
858 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask, &ev);
861 XUngrabPointer(dpy, CurrentTime);
863 case ConfigureRequest:
866 handler[ev.type](&ev);
870 nx = ocx + (ev.xmotion.x - x1);
871 ny = ocy + (ev.xmotion.y - y1);
872 if(abs(wax + nx) < SNAP)
874 else if(abs((wax + waw) - (nx + c->w + 2 * c->border)) < SNAP)
875 nx = wax + waw - c->w - 2 * c->border;
876 if(abs(way - ny) < SNAP)
878 else if(abs((way + wah) - (ny + c->h + 2 * c->border)) < SNAP)
879 ny = way + wah - c->h - 2 * c->border;
880 resize(c, nx, ny, c->w, c->h, False);
887 resizemouse(Client *c) {
894 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
895 None, cursor[CurResize], CurrentTime) != GrabSuccess)
898 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
900 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask , &ev);
903 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
904 c->w + c->border - 1, c->h + c->border - 1);
905 XUngrabPointer(dpy, CurrentTime);
906 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
908 case ConfigureRequest:
911 handler[ev.type](&ev);
915 if((nw = ev.xmotion.x - ocx - 2 * c->border + 1) <= 0)
917 if((nh = ev.xmotion.y - ocy - 2 * c->border + 1) <= 0)
919 resize(c, c->x, c->y, nw, nh, True);
926 buttonpress(XEvent *e) {
929 XButtonPressedEvent *ev = &e->xbutton;
931 if(barwin == ev->window) {
933 for(i = 0; i < ntags; i++) {
936 if(ev->button == Button1) {
937 if(ev->state & MODKEY)
942 else if(ev->button == Button3) {
943 if(ev->state & MODKEY)
951 if((ev->x < x + blw) && ev->button == Button1)
954 else if((c = getclient(ev->window))) {
956 if(CLEANMASK(ev->state) != MODKEY)
958 if(ev->button == Button1 && (isfloating() || c->isfloating)) {
962 else if(ev->button == Button2)
964 else if(ev->button == Button3
965 && (isfloating() || c->isfloating) && !c->isfixed)
974 configurerequest(XEvent *e) {
976 XConfigureRequestEvent *ev = &e->xconfigurerequest;
979 if((c = getclient(ev->window))) {
981 if(ev->value_mask & CWBorderWidth)
982 c->border = ev->border_width;
983 if(c->isfixed || c->isfloating || isfloating()) {
984 if(ev->value_mask & CWX)
986 if(ev->value_mask & CWY)
988 if(ev->value_mask & CWWidth)
990 if(ev->value_mask & CWHeight)
992 if((c->x + c->w) > sw && c->isfloating)
993 c->x = sw / 2 - c->w / 2; /* center in x direction */
994 if((c->y + c->h) > sh && c->isfloating)
995 c->y = sh / 2 - c->h / 2; /* center in y direction */
996 if((ev->value_mask & (CWX | CWY))
997 && !(ev->value_mask & (CWWidth | CWHeight)))
1000 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
1008 wc.width = ev->width;
1009 wc.height = ev->height;
1010 wc.border_width = ev->border_width;
1011 wc.sibling = ev->above;
1012 wc.stack_mode = ev->detail;
1013 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
1019 configurenotify(XEvent *e) {
1020 XConfigureEvent *ev = &e->xconfigure;
1022 if (ev->window == root && (ev->width != sw || ev->height != sh)) {
1025 XFreePixmap(dpy, dc.drawable);
1026 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
1027 XResizeWindow(dpy, barwin, sw, bh);
1034 destroynotify(XEvent *e) {
1036 XDestroyWindowEvent *ev = &e->xdestroywindow;
1038 if((c = getclient(ev->window)))
1043 enternotify(XEvent *e) {
1045 XCrossingEvent *ev = &e->xcrossing;
1047 if(ev->mode != NotifyNormal || ev->detail == NotifyInferior)
1049 if((c = getclient(ev->window)))
1051 else if(ev->window == root) {
1059 XExposeEvent *ev = &e->xexpose;
1061 if(ev->count == 0) {
1062 if(barwin == ev->window)
1068 keypress(XEvent *e) {
1070 unsigned int len = sizeof keys / sizeof keys[0];
1076 if(!e) { /* grabkeys */
1077 XUngrabKey(dpy, AnyKey, AnyModifier, root);
1078 for(i = 0; i < len; i++) {
1079 code = XKeysymToKeycode(dpy, keys[i].keysym);
1080 XGrabKey(dpy, code, keys[i].mod, root, True,
1081 GrabModeAsync, GrabModeAsync);
1082 XGrabKey(dpy, code, keys[i].mod | LockMask, root, True,
1083 GrabModeAsync, GrabModeAsync);
1084 XGrabKey(dpy, code, keys[i].mod | numlockmask, root, True,
1085 GrabModeAsync, GrabModeAsync);
1086 XGrabKey(dpy, code, keys[i].mod | numlockmask | LockMask, root, True,
1087 GrabModeAsync, GrabModeAsync);
1092 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
1093 for(i = 0; i < len; i++)
1094 if(keysym == keys[i].keysym
1095 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
1098 keys[i].func(keys[i].arg);
1103 leavenotify(XEvent *e) {
1104 XCrossingEvent *ev = &e->xcrossing;
1106 if((ev->window == root) && !ev->same_screen) {
1113 mappingnotify(XEvent *e) {
1114 XMappingEvent *ev = &e->xmapping;
1116 XRefreshKeyboardMapping(ev);
1117 if(ev->request == MappingKeyboard)
1122 maprequest(XEvent *e) {
1123 static XWindowAttributes wa;
1124 XMapRequestEvent *ev = &e->xmaprequest;
1126 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1128 if(wa.override_redirect)
1130 if(!getclient(ev->window))
1131 manage(ev->window, &wa);
1135 propertynotify(XEvent *e) {
1138 XPropertyEvent *ev = &e->xproperty;
1140 if(ev->state == PropertyDelete)
1141 return; /* ignore */
1142 if((c = getclient(ev->window))) {
1145 case XA_WM_TRANSIENT_FOR:
1146 XGetTransientForHint(dpy, c->win, &trans);
1147 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1150 case XA_WM_NORMAL_HINTS:
1154 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1163 unmapnotify(XEvent *e) {
1165 XUnmapEvent *ev = &e->xunmap;
1167 if((c = getclient(ev->window)))
1172 idxoftag(const char *tag) {
1175 for(i = 0; i < ntags; i++)
1182 floating(void) { /* default floating layout */
1185 for(c = clients; c; c = c->next)
1187 resize(c, c->x, c->y, c->w, c->h, True);
1191 applyrules(Client *c) {
1192 static char buf[512];
1195 Bool matched = False;
1196 XClassHint ch = { 0 };
1199 XGetClassHint(dpy, c->win, &ch);
1200 snprintf(buf, sizeof buf, "%s:%s:%s",
1201 ch.res_class ? ch.res_class : "",
1202 ch.res_name ? ch.res_name : "", c->name);
1203 for(i = 0; i < nrules; i++)
1204 if(regs[i].propregex && !regexec(regs[i].propregex, buf, 1, &tmp, 0)) {
1205 c->isfloating = rules[i].isfloating;
1206 for(j = 0; regs[i].tagregex && j < ntags; j++) {
1207 if(!regexec(regs[i].tagregex, tags[j], 1, &tmp, 0)) {
1214 XFree(ch.res_class);
1218 for(i = 0; i < ntags; i++)
1219 c->tags[i] = seltags[i];
1229 nrules = sizeof rules / sizeof rules[0];
1230 regs = emallocz(nrules * sizeof(Regs));
1231 for(i = 0; i < nrules; i++) {
1233 reg = emallocz(sizeof(regex_t));
1234 if(regcomp(reg, rules[i].prop, REG_EXTENDED))
1237 regs[i].propregex = reg;
1240 reg = emallocz(sizeof(regex_t));
1241 if(regcomp(reg, rules[i].tags, REG_EXTENDED))
1244 regs[i].tagregex = reg;
1250 focusnext(const char *arg) {
1255 for(c = sel->next; c && !isvisible(c); c = c->next);
1257 for(c = clients; c && !isvisible(c); c = c->next);
1265 focusprev(const char *arg) {
1270 for(c = sel->prev; c && !isvisible(c); c = c->prev);
1272 for(c = clients; c && c->next; c = c->next);
1273 for(; c && !isvisible(c); c = c->prev);
1285 nlayouts = sizeof layouts / sizeof layouts[0];
1286 for(blw = i = 0; i < nlayouts; i++) {
1287 w = textw(layouts[i].symbol);
1295 return layouts[ltidx].arrange == floating;
1299 isvisible(Client *c) {
1302 for(i = 0; i < ntags; i++)
1303 if(c->tags[i] && seltags[i])
1317 if(sel->isfloating || isfloating())
1318 XRaiseWindow(dpy, sel->win);
1320 wc.stack_mode = Below;
1321 wc.sibling = barwin;
1322 if(!sel->isfloating) {
1323 XConfigureWindow(dpy, sel->win, CWSibling | CWStackMode, &wc);
1324 wc.sibling = sel->win;
1326 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
1329 XConfigureWindow(dpy, c->win, CWSibling | CWStackMode, &wc);
1330 wc.sibling = c->win;
1334 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1338 setlayout(const char *arg) {
1342 if(++ltidx == nlayouts)
1346 for(i = 0; i < nlayouts; i++)
1347 if(!strcmp(arg, layouts[i].symbol))
1360 tag(const char *arg) {
1365 for(i = 0; i < ntags; i++)
1366 sel->tags[i] = arg == NULL;
1368 if(i >= 0 && i < ntags)
1369 sel->tags[i] = True;
1374 togglefloating(const char *arg) {
1377 sel->isfloating = !sel->isfloating;
1379 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1384 togglemax(const char *arg) {
1387 if(!sel || (!isfloating() && !sel->isfloating) || sel->isfixed)
1389 if((sel->ismax = !sel->ismax)) {
1394 resize(sel, wax, way, waw - 2 * sel->border, wah - 2 * sel->border, True);
1397 resize(sel, sel->rx, sel->ry, sel->rw, sel->rh, True);
1399 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1403 toggletag(const char *arg) {
1409 sel->tags[i] = !sel->tags[i];
1410 for(j = 0; j < ntags && !sel->tags[j]; j++);
1412 sel->tags[i] = True;
1417 toggleview(const char *arg) {
1421 seltags[i] = !seltags[i];
1422 for(j = 0; j < ntags && !seltags[j]; j++);
1424 seltags[i] = True; /* cannot toggle last view */
1429 view(const char *arg) {
1432 for(i = 0; i < ntags; i++)
1433 seltags[i] = arg == NULL;
1435 if(i >= 0 && i < ntags)
1442 close(STDIN_FILENO);
1448 XFreeFontSet(dpy, dc.font.set);
1450 XFreeFont(dpy, dc.font.xfont);
1451 XUngrabKey(dpy, AnyKey, AnyModifier, root);
1452 XFreePixmap(dpy, dc.drawable);
1453 XFreeGC(dpy, dc.gc);
1454 XDestroyWindow(dpy, barwin);
1455 XFreeCursor(dpy, cursor[CurNormal]);
1456 XFreeCursor(dpy, cursor[CurResize]);
1457 XFreeCursor(dpy, cursor[CurMove]);
1458 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
1464 getstate(Window w) {
1467 unsigned char *p = NULL;
1468 unsigned long n, extra;
1471 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
1472 &real, &format, &n, &extra, (unsigned char **)&p);
1473 if(status != Success)
1483 unsigned int i, num;
1484 Window *wins, d1, d2;
1485 XWindowAttributes wa;
1488 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1489 for(i = 0; i < num; i++) {
1490 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1491 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1493 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1494 manage(wins[i], &wa);
1496 for(i = 0; i < num; i++) { /* now the transients */
1497 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1499 if(XGetTransientForHint(dpy, wins[i], &d1)
1500 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1501 manage(wins[i], &wa);
1513 XModifierKeymap *modmap;
1514 XSetWindowAttributes wa;
1517 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1518 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1519 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1520 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1521 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1522 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1523 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1524 PropModeReplace, (unsigned char *) netatom, NetLast);
1526 cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1527 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1528 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1529 /* init modifier map */
1530 modmap = XGetModifierMapping(dpy);
1531 for (i = 0; i < 8; i++)
1532 for (j = 0; j < modmap->max_keypermod; j++) {
1533 if(modmap->modifiermap[i * modmap->max_keypermod + j]
1534 == XKeysymToKeycode(dpy, XK_Num_Lock))
1535 numlockmask = (1 << i);
1537 XFreeModifiermap(modmap);
1538 /* select for events */
1539 wa.event_mask = SubstructureRedirectMask | SubstructureNotifyMask
1540 | EnterWindowMask | LeaveWindowMask | StructureNotifyMask;
1541 wa.cursor = cursor[CurNormal];
1542 XChangeWindowAttributes(dpy, root, CWEventMask | CWCursor, &wa);
1543 XSelectInput(dpy, root, wa.event_mask);
1544 keypress(NULL); /* grabkeys */
1546 for(ntags = 0; tags[ntags]; ntags++);
1547 seltags = emallocz(sizeof(Bool) * ntags);
1551 sw = DisplayWidth(dpy, screen);
1552 sh = DisplayHeight(dpy, screen);
1556 /* multihead support */
1557 selscreen = XQueryPointer(dpy, root, &w, &w, &i, &i, &i, &i, &mask);
1561 * Startup Error handler to check if another window manager
1562 * is already running.
1565 xerrorstart(Display *dsply, XErrorEvent *ee) {
1571 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
1576 if(!text || size == 0)
1579 XGetTextProperty(dpy, w, &name, atom);
1582 if(name.encoding == XA_STRING)
1583 strncpy(text, (char *)name.value, size - 1);
1585 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
1588 strncpy(text, *list, size - 1);
1589 XFreeStringList(list);
1592 text[size - 1] = '\0';
1598 quit(const char *arg) {
1599 readin = running = False;
1602 /* There's no way to check accesses to destroyed windows, thus those cases are
1603 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1604 * default error handler, which may call exit.
1607 xerror(Display *dpy, XErrorEvent *ee) {
1608 if(ee->error_code == BadWindow
1609 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1610 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1611 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1612 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1613 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1614 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1615 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1617 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1618 ee->request_code, ee->error_code);
1619 return xerrorxlib(dpy, ee); /* may call exit */
1626 for(c = clients; c; c = c->next)
1631 layouts[ltidx].arrange();
1647 c->prev->next = c->next;
1649 c->next->prev = c->prev;
1652 c->next = c->prev = NULL;
1657 if((!c && selscreen) || (c && !isvisible(c)))
1658 for(c = stack; c && !isvisible(c); c = c->snext);
1659 if(sel && sel != c) {
1660 grabbuttons(sel, False);
1661 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
1666 grabbuttons(c, True);
1673 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
1674 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
1677 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
1681 isarrange(void (*func)())
1683 return func == layouts[ltidx].arrange;
1687 nexttiled(Client *c) {
1688 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1693 setmwfact(const char *arg) {
1696 if(!isarrange(tile))
1698 /* arg handling, manipulate mwfact */
1701 else if(1 == sscanf(arg, "%lf", &delta)) {
1702 if(arg[0] != '+' && arg[0] != '-')
1708 else if(mwfact > 0.9)
1716 unsigned int i, n, nx, ny, nw, nh, mw, th;
1719 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next))
1723 mw = (n == 1) ? waw : mwfact * waw;
1724 th = (n > 1) ? wah / (n - 1) : 0;
1725 if(n > 1 && th < bh)
1730 for(i = 0, c = nexttiled(clients); c; c = nexttiled(c->next), i++) {
1732 if(i == 0) { /* master */
1733 nw = mw - 2 * c->border;
1734 nh = wah - 2 * c->border;
1736 else { /* tile window */
1741 nw = waw - mw - 2 * c->border;
1742 if(i + 1 == n) /* remainder */
1743 nh = (way + wah) - ny - 2 * c->border;
1745 nh = th - 2 * c->border;
1747 resize(c, nx, ny, nw, nh, RESIZEHINTS);
1748 if(n > 1 && th != wah)
1749 ny += nh + 2 * c->border;
1754 zoom(const char *arg) {
1757 if(!sel || !isarrange(tile) || sel->isfloating)
1759 if((c = sel) == nexttiled(clients))
1760 if(!(c = nexttiled(c->next)))
1769 main(int argc, char *argv[]) {
1775 if(argc == 2 && !strcmp("-v", argv[1]))
1776 eprint("dwm-"VERSION", © 2006-2007 A. R. Garbe, S. van Dijk, J. Salmi, P. Hruby, S. Nagy\n");
1778 eprint("usage: dwm [-v]\n");
1779 setlocale(LC_CTYPE, "");
1780 if(!(dpy = XOpenDisplay(0)))
1781 eprint("dwm: cannot open display\n");
1782 xfd = ConnectionNumber(dpy);
1783 screen = DefaultScreen(dpy);
1784 root = RootWindow(dpy, screen);
1786 XSetErrorHandler(xerrorstart);
1787 /* this causes an error if some other window manager is running */
1788 XSelectInput(dpy, root, SubstructureRedirectMask);
1791 eprint("dwm: another window manager is already running\n");
1794 XSetErrorHandler(NULL);
1795 xerrorxlib = XSetErrorHandler(xerror);
1801 /* main event loop, also reads status text from stdin */
1807 FD_SET(STDIN_FILENO, &rd);
1809 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1812 eprint("select failed\n");
1814 if(FD_ISSET(STDIN_FILENO, &rd)) {
1815 switch(r = read(STDIN_FILENO, stext, sizeof stext - 1)) {
1817 strncpy(stext, strerror(errno), sizeof stext - 1);
1818 stext[sizeof stext - 1] = '\0';
1822 strncpy(stext, "EOF", 4);
1826 for(stext[r] = '\0', p = stext + strlen(stext) - 1; p >= stext && *p == '\n'; *p-- = '\0');
1827 for(; p >= stext && *p != '\n'; --p);
1829 strncpy(stext, p + 1, sizeof stext);
1833 while(XPending(dpy)) {
1834 XNextEvent(dpy, &ev);
1835 if(handler[ev.type])
1836 (handler[ev.type])(&ev); /* call handler */