Xinqi Bao's Git

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