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, NetWMCheck, NetWMName, NetLast }; /* EWMH atoms */
57 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
60 typedef struct Client Client;
64 int rx, ry, rw, rh; /* revert geometry */
65 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
66 int minax, maxax, minay, maxay;
68 unsigned int border, oldborder;
69 Bool isbanned, isfixed, ismax, isfloating, wasfloating;
79 unsigned long norm[ColLast];
80 unsigned long sel[ColLast];
90 } DC; /* draw context */
95 void (*func)(const char *arg);
101 void (*arrange)(void);
115 /* function declarations */
116 void applyrules(Client *c);
118 void attach(Client *c);
119 void attachstack(Client *c);
121 void buttonpress(XEvent *e);
122 void checkotherwm(void);
124 void compileregs(void);
125 void configure(Client *c);
126 void configurenotify(XEvent *e);
127 void configurerequest(XEvent *e);
128 void destroynotify(XEvent *e);
129 void detach(Client *c);
130 void detachstack(Client *c);
132 void drawsquare(Bool filled, Bool empty, unsigned long col[ColLast]);
133 void drawtext(const char *text, unsigned long col[ColLast]);
134 void *emallocz(unsigned int size);
135 void enternotify(XEvent *e);
136 void eprint(const char *errstr, ...);
137 void expose(XEvent *e);
138 void floating(void); /* default floating layout */
139 void focus(Client *c);
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 movemouse(Client *c);
160 Client *nexttiled(Client *c);
161 void propertynotify(XEvent *e);
162 void quit(const char *arg);
163 void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
164 void resizemouse(Client *c);
168 void setclientstate(Client *c, long state);
169 void setlayout(const char *arg);
170 void setmwfact(const char *arg);
172 void spawn(const char *arg);
173 void tag(const char *arg);
174 unsigned int textnw(const char *text, unsigned int len);
175 unsigned int textw(const char *text);
177 void togglebar(const char *arg);
178 void togglefloating(const char *arg);
179 void togglemax(const char *arg);
180 void toggletag(const char *arg);
181 void toggleview(const char *arg);
182 void unban(Client *c);
183 void unmanage(Client *c);
184 void unmapnotify(XEvent *e);
185 void updatebarpos(void);
186 void updatesizehints(Client *c);
187 void updatetitle(Client *c);
188 void view(const char *arg);
189 void viewprevtag(const char *arg); /* views previous selected tags */
190 int xerror(Display *dpy, XErrorEvent *ee);
191 int xerrordummy(Display *dsply, XErrorEvent *ee);
192 int xerrorstart(Display *dsply, XErrorEvent *ee);
193 void zoom(const char *arg);
198 int screen, sx, sy, sw, sh, wax, way, waw, wah;
199 int (*xerrorxlib)(Display *, XErrorEvent *);
200 unsigned int bh, bpos;
201 unsigned int blw = 0;
202 unsigned int numlockmask = 0;
203 void (*handler[LASTEvent]) (XEvent *) = {
204 [ButtonPress] = buttonpress,
205 [ConfigureRequest] = configurerequest,
206 [ConfigureNotify] = configurenotify,
207 [DestroyNotify] = destroynotify,
208 [EnterNotify] = enternotify,
209 [LeaveNotify] = leavenotify,
211 [KeyPress] = keypress,
212 [MappingNotify] = mappingnotify,
213 [MapRequest] = maprequest,
214 [PropertyNotify] = propertynotify,
215 [UnmapNotify] = unmapnotify
217 Atom wmatom[WMLast], netatom[NetLast];
218 Bool domwfact = True;
220 Bool otherwm, readin;
222 Bool selscreen = True;
223 Client *clients = NULL;
225 Client *stack = NULL;
226 Cursor cursor[CurLast];
229 Layout *layout = NULL;
233 /* configuration, allows nested code to access above variables */
236 Bool prevtags[LENGTH(tags)];
238 /* function implementations */
240 applyrules(Client *c) {
241 static char buf[512];
244 Bool matched = False;
245 XClassHint ch = { 0 };
248 XGetClassHint(dpy, c->win, &ch);
249 snprintf(buf, sizeof buf, "%s:%s:%s",
250 ch.res_class ? ch.res_class : "",
251 ch.res_name ? ch.res_name : "", c->name);
252 for(i = 0; i < LENGTH(rules); i++)
253 if(regs[i].propregex && !regexec(regs[i].propregex, buf, 1, &tmp, 0)) {
254 c->isfloating = rules[i].isfloating;
255 for(j = 0; regs[i].tagregex && j < LENGTH(tags); j++) {
256 if(!regexec(regs[i].tagregex, tags[j], 1, &tmp, 0)) {
267 memcpy(c->tags, seltags, sizeof seltags);
274 for(c = clients; c; c = c->next)
293 attachstack(Client *c) {
302 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
307 buttonpress(XEvent *e) {
310 XButtonPressedEvent *ev = &e->xbutton;
312 if(ev->window == barwin) {
314 for(i = 0; i < LENGTH(tags); i++) {
317 if(ev->button == Button1) {
318 if(ev->state & MODKEY)
323 else if(ev->button == Button3) {
324 if(ev->state & MODKEY)
332 if((ev->x < x + blw) && ev->button == Button1)
335 else if((c = getclient(ev->window))) {
337 if(CLEANMASK(ev->state) != MODKEY)
339 if(ev->button == Button1) {
340 if((layout->arrange == floating) || c->isfloating)
343 togglefloating(NULL);
346 else if(ev->button == Button2) {
347 if((floating != layout->arrange) && c->isfloating)
348 togglefloating(NULL);
352 else if(ev->button == Button3 && !c->isfixed) {
353 if((floating == layout->arrange) || c->isfloating)
356 togglefloating(NULL);
365 XSetErrorHandler(xerrorstart);
367 /* this causes an error if some other window manager is running */
368 XSelectInput(dpy, root, SubstructureRedirectMask);
371 eprint("dwm: another window manager is already running\n");
373 XSetErrorHandler(NULL);
374 xerrorxlib = XSetErrorHandler(xerror);
386 XFreeFontSet(dpy, dc.font.set);
388 XFreeFont(dpy, dc.font.xfont);
389 XUngrabKey(dpy, AnyKey, AnyModifier, root);
390 XFreePixmap(dpy, dc.drawable);
392 XDestroyWindow(dpy, barwin);
393 XFreeCursor(dpy, cursor[CurNormal]);
394 XFreeCursor(dpy, cursor[CurResize]);
395 XFreeCursor(dpy, cursor[CurMove]);
396 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
407 regs = emallocz(LENGTH(rules) * sizeof(Regs));
408 for(i = 0; i < LENGTH(rules); i++) {
410 reg = emallocz(sizeof(regex_t));
411 if(regcomp(reg, rules[i].prop, REG_EXTENDED))
414 regs[i].propregex = reg;
417 reg = emallocz(sizeof(regex_t));
418 if(regcomp(reg, rules[i].tags, REG_EXTENDED))
421 regs[i].tagregex = reg;
427 configure(Client *c) {
430 ce.type = ConfigureNotify;
438 ce.border_width = c->border;
440 ce.override_redirect = False;
441 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
445 configurenotify(XEvent *e) {
446 XConfigureEvent *ev = &e->xconfigure;
448 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
451 XFreePixmap(dpy, dc.drawable);
452 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
453 XResizeWindow(dpy, barwin, sw, bh);
460 configurerequest(XEvent *e) {
462 XConfigureRequestEvent *ev = &e->xconfigurerequest;
465 if((c = getclient(ev->window))) {
467 if(ev->value_mask & CWBorderWidth)
468 c->border = ev->border_width;
469 if(c->isfixed || c->isfloating || (floating == layout->arrange)) {
470 if(ev->value_mask & CWX)
472 if(ev->value_mask & CWY)
474 if(ev->value_mask & CWWidth)
476 if(ev->value_mask & CWHeight)
478 if((c->x + c->w) > sw && c->isfloating)
479 c->x = sw / 2 - c->w / 2; /* center in x direction */
480 if((c->y + c->h) > sh && c->isfloating)
481 c->y = sh / 2 - c->h / 2; /* center in y direction */
482 if((ev->value_mask & (CWX | CWY))
483 && !(ev->value_mask & (CWWidth | CWHeight)))
486 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
494 wc.width = ev->width;
495 wc.height = ev->height;
496 wc.border_width = ev->border_width;
497 wc.sibling = ev->above;
498 wc.stack_mode = ev->detail;
499 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
505 destroynotify(XEvent *e) {
507 XDestroyWindowEvent *ev = &e->xdestroywindow;
509 if((c = getclient(ev->window)))
516 c->prev->next = c->next;
518 c->next->prev = c->prev;
521 c->next = c->prev = NULL;
525 detachstack(Client *c) {
528 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
537 for(i = 0; i < LENGTH(tags); i++) {
538 dc.w = textw(tags[i]);
540 drawtext(tags[i], dc.sel);
541 drawsquare(sel && sel->tags[i], isoccupied(i), dc.sel);
544 drawtext(tags[i], dc.norm);
545 drawsquare(sel && sel->tags[i], isoccupied(i), dc.norm);
550 drawtext(layout->symbol, dc.norm);
558 drawtext(stext, dc.norm);
559 if((dc.w = dc.x - x) > bh) {
562 drawtext(sel->name, dc.sel);
563 drawsquare(sel->ismax, sel->isfloating, dc.sel);
566 drawtext(NULL, dc.norm);
568 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, sw, bh, 0, 0);
573 drawsquare(Bool filled, Bool empty, unsigned long col[ColLast]) {
576 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
578 gcv.foreground = col[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(const char *text, unsigned long col[ColLast]) {
596 static char buf[256];
597 unsigned int len, olen;
598 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
600 XSetForeground(dpy, dc.gc, col[ColBG]);
601 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
605 olen = len = strlen(text);
606 if(len >= sizeof buf)
607 len = sizeof buf - 1;
608 memcpy(buf, text, len);
610 h = dc.font.ascent + dc.font.descent;
611 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
613 /* shorten text if necessary */
614 while(len && (w = textnw(buf, len)) > dc.w - h)
625 return; /* too long */
626 XSetForeground(dpy, dc.gc, col[ColFG]);
628 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
630 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
634 emallocz(unsigned int size) {
635 void *res = calloc(1, size);
638 eprint("fatal: could not malloc() %u bytes\n", size);
643 enternotify(XEvent *e) {
645 XCrossingEvent *ev = &e->xcrossing;
647 if(ev->mode != NotifyNormal || ev->detail == NotifyInferior)
649 if((c = getclient(ev->window)))
651 else if(ev->window == root) {
658 eprint(const char *errstr, ...) {
661 va_start(ap, errstr);
662 vfprintf(stderr, errstr, ap);
669 XExposeEvent *ev = &e->xexpose;
672 if(ev->window == barwin)
678 floating(void) { /* default floating layout */
681 domwfact = dozoom = False;
682 for(c = clients; c; c = c->next)
684 resize(c, c->x, c->y, c->w, c->h, True);
689 if((!c && selscreen) || (c && !isvisible(c)))
690 for(c = stack; c && !isvisible(c); c = c->snext);
691 if(sel && sel != c) {
692 grabbuttons(sel, False);
693 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
698 grabbuttons(c, True);
705 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
706 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
709 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
713 focusnext(const char *arg) {
718 for(c = sel->next; c && !isvisible(c); c = c->next);
720 for(c = clients; c && !isvisible(c); c = c->next);
728 focusprev(const char *arg) {
733 for(c = sel->prev; c && !isvisible(c); c = c->prev);
735 for(c = clients; c && c->next; c = c->next);
736 for(; c && !isvisible(c); c = c->prev);
745 getclient(Window w) {
748 for(c = clients; c && c->win != w; c = c->next);
753 getcolor(const char *colstr) {
754 Colormap cmap = DefaultColormap(dpy, screen);
757 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
758 eprint("error, cannot allocate color '%s'\n", colstr);
766 unsigned char *p = NULL;
767 unsigned long n, extra;
770 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
771 &real, &format, &n, &extra, (unsigned char **)&p);
772 if(status != Success)
781 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
786 if(!text || size == 0)
789 XGetTextProperty(dpy, w, &name, atom);
792 if(name.encoding == XA_STRING)
793 strncpy(text, (char *)name.value, size - 1);
795 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
797 strncpy(text, *list, size - 1);
798 XFreeStringList(list);
801 text[size - 1] = '\0';
807 grabbuttons(Client *c, Bool focused) {
808 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
811 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
812 GrabModeAsync, GrabModeSync, None, None);
813 XGrabButton(dpy, Button1, MODKEY | LockMask, c->win, False, BUTTONMASK,
814 GrabModeAsync, GrabModeSync, None, None);
815 XGrabButton(dpy, Button1, MODKEY | numlockmask, c->win, False, BUTTONMASK,
816 GrabModeAsync, GrabModeSync, None, None);
817 XGrabButton(dpy, Button1, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
818 GrabModeAsync, GrabModeSync, None, None);
820 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
821 GrabModeAsync, GrabModeSync, None, None);
822 XGrabButton(dpy, Button2, MODKEY | LockMask, c->win, False, BUTTONMASK,
823 GrabModeAsync, GrabModeSync, None, None);
824 XGrabButton(dpy, Button2, MODKEY | numlockmask, c->win, False, BUTTONMASK,
825 GrabModeAsync, GrabModeSync, None, None);
826 XGrabButton(dpy, Button2, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
827 GrabModeAsync, GrabModeSync, None, None);
829 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
830 GrabModeAsync, GrabModeSync, None, None);
831 XGrabButton(dpy, Button3, MODKEY | LockMask, c->win, False, BUTTONMASK,
832 GrabModeAsync, GrabModeSync, None, None);
833 XGrabButton(dpy, Button3, MODKEY | numlockmask, c->win, False, BUTTONMASK,
834 GrabModeAsync, GrabModeSync, None, None);
835 XGrabButton(dpy, Button3, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
836 GrabModeAsync, GrabModeSync, None, None);
839 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
840 GrabModeAsync, GrabModeSync, None, None);
848 XUngrabKey(dpy, AnyKey, AnyModifier, root);
849 for(i = 0; i < LENGTH(keys); i++) {
850 code = XKeysymToKeycode(dpy, keys[i].keysym);
851 XGrabKey(dpy, code, keys[i].mod, root, True,
852 GrabModeAsync, GrabModeAsync);
853 XGrabKey(dpy, code, keys[i].mod | LockMask, root, True,
854 GrabModeAsync, GrabModeAsync);
855 XGrabKey(dpy, code, keys[i].mod | numlockmask, root, True,
856 GrabModeAsync, GrabModeAsync);
857 XGrabKey(dpy, code, keys[i].mod | numlockmask | LockMask, root, True,
858 GrabModeAsync, GrabModeAsync);
863 idxoftag(const char *tag) {
866 for(i = 0; (i < LENGTH(tags)) && (tags[i] != tag); i++);
867 return (i < LENGTH(tags)) ? i : 0;
871 initfont(const char *fontstr) {
872 char *def, **missing;
877 XFreeFontSet(dpy, dc.font.set);
878 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
881 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
882 XFreeStringList(missing);
885 XFontSetExtents *font_extents;
886 XFontStruct **xfonts;
888 dc.font.ascent = dc.font.descent = 0;
889 font_extents = XExtentsOfFontSet(dc.font.set);
890 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
891 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
892 if(dc.font.ascent < (*xfonts)->ascent)
893 dc.font.ascent = (*xfonts)->ascent;
894 if(dc.font.descent < (*xfonts)->descent)
895 dc.font.descent = (*xfonts)->descent;
901 XFreeFont(dpy, dc.font.xfont);
902 dc.font.xfont = NULL;
903 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
904 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
905 eprint("error, cannot load font: '%s'\n", fontstr);
906 dc.font.ascent = dc.font.xfont->ascent;
907 dc.font.descent = dc.font.xfont->descent;
909 dc.font.height = dc.font.ascent + dc.font.descent;
913 isoccupied(unsigned int t) {
916 for(c = clients; c; c = c->next)
923 isprotodel(Client *c) {
928 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
929 for(i = 0; !ret && i < n; i++)
930 if(protocols[i] == wmatom[WMDelete])
938 isvisible(Client *c) {
941 for(i = 0; i < LENGTH(tags); i++)
942 if(c->tags[i] && seltags[i])
948 keypress(XEvent *e) {
954 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
955 for(i = 0; i < LENGTH(keys); i++)
956 if(keysym == keys[i].keysym
957 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
960 keys[i].func(keys[i].arg);
965 killclient(const char *arg) {
970 if(isprotodel(sel)) {
971 ev.type = ClientMessage;
972 ev.xclient.window = sel->win;
973 ev.xclient.message_type = wmatom[WMProtocols];
974 ev.xclient.format = 32;
975 ev.xclient.data.l[0] = wmatom[WMDelete];
976 ev.xclient.data.l[1] = CurrentTime;
977 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
980 XKillClient(dpy, sel->win);
984 leavenotify(XEvent *e) {
985 XCrossingEvent *ev = &e->xcrossing;
987 if((ev->window == root) && !ev->same_screen) {
994 manage(Window w, XWindowAttributes *wa) {
995 Client *c, *t = NULL;
1000 c = emallocz(sizeof(Client));
1001 c->tags = emallocz(sizeof seltags);
1007 c->oldborder = wa->border_width;
1008 if(c->w == sw && c->h == sh) {
1011 c->border = wa->border_width;
1014 if(c->x + c->w + 2 * c->border > wax + waw)
1015 c->x = wax + waw - c->w - 2 * c->border;
1016 if(c->y + c->h + 2 * c->border > way + wah)
1017 c->y = way + wah - c->h - 2 * c->border;
1022 c->border = BORDERPX;
1024 wc.border_width = c->border;
1025 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1026 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1027 configure(c); /* propagates border_width, if size doesn't change */
1029 XSelectInput(dpy, w,
1030 StructureNotifyMask | PropertyChangeMask | EnterWindowMask);
1031 grabbuttons(c, False);
1033 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
1034 for(t = clients; t && t->win != trans; t = t->next);
1036 memcpy(c->tags, t->tags, sizeof seltags);
1039 c->isfloating = (rettrans == Success) || c->isfixed;
1042 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
1044 XMapWindow(dpy, c->win);
1045 setclientstate(c, NormalState);
1050 mappingnotify(XEvent *e) {
1051 XMappingEvent *ev = &e->xmapping;
1053 XRefreshKeyboardMapping(ev);
1054 if(ev->request == MappingKeyboard)
1059 maprequest(XEvent *e) {
1060 static XWindowAttributes wa;
1061 XMapRequestEvent *ev = &e->xmaprequest;
1063 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1065 if(wa.override_redirect)
1067 if(!getclient(ev->window))
1068 manage(ev->window, &wa);
1072 movemouse(Client *c) {
1073 int x1, y1, ocx, ocy, di, nx, ny;
1080 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1081 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1084 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1086 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask, &ev);
1089 XUngrabPointer(dpy, CurrentTime);
1091 case ConfigureRequest:
1094 handler[ev.type](&ev);
1098 nx = ocx + (ev.xmotion.x - x1);
1099 ny = ocy + (ev.xmotion.y - y1);
1100 if(abs(wax + nx) < SNAP)
1102 else if(abs((wax + waw) - (nx + c->w + 2 * c->border)) < SNAP)
1103 nx = wax + waw - c->w - 2 * c->border;
1104 if(abs(way - ny) < SNAP)
1106 else if(abs((way + wah) - (ny + c->h + 2 * c->border)) < SNAP)
1107 ny = way + wah - c->h - 2 * c->border;
1108 resize(c, nx, ny, c->w, c->h, False);
1115 nexttiled(Client *c) {
1116 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1121 propertynotify(XEvent *e) {
1124 XPropertyEvent *ev = &e->xproperty;
1126 if(ev->state == PropertyDelete)
1127 return; /* ignore */
1128 if((c = getclient(ev->window))) {
1131 case XA_WM_TRANSIENT_FOR:
1132 XGetTransientForHint(dpy, c->win, &trans);
1133 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1136 case XA_WM_NORMAL_HINTS:
1140 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1149 quit(const char *arg) {
1150 readin = running = False;
1155 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1159 /* set minimum possible */
1165 /* temporarily remove base dimensions */
1169 /* adjust for aspect limits */
1170 if (c->minay > 0 && c->maxay > 0 && c->minax > 0 && c->maxax > 0) {
1171 if (w * c->maxay > h * c->maxax)
1172 w = h * c->maxax / c->maxay;
1173 else if (w * c->minay < h * c->minax)
1174 h = w * c->minay / c->minax;
1177 /* adjust for increment value */
1183 /* restore base dimensions */
1187 if(c->minw > 0 && w < c->minw)
1189 if(c->minh > 0 && h < c->minh)
1191 if(c->maxw > 0 && w > c->maxw)
1193 if(c->maxh > 0 && h > c->maxh)
1196 if(w <= 0 || h <= 0)
1198 /* offscreen appearance fixes */
1200 x = sw - w - 2 * c->border;
1202 y = sh - h - 2 * c->border;
1203 if(x + w + 2 * c->border < sx)
1205 if(y + h + 2 * c->border < sy)
1207 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1210 c->w = wc.width = w;
1211 c->h = wc.height = h;
1212 wc.border_width = c->border;
1213 XConfigureWindow(dpy, c->win, CWX | CWY | CWWidth | CWHeight | CWBorderWidth, &wc);
1220 resizemouse(Client *c) {
1227 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1228 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1231 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
1233 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask , &ev);
1236 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1237 c->w + c->border - 1, c->h + c->border - 1);
1238 XUngrabPointer(dpy, CurrentTime);
1239 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1241 case ConfigureRequest:
1244 handler[ev.type](&ev);
1248 if((nw = ev.xmotion.x - ocx - 2 * c->border + 1) <= 0)
1250 if((nh = ev.xmotion.y - ocy - 2 * c->border + 1) <= 0)
1252 resize(c, c->x, c->y, nw, nh, True);
1267 if(sel->isfloating || (layout->arrange == floating))
1268 XRaiseWindow(dpy, sel->win);
1269 if(layout->arrange != floating) {
1270 wc.stack_mode = Below;
1271 wc.sibling = barwin;
1272 if(!sel->isfloating) {
1273 XConfigureWindow(dpy, sel->win, CWSibling | CWStackMode, &wc);
1274 wc.sibling = sel->win;
1276 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
1279 XConfigureWindow(dpy, c->win, CWSibling | CWStackMode, &wc);
1280 wc.sibling = c->win;
1284 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1290 char buf[sizeof stext];
1293 unsigned int len, offset;
1296 /* main event loop, also reads status text from stdin */
1298 xfd = ConnectionNumber(dpy);
1301 len = sizeof stext - 1;
1302 buf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1306 FD_SET(STDIN_FILENO, &rd);
1308 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1311 eprint("select failed\n");
1313 if(FD_ISSET(STDIN_FILENO, &rd)) {
1314 switch((r = read(STDIN_FILENO, buf + offset, len - offset))) {
1316 strncpy(stext, strerror(errno), len);
1320 strncpy(stext, "EOF", 4);
1324 for(p = buf + offset; r > 0; p++, r--, offset++)
1325 if(*p == '\n' || *p == '\0') {
1327 strncpy(stext, buf, len);
1328 p += r - 1; /* p is buf + offset + r - 1 */
1329 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1332 memmove(buf, p - r + 1, r);
1339 while(XPending(dpy)) {
1340 XNextEvent(dpy, &ev);
1341 if(handler[ev.type])
1342 (handler[ev.type])(&ev); /* call handler */
1349 unsigned int i, num;
1350 Window *wins, d1, d2;
1351 XWindowAttributes wa;
1354 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1355 for(i = 0; i < num; i++) {
1356 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1357 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1359 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1360 manage(wins[i], &wa);
1362 for(i = 0; i < num; i++) { /* now the transients */
1363 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1365 if(XGetTransientForHint(dpy, wins[i], &d1)
1366 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1367 manage(wins[i], &wa);
1375 setclientstate(Client *c, long state) {
1376 long data[] = {state, None};
1378 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1379 PropModeReplace, (unsigned char *)data, 2);
1383 setlayout(const char *arg) {
1387 if(++layout == &layouts[LENGTH(layouts)])
1388 layout = &layouts[0];
1391 for(i = 0; i < LENGTH(layouts); i++)
1392 if(!strcmp(arg, layouts[i].symbol))
1394 if(i == LENGTH(layouts))
1396 layout = &layouts[i];
1405 setmwfact(const char *arg) {
1410 /* arg handling, manipulate mwfact */
1413 else if(sscanf(arg, "%lf", &delta) == 1) {
1414 if(arg[0] == '+' || arg[0] == '-')
1420 else if(mwfact > 0.9)
1429 unsigned int i, j, mask;
1432 XModifierKeymap *modmap;
1433 XSetWindowAttributes wa;
1436 utf8string = XInternAtom(dpy, "UTF8_STRING", False);
1437 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1438 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1439 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1440 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1441 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1442 netatom[NetWMCheck] = XInternAtom(dpy, "_NET_SUPPORTING_WM_CHECK", False);
1443 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1446 cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1447 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1448 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1452 sw = DisplayWidth(dpy, screen);
1453 sh = DisplayHeight(dpy, screen);
1455 /* init modifier map */
1456 modmap = XGetModifierMapping(dpy);
1457 for(i = 0; i < 8; i++)
1458 for(j = 0; j < modmap->max_keypermod; j++) {
1459 if(modmap->modifiermap[i * modmap->max_keypermod + j]
1460 == XKeysymToKeycode(dpy, XK_Num_Lock))
1461 numlockmask = (1 << i);
1463 XFreeModifiermap(modmap);
1465 /* select for events */
1466 wa.event_mask = SubstructureRedirectMask | SubstructureNotifyMask
1467 | EnterWindowMask | LeaveWindowMask | StructureNotifyMask;
1468 wa.cursor = cursor[CurNormal];
1469 XChangeWindowAttributes(dpy, root, CWEventMask | CWCursor, &wa);
1470 XSelectInput(dpy, root, wa.event_mask);
1476 memcpy(prevtags, seltags, sizeof seltags);
1479 /* init appearance */
1480 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1481 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1482 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1483 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1484 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1485 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1487 dc.h = bh = dc.font.height + 2;
1491 layout = &layouts[0];
1492 for(blw = i = 0; i < LENGTH(layouts); i++) {
1493 j = textw(layouts[i].symbol);
1500 wa.override_redirect = 1;
1501 wa.background_pixmap = ParentRelative;
1502 wa.event_mask = ButtonPressMask | ExposureMask;
1503 barwin = XCreateWindow(dpy, root, sx, sy, sw, bh, 0,
1504 DefaultDepth(dpy, screen), CopyFromParent, DefaultVisual(dpy, screen),
1505 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
1506 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1508 XMapRaised(dpy, barwin);
1509 strcpy(stext, "dwm-"VERSION);
1510 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
1511 dc.gc = XCreateGC(dpy, root, 0, 0);
1512 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1514 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1516 /* multihead support */
1517 selscreen = XQueryPointer(dpy, root, &w, &w, &d, &d, &d, &d, &mask);
1519 /* EWMH properties */
1520 XChangeProperty(dpy, barwin, netatom[NetWMCheck], XA_WINDOW, 32,
1521 PropModeReplace, (unsigned char *) &barwin, 1);
1522 /* HACK: dwm identifies itself as compiz to workaround the XToolkit bug of Sun JDK */
1523 XChangeProperty(dpy, barwin, netatom[NetWMName], utf8string, 8,
1524 PropModeReplace, (unsigned char *) "compiz", 7);
1525 XChangeProperty(dpy, root, netatom[NetWMCheck], XA_WINDOW, 32,
1526 PropModeReplace, (unsigned char *) &barwin, 1);
1527 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1528 PropModeReplace, (unsigned char *) netatom, NetLast);
1532 spawn(const char *arg) {
1533 static char *shell = NULL;
1535 if(!shell && !(shell = getenv("SHELL")))
1539 /* The double-fork construct avoids zombie processes and keeps the code
1540 * clean from stupid signal handlers. */
1544 close(ConnectionNumber(dpy));
1546 execl(shell, shell, "-c", arg, (char *)NULL);
1547 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1556 tag(const char *arg) {
1561 for(i = 0; i < LENGTH(tags); i++)
1562 sel->tags[i] = (NULL == arg);
1563 sel->tags[idxoftag(arg)] = True;
1568 textnw(const char *text, unsigned int len) {
1572 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1575 return XTextWidth(dc.font.xfont, text, len);
1579 textw(const char *text) {
1580 return textnw(text, strlen(text)) + dc.font.height;
1585 unsigned int i, n, nx, ny, nw, nh, mw, th;
1588 domwfact = dozoom = True;
1589 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next))
1593 mw = (n == 1) ? waw : mwfact * waw;
1594 th = (n > 1) ? wah / (n - 1) : 0;
1595 if(n > 1 && th < bh)
1600 nw = 0; /* gcc stupidity requires this */
1601 for(i = 0, c = mc = nexttiled(clients); c; c = nexttiled(c->next), i++) {
1603 if(i == 0) { /* master */
1604 nw = mw - 2 * c->border;
1605 nh = wah - 2 * c->border;
1607 else { /* tile window */
1610 nx += mc->w + 2 * mc->border;
1611 nw = waw - nx - 2 * c->border;
1613 if(i + 1 == n) /* remainder */
1614 nh = (way + wah) - ny - 2 * c->border;
1616 nh = th - 2 * c->border;
1618 resize(c, nx, ny, nw, nh, RESIZEHINTS);
1619 if((RESIZEHINTS) && ((c->h < bh) || (c->h > nh) || (c->w < bh) || (c->w > nw)))
1620 /* client doesn't accept size constraints */
1621 resize(c, nx, ny, nw, nh, False);
1622 if(n > 1 && th != wah)
1623 ny = c->y + c->h + 2 * c->border;
1628 togglebar(const char *arg) {
1630 bpos = (BARPOS == BarOff) ? BarTop : BARPOS;
1638 togglefloating(const char *arg) {
1641 sel->isfloating = !sel->isfloating;
1643 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1648 togglemax(const char *arg) {
1651 if(!sel || sel->isfixed)
1653 if((sel->ismax = !sel->ismax)) {
1654 if((layout->arrange == floating) || sel->isfloating)
1655 sel->wasfloating = True;
1657 togglefloating(NULL);
1658 sel->wasfloating = False;
1664 resize(sel, wax, way, waw - 2 * sel->border, wah - 2 * sel->border, True);
1667 resize(sel, sel->rx, sel->ry, sel->rw, sel->rh, True);
1668 if(!sel->wasfloating)
1669 togglefloating(NULL);
1672 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1676 toggletag(const char *arg) {
1682 sel->tags[i] = !sel->tags[i];
1683 for(j = 0; j < LENGTH(tags) && !sel->tags[j]; j++);
1684 if(j == LENGTH(tags))
1685 sel->tags[i] = True; /* at least one tag must be enabled */
1690 toggleview(const char *arg) {
1694 seltags[i] = !seltags[i];
1695 for(j = 0; j < LENGTH(tags) && !seltags[j]; j++);
1696 if(j == LENGTH(tags))
1697 seltags[i] = True; /* at least one tag must be viewed */
1705 XMoveWindow(dpy, c->win, c->x, c->y);
1706 c->isbanned = False;
1710 unmanage(Client *c) {
1713 wc.border_width = c->oldborder;
1714 /* The server grab construct avoids race conditions. */
1716 XSetErrorHandler(xerrordummy);
1717 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1722 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1723 setclientstate(c, WithdrawnState);
1727 XSetErrorHandler(xerror);
1733 unmapnotify(XEvent *e) {
1735 XUnmapEvent *ev = &e->xunmap;
1737 if((c = getclient(ev->window)))
1742 updatebarpos(void) {
1753 XMoveWindow(dpy, barwin, sx, sy);
1757 XMoveWindow(dpy, barwin, sx, sy + wah);
1760 XMoveWindow(dpy, barwin, sx, sy - bh);
1764 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1768 updatesizehints(Client *c) {
1772 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1774 c->flags = size.flags;
1775 if(c->flags & PBaseSize) {
1776 c->basew = size.base_width;
1777 c->baseh = size.base_height;
1779 else if(c->flags & PMinSize) {
1780 c->basew = size.min_width;
1781 c->baseh = size.min_height;
1784 c->basew = c->baseh = 0;
1785 if(c->flags & PResizeInc) {
1786 c->incw = size.width_inc;
1787 c->inch = size.height_inc;
1790 c->incw = c->inch = 0;
1791 if(c->flags & PMaxSize) {
1792 c->maxw = size.max_width;
1793 c->maxh = size.max_height;
1796 c->maxw = c->maxh = 0;
1797 if(c->flags & PMinSize) {
1798 c->minw = size.min_width;
1799 c->minh = size.min_height;
1801 else if(c->flags & PBaseSize) {
1802 c->minw = size.base_width;
1803 c->minh = size.base_height;
1806 c->minw = c->minh = 0;
1807 if(c->flags & PAspect) {
1808 c->minax = size.min_aspect.x;
1809 c->maxax = size.max_aspect.x;
1810 c->minay = size.min_aspect.y;
1811 c->maxay = size.max_aspect.y;
1814 c->minax = c->maxax = c->minay = c->maxay = 0;
1815 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1816 && c->maxw == c->minw && c->maxh == c->minh);
1820 updatetitle(Client *c) {
1821 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1822 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1825 /* There's no way to check accesses to destroyed windows, thus those cases are
1826 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1827 * default error handler, which may call exit. */
1829 xerror(Display *dpy, XErrorEvent *ee) {
1830 if(ee->error_code == BadWindow
1831 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1832 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1833 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1834 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1835 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1836 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1837 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1839 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1840 ee->request_code, ee->error_code);
1841 return xerrorxlib(dpy, ee); /* may call exit */
1845 xerrordummy(Display *dsply, XErrorEvent *ee) {
1849 /* Startup Error handler to check if another window manager
1850 * is already running. */
1852 xerrorstart(Display *dsply, XErrorEvent *ee) {
1858 view(const char *arg) {
1861 memcpy(prevtags, seltags, sizeof seltags);
1862 for(i = 0; i < LENGTH(tags); i++)
1863 seltags[i] = (NULL == arg);
1864 seltags[idxoftag(arg)] = True;
1869 viewprevtag(const char *arg) {
1870 static Bool tmp[LENGTH(tags)];
1872 memcpy(tmp, seltags, sizeof seltags);
1873 memcpy(seltags, prevtags, sizeof seltags);
1874 memcpy(prevtags, tmp, sizeof seltags);
1879 zoom(const char *arg) {
1882 if(!sel || !dozoom || sel->isfloating)
1884 if((c = sel) == nexttiled(clients))
1885 if(!(c = nexttiled(c->next)))
1894 main(int argc, char *argv[]) {
1895 if(argc == 2 && !strcmp("-v", argv[1]))
1896 eprint("dwm-"VERSION", © 2006-2007 Anselm R. Garbe, Sander van Dijk, "
1897 "Jukka Salmi, Premysl Hruby, Szabolcs Nagy\n");
1899 eprint("usage: dwm [-v]\n");
1901 setlocale(LC_CTYPE, "");
1902 if(!(dpy = XOpenDisplay(0)))
1903 eprint("dwm: cannot open display\n");
1904 screen = DefaultScreen(dpy);
1905 root = RootWindow(dpy, screen);