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);
104 const char *instance;
110 /* function declarations */
111 void applyrules(Client *c);
113 void attach(Client *c);
114 void attachstack(Client *c);
116 void buttonpress(XEvent *e);
117 void checkotherwm(void);
119 void configure(Client *c);
120 void configurenotify(XEvent *e);
121 void configurerequest(XEvent *e);
122 void destroynotify(XEvent *e);
123 void detach(Client *c);
124 void detachstack(Client *c);
126 void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
127 void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
128 void *emallocz(unsigned int size);
129 void enternotify(XEvent *e);
130 void eprint(const char *errstr, ...);
131 void expose(XEvent *e);
132 void focus(Client *c);
133 void focusin(XEvent *e);
134 void focusnext(const char *arg);
135 void focusprev(const char *arg);
136 Client *getclient(Window w);
137 unsigned long getcolor(const char *colstr);
138 long getstate(Window w);
139 Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
140 void grabbuttons(Client *c, Bool focused);
142 unsigned int idxoftag(const char *t);
143 void initfont(const char *fontstr);
144 Bool isoccupied(unsigned int t);
145 Bool isprotodel(Client *c);
146 Bool isurgent(unsigned int t);
147 Bool isvisible(Client *c, Bool *cmp);
148 void keypress(XEvent *e);
149 void killclient(const char *arg);
150 void manage(Window w, XWindowAttributes *wa);
151 void mappingnotify(XEvent *e);
152 void maprequest(XEvent *e);
154 void movemouse(Client *c);
155 Client *nexttiled(Client *c);
156 void propertynotify(XEvent *e);
157 void quit(const char *arg);
158 void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
159 void resizemouse(Client *c);
163 void setclientstate(Client *c, long state);
164 void setmfact(const char *arg);
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 tileresize(Client *c, int x, int y, int w, int h);
172 void togglefloating(const char *arg);
173 void togglelayout(const char *arg);
174 void toggletag(const char *arg);
175 void toggleview(const char *arg);
176 void unban(Client *c);
177 void unmanage(Client *c);
178 void unmapnotify(XEvent *e);
179 void updatebar(void);
180 void updategeom(void);
181 void updatesizehints(Client *c);
182 void updatetitle(Client *c);
183 void updatewmhints(Client *c);
184 void view(const char *arg);
185 void viewprevtag(const char *arg); /* views previous selected tags */
186 int xerror(Display *dpy, XErrorEvent *ee);
187 int xerrordummy(Display *dpy, XErrorEvent *ee);
188 int xerrorstart(Display *dpy, XErrorEvent *ee);
189 void zoom(const char *arg);
193 int screen, sx, sy, sw, sh;
194 int (*xerrorxlib)(Display *, XErrorEvent *);
195 int bx, by, bw, bh, blw, mx, my, mw, mh, tx, ty, tw, th, wx, wy, ww, wh;
198 unsigned int numlockmask = 0;
199 void (*handler[LASTEvent]) (XEvent *) = {
200 [ButtonPress] = buttonpress,
201 [ConfigureRequest] = configurerequest,
202 [ConfigureNotify] = configurenotify,
203 [DestroyNotify] = destroynotify,
204 [EnterNotify] = enternotify,
207 [KeyPress] = keypress,
208 [MappingNotify] = mappingnotify,
209 [MapRequest] = maprequest,
210 [PropertyNotify] = propertynotify,
211 [UnmapNotify] = unmapnotify
213 Atom wmatom[WMLast], netatom[NetLast];
214 Bool otherwm, readin;
217 Client *clients = NULL;
219 Client *stack = NULL;
220 Cursor cursor[CurLast];
224 Layout *lt = layouts;
227 /* configuration, allows nested code to access above variables */
229 #define TAGSZ (LENGTH(tags) * sizeof(Bool))
231 /* function implementations */
234 applyrules(Client *c) {
236 Bool matched = False;
238 XClassHint ch = { 0 };
241 XGetClassHint(dpy, c->win, &ch);
242 for(i = 0; i < LENGTH(rules); i++) {
244 if((!r->title || strstr(c->name, r->title))
245 && (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
246 && (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
247 c->isfloating = r->isfloating;
249 c->tags[idxoftag(r->tag)] = True;
259 memcpy(c->tags, tagset[seltags], TAGSZ);
266 for(c = clients; c; c = c->next)
267 if(isvisible(c, NULL)) {
269 if(!lt->arrange || c->isfloating)
270 resize(c, c->x, c->y, c->w, c->h, True);
290 attachstack(Client *c) {
299 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
304 buttonpress(XEvent *e) {
307 XButtonPressedEvent *ev = &e->xbutton;
309 if(ev->window == barwin) {
311 for(i = 0; i < LENGTH(tags); i++) {
314 if(ev->button == Button1) {
315 if(ev->state & MODKEY)
320 else if(ev->button == Button3) {
321 if(ev->state & MODKEY)
329 if((ev->x < x + blw) && ev->button == Button1)
332 else if((c = getclient(ev->window))) {
334 if(CLEANMASK(ev->state) != MODKEY)
336 if(ev->button == Button1) {
340 else if(ev->button == Button2) {
341 if(lt->arrange && c->isfloating)
342 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)))
447 if(isvisible(c, NULL))
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, NULL); c = c->snext);
501 for(i = 0; i < LENGTH(tags); i++) {
502 dc.w = textw(tags[i]);
503 if(tagset[seltags][i]) {
504 drawtext(tags[i], dc.sel, isurgent(i));
505 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.sel);
508 drawtext(tags[i], dc.norm, isurgent(i));
509 drawsquare(c && c->tags[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, NULL)))
641 for(c = stack; c && !isvisible(c, NULL); 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 char *arg) {
675 for(c = sel->next; c && !isvisible(c, arg ? sel->tags : NULL); c = c->next);
677 for(c = clients; c && !isvisible(c, arg ? sel->tags : NULL); c = c->next);
685 focusprev(const char *arg) {
690 for(c = sel->prev; c && !isvisible(c, arg ? sel->tags : NULL); c = c->prev);
692 for(c = clients; c && c->next; c = c->next);
693 for(; c && !isvisible(c, arg ? sel->tags : NULL); 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 idxoftag(const char *t) {
814 for(i = 0; (i < LENGTH(tags)) && t && strcmp(tags[i], t); i++);
815 return (i < LENGTH(tags)) ? i : 0;
819 initfont(const char *fontstr) {
820 char *def, **missing;
825 XFreeFontSet(dpy, dc.font.set);
826 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
829 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
830 XFreeStringList(missing);
833 XFontSetExtents *font_extents;
834 XFontStruct **xfonts;
836 dc.font.ascent = dc.font.descent = 0;
837 font_extents = XExtentsOfFontSet(dc.font.set);
838 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
839 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
840 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
841 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
847 XFreeFont(dpy, dc.font.xfont);
848 dc.font.xfont = NULL;
849 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
850 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
851 eprint("error, cannot load font: '%s'\n", fontstr);
852 dc.font.ascent = dc.font.xfont->ascent;
853 dc.font.descent = dc.font.xfont->descent;
855 dc.font.height = dc.font.ascent + dc.font.descent;
859 isoccupied(unsigned int t) {
862 for(c = clients; c; c = c->next)
869 isprotodel(Client *c) {
874 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
875 for(i = 0; !ret && i < n; i++)
876 if(protocols[i] == wmatom[WMDelete])
884 isurgent(unsigned int t) {
887 for(c = clients; c; c = c->next)
888 if(c->isurgent && c->tags[t])
894 isvisible(Client *c, Bool *cmp) {
898 cmp = tagset[seltags];
899 for(i = 0; i < LENGTH(tags); i++)
900 if(c->tags[i] && cmp[i])
906 keypress(XEvent *e) {
912 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
913 for(i = 0; i < LENGTH(keys); i++)
914 if(keysym == keys[i].keysym
915 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
918 keys[i].func(keys[i].arg);
923 killclient(const char *arg) {
928 if(isprotodel(sel)) {
929 ev.type = ClientMessage;
930 ev.xclient.window = sel->win;
931 ev.xclient.message_type = wmatom[WMProtocols];
932 ev.xclient.format = 32;
933 ev.xclient.data.l[0] = wmatom[WMDelete];
934 ev.xclient.data.l[1] = CurrentTime;
935 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
938 XKillClient(dpy, sel->win);
942 manage(Window w, XWindowAttributes *wa) {
943 Client *c, *t = NULL;
948 c = emallocz(sizeof(Client));
949 c->tags = emallocz(TAGSZ);
957 c->oldbw = wa->border_width;
958 if(c->w == sw && c->h == sh) {
961 c->bw = wa->border_width;
964 if(c->x + c->w + 2 * c->bw > wx + ww)
965 c->x = wx + ww - c->w - 2 * c->bw;
966 if(c->y + c->h + 2 * c->bw > wy + wh)
967 c->y = wy + wh - c->h - 2 * c->bw;
968 c->x = MAX(c->x, wx);
969 c->y = MAX(c->y, wy);
973 wc.border_width = c->bw;
974 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
975 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
976 configure(c); /* propagates border_width, if size doesn't change */
978 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
979 grabbuttons(c, False);
981 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
982 for(t = clients; t && t->win != trans; t = t->next);
984 memcpy(c->tags, t->tags, TAGSZ);
988 c->isfloating = (rettrans == Success) || c->isfixed;
991 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
993 XMapWindow(dpy, c->win);
994 setclientstate(c, NormalState);
999 mappingnotify(XEvent *e) {
1000 XMappingEvent *ev = &e->xmapping;
1002 XRefreshKeyboardMapping(ev);
1003 if(ev->request == MappingKeyboard)
1008 maprequest(XEvent *e) {
1009 static XWindowAttributes wa;
1010 XMapRequestEvent *ev = &e->xmaprequest;
1012 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1014 if(wa.override_redirect)
1016 if(!getclient(ev->window))
1017 manage(ev->window, &wa);
1024 for(c = clients; c; c = c->next)
1025 if(!c->isfloating && isvisible(c, NULL))
1026 resize(c, wx, wy, ww - 2 * c->bw, wh - 2 * c->bw, RESIZEHINTS);
1030 movemouse(Client *c) {
1031 int x1, y1, ocx, ocy, di, nx, ny;
1038 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1039 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1041 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1043 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1046 XUngrabPointer(dpy, CurrentTime);
1048 case ConfigureRequest:
1051 handler[ev.type](&ev);
1055 nx = ocx + (ev.xmotion.x - x1);
1056 ny = ocy + (ev.xmotion.y - y1);
1057 if(abs(wx - nx) < SNAP)
1059 else if(abs((wx + ww) - (nx + c->w + 2 * c->bw)) < SNAP)
1060 nx = wx + ww - c->w - 2 * c->bw;
1061 if(abs(wy - ny) < SNAP)
1063 else if(abs((wy + wh) - (ny + c->h + 2 * c->bw)) < SNAP)
1064 ny = wy + wh - c->h - 2 * c->bw;
1065 if(!c->isfloating && lt->arrange && (abs(nx - c->x) > SNAP || abs(ny - c->y) > SNAP))
1066 togglefloating(NULL);
1067 if(!lt->arrange || c->isfloating)
1068 resize(c, nx, ny, c->w, c->h, False);
1075 nexttiled(Client *c) {
1076 for(; c && (c->isfloating || !isvisible(c, NULL)); c = c->next);
1081 propertynotify(XEvent *e) {
1084 XPropertyEvent *ev = &e->xproperty;
1086 if(ev->state == PropertyDelete)
1087 return; /* ignore */
1088 if((c = getclient(ev->window))) {
1091 case XA_WM_TRANSIENT_FOR:
1092 XGetTransientForHint(dpy, c->win, &trans);
1093 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1096 case XA_WM_NORMAL_HINTS:
1104 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1113 quit(const char *arg) {
1114 readin = running = False;
1118 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1122 /* set minimum possible */
1126 /* temporarily remove base dimensions */
1130 /* adjust for aspect limits */
1131 if(c->minax != c->maxax && c->minay != c->maxay
1132 && c->minax > 0 && c->maxax > 0 && c->minay > 0 && c->maxay > 0) {
1133 if(w * c->maxay > h * c->maxax)
1134 w = h * c->maxax / c->maxay;
1135 else if(w * c->minay < h * c->minax)
1136 h = w * c->minay / c->minax;
1139 /* adjust for increment value */
1145 /* restore base dimensions */
1149 w = MAX(w, c->minw);
1150 h = MAX(h, c->minh);
1153 w = MIN(w, c->maxw);
1156 h = MIN(h, c->maxh);
1158 if(w <= 0 || h <= 0)
1161 x = sw - w - 2 * c->bw;
1163 y = sh - h - 2 * c->bw;
1164 if(x + w + 2 * c->bw < sx)
1166 if(y + h + 2 * c->bw < sy)
1168 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1171 c->w = wc.width = w;
1172 c->h = wc.height = h;
1173 wc.border_width = c->bw;
1174 XConfigureWindow(dpy, c->win,
1175 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1182 resizemouse(Client *c) {
1189 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1190 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1192 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1194 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1197 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1198 c->w + c->bw - 1, c->h + c->bw - 1);
1199 XUngrabPointer(dpy, CurrentTime);
1200 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1202 case ConfigureRequest:
1205 handler[ev.type](&ev);
1209 nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1210 nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1211 if(!c->isfloating && lt->arrange && (abs(nw - c->w) > SNAP || abs(nh - c->h) > SNAP)) {
1212 togglefloating(NULL);
1214 if(!lt->arrange || c->isfloating)
1215 resize(c, c->x, c->y, nw, nh, True);
1230 if(sel->isfloating || !lt->arrange)
1231 XRaiseWindow(dpy, sel->win);
1233 wc.stack_mode = Below;
1234 wc.sibling = barwin;
1235 for(c = stack; c; c = c->snext)
1236 if(!c->isfloating && isvisible(c, NULL)) {
1237 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1238 wc.sibling = c->win;
1242 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1248 char sbuf[sizeof stext];
1251 unsigned int len, offset;
1254 /* main event loop, also reads status text from stdin */
1256 xfd = ConnectionNumber(dpy);
1259 len = sizeof stext - 1;
1260 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1264 FD_SET(STDIN_FILENO, &rd);
1266 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1269 eprint("select failed\n");
1271 if(FD_ISSET(STDIN_FILENO, &rd)) {
1272 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1274 strncpy(stext, strerror(errno), len);
1278 strncpy(stext, "EOF", 4);
1282 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1283 if(*p == '\n' || *p == '\0') {
1285 strncpy(stext, sbuf, len);
1286 p += r - 1; /* p is sbuf + offset + r - 1 */
1287 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1290 memmove(sbuf, p - r + 1, r);
1297 while(XPending(dpy)) {
1298 XNextEvent(dpy, &ev);
1299 if(handler[ev.type])
1300 (handler[ev.type])(&ev); /* call handler */
1307 unsigned int i, num;
1308 Window *wins, d1, d2;
1309 XWindowAttributes wa;
1312 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1313 for(i = 0; i < num; i++) {
1314 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1315 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1317 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1318 manage(wins[i], &wa);
1320 for(i = 0; i < num; i++) { /* now the transients */
1321 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1323 if(XGetTransientForHint(dpy, wins[i], &d1)
1324 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1325 manage(wins[i], &wa);
1333 setclientstate(Client *c, long state) {
1334 long data[] = {state, None};
1336 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1337 PropModeReplace, (unsigned char *)data, 2);
1340 /* TODO: move this into tile.c */
1342 setmfact(const char *arg) {
1345 if(!lt->arrange) /* TODO: check this against the actual tile() function */
1350 d = strtod(arg, NULL);
1351 if(arg[0] == '-' || arg[0] == '+')
1353 if(d < 0.1 || d > 0.9)
1364 XSetWindowAttributes wa;
1367 screen = DefaultScreen(dpy);
1368 root = RootWindow(dpy, screen);
1372 sw = DisplayWidth(dpy, screen);
1373 sh = DisplayHeight(dpy, screen);
1374 bh = dc.font.height + 2;
1379 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1380 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1381 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1382 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1383 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1384 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1387 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1388 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1389 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1391 /* init appearance */
1392 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1393 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1394 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1395 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1396 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1397 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1400 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1401 dc.gc = XCreateGC(dpy, root, 0, 0);
1402 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1404 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1407 tagset[0] = emallocz(TAGSZ);
1408 tagset[1] = emallocz(TAGSZ);
1409 tagset[0][0] = tagset[1][0] = True;
1412 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1413 w = textw(layouts[i].symbol);
1417 wa.override_redirect = 1;
1418 wa.background_pixmap = ParentRelative;
1419 wa.event_mask = ButtonPressMask|ExposureMask;
1421 barwin = XCreateWindow(dpy, root, bx, by, bw, bh, 0, DefaultDepth(dpy, screen),
1422 CopyFromParent, DefaultVisual(dpy, screen),
1423 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1424 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1425 XMapRaised(dpy, barwin);
1426 strcpy(stext, "dwm-"VERSION);
1429 /* EWMH support per view */
1430 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1431 PropModeReplace, (unsigned char *) netatom, NetLast);
1433 /* select for events */
1434 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1435 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1436 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1437 XSelectInput(dpy, root, wa.event_mask);
1445 spawn(const char *arg) {
1446 static char *shell = NULL;
1448 if(!shell && !(shell = getenv("SHELL")))
1452 /* The double-fork construct avoids zombie processes and keeps the code
1453 * clean from stupid signal handlers. */
1457 close(ConnectionNumber(dpy));
1459 execl(shell, shell, "-c", arg, (char *)NULL);
1460 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1469 tag(const char *arg) {
1474 for(i = 0; i < LENGTH(tags); i++)
1475 sel->tags[i] = (arg == NULL);
1476 sel->tags[idxoftag(arg)] = True;
1481 textnw(const char *text, unsigned int len) {
1485 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1488 return XTextWidth(dc.font.xfont, text, len);
1492 textw(const char *text) {
1493 return textnw(text, strlen(text)) + dc.font.height;
1497 tileresize(Client *c, int x, int y, int w, int h) {
1498 resize(c, x, y, w, h, RESIZEHINTS);
1499 if((RESIZEHINTS) && ((c->h < bh) || (c->h > h) || (c->w < bh) || (c->w > w)))
1500 /* client doesn't accept size constraints */
1501 resize(c, x, y, w, h, False);
1510 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next), n++);
1515 c = nexttiled(clients);
1518 tileresize(c, wx, wy, ww - 2 * c->bw, wh - 2 * c->bw);
1520 tileresize(c, mx, my, mw - 2 * c->bw, mh - 2 * c->bw);
1531 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1532 if(i + 1 == n) /* remainder */
1533 tileresize(c, tx, y, tw - 2 * c->bw, (ty + th) - y - 2 * c->bw);
1535 tileresize(c, tx, y, tw - 2 * c->bw, h - 2 * c->bw);
1537 y = c->y + c->h + 2 * c->bw;
1542 togglefloating(const char *arg) {
1545 sel->isfloating = !sel->isfloating;
1547 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1552 togglelayout(const char *arg) {
1556 if(++lt == &layouts[LENGTH(layouts)])
1560 for(i = 0; i < LENGTH(layouts); i++)
1561 if(!strcmp(arg, layouts[i].symbol))
1563 if(i == LENGTH(layouts))
1574 toggletag(const char *arg) {
1580 sel->tags[i] = !sel->tags[i];
1581 for(j = 0; j < LENGTH(tags) && !sel->tags[j]; j++);
1582 if(j == LENGTH(tags))
1583 sel->tags[i] = True; /* at least one tag must be enabled */
1588 toggleview(const char *arg) {
1592 tagset[seltags][i] = !tagset[seltags][i];
1593 for(j = 0; j < LENGTH(tags) && !tagset[seltags][j]; j++);
1594 if(j == LENGTH(tags))
1595 tagset[seltags][i] = True; /* at least one tag must be viewed */
1603 XMoveWindow(dpy, c->win, c->x, c->y);
1604 c->isbanned = False;
1608 unmanage(Client *c) {
1611 wc.border_width = c->oldbw;
1612 /* The server grab construct avoids race conditions. */
1614 XSetErrorHandler(xerrordummy);
1615 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1620 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1621 setclientstate(c, WithdrawnState);
1625 XSetErrorHandler(xerror);
1631 unmapnotify(XEvent *e) {
1633 XUnmapEvent *ev = &e->xunmap;
1635 if((c = getclient(ev->window)))
1641 if(dc.drawable != 0)
1642 XFreePixmap(dpy, dc.drawable);
1643 dc.drawable = XCreatePixmap(dpy, root, bw, bh, DefaultDepth(dpy, screen));
1644 XMoveResizeWindow(dpy, barwin, bx, by, bw, bh);
1655 /* window area geometry */
1661 /* master area geometry */
1667 /* tile area geometry */
1675 updatesizehints(Client *c) {
1679 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1681 c->flags = size.flags;
1682 if(c->flags & PBaseSize) {
1683 c->basew = size.base_width;
1684 c->baseh = size.base_height;
1686 else if(c->flags & PMinSize) {
1687 c->basew = size.min_width;
1688 c->baseh = size.min_height;
1691 c->basew = c->baseh = 0;
1692 if(c->flags & PResizeInc) {
1693 c->incw = size.width_inc;
1694 c->inch = size.height_inc;
1697 c->incw = c->inch = 0;
1698 if(c->flags & PMaxSize) {
1699 c->maxw = size.max_width;
1700 c->maxh = size.max_height;
1703 c->maxw = c->maxh = 0;
1704 if(c->flags & PMinSize) {
1705 c->minw = size.min_width;
1706 c->minh = size.min_height;
1708 else if(c->flags & PBaseSize) {
1709 c->minw = size.base_width;
1710 c->minh = size.base_height;
1713 c->minw = c->minh = 0;
1714 if(c->flags & PAspect) {
1715 c->minax = size.min_aspect.x;
1716 c->maxax = size.max_aspect.x;
1717 c->minay = size.min_aspect.y;
1718 c->maxay = size.max_aspect.y;
1721 c->minax = c->maxax = c->minay = c->maxay = 0;
1722 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1723 && c->maxw == c->minw && c->maxh == c->minh);
1727 updatetitle(Client *c) {
1728 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1729 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1733 updatewmhints(Client *c) {
1736 if((wmh = XGetWMHints(dpy, c->win))) {
1738 sel->isurgent = False;
1740 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1746 view(const char *arg) {
1747 seltags ^= 1; /* toggle sel tagset */
1748 memset(tagset[seltags], (NULL == arg), TAGSZ);
1749 tagset[seltags][idxoftag(arg)] = True;
1754 viewprevtag(const char *arg) {
1755 seltags ^= 1; /* toggle sel tagset */
1759 /* There's no way to check accesses to destroyed windows, thus those cases are
1760 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1761 * default error handler, which may call exit. */
1763 xerror(Display *dpy, XErrorEvent *ee) {
1764 if(ee->error_code == BadWindow
1765 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1766 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1767 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1768 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1769 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1770 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1771 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1772 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1774 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1775 ee->request_code, ee->error_code);
1776 return xerrorxlib(dpy, ee); /* may call exit */
1780 xerrordummy(Display *dpy, XErrorEvent *ee) {
1784 /* Startup Error handler to check if another window manager
1785 * is already running. */
1787 xerrorstart(Display *dpy, XErrorEvent *ee) {
1792 /* TODO: move this into tile.c */
1794 zoom(const char *arg) {
1797 if(c == nexttiled(clients))
1798 if(!c || !(c = nexttiled(c->next)))
1800 if(lt->arrange && !sel->isfloating) { /* TODO: check this against tile() */
1809 main(int argc, char *argv[]) {
1810 if(argc == 2 && !strcmp("-v", argv[1]))
1811 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1813 eprint("usage: dwm [-v]\n");
1815 setlocale(LC_CTYPE, "");
1816 if(!(dpy = XOpenDisplay(0)))
1817 eprint("dwm: cannot open display\n");