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 BUTTONMASK (ButtonPressMask|ButtonReleaseMask)
45 #define CLEANMASK(mask) (mask & ~(numlockmask|LockMask))
46 #define LENGTH(x) (sizeof x / sizeof x[0])
48 #define MOUSEMASK (BUTTONMASK|PointerMotionMask)
49 #define DEFGEOM(GEONAME,BX,BY,BW,WX,WY,WW,WH,MX,MY,MW,MH,TX,TY,TW,TH,MOX,MOY,MOW,MOH) \
50 void GEONAME(void) { \
51 bx = (BX); by = (BY); bw = (BW); \
52 wx = (WX); wy = (WY); ww = (WW); wh = (WH); \
53 mx = (MX); my = (MY); mw = (MW); mh = (MH); \
54 tx = (TX); ty = (TY); tw = (TW); th = (TH); \
55 mox = (MOX); moy = (MOY); mow = (MOW); moh = (MOH); \
59 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
60 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
61 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
62 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
65 typedef struct Client Client;
69 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
70 int minax, maxax, minay, maxay;
72 unsigned int bw, oldbw;
73 Bool isbanned, isfixed, isfloating, isurgent;
83 unsigned long norm[ColLast];
84 unsigned long sel[ColLast];
94 } DC; /* draw context */
104 void (*func)(const char *arg);
110 void (*arrange)(void);
116 const char *instance;
122 /* function declarations */
123 void applyrules(Client *c);
125 void attach(Client *c);
126 void attachstack(Client *c);
128 void buttonpress(XEvent *e);
129 void checkotherwm(void);
131 void configure(Client *c);
132 void configurenotify(XEvent *e);
133 void configurerequest(XEvent *e);
134 unsigned int counttiled(void);
135 void destroynotify(XEvent *e);
136 void detach(Client *c);
137 void detachstack(Client *c);
139 void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
140 void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
141 void *emallocz(unsigned int size);
142 void enternotify(XEvent *e);
143 void eprint(const char *errstr, ...);
144 void expose(XEvent *e);
145 void floating(void); /* default floating layout */
146 void focus(Client *c);
147 void focusin(XEvent *e);
148 void focusnext(const char *arg);
149 void focusprev(const char *arg);
150 Client *getclient(Window w);
151 unsigned long getcolor(const char *colstr);
152 long getstate(Window w);
153 Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
154 void grabbuttons(Client *c, Bool focused);
156 unsigned int idxoftag(const char *t);
157 void initfont(const char *fontstr);
158 Bool isoccupied(unsigned int t);
159 Bool isprotodel(Client *c);
160 Bool isurgent(unsigned int t);
161 Bool isvisible(Client *c);
162 void keypress(XEvent *e);
163 void killclient(const char *arg);
164 void manage(Window w, XWindowAttributes *wa);
165 void mappingnotify(XEvent *e);
166 void maprequest(XEvent *e);
168 void movemouse(Client *c);
169 Client *nexttiled(Client *c);
170 void propertynotify(XEvent *e);
171 void quit(const char *arg);
172 void reapply(const char *arg);
173 void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
174 void resizemouse(Client *c);
178 void setclientstate(Client *c, long state);
179 void setgeom(const char *arg);
180 void setlayout(const char *arg);
181 void setmfact(const char *arg);
183 void spawn(const char *arg);
184 void tag(const char *arg);
185 unsigned int textnw(const char *text, unsigned int len);
186 unsigned int textw(const char *text);
188 void tilehstack(unsigned int n);
189 Client *tilemaster(unsigned int n);
190 void tileresize(Client *c, int x, int y, int w, int h);
192 void tilevstack(unsigned int n);
193 void togglefloating(const char *arg);
194 void toggletag(const char *arg);
195 void toggleview(const char *arg);
196 void unban(Client *c);
197 void unmanage(Client *c);
198 void unmapnotify(XEvent *e);
199 void updatebarpos(void);
200 void updatesizehints(Client *c);
201 void updatetitle(Client *c);
202 void updatewmhints(Client *c);
203 void view(const char *arg);
204 void viewprevtag(const char *arg); /* views previous selected tags */
205 int xerror(Display *dpy, XErrorEvent *ee);
206 int xerrordummy(Display *dpy, XErrorEvent *ee);
207 int xerrorstart(Display *dpy, XErrorEvent *ee);
208 void zoom(const char *arg);
211 char stext[256], buf[256];
212 int screen, sx, sy, sw, sh;
213 int (*xerrorxlib)(Display *, XErrorEvent *);
214 int bx, by, bw, bh, blw, bgw, mx, my, mw, mh, mox, moy, mow, moh, tx, ty, tw, th, wx, wy, ww, wh;
216 unsigned int numlockmask = 0;
217 void (*handler[LASTEvent]) (XEvent *) = {
218 [ButtonPress] = buttonpress,
219 [ConfigureRequest] = configurerequest,
220 [ConfigureNotify] = configurenotify,
221 [DestroyNotify] = destroynotify,
222 [EnterNotify] = enternotify,
225 [KeyPress] = keypress,
226 [MappingNotify] = mappingnotify,
227 [MapRequest] = maprequest,
228 [PropertyNotify] = propertynotify,
229 [UnmapNotify] = unmapnotify
231 Atom wmatom[WMLast], netatom[NetLast];
232 Bool otherwm, readin;
236 Client *clients = NULL;
238 Client *stack = NULL;
239 Cursor cursor[CurLast];
244 /* configuration, allows nested code to access above variables */
246 #define TAGSZ (LENGTH(tags) * sizeof(Bool))
247 Bool tmp[LENGTH(tags)];
248 Layout *lt = layouts;
251 /* function implementations */
254 applyrules(Client *c) {
256 Bool matched = False;
258 XClassHint ch = { 0 };
261 XGetClassHint(dpy, c->win, &ch);
262 for(i = 0; i < LENGTH(rules); i++) {
264 if((!r->title || strstr(c->name, r->title))
265 && (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
266 && (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
267 c->isfloating = r->isfloating;
269 c->tags[idxoftag(r->tag)] = True;
279 memcpy(c->tags, seltags, TAGSZ);
286 for(c = clients; c; c = c->next)
306 attachstack(Client *c) {
315 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
320 buttonpress(XEvent *e) {
323 XButtonPressedEvent *ev = &e->xbutton;
325 if(ev->window == barwin) {
326 if((ev->x < bgw) && ev->button == Button1) {
331 for(i = 0; i < LENGTH(tags); i++) {
333 if(ev->x >= bgw && ev->x < x) {
334 if(ev->button == Button1) {
335 if(ev->state & MODKEY)
340 else if(ev->button == Button3) {
341 if(ev->state & MODKEY)
349 if((ev->x < x + blw) && ev->button == Button1)
352 else if((c = getclient(ev->window))) {
354 if(CLEANMASK(ev->state) != MODKEY)
356 if(ev->button == Button1) {
360 else if(ev->button == Button2) {
361 if((floating != lt->arrange) && c->isfloating)
362 togglefloating(NULL);
366 else if(ev->button == Button3 && !c->isfixed) {
376 XSetErrorHandler(xerrorstart);
378 /* this causes an error if some other window manager is running */
379 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
382 eprint("dwm: another window manager is already running\n");
384 XSetErrorHandler(NULL);
385 xerrorxlib = XSetErrorHandler(xerror);
397 XFreeFontSet(dpy, dc.font.set);
399 XFreeFont(dpy, dc.font.xfont);
400 XUngrabKey(dpy, AnyKey, AnyModifier, root);
401 XFreePixmap(dpy, dc.drawable);
403 XFreeCursor(dpy, cursor[CurNormal]);
404 XFreeCursor(dpy, cursor[CurResize]);
405 XFreeCursor(dpy, cursor[CurMove]);
406 XDestroyWindow(dpy, barwin);
408 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
412 configure(Client *c) {
415 ce.type = ConfigureNotify;
423 ce.border_width = c->bw;
425 ce.override_redirect = False;
426 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
430 configurenotify(XEvent *e) {
431 XConfigureEvent *ev = &e->xconfigure;
433 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
436 setgeom(geom->symbol);
441 configurerequest(XEvent *e) {
443 XConfigureRequestEvent *ev = &e->xconfigurerequest;
446 if((c = getclient(ev->window))) {
447 if(ev->value_mask & CWBorderWidth)
448 c->bw = ev->border_width;
449 if(c->isfixed || c->isfloating || lt->isfloating) {
450 if(ev->value_mask & CWX)
452 if(ev->value_mask & CWY)
454 if(ev->value_mask & CWWidth)
456 if(ev->value_mask & CWHeight)
458 if((c->x - sx + c->w) > sw && c->isfloating)
459 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
460 if((c->y - sy + c->h) > sh && c->isfloating)
461 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
462 if((ev->value_mask & (CWX|CWY))
463 && !(ev->value_mask & (CWWidth|CWHeight)))
466 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
474 wc.width = ev->width;
475 wc.height = ev->height;
476 wc.border_width = ev->border_width;
477 wc.sibling = ev->above;
478 wc.stack_mode = ev->detail;
479 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
489 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next), n++);
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);
529 drawtext(geom->symbol, dc.norm, False);
532 for(c = stack; c && !isvisible(c); c = c->snext);
533 for(i = 0; i < LENGTH(tags); i++) {
534 dc.w = textw(tags[i]);
536 drawtext(tags[i], dc.sel, isurgent(i));
537 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.sel);
540 drawtext(tags[i], dc.norm, isurgent(i));
541 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.norm);
547 drawtext(lt->symbol, dc.norm, False);
558 drawtext(stext, dc.norm, False);
559 if((dc.w = dc.x - x) > bh) {
562 drawtext(c->name, dc.sel, False);
563 drawsquare(False, c->isfloating, False, dc.sel);
566 drawtext(NULL, dc.norm, False);
568 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, bw, bh, 0, 0);
573 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
576 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
578 gcv.foreground = col[invert ? ColBG : ColFG];
579 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
580 x = (dc.font.ascent + dc.font.descent + 2) / 4;
584 r.width = r.height = x + 1;
585 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
588 r.width = r.height = x;
589 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
594 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
596 unsigned int len, olen;
597 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
599 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
600 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
604 olen = len = strlen(text);
605 if(len >= sizeof buf)
606 len = sizeof buf - 1;
607 memcpy(buf, text, len);
609 h = dc.font.ascent + dc.font.descent;
610 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
612 /* shorten text if necessary */
613 while(len && (w = textnw(buf, len)) > dc.w - h)
624 return; /* too long */
625 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
627 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
629 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
633 emallocz(unsigned int size) {
634 void *res = calloc(1, size);
637 eprint("fatal: could not malloc() %u bytes\n", size);
642 enternotify(XEvent *e) {
644 XCrossingEvent *ev = &e->xcrossing;
646 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
648 if((c = getclient(ev->window)))
655 eprint(const char *errstr, ...) {
658 va_start(ap, errstr);
659 vfprintf(stderr, errstr, ap);
666 XExposeEvent *ev = &e->xexpose;
668 if(ev->count == 0 && (ev->window == barwin))
673 floating(void) { /* default floating layout */
676 for(c = clients; c; c = c->next)
678 resize(c, c->x, c->y, c->w, c->h, True);
683 if(!c || (c && !isvisible(c)))
684 for(c = stack; c && !isvisible(c); c = c->snext);
685 if(sel && sel != c) {
686 grabbuttons(sel, False);
687 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
692 grabbuttons(c, True);
696 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
697 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
700 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
705 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
706 XFocusChangeEvent *ev = &e->xfocus;
708 if(sel && ev->window != sel->win)
709 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
713 focusnext(const char *arg) {
718 for(c = sel->next; c && !isvisible(c); c = c->next);
720 for(c = clients; c && !isvisible(c); c = c->next);
728 focusprev(const char *arg) {
733 for(c = sel->prev; c && !isvisible(c); c = c->prev);
735 for(c = clients; c && c->next; c = c->next);
736 for(; c && !isvisible(c); c = c->prev);
745 getclient(Window w) {
748 for(c = clients; c && c->win != w; c = c->next);
753 getcolor(const char *colstr) {
754 Colormap cmap = DefaultColormap(dpy, screen);
757 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
758 eprint("error, cannot allocate color '%s'\n", colstr);
766 unsigned char *p = NULL;
767 unsigned long n, extra;
770 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
771 &real, &format, &n, &extra, (unsigned char **)&p);
772 if(status != Success)
781 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
786 if(!text || size == 0)
789 XGetTextProperty(dpy, w, &name, atom);
792 if(name.encoding == XA_STRING)
793 strncpy(text, (char *)name.value, size - 1);
795 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
797 strncpy(text, *list, size - 1);
798 XFreeStringList(list);
801 text[size - 1] = '\0';
807 grabbuttons(Client *c, Bool focused) {
809 unsigned int buttons[] = { Button1, Button2, Button3 };
810 unsigned int modifiers[] = { MODKEY, MODKEY|LockMask, MODKEY|numlockmask,
811 MODKEY|numlockmask|LockMask} ;
813 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
815 for(i = 0; i < LENGTH(buttons); i++)
816 for(j = 0; j < LENGTH(modifiers); j++)
817 XGrabButton(dpy, buttons[i], modifiers[j], c->win, False,
818 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
820 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
821 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
828 XModifierKeymap *modmap;
830 /* init modifier map */
831 modmap = XGetModifierMapping(dpy);
832 for(i = 0; i < 8; i++)
833 for(j = 0; j < modmap->max_keypermod; j++) {
834 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
835 numlockmask = (1 << i);
837 XFreeModifiermap(modmap);
839 XUngrabKey(dpy, AnyKey, AnyModifier, root);
840 for(i = 0; i < LENGTH(keys); i++) {
841 code = XKeysymToKeycode(dpy, keys[i].keysym);
842 XGrabKey(dpy, code, keys[i].mod, root, True,
843 GrabModeAsync, GrabModeAsync);
844 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
845 GrabModeAsync, GrabModeAsync);
846 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
847 GrabModeAsync, GrabModeAsync);
848 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
849 GrabModeAsync, GrabModeAsync);
854 idxoftag(const char *t) {
857 for(i = 0; (i < LENGTH(tags)) && t && strcmp(tags[i], t); i++);
858 return (i < LENGTH(tags)) ? i : 0;
862 initfont(const char *fontstr) {
863 char *def, **missing;
868 XFreeFontSet(dpy, dc.font.set);
869 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
872 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
873 XFreeStringList(missing);
876 XFontSetExtents *font_extents;
877 XFontStruct **xfonts;
879 dc.font.ascent = dc.font.descent = 0;
880 font_extents = XExtentsOfFontSet(dc.font.set);
881 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
882 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
883 if(dc.font.ascent < (*xfonts)->ascent)
884 dc.font.ascent = (*xfonts)->ascent;
885 if(dc.font.descent < (*xfonts)->descent)
886 dc.font.descent = (*xfonts)->descent;
892 XFreeFont(dpy, dc.font.xfont);
893 dc.font.xfont = NULL;
894 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
895 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
896 eprint("error, cannot load font: '%s'\n", fontstr);
897 dc.font.ascent = dc.font.xfont->ascent;
898 dc.font.descent = dc.font.xfont->descent;
900 dc.font.height = dc.font.ascent + dc.font.descent;
904 isoccupied(unsigned int t) {
907 for(c = clients; c; c = c->next)
914 isprotodel(Client *c) {
919 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
920 for(i = 0; !ret && i < n; i++)
921 if(protocols[i] == wmatom[WMDelete])
929 isurgent(unsigned int t) {
932 for(c = clients; c; c = c->next)
933 if(c->isurgent && c->tags[t])
939 isvisible(Client *c) {
942 for(i = 0; i < LENGTH(tags); i++)
943 if(c->tags[i] && seltags[i])
949 keypress(XEvent *e) {
955 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
956 for(i = 0; i < LENGTH(keys); i++)
957 if(keysym == keys[i].keysym
958 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
961 keys[i].func(keys[i].arg);
966 killclient(const char *arg) {
971 if(isprotodel(sel)) {
972 ev.type = ClientMessage;
973 ev.xclient.window = sel->win;
974 ev.xclient.message_type = wmatom[WMProtocols];
975 ev.xclient.format = 32;
976 ev.xclient.data.l[0] = wmatom[WMDelete];
977 ev.xclient.data.l[1] = CurrentTime;
978 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
981 XKillClient(dpy, sel->win);
985 manage(Window w, XWindowAttributes *wa) {
986 Client *c, *t = NULL;
991 c = emallocz(sizeof(Client));
992 c->tags = emallocz(TAGSZ);
1000 c->oldbw = wa->border_width;
1001 if(c->w == sw && c->h == sh) {
1004 c->bw = wa->border_width;
1007 if(c->x + c->w + 2 * c->bw > wx + ww)
1008 c->x = wx + ww - c->w - 2 * c->bw;
1009 if(c->y + c->h + 2 * c->bw > wy + wh)
1010 c->y = wy + wh - c->h - 2 * c->bw;
1018 wc.border_width = c->bw;
1019 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1020 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1021 configure(c); /* propagates border_width, if size doesn't change */
1023 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
1024 grabbuttons(c, False);
1026 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
1027 for(t = clients; t && t->win != trans; t = t->next);
1029 memcpy(c->tags, t->tags, TAGSZ);
1033 c->isfloating = (rettrans == Success) || c->isfixed;
1036 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
1038 XMapWindow(dpy, c->win);
1039 setclientstate(c, NormalState);
1044 mappingnotify(XEvent *e) {
1045 XMappingEvent *ev = &e->xmapping;
1047 XRefreshKeyboardMapping(ev);
1048 if(ev->request == MappingKeyboard)
1053 maprequest(XEvent *e) {
1054 static XWindowAttributes wa;
1055 XMapRequestEvent *ev = &e->xmaprequest;
1057 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1059 if(wa.override_redirect)
1061 if(!getclient(ev->window))
1062 manage(ev->window, &wa);
1069 for(c = clients; c; c = c->next)
1070 if((lt->isfloating || !c->isfloating) && isvisible(c))
1071 resize(c, mox, moy, mow - 2 * c->bw, moh - 2 * c->bw, RESIZEHINTS);
1075 movemouse(Client *c) {
1076 int x1, y1, ocx, ocy, di, nx, ny;
1083 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1084 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1086 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1088 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1091 XUngrabPointer(dpy, CurrentTime);
1093 case ConfigureRequest:
1096 handler[ev.type](&ev);
1100 nx = ocx + (ev.xmotion.x - x1);
1101 ny = ocy + (ev.xmotion.y - y1);
1102 if(abs(wx - nx) < SNAP)
1104 else if(abs((wx + ww) - (nx + c->w + 2 * c->bw)) < SNAP)
1105 nx = wx + ww - c->w - 2 * c->bw;
1106 if(abs(wy - ny) < SNAP)
1108 else if(abs((wy + wh) - (ny + c->h + 2 * c->bw)) < SNAP)
1109 ny = wy + wh - c->h - 2 * c->bw;
1110 if(!c->isfloating && !lt->isfloating && (abs(nx - c->x) > SNAP || abs(ny - c->y) > SNAP))
1111 togglefloating(NULL);
1112 if((lt->isfloating) || c->isfloating)
1113 resize(c, nx, ny, c->w, c->h, False);
1120 nexttiled(Client *c) {
1121 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1126 propertynotify(XEvent *e) {
1129 XPropertyEvent *ev = &e->xproperty;
1131 if(ev->state == PropertyDelete)
1132 return; /* ignore */
1133 if((c = getclient(ev->window))) {
1136 case XA_WM_TRANSIENT_FOR:
1137 XGetTransientForHint(dpy, c->win, &trans);
1138 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1141 case XA_WM_NORMAL_HINTS:
1149 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1158 quit(const char *arg) {
1159 readin = running = False;
1163 reapply(const char *arg) {
1164 static Bool zerotags[LENGTH(tags)] = { 0 };
1167 for(c = clients; c; c = c->next) {
1168 memcpy(c->tags, zerotags, sizeof zerotags);
1175 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1179 /* set minimum possible */
1185 /* temporarily remove base dimensions */
1189 /* adjust for aspect limits */
1190 if(c->minax != c->maxax && c->minay != c->maxay
1191 && c->minax > 0 && c->maxax > 0 && c->minay > 0 && c->maxay > 0)
1193 if(w * c->maxay > h * c->maxax)
1194 w = h * c->maxax / c->maxay;
1195 else if(w * c->minay < h * c->minax)
1196 h = w * c->minay / c->minax;
1199 /* adjust for increment value */
1205 /* restore base dimensions */
1209 if(c->minw > 0 && w < c->minw)
1211 if(c->minh > 0 && h < c->minh)
1213 if(c->maxw > 0 && w > c->maxw)
1215 if(c->maxh > 0 && h > c->maxh)
1218 if(w <= 0 || h <= 0)
1221 x = sw - w - 2 * c->bw;
1223 y = sh - h - 2 * c->bw;
1224 if(x + w + 2 * c->bw < sx)
1226 if(y + h + 2 * c->bw < sy)
1228 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1231 c->w = wc.width = w;
1232 c->h = wc.height = h;
1233 wc.border_width = c->bw;
1234 XConfigureWindow(dpy, c->win,
1235 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1242 resizemouse(Client *c) {
1249 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1250 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1252 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1254 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1257 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1258 c->w + c->bw - 1, c->h + c->bw - 1);
1259 XUngrabPointer(dpy, CurrentTime);
1260 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1262 case ConfigureRequest:
1265 handler[ev.type](&ev);
1269 if((nw = ev.xmotion.x - ocx - 2 * c->bw + 1) <= 0)
1271 if((nh = ev.xmotion.y - ocy - 2 * c->bw + 1) <= 0)
1273 if(!c->isfloating && !lt->isfloating && (abs(nw - c->w) > SNAP || abs(nh - c->h) > SNAP))
1274 togglefloating(NULL);
1275 if((lt->isfloating) || c->isfloating)
1276 resize(c, c->x, c->y, nw, nh, True);
1291 if(sel->isfloating || lt->isfloating)
1292 XRaiseWindow(dpy, sel->win);
1293 if(!lt->isfloating) {
1294 wc.stack_mode = Below;
1295 wc.sibling = barwin;
1296 if(!sel->isfloating) {
1297 XConfigureWindow(dpy, sel->win, CWSibling|CWStackMode, &wc);
1298 wc.sibling = sel->win;
1300 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
1303 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1304 wc.sibling = c->win;
1308 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1314 char sbuf[sizeof stext];
1317 unsigned int len, offset;
1320 /* main event loop, also reads status text from stdin */
1322 xfd = ConnectionNumber(dpy);
1325 len = sizeof stext - 1;
1326 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1330 FD_SET(STDIN_FILENO, &rd);
1332 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1335 eprint("select failed\n");
1337 if(FD_ISSET(STDIN_FILENO, &rd)) {
1338 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1340 strncpy(stext, strerror(errno), len);
1344 strncpy(stext, "EOF", 4);
1348 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1349 if(*p == '\n' || *p == '\0') {
1351 strncpy(stext, sbuf, len);
1352 p += r - 1; /* p is sbuf + offset + r - 1 */
1353 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1356 memmove(sbuf, p - r + 1, r);
1363 while(XPending(dpy)) {
1364 XNextEvent(dpy, &ev);
1365 if(handler[ev.type])
1366 (handler[ev.type])(&ev); /* call handler */
1373 unsigned int i, num;
1374 Window *wins, d1, d2;
1375 XWindowAttributes wa;
1378 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1379 for(i = 0; i < num; i++) {
1380 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1381 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1383 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1384 manage(wins[i], &wa);
1386 for(i = 0; i < num; i++) { /* now the transients */
1387 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1389 if(XGetTransientForHint(dpy, wins[i], &d1)
1390 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1391 manage(wins[i], &wa);
1399 setclientstate(Client *c, long state) {
1400 long data[] = {state, None};
1402 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1403 PropModeReplace, (unsigned char *)data, 2);
1407 setgeom(const char *arg) {
1411 if(++geom == &geoms[LENGTH(geoms)])
1415 for(i = 0; i < LENGTH(geoms); i++)
1416 if(!strcmp(geoms[i].symbol, arg))
1418 if(i == LENGTH(geoms))
1428 setlayout(const char *arg) {
1432 if(++lt == &layouts[LENGTH(layouts)])
1436 for(i = 0; i < LENGTH(layouts); i++)
1437 if(!strcmp(arg, layouts[i].symbol))
1439 if(i == LENGTH(layouts))
1450 setmfact(const char *arg) {
1458 d = strtod(arg, NULL);
1459 if(arg[0] == '-' || arg[0] == '+')
1461 if(d < 0.1 || d > 0.9)
1465 setgeom(geom->symbol);
1471 XSetWindowAttributes wa;
1474 screen = DefaultScreen(dpy);
1475 root = RootWindow(dpy, screen);
1478 /* apply default geometry */
1481 sw = DisplayWidth(dpy, screen);
1482 sh = DisplayHeight(dpy, screen);
1483 bh = dc.font.height + 2;
1488 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1489 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1490 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1491 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1492 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1493 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1496 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1497 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1498 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1500 /* init appearance */
1501 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1502 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1503 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1504 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1505 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1506 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1509 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1510 dc.gc = XCreateGC(dpy, root, 0, 0);
1511 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1513 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1516 seltags = emallocz(TAGSZ);
1517 prevtags = emallocz(TAGSZ);
1518 seltags[0] = prevtags[0] = True;
1521 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1522 w = textw(layouts[i].symbol);
1526 for(bgw = i = 0; LENGTH(geoms) > 1 && i < LENGTH(geoms); i++) {
1527 w = textw(geoms[i].symbol);
1532 wa.override_redirect = 1;
1533 wa.background_pixmap = ParentRelative;
1534 wa.event_mask = ButtonPressMask|ExposureMask;
1536 barwin = XCreateWindow(dpy, root, bx, by, bw, bh, 0, DefaultDepth(dpy, screen),
1537 CopyFromParent, DefaultVisual(dpy, screen),
1538 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1539 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1540 XMapRaised(dpy, barwin);
1541 strcpy(stext, "dwm-"VERSION);
1544 /* EWMH support per view */
1545 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1546 PropModeReplace, (unsigned char *) netatom, NetLast);
1548 /* select for events */
1549 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1550 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1551 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1552 XSelectInput(dpy, root, wa.event_mask);
1560 spawn(const char *arg) {
1561 static char *shell = NULL;
1563 if(!shell && !(shell = getenv("SHELL")))
1567 /* The double-fork construct avoids zombie processes and keeps the code
1568 * clean from stupid signal handlers. */
1572 close(ConnectionNumber(dpy));
1574 execl(shell, shell, "-c", arg, (char *)NULL);
1575 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1584 tag(const char *arg) {
1589 for(i = 0; i < LENGTH(tags); i++)
1590 sel->tags[i] = (NULL == arg);
1591 sel->tags[idxoftag(arg)] = True;
1596 textnw(const char *text, unsigned int len) {
1600 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1603 return XTextWidth(dc.font.xfont, text, len);
1607 textw(const char *text) {
1608 return textnw(text, strlen(text)) + dc.font.height;
1614 unsigned int i, n = counttiled();
1628 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1629 if(i + 1 == n) /* remainder */
1630 tileresize(c, x, ty, (tx + tw) - x - 2 * c->bw, th - 2 * c->bw);
1632 tileresize(c, x, ty, w - 2 * c->bw, th - 2 * c->bw);
1634 x = c->x + c->w + 2 * c->bw;
1639 tilemaster(unsigned int n) {
1640 Client *c = nexttiled(clients);
1643 tileresize(c, mox, moy, mow - 2 * c->bw, moh - 2 * c->bw);
1645 tileresize(c, mx, my, mw - 2 * c->bw, mh - 2 * c->bw);
1650 tileresize(Client *c, int x, int y, int w, int h) {
1651 resize(c, x, y, w, h, RESIZEHINTS);
1652 if((RESIZEHINTS) && ((c->h < bh) || (c->h > h) || (c->w < bh) || (c->w > w)))
1653 /* client doesn't accept size constraints */
1654 resize(c, x, y, w, h, False);
1660 unsigned int i, n = counttiled();
1674 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1675 if(i + 1 == n) /* remainder */
1676 tileresize(c, tx, y, tw - 2 * c->bw, (ty + th) - y - 2 * c->bw);
1678 tileresize(c, tx, y, tw - 2 * c->bw, h - 2 * c->bw);
1680 y = c->y + c->h + 2 * c->bw;
1685 togglefloating(const char *arg) {
1688 sel->isfloating = !sel->isfloating;
1690 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1695 toggletag(const char *arg) {
1701 sel->tags[i] = !sel->tags[i];
1702 for(j = 0; j < LENGTH(tags) && !sel->tags[j]; j++);
1703 if(j == LENGTH(tags))
1704 sel->tags[i] = True; /* at least one tag must be enabled */
1709 toggleview(const char *arg) {
1713 seltags[i] = !seltags[i];
1714 for(j = 0; j < LENGTH(tags) && !seltags[j]; j++);
1715 if(j == LENGTH(tags))
1716 seltags[i] = True; /* at least one tag must be viewed */
1724 XMoveWindow(dpy, c->win, c->x, c->y);
1725 c->isbanned = False;
1729 unmanage(Client *c) {
1732 wc.border_width = c->oldbw;
1733 /* The server grab construct avoids race conditions. */
1735 XSetErrorHandler(xerrordummy);
1736 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1741 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1742 setclientstate(c, WithdrawnState);
1746 XSetErrorHandler(xerror);
1752 unmapnotify(XEvent *e) {
1754 XUnmapEvent *ev = &e->xunmap;
1756 if((c = getclient(ev->window)))
1761 updatebarpos(void) {
1763 if(dc.drawable != 0)
1764 XFreePixmap(dpy, dc.drawable);
1765 dc.drawable = XCreatePixmap(dpy, root, bw, bh, DefaultDepth(dpy, screen));
1766 XMoveResizeWindow(dpy, barwin, bx, by, bw, bh);
1770 updatesizehints(Client *c) {
1774 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1776 c->flags = size.flags;
1777 if(c->flags & PBaseSize) {
1778 c->basew = size.base_width;
1779 c->baseh = size.base_height;
1781 else if(c->flags & PMinSize) {
1782 c->basew = size.min_width;
1783 c->baseh = size.min_height;
1786 c->basew = c->baseh = 0;
1787 if(c->flags & PResizeInc) {
1788 c->incw = size.width_inc;
1789 c->inch = size.height_inc;
1792 c->incw = c->inch = 0;
1793 if(c->flags & PMaxSize) {
1794 c->maxw = size.max_width;
1795 c->maxh = size.max_height;
1798 c->maxw = c->maxh = 0;
1799 if(c->flags & PMinSize) {
1800 c->minw = size.min_width;
1801 c->minh = size.min_height;
1803 else if(c->flags & PBaseSize) {
1804 c->minw = size.base_width;
1805 c->minh = size.base_height;
1808 c->minw = c->minh = 0;
1809 if(c->flags & PAspect) {
1810 c->minax = size.min_aspect.x;
1811 c->maxax = size.max_aspect.x;
1812 c->minay = size.min_aspect.y;
1813 c->maxay = size.max_aspect.y;
1816 c->minax = c->maxax = c->minay = c->maxay = 0;
1817 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1818 && c->maxw == c->minw && c->maxh == c->minh);
1822 updatetitle(Client *c) {
1823 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1824 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1828 updatewmhints(Client *c) {
1831 if((wmh = XGetWMHints(dpy, c->win))) {
1833 sel->isurgent = False;
1835 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1842 view(const char *arg) {
1845 for(i = 0; i < LENGTH(tags); i++)
1846 tmp[i] = (NULL == arg);
1847 tmp[idxoftag(arg)] = True;
1849 if(memcmp(seltags, tmp, TAGSZ) != 0) {
1850 memcpy(prevtags, seltags, TAGSZ);
1851 memcpy(seltags, tmp, TAGSZ);
1857 viewprevtag(const char *arg) {
1859 memcpy(tmp, seltags, TAGSZ);
1860 memcpy(seltags, prevtags, TAGSZ);
1861 memcpy(prevtags, tmp, TAGSZ);
1865 /* There's no way to check accesses to destroyed windows, thus those cases are
1866 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1867 * default error handler, which may call exit. */
1869 xerror(Display *dpy, XErrorEvent *ee) {
1870 if(ee->error_code == BadWindow
1871 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1872 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1873 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1874 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1875 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1876 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1877 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1879 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1880 ee->request_code, ee->error_code);
1881 return xerrorxlib(dpy, ee); /* may call exit */
1885 xerrordummy(Display *dpy, XErrorEvent *ee) {
1889 /* Startup Error handler to check if another window manager
1890 * is already running. */
1892 xerrorstart(Display *dpy, XErrorEvent *ee) {
1898 zoom(const char *arg) {
1901 if(!sel || lt->isfloating || sel->isfloating)
1903 if(c == nexttiled(clients))
1904 if(!(c = nexttiled(c->next)))
1913 main(int argc, char *argv[]) {
1914 if(argc == 2 && !strcmp("-v", argv[1]))
1915 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1917 eprint("usage: dwm [-v]\n");
1919 setlocale(LC_CTYPE, "");
1920 if(!(dpy = XOpenDisplay(0)))
1921 eprint("dwm: cannot open display\n");