Xinqi Bao's Git

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