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