dwm.c (view raw)
1/* See LICENSE file for copyright and license details.
2 *
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.
8 *
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.
15 *
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 a bit array to indicate the tags of a
20 * client.
21 *
22 * Keys and tagging rules are organized as arrays and defined in config.h.
23 *
24 * To understand everything else, start reading main().
25 */
26#include <errno.h>
27#include <locale.h>
28#include <stdarg.h>
29#include <stdio.h>
30#include <stdlib.h>
31#include <string.h>
32#include <unistd.h>
33#include <sys/select.h>
34#include <sys/types.h>
35#include <sys/wait.h>
36#include <X11/cursorfont.h>
37#include <X11/keysym.h>
38#include <X11/Xatom.h>
39#include <X11/Xlib.h>
40#include <X11/Xproto.h>
41#include <X11/Xutil.h>
42#ifdef XINERAMA
43#include <X11/extensions/Xinerama.h>
44#endif
45
46/* macros */
47#define BUTTONMASK (ButtonPressMask|ButtonReleaseMask)
48#define CLEANMASK(mask) (mask & ~(numlockmask|LockMask))
49#define INRECT(X,Y,RX,RY,RW,RH) ((X) >= (RX) && (X) < (RX) + (RW) && (Y) >= (RY) && (Y) < (RY) + (RH))
50#define ISVISIBLE(x) (x->tags & tagset[seltags])
51#define LENGTH(x) (sizeof x / sizeof x[0])
52#define MAX(a, b) ((a) > (b) ? (a) : (b))
53#define MIN(a, b) ((a) < (b) ? (a) : (b))
54#define MAXTAGLEN 16
55#define MOUSEMASK (BUTTONMASK|PointerMotionMask)
56#define NOBORDER(x) ((x) - 2 * c->bw)
57#define TAGMASK ((int)((1LL << LENGTH(tags)) - 1))
58#define TEXTW(x) (textnw(x, strlen(x)) + dc.font.height)
59
60/* enums */
61enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
62enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
63enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
64enum { WMProtocols, WMDelete, WMState, WMLast }; /* default atoms */
65enum { ClkTagBar, ClkLtSymbol, ClkStatusText, ClkWinTitle,
66 ClkClientWin, ClkRootWin, ClkLast }; /* clicks */
67
68typedef union {
69 int i;
70 unsigned int ui;
71 float f;
72 void *v;
73} Arg;
74
75typedef struct {
76 unsigned int click;
77 unsigned int mask;
78 unsigned int button;
79 void (*func)(const Arg *arg);
80 const Arg arg;
81} Button;
82
83typedef struct Client Client;
84struct Client {
85 char name[256];
86 float mina, maxa;
87 int x, y, w, h;
88 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
89 int bw, oldbw;
90 unsigned int tags;
91 Bool isfixed, isfloating, isurgent;
92 Client *next;
93 Client *snext;
94 Window win;
95};
96
97typedef struct {
98 int x, y, w, h;
99 unsigned long norm[ColLast];
100 unsigned long sel[ColLast];
101 Drawable drawable;
102 GC gc;
103 struct {
104 int ascent;
105 int descent;
106 int height;
107 XFontSet set;
108 XFontStruct *xfont;
109 } font;
110} DC; /* draw context */
111
112typedef struct {
113 unsigned int mod;
114 KeySym keysym;
115 void (*func)(const Arg *);
116 const Arg arg;
117} Key;
118
119typedef struct {
120 const char *symbol;
121 void (*arrange)(void);
122} Layout;
123
124typedef struct {
125 const char *class;
126 const char *instance;
127 const char *title;
128 unsigned int tags;
129 Bool isfloating;
130} Rule;
131
132/* function declarations */
133static void applyrules(Client *c);
134static void arrange(void);
135static void attach(Client *c);
136static void attachstack(Client *c);
137static void buttonpress(XEvent *e);
138static void checkotherwm(void);
139static void cleanup(void);
140static void clearurgent(void);
141static void configure(Client *c);
142static void configurenotify(XEvent *e);
143static void configurerequest(XEvent *e);
144static void destroynotify(XEvent *e);
145static void detach(Client *c);
146static void detachstack(Client *c);
147static void die(const char *errstr, ...);
148static void drawbar(void);
149static void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
150static void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
151static void enternotify(XEvent *e);
152static void expose(XEvent *e);
153static void focus(Client *c);
154static void focusin(XEvent *e);
155static void focusstack(const Arg *arg);
156static Client *getclient(Window w);
157static unsigned long getcolor(const char *colstr);
158static long getstate(Window w);
159static Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
160static void grabbuttons(Client *c, Bool focused);
161static void grabkeys(void);
162static void initfont(const char *fontstr);
163static Bool isprotodel(Client *c);
164static void keypress(XEvent *e);
165static void killclient(const Arg *arg);
166static void manage(Window w, XWindowAttributes *wa);
167static void mappingnotify(XEvent *e);
168static void maprequest(XEvent *e);
169static void monocle(void);
170static void movemouse(const Arg *arg);
171static Client *nexttiled(Client *c);
172static void propertynotify(XEvent *e);
173static void quit(const Arg *arg);
174static void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
175static void resizemouse(const Arg *arg);
176static void restack(void);
177static void run(void);
178static void scan(void);
179static void setclientstate(Client *c, long state);
180static void setlayout(const Arg *arg);
181static void setmfact(const Arg *arg);
182static void setup(void);
183static void showhide(Client *c);
184static void spawn(const Arg *arg);
185static void tag(const Arg *arg);
186static int textnw(const char *text, unsigned int len);
187static void tile(void);
188static void togglebar(const Arg *arg);
189static void togglefloating(const Arg *arg);
190static void toggletag(const Arg *arg);
191static void toggleview(const Arg *arg);
192static void unmanage(Client *c);
193static void unmapnotify(XEvent *e);
194static void updatebar(void);
195static void updategeom(void);
196static void updatenumlockmask(void);
197static void updatesizehints(Client *c);
198static void updatetitle(Client *c);
199static void updatewmhints(Client *c);
200static void view(const Arg *arg);
201static int xerror(Display *dpy, XErrorEvent *ee);
202static int xerrordummy(Display *dpy, XErrorEvent *ee);
203static int xerrorstart(Display *dpy, XErrorEvent *ee);
204static void zoom(const Arg *arg);
205
206/* variables */
207static char stext[256];
208static int screen;
209static int sx, sy, sw, sh; /* X display screen geometry x, y, width, height */
210static int by, bh, blw; /* bar geometry y, height and layout symbol width */
211static int wx, wy, ww, wh; /* window area geometry x, y, width, height, bar excluded */
212static unsigned int seltags = 0, sellt = 0;
213static int (*xerrorxlib)(Display *, XErrorEvent *);
214static unsigned int numlockmask = 0;
215static void (*handler[LASTEvent]) (XEvent *) = {
216 [ButtonPress] = buttonpress,
217 [ConfigureRequest] = configurerequest,
218 [ConfigureNotify] = configurenotify,
219 [DestroyNotify] = destroynotify,
220 [EnterNotify] = enternotify,
221 [Expose] = expose,
222 [FocusIn] = focusin,
223 [KeyPress] = keypress,
224 [MappingNotify] = mappingnotify,
225 [MapRequest] = maprequest,
226 [PropertyNotify] = propertynotify,
227 [UnmapNotify] = unmapnotify
228};
229static Atom wmatom[WMLast], netatom[NetLast];
230static Bool otherwm;
231static Bool running = True;
232static Client *clients = NULL;
233static Client *sel = NULL;
234static Client *stack = NULL;
235static Cursor cursor[CurLast];
236static Display *dpy;
237static DC dc;
238static Layout *lt[] = { NULL, NULL };
239static Window root, barwin;
240/* configuration, allows nested code to access above variables */
241#include "config.h"
242
243/* compile-time check if all tags fit into an unsigned int bit array. */
244struct NumTags { char limitexceeded[sizeof(unsigned int) * 8 < LENGTH(tags) ? -1 : 1]; };
245
246/* function implementations */
247void
248applyrules(Client *c) {
249 unsigned int i;
250 Rule *r;
251 XClassHint ch = { 0 };
252
253 /* rule matching */
254 if(XGetClassHint(dpy, c->win, &ch)) {
255 for(i = 0; i < LENGTH(rules); i++) {
256 r = &rules[i];
257 if((!r->title || strstr(c->name, r->title))
258 && (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
259 && (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
260 c->isfloating = r->isfloating;
261 c->tags |= r->tags & TAGMASK;
262 }
263 }
264 if(ch.res_class)
265 XFree(ch.res_class);
266 if(ch.res_name)
267 XFree(ch.res_name);
268 }
269 if(!c->tags)
270 c->tags = tagset[seltags];
271}
272
273void
274arrange(void) {
275 if(stack)
276 showhide(stack);
277 focus(NULL);
278 if(lt[sellt]->arrange)
279 lt[sellt]->arrange();
280 restack();
281}
282
283void
284attach(Client *c) {
285 c->next = clients;
286 clients = c;
287}
288
289void
290attachstack(Client *c) {
291 c->snext = stack;
292 stack = c;
293}
294
295void
296buttonpress(XEvent *e) {
297 unsigned int i, x, click;
298 Arg arg = {0};
299 Client *c;
300 XButtonPressedEvent *ev = &e->xbutton;
301
302 click = ClkRootWin;
303 if(ev->window == barwin) {
304 i = x = 0;
305 do x += TEXTW(tags[i]); while(ev->x >= x && ++i < LENGTH(tags));
306 if(i < LENGTH(tags)) {
307 click = ClkTagBar;
308 arg.ui = 1 << i;
309 }
310 else if(ev->x < x + blw)
311 click = ClkLtSymbol;
312 else if(ev->x > wx + ww - TEXTW(stext))
313 click = ClkStatusText;
314 else
315 click = ClkWinTitle;
316 }
317 else if((c = getclient(ev->window))) {
318 focus(c);
319 click = ClkClientWin;
320 }
321
322 for(i = 0; i < LENGTH(buttons); i++)
323 if(click == buttons[i].click && buttons[i].func && buttons[i].button == ev->button
324 && CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
325 buttons[i].func(click == ClkTagBar && buttons[i].arg.i == 0 ? &arg : &buttons[i].arg);
326}
327
328void
329checkotherwm(void) {
330 otherwm = False;
331 xerrorxlib = XSetErrorHandler(xerrorstart);
332
333 /* this causes an error if some other window manager is running */
334 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
335 XSync(dpy, False);
336 if(otherwm)
337 die("dwm: another window manager is already running\n");
338 XSetErrorHandler(xerror);
339 XSync(dpy, False);
340}
341
342void
343cleanup(void) {
344 Arg a = {.ui = ~0};
345 Layout foo = { "", NULL };
346
347 close(STDIN_FILENO);
348 view(&a);
349 lt[sellt] = &foo;
350 while(stack)
351 unmanage(stack);
352 if(dc.font.set)
353 XFreeFontSet(dpy, dc.font.set);
354 else
355 XFreeFont(dpy, dc.font.xfont);
356 XUngrabKey(dpy, AnyKey, AnyModifier, root);
357 XFreePixmap(dpy, dc.drawable);
358 XFreeGC(dpy, dc.gc);
359 XFreeCursor(dpy, cursor[CurNormal]);
360 XFreeCursor(dpy, cursor[CurResize]);
361 XFreeCursor(dpy, cursor[CurMove]);
362 XDestroyWindow(dpy, barwin);
363 XSync(dpy, False);
364 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
365}
366
367void
368clearurgent(void) {
369 XWMHints *wmh;
370 Client *c;
371
372 for(c = clients; c; c = c->next)
373 if(ISVISIBLE(c) && c->isurgent) {
374 c->isurgent = False;
375 if (!(wmh = XGetWMHints(dpy, c->win)))
376 continue;
377
378 wmh->flags &= ~XUrgencyHint;
379 XSetWMHints(dpy, c->win, wmh);
380 XFree(wmh);
381 }
382}
383
384void
385configure(Client *c) {
386 XConfigureEvent ce;
387
388 ce.type = ConfigureNotify;
389 ce.display = dpy;
390 ce.event = c->win;
391 ce.window = c->win;
392 ce.x = c->x;
393 ce.y = c->y;
394 ce.width = c->w;
395 ce.height = c->h;
396 ce.border_width = c->bw;
397 ce.above = None;
398 ce.override_redirect = False;
399 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
400}
401
402void
403configurenotify(XEvent *e) {
404 XConfigureEvent *ev = &e->xconfigure;
405
406 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
407 sw = ev->width;
408 sh = ev->height;
409 updategeom();
410 updatebar();
411 arrange();
412 }
413}
414
415void
416configurerequest(XEvent *e) {
417 Client *c;
418 XConfigureRequestEvent *ev = &e->xconfigurerequest;
419 XWindowChanges wc;
420
421 if((c = getclient(ev->window))) {
422 if(ev->value_mask & CWBorderWidth)
423 c->bw = ev->border_width;
424 else if(c->isfloating || !lt[sellt]->arrange) {
425 if(ev->value_mask & CWX)
426 c->x = sx + ev->x;
427 if(ev->value_mask & CWY)
428 c->y = sy + ev->y;
429 if(ev->value_mask & CWWidth)
430 c->w = ev->width;
431 if(ev->value_mask & CWHeight)
432 c->h = ev->height;
433 if((c->x - sx + c->w) > sw && c->isfloating)
434 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
435 if((c->y - sy + c->h) > sh && c->isfloating)
436 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
437 if((ev->value_mask & (CWX|CWY)) && !(ev->value_mask & (CWWidth|CWHeight)))
438 configure(c);
439 if(ISVISIBLE(c))
440 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
441 }
442 else
443 configure(c);
444 }
445 else {
446 wc.x = ev->x;
447 wc.y = ev->y;
448 wc.width = ev->width;
449 wc.height = ev->height;
450 wc.border_width = ev->border_width;
451 wc.sibling = ev->above;
452 wc.stack_mode = ev->detail;
453 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
454 }
455 XSync(dpy, False);
456}
457
458void
459destroynotify(XEvent *e) {
460 Client *c;
461 XDestroyWindowEvent *ev = &e->xdestroywindow;
462
463 if((c = getclient(ev->window)))
464 unmanage(c);
465}
466
467void
468detach(Client *c) {
469 Client **tc;
470
471 for(tc = &clients; *tc && *tc != c; tc = &(*tc)->next);
472 *tc = c->next;
473}
474
475void
476detachstack(Client *c) {
477 Client **tc;
478
479 for(tc = &stack; *tc && *tc != c; tc = &(*tc)->snext);
480 *tc = c->snext;
481}
482
483void
484die(const char *errstr, ...) {
485 va_list ap;
486
487 va_start(ap, errstr);
488 vfprintf(stderr, errstr, ap);
489 va_end(ap);
490 exit(EXIT_FAILURE);
491}
492
493void
494drawbar(void) {
495 int x;
496 unsigned int i, occ = 0, urg = 0;
497 unsigned long *col;
498 Client *c;
499
500 for(c = clients; c; c = c->next) {
501 occ |= c->tags;
502 if(c->isurgent)
503 urg |= c->tags;
504 }
505
506 dc.x = 0;
507 for(i = 0; i < LENGTH(tags); i++) {
508 dc.w = TEXTW(tags[i]);
509 col = tagset[seltags] & 1 << i ? dc.sel : dc.norm;
510 drawtext(tags[i], col, urg & 1 << i);
511 drawsquare(sel && sel->tags & 1 << i, occ & 1 << i, urg & 1 << i, col);
512 dc.x += dc.w;
513 }
514 if(blw > 0) {
515 dc.w = blw;
516 drawtext(lt[sellt]->symbol, dc.norm, False);
517 x = dc.x + dc.w;
518 }
519 else
520 x = dc.x;
521 dc.w = TEXTW(stext);
522 dc.x = ww - dc.w;
523 if(dc.x < x) {
524 dc.x = x;
525 dc.w = ww - x;
526 }
527 drawtext(stext, dc.norm, False);
528 if((dc.w = dc.x - x) > bh) {
529 dc.x = x;
530 if(sel) {
531 drawtext(sel->name, dc.sel, False);
532 drawsquare(sel->isfixed, sel->isfloating, False, dc.sel);
533 }
534 else
535 drawtext(NULL, dc.norm, False);
536 }
537 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, ww, bh, 0, 0);
538 XSync(dpy, False);
539}
540
541void
542drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
543 int x;
544 XGCValues gcv;
545 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
546
547 gcv.foreground = col[invert ? ColBG : ColFG];
548 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
549 x = (dc.font.ascent + dc.font.descent + 2) / 4;
550 r.x = dc.x + 1;
551 r.y = dc.y + 1;
552 if(filled) {
553 r.width = r.height = x + 1;
554 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
555 }
556 else if(empty) {
557 r.width = r.height = x;
558 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
559 }
560}
561
562void
563drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
564 char buf[256];
565 int i, x, y, h, len, olen;
566 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
567
568 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
569 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
570 if(!text)
571 return;
572 olen = strlen(text);
573 h = dc.font.ascent + dc.font.descent;
574 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
575 x = dc.x + (h / 2);
576 /* shorten text if necessary */
577 for(len = MIN(olen, sizeof buf); len && textnw(text, len) > dc.w - h; len--);
578 if(!len)
579 return;
580 memcpy(buf, text, len);
581 if(len < olen)
582 for(i = len; i && i > len - 3; buf[--i] = '.');
583 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
584 if(dc.font.set)
585 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
586 else
587 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
588}
589
590void
591enternotify(XEvent *e) {
592 Client *c;
593 XCrossingEvent *ev = &e->xcrossing;
594
595 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
596 return;
597 if((c = getclient(ev->window)))
598 focus(c);
599 else
600 focus(NULL);
601}
602
603void
604expose(XEvent *e) {
605 XExposeEvent *ev = &e->xexpose;
606
607 if(ev->count == 0 && (ev->window == barwin))
608 drawbar();
609}
610
611void
612focus(Client *c) {
613 if(!c || !ISVISIBLE(c))
614 for(c = stack; c && !ISVISIBLE(c); c = c->snext);
615 if(sel && sel != c) {
616 grabbuttons(sel, False);
617 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
618 }
619 if(c) {
620 detachstack(c);
621 attachstack(c);
622 grabbuttons(c, True);
623 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
624 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
625 }
626 else
627 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
628 sel = c;
629 drawbar();
630}
631
632void
633focusin(XEvent *e) { /* there are some broken focus acquiring clients */
634 XFocusChangeEvent *ev = &e->xfocus;
635
636 if(sel && ev->window != sel->win)
637 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
638}
639
640void
641focusstack(const Arg *arg) {
642 Client *c = NULL, *i;
643
644 if(!sel)
645 return;
646 if (arg->i > 0) {
647 for(c = sel->next; c && !ISVISIBLE(c); c = c->next);
648 if(!c)
649 for(c = clients; c && !ISVISIBLE(c); c = c->next);
650 }
651 else {
652 for(i = clients; i != sel; i = i->next)
653 if(ISVISIBLE(i))
654 c = i;
655 if(!c)
656 for(; i; i = i->next)
657 if(ISVISIBLE(i))
658 c = i;
659 }
660 if(c) {
661 focus(c);
662 restack();
663 }
664}
665
666Client *
667getclient(Window w) {
668 Client *c;
669
670 for(c = clients; c && c->win != w; c = c->next);
671 return c;
672}
673
674unsigned long
675getcolor(const char *colstr) {
676 Colormap cmap = DefaultColormap(dpy, screen);
677 XColor color;
678
679 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
680 die("error, cannot allocate color '%s'\n", colstr);
681 return color.pixel;
682}
683
684long
685getstate(Window w) {
686 int format, status;
687 long result = -1;
688 unsigned char *p = NULL;
689 unsigned long n, extra;
690 Atom real;
691
692 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
693 &real, &format, &n, &extra, (unsigned char **)&p);
694 if(status != Success)
695 return -1;
696 if(n != 0)
697 result = *p;
698 XFree(p);
699 return result;
700}
701
702Bool
703gettextprop(Window w, Atom atom, char *text, unsigned int size) {
704 char **list = NULL;
705 int n;
706 XTextProperty name;
707
708 if(!text || size == 0)
709 return False;
710 text[0] = '\0';
711 XGetTextProperty(dpy, w, &name, atom);
712 if(!name.nitems)
713 return False;
714 if(name.encoding == XA_STRING)
715 strncpy(text, (char *)name.value, size - 1);
716 else {
717 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
718 && n > 0 && *list) {
719 strncpy(text, *list, size - 1);
720 XFreeStringList(list);
721 }
722 }
723 text[size - 1] = '\0';
724 XFree(name.value);
725 return True;
726}
727
728void
729grabbuttons(Client *c, Bool focused) {
730 updatenumlockmask();
731 {
732 unsigned int i, j;
733 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
734 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
735 if(focused) {
736 for(i = 0; i < LENGTH(buttons); i++)
737 if(buttons[i].click == ClkClientWin)
738 for(j = 0; j < LENGTH(modifiers); j++)
739 XGrabButton(dpy, buttons[i].button, buttons[i].mask | modifiers[j], c->win, False, BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
740 } else
741 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
742 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
743 }
744}
745
746void
747grabkeys(void) {
748 updatenumlockmask();
749 { /* grab keys */
750 unsigned int i, j;
751 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
752 KeyCode code;
753
754 XUngrabKey(dpy, AnyKey, AnyModifier, root);
755 for(i = 0; i < LENGTH(keys); i++) {
756 if((code = XKeysymToKeycode(dpy, keys[i].keysym)))
757 for(j = 0; j < LENGTH(modifiers); j++)
758 XGrabKey(dpy, code, keys[i].mod | modifiers[j], root,
759 True, GrabModeAsync, GrabModeAsync);
760 }
761 }
762}
763
764void
765initfont(const char *fontstr) {
766 char *def, **missing;
767 int i, n;
768
769 missing = NULL;
770 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
771 if(missing) {
772 while(n--)
773 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
774 XFreeStringList(missing);
775 }
776 if(dc.font.set) {
777 XFontSetExtents *font_extents;
778 XFontStruct **xfonts;
779 char **font_names;
780 dc.font.ascent = dc.font.descent = 0;
781 font_extents = XExtentsOfFontSet(dc.font.set);
782 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
783 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
784 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
785 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
786 xfonts++;
787 }
788 }
789 else {
790 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
791 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
792 die("error, cannot load font: '%s'\n", fontstr);
793 dc.font.ascent = dc.font.xfont->ascent;
794 dc.font.descent = dc.font.xfont->descent;
795 }
796 dc.font.height = dc.font.ascent + dc.font.descent;
797}
798
799Bool
800isprotodel(Client *c) {
801 int i, n;
802 Atom *protocols;
803 Bool ret = False;
804
805 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
806 for(i = 0; !ret && i < n; i++)
807 if(protocols[i] == wmatom[WMDelete])
808 ret = True;
809 XFree(protocols);
810 }
811 return ret;
812}
813
814void
815keypress(XEvent *e) {
816 unsigned int i;
817 KeySym keysym;
818 XKeyEvent *ev;
819
820 ev = &e->xkey;
821 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
822 for(i = 0; i < LENGTH(keys); i++)
823 if(keysym == keys[i].keysym
824 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
825 && keys[i].func)
826 keys[i].func(&(keys[i].arg));
827}
828
829void
830killclient(const Arg *arg) {
831 XEvent ev;
832
833 if(!sel)
834 return;
835 if(isprotodel(sel)) {
836 ev.type = ClientMessage;
837 ev.xclient.window = sel->win;
838 ev.xclient.message_type = wmatom[WMProtocols];
839 ev.xclient.format = 32;
840 ev.xclient.data.l[0] = wmatom[WMDelete];
841 ev.xclient.data.l[1] = CurrentTime;
842 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
843 }
844 else
845 XKillClient(dpy, sel->win);
846}
847
848void
849manage(Window w, XWindowAttributes *wa) {
850 Client *c, *t = NULL;
851 Window trans = None;
852 XWindowChanges wc;
853
854 if(!(c = calloc(1, sizeof(Client))))
855 die("fatal: could not calloc() %u bytes\n", sizeof(Client));
856 c->win = w;
857
858 /* geometry */
859 c->x = wa->x;
860 c->y = wa->y;
861 c->w = wa->width;
862 c->h = wa->height;
863 c->oldbw = wa->border_width;
864 if(c->w == sw && c->h == sh) {
865 c->x = sx;
866 c->y = sy;
867 c->bw = 0;
868 }
869 else {
870 if(c->x + c->w + 2 * c->bw > sx + sw)
871 c->x = sx + sw - NOBORDER(c->w);
872 if(c->y + c->h + 2 * c->bw > sy + sh)
873 c->y = sy + sh - NOBORDER(c->h);
874 c->x = MAX(c->x, sx);
875 /* only fix client y-offset, if the client center might cover the bar */
876 c->y = MAX(c->y, ((by == 0) && (c->x + (c->w / 2) >= wx) && (c->x + (c->w / 2) < wx + ww)) ? bh : sy);
877 c->bw = borderpx;
878 }
879
880 wc.border_width = c->bw;
881 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
882 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
883 configure(c); /* propagates border_width, if size doesn't change */
884 updatesizehints(c);
885 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
886 grabbuttons(c, False);
887 updatetitle(c);
888 if(XGetTransientForHint(dpy, w, &trans))
889 t = getclient(trans);
890 if(t)
891 c->tags = t->tags;
892 else
893 applyrules(c);
894 if(!c->isfloating)
895 c->isfloating = trans != None || c->isfixed;
896 if(c->isfloating)
897 XRaiseWindow(dpy, c->win);
898 attach(c);
899 attachstack(c);
900 XMoveResizeWindow(dpy, c->win, c->x + 2 * sw, c->y, c->w, c->h); /* some windows require this */
901 XMapWindow(dpy, c->win);
902 setclientstate(c, NormalState);
903 arrange();
904}
905
906void
907mappingnotify(XEvent *e) {
908 XMappingEvent *ev = &e->xmapping;
909
910 XRefreshKeyboardMapping(ev);
911 if(ev->request == MappingKeyboard)
912 grabkeys();
913}
914
915void
916maprequest(XEvent *e) {
917 static XWindowAttributes wa;
918 XMapRequestEvent *ev = &e->xmaprequest;
919
920 if(!XGetWindowAttributes(dpy, ev->window, &wa))
921 return;
922 if(wa.override_redirect)
923 return;
924 if(!getclient(ev->window))
925 manage(ev->window, &wa);
926}
927
928void
929monocle(void) {
930 Client *c;
931
932 for(c = nexttiled(clients); c; c = nexttiled(c->next))
933 resize(c, wx, wy, NOBORDER(ww), NOBORDER(wh), resizehints);
934}
935
936void
937movemouse(const Arg *arg) {
938 int x, y, ocx, ocy, di, nx, ny;
939 unsigned int dui;
940 Client *c;
941 Window dummy;
942 XEvent ev;
943
944 if(!(c = sel))
945 return;
946 restack();
947 ocx = c->x;
948 ocy = c->y;
949 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
950 None, cursor[CurMove], CurrentTime) != GrabSuccess)
951 return;
952 XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui);
953 do {
954 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
955 switch (ev.type) {
956 case ConfigureRequest:
957 case Expose:
958 case MapRequest:
959 handler[ev.type](&ev);
960 break;
961 case MotionNotify:
962 XSync(dpy, False);
963 nx = ocx + (ev.xmotion.x - x);
964 ny = ocy + (ev.xmotion.y - y);
965 if(snap && nx >= wx && nx <= wx + ww
966 && ny >= wy && ny <= wy + wh) {
967 if(abs(wx - nx) < snap)
968 nx = wx;
969 else if(abs((wx + ww) - (nx + c->w + 2 * c->bw)) < snap)
970 nx = wx + ww - NOBORDER(c->w);
971 if(abs(wy - ny) < snap)
972 ny = wy;
973 else if(abs((wy + wh) - (ny + c->h + 2 * c->bw)) < snap)
974 ny = wy + wh - NOBORDER(c->h);
975 if(!c->isfloating && lt[sellt]->arrange && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
976 togglefloating(NULL);
977 }
978 if(!lt[sellt]->arrange || c->isfloating)
979 resize(c, nx, ny, c->w, c->h, False);
980 break;
981 }
982 }
983 while(ev.type != ButtonRelease);
984 XUngrabPointer(dpy, CurrentTime);
985}
986
987Client *
988nexttiled(Client *c) {
989 for(; c && (c->isfloating || !ISVISIBLE(c)); c = c->next);
990 return c;
991}
992
993void
994propertynotify(XEvent *e) {
995 Client *c;
996 Window trans;
997 XPropertyEvent *ev = &e->xproperty;
998
999 if(ev->state == PropertyDelete)
1000 return; /* ignore */
1001 if((c = getclient(ev->window))) {
1002 switch (ev->atom) {
1003 default: break;
1004 case XA_WM_TRANSIENT_FOR:
1005 XGetTransientForHint(dpy, c->win, &trans);
1006 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1007 arrange();
1008 break;
1009 case XA_WM_NORMAL_HINTS:
1010 updatesizehints(c);
1011 break;
1012 case XA_WM_HINTS:
1013 updatewmhints(c);
1014 drawbar();
1015 break;
1016 }
1017 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1018 updatetitle(c);
1019 if(c == sel)
1020 drawbar();
1021 }
1022 }
1023}
1024
1025void
1026quit(const Arg *arg) {
1027 readin = running = False;
1028}
1029
1030void
1031resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1032 XWindowChanges wc;
1033
1034 if(sizehints) {
1035 /* see last two sentences in ICCCM 4.1.2.3 */
1036 Bool baseismin = c->basew == c->minw && c->baseh == c->minh;
1037
1038 /* set minimum possible */
1039 w = MAX(1, w);
1040 h = MAX(1, h);
1041
1042 if(!baseismin) { /* temporarily remove base dimensions */
1043 w -= c->basew;
1044 h -= c->baseh;
1045 }
1046
1047 /* adjust for aspect limits */
1048 if(c->mina > 0 && c->maxa > 0) {
1049 if(c->maxa < (float)w / h)
1050 w = h * c->maxa;
1051 else if(c->mina < (float)h / w)
1052 h = w * c->mina;
1053 }
1054
1055 if(baseismin) { /* increment calculation requires this */
1056 w -= c->basew;
1057 h -= c->baseh;
1058 }
1059
1060 /* adjust for increment value */
1061 if(c->incw)
1062 w -= w % c->incw;
1063 if(c->inch)
1064 h -= h % c->inch;
1065
1066 /* restore base dimensions */
1067 w += c->basew;
1068 h += c->baseh;
1069
1070 w = MAX(w, c->minw);
1071 h = MAX(h, c->minh);
1072
1073 if(c->maxw)
1074 w = MIN(w, c->maxw);
1075
1076 if(c->maxh)
1077 h = MIN(h, c->maxh);
1078 }
1079 if(w <= 0 || h <= 0)
1080 return;
1081 if(x > sx + sw)
1082 x = sw - NOBORDER(w);
1083 if(y > sy + sh)
1084 y = sh - NOBORDER(h);
1085 if(x + w + 2 * c->bw < sx)
1086 x = sx;
1087 if(y + h + 2 * c->bw < sy)
1088 y = sy;
1089 if(h < bh)
1090 h = bh;
1091 if(w < bh)
1092 w = bh;
1093 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1094 c->x = wc.x = x;
1095 c->y = wc.y = y;
1096 c->w = wc.width = w;
1097 c->h = wc.height = h;
1098 wc.border_width = c->bw;
1099 XConfigureWindow(dpy, c->win,
1100 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1101 configure(c);
1102 XSync(dpy, False);
1103 }
1104}
1105
1106void
1107resizemouse(const Arg *arg) {
1108 int ocx, ocy;
1109 int nw, nh;
1110 Client *c;
1111 XEvent ev;
1112
1113 if(!(c = sel))
1114 return;
1115 restack();
1116 ocx = c->x;
1117 ocy = c->y;
1118 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1119 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1120 return;
1121 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1122 do {
1123 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1124 switch(ev.type) {
1125 case ConfigureRequest:
1126 case Expose:
1127 case MapRequest:
1128 handler[ev.type](&ev);
1129 break;
1130 case MotionNotify:
1131 XSync(dpy, False);
1132 nw = MAX(ev.xmotion.x - NOBORDER(ocx) + 1, 1);
1133 nh = MAX(ev.xmotion.y - NOBORDER(ocy) + 1, 1);
1134
1135 if(snap && nw >= wx && nw <= wx + ww
1136 && nh >= wy && nh <= wy + wh) {
1137 if(!c->isfloating && lt[sellt]->arrange
1138 && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1139 togglefloating(NULL);
1140 }
1141 if(!lt[sellt]->arrange || c->isfloating)
1142 resize(c, c->x, c->y, nw, nh, True);
1143 break;
1144 }
1145 }
1146 while(ev.type != ButtonRelease);
1147 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1148 XUngrabPointer(dpy, CurrentTime);
1149 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1150}
1151
1152void
1153restack(void) {
1154 Client *c;
1155 XEvent ev;
1156 XWindowChanges wc;
1157
1158 drawbar();
1159 if(!sel)
1160 return;
1161 if(sel->isfloating || !lt[sellt]->arrange)
1162 XRaiseWindow(dpy, sel->win);
1163 if(lt[sellt]->arrange) {
1164 wc.stack_mode = Below;
1165 wc.sibling = barwin;
1166 for(c = stack; c; c = c->snext)
1167 if(!c->isfloating && ISVISIBLE(c)) {
1168 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1169 wc.sibling = c->win;
1170 }
1171 }
1172 XSync(dpy, False);
1173 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1174}
1175
1176void
1177run(void) {
1178 char *p;
1179 char sbuf[sizeof stext];
1180 fd_set rd;
1181 int r, xfd;
1182 unsigned int len, offset;
1183 XEvent ev;
1184
1185 /* main event loop, also reads status text from stdin */
1186 XSync(dpy, False);
1187 xfd = ConnectionNumber(dpy);
1188 offset = 0;
1189 len = sizeof stext - 1;
1190 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1191 while(running) {
1192 FD_ZERO(&rd);
1193 if(readin)
1194 FD_SET(STDIN_FILENO, &rd);
1195 FD_SET(xfd, &rd);
1196 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1197 if(errno == EINTR)
1198 continue;
1199 die("select failed\n");
1200 }
1201 if(FD_ISSET(STDIN_FILENO, &rd)) {
1202 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1203 case -1:
1204 strncpy(stext, strerror(errno), len);
1205 readin = False;
1206 break;
1207 case 0:
1208 strncpy(stext, "EOF", 4);
1209 readin = False;
1210 break;
1211 default:
1212 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1213 if(*p == '\n' || *p == '\0') {
1214 *p = '\0';
1215 strncpy(stext, sbuf, len);
1216 p += r - 1; /* p is sbuf + offset + r - 1 */
1217 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1218 offset = r;
1219 if(r)
1220 memmove(sbuf, p - r + 1, r);
1221 break;
1222 }
1223 break;
1224 }
1225 drawbar();
1226 }
1227 while(XPending(dpy)) {
1228 XNextEvent(dpy, &ev);
1229 if(handler[ev.type])
1230 (handler[ev.type])(&ev); /* call handler */
1231 }
1232 }
1233}
1234
1235void
1236scan(void) {
1237 unsigned int i, num;
1238 Window d1, d2, *wins = NULL;
1239 XWindowAttributes wa;
1240
1241 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1242 for(i = 0; i < num; i++) {
1243 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1244 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1245 continue;
1246 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1247 manage(wins[i], &wa);
1248 }
1249 for(i = 0; i < num; i++) { /* now the transients */
1250 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1251 continue;
1252 if(XGetTransientForHint(dpy, wins[i], &d1)
1253 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1254 manage(wins[i], &wa);
1255 }
1256 if(wins)
1257 XFree(wins);
1258 }
1259}
1260
1261void
1262setclientstate(Client *c, long state) {
1263 long data[] = {state, None};
1264
1265 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1266 PropModeReplace, (unsigned char *)data, 2);
1267}
1268
1269void
1270setlayout(const Arg *arg) {
1271 if(!arg || !arg->v || arg->v != lt[sellt])
1272 sellt ^= 1;
1273 if(arg && arg->v)
1274 lt[sellt] = (Layout *)arg->v;
1275 if(sel)
1276 arrange();
1277 else
1278 drawbar();
1279}
1280
1281/* arg > 1.0 will set mfact absolutly */
1282void
1283setmfact(const Arg *arg) {
1284 float f;
1285
1286 if(!arg || !lt[sellt]->arrange)
1287 return;
1288 f = arg->f < 1.0 ? arg->f + mfact : arg->f - 1.0;
1289 if(f < 0.1 || f > 0.9)
1290 return;
1291 mfact = f;
1292 arrange();
1293}
1294
1295void
1296setup(void) {
1297 unsigned int i;
1298 int w;
1299 XSetWindowAttributes wa;
1300
1301 /* init screen */
1302 screen = DefaultScreen(dpy);
1303 root = RootWindow(dpy, screen);
1304 initfont(font);
1305 sx = 0;
1306 sy = 0;
1307 sw = DisplayWidth(dpy, screen);
1308 sh = DisplayHeight(dpy, screen);
1309 bh = dc.h = dc.font.height + 2;
1310 lt[0] = &layouts[0];
1311 lt[1] = &layouts[1 % LENGTH(layouts)];
1312 updategeom();
1313
1314 /* init atoms */
1315 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1316 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1317 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1318 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1319 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1320
1321 /* init cursors */
1322 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1323 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1324 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1325
1326 /* init appearance */
1327 dc.norm[ColBorder] = getcolor(normbordercolor);
1328 dc.norm[ColBG] = getcolor(normbgcolor);
1329 dc.norm[ColFG] = getcolor(normfgcolor);
1330 dc.sel[ColBorder] = getcolor(selbordercolor);
1331 dc.sel[ColBG] = getcolor(selbgcolor);
1332 dc.sel[ColFG] = getcolor(selfgcolor);
1333 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1334 dc.gc = XCreateGC(dpy, root, 0, 0);
1335 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1336 if(!dc.font.set)
1337 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1338
1339 /* init bar */
1340 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1341 w = TEXTW(layouts[i].symbol);
1342 blw = MAX(blw, w);
1343 }
1344
1345 wa.override_redirect = 1;
1346 wa.background_pixmap = ParentRelative;
1347 wa.event_mask = ButtonPressMask|ExposureMask;
1348
1349 barwin = XCreateWindow(dpy, root, wx, by, ww, bh, 0, DefaultDepth(dpy, screen),
1350 CopyFromParent, DefaultVisual(dpy, screen),
1351 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1352 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1353 XMapRaised(dpy, barwin);
1354 strcpy(stext, "dwm-"VERSION);
1355 drawbar();
1356
1357 /* EWMH support per view */
1358 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1359 PropModeReplace, (unsigned char *) netatom, NetLast);
1360
1361 /* select for events */
1362 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask|ButtonPressMask
1363 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1364 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1365 XSelectInput(dpy, root, wa.event_mask);
1366
1367 grabkeys();
1368}
1369
1370void
1371showhide(Client *c) {
1372 if(ISVISIBLE(c)) { /* show clients top down */
1373 XMoveWindow(dpy, c->win, c->x, c->y);
1374 if(!lt[sellt]->arrange || c->isfloating)
1375 resize(c, c->x, c->y, c->w, c->h, True);
1376 }
1377 if(c->snext) /* hide clients bottom up */
1378 showhide(c->snext);
1379 if(!ISVISIBLE(c))
1380 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
1381}
1382
1383void
1384spawn(const Arg *arg) {
1385 /* The double-fork construct avoids zombie processes and keeps the code
1386 * clean from stupid signal handlers. */
1387 if(fork() == 0) {
1388 if(fork() == 0) {
1389 if(dpy)
1390 close(ConnectionNumber(dpy));
1391 setsid();
1392 execvp(((char **)arg->v)[0], (char **)arg->v);
1393 fprintf(stderr, "dwm: execvp %s", ((char **)arg->v)[0]);
1394 perror(" failed");
1395 }
1396 exit(0);
1397 }
1398 wait(0);
1399}
1400
1401void
1402tag(const Arg *arg) {
1403 if(sel && arg->ui & TAGMASK) {
1404 sel->tags = arg->ui & TAGMASK;
1405 arrange();
1406 }
1407}
1408
1409int
1410textnw(const char *text, unsigned int len) {
1411 XRectangle r;
1412
1413 if(dc.font.set) {
1414 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1415 return r.width;
1416 }
1417 return XTextWidth(dc.font.xfont, text, len);
1418}
1419
1420void
1421tile(void) {
1422 int x, y, h, w, mw;
1423 unsigned int i, n;
1424 Client *c;
1425
1426 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next), n++);
1427 if(n == 0)
1428 return;
1429
1430 /* master */
1431 c = nexttiled(clients);
1432 mw = mfact * ww;
1433 resize(c, wx, wy, NOBORDER(n == 1 ? ww : mw), NOBORDER(wh), resizehints);
1434
1435 if(--n == 0)
1436 return;
1437
1438 /* tile stack */
1439 x = (wx + mw > c->x + c->w) ? c->x + c->w + 2 * c->bw : wx + mw;
1440 y = wy;
1441 w = (wx + mw > c->x + c->w) ? wx + ww - x : ww - mw;
1442 h = wh / n;
1443 if(h < bh)
1444 h = wh;
1445
1446 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1447 resize(c, x, y, NOBORDER(w), /* remainder */ ((i + 1 == n)
1448 ? NOBORDER(wy + wh) - y : h), resizehints);
1449 if(h != wh)
1450 y = c->y + c->h + 2 * c->bw;
1451 }
1452}
1453
1454void
1455togglebar(const Arg *arg) {
1456 showbar = !showbar;
1457 updategeom();
1458 updatebar();
1459 arrange();
1460}
1461
1462void
1463togglefloating(const Arg *arg) {
1464 if(!sel)
1465 return;
1466 sel->isfloating = !sel->isfloating || sel->isfixed;
1467 if(sel->isfloating)
1468 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1469 arrange();
1470}
1471
1472void
1473toggletag(const Arg *arg) {
1474 unsigned int mask;
1475
1476 if (!sel)
1477 return;
1478
1479 mask = sel->tags ^ (arg->ui & TAGMASK);
1480 if(sel && mask) {
1481 sel->tags = mask;
1482 arrange();
1483 }
1484}
1485
1486void
1487toggleview(const Arg *arg) {
1488 unsigned int mask = tagset[seltags] ^ (arg->ui & TAGMASK);
1489
1490 if(mask) {
1491 tagset[seltags] = mask;
1492 clearurgent();
1493 arrange();
1494 }
1495}
1496
1497void
1498unmanage(Client *c) {
1499 XWindowChanges wc;
1500
1501 wc.border_width = c->oldbw;
1502 /* The server grab construct avoids race conditions. */
1503 XGrabServer(dpy);
1504 XSetErrorHandler(xerrordummy);
1505 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1506 detach(c);
1507 detachstack(c);
1508 if(sel == c)
1509 focus(NULL);
1510 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1511 setclientstate(c, WithdrawnState);
1512 free(c);
1513 XSync(dpy, False);
1514 XSetErrorHandler(xerror);
1515 XUngrabServer(dpy);
1516 arrange();
1517}
1518
1519void
1520unmapnotify(XEvent *e) {
1521 Client *c;
1522 XUnmapEvent *ev = &e->xunmap;
1523
1524 if((c = getclient(ev->window)))
1525 unmanage(c);
1526}
1527
1528void
1529updatebar(void) {
1530 if(dc.drawable != 0)
1531 XFreePixmap(dpy, dc.drawable);
1532 dc.drawable = XCreatePixmap(dpy, root, ww, bh, DefaultDepth(dpy, screen));
1533 XMoveResizeWindow(dpy, barwin, wx, by, ww, bh);
1534}
1535
1536void
1537updategeom(void) {
1538#ifdef XINERAMA
1539 int n, i = 0;
1540 XineramaScreenInfo *info = NULL;
1541
1542 /* window area geometry */
1543 if(XineramaIsActive(dpy) && (info = XineramaQueryScreens(dpy, &n))) {
1544 if(n > 1) {
1545 int di, x, y;
1546 unsigned int dui;
1547 Window dummy;
1548 if(XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui))
1549 for(i = 0; i < n; i++)
1550 if(INRECT(x, y, info[i].x_org, info[i].y_org, info[i].width, info[i].height))
1551 break;
1552 }
1553 wx = info[i].x_org;
1554 wy = showbar && topbar ? info[i].y_org + bh : info[i].y_org;
1555 ww = info[i].width;
1556 wh = showbar ? info[i].height - bh : info[i].height;
1557 XFree(info);
1558 }
1559 else
1560#endif
1561 {
1562 wx = sx;
1563 wy = showbar && topbar ? sy + bh : sy;
1564 ww = sw;
1565 wh = showbar ? sh - bh : sh;
1566 }
1567
1568 /* bar position */
1569 by = showbar ? (topbar ? wy - bh : wy + wh) : -bh;
1570}
1571
1572void
1573updatenumlockmask(void) {
1574 unsigned int i, j;
1575 XModifierKeymap *modmap;
1576
1577 numlockmask = 0;
1578 modmap = XGetModifierMapping(dpy);
1579 for(i = 0; i < 8; i++)
1580 for(j = 0; j < modmap->max_keypermod; j++)
1581 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
1582 numlockmask = (1 << i);
1583 XFreeModifiermap(modmap);
1584}
1585
1586void
1587updatesizehints(Client *c) {
1588 long msize;
1589 XSizeHints size;
1590
1591 XGetWMNormalHints(dpy, c->win, &size, &msize);
1592 if(size.flags & PBaseSize) {
1593 c->basew = size.base_width;
1594 c->baseh = size.base_height;
1595 }
1596 else if(size.flags & PMinSize) {
1597 c->basew = size.min_width;
1598 c->baseh = size.min_height;
1599 }
1600 else
1601 c->basew = c->baseh = 0;
1602 if(size.flags & PResizeInc) {
1603 c->incw = size.width_inc;
1604 c->inch = size.height_inc;
1605 }
1606 else
1607 c->incw = c->inch = 0;
1608 if(size.flags & PMaxSize) {
1609 c->maxw = size.max_width;
1610 c->maxh = size.max_height;
1611 }
1612 else
1613 c->maxw = c->maxh = 0;
1614 if(size.flags & PMinSize) {
1615 c->minw = size.min_width;
1616 c->minh = size.min_height;
1617 }
1618 else if(size.flags & PBaseSize) {
1619 c->minw = size.base_width;
1620 c->minh = size.base_height;
1621 }
1622 else
1623 c->minw = c->minh = 0;
1624 if(size.flags & PAspect) {
1625 c->mina = (float)size.min_aspect.y / (float)size.min_aspect.x;
1626 c->maxa = (float)size.max_aspect.x / (float)size.max_aspect.y;
1627 }
1628 else
1629 c->maxa = c->mina = 0.0;
1630 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1631 && c->maxw == c->minw && c->maxh == c->minh);
1632}
1633
1634void
1635updatetitle(Client *c) {
1636 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1637 gettextprop(c->win, XA_WM_NAME, c->name, sizeof c->name);
1638}
1639
1640void
1641updatewmhints(Client *c) {
1642 XWMHints *wmh;
1643
1644 if((wmh = XGetWMHints(dpy, c->win))) {
1645 if(ISVISIBLE(c) && wmh->flags & XUrgencyHint) {
1646 wmh->flags &= ~XUrgencyHint;
1647 XSetWMHints(dpy, c->win, wmh);
1648 }
1649 else
1650 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1651
1652 XFree(wmh);
1653 }
1654}
1655
1656void
1657view(const Arg *arg) {
1658 if((arg->ui & TAGMASK) == tagset[seltags])
1659 return;
1660 seltags ^= 1; /* toggle sel tagset */
1661 if(arg->ui & TAGMASK)
1662 tagset[seltags] = arg->ui & TAGMASK;
1663 clearurgent();
1664 arrange();
1665}
1666
1667/* There's no way to check accesses to destroyed windows, thus those cases are
1668 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1669 * default error handler, which may call exit. */
1670int
1671xerror(Display *dpy, XErrorEvent *ee) {
1672 if(ee->error_code == BadWindow
1673 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1674 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1675 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1676 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1677 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1678 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1679 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1680 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1681 return 0;
1682 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1683 ee->request_code, ee->error_code);
1684 return xerrorxlib(dpy, ee); /* may call exit */
1685}
1686
1687int
1688xerrordummy(Display *dpy, XErrorEvent *ee) {
1689 return 0;
1690}
1691
1692/* Startup Error handler to check if another window manager
1693 * is already running. */
1694int
1695xerrorstart(Display *dpy, XErrorEvent *ee) {
1696 otherwm = True;
1697 return -1;
1698}
1699
1700void
1701zoom(const Arg *arg) {
1702 Client *c = sel;
1703
1704 if(!lt[sellt]->arrange || lt[sellt]->arrange == monocle || (sel && sel->isfloating))
1705 return;
1706 if(c == nexttiled(clients))
1707 if(!c || !(c = nexttiled(c->next)))
1708 return;
1709 detach(c);
1710 attach(c);
1711 focus(c);
1712 arrange();
1713}
1714
1715int
1716main(int argc, char *argv[]) {
1717 if(argc == 2 && !strcmp("-v", argv[1]))
1718 die("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1719 else if(argc != 1)
1720 die("usage: dwm [-v]\n");
1721
1722 if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
1723 fprintf(stderr, "warning: no locale support\n");
1724
1725 if(!(dpy = XOpenDisplay(0)))
1726 die("dwm: cannot open display\n");
1727
1728 checkotherwm();
1729 setup();
1730 scan();
1731 run();
1732 cleanup();
1733
1734 XCloseDisplay(dpy);
1735 return 0;
1736}