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>
37 #include <X11/cursorfont.h>
38 #include <X11/keysym.h>
39 #include <X11/Xatom.h>
41 #include <X11/Xproto.h>
42 #include <X11/Xutil.h>
45 * I intend to not provide real Xinerama support, but instead having a Column
46 * tilecols[] array which is used by tile(), and a Column maxcols[] arrays which is used by
47 * maximise(). Those arrays should be initialized in config.h. For simplicity
48 * reasons mwfact should be replaced with a more advanced method which
49 * implements the same, but using the boundary between tilecols[0] and
50 * tilecols[1] instead. Besides this, get rid of BARPOS and use instead the
51 * following mechanism:
56 * bh is calculated automatically and should be used for the
59 #include <X11/extensions/Xinerama.h>
63 #define BUTTONMASK (ButtonPressMask|ButtonReleaseMask)
64 #define CLEANMASK(mask) (mask & ~(numlockmask|LockMask))
65 #define LENGTH(x) (sizeof x / sizeof x[0])
67 #define MOUSEMASK (BUTTONMASK|PointerMotionMask)
71 enum { BarTop, BarBot, BarOff }; /* bar position */
72 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
73 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
74 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
75 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
78 typedef struct Client Client;
82 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
83 int minax, maxax, minay, maxay;
85 unsigned int border, oldborder;
86 Bool isbanned, isfixed, isfloating, isurgent;
100 unsigned long norm[ColLast];
101 unsigned long sel[ColLast];
111 } DC; /* draw context */
116 void (*func)(const char *arg);
122 void (*arrange)(void);
131 /* function declarations */
132 void applyrules(Client *c);
134 void attach(Client *c);
135 void attachstack(Client *c);
137 void buttonpress(XEvent *e);
138 void checkotherwm(void);
140 void configure(Client *c);
141 void configurenotify(XEvent *e);
142 void configurerequest(XEvent *e);
143 void destroynotify(XEvent *e);
144 void detach(Client *c);
145 void detachstack(Client *c);
147 void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
148 void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
149 void *emallocz(unsigned int size);
150 void enternotify(XEvent *e);
151 void eprint(const char *errstr, ...);
152 void expose(XEvent *e);
153 void floating(void); /* default floating layout */
154 void focus(Client *c);
155 void focusin(XEvent *e);
156 void focusnext(const char *arg);
157 void focusprev(const char *arg);
158 Client *getclient(Window w);
159 unsigned long getcolor(const char *colstr);
160 long getstate(Window w);
161 Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
162 void grabbuttons(Client *c, Bool focused);
164 unsigned int idxoftag(const char *t);
165 void initfont(const char *fontstr);
166 Bool isoccupied(unsigned int t);
167 Bool isprotodel(Client *c);
168 Bool isurgent(unsigned int t);
169 Bool isvisible(Client *c);
170 void keypress(XEvent *e);
171 void killclient(const char *arg);
172 void manage(Window w, XWindowAttributes *wa);
173 void mappingnotify(XEvent *e);
174 void maprequest(XEvent *e);
176 void movemouse(Client *c);
177 Client *nexttiled(Client *c);
178 void propertynotify(XEvent *e);
179 void quit(const char *arg);
180 void reapply(const char *arg);
181 void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
182 void resizemouse(Client *c);
186 void setclientstate(Client *c, long state);
187 void setlayout(const char *arg);
188 void setmwfact(const char *arg);
190 void spawn(const char *arg);
191 void tag(const char *arg);
192 unsigned int textnw(const char *text, unsigned int len);
193 unsigned int textw(const char *text);
195 void togglebar(const char *arg);
196 void togglefloating(const char *arg);
197 void toggletag(const char *arg);
198 void toggleview(const char *arg);
199 void unban(Client *c);
200 void unmanage(Client *c);
201 void unmapnotify(XEvent *e);
202 void updatebarpos(void);
203 void updatesizehints(Client *c);
204 void updatetitle(Client *c);
205 void updatewmhints(Client *c);
206 void view(const char *arg);
207 void viewprevtag(const char *arg); /* views previous selected tags */
208 int xerror(Display *dpy, XErrorEvent *ee);
209 int xerrordummy(Display *dpy, XErrorEvent *ee);
210 int xerrorstart(Display *dpy, XErrorEvent *ee);
211 void zoom(const char *arg);
212 void selectview(const char *arg);
215 char stext[256], buf[256];
217 int screen, sx, sy, sw, sh, wax, way, waw, wah, ncols;
218 int (*xerrorxlib)(Display *, XErrorEvent *);
219 unsigned int bh, bpos;
220 unsigned int blw = 0;
221 unsigned int numlockmask = 0;
222 void (*handler[LASTEvent]) (XEvent *) = {
223 [ButtonPress] = buttonpress,
224 [ConfigureRequest] = configurerequest,
225 [ConfigureNotify] = configurenotify,
226 [DestroyNotify] = destroynotify,
227 [EnterNotify] = enternotify,
230 [KeyPress] = keypress,
231 [MappingNotify] = mappingnotify,
232 [MapRequest] = maprequest,
233 [PropertyNotify] = propertynotify,
234 [UnmapNotify] = unmapnotify
236 Atom wmatom[WMLast], netatom[NetLast];
237 Bool domwfact = True;
239 Bool otherwm, readin;
243 Client *clients = NULL;
245 Client *stack = NULL;
247 Cursor cursor[CurLast];
253 /* configuration, allows nested code to access above variables */
255 #define TAGSZ (LENGTH(tags) * sizeof(Bool))
256 static Bool tmp[LENGTH(tags)];
258 /* function implementations */
261 applyrules(Client *c) {
263 Bool matched = False;
265 XClassHint ch = { 0 };
268 XGetClassHint(dpy, c->win, &ch);
269 for(i = 0; i < LENGTH(rules); i++) {
271 if(strstr(c->name, r->prop)
272 || (ch.res_class && strstr(ch.res_class, r->prop))
273 || (ch.res_name && strstr(ch.res_name, r->prop)))
275 c->isfloating = r->isfloating;
277 c->tags[idxoftag(r->tag)] = True;
287 memcpy(c->tags, seltags, TAGSZ);
294 for(c = clients; c; c = c->next)
314 attachstack(Client *c) {
323 XMoveWindow(dpy, c->win, c->x + 3 * sw, c->y);
328 buttonpress(XEvent *e) {
331 XButtonPressedEvent *ev = &e->xbutton;
333 if(ev->window == barwin) {
335 for(i = 0; i < LENGTH(tags); i++) {
338 if(ev->button == Button1) {
339 if(ev->state & MODKEY)
344 else if(ev->button == Button3) {
345 if(ev->state & MODKEY)
353 if((ev->x < x + blw) && ev->button == Button1)
356 else if((c = getclient(ev->window))) {
358 if(CLEANMASK(ev->state) != MODKEY)
360 if(ev->button == Button1) {
364 else if(ev->button == Button2) {
365 if((floating != lt->arrange) && c->isfloating)
366 togglefloating(NULL);
370 else if(ev->button == Button3 && !c->isfixed) {
380 XSetErrorHandler(xerrorstart);
382 /* this causes an error if some other window manager is running */
383 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
386 eprint("dwm: another window manager is already running\n");
388 XSetErrorHandler(NULL);
389 xerrorxlib = XSetErrorHandler(xerror);
402 XFreeFontSet(dpy, dc.font.set);
404 XFreeFont(dpy, dc.font.xfont);
406 XUngrabKey(dpy, AnyKey, AnyModifier, root);
407 XFreePixmap(dpy, dc.drawable);
409 XFreeCursor(dpy, cursor[CurNormal]);
410 XFreeCursor(dpy, cursor[CurResize]);
411 XFreeCursor(dpy, cursor[CurMove]);
412 XDestroyWindow(dpy, barwin);
414 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
418 configure(Client *c) {
421 ce.type = ConfigureNotify;
429 ce.border_width = c->border;
431 ce.override_redirect = False;
432 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
436 configurenotify(XEvent *e) {
437 XConfigureEvent *ev = &e->xconfigure;
439 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
440 /* TODO -- use Xinerama dimensions here ? */
443 XFreePixmap(dpy, dc.drawable);
444 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(root, screen), bh, DefaultDepth(dpy, screen));
445 XResizeWindow(dpy, barwin, sw, bh);
452 configurerequest(XEvent *e) {
454 XConfigureRequestEvent *ev = &e->xconfigurerequest;
457 /* TODO -- consider Xinerama if necessary when centering */
458 if((c = getclient(ev->window))) {
459 if(ev->value_mask & CWBorderWidth)
460 c->border = ev->border_width;
461 if(c->isfixed || c->isfloating || (floating == lt->arrange)) {
462 if(ev->value_mask & CWX)
464 if(ev->value_mask & CWY)
466 if(ev->value_mask & CWWidth)
468 if(ev->value_mask & CWHeight)
470 if((c->x - sx + c->w) > sw && c->isfloating)
471 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
472 if((c->y - sy + c->h) > sh && c->isfloating)
473 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
474 if((ev->value_mask & (CWX|CWY))
475 && !(ev->value_mask & (CWWidth|CWHeight)))
478 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
486 wc.width = ev->width;
487 wc.height = ev->height;
488 wc.border_width = ev->border_width;
489 wc.sibling = ev->above;
490 wc.stack_mode = ev->detail;
491 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
497 conflicts(Client *c, unsigned int tidx) {
500 for(i = 0; i < LENGTH(tags); i++)
502 return True; /* conflict */
507 destroynotify(XEvent *e) {
509 XDestroyWindowEvent *ev = &e->xdestroywindow;
511 if((c = getclient(ev->window)))
518 c->prev->next = c->next;
520 c->next->prev = c->prev;
523 c->next = c->prev = NULL;
527 detachstack(Client *c) {
530 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
540 for(c = stack; c && !isvisible(c); c = c->snext);
541 for(i = 0; i < LENGTH(tags); i++) {
542 dc.w = textw(tags[i]);
544 drawtext(tags[i], dc.sel, isurgent(i));
545 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.sel);
548 drawtext(tags[i], dc.norm, isurgent(i));
549 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.norm);
554 drawtext(lt->symbol, dc.norm, False);
562 drawtext(stext, dc.norm, False);
563 if((dc.w = dc.x - x) > bh) {
566 drawtext(c->name, dc.sel, False);
567 drawsquare(False, c->isfloating, False, dc.sel);
570 drawtext(NULL, dc.norm, False);
572 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, sw, bh, 0, 0);
577 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
580 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
582 gcv.foreground = col[invert ? ColBG : ColFG];
583 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
584 x = (dc.font.ascent + dc.font.descent + 2) / 4;
588 r.width = r.height = x + 1;
589 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
592 r.width = r.height = x;
593 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
598 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
600 unsigned int len, olen;
601 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
603 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
604 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
608 olen = len = strlen(text);
609 if(len >= sizeof buf)
610 len = sizeof buf - 1;
611 memcpy(buf, text, len);
613 h = dc.font.ascent + dc.font.descent;
614 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
616 /* shorten text if necessary */
617 while(len && (w = textnw(buf, len)) > dc.w - h)
628 return; /* too long */
629 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
631 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
633 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
637 emallocz(unsigned int size) {
638 void *res = calloc(1, size);
641 eprint("fatal: could not malloc() %u bytes\n", size);
646 enternotify(XEvent *e) {
648 XCrossingEvent *ev = &e->xcrossing;
650 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
652 if((c = getclient(ev->window)))
659 eprint(const char *errstr, ...) {
662 va_start(ap, errstr);
663 vfprintf(stderr, errstr, ap);
670 XExposeEvent *ev = &e->xexpose;
672 if(ev->count == 0 && (ev->window == barwin))
677 floating(void) { /* default floating layout */
680 domwfact = dozoom = False;
681 for(c = clients; c; c = c->next)
683 resize(c, c->x, c->y, c->w, c->h, True);
688 if(!c || (c && !isvisible(c)))
689 for(c = stack; c && !isvisible(c); c = c->snext);
690 if(sel && sel != c) {
691 grabbuttons(sel, False);
692 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
697 grabbuttons(c, True);
701 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
702 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
705 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
710 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
711 XFocusChangeEvent *ev = &e->xfocus;
713 if(sel && ev->window != sel->win)
714 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
718 focusnext(const char *arg) {
723 for(c = sel->next; c && !isvisible(c); c = c->next);
725 for(c = clients; c && !isvisible(c); c = c->next);
733 focusprev(const char *arg) {
738 for(c = sel->prev; c && !isvisible(c); c = c->prev);
740 for(c = clients; c && c->next; c = c->next);
741 for(; c && !isvisible(c); c = c->prev);
750 getclient(Window w) {
753 for(c = clients; c && c->win != w; c = c->next);
758 getcolor(const char *colstr) {
759 Colormap cmap = DefaultColormap(dpy, screen);
762 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
763 eprint("error, cannot allocate color '%s'\n", colstr);
771 unsigned char *p = NULL;
772 unsigned long n, extra;
775 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
776 &real, &format, &n, &extra, (unsigned char **)&p);
777 if(status != Success)
786 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
791 if(!text || size == 0)
794 XGetTextProperty(dpy, w, &name, atom);
797 if(name.encoding == XA_STRING)
798 strncpy(text, (char *)name.value, size - 1);
800 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
802 strncpy(text, *list, size - 1);
803 XFreeStringList(list);
806 text[size - 1] = '\0';
812 grabbuttons(Client *c, Bool focused) {
813 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
816 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
817 GrabModeAsync, GrabModeSync, None, None);
818 XGrabButton(dpy, Button1, MODKEY|LockMask, c->win, False, BUTTONMASK,
819 GrabModeAsync, GrabModeSync, None, None);
820 XGrabButton(dpy, Button1, MODKEY|numlockmask, c->win, False, BUTTONMASK,
821 GrabModeAsync, GrabModeSync, None, None);
822 XGrabButton(dpy, Button1, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
823 GrabModeAsync, GrabModeSync, None, None);
825 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
826 GrabModeAsync, GrabModeSync, None, None);
827 XGrabButton(dpy, Button2, MODKEY|LockMask, c->win, False, BUTTONMASK,
828 GrabModeAsync, GrabModeSync, None, None);
829 XGrabButton(dpy, Button2, MODKEY|numlockmask, c->win, False, BUTTONMASK,
830 GrabModeAsync, GrabModeSync, None, None);
831 XGrabButton(dpy, Button2, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
832 GrabModeAsync, GrabModeSync, None, None);
834 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
835 GrabModeAsync, GrabModeSync, None, None);
836 XGrabButton(dpy, Button3, MODKEY|LockMask, c->win, False, BUTTONMASK,
837 GrabModeAsync, GrabModeSync, None, None);
838 XGrabButton(dpy, Button3, MODKEY|numlockmask, c->win, False, BUTTONMASK,
839 GrabModeAsync, GrabModeSync, None, None);
840 XGrabButton(dpy, Button3, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
841 GrabModeAsync, GrabModeSync, None, None);
844 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
845 GrabModeAsync, GrabModeSync, None, None);
852 XModifierKeymap *modmap;
854 /* init modifier map */
855 modmap = XGetModifierMapping(dpy);
856 for(i = 0; i < 8; i++)
857 for(j = 0; j < modmap->max_keypermod; j++) {
858 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
859 numlockmask = (1 << i);
861 XFreeModifiermap(modmap);
863 XUngrabKey(dpy, AnyKey, AnyModifier, root);
864 for(i = 0; i < LENGTH(keys); i++) {
865 code = XKeysymToKeycode(dpy, keys[i].keysym);
866 XGrabKey(dpy, code, keys[i].mod, root, True,
867 GrabModeAsync, GrabModeAsync);
868 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
869 GrabModeAsync, GrabModeAsync);
870 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
871 GrabModeAsync, GrabModeAsync);
872 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
873 GrabModeAsync, GrabModeAsync);
878 idxoftag(const char *t) {
881 for(i = 0; (i < LENGTH(tags)) && (tags[i] != t); i++);
882 return (i < LENGTH(tags)) ? i : 0;
886 initfont(const char *fontstr) {
887 char *def, **missing;
892 XFreeFontSet(dpy, dc.font.set);
893 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
896 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
897 XFreeStringList(missing);
900 XFontSetExtents *font_extents;
901 XFontStruct **xfonts;
903 dc.font.ascent = dc.font.descent = 0;
904 font_extents = XExtentsOfFontSet(dc.font.set);
905 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
906 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
907 if(dc.font.ascent < (*xfonts)->ascent)
908 dc.font.ascent = (*xfonts)->ascent;
909 if(dc.font.descent < (*xfonts)->descent)
910 dc.font.descent = (*xfonts)->descent;
916 XFreeFont(dpy, dc.font.xfont);
917 dc.font.xfont = NULL;
918 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
919 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
920 eprint("error, cannot load font: '%s'\n", fontstr);
921 dc.font.ascent = dc.font.xfont->ascent;
922 dc.font.descent = dc.font.xfont->descent;
924 dc.font.height = dc.font.ascent + dc.font.descent;
928 isoccupied(unsigned int t) {
931 for(c = clients; c; c = c->next)
938 isprotodel(Client *c) {
943 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
944 for(i = 0; !ret && i < n; i++)
945 if(protocols[i] == wmatom[WMDelete])
953 isurgent(unsigned int t) {
956 for(c = clients; c; c = c->next)
957 if(c->isurgent && c->tags[t])
963 isvisible(Client *c) {
966 for(i = 0; i < LENGTH(tags); i++)
967 if(c->tags[i] && seltags[i])
973 keypress(XEvent *e) {
979 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
980 for(i = 0; i < LENGTH(keys); i++)
981 if(keysym == keys[i].keysym
982 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
985 keys[i].func(keys[i].arg);
990 killclient(const char *arg) {
995 if(isprotodel(sel)) {
996 ev.type = ClientMessage;
997 ev.xclient.window = sel->win;
998 ev.xclient.message_type = wmatom[WMProtocols];
999 ev.xclient.format = 32;
1000 ev.xclient.data.l[0] = wmatom[WMDelete];
1001 ev.xclient.data.l[1] = CurrentTime;
1002 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
1005 XKillClient(dpy, sel->win);
1009 manage(Window w, XWindowAttributes *wa) {
1010 Client *c, *t = NULL;
1015 c = emallocz(sizeof(Client));
1016 c->tags = emallocz(TAGSZ);
1023 c->oldborder = wa->border_width;
1025 if(c->w == sw && c->h == sh) {
1028 c->border = wa->border_width;
1031 if(c->x + c->w + 2 * c->border > wax + waw)
1032 c->x = wax + waw - c->w - 2 * c->border;
1033 if(c->y + c->h + 2 * c->border > way + wah)
1034 c->y = way + wah - c->h - 2 * c->border;
1039 c->border = BORDERPX;
1041 wc.border_width = c->border;
1042 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1043 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1044 configure(c); /* propagates border_width, if size doesn't change */
1046 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
1047 grabbuttons(c, False);
1049 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
1050 for(t = clients; t && t->win != trans; t = t->next);
1052 memcpy(c->tags, t->tags, TAGSZ);
1056 c->isfloating = (rettrans == Success) || c->isfixed;
1059 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
1061 XMapWindow(dpy, c->win);
1062 setclientstate(c, NormalState);
1067 mappingnotify(XEvent *e) {
1068 XMappingEvent *ev = &e->xmapping;
1070 XRefreshKeyboardMapping(ev);
1071 if(ev->request == MappingKeyboard)
1076 maprequest(XEvent *e) {
1077 static XWindowAttributes wa;
1078 XMapRequestEvent *ev = &e->xmaprequest;
1080 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1082 if(wa.override_redirect)
1084 if(!getclient(ev->window))
1085 manage(ev->window, &wa);
1092 domwfact = dozoom = False;
1093 for(c = nexttiled(clients); c; c = nexttiled(c->next))
1094 resize(c, wax, way, waw - 2 * c->border, wah - 2 * c->border, RESIZEHINTS);
1098 movemouse(Client *c) {
1099 int x1, y1, ocx, ocy, di, nx, ny;
1106 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1107 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1109 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1111 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1114 XUngrabPointer(dpy, CurrentTime);
1116 case ConfigureRequest:
1119 handler[ev.type](&ev);
1123 nx = ocx + (ev.xmotion.x - x1);
1124 ny = ocy + (ev.xmotion.y - y1);
1125 if(abs(wax - nx) < SNAP)
1127 else if(abs((wax + waw) - (nx + c->w + 2 * c->border)) < SNAP)
1128 nx = wax + waw - c->w - 2 * c->border;
1129 if(abs(way - ny) < SNAP)
1131 else if(abs((way + wah) - (ny + c->h + 2 * c->border)) < SNAP)
1132 ny = way + wah - c->h - 2 * c->border;
1133 if(!c->isfloating && (lt->arrange != floating) && (abs(nx - c->x) > SNAP || abs(ny - c->y) > SNAP))
1134 togglefloating(NULL);
1135 if((lt->arrange == floating) || c->isfloating)
1136 resize(c, nx, ny, c->w, c->h, False);
1143 nexttiled(Client *c) {
1144 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1149 propertynotify(XEvent *e) {
1152 XPropertyEvent *ev = &e->xproperty;
1154 if(ev->state == PropertyDelete)
1155 return; /* ignore */
1156 if((c = getclient(ev->window))) {
1159 case XA_WM_TRANSIENT_FOR:
1160 XGetTransientForHint(dpy, c->win, &trans);
1161 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1164 case XA_WM_NORMAL_HINTS:
1172 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1181 quit(const char *arg) {
1182 readin = running = False;
1186 reapply(const char *arg) {
1187 static Bool zerotags[LENGTH(tags)] = { 0 };
1190 for(c = clients; c; c = c->next) {
1191 memcpy(c->tags, zerotags, sizeof zerotags);
1198 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1202 /* set minimum possible */
1208 /* temporarily remove base dimensions */
1212 /* adjust for aspect limits */
1213 if (c->minay > 0 && c->maxay > 0 && c->minax > 0 && c->maxax > 0) {
1214 if (w * c->maxay > h * c->maxax)
1215 w = h * c->maxax / c->maxay;
1216 else if (w * c->minay < h * c->minax)
1217 h = w * c->minay / c->minax;
1220 /* adjust for increment value */
1226 /* restore base dimensions */
1230 if(c->minw > 0 && w < c->minw)
1232 if(c->minh > 0 && h < c->minh)
1234 if(c->maxw > 0 && w > c->maxw)
1236 if(c->maxh > 0 && h > c->maxh)
1239 if(w <= 0 || h <= 0)
1242 x = sw - w - 2 * c->border;
1244 y = sh - h - 2 * c->border;
1245 if(x + w + 2 * c->border < sx)
1247 if(y + h + 2 * c->border < sy)
1249 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1252 c->w = wc.width = w;
1253 c->h = wc.height = h;
1254 wc.border_width = c->border;
1255 XConfigureWindow(dpy, c->win,
1256 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1263 resizemouse(Client *c) {
1270 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1271 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1273 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
1275 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1278 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1279 c->w + c->border - 1, c->h + c->border - 1);
1280 XUngrabPointer(dpy, CurrentTime);
1281 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1283 case ConfigureRequest:
1286 handler[ev.type](&ev);
1290 if((nw = ev.xmotion.x - ocx - 2 * c->border + 1) <= 0)
1292 if((nh = ev.xmotion.y - ocy - 2 * c->border + 1) <= 0)
1294 if(!c->isfloating && (lt->arrange != floating) && (abs(nw - c->w) > SNAP || abs(nh - c->h) > SNAP))
1295 togglefloating(NULL);
1296 if((lt->arrange == floating) || c->isfloating)
1297 resize(c, c->x, c->y, nw, nh, True);
1312 if(sel->isfloating || (lt->arrange == floating))
1313 XRaiseWindow(dpy, sel->win);
1314 if(lt->arrange != floating) {
1315 wc.stack_mode = Below;
1316 wc.sibling = barwin;
1317 if(!sel->isfloating) {
1318 XConfigureWindow(dpy, sel->win, CWSibling|CWStackMode, &wc);
1319 wc.sibling = sel->win;
1321 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
1324 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1325 wc.sibling = c->win;
1329 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1335 char sbuf[sizeof stext];
1338 unsigned int len, offset;
1341 /* main event loop, also reads status text from stdin */
1343 xfd = ConnectionNumber(dpy);
1346 len = sizeof stext - 1;
1347 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1351 FD_SET(STDIN_FILENO, &rd);
1353 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1356 eprint("select failed\n");
1358 if(FD_ISSET(STDIN_FILENO, &rd)) {
1359 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1361 strncpy(stext, strerror(errno), len);
1365 strncpy(stext, "EOF", 4);
1369 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1370 if(*p == '\n' || *p == '\0') {
1372 strncpy(stext, sbuf, len);
1373 p += r - 1; /* p is sbuf + offset + r - 1 */
1374 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1377 memmove(sbuf, p - r + 1, r);
1384 while(XPending(dpy)) {
1385 XNextEvent(dpy, &ev);
1386 if(handler[ev.type])
1387 (handler[ev.type])(&ev); /* call handler */
1394 unsigned int i, num;
1395 Window *wins, d1, d2;
1396 XWindowAttributes wa;
1399 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1400 for(i = 0; i < num; i++) {
1401 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1402 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1404 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1405 manage(wins[i], &wa);
1407 for(i = 0; i < num; i++) { /* now the transients */
1408 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1410 if(XGetTransientForHint(dpy, wins[i], &d1)
1411 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1412 manage(wins[i], &wa);
1420 setclientstate(Client *c, long state) {
1421 long data[] = {state, None};
1423 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1424 PropModeReplace, (unsigned char *)data, 2);
1428 setlayout(const char *arg) {
1433 if(lt == &layouts[LENGTH(layouts)])
1437 for(i = 0; i < LENGTH(layouts); i++)
1438 if(!strcmp(arg, layouts[i].symbol))
1440 if(i == LENGTH(layouts))
1451 setmwfact(const char *arg) {
1456 /* arg handling, manipulate mwfact */
1459 else if(sscanf(arg, "%lf", &delta) == 1) {
1460 if(arg[0] == '+' || arg[0] == '-')
1466 else if(mwfact > 0.9)
1476 XSetWindowAttributes wa;
1478 XineramaScreenInfo *info;
1482 screen = DefaultScreen(dpy);
1483 root = RootWindow(dpy, screen);
1486 sw = DisplayWidth(dpy, screen);
1487 sh = DisplayHeight(dpy, screen);
1490 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1491 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1492 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1493 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1494 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1495 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1498 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1499 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1500 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1504 if(XineramaIsActive(dpy)) {
1505 if((info = XineramaQueryScreens(dpy, &screens))) {
1510 sh = info[0].height;
1514 cols = emallocz(ncols * sizeof(Column));
1515 for(i = 0; i < ncols; i++) {
1516 cols[i].x = info[i].x_org;
1517 cols[i].y = info[i].y_org;
1518 cols[i].w = info[i].width;
1519 cols[i].h = info[i].height;
1528 cols = emallocz(ncols * sizeof(Column));
1534 /* init appearance */
1535 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1536 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1537 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1538 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1539 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1540 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1542 dc.h = bh = dc.font.height + 2;
1543 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1544 dc.gc = XCreateGC(dpy, root, 0, 0);
1545 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1547 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1550 seltags = emallocz(TAGSZ);
1551 prevtags = emallocz(TAGSZ);
1552 seltags[0] = prevtags[0] = True;
1558 /* TODO: Xinerama hints ? */
1560 for(blw = i = 0; i < LENGTH(layouts); i++) {
1561 i = textw(layouts[i].symbol);
1567 wa.override_redirect = 1;
1568 wa.background_pixmap = ParentRelative;
1569 wa.event_mask = ButtonPressMask|ExposureMask;
1571 barwin = XCreateWindow(dpy, root, sx, sy, sw, bh, 0, DefaultDepth(dpy, screen),
1572 CopyFromParent, DefaultVisual(dpy, screen),
1573 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1574 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1576 XMapRaised(dpy, barwin);
1577 strcpy(stext, "dwm-"VERSION);
1580 /* EWMH support per view */
1581 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1582 PropModeReplace, (unsigned char *) netatom, NetLast);
1584 /* select for events */
1585 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1586 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1587 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1588 XSelectInput(dpy, root, wa.event_mask);
1596 spawn(const char *arg) {
1597 static char *shell = NULL;
1599 if(!shell && !(shell = getenv("SHELL")))
1603 /* The double-fork construct avoids zombie processes and keeps the code
1604 * clean from stupid signal handlers. */
1608 close(ConnectionNumber(dpy));
1610 execl(shell, shell, "-c", arg, (char *)NULL);
1611 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1620 tag(const char *arg) {
1625 for(i = 0; i < LENGTH(tags); i++)
1626 sel->tags[i] = (NULL == arg);
1627 sel->tags[idxoftag(arg)] = True;
1632 textnw(const char *text, unsigned int len) {
1636 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1639 return XTextWidth(dc.font.xfont, text, len);
1643 textw(const char *text) {
1644 return textnw(text, strlen(text)) + dc.font.height;
1649 unsigned int i, n, nx, ny, nw, nh, mw, th;
1652 domwfact = dozoom = True;
1656 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next))
1660 mw = (n == 1) ? waw : mwfact * waw;
1661 th = (n > 1) ? wah / (n - 1) : 0;
1662 if(n > 1 && th < bh)
1665 for(i = 0, c = mc = nexttiled(clients); c; c = nexttiled(c->next)) {
1666 if(i == 0) { /* master */
1667 nw = mw - 2 * c->border;
1668 nh = wah - 2 * c->border;
1670 else { /* tile window */
1673 nx += mc->w + 2 * mc->border;
1674 nw = waw - mw - 2 * c->border;
1676 if(i + 1 == n) /* remainder */
1677 nh = (way + wah) - ny - 2 * c->border;
1679 nh = th - 2 * c->border;
1681 resize(c, nx, ny, nw, nh, RESIZEHINTS);
1682 if((RESIZEHINTS) && ((c->h < bh) || (c->h > nh) || (c->w < bh) || (c->w > nw)))
1683 /* client doesn't accept size constraints */
1684 resize(c, nx, ny, nw, nh, False);
1685 if(n > 1 && th != wah)
1686 ny = c->y + c->h + 2 * c->border;
1692 togglebar(const char *arg) {
1694 bpos = (BARPOS == BarOff) ? BarTop : BARPOS;
1702 togglefloating(const char *arg) {
1705 sel->isfloating = !sel->isfloating;
1707 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1712 toggletag(const char *arg) {
1718 if(conflicts(sel, i))
1720 sel->tags[i] = !sel->tags[i];
1721 for(j = 0; j < LENGTH(tags) && !sel->tags[j]; j++);
1722 if(j == LENGTH(tags))
1723 sel->tags[i] = True; /* at least one tag must be enabled */
1728 toggleview(const char *arg) {
1732 seltags[i] = !seltags[i];
1733 for(j = 0; j < LENGTH(tags) && !seltags[j]; j++);
1734 if(j == LENGTH(tags))
1735 seltags[i] = True; /* at least one tag must be viewed */
1743 XMoveWindow(dpy, c->win, c->x, c->y);
1744 c->isbanned = False;
1748 unmanage(Client *c) {
1751 wc.border_width = c->oldborder;
1752 /* The server grab construct avoids race conditions. */
1754 XSetErrorHandler(xerrordummy);
1755 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1760 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1761 setclientstate(c, WithdrawnState);
1765 XSetErrorHandler(xerror);
1771 unmapnotify(XEvent *e) {
1773 XUnmapEvent *ev = &e->xunmap;
1775 if((c = getclient(ev->window)))
1780 updatebarpos(void) {
1791 XMoveWindow(dpy, barwin, sx, sy);
1795 XMoveWindow(dpy, barwin, sx, sy + wah);
1798 XMoveWindow(dpy, barwin, sx, sy - bh);
1802 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1806 updatesizehints(Client *c) {
1810 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1812 c->flags = size.flags;
1813 if(c->flags & PBaseSize) {
1814 c->basew = size.base_width;
1815 c->baseh = size.base_height;
1817 else if(c->flags & PMinSize) {
1818 c->basew = size.min_width;
1819 c->baseh = size.min_height;
1822 c->basew = c->baseh = 0;
1823 if(c->flags & PResizeInc) {
1824 c->incw = size.width_inc;
1825 c->inch = size.height_inc;
1828 c->incw = c->inch = 0;
1829 if(c->flags & PMaxSize) {
1830 c->maxw = size.max_width;
1831 c->maxh = size.max_height;
1834 c->maxw = c->maxh = 0;
1835 if(c->flags & PMinSize) {
1836 c->minw = size.min_width;
1837 c->minh = size.min_height;
1839 else if(c->flags & PBaseSize) {
1840 c->minw = size.base_width;
1841 c->minh = size.base_height;
1844 c->minw = c->minh = 0;
1845 if(c->flags & PAspect) {
1846 c->minax = size.min_aspect.x;
1847 c->maxax = size.max_aspect.x;
1848 c->minay = size.min_aspect.y;
1849 c->maxay = size.max_aspect.y;
1852 c->minax = c->maxax = c->minay = c->maxay = 0;
1853 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1854 && c->maxw == c->minw && c->maxh == c->minh);
1858 updatetitle(Client *c) {
1859 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1860 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1864 updatewmhints(Client *c) {
1867 if((wmh = XGetWMHints(dpy, c->win))) {
1868 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1875 view(const char *arg) {
1878 for(i = 0; i < LENGTH(tags); i++)
1879 tmp[i] = (NULL == arg);
1880 tmp[idxoftag(arg)] = True;
1882 if(memcmp(seltags, tmp, TAGSZ) != 0) {
1883 memcpy(prevtags, seltags, TAGSZ);
1884 memcpy(seltags, tmp, TAGSZ);
1890 viewprevtag(const char *arg) {
1892 memcpy(tmp, seltags, TAGSZ);
1893 memcpy(seltags, prevtags, TAGSZ);
1894 memcpy(prevtags, tmp, TAGSZ);
1898 /* There's no way to check accesses to destroyed windows, thus those cases are
1899 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1900 * default error handler, which may call exit. */
1902 xerror(Display *dpy, XErrorEvent *ee) {
1903 if(ee->error_code == BadWindow
1904 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1905 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1906 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1907 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1908 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1909 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1910 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1912 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1913 ee->request_code, ee->error_code);
1914 return xerrorxlib(dpy, ee); /* may call exit */
1918 xerrordummy(Display *dpy, XErrorEvent *ee) {
1922 /* Startup Error handler to check if another window manager
1923 * is already running. */
1925 xerrorstart(Display *dpy, XErrorEvent *ee) {
1931 zoom(const char *arg) {
1934 if(!sel || !dozoom || sel->isfloating)
1936 if(c == nexttiled(clients))
1937 if(!(c = nexttiled(c->next)))
1946 main(int argc, char *argv[]) {
1947 if(argc == 2 && !strcmp("-v", argv[1]))
1948 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1950 eprint("usage: dwm [-v]\n");
1952 setlocale(LC_CTYPE, "");
1953 if(!(dpy = XOpenDisplay(0)))
1954 eprint("dwm: cannot open display\n");