Xinqi Bao's Git

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