Xinqi Bao's Git

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