Xinqi Bao's Git

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