1 /* See LICENSE file for copyright and license details.
3 * dynamic window manager is designed like any other X client as well. It is
4 * driven through handling X events. In contrast to other X clients, a window
5 * manager selects for SubstructureRedirectMask on the root window, to receive
6 * events about window (dis-)appearance. Only one X connection at a time is
7 * allowed to select for this event mask.
9 * Calls to fetch an X event from the event queue are blocking. Due reading
10 * status text from standard input, a select()-driven main loop has been
11 * implemented which selects for reads on the X connection and STDIN_FILENO to
12 * handle all data smoothly. The event handlers of dwm are organized in an
13 * array which is accessed whenever a new event has been fetched. This allows
14 * event dispatching in O(1) time.
16 * Each child of the root window is called a client, except windows which have
17 * set the override_redirect flag. Clients are organized in a global
18 * doubly-linked client list, the focus history is remembered through a global
19 * stack list. Each client contains an array of Bools of the same size as the
20 * global tags array to indicate the tags of a client.
22 * Keys and tagging rules are organized as arrays and defined in config.h.
24 * To understand everything else, start reading main().
33 #include <sys/select.h>
34 #include <sys/types.h>
36 #include <X11/cursorfont.h>
37 #include <X11/keysym.h>
38 #include <X11/Xatom.h>
40 #include <X11/Xproto.h>
41 #include <X11/Xutil.h>
43 #include <X11/extensions/Xinerama.h>
47 #define MAX(a, b) ((a) > (b) ? (a) : (b))
48 #define MIN(a, b) ((a) < (b) ? (a) : (b))
49 #define BUTTONMASK (ButtonPressMask|ButtonReleaseMask)
50 #define CLEANMASK(mask) (mask & ~(numlockmask|LockMask))
51 #define LENGTH(x) (sizeof x / sizeof x[0])
53 #define MOUSEMASK (BUTTONMASK|PointerMotionMask)
56 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
57 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
58 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
59 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
62 typedef struct Client Client;
66 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
67 int minax, maxax, minay, maxay;
69 unsigned int bw, oldbw;
70 Bool isbanned, isfixed, isfloating, isurgent;
80 unsigned long norm[ColLast];
81 unsigned long sel[ColLast];
91 } DC; /* draw context */
96 void (*func)(const char *arg);
102 void (*arrange)(void);
103 void (*updategeom)(void);
108 const char *instance;
114 /* function declarations */
115 void applyrules(Client *c);
117 void attach(Client *c);
118 void attachstack(Client *c);
120 void buttonpress(XEvent *e);
121 void checkotherwm(void);
123 void configure(Client *c);
124 void configurenotify(XEvent *e);
125 void configurerequest(XEvent *e);
126 void destroynotify(XEvent *e);
127 void detach(Client *c);
128 void detachstack(Client *c);
130 void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
131 void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
132 void *emallocz(unsigned int size);
133 void enternotify(XEvent *e);
134 void eprint(const char *errstr, ...);
135 void expose(XEvent *e);
136 void focus(Client *c);
137 void focusin(XEvent *e);
138 void focusnext(const char *arg);
139 void focusprev(const char *arg);
140 Client *getclient(Window w);
141 unsigned long getcolor(const char *colstr);
142 long getstate(Window w);
143 Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
144 void grabbuttons(Client *c, Bool focused);
146 unsigned int idxoftag(const char *t);
147 void initfont(const char *fontstr);
148 Bool isoccupied(unsigned int t);
149 Bool isprotodel(Client *c);
150 Bool isurgent(unsigned int t);
151 Bool isvisible(Client *c);
152 void keypress(XEvent *e);
153 void killclient(const char *arg);
154 void manage(Window w, XWindowAttributes *wa);
155 void mappingnotify(XEvent *e);
156 void maprequest(XEvent *e);
157 void movemouse(Client *c);
158 Client *nextunfloating(Client *c);
159 void propertynotify(XEvent *e);
160 void quit(const char *arg);
161 void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
162 void resizemouse(Client *c);
166 void setclientstate(Client *c, long state);
167 void setmfact(const char *arg);
169 void spawn(const char *arg);
170 void tag(const char *arg);
171 unsigned int textnw(const char *text, unsigned int len);
172 unsigned int textw(const char *text);
174 void tileresize(Client *c, int x, int y, int w, int h);
175 void togglebar(const char *arg);
176 void togglefloating(const char *arg);
177 void togglelayout(const char *arg);
178 void toggletag(const char *arg);
179 void toggleview(const char *arg);
180 void unban(Client *c);
181 void unmanage(Client *c);
182 void unmapnotify(XEvent *e);
183 void updatebar(void);
184 void updategeom(void);
185 void updatesizehints(Client *c);
186 void updatetilegeom(void);
187 void updatetitle(Client *c);
188 void updatewmhints(Client *c);
189 void view(const char *arg);
190 void viewprevtag(const char *arg);
191 int xerror(Display *dpy, XErrorEvent *ee);
192 int xerrordummy(Display *dpy, XErrorEvent *ee);
193 int xerrorstart(Display *dpy, XErrorEvent *ee);
194 void zoom(const char *arg);
198 int screen, sx, sy, sw, sh;
199 int bx, by, bw, bh, blw, wx, wy, ww, wh;
200 int mx, my, mw, mh, tx, ty, tw, th;
202 int (*xerrorxlib)(Display *, XErrorEvent *);
203 unsigned int numlockmask = 0;
204 void (*handler[LASTEvent]) (XEvent *) = {
205 [ButtonPress] = buttonpress,
206 [ConfigureRequest] = configurerequest,
207 [ConfigureNotify] = configurenotify,
208 [DestroyNotify] = destroynotify,
209 [EnterNotify] = enternotify,
212 [KeyPress] = keypress,
213 [MappingNotify] = mappingnotify,
214 [MapRequest] = maprequest,
215 [PropertyNotify] = propertynotify,
216 [UnmapNotify] = unmapnotify
218 Atom wmatom[WMLast], netatom[NetLast];
219 Bool otherwm, readin;
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)
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 togglefloating(NULL);
347 else if(ev->button == Button3 && !c->isfixed) {
357 XSetErrorHandler(xerrorstart);
359 /* this causes an error if some other window manager is running */
360 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
363 eprint("dwm: another window manager is already running\n");
365 XSetErrorHandler(NULL);
366 xerrorxlib = XSetErrorHandler(xerror);
378 XFreeFontSet(dpy, dc.font.set);
380 XFreeFont(dpy, dc.font.xfont);
381 XUngrabKey(dpy, AnyKey, AnyModifier, root);
382 XFreePixmap(dpy, dc.drawable);
384 XFreeCursor(dpy, cursor[CurNormal]);
385 XFreeCursor(dpy, cursor[CurResize]);
386 XFreeCursor(dpy, cursor[CurMove]);
387 XDestroyWindow(dpy, barwin);
389 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
393 configure(Client *c) {
396 ce.type = ConfigureNotify;
404 ce.border_width = c->bw;
406 ce.override_redirect = False;
407 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
411 configurenotify(XEvent *e) {
412 XConfigureEvent *ev = &e->xconfigure;
414 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
424 configurerequest(XEvent *e) {
426 XConfigureRequestEvent *ev = &e->xconfigurerequest;
429 if((c = getclient(ev->window))) {
430 if(ev->value_mask & CWBorderWidth)
431 c->bw = ev->border_width;
432 if(c->isfixed || c->isfloating || !lt->arrange) {
433 if(ev->value_mask & CWX)
435 if(ev->value_mask & CWY)
437 if(ev->value_mask & CWWidth)
439 if(ev->value_mask & CWHeight)
441 if((c->x - sx + c->w) > sw && c->isfloating)
442 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
443 if((c->y - sy + c->h) > sh && c->isfloating)
444 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
445 if((ev->value_mask & (CWX|CWY))
446 && !(ev->value_mask & (CWWidth|CWHeight)))
449 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
457 wc.width = ev->width;
458 wc.height = ev->height;
459 wc.border_width = ev->border_width;
460 wc.sibling = ev->above;
461 wc.stack_mode = ev->detail;
462 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
468 destroynotify(XEvent *e) {
470 XDestroyWindowEvent *ev = &e->xdestroywindow;
472 if((c = getclient(ev->window)))
479 c->prev->next = c->next;
481 c->next->prev = c->prev;
484 c->next = c->prev = NULL;
488 detachstack(Client *c) {
491 for(tc = &stack; *tc && *tc != c; tc = &(*tc)->snext);
501 for(c = stack; c && !isvisible(c); c = c->snext);
502 for(i = 0; i < LENGTH(tags); i++) {
503 dc.w = textw(tags[i]);
504 if(tagset[seltags][i]) {
505 drawtext(tags[i], dc.sel, isurgent(i));
506 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.sel);
509 drawtext(tags[i], dc.norm, isurgent(i));
510 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.norm);
516 drawtext(lt->symbol, dc.norm, False);
527 drawtext(stext, dc.norm, False);
528 if((dc.w = dc.x - x) > bh) {
531 drawtext(c->name, dc.sel, False);
532 drawsquare(False, c->isfloating, False, dc.sel);
535 drawtext(NULL, dc.norm, False);
537 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, bw, bh, 0, 0);
542 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
545 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
547 gcv.foreground = col[invert ? ColBG : ColFG];
548 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
549 x = (dc.font.ascent + dc.font.descent + 2) / 4;
553 r.width = r.height = x + 1;
554 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
557 r.width = r.height = x;
558 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
563 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
565 unsigned int len, olen;
566 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
569 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
570 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
574 len = MIN(olen, sizeof buf);
575 memcpy(buf, text, len);
577 h = dc.font.ascent + dc.font.descent;
578 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
580 /* shorten text if necessary */
581 for(; len && (w = textnw(buf, len)) > dc.w - h; len--);
592 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
594 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
596 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
600 emallocz(unsigned int size) {
601 void *res = calloc(1, size);
604 eprint("fatal: could not malloc() %u bytes\n", size);
609 enternotify(XEvent *e) {
611 XCrossingEvent *ev = &e->xcrossing;
613 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
615 if((c = getclient(ev->window)))
622 eprint(const char *errstr, ...) {
625 va_start(ap, errstr);
626 vfprintf(stderr, errstr, ap);
633 XExposeEvent *ev = &e->xexpose;
635 if(ev->count == 0 && (ev->window == barwin))
641 if(!c || (c && !isvisible(c)))
642 for(c = stack; c && !isvisible(c); c = c->snext);
643 if(sel && sel != c) {
644 grabbuttons(sel, False);
645 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
650 grabbuttons(c, True);
654 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
655 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
658 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
663 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
664 XFocusChangeEvent *ev = &e->xfocus;
666 if(sel && ev->window != sel->win)
667 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
671 focusnext(const char *arg) {
676 for(c = sel->next; c && !isvisible(c); c = c->next);
678 for(c = clients; c && !isvisible(c); c = c->next);
686 focusprev(const char *arg) {
691 for(c = sel->prev; c && !isvisible(c); c = c->prev);
693 for(c = clients; c && c->next; c = c->next);
694 for(; c && !isvisible(c); c = c->prev);
703 getclient(Window w) {
706 for(c = clients; c && c->win != w; c = c->next);
711 getcolor(const char *colstr) {
712 Colormap cmap = DefaultColormap(dpy, screen);
715 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
716 eprint("error, cannot allocate color '%s'\n", colstr);
724 unsigned char *p = NULL;
725 unsigned long n, extra;
728 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
729 &real, &format, &n, &extra, (unsigned char **)&p);
730 if(status != Success)
739 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
744 if(!text || size == 0)
747 XGetTextProperty(dpy, w, &name, atom);
750 if(name.encoding == XA_STRING)
751 strncpy(text, (char *)name.value, size - 1);
753 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
755 strncpy(text, *list, size - 1);
756 XFreeStringList(list);
759 text[size - 1] = '\0';
765 grabbuttons(Client *c, Bool focused) {
767 unsigned int buttons[] = { Button1, Button2, Button3 };
768 unsigned int modifiers[] = { MODKEY, MODKEY|LockMask, MODKEY|numlockmask,
769 MODKEY|numlockmask|LockMask} ;
771 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
773 for(i = 0; i < LENGTH(buttons); i++)
774 for(j = 0; j < LENGTH(modifiers); j++)
775 XGrabButton(dpy, buttons[i], modifiers[j], c->win, False,
776 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
778 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
779 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
786 XModifierKeymap *modmap;
788 /* init modifier map */
789 modmap = XGetModifierMapping(dpy);
790 for(i = 0; i < 8; i++)
791 for(j = 0; j < modmap->max_keypermod; j++) {
792 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
793 numlockmask = (1 << i);
795 XFreeModifiermap(modmap);
797 XUngrabKey(dpy, AnyKey, AnyModifier, root);
798 for(i = 0; i < LENGTH(keys); i++) {
799 code = XKeysymToKeycode(dpy, keys[i].keysym);
800 XGrabKey(dpy, code, keys[i].mod, root, True,
801 GrabModeAsync, GrabModeAsync);
802 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
803 GrabModeAsync, GrabModeAsync);
804 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
805 GrabModeAsync, GrabModeAsync);
806 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
807 GrabModeAsync, GrabModeAsync);
812 idxoftag(const char *t) {
815 for(i = 0; (i < LENGTH(tags)) && t && strcmp(tags[i], t); i++);
816 return (i < LENGTH(tags)) ? i : 0;
820 initfont(const char *fontstr) {
821 char *def, **missing;
826 XFreeFontSet(dpy, dc.font.set);
827 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
830 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
831 XFreeStringList(missing);
834 XFontSetExtents *font_extents;
835 XFontStruct **xfonts;
837 dc.font.ascent = dc.font.descent = 0;
838 font_extents = XExtentsOfFontSet(dc.font.set);
839 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
840 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
841 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
842 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
848 XFreeFont(dpy, dc.font.xfont);
849 dc.font.xfont = NULL;
850 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
851 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
852 eprint("error, cannot load font: '%s'\n", fontstr);
853 dc.font.ascent = dc.font.xfont->ascent;
854 dc.font.descent = dc.font.xfont->descent;
856 dc.font.height = dc.font.ascent + dc.font.descent;
860 isoccupied(unsigned int t) {
863 for(c = clients; c; c = c->next)
870 isprotodel(Client *c) {
875 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
876 for(i = 0; !ret && i < n; i++)
877 if(protocols[i] == wmatom[WMDelete])
885 isurgent(unsigned int t) {
888 for(c = clients; c; c = c->next)
889 if(c->isurgent && c->tags[t])
895 isvisible(Client *c) {
898 for(i = 0; i < LENGTH(tags); i++)
899 if(c->tags[i] && tagset[seltags][i])
905 keypress(XEvent *e) {
911 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
912 for(i = 0; i < LENGTH(keys); i++)
913 if(keysym == keys[i].keysym
914 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
917 keys[i].func(keys[i].arg);
922 killclient(const char *arg) {
927 if(isprotodel(sel)) {
928 ev.type = ClientMessage;
929 ev.xclient.window = sel->win;
930 ev.xclient.message_type = wmatom[WMProtocols];
931 ev.xclient.format = 32;
932 ev.xclient.data.l[0] = wmatom[WMDelete];
933 ev.xclient.data.l[1] = CurrentTime;
934 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
937 XKillClient(dpy, sel->win);
941 manage(Window w, XWindowAttributes *wa) {
942 Client *c, *t = NULL;
947 c = emallocz(sizeof(Client));
948 c->tags = emallocz(TAGSZ);
956 c->oldbw = wa->border_width;
957 if(c->w == sw && c->h == sh) {
960 c->bw = wa->border_width;
963 if(c->x + c->w + 2 * c->bw > sx + sw)
964 c->x = sx + sw - c->w - 2 * c->bw;
965 if(c->y + c->h + 2 * c->bw > sy + sh)
966 c->y = sy + sh - c->h - 2 * c->bw;
967 c->x = MAX(c->x, sx);
968 c->y = MAX(c->y, by == 0 ? bh : sy);
972 wc.border_width = c->bw;
973 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
974 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
975 configure(c); /* propagates border_width, if size doesn't change */
977 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
978 grabbuttons(c, False);
980 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
981 for(t = clients; t && t->win != trans; t = t->next);
983 memcpy(c->tags, t->tags, TAGSZ);
987 c->isfloating = (rettrans == Success) || c->isfixed;
990 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
992 XMapWindow(dpy, c->win);
993 setclientstate(c, NormalState);
998 mappingnotify(XEvent *e) {
999 XMappingEvent *ev = &e->xmapping;
1001 XRefreshKeyboardMapping(ev);
1002 if(ev->request == MappingKeyboard)
1007 maprequest(XEvent *e) {
1008 static XWindowAttributes wa;
1009 XMapRequestEvent *ev = &e->xmaprequest;
1011 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1013 if(wa.override_redirect)
1015 if(!getclient(ev->window))
1016 manage(ev->window, &wa);
1020 movemouse(Client *c) {
1021 int x1, y1, ocx, ocy, di, nx, ny;
1028 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1029 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1031 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1033 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1036 XUngrabPointer(dpy, CurrentTime);
1038 case ConfigureRequest:
1041 handler[ev.type](&ev);
1045 nx = ocx + (ev.xmotion.x - x1);
1046 ny = ocy + (ev.xmotion.y - y1);
1047 if(snap && nx >= wx && nx <= wx + ww
1048 && ny >= wy && ny <= wy + wh) {
1049 if(abs(wx - nx) < snap)
1051 else if(abs((wx + ww) - (nx + c->w + 2 * c->bw)) < snap)
1052 nx = wx + ww - c->w - 2 * c->bw;
1053 if(abs(wy - ny) < snap)
1055 else if(abs((wy + wh) - (ny + c->h + 2 * c->bw)) < snap)
1056 ny = wy + wh - c->h - 2 * c->bw;
1057 if(!c->isfloating && lt->arrange && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
1058 togglefloating(NULL);
1060 if(!lt->arrange || c->isfloating)
1061 resize(c, nx, ny, c->w, c->h, False);
1068 nextunfloating(Client *c) {
1069 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1074 propertynotify(XEvent *e) {
1077 XPropertyEvent *ev = &e->xproperty;
1079 if(ev->state == PropertyDelete)
1080 return; /* ignore */
1081 if((c = getclient(ev->window))) {
1084 case XA_WM_TRANSIENT_FOR:
1085 XGetTransientForHint(dpy, c->win, &trans);
1086 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1089 case XA_WM_NORMAL_HINTS:
1097 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1106 quit(const char *arg) {
1107 readin = running = False;
1111 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1115 /* set minimum possible */
1119 /* temporarily remove base dimensions */
1123 /* adjust for aspect limits */
1124 if(c->minax != c->maxax && c->minay != c->maxay
1125 && c->minax > 0 && c->maxax > 0 && c->minay > 0 && c->maxay > 0) {
1126 if(w * c->maxay > h * c->maxax)
1127 w = h * c->maxax / c->maxay;
1128 else if(w * c->minay < h * c->minax)
1129 h = w * c->minay / c->minax;
1132 /* adjust for increment value */
1138 /* restore base dimensions */
1142 w = MAX(w, c->minw);
1143 h = MAX(h, c->minh);
1146 w = MIN(w, c->maxw);
1149 h = MIN(h, c->maxh);
1151 if(w <= 0 || h <= 0)
1154 x = sw - w - 2 * c->bw;
1156 y = sh - h - 2 * c->bw;
1157 if(x + w + 2 * c->bw < sx)
1159 if(y + h + 2 * c->bw < sy)
1161 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1164 c->w = wc.width = w;
1165 c->h = wc.height = h;
1166 wc.border_width = c->bw;
1167 XConfigureWindow(dpy, c->win,
1168 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1175 resizemouse(Client *c) {
1182 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1183 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1185 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1187 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1190 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1191 c->w + c->bw - 1, c->h + c->bw - 1);
1192 XUngrabPointer(dpy, CurrentTime);
1193 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1195 case ConfigureRequest:
1198 handler[ev.type](&ev);
1202 nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1203 nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1205 if(snap && nw >= wx && nw <= wx + ww
1206 && nh >= wy && nh <= wy + wh) {
1207 if(!c->isfloating && lt->arrange
1208 && (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)) {
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);
1338 setmfact(const char *arg) {
1341 if(!arg || lt->arrange != tile)
1344 d = strtod(arg, NULL);
1345 if(arg[0] == '-' || arg[0] == '+')
1347 if(d < 0.1 || d > 0.9)
1358 XSetWindowAttributes wa;
1361 screen = DefaultScreen(dpy);
1362 root = RootWindow(dpy, screen);
1366 sw = DisplayWidth(dpy, screen);
1367 sh = DisplayHeight(dpy, screen);
1368 bh = dc.font.height + 2;
1372 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1373 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1374 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1375 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1376 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1377 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1380 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1381 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1382 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1384 /* init appearance */
1385 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1386 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1387 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1388 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1389 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1390 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1393 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1394 dc.gc = XCreateGC(dpy, root, 0, 0);
1395 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1397 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1400 tagset[0] = emallocz(TAGSZ);
1401 tagset[1] = emallocz(TAGSZ);
1402 tagset[0][0] = tagset[1][0] = True;
1405 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1406 w = textw(layouts[i].symbol);
1410 wa.override_redirect = 1;
1411 wa.background_pixmap = ParentRelative;
1412 wa.event_mask = ButtonPressMask|ExposureMask;
1414 barwin = XCreateWindow(dpy, root, bx, by, bw, bh, 0, DefaultDepth(dpy, screen),
1415 CopyFromParent, DefaultVisual(dpy, screen),
1416 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1417 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1418 XMapRaised(dpy, barwin);
1419 strcpy(stext, "dwm-"VERSION);
1422 /* EWMH support per view */
1423 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1424 PropModeReplace, (unsigned char *) netatom, NetLast);
1426 /* select for events */
1427 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1428 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1429 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1430 XSelectInput(dpy, root, wa.event_mask);
1438 spawn(const char *arg) {
1439 static char *shell = NULL;
1441 if(!shell && !(shell = getenv("SHELL")))
1445 /* The double-fork construct avoids zombie processes and keeps the code
1446 * clean from stupid signal handlers. */
1450 close(ConnectionNumber(dpy));
1452 execl(shell, shell, "-c", arg, (char *)NULL);
1453 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1462 tag(const char *arg) {
1467 for(i = 0; i < LENGTH(tags); i++)
1468 sel->tags[i] = (arg == NULL);
1469 sel->tags[idxoftag(arg)] = True;
1474 textnw(const char *text, unsigned int len) {
1478 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1481 return XTextWidth(dc.font.xfont, text, len);
1485 textw(const char *text) {
1486 return textnw(text, strlen(text)) + dc.font.height;
1495 for(n = 0, c = nextunfloating(clients); c; c = nextunfloating(c->next), n++);
1500 c = nextunfloating(clients);
1503 tileresize(c, wx, wy, ww - 2 * c->bw, wh - 2 * c->bw);
1505 tileresize(c, mx, my, mw - 2 * c->bw, mh - 2 * c->bw);
1511 x = (tx > c->x + c->w) ? c->x + c->w + 2 * c->bw : tw;
1513 w = (tx > c->x + c->w) ? wx + ww - x : tw;
1518 for(i = 0, c = nextunfloating(c->next); c; c = nextunfloating(c->next), i++) {
1519 if(i + 1 == n) /* remainder */
1520 tileresize(c, x, y, w - 2 * c->bw, (ty + th) - y - 2 * c->bw);
1522 tileresize(c, x, y, w - 2 * c->bw, h - 2 * c->bw);
1524 y = c->y + c->h + 2 * c->bw;
1529 tileresize(Client *c, int x, int y, int w, int h) {
1530 resize(c, x, y, w, h, resizehints);
1531 if(resizehints && ((c->h < bh) || (c->h > h) || (c->w < bh) || (c->w > w)))
1532 /* client doesn't accept size constraints */
1533 resize(c, x, y, w, h, False);
1537 togglebar(const char *arg) {
1545 togglefloating(const char *arg) {
1548 sel->isfloating = !sel->isfloating;
1550 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1555 togglelayout(const char *arg) {
1559 if(++lt == &layouts[LENGTH(layouts)])
1563 for(i = 0; i < LENGTH(layouts); i++)
1564 if(!strcmp(arg, layouts[i].symbol))
1566 if(i == LENGTH(layouts))
1577 toggletag(const char *arg) {
1583 sel->tags[i] = !sel->tags[i];
1584 for(j = 0; j < LENGTH(tags) && !sel->tags[j]; j++);
1585 if(j == LENGTH(tags))
1586 sel->tags[i] = True; /* at least one tag must be enabled */
1591 toggleview(const char *arg) {
1595 tagset[seltags][i] = !tagset[seltags][i];
1596 for(j = 0; j < LENGTH(tags) && !tagset[seltags][j]; j++);
1597 if(j == LENGTH(tags))
1598 tagset[seltags][i] = True; /* at least one tag must be viewed */
1606 XMoveWindow(dpy, c->win, c->x, c->y);
1607 c->isbanned = False;
1611 unmanage(Client *c) {
1614 wc.border_width = c->oldbw;
1615 /* The server grab construct avoids race conditions. */
1617 XSetErrorHandler(xerrordummy);
1618 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1623 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1624 setclientstate(c, WithdrawnState);
1628 XSetErrorHandler(xerror);
1634 unmapnotify(XEvent *e) {
1636 XUnmapEvent *ev = &e->xunmap;
1638 if((c = getclient(ev->window)))
1644 if(dc.drawable != 0)
1645 XFreePixmap(dpy, dc.drawable);
1646 dc.drawable = XCreatePixmap(dpy, root, bw, bh, DefaultDepth(dpy, screen));
1647 XMoveResizeWindow(dpy, barwin, bx, by, bw, bh);
1654 XineramaScreenInfo *info = NULL;
1656 /* window area geometry */
1657 if(XineramaIsActive(dpy)) {
1658 info = XineramaQueryScreens(dpy, &i);
1660 wy = showbar && topbar ? info[0].y_org + bh : info[0].y_org;
1662 wh = showbar ? info[0].height - bh : info[0].height;
1669 wy = showbar && topbar ? sy + bh : sy;
1671 wh = showbar ? sh - bh : sh;
1676 by = showbar ? (topbar ? 0 : wy + wh) : -bh;
1679 /* update layout geometries */
1680 for(i = 0; i < LENGTH(layouts); i++)
1681 if(layouts[i].updategeom)
1682 layouts[i].updategeom();
1686 updatesizehints(Client *c) {
1690 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1692 c->flags = size.flags;
1693 if(c->flags & PBaseSize) {
1694 c->basew = size.base_width;
1695 c->baseh = size.base_height;
1697 else if(c->flags & PMinSize) {
1698 c->basew = size.min_width;
1699 c->baseh = size.min_height;
1702 c->basew = c->baseh = 0;
1703 if(c->flags & PResizeInc) {
1704 c->incw = size.width_inc;
1705 c->inch = size.height_inc;
1708 c->incw = c->inch = 0;
1709 if(c->flags & PMaxSize) {
1710 c->maxw = size.max_width;
1711 c->maxh = size.max_height;
1714 c->maxw = c->maxh = 0;
1715 if(c->flags & PMinSize) {
1716 c->minw = size.min_width;
1717 c->minh = size.min_height;
1719 else if(c->flags & PBaseSize) {
1720 c->minw = size.base_width;
1721 c->minh = size.base_height;
1724 c->minw = c->minh = 0;
1725 if(c->flags & PAspect) {
1726 c->minax = size.min_aspect.x;
1727 c->maxax = size.max_aspect.x;
1728 c->minay = size.min_aspect.y;
1729 c->maxay = size.max_aspect.y;
1732 c->minax = c->maxax = c->minay = c->maxay = 0;
1733 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1734 && c->maxw == c->minw && c->maxh == c->minh);
1738 updatetilegeom(void) {
1739 /* master area geometry */
1745 /* tile area geometry */
1753 updatetitle(Client *c) {
1754 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1755 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1759 updatewmhints(Client *c) {
1762 if((wmh = XGetWMHints(dpy, c->win))) {
1764 sel->isurgent = False;
1766 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1772 view(const char *arg) {
1773 seltags ^= 1; /* toggle sel tagset */
1774 memset(tagset[seltags], (NULL == arg), TAGSZ);
1775 tagset[seltags][idxoftag(arg)] = True;
1780 viewprevtag(const char *arg) {
1781 seltags ^= 1; /* toggle sel tagset */
1785 /* There's no way to check accesses to destroyed windows, thus those cases are
1786 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1787 * default error handler, which may call exit. */
1789 xerror(Display *dpy, XErrorEvent *ee) {
1790 if(ee->error_code == BadWindow
1791 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1792 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1793 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1794 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1795 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1796 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1797 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1798 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1800 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1801 ee->request_code, ee->error_code);
1802 return xerrorxlib(dpy, ee); /* may call exit */
1806 xerrordummy(Display *dpy, XErrorEvent *ee) {
1810 /* Startup Error handler to check if another window manager
1811 * is already running. */
1813 xerrorstart(Display *dpy, XErrorEvent *ee) {
1819 zoom(const char *arg) {
1822 if(c == nextunfloating(clients))
1823 if(!c || !(c = nextunfloating(c->next)))
1825 if(lt->arrange == tile && !sel->isfloating) {
1834 main(int argc, char *argv[]) {
1835 if(argc == 2 && !strcmp("-v", argv[1]))
1836 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1838 eprint("usage: dwm [-v]\n");
1840 setlocale(LC_CTYPE, "");
1841 if(!(dpy = XOpenDisplay(0)))
1842 eprint("dwm: cannot open display\n");