Xinqi Bao's Git

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