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>
44 #define MAX(a, b) ((a) > (b) ? (a) : (b))
45 #define MIN(a, b) ((a) < (b) ? (a) : (b))
46 #define BUTTONMASK (ButtonPressMask|ButtonReleaseMask)
47 #define CLEANMASK(mask) (mask & ~(numlockmask|LockMask))
48 #define LENGTH(x) (sizeof x / sizeof x[0])
50 #define MOUSEMASK (BUTTONMASK|PointerMotionMask)
53 enum { BarTop, BarBot, BarOff, BarLast }; /* bar appearance */
54 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
55 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
56 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
57 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
60 typedef struct Client Client;
64 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
65 int minax, maxax, minay, maxay;
67 unsigned int bw, oldbw;
68 Bool isbanned, isfixed, isfloating, isurgent;
78 unsigned long norm[ColLast];
79 unsigned long sel[ColLast];
89 } DC; /* draw context */
94 void (*func)(const char *arg);
100 void (*arrange)(void);
101 void (*updategeom)(void);
106 const char *instance;
112 /* function declarations */
113 void applyrules(Client *c);
115 void attach(Client *c);
116 void attachstack(Client *c);
118 void buttonpress(XEvent *e);
119 void checkotherwm(void);
121 void configure(Client *c);
122 void configurenotify(XEvent *e);
123 void configurerequest(XEvent *e);
124 void destroynotify(XEvent *e);
125 void detach(Client *c);
126 void detachstack(Client *c);
128 void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
129 void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
130 void *emallocz(unsigned int size);
131 void enternotify(XEvent *e);
132 void eprint(const char *errstr, ...);
133 void expose(XEvent *e);
134 void focus(Client *c);
135 void focusin(XEvent *e);
136 void focusnext(const char *arg);
137 void focusprev(const char *arg);
138 Client *getclient(Window w);
139 unsigned long getcolor(const char *colstr);
140 long getstate(Window w);
141 Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
142 void grabbuttons(Client *c, Bool focused);
144 unsigned int idxoftag(const char *t);
145 void initfont(const char *fontstr);
146 Bool isoccupied(unsigned int t);
147 Bool isprotodel(Client *c);
148 Bool isurgent(unsigned int t);
149 Bool isvisible(Client *c);
150 void keypress(XEvent *e);
151 void killclient(const char *arg);
152 void manage(Window w, XWindowAttributes *wa);
153 void mappingnotify(XEvent *e);
154 void maprequest(XEvent *e);
155 void movemouse(Client *c);
156 Client *nextunfloating(Client *c);
157 void propertynotify(XEvent *e);
158 void quit(const char *arg);
159 void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
160 void resizemouse(Client *c);
164 void setclientstate(Client *c, long state);
166 void spawn(const char *arg);
167 void tag(const char *arg);
168 unsigned int textnw(const char *text, unsigned int len);
169 unsigned int textw(const char *text);
170 void togglebar(const char *arg);
171 void togglefloating(const char *arg);
172 void togglelayout(const char *arg);
173 void toggletag(const char *arg);
174 void toggleview(const char *arg);
175 void unban(Client *c);
176 void unmanage(Client *c);
177 void unmapnotify(XEvent *e);
178 void updatebar(void);
179 void updategeom(void);
180 void updatesizehints(Client *c);
181 void updatetitle(Client *c);
182 void updatewmhints(Client *c);
183 void view(const char *arg);
184 void viewprevtag(const char *arg);
185 int xerror(Display *dpy, XErrorEvent *ee);
186 int xerrordummy(Display *dpy, XErrorEvent *ee);
187 int xerrorstart(Display *dpy, XErrorEvent *ee);
188 void zoom(const char *arg);
192 int screen, sx, sy, sw, sh;
193 int bx, by, bw, bh, blw, wx, wy, ww, wh;
195 int (*xerrorxlib)(Display *, XErrorEvent *);
196 unsigned int numlockmask = 0;
197 void (*handler[LASTEvent]) (XEvent *) = {
198 [ButtonPress] = buttonpress,
199 [ConfigureRequest] = configurerequest,
200 [ConfigureNotify] = configurenotify,
201 [DestroyNotify] = destroynotify,
202 [EnterNotify] = enternotify,
205 [KeyPress] = keypress,
206 [MappingNotify] = mappingnotify,
207 [MapRequest] = maprequest,
208 [PropertyNotify] = propertynotify,
209 [UnmapNotify] = unmapnotify
211 Atom wmatom[WMLast], netatom[NetLast];
212 Bool otherwm, readin;
215 Client *clients = NULL;
217 Client *stack = NULL;
218 Cursor cursor[CurLast];
222 Layout *lt = layouts;
225 /* configuration, allows nested code to access above variables */
227 #define TAGSZ (LENGTH(tags) * sizeof(Bool))
229 /* function implementations */
232 applyrules(Client *c) {
234 Bool matched = False;
236 XClassHint ch = { 0 };
239 XGetClassHint(dpy, c->win, &ch);
240 for(i = 0; i < LENGTH(rules); i++) {
242 if((!r->title || strstr(c->name, r->title))
243 && (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
244 && (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
245 c->isfloating = r->isfloating;
247 c->tags[idxoftag(r->tag)] = True;
257 memcpy(c->tags, tagset[seltags], TAGSZ);
264 for(c = clients; c; c = c->next)
267 if(!lt->arrange || c->isfloating)
268 resize(c, c->x, c->y, c->w, c->h, True);
288 attachstack(Client *c) {
297 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
302 buttonpress(XEvent *e) {
305 XButtonPressedEvent *ev = &e->xbutton;
307 if(ev->window == barwin) {
309 for(i = 0; i < LENGTH(tags); i++) {
312 if(ev->button == Button1) {
313 if(ev->state & MODKEY)
318 else if(ev->button == Button3) {
319 if(ev->state & MODKEY)
327 if((ev->x < x + blw) && ev->button == Button1)
330 else if((c = getclient(ev->window))) {
332 if(CLEANMASK(ev->state) != MODKEY)
334 if(ev->button == Button1) {
338 else if(ev->button == Button2) {
339 if(lt->arrange && c->isfloating)
340 togglefloating(NULL);
342 else if(ev->button == Button3 && !c->isfixed) {
352 XSetErrorHandler(xerrorstart);
354 /* this causes an error if some other window manager is running */
355 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
358 eprint("dwm: another window manager is already running\n");
360 XSetErrorHandler(NULL);
361 xerrorxlib = XSetErrorHandler(xerror);
373 XFreeFontSet(dpy, dc.font.set);
375 XFreeFont(dpy, dc.font.xfont);
376 XUngrabKey(dpy, AnyKey, AnyModifier, root);
377 XFreePixmap(dpy, dc.drawable);
379 XFreeCursor(dpy, cursor[CurNormal]);
380 XFreeCursor(dpy, cursor[CurResize]);
381 XFreeCursor(dpy, cursor[CurMove]);
382 XDestroyWindow(dpy, barwin);
384 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
388 configure(Client *c) {
391 ce.type = ConfigureNotify;
399 ce.border_width = c->bw;
401 ce.override_redirect = False;
402 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
406 configurenotify(XEvent *e) {
407 XConfigureEvent *ev = &e->xconfigure;
409 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
419 configurerequest(XEvent *e) {
421 XConfigureRequestEvent *ev = &e->xconfigurerequest;
424 if((c = getclient(ev->window))) {
425 if(ev->value_mask & CWBorderWidth)
426 c->bw = ev->border_width;
427 if(c->isfixed || c->isfloating || !lt->arrange) {
428 if(ev->value_mask & CWX)
430 if(ev->value_mask & CWY)
432 if(ev->value_mask & CWWidth)
434 if(ev->value_mask & CWHeight)
436 if((c->x - sx + c->w) > sw && c->isfloating)
437 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
438 if((c->y - sy + c->h) > sh && c->isfloating)
439 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
440 if((ev->value_mask & (CWX|CWY))
441 && !(ev->value_mask & (CWWidth|CWHeight)))
444 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
452 wc.width = ev->width;
453 wc.height = ev->height;
454 wc.border_width = ev->border_width;
455 wc.sibling = ev->above;
456 wc.stack_mode = ev->detail;
457 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
463 destroynotify(XEvent *e) {
465 XDestroyWindowEvent *ev = &e->xdestroywindow;
467 if((c = getclient(ev->window)))
474 c->prev->next = c->next;
476 c->next->prev = c->prev;
479 c->next = c->prev = NULL;
483 detachstack(Client *c) {
486 for(tc = &stack; *tc && *tc != c; tc = &(*tc)->snext);
496 for(c = stack; c && !isvisible(c); c = c->snext);
497 for(i = 0; i < LENGTH(tags); i++) {
498 dc.w = textw(tags[i]);
499 if(tagset[seltags][i]) {
500 drawtext(tags[i], dc.sel, isurgent(i));
501 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.sel);
504 drawtext(tags[i], dc.norm, isurgent(i));
505 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.norm);
511 drawtext(lt->symbol, dc.norm, False);
522 drawtext(stext, dc.norm, False);
523 if((dc.w = dc.x - x) > bh) {
526 drawtext(c->name, dc.sel, False);
527 drawsquare(False, c->isfloating, False, dc.sel);
530 drawtext(NULL, dc.norm, False);
532 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, bw, bh, 0, 0);
537 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
540 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
542 gcv.foreground = col[invert ? ColBG : ColFG];
543 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
544 x = (dc.font.ascent + dc.font.descent + 2) / 4;
548 r.width = r.height = x + 1;
549 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
552 r.width = r.height = x;
553 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
558 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
560 unsigned int len, olen;
561 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
564 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
565 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
569 len = MIN(olen, sizeof buf);
570 memcpy(buf, text, len);
572 h = dc.font.ascent + dc.font.descent;
573 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
575 /* shorten text if necessary */
576 for(; len && (w = textnw(buf, len)) > dc.w - h; len--);
587 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
589 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
591 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
595 emallocz(unsigned int size) {
596 void *res = calloc(1, size);
599 eprint("fatal: could not malloc() %u bytes\n", size);
604 enternotify(XEvent *e) {
606 XCrossingEvent *ev = &e->xcrossing;
608 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
610 if((c = getclient(ev->window)))
617 eprint(const char *errstr, ...) {
620 va_start(ap, errstr);
621 vfprintf(stderr, errstr, ap);
628 XExposeEvent *ev = &e->xexpose;
630 if(ev->count == 0 && (ev->window == barwin))
636 if(!c || (c && !isvisible(c)))
637 for(c = stack; c && !isvisible(c); c = c->snext);
638 if(sel && sel != c) {
639 grabbuttons(sel, False);
640 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
645 grabbuttons(c, True);
649 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
650 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
653 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
658 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
659 XFocusChangeEvent *ev = &e->xfocus;
661 if(sel && ev->window != sel->win)
662 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
666 focusnext(const char *arg) {
671 for(c = sel->next; c && !isvisible(c); c = c->next);
673 for(c = clients; c && !isvisible(c); c = c->next);
681 focusprev(const char *arg) {
686 for(c = sel->prev; c && !isvisible(c); c = c->prev);
688 for(c = clients; c && c->next; c = c->next);
689 for(; c && !isvisible(c); c = c->prev);
698 getclient(Window w) {
701 for(c = clients; c && c->win != w; c = c->next);
706 getcolor(const char *colstr) {
707 Colormap cmap = DefaultColormap(dpy, screen);
710 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
711 eprint("error, cannot allocate color '%s'\n", colstr);
719 unsigned char *p = NULL;
720 unsigned long n, extra;
723 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
724 &real, &format, &n, &extra, (unsigned char **)&p);
725 if(status != Success)
734 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
739 if(!text || size == 0)
742 XGetTextProperty(dpy, w, &name, atom);
745 if(name.encoding == XA_STRING)
746 strncpy(text, (char *)name.value, size - 1);
748 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
750 strncpy(text, *list, size - 1);
751 XFreeStringList(list);
754 text[size - 1] = '\0';
760 grabbuttons(Client *c, Bool focused) {
762 unsigned int buttons[] = { Button1, Button2, Button3 };
763 unsigned int modifiers[] = { MODKEY, MODKEY|LockMask, MODKEY|numlockmask,
764 MODKEY|numlockmask|LockMask} ;
766 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
768 for(i = 0; i < LENGTH(buttons); i++)
769 for(j = 0; j < LENGTH(modifiers); j++)
770 XGrabButton(dpy, buttons[i], modifiers[j], c->win, False,
771 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
773 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
774 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
781 XModifierKeymap *modmap;
783 /* init modifier map */
784 modmap = XGetModifierMapping(dpy);
785 for(i = 0; i < 8; i++)
786 for(j = 0; j < modmap->max_keypermod; j++) {
787 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
788 numlockmask = (1 << i);
790 XFreeModifiermap(modmap);
792 XUngrabKey(dpy, AnyKey, AnyModifier, root);
793 for(i = 0; i < LENGTH(keys); i++) {
794 code = XKeysymToKeycode(dpy, keys[i].keysym);
795 XGrabKey(dpy, code, keys[i].mod, root, True,
796 GrabModeAsync, GrabModeAsync);
797 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
798 GrabModeAsync, GrabModeAsync);
799 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
800 GrabModeAsync, GrabModeAsync);
801 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
802 GrabModeAsync, GrabModeAsync);
807 idxoftag(const char *t) {
810 for(i = 0; (i < LENGTH(tags)) && t && strcmp(tags[i], t); i++);
811 return (i < LENGTH(tags)) ? i : 0;
815 initfont(const char *fontstr) {
816 char *def, **missing;
821 XFreeFontSet(dpy, dc.font.set);
822 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
825 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
826 XFreeStringList(missing);
829 XFontSetExtents *font_extents;
830 XFontStruct **xfonts;
832 dc.font.ascent = dc.font.descent = 0;
833 font_extents = XExtentsOfFontSet(dc.font.set);
834 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
835 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
836 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
837 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
843 XFreeFont(dpy, dc.font.xfont);
844 dc.font.xfont = NULL;
845 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
846 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
847 eprint("error, cannot load font: '%s'\n", fontstr);
848 dc.font.ascent = dc.font.xfont->ascent;
849 dc.font.descent = dc.font.xfont->descent;
851 dc.font.height = dc.font.ascent + dc.font.descent;
855 isoccupied(unsigned int t) {
858 for(c = clients; c; c = c->next)
865 isprotodel(Client *c) {
870 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
871 for(i = 0; !ret && i < n; i++)
872 if(protocols[i] == wmatom[WMDelete])
880 isurgent(unsigned int t) {
883 for(c = clients; c; c = c->next)
884 if(c->isurgent && c->tags[t])
890 isvisible(Client *c) {
893 for(i = 0; i < LENGTH(tags); i++)
894 if(c->tags[i] && tagset[seltags][i])
900 keypress(XEvent *e) {
906 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
907 for(i = 0; i < LENGTH(keys); i++)
908 if(keysym == keys[i].keysym
909 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
912 keys[i].func(keys[i].arg);
917 killclient(const char *arg) {
922 if(isprotodel(sel)) {
923 ev.type = ClientMessage;
924 ev.xclient.window = sel->win;
925 ev.xclient.message_type = wmatom[WMProtocols];
926 ev.xclient.format = 32;
927 ev.xclient.data.l[0] = wmatom[WMDelete];
928 ev.xclient.data.l[1] = CurrentTime;
929 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
932 XKillClient(dpy, sel->win);
936 manage(Window w, XWindowAttributes *wa) {
937 Client *c, *t = NULL;
942 c = emallocz(sizeof(Client));
943 c->tags = emallocz(TAGSZ);
951 c->oldbw = wa->border_width;
952 if(c->w == sw && c->h == sh) {
955 c->bw = wa->border_width;
958 if(c->x + c->w + 2 * c->bw > wx + ww)
959 c->x = wx + ww - c->w - 2 * c->bw;
960 if(c->y + c->h + 2 * c->bw > wy + wh)
961 c->y = wy + wh - c->h - 2 * c->bw;
962 c->x = MAX(c->x, wx);
963 c->y = MAX(c->y, wy);
967 wc.border_width = c->bw;
968 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
969 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
970 configure(c); /* propagates border_width, if size doesn't change */
972 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
973 grabbuttons(c, False);
975 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
976 for(t = clients; t && t->win != trans; t = t->next);
978 memcpy(c->tags, t->tags, TAGSZ);
982 c->isfloating = (rettrans == Success) || c->isfixed;
985 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
987 XMapWindow(dpy, c->win);
988 setclientstate(c, NormalState);
993 mappingnotify(XEvent *e) {
994 XMappingEvent *ev = &e->xmapping;
996 XRefreshKeyboardMapping(ev);
997 if(ev->request == MappingKeyboard)
1002 maprequest(XEvent *e) {
1003 static XWindowAttributes wa;
1004 XMapRequestEvent *ev = &e->xmaprequest;
1006 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1008 if(wa.override_redirect)
1010 if(!getclient(ev->window))
1011 manage(ev->window, &wa);
1015 movemouse(Client *c) {
1016 int x1, y1, ocx, ocy, di, nx, ny;
1023 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1024 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1026 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1028 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1031 XUngrabPointer(dpy, CurrentTime);
1033 case ConfigureRequest:
1036 handler[ev.type](&ev);
1040 nx = ocx + (ev.xmotion.x - x1);
1041 ny = ocy + (ev.xmotion.y - y1);
1042 if(abs(wx - nx) < snap)
1044 else if(abs((wx + ww) - (nx + c->w + 2 * c->bw)) < snap)
1045 nx = wx + ww - c->w - 2 * c->bw;
1046 if(abs(wy - ny) < snap)
1048 else if(abs((wy + wh) - (ny + c->h + 2 * c->bw)) < snap)
1049 ny = wy + wh - c->h - 2 * c->bw;
1050 if(!c->isfloating && lt->arrange && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
1051 togglefloating(NULL);
1052 if(!lt->arrange || c->isfloating)
1053 resize(c, nx, ny, c->w, c->h, False);
1060 nextunfloating(Client *c) {
1061 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1066 propertynotify(XEvent *e) {
1069 XPropertyEvent *ev = &e->xproperty;
1071 if(ev->state == PropertyDelete)
1072 return; /* ignore */
1073 if((c = getclient(ev->window))) {
1076 case XA_WM_TRANSIENT_FOR:
1077 XGetTransientForHint(dpy, c->win, &trans);
1078 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1081 case XA_WM_NORMAL_HINTS:
1089 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1098 quit(const char *arg) {
1099 readin = running = False;
1103 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1107 /* set minimum possible */
1111 /* temporarily remove base dimensions */
1115 /* adjust for aspect limits */
1116 if(c->minax != c->maxax && c->minay != c->maxay
1117 && c->minax > 0 && c->maxax > 0 && c->minay > 0 && c->maxay > 0) {
1118 if(w * c->maxay > h * c->maxax)
1119 w = h * c->maxax / c->maxay;
1120 else if(w * c->minay < h * c->minax)
1121 h = w * c->minay / c->minax;
1124 /* adjust for increment value */
1130 /* restore base dimensions */
1134 w = MAX(w, c->minw);
1135 h = MAX(h, c->minh);
1138 w = MIN(w, c->maxw);
1141 h = MIN(h, c->maxh);
1143 if(w <= 0 || h <= 0)
1146 x = sw - w - 2 * c->bw;
1148 y = sh - h - 2 * c->bw;
1149 if(x + w + 2 * c->bw < sx)
1151 if(y + h + 2 * c->bw < sy)
1153 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1156 c->w = wc.width = w;
1157 c->h = wc.height = h;
1158 wc.border_width = c->bw;
1159 XConfigureWindow(dpy, c->win,
1160 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1167 resizemouse(Client *c) {
1174 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1175 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1177 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1179 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1182 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1183 c->w + c->bw - 1, c->h + c->bw - 1);
1184 XUngrabPointer(dpy, CurrentTime);
1185 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1187 case ConfigureRequest:
1190 handler[ev.type](&ev);
1194 nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1195 nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1196 if(!c->isfloating && lt->arrange && (abs(nw - c->w) > snap || abs(nh - c->h) > snap)) {
1197 togglefloating(NULL);
1199 if(!lt->arrange || c->isfloating)
1200 resize(c, c->x, c->y, nw, nh, True);
1215 if(sel->isfloating || !lt->arrange)
1216 XRaiseWindow(dpy, sel->win);
1218 wc.stack_mode = Below;
1219 wc.sibling = barwin;
1220 for(c = stack; c; c = c->snext)
1221 if(!c->isfloating && isvisible(c)) {
1222 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1223 wc.sibling = c->win;
1227 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1233 char sbuf[sizeof stext];
1236 unsigned int len, offset;
1239 /* main event loop, also reads status text from stdin */
1241 xfd = ConnectionNumber(dpy);
1244 len = sizeof stext - 1;
1245 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1249 FD_SET(STDIN_FILENO, &rd);
1251 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1254 eprint("select failed\n");
1256 if(FD_ISSET(STDIN_FILENO, &rd)) {
1257 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1259 strncpy(stext, strerror(errno), len);
1263 strncpy(stext, "EOF", 4);
1267 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1268 if(*p == '\n' || *p == '\0') {
1270 strncpy(stext, sbuf, len);
1271 p += r - 1; /* p is sbuf + offset + r - 1 */
1272 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1275 memmove(sbuf, p - r + 1, r);
1282 while(XPending(dpy)) {
1283 XNextEvent(dpy, &ev);
1284 if(handler[ev.type])
1285 (handler[ev.type])(&ev); /* call handler */
1292 unsigned int i, num;
1293 Window *wins, d1, d2;
1294 XWindowAttributes wa;
1297 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1298 for(i = 0; i < num; i++) {
1299 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1300 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1302 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1303 manage(wins[i], &wa);
1305 for(i = 0; i < num; i++) { /* now the transients */
1306 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1308 if(XGetTransientForHint(dpy, wins[i], &d1)
1309 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1310 manage(wins[i], &wa);
1318 setclientstate(Client *c, long state) {
1319 long data[] = {state, None};
1321 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1322 PropModeReplace, (unsigned char *)data, 2);
1328 XSetWindowAttributes wa;
1331 screen = DefaultScreen(dpy);
1332 root = RootWindow(dpy, screen);
1336 sw = DisplayWidth(dpy, screen);
1337 sh = DisplayHeight(dpy, screen);
1338 bh = dc.font.height + 2;
1342 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1343 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1344 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1345 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1346 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1347 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1350 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1351 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1352 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1354 /* init appearance */
1355 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1356 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1357 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1358 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1359 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1360 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1363 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1364 dc.gc = XCreateGC(dpy, root, 0, 0);
1365 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1367 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1370 tagset[0] = emallocz(TAGSZ);
1371 tagset[1] = emallocz(TAGSZ);
1372 tagset[0][0] = tagset[1][0] = True;
1375 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1376 w = textw(layouts[i].symbol);
1380 wa.override_redirect = 1;
1381 wa.background_pixmap = ParentRelative;
1382 wa.event_mask = ButtonPressMask|ExposureMask;
1384 barwin = XCreateWindow(dpy, root, bx, by, bw, bh, 0, DefaultDepth(dpy, screen),
1385 CopyFromParent, DefaultVisual(dpy, screen),
1386 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1387 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1388 XMapRaised(dpy, barwin);
1389 strcpy(stext, "dwm-"VERSION);
1392 /* EWMH support per view */
1393 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1394 PropModeReplace, (unsigned char *) netatom, NetLast);
1396 /* select for events */
1397 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1398 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1399 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1400 XSelectInput(dpy, root, wa.event_mask);
1408 spawn(const char *arg) {
1409 static char *shell = NULL;
1411 if(!shell && !(shell = getenv("SHELL")))
1415 /* The double-fork construct avoids zombie processes and keeps the code
1416 * clean from stupid signal handlers. */
1420 close(ConnectionNumber(dpy));
1422 execl(shell, shell, "-c", arg, (char *)NULL);
1423 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1432 tag(const char *arg) {
1437 for(i = 0; i < LENGTH(tags); i++)
1438 sel->tags[i] = (arg == NULL);
1439 sel->tags[idxoftag(arg)] = True;
1444 textnw(const char *text, unsigned int len) {
1448 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1451 return XTextWidth(dc.font.xfont, text, len);
1455 textw(const char *text) {
1456 return textnw(text, strlen(text)) + dc.font.height;
1460 togglebar(const char *arg) {
1468 togglefloating(const char *arg) {
1471 sel->isfloating = !sel->isfloating;
1473 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1478 togglelayout(const char *arg) {
1482 if(++lt == &layouts[LENGTH(layouts)])
1486 for(i = 0; i < LENGTH(layouts); i++)
1487 if(!strcmp(arg, layouts[i].symbol))
1489 if(i == LENGTH(layouts))
1500 toggletag(const char *arg) {
1506 sel->tags[i] = !sel->tags[i];
1507 for(j = 0; j < LENGTH(tags) && !sel->tags[j]; j++);
1508 if(j == LENGTH(tags))
1509 sel->tags[i] = True; /* at least one tag must be enabled */
1514 toggleview(const char *arg) {
1518 tagset[seltags][i] = !tagset[seltags][i];
1519 for(j = 0; j < LENGTH(tags) && !tagset[seltags][j]; j++);
1520 if(j == LENGTH(tags))
1521 tagset[seltags][i] = True; /* at least one tag must be viewed */
1529 XMoveWindow(dpy, c->win, c->x, c->y);
1530 c->isbanned = False;
1534 unmanage(Client *c) {
1537 wc.border_width = c->oldbw;
1538 /* The server grab construct avoids race conditions. */
1540 XSetErrorHandler(xerrordummy);
1541 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1546 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1547 setclientstate(c, WithdrawnState);
1551 XSetErrorHandler(xerror);
1557 unmapnotify(XEvent *e) {
1559 XUnmapEvent *ev = &e->xunmap;
1561 if((c = getclient(ev->window)))
1567 if(dc.drawable != 0)
1568 XFreePixmap(dpy, dc.drawable);
1569 dc.drawable = XCreatePixmap(dpy, root, bw, bh, DefaultDepth(dpy, screen));
1570 XMoveResizeWindow(dpy, barwin, bx, by, bw, bh);
1577 #ifdef DEFGEOM /* define your own if you are Xinerama user */
1582 by = showbar ? (topbar ? 0 : sh - bh) : -bh;
1585 /* window area geometry */
1587 wy = showbar && topbar ? sy + bh : sy;
1589 wh = showbar ? sh - bh : sh;
1592 /* update layout geometries */
1593 for(i = 0; i < LENGTH(layouts); i++)
1594 if(layouts[i].updategeom)
1595 layouts[i].updategeom();
1599 updatesizehints(Client *c) {
1603 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1605 c->flags = size.flags;
1606 if(c->flags & PBaseSize) {
1607 c->basew = size.base_width;
1608 c->baseh = size.base_height;
1610 else if(c->flags & PMinSize) {
1611 c->basew = size.min_width;
1612 c->baseh = size.min_height;
1615 c->basew = c->baseh = 0;
1616 if(c->flags & PResizeInc) {
1617 c->incw = size.width_inc;
1618 c->inch = size.height_inc;
1621 c->incw = c->inch = 0;
1622 if(c->flags & PMaxSize) {
1623 c->maxw = size.max_width;
1624 c->maxh = size.max_height;
1627 c->maxw = c->maxh = 0;
1628 if(c->flags & PMinSize) {
1629 c->minw = size.min_width;
1630 c->minh = size.min_height;
1632 else if(c->flags & PBaseSize) {
1633 c->minw = size.base_width;
1634 c->minh = size.base_height;
1637 c->minw = c->minh = 0;
1638 if(c->flags & PAspect) {
1639 c->minax = size.min_aspect.x;
1640 c->maxax = size.max_aspect.x;
1641 c->minay = size.min_aspect.y;
1642 c->maxay = size.max_aspect.y;
1645 c->minax = c->maxax = c->minay = c->maxay = 0;
1646 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1647 && c->maxw == c->minw && c->maxh == c->minh);
1651 updatetitle(Client *c) {
1652 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1653 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1657 updatewmhints(Client *c) {
1660 if((wmh = XGetWMHints(dpy, c->win))) {
1662 sel->isurgent = False;
1664 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1670 view(const char *arg) {
1671 seltags ^= 1; /* toggle sel tagset */
1672 memset(tagset[seltags], (NULL == arg), TAGSZ);
1673 tagset[seltags][idxoftag(arg)] = True;
1678 viewprevtag(const char *arg) {
1679 seltags ^= 1; /* toggle sel tagset */
1683 /* There's no way to check accesses to destroyed windows, thus those cases are
1684 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1685 * default error handler, which may call exit. */
1687 xerror(Display *dpy, XErrorEvent *ee) {
1688 if(ee->error_code == BadWindow
1689 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1690 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1691 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1692 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1693 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1694 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1695 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1696 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1698 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1699 ee->request_code, ee->error_code);
1700 return xerrorxlib(dpy, ee); /* may call exit */
1704 xerrordummy(Display *dpy, XErrorEvent *ee) {
1708 /* Startup Error handler to check if another window manager
1709 * is already running. */
1711 xerrorstart(Display *dpy, XErrorEvent *ee) {
1717 main(int argc, char *argv[]) {
1718 if(argc == 2 && !strcmp("-v", argv[1]))
1719 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1721 eprint("usage: dwm [-v]\n");
1723 setlocale(LC_CTYPE, "");
1724 if(!(dpy = XOpenDisplay(0)))
1725 eprint("dwm: cannot open display\n");