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 unsigned int counttiled(void);
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 *nexttiled(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);
165 void setmfact(const char *arg);
167 void spawn(const char *arg);
168 void tag(const char *arg);
169 unsigned int textnw(const char *text, unsigned int len);
170 unsigned int textw(const char *text);
172 void tilehstack(unsigned int n);
173 Client *tilemaster(unsigned int n);
174 void tileresize(Client *c, int x, int y, int w, int h);
176 void tilevstack(unsigned int n);
177 void togglefloating(const char *arg);
178 void togglelayout(const char *arg);
179 void toggletag(const char *arg);
180 void toggleview(const char *arg);
181 void unban(Client *c);
182 void unmanage(Client *c);
183 void unmapnotify(XEvent *e);
184 void updatebar(void);
185 void updategeom(void);
186 void updatesizehints(Client *c);
187 void updatetitle(Client *c);
188 void updatewmhints(Client *c);
189 void view(const char *arg);
190 void viewprevtag(const char *arg); /* views previous selected tags */
191 int xerror(Display *dpy, XErrorEvent *ee);
192 int xerrordummy(Display *dpy, XErrorEvent *ee);
193 int xerrorstart(Display *dpy, XErrorEvent *ee);
194 void zoom(const char *arg);
198 int screen, sx, sy, sw, sh;
199 int (*xerrorxlib)(Display *, XErrorEvent *);
200 int bx, by, bw, bh, blw, mx, my, mw, mh, tx, ty, tw, th, wx, wy, ww, wh;
203 unsigned int numlockmask = 0;
204 void (*handler[LASTEvent]) (XEvent *) = {
205 [ButtonPress] = buttonpress,
206 [ConfigureRequest] = configurerequest,
207 [ConfigureNotify] = configurenotify,
208 [DestroyNotify] = destroynotify,
209 [EnterNotify] = enternotify,
212 [KeyPress] = keypress,
213 [MappingNotify] = mappingnotify,
214 [MapRequest] = maprequest,
215 [PropertyNotify] = propertynotify,
216 [UnmapNotify] = unmapnotify
218 Atom wmatom[WMLast], netatom[NetLast];
219 Bool otherwm, readin;
222 Client *clients = NULL;
224 Client *stack = NULL;
225 Cursor cursor[CurLast];
229 Layout *lt = layouts;
232 /* configuration, allows nested code to access above variables */
234 #define TAGSZ (LENGTH(tags) * sizeof(Bool))
236 /* function implementations */
239 applyrules(Client *c) {
241 Bool matched = False;
243 XClassHint ch = { 0 };
246 XGetClassHint(dpy, c->win, &ch);
247 for(i = 0; i < LENGTH(rules); i++) {
249 if((!r->title || strstr(c->name, r->title))
250 && (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
251 && (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
252 c->isfloating = r->isfloating;
254 c->tags[idxoftag(r->tag)] = True;
264 memcpy(c->tags, tagset[seltags], TAGSZ);
271 for(c = clients; c; c = c->next)
272 if(isvisible(c, NULL)) {
274 if(!lt->arrange || c->isfloating)
275 resize(c, c->x, c->y, c->w, c->h, True);
295 attachstack(Client *c) {
304 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
309 buttonpress(XEvent *e) {
312 XButtonPressedEvent *ev = &e->xbutton;
314 if(ev->window == barwin) {
316 for(i = 0; i < LENGTH(tags); i++) {
319 if(ev->button == Button1) {
320 if(ev->state & MODKEY)
325 else if(ev->button == Button3) {
326 if(ev->state & MODKEY)
334 if((ev->x < x + blw) && ev->button == Button1)
337 else if((c = getclient(ev->window))) {
339 if(CLEANMASK(ev->state) != MODKEY)
341 if(ev->button == Button1) {
345 else if(ev->button == Button2) {
346 if(lt->arrange && c->isfloating)
347 togglefloating(NULL);
351 else if(ev->button == Button3 && !c->isfixed) {
361 XSetErrorHandler(xerrorstart);
363 /* this causes an error if some other window manager is running */
364 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
367 eprint("dwm: another window manager is already running\n");
369 XSetErrorHandler(NULL);
370 xerrorxlib = XSetErrorHandler(xerror);
382 XFreeFontSet(dpy, dc.font.set);
384 XFreeFont(dpy, dc.font.xfont);
385 XUngrabKey(dpy, AnyKey, AnyModifier, root);
386 XFreePixmap(dpy, dc.drawable);
388 XFreeCursor(dpy, cursor[CurNormal]);
389 XFreeCursor(dpy, cursor[CurResize]);
390 XFreeCursor(dpy, cursor[CurMove]);
391 XDestroyWindow(dpy, barwin);
393 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
397 configure(Client *c) {
400 ce.type = ConfigureNotify;
408 ce.border_width = c->bw;
410 ce.override_redirect = False;
411 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
415 configurenotify(XEvent *e) {
416 XConfigureEvent *ev = &e->xconfigure;
418 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
428 configurerequest(XEvent *e) {
430 XConfigureRequestEvent *ev = &e->xconfigurerequest;
433 if((c = getclient(ev->window))) {
434 if(ev->value_mask & CWBorderWidth)
435 c->bw = ev->border_width;
436 if(c->isfixed || c->isfloating || !lt->arrange) {
437 if(ev->value_mask & CWX)
439 if(ev->value_mask & CWY)
441 if(ev->value_mask & CWWidth)
443 if(ev->value_mask & CWHeight)
445 if((c->x - sx + c->w) > sw && c->isfloating)
446 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
447 if((c->y - sy + c->h) > sh && c->isfloating)
448 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
449 if((ev->value_mask & (CWX|CWY))
450 && !(ev->value_mask & (CWWidth|CWHeight)))
452 if(isvisible(c, NULL))
453 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
461 wc.width = ev->width;
462 wc.height = ev->height;
463 wc.border_width = ev->border_width;
464 wc.sibling = ev->above;
465 wc.stack_mode = ev->detail;
466 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
476 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next), n++);
481 destroynotify(XEvent *e) {
483 XDestroyWindowEvent *ev = &e->xdestroywindow;
485 if((c = getclient(ev->window)))
492 c->prev->next = c->next;
494 c->next->prev = c->prev;
497 c->next = c->prev = NULL;
501 detachstack(Client *c) {
504 for(tc = &stack; *tc && *tc != c; tc = &(*tc)->snext);
514 for(c = stack; c && !isvisible(c, NULL); c = c->snext);
515 for(i = 0; i < LENGTH(tags); i++) {
516 dc.w = textw(tags[i]);
517 if(tagset[seltags][i]) {
518 drawtext(tags[i], dc.sel, isurgent(i));
519 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.sel);
522 drawtext(tags[i], dc.norm, isurgent(i));
523 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.norm);
529 drawtext(lt->symbol, dc.norm, False);
540 drawtext(stext, dc.norm, False);
541 if((dc.w = dc.x - x) > bh) {
544 drawtext(c->name, dc.sel, False);
545 drawsquare(False, c->isfloating, False, dc.sel);
548 drawtext(NULL, dc.norm, False);
550 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, bw, bh, 0, 0);
555 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
558 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
560 gcv.foreground = col[invert ? ColBG : ColFG];
561 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
562 x = (dc.font.ascent + dc.font.descent + 2) / 4;
566 r.width = r.height = x + 1;
567 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
570 r.width = r.height = x;
571 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
576 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
578 unsigned int len, olen;
579 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
582 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
583 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
587 len = MIN(olen, sizeof buf);
588 memcpy(buf, text, len);
590 h = dc.font.ascent + dc.font.descent;
591 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
593 /* shorten text if necessary */
594 for(; len && (w = textnw(buf, len)) > dc.w - h; len--);
605 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
607 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
609 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
613 emallocz(unsigned int size) {
614 void *res = calloc(1, size);
617 eprint("fatal: could not malloc() %u bytes\n", size);
622 enternotify(XEvent *e) {
624 XCrossingEvent *ev = &e->xcrossing;
626 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
628 if((c = getclient(ev->window)))
635 eprint(const char *errstr, ...) {
638 va_start(ap, errstr);
639 vfprintf(stderr, errstr, ap);
646 XExposeEvent *ev = &e->xexpose;
648 if(ev->count == 0 && (ev->window == barwin))
654 if(!c || (c && !isvisible(c, NULL)))
655 for(c = stack; c && !isvisible(c, NULL); c = c->snext);
656 if(sel && sel != c) {
657 grabbuttons(sel, False);
658 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
663 grabbuttons(c, True);
667 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
668 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
671 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
676 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
677 XFocusChangeEvent *ev = &e->xfocus;
679 if(sel && ev->window != sel->win)
680 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
684 focusnext(const char *arg) {
689 for(c = sel->next; c && !isvisible(c, arg ? sel->tags : NULL); c = c->next);
691 for(c = clients; c && !isvisible(c, arg ? sel->tags : NULL); c = c->next);
699 focusprev(const char *arg) {
704 for(c = sel->prev; c && !isvisible(c, arg ? sel->tags : NULL); c = c->prev);
706 for(c = clients; c && c->next; c = c->next);
707 for(; c && !isvisible(c, arg ? sel->tags : NULL); c = c->prev);
716 getclient(Window w) {
719 for(c = clients; c && c->win != w; c = c->next);
724 getcolor(const char *colstr) {
725 Colormap cmap = DefaultColormap(dpy, screen);
728 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
729 eprint("error, cannot allocate color '%s'\n", colstr);
737 unsigned char *p = NULL;
738 unsigned long n, extra;
741 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
742 &real, &format, &n, &extra, (unsigned char **)&p);
743 if(status != Success)
752 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
757 if(!text || size == 0)
760 XGetTextProperty(dpy, w, &name, atom);
763 if(name.encoding == XA_STRING)
764 strncpy(text, (char *)name.value, size - 1);
766 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
768 strncpy(text, *list, size - 1);
769 XFreeStringList(list);
772 text[size - 1] = '\0';
778 grabbuttons(Client *c, Bool focused) {
780 unsigned int buttons[] = { Button1, Button2, Button3 };
781 unsigned int modifiers[] = { MODKEY, MODKEY|LockMask, MODKEY|numlockmask,
782 MODKEY|numlockmask|LockMask} ;
784 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
786 for(i = 0; i < LENGTH(buttons); i++)
787 for(j = 0; j < LENGTH(modifiers); j++)
788 XGrabButton(dpy, buttons[i], modifiers[j], c->win, False,
789 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
791 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
792 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
799 XModifierKeymap *modmap;
801 /* init modifier map */
802 modmap = XGetModifierMapping(dpy);
803 for(i = 0; i < 8; i++)
804 for(j = 0; j < modmap->max_keypermod; j++) {
805 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
806 numlockmask = (1 << i);
808 XFreeModifiermap(modmap);
810 XUngrabKey(dpy, AnyKey, AnyModifier, root);
811 for(i = 0; i < LENGTH(keys); i++) {
812 code = XKeysymToKeycode(dpy, keys[i].keysym);
813 XGrabKey(dpy, code, keys[i].mod, root, True,
814 GrabModeAsync, GrabModeAsync);
815 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
816 GrabModeAsync, GrabModeAsync);
817 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
818 GrabModeAsync, GrabModeAsync);
819 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
820 GrabModeAsync, GrabModeAsync);
825 idxoftag(const char *t) {
828 for(i = 0; (i < LENGTH(tags)) && t && strcmp(tags[i], t); i++);
829 return (i < LENGTH(tags)) ? i : 0;
833 initfont(const char *fontstr) {
834 char *def, **missing;
839 XFreeFontSet(dpy, dc.font.set);
840 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
843 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
844 XFreeStringList(missing);
847 XFontSetExtents *font_extents;
848 XFontStruct **xfonts;
850 dc.font.ascent = dc.font.descent = 0;
851 font_extents = XExtentsOfFontSet(dc.font.set);
852 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
853 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
854 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
855 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
861 XFreeFont(dpy, dc.font.xfont);
862 dc.font.xfont = NULL;
863 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
864 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
865 eprint("error, cannot load font: '%s'\n", fontstr);
866 dc.font.ascent = dc.font.xfont->ascent;
867 dc.font.descent = dc.font.xfont->descent;
869 dc.font.height = dc.font.ascent + dc.font.descent;
873 isoccupied(unsigned int t) {
876 for(c = clients; c; c = c->next)
883 isprotodel(Client *c) {
888 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
889 for(i = 0; !ret && i < n; i++)
890 if(protocols[i] == wmatom[WMDelete])
898 isurgent(unsigned int t) {
901 for(c = clients; c; c = c->next)
902 if(c->isurgent && c->tags[t])
908 isvisible(Client *c, Bool *cmp) {
912 cmp = tagset[seltags];
913 for(i = 0; i < LENGTH(tags); i++)
914 if(c->tags[i] && cmp[i])
920 keypress(XEvent *e) {
926 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
927 for(i = 0; i < LENGTH(keys); i++)
928 if(keysym == keys[i].keysym
929 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
932 keys[i].func(keys[i].arg);
937 killclient(const char *arg) {
942 if(isprotodel(sel)) {
943 ev.type = ClientMessage;
944 ev.xclient.window = sel->win;
945 ev.xclient.message_type = wmatom[WMProtocols];
946 ev.xclient.format = 32;
947 ev.xclient.data.l[0] = wmatom[WMDelete];
948 ev.xclient.data.l[1] = CurrentTime;
949 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
952 XKillClient(dpy, sel->win);
956 manage(Window w, XWindowAttributes *wa) {
957 Client *c, *t = NULL;
962 c = emallocz(sizeof(Client));
963 c->tags = emallocz(TAGSZ);
971 c->oldbw = wa->border_width;
972 if(c->w == sw && c->h == sh) {
975 c->bw = wa->border_width;
978 if(c->x + c->w + 2 * c->bw > wx + ww)
979 c->x = wx + ww - c->w - 2 * c->bw;
980 if(c->y + c->h + 2 * c->bw > wy + wh)
981 c->y = wy + wh - c->h - 2 * c->bw;
982 c->x = MAX(c->x, wx);
983 c->y = MAX(c->y, wy);
987 wc.border_width = c->bw;
988 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
989 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
990 configure(c); /* propagates border_width, if size doesn't change */
992 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
993 grabbuttons(c, False);
995 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
996 for(t = clients; t && t->win != trans; t = t->next);
998 memcpy(c->tags, t->tags, TAGSZ);
1002 c->isfloating = (rettrans == Success) || c->isfixed;
1005 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
1007 XMapWindow(dpy, c->win);
1008 setclientstate(c, NormalState);
1013 mappingnotify(XEvent *e) {
1014 XMappingEvent *ev = &e->xmapping;
1016 XRefreshKeyboardMapping(ev);
1017 if(ev->request == MappingKeyboard)
1022 maprequest(XEvent *e) {
1023 static XWindowAttributes wa;
1024 XMapRequestEvent *ev = &e->xmaprequest;
1026 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1028 if(wa.override_redirect)
1030 if(!getclient(ev->window))
1031 manage(ev->window, &wa);
1038 for(c = clients; c; c = c->next)
1039 if(!c->isfloating && isvisible(c, NULL))
1040 resize(c, wx, wy, ww - 2 * c->bw, wh - 2 * c->bw, RESIZEHINTS);
1044 movemouse(Client *c) {
1045 int x1, y1, ocx, ocy, di, nx, ny;
1052 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1053 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1055 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1057 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1060 XUngrabPointer(dpy, CurrentTime);
1062 case ConfigureRequest:
1065 handler[ev.type](&ev);
1069 nx = ocx + (ev.xmotion.x - x1);
1070 ny = ocy + (ev.xmotion.y - y1);
1071 if(abs(wx - nx) < SNAP)
1073 else if(abs((wx + ww) - (nx + c->w + 2 * c->bw)) < SNAP)
1074 nx = wx + ww - c->w - 2 * c->bw;
1075 if(abs(wy - ny) < SNAP)
1077 else if(abs((wy + wh) - (ny + c->h + 2 * c->bw)) < SNAP)
1078 ny = wy + wh - c->h - 2 * c->bw;
1079 if(!c->isfloating && lt->arrange && (abs(nx - c->x) > SNAP || abs(ny - c->y) > SNAP))
1080 togglefloating(NULL);
1081 if(!lt->arrange || c->isfloating)
1082 resize(c, nx, ny, c->w, c->h, False);
1089 nexttiled(Client *c) {
1090 for(; c && (c->isfloating || !isvisible(c, NULL)); c = c->next);
1095 propertynotify(XEvent *e) {
1098 XPropertyEvent *ev = &e->xproperty;
1100 if(ev->state == PropertyDelete)
1101 return; /* ignore */
1102 if((c = getclient(ev->window))) {
1105 case XA_WM_TRANSIENT_FOR:
1106 XGetTransientForHint(dpy, c->win, &trans);
1107 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1110 case XA_WM_NORMAL_HINTS:
1118 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1127 quit(const char *arg) {
1128 readin = running = False;
1132 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1136 /* set minimum possible */
1140 /* temporarily remove base dimensions */
1144 /* adjust for aspect limits */
1145 if(c->minax != c->maxax && c->minay != c->maxay
1146 && c->minax > 0 && c->maxax > 0 && c->minay > 0 && c->maxay > 0) {
1147 if(w * c->maxay > h * c->maxax)
1148 w = h * c->maxax / c->maxay;
1149 else if(w * c->minay < h * c->minax)
1150 h = w * c->minay / c->minax;
1153 /* adjust for increment value */
1159 /* restore base dimensions */
1163 w = MAX(w, c->minw);
1164 h = MAX(h, c->minh);
1167 w = MIN(w, c->maxw);
1170 h = MIN(h, c->maxh);
1172 if(w <= 0 || h <= 0)
1175 x = sw - w - 2 * c->bw;
1177 y = sh - h - 2 * c->bw;
1178 if(x + w + 2 * c->bw < sx)
1180 if(y + h + 2 * c->bw < sy)
1182 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1185 c->w = wc.width = w;
1186 c->h = wc.height = h;
1187 wc.border_width = c->bw;
1188 XConfigureWindow(dpy, c->win,
1189 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1196 resizemouse(Client *c) {
1203 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1204 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1206 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1208 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1211 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1212 c->w + c->bw - 1, c->h + c->bw - 1);
1213 XUngrabPointer(dpy, CurrentTime);
1214 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1216 case ConfigureRequest:
1219 handler[ev.type](&ev);
1223 nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1224 nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1225 if(!c->isfloating && lt->arrange && (abs(nw - c->w) > SNAP || abs(nh - c->h) > SNAP)) {
1226 togglefloating(NULL);
1228 if(!lt->arrange || c->isfloating)
1229 resize(c, c->x, c->y, nw, nh, True);
1244 if(sel->isfloating || !lt->arrange)
1245 XRaiseWindow(dpy, sel->win);
1247 wc.stack_mode = Below;
1248 wc.sibling = barwin;
1249 for(c = stack; c; c = c->snext)
1250 if(!c->isfloating && isvisible(c, NULL)) {
1251 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1252 wc.sibling = c->win;
1256 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1262 char sbuf[sizeof stext];
1265 unsigned int len, offset;
1268 /* main event loop, also reads status text from stdin */
1270 xfd = ConnectionNumber(dpy);
1273 len = sizeof stext - 1;
1274 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1278 FD_SET(STDIN_FILENO, &rd);
1280 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1283 eprint("select failed\n");
1285 if(FD_ISSET(STDIN_FILENO, &rd)) {
1286 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1288 strncpy(stext, strerror(errno), len);
1292 strncpy(stext, "EOF", 4);
1296 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1297 if(*p == '\n' || *p == '\0') {
1299 strncpy(stext, sbuf, len);
1300 p += r - 1; /* p is sbuf + offset + r - 1 */
1301 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1304 memmove(sbuf, p - r + 1, r);
1311 while(XPending(dpy)) {
1312 XNextEvent(dpy, &ev);
1313 if(handler[ev.type])
1314 (handler[ev.type])(&ev); /* call handler */
1321 unsigned int i, num;
1322 Window *wins, d1, d2;
1323 XWindowAttributes wa;
1326 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1327 for(i = 0; i < num; i++) {
1328 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1329 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1331 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1332 manage(wins[i], &wa);
1334 for(i = 0; i < num; i++) { /* now the transients */
1335 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1337 if(XGetTransientForHint(dpy, wins[i], &d1)
1338 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1339 manage(wins[i], &wa);
1347 setclientstate(Client *c, long state) {
1348 long data[] = {state, None};
1350 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1351 PropModeReplace, (unsigned char *)data, 2);
1354 /* TODO: move this into tile.c */
1356 setmfact(const char *arg) {
1359 if(!lt->arrange) /* TODO: check this against the actual tile() function */
1364 d = strtod(arg, NULL);
1365 if(arg[0] == '-' || arg[0] == '+')
1367 if(d < 0.1 || d > 0.9)
1378 XSetWindowAttributes wa;
1381 screen = DefaultScreen(dpy);
1382 root = RootWindow(dpy, screen);
1386 sw = DisplayWidth(dpy, screen);
1387 sh = DisplayHeight(dpy, screen);
1388 bh = dc.font.height + 2;
1393 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1394 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1395 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1396 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1397 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1398 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1401 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1402 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1403 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1405 /* init appearance */
1406 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1407 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1408 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1409 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1410 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1411 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1414 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1415 dc.gc = XCreateGC(dpy, root, 0, 0);
1416 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1418 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1421 tagset[0] = emallocz(TAGSZ);
1422 tagset[1] = emallocz(TAGSZ);
1423 tagset[0][0] = tagset[1][0] = True;
1426 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1427 w = textw(layouts[i].symbol);
1431 wa.override_redirect = 1;
1432 wa.background_pixmap = ParentRelative;
1433 wa.event_mask = ButtonPressMask|ExposureMask;
1435 barwin = XCreateWindow(dpy, root, bx, by, bw, bh, 0, DefaultDepth(dpy, screen),
1436 CopyFromParent, DefaultVisual(dpy, screen),
1437 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1438 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1439 XMapRaised(dpy, barwin);
1440 strcpy(stext, "dwm-"VERSION);
1443 /* EWMH support per view */
1444 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1445 PropModeReplace, (unsigned char *) netatom, NetLast);
1447 /* select for events */
1448 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1449 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1450 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1451 XSelectInput(dpy, root, wa.event_mask);
1459 spawn(const char *arg) {
1460 static char *shell = NULL;
1462 if(!shell && !(shell = getenv("SHELL")))
1466 /* The double-fork construct avoids zombie processes and keeps the code
1467 * clean from stupid signal handlers. */
1471 close(ConnectionNumber(dpy));
1473 execl(shell, shell, "-c", arg, (char *)NULL);
1474 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1483 tag(const char *arg) {
1488 for(i = 0; i < LENGTH(tags); i++)
1489 sel->tags[i] = (arg == NULL);
1490 sel->tags[idxoftag(arg)] = True;
1495 textnw(const char *text, unsigned int len) {
1499 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1502 return XTextWidth(dc.font.xfont, text, len);
1506 textw(const char *text) {
1507 return textnw(text, strlen(text)) + dc.font.height;
1513 unsigned int i, n = counttiled();
1527 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1528 if(i + 1 == n) /* remainder */
1529 tileresize(c, x, ty, (tx + tw) - x - 2 * c->bw, th - 2 * c->bw);
1531 tileresize(c, x, ty, w - 2 * c->bw, th - 2 * c->bw);
1533 x = c->x + c->w + 2 * c->bw;
1538 tilemaster(unsigned int n) {
1539 Client *c = nexttiled(clients);
1542 tileresize(c, wx, wy, ww - 2 * c->bw, wh - 2 * c->bw);
1544 tileresize(c, mx, my, mw - 2 * c->bw, mh - 2 * c->bw);
1549 tileresize(Client *c, int x, int y, int w, int h) {
1550 resize(c, x, y, w, h, RESIZEHINTS);
1551 if((RESIZEHINTS) && ((c->h < bh) || (c->h > h) || (c->w < bh) || (c->w > w)))
1552 /* client doesn't accept size constraints */
1553 resize(c, x, y, w, h, False);
1559 unsigned int i, n = counttiled();
1573 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1574 if(i + 1 == n) /* remainder */
1575 tileresize(c, tx, y, tw - 2 * c->bw, (ty + th) - y - 2 * c->bw);
1577 tileresize(c, tx, y, tw - 2 * c->bw, h - 2 * c->bw);
1579 y = c->y + c->h + 2 * c->bw;
1584 togglefloating(const char *arg) {
1587 sel->isfloating = !sel->isfloating;
1589 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1594 togglelayout(const char *arg) {
1598 if(++lt == &layouts[LENGTH(layouts)])
1602 for(i = 0; i < LENGTH(layouts); i++)
1603 if(!strcmp(arg, layouts[i].symbol))
1605 if(i == LENGTH(layouts))
1616 toggletag(const char *arg) {
1622 sel->tags[i] = !sel->tags[i];
1623 for(j = 0; j < LENGTH(tags) && !sel->tags[j]; j++);
1624 if(j == LENGTH(tags))
1625 sel->tags[i] = True; /* at least one tag must be enabled */
1630 toggleview(const char *arg) {
1634 tagset[seltags][i] = !tagset[seltags][i];
1635 for(j = 0; j < LENGTH(tags) && !tagset[seltags][j]; j++);
1636 if(j == LENGTH(tags))
1637 tagset[seltags][i] = True; /* at least one tag must be viewed */
1645 XMoveWindow(dpy, c->win, c->x, c->y);
1646 c->isbanned = False;
1650 unmanage(Client *c) {
1653 wc.border_width = c->oldbw;
1654 /* The server grab construct avoids race conditions. */
1656 XSetErrorHandler(xerrordummy);
1657 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1662 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1663 setclientstate(c, WithdrawnState);
1667 XSetErrorHandler(xerror);
1673 unmapnotify(XEvent *e) {
1675 XUnmapEvent *ev = &e->xunmap;
1677 if((c = getclient(ev->window)))
1683 if(dc.drawable != 0)
1684 XFreePixmap(dpy, dc.drawable);
1685 dc.drawable = XCreatePixmap(dpy, root, bw, bh, DefaultDepth(dpy, screen));
1686 XMoveResizeWindow(dpy, barwin, bx, by, bw, bh);
1697 /* window area geometry */
1703 /* master area geometry */
1709 /* tile area geometry */
1717 updatesizehints(Client *c) {
1721 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1723 c->flags = size.flags;
1724 if(c->flags & PBaseSize) {
1725 c->basew = size.base_width;
1726 c->baseh = size.base_height;
1728 else if(c->flags & PMinSize) {
1729 c->basew = size.min_width;
1730 c->baseh = size.min_height;
1733 c->basew = c->baseh = 0;
1734 if(c->flags & PResizeInc) {
1735 c->incw = size.width_inc;
1736 c->inch = size.height_inc;
1739 c->incw = c->inch = 0;
1740 if(c->flags & PMaxSize) {
1741 c->maxw = size.max_width;
1742 c->maxh = size.max_height;
1745 c->maxw = c->maxh = 0;
1746 if(c->flags & PMinSize) {
1747 c->minw = size.min_width;
1748 c->minh = size.min_height;
1750 else if(c->flags & PBaseSize) {
1751 c->minw = size.base_width;
1752 c->minh = size.base_height;
1755 c->minw = c->minh = 0;
1756 if(c->flags & PAspect) {
1757 c->minax = size.min_aspect.x;
1758 c->maxax = size.max_aspect.x;
1759 c->minay = size.min_aspect.y;
1760 c->maxay = size.max_aspect.y;
1763 c->minax = c->maxax = c->minay = c->maxay = 0;
1764 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1765 && c->maxw == c->minw && c->maxh == c->minh);
1769 updatetitle(Client *c) {
1770 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1771 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1775 updatewmhints(Client *c) {
1778 if((wmh = XGetWMHints(dpy, c->win))) {
1780 sel->isurgent = False;
1782 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1788 view(const char *arg) {
1789 seltags ^= 1; /* toggle sel tagset */
1790 memset(tagset[seltags], (NULL == arg), TAGSZ);
1791 tagset[seltags][idxoftag(arg)] = True;
1796 viewprevtag(const char *arg) {
1797 seltags ^= 1; /* toggle sel tagset */
1801 /* There's no way to check accesses to destroyed windows, thus those cases are
1802 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1803 * default error handler, which may call exit. */
1805 xerror(Display *dpy, XErrorEvent *ee) {
1806 if(ee->error_code == BadWindow
1807 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1808 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1809 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1810 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1811 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1812 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1813 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1814 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1816 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1817 ee->request_code, ee->error_code);
1818 return xerrorxlib(dpy, ee); /* may call exit */
1822 xerrordummy(Display *dpy, XErrorEvent *ee) {
1826 /* Startup Error handler to check if another window manager
1827 * is already running. */
1829 xerrorstart(Display *dpy, XErrorEvent *ee) {
1834 /* TODO: move this into tile.c */
1836 zoom(const char *arg) {
1839 if(c == nexttiled(clients))
1840 if(!c || !(c = nexttiled(c->next)))
1842 if(lt->arrange && !sel->isfloating) { /* TODO: check this against tile() */
1851 main(int argc, char *argv[]) {
1852 if(argc == 2 && !strcmp("-v", argv[1]))
1853 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1855 eprint("usage: dwm [-v]\n");
1857 setlocale(LC_CTYPE, "");
1858 if(!(dpy = XOpenDisplay(0)))
1859 eprint("dwm: cannot open display\n");