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];
246 /* configuration, allows nested code to access above variables */
248 #define TAGSZ (LENGTH(tags) * sizeof(Bool))
249 static Bool tmp[LENGTH(tags)];
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 || (ch.res_class && r->class && strstr(ch.res_class, r->class))
266 || (ch.res_name && r->instance && strstr(ch.res_name, r->instance)))
268 c->isfloating = r->isfloating;
270 c->tags[idxoftag(r->tag)] = True;
280 memcpy(c->tags, seltags, TAGSZ);
287 for(c = clients; c; c = c->next)
307 attachstack(Client *c) {
316 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
321 buttonpress(XEvent *e) {
324 XButtonPressedEvent *ev = &e->xbutton;
326 if(ev->window == barwin) {
327 if((ev->x < bgw) && ev->button == Button1) {
332 for(i = 0; i < LENGTH(tags); i++) {
334 if(ev->x >= bgw && ev->x < x) {
335 if(ev->button == Button1) {
336 if(ev->state & MODKEY)
341 else if(ev->button == Button3) {
342 if(ev->state & MODKEY)
350 if((ev->x < x + blw) && ev->button == Button1)
353 else if((c = getclient(ev->window))) {
355 if(CLEANMASK(ev->state) != MODKEY)
357 if(ev->button == Button1) {
361 else if(ev->button == Button2) {
362 if((floating != lt->arrange) && c->isfloating)
363 togglefloating(NULL);
367 else if(ev->button == Button3 && !c->isfixed) {
377 XSetErrorHandler(xerrorstart);
379 /* this causes an error if some other window manager is running */
380 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
383 eprint("dwm: another window manager is already running\n");
385 XSetErrorHandler(NULL);
386 xerrorxlib = XSetErrorHandler(xerror);
398 XFreeFontSet(dpy, dc.font.set);
400 XFreeFont(dpy, dc.font.xfont);
401 XUngrabKey(dpy, AnyKey, AnyModifier, root);
402 XFreePixmap(dpy, dc.drawable);
404 XFreeCursor(dpy, cursor[CurNormal]);
405 XFreeCursor(dpy, cursor[CurResize]);
406 XFreeCursor(dpy, cursor[CurMove]);
407 XDestroyWindow(dpy, barwin);
409 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
413 configure(Client *c) {
416 ce.type = ConfigureNotify;
424 ce.border_width = c->bw;
426 ce.override_redirect = False;
427 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
431 configurenotify(XEvent *e) {
432 XConfigureEvent *ev = &e->xconfigure;
434 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
437 setgeom(geom->symbol);
442 configurerequest(XEvent *e) {
444 XConfigureRequestEvent *ev = &e->xconfigurerequest;
447 if((c = getclient(ev->window))) {
448 if(ev->value_mask & CWBorderWidth)
449 c->bw = ev->border_width;
450 if(c->isfixed || c->isfloating || lt->isfloating) {
451 if(ev->value_mask & CWX)
453 if(ev->value_mask & CWY)
455 if(ev->value_mask & CWWidth)
457 if(ev->value_mask & CWHeight)
459 if((c->x - sx + c->w) > sw && c->isfloating)
460 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
461 if((c->y - sy + c->h) > sh && c->isfloating)
462 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
463 if((ev->value_mask & (CWX|CWY))
464 && !(ev->value_mask & (CWWidth|CWHeight)))
467 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
475 wc.width = ev->width;
476 wc.height = ev->height;
477 wc.border_width = ev->border_width;
478 wc.sibling = ev->above;
479 wc.stack_mode = ev->detail;
480 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
490 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next), n++);
495 destroynotify(XEvent *e) {
497 XDestroyWindowEvent *ev = &e->xdestroywindow;
499 if((c = getclient(ev->window)))
506 c->prev->next = c->next;
508 c->next->prev = c->prev;
511 c->next = c->prev = NULL;
515 detachstack(Client *c) {
518 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
530 drawtext(geom->symbol, dc.norm, False);
533 for(c = stack; c && !isvisible(c); c = c->snext);
534 for(i = 0; i < LENGTH(tags); i++) {
535 dc.w = textw(tags[i]);
537 drawtext(tags[i], dc.sel, isurgent(i));
538 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.sel);
541 drawtext(tags[i], dc.norm, isurgent(i));
542 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.norm);
548 drawtext(lt->symbol, dc.norm, False);
559 drawtext(stext, dc.norm, False);
560 if((dc.w = dc.x - x) > bh) {
563 drawtext(c->name, dc.sel, False);
564 drawsquare(False, c->isfloating, False, dc.sel);
567 drawtext(NULL, dc.norm, False);
569 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, bw, bh, 0, 0);
574 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
577 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
579 gcv.foreground = col[invert ? ColBG : ColFG];
580 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
581 x = (dc.font.ascent + dc.font.descent + 2) / 4;
585 r.width = r.height = x + 1;
586 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
589 r.width = r.height = x;
590 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
595 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
597 unsigned int len, olen;
598 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
600 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
601 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
605 olen = len = strlen(text);
606 if(len >= sizeof buf)
607 len = sizeof buf - 1;
608 memcpy(buf, text, len);
610 h = dc.font.ascent + dc.font.descent;
611 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
613 /* shorten text if necessary */
614 while(len && (w = textnw(buf, len)) > dc.w - h)
625 return; /* too long */
626 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
628 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
630 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
634 emallocz(unsigned int size) {
635 void *res = calloc(1, size);
638 eprint("fatal: could not malloc() %u bytes\n", size);
643 enternotify(XEvent *e) {
645 XCrossingEvent *ev = &e->xcrossing;
647 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
649 if((c = getclient(ev->window)))
656 eprint(const char *errstr, ...) {
659 va_start(ap, errstr);
660 vfprintf(stderr, errstr, ap);
667 XExposeEvent *ev = &e->xexpose;
669 if(ev->count == 0 && (ev->window == barwin))
674 floating(void) { /* default floating layout */
677 for(c = clients; c; c = c->next)
679 resize(c, c->x, c->y, c->w, c->h, True);
684 if(!c || (c && !isvisible(c)))
685 for(c = stack; c && !isvisible(c); c = c->snext);
686 if(sel && sel != c) {
687 grabbuttons(sel, False);
688 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
693 grabbuttons(c, True);
697 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
698 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
701 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
706 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
707 XFocusChangeEvent *ev = &e->xfocus;
709 if(sel && ev->window != sel->win)
710 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
714 focusnext(const char *arg) {
719 for(c = sel->next; c && !isvisible(c); c = c->next);
721 for(c = clients; c && !isvisible(c); c = c->next);
729 focusprev(const char *arg) {
734 for(c = sel->prev; c && !isvisible(c); c = c->prev);
736 for(c = clients; c && c->next; c = c->next);
737 for(; c && !isvisible(c); c = c->prev);
746 getclient(Window w) {
749 for(c = clients; c && c->win != w; c = c->next);
754 getcolor(const char *colstr) {
755 Colormap cmap = DefaultColormap(dpy, screen);
758 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
759 eprint("error, cannot allocate color '%s'\n", colstr);
767 unsigned char *p = NULL;
768 unsigned long n, extra;
771 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
772 &real, &format, &n, &extra, (unsigned char **)&p);
773 if(status != Success)
782 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
787 if(!text || size == 0)
790 XGetTextProperty(dpy, w, &name, atom);
793 if(name.encoding == XA_STRING)
794 strncpy(text, (char *)name.value, size - 1);
796 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
798 strncpy(text, *list, size - 1);
799 XFreeStringList(list);
802 text[size - 1] = '\0';
808 grabbuttons(Client *c, Bool focused) {
810 unsigned int buttons[] = { Button1, Button2, Button3 };
811 unsigned int modifiers[] = { MODKEY, MODKEY|LockMask, MODKEY|numlockmask,
812 MODKEY|numlockmask|LockMask} ;
814 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
816 for(i = 0; i < LENGTH(buttons); i++)
817 for(j = 0; j < LENGTH(modifiers); j++)
818 XGrabButton(dpy, buttons[i], modifiers[j], c->win, False,
819 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
821 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
822 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
829 XModifierKeymap *modmap;
831 /* init modifier map */
832 modmap = XGetModifierMapping(dpy);
833 for(i = 0; i < 8; i++)
834 for(j = 0; j < modmap->max_keypermod; j++) {
835 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
836 numlockmask = (1 << i);
838 XFreeModifiermap(modmap);
840 XUngrabKey(dpy, AnyKey, AnyModifier, root);
841 for(i = 0; i < LENGTH(keys); i++) {
842 code = XKeysymToKeycode(dpy, keys[i].keysym);
843 XGrabKey(dpy, code, keys[i].mod, root, True,
844 GrabModeAsync, GrabModeAsync);
845 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
846 GrabModeAsync, GrabModeAsync);
847 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
848 GrabModeAsync, GrabModeAsync);
849 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
850 GrabModeAsync, GrabModeAsync);
855 idxoftag(const char *t) {
858 for(i = 0; (i < LENGTH(tags)) && t && strcmp(tags[i], t); i++);
859 return (i < LENGTH(tags)) ? i : 0;
863 initfont(const char *fontstr) {
864 char *def, **missing;
869 XFreeFontSet(dpy, dc.font.set);
870 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
873 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
874 XFreeStringList(missing);
877 XFontSetExtents *font_extents;
878 XFontStruct **xfonts;
880 dc.font.ascent = dc.font.descent = 0;
881 font_extents = XExtentsOfFontSet(dc.font.set);
882 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
883 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
884 if(dc.font.ascent < (*xfonts)->ascent)
885 dc.font.ascent = (*xfonts)->ascent;
886 if(dc.font.descent < (*xfonts)->descent)
887 dc.font.descent = (*xfonts)->descent;
893 XFreeFont(dpy, dc.font.xfont);
894 dc.font.xfont = NULL;
895 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
896 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
897 eprint("error, cannot load font: '%s'\n", fontstr);
898 dc.font.ascent = dc.font.xfont->ascent;
899 dc.font.descent = dc.font.xfont->descent;
901 dc.font.height = dc.font.ascent + dc.font.descent;
905 isoccupied(unsigned int t) {
908 for(c = clients; c; c = c->next)
915 isprotodel(Client *c) {
920 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
921 for(i = 0; !ret && i < n; i++)
922 if(protocols[i] == wmatom[WMDelete])
930 isurgent(unsigned int t) {
933 for(c = clients; c; c = c->next)
934 if(c->isurgent && c->tags[t])
940 isvisible(Client *c) {
943 for(i = 0; i < LENGTH(tags); i++)
944 if(c->tags[i] && seltags[i])
950 keypress(XEvent *e) {
956 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
957 for(i = 0; i < LENGTH(keys); i++)
958 if(keysym == keys[i].keysym
959 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
962 keys[i].func(keys[i].arg);
967 killclient(const char *arg) {
972 if(isprotodel(sel)) {
973 ev.type = ClientMessage;
974 ev.xclient.window = sel->win;
975 ev.xclient.message_type = wmatom[WMProtocols];
976 ev.xclient.format = 32;
977 ev.xclient.data.l[0] = wmatom[WMDelete];
978 ev.xclient.data.l[1] = CurrentTime;
979 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
982 XKillClient(dpy, sel->win);
986 manage(Window w, XWindowAttributes *wa) {
987 Client *c, *t = NULL;
992 c = emallocz(sizeof(Client));
993 c->tags = emallocz(TAGSZ);
1001 c->oldbw = wa->border_width;
1002 if(c->w == sw && c->h == sh) {
1005 c->bw = wa->border_width;
1008 if(c->x + c->w + 2 * c->bw > wx + ww)
1009 c->x = wx + ww - c->w - 2 * c->bw;
1010 if(c->y + c->h + 2 * c->bw > wy + wh)
1011 c->y = wy + wh - c->h - 2 * c->bw;
1019 wc.border_width = c->bw;
1020 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1021 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1022 configure(c); /* propagates border_width, if size doesn't change */
1024 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
1025 grabbuttons(c, False);
1027 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
1028 for(t = clients; t && t->win != trans; t = t->next);
1030 memcpy(c->tags, t->tags, TAGSZ);
1034 c->isfloating = (rettrans == Success) || c->isfixed;
1037 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
1039 XMapWindow(dpy, c->win);
1040 setclientstate(c, NormalState);
1045 mappingnotify(XEvent *e) {
1046 XMappingEvent *ev = &e->xmapping;
1048 XRefreshKeyboardMapping(ev);
1049 if(ev->request == MappingKeyboard)
1054 maprequest(XEvent *e) {
1055 static XWindowAttributes wa;
1056 XMapRequestEvent *ev = &e->xmaprequest;
1058 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1060 if(wa.override_redirect)
1062 if(!getclient(ev->window))
1063 manage(ev->window, &wa);
1070 for(c = clients; c; c = c->next)
1071 if((lt->isfloating || !c->floating) && isvisible(c))
1072 resize(c, mox, moy, mow - 2 * c->bw, moh - 2 * c->bw, RESIZEHINTS);
1076 movemouse(Client *c) {
1077 int x1, y1, ocx, ocy, di, nx, ny;
1084 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1085 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1087 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1089 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1092 XUngrabPointer(dpy, CurrentTime);
1094 case ConfigureRequest:
1097 handler[ev.type](&ev);
1101 nx = ocx + (ev.xmotion.x - x1);
1102 ny = ocy + (ev.xmotion.y - y1);
1103 if(abs(wx - nx) < SNAP)
1105 else if(abs((wx + ww) - (nx + c->w + 2 * c->bw)) < SNAP)
1106 nx = wx + ww - c->w - 2 * c->bw;
1107 if(abs(wy - ny) < SNAP)
1109 else if(abs((wy + wh) - (ny + c->h + 2 * c->bw)) < SNAP)
1110 ny = wy + wh - c->h - 2 * c->bw;
1111 if(!c->isfloating && !lt->isfloating && (abs(nx - c->x) > SNAP || abs(ny - c->y) > SNAP))
1112 togglefloating(NULL);
1113 if((lt->isfloating) || c->isfloating)
1114 resize(c, nx, ny, c->w, c->h, False);
1121 nexttiled(Client *c) {
1122 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1127 propertynotify(XEvent *e) {
1130 XPropertyEvent *ev = &e->xproperty;
1132 if(ev->state == PropertyDelete)
1133 return; /* ignore */
1134 if((c = getclient(ev->window))) {
1137 case XA_WM_TRANSIENT_FOR:
1138 XGetTransientForHint(dpy, c->win, &trans);
1139 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1142 case XA_WM_NORMAL_HINTS:
1150 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1159 quit(const char *arg) {
1160 readin = running = False;
1164 reapply(const char *arg) {
1165 static Bool zerotags[LENGTH(tags)] = { 0 };
1168 for(c = clients; c; c = c->next) {
1169 memcpy(c->tags, zerotags, sizeof zerotags);
1176 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1180 /* set minimum possible */
1186 /* temporarily remove base dimensions */
1190 /* adjust for aspect limits */
1191 if(c->minax != c->maxax && c->minay != c->maxay
1192 && c->minax > 0 && c->maxax > 0 && c->minay > 0 && c->maxay > 0)
1194 if(w * c->maxay > h * c->maxax)
1195 w = h * c->maxax / c->maxay;
1196 else if(w * c->minay < h * c->minax)
1197 h = w * c->minay / c->minax;
1200 /* adjust for increment value */
1206 /* restore base dimensions */
1210 if(c->minw > 0 && w < c->minw)
1212 if(c->minh > 0 && h < c->minh)
1214 if(c->maxw > 0 && w > c->maxw)
1216 if(c->maxh > 0 && h > c->maxh)
1219 if(w <= 0 || h <= 0)
1222 x = sw - w - 2 * c->bw;
1224 y = sh - h - 2 * c->bw;
1225 if(x + w + 2 * c->bw < sx)
1227 if(y + h + 2 * c->bw < sy)
1229 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1232 c->w = wc.width = w;
1233 c->h = wc.height = h;
1234 wc.border_width = c->bw;
1235 XConfigureWindow(dpy, c->win,
1236 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1243 resizemouse(Client *c) {
1250 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1251 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1253 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1255 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1258 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1259 c->w + c->bw - 1, c->h + c->bw - 1);
1260 XUngrabPointer(dpy, CurrentTime);
1261 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1263 case ConfigureRequest:
1266 handler[ev.type](&ev);
1270 if((nw = ev.xmotion.x - ocx - 2 * c->bw + 1) <= 0)
1272 if((nh = ev.xmotion.y - ocy - 2 * c->bw + 1) <= 0)
1274 if(!c->isfloating && !lt->isfloating && (abs(nw - c->w) > SNAP || abs(nh - c->h) > SNAP))
1275 togglefloating(NULL);
1276 if((lt->isfloating) || c->isfloating)
1277 resize(c, c->x, c->y, nw, nh, True);
1292 if(sel->isfloating || lt->isfloating)
1293 XRaiseWindow(dpy, sel->win);
1294 if(!lt->isfloating) {
1295 wc.stack_mode = Below;
1296 wc.sibling = barwin;
1297 if(!sel->isfloating) {
1298 XConfigureWindow(dpy, sel->win, CWSibling|CWStackMode, &wc);
1299 wc.sibling = sel->win;
1301 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
1304 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1305 wc.sibling = c->win;
1309 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1315 char sbuf[sizeof stext];
1318 unsigned int len, offset;
1321 /* main event loop, also reads status text from stdin */
1323 xfd = ConnectionNumber(dpy);
1326 len = sizeof stext - 1;
1327 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1331 FD_SET(STDIN_FILENO, &rd);
1333 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1336 eprint("select failed\n");
1338 if(FD_ISSET(STDIN_FILENO, &rd)) {
1339 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1341 strncpy(stext, strerror(errno), len);
1345 strncpy(stext, "EOF", 4);
1349 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1350 if(*p == '\n' || *p == '\0') {
1352 strncpy(stext, sbuf, len);
1353 p += r - 1; /* p is sbuf + offset + r - 1 */
1354 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1357 memmove(sbuf, p - r + 1, r);
1364 while(XPending(dpy)) {
1365 XNextEvent(dpy, &ev);
1366 if(handler[ev.type])
1367 (handler[ev.type])(&ev); /* call handler */
1374 unsigned int i, num;
1375 Window *wins, d1, d2;
1376 XWindowAttributes wa;
1379 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1380 for(i = 0; i < num; i++) {
1381 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1382 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1384 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1385 manage(wins[i], &wa);
1387 for(i = 0; i < num; i++) { /* now the transients */
1388 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1390 if(XGetTransientForHint(dpy, wins[i], &d1)
1391 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1392 manage(wins[i], &wa);
1400 setclientstate(Client *c, long state) {
1401 long data[] = {state, None};
1403 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1404 PropModeReplace, (unsigned char *)data, 2);
1408 setgeom(const char *arg) {
1412 if(++geom == &geoms[LENGTH(geoms)])
1416 for(i = 0; i < LENGTH(geoms); i++)
1417 if(!strcmp(geoms[i].symbol, arg))
1419 if(i == LENGTH(geoms))
1429 setlayout(const char *arg) {
1433 if(++lt == &layouts[LENGTH(layouts)])
1437 for(i = 0; i < LENGTH(layouts); i++)
1438 if(!strcmp(arg, layouts[i].symbol))
1440 if(i == LENGTH(layouts))
1451 setmfact(const char *arg) {
1459 d = strtod(arg, NULL);
1460 if(arg[0] == '-' || arg[0] == '+')
1462 if(d < 0.1 || d > 0.9)
1466 setgeom(geom->symbol);
1472 XSetWindowAttributes wa;
1475 screen = DefaultScreen(dpy);
1476 root = RootWindow(dpy, screen);
1479 /* apply default geometry */
1482 sw = DisplayWidth(dpy, screen);
1483 sh = DisplayHeight(dpy, screen);
1484 bh = dc.font.height + 2;
1490 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1491 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1492 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1493 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1494 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1495 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1498 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1499 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1500 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1502 /* init appearance */
1503 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1504 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1505 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1506 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1507 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1508 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1511 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1512 dc.gc = XCreateGC(dpy, root, 0, 0);
1513 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1515 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1518 seltags = emallocz(TAGSZ);
1519 prevtags = emallocz(TAGSZ);
1520 seltags[0] = prevtags[0] = True;
1526 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1527 w = textw(layouts[i].symbol);
1531 for(bgw = i = 0; LENGTH(geoms) > 1 && i < LENGTH(geoms); i++) {
1532 w = textw(geoms[i].symbol);
1537 wa.override_redirect = 1;
1538 wa.background_pixmap = ParentRelative;
1539 wa.event_mask = ButtonPressMask|ExposureMask;
1541 barwin = XCreateWindow(dpy, root, bx, by, bw, bh, 0, DefaultDepth(dpy, screen),
1542 CopyFromParent, DefaultVisual(dpy, screen),
1543 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1544 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1545 XMapRaised(dpy, barwin);
1546 strcpy(stext, "dwm-"VERSION);
1549 /* EWMH support per view */
1550 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1551 PropModeReplace, (unsigned char *) netatom, NetLast);
1553 /* select for events */
1554 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1555 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1556 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1557 XSelectInput(dpy, root, wa.event_mask);
1565 spawn(const char *arg) {
1566 static char *shell = NULL;
1568 if(!shell && !(shell = getenv("SHELL")))
1572 /* The double-fork construct avoids zombie processes and keeps the code
1573 * clean from stupid signal handlers. */
1577 close(ConnectionNumber(dpy));
1579 execl(shell, shell, "-c", arg, (char *)NULL);
1580 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1589 tag(const char *arg) {
1594 for(i = 0; i < LENGTH(tags); i++)
1595 sel->tags[i] = (NULL == arg);
1596 sel->tags[idxoftag(arg)] = True;
1601 textnw(const char *text, unsigned int len) {
1605 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1608 return XTextWidth(dc.font.xfont, text, len);
1612 textw(const char *text) {
1613 return textnw(text, strlen(text)) + dc.font.height;
1619 unsigned int i, n = counttiled();
1633 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1634 if(i + 1 == n) /* remainder */
1635 tileresize(c, x, ty, (tx + tw) - x - 2 * c->bw, th - 2 * c->bw);
1637 tileresize(c, x, ty, w - 2 * c->bw, th - 2 * c->bw);
1639 x = c->x + c->w + 2 * c->bw;
1644 tilemaster(unsigned int n) {
1645 Client *c = nexttiled(clients);
1648 tileresize(c, mox, moy, mow - 2 * c->bw, moh - 2 * c->bw);
1650 tileresize(c, mx, my, mw - 2 * c->bw, mh - 2 * c->bw);
1655 tileresize(Client *c, int x, int y, int w, int h) {
1656 resize(c, x, y, w, h, RESIZEHINTS);
1657 if((RESIZEHINTS) && ((c->h < bh) || (c->h > h) || (c->w < bh) || (c->w > w)))
1658 /* client doesn't accept size constraints */
1659 resize(c, x, y, w, h, False);
1665 unsigned int i, n = counttiled();
1679 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1680 if(i + 1 == n) /* remainder */
1681 tileresize(c, tx, y, tw - 2 * c->bw, (ty + th) - y - 2 * c->bw);
1683 tileresize(c, tx, y, tw - 2 * c->bw, h - 2 * c->bw);
1685 y = c->y + c->h + 2 * c->bw;
1690 togglefloating(const char *arg) {
1693 sel->isfloating = !sel->isfloating;
1695 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1700 toggletag(const char *arg) {
1706 sel->tags[i] = !sel->tags[i];
1707 for(j = 0; j < LENGTH(tags) && !sel->tags[j]; j++);
1708 if(j == LENGTH(tags))
1709 sel->tags[i] = True; /* at least one tag must be enabled */
1714 toggleview(const char *arg) {
1718 seltags[i] = !seltags[i];
1719 for(j = 0; j < LENGTH(tags) && !seltags[j]; j++);
1720 if(j == LENGTH(tags))
1721 seltags[i] = True; /* at least one tag must be viewed */
1729 XMoveWindow(dpy, c->win, c->x, c->y);
1730 c->isbanned = False;
1734 unmanage(Client *c) {
1737 wc.border_width = c->oldbw;
1738 /* The server grab construct avoids race conditions. */
1740 XSetErrorHandler(xerrordummy);
1741 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1746 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1747 setclientstate(c, WithdrawnState);
1751 XSetErrorHandler(xerror);
1757 unmapnotify(XEvent *e) {
1759 XUnmapEvent *ev = &e->xunmap;
1761 if((c = getclient(ev->window)))
1766 updatebarpos(void) {
1768 if(dc.drawable != 0)
1769 XFreePixmap(dpy, dc.drawable);
1770 dc.drawable = XCreatePixmap(dpy, root, bw, bh, DefaultDepth(dpy, screen));
1771 XMoveResizeWindow(dpy, barwin, bx, by, bw, bh);
1775 updatesizehints(Client *c) {
1779 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1781 c->flags = size.flags;
1782 if(c->flags & PBaseSize) {
1783 c->basew = size.base_width;
1784 c->baseh = size.base_height;
1786 else if(c->flags & PMinSize) {
1787 c->basew = size.min_width;
1788 c->baseh = size.min_height;
1791 c->basew = c->baseh = 0;
1792 if(c->flags & PResizeInc) {
1793 c->incw = size.width_inc;
1794 c->inch = size.height_inc;
1797 c->incw = c->inch = 0;
1798 if(c->flags & PMaxSize) {
1799 c->maxw = size.max_width;
1800 c->maxh = size.max_height;
1803 c->maxw = c->maxh = 0;
1804 if(c->flags & PMinSize) {
1805 c->minw = size.min_width;
1806 c->minh = size.min_height;
1808 else if(c->flags & PBaseSize) {
1809 c->minw = size.base_width;
1810 c->minh = size.base_height;
1813 c->minw = c->minh = 0;
1814 if(c->flags & PAspect) {
1815 c->minax = size.min_aspect.x;
1816 c->maxax = size.max_aspect.x;
1817 c->minay = size.min_aspect.y;
1818 c->maxay = size.max_aspect.y;
1821 c->minax = c->maxax = c->minay = c->maxay = 0;
1822 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1823 && c->maxw == c->minw && c->maxh == c->minh);
1827 updatetitle(Client *c) {
1828 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1829 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1833 updatewmhints(Client *c) {
1836 if((wmh = XGetWMHints(dpy, c->win))) {
1838 sel->isurgent = False;
1840 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1847 view(const char *arg) {
1850 for(i = 0; i < LENGTH(tags); i++)
1851 tmp[i] = (NULL == arg);
1852 tmp[idxoftag(arg)] = True;
1854 if(memcmp(seltags, tmp, TAGSZ) != 0) {
1855 memcpy(prevtags, seltags, TAGSZ);
1856 memcpy(seltags, tmp, TAGSZ);
1862 viewprevtag(const char *arg) {
1864 memcpy(tmp, seltags, TAGSZ);
1865 memcpy(seltags, prevtags, TAGSZ);
1866 memcpy(prevtags, tmp, TAGSZ);
1870 /* There's no way to check accesses to destroyed windows, thus those cases are
1871 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1872 * default error handler, which may call exit. */
1874 xerror(Display *dpy, XErrorEvent *ee) {
1875 if(ee->error_code == BadWindow
1876 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1877 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1878 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1879 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1880 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1881 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1882 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1884 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1885 ee->request_code, ee->error_code);
1886 return xerrorxlib(dpy, ee); /* may call exit */
1890 xerrordummy(Display *dpy, XErrorEvent *ee) {
1894 /* Startup Error handler to check if another window manager
1895 * is already running. */
1897 xerrorstart(Display *dpy, XErrorEvent *ee) {
1903 zoom(const char *arg) {
1906 if(!sel || lt->isfloating || sel->isfloating)
1908 if(c == nexttiled(clients))
1909 if(!(c = nexttiled(c->next)))
1918 main(int argc, char *argv[]) {
1919 if(argc == 2 && !strcmp("-v", argv[1]))
1920 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1922 eprint("usage: dwm [-v]\n");
1924 setlocale(LC_CTYPE, "");
1925 if(!(dpy = XOpenDisplay(0)))
1926 eprint("dwm: cannot open display\n");