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)
53 enum { BarTop, BarBot, BarOff }; /* bar position */
54 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
55 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
56 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
57 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
60 typedef struct Client Client;
64 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
65 int minax, maxax, minay, maxay;
67 unsigned int border, oldborder;
68 Bool isbanned, isfixed, isfloating;
78 unsigned long norm[ColLast];
79 unsigned long sel[ColLast];
89 } DC; /* draw context */
94 void (*func)(const char *arg);
100 void (*arrange)(void);
114 /* function declarations */
115 void applyrules(Client *c);
117 void attach(Client *c);
118 void attachstack(Client *c);
120 void buttonpress(XEvent *e);
121 void checkotherwm(void);
123 void compileregs(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, unsigned long col[ColLast]);
132 void drawtext(const char *text, unsigned long col[ColLast]);
133 void *emallocz(unsigned int size);
134 void enternotify(XEvent *e);
135 void eprint(const char *errstr, ...);
136 void expose(XEvent *e);
137 void floating(void); /* default floating layout */
138 void focus(Client *c);
139 void focusin(XEvent *e);
140 void focusnext(const char *arg);
141 void focusprev(const char *arg);
142 Client *getclient(Window w);
143 unsigned long getcolor(const char *colstr);
144 long getstate(Window w);
145 Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
146 void grabbuttons(Client *c, Bool focused);
148 unsigned int idxoftag(const char *tag);
149 void initfont(const char *fontstr);
150 Bool isoccupied(unsigned int t);
151 Bool isprotodel(Client *c);
152 Bool isvisible(Client *c);
153 void keypress(XEvent *e);
154 void killclient(const char *arg);
155 void leavenotify(XEvent *e);
156 void manage(Window w, XWindowAttributes *wa);
157 void mappingnotify(XEvent *e);
158 void maprequest(XEvent *e);
159 void maximize(const char *arg);
160 void movemouse(Client *c);
161 Client *nexttiled(Client *c);
162 void propertynotify(XEvent *e);
163 void quit(const char *arg);
164 void reapply(const char *arg);
165 void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
166 void resizemouse(Client *c);
170 void setclientstate(Client *c, long state);
171 void setlayout(const char *arg);
172 void setmwfact(const char *arg);
174 void spawn(const char *arg);
175 void tag(const char *arg);
176 unsigned int textnw(const char *text, unsigned int len);
177 unsigned int textw(const char *text);
179 void togglebar(const char *arg);
180 void togglefloating(const char *arg);
181 void toggletag(const char *arg);
182 void toggleview(const char *arg);
183 void unban(Client *c);
184 void unmanage(Client *c);
185 void unmapnotify(XEvent *e);
186 void updatebarpos(void);
187 void updatesizehints(Client *c);
188 void updatetitle(Client *c);
189 void view(const char *arg);
190 void viewprevtag(const char *arg); /* views previous selected tags */
191 int xerror(Display *dpy, XErrorEvent *ee);
192 int xerrordummy(Display *dsply, XErrorEvent *ee);
193 int xerrorstart(Display *dsply, XErrorEvent *ee);
194 void zoom(const char *arg);
199 int screen, sx, sy, sw, sh, wax, way, waw, wah;
200 int (*xerrorxlib)(Display *, XErrorEvent *);
201 unsigned int bh, bpos;
202 unsigned int blw = 0;
203 unsigned int numlockmask = 0;
204 void (*handler[LASTEvent]) (XEvent *) = {
205 [ButtonPress] = buttonpress,
206 [ConfigureRequest] = configurerequest,
207 [ConfigureNotify] = configurenotify,
208 [DestroyNotify] = destroynotify,
209 [EnterNotify] = enternotify,
212 [KeyPress] = keypress,
213 [LeaveNotify] = leavenotify,
214 [MappingNotify] = mappingnotify,
215 [MapRequest] = maprequest,
216 [PropertyNotify] = propertynotify,
217 [UnmapNotify] = unmapnotify
219 Atom wmatom[WMLast], netatom[NetLast];
220 Bool domwfact = True;
222 Bool otherwm, readin;
224 Bool selscreen = True;
225 Client *clients = NULL;
227 Client *stack = NULL;
228 Cursor cursor[CurLast];
231 Layout *layout = NULL;
235 /* configuration, allows nested code to access above variables */
238 Bool prevtags[LENGTH(tags)];
240 /* function implementations */
242 applyrules(Client *c) {
243 static char buf[512];
246 Bool matched = False;
247 XClassHint ch = { 0 };
250 XGetClassHint(dpy, c->win, &ch);
251 snprintf(buf, sizeof buf, "%s:%s:%s",
252 ch.res_class ? ch.res_class : "",
253 ch.res_name ? ch.res_name : "", c->name);
254 for(i = 0; i < LENGTH(rules); i++)
255 if(regs[i].propregex && !regexec(regs[i].propregex, buf, 1, &tmp, 0)) {
256 c->isfloating = rules[i].isfloating;
257 for(j = 0; regs[i].tagregex && j < LENGTH(tags); j++) {
258 if(!regexec(regs[i].tagregex, tags[j], 1, &tmp, 0)) {
269 memcpy(c->tags, seltags, sizeof seltags);
276 for(c = clients; c; c = c->next)
295 attachstack(Client *c) {
304 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
309 buttonpress(XEvent *e) {
312 XButtonPressedEvent *ev = &e->xbutton;
314 if(ev->window == barwin) {
316 for(i = 0; i < LENGTH(tags); i++) {
319 if(ev->button == Button1) {
320 if(ev->state & MODKEY)
325 else if(ev->button == Button3) {
326 if(ev->state & MODKEY)
334 if((ev->x < x + blw) && ev->button == Button1)
337 else if((c = getclient(ev->window))) {
339 if(CLEANMASK(ev->state) != MODKEY)
341 if(ev->button == Button1) {
342 if((layout->arrange == floating) || c->isfloating)
345 togglefloating(NULL);
348 else if(ev->button == Button2) {
349 if((floating != layout->arrange) && c->isfloating)
350 togglefloating(NULL);
354 else if(ev->button == Button3 && !c->isfixed) {
355 if((floating == layout->arrange) || c->isfloating)
358 togglefloating(NULL);
367 XSetErrorHandler(xerrorstart);
369 /* this causes an error if some other window manager is running */
370 XSelectInput(dpy, root, SubstructureRedirectMask);
373 eprint("dwm: another window manager is already running\n");
375 XSetErrorHandler(NULL);
376 xerrorxlib = XSetErrorHandler(xerror);
388 XFreeFontSet(dpy, dc.font.set);
390 XFreeFont(dpy, dc.font.xfont);
391 XUngrabKey(dpy, AnyKey, AnyModifier, root);
392 XFreePixmap(dpy, dc.drawable);
394 XDestroyWindow(dpy, barwin);
395 XFreeCursor(dpy, cursor[CurNormal]);
396 XFreeCursor(dpy, cursor[CurResize]);
397 XFreeCursor(dpy, cursor[CurMove]);
398 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
409 regs = emallocz(LENGTH(rules) * sizeof(Regs));
410 for(i = 0; i < LENGTH(rules); i++) {
412 reg = emallocz(sizeof(regex_t));
413 if(regcomp(reg, rules[i].prop, REG_EXTENDED))
416 regs[i].propregex = reg;
419 reg = emallocz(sizeof(regex_t));
420 if(regcomp(reg, rules[i].tags, REG_EXTENDED))
423 regs[i].tagregex = reg;
429 configure(Client *c) {
432 ce.type = ConfigureNotify;
440 ce.border_width = c->border;
442 ce.override_redirect = False;
443 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
447 configurenotify(XEvent *e) {
448 XConfigureEvent *ev = &e->xconfigure;
450 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
453 XFreePixmap(dpy, dc.drawable);
454 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
455 XResizeWindow(dpy, barwin, sw, bh);
462 configurerequest(XEvent *e) {
464 XConfigureRequestEvent *ev = &e->xconfigurerequest;
467 if((c = getclient(ev->window))) {
468 if(ev->value_mask & CWBorderWidth)
469 c->border = ev->border_width;
470 if(c->isfixed || c->isfloating || (floating == layout->arrange)) {
471 if(ev->value_mask & CWX)
473 if(ev->value_mask & CWY)
475 if(ev->value_mask & CWWidth)
477 if(ev->value_mask & CWHeight)
479 if((c->x + c->w) > sw && c->isfloating)
480 c->x = sw / 2 - c->w / 2; /* center in x direction */
481 if((c->y + c->h) > sh && c->isfloating)
482 c->y = sh / 2 - c->h / 2; /* center in y direction */
483 if((ev->value_mask & (CWX | CWY))
484 && !(ev->value_mask & (CWWidth | CWHeight)))
487 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
495 wc.width = ev->width;
496 wc.height = ev->height;
497 wc.border_width = ev->border_width;
498 wc.sibling = ev->above;
499 wc.stack_mode = ev->detail;
500 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
506 destroynotify(XEvent *e) {
508 XDestroyWindowEvent *ev = &e->xdestroywindow;
510 if((c = getclient(ev->window)))
517 c->prev->next = c->next;
519 c->next->prev = c->prev;
522 c->next = c->prev = NULL;
526 detachstack(Client *c) {
529 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
538 for(i = 0; i < LENGTH(tags); i++) {
539 dc.w = textw(tags[i]);
541 drawtext(tags[i], dc.sel);
542 drawsquare(sel && sel->tags[i], isoccupied(i), dc.sel);
545 drawtext(tags[i], dc.norm);
546 drawsquare(sel && sel->tags[i], isoccupied(i), dc.norm);
551 drawtext(layout->symbol, dc.norm);
559 drawtext(stext, dc.norm);
560 if((dc.w = dc.x - x) > bh) {
563 drawtext(sel->name, dc.sel);
564 drawsquare(False, sel->isfloating, dc.sel);
567 drawtext(NULL, dc.norm);
569 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, sw, bh, 0, 0);
574 drawsquare(Bool filled, Bool empty, unsigned long col[ColLast]) {
577 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
579 gcv.foreground = col[ColFG];
580 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
581 x = (dc.font.ascent + dc.font.descent + 2) / 4;
585 r.width = r.height = x + 1;
586 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
589 r.width = r.height = x;
590 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
595 drawtext(const char *text, unsigned long col[ColLast]) {
597 static char buf[256];
598 unsigned int len, olen;
599 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
601 XSetForeground(dpy, dc.gc, col[ColBG]);
602 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
606 olen = len = strlen(text);
607 if(len >= sizeof buf)
608 len = sizeof buf - 1;
609 memcpy(buf, text, len);
611 h = dc.font.ascent + dc.font.descent;
612 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
614 /* shorten text if necessary */
615 while(len && (w = textnw(buf, len)) > dc.w - h)
626 return; /* too long */
627 XSetForeground(dpy, dc.gc, col[ColFG]);
629 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
631 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
635 emallocz(unsigned int size) {
636 void *res = calloc(1, size);
639 eprint("fatal: could not malloc() %u bytes\n", size);
644 enternotify(XEvent *e) {
646 XCrossingEvent *ev = &e->xcrossing;
648 if(ev->mode != NotifyNormal || ev->detail == NotifyInferior)
650 if((c = getclient(ev->window)))
652 else if(ev->window == root) {
659 eprint(const char *errstr, ...) {
662 va_start(ap, errstr);
663 vfprintf(stderr, errstr, ap);
670 XExposeEvent *ev = &e->xexpose;
673 if(ev->window == barwin)
679 floating(void) { /* default floating layout */
682 domwfact = dozoom = False;
683 for(c = clients; c; c = c->next)
685 resize(c, c->x, c->y, c->w, c->h, True);
690 if((!c && selscreen) || (c && !isvisible(c)))
691 for(c = stack; c && !isvisible(c); c = c->snext);
692 if(sel && sel != c) {
693 grabbuttons(sel, False);
694 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
699 grabbuttons(c, True);
706 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
707 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
710 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
714 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
715 XFocusChangeEvent *ev = &e->xfocus;
717 if(sel && ev->window != sel->win)
718 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
722 focusnext(const char *arg) {
727 for(c = sel->next; c && !isvisible(c); c = c->next);
729 for(c = clients; c && !isvisible(c); c = c->next);
737 focusprev(const char *arg) {
742 for(c = sel->prev; c && !isvisible(c); c = c->prev);
744 for(c = clients; c && c->next; c = c->next);
745 for(; c && !isvisible(c); c = c->prev);
754 getclient(Window w) {
757 for(c = clients; c && c->win != w; c = c->next);
762 getcolor(const char *colstr) {
763 Colormap cmap = DefaultColormap(dpy, screen);
766 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
767 eprint("error, cannot allocate color '%s'\n", colstr);
775 unsigned char *p = NULL;
776 unsigned long n, extra;
779 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
780 &real, &format, &n, &extra, (unsigned char **)&p);
781 if(status != Success)
790 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
795 if(!text || size == 0)
798 XGetTextProperty(dpy, w, &name, atom);
801 if(name.encoding == XA_STRING)
802 strncpy(text, (char *)name.value, size - 1);
804 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
806 strncpy(text, *list, size - 1);
807 XFreeStringList(list);
810 text[size - 1] = '\0';
816 grabbuttons(Client *c, Bool focused) {
817 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
820 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
821 GrabModeAsync, GrabModeSync, None, None);
822 XGrabButton(dpy, Button1, MODKEY | LockMask, c->win, False, BUTTONMASK,
823 GrabModeAsync, GrabModeSync, None, None);
824 XGrabButton(dpy, Button1, MODKEY | numlockmask, c->win, False, BUTTONMASK,
825 GrabModeAsync, GrabModeSync, None, None);
826 XGrabButton(dpy, Button1, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
827 GrabModeAsync, GrabModeSync, None, None);
829 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
830 GrabModeAsync, GrabModeSync, None, None);
831 XGrabButton(dpy, Button2, MODKEY | LockMask, c->win, False, BUTTONMASK,
832 GrabModeAsync, GrabModeSync, None, None);
833 XGrabButton(dpy, Button2, MODKEY | numlockmask, c->win, False, BUTTONMASK,
834 GrabModeAsync, GrabModeSync, None, None);
835 XGrabButton(dpy, Button2, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
836 GrabModeAsync, GrabModeSync, None, None);
838 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
839 GrabModeAsync, GrabModeSync, None, None);
840 XGrabButton(dpy, Button3, MODKEY | LockMask, c->win, False, BUTTONMASK,
841 GrabModeAsync, GrabModeSync, None, None);
842 XGrabButton(dpy, Button3, MODKEY | numlockmask, c->win, False, BUTTONMASK,
843 GrabModeAsync, GrabModeSync, None, None);
844 XGrabButton(dpy, Button3, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
845 GrabModeAsync, GrabModeSync, None, None);
848 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
849 GrabModeAsync, GrabModeSync, None, None);
857 XUngrabKey(dpy, AnyKey, AnyModifier, root);
858 for(i = 0; i < LENGTH(keys); i++) {
859 code = XKeysymToKeycode(dpy, keys[i].keysym);
860 XGrabKey(dpy, code, keys[i].mod, root, True,
861 GrabModeAsync, GrabModeAsync);
862 XGrabKey(dpy, code, keys[i].mod | LockMask, root, True,
863 GrabModeAsync, GrabModeAsync);
864 XGrabKey(dpy, code, keys[i].mod | numlockmask, root, True,
865 GrabModeAsync, GrabModeAsync);
866 XGrabKey(dpy, code, keys[i].mod | numlockmask | LockMask, root, True,
867 GrabModeAsync, GrabModeAsync);
872 idxoftag(const char *tag) {
875 for(i = 0; (i < LENGTH(tags)) && (tags[i] != tag); i++);
876 return (i < LENGTH(tags)) ? i : 0;
880 initfont(const char *fontstr) {
881 char *def, **missing;
886 XFreeFontSet(dpy, dc.font.set);
887 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
890 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
891 XFreeStringList(missing);
894 XFontSetExtents *font_extents;
895 XFontStruct **xfonts;
897 dc.font.ascent = dc.font.descent = 0;
898 font_extents = XExtentsOfFontSet(dc.font.set);
899 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
900 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
901 if(dc.font.ascent < (*xfonts)->ascent)
902 dc.font.ascent = (*xfonts)->ascent;
903 if(dc.font.descent < (*xfonts)->descent)
904 dc.font.descent = (*xfonts)->descent;
910 XFreeFont(dpy, dc.font.xfont);
911 dc.font.xfont = NULL;
912 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
913 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
914 eprint("error, cannot load font: '%s'\n", fontstr);
915 dc.font.ascent = dc.font.xfont->ascent;
916 dc.font.descent = dc.font.xfont->descent;
918 dc.font.height = dc.font.ascent + dc.font.descent;
922 isoccupied(unsigned int t) {
925 for(c = clients; c; c = c->next)
932 isprotodel(Client *c) {
937 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
938 for(i = 0; !ret && i < n; i++)
939 if(protocols[i] == wmatom[WMDelete])
947 isvisible(Client *c) {
950 for(i = 0; i < LENGTH(tags); i++)
951 if(c->tags[i] && seltags[i])
957 keypress(XEvent *e) {
963 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
964 for(i = 0; i < LENGTH(keys); i++)
965 if(keysym == keys[i].keysym
966 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
969 keys[i].func(keys[i].arg);
974 killclient(const char *arg) {
979 if(isprotodel(sel)) {
980 ev.type = ClientMessage;
981 ev.xclient.window = sel->win;
982 ev.xclient.message_type = wmatom[WMProtocols];
983 ev.xclient.format = 32;
984 ev.xclient.data.l[0] = wmatom[WMDelete];
985 ev.xclient.data.l[1] = CurrentTime;
986 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
989 XKillClient(dpy, sel->win);
993 leavenotify(XEvent *e) {
994 XCrossingEvent *ev = &e->xcrossing;
996 if((ev->window == root) && !ev->same_screen) {
1003 manage(Window w, XWindowAttributes *wa) {
1004 Client *c, *t = NULL;
1009 c = emallocz(sizeof(Client));
1010 c->tags = emallocz(sizeof seltags);
1016 c->oldborder = wa->border_width;
1017 if(c->w == sw && c->h == sh) {
1020 c->border = wa->border_width;
1023 if(c->x + c->w + 2 * c->border > wax + waw)
1024 c->x = wax + waw - c->w - 2 * c->border;
1025 if(c->y + c->h + 2 * c->border > way + wah)
1026 c->y = way + wah - c->h - 2 * c->border;
1031 c->border = BORDERPX;
1033 wc.border_width = c->border;
1034 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1035 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1036 configure(c); /* propagates border_width, if size doesn't change */
1038 XSelectInput(dpy, w, EnterWindowMask | FocusChangeMask | PropertyChangeMask | StructureNotifyMask);
1039 grabbuttons(c, False);
1041 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
1042 for(t = clients; t && t->win != trans; t = t->next);
1044 memcpy(c->tags, t->tags, sizeof seltags);
1047 c->isfloating = (rettrans == Success) || c->isfixed;
1050 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
1052 XMapWindow(dpy, c->win);
1053 setclientstate(c, NormalState);
1058 mappingnotify(XEvent *e) {
1059 XMappingEvent *ev = &e->xmapping;
1061 XRefreshKeyboardMapping(ev);
1062 if(ev->request == MappingKeyboard)
1067 maprequest(XEvent *e) {
1068 static XWindowAttributes wa;
1069 XMapRequestEvent *ev = &e->xmaprequest;
1071 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1073 if(wa.override_redirect)
1075 if(!getclient(ev->window))
1076 manage(ev->window, &wa);
1080 maximize(const char *arg) {
1081 if(!sel || (!sel->isfloating && layout->arrange != floating))
1083 resize(sel, wax, way, waw - 2 * sel->border, wah - 2 * sel->border, True);
1087 movemouse(Client *c) {
1088 int x1, y1, ocx, ocy, di, nx, ny;
1095 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1096 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1098 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1100 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask, &ev);
1103 XUngrabPointer(dpy, CurrentTime);
1105 case ConfigureRequest:
1108 handler[ev.type](&ev);
1112 nx = ocx + (ev.xmotion.x - x1);
1113 ny = ocy + (ev.xmotion.y - y1);
1114 if(abs(wax + nx) < SNAP)
1116 else if(abs((wax + waw) - (nx + c->w + 2 * c->border)) < SNAP)
1117 nx = wax + waw - c->w - 2 * c->border;
1118 if(abs(way - ny) < SNAP)
1120 else if(abs((way + wah) - (ny + c->h + 2 * c->border)) < SNAP)
1121 ny = way + wah - c->h - 2 * c->border;
1122 resize(c, nx, ny, c->w, c->h, False);
1129 nexttiled(Client *c) {
1130 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1135 propertynotify(XEvent *e) {
1138 XPropertyEvent *ev = &e->xproperty;
1140 if(ev->state == PropertyDelete)
1141 return; /* ignore */
1142 if((c = getclient(ev->window))) {
1145 case XA_WM_TRANSIENT_FOR:
1146 XGetTransientForHint(dpy, c->win, &trans);
1147 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1150 case XA_WM_NORMAL_HINTS:
1154 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1163 quit(const char *arg) {
1164 readin = running = False;
1168 reapply(const char *arg) {
1169 static Bool zerotags[LENGTH(tags)] = { 0 };
1172 for(c = clients; c; c = c->next) {
1173 memcpy(c->tags, zerotags, sizeof zerotags);
1180 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1184 /* set minimum possible */
1190 /* temporarily remove base dimensions */
1194 /* adjust for aspect limits */
1195 if (c->minay > 0 && c->maxay > 0 && c->minax > 0 && c->maxax > 0) {
1196 if (w * c->maxay > h * c->maxax)
1197 w = h * c->maxax / c->maxay;
1198 else if (w * c->minay < h * c->minax)
1199 h = w * c->minay / c->minax;
1202 /* adjust for increment value */
1208 /* restore base dimensions */
1212 if(c->minw > 0 && w < c->minw)
1214 if(c->minh > 0 && h < c->minh)
1216 if(c->maxw > 0 && w > c->maxw)
1218 if(c->maxh > 0 && h > c->maxh)
1221 if(w <= 0 || h <= 0)
1223 /* offscreen appearance fixes */
1225 x = sw - w - 2 * c->border;
1227 y = sh - h - 2 * c->border;
1228 if(x + w + 2 * c->border < sx)
1230 if(y + h + 2 * c->border < sy)
1232 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1235 c->w = wc.width = w;
1236 c->h = wc.height = h;
1237 wc.border_width = c->border;
1238 XConfigureWindow(dpy, c->win, CWX | CWY | CWWidth | CWHeight | CWBorderWidth, &wc);
1245 resizemouse(Client *c) {
1252 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1253 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1255 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
1257 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask , &ev);
1260 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1261 c->w + c->border - 1, c->h + c->border - 1);
1262 XUngrabPointer(dpy, CurrentTime);
1263 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1265 case ConfigureRequest:
1268 handler[ev.type](&ev);
1272 if((nw = ev.xmotion.x - ocx - 2 * c->border + 1) <= 0)
1274 if((nh = ev.xmotion.y - ocy - 2 * c->border + 1) <= 0)
1276 resize(c, c->x, c->y, nw, nh, True);
1291 if(sel->isfloating || (layout->arrange == floating))
1292 XRaiseWindow(dpy, sel->win);
1293 if(layout->arrange != floating) {
1294 wc.stack_mode = Below;
1295 wc.sibling = barwin;
1296 if(!sel->isfloating) {
1297 XConfigureWindow(dpy, sel->win, CWSibling | CWStackMode, &wc);
1298 wc.sibling = sel->win;
1300 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
1303 XConfigureWindow(dpy, c->win, CWSibling | CWStackMode, &wc);
1304 wc.sibling = c->win;
1308 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1314 char buf[sizeof stext];
1317 unsigned int len, offset;
1320 /* main event loop, also reads status text from stdin */
1322 xfd = ConnectionNumber(dpy);
1325 len = sizeof stext - 1;
1326 buf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1330 FD_SET(STDIN_FILENO, &rd);
1332 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1335 eprint("select failed\n");
1337 if(FD_ISSET(STDIN_FILENO, &rd)) {
1338 switch((r = read(STDIN_FILENO, buf + offset, len - offset))) {
1340 strncpy(stext, strerror(errno), len);
1344 strncpy(stext, "EOF", 4);
1348 for(p = buf + offset; r > 0; p++, r--, offset++)
1349 if(*p == '\n' || *p == '\0') {
1351 strncpy(stext, buf, len);
1352 p += r - 1; /* p is buf + offset + r - 1 */
1353 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1356 memmove(buf, p - r + 1, r);
1363 while(XPending(dpy)) {
1364 XNextEvent(dpy, &ev);
1365 if(handler[ev.type])
1366 (handler[ev.type])(&ev); /* call handler */
1373 unsigned int i, num;
1374 Window *wins, d1, d2;
1375 XWindowAttributes wa;
1378 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1379 for(i = 0; i < num; i++) {
1380 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1381 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1383 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1384 manage(wins[i], &wa);
1386 for(i = 0; i < num; i++) { /* now the transients */
1387 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1389 if(XGetTransientForHint(dpy, wins[i], &d1)
1390 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1391 manage(wins[i], &wa);
1399 setclientstate(Client *c, long state) {
1400 long data[] = {state, None};
1402 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1403 PropModeReplace, (unsigned char *)data, 2);
1407 setlayout(const char *arg) {
1411 if(++layout == &layouts[LENGTH(layouts)])
1412 layout = &layouts[0];
1415 for(i = 0; i < LENGTH(layouts); i++)
1416 if(!strcmp(arg, layouts[i].symbol))
1418 if(i == LENGTH(layouts))
1420 layout = &layouts[i];
1429 setmwfact(const char *arg) {
1434 /* arg handling, manipulate mwfact */
1437 else if(sscanf(arg, "%lf", &delta) == 1) {
1438 if(arg[0] == '+' || arg[0] == '-')
1444 else if(mwfact > 0.9)
1453 unsigned int i, j, mask;
1455 XModifierKeymap *modmap;
1456 XSetWindowAttributes wa;
1459 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1460 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1461 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1462 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1463 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1464 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1465 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1466 PropModeReplace, (unsigned char *) netatom, NetLast);
1469 cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1470 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1471 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1475 sw = DisplayWidth(dpy, screen);
1476 sh = DisplayHeight(dpy, screen);
1478 /* init modifier map */
1479 modmap = XGetModifierMapping(dpy);
1480 for(i = 0; i < 8; i++)
1481 for(j = 0; j < modmap->max_keypermod; j++) {
1482 if(modmap->modifiermap[i * modmap->max_keypermod + j]
1483 == XKeysymToKeycode(dpy, XK_Num_Lock))
1484 numlockmask = (1 << i);
1486 XFreeModifiermap(modmap);
1488 /* select for events */
1489 wa.event_mask = SubstructureRedirectMask | SubstructureNotifyMask
1490 | EnterWindowMask | LeaveWindowMask | StructureNotifyMask;
1491 wa.cursor = cursor[CurNormal];
1492 XChangeWindowAttributes(dpy, root, CWEventMask | CWCursor, &wa);
1493 XSelectInput(dpy, root, wa.event_mask);
1499 memcpy(prevtags, seltags, sizeof seltags);
1502 /* init appearance */
1503 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1504 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1505 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1506 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1507 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1508 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1510 dc.h = bh = dc.font.height + 2;
1514 layout = &layouts[0];
1515 for(blw = i = 0; i < LENGTH(layouts); i++) {
1516 j = textw(layouts[i].symbol);
1523 wa.override_redirect = 1;
1524 wa.background_pixmap = ParentRelative;
1525 wa.event_mask = ButtonPressMask | ExposureMask;
1526 barwin = XCreateWindow(dpy, root, sx, sy, sw, bh, 0,
1527 DefaultDepth(dpy, screen), CopyFromParent, DefaultVisual(dpy, screen),
1528 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
1529 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1531 XMapRaised(dpy, barwin);
1532 strcpy(stext, "dwm-"VERSION);
1533 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
1534 dc.gc = XCreateGC(dpy, root, 0, 0);
1535 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1537 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1539 /* multihead support */
1540 selscreen = XQueryPointer(dpy, root, &w, &w, &d, &d, &d, &d, &mask);
1545 spawn(const char *arg) {
1546 static char *shell = NULL;
1548 if(!shell && !(shell = getenv("SHELL")))
1552 /* The double-fork construct avoids zombie processes and keeps the code
1553 * clean from stupid signal handlers. */
1557 close(ConnectionNumber(dpy));
1559 execl(shell, shell, "-c", arg, (char *)NULL);
1560 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1569 tag(const char *arg) {
1574 for(i = 0; i < LENGTH(tags); i++)
1575 sel->tags[i] = (NULL == arg);
1576 sel->tags[idxoftag(arg)] = True;
1581 textnw(const char *text, unsigned int len) {
1585 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1588 return XTextWidth(dc.font.xfont, text, len);
1592 textw(const char *text) {
1593 return textnw(text, strlen(text)) + dc.font.height;
1598 unsigned int i, n, nx, ny, nw, nh, mw, th;
1601 domwfact = dozoom = True;
1602 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next))
1606 mw = (n == 1) ? waw : mwfact * waw;
1607 th = (n > 1) ? wah / (n - 1) : 0;
1608 if(n > 1 && th < bh)
1613 nw = 0; /* gcc stupidity requires this */
1614 for(i = 0, c = mc = nexttiled(clients); c; c = nexttiled(c->next), i++) {
1615 if(i == 0) { /* master */
1616 nw = mw - 2 * c->border;
1617 nh = wah - 2 * c->border;
1619 else { /* tile window */
1622 nx += mc->w + 2 * mc->border;
1623 nw = waw - nx - 2 * c->border;
1625 if(i + 1 == n) /* remainder */
1626 nh = (way + wah) - ny - 2 * c->border;
1628 nh = th - 2 * c->border;
1630 resize(c, nx, ny, nw, nh, RESIZEHINTS);
1631 if((RESIZEHINTS) && ((c->h < bh) || (c->h > nh) || (c->w < bh) || (c->w > nw)))
1632 /* client doesn't accept size constraints */
1633 resize(c, nx, ny, nw, nh, False);
1634 if(n > 1 && th != wah)
1635 ny = c->y + c->h + 2 * c->border;
1640 togglebar(const char *arg) {
1642 bpos = (BARPOS == BarOff) ? BarTop : BARPOS;
1650 togglefloating(const char *arg) {
1653 sel->isfloating = !sel->isfloating;
1655 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1660 toggletag(const char *arg) {
1666 sel->tags[i] = !sel->tags[i];
1667 for(j = 0; j < LENGTH(tags) && !sel->tags[j]; j++);
1668 if(j == LENGTH(tags))
1669 sel->tags[i] = True; /* at least one tag must be enabled */
1674 toggleview(const char *arg) {
1678 seltags[i] = !seltags[i];
1679 for(j = 0; j < LENGTH(tags) && !seltags[j]; j++);
1680 if(j == LENGTH(tags))
1681 seltags[i] = True; /* at least one tag must be viewed */
1689 XMoveWindow(dpy, c->win, c->x, c->y);
1690 c->isbanned = False;
1694 unmanage(Client *c) {
1697 wc.border_width = c->oldborder;
1698 /* The server grab construct avoids race conditions. */
1700 XSetErrorHandler(xerrordummy);
1701 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1706 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1707 setclientstate(c, WithdrawnState);
1711 XSetErrorHandler(xerror);
1717 unmapnotify(XEvent *e) {
1719 XUnmapEvent *ev = &e->xunmap;
1721 if((c = getclient(ev->window)))
1726 updatebarpos(void) {
1737 XMoveWindow(dpy, barwin, sx, sy);
1741 XMoveWindow(dpy, barwin, sx, sy + wah);
1744 XMoveWindow(dpy, barwin, sx, sy - bh);
1748 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1752 updatesizehints(Client *c) {
1756 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1758 c->flags = size.flags;
1759 if(c->flags & PBaseSize) {
1760 c->basew = size.base_width;
1761 c->baseh = size.base_height;
1763 else if(c->flags & PMinSize) {
1764 c->basew = size.min_width;
1765 c->baseh = size.min_height;
1768 c->basew = c->baseh = 0;
1769 if(c->flags & PResizeInc) {
1770 c->incw = size.width_inc;
1771 c->inch = size.height_inc;
1774 c->incw = c->inch = 0;
1775 if(c->flags & PMaxSize) {
1776 c->maxw = size.max_width;
1777 c->maxh = size.max_height;
1780 c->maxw = c->maxh = 0;
1781 if(c->flags & PMinSize) {
1782 c->minw = size.min_width;
1783 c->minh = size.min_height;
1785 else if(c->flags & PBaseSize) {
1786 c->minw = size.base_width;
1787 c->minh = size.base_height;
1790 c->minw = c->minh = 0;
1791 if(c->flags & PAspect) {
1792 c->minax = size.min_aspect.x;
1793 c->maxax = size.max_aspect.x;
1794 c->minay = size.min_aspect.y;
1795 c->maxay = size.max_aspect.y;
1798 c->minax = c->maxax = c->minay = c->maxay = 0;
1799 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1800 && c->maxw == c->minw && c->maxh == c->minh);
1804 updatetitle(Client *c) {
1805 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1806 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1809 /* There's no way to check accesses to destroyed windows, thus those cases are
1810 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1811 * default error handler, which may call exit. */
1813 xerror(Display *dpy, XErrorEvent *ee) {
1814 if(ee->error_code == BadWindow
1815 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1816 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1817 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1818 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1819 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1820 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1821 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1823 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1824 ee->request_code, ee->error_code);
1825 return xerrorxlib(dpy, ee); /* may call exit */
1829 xerrordummy(Display *dsply, XErrorEvent *ee) {
1833 /* Startup Error handler to check if another window manager
1834 * is already running. */
1836 xerrorstart(Display *dsply, XErrorEvent *ee) {
1842 view(const char *arg) {
1845 memcpy(prevtags, seltags, sizeof seltags);
1846 for(i = 0; i < LENGTH(tags); i++)
1847 seltags[i] = (NULL == arg);
1848 seltags[idxoftag(arg)] = True;
1853 viewprevtag(const char *arg) {
1854 static Bool tmp[LENGTH(tags)];
1856 memcpy(tmp, seltags, sizeof seltags);
1857 memcpy(seltags, prevtags, sizeof seltags);
1858 memcpy(prevtags, tmp, sizeof seltags);
1863 zoom(const char *arg) {
1866 if(!sel || !dozoom || sel->isfloating)
1868 if((c = sel) == nexttiled(clients))
1869 if(!(c = nexttiled(c->next)))
1878 main(int argc, char *argv[]) {
1879 if(argc == 2 && !strcmp("-v", argv[1]))
1880 eprint("dwm-"VERSION", © 2006-2007 Anselm R. Garbe, Sander van Dijk, "
1881 "Jukka Salmi, Premysl Hruby, Szabolcs Nagy\n");
1883 eprint("usage: dwm [-v]\n");
1885 setlocale(LC_CTYPE, "");
1886 if(!(dpy = XOpenDisplay(0)))
1887 eprint("dwm: cannot open display\n");
1888 screen = DefaultScreen(dpy);
1889 root = RootWindow(dpy, screen);