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