Xinqi Bao's Git

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