Xinqi Bao's Git

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