Xinqi Bao's Git

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