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. For each client dwm
21 * creates a small title window, which is resized whenever the (_NET_)WM_NAME
22 * properties are updated or the client is moved/resized.
24 * Keys and tagging rules are organized as arrays and defined in config.h.
26 * To understand everything else, start reading main().
35 #include <sys/select.h>
36 #include <sys/types.h>
39 #include <X11/cursorfont.h>
40 #include <X11/keysym.h>
41 #include <X11/Xatom.h>
43 #include <X11/Xproto.h>
44 #include <X11/Xutil.h>
47 #define BUTTONMASK (ButtonPressMask | ButtonReleaseMask)
48 #define CLEANMASK(mask) (mask & ~(numlockmask | LockMask))
49 #define MOUSEMASK (BUTTONMASK | PointerMotionMask)
52 enum { BarTop, BarBot, BarOff }; /* bar position */
53 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
54 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
55 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
56 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
59 typedef struct Client Client;
63 int rx, ry, rw, rh; /* revert geometry */
64 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
65 int minax, maxax, minay, maxay;
67 unsigned int border, oldborder;
68 Bool isbanned, isfixed, ismax, isfloating, wasfloating;
78 unsigned long norm[ColLast];
79 unsigned long sel[ColLast];
89 } DC; /* draw context */
94 void (*func)(const char *arg);
100 void (*arrange)(void);
114 /* function declarations */
115 void applyrules(Client *c);
117 void attach(Client *c);
118 void attachstack(Client *c);
120 void buttonpress(XEvent *e);
121 void checkotherwm(void);
123 void compileregs(void);
124 void configure(Client *c);
125 void configurenotify(XEvent *e);
126 void configurerequest(XEvent *e);
127 void destroynotify(XEvent *e);
128 void detach(Client *c);
129 void detachstack(Client *c);
131 void drawsquare(Bool filled, Bool empty, unsigned long col[ColLast]);
132 void drawtext(const char *text, unsigned long col[ColLast]);
133 void *emallocz(unsigned int size);
134 void enternotify(XEvent *e);
135 void eprint(const char *errstr, ...);
136 void expose(XEvent *e);
137 void floating(void); /* default floating layout */
138 void focus(Client *c);
139 void focusnext(const char *arg);
140 void focusprev(const char *arg);
141 Client *getclient(Window w);
142 unsigned long getcolor(const char *colstr);
143 long getstate(Window w);
144 Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
145 void grabbuttons(Client *c, Bool focused);
146 unsigned int idxoftag(const char *tag);
147 void initfont(const char *fontstr);
148 Bool isarrange(void (*func)());
149 Bool isoccupied(unsigned int t);
150 Bool isprotodel(Client *c);
151 Bool isvisible(Client *c);
152 void keypress(XEvent *e);
153 void killclient(const char *arg);
154 void leavenotify(XEvent *e);
155 void manage(Window w, XWindowAttributes *wa);
156 void mappingnotify(XEvent *e);
157 void maprequest(XEvent *e);
158 void movemouse(Client *c);
159 Client *nexttiled(Client *c);
160 void propertynotify(XEvent *e);
161 void quit(const char *arg);
162 void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
163 void resizemouse(Client *c);
167 void setclientstate(Client *c, long state);
168 void setlayout(const char *arg);
169 void setmwfact(const char *arg);
171 void spawn(const char *arg);
172 void tag(const char *arg);
173 unsigned int textnw(const char *text, unsigned int len);
174 unsigned int textw(const char *text);
176 void togglebar(const char *arg);
177 void togglefloating(const char *arg);
178 void togglemax(const char *arg);
179 void toggletag(const char *arg);
180 void toggleview(const char *arg);
181 void unban(Client *c);
182 void unmanage(Client *c);
183 void unmapnotify(XEvent *e);
184 void updatebarpos(void);
185 void updatesizehints(Client *c);
186 void updatetitle(Client *c);
187 void view(const char *arg);
188 void viewprevtag(const char *arg); /* views previous selected tags */
189 int xerror(Display *dpy, XErrorEvent *ee);
190 int xerrordummy(Display *dsply, XErrorEvent *ee);
191 int xerrorstart(Display *dsply, XErrorEvent *ee);
192 void zoom(const char *arg);
197 int screen, sx, sy, sw, sh, wax, way, waw, wah;
198 int (*xerrorxlib)(Display *, XErrorEvent *);
199 unsigned int bh, bpos;
200 unsigned int blw = 0;
201 unsigned int ltidx = 0; /* default */
202 unsigned int nlayouts = 0;
203 unsigned int nrules = 0;
204 unsigned int numlockmask = 0;
205 void (*handler[LASTEvent]) (XEvent *) = {
206 [ButtonPress] = buttonpress,
207 [ConfigureRequest] = configurerequest,
208 [ConfigureNotify] = configurenotify,
209 [DestroyNotify] = destroynotify,
210 [EnterNotify] = enternotify,
211 [LeaveNotify] = leavenotify,
213 [KeyPress] = keypress,
214 [MappingNotify] = mappingnotify,
215 [MapRequest] = maprequest,
216 [PropertyNotify] = propertynotify,
217 [UnmapNotify] = unmapnotify
219 Atom wmatom[WMLast], netatom[NetLast];
220 Bool otherwm, readin;
222 Bool selscreen = True;
223 Client *clients = NULL;
225 Client *stack = NULL;
226 Cursor cursor[CurLast];
232 /* configuration, allows nested code to access above variables */
235 /* function implementations */
237 applyrules(Client *c) {
238 static char buf[512];
241 Bool matched = False;
242 XClassHint ch = { 0 };
245 XGetClassHint(dpy, c->win, &ch);
246 snprintf(buf, sizeof buf, "%s:%s:%s",
247 ch.res_class ? ch.res_class : "",
248 ch.res_name ? ch.res_name : "", c->name);
249 for(i = 0; i < nrules; i++)
250 if(regs[i].propregex && !regexec(regs[i].propregex, buf, 1, &tmp, 0)) {
251 c->isfloating = rules[i].isfloating;
252 for(j = 0; regs[i].tagregex && j < NTAGS; j++) {
253 if(!regexec(regs[i].tagregex, tags[j], 1, &tmp, 0)) {
264 memcpy(c->tags, seltags, sizeof seltags);
271 for(c = clients; c; c = c->next)
276 layouts[ltidx].arrange();
290 attachstack(Client *c) {
299 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
304 buttonpress(XEvent *e) {
307 XButtonPressedEvent *ev = &e->xbutton;
309 if(barwin == ev->window) {
311 for(i = 0; i < NTAGS; i++) {
314 if(ev->button == Button1) {
315 if(ev->state & MODKEY)
320 else if(ev->button == Button3) {
321 if(ev->state & MODKEY)
329 if((ev->x < x + blw) && ev->button == Button1)
332 else if((c = getclient(ev->window))) {
334 if(CLEANMASK(ev->state) != MODKEY)
336 if(ev->button == Button1) {
337 if(isarrange(floating) || c->isfloating)
340 togglefloating(NULL);
343 else if(ev->button == Button2) {
344 if((ISTILE) && !c->isfixed && c->isfloating)
345 togglefloating(NULL);
349 else if(ev->button == Button3 && !c->isfixed) {
350 if(isarrange(floating) || c->isfloating)
353 togglefloating(NULL);
362 XSetErrorHandler(xerrorstart);
364 /* this causes an error if some other window manager is running */
365 XSelectInput(dpy, root, SubstructureRedirectMask);
368 eprint("dwm: another window manager is already running\n");
370 XSetErrorHandler(NULL);
371 xerrorxlib = XSetErrorHandler(xerror);
383 XFreeFontSet(dpy, dc.font.set);
385 XFreeFont(dpy, dc.font.xfont);
386 XUngrabKey(dpy, AnyKey, AnyModifier, root);
387 XFreePixmap(dpy, dc.drawable);
389 XDestroyWindow(dpy, barwin);
390 XFreeCursor(dpy, cursor[CurNormal]);
391 XFreeCursor(dpy, cursor[CurResize]);
392 XFreeCursor(dpy, cursor[CurMove]);
393 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
404 nrules = sizeof rules / sizeof rules[0];
405 regs = emallocz(nrules * sizeof(Regs));
406 for(i = 0; i < nrules; i++) {
408 reg = emallocz(sizeof(regex_t));
409 if(regcomp(reg, rules[i].prop, REG_EXTENDED))
412 regs[i].propregex = reg;
415 reg = emallocz(sizeof(regex_t));
416 if(regcomp(reg, rules[i].tags, REG_EXTENDED))
419 regs[i].tagregex = reg;
425 configure(Client *c) {
428 ce.type = ConfigureNotify;
436 ce.border_width = c->border;
438 ce.override_redirect = False;
439 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
443 configurenotify(XEvent *e) {
444 XConfigureEvent *ev = &e->xconfigure;
446 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
449 XFreePixmap(dpy, dc.drawable);
450 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
451 XResizeWindow(dpy, barwin, sw, bh);
458 configurerequest(XEvent *e) {
460 XConfigureRequestEvent *ev = &e->xconfigurerequest;
463 if((c = getclient(ev->window))) {
465 if(ev->value_mask & CWBorderWidth)
466 c->border = ev->border_width;
467 if(c->isfixed || c->isfloating || isarrange(floating)) {
468 if(ev->value_mask & CWX)
470 if(ev->value_mask & CWY)
472 if(ev->value_mask & CWWidth)
474 if(ev->value_mask & CWHeight)
476 if((c->x + c->w) > sw && c->isfloating)
477 c->x = sw / 2 - c->w / 2; /* center in x direction */
478 if((c->y + c->h) > sh && c->isfloating)
479 c->y = sh / 2 - c->h / 2; /* center in y direction */
480 if((ev->value_mask & (CWX | CWY))
481 && !(ev->value_mask & (CWWidth | CWHeight)))
484 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
492 wc.width = ev->width;
493 wc.height = ev->height;
494 wc.border_width = ev->border_width;
495 wc.sibling = ev->above;
496 wc.stack_mode = ev->detail;
497 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
503 destroynotify(XEvent *e) {
505 XDestroyWindowEvent *ev = &e->xdestroywindow;
507 if((c = getclient(ev->window)))
514 c->prev->next = c->next;
516 c->next->prev = c->prev;
519 c->next = c->prev = NULL;
523 detachstack(Client *c) {
526 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
535 for(i = 0; i < NTAGS; i++) {
536 dc.w = textw(tags[i]);
538 drawtext(tags[i], dc.sel);
539 drawsquare(sel && sel->tags[i], isoccupied(i), dc.sel);
542 drawtext(tags[i], dc.norm);
543 drawsquare(sel && sel->tags[i], isoccupied(i), dc.norm);
548 drawtext(layouts[ltidx].symbol, dc.norm);
556 drawtext(stext, dc.norm);
557 if((dc.w = dc.x - x) > bh) {
560 drawtext(sel->name, dc.sel);
561 drawsquare(sel->ismax, sel->isfloating, dc.sel);
564 drawtext(NULL, dc.norm);
566 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, sw, bh, 0, 0);
571 drawsquare(Bool filled, Bool empty, unsigned long col[ColLast]) {
574 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
576 gcv.foreground = col[ColFG];
577 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
578 x = (dc.font.ascent + dc.font.descent + 2) / 4;
582 r.width = r.height = x + 1;
583 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
586 r.width = r.height = x;
587 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
592 drawtext(const char *text, unsigned long col[ColLast]) {
594 static char buf[256];
595 unsigned int len, olen;
596 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
598 XSetForeground(dpy, dc.gc, col[ColBG]);
599 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
603 olen = len = strlen(text);
604 if(len >= sizeof buf)
605 len = sizeof buf - 1;
606 memcpy(buf, text, len);
608 h = dc.font.ascent + dc.font.descent;
609 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
611 /* shorten text if necessary */
612 while(len && (w = textnw(buf, len)) > dc.w - h)
623 return; /* too long */
624 XSetForeground(dpy, dc.gc, col[ColFG]);
626 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
628 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
632 emallocz(unsigned int size) {
633 void *res = calloc(1, size);
636 eprint("fatal: could not malloc() %u bytes\n", size);
641 enternotify(XEvent *e) {
643 XCrossingEvent *ev = &e->xcrossing;
645 if(ev->mode != NotifyNormal || ev->detail == NotifyInferior)
647 if((c = getclient(ev->window)))
649 else if(ev->window == root) {
656 eprint(const char *errstr, ...) {
659 va_start(ap, errstr);
660 vfprintf(stderr, errstr, ap);
667 XExposeEvent *ev = &e->xexpose;
670 if(barwin == ev->window)
676 floating(void) { /* default floating layout */
679 for(c = clients; c; c = c->next)
681 resize(c, c->x, c->y, c->w, c->h, True);
686 if((!c && selscreen) || (c && !isvisible(c)))
687 for(c = stack; c && !isvisible(c); c = c->snext);
688 if(sel && sel != c) {
689 grabbuttons(sel, False);
690 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
695 grabbuttons(c, True);
702 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
703 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
706 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
710 focusnext(const char *arg) {
715 for(c = sel->next; c && !isvisible(c); c = c->next);
717 for(c = clients; c && !isvisible(c); c = c->next);
725 focusprev(const char *arg) {
730 for(c = sel->prev; c && !isvisible(c); c = c->prev);
732 for(c = clients; c && c->next; c = c->next);
733 for(; c && !isvisible(c); c = c->prev);
742 getclient(Window w) {
745 for(c = clients; c && c->win != w; c = c->next);
750 getcolor(const char *colstr) {
751 Colormap cmap = DefaultColormap(dpy, screen);
754 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
755 eprint("error, cannot allocate color '%s'\n", colstr);
763 unsigned char *p = NULL;
764 unsigned long n, extra;
767 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
768 &real, &format, &n, &extra, (unsigned char **)&p);
769 if(status != Success)
778 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
783 if(!text || size == 0)
786 XGetTextProperty(dpy, w, &name, atom);
789 if(name.encoding == XA_STRING)
790 strncpy(text, (char *)name.value, size - 1);
792 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
795 strncpy(text, *list, size - 1);
796 XFreeStringList(list);
799 text[size - 1] = '\0';
805 grabbuttons(Client *c, Bool focused) {
806 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
809 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
810 GrabModeAsync, GrabModeSync, None, None);
811 XGrabButton(dpy, Button1, MODKEY | LockMask, c->win, False, BUTTONMASK,
812 GrabModeAsync, GrabModeSync, None, None);
813 XGrabButton(dpy, Button1, MODKEY | numlockmask, c->win, False, BUTTONMASK,
814 GrabModeAsync, GrabModeSync, None, None);
815 XGrabButton(dpy, Button1, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
816 GrabModeAsync, GrabModeSync, None, None);
818 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
819 GrabModeAsync, GrabModeSync, None, None);
820 XGrabButton(dpy, Button2, MODKEY | LockMask, c->win, False, BUTTONMASK,
821 GrabModeAsync, GrabModeSync, None, None);
822 XGrabButton(dpy, Button2, MODKEY | numlockmask, c->win, False, BUTTONMASK,
823 GrabModeAsync, GrabModeSync, None, None);
824 XGrabButton(dpy, Button2, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
825 GrabModeAsync, GrabModeSync, None, None);
827 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
828 GrabModeAsync, GrabModeSync, None, None);
829 XGrabButton(dpy, Button3, MODKEY | LockMask, c->win, False, BUTTONMASK,
830 GrabModeAsync, GrabModeSync, None, None);
831 XGrabButton(dpy, Button3, MODKEY | numlockmask, c->win, False, BUTTONMASK,
832 GrabModeAsync, GrabModeSync, None, None);
833 XGrabButton(dpy, Button3, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
834 GrabModeAsync, GrabModeSync, None, None);
837 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
838 GrabModeAsync, GrabModeSync, None, None);
842 idxoftag(const char *tag) {
845 for(i = 0; (i < NTAGS) && (tags[i] != tag); i++);
846 return (i < NTAGS) ? i : 0;
850 initfont(const char *fontstr) {
851 char *def, **missing;
856 XFreeFontSet(dpy, dc.font.set);
857 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
860 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
861 XFreeStringList(missing);
864 XFontSetExtents *font_extents;
865 XFontStruct **xfonts;
867 dc.font.ascent = dc.font.descent = 0;
868 font_extents = XExtentsOfFontSet(dc.font.set);
869 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
870 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
871 if(dc.font.ascent < (*xfonts)->ascent)
872 dc.font.ascent = (*xfonts)->ascent;
873 if(dc.font.descent < (*xfonts)->descent)
874 dc.font.descent = (*xfonts)->descent;
880 XFreeFont(dpy, dc.font.xfont);
881 dc.font.xfont = NULL;
882 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
883 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
884 eprint("error, cannot load font: '%s'\n", fontstr);
885 dc.font.ascent = dc.font.xfont->ascent;
886 dc.font.descent = dc.font.xfont->descent;
888 dc.font.height = dc.font.ascent + dc.font.descent;
892 isarrange(void (*func)())
894 return func == layouts[ltidx].arrange;
898 isoccupied(unsigned int t) {
901 for(c = clients; c; c = c->next)
908 isprotodel(Client *c) {
913 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
914 for(i = 0; !ret && i < n; i++)
915 if(protocols[i] == wmatom[WMDelete])
923 isvisible(Client *c) {
926 for(i = 0; i < NTAGS; i++)
927 if(c->tags[i] && seltags[i])
933 keypress(XEvent *e) {
935 unsigned int len = sizeof keys / sizeof keys[0];
941 if(!e) { /* grabkeys */
942 XUngrabKey(dpy, AnyKey, AnyModifier, root);
943 for(i = 0; i < len; i++) {
944 code = XKeysymToKeycode(dpy, keys[i].keysym);
945 XGrabKey(dpy, code, keys[i].mod, root, True,
946 GrabModeAsync, GrabModeAsync);
947 XGrabKey(dpy, code, keys[i].mod | LockMask, root, True,
948 GrabModeAsync, GrabModeAsync);
949 XGrabKey(dpy, code, keys[i].mod | numlockmask, root, True,
950 GrabModeAsync, GrabModeAsync);
951 XGrabKey(dpy, code, keys[i].mod | numlockmask | LockMask, root, True,
952 GrabModeAsync, GrabModeAsync);
957 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
958 for(i = 0; i < len; i++)
959 if(keysym == keys[i].keysym
960 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
963 keys[i].func(keys[i].arg);
968 killclient(const char *arg) {
973 if(isprotodel(sel)) {
974 ev.type = ClientMessage;
975 ev.xclient.window = sel->win;
976 ev.xclient.message_type = wmatom[WMProtocols];
977 ev.xclient.format = 32;
978 ev.xclient.data.l[0] = wmatom[WMDelete];
979 ev.xclient.data.l[1] = CurrentTime;
980 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
983 XKillClient(dpy, sel->win);
987 leavenotify(XEvent *e) {
988 XCrossingEvent *ev = &e->xcrossing;
990 if((ev->window == root) && !ev->same_screen) {
997 manage(Window w, XWindowAttributes *wa) {
998 Client *c, *t = NULL;
1003 c = emallocz(sizeof(Client));
1004 c->tags = emallocz(sizeof seltags);
1010 c->oldborder = wa->border_width;
1011 if(c->w == sw && c->h == sh) {
1014 c->border = wa->border_width;
1017 if(c->x + c->w + 2 * c->border > wax + waw)
1018 c->x = wax + waw - c->w - 2 * c->border;
1019 if(c->y + c->h + 2 * c->border > way + wah)
1020 c->y = way + wah - c->h - 2 * c->border;
1025 c->border = BORDERPX;
1027 wc.border_width = c->border;
1028 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1029 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1030 configure(c); /* propagates border_width, if size doesn't change */
1032 XSelectInput(dpy, w,
1033 StructureNotifyMask | PropertyChangeMask | EnterWindowMask);
1034 grabbuttons(c, False);
1036 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
1037 for(t = clients; t && t->win != trans; t = t->next);
1039 memcpy(c->tags, t->tags, sizeof seltags);
1042 c->isfloating = (rettrans == Success) || c->isfixed;
1045 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
1047 XMapWindow(dpy, c->win);
1048 setclientstate(c, NormalState);
1053 mappingnotify(XEvent *e) {
1054 XMappingEvent *ev = &e->xmapping;
1056 XRefreshKeyboardMapping(ev);
1057 if(ev->request == MappingKeyboard)
1062 maprequest(XEvent *e) {
1063 static XWindowAttributes wa;
1064 XMapRequestEvent *ev = &e->xmaprequest;
1066 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1068 if(wa.override_redirect)
1070 if(!getclient(ev->window))
1071 manage(ev->window, &wa);
1075 movemouse(Client *c) {
1076 int x1, y1, ocx, ocy, di, nx, ny;
1083 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1084 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1087 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1089 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask, &ev);
1092 XUngrabPointer(dpy, CurrentTime);
1094 case ConfigureRequest:
1097 handler[ev.type](&ev);
1101 nx = ocx + (ev.xmotion.x - x1);
1102 ny = ocy + (ev.xmotion.y - y1);
1103 if(abs(wax + nx) < SNAP)
1105 else if(abs((wax + waw) - (nx + c->w + 2 * c->border)) < SNAP)
1106 nx = wax + waw - c->w - 2 * c->border;
1107 if(abs(way - ny) < SNAP)
1109 else if(abs((way + wah) - (ny + c->h + 2 * c->border)) < SNAP)
1110 ny = way + wah - c->h - 2 * c->border;
1111 resize(c, nx, ny, c->w, c->h, False);
1118 nexttiled(Client *c) {
1119 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1124 propertynotify(XEvent *e) {
1127 XPropertyEvent *ev = &e->xproperty;
1129 if(ev->state == PropertyDelete)
1130 return; /* ignore */
1131 if((c = getclient(ev->window))) {
1134 case XA_WM_TRANSIENT_FOR:
1135 XGetTransientForHint(dpy, c->win, &trans);
1136 if(!c->isfloating && (c->isfloating = (NULL != getclient(trans))))
1139 case XA_WM_NORMAL_HINTS:
1143 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1152 quit(const char *arg) {
1153 readin = running = False;
1157 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1161 /* set minimum possible */
1167 /* temporarily remove base dimensions */
1171 /* adjust for aspect limits */
1172 if (c->minay > 0 && c->maxay > 0 && c->minax > 0 && c->maxax > 0) {
1173 if (w * c->maxay > h * c->maxax)
1174 w = h * c->maxax / c->maxay;
1175 else if (w * c->minay < h * c->minax)
1176 h = w * c->minay / c->minax;
1179 /* adjust for increment value */
1185 /* restore base dimensions */
1189 if(c->minw > 0 && w < c->minw)
1191 if(c->minh > 0 && h < c->minh)
1193 if(c->maxw > 0 && w > c->maxw)
1195 if(c->maxh > 0 && h > c->maxh)
1198 if(w <= 0 || h <= 0)
1200 /* offscreen appearance fixes */
1202 x = sw - w - 2 * c->border;
1204 y = sh - h - 2 * c->border;
1205 if(x + w + 2 * c->border < sx)
1207 if(y + h + 2 * c->border < sy)
1209 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1212 c->w = wc.width = w;
1213 c->h = wc.height = h;
1214 wc.border_width = c->border;
1215 XConfigureWindow(dpy, c->win, CWX | CWY | CWWidth | CWHeight | CWBorderWidth, &wc);
1222 resizemouse(Client *c) {
1229 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1230 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1233 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
1235 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask , &ev);
1238 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1239 c->w + c->border - 1, c->h + c->border - 1);
1240 XUngrabPointer(dpy, CurrentTime);
1241 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1243 case ConfigureRequest:
1246 handler[ev.type](&ev);
1250 if((nw = ev.xmotion.x - ocx - 2 * c->border + 1) <= 0)
1252 if((nh = ev.xmotion.y - ocy - 2 * c->border + 1) <= 0)
1254 resize(c, c->x, c->y, nw, nh, True);
1269 if(sel->isfloating || isarrange(floating))
1270 XRaiseWindow(dpy, sel->win);
1271 if(!isarrange(floating)) {
1272 wc.stack_mode = Below;
1273 wc.sibling = barwin;
1274 if(!sel->isfloating) {
1275 XConfigureWindow(dpy, sel->win, CWSibling | CWStackMode, &wc);
1276 wc.sibling = sel->win;
1278 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
1281 XConfigureWindow(dpy, c->win, CWSibling | CWStackMode, &wc);
1282 wc.sibling = c->win;
1286 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1296 /* main event loop, also reads status text from stdin */
1298 xfd = ConnectionNumber(dpy);
1303 FD_SET(STDIN_FILENO, &rd);
1305 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1308 eprint("select failed\n");
1310 if(FD_ISSET(STDIN_FILENO, &rd)) {
1311 switch(r = read(STDIN_FILENO, stext, sizeof stext - 1)) {
1313 strncpy(stext, strerror(errno), sizeof stext - 1);
1314 stext[sizeof stext - 1] = '\0';
1318 strncpy(stext, "EOF", 4);
1322 for(stext[r] = '\0', p = stext + strlen(stext) - 1; p >= stext && *p == '\n'; *p-- = '\0');
1323 for(; p >= stext && *p != '\n'; --p);
1325 strncpy(stext, p + 1, sizeof stext);
1329 while(XPending(dpy)) {
1330 XNextEvent(dpy, &ev);
1331 if(handler[ev.type])
1332 (handler[ev.type])(&ev); /* call handler */
1339 unsigned int i, num;
1340 Window *wins, d1, d2;
1341 XWindowAttributes wa;
1344 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1345 for(i = 0; i < num; i++) {
1346 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1347 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1349 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1350 manage(wins[i], &wa);
1352 for(i = 0; i < num; i++) { /* now the transients */
1353 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1355 if(XGetTransientForHint(dpy, wins[i], &d1)
1356 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1357 manage(wins[i], &wa);
1365 setclientstate(Client *c, long state) {
1366 long data[] = {state, None};
1368 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1369 PropModeReplace, (unsigned char *)data, 2);
1373 setlayout(const char *arg) {
1377 if(++ltidx == nlayouts)
1381 for(i = 0; i < nlayouts; i++)
1382 if(!strcmp(arg, layouts[i].symbol))
1395 setmwfact(const char *arg) {
1400 /* arg handling, manipulate mwfact */
1403 else if(1 == sscanf(arg, "%lf", &delta)) {
1404 if(arg[0] == '+' || arg[0] == '-')
1410 else if(mwfact > 0.9)
1419 unsigned int i, j, mask;
1421 XModifierKeymap *modmap;
1422 XSetWindowAttributes wa;
1425 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1426 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1427 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1428 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1429 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1430 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1431 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1432 PropModeReplace, (unsigned char *) netatom, NetLast);
1435 cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1436 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1437 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1441 sw = DisplayWidth(dpy, screen);
1442 sh = DisplayHeight(dpy, screen);
1444 /* init modifier map */
1445 modmap = XGetModifierMapping(dpy);
1446 for(i = 0; i < 8; i++)
1447 for(j = 0; j < modmap->max_keypermod; j++) {
1448 if(modmap->modifiermap[i * modmap->max_keypermod + j]
1449 == XKeysymToKeycode(dpy, XK_Num_Lock))
1450 numlockmask = (1 << i);
1452 XFreeModifiermap(modmap);
1454 /* select for events */
1455 wa.event_mask = SubstructureRedirectMask | SubstructureNotifyMask
1456 | EnterWindowMask | LeaveWindowMask | StructureNotifyMask;
1457 wa.cursor = cursor[CurNormal];
1458 XChangeWindowAttributes(dpy, root, CWEventMask | CWCursor, &wa);
1459 XSelectInput(dpy, root, wa.event_mask);
1467 /* init appearance */
1468 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1469 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1470 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1471 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1472 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1473 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1475 dc.h = bh = dc.font.height + 2;
1479 nlayouts = sizeof layouts / sizeof layouts[0];
1480 for(blw = i = 0; i < nlayouts; i++) {
1481 j = textw(layouts[i].symbol);
1488 wa.override_redirect = 1;
1489 wa.background_pixmap = ParentRelative;
1490 wa.event_mask = ButtonPressMask | ExposureMask;
1491 barwin = XCreateWindow(dpy, root, sx, sy, sw, bh, 0,
1492 DefaultDepth(dpy, screen), CopyFromParent, DefaultVisual(dpy, screen),
1493 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
1494 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1496 XMapRaised(dpy, barwin);
1497 strcpy(stext, "dwm-"VERSION);
1498 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
1499 dc.gc = XCreateGC(dpy, root, 0, 0);
1500 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1502 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1504 /* multihead support */
1505 selscreen = XQueryPointer(dpy, root, &w, &w, &d, &d, &d, &d, &mask);
1509 spawn(const char *arg) {
1510 static char *shell = NULL;
1512 if(!shell && !(shell = getenv("SHELL")))
1516 /* The double-fork construct avoids zombie processes and keeps the code
1517 * clean from stupid signal handlers. */
1521 close(ConnectionNumber(dpy));
1523 execl(shell, shell, "-c", arg, (char *)NULL);
1524 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1533 tag(const char *arg) {
1538 for(i = 0; i < NTAGS; i++)
1539 sel->tags[i] = (NULL == arg);
1540 sel->tags[idxoftag(arg)] = True;
1545 textnw(const char *text, unsigned int len) {
1549 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1552 return XTextWidth(dc.font.xfont, text, len);
1556 textw(const char *text) {
1557 return textnw(text, strlen(text)) + dc.font.height;
1562 unsigned int i, n, nx, ny, nw, nh, mw, th;
1565 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next))
1569 mw = (n == 1) ? waw : mwfact * waw;
1570 th = (n > 1) ? wah / (n - 1) : 0;
1571 if(n > 1 && th < bh)
1576 nw = 0; /* gcc stupidity requires this */
1577 for(i = 0, c = mc = nexttiled(clients); c; c = nexttiled(c->next), i++) {
1579 if(i == 0) { /* master */
1580 nw = mw - 2 * c->border;
1581 nh = wah - 2 * c->border;
1583 else { /* tile window */
1586 nx += mc->w + 2 * mc->border;
1587 nw = waw - nx - 2 * c->border;
1589 if(i + 1 == n) /* remainder */
1590 nh = (way + wah) - ny - 2 * c->border;
1592 nh = th - 2 * c->border;
1594 resize(c, nx, ny, nw, nh, True);
1595 if((c->h < bh) || (c->h > nh) || (c->w < bh) || (c->w > nw))
1596 /* client doesn't accept size constraints */
1597 resize(c, nx, ny, nw, nh, False);
1598 if(n > 1 && th != wah)
1599 ny = c->y + c->h + 2 * c->border;
1604 togglebar(const char *arg) {
1606 bpos = (BARPOS == BarOff) ? BarTop : BARPOS;
1614 togglefloating(const char *arg) {
1617 sel->isfloating = !sel->isfloating;
1619 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1624 togglemax(const char *arg) {
1627 if(!sel || sel->isfixed)
1629 if((sel->ismax = !sel->ismax)) {
1630 if(isarrange(floating) || sel->isfloating)
1631 sel->wasfloating = True;
1633 togglefloating(NULL);
1634 sel->wasfloating = False;
1640 resize(sel, wax, way, waw - 2 * sel->border, wah - 2 * sel->border, True);
1643 resize(sel, sel->rx, sel->ry, sel->rw, sel->rh, True);
1644 if(!sel->wasfloating)
1645 togglefloating(NULL);
1648 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1652 toggletag(const char *arg) {
1658 sel->tags[i] = !sel->tags[i];
1659 for(j = 0; j < NTAGS && !sel->tags[j]; j++);
1661 sel->tags[i] = True; /* at least one tag must be enabled */
1666 toggleview(const char *arg) {
1670 seltags[i] = !seltags[i];
1671 for(j = 0; j < NTAGS && !seltags[j]; j++);
1673 seltags[i] = True; /* at least one tag must be viewed */
1681 XMoveWindow(dpy, c->win, c->x, c->y);
1682 c->isbanned = False;
1686 unmanage(Client *c) {
1689 wc.border_width = c->oldborder;
1690 /* The server grab construct avoids race conditions. */
1692 XSetErrorHandler(xerrordummy);
1693 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1698 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1699 setclientstate(c, WithdrawnState);
1703 XSetErrorHandler(xerror);
1709 unmapnotify(XEvent *e) {
1711 XUnmapEvent *ev = &e->xunmap;
1713 if((c = getclient(ev->window)))
1718 updatebarpos(void) {
1729 XMoveWindow(dpy, barwin, sx, sy);
1733 XMoveWindow(dpy, barwin, sx, sy + wah);
1736 XMoveWindow(dpy, barwin, sx, sy - bh);
1740 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1744 updatesizehints(Client *c) {
1748 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1750 c->flags = size.flags;
1751 if(c->flags & PBaseSize) {
1752 c->basew = size.base_width;
1753 c->baseh = size.base_height;
1755 else if(c->flags & PMinSize) {
1756 c->basew = size.min_width;
1757 c->baseh = size.min_height;
1760 c->basew = c->baseh = 0;
1761 if(c->flags & PResizeInc) {
1762 c->incw = size.width_inc;
1763 c->inch = size.height_inc;
1766 c->incw = c->inch = 0;
1767 if(c->flags & PMaxSize) {
1768 c->maxw = size.max_width;
1769 c->maxh = size.max_height;
1772 c->maxw = c->maxh = 0;
1773 if(c->flags & PMinSize) {
1774 c->minw = size.min_width;
1775 c->minh = size.min_height;
1777 else if(c->flags & PBaseSize) {
1778 c->minw = size.base_width;
1779 c->minh = size.base_height;
1782 c->minw = c->minh = 0;
1783 if(c->flags & PAspect) {
1784 c->minax = size.min_aspect.x;
1785 c->maxax = size.max_aspect.x;
1786 c->minay = size.min_aspect.y;
1787 c->maxay = size.max_aspect.y;
1790 c->minax = c->maxax = c->minay = c->maxay = 0;
1791 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1792 && c->maxw == c->minw && c->maxh == c->minh);
1796 updatetitle(Client *c) {
1797 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1798 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1801 /* There's no way to check accesses to destroyed windows, thus those cases are
1802 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1803 * default error handler, which may call exit. */
1805 xerror(Display *dpy, XErrorEvent *ee) {
1806 if(ee->error_code == BadWindow
1807 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1808 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1809 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1810 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1811 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1812 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1813 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1815 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1816 ee->request_code, ee->error_code);
1817 return xerrorxlib(dpy, ee); /* may call exit */
1821 xerrordummy(Display *dsply, XErrorEvent *ee) {
1825 /* Startup Error handler to check if another window manager
1826 * is already running. */
1828 xerrorstart(Display *dsply, XErrorEvent *ee) {
1834 view(const char *arg) {
1837 memcpy(prevtags, seltags, sizeof seltags);
1838 for(i = 0; i < NTAGS; i++)
1839 seltags[i] = arg == NULL;
1840 seltags[idxoftag(arg)] = True;
1845 viewprevtag(const char *arg) {
1846 static Bool tmptags[sizeof tags / sizeof tags[0]];
1848 memcpy(tmptags, seltags, sizeof seltags);
1849 memcpy(seltags, prevtags, sizeof seltags);
1850 memcpy(prevtags, tmptags, sizeof seltags);
1855 zoom(const char *arg) {
1858 if(!sel || !(ISTILE) || sel->isfloating)
1860 if((c = sel) == nexttiled(clients))
1861 if(!(c = nexttiled(c->next)))
1870 main(int argc, char *argv[]) {
1871 if(argc == 2 && !strcmp("-v", argv[1]))
1872 eprint("dwm-"VERSION", © 2006-2007 A. R. Garbe, S. van Dijk, J. Salmi, P. Hruby, S. Nagy\n");
1874 eprint("usage: dwm [-v]\n");
1876 setlocale(LC_CTYPE, "");
1877 if(!(dpy = XOpenDisplay(0)))
1878 eprint("dwm: cannot open display\n");
1879 screen = DefaultScreen(dpy);
1880 root = RootWindow(dpy, screen);