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)
56 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
57 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
58 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
59 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
62 typedef struct Client Client;
66 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
67 int minax, maxax, minay, maxay;
69 unsigned int bw, oldbw;
70 Bool isbanned, isfixed, isfloating, isurgent;
80 unsigned long norm[ColLast];
81 unsigned long sel[ColLast];
91 } DC; /* draw context */
96 void (*func)(const char *arg);
102 void (*arrange)(void);
103 void (*updategeom)(void);
108 const char *instance;
114 /* function declarations */
115 void applyrules(Client *c);
117 void attach(Client *c);
118 void attachstack(Client *c);
120 void buttonpress(XEvent *e);
121 void checkotherwm(void);
123 void configure(Client *c);
124 void configurenotify(XEvent *e);
125 void configurerequest(XEvent *e);
126 void destroynotify(XEvent *e);
127 void detach(Client *c);
128 void detachstack(Client *c);
130 void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
131 void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
132 void *emallocz(unsigned int size);
133 void enternotify(XEvent *e);
134 void eprint(const char *errstr, ...);
135 void expose(XEvent *e);
136 void focus(Client *c);
137 void focusin(XEvent *e);
138 void focusnext(const char *arg);
139 void focusprev(const char *arg);
140 Client *getclient(Window w);
141 unsigned long getcolor(const char *colstr);
142 long getstate(Window w);
143 Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
144 void grabbuttons(Client *c, Bool focused);
146 unsigned int idxoftag(const char *t);
147 void initfont(const char *fontstr);
148 Bool isoccupied(unsigned int t);
149 Bool isprotodel(Client *c);
150 Bool isurgent(unsigned int t);
151 Bool isvisible(Client *c);
152 void keypress(XEvent *e);
153 void killclient(const char *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 *nextunfloating(Client *c);
159 void propertynotify(XEvent *e);
160 void quit(const char *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 char *arg);
169 void spawn(const char *arg);
170 void tag(const char *arg);
171 unsigned int textnw(const char *text, unsigned int len);
172 unsigned int textw(const char *text);
174 void tileresize(Client *c, int x, int y, int w, int h);
175 void togglebar(const char *arg);
176 void togglefloating(const char *arg);
177 void togglelayout(const char *arg);
178 void toggletag(const char *arg);
179 void toggleview(const char *arg);
180 void unban(Client *c);
181 void unmanage(Client *c);
182 void unmapnotify(XEvent *e);
183 void updatebar(void);
184 void updategeom(void);
185 void updatesizehints(Client *c);
186 void updatetilegeom(void);
187 void updatetitle(Client *c);
188 void updatewmhints(Client *c);
189 void view(const char *arg);
190 void viewprevtag(const char *arg);
191 int xerror(Display *dpy, XErrorEvent *ee);
192 int xerrordummy(Display *dpy, XErrorEvent *ee);
193 int xerrorstart(Display *dpy, XErrorEvent *ee);
194 void zoom(const char *arg);
198 int screen, sx, sy, sw, sh;
199 int bx, by, bw, bh, blw, wx, wy, ww, wh;
200 int mx, my, mw, mh, tx, ty, tw, th;
202 int (*xerrorxlib)(Display *, XErrorEvent *);
203 unsigned int numlockmask = 0;
204 void (*handler[LASTEvent]) (XEvent *) = {
205 [ButtonPress] = buttonpress,
206 [ConfigureRequest] = configurerequest,
207 [ConfigureNotify] = configurenotify,
208 [DestroyNotify] = destroynotify,
209 [EnterNotify] = enternotify,
212 [KeyPress] = keypress,
213 [MappingNotify] = mappingnotify,
214 [MapRequest] = maprequest,
215 [PropertyNotify] = propertynotify,
216 [UnmapNotify] = unmapnotify
218 Atom wmatom[WMLast], netatom[NetLast];
219 Bool otherwm, readin;
222 Client *clients = NULL;
224 Client *stack = NULL;
225 Cursor cursor[CurLast];
229 Layout *lt = layouts;
232 /* configuration, allows nested code to access above variables */
234 #define TAGSZ (LENGTH(tags) * sizeof(Bool))
236 /* function implementations */
239 applyrules(Client *c) {
241 Bool matched = False;
243 XClassHint ch = { 0 };
246 XGetClassHint(dpy, c->win, &ch);
247 for(i = 0; i < LENGTH(rules); i++) {
249 if((!r->title || strstr(c->name, r->title))
250 && (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
251 && (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
252 c->isfloating = r->isfloating;
254 c->tags[idxoftag(r->tag)] = True;
264 memcpy(c->tags, tagset[seltags], TAGSZ);
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++) {
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 if(lt->arrange && c->isfloating)
347 togglefloating(NULL);
349 else if(ev->button == Button3 && !c->isfixed) {
359 XSetErrorHandler(xerrorstart);
361 /* this causes an error if some other window manager is running */
362 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
365 eprint("dwm: another window manager is already running\n");
367 XSetErrorHandler(NULL);
368 xerrorxlib = XSetErrorHandler(xerror);
380 XFreeFontSet(dpy, dc.font.set);
382 XFreeFont(dpy, dc.font.xfont);
383 XUngrabKey(dpy, AnyKey, AnyModifier, root);
384 XFreePixmap(dpy, dc.drawable);
386 XFreeCursor(dpy, cursor[CurNormal]);
387 XFreeCursor(dpy, cursor[CurResize]);
388 XFreeCursor(dpy, cursor[CurMove]);
389 XDestroyWindow(dpy, barwin);
391 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
395 configure(Client *c) {
398 ce.type = ConfigureNotify;
406 ce.border_width = c->bw;
408 ce.override_redirect = False;
409 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
413 configurenotify(XEvent *e) {
414 XConfigureEvent *ev = &e->xconfigure;
416 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
426 configurerequest(XEvent *e) {
428 XConfigureRequestEvent *ev = &e->xconfigurerequest;
431 if((c = getclient(ev->window))) {
432 if(ev->value_mask & CWBorderWidth)
433 c->bw = ev->border_width;
434 if(c->isfixed || c->isfloating || !lt->arrange) {
435 if(ev->value_mask & CWX)
437 if(ev->value_mask & CWY)
439 if(ev->value_mask & CWWidth)
441 if(ev->value_mask & CWHeight)
443 if((c->x - sx + c->w) > sw && c->isfloating)
444 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
445 if((c->y - sy + c->h) > sh && c->isfloating)
446 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
447 if((ev->value_mask & (CWX|CWY))
448 && !(ev->value_mask & (CWWidth|CWHeight)))
451 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
459 wc.width = ev->width;
460 wc.height = ev->height;
461 wc.border_width = ev->border_width;
462 wc.sibling = ev->above;
463 wc.stack_mode = ev->detail;
464 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
470 destroynotify(XEvent *e) {
472 XDestroyWindowEvent *ev = &e->xdestroywindow;
474 if((c = getclient(ev->window)))
481 c->prev->next = c->next;
483 c->next->prev = c->prev;
486 c->next = c->prev = NULL;
490 detachstack(Client *c) {
493 for(tc = &stack; *tc && *tc != c; tc = &(*tc)->snext);
503 for(c = stack; c && !isvisible(c); c = c->snext);
504 for(i = 0; i < LENGTH(tags); i++) {
505 dc.w = textw(tags[i]);
506 if(tagset[seltags][i]) {
507 drawtext(tags[i], dc.sel, isurgent(i));
508 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.sel);
511 drawtext(tags[i], dc.norm, isurgent(i));
512 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.norm);
518 drawtext(lt->symbol, dc.norm, False);
529 drawtext(stext, dc.norm, False);
530 if((dc.w = dc.x - x) > bh) {
533 drawtext(c->name, dc.sel, False);
534 drawsquare(False, c->isfloating, False, dc.sel);
537 drawtext(NULL, dc.norm, False);
539 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, bw, bh, 0, 0);
544 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
547 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
549 gcv.foreground = col[invert ? ColBG : ColFG];
550 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
551 x = (dc.font.ascent + dc.font.descent + 2) / 4;
555 r.width = r.height = x + 1;
556 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
559 r.width = r.height = x;
560 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
565 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
567 unsigned int len, olen;
568 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
571 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
572 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
576 len = MIN(olen, sizeof buf);
577 memcpy(buf, text, len);
579 h = dc.font.ascent + dc.font.descent;
580 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
582 /* shorten text if necessary */
583 for(; len && (w = textnw(buf, len)) > dc.w - h; len--);
594 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
596 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
598 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
602 emallocz(unsigned int size) {
603 void *res = calloc(1, size);
606 eprint("fatal: could not malloc() %u bytes\n", size);
611 enternotify(XEvent *e) {
613 XCrossingEvent *ev = &e->xcrossing;
615 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
617 if((c = getclient(ev->window)))
624 eprint(const char *errstr, ...) {
627 va_start(ap, errstr);
628 vfprintf(stderr, errstr, ap);
635 XExposeEvent *ev = &e->xexpose;
637 if(ev->count == 0 && (ev->window == barwin))
643 if(!c || (c && !isvisible(c)))
644 for(c = stack; c && !isvisible(c); c = c->snext);
645 if(sel && sel != c) {
646 grabbuttons(sel, False);
647 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
652 grabbuttons(c, True);
656 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
657 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
660 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
665 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
666 XFocusChangeEvent *ev = &e->xfocus;
668 if(sel && ev->window != sel->win)
669 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
673 focusnext(const char *arg) {
678 for(c = sel->next; c && !isvisible(c); c = c->next);
680 for(c = clients; c && !isvisible(c); c = c->next);
688 focusprev(const char *arg) {
693 for(c = sel->prev; c && !isvisible(c); c = c->prev);
695 for(c = clients; c && c->next; c = c->next);
696 for(; c && !isvisible(c); c = c->prev);
705 getclient(Window w) {
708 for(c = clients; c && c->win != w; c = c->next);
713 getcolor(const char *colstr) {
714 Colormap cmap = DefaultColormap(dpy, screen);
717 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
718 eprint("error, cannot allocate color '%s'\n", colstr);
726 unsigned char *p = NULL;
727 unsigned long n, extra;
730 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
731 &real, &format, &n, &extra, (unsigned char **)&p);
732 if(status != Success)
741 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
746 if(!text || size == 0)
749 XGetTextProperty(dpy, w, &name, atom);
752 if(name.encoding == XA_STRING)
753 strncpy(text, (char *)name.value, size - 1);
755 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
757 strncpy(text, *list, size - 1);
758 XFreeStringList(list);
761 text[size - 1] = '\0';
767 grabbuttons(Client *c, Bool focused) {
769 unsigned int buttons[] = { Button1, Button2, Button3 };
770 unsigned int modifiers[] = { MODKEY, MODKEY|LockMask, MODKEY|numlockmask,
771 MODKEY|numlockmask|LockMask} ;
773 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
775 for(i = 0; i < LENGTH(buttons); i++)
776 for(j = 0; j < LENGTH(modifiers); j++)
777 XGrabButton(dpy, buttons[i], modifiers[j], c->win, False,
778 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
780 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
781 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
788 XModifierKeymap *modmap;
790 /* init modifier map */
791 modmap = XGetModifierMapping(dpy);
792 for(i = 0; i < 8; i++)
793 for(j = 0; j < modmap->max_keypermod; j++) {
794 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
795 numlockmask = (1 << i);
797 XFreeModifiermap(modmap);
799 XUngrabKey(dpy, AnyKey, AnyModifier, root);
800 for(i = 0; i < LENGTH(keys); i++) {
801 code = XKeysymToKeycode(dpy, keys[i].keysym);
802 XGrabKey(dpy, code, keys[i].mod, root, True,
803 GrabModeAsync, GrabModeAsync);
804 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
805 GrabModeAsync, GrabModeAsync);
806 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
807 GrabModeAsync, GrabModeAsync);
808 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
809 GrabModeAsync, GrabModeAsync);
814 idxoftag(const char *t) {
817 for(i = 0; (i < LENGTH(tags)) && t && strcmp(tags[i], t); i++);
818 return (i < LENGTH(tags)) ? i : 0;
822 initfont(const char *fontstr) {
823 char *def, **missing;
828 XFreeFontSet(dpy, dc.font.set);
829 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
832 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
833 XFreeStringList(missing);
836 XFontSetExtents *font_extents;
837 XFontStruct **xfonts;
839 dc.font.ascent = dc.font.descent = 0;
840 font_extents = XExtentsOfFontSet(dc.font.set);
841 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
842 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
843 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
844 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
850 XFreeFont(dpy, dc.font.xfont);
851 dc.font.xfont = NULL;
852 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
853 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
854 eprint("error, cannot load font: '%s'\n", fontstr);
855 dc.font.ascent = dc.font.xfont->ascent;
856 dc.font.descent = dc.font.xfont->descent;
858 dc.font.height = dc.font.ascent + dc.font.descent;
862 isoccupied(unsigned int t) {
865 for(c = clients; c; c = c->next)
872 isprotodel(Client *c) {
877 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
878 for(i = 0; !ret && i < n; i++)
879 if(protocols[i] == wmatom[WMDelete])
887 isurgent(unsigned int t) {
890 for(c = clients; c; c = c->next)
891 if(c->isurgent && c->tags[t])
897 isvisible(Client *c) {
900 for(i = 0; i < LENGTH(tags); i++)
901 if(c->tags[i] && tagset[seltags][i])
907 keypress(XEvent *e) {
913 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
914 for(i = 0; i < LENGTH(keys); i++)
915 if(keysym == keys[i].keysym
916 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
919 keys[i].func(keys[i].arg);
924 killclient(const char *arg) {
929 if(isprotodel(sel)) {
930 ev.type = ClientMessage;
931 ev.xclient.window = sel->win;
932 ev.xclient.message_type = wmatom[WMProtocols];
933 ev.xclient.format = 32;
934 ev.xclient.data.l[0] = wmatom[WMDelete];
935 ev.xclient.data.l[1] = CurrentTime;
936 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
939 XKillClient(dpy, sel->win);
943 manage(Window w, XWindowAttributes *wa) {
944 Client *c, *t = NULL;
949 c = emallocz(sizeof(Client));
950 c->tags = emallocz(TAGSZ);
958 c->oldbw = wa->border_width;
959 if(c->w == sw && c->h == sh) {
962 c->bw = wa->border_width;
965 if(c->x + c->w + 2 * c->bw > sx + sw)
966 c->x = sx + sw - c->w - 2 * c->bw;
967 if(c->y + c->h + 2 * c->bw > sy + sh)
968 c->y = sy + sh - c->h - 2 * c->bw;
969 c->x = MAX(c->x, sx);
970 c->y = MAX(c->y, by == 0 ? bh : sy);
974 wc.border_width = c->bw;
975 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
976 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
977 configure(c); /* propagates border_width, if size doesn't change */
979 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
980 grabbuttons(c, False);
982 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
983 for(t = clients; t && t->win != trans; t = t->next);
985 memcpy(c->tags, t->tags, TAGSZ);
989 c->isfloating = (rettrans == Success) || c->isfixed;
992 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
994 XMapWindow(dpy, c->win);
995 setclientstate(c, NormalState);
1000 mappingnotify(XEvent *e) {
1001 XMappingEvent *ev = &e->xmapping;
1003 XRefreshKeyboardMapping(ev);
1004 if(ev->request == MappingKeyboard)
1009 maprequest(XEvent *e) {
1010 static XWindowAttributes wa;
1011 XMapRequestEvent *ev = &e->xmaprequest;
1013 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1015 if(wa.override_redirect)
1017 if(!getclient(ev->window))
1018 manage(ev->window, &wa);
1022 movemouse(Client *c) {
1023 int x1, y1, ocx, ocy, di, nx, ny;
1030 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1031 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1033 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1035 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1038 XUngrabPointer(dpy, CurrentTime);
1040 case ConfigureRequest:
1043 handler[ev.type](&ev);
1047 nx = ocx + (ev.xmotion.x - x1);
1048 ny = ocy + (ev.xmotion.y - y1);
1049 if(snap && nx >= wx && nx <= wx + ww
1050 && ny >= wy && ny <= wy + wh) {
1051 if(abs(wx - nx) < snap)
1053 else if(abs((wx + ww) - (nx + c->w + 2 * c->bw)) < snap)
1054 nx = wx + ww - c->w - 2 * c->bw;
1055 if(abs(wy - ny) < snap)
1057 else if(abs((wy + wh) - (ny + c->h + 2 * c->bw)) < snap)
1058 ny = wy + wh - c->h - 2 * c->bw;
1059 if(!c->isfloating && lt->arrange && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
1060 togglefloating(NULL);
1062 if(!lt->arrange || c->isfloating)
1063 resize(c, nx, ny, c->w, c->h, False);
1070 nextunfloating(Client *c) {
1071 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1076 propertynotify(XEvent *e) {
1079 XPropertyEvent *ev = &e->xproperty;
1081 if(ev->state == PropertyDelete)
1082 return; /* ignore */
1083 if((c = getclient(ev->window))) {
1086 case XA_WM_TRANSIENT_FOR:
1087 XGetTransientForHint(dpy, c->win, &trans);
1088 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1091 case XA_WM_NORMAL_HINTS:
1099 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1108 quit(const char *arg) {
1109 readin = running = False;
1113 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1117 /* set minimum possible */
1121 /* temporarily remove base dimensions */
1125 /* adjust for aspect limits */
1126 if(c->minax != c->maxax && c->minay != c->maxay
1127 && c->minax > 0 && c->maxax > 0 && c->minay > 0 && c->maxay > 0) {
1128 if(w * c->maxay > h * c->maxax)
1129 w = h * c->maxax / c->maxay;
1130 else if(w * c->minay < h * c->minax)
1131 h = w * c->minay / c->minax;
1134 /* adjust for increment value */
1140 /* restore base dimensions */
1144 w = MAX(w, c->minw);
1145 h = MAX(h, c->minh);
1148 w = MIN(w, c->maxw);
1151 h = MIN(h, c->maxh);
1153 if(w <= 0 || h <= 0)
1156 x = sw - w - 2 * c->bw;
1158 y = sh - h - 2 * c->bw;
1159 if(x + w + 2 * c->bw < sx)
1161 if(y + h + 2 * c->bw < sy)
1163 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1166 c->w = wc.width = w;
1167 c->h = wc.height = h;
1168 wc.border_width = c->bw;
1169 XConfigureWindow(dpy, c->win,
1170 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1177 resizemouse(Client *c) {
1184 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1185 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1187 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1189 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1192 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1193 c->w + c->bw - 1, c->h + c->bw - 1);
1194 XUngrabPointer(dpy, CurrentTime);
1195 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1197 case ConfigureRequest:
1200 handler[ev.type](&ev);
1204 nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1205 nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1207 if(snap && nw >= wx && nw <= wx + ww
1208 && nh >= wy && nh <= wy + wh) {
1209 if(!c->isfloating && lt->arrange
1210 && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1211 togglefloating(NULL);
1213 if(!lt->arrange || c->isfloating)
1214 resize(c, c->x, c->y, nw, nh, True);
1229 if(sel->isfloating || !lt->arrange)
1230 XRaiseWindow(dpy, sel->win);
1232 wc.stack_mode = Below;
1233 wc.sibling = barwin;
1234 for(c = stack; c; c = c->snext)
1235 if(!c->isfloating && isvisible(c)) {
1236 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1237 wc.sibling = c->win;
1241 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1247 char sbuf[sizeof stext];
1250 unsigned int len, offset;
1253 /* main event loop, also reads status text from stdin */
1255 xfd = ConnectionNumber(dpy);
1258 len = sizeof stext - 1;
1259 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1263 FD_SET(STDIN_FILENO, &rd);
1265 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1268 eprint("select failed\n");
1270 if(FD_ISSET(STDIN_FILENO, &rd)) {
1271 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1273 strncpy(stext, strerror(errno), len);
1277 strncpy(stext, "EOF", 4);
1281 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1282 if(*p == '\n' || *p == '\0') {
1284 strncpy(stext, sbuf, len);
1285 p += r - 1; /* p is sbuf + offset + r - 1 */
1286 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1289 memmove(sbuf, p - r + 1, r);
1296 while(XPending(dpy)) {
1297 XNextEvent(dpy, &ev);
1298 if(handler[ev.type])
1299 (handler[ev.type])(&ev); /* call handler */
1306 unsigned int i, num;
1307 Window *wins, d1, d2;
1308 XWindowAttributes wa;
1311 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1312 for(i = 0; i < num; i++) {
1313 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1314 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1316 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1317 manage(wins[i], &wa);
1319 for(i = 0; i < num; i++) { /* now the transients */
1320 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1322 if(XGetTransientForHint(dpy, wins[i], &d1)
1323 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1324 manage(wins[i], &wa);
1332 setclientstate(Client *c, long state) {
1333 long data[] = {state, None};
1335 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1336 PropModeReplace, (unsigned char *)data, 2);
1340 setmfact(const char *arg) {
1343 if(!arg || lt->arrange != tile)
1346 d = strtod(arg, NULL);
1347 if(arg[0] == '-' || arg[0] == '+')
1349 if(d < 0.1 || d > 0.9)
1360 XSetWindowAttributes wa;
1363 screen = DefaultScreen(dpy);
1364 root = RootWindow(dpy, screen);
1368 sw = DisplayWidth(dpy, screen);
1369 sh = DisplayHeight(dpy, screen);
1370 bh = dc.font.height + 2;
1374 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1375 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1376 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1377 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1378 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1379 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1382 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1383 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1384 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1386 /* init appearance */
1387 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1388 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1389 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1390 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1391 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1392 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1395 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1396 dc.gc = XCreateGC(dpy, root, 0, 0);
1397 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1399 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1402 tagset[0] = emallocz(TAGSZ);
1403 tagset[1] = emallocz(TAGSZ);
1404 tagset[0][0] = tagset[1][0] = True;
1407 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1408 w = textw(layouts[i].symbol);
1412 wa.override_redirect = 1;
1413 wa.background_pixmap = ParentRelative;
1414 wa.event_mask = ButtonPressMask|ExposureMask;
1416 barwin = XCreateWindow(dpy, root, bx, by, bw, bh, 0, DefaultDepth(dpy, screen),
1417 CopyFromParent, DefaultVisual(dpy, screen),
1418 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1419 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1420 XMapRaised(dpy, barwin);
1421 strcpy(stext, "dwm-"VERSION);
1424 /* EWMH support per view */
1425 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1426 PropModeReplace, (unsigned char *) netatom, NetLast);
1428 /* select for events */
1429 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1430 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1431 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1432 XSelectInput(dpy, root, wa.event_mask);
1440 spawn(const char *arg) {
1441 static char *shell = NULL;
1443 if(!shell && !(shell = getenv("SHELL")))
1447 /* The double-fork construct avoids zombie processes and keeps the code
1448 * clean from stupid signal handlers. */
1452 close(ConnectionNumber(dpy));
1454 execl(shell, shell, "-c", arg, (char *)NULL);
1455 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1464 tag(const char *arg) {
1469 for(i = 0; i < LENGTH(tags); i++)
1470 sel->tags[i] = (arg == NULL);
1471 sel->tags[idxoftag(arg)] = True;
1476 textnw(const char *text, unsigned int len) {
1480 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1483 return XTextWidth(dc.font.xfont, text, len);
1487 textw(const char *text) {
1488 return textnw(text, strlen(text)) + dc.font.height;
1497 for(n = 0, c = nextunfloating(clients); c; c = nextunfloating(c->next), n++);
1502 c = nextunfloating(clients);
1505 tileresize(c, wx, wy, ww - 2 * c->bw, wh - 2 * c->bw);
1507 tileresize(c, mx, my, mw - 2 * c->bw, mh - 2 * c->bw);
1513 x = (tx > c->x + c->w) ? c->x + c->w + 2 * c->bw : tw;
1515 w = (tx > c->x + c->w) ? wx + ww - x : tw;
1520 for(i = 0, c = nextunfloating(c->next); c; c = nextunfloating(c->next), i++) {
1521 if(i + 1 == n) /* remainder */
1522 tileresize(c, x, y, w - 2 * c->bw, (ty + th) - y - 2 * c->bw);
1524 tileresize(c, x, y, w - 2 * c->bw, h - 2 * c->bw);
1526 y = c->y + c->h + 2 * c->bw;
1531 tileresize(Client *c, int x, int y, int w, int h) {
1532 resize(c, x, y, w, h, resizehints);
1533 if(resizehints && ((c->h < bh) || (c->h > h) || (c->w < bh) || (c->w > w)))
1534 /* client doesn't accept size constraints */
1535 resize(c, x, y, w, h, False);
1539 togglebar(const char *arg) {
1547 togglefloating(const char *arg) {
1550 sel->isfloating = !sel->isfloating;
1552 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1557 togglelayout(const char *arg) {
1561 if(++lt == &layouts[LENGTH(layouts)])
1565 for(i = 0; i < LENGTH(layouts); i++)
1566 if(!strcmp(arg, layouts[i].symbol))
1568 if(i == LENGTH(layouts))
1579 toggletag(const char *arg) {
1585 sel->tags[i] = !sel->tags[i];
1586 for(j = 0; j < LENGTH(tags) && !sel->tags[j]; j++);
1587 if(j == LENGTH(tags))
1588 sel->tags[i] = True; /* at least one tag must be enabled */
1593 toggleview(const char *arg) {
1597 tagset[seltags][i] = !tagset[seltags][i];
1598 for(j = 0; j < LENGTH(tags) && !tagset[seltags][j]; j++);
1599 if(j == LENGTH(tags))
1600 tagset[seltags][i] = True; /* at least one tag must be viewed */
1608 XMoveWindow(dpy, c->win, c->x, c->y);
1609 c->isbanned = False;
1613 unmanage(Client *c) {
1616 wc.border_width = c->oldbw;
1617 /* The server grab construct avoids race conditions. */
1619 XSetErrorHandler(xerrordummy);
1620 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1625 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1626 setclientstate(c, WithdrawnState);
1630 XSetErrorHandler(xerror);
1636 unmapnotify(XEvent *e) {
1638 XUnmapEvent *ev = &e->xunmap;
1640 if((c = getclient(ev->window)))
1646 if(dc.drawable != 0)
1647 XFreePixmap(dpy, dc.drawable);
1648 dc.drawable = XCreatePixmap(dpy, root, bw, bh, DefaultDepth(dpy, screen));
1649 XMoveResizeWindow(dpy, barwin, bx, by, bw, bh);
1656 XineramaScreenInfo *info = NULL;
1658 /* window area geometry */
1659 if(XineramaIsActive(dpy)) {
1660 info = XineramaQueryScreens(dpy, &i);
1662 wy = showbar && topbar ? info[0].y_org + bh : info[0].y_org;
1664 wh = showbar ? info[0].height - bh : info[0].height;
1671 wy = showbar && topbar ? sy + bh : sy;
1673 wh = showbar ? sh - bh : sh;
1678 by = showbar ? (topbar ? 0 : wy + wh) : -bh;
1681 /* update layout geometries */
1682 for(i = 0; i < LENGTH(layouts); i++)
1683 if(layouts[i].updategeom)
1684 layouts[i].updategeom();
1688 updatesizehints(Client *c) {
1692 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1694 c->flags = size.flags;
1695 if(c->flags & PBaseSize) {
1696 c->basew = size.base_width;
1697 c->baseh = size.base_height;
1699 else if(c->flags & PMinSize) {
1700 c->basew = size.min_width;
1701 c->baseh = size.min_height;
1704 c->basew = c->baseh = 0;
1705 if(c->flags & PResizeInc) {
1706 c->incw = size.width_inc;
1707 c->inch = size.height_inc;
1710 c->incw = c->inch = 0;
1711 if(c->flags & PMaxSize) {
1712 c->maxw = size.max_width;
1713 c->maxh = size.max_height;
1716 c->maxw = c->maxh = 0;
1717 if(c->flags & PMinSize) {
1718 c->minw = size.min_width;
1719 c->minh = size.min_height;
1721 else if(c->flags & PBaseSize) {
1722 c->minw = size.base_width;
1723 c->minh = size.base_height;
1726 c->minw = c->minh = 0;
1727 if(c->flags & PAspect) {
1728 c->minax = size.min_aspect.x;
1729 c->maxax = size.max_aspect.x;
1730 c->minay = size.min_aspect.y;
1731 c->maxay = size.max_aspect.y;
1734 c->minax = c->maxax = c->minay = c->maxay = 0;
1735 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1736 && c->maxw == c->minw && c->maxh == c->minh);
1740 updatetilegeom(void) {
1741 /* master area geometry */
1747 /* tile area geometry */
1755 updatetitle(Client *c) {
1756 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1757 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1761 updatewmhints(Client *c) {
1764 if((wmh = XGetWMHints(dpy, c->win))) {
1766 sel->isurgent = False;
1768 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1774 view(const char *arg) {
1775 seltags ^= 1; /* toggle sel tagset */
1776 memset(tagset[seltags], (NULL == arg), TAGSZ);
1777 tagset[seltags][idxoftag(arg)] = True;
1782 viewprevtag(const char *arg) {
1783 seltags ^= 1; /* toggle sel tagset */
1787 /* There's no way to check accesses to destroyed windows, thus those cases are
1788 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1789 * default error handler, which may call exit. */
1791 xerror(Display *dpy, XErrorEvent *ee) {
1792 if(ee->error_code == BadWindow
1793 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1794 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1795 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1796 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1797 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1798 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1799 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1800 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1802 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1803 ee->request_code, ee->error_code);
1804 return xerrorxlib(dpy, ee); /* may call exit */
1808 xerrordummy(Display *dpy, XErrorEvent *ee) {
1812 /* Startup Error handler to check if another window manager
1813 * is already running. */
1815 xerrorstart(Display *dpy, XErrorEvent *ee) {
1821 zoom(const char *arg) {
1824 if(c == nextunfloating(clients))
1825 if(!c || !(c = nextunfloating(c->next)))
1827 if(lt->arrange == tile && !sel->isfloating) {
1836 main(int argc, char *argv[]) {
1837 if(argc == 2 && !strcmp("-v", argv[1]))
1838 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1840 eprint("usage: dwm [-v]\n");
1842 setlocale(LC_CTYPE, "");
1843 if(!(dpy = XOpenDisplay(0)))
1844 eprint("dwm: cannot open display\n");