Xinqi Bao's Git

4153f416e979087c31d8bf7fb50c28c434d42f68
[dwm.git] / dwm.c
1 /* See LICENSE file for copyright and license details.
2 *
3 * dynamic window manager is designed like any other X client as well. It is
4 * driven through handling X events. In contrast to other X clients, a window
5 * manager selects for SubstructureRedirectMask on the root window, to receive
6 * events about window (dis-)appearance. Only one X connection at a time is
7 * allowed to select for this event mask.
8 *
9 * Calls to fetch an X event from the event queue are blocking. Due reading
10 * status text from standard input, a select()-driven main loop has been
11 * implemented which selects for reads on the X connection and STDIN_FILENO to
12 * handle all data smoothly. The event handlers of dwm are organized in an
13 * array which is accessed whenever a new event has been fetched. This allows
14 * event dispatching in O(1) time.
15 *
16 * Each child of the root window is called a client, except windows which have
17 * set the override_redirect flag. Clients are organized in a global
18 * doubly-linked client list, the focus history is remembered through a global
19 * stack list. Each client contains 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 */
58 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
59 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
60 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
61 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
62 enum { ClkLtSymbol = -1, ClkStatusText = -2, ClkWinTitle = -3,
63 ClkClientWin = -4, ClkRootWin = -5, ClkLast = -6};/* clicks */
64
65 /* typedefs */
66 typedef unsigned int uint;
67 typedef unsigned long ulong;
68
69 typedef union {
70 int i;
71 uint ui;
72 float f;
73 void *v;
74 } Arg;
75
76 typedef struct {
77 uint click;
78 uint mask;
79 uint button;
80 void (*func)(const Arg *arg);
81 const Arg arg;
82 } Button;
83
84 typedef struct Client Client;
85 struct Client {
86 char name[256];
87 int x, y, w, h;
88 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
89 float mina, maxa;
90 int bw, oldbw;
91 Bool isbanned, isfixed, isfloating, ismoved, isurgent;
92 uint tags;
93 Client *next;
94 Client *snext;
95 Window win;
96 };
97
98 typedef struct {
99 int x, y, w, h;
100 ulong norm[ColLast];
101 ulong sel[ColLast];
102 Drawable drawable;
103 GC gc;
104 struct {
105 int ascent;
106 int descent;
107 int height;
108 XFontSet set;
109 XFontStruct *xfont;
110 } font;
111 } DC; /* draw context */
112
113 typedef struct {
114 uint mod;
115 KeySym keysym;
116 void (*func)(const Arg *);
117 const Arg arg;
118 } Key;
119
120 typedef struct {
121 const char *symbol;
122 void (*arrange)(void);
123 } Layout;
124
125 typedef struct {
126 const char *class;
127 const char *instance;
128 const char *title;
129 uint tags;
130 Bool isfloating;
131 } Rule;
132
133 /* function declarations */
134 static void applyrules(Client *c);
135 static void arrange(void);
136 static void attach(Client *c);
137 static void attachstack(Client *c);
138 static void buttonpress(XEvent *e);
139 static void checkotherwm(void);
140 static void cleanup(void);
141 static void configure(Client *c);
142 static void configurenotify(XEvent *e);
143 static void configurerequest(XEvent *e);
144 static void destroynotify(XEvent *e);
145 static void detach(Client *c);
146 static void detachstack(Client *c);
147 static void drawbar(void);
148 static void drawsquare(Bool filled, Bool empty, Bool invert, ulong col[ColLast]);
149 static void drawtext(const char *text, ulong col[ColLast], Bool invert);
150 static void enternotify(XEvent *e);
151 static void eprint(const char *errstr, ...);
152 static void expose(XEvent *e);
153 static void focus(Client *c);
154 static void focusin(XEvent *e);
155 static void focusstack(const Arg *arg);
156 static Client *getclient(Window w);
157 static ulong getcolor(const char *colstr);
158 static long getstate(Window w);
159 static Bool gettextprop(Window w, Atom atom, char *text, uint size);
160 static void grabbuttons(Client *c, Bool focused);
161 static void grabkeys(void);
162 static void initfont(const char *fontstr);
163 static Bool isoccupied(uint t);
164 static Bool isprotodel(Client *c);
165 static Bool isurgent(uint t);
166 static void keypress(XEvent *e);
167 static void killclient(const Arg *arg);
168 static void manage(Window w, XWindowAttributes *wa);
169 static void mappingnotify(XEvent *e);
170 static void maprequest(XEvent *e);
171 static void movemouse(const Arg *arg);
172 static Client *nexttiled(Client *c);
173 static void propertynotify(XEvent *e);
174 static void quit(const Arg *arg);
175 static void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
176 static void resizemouse(const Arg *arg);
177 static void restack(void);
178 static void run(void);
179 static void scan(void);
180 static void setclientstate(Client *c, long state);
181 static void setmfact(const Arg *arg);
182 static void setup(void);
183 static void spawn(const Arg *arg);
184 static void tag(const Arg *arg);
185 static int textnw(const char *text, uint len);
186 static void tile(void);
187 static void togglebar(const Arg *arg);
188 static void togglefloating(const Arg *arg);
189 static void togglelayout(const Arg *arg);
190 static void togglemax(const Arg *arg);
191 static void toggletag(const Arg *arg);
192 static void toggleview(const Arg *arg);
193 static void unmanage(Client *c);
194 static void unmapnotify(XEvent *e);
195 static void updatebar(void);
196 static void updategeom(void);
197 static void updatesizehints(Client *c);
198 static void updatetitle(Client *c);
199 static void updatewmhints(Client *c);
200 static void view(const Arg *arg);
201 static int xerror(Display *dpy, XErrorEvent *ee);
202 static int xerrordummy(Display *dpy, XErrorEvent *ee);
203 static int xerrorstart(Display *dpy, XErrorEvent *ee);
204 static void zoom(const Arg *arg);
205
206 /* variables */
207 static char stext[256];
208 static int screen, sx, sy, sw, sh;
209 static int by, bh, blw, wx, wy, ww, wh;
210 static uint seltags = 0;
211 static int (*xerrorxlib)(Display *, XErrorEvent *);
212 static uint numlockmask = 0;
213 static void (*handler[LASTEvent]) (XEvent *) = {
214 [ButtonPress] = buttonpress,
215 [ConfigureRequest] = configurerequest,
216 [ConfigureNotify] = configurenotify,
217 [DestroyNotify] = destroynotify,
218 [EnterNotify] = enternotify,
219 [Expose] = expose,
220 [FocusIn] = focusin,
221 [KeyPress] = keypress,
222 [MappingNotify] = mappingnotify,
223 [MapRequest] = maprequest,
224 [PropertyNotify] = propertynotify,
225 [UnmapNotify] = unmapnotify
226 };
227 static Atom wmatom[WMLast], netatom[NetLast];
228 static Bool ismax = False;
229 static Bool otherwm, readin;
230 static Bool running = True;
231 static uint tagset[] = {1, 1}; /* after start, first tag is selected */
232 static Client *clients = NULL;
233 static Client *sel = NULL;
234 static Client *stack = NULL;
235 static Cursor cursor[CurLast];
236 static Display *dpy;
237 static DC dc = {0};
238 static Layout *lt = NULL;
239 static Window root, barwin;
240 /* configuration, allows nested code to access above variables */
241 #include "config.h"
242
243 /* compile-time check if all tags fit into an uint bit array. */
244 struct NumTags { char limitexceeded[sizeof(uint) * 8 < LENGTH(tags) ? -1 : 1]; };
245
246 /* function implementations */
247 void
248 applyrules(Client *c) {
249 uint i;
250 Rule *r;
251 XClassHint ch = { 0 };
252
253 /* rule matching */
254 XGetClassHint(dpy, c->win, &ch);
255 for(i = 0; i < LENGTH(rules); i++) {
256 r = &rules[i];
257 if((!r->title || strstr(c->name, r->title))
258 && (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
259 && (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
260 c->isfloating = r->isfloating;
261 c->tags |= r->tags & TAGMASK;
262 }
263 }
264 if(ch.res_class)
265 XFree(ch.res_class);
266 if(ch.res_name)
267 XFree(ch.res_name);
268 if(!c->tags)
269 c->tags = tagset[seltags];
270 }
271
272 void
273 arrange(void) {
274 Client *c;
275
276 for(c = clients; c; c = c->next)
277 if(c->tags & tagset[seltags]) { /* is visible */
278 if(ismax && !c->isfixed) {
279 XMoveResizeWindow(dpy, c->win, wx, wy, ww - 2 * c->bw, wh - 2 * c->bw);
280 c->ismoved = True;
281 }
282 else if(!lt->arrange || c->isfloating)
283 resize(c, c->x, c->y, c->w, c->h, True);
284 c->isbanned = False;
285 }
286 else if(!c->isbanned) {
287 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
288 c->isbanned = c->ismoved = True;
289 }
290
291 focus(NULL);
292 if(lt->arrange && !ismax)
293 lt->arrange();
294 restack();
295 }
296
297 void
298 attach(Client *c) {
299 c->next = clients;
300 clients = c;
301 }
302
303 void
304 attachstack(Client *c) {
305 c->snext = stack;
306 stack = c;
307 }
308
309 void
310 buttonpress(XEvent *e) {
311 uint i, x, click;
312 Client *c;
313 XButtonPressedEvent *ev = &e->xbutton;
314
315 click = ClkRootWin;
316 if(ev->window == barwin) {
317 x = 0;
318 for(i = 0; i < LENGTH(tags) && ev->x >= x; i++) {
319 x += TEXTW(tags[i]);
320 if(i < LENGTH(tags) || ev->x <= x)
321 click = i - 1;
322 else if(ev->x < x + blw)
323 click = ClkLtSymbol;
324 else if(ev->x > wx + ww - TEXTW(stext))
325 click = ClkStatusText;
326 else
327 click = ClkWinTitle;
328 }
329 }
330 else if((c = getclient(ev->window)))
331 click = ClkClientWin;
332
333 for(i = 0; i < LENGTH(buttons); i++)
334 if(click == buttons[i].click && buttons[i].func && buttons[i].button == ev->button && CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
335 buttons[i].func(&buttons[i].arg);
336 }
337
338 void
339 checkotherwm(void) {
340 otherwm = False;
341 XSetErrorHandler(xerrorstart);
342
343 /* this causes an error if some other window manager is running */
344 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
345 XSync(dpy, False);
346 if(otherwm)
347 eprint("dwm: another window manager is already running\n");
348 XSetErrorHandler(NULL);
349 xerrorxlib = XSetErrorHandler(xerror);
350 XSync(dpy, False);
351 }
352
353 void
354 cleanup(void) {
355 Arg a = {.i = ~0};
356 Layout foo = { "", NULL };
357
358 close(STDIN_FILENO);
359 view(&a);
360 lt = &foo;
361 while(stack)
362 unmanage(stack);
363 if(dc.font.set)
364 XFreeFontSet(dpy, dc.font.set);
365 else
366 XFreeFont(dpy, dc.font.xfont);
367 XUngrabKey(dpy, AnyKey, AnyModifier, root);
368 XFreePixmap(dpy, dc.drawable);
369 XFreeGC(dpy, dc.gc);
370 XFreeCursor(dpy, cursor[CurNormal]);
371 XFreeCursor(dpy, cursor[CurResize]);
372 XFreeCursor(dpy, cursor[CurMove]);
373 XDestroyWindow(dpy, barwin);
374 XSync(dpy, False);
375 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
376 }
377
378 void
379 configure(Client *c) {
380 XConfigureEvent ce;
381
382 ce.type = ConfigureNotify;
383 ce.display = dpy;
384 ce.event = c->win;
385 ce.window = c->win;
386 ce.x = c->x;
387 ce.y = c->y;
388 ce.width = c->w;
389 ce.height = c->h;
390 ce.border_width = c->bw;
391 ce.above = None;
392 ce.override_redirect = False;
393 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
394 }
395
396 void
397 configurenotify(XEvent *e) {
398 XConfigureEvent *ev = &e->xconfigure;
399
400 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
401 sw = ev->width;
402 sh = ev->height;
403 updategeom();
404 updatebar();
405 arrange();
406 }
407 }
408
409 void
410 configurerequest(XEvent *e) {
411 Client *c;
412 XConfigureRequestEvent *ev = &e->xconfigurerequest;
413 XWindowChanges wc;
414
415 if((c = getclient(ev->window))) {
416 if(ev->value_mask & CWBorderWidth)
417 c->bw = ev->border_width;
418 if(ismax && !c->isbanned && !c->isfixed)
419 XMoveResizeWindow(dpy, c->win, wx, wy, ww - 2 * c->bw, wh + 2 * c->bw);
420 else if(c->isfloating || !lt->arrange) {
421 if(ev->value_mask & CWX)
422 c->x = sx + ev->x;
423 if(ev->value_mask & CWY)
424 c->y = sy + ev->y;
425 if(ev->value_mask & CWWidth)
426 c->w = ev->width;
427 if(ev->value_mask & CWHeight)
428 c->h = ev->height;
429 if((c->x - sx + c->w) > sw && c->isfloating)
430 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
431 if((c->y - sy + c->h) > sh && c->isfloating)
432 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
433 if((ev->value_mask & (CWX|CWY))
434 && !(ev->value_mask & (CWWidth|CWHeight)))
435 configure(c);
436 if(!c->isbanned)
437 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
438 }
439 else
440 configure(c);
441 }
442 else {
443 wc.x = ev->x;
444 wc.y = ev->y;
445 wc.width = ev->width;
446 wc.height = ev->height;
447 wc.border_width = ev->border_width;
448 wc.sibling = ev->above;
449 wc.stack_mode = ev->detail;
450 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
451 }
452 XSync(dpy, False);
453 }
454
455 void
456 destroynotify(XEvent *e) {
457 Client *c;
458 XDestroyWindowEvent *ev = &e->xdestroywindow;
459
460 if((c = getclient(ev->window)))
461 unmanage(c);
462 }
463
464 void
465 detach(Client *c) {
466 Client *i;
467
468 if (c != clients) {
469 for(i = clients; i->next != c; i = i->next);
470 i->next = c->next;
471 }
472 else {
473 clients = c->next;
474 }
475 c->next = NULL;
476 }
477
478 void
479 detachstack(Client *c) {
480 Client **tc;
481
482 for(tc = &stack; *tc && *tc != c; tc = &(*tc)->snext);
483 *tc = c->snext;
484 }
485
486 void
487 drawbar(void) {
488 int i, x;
489 Client *c;
490
491 dc.x = 0;
492 for(c = stack; c && c->isbanned; c = c->snext);
493 for(i = 0; i < LENGTH(tags); i++) {
494 dc.w = TEXTW(tags[i]);
495 if(tagset[seltags] & 1 << i) {
496 drawtext(tags[i], dc.sel, isurgent(i));
497 drawsquare(c && c->tags & 1 << i, isoccupied(i), isurgent(i), dc.sel);
498 }
499 else {
500 drawtext(tags[i], dc.norm, isurgent(i));
501 drawsquare(c && c->tags & 1 << i, isoccupied(i), isurgent(i), dc.norm);
502 }
503 dc.x += dc.w;
504 }
505 if(blw > 0) {
506 dc.w = blw;
507 drawtext(lt->symbol, dc.norm, ismax);
508 x = dc.x + dc.w;
509 }
510 else
511 x = dc.x;
512 dc.w = TEXTW(stext);
513 dc.x = ww - dc.w;
514 if(dc.x < x) {
515 dc.x = x;
516 dc.w = ww - x;
517 }
518 drawtext(stext, dc.norm, False);
519 if((dc.w = dc.x - x) > bh) {
520 dc.x = x;
521 if(c) {
522 drawtext(c->name, dc.sel, False);
523 drawsquare(c->isfixed, c->isfloating, False, dc.sel);
524 }
525 else
526 drawtext(NULL, dc.norm, False);
527 }
528 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, ww, bh, 0, 0);
529 XSync(dpy, False);
530 }
531
532 void
533 drawsquare(Bool filled, Bool empty, Bool invert, ulong col[ColLast]) {
534 int x;
535 XGCValues gcv;
536 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
537
538 gcv.foreground = col[invert ? ColBG : ColFG];
539 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
540 x = (dc.font.ascent + dc.font.descent + 2) / 4;
541 r.x = dc.x + 1;
542 r.y = dc.y + 1;
543 if(filled) {
544 r.width = r.height = x + 1;
545 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
546 }
547 else if(empty) {
548 r.width = r.height = x;
549 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
550 }
551 }
552
553 void
554 drawtext(const char *text, ulong col[ColLast], Bool invert) {
555 int i, x, y, h, 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 h = dc.font.ascent + dc.font.descent;
567 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
568 x = dc.x + (h / 2);
569 /* shorten text if necessary */
570 for(; len && (i = textnw(buf, len)) > dc.w - h; len--);
571 if(!len)
572 return;
573 if(len < olen)
574 for(i = len; i && i > len - 3; buf[--i] = '.');
575 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
576 if(dc.font.set)
577 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
578 else
579 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
580 }
581
582 void
583 enternotify(XEvent *e) {
584 Client *c;
585 XCrossingEvent *ev = &e->xcrossing;
586
587 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
588 return;
589 if((c = getclient(ev->window)))
590 focus(c);
591 else
592 focus(NULL);
593 }
594
595 void
596 eprint(const char *errstr, ...) {
597 va_list ap;
598
599 va_start(ap, errstr);
600 vfprintf(stderr, errstr, ap);
601 va_end(ap);
602 exit(EXIT_FAILURE);
603 }
604
605 void
606 expose(XEvent *e) {
607 XExposeEvent *ev = &e->xexpose;
608
609 if(ev->count == 0 && (ev->window == barwin))
610 drawbar();
611 }
612
613 void
614 focus(Client *c) {
615 if(!c || c->isbanned)
616 for(c = stack; c && c->isbanned; c = c->snext);
617 if(sel && sel != c) {
618 grabbuttons(sel, False);
619 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
620 }
621 if(c) {
622 detachstack(c);
623 attachstack(c);
624 grabbuttons(c, True);
625 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
626 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
627 }
628 else
629 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
630 sel = c;
631 drawbar();
632 }
633
634 void
635 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
636 XFocusChangeEvent *ev = &e->xfocus;
637
638 if(sel && ev->window != sel->win)
639 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
640 }
641
642 void
643 focusstack(const Arg *arg) {
644 Client *c = NULL, *i;
645
646 if(!sel)
647 return;
648 if (arg->i > 0) {
649 for(c = sel->next; c && c->isbanned; c = c->next);
650 if(!c)
651 for(c = clients; c && c->isbanned; c = c->next);
652 }
653 else {
654 for(i = clients; i != sel; i = i->next)
655 if (!i->isbanned)
656 c = i;
657 if(!c)
658 for(; i; i = i->next)
659 if (!i->isbanned)
660 c = i;
661 }
662 if(c) {
663 focus(c);
664 restack();
665 }
666 }
667
668 Client *
669 getclient(Window w) {
670 Client *c;
671
672 for(c = clients; c && c->win != w; c = c->next);
673 return c;
674 }
675
676 ulong
677 getcolor(const char *colstr) {
678 Colormap cmap = DefaultColormap(dpy, screen);
679 XColor color;
680
681 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
682 eprint("error, cannot allocate color '%s'\n", colstr);
683 return color.pixel;
684 }
685
686 long
687 getstate(Window w) {
688 int format, status;
689 long result = -1;
690 unsigned char *p = NULL;
691 ulong n, extra;
692 Atom real;
693
694 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
695 &real, &format, &n, &extra, (unsigned char **)&p);
696 if(status != Success)
697 return -1;
698 if(n != 0)
699 result = *p;
700 XFree(p);
701 return result;
702 }
703
704 Bool
705 gettextprop(Window w, Atom atom, char *text, uint size) {
706 char **list = NULL;
707 int n;
708 XTextProperty name;
709
710 if(!text || size == 0)
711 return False;
712 text[0] = '\0';
713 XGetTextProperty(dpy, w, &name, atom);
714 if(!name.nitems)
715 return False;
716 if(name.encoding == XA_STRING)
717 strncpy(text, (char *)name.value, size - 1);
718 else {
719 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
720 && n > 0 && *list) {
721 strncpy(text, *list, size - 1);
722 XFreeStringList(list);
723 }
724 }
725 text[size - 1] = '\0';
726 XFree(name.value);
727 return True;
728 }
729
730 void
731 grabbuttons(Client *c, Bool focused) {
732 int i, j;
733 uint buttons[] = { Button1, Button2, Button3 };
734 uint modifiers[] = { MODKEY, MODKEY|LockMask, MODKEY|numlockmask, MODKEY|numlockmask|LockMask };
735
736 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
737 if(focused)
738 for(i = 0; i < LENGTH(buttons); i++)
739 for(j = 0; j < LENGTH(modifiers); j++)
740 XGrabButton(dpy, buttons[i], modifiers[j], c->win, False,
741 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
742 else
743 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
744 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
745 }
746
747 void
748 grabkeys(void) {
749 uint i, j;
750 KeyCode code;
751 XModifierKeymap *modmap;
752
753 /* init modifier map */
754 modmap = XGetModifierMapping(dpy);
755 for(i = 0; i < 8; i++)
756 for(j = 0; j < modmap->max_keypermod; j++) {
757 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
758 numlockmask = (1 << i);
759 }
760 XFreeModifiermap(modmap);
761
762 XUngrabKey(dpy, AnyKey, AnyModifier, root);
763 for(i = 0; i < LENGTH(keys); i++) {
764 code = XKeysymToKeycode(dpy, keys[i].keysym);
765 XGrabKey(dpy, code, keys[i].mod, root, True,
766 GrabModeAsync, GrabModeAsync);
767 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
768 GrabModeAsync, GrabModeAsync);
769 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
770 GrabModeAsync, GrabModeAsync);
771 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
772 GrabModeAsync, GrabModeAsync);
773 }
774 }
775
776 void
777 initfont(const char *fontstr) {
778 char *def, **missing;
779 int i, n;
780
781 missing = NULL;
782 if(dc.font.set)
783 XFreeFontSet(dpy, dc.font.set);
784 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
785 if(missing) {
786 while(n--)
787 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
788 XFreeStringList(missing);
789 }
790 if(dc.font.set) {
791 XFontSetExtents *font_extents;
792 XFontStruct **xfonts;
793 char **font_names;
794 dc.font.ascent = dc.font.descent = 0;
795 font_extents = XExtentsOfFontSet(dc.font.set);
796 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
797 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
798 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
799 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
800 xfonts++;
801 }
802 }
803 else {
804 if(dc.font.xfont)
805 XFreeFont(dpy, dc.font.xfont);
806 dc.font.xfont = NULL;
807 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
808 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
809 eprint("error, cannot load font: '%s'\n", fontstr);
810 dc.font.ascent = dc.font.xfont->ascent;
811 dc.font.descent = dc.font.xfont->descent;
812 }
813 dc.font.height = dc.font.ascent + dc.font.descent;
814 }
815
816 Bool
817 isoccupied(uint t) {
818 Client *c;
819
820 for(c = clients; c; c = c->next)
821 if(c->tags & 1 << t)
822 return True;
823 return False;
824 }
825
826 Bool
827 isprotodel(Client *c) {
828 int i, n;
829 Atom *protocols;
830 Bool ret = False;
831
832 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
833 for(i = 0; !ret && i < n; i++)
834 if(protocols[i] == wmatom[WMDelete])
835 ret = True;
836 XFree(protocols);
837 }
838 return ret;
839 }
840
841 Bool
842 isurgent(uint t) {
843 Client *c;
844
845 for(c = clients; c; c = c->next)
846 if(c->isurgent && c->tags & 1 << t)
847 return True;
848 return False;
849 }
850
851 void
852 keypress(XEvent *e) {
853 uint i;
854 KeySym keysym;
855 XKeyEvent *ev;
856
857 ev = &e->xkey;
858 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
859 for(i = 0; i < LENGTH(keys); i++)
860 if(keysym == keys[i].keysym
861 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
862 && keys[i].func)
863 keys[i].func(&(keys[i].arg));
864 }
865
866 void
867 killclient(const Arg *arg) {
868 XEvent ev;
869
870 if(!sel)
871 return;
872 if(isprotodel(sel)) {
873 ev.type = ClientMessage;
874 ev.xclient.window = sel->win;
875 ev.xclient.message_type = wmatom[WMProtocols];
876 ev.xclient.format = 32;
877 ev.xclient.data.l[0] = wmatom[WMDelete];
878 ev.xclient.data.l[1] = CurrentTime;
879 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
880 }
881 else
882 XKillClient(dpy, sel->win);
883 }
884
885 void
886 manage(Window w, XWindowAttributes *wa) {
887 Client *c, *t = NULL;
888 Status rettrans;
889 Window trans;
890 XWindowChanges wc;
891
892 if(!(c = calloc(1, sizeof(Client))))
893 eprint("fatal: could not calloc() %u bytes\n", sizeof(Client));
894 c->win = w;
895
896 /* geometry */
897 c->x = wa->x;
898 c->y = wa->y;
899 c->w = wa->width;
900 c->h = wa->height;
901 c->oldbw = wa->border_width;
902 if(c->w == sw && c->h == sh) {
903 c->x = sx;
904 c->y = sy;
905 c->bw = wa->border_width;
906 }
907 else {
908 if(c->x + c->w + 2 * c->bw > sx + sw)
909 c->x = sx + sw - c->w - 2 * c->bw;
910 if(c->y + c->h + 2 * c->bw > sy + sh)
911 c->y = sy + sh - c->h - 2 * c->bw;
912 c->x = MAX(c->x, sx);
913 c->y = MAX(c->y, by == 0 ? bh : sy);
914 c->bw = borderpx;
915 }
916
917 wc.border_width = c->bw;
918 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
919 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
920 configure(c); /* propagates border_width, if size doesn't change */
921 updatesizehints(c);
922 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
923 grabbuttons(c, False);
924 updatetitle(c);
925 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
926 for(t = clients; t && t->win != trans; t = t->next);
927 if(t)
928 c->tags = t->tags;
929 else
930 applyrules(c);
931 if(!c->isfloating)
932 c->isfloating = (rettrans == Success) || c->isfixed;
933 if(c->isfloating)
934 XRaiseWindow(dpy, c->win);
935 attach(c);
936 attachstack(c);
937 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
938 XMapWindow(dpy, c->win);
939 setclientstate(c, NormalState);
940 arrange();
941 }
942
943 void
944 mappingnotify(XEvent *e) {
945 XMappingEvent *ev = &e->xmapping;
946
947 XRefreshKeyboardMapping(ev);
948 if(ev->request == MappingKeyboard)
949 grabkeys();
950 }
951
952 void
953 maprequest(XEvent *e) {
954 static XWindowAttributes wa;
955 XMapRequestEvent *ev = &e->xmaprequest;
956
957 if(!XGetWindowAttributes(dpy, ev->window, &wa))
958 return;
959 if(wa.override_redirect)
960 return;
961 if(!getclient(ev->window))
962 manage(ev->window, &wa);
963 }
964
965 void
966 movemouse(const Arg *arg) {
967 int x1, y1, ocx, ocy, di, nx, ny;
968 uint dui;
969 Client *c;
970 Window dummy;
971 XEvent ev;
972
973 if(!(c = sel))
974 return;
975 restack();
976 ocx = nx = c->x;
977 ocy = ny = c->y;
978 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
979 None, cursor[CurMove], CurrentTime) != GrabSuccess)
980 return;
981 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
982 if(x1 < c->x || x1 > c->x + c->w || y1 < c->y || y1 > c->y + c->h) {
983 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, 0, 0);
984 x1 = c->x + 1;
985 y1 = c->y + 1;
986 }
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
1022 Client *
1023 nexttiled(Client *c) {
1024 for(; c && (c->isfloating || c->isbanned); c = c->next);
1025 return c;
1026 }
1027
1028 void
1029 propertynotify(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
1060 void
1061 quit(const Arg *arg) {
1062 readin = running = False;
1063 }
1064
1065 void
1066 resize(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
1133 void
1134 resizemouse(const Arg *arg) {
1135 int ocx, ocy;
1136 int nw, nh;
1137 Client *c;
1138 XEvent ev;
1139
1140 if(!(c = sel))
1141 return;
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
1181 void
1182 restack(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
1205 void
1206 run(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
1265 void
1266 scan(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
1292 void
1293 setclientstate(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 */
1301 void
1302 setmfact(const Arg *arg) {
1303 float f;
1304
1305 if(!arg || !lt->arrange)
1306 return;
1307 f = arg->f < 1.0 ? arg->f + mfact : arg->f - 1.0;
1308 if(f < 0.1 || f > 0.9)
1309 return;
1310 mfact = f;
1311 arrange();
1312 }
1313
1314 void
1315 setup(void) {
1316 uint i;
1317 int w;
1318 XSetWindowAttributes wa;
1319
1320 /* init screen */
1321 screen = DefaultScreen(dpy);
1322 root = RootWindow(dpy, screen);
1323 initfont(FONT);
1324 sx = 0;
1325 sy = 0;
1326 sw = DisplayWidth(dpy, screen);
1327 sh = DisplayHeight(dpy, screen);
1328 bh = dc.font.height + 2;
1329 lt = layouts;
1330 updategeom();
1331
1332 /* init atoms */
1333 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1334 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1335 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1336 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1337 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1338 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1339
1340 /* init cursors */
1341 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1342 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1343 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1344
1345 /* init appearance */
1346 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1347 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1348 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1349 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1350 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1351 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1352 initfont(FONT);
1353 dc.h = bh;
1354 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1355 dc.gc = XCreateGC(dpy, root, 0, 0);
1356 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1357 if(!dc.font.set)
1358 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1359
1360 /* init bar */
1361 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1362 w = TEXTW(layouts[i].symbol);
1363 blw = MAX(blw, w);
1364 }
1365
1366 wa.override_redirect = 1;
1367 wa.background_pixmap = ParentRelative;
1368 wa.event_mask = ButtonPressMask|ExposureMask;
1369
1370 barwin = XCreateWindow(dpy, root, wx, by, ww, bh, 0, DefaultDepth(dpy, screen),
1371 CopyFromParent, DefaultVisual(dpy, screen),
1372 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1373 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1374 XMapRaised(dpy, barwin);
1375 strcpy(stext, "dwm-"VERSION);
1376 drawbar();
1377
1378 /* EWMH support per view */
1379 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1380 PropModeReplace, (unsigned char *) netatom, NetLast);
1381
1382 /* select for events */
1383 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask|ButtonPressMask
1384 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1385 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1386 XSelectInput(dpy, root, wa.event_mask);
1387
1388
1389 /* grab keys */
1390 grabkeys();
1391 }
1392
1393 void
1394 spawn(const Arg *arg) {
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 execvp(((char **)arg->v)[0], (char **)arg->v);
1403 fprintf(stderr, "dwm: execvp %s", ((char **)arg->v)[0]);
1404 perror(" failed");
1405 }
1406 exit(0);
1407 }
1408 wait(0);
1409 }
1410
1411 void
1412 tag(const Arg *arg) {
1413 if(sel && arg->ui & TAGMASK) {
1414 sel->tags = arg->ui & TAGMASK;
1415 arrange();
1416 }
1417 }
1418
1419 int
1420 textnw(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
1430 void
1431 tile(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
1464 void
1465 togglebar(const Arg *arg) {
1466 showbar = !showbar;
1467 updategeom();
1468 updatebar();
1469 arrange();
1470 }
1471
1472 void
1473 togglefloating(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
1482 void
1483 togglelayout(const Arg *arg) {
1484 if(arg && arg->v)
1485 lt = (Layout *)arg->v;
1486 else if(++lt == &layouts[LENGTH(layouts)])
1487 lt = &layouts[0];
1488 if(sel)
1489 arrange();
1490 else
1491 drawbar();
1492 }
1493
1494 void
1495 togglemax(const Arg *arg) {
1496 ismax = !ismax;
1497 arrange();
1498 }
1499
1500 void
1501 toggletag(const Arg *arg) {
1502 if(sel && (sel->tags ^= (arg->ui & TAGMASK)))
1503 arrange();
1504 }
1505
1506 void
1507 toggleview(const Arg *arg) {
1508 if((tagset[seltags] ^= (arg->ui & TAGMASK)))
1509 arrange();
1510 }
1511
1512 void
1513 unmanage(Client *c) {
1514 XWindowChanges wc;
1515
1516 wc.border_width = c->oldbw;
1517 /* The server grab construct avoids race conditions. */
1518 XGrabServer(dpy);
1519 XSetErrorHandler(xerrordummy);
1520 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1521 detach(c);
1522 detachstack(c);
1523 if(sel == c)
1524 focus(NULL);
1525 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1526 setclientstate(c, WithdrawnState);
1527 free(c);
1528 XSync(dpy, False);
1529 XSetErrorHandler(xerror);
1530 XUngrabServer(dpy);
1531 arrange();
1532 }
1533
1534 void
1535 unmapnotify(XEvent *e) {
1536 Client *c;
1537 XUnmapEvent *ev = &e->xunmap;
1538
1539 if((c = getclient(ev->window)))
1540 unmanage(c);
1541 }
1542
1543 void
1544 updatebar(void) {
1545 if(dc.drawable != 0)
1546 XFreePixmap(dpy, dc.drawable);
1547 dc.drawable = XCreatePixmap(dpy, root, ww, bh, DefaultDepth(dpy, screen));
1548 XMoveResizeWindow(dpy, barwin, wx, by, ww, bh);
1549 }
1550
1551 void
1552 updategeom(void) {
1553 #ifdef XINERAMA
1554 int i;
1555 XineramaScreenInfo *info = NULL;
1556
1557 /* window area geometry */
1558 if(XineramaIsActive(dpy)) {
1559 info = XineramaQueryScreens(dpy, &i);
1560 wx = info[xidx].x_org;
1561 wy = showbar && topbar ? info[xidx].y_org + bh : info[xidx].y_org;
1562 ww = info[xidx].width;
1563 wh = showbar ? info[xidx].height - bh : info[xidx].height;
1564 XFree(info);
1565 }
1566 else
1567 #endif
1568 {
1569 wx = sx;
1570 wy = showbar && topbar ? sy + bh : sy;
1571 ww = sw;
1572 wh = showbar ? sh - bh : sh;
1573 }
1574
1575 /* bar position */
1576 by = showbar ? (topbar ? wy - bh : wy + wh) : -bh;
1577 }
1578
1579 void
1580 updatesizehints(Client *c) {
1581 long msize;
1582 XSizeHints size;
1583
1584 XGetWMNormalHints(dpy, c->win, &size, &msize);
1585 if(size.flags & PBaseSize) {
1586 c->basew = size.base_width;
1587 c->baseh = size.base_height;
1588 }
1589 else if(size.flags & PMinSize) {
1590 c->basew = size.min_width;
1591 c->baseh = size.min_height;
1592 }
1593 else
1594 c->basew = c->baseh = 0;
1595 if(size.flags & PResizeInc) {
1596 c->incw = size.width_inc;
1597 c->inch = size.height_inc;
1598 }
1599 else
1600 c->incw = c->inch = 0;
1601 if(size.flags & PMaxSize) {
1602 c->maxw = size.max_width;
1603 c->maxh = size.max_height;
1604 }
1605 else
1606 c->maxw = c->maxh = 0;
1607 if(size.flags & PMinSize) {
1608 c->minw = size.min_width;
1609 c->minh = size.min_height;
1610 }
1611 else if(size.flags & PBaseSize) {
1612 c->minw = size.base_width;
1613 c->minh = size.base_height;
1614 }
1615 else
1616 c->minw = c->minh = 0;
1617 if(size.flags & PAspect) {
1618 c->mina = (float)size.min_aspect.y / (float)size.min_aspect.x;
1619 c->maxa = (float)size.max_aspect.x / (float)size.max_aspect.y;
1620 }
1621 else
1622 c->maxa = c->mina = 0.0;
1623 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1624 && c->maxw == c->minw && c->maxh == c->minh);
1625 }
1626
1627 void
1628 updatetitle(Client *c) {
1629 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1630 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1631 }
1632
1633 void
1634 updatewmhints(Client *c) {
1635 XWMHints *wmh;
1636
1637 if((wmh = XGetWMHints(dpy, c->win))) {
1638 if(c == sel)
1639 sel->isurgent = False;
1640 else
1641 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1642 XFree(wmh);
1643 }
1644 }
1645
1646 void
1647 view(const Arg *arg) {
1648 seltags ^= 1; /* toggle sel tagset */
1649 if(arg && (arg->ui & TAGMASK) && (arg->ui & TAGMASK) != tagset[seltags ^ 1])
1650 tagset[seltags] = arg->i & TAGMASK;
1651 arrange();
1652 }
1653
1654 /* There's no way to check accesses to destroyed windows, thus those cases are
1655 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1656 * default error handler, which may call exit. */
1657 int
1658 xerror(Display *dpy, XErrorEvent *ee) {
1659 if(ee->error_code == BadWindow
1660 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1661 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1662 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1663 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1664 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1665 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1666 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1667 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1668 return 0;
1669 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1670 ee->request_code, ee->error_code);
1671 return xerrorxlib(dpy, ee); /* may call exit */
1672 }
1673
1674 int
1675 xerrordummy(Display *dpy, XErrorEvent *ee) {
1676 return 0;
1677 }
1678
1679 /* Startup Error handler to check if another window manager
1680 * is already running. */
1681 int
1682 xerrorstart(Display *dpy, XErrorEvent *ee) {
1683 otherwm = True;
1684 return -1;
1685 }
1686
1687 void
1688 zoom(const Arg *arg) {
1689 Client *c = sel;
1690
1691 if(ismax || !lt->arrange || (sel && sel->isfloating))
1692 return;
1693 if(c == nexttiled(clients))
1694 if(!c || !(c = nexttiled(c->next)))
1695 return;
1696 detach(c);
1697 attach(c);
1698 focus(c);
1699 arrange();
1700 }
1701
1702 int
1703 main(int argc, char *argv[]) {
1704 if(argc == 2 && !strcmp("-v", argv[1]))
1705 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1706 else if(argc != 1)
1707 eprint("usage: dwm [-v]\n");
1708
1709 setlocale(LC_CTYPE, "");
1710 if(!(dpy = XOpenDisplay(0)))
1711 eprint("dwm: cannot open display\n");
1712
1713 checkotherwm();
1714 setup();
1715 scan();
1716 run();
1717 cleanup();
1718
1719 XCloseDisplay(dpy);
1720 return 0;
1721 }