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)
67 int screen, sx, sy, sw, sh, wax, way, waw, wah;
68 int (*xerrorxlib)(Display *, XErrorEvent *);
69 unsigned int bh, bpos;
71 unsigned int ltidx = 0; /* default */
72 unsigned int nlayouts = 0;
73 unsigned int nrules = 0;
74 unsigned int numlockmask = 0;
75 void (*handler[LASTEvent]) (XEvent *) = {
76 [ButtonPress] = buttonpress,
77 [ConfigureRequest] = configurerequest,
78 [ConfigureNotify] = configurenotify,
79 [DestroyNotify] = destroynotify,
80 [EnterNotify] = enternotify,
81 [LeaveNotify] = leavenotify,
83 [KeyPress] = keypress,
84 [MappingNotify] = mappingnotify,
85 [MapRequest] = maprequest,
86 [PropertyNotify] = propertynotify,
87 [UnmapNotify] = unmapnotify
89 Atom wmatom[WMLast], netatom[NetLast];
92 Bool selscreen = True;
93 Client *clients = NULL;
96 Cursor cursor[CurLast];
102 /* configuration, allows nested code to access above variables */
105 /* Statically define the number of tags. */
106 unsigned int ntags = sizeof tags / sizeof tags[0];
107 Bool seltags[sizeof tags / sizeof tags[0]] = {[0] = True};
108 Bool prevtags[sizeof tags / sizeof tags[0]] = {[0] = True};
112 applyrules(Client *c) {
113 static char buf[512];
116 Bool matched = False;
117 XClassHint ch = { 0 };
120 XGetClassHint(dpy, c->win, &ch);
121 snprintf(buf, sizeof buf, "%s:%s:%s",
122 ch.res_class ? ch.res_class : "",
123 ch.res_name ? ch.res_name : "", c->name);
124 for(i = 0; i < nrules; i++)
125 if(regs[i].propregex && !regexec(regs[i].propregex, buf, 1, &tmp, 0)) {
126 c->isfloating = rules[i].isfloating;
127 for(j = 0; regs[i].tagregex && j < ntags; j++) {
128 if(!regexec(regs[i].tagregex, tags[j], 1, &tmp, 0)) {
139 memcpy(c->tags, seltags, sizeof seltags);
146 for(c = clients; c; c = c->next)
151 layouts[ltidx].arrange();
165 attachstack(Client *c) {
174 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
179 buttonpress(XEvent *e) {
182 XButtonPressedEvent *ev = &e->xbutton;
184 if(barwin == ev->window) {
186 for(i = 0; i < ntags; i++) {
189 if(ev->button == Button1) {
190 if(ev->state & MODKEY)
195 else if(ev->button == Button3) {
196 if(ev->state & MODKEY)
204 if((ev->x < x + blw) && ev->button == Button1)
207 else if((c = getclient(ev->window))) {
209 if(CLEANMASK(ev->state) != MODKEY)
211 if(ev->button == Button1) {
212 if(isarrange(floating) || c->isfloating)
215 togglefloating(NULL);
218 else if(ev->button == Button2) {
219 if(ISTILE && !c->isfixed && c->isfloating)
220 togglefloating(NULL);
224 else if(ev->button == Button3 && !c->isfixed) {
225 if(isarrange(floating) || c->isfloating)
228 togglefloating(NULL);
237 XSetErrorHandler(xerrorstart);
239 /* this causes an error if some other window manager is running */
240 XSelectInput(dpy, root, SubstructureRedirectMask);
243 eprint("dwm: another window manager is already running\n");
245 XSetErrorHandler(NULL);
246 xerrorxlib = XSetErrorHandler(xerror);
258 XFreeFontSet(dpy, dc.font.set);
260 XFreeFont(dpy, dc.font.xfont);
261 XUngrabKey(dpy, AnyKey, AnyModifier, root);
262 XFreePixmap(dpy, dc.drawable);
264 XDestroyWindow(dpy, barwin);
265 XFreeCursor(dpy, cursor[CurNormal]);
266 XFreeCursor(dpy, cursor[CurResize]);
267 XFreeCursor(dpy, cursor[CurMove]);
268 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
279 nrules = sizeof rules / sizeof rules[0];
280 regs = emallocz(nrules * sizeof(Regs));
281 for(i = 0; i < nrules; i++) {
283 reg = emallocz(sizeof(regex_t));
284 if(regcomp(reg, rules[i].prop, REG_EXTENDED))
287 regs[i].propregex = reg;
290 reg = emallocz(sizeof(regex_t));
291 if(regcomp(reg, rules[i].tags, REG_EXTENDED))
294 regs[i].tagregex = reg;
300 configure(Client *c) {
303 ce.type = ConfigureNotify;
311 ce.border_width = c->border;
313 ce.override_redirect = False;
314 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
318 configurenotify(XEvent *e) {
319 XConfigureEvent *ev = &e->xconfigure;
321 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
324 XFreePixmap(dpy, dc.drawable);
325 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
326 XResizeWindow(dpy, barwin, sw, bh);
333 configurerequest(XEvent *e) {
335 XConfigureRequestEvent *ev = &e->xconfigurerequest;
338 if((c = getclient(ev->window))) {
340 if(ev->value_mask & CWBorderWidth)
341 c->border = ev->border_width;
342 if(c->isfixed || c->isfloating || isarrange(floating)) {
343 if(ev->value_mask & CWX)
345 if(ev->value_mask & CWY)
347 if(ev->value_mask & CWWidth)
349 if(ev->value_mask & CWHeight)
351 if((c->x + c->w) > sw && c->isfloating)
352 c->x = sw / 2 - c->w / 2; /* center in x direction */
353 if((c->y + c->h) > sh && c->isfloating)
354 c->y = sh / 2 - c->h / 2; /* center in y direction */
355 if((ev->value_mask & (CWX | CWY))
356 && !(ev->value_mask & (CWWidth | CWHeight)))
359 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
367 wc.width = ev->width;
368 wc.height = ev->height;
369 wc.border_width = ev->border_width;
370 wc.sibling = ev->above;
371 wc.stack_mode = ev->detail;
372 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
378 destroynotify(XEvent *e) {
380 XDestroyWindowEvent *ev = &e->xdestroywindow;
382 if((c = getclient(ev->window)))
389 c->prev->next = c->next;
391 c->next->prev = c->prev;
394 c->next = c->prev = NULL;
398 detachstack(Client *c) {
401 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
410 for(i = 0; i < ntags; i++) {
411 dc.w = textw(tags[i]);
413 drawtext(tags[i], dc.sel);
414 drawsquare(sel && sel->tags[i], isoccupied(i), dc.sel);
417 drawtext(tags[i], dc.norm);
418 drawsquare(sel && sel->tags[i], isoccupied(i), dc.norm);
423 drawtext(layouts[ltidx].symbol, dc.norm);
431 drawtext(stext, dc.norm);
432 if((dc.w = dc.x - x) > bh) {
435 drawtext(sel->name, dc.sel);
436 drawsquare(sel->ismax, sel->isfloating, dc.sel);
439 drawtext(NULL, dc.norm);
441 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, sw, bh, 0, 0);
446 drawsquare(Bool filled, Bool empty, unsigned long col[ColLast]) {
449 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
451 gcv.foreground = col[ColFG];
452 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
453 x = (dc.font.ascent + dc.font.descent + 2) / 4;
457 r.width = r.height = x + 1;
458 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
461 r.width = r.height = x;
462 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
467 drawtext(const char *text, unsigned long col[ColLast]) {
469 static char buf[256];
470 unsigned int len, olen;
471 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
473 XSetForeground(dpy, dc.gc, col[ColBG]);
474 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
478 olen = len = strlen(text);
479 if(len >= sizeof buf)
480 len = sizeof buf - 1;
481 memcpy(buf, text, len);
483 h = dc.font.ascent + dc.font.descent;
484 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
486 /* shorten text if necessary */
487 while(len && (w = textnw(buf, len)) > dc.w - h)
498 return; /* too long */
499 XSetForeground(dpy, dc.gc, col[ColFG]);
501 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
503 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
507 emallocz(unsigned int size) {
508 void *res = calloc(1, size);
511 eprint("fatal: could not malloc() %u bytes\n", size);
516 enternotify(XEvent *e) {
518 XCrossingEvent *ev = &e->xcrossing;
520 if(ev->mode != NotifyNormal || ev->detail == NotifyInferior)
522 if((c = getclient(ev->window)))
524 else if(ev->window == root) {
531 eprint(const char *errstr, ...) {
534 va_start(ap, errstr);
535 vfprintf(stderr, errstr, ap);
542 XExposeEvent *ev = &e->xexpose;
545 if(barwin == ev->window)
551 floating(void) { /* default floating layout */
554 for(c = clients; c; c = c->next)
556 resize(c, c->x, c->y, c->w, c->h, True);
561 if((!c && selscreen) || (c && !isvisible(c)))
562 for(c = stack; c && !isvisible(c); c = c->snext);
563 if(sel && sel != c) {
564 grabbuttons(sel, False);
565 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
570 grabbuttons(c, True);
577 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
578 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
581 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
585 focusnext(const char *arg) {
590 for(c = sel->next; c && !isvisible(c); c = c->next);
592 for(c = clients; c && !isvisible(c); c = c->next);
600 focusprev(const char *arg) {
605 for(c = sel->prev; c && !isvisible(c); c = c->prev);
607 for(c = clients; c && c->next; c = c->next);
608 for(; c && !isvisible(c); c = c->prev);
617 getclient(Window w) {
620 for(c = clients; c && c->win != w; c = c->next);
625 getcolor(const char *colstr) {
626 Colormap cmap = DefaultColormap(dpy, screen);
629 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
630 eprint("error, cannot allocate color '%s'\n", colstr);
638 unsigned char *p = NULL;
639 unsigned long n, extra;
642 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
643 &real, &format, &n, &extra, (unsigned char **)&p);
644 if(status != Success)
653 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
658 if(!text || size == 0)
661 XGetTextProperty(dpy, w, &name, atom);
664 if(name.encoding == XA_STRING)
665 strncpy(text, (char *)name.value, size - 1);
667 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
670 strncpy(text, *list, size - 1);
671 XFreeStringList(list);
674 text[size - 1] = '\0';
680 grabbuttons(Client *c, Bool focused) {
681 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
684 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
685 GrabModeAsync, GrabModeSync, None, None);
686 XGrabButton(dpy, Button1, MODKEY | LockMask, c->win, False, BUTTONMASK,
687 GrabModeAsync, GrabModeSync, None, None);
688 XGrabButton(dpy, Button1, MODKEY | numlockmask, c->win, False, BUTTONMASK,
689 GrabModeAsync, GrabModeSync, None, None);
690 XGrabButton(dpy, Button1, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
691 GrabModeAsync, GrabModeSync, None, None);
693 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
694 GrabModeAsync, GrabModeSync, None, None);
695 XGrabButton(dpy, Button2, MODKEY | LockMask, c->win, False, BUTTONMASK,
696 GrabModeAsync, GrabModeSync, None, None);
697 XGrabButton(dpy, Button2, MODKEY | numlockmask, c->win, False, BUTTONMASK,
698 GrabModeAsync, GrabModeSync, None, None);
699 XGrabButton(dpy, Button2, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
700 GrabModeAsync, GrabModeSync, None, None);
702 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
703 GrabModeAsync, GrabModeSync, None, None);
704 XGrabButton(dpy, Button3, MODKEY | LockMask, c->win, False, BUTTONMASK,
705 GrabModeAsync, GrabModeSync, None, None);
706 XGrabButton(dpy, Button3, MODKEY | numlockmask, c->win, False, BUTTONMASK,
707 GrabModeAsync, GrabModeSync, None, None);
708 XGrabButton(dpy, Button3, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
709 GrabModeAsync, GrabModeSync, None, None);
712 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
713 GrabModeAsync, GrabModeSync, None, None);
717 idxoftag(const char *tag) {
720 for(i = 0; i < ntags; i++)
727 initfont(const char *fontstr) {
728 char *def, **missing;
733 XFreeFontSet(dpy, dc.font.set);
734 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
737 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
738 XFreeStringList(missing);
741 XFontSetExtents *font_extents;
742 XFontStruct **xfonts;
744 dc.font.ascent = dc.font.descent = 0;
745 font_extents = XExtentsOfFontSet(dc.font.set);
746 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
747 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
748 if(dc.font.ascent < (*xfonts)->ascent)
749 dc.font.ascent = (*xfonts)->ascent;
750 if(dc.font.descent < (*xfonts)->descent)
751 dc.font.descent = (*xfonts)->descent;
757 XFreeFont(dpy, dc.font.xfont);
758 dc.font.xfont = NULL;
759 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
760 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
761 eprint("error, cannot load font: '%s'\n", fontstr);
762 dc.font.ascent = dc.font.xfont->ascent;
763 dc.font.descent = dc.font.xfont->descent;
765 dc.font.height = dc.font.ascent + dc.font.descent;
769 isarrange(void (*func)())
771 return func == layouts[ltidx].arrange;
775 isoccupied(unsigned int t) {
778 for(c = clients; c; c = c->next)
785 isprotodel(Client *c) {
790 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
791 for(i = 0; !ret && i < n; i++)
792 if(protocols[i] == wmatom[WMDelete])
800 isvisible(Client *c) {
803 for(i = 0; i < ntags; i++)
804 if(c->tags[i] && seltags[i])
810 keypress(XEvent *e) {
812 unsigned int len = sizeof keys / sizeof keys[0];
818 if(!e) { /* grabkeys */
819 XUngrabKey(dpy, AnyKey, AnyModifier, root);
820 for(i = 0; i < len; i++) {
821 code = XKeysymToKeycode(dpy, keys[i].keysym);
822 XGrabKey(dpy, code, keys[i].mod, root, True,
823 GrabModeAsync, GrabModeAsync);
824 XGrabKey(dpy, code, keys[i].mod | LockMask, root, True,
825 GrabModeAsync, GrabModeAsync);
826 XGrabKey(dpy, code, keys[i].mod | numlockmask, root, True,
827 GrabModeAsync, GrabModeAsync);
828 XGrabKey(dpy, code, keys[i].mod | numlockmask | LockMask, root, True,
829 GrabModeAsync, GrabModeAsync);
834 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
835 for(i = 0; i < len; i++)
836 if(keysym == keys[i].keysym
837 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
840 keys[i].func(keys[i].arg);
845 killclient(const char *arg) {
850 if(isprotodel(sel)) {
851 ev.type = ClientMessage;
852 ev.xclient.window = sel->win;
853 ev.xclient.message_type = wmatom[WMProtocols];
854 ev.xclient.format = 32;
855 ev.xclient.data.l[0] = wmatom[WMDelete];
856 ev.xclient.data.l[1] = CurrentTime;
857 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
860 XKillClient(dpy, sel->win);
864 leavenotify(XEvent *e) {
865 XCrossingEvent *ev = &e->xcrossing;
867 if((ev->window == root) && !ev->same_screen) {
874 manage(Window w, XWindowAttributes *wa) {
875 Client *c, *t = NULL;
880 c = emallocz(sizeof(Client));
881 c->tags = emallocz(sizeof seltags);
887 c->oldborder = wa->border_width;
888 if(c->w == sw && c->h == sh) {
891 c->border = wa->border_width;
894 if(c->x + c->w + 2 * c->border > wax + waw)
895 c->x = wax + waw - c->w - 2 * c->border;
896 if(c->y + c->h + 2 * c->border > way + wah)
897 c->y = way + wah - c->h - 2 * c->border;
902 c->border = BORDERPX;
904 wc.border_width = c->border;
905 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
906 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
907 configure(c); /* propagates border_width, if size doesn't change */
910 StructureNotifyMask | PropertyChangeMask | EnterWindowMask);
911 grabbuttons(c, False);
913 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
914 for(t = clients; t && t->win != trans; t = t->next);
916 memcpy(c->tags, t->tags, sizeof seltags);
919 c->isfloating = (rettrans == Success) || c->isfixed;
922 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
924 XMapWindow(dpy, c->win);
925 setclientstate(c, NormalState);
930 mappingnotify(XEvent *e) {
931 XMappingEvent *ev = &e->xmapping;
933 XRefreshKeyboardMapping(ev);
934 if(ev->request == MappingKeyboard)
939 maprequest(XEvent *e) {
940 static XWindowAttributes wa;
941 XMapRequestEvent *ev = &e->xmaprequest;
943 if(!XGetWindowAttributes(dpy, ev->window, &wa))
945 if(wa.override_redirect)
947 if(!getclient(ev->window))
948 manage(ev->window, &wa);
952 movemouse(Client *c) {
953 int x1, y1, ocx, ocy, di, nx, ny;
960 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
961 None, cursor[CurMove], CurrentTime) != GrabSuccess)
964 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
966 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask, &ev);
969 XUngrabPointer(dpy, CurrentTime);
971 case ConfigureRequest:
974 handler[ev.type](&ev);
978 nx = ocx + (ev.xmotion.x - x1);
979 ny = ocy + (ev.xmotion.y - y1);
980 if(abs(wax + nx) < SNAP)
982 else if(abs((wax + waw) - (nx + c->w + 2 * c->border)) < SNAP)
983 nx = wax + waw - c->w - 2 * c->border;
984 if(abs(way - ny) < SNAP)
986 else if(abs((way + wah) - (ny + c->h + 2 * c->border)) < SNAP)
987 ny = way + wah - c->h - 2 * c->border;
988 resize(c, nx, ny, c->w, c->h, False);
995 nexttiled(Client *c) {
996 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1001 propertynotify(XEvent *e) {
1004 XPropertyEvent *ev = &e->xproperty;
1006 if(ev->state == PropertyDelete)
1007 return; /* ignore */
1008 if((c = getclient(ev->window))) {
1011 case XA_WM_TRANSIENT_FOR:
1012 XGetTransientForHint(dpy, c->win, &trans);
1013 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1016 case XA_WM_NORMAL_HINTS:
1020 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1029 quit(const char *arg) {
1030 readin = running = False;
1034 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1035 double dx, dy, max, min, ratio;
1039 if(c->minay > 0 && c->maxay > 0 && (h - c->baseh) > 0 && (w - c->basew) > 0) {
1040 dx = (double)(w - c->basew);
1041 dy = (double)(h - c->baseh);
1042 min = (double)(c->minax) / (double)(c->minay);
1043 max = (double)(c->maxax) / (double)(c->maxay);
1045 if(max > 0 && min > 0 && ratio > 0) {
1047 dy = (dx * min + dy) / (min * min + 1);
1049 w = (int)dx + c->basew;
1050 h = (int)dy + c->baseh;
1052 else if(ratio > max) {
1053 dy = (dx * min + dy) / (max * max + 1);
1055 w = (int)dx + c->basew;
1056 h = (int)dy + c->baseh;
1060 if(c->minw && w < c->minw)
1062 if(c->minh && h < c->minh)
1064 if(c->maxw && w > c->maxw)
1066 if(c->maxh && h > c->maxh)
1069 w -= (w - c->basew) % c->incw;
1071 h -= (h - c->baseh) % c->inch;
1073 if(w <= 0 || h <= 0)
1075 /* offscreen appearance fixes */
1077 x = sw - w - 2 * c->border;
1079 y = sh - h - 2 * c->border;
1080 if(x + w + 2 * c->border < sx)
1082 if(y + h + 2 * c->border < sy)
1084 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1087 c->w = wc.width = w;
1088 c->h = wc.height = h;
1089 wc.border_width = c->border;
1090 XConfigureWindow(dpy, c->win, CWX | CWY | CWWidth | CWHeight | CWBorderWidth, &wc);
1097 resizemouse(Client *c) {
1104 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1105 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1108 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
1110 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask , &ev);
1113 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1114 c->w + c->border - 1, c->h + c->border - 1);
1115 XUngrabPointer(dpy, CurrentTime);
1116 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1118 case ConfigureRequest:
1121 handler[ev.type](&ev);
1125 if((nw = ev.xmotion.x - ocx - 2 * c->border + 1) <= 0)
1127 if((nh = ev.xmotion.y - ocy - 2 * c->border + 1) <= 0)
1129 resize(c, c->x, c->y, nw, nh, True);
1144 if(sel->isfloating || isarrange(floating))
1145 XRaiseWindow(dpy, sel->win);
1146 if(!isarrange(floating)) {
1147 wc.stack_mode = Below;
1148 wc.sibling = barwin;
1149 if(!sel->isfloating) {
1150 XConfigureWindow(dpy, sel->win, CWSibling | CWStackMode, &wc);
1151 wc.sibling = sel->win;
1153 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
1156 XConfigureWindow(dpy, c->win, CWSibling | CWStackMode, &wc);
1157 wc.sibling = c->win;
1161 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1171 /* main event loop, also reads status text from stdin */
1173 xfd = ConnectionNumber(dpy);
1178 FD_SET(STDIN_FILENO, &rd);
1180 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1183 eprint("select failed\n");
1185 if(FD_ISSET(STDIN_FILENO, &rd)) {
1186 switch(r = read(STDIN_FILENO, stext, sizeof stext - 1)) {
1188 strncpy(stext, strerror(errno), sizeof stext - 1);
1189 stext[sizeof stext - 1] = '\0';
1193 strncpy(stext, "EOF", 4);
1197 for(stext[r] = '\0', p = stext + strlen(stext) - 1; p >= stext && *p == '\n'; *p-- = '\0');
1198 for(; p >= stext && *p != '\n'; --p);
1200 strncpy(stext, p + 1, sizeof stext);
1204 while(XPending(dpy)) {
1205 XNextEvent(dpy, &ev);
1206 if(handler[ev.type])
1207 (handler[ev.type])(&ev); /* call handler */
1214 unsigned int i, num;
1215 Window *wins, d1, d2;
1216 XWindowAttributes wa;
1219 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1220 for(i = 0; i < num; i++) {
1221 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1222 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1224 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1225 manage(wins[i], &wa);
1227 for(i = 0; i < num; i++) { /* now the transients */
1228 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1230 if(XGetTransientForHint(dpy, wins[i], &d1)
1231 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1232 manage(wins[i], &wa);
1240 setclientstate(Client *c, long state) {
1241 long data[] = {state, None};
1243 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1244 PropModeReplace, (unsigned char *)data, 2);
1248 setlayout(const char *arg) {
1252 if(++ltidx == nlayouts)
1256 for(i = 0; i < nlayouts; i++)
1257 if(!strcmp(arg, layouts[i].symbol))
1270 setmwfact(const char *arg) {
1275 /* arg handling, manipulate mwfact */
1278 else if(1 == sscanf(arg, "%lf", &delta)) {
1279 if(arg[0] == '+' || arg[0] == '-')
1285 else if(mwfact > 0.9)
1294 unsigned int i, j, mask;
1296 XModifierKeymap *modmap;
1297 XSetWindowAttributes wa;
1300 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1301 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1302 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1303 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1304 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1305 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1306 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1307 PropModeReplace, (unsigned char *) netatom, NetLast);
1310 cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1311 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1312 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1316 sw = DisplayWidth(dpy, screen);
1317 sh = DisplayHeight(dpy, screen);
1319 /* init modifier map */
1320 modmap = XGetModifierMapping(dpy);
1321 for(i = 0; i < 8; i++)
1322 for(j = 0; j < modmap->max_keypermod; j++) {
1323 if(modmap->modifiermap[i * modmap->max_keypermod + j]
1324 == XKeysymToKeycode(dpy, XK_Num_Lock))
1325 numlockmask = (1 << i);
1327 XFreeModifiermap(modmap);
1329 /* select for events */
1330 wa.event_mask = SubstructureRedirectMask | SubstructureNotifyMask
1331 | EnterWindowMask | LeaveWindowMask | StructureNotifyMask;
1332 wa.cursor = cursor[CurNormal];
1333 XChangeWindowAttributes(dpy, root, CWEventMask | CWCursor, &wa);
1334 XSelectInput(dpy, root, wa.event_mask);
1342 /* init appearance */
1343 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1344 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1345 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1346 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1347 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1348 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1350 dc.h = bh = dc.font.height + 2;
1354 nlayouts = sizeof layouts / sizeof layouts[0];
1355 for(blw = i = 0; i < nlayouts; i++) {
1356 j = textw(layouts[i].symbol);
1363 wa.override_redirect = 1;
1364 wa.background_pixmap = ParentRelative;
1365 wa.event_mask = ButtonPressMask | ExposureMask;
1366 barwin = XCreateWindow(dpy, root, sx, sy, sw, bh, 0,
1367 DefaultDepth(dpy, screen), CopyFromParent, DefaultVisual(dpy, screen),
1368 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
1369 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1371 XMapRaised(dpy, barwin);
1372 strcpy(stext, "dwm-"VERSION);
1373 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
1374 dc.gc = XCreateGC(dpy, root, 0, 0);
1375 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1377 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1379 /* multihead support */
1380 selscreen = XQueryPointer(dpy, root, &w, &w, &d, &d, &d, &d, &mask);
1384 spawn(const char *arg) {
1385 static char *shell = NULL;
1387 if(!shell && !(shell = getenv("SHELL")))
1391 /* The double-fork construct avoids zombie processes and keeps the code
1392 * clean from stupid signal handlers. */
1396 close(ConnectionNumber(dpy));
1398 execl(shell, shell, "-c", arg, (char *)NULL);
1399 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1408 tag(const char *arg) {
1413 for(i = 0; i < ntags; i++)
1414 sel->tags[i] = arg == NULL;
1416 if(i >= 0 && i < ntags)
1417 sel->tags[i] = True;
1422 textnw(const char *text, unsigned int len) {
1426 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1429 return XTextWidth(dc.font.xfont, text, len);
1433 textw(const char *text) {
1434 return textnw(text, strlen(text)) + dc.font.height;
1439 unsigned int i, n, nx, ny, nw, nh, mw, th;
1442 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next))
1446 mw = (n == 1) ? waw : mwfact * waw;
1447 th = (n > 1) ? wah / (n - 1) : 0;
1448 if(n > 1 && th < bh)
1453 nw = 0; /* gcc stupidity requires this */
1454 for(i = 0, c = mc = nexttiled(clients); c; c = nexttiled(c->next), i++) {
1456 if(i == 0) { /* master */
1457 nw = mw - 2 * c->border;
1458 nh = wah - 2 * c->border;
1460 else { /* tile window */
1463 nx += mc->w + 2 * mc->border;
1464 nw = waw - nx - 2 * c->border;
1466 if(i + 1 == n) /* remainder */
1467 nh = (way + wah) - ny - 2 * c->border;
1469 nh = th - 2 * c->border;
1471 resize(c, nx, ny, nw, nh, RESIZEHINTS);
1472 if(n > 1 && th != wah)
1473 ny = c->y + c->h + 2 * c->border;
1478 togglebar(const char *arg) {
1480 bpos = (BARPOS == BarOff) ? BarTop : BARPOS;
1488 togglefloating(const char *arg) {
1491 sel->isfloating = !sel->isfloating;
1493 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1498 togglemax(const char *arg) {
1501 if(!sel || sel->isfixed)
1503 if((sel->ismax = !sel->ismax)) {
1504 if(isarrange(floating) || sel->isfloating)
1505 sel->wasfloating = True;
1507 togglefloating(NULL);
1508 sel->wasfloating = False;
1514 resize(sel, wax, way, waw - 2 * sel->border, wah - 2 * sel->border, True);
1517 resize(sel, sel->rx, sel->ry, sel->rw, sel->rh, True);
1518 if(!sel->wasfloating)
1519 togglefloating(NULL);
1522 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1526 toggletag(const char *arg) {
1532 sel->tags[i] = !sel->tags[i];
1533 for(j = 0; j < ntags && !sel->tags[j]; j++);
1535 sel->tags[i] = True;
1540 toggleview(const char *arg) {
1544 seltags[i] = !seltags[i];
1545 for(j = 0; j < ntags && !seltags[j]; j++);
1547 seltags[i] = True; /* at least one tag must be viewed */
1555 XMoveWindow(dpy, c->win, c->x, c->y);
1556 c->isbanned = False;
1560 unmanage(Client *c) {
1563 wc.border_width = c->oldborder;
1564 /* The server grab construct avoids race conditions. */
1566 XSetErrorHandler(xerrordummy);
1567 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1572 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1573 setclientstate(c, WithdrawnState);
1577 XSetErrorHandler(xerror);
1583 unmapnotify(XEvent *e) {
1585 XUnmapEvent *ev = &e->xunmap;
1587 if((c = getclient(ev->window)))
1592 updatebarpos(void) {
1603 XMoveWindow(dpy, barwin, sx, sy);
1607 XMoveWindow(dpy, barwin, sx, sy + wah);
1610 XMoveWindow(dpy, barwin, sx, sy - bh);
1614 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1618 updatesizehints(Client *c) {
1622 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1624 c->flags = size.flags;
1625 if(c->flags & PBaseSize) {
1626 c->basew = size.base_width;
1627 c->baseh = size.base_height;
1629 else if(c->flags & PMinSize) {
1630 c->basew = size.min_width;
1631 c->baseh = size.min_height;
1634 c->basew = c->baseh = 0;
1635 if(c->flags & PResizeInc) {
1636 c->incw = size.width_inc;
1637 c->inch = size.height_inc;
1640 c->incw = c->inch = 0;
1641 if(c->flags & PMaxSize) {
1642 c->maxw = size.max_width;
1643 c->maxh = size.max_height;
1646 c->maxw = c->maxh = 0;
1647 if(c->flags & PMinSize) {
1648 c->minw = size.min_width;
1649 c->minh = size.min_height;
1651 else if(c->flags & PBaseSize) {
1652 c->minw = size.base_width;
1653 c->minh = size.base_height;
1656 c->minw = c->minh = 0;
1657 if(c->flags & PAspect) {
1658 c->minax = size.min_aspect.x;
1659 c->maxax = size.max_aspect.x;
1660 c->minay = size.min_aspect.y;
1661 c->maxay = size.max_aspect.y;
1664 c->minax = c->maxax = c->minay = c->maxay = 0;
1665 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1666 && c->maxw == c->minw && c->maxh == c->minh);
1670 updatetitle(Client *c) {
1671 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1672 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1675 /* There's no way to check accesses to destroyed windows, thus those cases are
1676 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1677 * default error handler, which may call exit. */
1679 xerror(Display *dpy, XErrorEvent *ee) {
1680 if(ee->error_code == BadWindow
1681 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1682 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1683 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1684 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1685 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1686 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1687 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1689 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1690 ee->request_code, ee->error_code);
1691 return xerrorxlib(dpy, ee); /* may call exit */
1695 xerrordummy(Display *dsply, XErrorEvent *ee) {
1699 /* Startup Error handler to check if another window manager
1700 * is already running. */
1702 xerrorstart(Display *dsply, XErrorEvent *ee) {
1708 view(const char *arg) {
1711 memcpy(prevtags, seltags, sizeof seltags);
1712 for(i = 0; i < ntags; i++)
1713 seltags[i] = arg == NULL;
1715 if(i >= 0 && i < ntags)
1721 viewprevtag(const char *arg) {
1722 static Bool tmptags[sizeof tags / sizeof tags[0]];
1724 memcpy(tmptags, seltags, sizeof seltags);
1725 memcpy(seltags, prevtags, sizeof seltags);
1726 memcpy(prevtags, tmptags, sizeof seltags);
1731 zoom(const char *arg) {
1734 if(!sel || !ISTILE || sel->isfloating)
1736 if((c = sel) == nexttiled(clients))
1737 if(!(c = nexttiled(c->next)))
1746 main(int argc, char *argv[]) {
1747 if(argc == 2 && !strcmp("-v", argv[1]))
1748 eprint("dwm-"VERSION", © 2006-2007 A. R. Garbe, S. van Dijk, J. Salmi, P. Hruby, S. Nagy\n");
1750 eprint("usage: dwm [-v]\n");
1752 setlocale(LC_CTYPE, "");
1753 if(!(dpy = XOpenDisplay(0)))
1754 eprint("dwm: cannot open display\n");
1755 screen = DefaultScreen(dpy);
1756 root = RootWindow(dpy, screen);