Xinqi Bao's Git

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