Xinqi Bao's Git

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