Xinqi Bao's Git

85292a9989775bc9d472a87801f989c037c438c3
[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 /* only fix client y-offset, if the client center might cover the bar */
917 c->y = MAX(c->y, ((by == 0) && (c->x + (c->w / 2) >= wx) && (c->x + (c->w / 2) < wx + ww)) ? bh : sy);
918 c->bw = borderpx;
919 }
920
921 wc.border_width = c->bw;
922 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
923 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
924 configure(c); /* propagates border_width, if size doesn't change */
925 updatesizehints(c);
926 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
927 grabbuttons(c, False);
928 updatetitle(c);
929 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
930 for(t = clients; t && t->win != trans; t = t->next);
931 if(t)
932 c->tags = t->tags;
933 else
934 applyrules(c);
935 if(!c->isfloating)
936 c->isfloating = (rettrans == Success) || c->isfixed;
937 if(c->isfloating)
938 XRaiseWindow(dpy, c->win);
939 attach(c);
940 attachstack(c);
941 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
942 XMapWindow(dpy, c->win);
943 setclientstate(c, NormalState);
944 arrange();
945 }
946
947 void
948 mappingnotify(XEvent *e) {
949 XMappingEvent *ev = &e->xmapping;
950
951 XRefreshKeyboardMapping(ev);
952 if(ev->request == MappingKeyboard)
953 grabkeys();
954 }
955
956 void
957 maprequest(XEvent *e) {
958 static XWindowAttributes wa;
959 XMapRequestEvent *ev = &e->xmaprequest;
960
961 if(!XGetWindowAttributes(dpy, ev->window, &wa))
962 return;
963 if(wa.override_redirect)
964 return;
965 if(!getclient(ev->window))
966 manage(ev->window, &wa);
967 }
968
969 void
970 movemouse(const Arg *arg) {
971 int x1, y1, ocx, ocy, di, nx, ny;
972 uint dui;
973 Client *c;
974 Window dummy;
975 XEvent ev;
976
977 if(!(c = sel))
978 return;
979 restack();
980 ocx = nx = c->x;
981 ocy = ny = c->y;
982 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
983 None, cursor[CurMove], CurrentTime) != GrabSuccess)
984 return;
985 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
986 for(;;) {
987 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
988 switch (ev.type) {
989 case ButtonRelease:
990 XUngrabPointer(dpy, CurrentTime);
991 return;
992 case ConfigureRequest:
993 case Expose:
994 case MapRequest:
995 handler[ev.type](&ev);
996 break;
997 case MotionNotify:
998 XSync(dpy, False);
999 nx = ocx + (ev.xmotion.x - x1);
1000 ny = ocy + (ev.xmotion.y - y1);
1001 if(snap && nx >= wx && nx <= wx + ww
1002 && ny >= wy && ny <= wy + wh) {
1003 if(abs(wx - nx) < snap)
1004 nx = wx;
1005 else if(abs((wx + ww) - (nx + c->w + 2 * c->bw)) < snap)
1006 nx = wx + ww - c->w - 2 * c->bw;
1007 if(abs(wy - ny) < snap)
1008 ny = wy;
1009 else if(abs((wy + wh) - (ny + c->h + 2 * c->bw)) < snap)
1010 ny = wy + wh - c->h - 2 * c->bw;
1011 if(!c->isfloating && lt->arrange && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
1012 togglefloating(NULL);
1013 }
1014 if(!lt->arrange || c->isfloating)
1015 resize(c, nx, ny, c->w, c->h, False);
1016 break;
1017 }
1018 }
1019 }
1020
1021 Client *
1022 nexttiled(Client *c) {
1023 for(; c && (c->isfloating || c->isbanned); c = c->next);
1024 return c;
1025 }
1026
1027 void
1028 propertynotify(XEvent *e) {
1029 Client *c;
1030 Window trans;
1031 XPropertyEvent *ev = &e->xproperty;
1032
1033 if(ev->state == PropertyDelete)
1034 return; /* ignore */
1035 if((c = getclient(ev->window))) {
1036 switch (ev->atom) {
1037 default: break;
1038 case XA_WM_TRANSIENT_FOR:
1039 XGetTransientForHint(dpy, c->win, &trans);
1040 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1041 arrange();
1042 break;
1043 case XA_WM_NORMAL_HINTS:
1044 updatesizehints(c);
1045 break;
1046 case XA_WM_HINTS:
1047 updatewmhints(c);
1048 drawbar();
1049 break;
1050 }
1051 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1052 updatetitle(c);
1053 if(c == sel)
1054 drawbar();
1055 }
1056 }
1057 }
1058
1059 void
1060 quit(const Arg *arg) {
1061 readin = running = False;
1062 }
1063
1064 void
1065 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1066 XWindowChanges wc;
1067
1068 if(sizehints) {
1069 /* set minimum possible */
1070 w = MAX(1, w);
1071 h = MAX(1, h);
1072
1073 /* temporarily remove base dimensions */
1074 w -= c->basew;
1075 h -= c->baseh;
1076
1077 /* adjust for aspect limits */
1078 if(c->mina > 0 && c->maxa > 0) {
1079 if(c->maxa < (float) w/h)
1080 w = h * c->maxa;
1081 else if(c->mina > (float) h/w)
1082 h = w * c->mina;
1083 }
1084
1085 /* adjust for increment value */
1086 if(c->incw)
1087 w -= w % c->incw;
1088 if(c->inch)
1089 h -= h % c->inch;
1090
1091 /* restore base dimensions */
1092 w += c->basew;
1093 h += c->baseh;
1094
1095 w = MAX(w, c->minw);
1096 h = MAX(h, c->minh);
1097
1098 if(c->maxw)
1099 w = MIN(w, c->maxw);
1100
1101 if(c->maxh)
1102 h = MIN(h, c->maxh);
1103 }
1104 if(w <= 0 || h <= 0)
1105 return;
1106 if(x > sx + sw)
1107 x = sw - w - 2 * c->bw;
1108 if(y > sy + sh)
1109 y = sh - h - 2 * c->bw;
1110 if(x + w + 2 * c->bw < sx)
1111 x = sx;
1112 if(y + h + 2 * c->bw < sy)
1113 y = sy;
1114 if(h < bh)
1115 h = bh;
1116 if(w < bh)
1117 w = bh;
1118 if(c->x != x || c->y != y || c->w != w || c->h != h || c->ismoved) {
1119 c->ismoved = False;
1120 c->x = wc.x = x;
1121 c->y = wc.y = y;
1122 c->w = wc.width = w;
1123 c->h = wc.height = h;
1124 wc.border_width = c->bw;
1125 XConfigureWindow(dpy, c->win,
1126 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1127 configure(c);
1128 XSync(dpy, False);
1129 }
1130 }
1131
1132 void
1133 resizemouse(const Arg *arg) {
1134 int ocx, ocy;
1135 int nw, nh;
1136 Client *c;
1137 XEvent ev;
1138
1139 if(!(c = sel))
1140 return;
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.h = dc.font.height + 2;
1328 lt = layouts;
1329 updategeom();
1330
1331 /* init atoms */
1332 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1333 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1334 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1335 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1336 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1337 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1338
1339 /* init cursors */
1340 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1341 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1342 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1343
1344 /* init appearance */
1345 dc.norm[ColBorder] = getcolor(normbordercolor);
1346 dc.norm[ColBG] = getcolor(normbgcolor);
1347 dc.norm[ColFG] = getcolor(normfgcolor);
1348 dc.sel[ColBorder] = getcolor(selbordercolor);
1349 dc.sel[ColBG] = getcolor(selbgcolor);
1350 dc.sel[ColFG] = getcolor(selfgcolor);
1351 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1352 dc.gc = XCreateGC(dpy, root, 0, 0);
1353 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1354 if(!dc.font.set)
1355 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1356
1357 /* init bar */
1358 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1359 w = TEXTW(layouts[i].symbol);
1360 blw = MAX(blw, w);
1361 }
1362
1363 wa.override_redirect = 1;
1364 wa.background_pixmap = ParentRelative;
1365 wa.event_mask = ButtonPressMask|ExposureMask;
1366
1367 barwin = XCreateWindow(dpy, root, wx, by, ww, bh, 0, DefaultDepth(dpy, screen),
1368 CopyFromParent, DefaultVisual(dpy, screen),
1369 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1370 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1371 XMapRaised(dpy, barwin);
1372 strcpy(stext, "dwm-"VERSION);
1373 drawbar();
1374
1375 /* EWMH support per view */
1376 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1377 PropModeReplace, (unsigned char *) netatom, NetLast);
1378
1379 /* select for events */
1380 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask|ButtonPressMask
1381 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1382 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1383 XSelectInput(dpy, root, wa.event_mask);
1384
1385
1386 /* grab keys */
1387 grabkeys();
1388 }
1389
1390 void
1391 spawn(const Arg *arg) {
1392 /* The double-fork construct avoids zombie processes and keeps the code
1393 * clean from stupid signal handlers. */
1394 if(fork() == 0) {
1395 if(fork() == 0) {
1396 if(dpy)
1397 close(ConnectionNumber(dpy));
1398 setsid();
1399 execvp(((char **)arg->v)[0], (char **)arg->v);
1400 fprintf(stderr, "dwm: execvp %s", ((char **)arg->v)[0]);
1401 perror(" failed");
1402 }
1403 exit(0);
1404 }
1405 wait(0);
1406 }
1407
1408 void
1409 tag(const Arg *arg) {
1410 if(sel && arg->ui & TAGMASK) {
1411 sel->tags = arg->ui & TAGMASK;
1412 arrange();
1413 }
1414 }
1415
1416 int
1417 textnw(const char *text, uint len) {
1418 XRectangle r;
1419
1420 if(dc.font.set) {
1421 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1422 return r.width;
1423 }
1424 return XTextWidth(dc.font.xfont, text, len);
1425 }
1426
1427 void
1428 tile(void) {
1429 int x, y, h, w, mw;
1430 uint i, n;
1431 Client *c;
1432
1433 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next), n++);
1434 if(n == 0)
1435 return;
1436
1437 /* master */
1438 c = nexttiled(clients);
1439 mw = mfact * ww;
1440 resize(c, wx, wy, (n == 1 ? ww : mw) - 2 * c->bw, wh - 2 * c->bw, resizehints);
1441
1442 if(--n == 0)
1443 return;
1444
1445 /* tile stack */
1446 x = (wx + mw > c->x + c->w) ? c->x + c->w + 2 * c->bw : wx + mw;
1447 y = wy;
1448 w = (wx + mw > c->x + c->w) ? wx + ww - x : ww - mw;
1449 h = wh / n;
1450 if(h < bh)
1451 h = wh;
1452
1453 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1454 resize(c, x, y, w - 2 * c->bw, /* remainder */ ((i + 1 == n)
1455 ? (wy + wh) - y : h) - 2 * c->bw, resizehints);
1456 if(h != wh)
1457 y = c->y + c->h + 2 * c->bw;
1458 }
1459 }
1460
1461 void
1462 togglebar(const Arg *arg) {
1463 showbar = !showbar;
1464 updategeom();
1465 updatebar();
1466 arrange();
1467 }
1468
1469 void
1470 togglefloating(const Arg *arg) {
1471 if(!sel)
1472 return;
1473 sel->isfloating = !sel->isfloating || sel->isfixed;
1474 if(sel->isfloating)
1475 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1476 arrange();
1477 }
1478
1479 void
1480 togglelayout(const Arg *arg) {
1481 if(arg && arg->v)
1482 lt = (Layout *)arg->v;
1483 else if(++lt == &layouts[LENGTH(layouts)])
1484 lt = &layouts[0];
1485 if(sel)
1486 arrange();
1487 else
1488 drawbar();
1489 }
1490
1491 void
1492 togglemax(const Arg *arg) {
1493 ismax = !ismax;
1494 arrange();
1495 }
1496
1497 void
1498 toggletag(const Arg *arg) {
1499 uint mask = sel->tags ^ (arg->ui & TAGMASK);
1500
1501 if(sel && mask) {
1502 sel->tags = mask;
1503 arrange();
1504 }
1505 }
1506
1507 void
1508 toggleview(const Arg *arg) {
1509 uint mask = tagset[seltags] ^ (arg->ui & TAGMASK);
1510
1511 if(mask) {
1512 tagset[seltags] = mask;
1513 arrange();
1514 }
1515 }
1516
1517 void
1518 unmanage(Client *c) {
1519 XWindowChanges wc;
1520
1521 wc.border_width = c->oldbw;
1522 /* The server grab construct avoids race conditions. */
1523 XGrabServer(dpy);
1524 XSetErrorHandler(xerrordummy);
1525 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1526 detach(c);
1527 detachstack(c);
1528 if(sel == c)
1529 focus(NULL);
1530 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1531 setclientstate(c, WithdrawnState);
1532 free(c);
1533 XSync(dpy, False);
1534 XSetErrorHandler(xerror);
1535 XUngrabServer(dpy);
1536 arrange();
1537 }
1538
1539 void
1540 unmapnotify(XEvent *e) {
1541 Client *c;
1542 XUnmapEvent *ev = &e->xunmap;
1543
1544 if((c = getclient(ev->window)))
1545 unmanage(c);
1546 }
1547
1548 void
1549 updatebar(void) {
1550 if(dc.drawable != 0)
1551 XFreePixmap(dpy, dc.drawable);
1552 dc.drawable = XCreatePixmap(dpy, root, ww, bh, DefaultDepth(dpy, screen));
1553 XMoveResizeWindow(dpy, barwin, wx, by, ww, bh);
1554 }
1555
1556 void
1557 updategeom(void) {
1558 #ifdef XINERAMA
1559 int i;
1560 XineramaScreenInfo *info = NULL;
1561
1562 /* window area geometry */
1563 if(XineramaIsActive(dpy)) {
1564 info = XineramaQueryScreens(dpy, &i);
1565 wx = info[xidx].x_org;
1566 wy = showbar && topbar ? info[xidx].y_org + bh : info[xidx].y_org;
1567 ww = info[xidx].width;
1568 wh = showbar ? info[xidx].height - bh : info[xidx].height;
1569 XFree(info);
1570 }
1571 else
1572 #endif
1573 {
1574 wx = sx;
1575 wy = showbar && topbar ? sy + bh : sy;
1576 ww = sw;
1577 wh = showbar ? sh - bh : sh;
1578 }
1579
1580 /* bar position */
1581 by = showbar ? (topbar ? wy - bh : wy + wh) : -bh;
1582 }
1583
1584 void
1585 updatesizehints(Client *c) {
1586 long msize;
1587 XSizeHints size;
1588
1589 XGetWMNormalHints(dpy, c->win, &size, &msize);
1590 if(size.flags & PBaseSize) {
1591 c->basew = size.base_width;
1592 c->baseh = size.base_height;
1593 }
1594 else if(size.flags & PMinSize) {
1595 c->basew = size.min_width;
1596 c->baseh = size.min_height;
1597 }
1598 else
1599 c->basew = c->baseh = 0;
1600 if(size.flags & PResizeInc) {
1601 c->incw = size.width_inc;
1602 c->inch = size.height_inc;
1603 }
1604 else
1605 c->incw = c->inch = 0;
1606 if(size.flags & PMaxSize) {
1607 c->maxw = size.max_width;
1608 c->maxh = size.max_height;
1609 }
1610 else
1611 c->maxw = c->maxh = 0;
1612 if(size.flags & PMinSize) {
1613 c->minw = size.min_width;
1614 c->minh = size.min_height;
1615 }
1616 else if(size.flags & PBaseSize) {
1617 c->minw = size.base_width;
1618 c->minh = size.base_height;
1619 }
1620 else
1621 c->minw = c->minh = 0;
1622 if(size.flags & PAspect) {
1623 c->mina = (float)size.min_aspect.y / (float)size.min_aspect.x;
1624 c->maxa = (float)size.max_aspect.x / (float)size.max_aspect.y;
1625 }
1626 else
1627 c->maxa = c->mina = 0.0;
1628 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1629 && c->maxw == c->minw && c->maxh == c->minh);
1630 }
1631
1632 void
1633 updatetitle(Client *c) {
1634 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1635 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1636 }
1637
1638 void
1639 updatewmhints(Client *c) {
1640 XWMHints *wmh;
1641
1642 if((wmh = XGetWMHints(dpy, c->win))) {
1643 if(c == sel)
1644 sel->isurgent = False;
1645 else
1646 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1647 XFree(wmh);
1648 }
1649 }
1650
1651 void
1652 view(const Arg *arg) {
1653 seltags ^= 1; /* toggle sel tagset */
1654 if(arg && (arg->ui & TAGMASK))
1655 tagset[seltags] = arg->i & TAGMASK;
1656 arrange();
1657 }
1658
1659 /* There's no way to check accesses to destroyed windows, thus those cases are
1660 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1661 * default error handler, which may call exit. */
1662 int
1663 xerror(Display *dpy, XErrorEvent *ee) {
1664 if(ee->error_code == BadWindow
1665 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1666 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1667 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1668 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1669 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1670 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1671 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1672 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1673 return 0;
1674 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1675 ee->request_code, ee->error_code);
1676 return xerrorxlib(dpy, ee); /* may call exit */
1677 }
1678
1679 int
1680 xerrordummy(Display *dpy, XErrorEvent *ee) {
1681 return 0;
1682 }
1683
1684 /* Startup Error handler to check if another window manager
1685 * is already running. */
1686 int
1687 xerrorstart(Display *dpy, XErrorEvent *ee) {
1688 otherwm = True;
1689 return -1;
1690 }
1691
1692 void
1693 zoom(const Arg *arg) {
1694 Client *c = sel;
1695
1696 if(ismax || !lt->arrange || (sel && sel->isfloating))
1697 return;
1698 if(c == nexttiled(clients))
1699 if(!c || !(c = nexttiled(c->next)))
1700 return;
1701 detach(c);
1702 attach(c);
1703 focus(c);
1704 arrange();
1705 }
1706
1707 int
1708 main(int argc, char *argv[]) {
1709 if(argc == 2 && !strcmp("-v", argv[1]))
1710 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1711 else if(argc != 1)
1712 eprint("usage: dwm [-v]\n");
1713
1714 setlocale(LC_CTYPE, "");
1715 if(!(dpy = XOpenDisplay(0)))
1716 eprint("dwm: cannot open display\n");
1717
1718 checkotherwm();
1719 setup();
1720 scan();
1721 run();
1722 cleanup();
1723
1724 XCloseDisplay(dpy);
1725 return 0;
1726 }