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 the config.h
25 * file. These arrays are kept static in event.o and tag.o respectively,
26 * because no other part of dwm needs access to them. The current layout is
27 * represented by the lt pointer.
29 * To understand everything else, start reading main().
39 #include <sys/select.h>
41 #include <X11/cursorfont.h>
42 #include <X11/keysym.h>
43 #include <X11/Xatom.h>
44 #include <X11/Xproto.h>
45 #include <X11/Xutil.h>
48 #define BUTTONMASK (ButtonPressMask | ButtonReleaseMask)
49 #define CLEANMASK(mask) (mask & ~(numlockmask | LockMask))
50 #define MOUSEMASK (BUTTONMASK | PointerMotionMask)
53 enum { BarTop, BarBot, BarOff }; /* bar position */
54 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
55 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
56 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
57 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
60 typedef struct Client Client;
64 int 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;
79 unsigned long norm[ColLast];
80 unsigned long sel[ColLast];
90 } DC; /* draw context */
95 void (*func)(const char *arg);
101 void (*arrange)(void);
117 static void applyrules(Client *c);
118 static void arrange(void);
119 static void attach(Client *c);
120 static void attachstack(Client *c);
121 static void ban(Client *c);
122 static void buttonpress(XEvent *e);
123 static void cleanup(void);
124 static void compileregs(void);
125 static void configure(Client *c);
126 static void configurenotify(XEvent *e);
127 static void configurerequest(XEvent *e);
128 static void destroynotify(XEvent *e);
129 static void detach(Client *c);
130 static void detachstack(Client *c);
131 static void drawbar(void);
132 static void drawsquare(Bool filled, Bool empty, unsigned long col[ColLast]);
133 static void drawtext(const char *text, unsigned long col[ColLast]);
134 static void *emallocz(unsigned int size);
135 static void enternotify(XEvent *e);
136 static void eprint(const char *errstr, ...);
137 static void expose(XEvent *e);
138 static void floating(void); /* default floating layout */
139 static void focus(Client *c);
140 static void focusnext(const char *arg);
141 static void focusprev(const char *arg);
142 static Client *getclient(Window w);
143 static long getstate(Window w);
144 static Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
145 static void grabbuttons(Client *c, Bool focused);
146 static unsigned int idxoftag(const char *tag);
147 static void initbar(void);
148 static unsigned long initcolor(const char *colstr);
149 static void initfont(const char *fontstr);
150 static void initlayouts(void);
151 static void initstyle(void);
152 static Bool isarrange(void (*func)());
153 static Bool isfloating(void);
154 static Bool isoccupied(unsigned int t);
155 static Bool isprotodel(Client *c);
156 static Bool isvisible(Client *c);
157 static void keypress(XEvent *e);
158 static void killclient(const char *arg);
159 static void leavenotify(XEvent *e);
160 static void manage(Window w, XWindowAttributes *wa);
161 static void mappingnotify(XEvent *e);
162 static void maprequest(XEvent *e);
163 static void movemouse(Client *c);
164 static Client *nexttiled(Client *c);
165 static void propertynotify(XEvent *e);
166 static void quit(const char *arg);
167 static void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
168 static void resizemouse(Client *c);
169 static void restack(void);
170 static void scan(void);
171 static void setclientstate(Client *c, long state);
172 static void setlayout(const char *arg);
173 static void setmwfact(const char *arg);
174 static void setup(void);
175 static void spawn(const char *arg);
176 static void tag(const char *arg);
177 static unsigned int textnw(const char *text, unsigned int len);
178 static unsigned int textw(const char *text);
179 static void tile(void);
180 static void togglebar(const char *arg);
181 static void togglefloating(const char *arg);
182 static void togglemax(const char *arg);
183 static void toggletag(const char *arg);
184 static void toggleview(const char *arg);
185 static void unban(Client *c);
186 static void unmanage(Client *c);
187 static void unmapnotify(XEvent *e);
188 static void updatebarpos(void);
189 static void updatesizehints(Client *c);
190 static void updatetitle(Client *c);
191 static void view(const char *arg);
192 static int xerror(Display *dpy, XErrorEvent *ee);
193 static int xerrordummy(Display *dsply, XErrorEvent *ee);
194 static int xerrorstart(Display *dsply, XErrorEvent *ee);
195 static void zoom(const char *arg);
198 static char stext[256];
199 static double mwfact;
200 static int screen, sx, sy, sw, sh, wax, way, waw, wah;
201 static int (*xerrorxlib)(Display *, XErrorEvent *);
202 static unsigned int bh, bpos, ntags;
203 static unsigned int blw = 0;
204 static unsigned int ltidx = 0; /* default */
205 static unsigned int nlayouts = 0;
206 static unsigned int nrules = 0;
207 static unsigned int numlockmask = 0;
208 static void (*handler[LASTEvent]) (XEvent *) = {
209 [ButtonPress] = buttonpress,
210 [ConfigureRequest] = configurerequest,
211 [ConfigureNotify] = configurenotify,
212 [DestroyNotify] = destroynotify,
213 [EnterNotify] = enternotify,
214 [LeaveNotify] = leavenotify,
216 [KeyPress] = keypress,
217 [MappingNotify] = mappingnotify,
218 [MapRequest] = maprequest,
219 [PropertyNotify] = propertynotify,
220 [UnmapNotify] = unmapnotify
222 static Atom wmatom[WMLast], netatom[NetLast];
223 static Bool otherwm, readin;
224 static Bool running = True;
225 static Bool *seltags;
226 static Bool selscreen = True;
227 static Client *clients = NULL;
228 static Client *sel = NULL;
229 static Client *stack = NULL;
230 static Cursor cursor[CurLast];
233 static Window barwin, root;
234 static Regs *regs = NULL;
236 /* configuration, allows nested code to access above variables */
241 applyrules(Client *c) {
242 static char buf[512];
245 Bool matched = False;
246 XClassHint ch = { 0 };
249 XGetClassHint(dpy, c->win, &ch);
250 snprintf(buf, sizeof buf, "%s:%s:%s",
251 ch.res_class ? ch.res_class : "",
252 ch.res_name ? ch.res_name : "", c->name);
253 for(i = 0; i < nrules; i++)
254 if(regs[i].propregex && !regexec(regs[i].propregex, buf, 1, &tmp, 0)) {
255 c->isfloating = rules[i].isfloating;
256 for(j = 0; regs[i].tagregex && j < ntags; j++) {
257 if(!regexec(regs[i].tagregex, tags[j], 1, &tmp, 0)) {
268 for(i = 0; i < ntags; i++)
269 c->tags[i] = seltags[i];
276 for(c = clients; c; c = c->next)
281 layouts[ltidx].arrange();
295 attachstack(Client *c) {
304 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
309 buttonpress(XEvent *e) {
312 XButtonPressedEvent *ev = &e->xbutton;
314 if(barwin == ev->window) {
316 for(i = 0; i < ntags; i++) {
319 if(ev->button == Button1) {
320 if(ev->state & MODKEY)
325 else if(ev->button == Button3) {
326 if(ev->state & MODKEY)
334 if((ev->x < x + blw) && ev->button == Button1)
337 else if((c = getclient(ev->window))) {
339 if(CLEANMASK(ev->state) != MODKEY)
341 if(ev->button == Button1 && (isfloating() || c->isfloating)) {
345 else if(ev->button == Button2)
347 else if(ev->button == Button3
348 && (isfloating() || c->isfloating) && !c->isfixed)
364 XFreeFontSet(dpy, dc.font.set);
366 XFreeFont(dpy, dc.font.xfont);
367 XUngrabKey(dpy, AnyKey, AnyModifier, root);
368 XFreePixmap(dpy, dc.drawable);
370 XDestroyWindow(dpy, barwin);
371 XFreeCursor(dpy, cursor[CurNormal]);
372 XFreeCursor(dpy, cursor[CurResize]);
373 XFreeCursor(dpy, cursor[CurMove]);
374 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
386 nrules = sizeof rules / sizeof rules[0];
387 regs = emallocz(nrules * sizeof(Regs));
388 for(i = 0; i < nrules; i++) {
390 reg = emallocz(sizeof(regex_t));
391 if(regcomp(reg, rules[i].prop, REG_EXTENDED))
394 regs[i].propregex = reg;
397 reg = emallocz(sizeof(regex_t));
398 if(regcomp(reg, rules[i].tags, REG_EXTENDED))
401 regs[i].tagregex = reg;
407 configure(Client *c) {
410 ce.type = ConfigureNotify;
418 ce.border_width = c->border;
420 ce.override_redirect = False;
421 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
425 configurenotify(XEvent *e) {
426 XConfigureEvent *ev = &e->xconfigure;
428 if (ev->window == root && (ev->width != sw || ev->height != sh)) {
431 XFreePixmap(dpy, dc.drawable);
432 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
433 XResizeWindow(dpy, barwin, sw, bh);
440 configurerequest(XEvent *e) {
442 XConfigureRequestEvent *ev = &e->xconfigurerequest;
445 if((c = getclient(ev->window))) {
447 if(ev->value_mask & CWBorderWidth)
448 c->border = ev->border_width;
449 if(c->isfixed || c->isfloating || isfloating()) {
450 if(ev->value_mask & CWX)
452 if(ev->value_mask & CWY)
454 if(ev->value_mask & CWWidth)
456 if(ev->value_mask & CWHeight)
458 if((c->x + c->w) > sw && c->isfloating)
459 c->x = sw / 2 - c->w / 2; /* center in x direction */
460 if((c->y + c->h) > sh && c->isfloating)
461 c->y = sh / 2 - c->h / 2; /* center in y direction */
462 if((ev->value_mask & (CWX | CWY))
463 && !(ev->value_mask & (CWWidth | CWHeight)))
466 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
474 wc.width = ev->width;
475 wc.height = ev->height;
476 wc.border_width = ev->border_width;
477 wc.sibling = ev->above;
478 wc.stack_mode = ev->detail;
479 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
485 destroynotify(XEvent *e) {
487 XDestroyWindowEvent *ev = &e->xdestroywindow;
489 if((c = getclient(ev->window)))
496 c->prev->next = c->next;
498 c->next->prev = c->prev;
501 c->next = c->prev = NULL;
505 detachstack(Client *c) {
508 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
517 for(i = 0; i < ntags; i++) {
518 dc.w = textw(tags[i]);
520 drawtext(tags[i], dc.sel);
521 drawsquare(sel && sel->tags[i], isoccupied(i), dc.sel);
524 drawtext(tags[i], dc.norm);
525 drawsquare(sel && sel->tags[i], isoccupied(i), dc.norm);
530 drawtext(layouts[ltidx].symbol, dc.norm);
538 drawtext(stext, dc.norm);
539 if((dc.w = dc.x - x) > bh) {
542 drawtext(sel->name, dc.sel);
543 drawsquare(sel->ismax, sel->isfloating, dc.sel);
546 drawtext(NULL, dc.norm);
548 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, sw, bh, 0, 0);
553 drawsquare(Bool filled, Bool empty, unsigned long col[ColLast]) {
556 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
558 gcv.foreground = col[ColFG];
559 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
560 x = (dc.font.ascent + dc.font.descent + 2) / 4;
564 r.width = r.height = x + 1;
565 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
568 r.width = r.height = x;
569 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
574 drawtext(const char *text, unsigned long col[ColLast]) {
576 static char buf[256];
577 unsigned int len, olen;
578 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
580 XSetForeground(dpy, dc.gc, col[ColBG]);
581 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
585 olen = len = strlen(text);
586 if(len >= sizeof buf)
587 len = sizeof buf - 1;
588 memcpy(buf, text, len);
590 h = dc.font.ascent + dc.font.descent;
591 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
593 /* shorten text if necessary */
594 while(len && (w = textnw(buf, len)) > dc.w - h)
605 return; /* too long */
606 XSetForeground(dpy, dc.gc, col[ColFG]);
608 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
610 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
614 emallocz(unsigned int size) {
615 void *res = calloc(1, size);
618 eprint("fatal: could not malloc() %u bytes\n", size);
623 enternotify(XEvent *e) {
625 XCrossingEvent *ev = &e->xcrossing;
627 if(ev->mode != NotifyNormal || ev->detail == NotifyInferior)
629 if((c = getclient(ev->window)))
631 else if(ev->window == root) {
638 eprint(const char *errstr, ...) {
641 va_start(ap, errstr);
642 vfprintf(stderr, errstr, ap);
649 XExposeEvent *ev = &e->xexpose;
652 if(barwin == ev->window)
658 floating(void) { /* default floating layout */
661 for(c = clients; c; c = c->next)
663 resize(c, c->x, c->y, c->w, c->h, True);
668 if((!c && selscreen) || (c && !isvisible(c)))
669 for(c = stack; c && !isvisible(c); c = c->snext);
670 if(sel && sel != c) {
671 grabbuttons(sel, False);
672 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
677 grabbuttons(c, True);
684 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
685 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
688 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
692 focusnext(const char *arg) {
697 for(c = sel->next; c && !isvisible(c); c = c->next);
699 for(c = clients; c && !isvisible(c); c = c->next);
707 focusprev(const char *arg) {
712 for(c = sel->prev; c && !isvisible(c); c = c->prev);
714 for(c = clients; c && c->next; c = c->next);
715 for(; c && !isvisible(c); c = c->prev);
724 getclient(Window w) {
727 for(c = clients; c && c->win != w; c = c->next);
735 unsigned char *p = NULL;
736 unsigned long n, extra;
739 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
740 &real, &format, &n, &extra, (unsigned char **)&p);
741 if(status != Success)
750 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
755 if(!text || size == 0)
758 XGetTextProperty(dpy, w, &name, atom);
761 if(name.encoding == XA_STRING)
762 strncpy(text, (char *)name.value, size - 1);
764 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
767 strncpy(text, *list, size - 1);
768 XFreeStringList(list);
771 text[size - 1] = '\0';
777 grabbuttons(Client *c, Bool focused) {
778 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
781 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
782 GrabModeAsync, GrabModeSync, None, None);
783 XGrabButton(dpy, Button1, MODKEY | LockMask, c->win, False, BUTTONMASK,
784 GrabModeAsync, GrabModeSync, None, None);
785 XGrabButton(dpy, Button1, MODKEY | numlockmask, c->win, False, BUTTONMASK,
786 GrabModeAsync, GrabModeSync, None, None);
787 XGrabButton(dpy, Button1, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
788 GrabModeAsync, GrabModeSync, None, None);
790 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
791 GrabModeAsync, GrabModeSync, None, None);
792 XGrabButton(dpy, Button2, MODKEY | LockMask, c->win, False, BUTTONMASK,
793 GrabModeAsync, GrabModeSync, None, None);
794 XGrabButton(dpy, Button2, MODKEY | numlockmask, c->win, False, BUTTONMASK,
795 GrabModeAsync, GrabModeSync, None, None);
796 XGrabButton(dpy, Button2, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
797 GrabModeAsync, GrabModeSync, None, None);
799 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
800 GrabModeAsync, GrabModeSync, None, None);
801 XGrabButton(dpy, Button3, MODKEY | LockMask, c->win, False, BUTTONMASK,
802 GrabModeAsync, GrabModeSync, None, None);
803 XGrabButton(dpy, Button3, MODKEY | numlockmask, c->win, False, BUTTONMASK,
804 GrabModeAsync, GrabModeSync, None, None);
805 XGrabButton(dpy, Button3, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
806 GrabModeAsync, GrabModeSync, None, None);
809 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
810 GrabModeAsync, GrabModeSync, None, None);
814 idxoftag(const char *tag) {
817 for(i = 0; i < ntags; i++)
825 XSetWindowAttributes wa;
827 wa.override_redirect = 1;
828 wa.background_pixmap = ParentRelative;
829 wa.event_mask = ButtonPressMask | ExposureMask;
830 barwin = XCreateWindow(dpy, root, sx, sy, sw, bh, 0,
831 DefaultDepth(dpy, screen), CopyFromParent, DefaultVisual(dpy, screen),
832 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
833 XDefineCursor(dpy, barwin, cursor[CurNormal]);
835 XMapRaised(dpy, barwin);
836 strcpy(stext, "dwm-"VERSION);
837 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
838 dc.gc = XCreateGC(dpy, root, 0, 0);
839 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
841 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
845 initcolor(const char *colstr) {
846 Colormap cmap = DefaultColormap(dpy, screen);
849 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
850 eprint("error, cannot allocate color '%s'\n", colstr);
855 initfont(const char *fontstr) {
856 char *def, **missing;
861 XFreeFontSet(dpy, dc.font.set);
862 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
865 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
866 XFreeStringList(missing);
869 XFontSetExtents *font_extents;
870 XFontStruct **xfonts;
872 dc.font.ascent = dc.font.descent = 0;
873 font_extents = XExtentsOfFontSet(dc.font.set);
874 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
875 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
876 if(dc.font.ascent < (*xfonts)->ascent)
877 dc.font.ascent = (*xfonts)->ascent;
878 if(dc.font.descent < (*xfonts)->descent)
879 dc.font.descent = (*xfonts)->descent;
885 XFreeFont(dpy, dc.font.xfont);
886 dc.font.xfont = NULL;
887 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
888 || !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
889 eprint("error, cannot load font: '%s'\n", fontstr);
890 dc.font.ascent = dc.font.xfont->ascent;
891 dc.font.descent = dc.font.xfont->descent;
893 dc.font.height = dc.font.ascent + dc.font.descent;
900 nlayouts = sizeof layouts / sizeof layouts[0];
901 for(blw = i = 0; i < nlayouts; i++) {
902 w = textw(layouts[i].symbol);
910 dc.norm[ColBorder] = initcolor(NORMBORDERCOLOR);
911 dc.norm[ColBG] = initcolor(NORMBGCOLOR);
912 dc.norm[ColFG] = initcolor(NORMFGCOLOR);
913 dc.sel[ColBorder] = initcolor(SELBORDERCOLOR);
914 dc.sel[ColBG] = initcolor(SELBGCOLOR);
915 dc.sel[ColFG] = initcolor(SELFGCOLOR);
917 dc.h = bh = dc.font.height + 2;
921 isarrange(void (*func)())
923 return func == layouts[ltidx].arrange;
928 return layouts[ltidx].arrange == floating;
932 isoccupied(unsigned int t) {
935 for(c = clients; c; c = c->next)
942 isprotodel(Client *c) {
947 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
948 for(i = 0; !ret && i < n; i++)
949 if(protocols[i] == wmatom[WMDelete])
957 isvisible(Client *c) {
960 for(i = 0; i < ntags; i++)
961 if(c->tags[i] && seltags[i])
967 keypress(XEvent *e) {
969 unsigned int len = sizeof keys / sizeof keys[0];
975 if(!e) { /* grabkeys */
976 XUngrabKey(dpy, AnyKey, AnyModifier, root);
977 for(i = 0; i < len; i++) {
978 code = XKeysymToKeycode(dpy, keys[i].keysym);
979 XGrabKey(dpy, code, keys[i].mod, root, True,
980 GrabModeAsync, GrabModeAsync);
981 XGrabKey(dpy, code, keys[i].mod | LockMask, root, True,
982 GrabModeAsync, GrabModeAsync);
983 XGrabKey(dpy, code, keys[i].mod | numlockmask, root, True,
984 GrabModeAsync, GrabModeAsync);
985 XGrabKey(dpy, code, keys[i].mod | numlockmask | LockMask, root, True,
986 GrabModeAsync, GrabModeAsync);
991 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
992 for(i = 0; i < len; i++)
993 if(keysym == keys[i].keysym
994 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
997 keys[i].func(keys[i].arg);
1002 killclient(const char *arg) {
1007 if(isprotodel(sel)) {
1008 ev.type = ClientMessage;
1009 ev.xclient.window = sel->win;
1010 ev.xclient.message_type = wmatom[WMProtocols];
1011 ev.xclient.format = 32;
1012 ev.xclient.data.l[0] = wmatom[WMDelete];
1013 ev.xclient.data.l[1] = CurrentTime;
1014 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
1017 XKillClient(dpy, sel->win);
1021 leavenotify(XEvent *e) {
1022 XCrossingEvent *ev = &e->xcrossing;
1024 if((ev->window == root) && !ev->same_screen) {
1031 manage(Window w, XWindowAttributes *wa) {
1033 Client *c, *t = NULL;
1038 c = emallocz(sizeof(Client));
1039 c->tags = emallocz(ntags * sizeof(Bool));
1045 c->oldborder = wa->border_width;
1046 if(c->w == sw && c->h == sh) {
1049 c->border = wa->border_width;
1052 if(c->x + c->w + 2 * c->border > wax + waw)
1053 c->x = wax + waw - c->w - 2 * c->border;
1054 if(c->y + c->h + 2 * c->border > way + wah)
1055 c->y = way + wah - c->h - 2 * c->border;
1060 c->border = BORDERPX;
1062 wc.border_width = c->border;
1063 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1064 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1065 configure(c); /* propagates border_width, if size doesn't change */
1067 XSelectInput(dpy, w,
1068 StructureNotifyMask | PropertyChangeMask | EnterWindowMask);
1069 grabbuttons(c, False);
1071 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
1072 for(t = clients; t && t->win != trans; t = t->next);
1074 for(i = 0; i < ntags; i++)
1075 c->tags[i] = t->tags[i];
1078 c->isfloating = (rettrans == Success) || c->isfixed;
1081 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
1083 XMapWindow(dpy, c->win);
1084 setclientstate(c, NormalState);
1089 mappingnotify(XEvent *e) {
1090 XMappingEvent *ev = &e->xmapping;
1092 XRefreshKeyboardMapping(ev);
1093 if(ev->request == MappingKeyboard)
1098 maprequest(XEvent *e) {
1099 static XWindowAttributes wa;
1100 XMapRequestEvent *ev = &e->xmaprequest;
1102 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1104 if(wa.override_redirect)
1106 if(!getclient(ev->window))
1107 manage(ev->window, &wa);
1111 movemouse(Client *c) {
1112 int x1, y1, ocx, ocy, di, nx, ny;
1119 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1120 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1123 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1125 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask, &ev);
1128 XUngrabPointer(dpy, CurrentTime);
1130 case ConfigureRequest:
1133 handler[ev.type](&ev);
1137 nx = ocx + (ev.xmotion.x - x1);
1138 ny = ocy + (ev.xmotion.y - y1);
1139 if(abs(wax + nx) < SNAP)
1141 else if(abs((wax + waw) - (nx + c->w + 2 * c->border)) < SNAP)
1142 nx = wax + waw - c->w - 2 * c->border;
1143 if(abs(way - ny) < SNAP)
1145 else if(abs((way + wah) - (ny + c->h + 2 * c->border)) < SNAP)
1146 ny = way + wah - c->h - 2 * c->border;
1147 resize(c, nx, ny, c->w, c->h, False);
1154 nexttiled(Client *c) {
1155 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1160 propertynotify(XEvent *e) {
1163 XPropertyEvent *ev = &e->xproperty;
1165 if(ev->state == PropertyDelete)
1166 return; /* ignore */
1167 if((c = getclient(ev->window))) {
1170 case XA_WM_TRANSIENT_FOR:
1171 XGetTransientForHint(dpy, c->win, &trans);
1172 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1175 case XA_WM_NORMAL_HINTS:
1179 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1188 quit(const char *arg) {
1189 readin = running = False;
1193 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1194 double dx, dy, max, min, ratio;
1198 if(c->minay > 0 && c->maxay > 0 && (h - c->baseh) > 0 && (w - c->basew) > 0) {
1199 dx = (double)(w - c->basew);
1200 dy = (double)(h - c->baseh);
1201 min = (double)(c->minax) / (double)(c->minay);
1202 max = (double)(c->maxax) / (double)(c->maxay);
1204 if(max > 0 && min > 0 && ratio > 0) {
1206 dy = (dx * min + dy) / (min * min + 1);
1208 w = (int)dx + c->basew;
1209 h = (int)dy + c->baseh;
1211 else if(ratio > max) {
1212 dy = (dx * min + dy) / (max * max + 1);
1214 w = (int)dx + c->basew;
1215 h = (int)dy + c->baseh;
1219 if(c->minw && w < c->minw)
1221 if(c->minh && h < c->minh)
1223 if(c->maxw && w > c->maxw)
1225 if(c->maxh && h > c->maxh)
1228 w -= (w - c->basew) % c->incw;
1230 h -= (h - c->baseh) % c->inch;
1232 if(w <= 0 || h <= 0)
1234 /* offscreen appearance fixes */
1236 x = sw - w - 2 * c->border;
1238 y = sh - h - 2 * c->border;
1239 if(x + w + 2 * c->border < sx)
1241 if(y + h + 2 * c->border < sy)
1243 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1246 c->w = wc.width = w;
1247 c->h = wc.height = h;
1248 wc.border_width = c->border;
1249 XConfigureWindow(dpy, c->win, CWX | CWY | CWWidth | CWHeight | CWBorderWidth, &wc);
1256 resizemouse(Client *c) {
1263 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1264 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1267 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
1269 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask , &ev);
1272 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1273 c->w + c->border - 1, c->h + c->border - 1);
1274 XUngrabPointer(dpy, CurrentTime);
1275 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1277 case ConfigureRequest:
1280 handler[ev.type](&ev);
1284 if((nw = ev.xmotion.x - ocx - 2 * c->border + 1) <= 0)
1286 if((nh = ev.xmotion.y - ocy - 2 * c->border + 1) <= 0)
1288 resize(c, c->x, c->y, nw, nh, True);
1303 if(sel->isfloating || isfloating())
1304 XRaiseWindow(dpy, sel->win);
1306 wc.stack_mode = Below;
1307 wc.sibling = barwin;
1308 if(!sel->isfloating) {
1309 XConfigureWindow(dpy, sel->win, CWSibling | CWStackMode, &wc);
1310 wc.sibling = sel->win;
1312 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
1315 XConfigureWindow(dpy, c->win, CWSibling | CWStackMode, &wc);
1316 wc.sibling = c->win;
1320 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1325 unsigned int i, num;
1326 Window *wins, d1, d2;
1327 XWindowAttributes wa;
1330 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1331 for(i = 0; i < num; i++) {
1332 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1333 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1335 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1336 manage(wins[i], &wa);
1338 for(i = 0; i < num; i++) { /* now the transients */
1339 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1341 if(XGetTransientForHint(dpy, wins[i], &d1)
1342 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1343 manage(wins[i], &wa);
1351 setclientstate(Client *c, long state) {
1352 long data[] = {state, None};
1354 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1355 PropModeReplace, (unsigned char *)data, 2);
1359 setlayout(const char *arg) {
1363 if(++ltidx == nlayouts)
1367 for(i = 0; i < nlayouts; i++)
1368 if(!strcmp(arg, layouts[i].symbol))
1381 setmwfact(const char *arg) {
1384 if(!isarrange(tile))
1386 /* arg handling, manipulate mwfact */
1389 else if(1 == sscanf(arg, "%lf", &delta)) {
1390 if(arg[0] != '+' && arg[0] != '-')
1396 else if(mwfact > 0.9)
1407 XModifierKeymap *modmap;
1408 XSetWindowAttributes wa;
1411 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1412 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1413 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1414 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1415 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1416 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1417 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1418 PropModeReplace, (unsigned char *) netatom, NetLast);
1420 cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1421 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1422 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1423 /* init modifier map */
1424 modmap = XGetModifierMapping(dpy);
1425 for (i = 0; i < 8; i++)
1426 for (j = 0; j < modmap->max_keypermod; j++) {
1427 if(modmap->modifiermap[i * modmap->max_keypermod + j]
1428 == XKeysymToKeycode(dpy, XK_Num_Lock))
1429 numlockmask = (1 << i);
1431 XFreeModifiermap(modmap);
1432 /* select for events */
1433 wa.event_mask = SubstructureRedirectMask | SubstructureNotifyMask
1434 | EnterWindowMask | LeaveWindowMask | StructureNotifyMask;
1435 wa.cursor = cursor[CurNormal];
1436 XChangeWindowAttributes(dpy, root, CWEventMask | CWCursor, &wa);
1437 XSelectInput(dpy, root, wa.event_mask);
1438 keypress(NULL); /* grabkeys */
1440 for(ntags = 0; tags[ntags]; ntags++);
1441 seltags = emallocz(sizeof(Bool) * ntags);
1445 sw = DisplayWidth(dpy, screen);
1446 sh = DisplayHeight(dpy, screen);
1450 /* multihead support */
1451 selscreen = XQueryPointer(dpy, root, &w, &w, &i, &i, &i, &i, &mask);
1455 spawn(const char *arg) {
1456 static char *shell = NULL;
1458 if(!shell && !(shell = getenv("SHELL")))
1462 /* The double-fork construct avoids zombie processes and keeps the code
1463 * clean from stupid signal handlers. */
1467 close(ConnectionNumber(dpy));
1469 execl(shell, shell, "-c", arg, (char *)NULL);
1470 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1479 tag(const char *arg) {
1484 for(i = 0; i < ntags; i++)
1485 sel->tags[i] = arg == NULL;
1487 if(i >= 0 && i < ntags)
1488 sel->tags[i] = True;
1493 textnw(const char *text, unsigned int len) {
1497 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1500 return XTextWidth(dc.font.xfont, text, len);
1504 textw(const char *text) {
1505 return textnw(text, strlen(text)) + dc.font.height;
1510 unsigned int i, n, nx, ny, nw, nh, mw, th;
1513 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next))
1517 mw = (n == 1) ? waw : mwfact * waw;
1518 th = (n > 1) ? wah / (n - 1) : 0;
1519 if(n > 1 && th < bh)
1524 for(i = 0, c = nexttiled(clients); c; c = nexttiled(c->next), i++) {
1526 if(i == 0) { /* master */
1527 nw = mw - 2 * c->border;
1528 nh = wah - 2 * c->border;
1530 else { /* tile window */
1535 nw = waw - mw - 2 * c->border;
1536 if(i + 1 == n) /* remainder */
1537 nh = (way + wah) - ny - 2 * c->border;
1539 nh = th - 2 * c->border;
1541 resize(c, nx, ny, nw, nh, RESIZEHINTS);
1542 if(n > 1 && th != wah)
1543 ny += nh + 2 * c->border;
1548 togglebar(const char *arg) {
1550 bpos = (BARPOS == BarOff) ? BarTop : BARPOS;
1558 togglefloating(const char *arg) {
1561 sel->isfloating = !sel->isfloating;
1563 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1568 togglemax(const char *arg) {
1571 if(!sel || (!isfloating() && !sel->isfloating) || sel->isfixed)
1573 if((sel->ismax = !sel->ismax)) {
1578 resize(sel, wax, way, waw - 2 * sel->border, wah - 2 * sel->border, True);
1581 resize(sel, sel->rx, sel->ry, sel->rw, sel->rh, True);
1583 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1587 toggletag(const char *arg) {
1593 sel->tags[i] = !sel->tags[i];
1594 for(j = 0; j < ntags && !sel->tags[j]; j++);
1596 sel->tags[i] = True;
1601 toggleview(const char *arg) {
1605 seltags[i] = !seltags[i];
1606 for(j = 0; j < ntags && !seltags[j]; j++);
1608 seltags[i] = True; /* cannot toggle last view */
1616 XMoveWindow(dpy, c->win, c->x, c->y);
1617 c->isbanned = False;
1621 unmanage(Client *c) {
1624 wc.border_width = c->oldborder;
1625 /* The server grab construct avoids race conditions. */
1627 XSetErrorHandler(xerrordummy);
1628 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1633 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1634 setclientstate(c, WithdrawnState);
1638 XSetErrorHandler(xerror);
1644 unmapnotify(XEvent *e) {
1646 XUnmapEvent *ev = &e->xunmap;
1648 if((c = getclient(ev->window)))
1653 updatebarpos(void) {
1664 XMoveWindow(dpy, barwin, sx, sy);
1668 XMoveWindow(dpy, barwin, sx, sy + wah);
1671 XMoveWindow(dpy, barwin, sx, sy - bh);
1675 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1679 updatesizehints(Client *c) {
1683 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1685 c->flags = size.flags;
1686 if(c->flags & PBaseSize) {
1687 c->basew = size.base_width;
1688 c->baseh = size.base_height;
1690 else if(c->flags & PMinSize) {
1691 c->basew = size.min_width;
1692 c->baseh = size.min_height;
1695 c->basew = c->baseh = 0;
1696 if(c->flags & PResizeInc) {
1697 c->incw = size.width_inc;
1698 c->inch = size.height_inc;
1701 c->incw = c->inch = 0;
1702 if(c->flags & PMaxSize) {
1703 c->maxw = size.max_width;
1704 c->maxh = size.max_height;
1707 c->maxw = c->maxh = 0;
1708 if(c->flags & PMinSize) {
1709 c->minw = size.min_width;
1710 c->minh = size.min_height;
1712 else if(c->flags & PBaseSize) {
1713 c->minw = size.base_width;
1714 c->minh = size.base_height;
1717 c->minw = c->minh = 0;
1718 if(c->flags & PAspect) {
1719 c->minax = size.min_aspect.x;
1720 c->maxax = size.max_aspect.x;
1721 c->minay = size.min_aspect.y;
1722 c->maxay = size.max_aspect.y;
1725 c->minax = c->maxax = c->minay = c->maxay = 0;
1726 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1727 && c->maxw == c->minw && c->maxh == c->minh);
1731 updatetitle(Client *c) {
1732 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1733 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1736 /* There's no way to check accesses to destroyed windows, thus those cases are
1737 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1738 * default error handler, which may call exit. */
1740 xerror(Display *dpy, XErrorEvent *ee) {
1741 if(ee->error_code == BadWindow
1742 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1743 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1744 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1745 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1746 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1747 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1748 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1750 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1751 ee->request_code, ee->error_code);
1752 return xerrorxlib(dpy, ee); /* may call exit */
1756 xerrordummy(Display *dsply, XErrorEvent *ee) {
1760 /* Startup Error handler to check if another window manager
1761 * is already running. */
1763 xerrorstart(Display *dsply, XErrorEvent *ee) {
1769 view(const char *arg) {
1772 for(i = 0; i < ntags; i++)
1773 seltags[i] = arg == NULL;
1775 if(i >= 0 && i < ntags)
1781 zoom(const char *arg) {
1784 if(!sel || !isarrange(tile) || sel->isfloating)
1786 if((c = sel) == nexttiled(clients))
1787 if(!(c = nexttiled(c->next)))
1796 main(int argc, char *argv[]) {
1802 if(argc == 2 && !strcmp("-v", argv[1]))
1803 eprint("dwm-"VERSION", © 2006-2007 A. R. Garbe, S. van Dijk, J. Salmi, P. Hruby, S. Nagy\n");
1805 eprint("usage: dwm [-v]\n");
1807 /* macros from config.h can be used at function level only */
1811 setlocale(LC_CTYPE, "");
1812 if(!(dpy = XOpenDisplay(0)))
1813 eprint("dwm: cannot open display\n");
1814 xfd = ConnectionNumber(dpy);
1815 screen = DefaultScreen(dpy);
1816 root = RootWindow(dpy, screen);
1818 XSetErrorHandler(xerrorstart);
1819 /* this causes an error if some other window manager is running */
1820 XSelectInput(dpy, root, SubstructureRedirectMask);
1823 eprint("dwm: another window manager is already running\n");
1826 XSetErrorHandler(NULL);
1827 xerrorxlib = XSetErrorHandler(xerror);
1833 /* main event loop, also reads status text from stdin */
1839 FD_SET(STDIN_FILENO, &rd);
1841 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1844 eprint("select failed\n");
1846 if(FD_ISSET(STDIN_FILENO, &rd)) {
1847 switch(r = read(STDIN_FILENO, stext, sizeof stext - 1)) {
1849 strncpy(stext, strerror(errno), sizeof stext - 1);
1850 stext[sizeof stext - 1] = '\0';
1854 strncpy(stext, "EOF", 4);
1858 for(stext[r] = '\0', p = stext + strlen(stext) - 1; p >= stext && *p == '\n'; *p-- = '\0');
1859 for(; p >= stext && *p != '\n'; --p);
1861 strncpy(stext, p + 1, sizeof stext);
1865 while(XPending(dpy)) {
1866 XNextEvent(dpy, &ev);
1867 if(handler[ev.type])
1868 (handler[ev.type])(&ev); /* call handler */