Xinqi Bao's Git

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