Xinqi Bao's Git

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