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