Xinqi Bao's Git

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