Xinqi Bao's Git

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