1 /* See LICENSE file for copyright and license details.
3 * dynamic window manager is designed like any other X client as well. It is
4 * driven through handling X events. In contrast to other X clients, a window
5 * manager selects for SubstructureRedirectMask on the root window, to receive
6 * events about window (dis-)appearance. Only one X connection at a time is
7 * allowed to select for this event mask.
9 * Calls to fetch an X event from the event queue are blocking. Due reading
10 * status text from standard input, a select()-driven main loop has been
11 * implemented which selects for reads on the X connection and STDIN_FILENO to
12 * handle all data smoothly. The event handlers of dwm are organized in an
13 * array which is accessed whenever a new event has been fetched. This allows
14 * event dispatching in O(1) time.
16 * Each child of the root window is called a client, except windows which have
17 * set the override_redirect flag. Clients are organized in a global
18 * doubly-linked client list, the focus history is remembered through a global
19 * stack list. Each client contains an array of Bools of the same size as the
20 * global tags array to indicate the tags of a client.
22 * Keys and tagging rules are organized as arrays and defined in config.h.
24 * To understand everything else, start reading main().
33 #include <sys/select.h>
34 #include <sys/types.h>
36 #include <X11/cursorfont.h>
37 #include <X11/keysym.h>
38 #include <X11/Xatom.h>
40 #include <X11/Xproto.h>
41 #include <X11/Xutil.h>
44 #define MAX(a, b) ((a)>(b)?(a):(b))
45 #define MIN(a, b) ((a)<(b)?(a):(b))
46 #define BUTTONMASK (ButtonPressMask|ButtonReleaseMask)
47 #define CLEANMASK(mask) (mask & ~(numlockmask|LockMask))
48 #define LENGTH(x) (sizeof x / sizeof x[0])
50 #define MOUSEMASK (BUTTONMASK|PointerMotionMask)
51 #define DEFGEOM(GEONAME,BX,BY,BW,WX,WY,WW,WH,MX,MY,MW,MH,TX,TY,TW,TH,MOX,MOY,MOW,MOH) \
52 void GEONAME(void) { \
53 bx = (BX); by = (BY); bw = (BW); \
54 wx = (WX); wy = (WY); ww = (WW); wh = (WH); \
55 mx = (MX); my = (MY); mw = (MW); mh = (MH); \
56 tx = (TX); ty = (TY); tw = (TW); th = (TH); \
57 mox = (MOX); moy = (MOY); mow = (MOW); moh = (MOH); \
61 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
62 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
63 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
64 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
67 typedef struct Client Client;
72 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
73 int minax, maxax, minay, maxay;
75 unsigned int bw, oldbw;
76 Bool isbanned, isfixed, isfloating, isurgent;
86 unsigned long norm[ColLast];
87 unsigned long sel[ColLast];
97 } DC; /* draw context */
107 void (*func)(const char *arg);
113 void (*arrange)(void);
119 const char *instance;
125 /* function declarations */
126 void applyrules(Client *c);
128 void attach(Client *c);
129 void attachstack(Client *c);
131 void buttonpress(XEvent *e);
132 void checkotherwm(void);
134 void configure(Client *c);
135 void configurenotify(XEvent *e);
136 void configurerequest(XEvent *e);
137 unsigned int counttiled(void);
138 void destroynotify(XEvent *e);
139 void detach(Client *c);
140 void detachstack(Client *c);
142 void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
143 void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
144 void *emallocz(unsigned int size);
145 void enternotify(XEvent *e);
146 void eprint(const char *errstr, ...);
147 void expose(XEvent *e);
148 void focus(Client *c);
149 void focusin(XEvent *e);
150 void focusnext(const char *arg);
151 void focusprev(const char *arg);
152 Client *getclient(Window w);
153 unsigned long getcolor(const char *colstr);
154 long getstate(Window w);
155 Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
156 void grabbuttons(Client *c, Bool focused);
158 unsigned int idxoftag(const char *t);
159 void initfont(const char *fontstr);
160 Bool isoccupied(unsigned int t);
161 Bool isprotodel(Client *c);
162 Bool isurgent(unsigned int t);
163 Bool isvisible(Client *c);
164 void keypress(XEvent *e);
165 void killclient(const char *arg);
166 void manage(Window w, XWindowAttributes *wa);
167 void mappingnotify(XEvent *e);
168 void maprequest(XEvent *e);
170 void movemouse(Client *c);
171 Client *nexttiled(Client *c);
172 void propertynotify(XEvent *e);
173 void quit(const char *arg);
174 void reapply(const char *arg);
175 void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
176 void resizemouse(Client *c);
180 void setclientstate(Client *c, long state);
181 void setgeom(const char *arg);
182 void setlayout(const char *arg);
183 void setmfact(const char *arg);
185 void spawn(const char *arg);
186 void tag(const char *arg);
187 unsigned int textnw(const char *text, unsigned int len);
188 unsigned int textw(const char *text);
190 void tilehstack(unsigned int n);
191 Client *tilemaster(unsigned int n);
192 void tileresize(Client *c, int x, int y, int w, int h);
194 void tilevstack(unsigned int n);
195 void togglefloating(const char *arg);
196 void toggletag(const char *arg);
197 void toggleview(const char *arg);
198 void unban(Client *c);
199 void unmanage(Client *c);
200 void unmapnotify(XEvent *e);
201 void updatebarpos(void);
202 void updatesizehints(Client *c);
203 void updatetitle(Client *c);
204 void updatewmhints(Client *c);
205 void view(const char *arg);
206 void viewprevtag(const char *arg); /* views previous selected tags */
207 int xerror(Display *dpy, XErrorEvent *ee);
208 int xerrordummy(Display *dpy, XErrorEvent *ee);
209 int xerrorstart(Display *dpy, XErrorEvent *ee);
210 void zoom(const char *arg);
214 int screen, sx, sy, sw, sh;
215 int (*xerrorxlib)(Display *, XErrorEvent *);
216 int bx, by, bw, bh, blw, bgw, mx, my, mw, mh, mox, moy, mow, moh, tx, ty, tw, th, wx, wy, ww, wh;
219 unsigned int numlockmask = 0;
220 void (*handler[LASTEvent]) (XEvent *) = {
221 [ButtonPress] = buttonpress,
222 [ConfigureRequest] = configurerequest,
223 [ConfigureNotify] = configurenotify,
224 [DestroyNotify] = destroynotify,
225 [EnterNotify] = enternotify,
228 [KeyPress] = keypress,
229 [MappingNotify] = mappingnotify,
230 [MapRequest] = maprequest,
231 [PropertyNotify] = propertynotify,
232 [UnmapNotify] = unmapnotify
234 Atom wmatom[WMLast], netatom[NetLast];
235 Bool otherwm, readin;
238 Client *clients = NULL;
240 Client *stack = NULL;
241 Cursor cursor[CurLast];
246 /* configuration, allows nested code to access above variables */
248 #define TAGSZ (LENGTH(tags) * sizeof(Bool))
249 Layout *lt = layouts;
252 /* function implementations */
255 applyrules(Client *c) {
257 Bool matched = False;
259 XClassHint ch = { 0 };
262 XGetClassHint(dpy, c->win, &ch);
263 for(i = 0; i < LENGTH(rules); i++) {
265 if((!r->title || strstr(c->name, r->title))
266 && (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
267 && (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
268 c->isfloating = r->isfloating;
270 c->tags[idxoftag(r->tag)] = True;
280 memcpy(c->tags, tagset[seltags], TAGSZ);
287 for(c = clients; c; c = c->next)
290 if(lt->isfloating || c->isfloating)
291 resize(c, c->fx, c->fy, c->fw, c->fh, True);
311 attachstack(Client *c) {
320 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
325 buttonpress(XEvent *e) {
328 XButtonPressedEvent *ev = &e->xbutton;
330 if(ev->window == barwin) {
331 if((ev->x < bgw) && ev->button == Button1) {
336 for(i = 0; i < LENGTH(tags); i++) {
338 if(ev->x >= bgw && ev->x < x) {
339 if(ev->button == Button1) {
340 if(ev->state & MODKEY)
345 else if(ev->button == Button3) {
346 if(ev->state & MODKEY)
354 if((ev->x < x + blw) && ev->button == Button1)
357 else if((c = getclient(ev->window))) {
359 if(CLEANMASK(ev->state) != MODKEY)
361 if(ev->button == Button1) {
365 else if(ev->button == Button2) {
366 if(!lt->isfloating && c->isfloating)
367 togglefloating(NULL);
371 else if(ev->button == Button3 && !c->isfixed) {
381 XSetErrorHandler(xerrorstart);
383 /* this causes an error if some other window manager is running */
384 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
387 eprint("dwm: another window manager is already running\n");
389 XSetErrorHandler(NULL);
390 xerrorxlib = XSetErrorHandler(xerror);
402 XFreeFontSet(dpy, dc.font.set);
404 XFreeFont(dpy, dc.font.xfont);
405 XUngrabKey(dpy, AnyKey, AnyModifier, root);
406 XFreePixmap(dpy, dc.drawable);
408 XFreeCursor(dpy, cursor[CurNormal]);
409 XFreeCursor(dpy, cursor[CurResize]);
410 XFreeCursor(dpy, cursor[CurMove]);
411 XDestroyWindow(dpy, barwin);
413 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
417 configure(Client *c) {
420 ce.type = ConfigureNotify;
428 ce.border_width = c->bw;
430 ce.override_redirect = False;
431 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
435 configurenotify(XEvent *e) {
436 XConfigureEvent *ev = &e->xconfigure;
438 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
441 setgeom(geom->symbol);
446 configurerequest(XEvent *e) {
448 XConfigureRequestEvent *ev = &e->xconfigurerequest;
451 if((c = getclient(ev->window))) {
452 if(ev->value_mask & CWBorderWidth)
453 c->bw = ev->border_width;
454 if(c->isfixed || c->isfloating || lt->isfloating) {
455 if(ev->value_mask & CWX)
457 if(ev->value_mask & CWY)
459 if(ev->value_mask & CWWidth)
461 if(ev->value_mask & CWHeight)
463 if((c->x - sx + c->w) > sw && c->isfloating)
464 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
465 if((c->y - sy + c->h) > sh && c->isfloating)
466 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
467 if((ev->value_mask & (CWX|CWY))
468 && !(ev->value_mask & (CWWidth|CWHeight)))
471 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
479 wc.width = ev->width;
480 wc.height = ev->height;
481 wc.border_width = ev->border_width;
482 wc.sibling = ev->above;
483 wc.stack_mode = ev->detail;
484 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
494 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next), n++);
499 destroynotify(XEvent *e) {
501 XDestroyWindowEvent *ev = &e->xdestroywindow;
503 if((c = getclient(ev->window)))
510 c->prev->next = c->next;
512 c->next->prev = c->prev;
515 c->next = c->prev = NULL;
519 detachstack(Client *c) {
522 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
534 drawtext(geom->symbol, dc.norm, False);
537 for(c = stack; c && !isvisible(c); c = c->snext);
538 for(i = 0; i < LENGTH(tags); i++) {
539 dc.w = textw(tags[i]);
540 if(tagset[seltags][i]) {
541 drawtext(tags[i], dc.sel, isurgent(i));
542 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.sel);
545 drawtext(tags[i], dc.norm, isurgent(i));
546 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.norm);
552 drawtext(lt->symbol, dc.norm, False);
563 drawtext(stext, dc.norm, False);
564 if((dc.w = dc.x - x) > bh) {
567 drawtext(c->name, dc.sel, False);
568 drawsquare(False, c->isfloating, False, dc.sel);
571 drawtext(NULL, dc.norm, False);
573 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, bw, bh, 0, 0);
578 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
581 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
583 gcv.foreground = col[invert ? ColBG : ColFG];
584 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
585 x = (dc.font.ascent + dc.font.descent + 2) / 4;
589 r.width = r.height = x + 1;
590 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
593 r.width = r.height = x;
594 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
599 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
601 unsigned int len, olen;
602 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
605 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
606 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
610 len = MIN(olen, sizeof buf);
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 for(; len && (w = textnw(buf, len)) > dc.w - h; len--);
628 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
630 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
632 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
636 emallocz(unsigned int size) {
637 void *res = calloc(1, size);
640 eprint("fatal: could not malloc() %u bytes\n", size);
645 enternotify(XEvent *e) {
647 XCrossingEvent *ev = &e->xcrossing;
649 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
651 if((c = getclient(ev->window)))
658 eprint(const char *errstr, ...) {
661 va_start(ap, errstr);
662 vfprintf(stderr, errstr, ap);
669 XExposeEvent *ev = &e->xexpose;
671 if(ev->count == 0 && (ev->window == barwin))
677 if(!c || (c && !isvisible(c)))
678 for(c = stack; c && !isvisible(c); c = c->snext);
679 if(sel && sel != c) {
680 grabbuttons(sel, False);
681 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
686 grabbuttons(c, True);
690 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
691 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
694 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
699 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
700 XFocusChangeEvent *ev = &e->xfocus;
702 if(sel && ev->window != sel->win)
703 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
707 focusnext(const char *arg) {
712 for(c = sel->next; c && !isvisible(c); c = c->next);
714 for(c = clients; c && !isvisible(c); c = c->next);
722 focusprev(const char *arg) {
727 for(c = sel->prev; c && !isvisible(c); c = c->prev);
729 for(c = clients; c && c->next; c = c->next);
730 for(; c && !isvisible(c); c = c->prev);
739 getclient(Window w) {
742 for(c = clients; c && c->win != w; c = c->next);
747 getcolor(const char *colstr) {
748 Colormap cmap = DefaultColormap(dpy, screen);
751 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
752 eprint("error, cannot allocate color '%s'\n", colstr);
760 unsigned char *p = NULL;
761 unsigned long n, extra;
764 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
765 &real, &format, &n, &extra, (unsigned char **)&p);
766 if(status != Success)
775 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
780 if(!text || size == 0)
783 XGetTextProperty(dpy, w, &name, atom);
786 if(name.encoding == XA_STRING)
787 strncpy(text, (char *)name.value, size - 1);
789 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
791 strncpy(text, *list, size - 1);
792 XFreeStringList(list);
795 text[size - 1] = '\0';
801 grabbuttons(Client *c, Bool focused) {
803 unsigned int buttons[] = { Button1, Button2, Button3 };
804 unsigned int modifiers[] = { MODKEY, MODKEY|LockMask, MODKEY|numlockmask,
805 MODKEY|numlockmask|LockMask} ;
807 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
809 for(i = 0; i < LENGTH(buttons); i++)
810 for(j = 0; j < LENGTH(modifiers); j++)
811 XGrabButton(dpy, buttons[i], modifiers[j], c->win, False,
812 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
814 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
815 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
822 XModifierKeymap *modmap;
824 /* init modifier map */
825 modmap = XGetModifierMapping(dpy);
826 for(i = 0; i < 8; i++)
827 for(j = 0; j < modmap->max_keypermod; j++) {
828 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
829 numlockmask = (1 << i);
831 XFreeModifiermap(modmap);
833 XUngrabKey(dpy, AnyKey, AnyModifier, root);
834 for(i = 0; i < LENGTH(keys); i++) {
835 code = XKeysymToKeycode(dpy, keys[i].keysym);
836 XGrabKey(dpy, code, keys[i].mod, root, True,
837 GrabModeAsync, GrabModeAsync);
838 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
839 GrabModeAsync, GrabModeAsync);
840 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
841 GrabModeAsync, GrabModeAsync);
842 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
843 GrabModeAsync, GrabModeAsync);
848 idxoftag(const char *t) {
851 for(i = 0; (i < LENGTH(tags)) && t && strcmp(tags[i], t); i++);
852 return (i < LENGTH(tags)) ? i : 0;
856 initfont(const char *fontstr) {
857 char *def, **missing;
862 XFreeFontSet(dpy, dc.font.set);
863 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
866 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
867 XFreeStringList(missing);
870 XFontSetExtents *font_extents;
871 XFontStruct **xfonts;
873 dc.font.ascent = dc.font.descent = 0;
874 font_extents = XExtentsOfFontSet(dc.font.set);
875 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
876 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
877 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
878 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
884 XFreeFont(dpy, dc.font.xfont);
885 dc.font.xfont = NULL;
886 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
887 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
888 eprint("error, cannot load font: '%s'\n", fontstr);
889 dc.font.ascent = dc.font.xfont->ascent;
890 dc.font.descent = dc.font.xfont->descent;
892 dc.font.height = dc.font.ascent + dc.font.descent;
896 isoccupied(unsigned int t) {
899 for(c = clients; c; c = c->next)
906 isprotodel(Client *c) {
911 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
912 for(i = 0; !ret && i < n; i++)
913 if(protocols[i] == wmatom[WMDelete])
921 isurgent(unsigned int t) {
924 for(c = clients; c; c = c->next)
925 if(c->isurgent && c->tags[t])
931 isvisible(Client *c) {
934 for(i = 0; i < LENGTH(tags); i++)
935 if(c->tags[i] && tagset[seltags][i])
941 keypress(XEvent *e) {
947 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
948 for(i = 0; i < LENGTH(keys); i++)
949 if(keysym == keys[i].keysym
950 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
953 keys[i].func(keys[i].arg);
958 killclient(const char *arg) {
963 if(isprotodel(sel)) {
964 ev.type = ClientMessage;
965 ev.xclient.window = sel->win;
966 ev.xclient.message_type = wmatom[WMProtocols];
967 ev.xclient.format = 32;
968 ev.xclient.data.l[0] = wmatom[WMDelete];
969 ev.xclient.data.l[1] = CurrentTime;
970 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
973 XKillClient(dpy, sel->win);
977 manage(Window w, XWindowAttributes *wa) {
978 Client *c, *t = NULL;
983 c = emallocz(sizeof(Client));
984 c->tags = emallocz(TAGSZ);
990 c->w = c->fw = wa->width;
991 c->h = c->fh = wa->height;
992 c->oldbw = wa->border_width;
993 if(c->w == sw && c->h == sh) {
996 c->bw = wa->border_width;
999 if(c->x + c->w + 2 * c->bw > wx + ww)
1000 c->x = wx + ww - c->w - 2 * c->bw;
1001 if(c->y + c->h + 2 * c->bw > wy + wh)
1002 c->y = wy + wh - c->h - 2 * c->bw;
1003 c->x = MAX(c->x, wx);
1004 c->y = MAX(c->y, wy);
1010 wc.border_width = c->bw;
1011 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1012 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1013 configure(c); /* propagates border_width, if size doesn't change */
1015 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
1016 grabbuttons(c, False);
1018 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
1019 for(t = clients; t && t->win != trans; t = t->next);
1021 memcpy(c->tags, t->tags, TAGSZ);
1025 c->isfloating = (rettrans == Success) || c->isfixed;
1028 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
1030 XMapWindow(dpy, c->win);
1031 setclientstate(c, NormalState);
1036 mappingnotify(XEvent *e) {
1037 XMappingEvent *ev = &e->xmapping;
1039 XRefreshKeyboardMapping(ev);
1040 if(ev->request == MappingKeyboard)
1045 maprequest(XEvent *e) {
1046 static XWindowAttributes wa;
1047 XMapRequestEvent *ev = &e->xmaprequest;
1049 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1051 if(wa.override_redirect)
1053 if(!getclient(ev->window))
1054 manage(ev->window, &wa);
1061 for(c = clients; c; c = c->next)
1062 if((lt->isfloating || !c->isfloating) && isvisible(c))
1063 resize(c, mox, moy, mow - 2 * c->bw, moh - 2 * c->bw, RESIZEHINTS);
1067 movemouse(Client *c) {
1068 int x1, y1, ocx, ocy, di, nx, ny;
1075 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1076 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1078 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1080 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1083 XUngrabPointer(dpy, CurrentTime);
1085 case ConfigureRequest:
1088 handler[ev.type](&ev);
1092 nx = ocx + (ev.xmotion.x - x1);
1093 ny = ocy + (ev.xmotion.y - y1);
1094 if(abs(wx - nx) < SNAP)
1096 else if(abs((wx + ww) - (nx + c->w + 2 * c->bw)) < SNAP)
1097 nx = wx + ww - c->w - 2 * c->bw;
1098 if(abs(wy - ny) < SNAP)
1100 else if(abs((wy + wh) - (ny + c->h + 2 * c->bw)) < SNAP)
1101 ny = wy + wh - c->h - 2 * c->bw;
1102 if(!c->isfloating && !lt->isfloating && (abs(nx - c->x) > SNAP || abs(ny - c->y) > SNAP))
1103 togglefloating(NULL);
1104 if(lt->isfloating || c->isfloating) {
1107 resize(c, nx, ny, c->w, c->h, False);
1115 nexttiled(Client *c) {
1116 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1121 propertynotify(XEvent *e) {
1124 XPropertyEvent *ev = &e->xproperty;
1126 if(ev->state == PropertyDelete)
1127 return; /* ignore */
1128 if((c = getclient(ev->window))) {
1131 case XA_WM_TRANSIENT_FOR:
1132 XGetTransientForHint(dpy, c->win, &trans);
1133 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1136 case XA_WM_NORMAL_HINTS:
1144 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1153 quit(const char *arg) {
1154 readin = running = False;
1158 reapply(const char *arg) {
1161 for(c = clients; c; c = c->next) {
1162 memset(c->tags, 0, TAGSZ);
1169 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1173 /* set minimum possible */
1177 /* temporarily remove base dimensions */
1181 /* adjust for aspect limits */
1182 if(c->minax != c->maxax && c->minay != c->maxay
1183 && c->minax > 0 && c->maxax > 0 && c->minay > 0 && c->maxay > 0)
1185 if(w * c->maxay > h * c->maxax)
1186 w = h * c->maxax / c->maxay;
1187 else if(w * c->minay < h * c->minax)
1188 h = w * c->minay / c->minax;
1191 /* adjust for increment value */
1197 /* restore base dimensions */
1201 w = MAX(w, c->minw);
1202 h = MAX(h, c->minh);
1205 w = MIN(w, c->maxw);
1208 h = MIN(h, c->maxh);
1210 if(w <= 0 || h <= 0)
1213 x = sw - w - 2 * c->bw;
1215 y = sh - h - 2 * c->bw;
1216 if(x + w + 2 * c->bw < sx)
1218 if(y + h + 2 * c->bw < sy)
1220 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1223 c->w = wc.width = w;
1224 c->h = wc.height = h;
1225 wc.border_width = c->bw;
1226 XConfigureWindow(dpy, c->win,
1227 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1234 resizemouse(Client *c) {
1241 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1242 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1244 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1246 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1249 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1250 c->w + c->bw - 1, c->h + c->bw - 1);
1251 XUngrabPointer(dpy, CurrentTime);
1252 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1254 case ConfigureRequest:
1257 handler[ev.type](&ev);
1261 nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1262 nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1263 if(!c->isfloating && !lt->isfloating && (abs(nw - c->w) > SNAP || abs(nh - c->h) > SNAP)) {
1266 togglefloating(NULL);
1268 if((lt->isfloating) || c->isfloating) {
1269 resize(c, c->x, c->y, nw, nh, True);
1287 if(sel->isfloating || lt->isfloating)
1288 XRaiseWindow(dpy, sel->win);
1289 if(!lt->isfloating) {
1290 wc.stack_mode = Below;
1291 wc.sibling = barwin;
1292 for(c = stack; c; c = c->snext)
1293 if(!c->isfloating && isvisible(c)) {
1294 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1295 wc.sibling = c->win;
1299 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1305 char sbuf[sizeof stext];
1308 unsigned int len, offset;
1311 /* main event loop, also reads status text from stdin */
1313 xfd = ConnectionNumber(dpy);
1316 len = sizeof stext - 1;
1317 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1321 FD_SET(STDIN_FILENO, &rd);
1323 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1326 eprint("select failed\n");
1328 if(FD_ISSET(STDIN_FILENO, &rd)) {
1329 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1331 strncpy(stext, strerror(errno), len);
1335 strncpy(stext, "EOF", 4);
1339 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1340 if(*p == '\n' || *p == '\0') {
1342 strncpy(stext, sbuf, len);
1343 p += r - 1; /* p is sbuf + offset + r - 1 */
1344 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1347 memmove(sbuf, p - r + 1, r);
1354 while(XPending(dpy)) {
1355 XNextEvent(dpy, &ev);
1356 if(handler[ev.type])
1357 (handler[ev.type])(&ev); /* call handler */
1364 unsigned int i, num;
1365 Window *wins, d1, d2;
1366 XWindowAttributes wa;
1369 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1370 for(i = 0; i < num; i++) {
1371 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1372 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1374 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1375 manage(wins[i], &wa);
1377 for(i = 0; i < num; i++) { /* now the transients */
1378 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1380 if(XGetTransientForHint(dpy, wins[i], &d1)
1381 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1382 manage(wins[i], &wa);
1390 setclientstate(Client *c, long state) {
1391 long data[] = {state, None};
1393 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1394 PropModeReplace, (unsigned char *)data, 2);
1398 setgeom(const char *arg) {
1402 if(++geom == &geoms[LENGTH(geoms)])
1406 for(i = 0; i < LENGTH(geoms); i++)
1407 if(!strcmp(geoms[i].symbol, arg))
1409 if(i == LENGTH(geoms))
1419 setlayout(const char *arg) {
1423 if(++lt == &layouts[LENGTH(layouts)])
1427 for(i = 0; i < LENGTH(layouts); i++)
1428 if(!strcmp(arg, layouts[i].symbol))
1430 if(i == LENGTH(layouts))
1441 setmfact(const char *arg) {
1449 d = strtod(arg, NULL);
1450 if(arg[0] == '-' || arg[0] == '+')
1452 if(d < 0.1 || d > 0.9)
1456 setgeom(geom->symbol);
1462 XSetWindowAttributes wa;
1465 screen = DefaultScreen(dpy);
1466 root = RootWindow(dpy, screen);
1469 /* apply default geometry */
1472 sw = DisplayWidth(dpy, screen);
1473 sh = DisplayHeight(dpy, screen);
1474 bh = dc.font.height + 2;
1479 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1480 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1481 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1482 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1483 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1484 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1487 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1488 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1489 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1491 /* init appearance */
1492 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1493 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1494 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1495 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1496 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1497 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1500 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1501 dc.gc = XCreateGC(dpy, root, 0, 0);
1502 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1504 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1507 tagset[0] = emallocz(TAGSZ);
1508 tagset[1] = emallocz(TAGSZ);
1509 tagset[0][0] = tagset[1][0] = True;
1512 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1513 w = textw(layouts[i].symbol);
1516 for(bgw = i = 0; LENGTH(geoms) > 1 && i < LENGTH(geoms); i++) {
1517 w = textw(geoms[i].symbol);
1521 wa.override_redirect = 1;
1522 wa.background_pixmap = ParentRelative;
1523 wa.event_mask = ButtonPressMask|ExposureMask;
1525 barwin = XCreateWindow(dpy, root, bx, by, bw, bh, 0, DefaultDepth(dpy, screen),
1526 CopyFromParent, DefaultVisual(dpy, screen),
1527 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1528 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1529 XMapRaised(dpy, barwin);
1530 strcpy(stext, "dwm-"VERSION);
1533 /* EWMH support per view */
1534 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1535 PropModeReplace, (unsigned char *) netatom, NetLast);
1537 /* select for events */
1538 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1539 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1540 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1541 XSelectInput(dpy, root, wa.event_mask);
1549 spawn(const char *arg) {
1550 static char *shell = NULL;
1552 if(!shell && !(shell = getenv("SHELL")))
1556 /* The double-fork construct avoids zombie processes and keeps the code
1557 * clean from stupid signal handlers. */
1561 close(ConnectionNumber(dpy));
1563 execl(shell, shell, "-c", arg, (char *)NULL);
1564 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1573 tag(const char *arg) {
1578 for(i = 0; i < LENGTH(tags); i++)
1579 sel->tags[i] = (NULL == arg);
1580 sel->tags[idxoftag(arg)] = True;
1585 textnw(const char *text, unsigned int len) {
1589 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1592 return XTextWidth(dc.font.xfont, text, len);
1596 textw(const char *text) {
1597 return textnw(text, strlen(text)) + dc.font.height;
1603 unsigned int i, n = counttiled();
1617 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1618 if(i + 1 == n) /* remainder */
1619 tileresize(c, x, ty, (tx + tw) - x - 2 * c->bw, th - 2 * c->bw);
1621 tileresize(c, x, ty, w - 2 * c->bw, th - 2 * c->bw);
1623 x = c->x + c->w + 2 * c->bw;
1628 tilemaster(unsigned int n) {
1629 Client *c = nexttiled(clients);
1632 tileresize(c, mox, moy, mow - 2 * c->bw, moh - 2 * c->bw);
1634 tileresize(c, mx, my, mw - 2 * c->bw, mh - 2 * c->bw);
1639 tileresize(Client *c, int x, int y, int w, int h) {
1640 resize(c, x, y, w, h, RESIZEHINTS);
1641 if((RESIZEHINTS) && ((c->h < bh) || (c->h > h) || (c->w < bh) || (c->w > w)))
1642 /* client doesn't accept size constraints */
1643 resize(c, x, y, w, h, False);
1649 unsigned int i, n = counttiled();
1663 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1664 if(i + 1 == n) /* remainder */
1665 tileresize(c, tx, y, tw - 2 * c->bw, (ty + th) - y - 2 * c->bw);
1667 tileresize(c, tx, y, tw - 2 * c->bw, h - 2 * c->bw);
1669 y = c->y + c->h + 2 * c->bw;
1674 togglefloating(const char *arg) {
1677 sel->isfloating = !sel->isfloating;
1679 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1684 toggletag(const char *arg) {
1690 sel->tags[i] = !sel->tags[i];
1691 for(j = 0; j < LENGTH(tags) && !sel->tags[j]; j++);
1692 if(j == LENGTH(tags))
1693 sel->tags[i] = True; /* at least one tag must be enabled */
1698 toggleview(const char *arg) {
1702 tagset[seltags][i] = !tagset[seltags][i];
1703 for(j = 0; j < LENGTH(tags) && !tagset[seltags][j]; j++);
1704 if(j == LENGTH(tags))
1705 tagset[seltags][i] = True; /* at least one tag must be viewed */
1713 XMoveWindow(dpy, c->win, c->x, c->y);
1714 c->isbanned = False;
1718 unmanage(Client *c) {
1721 wc.border_width = c->oldbw;
1722 /* The server grab construct avoids race conditions. */
1724 XSetErrorHandler(xerrordummy);
1725 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1730 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1731 setclientstate(c, WithdrawnState);
1735 XSetErrorHandler(xerror);
1741 unmapnotify(XEvent *e) {
1743 XUnmapEvent *ev = &e->xunmap;
1745 if((c = getclient(ev->window)))
1750 updatebarpos(void) {
1752 if(dc.drawable != 0)
1753 XFreePixmap(dpy, dc.drawable);
1754 dc.drawable = XCreatePixmap(dpy, root, bw, bh, DefaultDepth(dpy, screen));
1755 XMoveResizeWindow(dpy, barwin, bx, by, bw, bh);
1759 updatesizehints(Client *c) {
1763 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1765 c->flags = size.flags;
1766 if(c->flags & PBaseSize) {
1767 c->basew = size.base_width;
1768 c->baseh = size.base_height;
1770 else if(c->flags & PMinSize) {
1771 c->basew = size.min_width;
1772 c->baseh = size.min_height;
1775 c->basew = c->baseh = 0;
1776 if(c->flags & PResizeInc) {
1777 c->incw = size.width_inc;
1778 c->inch = size.height_inc;
1781 c->incw = c->inch = 0;
1782 if(c->flags & PMaxSize) {
1783 c->maxw = size.max_width;
1784 c->maxh = size.max_height;
1787 c->maxw = c->maxh = 0;
1788 if(c->flags & PMinSize) {
1789 c->minw = size.min_width;
1790 c->minh = size.min_height;
1792 else if(c->flags & PBaseSize) {
1793 c->minw = size.base_width;
1794 c->minh = size.base_height;
1797 c->minw = c->minh = 0;
1798 if(c->flags & PAspect) {
1799 c->minax = size.min_aspect.x;
1800 c->maxax = size.max_aspect.x;
1801 c->minay = size.min_aspect.y;
1802 c->maxay = size.max_aspect.y;
1805 c->minax = c->maxax = c->minay = c->maxay = 0;
1806 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1807 && c->maxw == c->minw && c->maxh == c->minh);
1811 updatetitle(Client *c) {
1812 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1813 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1817 updatewmhints(Client *c) {
1820 if((wmh = XGetWMHints(dpy, c->win))) {
1822 sel->isurgent = False;
1824 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1830 view(const char *arg) {
1832 memset(tagset[seltags], (NULL == arg), TAGSZ);
1833 tagset[seltags][idxoftag(arg)] = True;
1838 viewprevtag(const char *arg) {
1839 seltags ^= 1; /* toggle sel tagset */
1843 /* There's no way to check accesses to destroyed windows, thus those cases are
1844 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1845 * default error handler, which may call exit. */
1847 xerror(Display *dpy, XErrorEvent *ee) {
1848 if(ee->error_code == BadWindow
1849 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1850 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1851 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1852 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1853 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1854 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1855 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1856 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1858 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1859 ee->request_code, ee->error_code);
1860 return xerrorxlib(dpy, ee); /* may call exit */
1864 xerrordummy(Display *dpy, XErrorEvent *ee) {
1868 /* Startup Error handler to check if another window manager
1869 * is already running. */
1871 xerrorstart(Display *dpy, XErrorEvent *ee) {
1877 zoom(const char *arg) {
1880 if(c == nexttiled(clients))
1881 if(!c || !(c = nexttiled(c->next)))
1883 if(!lt->isfloating && !sel->isfloating) {
1892 main(int argc, char *argv[]) {
1893 if(argc == 2 && !strcmp("-v", argv[1]))
1894 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1896 eprint("usage: dwm [-v]\n");
1898 setlocale(LC_CTYPE, "");
1899 if(!(dpy = XOpenDisplay(0)))
1900 eprint("dwm: cannot open display\n");