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