Xinqi Bao's Git

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