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 struct Client Client;
68 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
69 int minax, maxax, minay, maxay;
72 Bool isbanned, isfixed, isfloating, isurgent;
82 unsigned long norm[ColLast];
83 unsigned long sel[ColLast];
93 } DC; /* draw context */
98 void (*func)(const void *arg);
104 void (*arrange)(void);
105 void (*updategeom)(void);
110 const char *instance;
116 /* function declarations */
117 void applyrules(Client *c);
119 void attach(Client *c);
120 void attachstack(Client *c);
122 void buttonpress(XEvent *e);
123 void checkotherwm(void);
125 void configure(Client *c);
126 void configurenotify(XEvent *e);
127 void configurerequest(XEvent *e);
128 void destroynotify(XEvent *e);
129 void detach(Client *c);
130 void detachstack(Client *c);
132 void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
133 void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
134 void *emallocz(uint size);
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 unsigned long 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 Bool isvisible(Client *c);
153 void keypress(XEvent *e);
154 void killclient(const void *arg);
155 void manage(Window w, XWindowAttributes *wa);
156 void mappingnotify(XEvent *e);
157 void maprequest(XEvent *e);
158 void movemouse(Client *c);
159 Client *nextunfloating(Client *c);
160 void propertynotify(XEvent *e);
161 void quit(const void *arg);
162 void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
163 void resizemouse(Client *c);
167 void setclientstate(Client *c, long state);
168 void setmfact(const void *arg);
170 void spawn(const void *arg);
171 void tag(const void *arg);
172 uint textnw(const char *text, uint len);
173 uint textw(const char *text);
175 void tileresize(Client *c, int x, int y, int w, int h);
176 void togglebar(const void *arg);
177 void togglefloating(const void *arg);
178 void togglelayout(const void *arg);
179 void toggletag(const void *arg);
180 void toggleview(const void *arg);
181 void unban(Client *c);
182 void unmanage(Client *c);
183 void unmapnotify(XEvent *e);
184 void updatebar(void);
185 void updategeom(void);
186 void updatesizehints(Client *c);
187 void updatetilegeom(void);
188 void updatetitle(Client *c);
189 void updatewmhints(Client *c);
190 void view(const void *arg);
191 void viewprevtag(const void *arg);
192 int xerror(Display *dpy, XErrorEvent *ee);
193 int xerrordummy(Display *dpy, XErrorEvent *ee);
194 int xerrorstart(Display *dpy, XErrorEvent *ee);
195 void zoom(const void *arg);
199 int screen, sx, sy, sw, sh;
200 int bx, by, bw, bh, blw, wx, wy, ww, wh;
201 int mx, my, mw, mh, tx, ty, tw, th;
203 int (*xerrorxlib)(Display *, XErrorEvent *);
204 uint numlockmask = 0;
205 void (*handler[LASTEvent]) (XEvent *) = {
206 [ButtonPress] = buttonpress,
207 [ConfigureRequest] = configurerequest,
208 [ConfigureNotify] = configurenotify,
209 [DestroyNotify] = destroynotify,
210 [EnterNotify] = enternotify,
213 [KeyPress] = keypress,
214 [MappingNotify] = mappingnotify,
215 [MapRequest] = maprequest,
216 [PropertyNotify] = propertynotify,
217 [UnmapNotify] = unmapnotify
219 Atom wmatom[WMLast], netatom[NetLast];
220 Bool otherwm, readin;
222 uint tagset[] = {1, 1}; /* after start, first tag is selected */
223 Client *clients = NULL;
225 Client *stack = NULL;
226 Cursor cursor[CurLast];
230 Layout *lt = layouts;
233 /* configuration, allows nested code to access above variables */
236 /* check if all tags will fit into a uint bitarray. */
237 static char tags_is_a_sign_that_your_IQ[sizeof(int) * 8 < LENGTH(tags) ? -1 : 1];
239 /* function implementations */
242 applyrules(Client *c) {
245 XClassHint ch = { 0 };
248 XGetClassHint(dpy, c->win, &ch);
249 for(i = 0; i < LENGTH(rules); i++) {
251 if((!r->title || strstr(c->name, r->title))
252 && (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
253 && (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
254 c->isfloating = r->isfloating;
255 c->tags |= r->tags & TAGMASK;
263 c->tags = tagset[seltags];
270 for(c = clients; c; c = c->next)
273 if(!lt->arrange || c->isfloating)
274 resize(c, c->x, c->y, c->w, c->h, True);
294 attachstack(Client *c) {
303 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
308 buttonpress(XEvent *e) {
311 XButtonPressedEvent *ev = &e->xbutton;
313 if(ev->window == barwin) {
315 for(i = 0; i < LENGTH(tags); i++) {
319 if(ev->button == Button1) {
320 if(ev->state & MODKEY)
325 else if(ev->button == Button3) {
326 if(ev->state & MODKEY)
334 if((ev->x < x + blw) && ev->button == Button1)
337 else if((c = getclient(ev->window))) {
339 if(CLEANMASK(ev->state) != MODKEY)
341 if(ev->button == Button1) {
345 else if(ev->button == Button2)
346 togglefloating(NULL);
347 else if(ev->button == Button3 && !c->isfixed) {
357 XSetErrorHandler(xerrorstart);
359 /* this causes an error if some other window manager is running */
360 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
363 eprint("dwm: another window manager is already running\n");
365 XSetErrorHandler(NULL);
366 xerrorxlib = XSetErrorHandler(xerror);
378 XFreeFontSet(dpy, dc.font.set);
380 XFreeFont(dpy, dc.font.xfont);
381 XUngrabKey(dpy, AnyKey, AnyModifier, root);
382 XFreePixmap(dpy, dc.drawable);
384 XFreeCursor(dpy, cursor[CurNormal]);
385 XFreeCursor(dpy, cursor[CurResize]);
386 XFreeCursor(dpy, cursor[CurMove]);
387 XDestroyWindow(dpy, barwin);
389 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
393 configure(Client *c) {
396 ce.type = ConfigureNotify;
404 ce.border_width = c->bw;
406 ce.override_redirect = False;
407 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
411 configurenotify(XEvent *e) {
412 XConfigureEvent *ev = &e->xconfigure;
414 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
424 configurerequest(XEvent *e) {
426 XConfigureRequestEvent *ev = &e->xconfigurerequest;
429 if((c = getclient(ev->window))) {
430 if(ev->value_mask & CWBorderWidth)
431 c->bw = ev->border_width;
432 if(c->isfixed || c->isfloating || !lt->arrange) {
433 if(ev->value_mask & CWX)
435 if(ev->value_mask & CWY)
437 if(ev->value_mask & CWWidth)
439 if(ev->value_mask & CWHeight)
441 if((c->x - sx + c->w) > sw && c->isfloating)
442 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
443 if((c->y - sy + c->h) > sh && c->isfloating)
444 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
445 if((ev->value_mask & (CWX|CWY))
446 && !(ev->value_mask & (CWWidth|CWHeight)))
449 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
457 wc.width = ev->width;
458 wc.height = ev->height;
459 wc.border_width = ev->border_width;
460 wc.sibling = ev->above;
461 wc.stack_mode = ev->detail;
462 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
468 destroynotify(XEvent *e) {
470 XDestroyWindowEvent *ev = &e->xdestroywindow;
472 if((c = getclient(ev->window)))
479 c->prev->next = c->next;
481 c->next->prev = c->prev;
484 c->next = c->prev = NULL;
488 detachstack(Client *c) {
491 for(tc = &stack; *tc && *tc != c; tc = &(*tc)->snext);
501 for(c = stack; c && !isvisible(c); c = c->snext);
502 for(i = 0; i < LENGTH(tags); i++) {
503 dc.w = textw(tags[i]);
504 if(tagset[seltags] & 1 << i) {
505 drawtext(tags[i], dc.sel, isurgent(i));
506 drawsquare(c && c->tags & 1 << i, isoccupied(i), isurgent(i), dc.sel);
509 drawtext(tags[i], dc.norm, isurgent(i));
510 drawsquare(c && c->tags & 1 << i, isoccupied(i), isurgent(i), dc.norm);
516 drawtext(lt->symbol, dc.norm, False);
527 drawtext(stext, dc.norm, False);
528 if((dc.w = dc.x - x) > bh) {
531 drawtext(c->name, dc.sel, False);
532 drawsquare(False, c->isfloating, False, dc.sel);
535 drawtext(NULL, dc.norm, False);
537 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, bw, bh, 0, 0);
542 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
545 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
547 gcv.foreground = col[invert ? ColBG : ColFG];
548 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
549 x = (dc.font.ascent + dc.font.descent + 2) / 4;
553 r.width = r.height = x + 1;
554 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
557 r.width = r.height = x;
558 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
563 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
566 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
569 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
570 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
574 len = MIN(olen, sizeof buf);
575 memcpy(buf, text, len);
577 h = dc.font.ascent + dc.font.descent;
578 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
580 /* shorten text if necessary */
581 for(; len && (w = textnw(buf, len)) > dc.w - h; len--);
592 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
594 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
596 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
600 emallocz(uint size) {
601 void *res = calloc(1, size);
604 eprint("fatal: could not malloc() %u bytes\n", size);
609 enternotify(XEvent *e) {
611 XCrossingEvent *ev = &e->xcrossing;
613 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
615 if((c = getclient(ev->window)))
622 eprint(const char *errstr, ...) {
625 va_start(ap, errstr);
626 vfprintf(stderr, errstr, ap);
633 XExposeEvent *ev = &e->xexpose;
635 if(ev->count == 0 && (ev->window == barwin))
641 if(!c || (c && !isvisible(c)))
642 for(c = stack; c && !isvisible(c); c = c->snext);
643 if(sel && sel != c) {
644 grabbuttons(sel, False);
645 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
650 grabbuttons(c, True);
654 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
655 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
658 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
663 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
664 XFocusChangeEvent *ev = &e->xfocus;
666 if(sel && ev->window != sel->win)
667 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
671 focusnext(const void *arg) {
676 for(c = sel->next; c && !isvisible(c); c = c->next);
678 for(c = clients; c && !isvisible(c); c = c->next);
686 focusprev(const void *arg) {
691 for(c = sel->prev; c && !isvisible(c); c = c->prev);
693 for(c = clients; c && c->next; c = c->next);
694 for(; c && !isvisible(c); c = c->prev);
703 getclient(Window w) {
706 for(c = clients; c && c->win != w; c = c->next);
711 getcolor(const char *colstr) {
712 Colormap cmap = DefaultColormap(dpy, screen);
715 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
716 eprint("error, cannot allocate color '%s'\n", colstr);
724 unsigned char *p = NULL;
725 unsigned long n, extra;
728 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
729 &real, &format, &n, &extra, (unsigned char **)&p);
730 if(status != Success)
739 gettextprop(Window w, Atom atom, char *text, uint size) {
744 if(!text || size == 0)
747 XGetTextProperty(dpy, w, &name, atom);
750 if(name.encoding == XA_STRING)
751 strncpy(text, (char *)name.value, size - 1);
753 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
755 strncpy(text, *list, size - 1);
756 XFreeStringList(list);
759 text[size - 1] = '\0';
765 grabbuttons(Client *c, Bool focused) {
767 uint buttons[] = { Button1, Button2, Button3 };
768 uint modifiers[] = { MODKEY, MODKEY|LockMask, MODKEY|numlockmask,
769 MODKEY|numlockmask|LockMask} ;
771 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
773 for(i = 0; i < LENGTH(buttons); i++)
774 for(j = 0; j < LENGTH(modifiers); j++)
775 XGrabButton(dpy, buttons[i], modifiers[j], c->win, False,
776 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
778 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
779 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
786 XModifierKeymap *modmap;
788 /* init modifier map */
789 modmap = XGetModifierMapping(dpy);
790 for(i = 0; i < 8; i++)
791 for(j = 0; j < modmap->max_keypermod; j++) {
792 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
793 numlockmask = (1 << i);
795 XFreeModifiermap(modmap);
797 XUngrabKey(dpy, AnyKey, AnyModifier, root);
798 for(i = 0; i < LENGTH(keys); i++) {
799 code = XKeysymToKeycode(dpy, keys[i].keysym);
800 XGrabKey(dpy, code, keys[i].mod, root, True,
801 GrabModeAsync, GrabModeAsync);
802 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
803 GrabModeAsync, GrabModeAsync);
804 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
805 GrabModeAsync, GrabModeAsync);
806 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
807 GrabModeAsync, GrabModeAsync);
812 initfont(const char *fontstr) {
813 char *def, **missing;
818 XFreeFontSet(dpy, dc.font.set);
819 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
822 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
823 XFreeStringList(missing);
826 XFontSetExtents *font_extents;
827 XFontStruct **xfonts;
829 dc.font.ascent = dc.font.descent = 0;
830 font_extents = XExtentsOfFontSet(dc.font.set);
831 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
832 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
833 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
834 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
840 XFreeFont(dpy, dc.font.xfont);
841 dc.font.xfont = NULL;
842 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
843 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
844 eprint("error, cannot load font: '%s'\n", fontstr);
845 dc.font.ascent = dc.font.xfont->ascent;
846 dc.font.descent = dc.font.xfont->descent;
848 dc.font.height = dc.font.ascent + dc.font.descent;
855 for(c = clients; c; c = c->next)
862 isprotodel(Client *c) {
867 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
868 for(i = 0; !ret && i < n; i++)
869 if(protocols[i] == wmatom[WMDelete])
880 for(c = clients; c; c = c->next)
881 if(c->isurgent && c->tags & 1 << t)
887 isvisible(Client *c) {
888 return c->tags & tagset[seltags];
892 keypress(XEvent *e) {
898 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
899 for(i = 0; i < LENGTH(keys); i++)
900 if(keysym == keys[i].keysym
901 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
904 keys[i].func(keys[i].arg);
909 killclient(const void *arg) {
914 if(isprotodel(sel)) {
915 ev.type = ClientMessage;
916 ev.xclient.window = sel->win;
917 ev.xclient.message_type = wmatom[WMProtocols];
918 ev.xclient.format = 32;
919 ev.xclient.data.l[0] = wmatom[WMDelete];
920 ev.xclient.data.l[1] = CurrentTime;
921 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
924 XKillClient(dpy, sel->win);
928 manage(Window w, XWindowAttributes *wa) {
929 Client *c, *t = NULL;
934 c = emallocz(sizeof(Client));
942 c->oldbw = wa->border_width;
943 if(c->w == sw && c->h == sh) {
946 c->bw = wa->border_width;
949 if(c->x + c->w + 2 * c->bw > sx + sw)
950 c->x = sx + sw - c->w - 2 * c->bw;
951 if(c->y + c->h + 2 * c->bw > sy + sh)
952 c->y = sy + sh - c->h - 2 * c->bw;
953 c->x = MAX(c->x, sx);
954 c->y = MAX(c->y, by == 0 ? bh : sy);
958 wc.border_width = c->bw;
959 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
960 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
961 configure(c); /* propagates border_width, if size doesn't change */
963 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
964 grabbuttons(c, False);
966 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
967 for(t = clients; t && t->win != trans; t = t->next);
973 c->isfloating = (rettrans == Success) || c->isfixed;
976 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
978 XMapWindow(dpy, c->win);
979 setclientstate(c, NormalState);
984 mappingnotify(XEvent *e) {
985 XMappingEvent *ev = &e->xmapping;
987 XRefreshKeyboardMapping(ev);
988 if(ev->request == MappingKeyboard)
993 maprequest(XEvent *e) {
994 static XWindowAttributes wa;
995 XMapRequestEvent *ev = &e->xmaprequest;
997 if(!XGetWindowAttributes(dpy, ev->window, &wa))
999 if(wa.override_redirect)
1001 if(!getclient(ev->window))
1002 manage(ev->window, &wa);
1006 movemouse(Client *c) {
1007 int x1, y1, ocx, ocy, di, nx, ny;
1014 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1015 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1017 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1019 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1022 XUngrabPointer(dpy, CurrentTime);
1024 case ConfigureRequest:
1027 handler[ev.type](&ev);
1031 nx = ocx + (ev.xmotion.x - x1);
1032 ny = ocy + (ev.xmotion.y - y1);
1033 if(snap && nx >= wx && nx <= wx + ww
1034 && ny >= wy && ny <= wy + wh) {
1035 if(abs(wx - nx) < snap)
1037 else if(abs((wx + ww) - (nx + c->w + 2 * c->bw)) < snap)
1038 nx = wx + ww - c->w - 2 * c->bw;
1039 if(abs(wy - ny) < snap)
1041 else if(abs((wy + wh) - (ny + c->h + 2 * c->bw)) < snap)
1042 ny = wy + wh - c->h - 2 * c->bw;
1043 if(!c->isfloating && lt->arrange && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
1044 togglefloating(NULL);
1046 if(!lt->arrange || c->isfloating)
1047 resize(c, nx, ny, c->w, c->h, False);
1054 nextunfloating(Client *c) {
1055 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1060 propertynotify(XEvent *e) {
1063 XPropertyEvent *ev = &e->xproperty;
1065 if(ev->state == PropertyDelete)
1066 return; /* ignore */
1067 if((c = getclient(ev->window))) {
1070 case XA_WM_TRANSIENT_FOR:
1071 XGetTransientForHint(dpy, c->win, &trans);
1072 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1075 case XA_WM_NORMAL_HINTS:
1083 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1092 quit(const void *arg) {
1093 readin = running = False;
1097 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1101 /* set minimum possible */
1105 /* temporarily remove base dimensions */
1109 /* adjust for aspect limits */
1110 if(c->minax != c->maxax && c->minay != c->maxay
1111 && c->minax > 0 && c->maxax > 0 && c->minay > 0 && c->maxay > 0) {
1112 if(w * c->maxay > h * c->maxax)
1113 w = h * c->maxax / c->maxay;
1114 else if(w * c->minay < h * c->minax)
1115 h = w * c->minay / c->minax;
1118 /* adjust for increment value */
1124 /* restore base dimensions */
1128 w = MAX(w, c->minw);
1129 h = MAX(h, c->minh);
1132 w = MIN(w, c->maxw);
1135 h = MIN(h, c->maxh);
1137 if(w <= 0 || h <= 0)
1140 x = sw - w - 2 * c->bw;
1142 y = sh - h - 2 * c->bw;
1143 if(x + w + 2 * c->bw < sx)
1145 if(y + h + 2 * c->bw < sy)
1147 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1150 c->w = wc.width = w;
1151 c->h = wc.height = h;
1152 wc.border_width = c->bw;
1153 XConfigureWindow(dpy, c->win,
1154 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1161 resizemouse(Client *c) {
1168 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1169 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1171 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1173 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1176 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1177 c->w + c->bw - 1, c->h + c->bw - 1);
1178 XUngrabPointer(dpy, CurrentTime);
1179 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1181 case ConfigureRequest:
1184 handler[ev.type](&ev);
1188 nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1189 nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1191 if(snap && nw >= wx && nw <= wx + ww
1192 && nh >= wy && nh <= wy + wh) {
1193 if(!c->isfloating && lt->arrange
1194 && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1195 togglefloating(NULL);
1197 if(!lt->arrange || c->isfloating)
1198 resize(c, c->x, c->y, nw, nh, True);
1213 if(sel->isfloating || !lt->arrange)
1214 XRaiseWindow(dpy, sel->win);
1216 wc.stack_mode = Below;
1217 wc.sibling = barwin;
1218 for(c = stack; c; c = c->snext)
1219 if(!c->isfloating && isvisible(c)) {
1220 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1221 wc.sibling = c->win;
1225 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1231 char sbuf[sizeof stext];
1237 /* main event loop, also reads status text from stdin */
1239 xfd = ConnectionNumber(dpy);
1242 len = sizeof stext - 1;
1243 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1247 FD_SET(STDIN_FILENO, &rd);
1249 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1252 eprint("select failed\n");
1254 if(FD_ISSET(STDIN_FILENO, &rd)) {
1255 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1257 strncpy(stext, strerror(errno), len);
1261 strncpy(stext, "EOF", 4);
1265 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1266 if(*p == '\n' || *p == '\0') {
1268 strncpy(stext, sbuf, len);
1269 p += r - 1; /* p is sbuf + offset + r - 1 */
1270 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1273 memmove(sbuf, p - r + 1, r);
1280 while(XPending(dpy)) {
1281 XNextEvent(dpy, &ev);
1282 if(handler[ev.type])
1283 (handler[ev.type])(&ev); /* call handler */
1291 Window *wins, d1, d2;
1292 XWindowAttributes wa;
1295 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1296 for(i = 0; i < num; i++) {
1297 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1298 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1300 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1301 manage(wins[i], &wa);
1303 for(i = 0; i < num; i++) { /* now the transients */
1304 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1306 if(XGetTransientForHint(dpy, wins[i], &d1)
1307 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1308 manage(wins[i], &wa);
1316 setclientstate(Client *c, long state) {
1317 long data[] = {state, None};
1319 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1320 PropModeReplace, (unsigned char *)data, 2);
1323 /* arg > 1.0 will set mfact absolutly */
1325 setmfact(const void *arg) {
1326 double d = *((double*) arg);
1328 if(!d || lt->arrange != tile)
1330 d = d < 1.0 ? d + mfact : d - 1.0;
1331 if(d < 0.1 || d > 0.9)
1341 XSetWindowAttributes wa;
1344 screen = DefaultScreen(dpy);
1345 root = RootWindow(dpy, screen);
1349 sw = DisplayWidth(dpy, screen);
1350 sh = DisplayHeight(dpy, screen);
1351 bh = dc.font.height + 2;
1355 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1356 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1357 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1358 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1359 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1360 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1363 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1364 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1365 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1367 /* init appearance */
1368 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1369 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1370 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1371 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1372 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1373 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1376 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1377 dc.gc = XCreateGC(dpy, root, 0, 0);
1378 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1380 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1383 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1384 w = textw(layouts[i].symbol);
1388 wa.override_redirect = 1;
1389 wa.background_pixmap = ParentRelative;
1390 wa.event_mask = ButtonPressMask|ExposureMask;
1392 barwin = XCreateWindow(dpy, root, bx, by, bw, bh, 0, DefaultDepth(dpy, screen),
1393 CopyFromParent, DefaultVisual(dpy, screen),
1394 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1395 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1396 XMapRaised(dpy, barwin);
1397 strcpy(stext, "dwm-"VERSION);
1400 /* EWMH support per view */
1401 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1402 PropModeReplace, (unsigned char *) netatom, NetLast);
1404 /* select for events */
1405 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1406 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1407 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1408 XSelectInput(dpy, root, wa.event_mask);
1416 spawn(const void *arg) {
1417 static char *shell = NULL;
1419 if(!shell && !(shell = getenv("SHELL")))
1421 /* The double-fork construct avoids zombie processes and keeps the code
1422 * clean from stupid signal handlers. */
1426 close(ConnectionNumber(dpy));
1428 execl(shell, shell, "-c", (char *)arg, (char *)NULL);
1429 fprintf(stderr, "dwm: execl '%s -c %s'", shell, (char *)arg);
1438 tag(const void *arg) {
1439 if(sel && *(int *)arg & TAGMASK) {
1440 sel->tags = *(int *)arg & TAGMASK;
1446 textnw(const char *text, uint len) {
1450 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1453 return XTextWidth(dc.font.xfont, text, len);
1457 textw(const char *text) {
1458 return textnw(text, strlen(text)) + dc.font.height;
1467 for(n = 0, c = nextunfloating(clients); c; c = nextunfloating(c->next), n++);
1472 c = nextunfloating(clients);
1475 tileresize(c, wx, wy, ww - 2 * c->bw, wh - 2 * c->bw);
1477 tileresize(c, mx, my, mw - 2 * c->bw, mh - 2 * c->bw);
1483 x = (tx > c->x + c->w) ? c->x + c->w + 2 * c->bw : tw;
1485 w = (tx > c->x + c->w) ? wx + ww - x : tw;
1490 for(i = 0, c = nextunfloating(c->next); c; c = nextunfloating(c->next), i++) {
1491 if(i + 1 == n) /* remainder */
1492 tileresize(c, x, y, w - 2 * c->bw, (ty + th) - y - 2 * c->bw);
1494 tileresize(c, x, y, w - 2 * c->bw, h - 2 * c->bw);
1496 y = c->y + c->h + 2 * c->bw;
1501 tileresize(Client *c, int x, int y, int w, int h) {
1502 resize(c, x, y, w, h, resizehints);
1503 if(resizehints && ((c->h < bh) || (c->h > h) || (c->w < bh) || (c->w > w)))
1504 /* client doesn't accept size constraints */
1505 resize(c, x, y, w, h, False);
1509 togglebar(const void *arg) {
1517 togglefloating(const void *arg) {
1520 sel->isfloating = !sel->isfloating;
1522 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1527 togglelayout(const void *arg) {
1531 if(++lt == &layouts[LENGTH(layouts)])
1535 for(i = 0; i < LENGTH(layouts); i++)
1536 if(!strcmp((char *)arg, layouts[i].symbol))
1538 if(i == LENGTH(layouts))
1549 toggletag(const void *arg) {
1550 int i, m = *(int *)arg;
1551 for(i = 0; i < sizeof(int) * 8; i++)
1552 fputc(m & 1 << i ? '1' : '0', stdout);
1554 for(i = 0; i < sizeof(int) * 8; i++)
1555 fputc(TAGMASK & 1 << i ? '1' : '0', stdout);
1558 if(sel && (sel->tags ^ ((*(int *)arg) & TAGMASK))) {
1559 sel->tags ^= (*(int *)arg) & TAGMASK;
1565 toggleview(const void *arg) {
1566 if((tagset[seltags] ^ ((*(int *)arg) & TAGMASK))) {
1567 tagset[seltags] ^= (*(int *)arg) & TAGMASK;
1576 XMoveWindow(dpy, c->win, c->x, c->y);
1577 c->isbanned = False;
1581 unmanage(Client *c) {
1584 wc.border_width = c->oldbw;
1585 /* The server grab construct avoids race conditions. */
1587 XSetErrorHandler(xerrordummy);
1588 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1593 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1594 setclientstate(c, WithdrawnState);
1597 XSetErrorHandler(xerror);
1603 unmapnotify(XEvent *e) {
1605 XUnmapEvent *ev = &e->xunmap;
1607 if((c = getclient(ev->window)))
1613 if(dc.drawable != 0)
1614 XFreePixmap(dpy, dc.drawable);
1615 dc.drawable = XCreatePixmap(dpy, root, bw, bh, DefaultDepth(dpy, screen));
1616 XMoveResizeWindow(dpy, barwin, bx, by, bw, bh);
1623 XineramaScreenInfo *info = NULL;
1625 /* window area geometry */
1626 if(XineramaIsActive(dpy)) {
1627 info = XineramaQueryScreens(dpy, &i);
1629 wy = showbar && topbar ? info[0].y_org + bh : info[0].y_org;
1631 wh = showbar ? info[0].height - bh : info[0].height;
1638 wy = showbar && topbar ? sy + bh : sy;
1640 wh = showbar ? sh - bh : sh;
1645 by = showbar ? (topbar ? wy - bh : wy + wh) : -bh;
1648 /* update layout geometries */
1649 for(i = 0; i < LENGTH(layouts); i++)
1650 if(layouts[i].updategeom)
1651 layouts[i].updategeom();
1655 updatesizehints(Client *c) {
1659 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1661 c->flags = size.flags;
1662 if(c->flags & PBaseSize) {
1663 c->basew = size.base_width;
1664 c->baseh = size.base_height;
1666 else if(c->flags & PMinSize) {
1667 c->basew = size.min_width;
1668 c->baseh = size.min_height;
1671 c->basew = c->baseh = 0;
1672 if(c->flags & PResizeInc) {
1673 c->incw = size.width_inc;
1674 c->inch = size.height_inc;
1677 c->incw = c->inch = 0;
1678 if(c->flags & PMaxSize) {
1679 c->maxw = size.max_width;
1680 c->maxh = size.max_height;
1683 c->maxw = c->maxh = 0;
1684 if(c->flags & PMinSize) {
1685 c->minw = size.min_width;
1686 c->minh = size.min_height;
1688 else if(c->flags & PBaseSize) {
1689 c->minw = size.base_width;
1690 c->minh = size.base_height;
1693 c->minw = c->minh = 0;
1694 if(c->flags & PAspect) {
1695 c->minax = size.min_aspect.x;
1696 c->maxax = size.max_aspect.x;
1697 c->minay = size.min_aspect.y;
1698 c->maxay = size.max_aspect.y;
1701 c->minax = c->maxax = c->minay = c->maxay = 0;
1702 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1703 && c->maxw == c->minw && c->maxh == c->minh);
1707 updatetilegeom(void) {
1708 /* master area geometry */
1714 /* tile area geometry */
1722 updatetitle(Client *c) {
1723 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1724 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1728 updatewmhints(Client *c) {
1731 if((wmh = XGetWMHints(dpy, c->win))) {
1733 sel->isurgent = False;
1735 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1741 view(const void *arg) {
1742 if(*(int *)arg & TAGMASK) {
1743 seltags ^= 1; /* toggle sel tagset */
1744 tagset[seltags] = *(int *)arg & TAGMASK;
1750 viewprevtag(const void *arg) {
1751 seltags ^= 1; /* toggle sel tagset */
1755 /* There's no way to check accesses to destroyed windows, thus those cases are
1756 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1757 * default error handler, which may call exit. */
1759 xerror(Display *dpy, XErrorEvent *ee) {
1760 if(ee->error_code == BadWindow
1761 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1762 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1763 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1764 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1765 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1766 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1767 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1768 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1770 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1771 ee->request_code, ee->error_code);
1772 return xerrorxlib(dpy, ee); /* may call exit */
1776 xerrordummy(Display *dpy, XErrorEvent *ee) {
1780 /* Startup Error handler to check if another window manager
1781 * is already running. */
1783 xerrorstart(Display *dpy, XErrorEvent *ee) {
1789 zoom(const void *arg) {
1792 if(c == nextunfloating(clients))
1793 if(!c || !(c = nextunfloating(c->next)))
1795 if(lt->arrange == tile && !sel->isfloating) {
1804 main(int argc, char *argv[]) {
1805 if(argc == 2 && !strcmp("-v", argv[1]))
1806 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1808 eprint("usage: dwm [-v]\n");
1810 setlocale(LC_CTYPE, "");
1811 if(!(dpy = XOpenDisplay(0)))
1812 eprint("dwm: cannot open display\n");