Xinqi Bao's Git

added a comment about FAQ regarding mfact meaning
[dwm.git] / dwm.c
1 /* See LICENSE file for copyright and license details.
2 *
3 * dynamic window manager is designed like any other X client as well. It is
4 * driven through handling X events. In contrast to other X clients, a window
5 * manager selects for SubstructureRedirectMask on the root window, to receive
6 * events about window (dis-)appearance. Only one X connection at a time is
7 * allowed to select for this event mask.
8 *
9 * Calls to fetch an X event from the event queue are blocking. Due reading
10 * status text from standard input, a select()-driven main loop has been
11 * implemented which selects for reads on the X connection and STDIN_FILENO to
12 * handle all data smoothly. The event handlers of dwm are organized in an
13 * array which is accessed whenever a new event has been fetched. This allows
14 * event dispatching in O(1) time.
15 *
16 * Each child of the root window is called a client, except windows which have
17 * set the override_redirect flag. Clients are organized in a global
18 * doubly-linked client list, the focus history is remembered through a global
19 * stack list. Each client contains a bit array to indicate the tags of a
20 * client.
21 *
22 * Keys and tagging rules are organized as arrays and defined in config.h.
23 *
24 * To understand everything else, start reading main().
25 */
26 #include <errno.h>
27 #include <locale.h>
28 #include <stdarg.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <unistd.h>
33 #include <sys/select.h>
34 #include <sys/types.h>
35 #include <sys/wait.h>
36 #include <X11/cursorfont.h>
37 #include <X11/keysym.h>
38 #include <X11/Xatom.h>
39 #include <X11/Xlib.h>
40 #include <X11/Xproto.h>
41 #include <X11/Xutil.h>
42 #ifdef XINERAMA
43 #include <X11/extensions/Xinerama.h>
44 #endif
45
46 /* macros */
47 #define 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 TAGMASK ((int)((1LL << LENGTH(tags)) - 1))
57 #define TEXTW(x) (textnw(x, strlen(x)) + dc.font.height)
58
59 /* enums */
60 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
61 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
62 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
63 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
64 enum { ClkTagBar, ClkLtSymbol, ClkStatusText, ClkWinTitle,
65 ClkClientWin, ClkRootWin, ClkLast }; /* clicks */
66
67 typedef union {
68 int i;
69 unsigned int ui;
70 float f;
71 void *v;
72 } Arg;
73
74 typedef struct {
75 unsigned int click;
76 unsigned int mask;
77 unsigned int button;
78 void (*func)(const Arg *arg);
79 const Arg arg;
80 } Button;
81
82 typedef struct Client Client;
83 struct Client {
84 char name[256];
85 float mina, maxa;
86 int x, y, w, h;
87 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
88 int bw, oldbw;
89 unsigned int tags;
90 Bool isfixed, isfloating, isurgent;
91 Client *next;
92 Client *snext;
93 Window win;
94 };
95
96 typedef struct {
97 int x, y, w, h;
98 unsigned long norm[ColLast];
99 unsigned long sel[ColLast];
100 Drawable drawable;
101 GC gc;
102 struct {
103 int ascent;
104 int descent;
105 int height;
106 XFontSet set;
107 XFontStruct *xfont;
108 } font;
109 } DC; /* draw context */
110
111 typedef struct {
112 unsigned int mod;
113 KeySym keysym;
114 void (*func)(const Arg *);
115 const Arg arg;
116 } Key;
117
118 typedef struct {
119 const char *symbol;
120 void (*arrange)(void);
121 } Layout;
122
123 typedef struct {
124 const char *class;
125 const char *instance;
126 const char *title;
127 unsigned int tags;
128 Bool isfloating;
129 } Rule;
130
131 /* function declarations */
132 static void applyrules(Client *c);
133 static void arrange(void);
134 static void attach(Client *c);
135 static void attachstack(Client *c);
136 static void buttonpress(XEvent *e);
137 static void checkotherwm(void);
138 static void cleanup(void);
139 static void clearurgent(void);
140 static void configure(Client *c);
141 static void configurenotify(XEvent *e);
142 static void configurerequest(XEvent *e);
143 static void destroynotify(XEvent *e);
144 static void detach(Client *c);
145 static void detachstack(Client *c);
146 static void die(const char *errstr, ...);
147 static void drawbar(void);
148 static void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
149 static void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
150 static void enternotify(XEvent *e);
151 static void expose(XEvent *e);
152 static void focus(Client *c);
153 static void focusin(XEvent *e);
154 static void focusstack(const Arg *arg);
155 static Client *getclient(Window w);
156 static unsigned long getcolor(const char *colstr);
157 static long getstate(Window w);
158 static Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
159 static void grabbuttons(Client *c, Bool focused);
160 static void grabkeys(void);
161 static void initfont(const char *fontstr);
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; /* display 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 int i, x, y, h, len, olen;
573 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
574 char buf[256];
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 len = MIN(olen, sizeof buf);
582 memcpy(buf, text, len);
583 h = dc.font.ascent + dc.font.descent;
584 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
585 x = dc.x + (h / 2);
586 /* shorten text if necessary */
587 for(; len && (i = textnw(buf, len)) > dc.w - h; len--);
588 if(!len)
589 return;
590 if(len < olen)
591 for(i = len; i && i > len - 3; buf[--i] = '.');
592 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
593 if(dc.font.set)
594 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
595 else
596 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
597 }
598
599 void
600 enternotify(XEvent *e) {
601 Client *c;
602 XCrossingEvent *ev = &e->xcrossing;
603
604 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
605 return;
606 if((c = getclient(ev->window)))
607 focus(c);
608 else
609 focus(NULL);
610 }
611
612 void
613 expose(XEvent *e) {
614 XExposeEvent *ev = &e->xexpose;
615
616 if(ev->count == 0 && (ev->window == barwin))
617 drawbar();
618 }
619
620 void
621 focus(Client *c) {
622 if(!c || !ISVISIBLE(c))
623 for(c = stack; c && !ISVISIBLE(c); c = c->snext);
624 if(sel && sel != c) {
625 grabbuttons(sel, False);
626 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
627 }
628 if(c) {
629 detachstack(c);
630 attachstack(c);
631 grabbuttons(c, True);
632 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
633 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
634 }
635 else
636 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
637 sel = c;
638 drawbar();
639 }
640
641 void
642 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
643 XFocusChangeEvent *ev = &e->xfocus;
644
645 if(sel && ev->window != sel->win)
646 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
647 }
648
649 void
650 focusstack(const Arg *arg) {
651 Client *c = NULL, *i;
652
653 if(!sel)
654 return;
655 if (arg->i > 0) {
656 for(c = sel->next; c && !ISVISIBLE(c); c = c->next);
657 if(!c)
658 for(c = clients; c && !ISVISIBLE(c); c = c->next);
659 }
660 else {
661 for(i = clients; i != sel; i = i->next)
662 if(ISVISIBLE(i))
663 c = i;
664 if(!c)
665 for(; i; i = i->next)
666 if(ISVISIBLE(i))
667 c = i;
668 }
669 if(c) {
670 focus(c);
671 restack();
672 }
673 }
674
675 Client *
676 getclient(Window w) {
677 Client *c;
678
679 for(c = clients; c && c->win != w; c = c->next);
680 return c;
681 }
682
683 unsigned long
684 getcolor(const char *colstr) {
685 Colormap cmap = DefaultColormap(dpy, screen);
686 XColor color;
687
688 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
689 die("error, cannot allocate color '%s'\n", colstr);
690 return color.pixel;
691 }
692
693 long
694 getstate(Window w) {
695 int format, status;
696 long result = -1;
697 unsigned char *p = NULL;
698 unsigned long n, extra;
699 Atom real;
700
701 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
702 &real, &format, &n, &extra, (unsigned char **)&p);
703 if(status != Success)
704 return -1;
705 if(n != 0)
706 result = *p;
707 XFree(p);
708 return result;
709 }
710
711 Bool
712 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
713 char **list = NULL;
714 int n;
715 XTextProperty name;
716
717 if(!text || size == 0)
718 return False;
719 text[0] = '\0';
720 XGetTextProperty(dpy, w, &name, atom);
721 if(!name.nitems)
722 return False;
723 if(name.encoding == XA_STRING)
724 strncpy(text, (char *)name.value, size - 1);
725 else {
726 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
727 && n > 0 && *list) {
728 strncpy(text, *list, size - 1);
729 XFreeStringList(list);
730 }
731 }
732 text[size - 1] = '\0';
733 XFree(name.value);
734 return True;
735 }
736
737 void
738 grabbuttons(Client *c, Bool focused) {
739 unsigned int i, j;
740 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
741
742 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
743 if(focused) {
744 for(i = 0; i < LENGTH(buttons); i++)
745 if(buttons[i].click == ClkClientWin)
746 for(j = 0; j < LENGTH(modifiers); j++)
747 XGrabButton(dpy, buttons[i].button, buttons[i].mask | modifiers[j], c->win, False, BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
748 } else
749 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
750 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
751 }
752
753 void
754 grabkeys(void) {
755 unsigned int i, j;
756 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
757 KeyCode code;
758 XModifierKeymap *modmap;
759
760 /* init modifier map */
761 modmap = XGetModifierMapping(dpy);
762 for(i = 0; i < 8; i++)
763 for(j = 0; j < modmap->max_keypermod; j++) {
764 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
765 numlockmask = (1 << i);
766 }
767 XFreeModifiermap(modmap);
768
769 XUngrabKey(dpy, AnyKey, AnyModifier, root);
770 for(i = 0; i < LENGTH(keys); i++) {
771 code = XKeysymToKeycode(dpy, keys[i].keysym);
772 for(j = 0; j < LENGTH(modifiers); j++)
773 XGrabKey(dpy, code, keys[i].mod | modifiers[j], root, True,
774 GrabModeAsync, GrabModeAsync);
775 }
776 }
777
778 void
779 initfont(const char *fontstr) {
780 char *def, **missing;
781 int i, n;
782
783 missing = NULL;
784 if(dc.font.set)
785 XFreeFontSet(dpy, dc.font.set);
786 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
787 if(missing) {
788 while(n--)
789 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
790 XFreeStringList(missing);
791 }
792 if(dc.font.set) {
793 XFontSetExtents *font_extents;
794 XFontStruct **xfonts;
795 char **font_names;
796 dc.font.ascent = dc.font.descent = 0;
797 font_extents = XExtentsOfFontSet(dc.font.set);
798 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
799 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
800 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
801 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
802 xfonts++;
803 }
804 }
805 else {
806 if(dc.font.xfont)
807 XFreeFont(dpy, dc.font.xfont);
808 dc.font.xfont = NULL;
809 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
810 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
811 die("error, cannot load font: '%s'\n", fontstr);
812 dc.font.ascent = dc.font.xfont->ascent;
813 dc.font.descent = dc.font.xfont->descent;
814 }
815 dc.font.height = dc.font.ascent + dc.font.descent;
816 }
817
818 Bool
819 isprotodel(Client *c) {
820 int i, n;
821 Atom *protocols;
822 Bool ret = False;
823
824 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
825 for(i = 0; !ret && i < n; i++)
826 if(protocols[i] == wmatom[WMDelete])
827 ret = True;
828 XFree(protocols);
829 }
830 return ret;
831 }
832
833 void
834 keypress(XEvent *e) {
835 unsigned int i;
836 KeySym keysym;
837 XKeyEvent *ev;
838
839 ev = &e->xkey;
840 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
841 for(i = 0; i < LENGTH(keys); i++)
842 if(keysym == keys[i].keysym
843 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
844 && keys[i].func)
845 keys[i].func(&(keys[i].arg));
846 }
847
848 void
849 killclient(const Arg *arg) {
850 XEvent ev;
851
852 if(!sel)
853 return;
854 if(isprotodel(sel)) {
855 ev.type = ClientMessage;
856 ev.xclient.window = sel->win;
857 ev.xclient.message_type = wmatom[WMProtocols];
858 ev.xclient.format = 32;
859 ev.xclient.data.l[0] = wmatom[WMDelete];
860 ev.xclient.data.l[1] = CurrentTime;
861 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
862 }
863 else
864 XKillClient(dpy, sel->win);
865 }
866
867 void
868 manage(Window w, XWindowAttributes *wa) {
869 Client *c, *t = NULL;
870 Window trans = 0;
871 XWindowChanges wc;
872
873 if(!(c = calloc(1, sizeof(Client))))
874 die("fatal: could not calloc() %u bytes\n", sizeof(Client));
875 c->win = w;
876
877 /* geometry */
878 c->x = wa->x;
879 c->y = wa->y;
880 c->w = wa->width;
881 c->h = wa->height;
882 c->oldbw = wa->border_width;
883 if(c->w == sw && c->h == sh) {
884 c->x = sx;
885 c->y = sy;
886 c->bw = 0;
887 }
888 else {
889 if(c->x + c->w + 2 * c->bw > sx + sw)
890 c->x = sx + sw - c->w - 2 * c->bw;
891 if(c->y + c->h + 2 * c->bw > sy + sh)
892 c->y = sy + sh - c->h - 2 * c->bw;
893 c->x = MAX(c->x, sx);
894 /* only fix client y-offset, if the client center might cover the bar */
895 c->y = MAX(c->y, ((by == 0) && (c->x + (c->w / 2) >= wx) && (c->x + (c->w / 2) < wx + ww)) ? bh : sy);
896 c->bw = borderpx;
897 }
898
899 wc.border_width = c->bw;
900 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
901 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
902 configure(c); /* propagates border_width, if size doesn't change */
903 updatesizehints(c);
904 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
905 grabbuttons(c, False);
906 updatetitle(c);
907 if(XGetTransientForHint(dpy, w, &trans))
908 t = getclient(trans);
909 if(t)
910 c->tags = t->tags;
911 else
912 applyrules(c);
913 if(!c->isfloating)
914 c->isfloating = trans || c->isfixed;
915 if(c->isfloating)
916 XRaiseWindow(dpy, c->win);
917 attach(c);
918 attachstack(c);
919 XMoveResizeWindow(dpy, c->win, c->x + 2 * sw, c->y, c->w, c->h); /* some windows require this */
920 XMapWindow(dpy, c->win);
921 setclientstate(c, NormalState);
922 arrange();
923 }
924
925 void
926 mappingnotify(XEvent *e) {
927 XMappingEvent *ev = &e->xmapping;
928
929 XRefreshKeyboardMapping(ev);
930 if(ev->request == MappingKeyboard)
931 grabkeys();
932 }
933
934 void
935 maprequest(XEvent *e) {
936 static XWindowAttributes wa;
937 XMapRequestEvent *ev = &e->xmaprequest;
938
939 if(!XGetWindowAttributes(dpy, ev->window, &wa))
940 return;
941 if(wa.override_redirect)
942 return;
943 if(!getclient(ev->window))
944 manage(ev->window, &wa);
945 }
946
947 void
948 monocle(void) {
949 Client *c;
950
951 for(c = nexttiled(clients); c; c = nexttiled(c->next))
952 resize(c, wx, wy, ww - 2 * c->bw, wh - 2 * c->bw, resizehints);
953 }
954
955 void
956 movemouse(const Arg *arg) {
957 int x, y, ocx, ocy, di, nx, ny;
958 unsigned int dui;
959 Client *c;
960 Window dummy;
961 XEvent ev;
962
963 if(!(c = sel))
964 return;
965 restack();
966 ocx = nx = c->x;
967 ocy = ny = c->y;
968 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
969 None, cursor[CurMove], CurrentTime) != GrabSuccess)
970 return;
971 XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui);
972 for(;;) {
973 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
974 switch (ev.type) {
975 case ButtonRelease:
976 XUngrabPointer(dpy, CurrentTime);
977 return;
978 case ConfigureRequest:
979 case Expose:
980 case MapRequest:
981 handler[ev.type](&ev);
982 break;
983 case MotionNotify:
984 XSync(dpy, False);
985 nx = ocx + (ev.xmotion.x - x);
986 ny = ocy + (ev.xmotion.y - y);
987 if(snap && nx >= wx && nx <= wx + ww
988 && ny >= wy && ny <= wy + wh) {
989 if(abs(wx - nx) < snap)
990 nx = wx;
991 else if(abs((wx + ww) - (nx + c->w + 2 * c->bw)) < snap)
992 nx = wx + ww - c->w - 2 * c->bw;
993 if(abs(wy - ny) < snap)
994 ny = wy;
995 else if(abs((wy + wh) - (ny + c->h + 2 * c->bw)) < snap)
996 ny = wy + wh - c->h - 2 * c->bw;
997 if(!c->isfloating && lt[sellt]->arrange && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
998 togglefloating(NULL);
999 }
1000 if(!lt[sellt]->arrange || c->isfloating)
1001 resize(c, nx, ny, c->w, c->h, False);
1002 break;
1003 }
1004 }
1005 }
1006
1007 Client *
1008 nexttiled(Client *c) {
1009 for(; c && (c->isfloating || !ISVISIBLE(c)); c = c->next);
1010 return c;
1011 }
1012
1013 void
1014 propertynotify(XEvent *e) {
1015 Client *c;
1016 Window trans;
1017 XPropertyEvent *ev = &e->xproperty;
1018
1019 if(ev->state == PropertyDelete)
1020 return; /* ignore */
1021 if((c = getclient(ev->window))) {
1022 switch (ev->atom) {
1023 default: break;
1024 case XA_WM_TRANSIENT_FOR:
1025 XGetTransientForHint(dpy, c->win, &trans);
1026 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1027 arrange();
1028 break;
1029 case XA_WM_NORMAL_HINTS:
1030 updatesizehints(c);
1031 break;
1032 case XA_WM_HINTS:
1033 updatewmhints(c);
1034 drawbar();
1035 break;
1036 }
1037 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1038 updatetitle(c);
1039 if(c == sel)
1040 drawbar();
1041 }
1042 }
1043 }
1044
1045 void
1046 quit(const Arg *arg) {
1047 readin = running = False;
1048 }
1049
1050 void
1051 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1052 XWindowChanges wc;
1053
1054 if(sizehints) {
1055 /* set minimum possible */
1056 w = MAX(1, w);
1057 h = MAX(1, h);
1058
1059 /* temporarily remove base dimensions */
1060 w -= c->basew;
1061 h -= c->baseh;
1062
1063 /* adjust for aspect limits */
1064 if(c->mina > 0 && c->maxa > 0) {
1065 if(c->maxa < (float) w/h)
1066 w = h * c->maxa;
1067 else if(c->mina > (float) h/w)
1068 h = w * c->mina;
1069 }
1070
1071 /* adjust for increment value */
1072 if(c->incw)
1073 w -= w % c->incw;
1074 if(c->inch)
1075 h -= h % c->inch;
1076
1077 /* restore base dimensions */
1078 w += c->basew;
1079 h += c->baseh;
1080
1081 w = MAX(w, c->minw);
1082 h = MAX(h, c->minh);
1083
1084 if(c->maxw)
1085 w = MIN(w, c->maxw);
1086
1087 if(c->maxh)
1088 h = MIN(h, c->maxh);
1089 }
1090 if(w <= 0 || h <= 0)
1091 return;
1092 if(x > sx + sw)
1093 x = sw - w - 2 * c->bw;
1094 if(y > sy + sh)
1095 y = sh - h - 2 * c->bw;
1096 if(x + w + 2 * c->bw < sx)
1097 x = sx;
1098 if(y + h + 2 * c->bw < sy)
1099 y = sy;
1100 if(h < bh)
1101 h = bh;
1102 if(w < bh)
1103 w = bh;
1104 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1105 c->x = wc.x = x;
1106 c->y = wc.y = y;
1107 c->w = wc.width = w;
1108 c->h = wc.height = h;
1109 wc.border_width = c->bw;
1110 XConfigureWindow(dpy, c->win,
1111 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1112 configure(c);
1113 XSync(dpy, False);
1114 }
1115 }
1116
1117 void
1118 resizemouse(const Arg *arg) {
1119 int ocx, ocy;
1120 int nw, nh;
1121 Client *c;
1122 XEvent ev;
1123
1124 if(!(c = sel))
1125 return;
1126 restack();
1127 ocx = c->x;
1128 ocy = c->y;
1129 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1130 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1131 return;
1132 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1133 for(;;) {
1134 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1135 switch(ev.type) {
1136 case ButtonRelease:
1137 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1138 c->w + c->bw - 1, c->h + c->bw - 1);
1139 XUngrabPointer(dpy, CurrentTime);
1140 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1141 return;
1142 case ConfigureRequest:
1143 case Expose:
1144 case MapRequest:
1145 handler[ev.type](&ev);
1146 break;
1147 case MotionNotify:
1148 XSync(dpy, False);
1149 nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1150 nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1151
1152 if(snap && nw >= wx && nw <= wx + ww
1153 && nh >= wy && nh <= wy + wh) {
1154 if(!c->isfloating && lt[sellt]->arrange
1155 && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1156 togglefloating(NULL);
1157 }
1158 if(!lt[sellt]->arrange || c->isfloating)
1159 resize(c, c->x, c->y, nw, nh, True);
1160 break;
1161 }
1162 }
1163 }
1164
1165 void
1166 restack(void) {
1167 Client *c;
1168 XEvent ev;
1169 XWindowChanges wc;
1170
1171 drawbar();
1172 if(!sel)
1173 return;
1174 if(sel->isfloating || !lt[sellt]->arrange)
1175 XRaiseWindow(dpy, sel->win);
1176 if(lt[sellt]->arrange) {
1177 wc.stack_mode = Below;
1178 wc.sibling = barwin;
1179 for(c = stack; c; c = c->snext)
1180 if(!c->isfloating && ISVISIBLE(c)) {
1181 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1182 wc.sibling = c->win;
1183 }
1184 }
1185 XSync(dpy, False);
1186 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1187 }
1188
1189 void
1190 run(void) {
1191 char *p;
1192 char sbuf[sizeof stext];
1193 fd_set rd;
1194 int r, xfd;
1195 unsigned int len, offset;
1196 XEvent ev;
1197
1198 /* main event loop, also reads status text from stdin */
1199 XSync(dpy, False);
1200 xfd = ConnectionNumber(dpy);
1201 offset = 0;
1202 len = sizeof stext - 1;
1203 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1204 while(running) {
1205 FD_ZERO(&rd);
1206 if(readin)
1207 FD_SET(STDIN_FILENO, &rd);
1208 FD_SET(xfd, &rd);
1209 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1210 if(errno == EINTR)
1211 continue;
1212 die("select failed\n");
1213 }
1214 if(FD_ISSET(STDIN_FILENO, &rd)) {
1215 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1216 case -1:
1217 strncpy(stext, strerror(errno), len);
1218 readin = False;
1219 break;
1220 case 0:
1221 strncpy(stext, "EOF", 4);
1222 readin = False;
1223 break;
1224 default:
1225 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1226 if(*p == '\n' || *p == '\0') {
1227 *p = '\0';
1228 strncpy(stext, sbuf, len);
1229 p += r - 1; /* p is sbuf + offset + r - 1 */
1230 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1231 offset = r;
1232 if(r)
1233 memmove(sbuf, p - r + 1, r);
1234 break;
1235 }
1236 break;
1237 }
1238 drawbar();
1239 }
1240 while(XPending(dpy)) {
1241 XNextEvent(dpy, &ev);
1242 if(handler[ev.type])
1243 (handler[ev.type])(&ev); /* call handler */
1244 }
1245 }
1246 }
1247
1248 void
1249 scan(void) {
1250 unsigned int i, num;
1251 Window *wins, d1, d2;
1252 XWindowAttributes wa;
1253
1254 wins = NULL;
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 }
1271 if(wins)
1272 XFree(wins);
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
1383 /* grab keys */
1384 grabkeys();
1385 }
1386
1387 void
1388 spawn(const Arg *arg) {
1389 /* The double-fork construct avoids zombie processes and keeps the code
1390 * clean from stupid signal handlers. */
1391 if(fork() == 0) {
1392 if(fork() == 0) {
1393 if(dpy)
1394 close(ConnectionNumber(dpy));
1395 setsid();
1396 execvp(((char **)arg->v)[0], (char **)arg->v);
1397 fprintf(stderr, "dwm: execvp %s", ((char **)arg->v)[0]);
1398 perror(" failed");
1399 }
1400 exit(0);
1401 }
1402 wait(0);
1403 }
1404
1405 void
1406 tag(const Arg *arg) {
1407 if(sel && arg->ui & TAGMASK) {
1408 sel->tags = arg->ui & TAGMASK;
1409 arrange();
1410 }
1411 }
1412
1413 int
1414 textnw(const char *text, unsigned int len) {
1415 XRectangle r;
1416
1417 if(dc.font.set) {
1418 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1419 return r.width;
1420 }
1421 return XTextWidth(dc.font.xfont, text, len);
1422 }
1423
1424 void
1425 tile(void) {
1426 int x, y, h, w, mw;
1427 unsigned int i, n;
1428 Client *c;
1429
1430 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next), n++);
1431 if(n == 0)
1432 return;
1433
1434 /* master */
1435 c = nexttiled(clients);
1436 mw = mfact * ww;
1437 resize(c, wx, wy, (n == 1 ? ww : mw) - 2 * c->bw, wh - 2 * c->bw, resizehints);
1438
1439 if(--n == 0)
1440 return;
1441
1442 /* tile stack */
1443 x = (wx + mw > c->x + c->w) ? c->x + c->w + 2 * c->bw : wx + mw;
1444 y = wy;
1445 w = (wx + mw > c->x + c->w) ? wx + ww - x : ww - mw;
1446 h = wh / n;
1447 if(h < bh)
1448 h = wh;
1449
1450 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1451 resize(c, x, y, w - 2 * c->bw, /* remainder */ ((i + 1 == n)
1452 ? (wy + wh) - y : h) - 2 * c->bw, resizehints);
1453 if(h != wh)
1454 y = c->y + c->h + 2 * c->bw;
1455 }
1456 }
1457
1458 void
1459 togglebar(const Arg *arg) {
1460 showbar = !showbar;
1461 updategeom();
1462 updatebar();
1463 arrange();
1464 }
1465
1466 void
1467 togglefloating(const Arg *arg) {
1468 if(!sel)
1469 return;
1470 sel->isfloating = !sel->isfloating || sel->isfixed;
1471 if(sel->isfloating)
1472 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1473 arrange();
1474 }
1475
1476 void
1477 toggletag(const Arg *arg) {
1478 unsigned int mask = sel->tags ^ (arg->ui & TAGMASK);
1479
1480 if(sel && mask) {
1481 sel->tags = mask;
1482 arrange();
1483 }
1484 }
1485
1486 void
1487 toggleview(const Arg *arg) {
1488 unsigned int mask = tagset[seltags] ^ (arg->ui & TAGMASK);
1489
1490 if(mask) {
1491 tagset[seltags] = mask;
1492 clearurgent();
1493 arrange();
1494 }
1495 }
1496
1497 void
1498 unmanage(Client *c) {
1499 XWindowChanges wc;
1500
1501 wc.border_width = c->oldbw;
1502 /* The server grab construct avoids race conditions. */
1503 XGrabServer(dpy);
1504 XSetErrorHandler(xerrordummy);
1505 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1506 detach(c);
1507 detachstack(c);
1508 if(sel == c)
1509 focus(NULL);
1510 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1511 setclientstate(c, WithdrawnState);
1512 free(c);
1513 XSync(dpy, False);
1514 XSetErrorHandler(xerror);
1515 XUngrabServer(dpy);
1516 arrange();
1517 }
1518
1519 void
1520 unmapnotify(XEvent *e) {
1521 Client *c;
1522 XUnmapEvent *ev = &e->xunmap;
1523
1524 if((c = getclient(ev->window)))
1525 unmanage(c);
1526 }
1527
1528 void
1529 updatebar(void) {
1530 if(dc.drawable != 0)
1531 XFreePixmap(dpy, dc.drawable);
1532 dc.drawable = XCreatePixmap(dpy, root, ww, bh, DefaultDepth(dpy, screen));
1533 XMoveResizeWindow(dpy, barwin, wx, by, ww, bh);
1534 }
1535
1536 void
1537 updategeom(void) {
1538 #ifdef XINERAMA
1539 int n, i = 0;
1540 XineramaScreenInfo *info = NULL;
1541
1542 /* window area geometry */
1543 if(XineramaIsActive(dpy) && (info = XineramaQueryScreens(dpy, &n))) {
1544 if(n > 1) {
1545 int di, x, y;
1546 unsigned int dui;
1547 Window dummy;
1548 if(XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui))
1549 for(i = 0; i < n; i++)
1550 if(INRECT(x, y, info[i].x_org, info[i].y_org, info[i].width, info[i].height))
1551 break;
1552 }
1553 wx = info[i].x_org;
1554 wy = showbar && topbar ? info[i].y_org + bh : info[i].y_org;
1555 ww = info[i].width;
1556 wh = showbar ? info[i].height - bh : info[i].height;
1557 XFree(info);
1558 }
1559 else
1560 #endif
1561 {
1562 wx = sx;
1563 wy = showbar && topbar ? sy + bh : sy;
1564 ww = sw;
1565 wh = showbar ? sh - bh : sh;
1566 }
1567
1568 /* bar position */
1569 by = showbar ? (topbar ? wy - bh : wy + wh) : -bh;
1570 }
1571
1572 void
1573 updatesizehints(Client *c) {
1574 long msize;
1575 XSizeHints size;
1576
1577 XGetWMNormalHints(dpy, c->win, &size, &msize);
1578 if(size.flags & PBaseSize) {
1579 c->basew = size.base_width;
1580 c->baseh = size.base_height;
1581 }
1582 else if(size.flags & PMinSize) {
1583 c->basew = size.min_width;
1584 c->baseh = size.min_height;
1585 }
1586 else
1587 c->basew = c->baseh = 0;
1588 if(size.flags & PResizeInc) {
1589 c->incw = size.width_inc;
1590 c->inch = size.height_inc;
1591 }
1592 else
1593 c->incw = c->inch = 0;
1594 if(size.flags & PMaxSize) {
1595 c->maxw = size.max_width;
1596 c->maxh = size.max_height;
1597 }
1598 else
1599 c->maxw = c->maxh = 0;
1600 if(size.flags & PMinSize) {
1601 c->minw = size.min_width;
1602 c->minh = size.min_height;
1603 }
1604 else if(size.flags & PBaseSize) {
1605 c->minw = size.base_width;
1606 c->minh = size.base_height;
1607 }
1608 else
1609 c->minw = c->minh = 0;
1610 if(size.flags & PAspect) {
1611 c->mina = (float)size.min_aspect.y / (float)size.min_aspect.x;
1612 c->maxa = (float)size.max_aspect.x / (float)size.max_aspect.y;
1613 }
1614 else
1615 c->maxa = c->mina = 0.0;
1616 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1617 && c->maxw == c->minw && c->maxh == c->minh);
1618 }
1619
1620 void
1621 updatetitle(Client *c) {
1622 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1623 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1624 }
1625
1626 void
1627 updatewmhints(Client *c) {
1628 XWMHints *wmh;
1629
1630 if((wmh = XGetWMHints(dpy, c->win))) {
1631 if(ISVISIBLE(c) && wmh->flags & XUrgencyHint) {
1632 wmh->flags &= ~XUrgencyHint;
1633 XSetWMHints(dpy, c->win, wmh);
1634 }
1635 else
1636 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1637
1638 XFree(wmh);
1639 }
1640 }
1641
1642 void
1643 view(const Arg *arg) {
1644 if(arg && (arg->ui & TAGMASK) == tagset[seltags])
1645 return;
1646 seltags ^= 1; /* toggle sel tagset */
1647 if(arg && (arg->ui & TAGMASK))
1648 tagset[seltags] = arg->ui & TAGMASK;
1649 clearurgent();
1650 arrange();
1651 }
1652
1653 /* There's no way to check accesses to destroyed windows, thus those cases are
1654 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1655 * default error handler, which may call exit. */
1656 int
1657 xerror(Display *dpy, XErrorEvent *ee) {
1658 if(ee->error_code == BadWindow
1659 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1660 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1661 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1662 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1663 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1664 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1665 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1666 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1667 return 0;
1668 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1669 ee->request_code, ee->error_code);
1670 return xerrorxlib(dpy, ee); /* may call exit */
1671 }
1672
1673 int
1674 xerrordummy(Display *dpy, XErrorEvent *ee) {
1675 return 0;
1676 }
1677
1678 /* Startup Error handler to check if another window manager
1679 * is already running. */
1680 int
1681 xerrorstart(Display *dpy, XErrorEvent *ee) {
1682 otherwm = True;
1683 return -1;
1684 }
1685
1686 void
1687 zoom(const Arg *arg) {
1688 Client *c = sel;
1689
1690 if(!lt[sellt]->arrange || lt[sellt]->arrange == monocle || (sel && sel->isfloating))
1691 return;
1692 if(c == nexttiled(clients))
1693 if(!c || !(c = nexttiled(c->next)))
1694 return;
1695 detach(c);
1696 attach(c);
1697 focus(c);
1698 arrange();
1699 }
1700
1701 int
1702 main(int argc, char *argv[]) {
1703 if(argc == 2 && !strcmp("-v", argv[1]))
1704 die("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1705 else if(argc != 1)
1706 die("usage: dwm [-v]\n");
1707
1708 if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
1709 fprintf(stderr, "warning: no locale support\n");
1710
1711 if(!(dpy = XOpenDisplay(0)))
1712 die("dwm: cannot open display\n");
1713
1714 checkotherwm();
1715 setup();
1716 scan();
1717 run();
1718 cleanup();
1719
1720 XCloseDisplay(dpy);
1721 return 0;
1722 }