Xinqi Bao's Git

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