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 { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
54 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
55 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
56 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
59 typedef struct Client Client;
63 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
64 int minax, maxax, minay, maxay;
66 unsigned int bw, oldbw;
67 Bool isbanned, isfixed, isfloating, isurgent;
77 unsigned long norm[ColLast];
78 unsigned long sel[ColLast];
88 } DC; /* draw context */
93 void (*func)(const char *arg);
99 void (*arrange)(void);
100 void (*updategeom)(void);
105 const char *instance;
111 /* function declarations */
112 void applyrules(Client *c);
114 void attach(Client *c);
115 void attachstack(Client *c);
117 void buttonpress(XEvent *e);
118 void checkotherwm(void);
120 void configure(Client *c);
121 void configurenotify(XEvent *e);
122 void configurerequest(XEvent *e);
123 void destroynotify(XEvent *e);
124 void detach(Client *c);
125 void detachstack(Client *c);
127 void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
128 void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
129 void *emallocz(unsigned int size);
130 void enternotify(XEvent *e);
131 void eprint(const char *errstr, ...);
132 void expose(XEvent *e);
133 void focus(Client *c);
134 void focusin(XEvent *e);
135 void focusnext(const char *arg);
136 void focusprev(const char *arg);
137 Client *getclient(Window w);
138 unsigned long getcolor(const char *colstr);
139 long getstate(Window w);
140 Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
141 void grabbuttons(Client *c, Bool focused);
143 unsigned int idxoftag(const char *t);
144 void initfont(const char *fontstr);
145 Bool isoccupied(unsigned int t);
146 Bool isprotodel(Client *c);
147 Bool isurgent(unsigned int t);
148 Bool isvisible(Client *c, Bool *cmp);
149 void keypress(XEvent *e);
150 void killclient(const char *arg);
151 void manage(Window w, XWindowAttributes *wa);
152 void mappingnotify(XEvent *e);
153 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 togglefloating(const char *arg);
171 void togglelayout(const char *arg);
172 void toggletag(const char *arg);
173 void toggleview(const char *arg);
174 void unban(Client *c);
175 void unmanage(Client *c);
176 void unmapnotify(XEvent *e);
177 void updatebar(void);
178 void updategeom(void);
179 void updatesizehints(Client *c);
180 void updatetitle(Client *c);
181 void updatewmhints(Client *c);
182 void view(const char *arg);
183 void viewprevtag(const char *arg); /* views previous selected tags */
184 int xerror(Display *dpy, XErrorEvent *ee);
185 int xerrordummy(Display *dpy, XErrorEvent *ee);
186 int xerrorstart(Display *dpy, XErrorEvent *ee);
187 void zoom(const char *arg);
191 int screen, sx, sy, sw, sh;
192 int (*xerrorxlib)(Display *, XErrorEvent *);
193 int bx, by, bw, bh, blw, wx, wy, ww, wh;
195 unsigned int numlockmask = 0;
196 void (*handler[LASTEvent]) (XEvent *) = {
197 [ButtonPress] = buttonpress,
198 [ConfigureRequest] = configurerequest,
199 [ConfigureNotify] = configurenotify,
200 [DestroyNotify] = destroynotify,
201 [EnterNotify] = enternotify,
204 [KeyPress] = keypress,
205 [MappingNotify] = mappingnotify,
206 [MapRequest] = maprequest,
207 [PropertyNotify] = propertynotify,
208 [UnmapNotify] = unmapnotify
210 Atom wmatom[WMLast], netatom[NetLast];
211 Bool otherwm, readin;
214 Client *clients = NULL;
216 Client *stack = NULL;
217 Cursor cursor[CurLast];
221 Layout *lt = layouts;
224 /* configuration, allows nested code to access above variables */
226 #define TAGSZ (LENGTH(tags) * sizeof(Bool))
228 /* function implementations */
231 applyrules(Client *c) {
233 Bool matched = False;
235 XClassHint ch = { 0 };
238 XGetClassHint(dpy, c->win, &ch);
239 for(i = 0; i < LENGTH(rules); i++) {
241 if((!r->title || strstr(c->name, r->title))
242 && (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
243 && (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
244 c->isfloating = r->isfloating;
246 c->tags[idxoftag(r->tag)] = True;
256 memcpy(c->tags, tagset[seltags], TAGSZ);
263 for(c = clients; c; c = c->next)
264 if(isvisible(c, NULL)) {
266 if(!lt->arrange || c->isfloating)
267 resize(c, c->x, c->y, c->w, c->h, True);
287 attachstack(Client *c) {
296 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
301 buttonpress(XEvent *e) {
304 XButtonPressedEvent *ev = &e->xbutton;
306 if(ev->window == barwin) {
308 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) && ev->button == Button1)
329 else if((c = getclient(ev->window))) {
331 if(CLEANMASK(ev->state) != MODKEY)
333 if(ev->button == Button1) {
337 else if(ev->button == Button2) {
338 if(lt->arrange && c->isfloating)
339 togglefloating(NULL);
343 else if(ev->button == Button3 && !c->isfixed) {
353 XSetErrorHandler(xerrorstart);
355 /* this causes an error if some other window manager is running */
356 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
359 eprint("dwm: another window manager is already running\n");
361 XSetErrorHandler(NULL);
362 xerrorxlib = XSetErrorHandler(xerror);
374 XFreeFontSet(dpy, dc.font.set);
376 XFreeFont(dpy, dc.font.xfont);
377 XUngrabKey(dpy, AnyKey, AnyModifier, root);
378 XFreePixmap(dpy, dc.drawable);
380 XFreeCursor(dpy, cursor[CurNormal]);
381 XFreeCursor(dpy, cursor[CurResize]);
382 XFreeCursor(dpy, cursor[CurMove]);
383 XDestroyWindow(dpy, barwin);
385 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
389 configure(Client *c) {
392 ce.type = ConfigureNotify;
400 ce.border_width = c->bw;
402 ce.override_redirect = False;
403 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
407 configurenotify(XEvent *e) {
408 XConfigureEvent *ev = &e->xconfigure;
410 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
420 configurerequest(XEvent *e) {
422 XConfigureRequestEvent *ev = &e->xconfigurerequest;
425 if((c = getclient(ev->window))) {
426 if(ev->value_mask & CWBorderWidth)
427 c->bw = ev->border_width;
428 if(c->isfixed || c->isfloating || !lt->arrange) {
429 if(ev->value_mask & CWX)
431 if(ev->value_mask & CWY)
433 if(ev->value_mask & CWWidth)
435 if(ev->value_mask & CWHeight)
437 if((c->x - sx + c->w) > sw && c->isfloating)
438 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
439 if((c->y - sy + c->h) > sh && c->isfloating)
440 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
441 if((ev->value_mask & (CWX|CWY))
442 && !(ev->value_mask & (CWWidth|CWHeight)))
444 if(isvisible(c, NULL))
445 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
453 wc.width = ev->width;
454 wc.height = ev->height;
455 wc.border_width = ev->border_width;
456 wc.sibling = ev->above;
457 wc.stack_mode = ev->detail;
458 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
464 destroynotify(XEvent *e) {
466 XDestroyWindowEvent *ev = &e->xdestroywindow;
468 if((c = getclient(ev->window)))
475 c->prev->next = c->next;
477 c->next->prev = c->prev;
480 c->next = c->prev = NULL;
484 detachstack(Client *c) {
487 for(tc = &stack; *tc && *tc != c; tc = &(*tc)->snext);
497 for(c = stack; c && !isvisible(c, NULL); c = c->snext);
498 for(i = 0; i < LENGTH(tags); i++) {
499 dc.w = textw(tags[i]);
500 if(tagset[seltags][i]) {
501 drawtext(tags[i], dc.sel, isurgent(i));
502 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.sel);
505 drawtext(tags[i], dc.norm, isurgent(i));
506 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.norm);
512 drawtext(lt->symbol, dc.norm, False);
523 drawtext(stext, dc.norm, False);
524 if((dc.w = dc.x - x) > bh) {
527 drawtext(c->name, dc.sel, False);
528 drawsquare(False, c->isfloating, False, dc.sel);
531 drawtext(NULL, dc.norm, False);
533 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, bw, bh, 0, 0);
538 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
541 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
543 gcv.foreground = col[invert ? ColBG : ColFG];
544 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
545 x = (dc.font.ascent + dc.font.descent + 2) / 4;
549 r.width = r.height = x + 1;
550 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
553 r.width = r.height = x;
554 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
559 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
561 unsigned int len, olen;
562 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
565 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
566 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
570 len = MIN(olen, sizeof buf);
571 memcpy(buf, text, len);
573 h = dc.font.ascent + dc.font.descent;
574 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
576 /* shorten text if necessary */
577 for(; len && (w = textnw(buf, len)) > dc.w - h; len--);
588 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
590 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
592 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
596 emallocz(unsigned int size) {
597 void *res = calloc(1, size);
600 eprint("fatal: could not malloc() %u bytes\n", size);
605 enternotify(XEvent *e) {
607 XCrossingEvent *ev = &e->xcrossing;
609 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
611 if((c = getclient(ev->window)))
618 eprint(const char *errstr, ...) {
621 va_start(ap, errstr);
622 vfprintf(stderr, errstr, ap);
629 XExposeEvent *ev = &e->xexpose;
631 if(ev->count == 0 && (ev->window == barwin))
637 if(!c || (c && !isvisible(c, NULL)))
638 for(c = stack; c && !isvisible(c, NULL); c = c->snext);
639 if(sel && sel != c) {
640 grabbuttons(sel, False);
641 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
646 grabbuttons(c, True);
650 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
651 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
654 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
659 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
660 XFocusChangeEvent *ev = &e->xfocus;
662 if(sel && ev->window != sel->win)
663 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
667 focusnext(const char *arg) {
672 for(c = sel->next; c && !isvisible(c, arg ? sel->tags : NULL); c = c->next);
674 for(c = clients; c && !isvisible(c, arg ? sel->tags : NULL); c = c->next);
682 focusprev(const char *arg) {
687 for(c = sel->prev; c && !isvisible(c, arg ? sel->tags : NULL); c = c->prev);
689 for(c = clients; c && c->next; c = c->next);
690 for(; c && !isvisible(c, arg ? sel->tags : NULL); c = c->prev);
699 getclient(Window w) {
702 for(c = clients; c && c->win != w; c = c->next);
707 getcolor(const char *colstr) {
708 Colormap cmap = DefaultColormap(dpy, screen);
711 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
712 eprint("error, cannot allocate color '%s'\n", colstr);
720 unsigned char *p = NULL;
721 unsigned long n, extra;
724 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
725 &real, &format, &n, &extra, (unsigned char **)&p);
726 if(status != Success)
735 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
740 if(!text || size == 0)
743 XGetTextProperty(dpy, w, &name, atom);
746 if(name.encoding == XA_STRING)
747 strncpy(text, (char *)name.value, size - 1);
749 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
751 strncpy(text, *list, size - 1);
752 XFreeStringList(list);
755 text[size - 1] = '\0';
761 grabbuttons(Client *c, Bool focused) {
763 unsigned int buttons[] = { Button1, Button2, Button3 };
764 unsigned int modifiers[] = { MODKEY, MODKEY|LockMask, MODKEY|numlockmask,
765 MODKEY|numlockmask|LockMask} ;
767 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
769 for(i = 0; i < LENGTH(buttons); i++)
770 for(j = 0; j < LENGTH(modifiers); j++)
771 XGrabButton(dpy, buttons[i], modifiers[j], c->win, False,
772 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
774 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
775 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
782 XModifierKeymap *modmap;
784 /* init modifier map */
785 modmap = XGetModifierMapping(dpy);
786 for(i = 0; i < 8; i++)
787 for(j = 0; j < modmap->max_keypermod; j++) {
788 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
789 numlockmask = (1 << i);
791 XFreeModifiermap(modmap);
793 XUngrabKey(dpy, AnyKey, AnyModifier, root);
794 for(i = 0; i < LENGTH(keys); i++) {
795 code = XKeysymToKeycode(dpy, keys[i].keysym);
796 XGrabKey(dpy, code, keys[i].mod, root, True,
797 GrabModeAsync, GrabModeAsync);
798 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
799 GrabModeAsync, GrabModeAsync);
800 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
801 GrabModeAsync, GrabModeAsync);
802 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
803 GrabModeAsync, GrabModeAsync);
808 idxoftag(const char *t) {
811 for(i = 0; (i < LENGTH(tags)) && t && strcmp(tags[i], t); i++);
812 return (i < LENGTH(tags)) ? i : 0;
816 initfont(const char *fontstr) {
817 char *def, **missing;
822 XFreeFontSet(dpy, dc.font.set);
823 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
826 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
827 XFreeStringList(missing);
830 XFontSetExtents *font_extents;
831 XFontStruct **xfonts;
833 dc.font.ascent = dc.font.descent = 0;
834 font_extents = XExtentsOfFontSet(dc.font.set);
835 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
836 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
837 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
838 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
844 XFreeFont(dpy, dc.font.xfont);
845 dc.font.xfont = NULL;
846 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
847 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
848 eprint("error, cannot load font: '%s'\n", fontstr);
849 dc.font.ascent = dc.font.xfont->ascent;
850 dc.font.descent = dc.font.xfont->descent;
852 dc.font.height = dc.font.ascent + dc.font.descent;
856 isoccupied(unsigned int t) {
859 for(c = clients; c; c = c->next)
866 isprotodel(Client *c) {
871 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
872 for(i = 0; !ret && i < n; i++)
873 if(protocols[i] == wmatom[WMDelete])
881 isurgent(unsigned int t) {
884 for(c = clients; c; c = c->next)
885 if(c->isurgent && c->tags[t])
891 isvisible(Client *c, Bool *cmp) {
895 cmp = tagset[seltags];
896 for(i = 0; i < LENGTH(tags); i++)
897 if(c->tags[i] && cmp[i])
903 keypress(XEvent *e) {
909 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
910 for(i = 0; i < LENGTH(keys); i++)
911 if(keysym == keys[i].keysym
912 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
915 keys[i].func(keys[i].arg);
920 killclient(const char *arg) {
925 if(isprotodel(sel)) {
926 ev.type = ClientMessage;
927 ev.xclient.window = sel->win;
928 ev.xclient.message_type = wmatom[WMProtocols];
929 ev.xclient.format = 32;
930 ev.xclient.data.l[0] = wmatom[WMDelete];
931 ev.xclient.data.l[1] = CurrentTime;
932 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
935 XKillClient(dpy, sel->win);
939 manage(Window w, XWindowAttributes *wa) {
940 Client *c, *t = NULL;
945 c = emallocz(sizeof(Client));
946 c->tags = emallocz(TAGSZ);
954 c->oldbw = wa->border_width;
955 if(c->w == sw && c->h == sh) {
958 c->bw = wa->border_width;
961 if(c->x + c->w + 2 * c->bw > wx + ww)
962 c->x = wx + ww - c->w - 2 * c->bw;
963 if(c->y + c->h + 2 * c->bw > wy + wh)
964 c->y = wy + wh - c->h - 2 * c->bw;
965 c->x = MAX(c->x, wx);
966 c->y = MAX(c->y, wy);
970 wc.border_width = c->bw;
971 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
972 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
973 configure(c); /* propagates border_width, if size doesn't change */
975 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
976 grabbuttons(c, False);
978 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
979 for(t = clients; t && t->win != trans; t = t->next);
981 memcpy(c->tags, t->tags, TAGSZ);
985 c->isfloating = (rettrans == Success) || c->isfixed;
988 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
990 XMapWindow(dpy, c->win);
991 setclientstate(c, NormalState);
996 mappingnotify(XEvent *e) {
997 XMappingEvent *ev = &e->xmapping;
999 XRefreshKeyboardMapping(ev);
1000 if(ev->request == MappingKeyboard)
1005 maprequest(XEvent *e) {
1006 static XWindowAttributes wa;
1007 XMapRequestEvent *ev = &e->xmaprequest;
1009 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1011 if(wa.override_redirect)
1013 if(!getclient(ev->window))
1014 manage(ev->window, &wa);
1021 for(c = clients; c; c = c->next)
1022 if(!c->isfloating && isvisible(c, NULL))
1023 resize(c, wx, wy, ww - 2 * c->bw, wh - 2 * c->bw, RESIZEHINTS);
1027 movemouse(Client *c) {
1028 int x1, y1, ocx, ocy, di, nx, ny;
1035 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1036 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1038 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1040 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1043 XUngrabPointer(dpy, CurrentTime);
1045 case ConfigureRequest:
1048 handler[ev.type](&ev);
1052 nx = ocx + (ev.xmotion.x - x1);
1053 ny = ocy + (ev.xmotion.y - y1);
1054 if(abs(wx - nx) < SNAP)
1056 else if(abs((wx + ww) - (nx + c->w + 2 * c->bw)) < SNAP)
1057 nx = wx + ww - c->w - 2 * c->bw;
1058 if(abs(wy - ny) < SNAP)
1060 else if(abs((wy + wh) - (ny + c->h + 2 * c->bw)) < SNAP)
1061 ny = wy + wh - c->h - 2 * c->bw;
1062 if(!c->isfloating && lt->arrange && (abs(nx - c->x) > SNAP || abs(ny - c->y) > SNAP))
1063 togglefloating(NULL);
1064 if(!lt->arrange || c->isfloating)
1065 resize(c, nx, ny, c->w, c->h, False);
1072 nextunfloating(Client *c) {
1073 for(; c && (c->isfloating || !isvisible(c, NULL)); c = c->next);
1078 propertynotify(XEvent *e) {
1081 XPropertyEvent *ev = &e->xproperty;
1083 if(ev->state == PropertyDelete)
1084 return; /* ignore */
1085 if((c = getclient(ev->window))) {
1088 case XA_WM_TRANSIENT_FOR:
1089 XGetTransientForHint(dpy, c->win, &trans);
1090 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1093 case XA_WM_NORMAL_HINTS:
1101 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1110 quit(const char *arg) {
1111 readin = running = False;
1115 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1119 /* set minimum possible */
1123 /* temporarily remove base dimensions */
1127 /* adjust for aspect limits */
1128 if(c->minax != c->maxax && c->minay != c->maxay
1129 && c->minax > 0 && c->maxax > 0 && c->minay > 0 && c->maxay > 0) {
1130 if(w * c->maxay > h * c->maxax)
1131 w = h * c->maxax / c->maxay;
1132 else if(w * c->minay < h * c->minax)
1133 h = w * c->minay / c->minax;
1136 /* adjust for increment value */
1142 /* restore base dimensions */
1146 w = MAX(w, c->minw);
1147 h = MAX(h, c->minh);
1150 w = MIN(w, c->maxw);
1153 h = MIN(h, c->maxh);
1155 if(w <= 0 || h <= 0)
1158 x = sw - w - 2 * c->bw;
1160 y = sh - h - 2 * c->bw;
1161 if(x + w + 2 * c->bw < sx)
1163 if(y + h + 2 * c->bw < sy)
1165 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1168 c->w = wc.width = w;
1169 c->h = wc.height = h;
1170 wc.border_width = c->bw;
1171 XConfigureWindow(dpy, c->win,
1172 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1179 resizemouse(Client *c) {
1186 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1187 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1189 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1191 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1194 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1195 c->w + c->bw - 1, c->h + c->bw - 1);
1196 XUngrabPointer(dpy, CurrentTime);
1197 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1199 case ConfigureRequest:
1202 handler[ev.type](&ev);
1206 nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1207 nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1208 if(!c->isfloating && lt->arrange && (abs(nw - c->w) > SNAP || abs(nh - c->h) > SNAP)) {
1209 togglefloating(NULL);
1211 if(!lt->arrange || c->isfloating)
1212 resize(c, c->x, c->y, nw, nh, True);
1227 if(sel->isfloating || !lt->arrange)
1228 XRaiseWindow(dpy, sel->win);
1230 wc.stack_mode = Below;
1231 wc.sibling = barwin;
1232 for(c = stack; c; c = c->snext)
1233 if(!c->isfloating && isvisible(c, NULL)) {
1234 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1235 wc.sibling = c->win;
1239 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1245 char sbuf[sizeof stext];
1248 unsigned int len, offset;
1251 /* main event loop, also reads status text from stdin */
1253 xfd = ConnectionNumber(dpy);
1256 len = sizeof stext - 1;
1257 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1261 FD_SET(STDIN_FILENO, &rd);
1263 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1266 eprint("select failed\n");
1268 if(FD_ISSET(STDIN_FILENO, &rd)) {
1269 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1271 strncpy(stext, strerror(errno), len);
1275 strncpy(stext, "EOF", 4);
1279 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1280 if(*p == '\n' || *p == '\0') {
1282 strncpy(stext, sbuf, len);
1283 p += r - 1; /* p is sbuf + offset + r - 1 */
1284 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1287 memmove(sbuf, p - r + 1, r);
1294 while(XPending(dpy)) {
1295 XNextEvent(dpy, &ev);
1296 if(handler[ev.type])
1297 (handler[ev.type])(&ev); /* call handler */
1304 unsigned int i, num;
1305 Window *wins, d1, d2;
1306 XWindowAttributes wa;
1309 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1310 for(i = 0; i < num; i++) {
1311 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1312 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1314 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1315 manage(wins[i], &wa);
1317 for(i = 0; i < num; i++) { /* now the transients */
1318 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1320 if(XGetTransientForHint(dpy, wins[i], &d1)
1321 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1322 manage(wins[i], &wa);
1330 setclientstate(Client *c, long state) {
1331 long data[] = {state, None};
1333 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1334 PropModeReplace, (unsigned char *)data, 2);
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 tagset[0] = emallocz(TAGSZ);
1383 tagset[1] = emallocz(TAGSZ);
1384 tagset[0][0] = tagset[1][0] = True;
1387 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1388 w = textw(layouts[i].symbol);
1392 wa.override_redirect = 1;
1393 wa.background_pixmap = ParentRelative;
1394 wa.event_mask = ButtonPressMask|ExposureMask;
1396 barwin = XCreateWindow(dpy, root, bx, by, bw, bh, 0, DefaultDepth(dpy, screen),
1397 CopyFromParent, DefaultVisual(dpy, screen),
1398 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1399 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1400 XMapRaised(dpy, barwin);
1401 strcpy(stext, "dwm-"VERSION);
1404 /* EWMH support per view */
1405 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1406 PropModeReplace, (unsigned char *) netatom, NetLast);
1408 /* select for events */
1409 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1410 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1411 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1412 XSelectInput(dpy, root, wa.event_mask);
1420 spawn(const char *arg) {
1421 static char *shell = NULL;
1423 if(!shell && !(shell = getenv("SHELL")))
1427 /* The double-fork construct avoids zombie processes and keeps the code
1428 * clean from stupid signal handlers. */
1432 close(ConnectionNumber(dpy));
1434 execl(shell, shell, "-c", arg, (char *)NULL);
1435 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1444 tag(const char *arg) {
1449 for(i = 0; i < LENGTH(tags); i++)
1450 sel->tags[i] = (arg == NULL);
1451 sel->tags[idxoftag(arg)] = True;
1456 textnw(const char *text, unsigned int len) {
1460 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1463 return XTextWidth(dc.font.xfont, text, len);
1467 textw(const char *text) {
1468 return textnw(text, strlen(text)) + dc.font.height;
1472 togglefloating(const char *arg) {
1475 sel->isfloating = !sel->isfloating;
1477 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1482 togglelayout(const char *arg) {
1486 if(++lt == &layouts[LENGTH(layouts)])
1490 for(i = 0; i < LENGTH(layouts); i++)
1491 if(!strcmp(arg, layouts[i].symbol))
1493 if(i == LENGTH(layouts))
1504 toggletag(const char *arg) {
1510 sel->tags[i] = !sel->tags[i];
1511 for(j = 0; j < LENGTH(tags) && !sel->tags[j]; j++);
1512 if(j == LENGTH(tags))
1513 sel->tags[i] = True; /* at least one tag must be enabled */
1518 toggleview(const char *arg) {
1522 tagset[seltags][i] = !tagset[seltags][i];
1523 for(j = 0; j < LENGTH(tags) && !tagset[seltags][j]; j++);
1524 if(j == LENGTH(tags))
1525 tagset[seltags][i] = True; /* at least one tag must be viewed */
1533 XMoveWindow(dpy, c->win, c->x, c->y);
1534 c->isbanned = False;
1538 unmanage(Client *c) {
1541 wc.border_width = c->oldbw;
1542 /* The server grab construct avoids race conditions. */
1544 XSetErrorHandler(xerrordummy);
1545 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1550 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1551 setclientstate(c, WithdrawnState);
1555 XSetErrorHandler(xerror);
1561 unmapnotify(XEvent *e) {
1563 XUnmapEvent *ev = &e->xunmap;
1565 if((c = getclient(ev->window)))
1571 if(dc.drawable != 0)
1572 XFreePixmap(dpy, dc.drawable);
1573 dc.drawable = XCreatePixmap(dpy, root, bw, bh, DefaultDepth(dpy, screen));
1574 XMoveResizeWindow(dpy, barwin, bx, by, bw, bh);
1586 /* window area geometry */
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");