Xinqi Bao's Git

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