1 /* See LICENSE file for copyright and license details.
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.
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.
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.
22 * Keys and tagging rules are organized as arrays and defined in config.h.
24 * To understand everything else, start reading main().
33 #include <sys/select.h>
34 #include <sys/types.h>
36 #include <X11/cursorfont.h>
37 #include <X11/keysym.h>
38 #include <X11/Xatom.h>
40 #include <X11/Xproto.h>
41 #include <X11/Xutil.h>
43 #include <X11/extensions/Xinerama.h>
47 #define MAX(a, b) ((a) > (b) ? (a) : (b))
48 #define MIN(a, b) ((a) < (b) ? (a) : (b))
49 #define BUTTONMASK (ButtonPressMask|ButtonReleaseMask)
50 #define CLEANMASK(mask) (mask & ~(numlockmask|LockMask))
51 #define LENGTH(x) (sizeof x / sizeof x[0])
53 #define MOUSEMASK (BUTTONMASK|PointerMotionMask)
54 #define TAGMASK ((int)((1LL << LENGTH(tags)) - 1))
57 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
58 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
59 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
60 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
63 typedef unsigned int uint;
64 typedef unsigned long ulong;
65 typedef struct Client Client;
69 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
70 int minax, maxax, minay, maxay;
73 Bool isbanned, isfixed, isfloating, isurgent;
94 } DC; /* draw context */
99 void (*func)(const void *arg);
105 void (*arrange)(void);
106 void (*updategeom)(void);
111 const char *instance;
117 /* function declarations */
118 void applyrules(Client *c);
120 void attach(Client *c);
121 void attachstack(Client *c);
123 void buttonpress(XEvent *e);
124 void checkotherwm(void);
126 void configure(Client *c);
127 void configurenotify(XEvent *e);
128 void configurerequest(XEvent *e);
129 void destroynotify(XEvent *e);
130 void detach(Client *c);
131 void detachstack(Client *c);
133 void drawsquare(Bool filled, Bool empty, Bool invert, ulong col[ColLast]);
134 void drawtext(const char *text, ulong col[ColLast], Bool invert);
135 void *emallocz(uint size);
136 void enternotify(XEvent *e);
137 void eprint(const char *errstr, ...);
138 void expose(XEvent *e);
139 void focus(Client *c);
140 void focusin(XEvent *e);
141 void focusnext(const void *arg);
142 void focusprev(const void *arg);
143 Client *getclient(Window w);
144 ulong getcolor(const char *colstr);
145 long getstate(Window w);
146 Bool gettextprop(Window w, Atom atom, char *text, uint size);
147 void grabbuttons(Client *c, Bool focused);
149 void initfont(const char *fontstr);
150 Bool isoccupied(uint t);
151 Bool isprotodel(Client *c);
152 Bool isurgent(uint t);
153 Bool isvisible(Client *c);
154 void keypress(XEvent *e);
155 void killclient(const void *arg);
156 void manage(Window w, XWindowAttributes *wa);
157 void mappingnotify(XEvent *e);
158 void maprequest(XEvent *e);
159 void movemouse(Client *c);
160 Client *nexttiled(Client *c);
161 void propertynotify(XEvent *e);
162 void quit(const void *arg);
163 void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
164 void resizemouse(Client *c);
168 void setclientstate(Client *c, long state);
169 void setmfact(const void *arg);
171 void spawn(const void *arg);
172 void tag(const void *arg);
173 uint textnw(const char *text, uint len);
174 uint textw(const char *text);
176 void tileresize(Client *c, int x, int y, int w, int h);
177 void togglebar(const void *arg);
178 void togglefloating(const void *arg);
179 void togglelayout(const void *arg);
180 void toggletag(const void *arg);
181 void toggleview(const void *arg);
182 void unban(Client *c);
183 void unmanage(Client *c);
184 void unmapnotify(XEvent *e);
185 void updatebar(void);
186 void updategeom(void);
187 void updatesizehints(Client *c);
188 void updatetilegeom(void);
189 void updatetitle(Client *c);
190 void updatewmhints(Client *c);
191 void view(const void *arg);
192 void viewprevtag(const void *arg);
193 int xerror(Display *dpy, XErrorEvent *ee);
194 int xerrordummy(Display *dpy, XErrorEvent *ee);
195 int xerrorstart(Display *dpy, XErrorEvent *ee);
196 void zoom(const void *arg);
200 int screen, sx, sy, sw, sh;
201 int bx, by, bw, bh, blw, wx, wy, ww, wh;
202 int mx, my, mw, mh, tx, ty, tw, th;
204 int (*xerrorxlib)(Display *, XErrorEvent *);
205 uint numlockmask = 0;
206 void (*handler[LASTEvent]) (XEvent *) = {
207 [ButtonPress] = buttonpress,
208 [ConfigureRequest] = configurerequest,
209 [ConfigureNotify] = configurenotify,
210 [DestroyNotify] = destroynotify,
211 [EnterNotify] = enternotify,
214 [KeyPress] = keypress,
215 [MappingNotify] = mappingnotify,
216 [MapRequest] = maprequest,
217 [PropertyNotify] = propertynotify,
218 [UnmapNotify] = unmapnotify
220 Atom wmatom[WMLast], netatom[NetLast];
221 Bool otherwm, readin;
223 uint tagset[] = {1, 1}; /* after start, first tag is selected */
224 Client *clients = NULL;
226 Client *stack = NULL;
227 Cursor cursor[CurLast];
231 Layout *lt = layouts;
234 /* configuration, allows nested code to access above variables */
237 /* check if all tags will fit into a uint bitarray. */
238 static char tags_is_a_sign_that_your_IQ[sizeof(int) * 8 < LENGTH(tags) ? -1 : 1];
240 /* function implementations */
243 applyrules(Client *c) {
246 XClassHint ch = { 0 };
249 XGetClassHint(dpy, c->win, &ch);
250 for(i = 0; i < LENGTH(rules); i++) {
252 if((!r->title || strstr(c->name, r->title))
253 && (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
254 && (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
255 c->isfloating = r->isfloating;
256 c->tags |= r->tags & TAGMASK;
264 c->tags = tagset[seltags];
271 for(c = clients; c; c = c->next)
274 if(!lt->arrange || c->isfloating)
275 resize(c, c->x, c->y, c->w, c->h, True);
295 attachstack(Client *c) {
304 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
309 buttonpress(XEvent *e) {
312 XButtonPressedEvent *ev = &e->xbutton;
314 if(ev->window == barwin) {
316 for(i = 0; i < LENGTH(tags); i++) {
320 if(ev->button == Button1) {
321 if(ev->state & MODKEY)
326 else if(ev->button == Button3) {
327 if(ev->state & MODKEY)
335 if((ev->x < x + blw) && ev->button == Button1)
338 else if((c = getclient(ev->window))) {
340 if(CLEANMASK(ev->state) != MODKEY)
342 if(ev->button == Button1) {
346 else if(ev->button == Button2)
347 togglefloating(NULL);
348 else if(ev->button == Button3 && !c->isfixed) {
358 XSetErrorHandler(xerrorstart);
360 /* this causes an error if some other window manager is running */
361 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
364 eprint("dwm: another window manager is already running\n");
366 XSetErrorHandler(NULL);
367 xerrorxlib = XSetErrorHandler(xerror);
379 XFreeFontSet(dpy, dc.font.set);
381 XFreeFont(dpy, dc.font.xfont);
382 XUngrabKey(dpy, AnyKey, AnyModifier, root);
383 XFreePixmap(dpy, dc.drawable);
385 XFreeCursor(dpy, cursor[CurNormal]);
386 XFreeCursor(dpy, cursor[CurResize]);
387 XFreeCursor(dpy, cursor[CurMove]);
388 XDestroyWindow(dpy, barwin);
390 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
394 configure(Client *c) {
397 ce.type = ConfigureNotify;
405 ce.border_width = c->bw;
407 ce.override_redirect = False;
408 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
412 configurenotify(XEvent *e) {
413 XConfigureEvent *ev = &e->xconfigure;
415 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
425 configurerequest(XEvent *e) {
427 XConfigureRequestEvent *ev = &e->xconfigurerequest;
430 if((c = getclient(ev->window))) {
431 if(ev->value_mask & CWBorderWidth)
432 c->bw = ev->border_width;
433 if(c->isfixed || c->isfloating || !lt->arrange) {
434 if(ev->value_mask & CWX)
436 if(ev->value_mask & CWY)
438 if(ev->value_mask & CWWidth)
440 if(ev->value_mask & CWHeight)
442 if((c->x - sx + c->w) > sw && c->isfloating)
443 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
444 if((c->y - sy + c->h) > sh && c->isfloating)
445 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
446 if((ev->value_mask & (CWX|CWY))
447 && !(ev->value_mask & (CWWidth|CWHeight)))
450 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
458 wc.width = ev->width;
459 wc.height = ev->height;
460 wc.border_width = ev->border_width;
461 wc.sibling = ev->above;
462 wc.stack_mode = ev->detail;
463 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
469 destroynotify(XEvent *e) {
471 XDestroyWindowEvent *ev = &e->xdestroywindow;
473 if((c = getclient(ev->window)))
480 c->prev->next = c->next;
482 c->next->prev = c->prev;
485 c->next = c->prev = NULL;
489 detachstack(Client *c) {
492 for(tc = &stack; *tc && *tc != c; tc = &(*tc)->snext);
502 for(c = stack; c && !isvisible(c); c = c->snext);
503 for(i = 0; i < LENGTH(tags); i++) {
504 dc.w = textw(tags[i]);
505 if(tagset[seltags] & 1 << i) {
506 drawtext(tags[i], dc.sel, isurgent(i));
507 drawsquare(c && c->tags & 1 << i, isoccupied(i), isurgent(i), dc.sel);
510 drawtext(tags[i], dc.norm, isurgent(i));
511 drawsquare(c && c->tags & 1 << i, isoccupied(i), isurgent(i), dc.norm);
517 drawtext(lt->symbol, dc.norm, False);
528 drawtext(stext, dc.norm, False);
529 if((dc.w = dc.x - x) > bh) {
532 drawtext(c->name, dc.sel, False);
533 drawsquare(False, c->isfloating, False, dc.sel);
536 drawtext(NULL, dc.norm, False);
538 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, bw, bh, 0, 0);
543 drawsquare(Bool filled, Bool empty, Bool invert, ulong col[ColLast]) {
546 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
548 gcv.foreground = col[invert ? ColBG : ColFG];
549 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
550 x = (dc.font.ascent + dc.font.descent + 2) / 4;
554 r.width = r.height = x + 1;
555 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
558 r.width = r.height = x;
559 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
564 drawtext(const char *text, ulong col[ColLast], Bool invert) {
567 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
570 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
571 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
575 len = MIN(olen, sizeof buf);
576 memcpy(buf, text, len);
578 h = dc.font.ascent + dc.font.descent;
579 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
581 /* shorten text if necessary */
582 for(; len && (w = textnw(buf, len)) > dc.w - h; len--);
593 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
595 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
597 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
601 emallocz(uint size) {
602 void *res = calloc(1, size);
605 eprint("fatal: could not malloc() %u bytes\n", size);
610 enternotify(XEvent *e) {
612 XCrossingEvent *ev = &e->xcrossing;
614 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
616 if((c = getclient(ev->window)))
623 eprint(const char *errstr, ...) {
626 va_start(ap, errstr);
627 vfprintf(stderr, errstr, ap);
634 XExposeEvent *ev = &e->xexpose;
636 if(ev->count == 0 && (ev->window == barwin))
642 if(!c || (c && !isvisible(c)))
643 for(c = stack; c && !isvisible(c); c = c->snext);
644 if(sel && sel != c) {
645 grabbuttons(sel, False);
646 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
651 grabbuttons(c, True);
655 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
656 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
659 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
664 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
665 XFocusChangeEvent *ev = &e->xfocus;
667 if(sel && ev->window != sel->win)
668 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
672 focusnext(const void *arg) {
677 for(c = sel->next; c && !isvisible(c); c = c->next);
679 for(c = clients; c && !isvisible(c); c = c->next);
687 focusprev(const void *arg) {
692 for(c = sel->prev; c && !isvisible(c); c = c->prev);
694 for(c = clients; c && c->next; c = c->next);
695 for(; c && !isvisible(c); c = c->prev);
704 getclient(Window w) {
707 for(c = clients; c && c->win != w; c = c->next);
712 getcolor(const char *colstr) {
713 Colormap cmap = DefaultColormap(dpy, screen);
716 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
717 eprint("error, cannot allocate color '%s'\n", colstr);
725 unsigned char *p = NULL;
729 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
730 &real, &format, &n, &extra, (unsigned char **)&p);
731 if(status != Success)
740 gettextprop(Window w, Atom atom, char *text, uint size) {
745 if(!text || size == 0)
748 XGetTextProperty(dpy, w, &name, atom);
751 if(name.encoding == XA_STRING)
752 strncpy(text, (char *)name.value, size - 1);
754 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
756 strncpy(text, *list, size - 1);
757 XFreeStringList(list);
760 text[size - 1] = '\0';
766 grabbuttons(Client *c, Bool focused) {
768 uint buttons[] = { Button1, Button2, Button3 };
769 uint modifiers[] = { MODKEY, MODKEY|LockMask, MODKEY|numlockmask,
770 MODKEY|numlockmask|LockMask} ;
772 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
774 for(i = 0; i < LENGTH(buttons); i++)
775 for(j = 0; j < LENGTH(modifiers); j++)
776 XGrabButton(dpy, buttons[i], modifiers[j], c->win, False,
777 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
779 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
780 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
787 XModifierKeymap *modmap;
789 /* init modifier map */
790 modmap = XGetModifierMapping(dpy);
791 for(i = 0; i < 8; i++)
792 for(j = 0; j < modmap->max_keypermod; j++) {
793 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
794 numlockmask = (1 << i);
796 XFreeModifiermap(modmap);
798 XUngrabKey(dpy, AnyKey, AnyModifier, root);
799 for(i = 0; i < LENGTH(keys); i++) {
800 code = XKeysymToKeycode(dpy, keys[i].keysym);
801 XGrabKey(dpy, code, keys[i].mod, root, True,
802 GrabModeAsync, GrabModeAsync);
803 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
804 GrabModeAsync, GrabModeAsync);
805 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
806 GrabModeAsync, GrabModeAsync);
807 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
808 GrabModeAsync, GrabModeAsync);
813 initfont(const char *fontstr) {
814 char *def, **missing;
819 XFreeFontSet(dpy, dc.font.set);
820 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
823 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
824 XFreeStringList(missing);
827 XFontSetExtents *font_extents;
828 XFontStruct **xfonts;
830 dc.font.ascent = dc.font.descent = 0;
831 font_extents = XExtentsOfFontSet(dc.font.set);
832 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
833 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
834 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
835 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
841 XFreeFont(dpy, dc.font.xfont);
842 dc.font.xfont = NULL;
843 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
844 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
845 eprint("error, cannot load font: '%s'\n", fontstr);
846 dc.font.ascent = dc.font.xfont->ascent;
847 dc.font.descent = dc.font.xfont->descent;
849 dc.font.height = dc.font.ascent + dc.font.descent;
856 for(c = clients; c; c = c->next)
863 isprotodel(Client *c) {
868 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
869 for(i = 0; !ret && i < n; i++)
870 if(protocols[i] == wmatom[WMDelete])
881 for(c = clients; c; c = c->next)
882 if(c->isurgent && c->tags & 1 << t)
888 isvisible(Client *c) {
889 return c->tags & tagset[seltags];
893 keypress(XEvent *e) {
899 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
900 for(i = 0; i < LENGTH(keys); i++)
901 if(keysym == keys[i].keysym
902 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
905 keys[i].func(keys[i].arg);
910 killclient(const void *arg) {
915 if(isprotodel(sel)) {
916 ev.type = ClientMessage;
917 ev.xclient.window = sel->win;
918 ev.xclient.message_type = wmatom[WMProtocols];
919 ev.xclient.format = 32;
920 ev.xclient.data.l[0] = wmatom[WMDelete];
921 ev.xclient.data.l[1] = CurrentTime;
922 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
925 XKillClient(dpy, sel->win);
929 manage(Window w, XWindowAttributes *wa) {
930 Client *c, *t = NULL;
935 c = emallocz(sizeof(Client));
943 c->oldbw = wa->border_width;
944 if(c->w == sw && c->h == sh) {
947 c->bw = wa->border_width;
950 if(c->x + c->w + 2 * c->bw > sx + sw)
951 c->x = sx + sw - c->w - 2 * c->bw;
952 if(c->y + c->h + 2 * c->bw > sy + sh)
953 c->y = sy + sh - c->h - 2 * c->bw;
954 c->x = MAX(c->x, sx);
955 c->y = MAX(c->y, by == 0 ? bh : sy);
959 wc.border_width = c->bw;
960 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
961 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
962 configure(c); /* propagates border_width, if size doesn't change */
964 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
965 grabbuttons(c, False);
967 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
968 for(t = clients; t && t->win != trans; t = t->next);
974 c->isfloating = (rettrans == Success) || c->isfixed;
977 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
979 XMapWindow(dpy, c->win);
980 setclientstate(c, NormalState);
985 mappingnotify(XEvent *e) {
986 XMappingEvent *ev = &e->xmapping;
988 XRefreshKeyboardMapping(ev);
989 if(ev->request == MappingKeyboard)
994 maprequest(XEvent *e) {
995 static XWindowAttributes wa;
996 XMapRequestEvent *ev = &e->xmaprequest;
998 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1000 if(wa.override_redirect)
1002 if(!getclient(ev->window))
1003 manage(ev->window, &wa);
1007 movemouse(Client *c) {
1008 int x1, y1, ocx, ocy, di, nx, ny;
1015 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1016 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1018 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1020 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1023 XUngrabPointer(dpy, CurrentTime);
1025 case ConfigureRequest:
1028 handler[ev.type](&ev);
1032 nx = ocx + (ev.xmotion.x - x1);
1033 ny = ocy + (ev.xmotion.y - y1);
1034 if(snap && nx >= wx && nx <= wx + ww
1035 && ny >= wy && ny <= wy + wh) {
1036 if(abs(wx - nx) < snap)
1038 else if(abs((wx + ww) - (nx + c->w + 2 * c->bw)) < snap)
1039 nx = wx + ww - c->w - 2 * c->bw;
1040 if(abs(wy - ny) < snap)
1042 else if(abs((wy + wh) - (ny + c->h + 2 * c->bw)) < snap)
1043 ny = wy + wh - c->h - 2 * c->bw;
1044 if(!c->isfloating && lt->arrange && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
1045 togglefloating(NULL);
1047 if(!lt->arrange || c->isfloating)
1048 resize(c, nx, ny, c->w, c->h, False);
1055 nexttiled(Client *c) {
1056 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1061 propertynotify(XEvent *e) {
1064 XPropertyEvent *ev = &e->xproperty;
1066 if(ev->state == PropertyDelete)
1067 return; /* ignore */
1068 if((c = getclient(ev->window))) {
1071 case XA_WM_TRANSIENT_FOR:
1072 XGetTransientForHint(dpy, c->win, &trans);
1073 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1076 case XA_WM_NORMAL_HINTS:
1084 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1093 quit(const void *arg) {
1094 readin = running = False;
1098 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1102 /* set minimum possible */
1106 /* temporarily remove base dimensions */
1110 /* adjust for aspect limits */
1111 if(c->minax != c->maxax && c->minay != c->maxay
1112 && c->minax > 0 && c->maxax > 0 && c->minay > 0 && c->maxay > 0) {
1113 if(w * c->maxay > h * c->maxax)
1114 w = h * c->maxax / c->maxay;
1115 else if(w * c->minay < h * c->minax)
1116 h = w * c->minay / c->minax;
1119 /* adjust for increment value */
1125 /* restore base dimensions */
1129 w = MAX(w, c->minw);
1130 h = MAX(h, c->minh);
1133 w = MIN(w, c->maxw);
1136 h = MIN(h, c->maxh);
1138 if(w <= 0 || h <= 0)
1141 x = sw - w - 2 * c->bw;
1143 y = sh - h - 2 * c->bw;
1144 if(x + w + 2 * c->bw < sx)
1146 if(y + h + 2 * c->bw < sy)
1148 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1151 c->w = wc.width = w;
1152 c->h = wc.height = h;
1153 wc.border_width = c->bw;
1154 XConfigureWindow(dpy, c->win,
1155 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1162 resizemouse(Client *c) {
1169 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1170 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1172 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1174 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1177 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1178 c->w + c->bw - 1, c->h + c->bw - 1);
1179 XUngrabPointer(dpy, CurrentTime);
1180 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1182 case ConfigureRequest:
1185 handler[ev.type](&ev);
1189 nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1190 nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1192 if(snap && nw >= wx && nw <= wx + ww
1193 && nh >= wy && nh <= wy + wh) {
1194 if(!c->isfloating && lt->arrange
1195 && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1196 togglefloating(NULL);
1198 if(!lt->arrange || c->isfloating)
1199 resize(c, c->x, c->y, nw, nh, True);
1214 if(sel->isfloating || !lt->arrange)
1215 XRaiseWindow(dpy, sel->win);
1217 wc.stack_mode = Below;
1218 wc.sibling = barwin;
1219 for(c = stack; c; c = c->snext)
1220 if(!c->isfloating && isvisible(c)) {
1221 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1222 wc.sibling = c->win;
1226 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1232 char sbuf[sizeof stext];
1238 /* main event loop, also reads status text from stdin */
1240 xfd = ConnectionNumber(dpy);
1243 len = sizeof stext - 1;
1244 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1248 FD_SET(STDIN_FILENO, &rd);
1250 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1253 eprint("select failed\n");
1255 if(FD_ISSET(STDIN_FILENO, &rd)) {
1256 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1258 strncpy(stext, strerror(errno), len);
1262 strncpy(stext, "EOF", 4);
1266 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1267 if(*p == '\n' || *p == '\0') {
1269 strncpy(stext, sbuf, len);
1270 p += r - 1; /* p is sbuf + offset + r - 1 */
1271 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1274 memmove(sbuf, p - r + 1, r);
1281 while(XPending(dpy)) {
1282 XNextEvent(dpy, &ev);
1283 if(handler[ev.type])
1284 (handler[ev.type])(&ev); /* call handler */
1292 Window *wins, d1, d2;
1293 XWindowAttributes wa;
1296 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1297 for(i = 0; i < num; i++) {
1298 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1299 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1301 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1302 manage(wins[i], &wa);
1304 for(i = 0; i < num; i++) { /* now the transients */
1305 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1307 if(XGetTransientForHint(dpy, wins[i], &d1)
1308 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1309 manage(wins[i], &wa);
1317 setclientstate(Client *c, long state) {
1318 long data[] = {state, None};
1320 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1321 PropModeReplace, (unsigned char *)data, 2);
1324 /* arg > 1.0 will set mfact absolutly */
1326 setmfact(const void *arg) {
1327 double d = *((double*) arg);
1329 if(!d || lt->arrange != tile)
1331 d = d < 1.0 ? d + mfact : d - 1.0;
1332 if(d < 0.1 || d > 0.9)
1342 XSetWindowAttributes wa;
1345 screen = DefaultScreen(dpy);
1346 root = RootWindow(dpy, screen);
1350 sw = DisplayWidth(dpy, screen);
1351 sh = DisplayHeight(dpy, screen);
1352 bh = dc.font.height + 2;
1356 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1357 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1358 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1359 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1360 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1361 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1364 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1365 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1366 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1368 /* init appearance */
1369 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1370 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1371 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1372 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1373 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1374 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1377 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1378 dc.gc = XCreateGC(dpy, root, 0, 0);
1379 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1381 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1384 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1385 w = textw(layouts[i].symbol);
1389 wa.override_redirect = 1;
1390 wa.background_pixmap = ParentRelative;
1391 wa.event_mask = ButtonPressMask|ExposureMask;
1393 barwin = XCreateWindow(dpy, root, bx, by, bw, bh, 0, DefaultDepth(dpy, screen),
1394 CopyFromParent, DefaultVisual(dpy, screen),
1395 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1396 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1397 XMapRaised(dpy, barwin);
1398 strcpy(stext, "dwm-"VERSION);
1401 /* EWMH support per view */
1402 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1403 PropModeReplace, (unsigned char *) netatom, NetLast);
1405 /* select for events */
1406 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1407 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1408 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1409 XSelectInput(dpy, root, wa.event_mask);
1417 spawn(const void *arg) {
1418 static char *shell = NULL;
1420 if(!shell && !(shell = getenv("SHELL")))
1422 /* The double-fork construct avoids zombie processes and keeps the code
1423 * clean from stupid signal handlers. */
1427 close(ConnectionNumber(dpy));
1429 execl(shell, shell, "-c", (char *)arg, (char *)NULL);
1430 fprintf(stderr, "dwm: execl '%s -c %s'", shell, (char *)arg);
1439 tag(const void *arg) {
1440 if(sel && *(int *)arg & TAGMASK) {
1441 sel->tags = *(int *)arg & TAGMASK;
1447 textnw(const char *text, uint len) {
1451 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1454 return XTextWidth(dc.font.xfont, text, len);
1458 textw(const char *text) {
1459 return textnw(text, strlen(text)) + dc.font.height;
1468 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next), n++);
1473 c = nexttiled(clients);
1476 tileresize(c, wx, wy, ww - 2 * c->bw, wh - 2 * c->bw);
1478 tileresize(c, mx, my, mw - 2 * c->bw, mh - 2 * c->bw);
1484 x = (tx > c->x + c->w) ? c->x + c->w + 2 * c->bw : tw;
1486 w = (tx > c->x + c->w) ? wx + ww - x : tw;
1491 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1492 if(i + 1 == n) /* remainder */
1493 tileresize(c, x, y, w - 2 * c->bw, (ty + th) - y - 2 * c->bw);
1495 tileresize(c, x, y, w - 2 * c->bw, h - 2 * c->bw);
1497 y = c->y + c->h + 2 * c->bw;
1502 tileresize(Client *c, int x, int y, int w, int h) {
1503 resize(c, x, y, w, h, resizehints);
1504 if(resizehints && ((c->h < bh) || (c->h > h) || (c->w < bh) || (c->w > w)))
1505 /* client doesn't accept size constraints */
1506 resize(c, x, y, w, h, False);
1510 togglebar(const void *arg) {
1518 togglefloating(const void *arg) {
1521 sel->isfloating = !sel->isfloating;
1523 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1528 togglelayout(const void *arg) {
1532 if(++lt == &layouts[LENGTH(layouts)])
1536 for(i = 0; i < LENGTH(layouts); i++)
1537 if(!strcmp((char *)arg, layouts[i].symbol))
1539 if(i == LENGTH(layouts))
1550 toggletag(const void *arg) {
1551 int i, m = *(int *)arg;
1552 for(i = 0; i < sizeof(int) * 8; i++)
1553 fputc(m & 1 << i ? '1' : '0', stdout);
1555 for(i = 0; i < sizeof(int) * 8; i++)
1556 fputc(TAGMASK & 1 << i ? '1' : '0', stdout);
1559 if(sel && (sel->tags ^ ((*(int *)arg) & TAGMASK))) {
1560 sel->tags ^= (*(int *)arg) & TAGMASK;
1566 toggleview(const void *arg) {
1567 if((tagset[seltags] ^ ((*(int *)arg) & TAGMASK))) {
1568 tagset[seltags] ^= (*(int *)arg) & TAGMASK;
1577 XMoveWindow(dpy, c->win, c->x, c->y);
1578 c->isbanned = False;
1582 unmanage(Client *c) {
1585 wc.border_width = c->oldbw;
1586 /* The server grab construct avoids race conditions. */
1588 XSetErrorHandler(xerrordummy);
1589 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1594 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1595 setclientstate(c, WithdrawnState);
1598 XSetErrorHandler(xerror);
1604 unmapnotify(XEvent *e) {
1606 XUnmapEvent *ev = &e->xunmap;
1608 if((c = getclient(ev->window)))
1614 if(dc.drawable != 0)
1615 XFreePixmap(dpy, dc.drawable);
1616 dc.drawable = XCreatePixmap(dpy, root, bw, bh, DefaultDepth(dpy, screen));
1617 XMoveResizeWindow(dpy, barwin, bx, by, bw, bh);
1624 XineramaScreenInfo *info = NULL;
1626 /* window area geometry */
1627 if(XineramaIsActive(dpy)) {
1628 info = XineramaQueryScreens(dpy, &i);
1630 wy = showbar && topbar ? info[0].y_org + bh : info[0].y_org;
1632 wh = showbar ? info[0].height - bh : info[0].height;
1639 wy = showbar && topbar ? sy + bh : sy;
1641 wh = showbar ? sh - bh : sh;
1646 by = showbar ? (topbar ? wy - bh : wy + wh) : -bh;
1649 /* update layout geometries */
1650 for(i = 0; i < LENGTH(layouts); i++)
1651 if(layouts[i].updategeom)
1652 layouts[i].updategeom();
1656 updatesizehints(Client *c) {
1660 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1662 c->flags = size.flags;
1663 if(c->flags & PBaseSize) {
1664 c->basew = size.base_width;
1665 c->baseh = size.base_height;
1667 else if(c->flags & PMinSize) {
1668 c->basew = size.min_width;
1669 c->baseh = size.min_height;
1672 c->basew = c->baseh = 0;
1673 if(c->flags & PResizeInc) {
1674 c->incw = size.width_inc;
1675 c->inch = size.height_inc;
1678 c->incw = c->inch = 0;
1679 if(c->flags & PMaxSize) {
1680 c->maxw = size.max_width;
1681 c->maxh = size.max_height;
1684 c->maxw = c->maxh = 0;
1685 if(c->flags & PMinSize) {
1686 c->minw = size.min_width;
1687 c->minh = size.min_height;
1689 else if(c->flags & PBaseSize) {
1690 c->minw = size.base_width;
1691 c->minh = size.base_height;
1694 c->minw = c->minh = 0;
1695 if(c->flags & PAspect) {
1696 c->minax = size.min_aspect.x;
1697 c->maxax = size.max_aspect.x;
1698 c->minay = size.min_aspect.y;
1699 c->maxay = size.max_aspect.y;
1702 c->minax = c->maxax = c->minay = c->maxay = 0;
1703 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1704 && c->maxw == c->minw && c->maxh == c->minh);
1708 updatetilegeom(void) {
1709 /* master area geometry */
1715 /* tile area geometry */
1723 updatetitle(Client *c) {
1724 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1725 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1729 updatewmhints(Client *c) {
1732 if((wmh = XGetWMHints(dpy, c->win))) {
1734 sel->isurgent = False;
1736 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1742 view(const void *arg) {
1743 if(*(int *)arg & TAGMASK) {
1744 seltags ^= 1; /* toggle sel tagset */
1745 tagset[seltags] = *(int *)arg & TAGMASK;
1751 viewprevtag(const void *arg) {
1752 seltags ^= 1; /* toggle sel tagset */
1756 /* There's no way to check accesses to destroyed windows, thus those cases are
1757 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1758 * default error handler, which may call exit. */
1760 xerror(Display *dpy, XErrorEvent *ee) {
1761 if(ee->error_code == BadWindow
1762 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1763 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1764 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1765 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1766 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1767 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1768 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1769 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1771 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1772 ee->request_code, ee->error_code);
1773 return xerrorxlib(dpy, ee); /* may call exit */
1777 xerrordummy(Display *dpy, XErrorEvent *ee) {
1781 /* Startup Error handler to check if another window manager
1782 * is already running. */
1784 xerrorstart(Display *dpy, XErrorEvent *ee) {
1790 zoom(const void *arg) {
1793 if(!lt->arrange || sel->isfloating)
1795 if(c == nexttiled(clients))
1796 if(!c || !(c = nexttiled(c->next)))
1805 main(int argc, char *argv[]) {
1806 if(argc == 2 && !strcmp("-v", argv[1]))
1807 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1809 eprint("usage: dwm [-v]\n");
1811 setlocale(LC_CTYPE, "");
1812 if(!(dpy = XOpenDisplay(0)))
1813 eprint("dwm: cannot open display\n");