Xinqi Bao's Git

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