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 VISIBLE(x) ((x)->tags & tagset[seltags])
58 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
59 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
60 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
61 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
64 typedef unsigned int uint;
65 typedef unsigned long ulong;
66 typedef struct Client Client;
70 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
71 int minax, maxax, minay, maxay;
74 Bool isbanned, isfixed, isfloating, ismax, isurgent;
95 } DC; /* draw context */
100 void (*func)(const void *arg);
106 void (*arrange)(void);
107 void (*updategeom)(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);
172 uint textw(const char *text);
174 void tileresize(Client *c, int x, int y, int w, int h);
175 void togglebar(const void *arg);
176 void togglefloating(const void *arg);
177 void togglelayout(const void *arg);
178 void togglemax(const void *arg);
179 void toggletag(const void *arg);
180 void toggleview(const void *arg);
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 void *arg);
190 void viewprevtag(const void *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 void *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 uint 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];
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 /* compile-time check if all tags fit into an uint bit array. */
237 struct NumTags { char limitexceeded[sizeof(uint) * 8 < LENGTH(tags) ? -1 : 1]; };
239 /* function implementations */
241 applyrules(Client *c) {
244 XClassHint ch = { 0 };
247 XGetClassHint(dpy, c->win, &ch);
248 for(i = 0; i < LENGTH(rules); i++) {
250 if((!r->title || strstr(c->name, r->title))
251 && (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
252 && (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
253 c->isfloating = r->isfloating;
254 c->tags |= r->tags & TAGMASK;
262 c->tags = tagset[seltags];
269 for(c = clients; c; c = c->next)
271 if(!lt->arrange || c->isfloating)
272 resize(c, c->x, c->y, c->w, c->h, True);
274 else if(!c->isbanned) {
275 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
280 if(lt->arrange && !domax)
294 attachstack(Client *c) {
300 buttonpress(XEvent *e) {
303 XButtonPressedEvent *ev = &e->xbutton;
305 if(ev->window == barwin) {
307 for(i = 0; i < LENGTH(tags); i++) {
311 if(ev->button == Button1) {
312 if(ev->state & MODKEY)
317 else if(ev->button == Button3) {
318 if(ev->state & MODKEY)
326 if(ev->x < x + blw) {
327 if(ev->button == Button1)
329 else if(ev->button == Button3)
333 else if((c = getclient(ev->window))) {
335 if(CLEANMASK(ev->state) != MODKEY || domax)
337 if(ev->button == Button1)
339 else if(ev->button == Button2)
340 togglefloating(NULL);
341 else if(ev->button == Button3 && !c->isfixed)
349 XSetErrorHandler(xerrorstart);
351 /* this causes an error if some other window manager is running */
352 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
355 eprint("dwm: another window manager is already running\n");
357 XSetErrorHandler(NULL);
358 xerrorxlib = XSetErrorHandler(xerror);
369 XFreeFontSet(dpy, dc.font.set);
371 XFreeFont(dpy, dc.font.xfont);
372 XUngrabKey(dpy, AnyKey, AnyModifier, root);
373 XFreePixmap(dpy, dc.drawable);
375 XFreeCursor(dpy, cursor[CurNormal]);
376 XFreeCursor(dpy, cursor[CurResize]);
377 XFreeCursor(dpy, cursor[CurMove]);
378 XDestroyWindow(dpy, barwin);
380 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
384 configure(Client *c) {
387 ce.type = ConfigureNotify;
395 ce.border_width = c->bw;
397 ce.override_redirect = False;
398 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
402 configurenotify(XEvent *e) {
403 XConfigureEvent *ev = &e->xconfigure;
405 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
415 configurerequest(XEvent *e) {
417 XConfigureRequestEvent *ev = &e->xconfigurerequest;
420 if((c = getclient(ev->window))) {
421 if(ev->value_mask & CWBorderWidth)
422 c->bw = ev->border_width;
423 if(c->isfixed || c->isfloating || !lt->arrange) {
424 if(ev->value_mask & CWX)
426 if(ev->value_mask & CWY)
428 if(ev->value_mask & CWWidth)
430 if(ev->value_mask & CWHeight)
432 if((c->x - sx + c->w) > sw && c->isfloating)
433 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
434 if((c->y - sy + c->h) > sh && c->isfloating)
435 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
436 if((ev->value_mask & (CWX|CWY))
437 && !(ev->value_mask & (CWWidth|CWHeight)))
440 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
448 wc.width = ev->width;
449 wc.height = ev->height;
450 wc.border_width = ev->border_width;
451 wc.sibling = ev->above;
452 wc.stack_mode = ev->detail;
453 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
459 destroynotify(XEvent *e) {
461 XDestroyWindowEvent *ev = &e->xdestroywindow;
463 if((c = getclient(ev->window)))
470 c->prev->next = c->next;
472 c->next->prev = c->prev;
475 c->next = c->prev = NULL;
479 detachstack(Client *c) {
482 for(tc = &stack; *tc && *tc != c; tc = &(*tc)->snext);
492 for(c = stack; c && !VISIBLE(c); c = c->snext);
493 for(i = 0; i < LENGTH(tags); i++) {
494 dc.w = textw(tags[i]);
495 if(tagset[seltags] & 1 << i) {
496 drawtext(tags[i], dc.sel, isurgent(i));
497 drawsquare(c && c->tags & 1 << i, isoccupied(i), isurgent(i), dc.sel);
500 drawtext(tags[i], dc.norm, isurgent(i));
501 drawsquare(c && c->tags & 1 << i, isoccupied(i), isurgent(i), dc.norm);
507 drawtext(lt->symbol, dc.norm, domax);
518 drawtext(stext, dc.norm, False);
519 if((dc.w = dc.x - x) > bh) {
522 drawtext(c->name, dc.sel, False);
523 drawsquare(False, c->isfloating, False, dc.sel);
526 drawtext(NULL, dc.norm, False);
528 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, bw, bh, 0, 0);
533 drawsquare(Bool filled, Bool empty, Bool invert, ulong col[ColLast]) {
536 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
538 gcv.foreground = col[invert ? ColBG : ColFG];
539 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
540 x = (dc.font.ascent + dc.font.descent + 2) / 4;
544 r.width = r.height = x + 1;
545 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
548 r.width = r.height = x;
549 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
554 drawtext(const char *text, ulong col[ColLast], Bool invert) {
557 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
560 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
561 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
565 len = MIN(olen, sizeof buf);
566 memcpy(buf, text, len);
568 h = dc.font.ascent + dc.font.descent;
569 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
571 /* shorten text if necessary */
572 for(; len && (w = textnw(buf, len)) > dc.w - h; len--);
583 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
585 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
587 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
591 enternotify(XEvent *e) {
593 XCrossingEvent *ev = &e->xcrossing;
595 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
597 if((c = getclient(ev->window)))
604 eprint(const char *errstr, ...) {
607 va_start(ap, errstr);
608 vfprintf(stderr, errstr, ap);
615 XExposeEvent *ev = &e->xexpose;
617 if(ev->count == 0 && (ev->window == barwin))
623 if(!c || (c && !VISIBLE(c)))
624 for(c = stack; c && !VISIBLE(c); c = c->snext);
625 if(sel && sel != c) {
626 grabbuttons(sel, False);
627 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
632 grabbuttons(c, True);
637 XMoveResizeWindow(dpy, c->win, wx, wy, ww - 2 * c->bw, wh - 2 * c->bw);
640 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
641 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
644 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
649 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
650 XFocusChangeEvent *ev = &e->xfocus;
652 if(sel && ev->window != sel->win)
653 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
657 focusnext(const void *arg) {
662 for(c = sel->next; c && !VISIBLE(c); c = c->next);
664 for(c = clients; c && !VISIBLE(c); c = c->next);
672 focusprev(const void *arg) {
677 for(c = sel->prev; c && !VISIBLE(c); c = c->prev);
679 for(c = clients; c && c->next; c = c->next);
680 for(; c && !VISIBLE(c); c = c->prev);
689 getclient(Window w) {
692 for(c = clients; c && c->win != w; c = c->next);
697 getcolor(const char *colstr) {
698 Colormap cmap = DefaultColormap(dpy, screen);
701 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
702 eprint("error, cannot allocate color '%s'\n", colstr);
710 unsigned char *p = NULL;
714 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
715 &real, &format, &n, &extra, (unsigned char **)&p);
716 if(status != Success)
725 gettextprop(Window w, Atom atom, char *text, uint size) {
730 if(!text || size == 0)
733 XGetTextProperty(dpy, w, &name, atom);
736 if(name.encoding == XA_STRING)
737 strncpy(text, (char *)name.value, size - 1);
739 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
741 strncpy(text, *list, size - 1);
742 XFreeStringList(list);
745 text[size - 1] = '\0';
751 grabbuttons(Client *c, Bool focused) {
753 uint buttons[] = { Button1, Button2, Button3 };
754 uint modifiers[] = { MODKEY, MODKEY|LockMask, MODKEY|numlockmask,
755 MODKEY|numlockmask|LockMask} ;
757 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
759 for(i = 0; i < LENGTH(buttons); i++)
760 for(j = 0; j < LENGTH(modifiers); j++)
761 XGrabButton(dpy, buttons[i], modifiers[j], c->win, False,
762 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
764 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
765 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
772 XModifierKeymap *modmap;
774 /* init modifier map */
775 modmap = XGetModifierMapping(dpy);
776 for(i = 0; i < 8; i++)
777 for(j = 0; j < modmap->max_keypermod; j++) {
778 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
779 numlockmask = (1 << i);
781 XFreeModifiermap(modmap);
783 XUngrabKey(dpy, AnyKey, AnyModifier, root);
784 for(i = 0; i < LENGTH(keys); i++) {
785 code = XKeysymToKeycode(dpy, keys[i].keysym);
786 XGrabKey(dpy, code, keys[i].mod, root, True,
787 GrabModeAsync, GrabModeAsync);
788 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
789 GrabModeAsync, GrabModeAsync);
790 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
791 GrabModeAsync, GrabModeAsync);
792 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
793 GrabModeAsync, GrabModeAsync);
798 initfont(const char *fontstr) {
799 char *def, **missing;
804 XFreeFontSet(dpy, dc.font.set);
805 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
808 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
809 XFreeStringList(missing);
812 XFontSetExtents *font_extents;
813 XFontStruct **xfonts;
815 dc.font.ascent = dc.font.descent = 0;
816 font_extents = XExtentsOfFontSet(dc.font.set);
817 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
818 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
819 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
820 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
826 XFreeFont(dpy, dc.font.xfont);
827 dc.font.xfont = NULL;
828 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
829 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
830 eprint("error, cannot load font: '%s'\n", fontstr);
831 dc.font.ascent = dc.font.xfont->ascent;
832 dc.font.descent = dc.font.xfont->descent;
834 dc.font.height = dc.font.ascent + dc.font.descent;
841 for(c = clients; c; c = c->next)
848 isprotodel(Client *c) {
853 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
854 for(i = 0; !ret && i < n; i++)
855 if(protocols[i] == wmatom[WMDelete])
866 for(c = clients; c; c = c->next)
867 if(c->isurgent && c->tags & 1 << t)
873 keypress(XEvent *e) {
879 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
880 for(i = 0; i < LENGTH(keys); i++)
881 if(keysym == keys[i].keysym
882 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
885 keys[i].func(keys[i].arg);
890 killclient(const void *arg) {
895 if(isprotodel(sel)) {
896 ev.type = ClientMessage;
897 ev.xclient.window = sel->win;
898 ev.xclient.message_type = wmatom[WMProtocols];
899 ev.xclient.format = 32;
900 ev.xclient.data.l[0] = wmatom[WMDelete];
901 ev.xclient.data.l[1] = CurrentTime;
902 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
905 XKillClient(dpy, sel->win);
909 manage(Window w, XWindowAttributes *wa) {
910 Client *c, *t = NULL;
915 if(!(c = calloc(1, sizeof(Client))))
916 eprint("fatal: could not calloc() %u bytes\n", sizeof(Client));
924 c->oldbw = wa->border_width;
925 if(c->w == sw && c->h == sh) {
928 c->bw = wa->border_width;
931 if(c->x + c->w + 2 * c->bw > sx + sw)
932 c->x = sx + sw - c->w - 2 * c->bw;
933 if(c->y + c->h + 2 * c->bw > sy + sh)
934 c->y = sy + sh - c->h - 2 * c->bw;
935 c->x = MAX(c->x, sx);
936 c->y = MAX(c->y, by == 0 ? bh : sy);
940 wc.border_width = c->bw;
941 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
942 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
943 configure(c); /* propagates border_width, if size doesn't change */
945 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
946 grabbuttons(c, False);
948 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
949 for(t = clients; t && t->win != trans; t = t->next);
955 c->isfloating = (rettrans == Success) || c->isfixed;
958 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
959 XMapWindow(dpy, c->win);
960 setclientstate(c, NormalState);
965 mappingnotify(XEvent *e) {
966 XMappingEvent *ev = &e->xmapping;
968 XRefreshKeyboardMapping(ev);
969 if(ev->request == MappingKeyboard)
974 maprequest(XEvent *e) {
975 static XWindowAttributes wa;
976 XMapRequestEvent *ev = &e->xmaprequest;
978 if(!XGetWindowAttributes(dpy, ev->window, &wa))
980 if(wa.override_redirect)
982 if(!getclient(ev->window))
983 manage(ev->window, &wa);
987 movemouse(Client *c) {
988 int x1, y1, ocx, ocy, di, nx, ny;
996 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
997 None, cursor[CurMove], CurrentTime) != GrabSuccess)
999 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1001 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1004 XUngrabPointer(dpy, CurrentTime);
1006 case ConfigureRequest:
1009 handler[ev.type](&ev);
1013 nx = ocx + (ev.xmotion.x - x1);
1014 ny = ocy + (ev.xmotion.y - y1);
1015 if(snap && nx >= wx && nx <= wx + ww
1016 && ny >= wy && ny <= wy + wh) {
1017 if(abs(wx - nx) < snap)
1019 else if(abs((wx + ww) - (nx + c->w + 2 * c->bw)) < snap)
1020 nx = wx + ww - c->w - 2 * c->bw;
1021 if(abs(wy - ny) < snap)
1023 else if(abs((wy + wh) - (ny + c->h + 2 * c->bw)) < snap)
1024 ny = wy + wh - c->h - 2 * c->bw;
1025 if(!c->isfloating && lt->arrange && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
1026 togglefloating(NULL);
1028 if(!lt->arrange || c->isfloating)
1029 resize(c, nx, ny, c->w, c->h, False);
1036 nexttiled(Client *c) {
1037 for(; c && (c->isfloating || !VISIBLE(c)); c = c->next);
1042 propertynotify(XEvent *e) {
1045 XPropertyEvent *ev = &e->xproperty;
1047 if(ev->state == PropertyDelete)
1048 return; /* ignore */
1049 if((c = getclient(ev->window))) {
1052 case XA_WM_TRANSIENT_FOR:
1053 XGetTransientForHint(dpy, c->win, &trans);
1054 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1057 case XA_WM_NORMAL_HINTS:
1065 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1074 quit(const void *arg) {
1075 readin = running = False;
1079 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1083 /* set minimum possible */
1087 /* temporarily remove base dimensions */
1091 /* adjust for aspect limits */
1092 if(c->minax != c->maxax && c->minay != c->maxay
1093 && c->minax > 0 && c->maxax > 0 && c->minay > 0 && c->maxay > 0) {
1094 if(w * c->maxay > h * c->maxax)
1095 w = h * c->maxax / c->maxay;
1096 else if(w * c->minay < h * c->minax)
1097 h = w * c->minay / c->minax;
1100 /* adjust for increment value */
1106 /* restore base dimensions */
1110 w = MAX(w, c->minw);
1111 h = MAX(h, c->minh);
1114 w = MIN(w, c->maxw);
1117 h = MIN(h, c->maxh);
1119 if(w <= 0 || h <= 0)
1122 x = sw - w - 2 * c->bw;
1124 y = sh - h - 2 * c->bw;
1125 if(x + w + 2 * c->bw < sx)
1127 if(y + h + 2 * c->bw < sy)
1129 if(c->x != x || c->y != y || c->w != w || c->h != h || c->isbanned || c->ismax) {
1130 c->isbanned = c->ismax = False;
1133 c->w = wc.width = w;
1134 c->h = wc.height = h;
1135 wc.border_width = c->bw;
1136 XConfigureWindow(dpy, c->win,
1137 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1144 resizemouse(Client *c) {
1152 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1153 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1155 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1157 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1160 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1161 c->w + c->bw - 1, c->h + c->bw - 1);
1162 XUngrabPointer(dpy, CurrentTime);
1163 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1165 case ConfigureRequest:
1168 handler[ev.type](&ev);
1172 nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1173 nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1175 if(snap && nw >= wx && nw <= wx + ww
1176 && nh >= wy && nh <= wy + wh) {
1177 if(!c->isfloating && lt->arrange
1178 && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1179 togglefloating(NULL);
1181 if(!lt->arrange || c->isfloating)
1182 resize(c, c->x, c->y, nw, nh, True);
1197 if(domax || sel->isfloating || !lt->arrange)
1198 XRaiseWindow(dpy, sel->win);
1199 if(!domax && lt->arrange) {
1200 wc.stack_mode = Below;
1201 wc.sibling = barwin;
1202 for(c = stack; c; c = c->snext)
1203 if(!c->isfloating && VISIBLE(c)) {
1204 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1205 wc.sibling = c->win;
1209 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1215 char sbuf[sizeof stext];
1221 /* main event loop, also reads status text from stdin */
1223 xfd = ConnectionNumber(dpy);
1226 len = sizeof stext - 1;
1227 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1231 FD_SET(STDIN_FILENO, &rd);
1233 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1236 eprint("select failed\n");
1238 if(FD_ISSET(STDIN_FILENO, &rd)) {
1239 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1241 strncpy(stext, strerror(errno), len);
1245 strncpy(stext, "EOF", 4);
1249 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1250 if(*p == '\n' || *p == '\0') {
1252 strncpy(stext, sbuf, len);
1253 p += r - 1; /* p is sbuf + offset + r - 1 */
1254 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1257 memmove(sbuf, p - r + 1, r);
1264 while(XPending(dpy)) {
1265 XNextEvent(dpy, &ev);
1266 if(handler[ev.type])
1267 (handler[ev.type])(&ev); /* call handler */
1275 Window *wins, d1, d2;
1276 XWindowAttributes wa;
1279 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1280 for(i = 0; i < num; i++) {
1281 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1282 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1284 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1285 manage(wins[i], &wa);
1287 for(i = 0; i < num; i++) { /* now the transients */
1288 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1290 if(XGetTransientForHint(dpy, wins[i], &d1)
1291 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1292 manage(wins[i], &wa);
1300 setclientstate(Client *c, long state) {
1301 long data[] = {state, None};
1303 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1304 PropModeReplace, (unsigned char *)data, 2);
1307 /* arg > 1.0 will set mfact absolutly */
1309 setmfact(const void *arg) {
1310 double d = *((double*) arg);
1312 if(!d || lt->arrange != tile)
1314 d = d < 1.0 ? d + mfact : d - 1.0;
1315 if(d < 0.1 || d > 0.9)
1325 XSetWindowAttributes wa;
1328 screen = DefaultScreen(dpy);
1329 root = RootWindow(dpy, screen);
1333 sw = DisplayWidth(dpy, screen);
1334 sh = DisplayHeight(dpy, screen);
1335 bh = dc.font.height + 2;
1339 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1340 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1341 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1342 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1343 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1344 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1347 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1348 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1349 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1351 /* init appearance */
1352 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1353 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1354 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1355 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1356 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1357 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1360 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1361 dc.gc = XCreateGC(dpy, root, 0, 0);
1362 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1364 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1367 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1368 w = textw(layouts[i].symbol);
1372 wa.override_redirect = 1;
1373 wa.background_pixmap = ParentRelative;
1374 wa.event_mask = ButtonPressMask|ExposureMask;
1376 barwin = XCreateWindow(dpy, root, bx, by, bw, bh, 0, DefaultDepth(dpy, screen),
1377 CopyFromParent, DefaultVisual(dpy, screen),
1378 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1379 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1380 XMapRaised(dpy, barwin);
1381 strcpy(stext, "dwm-"VERSION);
1384 /* EWMH support per view */
1385 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1386 PropModeReplace, (unsigned char *) netatom, NetLast);
1388 /* select for events */
1389 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1390 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1391 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1392 XSelectInput(dpy, root, wa.event_mask);
1400 spawn(const void *arg) {
1401 static char *shell = NULL;
1403 if(!shell && !(shell = getenv("SHELL")))
1405 /* The double-fork construct avoids zombie processes and keeps the code
1406 * clean from stupid signal handlers. */
1410 close(ConnectionNumber(dpy));
1412 execl(shell, shell, "-c", (char *)arg, (char *)NULL);
1413 fprintf(stderr, "dwm: execl '%s -c %s'", shell, (char *)arg);
1422 tag(const void *arg) {
1423 if(sel && *(int *)arg & TAGMASK) {
1424 sel->tags = *(int *)arg & TAGMASK;
1430 textnw(const char *text, uint len) {
1434 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1437 return XTextWidth(dc.font.xfont, text, len);
1441 textw(const char *text) {
1442 return textnw(text, strlen(text)) + dc.font.height;
1451 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next), n++);
1456 c = nexttiled(clients);
1459 tileresize(c, wx, wy, ww - 2 * c->bw, wh - 2 * c->bw);
1461 tileresize(c, mx, my, mw - 2 * c->bw, mh - 2 * c->bw);
1467 x = (tx > c->x + c->w) ? c->x + c->w + 2 * c->bw : tw;
1469 w = (tx > c->x + c->w) ? wx + ww - x : tw;
1474 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1475 if(i + 1 == n) /* remainder */
1476 tileresize(c, x, y, w - 2 * c->bw, (ty + th) - y - 2 * c->bw);
1478 tileresize(c, x, y, w - 2 * c->bw, h - 2 * c->bw);
1480 y = c->y + c->h + 2 * c->bw;
1485 tileresize(Client *c, int x, int y, int w, int h) {
1486 resize(c, x, y, w, h, resizehints);
1487 if(resizehints && ((c->h < bh) || (c->h > h) || (c->w < bh) || (c->w > w)))
1488 /* client doesn't accept size constraints */
1489 resize(c, x, y, w, h, False);
1493 togglebar(const void *arg) {
1501 togglefloating(const void *arg) {
1504 sel->isfloating = !sel->isfloating;
1506 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1511 togglelayout(const void *arg) {
1515 if(++lt == &layouts[LENGTH(layouts)])
1519 for(i = 0; i < LENGTH(layouts); i++)
1520 if(!strcmp((char *)arg, layouts[i].symbol))
1522 if(i == LENGTH(layouts))
1533 togglemax(const void *arg) {
1539 toggletag(const void *arg) {
1540 if(sel && (sel->tags ^ ((*(int *)arg) & TAGMASK))) {
1541 sel->tags ^= (*(int *)arg) & TAGMASK;
1547 toggleview(const void *arg) {
1548 if((tagset[seltags] ^ ((*(int *)arg) & TAGMASK))) {
1549 tagset[seltags] ^= (*(int *)arg) & TAGMASK;
1555 unmanage(Client *c) {
1558 wc.border_width = c->oldbw;
1559 /* The server grab construct avoids race conditions. */
1561 XSetErrorHandler(xerrordummy);
1562 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1567 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1568 setclientstate(c, WithdrawnState);
1571 XSetErrorHandler(xerror);
1577 unmapnotify(XEvent *e) {
1579 XUnmapEvent *ev = &e->xunmap;
1581 if((c = getclient(ev->window)))
1587 if(dc.drawable != 0)
1588 XFreePixmap(dpy, dc.drawable);
1589 dc.drawable = XCreatePixmap(dpy, root, bw, bh, DefaultDepth(dpy, screen));
1590 XMoveResizeWindow(dpy, barwin, bx, by, bw, bh);
1597 XineramaScreenInfo *info = NULL;
1599 /* window area geometry */
1600 if(XineramaIsActive(dpy)) {
1601 info = XineramaQueryScreens(dpy, &i);
1603 wy = showbar && topbar ? info[0].y_org + bh : info[0].y_org;
1605 wh = showbar ? info[0].height - bh : info[0].height;
1612 wy = showbar && topbar ? sy + bh : sy;
1614 wh = showbar ? sh - bh : sh;
1619 by = showbar ? (topbar ? wy - bh : wy + wh) : -bh;
1622 /* update layout geometries */
1623 for(i = 0; i < LENGTH(layouts); i++)
1624 if(layouts[i].updategeom)
1625 layouts[i].updategeom();
1629 updatesizehints(Client *c) {
1633 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1635 c->flags = size.flags;
1636 if(c->flags & PBaseSize) {
1637 c->basew = size.base_width;
1638 c->baseh = size.base_height;
1640 else if(c->flags & PMinSize) {
1641 c->basew = size.min_width;
1642 c->baseh = size.min_height;
1645 c->basew = c->baseh = 0;
1646 if(c->flags & PResizeInc) {
1647 c->incw = size.width_inc;
1648 c->inch = size.height_inc;
1651 c->incw = c->inch = 0;
1652 if(c->flags & PMaxSize) {
1653 c->maxw = size.max_width;
1654 c->maxh = size.max_height;
1657 c->maxw = c->maxh = 0;
1658 if(c->flags & PMinSize) {
1659 c->minw = size.min_width;
1660 c->minh = size.min_height;
1662 else if(c->flags & PBaseSize) {
1663 c->minw = size.base_width;
1664 c->minh = size.base_height;
1667 c->minw = c->minh = 0;
1668 if(c->flags & PAspect) {
1669 c->minax = size.min_aspect.x;
1670 c->maxax = size.max_aspect.x;
1671 c->minay = size.min_aspect.y;
1672 c->maxay = size.max_aspect.y;
1675 c->minax = c->maxax = c->minay = c->maxay = 0;
1676 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1677 && c->maxw == c->minw && c->maxh == c->minh);
1681 updatetilegeom(void) {
1682 /* master area geometry */
1688 /* tile area geometry */
1696 updatetitle(Client *c) {
1697 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1698 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1702 updatewmhints(Client *c) {
1705 if((wmh = XGetWMHints(dpy, c->win))) {
1707 sel->isurgent = False;
1709 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1715 view(const void *arg) {
1716 if(*(int *)arg & TAGMASK) {
1717 seltags ^= 1; /* toggle sel tagset */
1718 tagset[seltags] = *(int *)arg & TAGMASK;
1724 viewprevtag(const void *arg) {
1725 seltags ^= 1; /* toggle sel tagset */
1729 /* There's no way to check accesses to destroyed windows, thus those cases are
1730 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1731 * default error handler, which may call exit. */
1733 xerror(Display *dpy, XErrorEvent *ee) {
1734 if(ee->error_code == BadWindow
1735 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1736 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1737 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1738 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1739 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1740 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1741 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1742 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1744 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1745 ee->request_code, ee->error_code);
1746 return xerrorxlib(dpy, ee); /* may call exit */
1750 xerrordummy(Display *dpy, XErrorEvent *ee) {
1754 /* Startup Error handler to check if another window manager
1755 * is already running. */
1757 xerrorstart(Display *dpy, XErrorEvent *ee) {
1763 zoom(const void *arg) {
1766 if(!lt->arrange || sel->isfloating)
1768 if(c == nexttiled(clients))
1769 if(!c || !(c = nexttiled(c->next)))
1778 main(int argc, char *argv[]) {
1779 if(argc == 2 && !strcmp("-v", argv[1]))
1780 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1782 eprint("usage: dwm [-v]\n");
1784 setlocale(LC_CTYPE, "");
1785 if(!(dpy = XOpenDisplay(0)))
1786 eprint("dwm: cannot open display\n");