1 /* See LICENSE file for copyright and license details.
3 * dynamic window manager is designed like any other X client as well. It is
4 * driven through handling X events. In contrast to other X clients, a window
5 * manager selects for SubstructureRedirectMask on the root window, to receive
6 * events about window (dis-)appearance. Only one X connection at a time is
7 * allowed to select for this event mask.
9 * Calls to fetch an X event from the event queue are blocking. Due reading
10 * status text from standard input, a select()-driven main loop has been
11 * implemented which selects for reads on the X connection and STDIN_FILENO to
12 * handle all data smoothly. The event handlers of dwm are organized in an
13 * array which is accessed whenever a new event has been fetched. This allows
14 * event dispatching in O(1) time.
16 * Each child of the root window is called a client, except windows which have
17 * set the override_redirect flag. Clients are organized in a global
18 * doubly-linked client list, the focus history is remembered through a global
19 * stack list. Each client contains an array of Bools of the same size as the
20 * global tags array to indicate the tags of a client.
22 * Keys and tagging rules are organized as arrays and defined in config.h.
24 * To understand everything else, start reading main().
33 #include <sys/select.h>
34 #include <sys/types.h>
36 #include <X11/cursorfont.h>
37 #include <X11/keysym.h>
38 #include <X11/Xatom.h>
40 #include <X11/Xproto.h>
41 #include <X11/Xutil.h>
44 #define MAX(a, b) ((a)>(b)?(a):(b))
45 #define MIN(a, b) ((a)<(b)?(a):(b))
46 #define BUTTONMASK (ButtonPressMask|ButtonReleaseMask)
47 #define CLEANMASK(mask) (mask & ~(numlockmask|LockMask))
48 #define LENGTH(x) (sizeof x / sizeof x[0])
50 #define MOUSEMASK (BUTTONMASK|PointerMotionMask)
51 #define DEFGEOM(GEONAME,BX,BY,BW,WX,WY,WW,WH,MX,MY,MW,MH,TX,TY,TW,TH,MOX,MOY,MOW,MOH) \
52 void GEONAME(void) { \
53 bx = (BX); by = (BY); bw = (BW); \
54 wx = (WX); wy = (WY); ww = (WW); wh = (WH); \
55 mx = (MX); my = (MY); mw = (MW); mh = (MH); \
56 tx = (TX); ty = (TY); tw = (TW); th = (TH); \
57 mox = (MOX); moy = (MOY); mow = (MOW); moh = (MOH); \
61 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
62 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
63 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
64 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
67 typedef struct Client Client;
71 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
72 int minax, maxax, minay, maxay;
74 unsigned int bw, oldbw;
75 Bool isbanned, isfixed, isfloating, isurgent;
85 unsigned long norm[ColLast];
86 unsigned long sel[ColLast];
96 } DC; /* draw context */
106 void (*func)(const char *arg);
112 void (*arrange)(void);
118 const char *instance;
124 /* function declarations */
125 void applyrules(Client *c);
127 void attach(Client *c);
128 void attachstack(Client *c);
130 void buttonpress(XEvent *e);
131 void checkotherwm(void);
133 void configure(Client *c);
134 void configurenotify(XEvent *e);
135 void configurerequest(XEvent *e);
136 unsigned int counttiled(void);
137 void destroynotify(XEvent *e);
138 void detach(Client *c);
139 void detachstack(Client *c);
141 void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
142 void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
143 void *emallocz(unsigned int size);
144 void enternotify(XEvent *e);
145 void eprint(const char *errstr, ...);
146 void expose(XEvent *e);
147 void floating(void); /* default floating layout */
148 void focus(Client *c);
149 void focusin(XEvent *e);
150 void focusnext(const char *arg);
151 void focusprev(const char *arg);
152 Client *getclient(Window w);
153 unsigned long getcolor(const char *colstr);
154 long getstate(Window w);
155 Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
156 void grabbuttons(Client *c, Bool focused);
158 unsigned int idxoftag(const char *t);
159 void initfont(const char *fontstr);
160 Bool isoccupied(unsigned int t);
161 Bool isprotodel(Client *c);
162 Bool isurgent(unsigned int t);
163 Bool isvisible(Client *c);
164 void keypress(XEvent *e);
165 void killclient(const char *arg);
166 void manage(Window w, XWindowAttributes *wa);
167 void mappingnotify(XEvent *e);
168 void maprequest(XEvent *e);
170 void movemouse(Client *c);
171 Client *nexttiled(Client *c);
172 void propertynotify(XEvent *e);
173 void quit(const char *arg);
174 void reapply(const char *arg);
175 void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
176 void resizemouse(Client *c);
180 void setclientstate(Client *c, long state);
181 void setgeom(const char *arg);
182 void setlayout(const char *arg);
183 void setmfact(const char *arg);
185 void spawn(const char *arg);
186 void tag(const char *arg);
187 unsigned int textnw(const char *text, unsigned int len);
188 unsigned int textw(const char *text);
190 void tilehstack(unsigned int n);
191 Client *tilemaster(unsigned int n);
192 void tileresize(Client *c, int x, int y, int w, int h);
194 void tilevstack(unsigned int n);
195 void togglefloating(const char *arg);
196 void toggletag(const char *arg);
197 void toggleview(const char *arg);
198 void unban(Client *c);
199 void unmanage(Client *c);
200 void unmapnotify(XEvent *e);
201 void updatebarpos(void);
202 void updatesizehints(Client *c);
203 void updatetitle(Client *c);
204 void updatewmhints(Client *c);
205 void view(const char *arg);
206 void viewprevtag(const char *arg); /* views previous selected tags */
207 int xerror(Display *dpy, XErrorEvent *ee);
208 int xerrordummy(Display *dpy, XErrorEvent *ee);
209 int xerrorstart(Display *dpy, XErrorEvent *ee);
210 void zoom(const char *arg);
214 int screen, sx, sy, sw, sh;
215 int (*xerrorxlib)(Display *, XErrorEvent *);
216 int bx, by, bw, bh, blw, bgw, mx, my, mw, mh, mox, moy, mow, moh, tx, ty, tw, th, wx, wy, ww, wh;
217 int viewtags_set = 0;
219 unsigned int numlockmask = 0;
220 void (*handler[LASTEvent]) (XEvent *) = {
221 [ButtonPress] = buttonpress,
222 [ConfigureRequest] = configurerequest,
223 [ConfigureNotify] = configurenotify,
224 [DestroyNotify] = destroynotify,
225 [EnterNotify] = enternotify,
228 [KeyPress] = keypress,
229 [MappingNotify] = mappingnotify,
230 [MapRequest] = maprequest,
231 [PropertyNotify] = propertynotify,
232 [UnmapNotify] = unmapnotify
234 Atom wmatom[WMLast], netatom[NetLast];
235 Bool otherwm, readin;
239 Client *clients = NULL;
241 Client *stack = NULL;
242 Cursor cursor[CurLast];
247 /* configuration, allows nested code to access above variables */
249 #define TAGSZ (LENGTH(tags) * sizeof(Bool))
250 Layout *lt = layouts;
253 /* function implementations */
256 applyrules(Client *c) {
258 Bool matched = False;
260 XClassHint ch = { 0 };
263 XGetClassHint(dpy, c->win, &ch);
264 for(i = 0; i < LENGTH(rules); i++) {
266 if((!r->title || strstr(c->name, r->title))
267 && (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
268 && (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
269 c->isfloating = r->isfloating;
271 c->tags[idxoftag(r->tag)] = True;
281 memcpy(c->tags, seltags, TAGSZ);
288 for(c = clients; c; c = c->next)
308 attachstack(Client *c) {
317 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
322 buttonpress(XEvent *e) {
325 XButtonPressedEvent *ev = &e->xbutton;
327 if(ev->window == barwin) {
328 if((ev->x < bgw) && ev->button == Button1) {
333 for(i = 0; i < LENGTH(tags); i++) {
335 if(ev->x >= bgw && ev->x < x) {
336 if(ev->button == Button1) {
337 if(ev->state & MODKEY)
342 else if(ev->button == Button3) {
343 if(ev->state & MODKEY)
351 if((ev->x < x + blw) && ev->button == Button1)
354 else if((c = getclient(ev->window))) {
356 if(CLEANMASK(ev->state) != MODKEY)
358 if(ev->button == Button1) {
362 else if(ev->button == Button2) {
363 if((floating != lt->arrange) && c->isfloating)
364 togglefloating(NULL);
368 else if(ev->button == Button3 && !c->isfixed) {
378 XSetErrorHandler(xerrorstart);
380 /* this causes an error if some other window manager is running */
381 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
384 eprint("dwm: another window manager is already running\n");
386 XSetErrorHandler(NULL);
387 xerrorxlib = XSetErrorHandler(xerror);
399 XFreeFontSet(dpy, dc.font.set);
401 XFreeFont(dpy, dc.font.xfont);
402 XUngrabKey(dpy, AnyKey, AnyModifier, root);
403 XFreePixmap(dpy, dc.drawable);
405 XFreeCursor(dpy, cursor[CurNormal]);
406 XFreeCursor(dpy, cursor[CurResize]);
407 XFreeCursor(dpy, cursor[CurMove]);
408 XDestroyWindow(dpy, barwin);
410 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
414 configure(Client *c) {
417 ce.type = ConfigureNotify;
425 ce.border_width = c->bw;
427 ce.override_redirect = False;
428 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
432 configurenotify(XEvent *e) {
433 XConfigureEvent *ev = &e->xconfigure;
435 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
438 setgeom(geom->symbol);
443 configurerequest(XEvent *e) {
445 XConfigureRequestEvent *ev = &e->xconfigurerequest;
448 if((c = getclient(ev->window))) {
449 if(ev->value_mask & CWBorderWidth)
450 c->bw = ev->border_width;
451 if(c->isfixed || c->isfloating || lt->isfloating) {
452 if(ev->value_mask & CWX)
454 if(ev->value_mask & CWY)
456 if(ev->value_mask & CWWidth)
458 if(ev->value_mask & CWHeight)
460 if((c->x - sx + c->w) > sw && c->isfloating)
461 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
462 if((c->y - sy + c->h) > sh && c->isfloating)
463 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
464 if((ev->value_mask & (CWX|CWY))
465 && !(ev->value_mask & (CWWidth|CWHeight)))
468 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
476 wc.width = ev->width;
477 wc.height = ev->height;
478 wc.border_width = ev->border_width;
479 wc.sibling = ev->above;
480 wc.stack_mode = ev->detail;
481 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
491 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next), n++);
496 destroynotify(XEvent *e) {
498 XDestroyWindowEvent *ev = &e->xdestroywindow;
500 if((c = getclient(ev->window)))
507 c->prev->next = c->next;
509 c->next->prev = c->prev;
512 c->next = c->prev = NULL;
516 detachstack(Client *c) {
519 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
531 drawtext(geom->symbol, dc.norm, False);
534 for(c = stack; c && !isvisible(c); c = c->snext);
535 for(i = 0; i < LENGTH(tags); i++) {
536 dc.w = textw(tags[i]);
538 drawtext(tags[i], dc.sel, isurgent(i));
539 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.sel);
542 drawtext(tags[i], dc.norm, isurgent(i));
543 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.norm);
549 drawtext(lt->symbol, dc.norm, False);
560 drawtext(stext, dc.norm, False);
561 if((dc.w = dc.x - x) > bh) {
564 drawtext(c->name, dc.sel, False);
565 drawsquare(False, c->isfloating, False, dc.sel);
568 drawtext(NULL, dc.norm, False);
570 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, bw, bh, 0, 0);
575 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
578 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
580 gcv.foreground = col[invert ? ColBG : ColFG];
581 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
582 x = (dc.font.ascent + dc.font.descent + 2) / 4;
586 r.width = r.height = x + 1;
587 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
590 r.width = r.height = x;
591 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
596 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
598 unsigned int len, olen;
599 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
602 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
603 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
607 len = MIN(olen, sizeof buf);
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 for(; len && (w = textnw(buf, len)) > dc.w - h; len--);
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 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
884 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
890 XFreeFont(dpy, dc.font.xfont);
891 dc.font.xfont = NULL;
892 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
893 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
894 eprint("error, cannot load font: '%s'\n", fontstr);
895 dc.font.ascent = dc.font.xfont->ascent;
896 dc.font.descent = dc.font.xfont->descent;
898 dc.font.height = dc.font.ascent + dc.font.descent;
902 isoccupied(unsigned int t) {
905 for(c = clients; c; c = c->next)
912 isprotodel(Client *c) {
917 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
918 for(i = 0; !ret && i < n; i++)
919 if(protocols[i] == wmatom[WMDelete])
927 isurgent(unsigned int t) {
930 for(c = clients; c; c = c->next)
931 if(c->isurgent && c->tags[t])
937 isvisible(Client *c) {
940 for(i = 0; i < LENGTH(tags); i++)
941 if(c->tags[i] && seltags[i])
947 keypress(XEvent *e) {
953 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
954 for(i = 0; i < LENGTH(keys); i++)
955 if(keysym == keys[i].keysym
956 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
959 keys[i].func(keys[i].arg);
964 killclient(const char *arg) {
969 if(isprotodel(sel)) {
970 ev.type = ClientMessage;
971 ev.xclient.window = sel->win;
972 ev.xclient.message_type = wmatom[WMProtocols];
973 ev.xclient.format = 32;
974 ev.xclient.data.l[0] = wmatom[WMDelete];
975 ev.xclient.data.l[1] = CurrentTime;
976 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
979 XKillClient(dpy, sel->win);
983 manage(Window w, XWindowAttributes *wa) {
984 Client *c, *t = NULL;
989 c = emallocz(sizeof(Client));
990 c->tags = emallocz(TAGSZ);
998 c->oldbw = wa->border_width;
999 if(c->w == sw && c->h == sh) {
1002 c->bw = wa->border_width;
1005 if(c->x + c->w + 2 * c->bw > wx + ww)
1006 c->x = wx + ww - c->w - 2 * c->bw;
1007 if(c->y + c->h + 2 * c->bw > wy + wh)
1008 c->y = wy + wh - c->h - 2 * c->bw;
1009 c->x = MAX(c->x, wx);
1010 c->y = MAX(c->y, wy);
1014 wc.border_width = c->bw;
1015 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1016 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1017 configure(c); /* propagates border_width, if size doesn't change */
1019 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
1020 grabbuttons(c, False);
1022 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
1023 for(t = clients; t && t->win != trans; t = t->next);
1025 memcpy(c->tags, t->tags, TAGSZ);
1029 c->isfloating = (rettrans == Success) || c->isfixed;
1032 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
1034 XMapWindow(dpy, c->win);
1035 setclientstate(c, NormalState);
1040 mappingnotify(XEvent *e) {
1041 XMappingEvent *ev = &e->xmapping;
1043 XRefreshKeyboardMapping(ev);
1044 if(ev->request == MappingKeyboard)
1049 maprequest(XEvent *e) {
1050 static XWindowAttributes wa;
1051 XMapRequestEvent *ev = &e->xmaprequest;
1053 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1055 if(wa.override_redirect)
1057 if(!getclient(ev->window))
1058 manage(ev->window, &wa);
1065 for(c = clients; c; c = c->next)
1066 if((lt->isfloating || !c->isfloating) && isvisible(c))
1067 resize(c, mox, moy, mow - 2 * c->bw, moh - 2 * c->bw, RESIZEHINTS);
1071 movemouse(Client *c) {
1072 int x1, y1, ocx, ocy, di, nx, ny;
1079 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1080 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1082 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1084 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1087 XUngrabPointer(dpy, CurrentTime);
1089 case ConfigureRequest:
1092 handler[ev.type](&ev);
1096 nx = ocx + (ev.xmotion.x - x1);
1097 ny = ocy + (ev.xmotion.y - y1);
1098 if(abs(wx - nx) < SNAP)
1100 else if(abs((wx + ww) - (nx + c->w + 2 * c->bw)) < SNAP)
1101 nx = wx + ww - c->w - 2 * c->bw;
1102 if(abs(wy - ny) < SNAP)
1104 else if(abs((wy + wh) - (ny + c->h + 2 * c->bw)) < SNAP)
1105 ny = wy + wh - c->h - 2 * c->bw;
1106 if(!c->isfloating && !lt->isfloating && (abs(nx - c->x) > SNAP || abs(ny - c->y) > SNAP))
1107 togglefloating(NULL);
1108 if((lt->isfloating) || c->isfloating)
1109 resize(c, nx, ny, c->w, c->h, False);
1116 nexttiled(Client *c) {
1117 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1122 propertynotify(XEvent *e) {
1125 XPropertyEvent *ev = &e->xproperty;
1127 if(ev->state == PropertyDelete)
1128 return; /* ignore */
1129 if((c = getclient(ev->window))) {
1132 case XA_WM_TRANSIENT_FOR:
1133 XGetTransientForHint(dpy, c->win, &trans);
1134 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1137 case XA_WM_NORMAL_HINTS:
1145 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1154 quit(const char *arg) {
1155 readin = running = False;
1159 reapply(const char *arg) {
1162 for(c = clients; c; c = c->next) {
1163 memset(c->tags, 0, TAGSZ);
1170 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1174 /* set minimum possible */
1178 /* temporarily remove base dimensions */
1182 /* adjust for aspect limits */
1183 if(c->minax != c->maxax && c->minay != c->maxay
1184 && c->minax > 0 && c->maxax > 0 && c->minay > 0 && c->maxay > 0)
1186 if(w * c->maxay > h * c->maxax)
1187 w = h * c->maxax / c->maxay;
1188 else if(w * c->minay < h * c->minax)
1189 h = w * c->minay / c->minax;
1192 /* adjust for increment value */
1198 /* restore base dimensions */
1202 w = MAX(w, c->minw);
1203 h = MAX(h, c->minh);
1206 w = MIN(w, c->maxw);
1209 h = MIN(h, c->maxh);
1211 if(w <= 0 || h <= 0)
1214 x = sw - w - 2 * c->bw;
1216 y = sh - h - 2 * c->bw;
1217 if(x + w + 2 * c->bw < sx)
1219 if(y + h + 2 * c->bw < sy)
1221 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1224 c->w = wc.width = w;
1225 c->h = wc.height = h;
1226 wc.border_width = c->bw;
1227 XConfigureWindow(dpy, c->win,
1228 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1235 resizemouse(Client *c) {
1242 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1243 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1245 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1247 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1250 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1251 c->w + c->bw - 1, c->h + c->bw - 1);
1252 XUngrabPointer(dpy, CurrentTime);
1253 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1255 case ConfigureRequest:
1258 handler[ev.type](&ev);
1262 nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1263 nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1264 if(!c->isfloating && !lt->isfloating && (abs(nw - c->w) > SNAP || abs(nh - c->h) > SNAP))
1265 togglefloating(NULL);
1266 if((lt->isfloating) || c->isfloating)
1267 resize(c, c->x, c->y, nw, nh, True);
1282 if(sel->isfloating || lt->isfloating)
1283 XRaiseWindow(dpy, sel->win);
1284 if(!lt->isfloating) {
1285 wc.stack_mode = Below;
1286 wc.sibling = barwin;
1287 if(!sel->isfloating) {
1288 XConfigureWindow(dpy, sel->win, CWSibling|CWStackMode, &wc);
1289 wc.sibling = sel->win;
1291 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
1294 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1295 wc.sibling = c->win;
1299 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1305 char sbuf[sizeof stext];
1308 unsigned int len, offset;
1311 /* main event loop, also reads status text from stdin */
1313 xfd = ConnectionNumber(dpy);
1316 len = sizeof stext - 1;
1317 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1321 FD_SET(STDIN_FILENO, &rd);
1323 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1326 eprint("select failed\n");
1328 if(FD_ISSET(STDIN_FILENO, &rd)) {
1329 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1331 strncpy(stext, strerror(errno), len);
1335 strncpy(stext, "EOF", 4);
1339 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1340 if(*p == '\n' || *p == '\0') {
1342 strncpy(stext, sbuf, len);
1343 p += r - 1; /* p is sbuf + offset + r - 1 */
1344 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1347 memmove(sbuf, p - r + 1, r);
1354 while(XPending(dpy)) {
1355 XNextEvent(dpy, &ev);
1356 if(handler[ev.type])
1357 (handler[ev.type])(&ev); /* call handler */
1364 unsigned int i, num;
1365 Window *wins, d1, d2;
1366 XWindowAttributes wa;
1369 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1370 for(i = 0; i < num; i++) {
1371 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1372 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1374 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1375 manage(wins[i], &wa);
1377 for(i = 0; i < num; i++) { /* now the transients */
1378 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1380 if(XGetTransientForHint(dpy, wins[i], &d1)
1381 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1382 manage(wins[i], &wa);
1390 setclientstate(Client *c, long state) {
1391 long data[] = {state, None};
1393 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1394 PropModeReplace, (unsigned char *)data, 2);
1398 setgeom(const char *arg) {
1402 if(++geom == &geoms[LENGTH(geoms)])
1406 for(i = 0; i < LENGTH(geoms); i++)
1407 if(!strcmp(geoms[i].symbol, arg))
1409 if(i == LENGTH(geoms))
1419 setlayout(const char *arg) {
1423 if(++lt == &layouts[LENGTH(layouts)])
1427 for(i = 0; i < LENGTH(layouts); i++)
1428 if(!strcmp(arg, layouts[i].symbol))
1430 if(i == LENGTH(layouts))
1441 setmfact(const char *arg) {
1449 d = strtod(arg, NULL);
1450 if(arg[0] == '-' || arg[0] == '+')
1452 if(d < 0.1 || d > 0.9)
1456 setgeom(geom->symbol);
1462 XSetWindowAttributes wa;
1465 screen = DefaultScreen(dpy);
1466 root = RootWindow(dpy, screen);
1469 /* apply default geometry */
1472 sw = DisplayWidth(dpy, screen);
1473 sh = DisplayHeight(dpy, screen);
1474 bh = dc.font.height + 2;
1479 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1480 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1481 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1482 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1483 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1484 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1487 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1488 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1489 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1491 /* init appearance */
1492 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1493 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1494 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1495 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1496 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1497 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1500 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1501 dc.gc = XCreateGC(dpy, root, 0, 0);
1502 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1504 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1507 viewtags[0] = emallocz(TAGSZ);
1508 viewtags[1] = emallocz(TAGSZ);
1509 viewtags[0][0] = viewtags[1][0] = True;
1510 seltags = viewtags[0];
1513 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1514 w = textw(layouts[i].symbol);
1517 for(bgw = i = 0; LENGTH(geoms) > 1 && i < LENGTH(geoms); i++) {
1518 w = textw(geoms[i].symbol);
1522 wa.override_redirect = 1;
1523 wa.background_pixmap = ParentRelative;
1524 wa.event_mask = ButtonPressMask|ExposureMask;
1526 barwin = XCreateWindow(dpy, root, bx, by, bw, bh, 0, DefaultDepth(dpy, screen),
1527 CopyFromParent, DefaultVisual(dpy, screen),
1528 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1529 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1530 XMapRaised(dpy, barwin);
1531 strcpy(stext, "dwm-"VERSION);
1534 /* EWMH support per view */
1535 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1536 PropModeReplace, (unsigned char *) netatom, NetLast);
1538 /* select for events */
1539 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1540 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1541 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1542 XSelectInput(dpy, root, wa.event_mask);
1550 spawn(const char *arg) {
1551 static char *shell = NULL;
1553 if(!shell && !(shell = getenv("SHELL")))
1557 /* The double-fork construct avoids zombie processes and keeps the code
1558 * clean from stupid signal handlers. */
1562 close(ConnectionNumber(dpy));
1564 execl(shell, shell, "-c", arg, (char *)NULL);
1565 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1574 tag(const char *arg) {
1579 for(i = 0; i < LENGTH(tags); i++)
1580 sel->tags[i] = (NULL == arg);
1581 sel->tags[idxoftag(arg)] = True;
1586 textnw(const char *text, unsigned int len) {
1590 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1593 return XTextWidth(dc.font.xfont, text, len);
1597 textw(const char *text) {
1598 return textnw(text, strlen(text)) + dc.font.height;
1604 unsigned int i, n = counttiled();
1618 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1619 if(i + 1 == n) /* remainder */
1620 tileresize(c, x, ty, (tx + tw) - x - 2 * c->bw, th - 2 * c->bw);
1622 tileresize(c, x, ty, w - 2 * c->bw, th - 2 * c->bw);
1624 x = c->x + c->w + 2 * c->bw;
1629 tilemaster(unsigned int n) {
1630 Client *c = nexttiled(clients);
1633 tileresize(c, mox, moy, mow - 2 * c->bw, moh - 2 * c->bw);
1635 tileresize(c, mx, my, mw - 2 * c->bw, mh - 2 * c->bw);
1640 tileresize(Client *c, int x, int y, int w, int h) {
1641 resize(c, x, y, w, h, RESIZEHINTS);
1642 if((RESIZEHINTS) && ((c->h < bh) || (c->h > h) || (c->w < bh) || (c->w > w)))
1643 /* client doesn't accept size constraints */
1644 resize(c, x, y, w, h, False);
1650 unsigned int i, n = counttiled();
1664 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1665 if(i + 1 == n) /* remainder */
1666 tileresize(c, tx, y, tw - 2 * c->bw, (ty + th) - y - 2 * c->bw);
1668 tileresize(c, tx, y, tw - 2 * c->bw, h - 2 * c->bw);
1670 y = c->y + c->h + 2 * c->bw;
1675 togglefloating(const char *arg) {
1678 sel->isfloating = !sel->isfloating;
1680 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1685 toggletag(const char *arg) {
1691 sel->tags[i] = !sel->tags[i];
1692 for(j = 0; j < LENGTH(tags) && !sel->tags[j]; j++);
1693 if(j == LENGTH(tags))
1694 sel->tags[i] = True; /* at least one tag must be enabled */
1699 toggleview(const char *arg) {
1703 seltags[i] = !seltags[i];
1704 for(j = 0; j < LENGTH(tags) && !seltags[j]; j++);
1705 if(j == LENGTH(tags))
1706 seltags[i] = True; /* at least one tag must be viewed */
1714 XMoveWindow(dpy, c->win, c->x, c->y);
1715 c->isbanned = False;
1719 unmanage(Client *c) {
1722 wc.border_width = c->oldbw;
1723 /* The server grab construct avoids race conditions. */
1725 XSetErrorHandler(xerrordummy);
1726 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1731 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1732 setclientstate(c, WithdrawnState);
1736 XSetErrorHandler(xerror);
1742 unmapnotify(XEvent *e) {
1744 XUnmapEvent *ev = &e->xunmap;
1746 if((c = getclient(ev->window)))
1751 updatebarpos(void) {
1753 if(dc.drawable != 0)
1754 XFreePixmap(dpy, dc.drawable);
1755 dc.drawable = XCreatePixmap(dpy, root, bw, bh, DefaultDepth(dpy, screen));
1756 XMoveResizeWindow(dpy, barwin, bx, by, bw, bh);
1760 updatesizehints(Client *c) {
1764 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1766 c->flags = size.flags;
1767 if(c->flags & PBaseSize) {
1768 c->basew = size.base_width;
1769 c->baseh = size.base_height;
1771 else if(c->flags & PMinSize) {
1772 c->basew = size.min_width;
1773 c->baseh = size.min_height;
1776 c->basew = c->baseh = 0;
1777 if(c->flags & PResizeInc) {
1778 c->incw = size.width_inc;
1779 c->inch = size.height_inc;
1782 c->incw = c->inch = 0;
1783 if(c->flags & PMaxSize) {
1784 c->maxw = size.max_width;
1785 c->maxh = size.max_height;
1788 c->maxw = c->maxh = 0;
1789 if(c->flags & PMinSize) {
1790 c->minw = size.min_width;
1791 c->minh = size.min_height;
1793 else if(c->flags & PBaseSize) {
1794 c->minw = size.base_width;
1795 c->minh = size.base_height;
1798 c->minw = c->minh = 0;
1799 if(c->flags & PAspect) {
1800 c->minax = size.min_aspect.x;
1801 c->maxax = size.max_aspect.x;
1802 c->minay = size.min_aspect.y;
1803 c->maxay = size.max_aspect.y;
1806 c->minax = c->maxax = c->minay = c->maxay = 0;
1807 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1808 && c->maxw == c->minw && c->maxh == c->minh);
1812 updatetitle(Client *c) {
1813 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1814 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1818 updatewmhints(Client *c) {
1821 if((wmh = XGetWMHints(dpy, c->win))) {
1823 sel->isurgent = False;
1825 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1831 view(const char *arg) {
1832 Bool tmp[LENGTH(tags)];
1835 for(i = 0; i < LENGTH(tags); i++)
1836 tmp[i] = (NULL == arg);
1837 tmp[idxoftag(arg)] = True;
1839 if(memcmp(seltags, tmp, TAGSZ) != 0) {
1840 seltags = viewtags[viewtags_set ^= 1]; /* toggle tagset */
1841 memcpy(seltags, tmp, TAGSZ);
1847 viewprevtag(const char *arg) {
1848 seltags = viewtags[viewtags_set ^= 1]; /* toggle tagset */
1852 /* There's no way to check accesses to destroyed windows, thus those cases are
1853 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1854 * default error handler, which may call exit. */
1856 xerror(Display *dpy, XErrorEvent *ee) {
1857 if(ee->error_code == BadWindow
1858 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1859 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1860 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1861 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1862 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1863 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1864 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1866 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1867 ee->request_code, ee->error_code);
1868 return xerrorxlib(dpy, ee); /* may call exit */
1872 xerrordummy(Display *dpy, XErrorEvent *ee) {
1876 /* Startup Error handler to check if another window manager
1877 * is already running. */
1879 xerrorstart(Display *dpy, XErrorEvent *ee) {
1885 zoom(const char *arg) {
1888 if(!sel || lt->isfloating || sel->isfloating)
1890 if(c == nexttiled(clients))
1891 if(!(c = nexttiled(c->next)))
1900 main(int argc, char *argv[]) {
1901 if(argc == 2 && !strcmp("-v", argv[1]))
1902 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1904 eprint("usage: dwm [-v]\n");
1906 setlocale(LC_CTYPE, "");
1907 if(!(dpy = XOpenDisplay(0)))
1908 eprint("dwm: cannot open display\n");