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().
37 #include <sys/select.h>
38 #include <sys/types.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 */
61 unsigned long norm[ColLast];
62 unsigned long sel[ColLast];
72 } DC; /* draw context */
77 void (*func)(const char *arg);
83 void (*arrange)(void);
97 /* forward declarations */
98 void applyrules(Client *c);
100 void attach(Client *c);
101 void attachstack(Client *c);
103 void buttonpress(XEvent *e);
104 void checkotherwm(void);
106 void compileregs(void);
107 void configure(Client *c);
108 void configurenotify(XEvent *e);
109 void configurerequest(XEvent *e);
110 void destroynotify(XEvent *e);
111 void detach(Client *c);
112 void detachstack(Client *c);
114 void drawsquare(Bool filled, Bool empty, unsigned long col[ColLast]);
115 void drawtext(const char *text, unsigned long col[ColLast]);
116 void *emallocz(unsigned int size);
117 void enternotify(XEvent *e);
118 void eprint(const char *errstr, ...);
119 void expose(XEvent *e);
120 void floating(void); /* default floating layout */
121 void focus(Client *c);
122 void focusnext(const char *arg);
123 void focusprev(const char *arg);
124 Client *getclient(Window w);
125 unsigned long getcolor(const char *colstr);
126 long getstate(Window w);
127 Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
128 void grabbuttons(Client *c, Bool focused);
129 unsigned int idxoftag(const char *tag);
130 void initfont(const char *fontstr);
131 Bool isarrange(void (*func)());
132 Bool isoccupied(unsigned int t);
133 Bool isprotodel(Client *c);
134 Bool isvisible(Client *c);
135 void keypress(XEvent *e);
136 void killclient(const char *arg);
137 void leavenotify(XEvent *e);
138 void manage(Window w, XWindowAttributes *wa);
139 void mappingnotify(XEvent *e);
140 void maprequest(XEvent *e);
141 void movemouse(Client *c);
142 Client *nexttiled(Client *c);
143 void propertynotify(XEvent *e);
144 void quit(const char *arg);
145 void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
146 void resizemouse(Client *c);
150 void setclientstate(Client *c, long state);
151 void setlayout(const char *arg);
152 void setmwfact(const char *arg);
154 void spawn(const char *arg);
155 void tag(const char *arg);
156 unsigned int textnw(const char *text, unsigned int len);
157 unsigned int textw(const char *text);
159 void togglebar(const char *arg);
160 void togglefloating(const char *arg);
161 void togglemax(const char *arg);
162 void toggletag(const char *arg);
163 void toggleview(const char *arg);
164 void unban(Client *c);
165 void unmanage(Client *c);
166 void unmapnotify(XEvent *e);
167 void updatebarpos(void);
168 void updatesizehints(Client *c);
169 void updatetitle(Client *c);
170 void view(const char *arg);
171 void viewprevtag(const char *arg); /* views previous selected tags */
172 int xerror(Display *dpy, XErrorEvent *ee);
173 int xerrordummy(Display *dsply, XErrorEvent *ee);
174 int xerrorstart(Display *dsply, XErrorEvent *ee);
175 void zoom(const char *arg);
180 int screen, sx, sy, sw, sh, wax, way, waw, wah;
181 int (*xerrorxlib)(Display *, XErrorEvent *);
182 unsigned int bh, bpos;
183 unsigned int blw = 0;
184 unsigned int ltidx = 0; /* default */
185 unsigned int nlayouts = 0;
186 unsigned int nrules = 0;
187 unsigned int numlockmask = 0;
188 void (*handler[LASTEvent]) (XEvent *) = {
189 [ButtonPress] = buttonpress,
190 [ConfigureRequest] = configurerequest,
191 [ConfigureNotify] = configurenotify,
192 [DestroyNotify] = destroynotify,
193 [EnterNotify] = enternotify,
194 [LeaveNotify] = leavenotify,
196 [KeyPress] = keypress,
197 [MappingNotify] = mappingnotify,
198 [MapRequest] = maprequest,
199 [PropertyNotify] = propertynotify,
200 [UnmapNotify] = unmapnotify
202 Atom wmatom[WMLast], netatom[NetLast];
203 Bool otherwm, readin;
205 Bool selscreen = True;
206 Client *clients = NULL;
208 Client *stack = NULL;
209 Cursor cursor[CurLast];
215 /* configuration, allows nested code to access above variables */
218 /* Statically define the number of tags. */
219 unsigned int ntags = sizeof tags / sizeof tags[0];
220 Bool seltags[sizeof tags / sizeof tags[0]] = {[0] = True};
221 Bool prevtags[sizeof tags / sizeof tags[0]] = {[0] = True};
225 applyrules(Client *c) {
226 static char buf[512];
229 Bool matched = False;
230 XClassHint ch = { 0 };
233 XGetClassHint(dpy, c->win, &ch);
234 snprintf(buf, sizeof buf, "%s:%s:%s",
235 ch.res_class ? ch.res_class : "",
236 ch.res_name ? ch.res_name : "", c->name);
237 for(i = 0; i < nrules; i++)
238 if(regs[i].propregex && !regexec(regs[i].propregex, buf, 1, &tmp, 0)) {
239 c->isfloating = rules[i].isfloating;
240 for(j = 0; regs[i].tagregex && j < ntags; j++) {
241 if(!regexec(regs[i].tagregex, tags[j], 1, &tmp, 0)) {
252 memcpy(c->tags, seltags, sizeof seltags);
259 for(c = clients; c; c = c->next)
264 layouts[ltidx].arrange();
278 attachstack(Client *c) {
287 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
292 buttonpress(XEvent *e) {
295 XButtonPressedEvent *ev = &e->xbutton;
297 if(barwin == ev->window) {
299 for(i = 0; i < ntags; i++) {
302 if(ev->button == Button1) {
303 if(ev->state & MODKEY)
308 else if(ev->button == Button3) {
309 if(ev->state & MODKEY)
317 if((ev->x < x + blw) && ev->button == Button1)
320 else if((c = getclient(ev->window))) {
322 if(CLEANMASK(ev->state) != MODKEY)
324 if(ev->button == Button1) {
325 if(isarrange(floating) || c->isfloating)
328 togglefloating(NULL);
331 else if(ev->button == Button2) {
332 if(ISTILE && !c->isfixed && c->isfloating)
333 togglefloating(NULL);
337 else if(ev->button == Button3 && !c->isfixed) {
338 if(isarrange(floating) || c->isfloating)
341 togglefloating(NULL);
350 XSetErrorHandler(xerrorstart);
352 /* this causes an error if some other window manager is running */
353 XSelectInput(dpy, root, SubstructureRedirectMask);
356 eprint("dwm: another window manager is already running\n");
358 XSetErrorHandler(NULL);
359 xerrorxlib = XSetErrorHandler(xerror);
371 XFreeFontSet(dpy, dc.font.set);
373 XFreeFont(dpy, dc.font.xfont);
374 XUngrabKey(dpy, AnyKey, AnyModifier, root);
375 XFreePixmap(dpy, dc.drawable);
377 XDestroyWindow(dpy, barwin);
378 XFreeCursor(dpy, cursor[CurNormal]);
379 XFreeCursor(dpy, cursor[CurResize]);
380 XFreeCursor(dpy, cursor[CurMove]);
381 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
392 nrules = sizeof rules / sizeof rules[0];
393 regs = emallocz(nrules * sizeof(Regs));
394 for(i = 0; i < nrules; i++) {
396 reg = emallocz(sizeof(regex_t));
397 if(regcomp(reg, rules[i].prop, REG_EXTENDED))
400 regs[i].propregex = reg;
403 reg = emallocz(sizeof(regex_t));
404 if(regcomp(reg, rules[i].tags, REG_EXTENDED))
407 regs[i].tagregex = reg;
413 configure(Client *c) {
416 ce.type = ConfigureNotify;
424 ce.border_width = c->border;
426 ce.override_redirect = False;
427 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
431 configurenotify(XEvent *e) {
432 XConfigureEvent *ev = &e->xconfigure;
434 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
437 XFreePixmap(dpy, dc.drawable);
438 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
439 XResizeWindow(dpy, barwin, sw, bh);
446 configurerequest(XEvent *e) {
448 XConfigureRequestEvent *ev = &e->xconfigurerequest;
451 if((c = getclient(ev->window))) {
453 if(ev->value_mask & CWBorderWidth)
454 c->border = ev->border_width;
455 if(c->isfixed || c->isfloating || isarrange(floating)) {
456 if(ev->value_mask & CWX)
458 if(ev->value_mask & CWY)
460 if(ev->value_mask & CWWidth)
462 if(ev->value_mask & CWHeight)
464 if((c->x + c->w) > sw && c->isfloating)
465 c->x = sw / 2 - c->w / 2; /* center in x direction */
466 if((c->y + c->h) > sh && c->isfloating)
467 c->y = sh / 2 - c->h / 2; /* center in y direction */
468 if((ev->value_mask & (CWX | CWY))
469 && !(ev->value_mask & (CWWidth | CWHeight)))
472 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
480 wc.width = ev->width;
481 wc.height = ev->height;
482 wc.border_width = ev->border_width;
483 wc.sibling = ev->above;
484 wc.stack_mode = ev->detail;
485 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
491 destroynotify(XEvent *e) {
493 XDestroyWindowEvent *ev = &e->xdestroywindow;
495 if((c = getclient(ev->window)))
502 c->prev->next = c->next;
504 c->next->prev = c->prev;
507 c->next = c->prev = NULL;
511 detachstack(Client *c) {
514 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
523 for(i = 0; i < ntags; i++) {
524 dc.w = textw(tags[i]);
526 drawtext(tags[i], dc.sel);
527 drawsquare(sel && sel->tags[i], isoccupied(i), dc.sel);
530 drawtext(tags[i], dc.norm);
531 drawsquare(sel && sel->tags[i], isoccupied(i), dc.norm);
536 drawtext(layouts[ltidx].symbol, dc.norm);
544 drawtext(stext, dc.norm);
545 if((dc.w = dc.x - x) > bh) {
548 drawtext(sel->name, dc.sel);
549 drawsquare(sel->ismax, sel->isfloating, dc.sel);
552 drawtext(NULL, dc.norm);
554 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, sw, bh, 0, 0);
559 drawsquare(Bool filled, Bool empty, unsigned long col[ColLast]) {
562 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
564 gcv.foreground = col[ColFG];
565 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
566 x = (dc.font.ascent + dc.font.descent + 2) / 4;
570 r.width = r.height = x + 1;
571 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
574 r.width = r.height = x;
575 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
580 drawtext(const char *text, unsigned long col[ColLast]) {
582 static char buf[256];
583 unsigned int len, olen;
584 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
586 XSetForeground(dpy, dc.gc, col[ColBG]);
587 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
591 olen = len = strlen(text);
592 if(len >= sizeof buf)
593 len = sizeof buf - 1;
594 memcpy(buf, text, len);
596 h = dc.font.ascent + dc.font.descent;
597 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
599 /* shorten text if necessary */
600 while(len && (w = textnw(buf, len)) > dc.w - h)
611 return; /* too long */
612 XSetForeground(dpy, dc.gc, col[ColFG]);
614 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
616 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
620 emallocz(unsigned int size) {
621 void *res = calloc(1, size);
624 eprint("fatal: could not malloc() %u bytes\n", size);
629 enternotify(XEvent *e) {
631 XCrossingEvent *ev = &e->xcrossing;
633 if(ev->mode != NotifyNormal || ev->detail == NotifyInferior)
635 if((c = getclient(ev->window)))
637 else if(ev->window == root) {
644 eprint(const char *errstr, ...) {
647 va_start(ap, errstr);
648 vfprintf(stderr, errstr, ap);
655 XExposeEvent *ev = &e->xexpose;
658 if(barwin == ev->window)
664 floating(void) { /* default floating layout */
667 for(c = clients; c; c = c->next)
669 resize(c, c->x, c->y, c->w, c->h, True);
674 if((!c && selscreen) || (c && !isvisible(c)))
675 for(c = stack; c && !isvisible(c); c = c->snext);
676 if(sel && sel != c) {
677 grabbuttons(sel, False);
678 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
683 grabbuttons(c, True);
690 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
691 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
694 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
698 focusnext(const char *arg) {
703 for(c = sel->next; c && !isvisible(c); c = c->next);
705 for(c = clients; c && !isvisible(c); c = c->next);
713 focusprev(const char *arg) {
718 for(c = sel->prev; c && !isvisible(c); c = c->prev);
720 for(c = clients; c && c->next; c = c->next);
721 for(; c && !isvisible(c); c = c->prev);
730 getclient(Window w) {
733 for(c = clients; c && c->win != w; c = c->next);
738 getcolor(const char *colstr) {
739 Colormap cmap = DefaultColormap(dpy, screen);
742 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
743 eprint("error, cannot allocate color '%s'\n", colstr);
751 unsigned char *p = NULL;
752 unsigned long n, extra;
755 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
756 &real, &format, &n, &extra, (unsigned char **)&p);
757 if(status != Success)
766 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
771 if(!text || size == 0)
774 XGetTextProperty(dpy, w, &name, atom);
777 if(name.encoding == XA_STRING)
778 strncpy(text, (char *)name.value, size - 1);
780 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
783 strncpy(text, *list, size - 1);
784 XFreeStringList(list);
787 text[size - 1] = '\0';
793 grabbuttons(Client *c, Bool focused) {
794 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
797 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
798 GrabModeAsync, GrabModeSync, None, None);
799 XGrabButton(dpy, Button1, MODKEY | LockMask, c->win, False, BUTTONMASK,
800 GrabModeAsync, GrabModeSync, None, None);
801 XGrabButton(dpy, Button1, MODKEY | numlockmask, c->win, False, BUTTONMASK,
802 GrabModeAsync, GrabModeSync, None, None);
803 XGrabButton(dpy, Button1, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
804 GrabModeAsync, GrabModeSync, None, None);
806 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
807 GrabModeAsync, GrabModeSync, None, None);
808 XGrabButton(dpy, Button2, MODKEY | LockMask, c->win, False, BUTTONMASK,
809 GrabModeAsync, GrabModeSync, None, None);
810 XGrabButton(dpy, Button2, MODKEY | numlockmask, c->win, False, BUTTONMASK,
811 GrabModeAsync, GrabModeSync, None, None);
812 XGrabButton(dpy, Button2, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
813 GrabModeAsync, GrabModeSync, None, None);
815 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
816 GrabModeAsync, GrabModeSync, None, None);
817 XGrabButton(dpy, Button3, MODKEY | LockMask, c->win, False, BUTTONMASK,
818 GrabModeAsync, GrabModeSync, None, None);
819 XGrabButton(dpy, Button3, MODKEY | numlockmask, c->win, False, BUTTONMASK,
820 GrabModeAsync, GrabModeSync, None, None);
821 XGrabButton(dpy, Button3, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
822 GrabModeAsync, GrabModeSync, None, None);
825 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
826 GrabModeAsync, GrabModeSync, None, None);
830 idxoftag(const char *tag) {
833 for(i = 0; i < ntags; i++)
840 initfont(const char *fontstr) {
841 char *def, **missing;
846 XFreeFontSet(dpy, dc.font.set);
847 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
850 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
851 XFreeStringList(missing);
854 XFontSetExtents *font_extents;
855 XFontStruct **xfonts;
857 dc.font.ascent = dc.font.descent = 0;
858 font_extents = XExtentsOfFontSet(dc.font.set);
859 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
860 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
861 if(dc.font.ascent < (*xfonts)->ascent)
862 dc.font.ascent = (*xfonts)->ascent;
863 if(dc.font.descent < (*xfonts)->descent)
864 dc.font.descent = (*xfonts)->descent;
870 XFreeFont(dpy, dc.font.xfont);
871 dc.font.xfont = NULL;
872 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
873 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
874 eprint("error, cannot load font: '%s'\n", fontstr);
875 dc.font.ascent = dc.font.xfont->ascent;
876 dc.font.descent = dc.font.xfont->descent;
878 dc.font.height = dc.font.ascent + dc.font.descent;
882 isarrange(void (*func)())
884 return func == layouts[ltidx].arrange;
888 isoccupied(unsigned int t) {
891 for(c = clients; c; c = c->next)
898 isprotodel(Client *c) {
903 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
904 for(i = 0; !ret && i < n; i++)
905 if(protocols[i] == wmatom[WMDelete])
913 isvisible(Client *c) {
916 for(i = 0; i < ntags; i++)
917 if(c->tags[i] && seltags[i])
923 keypress(XEvent *e) {
925 unsigned int len = sizeof keys / sizeof keys[0];
931 if(!e) { /* grabkeys */
932 XUngrabKey(dpy, AnyKey, AnyModifier, root);
933 for(i = 0; i < len; i++) {
934 code = XKeysymToKeycode(dpy, keys[i].keysym);
935 XGrabKey(dpy, code, keys[i].mod, root, True,
936 GrabModeAsync, GrabModeAsync);
937 XGrabKey(dpy, code, keys[i].mod | LockMask, root, True,
938 GrabModeAsync, GrabModeAsync);
939 XGrabKey(dpy, code, keys[i].mod | numlockmask, root, True,
940 GrabModeAsync, GrabModeAsync);
941 XGrabKey(dpy, code, keys[i].mod | numlockmask | LockMask, root, True,
942 GrabModeAsync, GrabModeAsync);
947 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
948 for(i = 0; i < len; i++)
949 if(keysym == keys[i].keysym
950 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
953 keys[i].func(keys[i].arg);
958 killclient(const char *arg) {
963 if(isprotodel(sel)) {
964 ev.type = ClientMessage;
965 ev.xclient.window = sel->win;
966 ev.xclient.message_type = wmatom[WMProtocols];
967 ev.xclient.format = 32;
968 ev.xclient.data.l[0] = wmatom[WMDelete];
969 ev.xclient.data.l[1] = CurrentTime;
970 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
973 XKillClient(dpy, sel->win);
977 leavenotify(XEvent *e) {
978 XCrossingEvent *ev = &e->xcrossing;
980 if((ev->window == root) && !ev->same_screen) {
987 manage(Window w, XWindowAttributes *wa) {
988 Client *c, *t = NULL;
993 c = emallocz(sizeof(Client));
994 c->tags = emallocz(sizeof seltags);
1000 c->oldborder = wa->border_width;
1001 if(c->w == sw && c->h == sh) {
1004 c->border = wa->border_width;
1007 if(c->x + c->w + 2 * c->border > wax + waw)
1008 c->x = wax + waw - c->w - 2 * c->border;
1009 if(c->y + c->h + 2 * c->border > way + wah)
1010 c->y = way + wah - c->h - 2 * c->border;
1015 c->border = BORDERPX;
1017 wc.border_width = c->border;
1018 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1019 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1020 configure(c); /* propagates border_width, if size doesn't change */
1022 XSelectInput(dpy, w,
1023 StructureNotifyMask | PropertyChangeMask | EnterWindowMask);
1024 grabbuttons(c, False);
1026 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
1027 for(t = clients; t && t->win != trans; t = t->next);
1029 memcpy(c->tags, t->tags, sizeof seltags);
1032 c->isfloating = (rettrans == Success) || c->isfixed;
1035 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
1037 XMapWindow(dpy, c->win);
1038 setclientstate(c, NormalState);
1043 mappingnotify(XEvent *e) {
1044 XMappingEvent *ev = &e->xmapping;
1046 XRefreshKeyboardMapping(ev);
1047 if(ev->request == MappingKeyboard)
1052 maprequest(XEvent *e) {
1053 static XWindowAttributes wa;
1054 XMapRequestEvent *ev = &e->xmaprequest;
1056 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1058 if(wa.override_redirect)
1060 if(!getclient(ev->window))
1061 manage(ev->window, &wa);
1065 movemouse(Client *c) {
1066 int x1, y1, ocx, ocy, di, nx, ny;
1073 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1074 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1077 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1079 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask, &ev);
1082 XUngrabPointer(dpy, CurrentTime);
1084 case ConfigureRequest:
1087 handler[ev.type](&ev);
1091 nx = ocx + (ev.xmotion.x - x1);
1092 ny = ocy + (ev.xmotion.y - y1);
1093 if(abs(wax + nx) < SNAP)
1095 else if(abs((wax + waw) - (nx + c->w + 2 * c->border)) < SNAP)
1096 nx = wax + waw - c->w - 2 * c->border;
1097 if(abs(way - ny) < SNAP)
1099 else if(abs((way + wah) - (ny + c->h + 2 * c->border)) < SNAP)
1100 ny = way + wah - c->h - 2 * c->border;
1101 resize(c, nx, ny, c->w, c->h, False);
1108 nexttiled(Client *c) {
1109 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1114 propertynotify(XEvent *e) {
1117 XPropertyEvent *ev = &e->xproperty;
1119 if(ev->state == PropertyDelete)
1120 return; /* ignore */
1121 if((c = getclient(ev->window))) {
1124 case XA_WM_TRANSIENT_FOR:
1125 XGetTransientForHint(dpy, c->win, &trans);
1126 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1129 case XA_WM_NORMAL_HINTS:
1133 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1142 quit(const char *arg) {
1143 readin = running = False;
1147 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1148 double dx, dy, max, min, ratio;
1152 if(c->minay > 0 && c->maxay > 0 && (h - c->baseh) > 0 && (w - c->basew) > 0) {
1153 dx = (double)(w - c->basew);
1154 dy = (double)(h - c->baseh);
1155 min = (double)(c->minax) / (double)(c->minay);
1156 max = (double)(c->maxax) / (double)(c->maxay);
1158 if(max > 0 && min > 0 && ratio > 0) {
1160 dy = (dx * min + dy) / (min * min + 1);
1162 w = (int)dx + c->basew;
1163 h = (int)dy + c->baseh;
1165 else if(ratio > max) {
1166 dy = (dx * min + dy) / (max * max + 1);
1168 w = (int)dx + c->basew;
1169 h = (int)dy + c->baseh;
1173 if(c->minw && w < c->minw)
1175 if(c->minh && h < c->minh)
1177 if(c->maxw && w > c->maxw)
1179 if(c->maxh && h > c->maxh)
1182 w -= (w - c->basew) % c->incw;
1184 h -= (h - c->baseh) % c->inch;
1186 if(w <= 0 || h <= 0)
1188 /* offscreen appearance fixes */
1190 x = sw - w - 2 * c->border;
1192 y = sh - h - 2 * c->border;
1193 if(x + w + 2 * c->border < sx)
1195 if(y + h + 2 * c->border < sy)
1197 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1200 c->w = wc.width = w;
1201 c->h = wc.height = h;
1202 wc.border_width = c->border;
1203 XConfigureWindow(dpy, c->win, CWX | CWY | CWWidth | CWHeight | CWBorderWidth, &wc);
1210 resizemouse(Client *c) {
1217 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1218 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1221 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
1223 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask , &ev);
1226 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1227 c->w + c->border - 1, c->h + c->border - 1);
1228 XUngrabPointer(dpy, CurrentTime);
1229 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1231 case ConfigureRequest:
1234 handler[ev.type](&ev);
1238 if((nw = ev.xmotion.x - ocx - 2 * c->border + 1) <= 0)
1240 if((nh = ev.xmotion.y - ocy - 2 * c->border + 1) <= 0)
1242 resize(c, c->x, c->y, nw, nh, True);
1257 if(sel->isfloating || isarrange(floating))
1258 XRaiseWindow(dpy, sel->win);
1259 if(!isarrange(floating)) {
1260 wc.stack_mode = Below;
1261 wc.sibling = barwin;
1262 if(!sel->isfloating) {
1263 XConfigureWindow(dpy, sel->win, CWSibling | CWStackMode, &wc);
1264 wc.sibling = sel->win;
1266 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
1269 XConfigureWindow(dpy, c->win, CWSibling | CWStackMode, &wc);
1270 wc.sibling = c->win;
1274 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1284 /* main event loop, also reads status text from stdin */
1286 xfd = ConnectionNumber(dpy);
1291 FD_SET(STDIN_FILENO, &rd);
1293 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1296 eprint("select failed\n");
1298 if(FD_ISSET(STDIN_FILENO, &rd)) {
1299 switch(r = read(STDIN_FILENO, stext, sizeof stext - 1)) {
1301 strncpy(stext, strerror(errno), sizeof stext - 1);
1302 stext[sizeof stext - 1] = '\0';
1306 strncpy(stext, "EOF", 4);
1310 for(stext[r] = '\0', p = stext + strlen(stext) - 1; p >= stext && *p == '\n'; *p-- = '\0');
1311 for(; p >= stext && *p != '\n'; --p);
1313 strncpy(stext, p + 1, sizeof stext);
1317 while(XPending(dpy)) {
1318 XNextEvent(dpy, &ev);
1319 if(handler[ev.type])
1320 (handler[ev.type])(&ev); /* call handler */
1327 unsigned int i, num;
1328 Window *wins, d1, d2;
1329 XWindowAttributes wa;
1332 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1333 for(i = 0; i < num; i++) {
1334 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1335 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1337 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1338 manage(wins[i], &wa);
1340 for(i = 0; i < num; i++) { /* now the transients */
1341 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1343 if(XGetTransientForHint(dpy, wins[i], &d1)
1344 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1345 manage(wins[i], &wa);
1353 setclientstate(Client *c, long state) {
1354 long data[] = {state, None};
1356 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1357 PropModeReplace, (unsigned char *)data, 2);
1361 setlayout(const char *arg) {
1365 if(++ltidx == nlayouts)
1369 for(i = 0; i < nlayouts; i++)
1370 if(!strcmp(arg, layouts[i].symbol))
1383 setmwfact(const char *arg) {
1388 /* arg handling, manipulate mwfact */
1391 else if(1 == sscanf(arg, "%lf", &delta)) {
1392 if(arg[0] == '+' || arg[0] == '-')
1398 else if(mwfact > 0.9)
1407 unsigned int i, j, mask;
1409 XModifierKeymap *modmap;
1410 XSetWindowAttributes wa;
1413 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1414 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1415 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1416 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1417 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1418 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1419 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1420 PropModeReplace, (unsigned char *) netatom, NetLast);
1423 cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1424 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1425 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1429 sw = DisplayWidth(dpy, screen);
1430 sh = DisplayHeight(dpy, screen);
1432 /* init modifier map */
1433 modmap = XGetModifierMapping(dpy);
1434 for(i = 0; i < 8; i++)
1435 for(j = 0; j < modmap->max_keypermod; j++) {
1436 if(modmap->modifiermap[i * modmap->max_keypermod + j]
1437 == XKeysymToKeycode(dpy, XK_Num_Lock))
1438 numlockmask = (1 << i);
1440 XFreeModifiermap(modmap);
1442 /* select for events */
1443 wa.event_mask = SubstructureRedirectMask | SubstructureNotifyMask
1444 | EnterWindowMask | LeaveWindowMask | StructureNotifyMask;
1445 wa.cursor = cursor[CurNormal];
1446 XChangeWindowAttributes(dpy, root, CWEventMask | CWCursor, &wa);
1447 XSelectInput(dpy, root, wa.event_mask);
1455 /* init appearance */
1456 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1457 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1458 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1459 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1460 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1461 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1463 dc.h = bh = dc.font.height + 2;
1467 nlayouts = sizeof layouts / sizeof layouts[0];
1468 for(blw = i = 0; i < nlayouts; i++) {
1469 j = textw(layouts[i].symbol);
1476 wa.override_redirect = 1;
1477 wa.background_pixmap = ParentRelative;
1478 wa.event_mask = ButtonPressMask | ExposureMask;
1479 barwin = XCreateWindow(dpy, root, sx, sy, sw, bh, 0,
1480 DefaultDepth(dpy, screen), CopyFromParent, DefaultVisual(dpy, screen),
1481 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
1482 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1484 XMapRaised(dpy, barwin);
1485 strcpy(stext, "dwm-"VERSION);
1486 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
1487 dc.gc = XCreateGC(dpy, root, 0, 0);
1488 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1490 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1492 /* multihead support */
1493 selscreen = XQueryPointer(dpy, root, &w, &w, &d, &d, &d, &d, &mask);
1497 spawn(const char *arg) {
1498 static char *shell = NULL;
1500 if(!shell && !(shell = getenv("SHELL")))
1504 /* The double-fork construct avoids zombie processes and keeps the code
1505 * clean from stupid signal handlers. */
1509 close(ConnectionNumber(dpy));
1511 execl(shell, shell, "-c", arg, (char *)NULL);
1512 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1521 tag(const char *arg) {
1526 for(i = 0; i < ntags; i++)
1527 sel->tags[i] = arg == NULL;
1529 if(i >= 0 && i < ntags)
1530 sel->tags[i] = True;
1535 textnw(const char *text, unsigned int len) {
1539 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1542 return XTextWidth(dc.font.xfont, text, len);
1546 textw(const char *text) {
1547 return textnw(text, strlen(text)) + dc.font.height;
1552 unsigned int i, n, nx, ny, nw, nh, mw, th;
1555 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next))
1559 mw = (n == 1) ? waw : mwfact * waw;
1560 th = (n > 1) ? wah / (n - 1) : 0;
1561 if(n > 1 && th < bh)
1566 nw = 0; /* gcc stupidity requires this */
1567 for(i = 0, c = mc = nexttiled(clients); c; c = nexttiled(c->next), i++) {
1569 if(i == 0) { /* master */
1570 nw = mw - 2 * c->border;
1571 nh = wah - 2 * c->border;
1573 else { /* tile window */
1576 nx += mc->w + 2 * mc->border;
1577 nw = waw - nx - 2 * c->border;
1579 if(i + 1 == n) /* remainder */
1580 nh = (way + wah) - ny - 2 * c->border;
1582 nh = th - 2 * c->border;
1584 resize(c, nx, ny, nw, nh, RESIZEHINTS);
1585 if(n > 1 && th != wah)
1586 ny = c->y + c->h + 2 * c->border;
1591 togglebar(const char *arg) {
1593 bpos = (BARPOS == BarOff) ? BarTop : BARPOS;
1601 togglefloating(const char *arg) {
1604 sel->isfloating = !sel->isfloating;
1606 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1611 togglemax(const char *arg) {
1614 if(!sel || sel->isfixed)
1616 if((sel->ismax = !sel->ismax)) {
1617 if(isarrange(floating) || sel->isfloating)
1618 sel->wasfloating = True;
1620 togglefloating(NULL);
1621 sel->wasfloating = False;
1627 resize(sel, wax, way, waw - 2 * sel->border, wah - 2 * sel->border, True);
1630 resize(sel, sel->rx, sel->ry, sel->rw, sel->rh, True);
1631 if(!sel->wasfloating)
1632 togglefloating(NULL);
1635 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1639 toggletag(const char *arg) {
1645 sel->tags[i] = !sel->tags[i];
1646 for(j = 0; j < ntags && !sel->tags[j]; j++);
1648 sel->tags[i] = True;
1653 toggleview(const char *arg) {
1657 seltags[i] = !seltags[i];
1658 for(j = 0; j < ntags && !seltags[j]; j++);
1660 seltags[i] = True; /* at least one tag must be viewed */
1668 XMoveWindow(dpy, c->win, c->x, c->y);
1669 c->isbanned = False;
1673 unmanage(Client *c) {
1676 wc.border_width = c->oldborder;
1677 /* The server grab construct avoids race conditions. */
1679 XSetErrorHandler(xerrordummy);
1680 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1685 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1686 setclientstate(c, WithdrawnState);
1690 XSetErrorHandler(xerror);
1696 unmapnotify(XEvent *e) {
1698 XUnmapEvent *ev = &e->xunmap;
1700 if((c = getclient(ev->window)))
1705 updatebarpos(void) {
1716 XMoveWindow(dpy, barwin, sx, sy);
1720 XMoveWindow(dpy, barwin, sx, sy + wah);
1723 XMoveWindow(dpy, barwin, sx, sy - bh);
1727 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1731 updatesizehints(Client *c) {
1735 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1737 c->flags = size.flags;
1738 if(c->flags & PBaseSize) {
1739 c->basew = size.base_width;
1740 c->baseh = size.base_height;
1742 else if(c->flags & PMinSize) {
1743 c->basew = size.min_width;
1744 c->baseh = size.min_height;
1747 c->basew = c->baseh = 0;
1748 if(c->flags & PResizeInc) {
1749 c->incw = size.width_inc;
1750 c->inch = size.height_inc;
1753 c->incw = c->inch = 0;
1754 if(c->flags & PMaxSize) {
1755 c->maxw = size.max_width;
1756 c->maxh = size.max_height;
1759 c->maxw = c->maxh = 0;
1760 if(c->flags & PMinSize) {
1761 c->minw = size.min_width;
1762 c->minh = size.min_height;
1764 else if(c->flags & PBaseSize) {
1765 c->minw = size.base_width;
1766 c->minh = size.base_height;
1769 c->minw = c->minh = 0;
1770 if(c->flags & PAspect) {
1771 c->minax = size.min_aspect.x;
1772 c->maxax = size.max_aspect.x;
1773 c->minay = size.min_aspect.y;
1774 c->maxay = size.max_aspect.y;
1777 c->minax = c->maxax = c->minay = c->maxay = 0;
1778 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1779 && c->maxw == c->minw && c->maxh == c->minh);
1783 updatetitle(Client *c) {
1784 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1785 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1788 /* There's no way to check accesses to destroyed windows, thus those cases are
1789 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1790 * default error handler, which may call exit. */
1792 xerror(Display *dpy, XErrorEvent *ee) {
1793 if(ee->error_code == BadWindow
1794 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1795 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1796 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1797 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1798 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1799 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1800 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1802 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1803 ee->request_code, ee->error_code);
1804 return xerrorxlib(dpy, ee); /* may call exit */
1808 xerrordummy(Display *dsply, XErrorEvent *ee) {
1812 /* Startup Error handler to check if another window manager
1813 * is already running. */
1815 xerrorstart(Display *dsply, XErrorEvent *ee) {
1821 view(const char *arg) {
1824 memcpy(prevtags, seltags, sizeof seltags);
1825 for(i = 0; i < ntags; i++)
1826 seltags[i] = arg == NULL;
1828 if(i >= 0 && i < ntags)
1834 viewprevtag(const char *arg) {
1835 static Bool tmptags[sizeof tags / sizeof tags[0]];
1837 memcpy(tmptags, seltags, sizeof seltags);
1838 memcpy(seltags, prevtags, sizeof seltags);
1839 memcpy(prevtags, tmptags, sizeof seltags);
1844 zoom(const char *arg) {
1847 if(!sel || !ISTILE || sel->isfloating)
1849 if((c = sel) == nexttiled(clients))
1850 if(!(c = nexttiled(c->next)))
1859 main(int argc, char *argv[]) {
1860 if(argc == 2 && !strcmp("-v", argv[1]))
1861 eprint("dwm-"VERSION", © 2006-2007 A. R. Garbe, S. van Dijk, J. Salmi, P. Hruby, S. Nagy\n");
1863 eprint("usage: dwm [-v]\n");
1865 setlocale(LC_CTYPE, "");
1866 if(!(dpy = XOpenDisplay(0)))
1867 eprint("dwm: cannot open display\n");
1868 screen = DefaultScreen(dpy);
1869 root = RootWindow(dpy, screen);