Xinqi Bao's Git

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