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>
44 #include <X11/extensions/Xinerama.h>
48 #define BUTTONMASK (ButtonPressMask|ButtonReleaseMask)
49 #define CLEANMASK(mask) (mask & ~(numlockmask|LockMask))
50 #define LENGTH(x) (sizeof x / sizeof x[0])
52 #define MOUSEMASK (BUTTONMASK|PointerMotionMask)
56 enum { BarTop, BarBot, BarOff }; /* bar position */
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 View View;
64 typedef struct Client Client;
68 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
69 int minax, maxax, minay, maxay;
72 unsigned int border, oldborder;
73 Bool isbanned, isfixed, isfloating, isurgent;
82 unsigned long norm[ColLast];
83 unsigned long sel[ColLast];
93 } DC; /* draw context */
98 void (*func)(const char *arg);
104 void (*arrange)(View *);
115 int x, y, w, h, wax, way, wah, waw;
121 /* function declarations */
122 void applyrules(Client *c);
124 void attach(Client *c);
125 void attachstack(Client *c);
127 void buttonpress(XEvent *e);
128 void checkotherwm(void);
130 void configure(Client *c);
131 void configurenotify(XEvent *e);
132 void configurerequest(XEvent *e);
133 void destroynotify(XEvent *e);
134 void detach(Client *c);
135 void detachstack(Client *c);
136 void drawbar(View *v);
137 void drawsquare(View *v, Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
138 void drawtext(View *v, const char *text, unsigned long col[ColLast], Bool invert);
139 void *emallocz(unsigned int size);
140 void enternotify(XEvent *e);
141 void eprint(const char *errstr, ...);
142 void expose(XEvent *e);
143 void floating(View *v); /* default floating layout */
144 void focus(Client *c);
145 void focusin(XEvent *e);
146 void focusnext(const char *arg);
147 void focusprev(const char *arg);
148 Client *getclient(Window w);
149 unsigned long getcolor(const char *colstr);
150 View *getviewbar(Window barwin);
151 View *getview(Client *c);
152 long getstate(Window w);
153 Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
154 void grabbuttons(Client *c, Bool focused);
156 unsigned int idxoftag(const char *tag);
157 void initfont(const char *fontstr);
158 Bool isoccupied(unsigned int t);
159 Bool isprotodel(Client *c);
160 Bool isurgent(unsigned int t);
161 Bool isvisible(Client *c);
162 void keypress(XEvent *e);
163 void killclient(const char *arg);
164 void manage(Window w, XWindowAttributes *wa);
165 void mappingnotify(XEvent *e);
166 void maprequest(XEvent *e);
168 void movemouse(Client *c);
169 Client *nexttiled(Client *c, View *v);
170 void propertynotify(XEvent *e);
171 void quit(const char *arg);
172 void reapply(const char *arg);
173 void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
174 void resizemouse(Client *c);
175 void restack(View *v);
178 void setclientstate(Client *c, long state);
179 void setlayout(const char *arg);
180 void setmwfact(const char *arg);
182 void spawn(const char *arg);
183 void tag(const char *arg);
184 unsigned int textnw(const char *text, unsigned int len);
185 unsigned int textw(const char *text);
187 void togglebar(const char *arg);
188 void togglefloating(const char *arg);
189 void toggletag(const char *arg);
190 void toggleview(const char *arg);
191 void unban(Client *c);
192 void unmanage(Client *c);
193 void unmapnotify(XEvent *e);
194 void updatebarpos(View *v);
195 void updatesizehints(Client *c);
196 void updatetitle(Client *c);
197 void updatewmhints(Client *c);
198 void view(const char *arg);
199 void viewprevtag(const char *arg); /* views previous selected tags */
200 int xerror(Display *dpy, XErrorEvent *ee);
201 int xerrordummy(Display *dpy, XErrorEvent *ee);
202 int xerrorstart(Display *dpy, XErrorEvent *ee);
203 void zoom(const char *arg);
204 void selectview(const char *arg);
207 char stext[256], buf[256];
213 int (*xerrorxlib)(Display *, XErrorEvent *);
214 unsigned int bh, bpos;
215 unsigned int blw = 0;
216 unsigned int numlockmask = 0;
217 void (*handler[LASTEvent]) (XEvent *) = {
218 [ButtonPress] = buttonpress,
219 [ConfigureRequest] = configurerequest,
220 [ConfigureNotify] = configurenotify,
221 [DestroyNotify] = destroynotify,
222 [EnterNotify] = enternotify,
225 [KeyPress] = keypress,
226 [MappingNotify] = mappingnotify,
227 [MapRequest] = maprequest,
228 [PropertyNotify] = propertynotify,
229 [UnmapNotify] = unmapnotify
231 Atom wmatom[WMLast], netatom[NetLast];
232 Bool isxinerama = False;
233 Bool domwfact = True;
235 Bool otherwm, readin;
237 Client *clients = NULL;
239 Client *stack = NULL;
240 Cursor cursor[CurLast];
246 /* configuration, allows nested code to access above variables */
249 /* function implementations */
251 applyrules(Client *c) {
253 Bool matched_tag = False;
255 XClassHint ch = { 0 };
258 XGetClassHint(dpy, c->win, &ch);
259 snprintf(buf, sizeof buf, "%s:%s:%s",
260 ch.res_class ? ch.res_class : "",
261 ch.res_name ? ch.res_name : "", c->name);
262 for(i = 0; i < LENGTH(rules); i++) {
264 if(strstr(c->name, r->prop)
265 || (ch.res_class && strstr(ch.res_class, r->prop))
266 || (ch.res_name && strstr(ch.res_name, r->prop)))
268 c->isfloating = r->isfloating;
271 c->tags[idxoftag(r->tag)] = selview->id;
280 memcpy(c->tags, seltags, sizeof initags);
290 for(c = clients; c; c = c->next)
296 for(i = 0; i < nviews; i++) {
297 views[i].layout->arrange(&views[i]);
312 attachstack(Client *c) {
321 XMoveWindow(dpy, c->win, c->x + 3 * getview(c)->w, c->y);
326 buttonpress(XEvent *e) {
329 XButtonPressedEvent *ev = &e->xbutton;
333 if(ev->window == v->barwin) {
335 for(i = 0; i < LENGTH(tags); i++) {
338 if(ev->button == Button1) {
339 if(ev->state & MODKEY)
344 else if(ev->button == Button3) {
345 if(ev->state & MODKEY)
353 if((ev->x < x + blw) && ev->button == Button1)
356 else if((c = getclient(ev->window))) {
358 if(CLEANMASK(ev->state) != MODKEY)
360 if(ev->button == Button1) {
364 else if(ev->button == Button2) {
365 if((floating != v->layout->arrange) && c->isfloating)
366 togglefloating(NULL);
370 else if(ev->button == Button3 && !c->isfixed) {
380 XSetErrorHandler(xerrorstart);
382 /* this causes an error if some other window manager is running */
383 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
386 eprint("dwm: another window manager is already running\n");
388 XSetErrorHandler(NULL);
389 xerrorxlib = XSetErrorHandler(xerror);
402 XFreeFontSet(dpy, dc.font.set);
404 XFreeFont(dpy, dc.font.xfont);
406 XUngrabKey(dpy, AnyKey, AnyModifier, root);
407 XFreePixmap(dpy, dc.drawable);
409 XFreeCursor(dpy, cursor[CurNormal]);
410 XFreeCursor(dpy, cursor[CurResize]);
411 XFreeCursor(dpy, cursor[CurMove]);
412 for(i = 0; i < nviews; i++)
413 XDestroyWindow(dpy, views[i].barwin);
415 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
419 configure(Client *c) {
422 ce.type = ConfigureNotify;
430 ce.border_width = c->border;
432 ce.override_redirect = False;
433 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
437 configurenotify(XEvent *e) {
438 XConfigureEvent *ev = &e->xconfigure;
441 if(ev->window == root && (ev->width != v->w || ev->height != v->h)) {
442 /* TODO -- update Xinerama dimensions here */
445 XFreePixmap(dpy, dc.drawable);
446 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(root, screen), bh, DefaultDepth(dpy, screen));
447 XResizeWindow(dpy, v->barwin, v->w, bh);
454 configurerequest(XEvent *e) {
456 XConfigureRequestEvent *ev = &e->xconfigurerequest;
459 if((c = getclient(ev->window))) {
460 View *v = getview(c);
461 if(ev->value_mask & CWBorderWidth)
462 c->border = ev->border_width;
463 if(c->isfixed || c->isfloating || (floating == v->layout->arrange)) {
464 if(ev->value_mask & CWX)
466 if(ev->value_mask & CWY)
468 if(ev->value_mask & CWWidth)
470 if(ev->value_mask & CWHeight)
472 if((c->x - v->x + c->w) > v->w && c->isfloating)
473 c->x = v->x + (v->w / 2 - c->w / 2); /* center in x direction */
474 if((c->y - v->y + c->h) > v->h && c->isfloating)
475 c->y = v->y + (v->h / 2 - c->h / 2); /* center in y direction */
476 if((ev->value_mask & (CWX|CWY))
477 && !(ev->value_mask & (CWWidth|CWHeight)))
480 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
488 wc.width = ev->width;
489 wc.height = ev->height;
490 wc.border_width = ev->border_width;
491 wc.sibling = ev->above;
492 wc.stack_mode = ev->detail;
493 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
499 destroynotify(XEvent *e) {
501 XDestroyWindowEvent *ev = &e->xdestroywindow;
503 if((c = getclient(ev->window)))
510 c->prev->next = c->next;
512 c->next->prev = c->prev;
515 c->next = c->prev = NULL;
519 detachstack(Client *c) {
522 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
532 for(c = stack; c && (!isvisible(c) || getview(c) != v); c = c->snext);
533 for(i = 0; i < LENGTH(tags); i++) {
534 dc.w = textw(tags[i]);
535 if(seltags[i] && seltags[i] == v->id) {
536 drawtext(v, tags[i], dc.sel, isurgent(i));
537 drawsquare(v, c && c->tags[i], isoccupied(i), isurgent(i), dc.sel);
540 drawtext(v, tags[i], dc.norm, isurgent(i));
541 drawsquare(v, c && c->tags[i], isoccupied(i), isurgent(i), dc.norm);
546 drawtext(v, v->layout->symbol, dc.norm, False);
555 drawtext(v, stext, dc.norm, False);
559 if((dc.w = dc.x - x) > bh) {
562 drawtext(v, c->name, dc.sel, False);
563 drawsquare(v, False, c->isfloating, False, dc.sel);
566 drawtext(v, NULL, dc.norm, False);
568 XCopyArea(dpy, dc.drawable, v->barwin, dc.gc, 0, 0, v->w, bh, 0, 0);
573 drawsquare(View *v, Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
576 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
578 gcv.foreground = col[invert ? ColBG : ColFG];
579 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
580 x = (dc.font.ascent + dc.font.descent + 2) / 4;
584 r.width = r.height = x + 1;
585 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
588 r.width = r.height = x;
589 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
594 drawtext(View *v, const char *text, unsigned long col[ColLast], Bool invert) {
596 unsigned int len, olen;
597 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
599 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
600 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
604 olen = len = strlen(text);
605 if(len >= sizeof buf)
606 len = sizeof buf - 1;
607 memcpy(buf, text, len);
609 h = dc.font.ascent + dc.font.descent;
610 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
612 /* shorten text if necessary */
613 while(len && (w = textnw(buf, len)) > dc.w - h)
624 return; /* too long */
625 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
627 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
629 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
633 emallocz(unsigned int size) {
634 void *res = calloc(1, size);
637 eprint("fatal: could not malloc() %u bytes\n", size);
642 enternotify(XEvent *e) {
644 XCrossingEvent *ev = &e->xcrossing;
646 if(ev->mode != NotifyNormal || ev->detail == NotifyInferior) {
647 if(!isxinerama || ev->window != root)
650 if((c = getclient(ev->window)))
657 eprint(const char *errstr, ...) {
660 va_start(ap, errstr);
661 vfprintf(stderr, errstr, ap);
669 XExposeEvent *ev = &e->xexpose;
671 if(ev->count == 0 && (v = getviewbar(ev->window)))
676 floating(View *v) { /* default floating layout */
679 domwfact = dozoom = False;
680 for(c = clients; c; c = c->next)
682 resize(c, c->x, c->y, c->w, c->h, True);
689 selview = getview(c);
694 if(!c || (c && !isvisible(c)))
695 for(c = stack; c && (!isvisible(c) || getview(c) != selview); c = c->snext);
696 if(sel && sel != c) {
697 grabbuttons(sel, False);
698 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
703 grabbuttons(c, True);
707 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
708 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
709 selview = getview(c);
712 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
717 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
718 XFocusChangeEvent *ev = &e->xfocus;
720 if(sel && ev->window != sel->win)
721 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
725 focusnext(const char *arg) {
730 for(c = sel->next; c && !isvisible(c); c = c->next);
732 for(c = clients; c && !isvisible(c); c = c->next);
740 focusprev(const char *arg) {
745 for(c = sel->prev; c && !isvisible(c); c = c->prev);
747 for(c = clients; c && c->next; c = c->next);
748 for(; c && !isvisible(c); c = c->prev);
757 getclient(Window w) {
760 for(c = clients; c && c->win != w; c = c->next);
765 getcolor(const char *colstr) {
766 Colormap cmap = DefaultColormap(dpy, screen);
769 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
770 eprint("error, cannot allocate color '%s'\n", colstr);
775 getviewbar(Window barwin) {
778 for(i = 0; i < nviews; i++)
779 if(views[i].barwin == barwin)
788 for(i = 0; i < LENGTH(tags); i++)
790 return &views[c->tags[i] - 1];
791 return &views[0]; /* fallback */
798 unsigned char *p = NULL;
799 unsigned long n, extra;
802 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
803 &real, &format, &n, &extra, (unsigned char **)&p);
804 if(status != Success)
813 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
818 if(!text || size == 0)
821 XGetTextProperty(dpy, w, &name, atom);
824 if(name.encoding == XA_STRING)
825 strncpy(text, (char *)name.value, size - 1);
827 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
829 strncpy(text, *list, size - 1);
830 XFreeStringList(list);
833 text[size - 1] = '\0';
839 grabbuttons(Client *c, Bool focused) {
840 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
843 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
844 GrabModeAsync, GrabModeSync, None, None);
845 XGrabButton(dpy, Button1, MODKEY|LockMask, c->win, False, BUTTONMASK,
846 GrabModeAsync, GrabModeSync, None, None);
847 XGrabButton(dpy, Button1, MODKEY|numlockmask, c->win, False, BUTTONMASK,
848 GrabModeAsync, GrabModeSync, None, None);
849 XGrabButton(dpy, Button1, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
850 GrabModeAsync, GrabModeSync, None, None);
852 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
853 GrabModeAsync, GrabModeSync, None, None);
854 XGrabButton(dpy, Button2, MODKEY|LockMask, c->win, False, BUTTONMASK,
855 GrabModeAsync, GrabModeSync, None, None);
856 XGrabButton(dpy, Button2, MODKEY|numlockmask, c->win, False, BUTTONMASK,
857 GrabModeAsync, GrabModeSync, None, None);
858 XGrabButton(dpy, Button2, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
859 GrabModeAsync, GrabModeSync, None, None);
861 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
862 GrabModeAsync, GrabModeSync, None, None);
863 XGrabButton(dpy, Button3, MODKEY|LockMask, c->win, False, BUTTONMASK,
864 GrabModeAsync, GrabModeSync, None, None);
865 XGrabButton(dpy, Button3, MODKEY|numlockmask, c->win, False, BUTTONMASK,
866 GrabModeAsync, GrabModeSync, None, None);
867 XGrabButton(dpy, Button3, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
868 GrabModeAsync, GrabModeSync, None, None);
871 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
872 GrabModeAsync, GrabModeSync, None, None);
879 XModifierKeymap *modmap;
881 /* init modifier map */
882 modmap = XGetModifierMapping(dpy);
883 for(i = 0; i < 8; i++)
884 for(j = 0; j < modmap->max_keypermod; j++) {
885 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
886 numlockmask = (1 << i);
888 XFreeModifiermap(modmap);
890 XUngrabKey(dpy, AnyKey, AnyModifier, root);
891 for(i = 0; i < LENGTH(keys); i++) {
892 code = XKeysymToKeycode(dpy, keys[i].keysym);
893 XGrabKey(dpy, code, keys[i].mod, root, True,
894 GrabModeAsync, GrabModeAsync);
895 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
896 GrabModeAsync, GrabModeAsync);
897 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
898 GrabModeAsync, GrabModeAsync);
899 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
900 GrabModeAsync, GrabModeAsync);
905 idxoftag(const char *tag) {
908 for(i = 0; (i < LENGTH(tags)) && (tags[i] != tag); i++);
909 return (i < LENGTH(tags)) ? i : 0;
913 initfont(const char *fontstr) {
914 char *def, **missing;
919 XFreeFontSet(dpy, dc.font.set);
920 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
923 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
924 XFreeStringList(missing);
927 XFontSetExtents *font_extents;
928 XFontStruct **xfonts;
930 dc.font.ascent = dc.font.descent = 0;
931 font_extents = XExtentsOfFontSet(dc.font.set);
932 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
933 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
934 if(dc.font.ascent < (*xfonts)->ascent)
935 dc.font.ascent = (*xfonts)->ascent;
936 if(dc.font.descent < (*xfonts)->descent)
937 dc.font.descent = (*xfonts)->descent;
943 XFreeFont(dpy, dc.font.xfont);
944 dc.font.xfont = NULL;
945 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
946 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
947 eprint("error, cannot load font: '%s'\n", fontstr);
948 dc.font.ascent = dc.font.xfont->ascent;
949 dc.font.descent = dc.font.xfont->descent;
951 dc.font.height = dc.font.ascent + dc.font.descent;
955 isoccupied(unsigned int t) {
958 for(c = clients; c; c = c->next)
965 isprotodel(Client *c) {
970 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
971 for(i = 0; !ret && i < n; i++)
972 if(protocols[i] == wmatom[WMDelete])
980 isurgent(unsigned int t) {
983 for(c = clients; c; c = c->next)
984 if(c->isurgent && c->tags[t])
990 isvisible(Client *c) {
993 for(i = 0; i < LENGTH(tags); i++)
994 if(c->tags[i] && seltags[i])
1000 keypress(XEvent *e) {
1006 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
1007 for(i = 0; i < LENGTH(keys); i++)
1008 if(keysym == keys[i].keysym
1009 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
1012 keys[i].func(keys[i].arg);
1017 killclient(const char *arg) {
1022 if(isprotodel(sel)) {
1023 ev.type = ClientMessage;
1024 ev.xclient.window = sel->win;
1025 ev.xclient.message_type = wmatom[WMProtocols];
1026 ev.xclient.format = 32;
1027 ev.xclient.data.l[0] = wmatom[WMDelete];
1028 ev.xclient.data.l[1] = CurrentTime;
1029 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
1032 XKillClient(dpy, sel->win);
1036 manage(Window w, XWindowAttributes *wa) {
1037 Client *c, *t = NULL;
1043 c = emallocz(sizeof(Client));
1044 c->tags = emallocz(sizeof initags);
1051 c->x = wa->x + v->x;
1052 c->y = wa->y + v->y;
1055 c->oldborder = wa->border_width;
1057 if(c->w == v->w && c->h == v->h) {
1060 c->border = wa->border_width;
1063 if(c->x + c->w + 2 * c->border > v->wax + v->waw)
1064 c->x = v->wax + v->waw - c->w - 2 * c->border;
1065 if(c->y + c->h + 2 * c->border > v->way + v->wah)
1066 c->y = v->way + v->wah - c->h - 2 * c->border;
1071 c->border = BORDERPX;
1073 wc.border_width = c->border;
1074 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1075 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1076 configure(c); /* propagates border_width, if size doesn't change */
1078 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
1079 grabbuttons(c, False);
1081 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
1082 for(t = clients; t && t->win != trans; t = t->next);
1084 memcpy(c->tags, t->tags, sizeof initags);
1086 c->isfloating = (rettrans == Success) || c->isfixed;
1089 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
1091 XMapWindow(dpy, c->win);
1092 setclientstate(c, NormalState);
1097 mappingnotify(XEvent *e) {
1098 XMappingEvent *ev = &e->xmapping;
1100 XRefreshKeyboardMapping(ev);
1101 if(ev->request == MappingKeyboard)
1106 maprequest(XEvent *e) {
1107 static XWindowAttributes wa;
1108 XMapRequestEvent *ev = &e->xmaprequest;
1110 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1112 if(wa.override_redirect)
1114 if(!getclient(ev->window))
1115 manage(ev->window, &wa);
1119 movemouse(Client *c) {
1120 int x1, y1, ocx, ocy, di, nx, ny;
1129 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1130 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1132 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1134 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1137 XUngrabPointer(dpy, CurrentTime);
1139 case ConfigureRequest:
1142 handler[ev.type](&ev);
1146 nx = ocx + (ev.xmotion.x - x1);
1147 ny = ocy + (ev.xmotion.y - y1);
1148 if(abs(v->wax - nx) < SNAP)
1150 else if(abs((v->wax + v->waw) - (nx + c->w + 2 * c->border)) < SNAP)
1151 nx = v->wax + v->waw - c->w - 2 * c->border;
1152 if(abs(v->way - ny) < SNAP)
1154 else if(abs((v->way + v->wah) - (ny + c->h + 2 * c->border)) < SNAP)
1155 ny = v->way + v->wah - c->h - 2 * c->border;
1156 if(!c->isfloating && (v->layout->arrange != floating) && (abs(nx - c->x) > SNAP || abs(ny - c->y) > SNAP))
1157 togglefloating(NULL);
1158 if((v->layout->arrange == floating) || c->isfloating)
1159 resize(c, nx, ny, c->w, c->h, False);
1166 nexttiled(Client *c, View *v) {
1167 for(; c && (c->isfloating || getview(c) != v || !isvisible(c)); c = c->next);
1172 propertynotify(XEvent *e) {
1175 XPropertyEvent *ev = &e->xproperty;
1177 if(ev->state == PropertyDelete)
1178 return; /* ignore */
1179 if((c = getclient(ev->window))) {
1182 case XA_WM_TRANSIENT_FOR:
1183 XGetTransientForHint(dpy, c->win, &trans);
1184 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1187 case XA_WM_NORMAL_HINTS:
1192 drawbar(getview(c));
1195 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1204 quit(const char *arg) {
1205 readin = running = False;
1209 reapply(const char *arg) {
1210 static Bool zerotags[LENGTH(tags)] = { 0 };
1213 for(c = clients; c; c = c->next) {
1214 memcpy(c->tags, zerotags, sizeof zerotags);
1221 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1227 /* set minimum possible */
1233 /* temporarily remove base dimensions */
1237 /* adjust for aspect limits */
1238 if (c->minay > 0 && c->maxay > 0 && c->minax > 0 && c->maxax > 0) {
1239 if (w * c->maxay > h * c->maxax)
1240 w = h * c->maxax / c->maxay;
1241 else if (w * c->minay < h * c->minax)
1242 h = w * c->minay / c->minax;
1245 /* adjust for increment value */
1251 /* restore base dimensions */
1255 if(c->minw > 0 && w < c->minw)
1257 if(c->minh > 0 && h < c->minh)
1259 if(c->maxw > 0 && w > c->maxw)
1261 if(c->maxh > 0 && h > c->maxh)
1264 if(w <= 0 || h <= 0)
1267 x = v->w - w - 2 * c->border;
1269 y = v->h - h - 2 * c->border;
1270 if(x + w + 2 * c->border < v->x)
1272 if(y + h + 2 * c->border < v->y)
1274 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1277 c->w = wc.width = w;
1278 c->h = wc.height = h;
1279 wc.border_width = c->border;
1280 XConfigureWindow(dpy, c->win,
1281 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1288 resizemouse(Client *c) {
1297 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1298 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1300 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
1302 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1305 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1306 c->w + c->border - 1, c->h + c->border - 1);
1307 XUngrabPointer(dpy, CurrentTime);
1308 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1310 case ConfigureRequest:
1313 handler[ev.type](&ev);
1317 if((nw = ev.xmotion.x - ocx - 2 * c->border + 1) <= 0)
1319 if((nh = ev.xmotion.y - ocy - 2 * c->border + 1) <= 0)
1321 if(!c->isfloating && (v->layout->arrange != floating) && (abs(nw - c->w) > SNAP || abs(nh - c->h) > SNAP))
1322 togglefloating(NULL);
1323 if((v->layout->arrange == floating) || c->isfloating)
1324 resize(c, c->x, c->y, nw, nh, True);
1339 if(sel->isfloating || (v->layout->arrange == floating))
1340 XRaiseWindow(dpy, sel->win);
1341 if(v->layout->arrange != floating) {
1342 wc.stack_mode = Below;
1343 wc.sibling = v->barwin;
1344 if(!sel->isfloating) {
1345 XConfigureWindow(dpy, sel->win, CWSibling|CWStackMode, &wc);
1346 wc.sibling = sel->win;
1348 for(c = nexttiled(clients, v); c; c = nexttiled(c->next, v)) {
1351 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1352 wc.sibling = c->win;
1356 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1362 char sbuf[sizeof stext];
1365 unsigned int len, offset;
1368 /* main event loop, also reads status text from stdin */
1370 xfd = ConnectionNumber(dpy);
1373 len = sizeof stext - 1;
1374 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1378 FD_SET(STDIN_FILENO, &rd);
1380 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1383 eprint("select failed\n");
1385 if(FD_ISSET(STDIN_FILENO, &rd)) {
1386 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1388 strncpy(stext, strerror(errno), len);
1392 strncpy(stext, "EOF", 4);
1396 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1397 if(*p == '\n' || *p == '\0') {
1399 strncpy(stext, sbuf, len);
1400 p += r - 1; /* p is sbuf + offset + r - 1 */
1401 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1404 memmove(sbuf, p - r + 1, r);
1411 while(XPending(dpy)) {
1412 XNextEvent(dpy, &ev);
1413 if(handler[ev.type])
1414 (handler[ev.type])(&ev); /* call handler */
1421 unsigned int i, num;
1422 Window *wins, d1, d2;
1423 XWindowAttributes wa;
1426 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1427 for(i = 0; i < num; i++) {
1428 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1429 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1431 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1432 manage(wins[i], &wa);
1434 for(i = 0; i < num; i++) { /* now the transients */
1435 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1437 if(XGetTransientForHint(dpy, wins[i], &d1)
1438 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1439 manage(wins[i], &wa);
1447 setclientstate(Client *c, long state) {
1448 long data[] = {state, None};
1450 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1451 PropModeReplace, (unsigned char *)data, 2);
1455 setlayout(const char *arg) {
1461 if(v->layout == &layouts[LENGTH(layouts)])
1462 v->layout = &layouts[0];
1465 for(i = 0; i < LENGTH(layouts); i++)
1466 if(!strcmp(arg, layouts[i].symbol))
1468 if(i == LENGTH(layouts))
1470 v->layout = &layouts[i];
1479 setmwfact(const char *arg) {
1486 /* arg handling, manipulate mwfact */
1489 else if(sscanf(arg, "%lf", &delta) == 1) {
1490 if(arg[0] == '+' || arg[0] == '-')
1496 else if(v->mwfact > 0.9)
1506 XSetWindowAttributes wa;
1507 XineramaScreenInfo *info = NULL;
1510 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1511 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1512 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1513 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1514 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1515 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1518 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1519 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1520 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1522 if((isxinerama = XineramaIsActive(dpy)))
1523 info = XineramaQueryScreens(dpy, &nviews);
1524 #if defined(AIM_XINERAMA)
1526 nviews = 2; /* aim Xinerama */
1528 selview = views = emallocz(nviews * sizeof(View));
1530 screen = DefaultScreen(dpy);
1531 root = RootWindow(dpy, screen);
1533 /* init appearance */
1534 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1535 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1536 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1537 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1538 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1539 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1541 dc.h = bh = dc.font.height + 2;
1542 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1543 dc.gc = XCreateGC(dpy, root, 0, 0);
1544 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1546 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1548 for(blw = i = 0; i < LENGTH(layouts); i++) {
1549 i = textw(layouts[i].symbol);
1554 seltags = emallocz(sizeof initags);
1555 prevtags = emallocz(sizeof initags);
1556 memcpy(seltags, initags, sizeof initags);
1557 memcpy(prevtags, initags, sizeof initags);
1559 for(i = 0; i < nviews; i++) {
1564 if(nviews != 1 && isxinerama) {
1566 #if defined(AIM_XINERAMA)
1567 v->w = DisplayWidth(dpy, screen) / 2;
1568 v->x = (i == 0) ? 0 : v->w;
1570 v->h = DisplayHeight(dpy, screen);
1572 v->x = info[i].x_org;
1573 v->y = info[i].y_org;
1574 v->w = info[i].width;
1575 v->h = info[i].height;
1581 v->w = DisplayWidth(dpy, screen);
1582 v->h = DisplayHeight(dpy, screen);
1587 v->layout = &layouts[0];
1589 // TODO: bpos per screen?
1591 wa.override_redirect = 1;
1592 wa.background_pixmap = ParentRelative;
1593 wa.event_mask = ButtonPressMask|ExposureMask;
1596 v->barwin = XCreateWindow(dpy, root, v->x, v->y, v->w, bh, 0,
1597 DefaultDepth(dpy, screen), CopyFromParent, DefaultVisual(dpy, screen),
1598 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1599 XDefineCursor(dpy, v->barwin, cursor[CurNormal]);
1601 XMapRaised(dpy, v->barwin);
1602 strcpy(stext, "dwm-"VERSION);
1604 /* EWMH support per view */
1605 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1606 PropModeReplace, (unsigned char *) netatom, NetLast);
1608 /* select for events */
1609 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1610 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1611 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1612 XSelectInput(dpy, root, wa.event_mask);
1622 selview = &views[0];
1626 spawn(const char *arg) {
1627 static char *shell = NULL;
1629 if(!shell && !(shell = getenv("SHELL")))
1633 /* The double-fork construct avoids zombie processes and keeps the code
1634 * clean from stupid signal handlers. */
1638 close(ConnectionNumber(dpy));
1640 execl(shell, shell, "-c", arg, (char *)NULL);
1641 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1650 tag(const char *arg) {
1655 for(i = 0; i < LENGTH(tags); i++)
1656 sel->tags[i] = (NULL == arg) ? selview->id : 0;
1657 sel->tags[idxoftag(arg)] = selview->id;
1662 textnw(const char *text, unsigned int len) {
1666 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1669 return XTextWidth(dc.font.xfont, text, len);
1673 textw(const char *text) {
1674 return textnw(text, strlen(text)) + dc.font.height;
1679 unsigned int i, n, nx, ny, nw, nh, mw, th;
1682 domwfact = dozoom = True;
1686 for(n = 0, c = nexttiled(clients, v); c; c = nexttiled(c->next, v))
1690 mw = (n == 1) ? v->waw : v->mwfact * v->waw;
1691 th = (n > 1) ? v->wah / (n - 1) : 0;
1692 if(n > 1 && th < bh)
1695 for(i = 0, c = mc = nexttiled(clients, v); c; c = nexttiled(c->next, v)) {
1696 if(i == 0) { /* master */
1699 nw = mw - 2 * c->border;
1700 nh = v->wah - 2 * c->border;
1702 else { /* tile window */
1705 nx += mc->w + 2 * mc->border;
1706 nw = v->waw - mw - 2 * c->border;
1708 if(i + 1 == n) /* remainder */
1709 nh = (v->way + v->wah) - ny - 2 * c->border;
1711 nh = th - 2 * c->border;
1713 resize(c, nx, ny, nw, nh, RESIZEHINTS);
1714 if((RESIZEHINTS) && ((c->h < bh) || (c->h > nh) || (c->w < bh) || (c->w > nw)))
1715 /* client doesn't accept size constraints */
1716 resize(c, nx, ny, nw, nh, False);
1717 if(n > 1 && th != v->wah)
1718 ny = c->y + c->h + 2 * c->border;
1724 togglebar(const char *arg) {
1726 bpos = (BARPOS == BarOff) ? BarTop : BARPOS;
1729 updatebarpos(selview);
1734 togglefloating(const char *arg) {
1737 sel->isfloating = !sel->isfloating;
1739 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1744 toggletag(const char *arg) {
1750 sel->tags[i] = !sel->tags[i];
1751 for(j = 0; j < LENGTH(tags) && !sel->tags[j]; j++);
1752 if(j == LENGTH(tags))
1753 sel->tags[i] = selview->id; /* at least one tag must be enabled */
1758 toggleview(const char *arg) {
1762 seltags[i] = !seltags[i];
1763 for(j = 0; j < LENGTH(tags) && !seltags[j]; j++);
1764 if(j == LENGTH(tags))
1765 seltags[i] = selview->id; /* at least one tag must be viewed */
1773 XMoveWindow(dpy, c->win, c->x, c->y);
1774 c->isbanned = False;
1778 unmanage(Client *c) {
1781 wc.border_width = c->oldborder;
1782 /* The server grab construct avoids race conditions. */
1784 XSetErrorHandler(xerrordummy);
1785 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1790 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1791 setclientstate(c, WithdrawnState);
1795 XSetErrorHandler(xerror);
1801 unmapnotify(XEvent *e) {
1803 XUnmapEvent *ev = &e->xunmap;
1805 if((c = getclient(ev->window)))
1810 updatebarpos(View *v) {
1821 XMoveWindow(dpy, v->barwin, v->x, v->y);
1825 XMoveWindow(dpy, v->barwin, v->x, v->y + v->wah);
1828 XMoveWindow(dpy, v->barwin, v->x, v->y - bh);
1832 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1836 updatesizehints(Client *c) {
1840 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1842 c->flags = size.flags;
1843 if(c->flags & PBaseSize) {
1844 c->basew = size.base_width;
1845 c->baseh = size.base_height;
1847 else if(c->flags & PMinSize) {
1848 c->basew = size.min_width;
1849 c->baseh = size.min_height;
1852 c->basew = c->baseh = 0;
1853 if(c->flags & PResizeInc) {
1854 c->incw = size.width_inc;
1855 c->inch = size.height_inc;
1858 c->incw = c->inch = 0;
1859 if(c->flags & PMaxSize) {
1860 c->maxw = size.max_width;
1861 c->maxh = size.max_height;
1864 c->maxw = c->maxh = 0;
1865 if(c->flags & PMinSize) {
1866 c->minw = size.min_width;
1867 c->minh = size.min_height;
1869 else if(c->flags & PBaseSize) {
1870 c->minw = size.base_width;
1871 c->minh = size.base_height;
1874 c->minw = c->minh = 0;
1875 if(c->flags & PAspect) {
1876 c->minax = size.min_aspect.x;
1877 c->maxax = size.max_aspect.x;
1878 c->minay = size.min_aspect.y;
1879 c->maxay = size.max_aspect.y;
1882 c->minax = c->maxax = c->minay = c->maxay = 0;
1883 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1884 && c->maxw == c->minw && c->maxh == c->minh);
1888 updatetitle(Client *c) {
1889 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1890 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1894 updatewmhints(Client *c) {
1897 if((wmh = XGetWMHints(dpy, c->win))) {
1898 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1904 view(const char *arg) {
1906 int tmp[LENGTH(tags)];
1908 for(i = 0; i < LENGTH(tags); i++)
1909 tmp[i] = (NULL == arg) ? selview->id : 0;
1910 tmp[idxoftag(arg)] = selview->id;
1911 if(memcmp(seltags, tmp, sizeof initags) != 0) {
1912 memcpy(prevtags, seltags, sizeof initags);
1913 memcpy(seltags, tmp, sizeof initags);
1924 XQueryPointer(dpy, root, &win, &win, &x, &y, &i, &i, &mask);
1925 for(i = 0; i < nviews; i++) {
1926 if((x >= views[i].x && x < views[i].x + views[i].w)
1927 && (y >= views[i].y && y < views[i].y + views[i].h))
1934 viewprevtag(const char *arg) {
1935 static Bool tmp[LENGTH(tags)];
1937 memcpy(tmp, seltags, sizeof initags);
1938 memcpy(seltags, prevtags, sizeof initags);
1939 memcpy(prevtags, tmp, sizeof initags);
1943 /* There's no way to check accesses to destroyed windows, thus those cases are
1944 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1945 * default error handler, which may call exit. */
1947 xerror(Display *dpy, XErrorEvent *ee) {
1948 if(ee->error_code == BadWindow
1949 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1950 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1951 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1952 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1953 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1954 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1955 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1957 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1958 ee->request_code, ee->error_code);
1959 return xerrorxlib(dpy, ee); /* may call exit */
1963 xerrordummy(Display *dpy, XErrorEvent *ee) {
1967 /* Startup Error handler to check if another window manager
1968 * is already running. */
1970 xerrorstart(Display *dpy, XErrorEvent *ee) {
1976 zoom(const char *arg) {
1979 if(!sel || !dozoom || sel->isfloating)
1981 if(c == nexttiled(clients, getview(c)))
1982 if(!(c = nexttiled(c->next, getview(c))))
1991 main(int argc, char *argv[]) {
1992 if(argc == 2 && !strcmp("-v", argv[1]))
1993 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1995 eprint("usage: dwm [-v]\n");
1997 setlocale(LC_CTYPE, "");
1998 if(!(dpy = XOpenDisplay(0)))
1999 eprint("dwm: cannot open display\n");