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 struct Client Client;
67 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
68 int minax, maxax, minay, maxay;
70 unsigned int bw, oldbw;
71 Bool isbanned, isfixed, isfloating, isurgent;
81 unsigned long norm[ColLast];
82 unsigned long sel[ColLast];
92 } DC; /* draw context */
97 void (*func)(const void *arg);
103 void (*arrange)(void);
104 void (*updategeom)(void);
109 const char *instance;
115 /* function declarations */
116 void applyrules(Client *c);
118 void attach(Client *c);
119 void attachstack(Client *c);
121 void buttonpress(XEvent *e);
122 void checkotherwm(void);
124 void configure(Client *c);
125 void configurenotify(XEvent *e);
126 void configurerequest(XEvent *e);
127 void destroynotify(XEvent *e);
128 void detach(Client *c);
129 void detachstack(Client *c);
131 void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
132 void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
133 void *emallocz(unsigned int size);
134 void enternotify(XEvent *e);
135 void eprint(const char *errstr, ...);
136 void expose(XEvent *e);
137 void focus(Client *c);
138 void focusin(XEvent *e);
139 void focusnext(const void *arg);
140 void focusprev(const void *arg);
141 Client *getclient(Window w);
142 unsigned long getcolor(const char *colstr);
143 long getstate(Window w);
144 Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
145 void grabbuttons(Client *c, Bool focused);
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 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 *nextunfloating(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 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 void *arg);
176 void togglefloating(const void *arg);
177 void togglelayout(const void *arg);
178 void toggletag(const void *arg);
179 void toggleview(const void *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 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;
201 unsigned int seltags = 0;
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;
221 unsigned int tagset[] = {1, 1}; /* after start, first tag is selected */
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 */
235 /* check if all tags will fit into a unsigned int bitarray. */
236 static char tags_is_a_sign_that_your_IQ[sizeof(int) * 8 < LENGTH(tags) ? -1 : 1];
238 /* 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)
272 if(!lt->arrange || c->isfloating)
273 resize(c, c->x, c->y, c->w, c->h, True);
293 attachstack(Client *c) {
302 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
307 buttonpress(XEvent *e) {
308 unsigned int i, x, mask;
310 XButtonPressedEvent *ev = &e->xbutton;
312 if(ev->window == barwin) {
314 for(i = 0; i < LENGTH(tags); i++) {
318 if(ev->button == Button1) {
319 if(ev->state & MODKEY)
324 else if(ev->button == Button3) {
325 if(ev->state & MODKEY)
333 if((ev->x < x + blw) && ev->button == Button1)
336 else if((c = getclient(ev->window))) {
338 if(CLEANMASK(ev->state) != MODKEY)
340 if(ev->button == Button1) {
344 else if(ev->button == Button2)
345 togglefloating(NULL);
346 else if(ev->button == Button3 && !c->isfixed) {
356 XSetErrorHandler(xerrorstart);
358 /* this causes an error if some other window manager is running */
359 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
362 eprint("dwm: another window manager is already running\n");
364 XSetErrorHandler(NULL);
365 xerrorxlib = XSetErrorHandler(xerror);
377 XFreeFontSet(dpy, dc.font.set);
379 XFreeFont(dpy, dc.font.xfont);
380 XUngrabKey(dpy, AnyKey, AnyModifier, root);
381 XFreePixmap(dpy, dc.drawable);
383 XFreeCursor(dpy, cursor[CurNormal]);
384 XFreeCursor(dpy, cursor[CurResize]);
385 XFreeCursor(dpy, cursor[CurMove]);
386 XDestroyWindow(dpy, barwin);
388 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
392 configure(Client *c) {
395 ce.type = ConfigureNotify;
403 ce.border_width = c->bw;
405 ce.override_redirect = False;
406 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
410 configurenotify(XEvent *e) {
411 XConfigureEvent *ev = &e->xconfigure;
413 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
423 configurerequest(XEvent *e) {
425 XConfigureRequestEvent *ev = &e->xconfigurerequest;
428 if((c = getclient(ev->window))) {
429 if(ev->value_mask & CWBorderWidth)
430 c->bw = ev->border_width;
431 if(c->isfixed || c->isfloating || !lt->arrange) {
432 if(ev->value_mask & CWX)
434 if(ev->value_mask & CWY)
436 if(ev->value_mask & CWWidth)
438 if(ev->value_mask & CWHeight)
440 if((c->x - sx + c->w) > sw && c->isfloating)
441 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
442 if((c->y - sy + c->h) > sh && c->isfloating)
443 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
444 if((ev->value_mask & (CWX|CWY))
445 && !(ev->value_mask & (CWWidth|CWHeight)))
448 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
456 wc.width = ev->width;
457 wc.height = ev->height;
458 wc.border_width = ev->border_width;
459 wc.sibling = ev->above;
460 wc.stack_mode = ev->detail;
461 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
467 destroynotify(XEvent *e) {
469 XDestroyWindowEvent *ev = &e->xdestroywindow;
471 if((c = getclient(ev->window)))
478 c->prev->next = c->next;
480 c->next->prev = c->prev;
483 c->next = c->prev = NULL;
487 detachstack(Client *c) {
490 for(tc = &stack; *tc && *tc != c; tc = &(*tc)->snext);
500 for(c = stack; c && !isvisible(c); c = c->snext);
501 for(i = 0; i < LENGTH(tags); i++) {
502 dc.w = textw(tags[i]);
503 if(tagset[seltags] & 1 << i) {
504 drawtext(tags[i], dc.sel, isurgent(i));
505 drawsquare(c && c->tags & 1 << i, isoccupied(i), isurgent(i), dc.sel);
508 drawtext(tags[i], dc.norm, isurgent(i));
509 drawsquare(c && c->tags & 1 << i, isoccupied(i), isurgent(i), dc.norm);
515 drawtext(lt->symbol, dc.norm, False);
526 drawtext(stext, dc.norm, False);
527 if((dc.w = dc.x - x) > bh) {
530 drawtext(c->name, dc.sel, False);
531 drawsquare(False, c->isfloating, False, dc.sel);
534 drawtext(NULL, dc.norm, False);
536 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, bw, bh, 0, 0);
541 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
544 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
546 gcv.foreground = col[invert ? ColBG : ColFG];
547 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
548 x = (dc.font.ascent + dc.font.descent + 2) / 4;
552 r.width = r.height = x + 1;
553 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
556 r.width = r.height = x;
557 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
562 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
564 unsigned int len, olen;
565 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
568 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
569 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
573 len = MIN(olen, sizeof buf);
574 memcpy(buf, text, len);
576 h = dc.font.ascent + dc.font.descent;
577 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
579 /* shorten text if necessary */
580 for(; len && (w = textnw(buf, len)) > dc.w - h; len--);
591 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
593 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
595 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
599 emallocz(unsigned int size) {
600 void *res = calloc(1, size);
603 eprint("fatal: could not malloc() %u bytes\n", size);
608 enternotify(XEvent *e) {
610 XCrossingEvent *ev = &e->xcrossing;
612 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
614 if((c = getclient(ev->window)))
621 eprint(const char *errstr, ...) {
624 va_start(ap, errstr);
625 vfprintf(stderr, errstr, ap);
632 XExposeEvent *ev = &e->xexpose;
634 if(ev->count == 0 && (ev->window == barwin))
640 if(!c || (c && !isvisible(c)))
641 for(c = stack; c && !isvisible(c); c = c->snext);
642 if(sel && sel != c) {
643 grabbuttons(sel, False);
644 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
649 grabbuttons(c, True);
653 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
654 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
657 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
662 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
663 XFocusChangeEvent *ev = &e->xfocus;
665 if(sel && ev->window != sel->win)
666 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
670 focusnext(const void *arg) {
675 for(c = sel->next; c && !isvisible(c); c = c->next);
677 for(c = clients; c && !isvisible(c); c = c->next);
685 focusprev(const void *arg) {
690 for(c = sel->prev; c && !isvisible(c); c = c->prev);
692 for(c = clients; c && c->next; c = c->next);
693 for(; c && !isvisible(c); c = c->prev);
702 getclient(Window w) {
705 for(c = clients; c && c->win != w; c = c->next);
710 getcolor(const char *colstr) {
711 Colormap cmap = DefaultColormap(dpy, screen);
714 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
715 eprint("error, cannot allocate color '%s'\n", colstr);
723 unsigned char *p = NULL;
724 unsigned long n, extra;
727 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
728 &real, &format, &n, &extra, (unsigned char **)&p);
729 if(status != Success)
738 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
743 if(!text || size == 0)
746 XGetTextProperty(dpy, w, &name, atom);
749 if(name.encoding == XA_STRING)
750 strncpy(text, (char *)name.value, size - 1);
752 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
754 strncpy(text, *list, size - 1);
755 XFreeStringList(list);
758 text[size - 1] = '\0';
764 grabbuttons(Client *c, Bool focused) {
766 unsigned int buttons[] = { Button1, Button2, Button3 };
767 unsigned int modifiers[] = { MODKEY, MODKEY|LockMask, MODKEY|numlockmask,
768 MODKEY|numlockmask|LockMask} ;
770 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
772 for(i = 0; i < LENGTH(buttons); i++)
773 for(j = 0; j < LENGTH(modifiers); j++)
774 XGrabButton(dpy, buttons[i], modifiers[j], c->win, False,
775 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
777 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
778 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
785 XModifierKeymap *modmap;
787 /* init modifier map */
788 modmap = XGetModifierMapping(dpy);
789 for(i = 0; i < 8; i++)
790 for(j = 0; j < modmap->max_keypermod; j++) {
791 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
792 numlockmask = (1 << i);
794 XFreeModifiermap(modmap);
796 XUngrabKey(dpy, AnyKey, AnyModifier, root);
797 for(i = 0; i < LENGTH(keys); i++) {
798 code = XKeysymToKeycode(dpy, keys[i].keysym);
799 XGrabKey(dpy, code, keys[i].mod, root, True,
800 GrabModeAsync, GrabModeAsync);
801 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
802 GrabModeAsync, GrabModeAsync);
803 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
804 GrabModeAsync, GrabModeAsync);
805 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
806 GrabModeAsync, GrabModeAsync);
811 initfont(const char *fontstr) {
812 char *def, **missing;
817 XFreeFontSet(dpy, dc.font.set);
818 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
821 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
822 XFreeStringList(missing);
825 XFontSetExtents *font_extents;
826 XFontStruct **xfonts;
828 dc.font.ascent = dc.font.descent = 0;
829 font_extents = XExtentsOfFontSet(dc.font.set);
830 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
831 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
832 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
833 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
839 XFreeFont(dpy, dc.font.xfont);
840 dc.font.xfont = NULL;
841 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
842 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
843 eprint("error, cannot load font: '%s'\n", fontstr);
844 dc.font.ascent = dc.font.xfont->ascent;
845 dc.font.descent = dc.font.xfont->descent;
847 dc.font.height = dc.font.ascent + dc.font.descent;
851 isoccupied(unsigned int t) {
854 for(c = clients; c; c = c->next)
861 isprotodel(Client *c) {
866 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
867 for(i = 0; !ret && i < n; i++)
868 if(protocols[i] == wmatom[WMDelete])
876 isurgent(unsigned int t) {
879 for(c = clients; c; c = c->next)
880 if(c->isurgent && c->tags & 1 << t)
886 isvisible(Client *c) {
887 return c->tags & tagset[seltags];
891 keypress(XEvent *e) {
897 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
898 for(i = 0; i < LENGTH(keys); i++)
899 if(keysym == keys[i].keysym
900 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
903 keys[i].func(keys[i].arg);
908 killclient(const void *arg) {
913 if(isprotodel(sel)) {
914 ev.type = ClientMessage;
915 ev.xclient.window = sel->win;
916 ev.xclient.message_type = wmatom[WMProtocols];
917 ev.xclient.format = 32;
918 ev.xclient.data.l[0] = wmatom[WMDelete];
919 ev.xclient.data.l[1] = CurrentTime;
920 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
923 XKillClient(dpy, sel->win);
927 manage(Window w, XWindowAttributes *wa) {
928 Client *c, *t = NULL;
933 c = emallocz(sizeof(Client));
941 c->oldbw = wa->border_width;
942 if(c->w == sw && c->h == sh) {
945 c->bw = wa->border_width;
948 if(c->x + c->w + 2 * c->bw > sx + sw)
949 c->x = sx + sw - c->w - 2 * c->bw;
950 if(c->y + c->h + 2 * c->bw > sy + sh)
951 c->y = sy + sh - c->h - 2 * c->bw;
952 c->x = MAX(c->x, sx);
953 c->y = MAX(c->y, by == 0 ? bh : sy);
957 wc.border_width = c->bw;
958 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
959 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
960 configure(c); /* propagates border_width, if size doesn't change */
962 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
963 grabbuttons(c, False);
965 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
966 for(t = clients; t && t->win != trans; t = t->next);
972 c->isfloating = (rettrans == Success) || c->isfixed;
975 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
977 XMapWindow(dpy, c->win);
978 setclientstate(c, NormalState);
983 mappingnotify(XEvent *e) {
984 XMappingEvent *ev = &e->xmapping;
986 XRefreshKeyboardMapping(ev);
987 if(ev->request == MappingKeyboard)
992 maprequest(XEvent *e) {
993 static XWindowAttributes wa;
994 XMapRequestEvent *ev = &e->xmaprequest;
996 if(!XGetWindowAttributes(dpy, ev->window, &wa))
998 if(wa.override_redirect)
1000 if(!getclient(ev->window))
1001 manage(ev->window, &wa);
1005 movemouse(Client *c) {
1006 int x1, y1, ocx, ocy, di, nx, ny;
1013 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1014 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1016 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1018 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1021 XUngrabPointer(dpy, CurrentTime);
1023 case ConfigureRequest:
1026 handler[ev.type](&ev);
1030 nx = ocx + (ev.xmotion.x - x1);
1031 ny = ocy + (ev.xmotion.y - y1);
1032 if(snap && nx >= wx && nx <= wx + ww
1033 && ny >= wy && ny <= wy + wh) {
1034 if(abs(wx - nx) < snap)
1036 else if(abs((wx + ww) - (nx + c->w + 2 * c->bw)) < snap)
1037 nx = wx + ww - c->w - 2 * c->bw;
1038 if(abs(wy - ny) < snap)
1040 else if(abs((wy + wh) - (ny + c->h + 2 * c->bw)) < snap)
1041 ny = wy + wh - c->h - 2 * c->bw;
1042 if(!c->isfloating && lt->arrange && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
1043 togglefloating(NULL);
1045 if(!lt->arrange || c->isfloating)
1046 resize(c, nx, ny, c->w, c->h, False);
1053 nextunfloating(Client *c) {
1054 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1059 propertynotify(XEvent *e) {
1062 XPropertyEvent *ev = &e->xproperty;
1064 if(ev->state == PropertyDelete)
1065 return; /* ignore */
1066 if((c = getclient(ev->window))) {
1069 case XA_WM_TRANSIENT_FOR:
1070 XGetTransientForHint(dpy, c->win, &trans);
1071 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1074 case XA_WM_NORMAL_HINTS:
1082 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1091 quit(const void *arg) {
1092 readin = running = False;
1096 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1100 /* set minimum possible */
1104 /* temporarily remove base dimensions */
1108 /* adjust for aspect limits */
1109 if(c->minax != c->maxax && c->minay != c->maxay
1110 && c->minax > 0 && c->maxax > 0 && c->minay > 0 && c->maxay > 0) {
1111 if(w * c->maxay > h * c->maxax)
1112 w = h * c->maxax / c->maxay;
1113 else if(w * c->minay < h * c->minax)
1114 h = w * c->minay / c->minax;
1117 /* adjust for increment value */
1123 /* restore base dimensions */
1127 w = MAX(w, c->minw);
1128 h = MAX(h, c->minh);
1131 w = MIN(w, c->maxw);
1134 h = MIN(h, c->maxh);
1136 if(w <= 0 || h <= 0)
1139 x = sw - w - 2 * c->bw;
1141 y = sh - h - 2 * c->bw;
1142 if(x + w + 2 * c->bw < sx)
1144 if(y + h + 2 * c->bw < sy)
1146 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1149 c->w = wc.width = w;
1150 c->h = wc.height = h;
1151 wc.border_width = c->bw;
1152 XConfigureWindow(dpy, c->win,
1153 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1160 resizemouse(Client *c) {
1167 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1168 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1170 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1172 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1175 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1176 c->w + c->bw - 1, c->h + c->bw - 1);
1177 XUngrabPointer(dpy, CurrentTime);
1178 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1180 case ConfigureRequest:
1183 handler[ev.type](&ev);
1187 nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1188 nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1190 if(snap && nw >= wx && nw <= wx + ww
1191 && nh >= wy && nh <= wy + wh) {
1192 if(!c->isfloating && lt->arrange
1193 && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1194 togglefloating(NULL);
1196 if(!lt->arrange || c->isfloating)
1197 resize(c, c->x, c->y, nw, nh, True);
1212 if(sel->isfloating || !lt->arrange)
1213 XRaiseWindow(dpy, sel->win);
1215 wc.stack_mode = Below;
1216 wc.sibling = barwin;
1217 for(c = stack; c; c = c->snext)
1218 if(!c->isfloating && isvisible(c)) {
1219 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1220 wc.sibling = c->win;
1224 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1230 char sbuf[sizeof stext];
1233 unsigned int len, offset;
1236 /* main event loop, also reads status text from stdin */
1238 xfd = ConnectionNumber(dpy);
1241 len = sizeof stext - 1;
1242 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1246 FD_SET(STDIN_FILENO, &rd);
1248 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1251 eprint("select failed\n");
1253 if(FD_ISSET(STDIN_FILENO, &rd)) {
1254 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1256 strncpy(stext, strerror(errno), len);
1260 strncpy(stext, "EOF", 4);
1264 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1265 if(*p == '\n' || *p == '\0') {
1267 strncpy(stext, sbuf, len);
1268 p += r - 1; /* p is sbuf + offset + r - 1 */
1269 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1272 memmove(sbuf, p - r + 1, r);
1279 while(XPending(dpy)) {
1280 XNextEvent(dpy, &ev);
1281 if(handler[ev.type])
1282 (handler[ev.type])(&ev); /* call handler */
1289 unsigned int i, num;
1290 Window *wins, d1, d2;
1291 XWindowAttributes wa;
1294 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1295 for(i = 0; i < num; i++) {
1296 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1297 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1299 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1300 manage(wins[i], &wa);
1302 for(i = 0; i < num; i++) { /* now the transients */
1303 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1305 if(XGetTransientForHint(dpy, wins[i], &d1)
1306 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1307 manage(wins[i], &wa);
1315 setclientstate(Client *c, long state) {
1316 long data[] = {state, None};
1318 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1319 PropModeReplace, (unsigned char *)data, 2);
1322 /* arg > 1.0 will set mfact absolutly */
1324 setmfact(const void *arg) {
1325 double d = *((double*) arg);
1327 if(!d || lt->arrange != tile)
1329 d = d < 1.0 ? d + mfact : d - 1.0;
1330 if(d < 0.1 || d > 0.9)
1340 XSetWindowAttributes wa;
1343 screen = DefaultScreen(dpy);
1344 root = RootWindow(dpy, screen);
1348 sw = DisplayWidth(dpy, screen);
1349 sh = DisplayHeight(dpy, screen);
1350 bh = dc.font.height + 2;
1354 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1355 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1356 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1357 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1358 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1359 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1362 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1363 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1364 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1366 /* init appearance */
1367 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1368 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1369 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1370 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1371 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1372 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1375 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1376 dc.gc = XCreateGC(dpy, root, 0, 0);
1377 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1379 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1382 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1383 w = textw(layouts[i].symbol);
1387 wa.override_redirect = 1;
1388 wa.background_pixmap = ParentRelative;
1389 wa.event_mask = ButtonPressMask|ExposureMask;
1391 barwin = XCreateWindow(dpy, root, bx, by, bw, bh, 0, DefaultDepth(dpy, screen),
1392 CopyFromParent, DefaultVisual(dpy, screen),
1393 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1394 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1395 XMapRaised(dpy, barwin);
1396 strcpy(stext, "dwm-"VERSION);
1399 /* EWMH support per view */
1400 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1401 PropModeReplace, (unsigned char *) netatom, NetLast);
1403 /* select for events */
1404 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1405 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1406 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1407 XSelectInput(dpy, root, wa.event_mask);
1415 spawn(const void *arg) {
1416 static char *shell = NULL;
1418 if(!shell && !(shell = getenv("SHELL")))
1420 /* The double-fork construct avoids zombie processes and keeps the code
1421 * clean from stupid signal handlers. */
1425 close(ConnectionNumber(dpy));
1427 execl(shell, shell, "-c", (char *)arg, (char *)NULL);
1428 fprintf(stderr, "dwm: execl '%s -c %s'", shell, (char *)arg);
1437 tag(const void *arg) {
1438 if(sel && *(int *)arg & TAGMASK) {
1439 sel->tags = *(int *)arg & TAGMASK;
1445 textnw(const char *text, unsigned int len) {
1449 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1452 return XTextWidth(dc.font.xfont, text, len);
1456 textw(const char *text) {
1457 return textnw(text, strlen(text)) + dc.font.height;
1466 for(n = 0, c = nextunfloating(clients); c; c = nextunfloating(c->next), n++);
1471 c = nextunfloating(clients);
1474 tileresize(c, wx, wy, ww - 2 * c->bw, wh - 2 * c->bw);
1476 tileresize(c, mx, my, mw - 2 * c->bw, mh - 2 * c->bw);
1482 x = (tx > c->x + c->w) ? c->x + c->w + 2 * c->bw : tw;
1484 w = (tx > c->x + c->w) ? wx + ww - x : tw;
1489 for(i = 0, c = nextunfloating(c->next); c; c = nextunfloating(c->next), i++) {
1490 if(i + 1 == n) /* remainder */
1491 tileresize(c, x, y, w - 2 * c->bw, (ty + th) - y - 2 * c->bw);
1493 tileresize(c, x, y, w - 2 * c->bw, h - 2 * c->bw);
1495 y = c->y + c->h + 2 * c->bw;
1500 tileresize(Client *c, int x, int y, int w, int h) {
1501 resize(c, x, y, w, h, resizehints);
1502 if(resizehints && ((c->h < bh) || (c->h > h) || (c->w < bh) || (c->w > w)))
1503 /* client doesn't accept size constraints */
1504 resize(c, x, y, w, h, False);
1508 togglebar(const void *arg) {
1516 togglefloating(const void *arg) {
1519 sel->isfloating = !sel->isfloating;
1521 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1526 togglelayout(const void *arg) {
1530 if(++lt == &layouts[LENGTH(layouts)])
1534 for(i = 0; i < LENGTH(layouts); i++)
1535 if(!strcmp((char *)arg, layouts[i].symbol))
1537 if(i == LENGTH(layouts))
1548 toggletag(const void *arg) {
1549 int i, m = *(int *)arg;
1550 for(i = 0; i < sizeof(int) * 8; i++)
1551 fputc(m & 1 << i ? '1' : '0', stdout);
1553 for(i = 0; i < sizeof(int) * 8; i++)
1554 fputc(TAGMASK & 1 << i ? '1' : '0', stdout);
1557 if(sel && (sel->tags ^ ((*(int *)arg) & TAGMASK))) {
1558 sel->tags ^= (*(int *)arg) & TAGMASK;
1564 toggleview(const void *arg) {
1565 if((tagset[seltags] ^ ((*(int *)arg) & TAGMASK))) {
1566 tagset[seltags] ^= (*(int *)arg) & TAGMASK;
1575 XMoveWindow(dpy, c->win, c->x, c->y);
1576 c->isbanned = False;
1580 unmanage(Client *c) {
1583 wc.border_width = c->oldbw;
1584 /* The server grab construct avoids race conditions. */
1586 XSetErrorHandler(xerrordummy);
1587 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1592 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1593 setclientstate(c, WithdrawnState);
1596 XSetErrorHandler(xerror);
1602 unmapnotify(XEvent *e) {
1604 XUnmapEvent *ev = &e->xunmap;
1606 if((c = getclient(ev->window)))
1612 if(dc.drawable != 0)
1613 XFreePixmap(dpy, dc.drawable);
1614 dc.drawable = XCreatePixmap(dpy, root, bw, bh, DefaultDepth(dpy, screen));
1615 XMoveResizeWindow(dpy, barwin, bx, by, bw, bh);
1622 XineramaScreenInfo *info = NULL;
1624 /* window area geometry */
1625 if(XineramaIsActive(dpy)) {
1626 info = XineramaQueryScreens(dpy, &i);
1628 wy = showbar && topbar ? info[0].y_org + bh : info[0].y_org;
1630 wh = showbar ? info[0].height - bh : info[0].height;
1637 wy = showbar && topbar ? sy + bh : sy;
1639 wh = showbar ? sh - bh : sh;
1644 by = showbar ? (topbar ? wy - bh : wy + wh) : -bh;
1647 /* update layout geometries */
1648 for(i = 0; i < LENGTH(layouts); i++)
1649 if(layouts[i].updategeom)
1650 layouts[i].updategeom();
1654 updatesizehints(Client *c) {
1658 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1660 c->flags = size.flags;
1661 if(c->flags & PBaseSize) {
1662 c->basew = size.base_width;
1663 c->baseh = size.base_height;
1665 else if(c->flags & PMinSize) {
1666 c->basew = size.min_width;
1667 c->baseh = size.min_height;
1670 c->basew = c->baseh = 0;
1671 if(c->flags & PResizeInc) {
1672 c->incw = size.width_inc;
1673 c->inch = size.height_inc;
1676 c->incw = c->inch = 0;
1677 if(c->flags & PMaxSize) {
1678 c->maxw = size.max_width;
1679 c->maxh = size.max_height;
1682 c->maxw = c->maxh = 0;
1683 if(c->flags & PMinSize) {
1684 c->minw = size.min_width;
1685 c->minh = size.min_height;
1687 else if(c->flags & PBaseSize) {
1688 c->minw = size.base_width;
1689 c->minh = size.base_height;
1692 c->minw = c->minh = 0;
1693 if(c->flags & PAspect) {
1694 c->minax = size.min_aspect.x;
1695 c->maxax = size.max_aspect.x;
1696 c->minay = size.min_aspect.y;
1697 c->maxay = size.max_aspect.y;
1700 c->minax = c->maxax = c->minay = c->maxay = 0;
1701 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1702 && c->maxw == c->minw && c->maxh == c->minh);
1706 updatetilegeom(void) {
1707 /* master area geometry */
1713 /* tile area geometry */
1721 updatetitle(Client *c) {
1722 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1723 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1727 updatewmhints(Client *c) {
1730 if((wmh = XGetWMHints(dpy, c->win))) {
1732 sel->isurgent = False;
1734 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1740 view(const void *arg) {
1741 if(*(int *)arg & TAGMASK) {
1742 seltags ^= 1; /* toggle sel tagset */
1743 tagset[seltags] = *(int *)arg & TAGMASK;
1749 viewprevtag(const void *arg) {
1750 seltags ^= 1; /* toggle sel tagset */
1754 /* There's no way to check accesses to destroyed windows, thus those cases are
1755 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1756 * default error handler, which may call exit. */
1758 xerror(Display *dpy, XErrorEvent *ee) {
1759 if(ee->error_code == BadWindow
1760 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1761 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1762 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1763 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1764 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1765 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1766 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1767 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1769 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1770 ee->request_code, ee->error_code);
1771 return xerrorxlib(dpy, ee); /* may call exit */
1775 xerrordummy(Display *dpy, XErrorEvent *ee) {
1779 /* Startup Error handler to check if another window manager
1780 * is already running. */
1782 xerrorstart(Display *dpy, XErrorEvent *ee) {
1788 zoom(const void *arg) {
1791 if(c == nextunfloating(clients))
1792 if(!c || !(c = nextunfloating(c->next)))
1794 if(lt->arrange == tile && !sel->isfloating) {
1803 main(int argc, char *argv[]) {
1804 if(argc == 2 && !strcmp("-v", argv[1]))
1805 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1807 eprint("usage: dwm [-v]\n");
1809 setlocale(LC_CTYPE, "");
1810 if(!(dpy = XOpenDisplay(0)))
1811 eprint("dwm: cannot open display\n");