Xinqi Bao's Git

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