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