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>
43 #include <X11/extensions/Xinerama.h>
47 #define MAX(a, b) ((a) > (b) ? (a) : (b))
48 #define MIN(a, b) ((a) < (b) ? (a) : (b))
49 #define BUTTONMASK (ButtonPressMask|ButtonReleaseMask)
50 #define CLEANMASK(mask) (mask & ~(numlockmask|LockMask))
51 #define LENGTH(x) (sizeof x / sizeof x[0])
53 #define MOUSEMASK (BUTTONMASK|PointerMotionMask)
56 enum { BarTop, BarBot, BarOff, BarLast }; /* bar appearance */
57 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
58 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
59 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
60 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
63 typedef struct Client Client;
67 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
68 int minax, maxax, minay, maxay;
70 unsigned int bw, oldbw;
71 Bool isbanned, isfixed, isfloating, isurgent;
81 unsigned long norm[ColLast];
82 unsigned long sel[ColLast];
92 } DC; /* draw context */
97 void (*func)(const char *arg);
103 void (*arrange)(void);
104 void (*updategeom)(void);
109 const char *instance;
115 /* function declarations */
116 void applyrules(Client *c);
118 void attach(Client *c);
119 void attachstack(Client *c);
121 void buttonpress(XEvent *e);
122 void checkotherwm(void);
124 void configure(Client *c);
125 void configurenotify(XEvent *e);
126 void configurerequest(XEvent *e);
127 void destroynotify(XEvent *e);
128 void detach(Client *c);
129 void detachstack(Client *c);
131 void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
132 void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
133 void *emallocz(unsigned int size);
134 void enternotify(XEvent *e);
135 void eprint(const char *errstr, ...);
136 void expose(XEvent *e);
137 void focus(Client *c);
138 void focusin(XEvent *e);
139 void focusnext(const char *arg);
140 void focusprev(const char *arg);
141 Client *getclient(Window w);
142 unsigned long getcolor(const char *colstr);
143 long getstate(Window w);
144 Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
145 void grabbuttons(Client *c, Bool focused);
147 unsigned int idxoftag(const char *t);
148 void initfont(const char *fontstr);
149 Bool isoccupied(unsigned int t);
150 Bool isprotodel(Client *c);
151 Bool isurgent(unsigned int t);
152 Bool isvisible(Client *c);
153 void keypress(XEvent *e);
154 void killclient(const char *arg);
155 void manage(Window w, XWindowAttributes *wa);
156 void mappingnotify(XEvent *e);
157 void maprequest(XEvent *e);
158 void movemouse(Client *c);
159 Client *nextunfloating(Client *c);
160 void propertynotify(XEvent *e);
161 void quit(const char *arg);
162 void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
163 void resizemouse(Client *c);
167 void setclientstate(Client *c, long state);
169 void spawn(const char *arg);
170 void tag(const char *arg);
171 unsigned int textnw(const char *text, unsigned int len);
172 unsigned int textw(const char *text);
173 void togglebar(const char *arg);
174 void togglefloating(const char *arg);
175 void togglelayout(const char *arg);
176 void toggletag(const char *arg);
177 void toggleview(const char *arg);
178 void unban(Client *c);
179 void unmanage(Client *c);
180 void unmapnotify(XEvent *e);
181 void updatebar(void);
182 void updategeom(void);
183 void updatesizehints(Client *c);
184 void updatetitle(Client *c);
185 void updatewmhints(Client *c);
186 void view(const char *arg);
187 void viewprevtag(const char *arg);
188 int xerror(Display *dpy, XErrorEvent *ee);
189 int xerrordummy(Display *dpy, XErrorEvent *ee);
190 int xerrorstart(Display *dpy, XErrorEvent *ee);
191 void zoom(const char *arg);
195 int screen, sx, sy, sw, sh;
196 int bx, by, bw, bh, blw, wx, wy, ww, wh;
198 int (*xerrorxlib)(Display *, XErrorEvent *);
199 unsigned int numlockmask = 0;
200 void (*handler[LASTEvent]) (XEvent *) = {
201 [ButtonPress] = buttonpress,
202 [ConfigureRequest] = configurerequest,
203 [ConfigureNotify] = configurenotify,
204 [DestroyNotify] = destroynotify,
205 [EnterNotify] = enternotify,
208 [KeyPress] = keypress,
209 [MappingNotify] = mappingnotify,
210 [MapRequest] = maprequest,
211 [PropertyNotify] = propertynotify,
212 [UnmapNotify] = unmapnotify
214 Atom wmatom[WMLast], netatom[NetLast];
215 Bool otherwm, readin;
218 Client *clients = NULL;
220 Client *stack = NULL;
221 Cursor cursor[CurLast];
225 Layout *lt = layouts;
228 /* configuration, allows nested code to access above variables */
230 #define TAGSZ (LENGTH(tags) * sizeof(Bool))
232 /* function implementations */
235 applyrules(Client *c) {
237 Bool matched = False;
239 XClassHint ch = { 0 };
242 XGetClassHint(dpy, c->win, &ch);
243 for(i = 0; i < LENGTH(rules); i++) {
245 if((!r->title || strstr(c->name, r->title))
246 && (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
247 && (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
248 c->isfloating = r->isfloating;
250 c->tags[idxoftag(r->tag)] = True;
260 memcpy(c->tags, tagset[seltags], TAGSZ);
267 for(c = clients; c; c = c->next)
270 if(!lt->arrange || c->isfloating)
271 resize(c, c->x, c->y, c->w, c->h, True);
291 attachstack(Client *c) {
300 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
305 buttonpress(XEvent *e) {
308 XButtonPressedEvent *ev = &e->xbutton;
310 if(ev->window == barwin) {
312 for(i = 0; i < LENGTH(tags); i++) {
315 if(ev->button == Button1) {
316 if(ev->state & MODKEY)
321 else if(ev->button == Button3) {
322 if(ev->state & MODKEY)
330 if((ev->x < x + blw) && ev->button == Button1)
333 else if((c = getclient(ev->window))) {
335 if(CLEANMASK(ev->state) != MODKEY)
337 if(ev->button == Button1) {
341 else if(ev->button == Button2) {
342 if(lt->arrange && c->isfloating)
343 togglefloating(NULL);
345 else if(ev->button == Button3 && !c->isfixed) {
355 XSetErrorHandler(xerrorstart);
357 /* this causes an error if some other window manager is running */
358 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
361 eprint("dwm: another window manager is already running\n");
363 XSetErrorHandler(NULL);
364 xerrorxlib = XSetErrorHandler(xerror);
376 XFreeFontSet(dpy, dc.font.set);
378 XFreeFont(dpy, dc.font.xfont);
379 XUngrabKey(dpy, AnyKey, AnyModifier, root);
380 XFreePixmap(dpy, dc.drawable);
382 XFreeCursor(dpy, cursor[CurNormal]);
383 XFreeCursor(dpy, cursor[CurResize]);
384 XFreeCursor(dpy, cursor[CurMove]);
385 XDestroyWindow(dpy, barwin);
387 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
391 configure(Client *c) {
394 ce.type = ConfigureNotify;
402 ce.border_width = c->bw;
404 ce.override_redirect = False;
405 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
409 configurenotify(XEvent *e) {
410 XConfigureEvent *ev = &e->xconfigure;
412 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
422 configurerequest(XEvent *e) {
424 XConfigureRequestEvent *ev = &e->xconfigurerequest;
427 if((c = getclient(ev->window))) {
428 if(ev->value_mask & CWBorderWidth)
429 c->bw = ev->border_width;
430 if(c->isfixed || c->isfloating || !lt->arrange) {
431 if(ev->value_mask & CWX)
433 if(ev->value_mask & CWY)
435 if(ev->value_mask & CWWidth)
437 if(ev->value_mask & CWHeight)
439 if((c->x - sx + c->w) > sw && c->isfloating)
440 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
441 if((c->y - sy + c->h) > sh && c->isfloating)
442 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
443 if((ev->value_mask & (CWX|CWY))
444 && !(ev->value_mask & (CWWidth|CWHeight)))
447 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
455 wc.width = ev->width;
456 wc.height = ev->height;
457 wc.border_width = ev->border_width;
458 wc.sibling = ev->above;
459 wc.stack_mode = ev->detail;
460 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
466 destroynotify(XEvent *e) {
468 XDestroyWindowEvent *ev = &e->xdestroywindow;
470 if((c = getclient(ev->window)))
477 c->prev->next = c->next;
479 c->next->prev = c->prev;
482 c->next = c->prev = NULL;
486 detachstack(Client *c) {
489 for(tc = &stack; *tc && *tc != c; tc = &(*tc)->snext);
499 for(c = stack; c && !isvisible(c); c = c->snext);
500 for(i = 0; i < LENGTH(tags); i++) {
501 dc.w = textw(tags[i]);
502 if(tagset[seltags][i]) {
503 drawtext(tags[i], dc.sel, isurgent(i));
504 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.sel);
507 drawtext(tags[i], dc.norm, isurgent(i));
508 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.norm);
514 drawtext(lt->symbol, dc.norm, False);
525 drawtext(stext, dc.norm, False);
526 if((dc.w = dc.x - x) > bh) {
529 drawtext(c->name, dc.sel, False);
530 drawsquare(False, c->isfloating, False, dc.sel);
533 drawtext(NULL, dc.norm, False);
535 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, bw, bh, 0, 0);
540 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
543 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
545 gcv.foreground = col[invert ? ColBG : ColFG];
546 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
547 x = (dc.font.ascent + dc.font.descent + 2) / 4;
551 r.width = r.height = x + 1;
552 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
555 r.width = r.height = x;
556 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
561 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
563 unsigned int len, olen;
564 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
567 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
568 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
572 len = MIN(olen, sizeof buf);
573 memcpy(buf, text, len);
575 h = dc.font.ascent + dc.font.descent;
576 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
578 /* shorten text if necessary */
579 for(; len && (w = textnw(buf, len)) > dc.w - h; len--);
590 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
592 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
594 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
598 emallocz(unsigned int size) {
599 void *res = calloc(1, size);
602 eprint("fatal: could not malloc() %u bytes\n", size);
607 enternotify(XEvent *e) {
609 XCrossingEvent *ev = &e->xcrossing;
611 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
613 if((c = getclient(ev->window)))
620 eprint(const char *errstr, ...) {
623 va_start(ap, errstr);
624 vfprintf(stderr, errstr, ap);
631 XExposeEvent *ev = &e->xexpose;
633 if(ev->count == 0 && (ev->window == barwin))
639 if(!c || (c && !isvisible(c)))
640 for(c = stack; c && !isvisible(c); c = c->snext);
641 if(sel && sel != c) {
642 grabbuttons(sel, False);
643 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
648 grabbuttons(c, True);
652 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
653 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
656 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
661 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
662 XFocusChangeEvent *ev = &e->xfocus;
664 if(sel && ev->window != sel->win)
665 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
669 focusnext(const char *arg) {
674 for(c = sel->next; c && !isvisible(c); c = c->next);
676 for(c = clients; c && !isvisible(c); c = c->next);
684 focusprev(const char *arg) {
689 for(c = sel->prev; c && !isvisible(c); c = c->prev);
691 for(c = clients; c && c->next; c = c->next);
692 for(; c && !isvisible(c); c = c->prev);
701 getclient(Window w) {
704 for(c = clients; c && c->win != w; c = c->next);
709 getcolor(const char *colstr) {
710 Colormap cmap = DefaultColormap(dpy, screen);
713 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
714 eprint("error, cannot allocate color '%s'\n", colstr);
722 unsigned char *p = NULL;
723 unsigned long n, extra;
726 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
727 &real, &format, &n, &extra, (unsigned char **)&p);
728 if(status != Success)
737 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
742 if(!text || size == 0)
745 XGetTextProperty(dpy, w, &name, atom);
748 if(name.encoding == XA_STRING)
749 strncpy(text, (char *)name.value, size - 1);
751 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
753 strncpy(text, *list, size - 1);
754 XFreeStringList(list);
757 text[size - 1] = '\0';
763 grabbuttons(Client *c, Bool focused) {
765 unsigned int buttons[] = { Button1, Button2, Button3 };
766 unsigned int modifiers[] = { MODKEY, MODKEY|LockMask, MODKEY|numlockmask,
767 MODKEY|numlockmask|LockMask} ;
769 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
771 for(i = 0; i < LENGTH(buttons); i++)
772 for(j = 0; j < LENGTH(modifiers); j++)
773 XGrabButton(dpy, buttons[i], modifiers[j], c->win, False,
774 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
776 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
777 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
784 XModifierKeymap *modmap;
786 /* init modifier map */
787 modmap = XGetModifierMapping(dpy);
788 for(i = 0; i < 8; i++)
789 for(j = 0; j < modmap->max_keypermod; j++) {
790 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
791 numlockmask = (1 << i);
793 XFreeModifiermap(modmap);
795 XUngrabKey(dpy, AnyKey, AnyModifier, root);
796 for(i = 0; i < LENGTH(keys); i++) {
797 code = XKeysymToKeycode(dpy, keys[i].keysym);
798 XGrabKey(dpy, code, keys[i].mod, root, True,
799 GrabModeAsync, GrabModeAsync);
800 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
801 GrabModeAsync, GrabModeAsync);
802 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
803 GrabModeAsync, GrabModeAsync);
804 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
805 GrabModeAsync, GrabModeAsync);
810 idxoftag(const char *t) {
813 for(i = 0; (i < LENGTH(tags)) && t && strcmp(tags[i], t); i++);
814 return (i < LENGTH(tags)) ? i : 0;
818 initfont(const char *fontstr) {
819 char *def, **missing;
824 XFreeFontSet(dpy, dc.font.set);
825 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
828 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
829 XFreeStringList(missing);
832 XFontSetExtents *font_extents;
833 XFontStruct **xfonts;
835 dc.font.ascent = dc.font.descent = 0;
836 font_extents = XExtentsOfFontSet(dc.font.set);
837 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
838 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
839 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
840 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
846 XFreeFont(dpy, dc.font.xfont);
847 dc.font.xfont = NULL;
848 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
849 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
850 eprint("error, cannot load font: '%s'\n", fontstr);
851 dc.font.ascent = dc.font.xfont->ascent;
852 dc.font.descent = dc.font.xfont->descent;
854 dc.font.height = dc.font.ascent + dc.font.descent;
858 isoccupied(unsigned int t) {
861 for(c = clients; c; c = c->next)
868 isprotodel(Client *c) {
873 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
874 for(i = 0; !ret && i < n; i++)
875 if(protocols[i] == wmatom[WMDelete])
883 isurgent(unsigned int t) {
886 for(c = clients; c; c = c->next)
887 if(c->isurgent && c->tags[t])
893 isvisible(Client *c) {
896 for(i = 0; i < LENGTH(tags); i++)
897 if(c->tags[i] && tagset[seltags][i])
903 keypress(XEvent *e) {
909 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
910 for(i = 0; i < LENGTH(keys); i++)
911 if(keysym == keys[i].keysym
912 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
915 keys[i].func(keys[i].arg);
920 killclient(const char *arg) {
925 if(isprotodel(sel)) {
926 ev.type = ClientMessage;
927 ev.xclient.window = sel->win;
928 ev.xclient.message_type = wmatom[WMProtocols];
929 ev.xclient.format = 32;
930 ev.xclient.data.l[0] = wmatom[WMDelete];
931 ev.xclient.data.l[1] = CurrentTime;
932 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
935 XKillClient(dpy, sel->win);
939 manage(Window w, XWindowAttributes *wa) {
940 Client *c, *t = NULL;
945 c = emallocz(sizeof(Client));
946 c->tags = emallocz(TAGSZ);
954 c->oldbw = wa->border_width;
955 if(c->w == sw && c->h == sh) {
958 c->bw = wa->border_width;
961 if(c->x + c->w + 2 * c->bw > wx + ww)
962 c->x = wx + ww - c->w - 2 * c->bw;
963 if(c->y + c->h + 2 * c->bw > wy + wh)
964 c->y = wy + wh - c->h - 2 * c->bw;
965 c->x = MAX(c->x, wx);
966 c->y = MAX(c->y, wy);
970 wc.border_width = c->bw;
971 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
972 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
973 configure(c); /* propagates border_width, if size doesn't change */
975 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
976 grabbuttons(c, False);
978 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
979 for(t = clients; t && t->win != trans; t = t->next);
981 memcpy(c->tags, t->tags, TAGSZ);
985 c->isfloating = (rettrans == Success) || c->isfixed;
988 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
990 XMapWindow(dpy, c->win);
991 setclientstate(c, NormalState);
996 mappingnotify(XEvent *e) {
997 XMappingEvent *ev = &e->xmapping;
999 XRefreshKeyboardMapping(ev);
1000 if(ev->request == MappingKeyboard)
1005 maprequest(XEvent *e) {
1006 static XWindowAttributes wa;
1007 XMapRequestEvent *ev = &e->xmaprequest;
1009 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1011 if(wa.override_redirect)
1013 if(!getclient(ev->window))
1014 manage(ev->window, &wa);
1018 movemouse(Client *c) {
1019 int x1, y1, ocx, ocy, di, nx, ny;
1026 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1027 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1029 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1031 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1034 XUngrabPointer(dpy, CurrentTime);
1036 case ConfigureRequest:
1039 handler[ev.type](&ev);
1043 nx = ocx + (ev.xmotion.x - x1);
1044 ny = ocy + (ev.xmotion.y - y1);
1045 if(snap && nx >= wx && nx <= wx + ww
1046 && ny >= wy && ny <= wy + wh) {
1047 if(abs(wx - nx) < snap)
1049 else if(abs((wx + ww) - (nx + c->w + 2 * c->bw)) < snap)
1050 nx = wx + ww - c->w - 2 * c->bw;
1051 if(abs(wy - ny) < snap)
1053 else if(abs((wy + wh) - (ny + c->h + 2 * c->bw)) < snap)
1054 ny = wy + wh - c->h - 2 * c->bw;
1055 if(!c->isfloating && lt->arrange && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
1056 togglefloating(NULL);
1058 if(!lt->arrange || c->isfloating)
1059 resize(c, nx, ny, c->w, c->h, False);
1066 nextunfloating(Client *c) {
1067 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1072 propertynotify(XEvent *e) {
1075 XPropertyEvent *ev = &e->xproperty;
1077 if(ev->state == PropertyDelete)
1078 return; /* ignore */
1079 if((c = getclient(ev->window))) {
1082 case XA_WM_TRANSIENT_FOR:
1083 XGetTransientForHint(dpy, c->win, &trans);
1084 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1087 case XA_WM_NORMAL_HINTS:
1095 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1104 quit(const char *arg) {
1105 readin = running = False;
1109 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1113 /* set minimum possible */
1117 /* temporarily remove base dimensions */
1121 /* adjust for aspect limits */
1122 if(c->minax != c->maxax && c->minay != c->maxay
1123 && c->minax > 0 && c->maxax > 0 && c->minay > 0 && c->maxay > 0) {
1124 if(w * c->maxay > h * c->maxax)
1125 w = h * c->maxax / c->maxay;
1126 else if(w * c->minay < h * c->minax)
1127 h = w * c->minay / c->minax;
1130 /* adjust for increment value */
1136 /* restore base dimensions */
1140 w = MAX(w, c->minw);
1141 h = MAX(h, c->minh);
1144 w = MIN(w, c->maxw);
1147 h = MIN(h, c->maxh);
1149 if(w <= 0 || h <= 0)
1152 x = sw - w - 2 * c->bw;
1154 y = sh - h - 2 * c->bw;
1155 if(x + w + 2 * c->bw < sx)
1157 if(y + h + 2 * c->bw < sy)
1159 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1162 c->w = wc.width = w;
1163 c->h = wc.height = h;
1164 wc.border_width = c->bw;
1165 XConfigureWindow(dpy, c->win,
1166 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1173 resizemouse(Client *c) {
1180 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1181 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1183 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1185 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1188 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1189 c->w + c->bw - 1, c->h + c->bw - 1);
1190 XUngrabPointer(dpy, CurrentTime);
1191 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1193 case ConfigureRequest:
1196 handler[ev.type](&ev);
1200 nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1201 nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1203 if(snap && nw >= wx && nw <= wx + ww
1204 && nh >= wy && nh <= wy + wh) {
1205 if(!c->isfloating && lt->arrange
1206 && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1207 togglefloating(NULL);
1209 if(!lt->arrange || c->isfloating)
1210 resize(c, c->x, c->y, nw, nh, True);
1225 if(sel->isfloating || !lt->arrange)
1226 XRaiseWindow(dpy, sel->win);
1228 wc.stack_mode = Below;
1229 wc.sibling = barwin;
1230 for(c = stack; c; c = c->snext)
1231 if(!c->isfloating && isvisible(c)) {
1232 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1233 wc.sibling = c->win;
1237 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1243 char sbuf[sizeof stext];
1246 unsigned int len, offset;
1249 /* main event loop, also reads status text from stdin */
1251 xfd = ConnectionNumber(dpy);
1254 len = sizeof stext - 1;
1255 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1259 FD_SET(STDIN_FILENO, &rd);
1261 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1264 eprint("select failed\n");
1266 if(FD_ISSET(STDIN_FILENO, &rd)) {
1267 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1269 strncpy(stext, strerror(errno), len);
1273 strncpy(stext, "EOF", 4);
1277 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1278 if(*p == '\n' || *p == '\0') {
1280 strncpy(stext, sbuf, len);
1281 p += r - 1; /* p is sbuf + offset + r - 1 */
1282 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1285 memmove(sbuf, p - r + 1, r);
1292 while(XPending(dpy)) {
1293 XNextEvent(dpy, &ev);
1294 if(handler[ev.type])
1295 (handler[ev.type])(&ev); /* call handler */
1302 unsigned int i, num;
1303 Window *wins, d1, d2;
1304 XWindowAttributes wa;
1307 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1308 for(i = 0; i < num; i++) {
1309 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1310 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1312 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1313 manage(wins[i], &wa);
1315 for(i = 0; i < num; i++) { /* now the transients */
1316 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1318 if(XGetTransientForHint(dpy, wins[i], &d1)
1319 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1320 manage(wins[i], &wa);
1328 setclientstate(Client *c, long state) {
1329 long data[] = {state, None};
1331 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1332 PropModeReplace, (unsigned char *)data, 2);
1338 XSetWindowAttributes wa;
1341 screen = DefaultScreen(dpy);
1342 root = RootWindow(dpy, screen);
1346 sw = DisplayWidth(dpy, screen);
1347 sh = DisplayHeight(dpy, screen);
1348 bh = dc.font.height + 2;
1352 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1353 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1354 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1355 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1356 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1357 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1360 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1361 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1362 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1364 /* init appearance */
1365 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1366 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1367 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1368 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1369 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1370 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1373 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1374 dc.gc = XCreateGC(dpy, root, 0, 0);
1375 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1377 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1380 tagset[0] = emallocz(TAGSZ);
1381 tagset[1] = emallocz(TAGSZ);
1382 tagset[0][0] = tagset[1][0] = True;
1385 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1386 w = textw(layouts[i].symbol);
1390 wa.override_redirect = 1;
1391 wa.background_pixmap = ParentRelative;
1392 wa.event_mask = ButtonPressMask|ExposureMask;
1394 barwin = XCreateWindow(dpy, root, bx, by, bw, bh, 0, DefaultDepth(dpy, screen),
1395 CopyFromParent, DefaultVisual(dpy, screen),
1396 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1397 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1398 XMapRaised(dpy, barwin);
1399 strcpy(stext, "dwm-"VERSION);
1402 /* EWMH support per view */
1403 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1404 PropModeReplace, (unsigned char *) netatom, NetLast);
1406 /* select for events */
1407 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1408 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1409 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1410 XSelectInput(dpy, root, wa.event_mask);
1418 spawn(const char *arg) {
1419 static char *shell = NULL;
1421 if(!shell && !(shell = getenv("SHELL")))
1425 /* The double-fork construct avoids zombie processes and keeps the code
1426 * clean from stupid signal handlers. */
1430 close(ConnectionNumber(dpy));
1432 execl(shell, shell, "-c", arg, (char *)NULL);
1433 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1442 tag(const char *arg) {
1447 for(i = 0; i < LENGTH(tags); i++)
1448 sel->tags[i] = (arg == NULL);
1449 sel->tags[idxoftag(arg)] = True;
1454 textnw(const char *text, unsigned int len) {
1458 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1461 return XTextWidth(dc.font.xfont, text, len);
1465 textw(const char *text) {
1466 return textnw(text, strlen(text)) + dc.font.height;
1470 togglebar(const char *arg) {
1478 togglefloating(const char *arg) {
1481 sel->isfloating = !sel->isfloating;
1483 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1488 togglelayout(const char *arg) {
1492 if(++lt == &layouts[LENGTH(layouts)])
1496 for(i = 0; i < LENGTH(layouts); i++)
1497 if(!strcmp(arg, layouts[i].symbol))
1499 if(i == LENGTH(layouts))
1510 toggletag(const char *arg) {
1516 sel->tags[i] = !sel->tags[i];
1517 for(j = 0; j < LENGTH(tags) && !sel->tags[j]; j++);
1518 if(j == LENGTH(tags))
1519 sel->tags[i] = True; /* at least one tag must be enabled */
1524 toggleview(const char *arg) {
1528 tagset[seltags][i] = !tagset[seltags][i];
1529 for(j = 0; j < LENGTH(tags) && !tagset[seltags][j]; j++);
1530 if(j == LENGTH(tags))
1531 tagset[seltags][i] = True; /* at least one tag must be viewed */
1539 XMoveWindow(dpy, c->win, c->x, c->y);
1540 c->isbanned = False;
1544 unmanage(Client *c) {
1547 wc.border_width = c->oldbw;
1548 /* The server grab construct avoids race conditions. */
1550 XSetErrorHandler(xerrordummy);
1551 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1556 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1557 setclientstate(c, WithdrawnState);
1561 XSetErrorHandler(xerror);
1567 unmapnotify(XEvent *e) {
1569 XUnmapEvent *ev = &e->xunmap;
1571 if((c = getclient(ev->window)))
1577 if(dc.drawable != 0)
1578 XFreePixmap(dpy, dc.drawable);
1579 dc.drawable = XCreatePixmap(dpy, root, bw, bh, DefaultDepth(dpy, screen));
1580 XMoveResizeWindow(dpy, barwin, bx, by, bw, bh);
1587 XineramaScreenInfo *info = NULL;
1589 /* window area geometry */
1590 if(XineramaIsActive(dpy)) {
1591 info = XineramaQueryScreens(dpy, &i);
1593 wy = showbar && topbar ? info[0].y_org + info[0].height + bh : info[0].y_org;
1595 wh = showbar ? info[0].height - bh : info[0].height;
1602 wy = showbar && topbar ? sy + bh : sy;
1604 wh = showbar ? sh - bh : sh;
1609 by = showbar ? (topbar ? 0 : wy + wh) : -bh;
1612 /* update layout geometries */
1613 for(i = 0; i < LENGTH(layouts); i++)
1614 if(layouts[i].updategeom)
1615 layouts[i].updategeom();
1619 updatesizehints(Client *c) {
1623 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1625 c->flags = size.flags;
1626 if(c->flags & PBaseSize) {
1627 c->basew = size.base_width;
1628 c->baseh = size.base_height;
1630 else if(c->flags & PMinSize) {
1631 c->basew = size.min_width;
1632 c->baseh = size.min_height;
1635 c->basew = c->baseh = 0;
1636 if(c->flags & PResizeInc) {
1637 c->incw = size.width_inc;
1638 c->inch = size.height_inc;
1641 c->incw = c->inch = 0;
1642 if(c->flags & PMaxSize) {
1643 c->maxw = size.max_width;
1644 c->maxh = size.max_height;
1647 c->maxw = c->maxh = 0;
1648 if(c->flags & PMinSize) {
1649 c->minw = size.min_width;
1650 c->minh = size.min_height;
1652 else if(c->flags & PBaseSize) {
1653 c->minw = size.base_width;
1654 c->minh = size.base_height;
1657 c->minw = c->minh = 0;
1658 if(c->flags & PAspect) {
1659 c->minax = size.min_aspect.x;
1660 c->maxax = size.max_aspect.x;
1661 c->minay = size.min_aspect.y;
1662 c->maxay = size.max_aspect.y;
1665 c->minax = c->maxax = c->minay = c->maxay = 0;
1666 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1667 && c->maxw == c->minw && c->maxh == c->minh);
1671 updatetitle(Client *c) {
1672 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1673 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1677 updatewmhints(Client *c) {
1680 if((wmh = XGetWMHints(dpy, c->win))) {
1682 sel->isurgent = False;
1684 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1690 view(const char *arg) {
1691 seltags ^= 1; /* toggle sel tagset */
1692 memset(tagset[seltags], (NULL == arg), TAGSZ);
1693 tagset[seltags][idxoftag(arg)] = True;
1698 viewprevtag(const char *arg) {
1699 seltags ^= 1; /* toggle sel tagset */
1703 /* There's no way to check accesses to destroyed windows, thus those cases are
1704 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1705 * default error handler, which may call exit. */
1707 xerror(Display *dpy, XErrorEvent *ee) {
1708 if(ee->error_code == BadWindow
1709 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1710 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1711 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1712 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1713 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1714 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1715 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1716 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1718 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1719 ee->request_code, ee->error_code);
1720 return xerrorxlib(dpy, ee); /* may call exit */
1724 xerrordummy(Display *dpy, XErrorEvent *ee) {
1728 /* Startup Error handler to check if another window manager
1729 * is already running. */
1731 xerrorstart(Display *dpy, XErrorEvent *ee) {
1737 main(int argc, char *argv[]) {
1738 if(argc == 2 && !strcmp("-v", argv[1]))
1739 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1741 eprint("usage: dwm [-v]\n");
1743 setlocale(LC_CTYPE, "");
1744 if(!(dpy = XOpenDisplay(0)))
1745 eprint("dwm: cannot open display\n");