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 border, oldborder;
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);
182 void spawn(const char *arg);
183 void tag(const char *arg);
184 unsigned int textnw(const char *text, unsigned int len);
185 unsigned int textw(const char *text);
187 void tilehstack(unsigned int n);
188 Client *tilemaster(unsigned int n);
189 void tileresize(Client *c, int x, int y, int w, int h);
191 void tilevstack(unsigned int n);
192 void togglefloating(const char *arg);
193 void toggletag(const char *arg);
194 void toggleview(const char *arg);
195 void unban(Client *c);
196 void unmanage(Client *c);
197 void unmapnotify(XEvent *e);
198 void updatebarpos(void);
199 void updatesizehints(Client *c);
200 void updatetitle(Client *c);
201 void updatewmhints(Client *c);
202 void view(const char *arg);
203 void viewprevtag(const char *arg); /* views previous selected tags */
204 int xerror(Display *dpy, XErrorEvent *ee);
205 int xerrordummy(Display *dpy, XErrorEvent *ee);
206 int xerrorstart(Display *dpy, XErrorEvent *ee);
207 void zoom(const char *arg);
210 char stext[256], buf[256];
211 int screen, sx, sy, sw, sh;
212 int (*xerrorxlib)(Display *, XErrorEvent *);
213 int bx, by, bw, bh, blw, bgw, mx, my, mw, mh, mox, moy, mow, moh, tx, ty, tw, th, wx, wy, ww, wh;
214 unsigned int numlockmask = 0;
215 void (*handler[LASTEvent]) (XEvent *) = {
216 [ButtonPress] = buttonpress,
217 [ConfigureRequest] = configurerequest,
218 [ConfigureNotify] = configurenotify,
219 [DestroyNotify] = destroynotify,
220 [EnterNotify] = enternotify,
223 [KeyPress] = keypress,
224 [MappingNotify] = mappingnotify,
225 [MapRequest] = maprequest,
226 [PropertyNotify] = propertynotify,
227 [UnmapNotify] = unmapnotify
229 Atom wmatom[WMLast], netatom[NetLast];
230 Bool otherwm, readin;
234 Client *clients = NULL;
236 Client *stack = NULL;
237 Cursor cursor[CurLast];
244 /* configuration, allows nested code to access above variables */
246 #define TAGSZ (LENGTH(tags) * sizeof(Bool))
247 static Bool tmp[LENGTH(tags)];
249 /* function implementations */
252 applyrules(Client *c) {
254 Bool matched = False;
256 XClassHint ch = { 0 };
259 XGetClassHint(dpy, c->win, &ch);
260 for(i = 0; i < LENGTH(rules); i++) {
262 if(strstr(c->name, r->title)
263 || (ch.res_class && r->class && strstr(ch.res_class, r->class))
264 || (ch.res_name && r->instance && strstr(ch.res_name, r->instance)))
266 c->isfloating = r->isfloating;
268 c->tags[idxoftag(r->tag)] = True;
278 memcpy(c->tags, seltags, TAGSZ);
285 for(c = clients; c; c = c->next)
305 attachstack(Client *c) {
314 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
319 buttonpress(XEvent *e) {
322 XButtonPressedEvent *ev = &e->xbutton;
324 if(ev->window == barwin) {
326 for(i = 0; i < LENGTH(tags); i++) {
328 if(ev->x > bgw && ev->x < x) {
329 if(ev->button == Button1) {
330 if(ev->state & MODKEY)
335 else if(ev->button == Button3) {
336 if(ev->state & MODKEY)
345 else if((c = getclient(ev->window))) {
347 if(CLEANMASK(ev->state) != MODKEY)
349 if(ev->button == Button1) {
353 else if(ev->button == Button2) {
354 if((floating != lt->arrange) && c->isfloating)
355 togglefloating(NULL);
359 else if(ev->button == Button3 && !c->isfixed) {
369 XSetErrorHandler(xerrorstart);
371 /* this causes an error if some other window manager is running */
372 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
375 eprint("dwm: another window manager is already running\n");
377 XSetErrorHandler(NULL);
378 xerrorxlib = XSetErrorHandler(xerror);
390 XFreeFontSet(dpy, dc.font.set);
392 XFreeFont(dpy, dc.font.xfont);
393 XUngrabKey(dpy, AnyKey, AnyModifier, root);
394 XFreePixmap(dpy, dc.drawable);
396 XFreeCursor(dpy, cursor[CurNormal]);
397 XFreeCursor(dpy, cursor[CurResize]);
398 XFreeCursor(dpy, cursor[CurMove]);
399 XDestroyWindow(dpy, barwin);
401 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
405 configure(Client *c) {
408 ce.type = ConfigureNotify;
416 ce.border_width = c->border;
418 ce.override_redirect = False;
419 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
423 configurenotify(XEvent *e) {
424 XConfigureEvent *ev = &e->xconfigure;
426 if(ev->window == root && (ev->width != sw || ev->height != sh))
431 configurerequest(XEvent *e) {
433 XConfigureRequestEvent *ev = &e->xconfigurerequest;
436 if((c = getclient(ev->window))) {
437 if(ev->value_mask & CWBorderWidth)
438 c->border = ev->border_width;
439 if(c->isfixed || c->isfloating || lt->isfloating) {
440 if(ev->value_mask & CWX)
442 if(ev->value_mask & CWY)
444 if(ev->value_mask & CWWidth)
446 if(ev->value_mask & CWHeight)
448 if((c->x - sx + c->w) > sw && c->isfloating)
449 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
450 if((c->y - sy + c->h) > sh && c->isfloating)
451 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
452 if((ev->value_mask & (CWX|CWY))
453 && !(ev->value_mask & (CWWidth|CWHeight)))
456 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
464 wc.width = ev->width;
465 wc.height = ev->height;
466 wc.border_width = ev->border_width;
467 wc.sibling = ev->above;
468 wc.stack_mode = ev->detail;
469 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
479 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next), n++);
484 destroynotify(XEvent *e) {
486 XDestroyWindowEvent *ev = &e->xdestroywindow;
488 if((c = getclient(ev->window)))
495 c->prev->next = c->next;
497 c->next->prev = c->prev;
500 c->next = c->prev = NULL;
504 detachstack(Client *c) {
507 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
518 drawtext(geom->symbol, dc.norm, False);
520 for(c = stack; c && !isvisible(c); c = c->snext);
521 for(i = 0; i < LENGTH(tags); i++) {
522 dc.w = textw(tags[i]);
524 drawtext(tags[i], dc.sel, isurgent(i));
525 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.sel);
528 drawtext(tags[i], dc.norm, isurgent(i));
529 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.norm);
534 drawtext(lt->symbol, dc.norm, False);
542 drawtext(stext, dc.norm, False);
543 if((dc.w = dc.x - x) > bh) {
546 drawtext(c->name, dc.sel, False);
547 drawsquare(False, c->isfloating, False, dc.sel);
550 drawtext(NULL, dc.norm, False);
552 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, bw, bh, 0, 0);
557 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
560 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
562 gcv.foreground = col[invert ? ColBG : ColFG];
563 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
564 x = (dc.font.ascent + dc.font.descent + 2) / 4;
568 r.width = r.height = x + 1;
569 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
572 r.width = r.height = x;
573 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
578 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
580 unsigned int len, olen;
581 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
583 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
584 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
588 olen = len = strlen(text);
589 if(len >= sizeof buf)
590 len = sizeof buf - 1;
591 memcpy(buf, text, len);
593 h = dc.font.ascent + dc.font.descent;
594 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
596 /* shorten text if necessary */
597 while(len && (w = textnw(buf, len)) > dc.w - h)
608 return; /* too long */
609 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
611 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
613 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
617 emallocz(unsigned int size) {
618 void *res = calloc(1, size);
621 eprint("fatal: could not malloc() %u bytes\n", size);
626 enternotify(XEvent *e) {
628 XCrossingEvent *ev = &e->xcrossing;
630 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
632 if((c = getclient(ev->window)))
639 eprint(const char *errstr, ...) {
642 va_start(ap, errstr);
643 vfprintf(stderr, errstr, ap);
650 XExposeEvent *ev = &e->xexpose;
652 if(ev->count == 0 && (ev->window == barwin))
657 floating(void) { /* default floating layout */
660 for(c = clients; c; c = c->next)
662 resize(c, c->x, c->y, c->w, c->h, True);
667 if(!c || (c && !isvisible(c)))
668 for(c = stack; c && !isvisible(c); c = c->snext);
669 if(sel && sel != c) {
670 grabbuttons(sel, False);
671 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
676 grabbuttons(c, True);
680 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
681 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
684 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
689 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
690 XFocusChangeEvent *ev = &e->xfocus;
692 if(sel && ev->window != sel->win)
693 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
697 focusnext(const char *arg) {
702 for(c = sel->next; c && !isvisible(c); c = c->next);
704 for(c = clients; c && !isvisible(c); c = c->next);
712 focusprev(const char *arg) {
717 for(c = sel->prev; c && !isvisible(c); c = c->prev);
719 for(c = clients; c && c->next; c = c->next);
720 for(; c && !isvisible(c); c = c->prev);
729 getclient(Window w) {
732 for(c = clients; c && c->win != w; c = c->next);
737 getcolor(const char *colstr) {
738 Colormap cmap = DefaultColormap(dpy, screen);
741 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
742 eprint("error, cannot allocate color '%s'\n", colstr);
750 unsigned char *p = NULL;
751 unsigned long n, extra;
754 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
755 &real, &format, &n, &extra, (unsigned char **)&p);
756 if(status != Success)
765 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
770 if(!text || size == 0)
773 XGetTextProperty(dpy, w, &name, atom);
776 if(name.encoding == XA_STRING)
777 strncpy(text, (char *)name.value, size - 1);
779 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
781 strncpy(text, *list, size - 1);
782 XFreeStringList(list);
785 text[size - 1] = '\0';
791 grabbuttons(Client *c, Bool focused) {
792 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
795 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
796 GrabModeAsync, GrabModeSync, None, None);
797 XGrabButton(dpy, Button1, MODKEY|LockMask, c->win, False, BUTTONMASK,
798 GrabModeAsync, GrabModeSync, None, None);
799 XGrabButton(dpy, Button1, MODKEY|numlockmask, c->win, False, BUTTONMASK,
800 GrabModeAsync, GrabModeSync, None, None);
801 XGrabButton(dpy, Button1, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
802 GrabModeAsync, GrabModeSync, None, None);
804 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
805 GrabModeAsync, GrabModeSync, None, None);
806 XGrabButton(dpy, Button2, MODKEY|LockMask, c->win, False, BUTTONMASK,
807 GrabModeAsync, GrabModeSync, None, None);
808 XGrabButton(dpy, Button2, MODKEY|numlockmask, c->win, False, BUTTONMASK,
809 GrabModeAsync, GrabModeSync, None, None);
810 XGrabButton(dpy, Button2, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
811 GrabModeAsync, GrabModeSync, None, None);
813 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
814 GrabModeAsync, GrabModeSync, None, None);
815 XGrabButton(dpy, Button3, MODKEY|LockMask, c->win, False, BUTTONMASK,
816 GrabModeAsync, GrabModeSync, None, None);
817 XGrabButton(dpy, Button3, MODKEY|numlockmask, c->win, False, BUTTONMASK,
818 GrabModeAsync, GrabModeSync, None, None);
819 XGrabButton(dpy, Button3, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
820 GrabModeAsync, GrabModeSync, None, None);
823 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
824 GrabModeAsync, GrabModeSync, None, None);
831 XModifierKeymap *modmap;
833 /* init modifier map */
834 modmap = XGetModifierMapping(dpy);
835 for(i = 0; i < 8; i++)
836 for(j = 0; j < modmap->max_keypermod; j++) {
837 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
838 numlockmask = (1 << i);
840 XFreeModifiermap(modmap);
842 XUngrabKey(dpy, AnyKey, AnyModifier, root);
843 for(i = 0; i < LENGTH(keys); i++) {
844 code = XKeysymToKeycode(dpy, keys[i].keysym);
845 XGrabKey(dpy, code, keys[i].mod, root, True,
846 GrabModeAsync, GrabModeAsync);
847 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
848 GrabModeAsync, GrabModeAsync);
849 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
850 GrabModeAsync, GrabModeAsync);
851 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
852 GrabModeAsync, GrabModeAsync);
857 idxoftag(const char *t) {
860 for(i = 0; (i < LENGTH(tags)) && strcmp(tags[i], t); i++);
861 return (i < LENGTH(tags)) ? i : 0;
865 initfont(const char *fontstr) {
866 char *def, **missing;
871 XFreeFontSet(dpy, dc.font.set);
872 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
875 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
876 XFreeStringList(missing);
879 XFontSetExtents *font_extents;
880 XFontStruct **xfonts;
882 dc.font.ascent = dc.font.descent = 0;
883 font_extents = XExtentsOfFontSet(dc.font.set);
884 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
885 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
886 if(dc.font.ascent < (*xfonts)->ascent)
887 dc.font.ascent = (*xfonts)->ascent;
888 if(dc.font.descent < (*xfonts)->descent)
889 dc.font.descent = (*xfonts)->descent;
895 XFreeFont(dpy, dc.font.xfont);
896 dc.font.xfont = NULL;
897 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
898 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
899 eprint("error, cannot load font: '%s'\n", fontstr);
900 dc.font.ascent = dc.font.xfont->ascent;
901 dc.font.descent = dc.font.xfont->descent;
903 dc.font.height = dc.font.ascent + dc.font.descent;
907 isoccupied(unsigned int t) {
910 for(c = clients; c; c = c->next)
917 isprotodel(Client *c) {
922 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
923 for(i = 0; !ret && i < n; i++)
924 if(protocols[i] == wmatom[WMDelete])
932 isurgent(unsigned int t) {
935 for(c = clients; c; c = c->next)
936 if(c->isurgent && c->tags[t])
942 isvisible(Client *c) {
945 for(i = 0; i < LENGTH(tags); i++)
946 if(c->tags[i] && seltags[i])
952 keypress(XEvent *e) {
958 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
959 for(i = 0; i < LENGTH(keys); i++)
960 if(keysym == keys[i].keysym
961 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
964 keys[i].func(keys[i].arg);
969 killclient(const char *arg) {
974 if(isprotodel(sel)) {
975 ev.type = ClientMessage;
976 ev.xclient.window = sel->win;
977 ev.xclient.message_type = wmatom[WMProtocols];
978 ev.xclient.format = 32;
979 ev.xclient.data.l[0] = wmatom[WMDelete];
980 ev.xclient.data.l[1] = CurrentTime;
981 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
984 XKillClient(dpy, sel->win);
988 manage(Window w, XWindowAttributes *wa) {
989 Client *c, *t = NULL;
994 c = emallocz(sizeof(Client));
995 c->tags = emallocz(TAGSZ);
1003 c->oldborder = wa->border_width;
1004 if(c->w == sw && c->h == sh) {
1007 c->border = wa->border_width;
1010 if(c->x + c->w + 2 * c->border > wx + ww)
1011 c->x = wx + ww - c->w - 2 * c->border;
1012 if(c->y + c->h + 2 * c->border > wy + wh)
1013 c->y = wy + wh - c->h - 2 * c->border;
1018 c->border = BORDERPX;
1021 wc.border_width = c->border;
1022 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1023 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1024 configure(c); /* propagates border_width, if size doesn't change */
1026 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
1027 grabbuttons(c, False);
1029 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
1030 for(t = clients; t && t->win != trans; t = t->next);
1032 memcpy(c->tags, t->tags, TAGSZ);
1036 c->isfloating = (rettrans == Success) || c->isfixed;
1039 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
1041 XMapWindow(dpy, c->win);
1042 setclientstate(c, NormalState);
1047 mappingnotify(XEvent *e) {
1048 XMappingEvent *ev = &e->xmapping;
1050 XRefreshKeyboardMapping(ev);
1051 if(ev->request == MappingKeyboard)
1056 maprequest(XEvent *e) {
1057 static XWindowAttributes wa;
1058 XMapRequestEvent *ev = &e->xmaprequest;
1060 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1062 if(wa.override_redirect)
1064 if(!getclient(ev->window))
1065 manage(ev->window, &wa);
1072 for(c = clients; c; c = c->next)
1074 resize(c, mox, moy, mow, moh, RESIZEHINTS);
1078 movemouse(Client *c) {
1079 int x1, y1, ocx, ocy, di, nx, ny;
1086 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1087 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1089 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1091 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1094 XUngrabPointer(dpy, CurrentTime);
1096 case ConfigureRequest:
1099 handler[ev.type](&ev);
1103 nx = ocx + (ev.xmotion.x - x1);
1104 ny = ocy + (ev.xmotion.y - y1);
1105 if(abs(wx - nx) < SNAP)
1107 else if(abs((wx + ww) - (nx + c->w + 2 * c->border)) < SNAP)
1108 nx = wx + ww - c->w - 2 * c->border;
1109 if(abs(wy - ny) < SNAP)
1111 else if(abs((wy + wh) - (ny + c->h + 2 * c->border)) < SNAP)
1112 ny = wy + wh - c->h - 2 * c->border;
1113 if(!c->isfloating && !lt->isfloating && (abs(nx - c->x) > SNAP || abs(ny - c->y) > SNAP))
1114 togglefloating(NULL);
1115 if((lt->isfloating) || c->isfloating)
1116 resize(c, nx, ny, c->w, c->h, False);
1123 nexttiled(Client *c) {
1124 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1129 propertynotify(XEvent *e) {
1132 XPropertyEvent *ev = &e->xproperty;
1134 if(ev->state == PropertyDelete)
1135 return; /* ignore */
1136 if((c = getclient(ev->window))) {
1139 case XA_WM_TRANSIENT_FOR:
1140 XGetTransientForHint(dpy, c->win, &trans);
1141 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1144 case XA_WM_NORMAL_HINTS:
1152 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1161 quit(const char *arg) {
1162 readin = running = False;
1166 reapply(const char *arg) {
1167 static Bool zerotags[LENGTH(tags)] = { 0 };
1170 for(c = clients; c; c = c->next) {
1171 memcpy(c->tags, zerotags, sizeof zerotags);
1178 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1182 /* set minimum possible */
1188 /* temporarily remove base dimensions */
1192 /* adjust for aspect limits */
1193 if (c->minay > 0 && c->maxay > 0 && c->minax > 0 && c->maxax > 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->border;
1224 y = sh - h - 2 * c->border;
1225 if(x + w + 2 * c->border < sx)
1227 if(y + h + 2 * c->border < 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->border;
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->border - 1, c->h + c->border - 1);
1255 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1258 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1259 c->w + c->border - 1, c->h + c->border - 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->border + 1) <= 0)
1272 if((nh = ev.xmotion.y - ocy - 2 * c->border + 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) {
1411 for(i = 0; arg && i < LENGTH(geoms); i++)
1412 if(!strcmp(geoms[i].symbol, arg))
1414 if(i == LENGTH(geoms))
1423 setlayout(const char *arg) {
1424 static Layout *revert = 0;
1429 for(i = 0; i < LENGTH(layouts); i++)
1430 if(!strcmp(arg, layouts[i].symbol))
1432 if(i == LENGTH(layouts))
1434 if(revert && &layouts[i] == lt)
1449 XSetWindowAttributes wa;
1452 screen = DefaultScreen(dpy);
1453 root = RootWindow(dpy, screen);
1456 /* apply default geometry */
1459 sw = DisplayWidth(dpy, screen);
1460 sh = DisplayHeight(dpy, screen);
1461 bh = dc.font.height + 2;
1466 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1467 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1468 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1469 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1470 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1471 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1474 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1475 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1476 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1478 /* init appearance */
1479 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1480 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1481 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1482 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1483 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1484 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1487 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1488 dc.gc = XCreateGC(dpy, root, 0, 0);
1489 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1491 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1494 seltags = emallocz(TAGSZ);
1495 prevtags = emallocz(TAGSZ);
1496 seltags[0] = prevtags[0] = True;
1502 for(blw = i = 0; i < LENGTH(layouts); i++) {
1503 i = textw(layouts[i].symbol);
1507 for(bgw = i = 0; i < LENGTH(geoms); i++) {
1508 i = textw(geoms[i].symbol);
1513 wa.override_redirect = 1;
1514 wa.background_pixmap = ParentRelative;
1515 wa.event_mask = ButtonPressMask|ExposureMask;
1517 barwin = XCreateWindow(dpy, root, bx, by, bw, bh, 0, DefaultDepth(dpy, screen),
1518 CopyFromParent, DefaultVisual(dpy, screen),
1519 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1520 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1521 XMapRaised(dpy, barwin);
1522 strcpy(stext, "dwm-"VERSION);
1525 /* EWMH support per view */
1526 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1527 PropModeReplace, (unsigned char *) netatom, NetLast);
1529 /* select for events */
1530 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1531 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1532 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1533 XSelectInput(dpy, root, wa.event_mask);
1541 spawn(const char *arg) {
1542 static char *shell = NULL;
1544 if(!shell && !(shell = getenv("SHELL")))
1548 /* The double-fork construct avoids zombie processes and keeps the code
1549 * clean from stupid signal handlers. */
1553 close(ConnectionNumber(dpy));
1555 execl(shell, shell, "-c", arg, (char *)NULL);
1556 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1565 tag(const char *arg) {
1570 for(i = 0; i < LENGTH(tags); i++)
1571 sel->tags[i] = (NULL == arg);
1572 sel->tags[idxoftag(arg)] = True;
1577 textnw(const char *text, unsigned int len) {
1581 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1584 return XTextWidth(dc.font.xfont, text, len);
1588 textw(const char *text) {
1589 return textnw(text, strlen(text)) + dc.font.height;
1595 unsigned int i, n = counttiled();
1609 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1610 if(i + 1 == n) /* remainder */
1611 tileresize(c, x, ty, (tx + tw) - x - 2 * c->border, th - 2 * c->border);
1613 tileresize(c, x, ty, w - 2 * c->border, th - 2 * c->border);
1615 x = c->x + c->w + 2 * c->border;
1620 tilemaster(unsigned int n) {
1621 Client *c = nexttiled(clients);
1624 tileresize(c, mox, moy, mow - 2 * c->border, moh - 2 * c->border);
1626 tileresize(c, mx, my, mw - 2 * c->border, mh - 2 * c->border);
1631 tileresize(Client *c, int x, int y, int w, int h) {
1632 resize(c, x, y, w, h, RESIZEHINTS);
1633 if((RESIZEHINTS) && ((c->h < bh) || (c->h > h) || (c->w < bh) || (c->w > w)))
1634 /* client doesn't accept size constraints */
1635 resize(c, x, y, w, h, False);
1641 unsigned int i, n = counttiled();
1655 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1656 if(i + 1 == n) /* remainder */
1657 tileresize(c, tx, y, tw - 2 * c->border, (ty + th) - y - 2 * c->border);
1659 tileresize(c, tx, y, tw - 2 * c->border, h - 2 * c->border);
1661 y = c->y + c->h + 2 * c->border;
1666 togglefloating(const char *arg) {
1669 sel->isfloating = !sel->isfloating;
1671 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1676 toggletag(const char *arg) {
1682 sel->tags[i] = !sel->tags[i];
1683 for(j = 0; j < LENGTH(tags) && !sel->tags[j]; j++);
1684 if(j == LENGTH(tags))
1685 sel->tags[i] = True; /* at least one tag must be enabled */
1690 toggleview(const char *arg) {
1694 seltags[i] = !seltags[i];
1695 for(j = 0; j < LENGTH(tags) && !seltags[j]; j++);
1696 if(j == LENGTH(tags))
1697 seltags[i] = True; /* at least one tag must be viewed */
1705 XMoveWindow(dpy, c->win, c->x, c->y);
1706 c->isbanned = False;
1710 unmanage(Client *c) {
1713 wc.border_width = c->oldborder;
1714 /* The server grab construct avoids race conditions. */
1716 XSetErrorHandler(xerrordummy);
1717 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1722 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1723 setclientstate(c, WithdrawnState);
1727 XSetErrorHandler(xerror);
1733 unmapnotify(XEvent *e) {
1735 XUnmapEvent *ev = &e->xunmap;
1737 if((c = getclient(ev->window)))
1742 updatebarpos(void) {
1744 if(dc.drawable != 0)
1745 XFreePixmap(dpy, dc.drawable);
1746 dc.drawable = XCreatePixmap(dpy, root, bw, bh, DefaultDepth(dpy, screen));
1747 XMoveResizeWindow(dpy, barwin, bx, by, bw, bh);
1751 updatesizehints(Client *c) {
1755 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1757 c->flags = size.flags;
1758 if(c->flags & PBaseSize) {
1759 c->basew = size.base_width;
1760 c->baseh = size.base_height;
1762 else if(c->flags & PMinSize) {
1763 c->basew = size.min_width;
1764 c->baseh = size.min_height;
1767 c->basew = c->baseh = 0;
1768 if(c->flags & PResizeInc) {
1769 c->incw = size.width_inc;
1770 c->inch = size.height_inc;
1773 c->incw = c->inch = 0;
1774 if(c->flags & PMaxSize) {
1775 c->maxw = size.max_width;
1776 c->maxh = size.max_height;
1779 c->maxw = c->maxh = 0;
1780 if(c->flags & PMinSize) {
1781 c->minw = size.min_width;
1782 c->minh = size.min_height;
1784 else if(c->flags & PBaseSize) {
1785 c->minw = size.base_width;
1786 c->minh = size.base_height;
1789 c->minw = c->minh = 0;
1790 if(c->flags & PAspect) {
1791 c->minax = size.min_aspect.x;
1792 c->maxax = size.max_aspect.x;
1793 c->minay = size.min_aspect.y;
1794 c->maxay = size.max_aspect.y;
1797 c->minax = c->maxax = c->minay = c->maxay = 0;
1798 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1799 && c->maxw == c->minw && c->maxh == c->minh);
1803 updatetitle(Client *c) {
1804 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1805 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1809 updatewmhints(Client *c) {
1812 if((wmh = XGetWMHints(dpy, c->win))) {
1814 sel->isurgent = False;
1816 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1823 view(const char *arg) {
1826 for(i = 0; i < LENGTH(tags); i++)
1827 tmp[i] = (NULL == arg);
1828 tmp[idxoftag(arg)] = True;
1830 if(memcmp(seltags, tmp, TAGSZ) != 0) {
1831 memcpy(prevtags, seltags, TAGSZ);
1832 memcpy(seltags, tmp, TAGSZ);
1838 viewprevtag(const char *arg) {
1840 memcpy(tmp, seltags, TAGSZ);
1841 memcpy(seltags, prevtags, TAGSZ);
1842 memcpy(prevtags, tmp, TAGSZ);
1846 /* There's no way to check accesses to destroyed windows, thus those cases are
1847 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1848 * default error handler, which may call exit. */
1850 xerror(Display *dpy, XErrorEvent *ee) {
1851 if(ee->error_code == BadWindow
1852 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1853 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1854 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1855 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1856 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1857 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1858 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1860 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1861 ee->request_code, ee->error_code);
1862 return xerrorxlib(dpy, ee); /* may call exit */
1866 xerrordummy(Display *dpy, XErrorEvent *ee) {
1870 /* Startup Error handler to check if another window manager
1871 * is already running. */
1873 xerrorstart(Display *dpy, XErrorEvent *ee) {
1879 zoom(const char *arg) {
1882 if(!sel || lt->isfloating || sel->isfloating)
1884 if(c == nexttiled(clients))
1885 if(!(c = nexttiled(c->next)))
1894 main(int argc, char *argv[]) {
1895 if(argc == 2 && !strcmp("-v", argv[1]))
1896 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1898 eprint("usage: dwm [-v]\n");
1900 setlocale(LC_CTYPE, "");
1901 if(!(dpy = XOpenDisplay(0)))
1902 eprint("dwm: cannot open display\n");