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