Xinqi Bao's Git

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