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>
37 #include <X11/cursorfont.h>
38 #include <X11/keysym.h>
39 #include <X11/Xatom.h>
41 #include <X11/Xproto.h>
42 #include <X11/Xutil.h>
45 #define BUTTONMASK (ButtonPressMask|ButtonReleaseMask)
46 #define CLEANMASK(mask) (mask & ~(numlockmask|LockMask))
47 #define LENGTH(x) (sizeof x / sizeof x[0])
49 #define MOUSEMASK (BUTTONMASK|PointerMotionMask)
52 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
53 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
54 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
55 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
58 typedef struct Client Client;
63 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
64 int minax, maxax, minay, maxay;
66 unsigned int border, oldborder;
67 Bool isbanned, isfixed, isfloating, isurgent;
77 unsigned long norm[ColLast];
78 unsigned long sel[ColLast];
88 } DC; /* draw context */
93 void (*func)(const char *arg);
99 void (*arrange)(void);
108 /* function declarations */
109 void applyrules(Client *c);
111 void attach(Client *c);
112 void attachstack(Client *c);
114 void buttonpress(XEvent *e);
115 void checkotherwm(void);
117 void configure(Client *c);
118 void configurenotify(XEvent *e);
119 void configurerequest(XEvent *e);
120 void destroynotify(XEvent *e);
121 void detach(Client *c);
122 void detachstack(Client *c);
124 void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
125 void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
126 void *emallocz(unsigned int size);
127 void enternotify(XEvent *e);
128 void eprint(const char *errstr, ...);
129 void expose(XEvent *e);
130 void floating(void); /* default floating layout */
131 void focus(Client *c);
132 void focusin(XEvent *e);
133 void focusnext(const char *arg);
134 void focusprev(const char *arg);
135 Client *getclient(Window w);
136 unsigned long getcolor(const char *colstr);
137 long getstate(Window w);
138 Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
139 void grabbuttons(Client *c, Bool focused);
141 unsigned int idxoftag(const char *t);
142 void initfont(const char *fontstr);
143 Bool isoccupied(unsigned int t);
144 Bool isprotodel(Client *c);
145 Bool isurgent(unsigned int t);
146 Bool isvisible(Client *c);
147 void keypress(XEvent *e);
148 void killclient(const char *arg);
149 void manage(Window w, XWindowAttributes *wa);
150 void mappingnotify(XEvent *e);
151 void maprequest(XEvent *e);
153 void movemouse(Client *c);
154 Client *nexttiled(Client *c);
155 void propertynotify(XEvent *e);
156 void quit(const char *arg);
157 void reapply(const char *arg);
158 void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
159 void resizemouse(Client *c);
163 void setclientstate(Client *c, long state);
164 void setlayout(const char *arg);
166 void spawn(const char *arg);
167 void tag(const char *arg);
168 unsigned int textnw(const char *text, unsigned int len);
169 unsigned int textw(const char *text);
171 void togglefloating(const char *arg);
172 void toggletag(const char *arg);
173 void toggleview(const char *arg);
174 void unban(Client *c);
175 void unmanage(Client *c);
176 void unmapnotify(XEvent *e);
177 void updatesizehints(Client *c);
178 void updatetitle(Client *c);
179 void updatewmhints(Client *c);
180 void view(const char *arg);
181 void viewprevtag(const char *arg); /* views previous selected tags */
182 int xerror(Display *dpy, XErrorEvent *ee);
183 int xerrordummy(Display *dpy, XErrorEvent *ee);
184 int xerrorstart(Display *dpy, XErrorEvent *ee);
185 void zoom(const char *arg);
186 void selectview(const char *arg);
189 char stext[256], buf[256];
191 int screen, sx, sy, sw, sh;
192 int (*xerrorxlib)(Display *, XErrorEvent *);
193 unsigned int bh, bpos;
194 unsigned int blw = 0;
195 unsigned int numlockmask = 0;
196 void (*handler[LASTEvent]) (XEvent *) = {
197 [ButtonPress] = buttonpress,
198 [ConfigureRequest] = configurerequest,
199 [ConfigureNotify] = configurenotify,
200 [DestroyNotify] = destroynotify,
201 [EnterNotify] = enternotify,
204 [KeyPress] = keypress,
205 [MappingNotify] = mappingnotify,
206 [MapRequest] = maprequest,
207 [PropertyNotify] = propertynotify,
208 [UnmapNotify] = unmapnotify
210 Atom wmatom[WMLast], netatom[NetLast];
212 Bool otherwm, readin;
216 Client *clients = NULL;
218 Client *stack = NULL;
219 Cursor cursor[CurLast];
225 /* configuration, allows nested code to access above variables */
227 #define TAGSZ (LENGTH(tags) * sizeof(Bool))
228 static Bool tmp[LENGTH(tags)];
230 /* function implementations */
233 applyrules(Client *c) {
235 Bool matched = False;
237 XClassHint ch = { 0 };
240 XGetClassHint(dpy, c->win, &ch);
241 for(i = 0; i < LENGTH(rules); i++) {
243 if(strstr(c->name, r->prop)
244 || (ch.res_class && strstr(ch.res_class, r->prop))
245 || (ch.res_name && strstr(ch.res_name, r->prop)))
247 c->isfloating = r->isfloating;
249 c->tags[idxoftag(r->tag)] = True;
259 memcpy(c->tags, seltags, TAGSZ);
266 for(c = clients; c; c = c->next)
286 attachstack(Client *c) {
295 XMoveWindow(dpy, c->win, c->x + 3 * sw, c->y);
300 buttonpress(XEvent *e) {
303 XButtonPressedEvent *ev = &e->xbutton;
305 if(ev->window == barwin) {
307 for(i = 0; i < LENGTH(tags); i++) {
310 if(ev->button == Button1) {
311 if(ev->state & MODKEY)
316 else if(ev->button == Button3) {
317 if(ev->state & MODKEY)
326 else if((c = getclient(ev->window))) {
328 if(CLEANMASK(ev->state) != MODKEY)
330 if(ev->button == Button1) {
334 else if(ev->button == Button2) {
335 if((floating != lt->arrange) && c->isfloating)
336 togglefloating(NULL);
340 else if(ev->button == Button3 && !c->isfixed) {
350 XSetErrorHandler(xerrorstart);
352 /* this causes an error if some other window manager is running */
353 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
356 eprint("dwm: another window manager is already running\n");
358 XSetErrorHandler(NULL);
359 xerrorxlib = XSetErrorHandler(xerror);
372 XFreeFontSet(dpy, dc.font.set);
374 XFreeFont(dpy, dc.font.xfont);
376 XUngrabKey(dpy, AnyKey, AnyModifier, root);
377 XFreePixmap(dpy, dc.drawable);
379 XFreeCursor(dpy, cursor[CurNormal]);
380 XFreeCursor(dpy, cursor[CurResize]);
381 XFreeCursor(dpy, cursor[CurMove]);
382 XDestroyWindow(dpy, barwin);
384 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
388 configure(Client *c) {
391 ce.type = ConfigureNotify;
399 ce.border_width = c->border;
401 ce.override_redirect = False;
402 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
406 configurenotify(XEvent *e) {
407 XConfigureEvent *ev = &e->xconfigure;
409 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
412 XFreePixmap(dpy, dc.drawable);
413 dc.drawable = XCreatePixmap(dpy, root, BW, bh, DefaultDepth(dpy, screen));
414 XMoveResizeWindow(dpy, barwin, BX, BY, BW, bh);
420 configurerequest(XEvent *e) {
422 XConfigureRequestEvent *ev = &e->xconfigurerequest;
425 if((c = getclient(ev->window))) {
426 if(ev->value_mask & CWBorderWidth)
427 c->border = ev->border_width;
428 if(c->isfixed || c->isfloating || (floating == lt->arrange)) {
429 if(ev->value_mask & CWX)
431 if(ev->value_mask & CWY)
433 if(ev->value_mask & CWWidth)
435 if(ev->value_mask & CWHeight)
437 if((c->x - sx + c->w) > sw && c->isfloating)
438 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
439 if((c->y - sy + c->h) > sh && c->isfloating)
440 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
441 if((ev->value_mask & (CWX|CWY))
442 && !(ev->value_mask & (CWWidth|CWHeight)))
445 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
453 wc.width = ev->width;
454 wc.height = ev->height;
455 wc.border_width = ev->border_width;
456 wc.sibling = ev->above;
457 wc.stack_mode = ev->detail;
458 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
464 destroynotify(XEvent *e) {
466 XDestroyWindowEvent *ev = &e->xdestroywindow;
468 if((c = getclient(ev->window)))
475 c->prev->next = c->next;
477 c->next->prev = c->prev;
480 c->next = c->prev = NULL;
484 detachstack(Client *c) {
487 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
497 for(c = stack; c && !isvisible(c); c = c->snext);
498 for(i = 0; i < LENGTH(tags); i++) {
499 dc.w = textw(tags[i]);
501 drawtext(tags[i], dc.sel, isurgent(i));
502 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.sel);
505 drawtext(tags[i], dc.norm, isurgent(i));
506 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.norm);
511 drawtext(lt->symbol, dc.norm, False);
519 drawtext(stext, dc.norm, False);
520 if((dc.w = dc.x - x) > bh) {
523 drawtext(c->name, dc.sel, False);
524 drawsquare(False, c->isfloating, False, dc.sel);
527 drawtext(NULL, dc.norm, False);
529 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, BW, bh, 0, 0);
534 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
537 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
539 gcv.foreground = col[invert ? ColBG : ColFG];
540 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
541 x = (dc.font.ascent + dc.font.descent + 2) / 4;
545 r.width = r.height = x + 1;
546 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
549 r.width = r.height = x;
550 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
555 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
557 unsigned int len, olen;
558 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
560 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
561 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
565 olen = len = strlen(text);
566 if(len >= sizeof buf)
567 len = sizeof buf - 1;
568 memcpy(buf, text, len);
570 h = dc.font.ascent + dc.font.descent;
571 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
573 /* shorten text if necessary */
574 while(len && (w = textnw(buf, len)) > dc.w - h)
585 return; /* too long */
586 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
588 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
590 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
594 emallocz(unsigned int size) {
595 void *res = calloc(1, size);
598 eprint("fatal: could not malloc() %u bytes\n", size);
603 enternotify(XEvent *e) {
605 XCrossingEvent *ev = &e->xcrossing;
607 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
609 if((c = getclient(ev->window)))
616 eprint(const char *errstr, ...) {
619 va_start(ap, errstr);
620 vfprintf(stderr, errstr, ap);
627 XExposeEvent *ev = &e->xexpose;
629 if(ev->count == 0 && (ev->window == barwin))
634 floating(void) { /* default floating layout */
638 for(c = clients; c; c = c->next)
640 resize(c, c->x, c->y, c->w, c->h, True);
645 if(!c || (c && !isvisible(c)))
646 for(c = stack; c && !isvisible(c); c = c->snext);
647 if(sel && sel != c) {
648 grabbuttons(sel, False);
649 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
650 if(lt->arrange == monocle)
651 resize(sel, sel->rx, sel->ry, sel->rw, sel->rh, True);
656 grabbuttons(c, True);
657 if(lt->arrange == monocle) {
664 resize(c, MOX, MOY, MOW, MOH, RESIZEHINTS);
669 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
670 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
673 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
678 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
679 XFocusChangeEvent *ev = &e->xfocus;
681 if(sel && ev->window != sel->win)
682 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
686 focusnext(const char *arg) {
691 for(c = sel->next; c && !isvisible(c); c = c->next);
693 for(c = clients; c && !isvisible(c); c = c->next);
701 focusprev(const char *arg) {
706 for(c = sel->prev; c && !isvisible(c); c = c->prev);
708 for(c = clients; c && c->next; c = c->next);
709 for(; c && !isvisible(c); c = c->prev);
718 getclient(Window w) {
721 for(c = clients; c && c->win != w; c = c->next);
726 getcolor(const char *colstr) {
727 Colormap cmap = DefaultColormap(dpy, screen);
730 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
731 eprint("error, cannot allocate color '%s'\n", colstr);
739 unsigned char *p = NULL;
740 unsigned long n, extra;
743 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
744 &real, &format, &n, &extra, (unsigned char **)&p);
745 if(status != Success)
754 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
759 if(!text || size == 0)
762 XGetTextProperty(dpy, w, &name, atom);
765 if(name.encoding == XA_STRING)
766 strncpy(text, (char *)name.value, size - 1);
768 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
770 strncpy(text, *list, size - 1);
771 XFreeStringList(list);
774 text[size - 1] = '\0';
780 grabbuttons(Client *c, Bool focused) {
781 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
784 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
785 GrabModeAsync, GrabModeSync, None, None);
786 XGrabButton(dpy, Button1, MODKEY|LockMask, c->win, False, BUTTONMASK,
787 GrabModeAsync, GrabModeSync, None, None);
788 XGrabButton(dpy, Button1, MODKEY|numlockmask, c->win, False, BUTTONMASK,
789 GrabModeAsync, GrabModeSync, None, None);
790 XGrabButton(dpy, Button1, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
791 GrabModeAsync, GrabModeSync, None, None);
793 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
794 GrabModeAsync, GrabModeSync, None, None);
795 XGrabButton(dpy, Button2, MODKEY|LockMask, c->win, False, BUTTONMASK,
796 GrabModeAsync, GrabModeSync, None, None);
797 XGrabButton(dpy, Button2, MODKEY|numlockmask, c->win, False, BUTTONMASK,
798 GrabModeAsync, GrabModeSync, None, None);
799 XGrabButton(dpy, Button2, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
800 GrabModeAsync, GrabModeSync, None, None);
802 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
803 GrabModeAsync, GrabModeSync, None, None);
804 XGrabButton(dpy, Button3, MODKEY|LockMask, c->win, False, BUTTONMASK,
805 GrabModeAsync, GrabModeSync, None, None);
806 XGrabButton(dpy, Button3, MODKEY|numlockmask, c->win, False, BUTTONMASK,
807 GrabModeAsync, GrabModeSync, None, None);
808 XGrabButton(dpy, Button3, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
809 GrabModeAsync, GrabModeSync, None, None);
812 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
813 GrabModeAsync, GrabModeSync, None, None);
820 XModifierKeymap *modmap;
822 /* init modifier map */
823 modmap = XGetModifierMapping(dpy);
824 for(i = 0; i < 8; i++)
825 for(j = 0; j < modmap->max_keypermod; j++) {
826 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
827 numlockmask = (1 << i);
829 XFreeModifiermap(modmap);
831 XUngrabKey(dpy, AnyKey, AnyModifier, root);
832 for(i = 0; i < LENGTH(keys); i++) {
833 code = XKeysymToKeycode(dpy, keys[i].keysym);
834 XGrabKey(dpy, code, keys[i].mod, root, True,
835 GrabModeAsync, GrabModeAsync);
836 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
837 GrabModeAsync, GrabModeAsync);
838 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
839 GrabModeAsync, GrabModeAsync);
840 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
841 GrabModeAsync, GrabModeAsync);
846 idxoftag(const char *t) {
849 for(i = 0; (i < LENGTH(tags)) && (tags[i] != t); i++);
850 return (i < LENGTH(tags)) ? i : 0;
854 initfont(const char *fontstr) {
855 char *def, **missing;
860 XFreeFontSet(dpy, dc.font.set);
861 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
864 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
865 XFreeStringList(missing);
868 XFontSetExtents *font_extents;
869 XFontStruct **xfonts;
871 dc.font.ascent = dc.font.descent = 0;
872 font_extents = XExtentsOfFontSet(dc.font.set);
873 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
874 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
875 if(dc.font.ascent < (*xfonts)->ascent)
876 dc.font.ascent = (*xfonts)->ascent;
877 if(dc.font.descent < (*xfonts)->descent)
878 dc.font.descent = (*xfonts)->descent;
884 XFreeFont(dpy, dc.font.xfont);
885 dc.font.xfont = NULL;
886 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
887 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
888 eprint("error, cannot load font: '%s'\n", fontstr);
889 dc.font.ascent = dc.font.xfont->ascent;
890 dc.font.descent = dc.font.xfont->descent;
892 dc.font.height = dc.font.ascent + dc.font.descent;
896 isoccupied(unsigned int t) {
899 for(c = clients; c; c = c->next)
906 isprotodel(Client *c) {
911 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
912 for(i = 0; !ret && i < n; i++)
913 if(protocols[i] == wmatom[WMDelete])
921 isurgent(unsigned int t) {
924 for(c = clients; c; c = c->next)
925 if(c->isurgent && c->tags[t])
931 isvisible(Client *c) {
934 for(i = 0; i < LENGTH(tags); i++)
935 if(c->tags[i] && seltags[i])
941 keypress(XEvent *e) {
947 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
948 for(i = 0; i < LENGTH(keys); i++)
949 if(keysym == keys[i].keysym
950 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
953 keys[i].func(keys[i].arg);
958 killclient(const char *arg) {
963 if(isprotodel(sel)) {
964 ev.type = ClientMessage;
965 ev.xclient.window = sel->win;
966 ev.xclient.message_type = wmatom[WMProtocols];
967 ev.xclient.format = 32;
968 ev.xclient.data.l[0] = wmatom[WMDelete];
969 ev.xclient.data.l[1] = CurrentTime;
970 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
973 XKillClient(dpy, sel->win);
977 manage(Window w, XWindowAttributes *wa) {
978 Client *c, *t = NULL;
983 c = emallocz(sizeof(Client));
984 c->tags = emallocz(TAGSZ);
987 c->x = c->rx = wa->x + sx;
988 c->y = c->ry = wa->y + sy;
989 c->w = c->rw = wa->width;
990 c->h = c->rh = wa->height;
991 c->oldborder = wa->border_width;
993 if(c->w == sw && c->h == sh) {
996 c->border = wa->border_width;
999 if(c->x + c->w + 2 * c->border > sx + sw)
1000 c->x = sx + sw - c->w - 2 * c->border;
1001 if(c->y + c->h + 2 * c->border > sy + sh)
1002 c->y = sy + sh - c->h - 2 * c->border;
1007 c->border = BORDERPX;
1009 wc.border_width = c->border;
1010 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1011 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1012 configure(c); /* propagates border_width, if size doesn't change */
1014 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
1015 grabbuttons(c, False);
1017 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
1018 for(t = clients; t && t->win != trans; t = t->next);
1020 memcpy(c->tags, t->tags, TAGSZ);
1024 c->isfloating = (rettrans == Success) || c->isfixed;
1027 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
1029 XMapWindow(dpy, c->win);
1030 setclientstate(c, NormalState);
1035 mappingnotify(XEvent *e) {
1036 XMappingEvent *ev = &e->xmapping;
1038 XRefreshKeyboardMapping(ev);
1039 if(ev->request == MappingKeyboard)
1044 maprequest(XEvent *e) {
1045 static XWindowAttributes wa;
1046 XMapRequestEvent *ev = &e->xmaprequest;
1048 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1050 if(wa.override_redirect)
1052 if(!getclient(ev->window))
1053 manage(ev->window, &wa);
1062 movemouse(Client *c) {
1063 int x1, y1, ocx, ocy, di, nx, ny;
1070 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1071 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1073 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1075 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1078 XUngrabPointer(dpy, CurrentTime);
1080 case ConfigureRequest:
1083 handler[ev.type](&ev);
1087 nx = ocx + (ev.xmotion.x - x1);
1088 ny = ocy + (ev.xmotion.y - y1);
1089 if(abs(sx - nx) < SNAP)
1091 else if(abs((sx + sw) - (nx + c->w + 2 * c->border)) < SNAP)
1092 nx = sx + sw - c->w - 2 * c->border;
1093 if(abs(sy - ny) < SNAP)
1095 else if(abs((sy + sh) - (ny + c->h + 2 * c->border)) < SNAP)
1096 ny = sy + sh - c->h - 2 * c->border;
1097 if(!c->isfloating && (lt->arrange != floating) && (abs(nx - c->x) > SNAP || abs(ny - c->y) > SNAP))
1098 togglefloating(NULL);
1099 if((lt->arrange == floating) || c->isfloating)
1100 resize(c, nx, ny, c->w, c->h, False);
1107 nexttiled(Client *c) {
1108 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1113 propertynotify(XEvent *e) {
1116 XPropertyEvent *ev = &e->xproperty;
1118 if(ev->state == PropertyDelete)
1119 return; /* ignore */
1120 if((c = getclient(ev->window))) {
1123 case XA_WM_TRANSIENT_FOR:
1124 XGetTransientForHint(dpy, c->win, &trans);
1125 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1128 case XA_WM_NORMAL_HINTS:
1136 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1145 quit(const char *arg) {
1146 readin = running = False;
1150 reapply(const char *arg) {
1151 static Bool zerotags[LENGTH(tags)] = { 0 };
1154 for(c = clients; c; c = c->next) {
1155 memcpy(c->tags, zerotags, sizeof zerotags);
1162 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1166 /* set minimum possible */
1172 /* temporarily remove base dimensions */
1176 /* adjust for aspect limits */
1177 if (c->minay > 0 && c->maxay > 0 && c->minax > 0 && c->maxax > 0) {
1178 if (w * c->maxay > h * c->maxax)
1179 w = h * c->maxax / c->maxay;
1180 else if (w * c->minay < h * c->minax)
1181 h = w * c->minay / c->minax;
1184 /* adjust for increment value */
1190 /* restore base dimensions */
1194 if(c->minw > 0 && w < c->minw)
1196 if(c->minh > 0 && h < c->minh)
1198 if(c->maxw > 0 && w > c->maxw)
1200 if(c->maxh > 0 && h > c->maxh)
1203 if(w <= 0 || h <= 0)
1206 x = sw - w - 2 * c->border;
1208 y = sh - h - 2 * c->border;
1209 if(x + w + 2 * c->border < sx)
1211 if(y + h + 2 * c->border < sy)
1213 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1216 c->w = wc.width = w;
1217 c->h = wc.height = h;
1218 wc.border_width = c->border;
1219 XConfigureWindow(dpy, c->win,
1220 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1227 resizemouse(Client *c) {
1234 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1235 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1237 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
1239 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1242 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1243 c->w + c->border - 1, c->h + c->border - 1);
1244 XUngrabPointer(dpy, CurrentTime);
1245 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1247 case ConfigureRequest:
1250 handler[ev.type](&ev);
1254 if((nw = ev.xmotion.x - ocx - 2 * c->border + 1) <= 0)
1256 if((nh = ev.xmotion.y - ocy - 2 * c->border + 1) <= 0)
1258 if(!c->isfloating && (lt->arrange != floating) && (abs(nw - c->w) > SNAP || abs(nh - c->h) > SNAP))
1259 togglefloating(NULL);
1260 if((lt->arrange == floating) || c->isfloating)
1261 resize(c, c->x, c->y, nw, nh, True);
1276 if(sel->isfloating || (lt->arrange == floating))
1277 XRaiseWindow(dpy, sel->win);
1278 if(lt->arrange != floating) {
1279 wc.stack_mode = Below;
1280 wc.sibling = barwin;
1281 if(!sel->isfloating) {
1282 XConfigureWindow(dpy, sel->win, CWSibling|CWStackMode, &wc);
1283 wc.sibling = sel->win;
1285 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
1288 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1289 wc.sibling = c->win;
1293 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1299 char sbuf[sizeof stext];
1302 unsigned int len, offset;
1305 /* main event loop, also reads status text from stdin */
1307 xfd = ConnectionNumber(dpy);
1310 len = sizeof stext - 1;
1311 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1315 FD_SET(STDIN_FILENO, &rd);
1317 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1320 eprint("select failed\n");
1322 if(FD_ISSET(STDIN_FILENO, &rd)) {
1323 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1325 strncpy(stext, strerror(errno), len);
1329 strncpy(stext, "EOF", 4);
1333 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1334 if(*p == '\n' || *p == '\0') {
1336 strncpy(stext, sbuf, len);
1337 p += r - 1; /* p is sbuf + offset + r - 1 */
1338 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1341 memmove(sbuf, p - r + 1, r);
1348 while(XPending(dpy)) {
1349 XNextEvent(dpy, &ev);
1350 if(handler[ev.type])
1351 (handler[ev.type])(&ev); /* call handler */
1358 unsigned int i, num;
1359 Window *wins, d1, d2;
1360 XWindowAttributes wa;
1363 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1364 for(i = 0; i < num; i++) {
1365 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1366 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1368 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1369 manage(wins[i], &wa);
1371 for(i = 0; i < num; i++) { /* now the transients */
1372 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1374 if(XGetTransientForHint(dpy, wins[i], &d1)
1375 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1376 manage(wins[i], &wa);
1384 setclientstate(Client *c, long state) {
1385 long data[] = {state, None};
1387 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1388 PropModeReplace, (unsigned char *)data, 2);
1392 setlayout(const char *arg) {
1397 for(i = 0; i < LENGTH(layouts); i++)
1398 if(!strcmp(arg, layouts[i].symbol))
1400 if(i == LENGTH(layouts))
1412 XSetWindowAttributes wa;
1415 screen = DefaultScreen(dpy);
1416 root = RootWindow(dpy, screen);
1419 sw = DisplayWidth(dpy, screen);
1420 sh = DisplayHeight(dpy, screen);
1423 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1424 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1425 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1426 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1427 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1428 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1431 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1432 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1433 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1435 /* init appearance */
1436 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1437 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1438 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1439 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1440 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1441 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1443 dc.h = bh = dc.font.height + 2;
1444 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1445 dc.gc = XCreateGC(dpy, root, 0, 0);
1446 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1448 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1451 seltags = emallocz(TAGSZ);
1452 prevtags = emallocz(TAGSZ);
1453 seltags[0] = prevtags[0] = True;
1459 for(blw = i = 0; i < LENGTH(layouts); i++) {
1460 i = textw(layouts[i].symbol);
1465 wa.override_redirect = 1;
1466 wa.background_pixmap = ParentRelative;
1467 wa.event_mask = ButtonPressMask|ExposureMask;
1469 barwin = XCreateWindow(dpy, root, BX, BY, BW, bh, 0, DefaultDepth(dpy, screen),
1470 CopyFromParent, DefaultVisual(dpy, screen),
1471 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1472 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1473 XMapRaised(dpy, barwin);
1474 strcpy(stext, "dwm-"VERSION);
1477 /* EWMH support per view */
1478 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1479 PropModeReplace, (unsigned char *) netatom, NetLast);
1481 /* select for events */
1482 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1483 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1484 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1485 XSelectInput(dpy, root, wa.event_mask);
1493 spawn(const char *arg) {
1494 static char *shell = NULL;
1496 if(!shell && !(shell = getenv("SHELL")))
1500 /* The double-fork construct avoids zombie processes and keeps the code
1501 * clean from stupid signal handlers. */
1505 close(ConnectionNumber(dpy));
1507 execl(shell, shell, "-c", arg, (char *)NULL);
1508 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1517 tag(const char *arg) {
1522 for(i = 0; i < LENGTH(tags); i++)
1523 sel->tags[i] = (NULL == arg);
1524 sel->tags[idxoftag(arg)] = True;
1529 textnw(const char *text, unsigned int len) {
1533 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1536 return XTextWidth(dc.font.xfont, text, len);
1540 textw(const char *text) {
1541 return textnw(text, strlen(text)) + dc.font.height;
1546 unsigned int i, n, nx, ny, nw, nh, mw, th;
1553 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next))
1557 mw = (n == 1) ? MOW : MW;
1558 th = (n > 1) ? TH / (n - 1) : 0;
1559 if(n > 1 && th < bh)
1562 for(i = 0, c = mc = nexttiled(clients); c; c = nexttiled(c->next)) {
1563 if(i == 0) { /* master */
1564 nw = mw - 2 * c->border;
1565 nh = MH - 2 * c->border;
1567 else { /* tile window */
1571 nw = TW - 2 * c->border;
1573 if(i + 1 == n) /* remainder */
1574 nh = (TY + TH) - ny - 2 * c->border;
1576 nh = th - 2 * c->border;
1578 resize(c, nx, ny, nw, nh, RESIZEHINTS);
1579 if((RESIZEHINTS) && ((c->h < bh) || (c->h > nh) || (c->w < bh) || (c->w > nw)))
1580 /* client doesn't accept size constraints */
1581 resize(c, nx, ny, nw, nh, False);
1582 if(n > 1 && th != TH)
1583 ny = c->y + c->h + 2 * c->border;
1589 togglefloating(const char *arg) {
1592 sel->isfloating = !sel->isfloating;
1594 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1599 toggletag(const char *arg) {
1605 sel->tags[i] = !sel->tags[i];
1606 for(j = 0; j < LENGTH(tags) && !sel->tags[j]; j++);
1607 if(j == LENGTH(tags))
1608 sel->tags[i] = True; /* at least one tag must be enabled */
1613 toggleview(const char *arg) {
1617 seltags[i] = !seltags[i];
1618 for(j = 0; j < LENGTH(tags) && !seltags[j]; j++);
1619 if(j == LENGTH(tags))
1620 seltags[i] = True; /* at least one tag must be viewed */
1628 XMoveWindow(dpy, c->win, c->x, c->y);
1629 c->isbanned = False;
1633 unmanage(Client *c) {
1636 wc.border_width = c->oldborder;
1637 /* The server grab construct avoids race conditions. */
1639 XSetErrorHandler(xerrordummy);
1640 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1645 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1646 setclientstate(c, WithdrawnState);
1650 XSetErrorHandler(xerror);
1656 unmapnotify(XEvent *e) {
1658 XUnmapEvent *ev = &e->xunmap;
1660 if((c = getclient(ev->window)))
1665 updatesizehints(Client *c) {
1669 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1671 c->flags = size.flags;
1672 if(c->flags & PBaseSize) {
1673 c->basew = size.base_width;
1674 c->baseh = size.base_height;
1676 else if(c->flags & PMinSize) {
1677 c->basew = size.min_width;
1678 c->baseh = size.min_height;
1681 c->basew = c->baseh = 0;
1682 if(c->flags & PResizeInc) {
1683 c->incw = size.width_inc;
1684 c->inch = size.height_inc;
1687 c->incw = c->inch = 0;
1688 if(c->flags & PMaxSize) {
1689 c->maxw = size.max_width;
1690 c->maxh = size.max_height;
1693 c->maxw = c->maxh = 0;
1694 if(c->flags & PMinSize) {
1695 c->minw = size.min_width;
1696 c->minh = size.min_height;
1698 else if(c->flags & PBaseSize) {
1699 c->minw = size.base_width;
1700 c->minh = size.base_height;
1703 c->minw = c->minh = 0;
1704 if(c->flags & PAspect) {
1705 c->minax = size.min_aspect.x;
1706 c->maxax = size.max_aspect.x;
1707 c->minay = size.min_aspect.y;
1708 c->maxay = size.max_aspect.y;
1711 c->minax = c->maxax = c->minay = c->maxay = 0;
1712 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1713 && c->maxw == c->minw && c->maxh == c->minh);
1717 updatetitle(Client *c) {
1718 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1719 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1723 updatewmhints(Client *c) {
1726 if((wmh = XGetWMHints(dpy, c->win))) {
1728 sel->isurgent = False;
1730 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1737 view(const char *arg) {
1740 for(i = 0; i < LENGTH(tags); i++)
1741 tmp[i] = (NULL == arg);
1742 tmp[idxoftag(arg)] = True;
1744 if(memcmp(seltags, tmp, TAGSZ) != 0) {
1745 memcpy(prevtags, seltags, TAGSZ);
1746 memcpy(seltags, tmp, TAGSZ);
1752 viewprevtag(const char *arg) {
1754 memcpy(tmp, seltags, TAGSZ);
1755 memcpy(seltags, prevtags, TAGSZ);
1756 memcpy(prevtags, tmp, TAGSZ);
1760 /* There's no way to check accesses to destroyed windows, thus those cases are
1761 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1762 * default error handler, which may call exit. */
1764 xerror(Display *dpy, XErrorEvent *ee) {
1765 if(ee->error_code == BadWindow
1766 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1767 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1768 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1769 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1770 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1771 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1772 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1774 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1775 ee->request_code, ee->error_code);
1776 return xerrorxlib(dpy, ee); /* may call exit */
1780 xerrordummy(Display *dpy, XErrorEvent *ee) {
1784 /* Startup Error handler to check if another window manager
1785 * is already running. */
1787 xerrorstart(Display *dpy, XErrorEvent *ee) {
1793 zoom(const char *arg) {
1796 if(!sel || !dozoom || sel->isfloating)
1798 if(c == nexttiled(clients))
1799 if(!(c = nexttiled(c->next)))
1808 main(int argc, char *argv[]) {
1809 if(argc == 2 && !strcmp("-v", argv[1]))
1810 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1812 eprint("usage: dwm [-v]\n");
1814 setlocale(LC_CTYPE, "");
1815 if(!(dpy = XOpenDisplay(0)))
1816 eprint("dwm: cannot open display\n");