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 MOUSEMASK (BUTTONMASK | PointerMotionMask)
50 enum { BarTop, BarBot, BarOff }; /* bar position */
51 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
52 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
53 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
54 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
57 typedef struct Client Client;
61 int rx, ry, rw, rh; /* revert geometry */
62 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
63 int minax, maxax, minay, maxay;
65 unsigned int border, oldborder;
66 Bool isbanned, isfixed, ismax, isfloating, wasfloating;
76 unsigned long norm[ColLast];
77 unsigned long sel[ColLast];
87 } DC; /* draw context */
92 void (*func)(const char *arg);
98 void (*arrange)(void);
112 /* function declarations */
113 void applyrules(Client *c);
115 void attach(Client *c);
116 void attachstack(Client *c);
118 void buttonpress(XEvent *e);
119 void checkotherwm(void);
121 void compileregs(void);
122 void configure(Client *c);
123 void configurenotify(XEvent *e);
124 void configurerequest(XEvent *e);
125 void destroynotify(XEvent *e);
126 void detach(Client *c);
127 void detachstack(Client *c);
129 void drawsquare(Bool filled, Bool empty, unsigned long col[ColLast]);
130 void drawtext(const char *text, unsigned long col[ColLast]);
131 void *emallocz(unsigned int size);
132 void enternotify(XEvent *e);
133 void eprint(const char *errstr, ...);
134 void expose(XEvent *e);
135 void floating(void); /* default floating layout */
136 void focus(Client *c);
137 void focusnext(const char *arg);
138 void focusprev(const char *arg);
139 Client *getclient(Window w);
140 unsigned long getcolor(const char *colstr);
141 long getstate(Window w);
142 Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
143 void grabbuttons(Client *c, Bool focused);
144 unsigned int idxoftag(const char *tag);
145 void initfont(const char *fontstr);
146 Bool isoccupied(unsigned int t);
147 Bool isprotodel(Client *c);
148 Bool isvisible(Client *c);
149 void keypress(XEvent *e);
150 void killclient(const char *arg);
151 void leavenotify(XEvent *e);
152 void manage(Window w, XWindowAttributes *wa);
153 void mappingnotify(XEvent *e);
154 void maprequest(XEvent *e);
155 void movemouse(Client *c);
156 Client *nexttiled(Client *c);
157 void propertynotify(XEvent *e);
158 void quit(const char *arg);
159 void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
160 void resizemouse(Client *c);
164 void setclientstate(Client *c, long state);
165 void setlayout(const char *arg);
166 void setmwfact(const char *arg);
168 void spawn(const char *arg);
169 void tag(const char *arg);
170 unsigned int textnw(const char *text, unsigned int len);
171 unsigned int textw(const char *text);
173 void togglebar(const char *arg);
174 void togglefloating(const char *arg);
175 void togglemax(const char *arg);
176 void toggletag(const char *arg);
177 void toggleview(const char *arg);
178 void unban(Client *c);
179 void unmanage(Client *c);
180 void unmapnotify(XEvent *e);
181 void updatebarpos(void);
182 void updatesizehints(Client *c);
183 void updatetitle(Client *c);
184 void view(const char *arg);
185 void viewprevtag(const char *arg); /* views previous selected tags */
186 int xerror(Display *dpy, XErrorEvent *ee);
187 int xerrordummy(Display *dsply, XErrorEvent *ee);
188 int xerrorstart(Display *dsply, XErrorEvent *ee);
189 void zoom(const char *arg);
194 int screen, sx, sy, sw, sh, wax, way, waw, wah;
195 int (*xerrorxlib)(Display *, XErrorEvent *);
196 unsigned int bh, bpos;
197 unsigned int blw = 0;
198 unsigned int numlockmask = 0;
199 void (*handler[LASTEvent]) (XEvent *) = {
200 [ButtonPress] = buttonpress,
201 [ConfigureRequest] = configurerequest,
202 [ConfigureNotify] = configurenotify,
203 [DestroyNotify] = destroynotify,
204 [EnterNotify] = enternotify,
205 [LeaveNotify] = leavenotify,
207 [KeyPress] = keypress,
208 [MappingNotify] = mappingnotify,
209 [MapRequest] = maprequest,
210 [PropertyNotify] = propertynotify,
211 [UnmapNotify] = unmapnotify
213 Atom wmatom[WMLast], netatom[NetLast];
214 Bool domwfact = True;
216 Bool otherwm, readin;
218 Bool selscreen = True;
219 Client *clients = NULL;
221 Client *stack = NULL;
222 Cursor cursor[CurLast];
225 Layout *layout = NULL;
229 /* configuration, allows nested code to access above variables */
232 /* function implementations */
234 applyrules(Client *c) {
235 static char buf[512];
238 Bool matched = False;
239 XClassHint ch = { 0 };
242 XGetClassHint(dpy, c->win, &ch);
243 snprintf(buf, sizeof buf, "%s:%s:%s",
244 ch.res_class ? ch.res_class : "",
245 ch.res_name ? ch.res_name : "", c->name);
246 for(i = 0; i < LENGTH(rules); i++)
247 if(regs[i].propregex && !regexec(regs[i].propregex, buf, 1, &tmp, 0)) {
248 c->isfloating = rules[i].isfloating;
249 for(j = 0; regs[i].tagregex && j < LENGTH(tags); j++) {
250 if(!regexec(regs[i].tagregex, tags[j], 1, &tmp, 0)) {
261 memcpy(c->tags, seltags, sizeof seltags);
268 for(c = clients; c; c = c->next)
287 attachstack(Client *c) {
296 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
301 buttonpress(XEvent *e) {
304 XButtonPressedEvent *ev = &e->xbutton;
306 if(ev->window == barwin) {
308 for(i = 0; i < LENGTH(tags); i++) {
311 if(ev->button == Button1) {
312 if(ev->state & MODKEY)
317 else if(ev->button == Button3) {
318 if(ev->state & MODKEY)
326 if((ev->x < x + blw) && ev->button == Button1)
329 else if((c = getclient(ev->window))) {
331 if(CLEANMASK(ev->state) != MODKEY)
333 if(ev->button == Button1) {
334 if((layout->arrange == floating) || c->isfloating)
337 togglefloating(NULL);
340 else if(ev->button == Button2) {
341 if((floating != layout->arrange) && c->isfloating)
342 togglefloating(NULL);
346 else if(ev->button == Button3 && !c->isfixed) {
347 if((floating == layout->arrange) || c->isfloating)
350 togglefloating(NULL);
359 XSetErrorHandler(xerrorstart);
361 /* this causes an error if some other window manager is running */
362 XSelectInput(dpy, root, SubstructureRedirectMask);
365 eprint("dwm: another window manager is already running\n");
367 XSetErrorHandler(NULL);
368 xerrorxlib = XSetErrorHandler(xerror);
380 XFreeFontSet(dpy, dc.font.set);
382 XFreeFont(dpy, dc.font.xfont);
383 XUngrabKey(dpy, AnyKey, AnyModifier, root);
384 XFreePixmap(dpy, dc.drawable);
386 XDestroyWindow(dpy, barwin);
387 XFreeCursor(dpy, cursor[CurNormal]);
388 XFreeCursor(dpy, cursor[CurResize]);
389 XFreeCursor(dpy, cursor[CurMove]);
390 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
401 regs = emallocz(LENGTH(rules) * sizeof(Regs));
402 for(i = 0; i < LENGTH(rules); i++) {
404 reg = emallocz(sizeof(regex_t));
405 if(regcomp(reg, rules[i].prop, REG_EXTENDED))
408 regs[i].propregex = reg;
411 reg = emallocz(sizeof(regex_t));
412 if(regcomp(reg, rules[i].tags, REG_EXTENDED))
415 regs[i].tagregex = reg;
421 configure(Client *c) {
424 ce.type = ConfigureNotify;
432 ce.border_width = c->border;
434 ce.override_redirect = False;
435 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
439 configurenotify(XEvent *e) {
440 XConfigureEvent *ev = &e->xconfigure;
442 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
445 XFreePixmap(dpy, dc.drawable);
446 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
447 XResizeWindow(dpy, barwin, sw, bh);
454 configurerequest(XEvent *e) {
456 XConfigureRequestEvent *ev = &e->xconfigurerequest;
459 if((c = getclient(ev->window))) {
461 if(ev->value_mask & CWBorderWidth)
462 c->border = ev->border_width;
463 if(c->isfixed || c->isfloating || (floating == 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 + c->w) > sw && c->isfloating)
473 c->x = sw / 2 - c->w / 2; /* center in x direction */
474 if((c->y + c->h) > sh && c->isfloating)
475 c->y = sh / 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);
531 for(i = 0; i < LENGTH(tags); i++) {
532 dc.w = textw(tags[i]);
534 drawtext(tags[i], dc.sel);
535 drawsquare(sel && sel->tags[i], isoccupied(i), dc.sel);
538 drawtext(tags[i], dc.norm);
539 drawsquare(sel && sel->tags[i], isoccupied(i), dc.norm);
544 drawtext(layout->symbol, dc.norm);
552 drawtext(stext, dc.norm);
553 if((dc.w = dc.x - x) > bh) {
556 drawtext(sel->name, dc.sel);
557 drawsquare(sel->ismax, sel->isfloating, dc.sel);
560 drawtext(NULL, dc.norm);
562 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, sw, bh, 0, 0);
567 drawsquare(Bool filled, Bool empty, unsigned long col[ColLast]) {
570 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
572 gcv.foreground = col[ColFG];
573 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
574 x = (dc.font.ascent + dc.font.descent + 2) / 4;
578 r.width = r.height = x + 1;
579 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
582 r.width = r.height = x;
583 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
588 drawtext(const char *text, unsigned long col[ColLast]) {
590 static char buf[256];
591 unsigned int len, olen;
592 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
594 XSetForeground(dpy, dc.gc, col[ColBG]);
595 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
599 olen = len = strlen(text);
600 if(len >= sizeof buf)
601 len = sizeof buf - 1;
602 memcpy(buf, text, len);
604 h = dc.font.ascent + dc.font.descent;
605 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
607 /* shorten text if necessary */
608 while(len && (w = textnw(buf, len)) > dc.w - h)
619 return; /* too long */
620 XSetForeground(dpy, dc.gc, col[ColFG]);
622 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
624 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
628 emallocz(unsigned int size) {
629 void *res = calloc(1, size);
632 eprint("fatal: could not malloc() %u bytes\n", size);
637 enternotify(XEvent *e) {
639 XCrossingEvent *ev = &e->xcrossing;
641 if(ev->mode != NotifyNormal || ev->detail == NotifyInferior)
643 if((c = getclient(ev->window)))
645 else if(ev->window == root) {
652 eprint(const char *errstr, ...) {
655 va_start(ap, errstr);
656 vfprintf(stderr, errstr, ap);
663 XExposeEvent *ev = &e->xexpose;
666 if(ev->window == barwin)
672 floating(void) { /* default floating layout */
675 domwfact = dozoom = False;
676 for(c = clients; c; c = c->next)
678 resize(c, c->x, c->y, c->w, c->h, True);
683 if((!c && selscreen) || (c && !isvisible(c)))
684 for(c = stack; c && !isvisible(c); c = c->snext);
685 if(sel && sel != c) {
686 grabbuttons(sel, False);
687 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
692 grabbuttons(c, True);
699 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
700 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
703 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
707 focusnext(const char *arg) {
712 for(c = sel->next; c && !isvisible(c); c = c->next);
714 for(c = clients; c && !isvisible(c); c = c->next);
722 focusprev(const char *arg) {
727 for(c = sel->prev; c && !isvisible(c); c = c->prev);
729 for(c = clients; c && c->next; c = c->next);
730 for(; c && !isvisible(c); c = c->prev);
739 getclient(Window w) {
742 for(c = clients; c && c->win != w; c = c->next);
747 getcolor(const char *colstr) {
748 Colormap cmap = DefaultColormap(dpy, screen);
751 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
752 eprint("error, cannot allocate color '%s'\n", colstr);
760 unsigned char *p = NULL;
761 unsigned long n, extra;
764 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
765 &real, &format, &n, &extra, (unsigned char **)&p);
766 if(status != Success)
775 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
780 if(!text || size == 0)
783 XGetTextProperty(dpy, w, &name, atom);
786 if(name.encoding == XA_STRING)
787 strncpy(text, (char *)name.value, size - 1);
789 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
791 strncpy(text, *list, size - 1);
792 XFreeStringList(list);
795 text[size - 1] = '\0';
801 grabbuttons(Client *c, Bool focused) {
802 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
805 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
806 GrabModeAsync, GrabModeSync, None, None);
807 XGrabButton(dpy, Button1, MODKEY | LockMask, c->win, False, BUTTONMASK,
808 GrabModeAsync, GrabModeSync, None, None);
809 XGrabButton(dpy, Button1, MODKEY | numlockmask, c->win, False, BUTTONMASK,
810 GrabModeAsync, GrabModeSync, None, None);
811 XGrabButton(dpy, Button1, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
812 GrabModeAsync, GrabModeSync, None, None);
814 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
815 GrabModeAsync, GrabModeSync, None, None);
816 XGrabButton(dpy, Button2, MODKEY | LockMask, c->win, False, BUTTONMASK,
817 GrabModeAsync, GrabModeSync, None, None);
818 XGrabButton(dpy, Button2, MODKEY | numlockmask, c->win, False, BUTTONMASK,
819 GrabModeAsync, GrabModeSync, None, None);
820 XGrabButton(dpy, Button2, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
821 GrabModeAsync, GrabModeSync, None, None);
823 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
824 GrabModeAsync, GrabModeSync, None, None);
825 XGrabButton(dpy, Button3, MODKEY | LockMask, c->win, False, BUTTONMASK,
826 GrabModeAsync, GrabModeSync, None, None);
827 XGrabButton(dpy, Button3, MODKEY | numlockmask, c->win, False, BUTTONMASK,
828 GrabModeAsync, GrabModeSync, None, None);
829 XGrabButton(dpy, Button3, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
830 GrabModeAsync, GrabModeSync, None, None);
833 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
834 GrabModeAsync, GrabModeSync, None, None);
838 idxoftag(const char *tag) {
841 for(i = 0; (i < LENGTH(tags)) && (tags[i] != tag); i++);
842 return (i < LENGTH(tags)) ? i : 0;
846 initfont(const char *fontstr) {
847 char *def, **missing;
852 XFreeFontSet(dpy, dc.font.set);
853 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
856 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
857 XFreeStringList(missing);
860 XFontSetExtents *font_extents;
861 XFontStruct **xfonts;
863 dc.font.ascent = dc.font.descent = 0;
864 font_extents = XExtentsOfFontSet(dc.font.set);
865 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
866 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
867 if(dc.font.ascent < (*xfonts)->ascent)
868 dc.font.ascent = (*xfonts)->ascent;
869 if(dc.font.descent < (*xfonts)->descent)
870 dc.font.descent = (*xfonts)->descent;
876 XFreeFont(dpy, dc.font.xfont);
877 dc.font.xfont = NULL;
878 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
879 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
880 eprint("error, cannot load font: '%s'\n", fontstr);
881 dc.font.ascent = dc.font.xfont->ascent;
882 dc.font.descent = dc.font.xfont->descent;
884 dc.font.height = dc.font.ascent + dc.font.descent;
888 isoccupied(unsigned int t) {
891 for(c = clients; c; c = c->next)
898 isprotodel(Client *c) {
903 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
904 for(i = 0; !ret && i < n; i++)
905 if(protocols[i] == wmatom[WMDelete])
913 isvisible(Client *c) {
916 for(i = 0; i < LENGTH(tags); i++)
917 if(c->tags[i] && seltags[i])
923 keypress(XEvent *e) {
930 if(!e) { /* grabkeys */
931 XUngrabKey(dpy, AnyKey, AnyModifier, root);
932 for(i = 0; i < LENGTH(keys); i++) {
933 code = XKeysymToKeycode(dpy, keys[i].keysym);
934 XGrabKey(dpy, code, keys[i].mod, root, True,
935 GrabModeAsync, GrabModeAsync);
936 XGrabKey(dpy, code, keys[i].mod | LockMask, root, True,
937 GrabModeAsync, GrabModeAsync);
938 XGrabKey(dpy, code, keys[i].mod | numlockmask, root, True,
939 GrabModeAsync, GrabModeAsync);
940 XGrabKey(dpy, code, keys[i].mod | numlockmask | LockMask, root, True,
941 GrabModeAsync, GrabModeAsync);
946 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
947 for(i = 0; i < LENGTH(keys); i++)
948 if(keysym == keys[i].keysym
949 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
952 keys[i].func(keys[i].arg);
957 killclient(const char *arg) {
962 if(isprotodel(sel)) {
963 ev.type = ClientMessage;
964 ev.xclient.window = sel->win;
965 ev.xclient.message_type = wmatom[WMProtocols];
966 ev.xclient.format = 32;
967 ev.xclient.data.l[0] = wmatom[WMDelete];
968 ev.xclient.data.l[1] = CurrentTime;
969 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
972 XKillClient(dpy, sel->win);
976 leavenotify(XEvent *e) {
977 XCrossingEvent *ev = &e->xcrossing;
979 if((ev->window == root) && !ev->same_screen) {
986 manage(Window w, XWindowAttributes *wa) {
987 Client *c, *t = NULL;
992 c = emallocz(sizeof(Client));
993 c->tags = emallocz(sizeof seltags);
999 c->oldborder = wa->border_width;
1000 if(c->w == sw && c->h == sh) {
1003 c->border = wa->border_width;
1006 if(c->x + c->w + 2 * c->border > wax + waw)
1007 c->x = wax + waw - c->w - 2 * c->border;
1008 if(c->y + c->h + 2 * c->border > way + wah)
1009 c->y = way + wah - c->h - 2 * c->border;
1014 c->border = BORDERPX;
1016 wc.border_width = c->border;
1017 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1018 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1019 configure(c); /* propagates border_width, if size doesn't change */
1021 XSelectInput(dpy, w,
1022 StructureNotifyMask | PropertyChangeMask | EnterWindowMask);
1023 grabbuttons(c, False);
1025 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
1026 for(t = clients; t && t->win != trans; t = t->next);
1028 memcpy(c->tags, t->tags, sizeof seltags);
1031 c->isfloating = (rettrans == Success) || c->isfixed;
1034 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
1036 XMapWindow(dpy, c->win);
1037 setclientstate(c, NormalState);
1042 mappingnotify(XEvent *e) {
1043 XMappingEvent *ev = &e->xmapping;
1045 XRefreshKeyboardMapping(ev);
1046 if(ev->request == MappingKeyboard)
1051 maprequest(XEvent *e) {
1052 static XWindowAttributes wa;
1053 XMapRequestEvent *ev = &e->xmaprequest;
1055 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1057 if(wa.override_redirect)
1059 if(!getclient(ev->window))
1060 manage(ev->window, &wa);
1064 movemouse(Client *c) {
1065 int x1, y1, ocx, ocy, di, nx, ny;
1072 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1073 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1076 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1078 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask, &ev);
1081 XUngrabPointer(dpy, CurrentTime);
1083 case ConfigureRequest:
1086 handler[ev.type](&ev);
1090 nx = ocx + (ev.xmotion.x - x1);
1091 ny = ocy + (ev.xmotion.y - y1);
1092 if(abs(wax + nx) < SNAP)
1094 else if(abs((wax + waw) - (nx + c->w + 2 * c->border)) < SNAP)
1095 nx = wax + waw - c->w - 2 * c->border;
1096 if(abs(way - ny) < SNAP)
1098 else if(abs((way + wah) - (ny + c->h + 2 * c->border)) < SNAP)
1099 ny = way + wah - c->h - 2 * c->border;
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:
1132 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1141 quit(const char *arg) {
1142 readin = running = False;
1147 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1151 /* set minimum possible */
1157 /* temporarily remove base dimensions */
1161 /* adjust for aspect limits */
1162 if (c->minay > 0 && c->maxay > 0 && c->minax > 0 && c->maxax > 0) {
1163 if (w * c->maxay > h * c->maxax)
1164 w = h * c->maxax / c->maxay;
1165 else if (w * c->minay < h * c->minax)
1166 h = w * c->minay / c->minax;
1169 /* adjust for increment value */
1175 /* restore base dimensions */
1179 if(c->minw > 0 && w < c->minw)
1181 if(c->minh > 0 && h < c->minh)
1183 if(c->maxw > 0 && w > c->maxw)
1185 if(c->maxh > 0 && h > c->maxh)
1188 if(w <= 0 || h <= 0)
1190 /* offscreen appearance fixes */
1192 x = sw - w - 2 * c->border;
1194 y = sh - h - 2 * c->border;
1195 if(x + w + 2 * c->border < sx)
1197 if(y + h + 2 * c->border < sy)
1199 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1202 c->w = wc.width = w;
1203 c->h = wc.height = h;
1204 wc.border_width = c->border;
1205 XConfigureWindow(dpy, c->win, CWX | CWY | CWWidth | CWHeight | CWBorderWidth, &wc);
1212 resizemouse(Client *c) {
1219 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1220 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1223 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
1225 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask , &ev);
1228 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1229 c->w + c->border - 1, c->h + c->border - 1);
1230 XUngrabPointer(dpy, CurrentTime);
1231 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1233 case ConfigureRequest:
1236 handler[ev.type](&ev);
1240 if((nw = ev.xmotion.x - ocx - 2 * c->border + 1) <= 0)
1242 if((nh = ev.xmotion.y - ocy - 2 * c->border + 1) <= 0)
1244 resize(c, c->x, c->y, nw, nh, True);
1259 if(sel->isfloating || (layout->arrange == floating))
1260 XRaiseWindow(dpy, sel->win);
1261 if(layout->arrange != floating) {
1262 wc.stack_mode = Below;
1263 wc.sibling = barwin;
1264 if(!sel->isfloating) {
1265 XConfigureWindow(dpy, sel->win, CWSibling | CWStackMode, &wc);
1266 wc.sibling = sel->win;
1268 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
1271 XConfigureWindow(dpy, c->win, CWSibling | CWStackMode, &wc);
1272 wc.sibling = c->win;
1276 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1284 unsigned int len, offset;
1287 /* main event loop, also reads status text from stdin */
1289 xfd = ConnectionNumber(dpy);
1292 len = sizeof stext - 1;
1293 stext[len] = '\0'; /* 0-terminator is never touched */
1297 FD_SET(STDIN_FILENO, &rd);
1299 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1302 eprint("select failed\n");
1304 if(FD_ISSET(STDIN_FILENO, &rd)) {
1305 switch((r = read(STDIN_FILENO, stext + offset, len - offset))) {
1307 strncpy(stext, strerror(errno), len);
1311 strncpy(stext, "EOF", 4);
1315 stext[offset + r] = '\0';
1316 for(p = stext; *p && *p != '\n'; p++);
1322 offset = (offset + r < len - 1) ? offset + r : 0;
1326 while(XPending(dpy)) {
1327 XNextEvent(dpy, &ev);
1328 if(handler[ev.type])
1329 (handler[ev.type])(&ev); /* call handler */
1336 unsigned int i, num;
1337 Window *wins, d1, d2;
1338 XWindowAttributes wa;
1341 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1342 for(i = 0; i < num; i++) {
1343 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1344 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1346 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1347 manage(wins[i], &wa);
1349 for(i = 0; i < num; i++) { /* now the transients */
1350 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1352 if(XGetTransientForHint(dpy, wins[i], &d1)
1353 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1354 manage(wins[i], &wa);
1362 setclientstate(Client *c, long state) {
1363 long data[] = {state, None};
1365 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1366 PropModeReplace, (unsigned char *)data, 2);
1370 setlayout(const char *arg) {
1374 if(++layout == &layouts[LENGTH(layouts)])
1375 layout = &layouts[0];
1378 for(i = 0; i < LENGTH(layouts); i++)
1379 if(!strcmp(arg, layouts[i].symbol))
1381 if(i == LENGTH(layouts))
1383 layout = &layouts[i];
1392 setmwfact(const char *arg) {
1397 /* arg handling, manipulate mwfact */
1400 else if(sscanf(arg, "%lf", &delta) == 1) {
1401 if(arg[0] == '+' || arg[0] == '-')
1407 else if(mwfact > 0.9)
1416 unsigned int i, j, mask;
1418 XModifierKeymap *modmap;
1419 XSetWindowAttributes wa;
1422 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1423 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1424 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1425 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1426 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1427 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1428 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1429 PropModeReplace, (unsigned char *) netatom, NetLast);
1432 cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1433 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1434 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1438 sw = DisplayWidth(dpy, screen);
1439 sh = DisplayHeight(dpy, screen);
1441 /* init modifier map */
1442 modmap = XGetModifierMapping(dpy);
1443 for(i = 0; i < 8; i++)
1444 for(j = 0; j < modmap->max_keypermod; j++) {
1445 if(modmap->modifiermap[i * modmap->max_keypermod + j]
1446 == XKeysymToKeycode(dpy, XK_Num_Lock))
1447 numlockmask = (1 << i);
1449 XFreeModifiermap(modmap);
1451 /* select for events */
1452 wa.event_mask = SubstructureRedirectMask | SubstructureNotifyMask
1453 | EnterWindowMask | LeaveWindowMask | StructureNotifyMask;
1454 wa.cursor = cursor[CurNormal];
1455 XChangeWindowAttributes(dpy, root, CWEventMask | CWCursor, &wa);
1456 XSelectInput(dpy, root, wa.event_mask);
1464 /* init appearance */
1465 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1466 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1467 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1468 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1469 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1470 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1472 dc.h = bh = dc.font.height + 2;
1476 layout = &layouts[0];
1477 for(blw = i = 0; i < LENGTH(layouts); i++) {
1478 j = textw(layouts[i].symbol);
1485 wa.override_redirect = 1;
1486 wa.background_pixmap = ParentRelative;
1487 wa.event_mask = ButtonPressMask | ExposureMask;
1488 barwin = XCreateWindow(dpy, root, sx, sy, sw, bh, 0,
1489 DefaultDepth(dpy, screen), CopyFromParent, DefaultVisual(dpy, screen),
1490 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
1491 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1493 XMapRaised(dpy, barwin);
1494 strcpy(stext, "dwm-"VERSION);
1495 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
1496 dc.gc = XCreateGC(dpy, root, 0, 0);
1497 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1499 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1501 /* multihead support */
1502 selscreen = XQueryPointer(dpy, root, &w, &w, &d, &d, &d, &d, &mask);
1506 spawn(const char *arg) {
1507 static char *shell = NULL;
1509 if(!shell && !(shell = getenv("SHELL")))
1513 /* The double-fork construct avoids zombie processes and keeps the code
1514 * clean from stupid signal handlers. */
1518 close(ConnectionNumber(dpy));
1520 execl(shell, shell, "-c", arg, (char *)NULL);
1521 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1530 tag(const char *arg) {
1535 for(i = 0; i < LENGTH(tags); i++)
1536 sel->tags[i] = (NULL == arg);
1537 sel->tags[idxoftag(arg)] = True;
1542 textnw(const char *text, unsigned int len) {
1546 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1549 return XTextWidth(dc.font.xfont, text, len);
1553 textw(const char *text) {
1554 return textnw(text, strlen(text)) + dc.font.height;
1559 unsigned int i, n, nx, ny, nw, nh, mw, th;
1562 domwfact = dozoom = True;
1563 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next))
1567 mw = (n == 1) ? waw : mwfact * waw;
1568 th = (n > 1) ? wah / (n - 1) : 0;
1569 if(n > 1 && th < bh)
1574 nw = 0; /* gcc stupidity requires this */
1575 for(i = 0, c = mc = nexttiled(clients); c; c = nexttiled(c->next), i++) {
1577 if(i == 0) { /* master */
1578 nw = mw - 2 * c->border;
1579 nh = wah - 2 * c->border;
1581 else { /* tile window */
1584 nx += mc->w + 2 * mc->border;
1585 nw = waw - nx - 2 * c->border;
1587 if(i + 1 == n) /* remainder */
1588 nh = (way + wah) - ny - 2 * c->border;
1590 nh = th - 2 * c->border;
1592 resize(c, nx, ny, nw, nh, RESIZEHINTS);
1593 if((RESIZEHINTS) && ((c->h < bh) || (c->h > nh) || (c->w < bh) || (c->w > nw)))
1594 /* client doesn't accept size constraints */
1595 resize(c, nx, ny, nw, nh, False);
1596 if(n > 1 && th != wah)
1597 ny = c->y + c->h + 2 * c->border;
1602 togglebar(const char *arg) {
1604 bpos = (BARPOS == BarOff) ? BarTop : BARPOS;
1612 togglefloating(const char *arg) {
1615 sel->isfloating = !sel->isfloating;
1617 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1622 togglemax(const char *arg) {
1625 if(!sel || sel->isfixed)
1627 if((sel->ismax = !sel->ismax)) {
1628 if((layout->arrange == floating) || sel->isfloating)
1629 sel->wasfloating = True;
1631 togglefloating(NULL);
1632 sel->wasfloating = False;
1638 resize(sel, wax, way, waw - 2 * sel->border, wah - 2 * sel->border, True);
1641 resize(sel, sel->rx, sel->ry, sel->rw, sel->rh, True);
1642 if(!sel->wasfloating)
1643 togglefloating(NULL);
1646 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1650 toggletag(const char *arg) {
1656 sel->tags[i] = !sel->tags[i];
1657 for(j = 0; j < LENGTH(tags) && !sel->tags[j]; j++);
1658 if(j == LENGTH(tags))
1659 sel->tags[i] = True; /* at least one tag must be enabled */
1664 toggleview(const char *arg) {
1668 seltags[i] = !seltags[i];
1669 for(j = 0; j < LENGTH(tags) && !seltags[j]; j++);
1670 if(j == LENGTH(tags))
1671 seltags[i] = True; /* at least one tag must be viewed */
1679 XMoveWindow(dpy, c->win, c->x, c->y);
1680 c->isbanned = False;
1684 unmanage(Client *c) {
1687 wc.border_width = c->oldborder;
1688 /* The server grab construct avoids race conditions. */
1690 XSetErrorHandler(xerrordummy);
1691 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1696 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1697 setclientstate(c, WithdrawnState);
1701 XSetErrorHandler(xerror);
1707 unmapnotify(XEvent *e) {
1709 XUnmapEvent *ev = &e->xunmap;
1711 if((c = getclient(ev->window)))
1716 updatebarpos(void) {
1727 XMoveWindow(dpy, barwin, sx, sy);
1731 XMoveWindow(dpy, barwin, sx, sy + wah);
1734 XMoveWindow(dpy, barwin, sx, sy - bh);
1738 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1742 updatesizehints(Client *c) {
1746 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1748 c->flags = size.flags;
1749 if(c->flags & PBaseSize) {
1750 c->basew = size.base_width;
1751 c->baseh = size.base_height;
1753 else if(c->flags & PMinSize) {
1754 c->basew = size.min_width;
1755 c->baseh = size.min_height;
1758 c->basew = c->baseh = 0;
1759 if(c->flags & PResizeInc) {
1760 c->incw = size.width_inc;
1761 c->inch = size.height_inc;
1764 c->incw = c->inch = 0;
1765 if(c->flags & PMaxSize) {
1766 c->maxw = size.max_width;
1767 c->maxh = size.max_height;
1770 c->maxw = c->maxh = 0;
1771 if(c->flags & PMinSize) {
1772 c->minw = size.min_width;
1773 c->minh = size.min_height;
1775 else if(c->flags & PBaseSize) {
1776 c->minw = size.base_width;
1777 c->minh = size.base_height;
1780 c->minw = c->minh = 0;
1781 if(c->flags & PAspect) {
1782 c->minax = size.min_aspect.x;
1783 c->maxax = size.max_aspect.x;
1784 c->minay = size.min_aspect.y;
1785 c->maxay = size.max_aspect.y;
1788 c->minax = c->maxax = c->minay = c->maxay = 0;
1789 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1790 && c->maxw == c->minw && c->maxh == c->minh);
1794 updatetitle(Client *c) {
1795 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1796 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1799 /* There's no way to check accesses to destroyed windows, thus those cases are
1800 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1801 * default error handler, which may call exit. */
1803 xerror(Display *dpy, XErrorEvent *ee) {
1804 if(ee->error_code == BadWindow
1805 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1806 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1807 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1808 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1809 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1810 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1811 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1813 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1814 ee->request_code, ee->error_code);
1815 return xerrorxlib(dpy, ee); /* may call exit */
1819 xerrordummy(Display *dsply, XErrorEvent *ee) {
1823 /* Startup Error handler to check if another window manager
1824 * is already running. */
1826 xerrorstart(Display *dsply, XErrorEvent *ee) {
1832 view(const char *arg) {
1835 memcpy(prevtags, seltags, sizeof seltags);
1836 for(i = 0; i < LENGTH(tags); i++)
1837 seltags[i] = (NULL == arg);
1838 seltags[idxoftag(arg)] = True;
1843 viewprevtag(const char *arg) {
1844 static Bool tmptags[sizeof tags / sizeof tags[0]];
1846 memcpy(tmptags, seltags, sizeof seltags);
1847 memcpy(seltags, prevtags, sizeof seltags);
1848 memcpy(prevtags, tmptags, sizeof seltags);
1853 zoom(const char *arg) {
1856 if(!sel || !dozoom || sel->isfloating)
1858 if((c = sel) == nexttiled(clients))
1859 if(!(c = nexttiled(c->next)))
1868 main(int argc, char *argv[]) {
1869 if(argc == 2 && !strcmp("-v", argv[1]))
1870 eprint("dwm-"VERSION", © 2006-2007 Anselm R. Garbe, Sander van Dijk, "
1871 "Jukka Salmi, Premysl Hruby, Szabolcs Nagy\n");
1873 eprint("usage: dwm [-v]\n");
1875 setlocale(LC_CTYPE, "");
1876 if(!(dpy = XOpenDisplay(0)))
1877 eprint("dwm: cannot open display\n");
1878 screen = DefaultScreen(dpy);
1879 root = RootWindow(dpy, screen);