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))
55 #define TEXTW(x) (textnw(x, strlen(x)) + dc.font.height)
56 #define VISIBLE(x) ((x)->tags & tagset[seltags])
59 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
60 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
61 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
62 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
65 typedef unsigned int uint;
66 typedef unsigned long ulong;
67 typedef struct Client Client;
71 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
72 int minax, maxax, minay, maxay;
75 Bool isbanned, isfixed, isfloating, ismax, isurgent;
96 } DC; /* draw context */
101 void (*func)(const void *arg);
107 void (*arrange)(void);
112 const char *instance;
118 /* function declarations */
119 void applyrules(Client *c);
121 void attach(Client *c);
122 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 enternotify(XEvent *e);
136 void eprint(const char *errstr, ...);
137 void expose(XEvent *e);
138 void focus(Client *c);
139 void focusin(XEvent *e);
140 void focusnext(const void *arg);
141 void focusprev(const void *arg);
142 Client *getclient(Window w);
143 ulong getcolor(const char *colstr);
144 long getstate(Window w);
145 Bool gettextprop(Window w, Atom atom, char *text, uint size);
146 void grabbuttons(Client *c, Bool focused);
148 void initfont(const char *fontstr);
149 Bool isoccupied(uint t);
150 Bool isprotodel(Client *c);
151 Bool isurgent(uint t);
152 void keypress(XEvent *e);
153 void killclient(const void *arg);
154 void manage(Window w, XWindowAttributes *wa);
155 void mappingnotify(XEvent *e);
156 void maprequest(XEvent *e);
157 void movemouse(Client *c);
158 Client *nexttiled(Client *c);
159 void propertynotify(XEvent *e);
160 void quit(const void *arg);
161 void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
162 void resizemouse(Client *c);
166 void setclientstate(Client *c, long state);
167 void setmfact(const void *arg);
169 void spawn(const void *arg);
170 void tag(const void *arg);
171 uint textnw(const char *text, uint len);
173 void togglebar(const void *arg);
174 void togglefloating(const void *arg);
175 void togglelayout(const void *arg);
176 void togglemax(const void *arg);
177 void toggletag(const void *arg);
178 void toggleview(const void *arg);
179 void unmanage(Client *c);
180 void unmapnotify(XEvent *e);
181 void updatebar(void);
182 void updategeom(void);
183 void updatesizehints(Client *c);
184 void updatetitle(Client *c);
185 void updatewmhints(Client *c);
186 void view(const void *arg);
187 void viewprevtag(const void *arg);
188 int xerror(Display *dpy, XErrorEvent *ee);
189 int xerrordummy(Display *dpy, XErrorEvent *ee);
190 int xerrorstart(Display *dpy, XErrorEvent *ee);
191 void zoom(const void *arg);
195 int screen, sx, sy, sw, sh;
196 int by, bh, blw, wx, wy, ww, wh;
198 int (*xerrorxlib)(Display *, XErrorEvent *);
199 uint numlockmask = 0;
200 void (*handler[LASTEvent]) (XEvent *) = {
201 [ButtonPress] = buttonpress,
202 [ConfigureRequest] = configurerequest,
203 [ConfigureNotify] = configurenotify,
204 [DestroyNotify] = destroynotify,
205 [EnterNotify] = enternotify,
208 [KeyPress] = keypress,
209 [MappingNotify] = mappingnotify,
210 [MapRequest] = maprequest,
211 [PropertyNotify] = propertynotify,
212 [UnmapNotify] = unmapnotify
214 Atom wmatom[WMLast], netatom[NetLast];
216 Bool otherwm, readin;
218 uint tagset[] = {1, 1}; /* after start, first tag is selected */
219 Client *clients = NULL;
221 Client *stack = NULL;
222 Cursor cursor[CurLast];
226 Layout *lt = layouts;
229 /* configuration, allows nested code to access above variables */
232 /* compile-time check if all tags fit into an uint bit array. */
233 struct NumTags { char limitexceeded[sizeof(uint) * 8 < LENGTH(tags) ? -1 : 1]; };
235 /* function implementations */
237 applyrules(Client *c) {
240 XClassHint ch = { 0 };
243 XGetClassHint(dpy, c->win, &ch);
244 for(i = 0; i < LENGTH(rules); i++) {
246 if((!r->title || strstr(c->name, r->title))
247 && (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
248 && (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
249 c->isfloating = r->isfloating;
250 c->tags |= r->tags & TAGMASK;
258 c->tags = tagset[seltags];
265 for(c = clients; c; c = c->next)
267 if(!lt->arrange || c->isfloating)
268 resize(c, c->x, c->y, c->w, c->h, True);
270 else if(!c->isbanned) {
271 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
276 if(lt->arrange && !ismax)
290 attachstack(Client *c) {
296 buttonpress(XEvent *e) {
299 XButtonPressedEvent *ev = &e->xbutton;
301 if(ev->window == barwin) {
303 for(i = 0; i < LENGTH(tags); i++) {
307 if(ev->button == Button1) {
308 if(ev->state & MODKEY)
313 else if(ev->button == Button3) {
314 if(ev->state & MODKEY)
322 if(ev->x < x + blw) {
323 if(ev->button == Button1)
325 else if(ev->button == Button3)
329 else if((c = getclient(ev->window))) {
331 if(CLEANMASK(ev->state) != MODKEY || ismax)
333 if(ev->button == Button1)
335 else if(ev->button == Button2)
336 togglefloating(NULL);
337 else if(ev->button == Button3 && !c->isfixed)
345 XSetErrorHandler(xerrorstart);
347 /* this causes an error if some other window manager is running */
348 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
351 eprint("dwm: another window manager is already running\n");
352 XSetErrorHandler(NULL);
353 xerrorxlib = XSetErrorHandler(xerror);
364 XFreeFontSet(dpy, dc.font.set);
366 XFreeFont(dpy, dc.font.xfont);
367 XUngrabKey(dpy, AnyKey, AnyModifier, root);
368 XFreePixmap(dpy, dc.drawable);
370 XFreeCursor(dpy, cursor[CurNormal]);
371 XFreeCursor(dpy, cursor[CurResize]);
372 XFreeCursor(dpy, cursor[CurMove]);
373 XDestroyWindow(dpy, barwin);
375 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
379 configure(Client *c) {
382 ce.type = ConfigureNotify;
390 ce.border_width = c->bw;
392 ce.override_redirect = False;
393 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
397 configurenotify(XEvent *e) {
398 XConfigureEvent *ev = &e->xconfigure;
400 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
410 configurerequest(XEvent *e) {
412 XConfigureRequestEvent *ev = &e->xconfigurerequest;
415 if((c = getclient(ev->window))) {
416 if(ev->value_mask & CWBorderWidth)
417 c->bw = ev->border_width;
418 if(c->isfixed || c->isfloating || !lt->arrange) {
419 if(ev->value_mask & CWX)
421 if(ev->value_mask & CWY)
423 if(ev->value_mask & CWWidth)
425 if(ev->value_mask & CWHeight)
427 if((c->x - sx + c->w) > sw && c->isfloating)
428 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
429 if((c->y - sy + c->h) > sh && c->isfloating)
430 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
431 if((ev->value_mask & (CWX|CWY))
432 && !(ev->value_mask & (CWWidth|CWHeight)))
435 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
443 wc.width = ev->width;
444 wc.height = ev->height;
445 wc.border_width = ev->border_width;
446 wc.sibling = ev->above;
447 wc.stack_mode = ev->detail;
448 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
454 destroynotify(XEvent *e) {
456 XDestroyWindowEvent *ev = &e->xdestroywindow;
458 if((c = getclient(ev->window)))
465 c->prev->next = c->next;
467 c->next->prev = c->prev;
470 c->next = c->prev = NULL;
474 detachstack(Client *c) {
477 for(tc = &stack; *tc && *tc != c; tc = &(*tc)->snext);
487 for(c = stack; c && !VISIBLE(c); c = c->snext);
488 for(i = 0; i < LENGTH(tags); i++) {
489 dc.w = TEXTW(tags[i]);
490 if(tagset[seltags] & 1 << i) {
491 drawtext(tags[i], dc.sel, isurgent(i));
492 drawsquare(c && c->tags & 1 << i, isoccupied(i), isurgent(i), dc.sel);
495 drawtext(tags[i], dc.norm, isurgent(i));
496 drawsquare(c && c->tags & 1 << i, isoccupied(i), isurgent(i), dc.norm);
502 drawtext(lt->symbol, dc.norm, ismax);
513 drawtext(stext, dc.norm, False);
514 if((dc.w = dc.x - x) > bh) {
517 drawtext(c->name, dc.sel, False);
518 drawsquare(False, c->isfloating, False, dc.sel);
521 drawtext(NULL, dc.norm, False);
523 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, ww, bh, 0, 0);
528 drawsquare(Bool filled, Bool empty, Bool invert, ulong col[ColLast]) {
531 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
533 gcv.foreground = col[invert ? ColBG : ColFG];
534 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
535 x = (dc.font.ascent + dc.font.descent + 2) / 4;
539 r.width = r.height = x + 1;
540 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
543 r.width = r.height = x;
544 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
549 drawtext(const char *text, ulong col[ColLast], Bool invert) {
552 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
555 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
556 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
560 len = MIN(olen, sizeof buf);
561 memcpy(buf, text, len);
563 h = dc.font.ascent + dc.font.descent;
564 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
566 /* shorten text if necessary */
567 for(; len && (w = textnw(buf, len)) > dc.w - h; len--);
578 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
580 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
582 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
586 enternotify(XEvent *e) {
588 XCrossingEvent *ev = &e->xcrossing;
590 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
592 if((c = getclient(ev->window)))
599 eprint(const char *errstr, ...) {
602 va_start(ap, errstr);
603 vfprintf(stderr, errstr, ap);
610 XExposeEvent *ev = &e->xexpose;
612 if(ev->count == 0 && (ev->window == barwin))
618 if(!c || (c && !VISIBLE(c)))
619 for(c = stack; c && !VISIBLE(c); c = c->snext);
620 if(sel && sel != c) {
621 grabbuttons(sel, False);
622 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
627 grabbuttons(c, True);
632 XMoveResizeWindow(dpy, c->win, wx, wy, ww - 2 * c->bw, wh - 2 * c->bw);
635 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
636 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
639 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
644 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
645 XFocusChangeEvent *ev = &e->xfocus;
647 if(sel && ev->window != sel->win)
648 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
652 focusnext(const void *arg) {
657 for(c = sel->next; c && !VISIBLE(c); c = c->next);
659 for(c = clients; c && !VISIBLE(c); c = c->next);
667 focusprev(const void *arg) {
672 for(c = sel->prev; c && !VISIBLE(c); c = c->prev);
674 for(c = clients; c && c->next; c = c->next);
675 for(; c && !VISIBLE(c); c = c->prev);
684 getclient(Window w) {
687 for(c = clients; c && c->win != w; c = c->next);
692 getcolor(const char *colstr) {
693 Colormap cmap = DefaultColormap(dpy, screen);
696 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
697 eprint("error, cannot allocate color '%s'\n", colstr);
705 unsigned char *p = NULL;
709 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
710 &real, &format, &n, &extra, (unsigned char **)&p);
711 if(status != Success)
720 gettextprop(Window w, Atom atom, char *text, uint size) {
725 if(!text || size == 0)
728 XGetTextProperty(dpy, w, &name, atom);
731 if(name.encoding == XA_STRING)
732 strncpy(text, (char *)name.value, size - 1);
734 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
736 strncpy(text, *list, size - 1);
737 XFreeStringList(list);
740 text[size - 1] = '\0';
746 grabbuttons(Client *c, Bool focused) {
748 uint buttons[] = { Button1, Button2, Button3 };
749 uint modifiers[] = { MODKEY, MODKEY|LockMask, MODKEY|numlockmask,
750 MODKEY|numlockmask|LockMask} ;
752 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
754 for(i = 0; i < LENGTH(buttons); i++)
755 for(j = 0; j < LENGTH(modifiers); j++)
756 XGrabButton(dpy, buttons[i], modifiers[j], c->win, False,
757 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
759 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
760 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
767 XModifierKeymap *modmap;
769 /* init modifier map */
770 modmap = XGetModifierMapping(dpy);
771 for(i = 0; i < 8; i++)
772 for(j = 0; j < modmap->max_keypermod; j++) {
773 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
774 numlockmask = (1 << i);
776 XFreeModifiermap(modmap);
778 XUngrabKey(dpy, AnyKey, AnyModifier, root);
779 for(i = 0; i < LENGTH(keys); i++) {
780 code = XKeysymToKeycode(dpy, keys[i].keysym);
781 XGrabKey(dpy, code, keys[i].mod, root, True,
782 GrabModeAsync, GrabModeAsync);
783 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
784 GrabModeAsync, GrabModeAsync);
785 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
786 GrabModeAsync, GrabModeAsync);
787 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
788 GrabModeAsync, GrabModeAsync);
793 initfont(const char *fontstr) {
794 char *def, **missing;
799 XFreeFontSet(dpy, dc.font.set);
800 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
803 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
804 XFreeStringList(missing);
807 XFontSetExtents *font_extents;
808 XFontStruct **xfonts;
810 dc.font.ascent = dc.font.descent = 0;
811 font_extents = XExtentsOfFontSet(dc.font.set);
812 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
813 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
814 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
815 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
821 XFreeFont(dpy, dc.font.xfont);
822 dc.font.xfont = NULL;
823 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
824 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
825 eprint("error, cannot load font: '%s'\n", fontstr);
826 dc.font.ascent = dc.font.xfont->ascent;
827 dc.font.descent = dc.font.xfont->descent;
829 dc.font.height = dc.font.ascent + dc.font.descent;
836 for(c = clients; c; c = c->next)
843 isprotodel(Client *c) {
848 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
849 for(i = 0; !ret && i < n; i++)
850 if(protocols[i] == wmatom[WMDelete])
861 for(c = clients; c; c = c->next)
862 if(c->isurgent && c->tags & 1 << t)
868 keypress(XEvent *e) {
874 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
875 for(i = 0; i < LENGTH(keys); i++)
876 if(keysym == keys[i].keysym
877 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
879 keys[i].func(keys[i].arg);
883 killclient(const void *arg) {
888 if(isprotodel(sel)) {
889 ev.type = ClientMessage;
890 ev.xclient.window = sel->win;
891 ev.xclient.message_type = wmatom[WMProtocols];
892 ev.xclient.format = 32;
893 ev.xclient.data.l[0] = wmatom[WMDelete];
894 ev.xclient.data.l[1] = CurrentTime;
895 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
898 XKillClient(dpy, sel->win);
902 manage(Window w, XWindowAttributes *wa) {
903 Client *c, *t = NULL;
908 if(!(c = calloc(1, sizeof(Client))))
909 eprint("fatal: could not calloc() %u bytes\n", sizeof(Client));
917 c->oldbw = wa->border_width;
918 if(c->w == sw && c->h == sh) {
921 c->bw = wa->border_width;
924 if(c->x + c->w + 2 * c->bw > sx + sw)
925 c->x = sx + sw - c->w - 2 * c->bw;
926 if(c->y + c->h + 2 * c->bw > sy + sh)
927 c->y = sy + sh - c->h - 2 * c->bw;
928 c->x = MAX(c->x, sx);
929 c->y = MAX(c->y, by == 0 ? bh : sy);
933 wc.border_width = c->bw;
934 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
935 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
936 configure(c); /* propagates border_width, if size doesn't change */
938 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
939 grabbuttons(c, False);
941 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
942 for(t = clients; t && t->win != trans; t = t->next);
948 c->isfloating = (rettrans == Success) || c->isfixed;
951 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
952 XMapWindow(dpy, c->win);
953 setclientstate(c, NormalState);
958 mappingnotify(XEvent *e) {
959 XMappingEvent *ev = &e->xmapping;
961 XRefreshKeyboardMapping(ev);
962 if(ev->request == MappingKeyboard)
967 maprequest(XEvent *e) {
968 static XWindowAttributes wa;
969 XMapRequestEvent *ev = &e->xmaprequest;
971 if(!XGetWindowAttributes(dpy, ev->window, &wa))
973 if(wa.override_redirect)
975 if(!getclient(ev->window))
976 manage(ev->window, &wa);
980 movemouse(Client *c) {
981 int x1, y1, ocx, ocy, di, nx, ny;
989 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
990 None, cursor[CurMove], CurrentTime) != GrabSuccess)
992 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
994 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
997 XUngrabPointer(dpy, CurrentTime);
999 case ConfigureRequest:
1002 handler[ev.type](&ev);
1006 nx = ocx + (ev.xmotion.x - x1);
1007 ny = ocy + (ev.xmotion.y - y1);
1008 if(snap && nx >= wx && nx <= wx + ww
1009 && ny >= wy && ny <= wy + wh) {
1010 if(abs(wx - nx) < snap)
1012 else if(abs((wx + ww) - (nx + c->w + 2 * c->bw)) < snap)
1013 nx = wx + ww - c->w - 2 * c->bw;
1014 if(abs(wy - ny) < snap)
1016 else if(abs((wy + wh) - (ny + c->h + 2 * c->bw)) < snap)
1017 ny = wy + wh - c->h - 2 * c->bw;
1018 if(!c->isfloating && lt->arrange && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
1019 togglefloating(NULL);
1021 if(!lt->arrange || c->isfloating)
1022 resize(c, nx, ny, c->w, c->h, False);
1029 nexttiled(Client *c) {
1030 for(; c && (c->isfloating || !VISIBLE(c)); c = c->next);
1035 propertynotify(XEvent *e) {
1038 XPropertyEvent *ev = &e->xproperty;
1040 if(ev->state == PropertyDelete)
1041 return; /* ignore */
1042 if((c = getclient(ev->window))) {
1045 case XA_WM_TRANSIENT_FOR:
1046 XGetTransientForHint(dpy, c->win, &trans);
1047 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1050 case XA_WM_NORMAL_HINTS:
1058 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1067 quit(const void *arg) {
1068 readin = running = False;
1072 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1076 /* set minimum possible */
1080 /* temporarily remove base dimensions */
1084 /* adjust for aspect limits */
1085 if(c->minax != c->maxax && c->minay != c->maxay
1086 && c->minax > 0 && c->maxax > 0 && c->minay > 0 && c->maxay > 0) {
1087 if(w * c->maxay > h * c->maxax)
1088 w = h * c->maxax / c->maxay;
1089 else if(w * c->minay < h * c->minax)
1090 h = w * c->minay / c->minax;
1093 /* adjust for increment value */
1099 /* restore base dimensions */
1103 w = MAX(w, c->minw);
1104 h = MAX(h, c->minh);
1107 w = MIN(w, c->maxw);
1110 h = MIN(h, c->maxh);
1112 if(w <= 0 || h <= 0)
1115 x = sw - w - 2 * c->bw;
1117 y = sh - h - 2 * c->bw;
1118 if(x + w + 2 * c->bw < sx)
1120 if(y + h + 2 * c->bw < sy)
1126 if(c->x != x || c->y != y || c->w != w || c->h != h || c->isbanned || c->ismax) {
1127 c->isbanned = c->ismax = False;
1130 c->w = wc.width = w;
1131 c->h = wc.height = h;
1132 wc.border_width = c->bw;
1133 XConfigureWindow(dpy, c->win,
1134 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1141 resizemouse(Client *c) {
1149 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1150 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1152 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1154 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1157 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1158 c->w + c->bw - 1, c->h + c->bw - 1);
1159 XUngrabPointer(dpy, CurrentTime);
1160 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1162 case ConfigureRequest:
1165 handler[ev.type](&ev);
1169 nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1170 nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1172 if(snap && nw >= wx && nw <= wx + ww
1173 && nh >= wy && nh <= wy + wh) {
1174 if(!c->isfloating && lt->arrange
1175 && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1176 togglefloating(NULL);
1178 if(!lt->arrange || c->isfloating)
1179 resize(c, c->x, c->y, nw, nh, True);
1194 if(ismax || sel->isfloating || !lt->arrange)
1195 XRaiseWindow(dpy, sel->win);
1196 if(!ismax && lt->arrange) {
1197 wc.stack_mode = Below;
1198 wc.sibling = barwin;
1199 for(c = stack; c; c = c->snext)
1200 if(!c->isfloating && VISIBLE(c)) {
1201 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1202 wc.sibling = c->win;
1206 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1212 char sbuf[sizeof stext];
1218 /* main event loop, also reads status text from stdin */
1220 xfd = ConnectionNumber(dpy);
1223 len = sizeof stext - 1;
1224 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1228 FD_SET(STDIN_FILENO, &rd);
1230 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1233 eprint("select failed\n");
1235 if(FD_ISSET(STDIN_FILENO, &rd)) {
1236 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1238 strncpy(stext, strerror(errno), len);
1242 strncpy(stext, "EOF", 4);
1246 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1247 if(*p == '\n' || *p == '\0') {
1249 strncpy(stext, sbuf, len);
1250 p += r - 1; /* p is sbuf + offset + r - 1 */
1251 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1254 memmove(sbuf, p - r + 1, r);
1261 while(XPending(dpy)) {
1262 XNextEvent(dpy, &ev);
1263 if(handler[ev.type])
1264 (handler[ev.type])(&ev); /* call handler */
1272 Window *wins, d1, d2;
1273 XWindowAttributes wa;
1276 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1277 for(i = 0; i < num; i++) {
1278 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1279 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1281 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1282 manage(wins[i], &wa);
1284 for(i = 0; i < num; i++) { /* now the transients */
1285 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1287 if(XGetTransientForHint(dpy, wins[i], &d1)
1288 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1289 manage(wins[i], &wa);
1297 setclientstate(Client *c, long state) {
1298 long data[] = {state, None};
1300 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1301 PropModeReplace, (unsigned char *)data, 2);
1304 /* arg > 1.0 will set mfact absolutly */
1306 setmfact(const void *arg) {
1307 double d = *((double*) arg);
1309 if(!d || lt->arrange != tile)
1311 d = d < 1.0 ? d + mfact : d - 1.0;
1312 if(d < 0.1 || d > 0.9)
1321 XSetWindowAttributes wa;
1324 screen = DefaultScreen(dpy);
1325 root = RootWindow(dpy, screen);
1329 sw = DisplayWidth(dpy, screen);
1330 sh = DisplayHeight(dpy, screen);
1331 bh = dc.font.height + 2;
1335 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1336 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1337 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1338 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1339 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1340 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1343 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1344 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1345 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1347 /* init appearance */
1348 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1349 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1350 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1351 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1352 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1353 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1356 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1357 dc.gc = XCreateGC(dpy, root, 0, 0);
1358 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1360 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1363 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1364 w = TEXTW(layouts[i].symbol);
1368 wa.override_redirect = 1;
1369 wa.background_pixmap = ParentRelative;
1370 wa.event_mask = ButtonPressMask|ExposureMask;
1372 barwin = XCreateWindow(dpy, root, wx, by, ww, bh, 0, DefaultDepth(dpy, screen),
1373 CopyFromParent, DefaultVisual(dpy, screen),
1374 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1375 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1376 XMapRaised(dpy, barwin);
1377 strcpy(stext, "dwm-"VERSION);
1380 /* EWMH support per view */
1381 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1382 PropModeReplace, (unsigned char *) netatom, NetLast);
1384 /* select for events */
1385 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1386 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1387 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1388 XSelectInput(dpy, root, wa.event_mask);
1396 spawn(const void *arg) {
1397 static char *shell = NULL;
1399 if(!shell && !(shell = getenv("SHELL")))
1401 /* The double-fork construct avoids zombie processes and keeps the code
1402 * clean from stupid signal handlers. */
1406 close(ConnectionNumber(dpy));
1408 execl(shell, shell, "-c", (char *)arg, (char *)NULL);
1409 fprintf(stderr, "dwm: execl '%s -c %s'", shell, (char *)arg);
1418 tag(const void *arg) {
1419 if(sel && *(int *)arg & TAGMASK) {
1420 sel->tags = *(int *)arg & TAGMASK;
1426 textnw(const char *text, uint len) {
1430 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1433 return XTextWidth(dc.font.xfont, text, len);
1442 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next), n++);
1447 c = nexttiled(clients);
1449 resize(c, wx, wy, ((n == 1) ? ww : mw) - 2 * c->bw, wh - 2 * c->bw, resizehints);
1455 x = (wx + mw > c->x + c->w) ? c->x + c->w + 2 * c->bw : ww - mw;
1457 w = (wx + mw > c->x + c->w) ? wx + ww - x : ww - mw;
1462 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1463 resize(c, x, y, w - 2 * c->bw, /* remainder */ ((i + 1 == n)
1464 ? (wy + wh) - y : h) - 2 * c->bw, resizehints);
1466 y = c->y + c->h + 2 * c->bw;
1471 togglebar(const void *arg) {
1479 togglefloating(const void *arg) {
1482 sel->isfloating = !sel->isfloating;
1484 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1489 togglelayout(const void *arg) {
1493 if(++lt == &layouts[LENGTH(layouts)])
1497 for(i = 0; i < LENGTH(layouts); i++)
1498 if(!strcmp((char *)arg, layouts[i].symbol))
1500 if(i == LENGTH(layouts))
1511 togglemax(const void *arg) {
1517 toggletag(const void *arg) {
1518 if(sel && (sel->tags ^ ((*(int *)arg) & TAGMASK))) {
1519 sel->tags ^= (*(int *)arg) & TAGMASK;
1525 toggleview(const void *arg) {
1526 if((tagset[seltags] ^ ((*(int *)arg) & TAGMASK))) {
1527 tagset[seltags] ^= (*(int *)arg) & TAGMASK;
1533 unmanage(Client *c) {
1536 wc.border_width = c->oldbw;
1537 /* The server grab construct avoids race conditions. */
1539 XSetErrorHandler(xerrordummy);
1540 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1545 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1546 setclientstate(c, WithdrawnState);
1549 XSetErrorHandler(xerror);
1555 unmapnotify(XEvent *e) {
1557 XUnmapEvent *ev = &e->xunmap;
1559 if((c = getclient(ev->window)))
1565 if(dc.drawable != 0)
1566 XFreePixmap(dpy, dc.drawable);
1567 dc.drawable = XCreatePixmap(dpy, root, ww, bh, DefaultDepth(dpy, screen));
1568 XMoveResizeWindow(dpy, barwin, wx, by, ww, bh);
1575 XineramaScreenInfo *info = NULL;
1577 /* window area geometry */
1578 if(XineramaIsActive(dpy)) {
1579 info = XineramaQueryScreens(dpy, &i);
1581 wy = showbar && topbar ? info[0].y_org + bh : info[0].y_org;
1583 wh = showbar ? info[0].height - bh : info[0].height;
1590 wy = showbar && topbar ? sy + bh : sy;
1592 wh = showbar ? sh - bh : sh;
1596 by = showbar ? (topbar ? wy - bh : wy + wh) : -bh;
1600 updatesizehints(Client *c) {
1604 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1606 c->flags = size.flags;
1607 if(c->flags & PBaseSize) {
1608 c->basew = size.base_width;
1609 c->baseh = size.base_height;
1611 else if(c->flags & PMinSize) {
1612 c->basew = size.min_width;
1613 c->baseh = size.min_height;
1616 c->basew = c->baseh = 0;
1617 if(c->flags & PResizeInc) {
1618 c->incw = size.width_inc;
1619 c->inch = size.height_inc;
1622 c->incw = c->inch = 0;
1623 if(c->flags & PMaxSize) {
1624 c->maxw = size.max_width;
1625 c->maxh = size.max_height;
1628 c->maxw = c->maxh = 0;
1629 if(c->flags & PMinSize) {
1630 c->minw = size.min_width;
1631 c->minh = size.min_height;
1633 else if(c->flags & PBaseSize) {
1634 c->minw = size.base_width;
1635 c->minh = size.base_height;
1638 c->minw = c->minh = 0;
1639 if(c->flags & PAspect) {
1640 c->minax = size.min_aspect.x;
1641 c->maxax = size.max_aspect.x;
1642 c->minay = size.min_aspect.y;
1643 c->maxay = size.max_aspect.y;
1646 c->minax = c->maxax = c->minay = c->maxay = 0;
1647 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1648 && c->maxw == c->minw && c->maxh == c->minh);
1652 updatetitle(Client *c) {
1653 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1654 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1658 updatewmhints(Client *c) {
1661 if((wmh = XGetWMHints(dpy, c->win))) {
1663 sel->isurgent = False;
1665 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1671 view(const void *arg) {
1672 if(*(int *)arg & TAGMASK) {
1673 seltags ^= 1; /* toggle sel tagset */
1674 tagset[seltags] = *(int *)arg & TAGMASK;
1680 viewprevtag(const void *arg) {
1681 seltags ^= 1; /* toggle sel tagset */
1685 /* There's no way to check accesses to destroyed windows, thus those cases are
1686 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1687 * default error handler, which may call exit. */
1689 xerror(Display *dpy, XErrorEvent *ee) {
1690 if(ee->error_code == BadWindow
1691 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1692 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1693 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1694 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1695 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1696 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1697 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1698 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1700 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1701 ee->request_code, ee->error_code);
1702 return xerrorxlib(dpy, ee); /* may call exit */
1706 xerrordummy(Display *dpy, XErrorEvent *ee) {
1710 /* Startup Error handler to check if another window manager
1711 * is already running. */
1713 xerrorstart(Display *dpy, XErrorEvent *ee) {
1719 zoom(const void *arg) {
1722 if(!lt->arrange || sel->isfloating)
1724 if(c == nexttiled(clients))
1725 if(!c || !(c = nexttiled(c->next)))
1734 main(int argc, char *argv[]) {
1735 if(argc == 2 && !strcmp("-v", argv[1]))
1736 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1738 eprint("usage: dwm [-v]\n");
1740 setlocale(LC_CTYPE, "");
1741 if(!(dpy = XOpenDisplay(0)))
1742 eprint("dwm: cannot open display\n");