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>
44 #include <X11/extensions/Xinerama.h>
48 #define BUTTONMASK (ButtonPressMask|ButtonReleaseMask)
49 #define CLEANMASK(mask) (mask & ~(numlockmask|LockMask))
50 #define LENGTH(x) (sizeof x / sizeof x[0])
52 #define MOUSEMASK (BUTTONMASK|PointerMotionMask)
56 enum { BarTop, BarBot, BarOff }; /* bar position */
57 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
58 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
59 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
60 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
63 typedef struct Client Client;
67 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
68 int minax, maxax, minay, maxay;
70 unsigned int border, oldborder;
71 Bool isbanned, isfixed, isfloating, isurgent;
81 unsigned long norm[ColLast];
82 unsigned long sel[ColLast];
92 } DC; /* draw context */
97 void (*func)(const char *arg);
103 void (*arrange)(void);
112 /* function declarations */
113 void applyrules(Client *c);
115 void attach(Client *c);
116 void attachstack(Client *c);
118 void buttonpress(XEvent *e);
119 void checkotherwm(void);
121 void configure(Client *c);
122 void configurenotify(XEvent *e);
123 void configurerequest(XEvent *e);
124 void destroynotify(XEvent *e);
125 void detach(Client *c);
126 void detachstack(Client *c);
128 void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
129 void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
130 void *emallocz(unsigned int size);
131 void enternotify(XEvent *e);
132 void eprint(const char *errstr, ...);
133 void expose(XEvent *e);
134 void floating(void); /* default floating layout */
135 void focus(Client *c);
136 void focusin(XEvent *e);
137 void focusnext(const char *arg);
138 void focusprev(const char *arg);
139 Client *getclient(Window w);
140 unsigned long getcolor(const char *colstr);
141 long getstate(Window w);
142 Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
143 void grabbuttons(Client *c, Bool focused);
145 unsigned int idxoftag(const char *t);
146 void initfont(const char *fontstr);
147 Bool isoccupied(unsigned int t);
148 Bool isprotodel(Client *c);
149 Bool isurgent(unsigned int t);
150 Bool isvisible(Client *c);
151 void keypress(XEvent *e);
152 void killclient(const char *arg);
153 void manage(Window w, XWindowAttributes *wa);
154 void mappingnotify(XEvent *e);
155 void maprequest(XEvent *e);
157 void movemouse(Client *c);
158 Client *nexttiled(Client *c);
159 void propertynotify(XEvent *e);
160 void quit(const char *arg);
161 void reapply(const char *arg);
162 void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
163 void resizemouse(Client *c);
167 void setclientstate(Client *c, long state);
168 void setlayout(const char *arg);
169 void setmwfact(const char *arg);
171 void spawn(const char *arg);
172 void tag(const char *arg);
173 unsigned int textnw(const char *text, unsigned int len);
174 unsigned int textw(const char *text);
176 void togglebar(const char *arg);
177 void togglefloating(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 updatebarpos(void);
184 void updatesizehints(Client *c);
185 void updatetitle(Client *c);
186 void updatewmhints(Client *c);
187 void view(const char *arg);
188 void viewprevtag(const char *arg); /* views previous selected tags */
189 int xerror(Display *dpy, XErrorEvent *ee);
190 int xerrordummy(Display *dpy, XErrorEvent *ee);
191 int xerrorstart(Display *dpy, XErrorEvent *ee);
192 void zoom(const char *arg);
193 void selectview(const char *arg);
196 char stext[256], buf[256];
198 int screen, sx, sy, sw, sh, wax, way, waw, wah, xscreens;
199 int (*xerrorxlib)(Display *, XErrorEvent *);
200 unsigned int bh, bpos;
201 unsigned int blw = 0;
202 unsigned int numlockmask = 0;
203 void (*handler[LASTEvent]) (XEvent *) = {
204 [ButtonPress] = buttonpress,
205 [ConfigureRequest] = configurerequest,
206 [ConfigureNotify] = configurenotify,
207 [DestroyNotify] = destroynotify,
208 [EnterNotify] = enternotify,
211 [KeyPress] = keypress,
212 [MappingNotify] = mappingnotify,
213 [MapRequest] = maprequest,
214 [PropertyNotify] = propertynotify,
215 [UnmapNotify] = unmapnotify
217 Atom wmatom[WMLast], netatom[NetLast];
218 Bool domwfact = True;
220 Bool otherwm, readin;
224 Client *clients = NULL;
226 Client *stack = NULL;
227 Cursor cursor[CurLast];
233 XineramaScreenInfo *info = NULL;
236 /* configuration, allows nested code to access above variables */
238 #define TAGSZ (LENGTH(tags) * sizeof(Bool))
239 static Bool tmp[LENGTH(tags)];
241 /* function implementations */
244 applyrules(Client *c) {
246 Bool matched = False;
248 XClassHint ch = { 0 };
251 XGetClassHint(dpy, c->win, &ch);
252 for(i = 0; i < LENGTH(rules); i++) {
254 if(strstr(c->name, r->prop)
255 || (ch.res_class && strstr(ch.res_class, r->prop))
256 || (ch.res_name && strstr(ch.res_name, r->prop)))
258 c->isfloating = r->isfloating;
260 c->tags[idxoftag(r->tag)] = True;
270 memcpy(c->tags, seltags, TAGSZ);
277 for(c = clients; c; c = c->next)
297 attachstack(Client *c) {
306 XMoveWindow(dpy, c->win, c->x + 3 * sw, c->y);
311 buttonpress(XEvent *e) {
314 XButtonPressedEvent *ev = &e->xbutton;
316 if(ev->window == barwin) {
318 for(i = 0; i < LENGTH(tags); i++) {
321 if(ev->button == Button1) {
322 if(ev->state & MODKEY)
327 else if(ev->button == Button3) {
328 if(ev->state & MODKEY)
336 if((ev->x < x + blw) && ev->button == Button1)
339 else if((c = getclient(ev->window))) {
341 if(CLEANMASK(ev->state) != MODKEY)
343 if(ev->button == Button1) {
347 else if(ev->button == Button2) {
348 if((floating != lt->arrange) && c->isfloating)
349 togglefloating(NULL);
353 else if(ev->button == Button3 && !c->isfixed) {
363 XSetErrorHandler(xerrorstart);
365 /* this causes an error if some other window manager is running */
366 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
369 eprint("dwm: another window manager is already running\n");
371 XSetErrorHandler(NULL);
372 xerrorxlib = XSetErrorHandler(xerror);
385 XFreeFontSet(dpy, dc.font.set);
387 XFreeFont(dpy, dc.font.xfont);
389 XUngrabKey(dpy, AnyKey, AnyModifier, root);
390 XFreePixmap(dpy, dc.drawable);
392 XFreeCursor(dpy, cursor[CurNormal]);
393 XFreeCursor(dpy, cursor[CurResize]);
394 XFreeCursor(dpy, cursor[CurMove]);
395 XDestroyWindow(dpy, barwin);
401 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
405 configure(Client *c) {
408 ce.type = ConfigureNotify;
416 ce.border_width = c->border;
418 ce.override_redirect = False;
419 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
423 configurenotify(XEvent *e) {
424 XConfigureEvent *ev = &e->xconfigure;
426 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
427 /* TODO -- use Xinerama dimensions here ? */
430 XFreePixmap(dpy, dc.drawable);
431 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(root, screen), bh, DefaultDepth(dpy, screen));
432 XResizeWindow(dpy, barwin, sw, bh);
439 configurerequest(XEvent *e) {
441 XConfigureRequestEvent *ev = &e->xconfigurerequest;
444 /* TODO -- consider Xinerama if necessary when centering */
445 if((c = getclient(ev->window))) {
446 if(ev->value_mask & CWBorderWidth)
447 c->border = ev->border_width;
448 if(c->isfixed || c->isfloating || (floating == lt->arrange)) {
449 if(ev->value_mask & CWX)
451 if(ev->value_mask & CWY)
453 if(ev->value_mask & CWWidth)
455 if(ev->value_mask & CWHeight)
457 if((c->x - sx + c->w) > sw && c->isfloating)
458 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
459 if((c->y - sy + c->h) > sh && c->isfloating)
460 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
461 if((ev->value_mask & (CWX|CWY))
462 && !(ev->value_mask & (CWWidth|CWHeight)))
465 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
473 wc.width = ev->width;
474 wc.height = ev->height;
475 wc.border_width = ev->border_width;
476 wc.sibling = ev->above;
477 wc.stack_mode = ev->detail;
478 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
484 conflicts(Client *c, unsigned int tidx) {
487 for(i = 0; i < LENGTH(tags); i++)
489 return True; /* conflict */
494 destroynotify(XEvent *e) {
496 XDestroyWindowEvent *ev = &e->xdestroywindow;
498 if((c = getclient(ev->window)))
505 c->prev->next = c->next;
507 c->next->prev = c->prev;
510 c->next = c->prev = NULL;
514 detachstack(Client *c) {
517 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
527 for(c = stack; c && !isvisible(c); c = c->snext);
528 for(i = 0; i < LENGTH(tags); i++) {
529 dc.w = textw(tags[i]);
531 drawtext(tags[i], dc.sel, isurgent(i));
532 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.sel);
535 drawtext(tags[i], dc.norm, isurgent(i));
536 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.norm);
541 drawtext(lt->symbol, dc.norm, False);
549 drawtext(stext, dc.norm, False);
550 if((dc.w = dc.x - x) > bh) {
553 drawtext(c->name, dc.sel, False);
554 drawsquare(False, c->isfloating, False, dc.sel);
557 drawtext(NULL, dc.norm, False);
559 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, sw, bh, 0, 0);
564 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
567 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
569 gcv.foreground = col[invert ? ColBG : ColFG];
570 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
571 x = (dc.font.ascent + dc.font.descent + 2) / 4;
575 r.width = r.height = x + 1;
576 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
579 r.width = r.height = x;
580 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
585 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
587 unsigned int len, olen;
588 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
590 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
591 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
595 olen = len = strlen(text);
596 if(len >= sizeof buf)
597 len = sizeof buf - 1;
598 memcpy(buf, text, len);
600 h = dc.font.ascent + dc.font.descent;
601 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
603 /* shorten text if necessary */
604 while(len && (w = textnw(buf, len)) > dc.w - h)
615 return; /* too long */
616 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
618 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
620 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
624 emallocz(unsigned int size) {
625 void *res = calloc(1, size);
628 eprint("fatal: could not malloc() %u bytes\n", size);
633 enternotify(XEvent *e) {
635 XCrossingEvent *ev = &e->xcrossing;
637 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
639 if((c = getclient(ev->window)))
646 eprint(const char *errstr, ...) {
649 va_start(ap, errstr);
650 vfprintf(stderr, errstr, ap);
657 XExposeEvent *ev = &e->xexpose;
659 if(ev->count == 0 && (ev->window == barwin))
664 floating(void) { /* default floating layout */
667 domwfact = dozoom = False;
668 for(c = clients; c; c = c->next)
670 resize(c, c->x, c->y, c->w, c->h, True);
675 if(!c || (c && !isvisible(c)))
676 for(c = stack; c && !isvisible(c); c = c->snext);
677 if(sel && sel != c) {
678 grabbuttons(sel, False);
679 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
684 grabbuttons(c, True);
688 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
689 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
692 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
697 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
698 XFocusChangeEvent *ev = &e->xfocus;
700 if(sel && ev->window != sel->win)
701 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
705 focusnext(const char *arg) {
710 for(c = sel->next; c && !isvisible(c); c = c->next);
712 for(c = clients; c && !isvisible(c); c = c->next);
720 focusprev(const char *arg) {
725 for(c = sel->prev; c && !isvisible(c); c = c->prev);
727 for(c = clients; c && c->next; c = c->next);
728 for(; c && !isvisible(c); c = c->prev);
737 getclient(Window w) {
740 for(c = clients; c && c->win != w; c = c->next);
745 getcolor(const char *colstr) {
746 Colormap cmap = DefaultColormap(dpy, screen);
749 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
750 eprint("error, cannot allocate color '%s'\n", colstr);
758 unsigned char *p = NULL;
759 unsigned long n, extra;
762 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
763 &real, &format, &n, &extra, (unsigned char **)&p);
764 if(status != Success)
773 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
778 if(!text || size == 0)
781 XGetTextProperty(dpy, w, &name, atom);
784 if(name.encoding == XA_STRING)
785 strncpy(text, (char *)name.value, size - 1);
787 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
789 strncpy(text, *list, size - 1);
790 XFreeStringList(list);
793 text[size - 1] = '\0';
799 grabbuttons(Client *c, Bool focused) {
800 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
803 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
804 GrabModeAsync, GrabModeSync, None, None);
805 XGrabButton(dpy, Button1, MODKEY|LockMask, c->win, False, BUTTONMASK,
806 GrabModeAsync, GrabModeSync, None, None);
807 XGrabButton(dpy, Button1, MODKEY|numlockmask, c->win, False, BUTTONMASK,
808 GrabModeAsync, GrabModeSync, None, None);
809 XGrabButton(dpy, Button1, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
810 GrabModeAsync, GrabModeSync, None, None);
812 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
813 GrabModeAsync, GrabModeSync, None, None);
814 XGrabButton(dpy, Button2, MODKEY|LockMask, c->win, False, BUTTONMASK,
815 GrabModeAsync, GrabModeSync, None, None);
816 XGrabButton(dpy, Button2, MODKEY|numlockmask, c->win, False, BUTTONMASK,
817 GrabModeAsync, GrabModeSync, None, None);
818 XGrabButton(dpy, Button2, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
819 GrabModeAsync, GrabModeSync, None, None);
821 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
822 GrabModeAsync, GrabModeSync, None, None);
823 XGrabButton(dpy, Button3, MODKEY|LockMask, c->win, False, BUTTONMASK,
824 GrabModeAsync, GrabModeSync, None, None);
825 XGrabButton(dpy, Button3, MODKEY|numlockmask, c->win, False, BUTTONMASK,
826 GrabModeAsync, GrabModeSync, None, None);
827 XGrabButton(dpy, Button3, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
828 GrabModeAsync, GrabModeSync, None, None);
831 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
832 GrabModeAsync, GrabModeSync, None, None);
839 XModifierKeymap *modmap;
841 /* init modifier map */
842 modmap = XGetModifierMapping(dpy);
843 for(i = 0; i < 8; i++)
844 for(j = 0; j < modmap->max_keypermod; j++) {
845 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
846 numlockmask = (1 << i);
848 XFreeModifiermap(modmap);
850 XUngrabKey(dpy, AnyKey, AnyModifier, root);
851 for(i = 0; i < LENGTH(keys); i++) {
852 code = XKeysymToKeycode(dpy, keys[i].keysym);
853 XGrabKey(dpy, code, keys[i].mod, root, True,
854 GrabModeAsync, GrabModeAsync);
855 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
856 GrabModeAsync, GrabModeAsync);
857 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
858 GrabModeAsync, GrabModeAsync);
859 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
860 GrabModeAsync, GrabModeAsync);
865 idxoftag(const char *t) {
868 for(i = 0; (i < LENGTH(tags)) && (tags[i] != t); i++);
869 return (i < LENGTH(tags)) ? i : 0;
873 initfont(const char *fontstr) {
874 char *def, **missing;
879 XFreeFontSet(dpy, dc.font.set);
880 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
883 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
884 XFreeStringList(missing);
887 XFontSetExtents *font_extents;
888 XFontStruct **xfonts;
890 dc.font.ascent = dc.font.descent = 0;
891 font_extents = XExtentsOfFontSet(dc.font.set);
892 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
893 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
894 if(dc.font.ascent < (*xfonts)->ascent)
895 dc.font.ascent = (*xfonts)->ascent;
896 if(dc.font.descent < (*xfonts)->descent)
897 dc.font.descent = (*xfonts)->descent;
903 XFreeFont(dpy, dc.font.xfont);
904 dc.font.xfont = NULL;
905 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
906 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
907 eprint("error, cannot load font: '%s'\n", fontstr);
908 dc.font.ascent = dc.font.xfont->ascent;
909 dc.font.descent = dc.font.xfont->descent;
911 dc.font.height = dc.font.ascent + dc.font.descent;
915 isoccupied(unsigned int t) {
918 for(c = clients; c; c = c->next)
925 isprotodel(Client *c) {
930 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
931 for(i = 0; !ret && i < n; i++)
932 if(protocols[i] == wmatom[WMDelete])
940 isurgent(unsigned int t) {
943 for(c = clients; c; c = c->next)
944 if(c->isurgent && c->tags[t])
950 isvisible(Client *c) {
953 for(i = 0; i < LENGTH(tags); i++)
954 if(c->tags[i] && seltags[i])
960 keypress(XEvent *e) {
966 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
967 for(i = 0; i < LENGTH(keys); i++)
968 if(keysym == keys[i].keysym
969 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
972 keys[i].func(keys[i].arg);
977 killclient(const char *arg) {
982 if(isprotodel(sel)) {
983 ev.type = ClientMessage;
984 ev.xclient.window = sel->win;
985 ev.xclient.message_type = wmatom[WMProtocols];
986 ev.xclient.format = 32;
987 ev.xclient.data.l[0] = wmatom[WMDelete];
988 ev.xclient.data.l[1] = CurrentTime;
989 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
992 XKillClient(dpy, sel->win);
996 manage(Window w, XWindowAttributes *wa) {
997 Client *c, *t = NULL;
1002 c = emallocz(sizeof(Client));
1003 c->tags = emallocz(TAGSZ);
1010 c->oldborder = wa->border_width;
1012 if(c->w == sw && c->h == sh) {
1015 c->border = wa->border_width;
1018 if(c->x + c->w + 2 * c->border > wax + waw)
1019 c->x = wax + waw - c->w - 2 * c->border;
1020 if(c->y + c->h + 2 * c->border > way + wah)
1021 c->y = way + wah - c->h - 2 * c->border;
1026 c->border = BORDERPX;
1028 wc.border_width = c->border;
1029 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1030 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1031 configure(c); /* propagates border_width, if size doesn't change */
1033 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
1034 grabbuttons(c, False);
1036 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
1037 for(t = clients; t && t->win != trans; t = t->next);
1039 memcpy(c->tags, t->tags, TAGSZ);
1043 c->isfloating = (rettrans == Success) || c->isfixed;
1046 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
1048 XMapWindow(dpy, c->win);
1049 setclientstate(c, NormalState);
1054 mappingnotify(XEvent *e) {
1055 XMappingEvent *ev = &e->xmapping;
1057 XRefreshKeyboardMapping(ev);
1058 if(ev->request == MappingKeyboard)
1063 maprequest(XEvent *e) {
1064 static XWindowAttributes wa;
1065 XMapRequestEvent *ev = &e->xmaprequest;
1067 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1069 if(wa.override_redirect)
1071 if(!getclient(ev->window))
1072 manage(ev->window, &wa);
1079 domwfact = dozoom = False;
1080 for(c = nexttiled(clients); c; c = nexttiled(c->next))
1081 resize(c, wax, way, waw - 2 * c->border, wah - 2 * c->border, RESIZEHINTS);
1085 movemouse(Client *c) {
1086 int x1, y1, ocx, ocy, di, nx, ny;
1093 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1094 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1096 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1098 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1101 XUngrabPointer(dpy, CurrentTime);
1103 case ConfigureRequest:
1106 handler[ev.type](&ev);
1110 nx = ocx + (ev.xmotion.x - x1);
1111 ny = ocy + (ev.xmotion.y - y1);
1112 if(abs(wax - nx) < SNAP)
1114 else if(abs((wax + waw) - (nx + c->w + 2 * c->border)) < SNAP)
1115 nx = wax + waw - c->w - 2 * c->border;
1116 if(abs(way - ny) < SNAP)
1118 else if(abs((way + wah) - (ny + c->h + 2 * c->border)) < SNAP)
1119 ny = way + wah - c->h - 2 * c->border;
1120 if(!c->isfloating && (lt->arrange != floating) && (abs(nx - c->x) > SNAP || abs(ny - c->y) > SNAP))
1121 togglefloating(NULL);
1122 if((lt->arrange == floating) || c->isfloating)
1123 resize(c, nx, ny, c->w, c->h, False);
1130 nexttiled(Client *c) {
1131 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1136 propertynotify(XEvent *e) {
1139 XPropertyEvent *ev = &e->xproperty;
1141 if(ev->state == PropertyDelete)
1142 return; /* ignore */
1143 if((c = getclient(ev->window))) {
1146 case XA_WM_TRANSIENT_FOR:
1147 XGetTransientForHint(dpy, c->win, &trans);
1148 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1151 case XA_WM_NORMAL_HINTS:
1159 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1168 quit(const char *arg) {
1169 readin = running = False;
1173 reapply(const char *arg) {
1174 static Bool zerotags[LENGTH(tags)] = { 0 };
1177 for(c = clients; c; c = c->next) {
1178 memcpy(c->tags, zerotags, sizeof zerotags);
1185 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1189 /* set minimum possible */
1195 /* temporarily remove base dimensions */
1199 /* adjust for aspect limits */
1200 if (c->minay > 0 && c->maxay > 0 && c->minax > 0 && c->maxax > 0) {
1201 if (w * c->maxay > h * c->maxax)
1202 w = h * c->maxax / c->maxay;
1203 else if (w * c->minay < h * c->minax)
1204 h = w * c->minay / c->minax;
1207 /* adjust for increment value */
1213 /* restore base dimensions */
1217 if(c->minw > 0 && w < c->minw)
1219 if(c->minh > 0 && h < c->minh)
1221 if(c->maxw > 0 && w > c->maxw)
1223 if(c->maxh > 0 && h > c->maxh)
1226 if(w <= 0 || h <= 0)
1229 x = sw - w - 2 * c->border;
1231 y = sh - h - 2 * c->border;
1232 if(x + w + 2 * c->border < sx)
1234 if(y + h + 2 * c->border < sy)
1236 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1239 c->w = wc.width = w;
1240 c->h = wc.height = h;
1241 wc.border_width = c->border;
1242 XConfigureWindow(dpy, c->win,
1243 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1250 resizemouse(Client *c) {
1257 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1258 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1260 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
1262 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1265 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1266 c->w + c->border - 1, c->h + c->border - 1);
1267 XUngrabPointer(dpy, CurrentTime);
1268 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1270 case ConfigureRequest:
1273 handler[ev.type](&ev);
1277 if((nw = ev.xmotion.x - ocx - 2 * c->border + 1) <= 0)
1279 if((nh = ev.xmotion.y - ocy - 2 * c->border + 1) <= 0)
1281 if(!c->isfloating && (lt->arrange != floating) && (abs(nw - c->w) > SNAP || abs(nh - c->h) > SNAP))
1282 togglefloating(NULL);
1283 if((lt->arrange == floating) || c->isfloating)
1284 resize(c, c->x, c->y, nw, nh, True);
1299 if(sel->isfloating || (lt->arrange == floating))
1300 XRaiseWindow(dpy, sel->win);
1301 if(lt->arrange != floating) {
1302 wc.stack_mode = Below;
1303 wc.sibling = barwin;
1304 if(!sel->isfloating) {
1305 XConfigureWindow(dpy, sel->win, CWSibling|CWStackMode, &wc);
1306 wc.sibling = sel->win;
1308 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
1311 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1312 wc.sibling = c->win;
1316 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1322 char sbuf[sizeof stext];
1325 unsigned int len, offset;
1328 /* main event loop, also reads status text from stdin */
1330 xfd = ConnectionNumber(dpy);
1333 len = sizeof stext - 1;
1334 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1338 FD_SET(STDIN_FILENO, &rd);
1340 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1343 eprint("select failed\n");
1345 if(FD_ISSET(STDIN_FILENO, &rd)) {
1346 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1348 strncpy(stext, strerror(errno), len);
1352 strncpy(stext, "EOF", 4);
1356 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1357 if(*p == '\n' || *p == '\0') {
1359 strncpy(stext, sbuf, len);
1360 p += r - 1; /* p is sbuf + offset + r - 1 */
1361 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1364 memmove(sbuf, p - r + 1, r);
1371 while(XPending(dpy)) {
1372 XNextEvent(dpy, &ev);
1373 if(handler[ev.type])
1374 (handler[ev.type])(&ev); /* call handler */
1381 unsigned int i, num;
1382 Window *wins, d1, d2;
1383 XWindowAttributes wa;
1386 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1387 for(i = 0; i < num; i++) {
1388 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1389 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1391 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1392 manage(wins[i], &wa);
1394 for(i = 0; i < num; i++) { /* now the transients */
1395 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1397 if(XGetTransientForHint(dpy, wins[i], &d1)
1398 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1399 manage(wins[i], &wa);
1407 setclientstate(Client *c, long state) {
1408 long data[] = {state, None};
1410 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1411 PropModeReplace, (unsigned char *)data, 2);
1415 setlayout(const char *arg) {
1420 if(lt == &layouts[LENGTH(layouts)])
1424 for(i = 0; i < LENGTH(layouts); i++)
1425 if(!strcmp(arg, layouts[i].symbol))
1427 if(i == LENGTH(layouts))
1438 setmwfact(const char *arg) {
1443 /* arg handling, manipulate mwfact */
1446 else if(sscanf(arg, "%lf", &delta) == 1) {
1447 if(arg[0] == '+' || arg[0] == '-')
1453 else if(mwfact > 0.9)
1462 XSetWindowAttributes wa;
1465 screen = DefaultScreen(dpy);
1466 root = RootWindow(dpy, screen);
1469 sw = DisplayWidth(dpy, screen);
1470 sh = DisplayHeight(dpy, screen);
1473 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1474 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1475 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1476 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1477 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1478 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1481 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1482 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1483 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1486 if(XineramaIsActive(dpy))
1487 info = XineramaQueryScreens(dpy, &xscreens);
1490 /* init appearance */
1491 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1492 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1493 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1494 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1495 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1496 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1498 dc.h = bh = dc.font.height + 2;
1499 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1500 dc.gc = XCreateGC(dpy, root, 0, 0);
1501 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1503 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1506 seltags = emallocz(TAGSZ);
1507 prevtags = emallocz(TAGSZ);
1508 seltags[0] = prevtags[0] = True;
1514 /* TODO: Xinerama hints ? */
1516 for(blw = i = 0; i < LENGTH(layouts); i++) {
1517 i = textw(layouts[i].symbol);
1523 wa.override_redirect = 1;
1524 wa.background_pixmap = ParentRelative;
1525 wa.event_mask = ButtonPressMask|ExposureMask;
1527 barwin = XCreateWindow(dpy, root, sx, sy, sw, bh, 0, DefaultDepth(dpy, screen),
1528 CopyFromParent, DefaultVisual(dpy, screen),
1529 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1530 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1532 XMapRaised(dpy, barwin);
1533 strcpy(stext, "dwm-"VERSION);
1536 /* EWMH support per view */
1537 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1538 PropModeReplace, (unsigned char *) netatom, NetLast);
1540 /* select for events */
1541 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1542 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1543 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1544 XSelectInput(dpy, root, wa.event_mask);
1552 spawn(const char *arg) {
1553 static char *shell = NULL;
1555 if(!shell && !(shell = getenv("SHELL")))
1559 /* The double-fork construct avoids zombie processes and keeps the code
1560 * clean from stupid signal handlers. */
1564 close(ConnectionNumber(dpy));
1566 execl(shell, shell, "-c", arg, (char *)NULL);
1567 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1576 tag(const char *arg) {
1581 for(i = 0; i < LENGTH(tags); i++)
1582 sel->tags[i] = (NULL == arg);
1583 sel->tags[idxoftag(arg)] = True;
1588 textnw(const char *text, unsigned int len) {
1592 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1595 return XTextWidth(dc.font.xfont, text, len);
1599 textw(const char *text) {
1600 return textnw(text, strlen(text)) + dc.font.height;
1605 unsigned int i, n, nx, ny, nw, nh, mw, th;
1608 domwfact = dozoom = True;
1612 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next))
1616 mw = (n == 1) ? waw : mwfact * waw;
1617 th = (n > 1) ? wah / (n - 1) : 0;
1618 if(n > 1 && th < bh)
1621 for(i = 0, c = mc = nexttiled(clients); c; c = nexttiled(c->next)) {
1622 if(i == 0) { /* master */
1623 nw = mw - 2 * c->border;
1624 nh = wah - 2 * c->border;
1626 else { /* tile window */
1629 nx += mc->w + 2 * mc->border;
1630 nw = waw - mw - 2 * c->border;
1632 if(i + 1 == n) /* remainder */
1633 nh = (way + wah) - ny - 2 * c->border;
1635 nh = th - 2 * c->border;
1637 resize(c, nx, ny, nw, nh, RESIZEHINTS);
1638 if((RESIZEHINTS) && ((c->h < bh) || (c->h > nh) || (c->w < bh) || (c->w > nw)))
1639 /* client doesn't accept size constraints */
1640 resize(c, nx, ny, nw, nh, False);
1641 if(n > 1 && th != wah)
1642 ny = c->y + c->h + 2 * c->border;
1648 togglebar(const char *arg) {
1650 bpos = (BARPOS == BarOff) ? BarTop : BARPOS;
1658 togglefloating(const char *arg) {
1661 sel->isfloating = !sel->isfloating;
1663 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1668 toggletag(const char *arg) {
1674 if(conflicts(sel, i))
1676 sel->tags[i] = !sel->tags[i];
1677 for(j = 0; j < LENGTH(tags) && !sel->tags[j]; j++);
1678 if(j == LENGTH(tags))
1679 sel->tags[i] = True; /* at least one tag must be enabled */
1684 toggleview(const char *arg) {
1688 seltags[i] = !seltags[i];
1689 for(j = 0; j < LENGTH(tags) && !seltags[j]; j++);
1690 if(j == LENGTH(tags))
1691 seltags[i] = True; /* at least one tag must be viewed */
1699 XMoveWindow(dpy, c->win, c->x, c->y);
1700 c->isbanned = False;
1704 unmanage(Client *c) {
1707 wc.border_width = c->oldborder;
1708 /* The server grab construct avoids race conditions. */
1710 XSetErrorHandler(xerrordummy);
1711 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1716 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1717 setclientstate(c, WithdrawnState);
1721 XSetErrorHandler(xerror);
1727 unmapnotify(XEvent *e) {
1729 XUnmapEvent *ev = &e->xunmap;
1731 if((c = getclient(ev->window)))
1736 updatebarpos(void) {
1747 XMoveWindow(dpy, barwin, sx, sy);
1751 XMoveWindow(dpy, barwin, sx, sy + wah);
1754 XMoveWindow(dpy, barwin, sx, sy - bh);
1758 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1762 updatesizehints(Client *c) {
1766 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1768 c->flags = size.flags;
1769 if(c->flags & PBaseSize) {
1770 c->basew = size.base_width;
1771 c->baseh = size.base_height;
1773 else if(c->flags & PMinSize) {
1774 c->basew = size.min_width;
1775 c->baseh = size.min_height;
1778 c->basew = c->baseh = 0;
1779 if(c->flags & PResizeInc) {
1780 c->incw = size.width_inc;
1781 c->inch = size.height_inc;
1784 c->incw = c->inch = 0;
1785 if(c->flags & PMaxSize) {
1786 c->maxw = size.max_width;
1787 c->maxh = size.max_height;
1790 c->maxw = c->maxh = 0;
1791 if(c->flags & PMinSize) {
1792 c->minw = size.min_width;
1793 c->minh = size.min_height;
1795 else if(c->flags & PBaseSize) {
1796 c->minw = size.base_width;
1797 c->minh = size.base_height;
1800 c->minw = c->minh = 0;
1801 if(c->flags & PAspect) {
1802 c->minax = size.min_aspect.x;
1803 c->maxax = size.max_aspect.x;
1804 c->minay = size.min_aspect.y;
1805 c->maxay = size.max_aspect.y;
1808 c->minax = c->maxax = c->minay = c->maxay = 0;
1809 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1810 && c->maxw == c->minw && c->maxh == c->minh);
1814 updatetitle(Client *c) {
1815 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1816 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1820 updatewmhints(Client *c) {
1823 if((wmh = XGetWMHints(dpy, c->win))) {
1824 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1831 view(const char *arg) {
1834 for(i = 0; i < LENGTH(tags); i++)
1835 tmp[i] = (NULL == arg);
1836 tmp[idxoftag(arg)] = True;
1838 if(memcmp(seltags, tmp, TAGSZ) != 0) {
1839 memcpy(prevtags, seltags, TAGSZ);
1840 memcpy(seltags, tmp, TAGSZ);
1846 viewprevtag(const char *arg) {
1848 memcpy(tmp, seltags, TAGSZ);
1849 memcpy(seltags, prevtags, TAGSZ);
1850 memcpy(prevtags, tmp, TAGSZ);
1854 /* There's no way to check accesses to destroyed windows, thus those cases are
1855 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1856 * default error handler, which may call exit. */
1858 xerror(Display *dpy, XErrorEvent *ee) {
1859 if(ee->error_code == BadWindow
1860 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1861 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1862 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1863 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1864 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1865 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1866 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1868 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1869 ee->request_code, ee->error_code);
1870 return xerrorxlib(dpy, ee); /* may call exit */
1874 xerrordummy(Display *dpy, XErrorEvent *ee) {
1878 /* Startup Error handler to check if another window manager
1879 * is already running. */
1881 xerrorstart(Display *dpy, XErrorEvent *ee) {
1887 zoom(const char *arg) {
1890 if(!sel || !dozoom || sel->isfloating)
1892 if(c == nexttiled(clients))
1893 if(!(c = nexttiled(c->next)))
1902 main(int argc, char *argv[]) {
1903 if(argc == 2 && !strcmp("-v", argv[1]))
1904 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1906 eprint("usage: dwm [-v]\n");
1908 setlocale(LC_CTYPE, "");
1909 if(!(dpy = XOpenDisplay(0)))
1910 eprint("dwm: cannot open display\n");