Xinqi Bao's Git

does this fix anything?
[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 #define ISVISIBLE(x) (x->tags & tagset[seltags])
57
58 /* enums */
59 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
60 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
61 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
62 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
63 enum { ClkTagBar, ClkLtSymbol, ClkStatusText, ClkWinTitle,
64 ClkClientWin, ClkRootWin, ClkLast }; /* clicks */
65
66 /* typedefs */
67 typedef unsigned int uint;
68 typedef unsigned long ulong;
69
70 typedef union {
71 int i;
72 uint ui;
73 float f;
74 void *v;
75 } Arg;
76
77 typedef struct {
78 uint click;
79 uint mask;
80 uint button;
81 void (*func)(const Arg *arg);
82 const Arg arg;
83 } Button;
84
85 typedef struct Client Client;
86 struct Client {
87 char name[256];
88 float mina, maxa;
89 int x, y, w, h;
90 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
91 int bw, oldbw;
92 uint tags;
93 Bool isfixed, isfloating, isurgent;
94 Client *next;
95 Client *snext;
96 Window win;
97 };
98
99 typedef struct {
100 int x, y, w, h;
101 ulong norm[ColLast];
102 ulong sel[ColLast];
103 Drawable drawable;
104 GC gc;
105 struct {
106 int ascent;
107 int descent;
108 int height;
109 XFontSet set;
110 XFontStruct *xfont;
111 } font;
112 } DC; /* draw context */
113
114 typedef struct {
115 uint mod;
116 KeySym keysym;
117 void (*func)(const Arg *);
118 const Arg arg;
119 } Key;
120
121 typedef struct {
122 const char *symbol;
123 void (*arrange)(void);
124 } Layout;
125
126 typedef struct {
127 const char *class;
128 const char *instance;
129 const char *title;
130 uint tags;
131 Bool isfloating;
132 } Rule;
133
134 /* function declarations */
135 static void applyrules(Client *c);
136 static void arrange(void);
137 static void attach(Client *c);
138 static void attachstack(Client *c);
139 static void buttonpress(XEvent *e);
140 static void checkotherwm(void);
141 static void cleanup(void);
142 static void configure(Client *c);
143 static void configurenotify(XEvent *e);
144 static void configurerequest(XEvent *e);
145 static void destroynotify(XEvent *e);
146 static void detach(Client *c);
147 static void detachstack(Client *c);
148 static void drawbar(void);
149 static void drawsquare(Bool filled, Bool empty, Bool invert, ulong col[ColLast]);
150 static void drawtext(const char *text, ulong col[ColLast], Bool invert);
151 static void enternotify(XEvent *e);
152 static void eprint(const char *errstr, ...);
153 static void expose(XEvent *e);
154 static void focus(Client *c);
155 static void focusin(XEvent *e);
156 static void focusstack(const Arg *arg);
157 static Client *getclient(Window w);
158 static ulong getcolor(const char *colstr);
159 static long getstate(Window w);
160 static Bool gettextprop(Window w, Atom atom, char *text, uint size);
161 static void grabbuttons(Client *c, Bool focused);
162 static void grabkeys(void);
163 static void initfont(const char *fontstr);
164 static Bool isoccupied(uint t);
165 static Bool isprotodel(Client *c);
166 static Bool isurgent(uint t);
167 static void keypress(XEvent *e);
168 static void killclient(const Arg *arg);
169 static void manage(Window w, XWindowAttributes *wa);
170 static void mappingnotify(XEvent *e);
171 static void maprequest(XEvent *e);
172 static void monocle(void);
173 static void movemouse(const Arg *arg);
174 static Client *nexttiled(Client *c);
175 static void propertynotify(XEvent *e);
176 static void quit(const Arg *arg);
177 static void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
178 static void resizemouse(const Arg *arg);
179 static void restack(void);
180 static void run(void);
181 static void scan(void);
182 static void setclientstate(Client *c, long state);
183 static void setlayout(const Arg *arg);
184 static void setmfact(const Arg *arg);
185 static void setup(void);
186 static void spawn(const Arg *arg);
187 static void tag(const Arg *arg);
188 static int textnw(const char *text, uint len);
189 static void tile(void);
190 static void togglebar(const Arg *arg);
191 static void togglefloating(const Arg *arg);
192 static void toggletag(const Arg *arg);
193 static void toggleview(const Arg *arg);
194 static void unmanage(Client *c);
195 static void unmapnotify(XEvent *e);
196 static void updatebar(void);
197 static void updategeom(void);
198 static void updatesizehints(Client *c);
199 static void updatetitle(Client *c);
200 static void updatewmhints(Client *c);
201 static void view(const Arg *arg);
202 static int xerror(Display *dpy, XErrorEvent *ee);
203 static int xerrordummy(Display *dpy, XErrorEvent *ee);
204 static int xerrorstart(Display *dpy, XErrorEvent *ee);
205 static void zoom(const Arg *arg);
206
207 /* variables */
208 static char stext[256];
209 static int screen, sx, sy, sw, sh;
210 static int by, bh, blw, wx, wy, ww, wh;
211 static uint seltags = 0, sellt = 0;
212 static int (*xerrorxlib)(Display *, XErrorEvent *);
213 static uint numlockmask = 0;
214 static void (*handler[LASTEvent]) (XEvent *) = {
215 [ButtonPress] = buttonpress,
216 [ConfigureRequest] = configurerequest,
217 [ConfigureNotify] = configurenotify,
218 [DestroyNotify] = destroynotify,
219 [EnterNotify] = enternotify,
220 [Expose] = expose,
221 [FocusIn] = focusin,
222 [KeyPress] = keypress,
223 [MappingNotify] = mappingnotify,
224 [MapRequest] = maprequest,
225 [PropertyNotify] = propertynotify,
226 [UnmapNotify] = unmapnotify
227 };
228 static Atom wmatom[WMLast], netatom[NetLast];
229 static Bool otherwm, readin;
230 static Bool running = True;
231 static uint tagset[] = {1, 1}; /* after start, first tag is selected */
232 static Client *clients = NULL;
233 static Client *sel = NULL;
234 static Client *stack = NULL;
235 static Cursor cursor[CurLast];
236 static Display *dpy;
237 static DC dc = {0};
238 static Layout *lt[] = { NULL, NULL };
239 static Window root, barwin;
240 /* configuration, allows nested code to access above variables */
241 #include "config.h"
242
243 /* compile-time check if all tags fit into an uint bit array. */
244 struct NumTags { char limitexceeded[sizeof(uint) * 8 < LENGTH(tags) ? -1 : 1]; };
245
246 /* function implementations */
247 void
248 applyrules(Client *c) {
249 uint i;
250 Rule *r;
251 XClassHint ch = { 0 };
252
253 /* rule matching */
254 XGetClassHint(dpy, c->win, &ch);
255 for(i = 0; i < LENGTH(rules); i++) {
256 r = &rules[i];
257 if((!r->title || strstr(c->name, r->title))
258 && (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
259 && (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
260 c->isfloating = r->isfloating;
261 c->tags |= r->tags & TAGMASK;
262 }
263 }
264 if(ch.res_class)
265 XFree(ch.res_class);
266 if(ch.res_name)
267 XFree(ch.res_name);
268 if(!c->tags)
269 c->tags = tagset[seltags];
270 }
271
272 void
273 arrange(void) {
274 Client *c;
275
276 for(c = clients; c; c = c->next)
277 if(ISVISIBLE(c)) {
278 XMoveWindow(dpy, c->win, c->x, c->y);
279 if(!lt[sellt]->arrange || c->isfloating)
280 resize(c, c->x, c->y, c->w, c->h, True);
281 }
282 else {
283 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
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 Arg arg = {0};
308 Client *c;
309 XButtonPressedEvent *ev = &e->xbutton;
310
311 click = ClkRootWin;
312 if(ev->window == barwin) {
313 for(i = x = 0; ev->x >= x && ++i < LENGTH(tags); i++)
314 x += TEXTW(tags[i]);
315 if(i < LENGTH(tags)) {
316 click = ClkTagBar;
317 arg.ui = 1 << i;
318 }
319 else if(ev->x < x + blw)
320 click = ClkLtSymbol;
321 else if(ev->x > wx + ww - TEXTW(stext))
322 click = ClkStatusText;
323 else
324 click = ClkWinTitle;
325 }
326 else if((c = getclient(ev->window))) {
327 focus(c);
328 click = ClkClientWin;
329 }
330
331 for(i = 0; i < LENGTH(buttons); i++)
332 if(click == buttons[i].click && buttons[i].func && buttons[i].button == ev->button
333 && CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
334 buttons[i].func(click == ClkTagBar ? &arg : &buttons[i].arg);
335 }
336
337 void
338 checkotherwm(void) {
339 otherwm = False;
340 XSetErrorHandler(xerrorstart);
341
342 /* this causes an error if some other window manager is running */
343 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
344 XSync(dpy, False);
345 if(otherwm)
346 eprint("dwm: another window manager is already running\n");
347 XSetErrorHandler(NULL);
348 xerrorxlib = XSetErrorHandler(xerror);
349 XSync(dpy, False);
350 }
351
352 void
353 cleanup(void) {
354 Arg a = {.i = ~0};
355 Layout foo = { "", NULL };
356
357 close(STDIN_FILENO);
358 view(&a);
359 lt[sellt] = &foo;
360 while(stack)
361 unmanage(stack);
362 if(dc.font.set)
363 XFreeFontSet(dpy, dc.font.set);
364 else
365 XFreeFont(dpy, dc.font.xfont);
366 XUngrabKey(dpy, AnyKey, AnyModifier, root);
367 XFreePixmap(dpy, dc.drawable);
368 XFreeGC(dpy, dc.gc);
369 XFreeCursor(dpy, cursor[CurNormal]);
370 XFreeCursor(dpy, cursor[CurResize]);
371 XFreeCursor(dpy, cursor[CurMove]);
372 XDestroyWindow(dpy, barwin);
373 XSync(dpy, False);
374 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
375 }
376
377 void
378 configure(Client *c) {
379 XConfigureEvent ce;
380
381 ce.type = ConfigureNotify;
382 ce.display = dpy;
383 ce.event = c->win;
384 ce.window = c->win;
385 ce.x = c->x;
386 ce.y = c->y;
387 ce.width = c->w;
388 ce.height = c->h;
389 ce.border_width = c->bw;
390 ce.above = None;
391 ce.override_redirect = False;
392 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
393 }
394
395 void
396 configurenotify(XEvent *e) {
397 XConfigureEvent *ev = &e->xconfigure;
398
399 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
400 sw = ev->width;
401 sh = ev->height;
402 updategeom();
403 updatebar();
404 arrange();
405 }
406 }
407
408 void
409 configurerequest(XEvent *e) {
410 Client *c;
411 XConfigureRequestEvent *ev = &e->xconfigurerequest;
412 XWindowChanges wc;
413
414 if((c = getclient(ev->window))) {
415 if(ev->value_mask & CWBorderWidth)
416 c->bw = ev->border_width;
417 else if(c->isfloating || !lt[sellt]->arrange) {
418 if(ev->value_mask & CWX)
419 c->x = sx + ev->x;
420 if(ev->value_mask & CWY)
421 c->y = sy + ev->y;
422 if(ev->value_mask & CWWidth)
423 c->w = ev->width;
424 if(ev->value_mask & CWHeight)
425 c->h = ev->height;
426 if((c->x - sx + c->w) > sw && c->isfloating)
427 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
428 if((c->y - sy + c->h) > sh && c->isfloating)
429 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
430 if((ev->value_mask & (CWX|CWY)) && !(ev->value_mask & (CWWidth|CWHeight)))
431 configure(c);
432 if(ISVISIBLE(c))
433 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
434 }
435 else
436 configure(c);
437 }
438 else {
439 wc.x = ev->x;
440 wc.y = ev->y;
441 wc.width = ev->width;
442 wc.height = ev->height;
443 wc.border_width = ev->border_width;
444 wc.sibling = ev->above;
445 wc.stack_mode = ev->detail;
446 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
447 }
448 XSync(dpy, False);
449 }
450
451 void
452 destroynotify(XEvent *e) {
453 Client *c;
454 XDestroyWindowEvent *ev = &e->xdestroywindow;
455
456 if((c = getclient(ev->window)))
457 unmanage(c);
458 }
459
460 void
461 detach(Client *c) {
462 Client *i;
463
464 if (c != clients) {
465 for(i = clients; i->next != c; i = i->next);
466 i->next = c->next;
467 }
468 else {
469 clients = c->next;
470 }
471 c->next = NULL;
472 }
473
474 void
475 detachstack(Client *c) {
476 Client **tc;
477
478 for(tc = &stack; *tc && *tc != c; tc = &(*tc)->snext);
479 *tc = c->snext;
480 }
481
482 void
483 drawbar(void) {
484 int i, x;
485
486 dc.x = 0;
487 for(i = 0; i < LENGTH(tags); i++) {
488 dc.w = TEXTW(tags[i]);
489 if(tagset[seltags] & 1 << i) {
490 drawtext(tags[i], dc.sel, isurgent(i));
491 drawsquare(sel && sel->tags & 1 << i, isoccupied(i), isurgent(i), dc.sel);
492 }
493 else {
494 drawtext(tags[i], dc.norm, isurgent(i));
495 drawsquare(sel && sel->tags & 1 << i, isoccupied(i), isurgent(i), dc.norm);
496 }
497 dc.x += dc.w;
498 }
499 if(blw > 0) {
500 dc.w = blw;
501 drawtext(lt[sellt]->symbol, dc.norm, False);
502 x = dc.x + dc.w;
503 }
504 else
505 x = dc.x;
506 dc.w = TEXTW(stext);
507 dc.x = ww - dc.w;
508 if(dc.x < x) {
509 dc.x = x;
510 dc.w = ww - x;
511 }
512 drawtext(stext, dc.norm, False);
513 if((dc.w = dc.x - x) > bh) {
514 dc.x = x;
515 if(sel) {
516 drawtext(sel->name, dc.sel, False);
517 drawsquare(sel->isfixed, sel->isfloating, False, dc.sel);
518 }
519 else
520 drawtext(NULL, dc.norm, False);
521 }
522 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, ww, bh, 0, 0);
523 XSync(dpy, False);
524 }
525
526 void
527 drawsquare(Bool filled, Bool empty, Bool invert, ulong col[ColLast]) {
528 int x;
529 XGCValues gcv;
530 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
531
532 gcv.foreground = col[invert ? ColBG : ColFG];
533 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
534 x = (dc.font.ascent + dc.font.descent + 2) / 4;
535 r.x = dc.x + 1;
536 r.y = dc.y + 1;
537 if(filled) {
538 r.width = r.height = x + 1;
539 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
540 }
541 else if(empty) {
542 r.width = r.height = x;
543 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
544 }
545 }
546
547 void
548 drawtext(const char *text, ulong col[ColLast], Bool invert) {
549 int i, x, y, h, len, olen;
550 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
551 char buf[256];
552
553 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
554 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
555 if(!text)
556 return;
557 olen = strlen(text);
558 len = MIN(olen, sizeof buf);
559 memcpy(buf, text, len);
560 h = dc.font.ascent + dc.font.descent;
561 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
562 x = dc.x + (h / 2);
563 /* shorten text if necessary */
564 for(; len && (i = textnw(buf, len)) > dc.w - h; len--);
565 if(!len)
566 return;
567 if(len < olen)
568 for(i = len; i && i > len - 3; buf[--i] = '.');
569 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
570 if(dc.font.set)
571 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
572 else
573 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
574 }
575
576 void
577 enternotify(XEvent *e) {
578 Client *c;
579 XCrossingEvent *ev = &e->xcrossing;
580
581 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
582 return;
583 if((c = getclient(ev->window)))
584 focus(c);
585 else
586 focus(NULL);
587 }
588
589 void
590 eprint(const char *errstr, ...) {
591 va_list ap;
592
593 va_start(ap, errstr);
594 vfprintf(stderr, errstr, ap);
595 va_end(ap);
596 exit(EXIT_FAILURE);
597 }
598
599 void
600 expose(XEvent *e) {
601 XExposeEvent *ev = &e->xexpose;
602
603 if(ev->count == 0 && (ev->window == barwin))
604 drawbar();
605 }
606
607 void
608 focus(Client *c) {
609 if(!c || !ISVISIBLE(c))
610 for(c = stack; c && !ISVISIBLE(c); c = c->snext);
611 if(sel && sel != c) {
612 grabbuttons(sel, False);
613 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
614 }
615 if(c) {
616 detachstack(c);
617 attachstack(c);
618 grabbuttons(c, True);
619 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
620 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
621 }
622 else
623 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
624 sel = c;
625 drawbar();
626 }
627
628 void
629 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
630 XFocusChangeEvent *ev = &e->xfocus;
631
632 if(sel && ev->window != sel->win)
633 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
634 }
635
636 void
637 focusstack(const Arg *arg) {
638 Client *c = NULL, *i;
639
640 if(!sel)
641 return;
642 if (arg->i > 0) {
643 for(c = sel->next; c && !ISVISIBLE(c); c = c->next);
644 if(!c)
645 for(c = clients; c && !ISVISIBLE(c); c = c->next);
646 }
647 else {
648 for(i = clients; i != sel; i = i->next)
649 if(ISVISIBLE(i))
650 c = i;
651 if(!c)
652 for(; i; i = i->next)
653 if(ISVISIBLE(i))
654 c = i;
655 }
656 if(c) {
657 focus(c);
658 restack();
659 }
660 }
661
662 Client *
663 getclient(Window w) {
664 Client *c;
665
666 for(c = clients; c && c->win != w; c = c->next);
667 return c;
668 }
669
670 ulong
671 getcolor(const char *colstr) {
672 Colormap cmap = DefaultColormap(dpy, screen);
673 XColor color;
674
675 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
676 eprint("error, cannot allocate color '%s'\n", colstr);
677 return color.pixel;
678 }
679
680 long
681 getstate(Window w) {
682 int format, status;
683 long result = -1;
684 unsigned char *p = NULL;
685 ulong n, extra;
686 Atom real;
687
688 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
689 &real, &format, &n, &extra, (unsigned char **)&p);
690 if(status != Success)
691 return -1;
692 if(n != 0)
693 result = *p;
694 XFree(p);
695 return result;
696 }
697
698 Bool
699 gettextprop(Window w, Atom atom, char *text, uint size) {
700 char **list = NULL;
701 int n;
702 XTextProperty name;
703
704 if(!text || size == 0)
705 return False;
706 text[0] = '\0';
707 XGetTextProperty(dpy, w, &name, atom);
708 if(!name.nitems)
709 return False;
710 if(name.encoding == XA_STRING)
711 strncpy(text, (char *)name.value, size - 1);
712 else {
713 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
714 && n > 0 && *list) {
715 strncpy(text, *list, size - 1);
716 XFreeStringList(list);
717 }
718 }
719 text[size - 1] = '\0';
720 XFree(name.value);
721 return True;
722 }
723
724 void
725 grabbuttons(Client *c, Bool focused) {
726 int i, j;
727 uint buttons[] = { Button1, Button2, Button3 };
728 uint modifiers[] = { MODKEY, MODKEY|LockMask, MODKEY|numlockmask, MODKEY|numlockmask|LockMask };
729
730 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
731 if(focused)
732 for(i = 0; i < LENGTH(buttons); i++)
733 for(j = 0; j < LENGTH(modifiers); j++)
734 XGrabButton(dpy, buttons[i], modifiers[j], c->win, False,
735 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
736 else
737 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
738 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
739 }
740
741 void
742 grabkeys(void) {
743 uint i, j;
744 KeyCode code;
745 XModifierKeymap *modmap;
746
747 /* init modifier map */
748 modmap = XGetModifierMapping(dpy);
749 for(i = 0; i < 8; i++)
750 for(j = 0; j < modmap->max_keypermod; j++) {
751 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
752 numlockmask = (1 << i);
753 }
754 XFreeModifiermap(modmap);
755
756 XUngrabKey(dpy, AnyKey, AnyModifier, root);
757 for(i = 0; i < LENGTH(keys); i++) {
758 code = XKeysymToKeycode(dpy, keys[i].keysym);
759 XGrabKey(dpy, code, keys[i].mod, root, True,
760 GrabModeAsync, GrabModeAsync);
761 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
762 GrabModeAsync, GrabModeAsync);
763 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
764 GrabModeAsync, GrabModeAsync);
765 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
766 GrabModeAsync, GrabModeAsync);
767 }
768 }
769
770 void
771 initfont(const char *fontstr) {
772 char *def, **missing;
773 int i, n;
774
775 missing = NULL;
776 if(dc.font.set)
777 XFreeFontSet(dpy, dc.font.set);
778 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
779 if(missing) {
780 while(n--)
781 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
782 XFreeStringList(missing);
783 }
784 if(dc.font.set) {
785 XFontSetExtents *font_extents;
786 XFontStruct **xfonts;
787 char **font_names;
788 dc.font.ascent = dc.font.descent = 0;
789 font_extents = XExtentsOfFontSet(dc.font.set);
790 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
791 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
792 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
793 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
794 xfonts++;
795 }
796 }
797 else {
798 if(dc.font.xfont)
799 XFreeFont(dpy, dc.font.xfont);
800 dc.font.xfont = NULL;
801 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
802 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
803 eprint("error, cannot load font: '%s'\n", fontstr);
804 dc.font.ascent = dc.font.xfont->ascent;
805 dc.font.descent = dc.font.xfont->descent;
806 }
807 dc.font.height = dc.font.ascent + dc.font.descent;
808 }
809
810 Bool
811 isoccupied(uint t) {
812 Client *c;
813
814 for(c = clients; c; c = c->next)
815 if(c->tags & 1 << t)
816 return True;
817 return False;
818 }
819
820 Bool
821 isprotodel(Client *c) {
822 int i, n;
823 Atom *protocols;
824 Bool ret = False;
825
826 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
827 for(i = 0; !ret && i < n; i++)
828 if(protocols[i] == wmatom[WMDelete])
829 ret = True;
830 XFree(protocols);
831 }
832 return ret;
833 }
834
835 Bool
836 isurgent(uint t) {
837 Client *c;
838
839 for(c = clients; c; c = c->next)
840 if(c->isurgent && c->tags & 1 << t)
841 return True;
842 return False;
843 }
844
845 void
846 keypress(XEvent *e) {
847 uint i;
848 KeySym keysym;
849 XKeyEvent *ev;
850
851 ev = &e->xkey;
852 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
853 for(i = 0; i < LENGTH(keys); i++)
854 if(keysym == keys[i].keysym
855 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
856 && keys[i].func)
857 keys[i].func(&(keys[i].arg));
858 }
859
860 void
861 killclient(const Arg *arg) {
862 XEvent ev;
863
864 if(!sel)
865 return;
866 if(isprotodel(sel)) {
867 ev.type = ClientMessage;
868 ev.xclient.window = sel->win;
869 ev.xclient.message_type = wmatom[WMProtocols];
870 ev.xclient.format = 32;
871 ev.xclient.data.l[0] = wmatom[WMDelete];
872 ev.xclient.data.l[1] = CurrentTime;
873 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
874 }
875 else
876 XKillClient(dpy, sel->win);
877 }
878
879 void
880 manage(Window w, XWindowAttributes *wa) {
881 Client *c, *t = NULL;
882 Status rettrans;
883 Window trans;
884 XWindowChanges wc;
885
886 if(!(c = calloc(1, sizeof(Client))))
887 eprint("fatal: could not calloc() %u bytes\n", sizeof(Client));
888 c->win = w;
889
890 /* geometry */
891 c->x = wa->x;
892 c->y = wa->y;
893 c->w = wa->width;
894 c->h = wa->height;
895 c->oldbw = wa->border_width;
896 if(c->w == sw && c->h == sh) {
897 c->x = sx;
898 c->y = sy;
899 c->bw = wa->border_width;
900 }
901 else {
902 if(c->x + c->w + 2 * c->bw > sx + sw)
903 c->x = sx + sw - c->w - 2 * c->bw;
904 if(c->y + c->h + 2 * c->bw > sy + sh)
905 c->y = sy + sh - c->h - 2 * c->bw;
906 c->x = MAX(c->x, sx);
907 /* only fix client y-offset, if the client center might cover the bar */
908 c->y = MAX(c->y, ((by == 0) && (c->x + (c->w / 2) >= wx) && (c->x + (c->w / 2) < wx + ww)) ? bh : sy);
909 c->bw = borderpx;
910 }
911
912 wc.border_width = c->bw;
913 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
914 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
915 configure(c); /* propagates border_width, if size doesn't change */
916 updatesizehints(c);
917 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
918 grabbuttons(c, False);
919 updatetitle(c);
920 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
921 for(t = clients; t && t->win != trans; t = t->next);
922 if(t)
923 c->tags = t->tags;
924 else
925 applyrules(c);
926 if(!c->isfloating)
927 c->isfloating = (rettrans == Success) || c->isfixed;
928 if(c->isfloating)
929 XRaiseWindow(dpy, c->win);
930 attach(c);
931 attachstack(c);
932 XMoveResizeWindow(dpy, c->win, c->x + 2 * sw, c->y, c->w, c->h); /* some windows require this */
933 XMapWindow(dpy, c->win);
934 setclientstate(c, NormalState);
935 arrange();
936 }
937
938 void
939 mappingnotify(XEvent *e) {
940 XMappingEvent *ev = &e->xmapping;
941
942 XRefreshKeyboardMapping(ev);
943 if(ev->request == MappingKeyboard)
944 grabkeys();
945 }
946
947 void
948 maprequest(XEvent *e) {
949 static XWindowAttributes wa;
950 XMapRequestEvent *ev = &e->xmaprequest;
951
952 if(!XGetWindowAttributes(dpy, ev->window, &wa))
953 return;
954 if(wa.override_redirect)
955 return;
956 if(!getclient(ev->window))
957 manage(ev->window, &wa);
958 }
959
960 void
961 monocle(void) {
962 Client *c;
963
964 for(c = nexttiled(clients); c; c = nexttiled(c->next))
965 resize(c, wx, wy, ww, wh, resizehints);
966 }
967
968 void
969 movemouse(const Arg *arg) {
970 int x1, y1, ocx, ocy, di, nx, ny;
971 uint dui;
972 Client *c;
973 Window dummy;
974 XEvent ev;
975
976 if(!(c = sel))
977 return;
978 restack();
979 ocx = nx = c->x;
980 ocy = ny = c->y;
981 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
982 None, cursor[CurMove], CurrentTime) != GrabSuccess)
983 return;
984 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
985 for(;;) {
986 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
987 switch (ev.type) {
988 case ButtonRelease:
989 XUngrabPointer(dpy, CurrentTime);
990 return;
991 case ConfigureRequest:
992 case Expose:
993 case MapRequest:
994 handler[ev.type](&ev);
995 break;
996 case MotionNotify:
997 XSync(dpy, False);
998 nx = ocx + (ev.xmotion.x - x1);
999 ny = ocy + (ev.xmotion.y - y1);
1000 if(snap && nx >= wx && nx <= wx + ww
1001 && ny >= wy && ny <= wy + wh) {
1002 if(abs(wx - nx) < snap)
1003 nx = wx;
1004 else if(abs((wx + ww) - (nx + c->w + 2 * c->bw)) < snap)
1005 nx = wx + ww - c->w - 2 * c->bw;
1006 if(abs(wy - ny) < snap)
1007 ny = wy;
1008 else if(abs((wy + wh) - (ny + c->h + 2 * c->bw)) < snap)
1009 ny = wy + wh - c->h - 2 * c->bw;
1010 if(!c->isfloating && lt[sellt]->arrange && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
1011 togglefloating(NULL);
1012 }
1013 if(!lt[sellt]->arrange || c->isfloating)
1014 resize(c, nx, ny, c->w, c->h, False);
1015 break;
1016 }
1017 }
1018 }
1019
1020 Client *
1021 nexttiled(Client *c) {
1022 for(; c && (c->isfloating || !ISVISIBLE(c)); c = c->next);
1023 return c;
1024 }
1025
1026 void
1027 propertynotify(XEvent *e) {
1028 Client *c;
1029 Window trans;
1030 XPropertyEvent *ev = &e->xproperty;
1031
1032 if(ev->state == PropertyDelete)
1033 return; /* ignore */
1034 if((c = getclient(ev->window))) {
1035 switch (ev->atom) {
1036 default: break;
1037 case XA_WM_TRANSIENT_FOR:
1038 XGetTransientForHint(dpy, c->win, &trans);
1039 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1040 arrange();
1041 break;
1042 case XA_WM_NORMAL_HINTS:
1043 updatesizehints(c);
1044 break;
1045 case XA_WM_HINTS:
1046 updatewmhints(c);
1047 drawbar();
1048 break;
1049 }
1050 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1051 updatetitle(c);
1052 if(c == sel)
1053 drawbar();
1054 }
1055 }
1056 }
1057
1058 void
1059 quit(const Arg *arg) {
1060 readin = running = False;
1061 }
1062
1063 void
1064 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1065 XWindowChanges wc;
1066
1067 if(sizehints) {
1068 /* set minimum possible */
1069 w = MAX(1, w);
1070 h = MAX(1, h);
1071
1072 /* temporarily remove base dimensions */
1073 w -= c->basew;
1074 h -= c->baseh;
1075
1076 /* adjust for aspect limits */
1077 if(c->mina > 0 && c->maxa > 0) {
1078 if(c->maxa < (float) w/h)
1079 w = h * c->maxa;
1080 else if(c->mina > (float) h/w)
1081 h = w * c->mina;
1082 }
1083
1084 /* adjust for increment value */
1085 if(c->incw)
1086 w -= w % c->incw;
1087 if(c->inch)
1088 h -= h % c->inch;
1089
1090 /* restore base dimensions */
1091 w += c->basew;
1092 h += c->baseh;
1093
1094 w = MAX(w, c->minw);
1095 h = MAX(h, c->minh);
1096
1097 if(c->maxw)
1098 w = MIN(w, c->maxw);
1099
1100 if(c->maxh)
1101 h = MIN(h, c->maxh);
1102 }
1103 if(w <= 0 || h <= 0)
1104 return;
1105 if(x > sx + sw)
1106 x = sw - w - 2 * c->bw;
1107 if(y > sy + sh)
1108 y = sh - h - 2 * c->bw;
1109 if(x + w + 2 * c->bw < sx)
1110 x = sx;
1111 if(y + h + 2 * c->bw < sy)
1112 y = sy;
1113 if(h < bh)
1114 h = bh;
1115 if(w < bh)
1116 w = bh;
1117 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1118 c->x = wc.x = x;
1119 c->y = wc.y = y;
1120 c->w = wc.width = w;
1121 c->h = wc.height = h;
1122 wc.border_width = c->bw;
1123 XConfigureWindow(dpy, c->win,
1124 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1125 configure(c);
1126 XSync(dpy, False);
1127 }
1128 }
1129
1130 void
1131 resizemouse(const Arg *arg) {
1132 int ocx, ocy;
1133 int nw, nh;
1134 Client *c;
1135 XEvent ev;
1136
1137 if(!(c = sel))
1138 return;
1139 restack();
1140 ocx = c->x;
1141 ocy = c->y;
1142 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1143 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1144 return;
1145 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1146 for(;;) {
1147 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1148 switch(ev.type) {
1149 case ButtonRelease:
1150 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1151 c->w + c->bw - 1, c->h + c->bw - 1);
1152 XUngrabPointer(dpy, CurrentTime);
1153 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1154 return;
1155 case ConfigureRequest:
1156 case Expose:
1157 case MapRequest:
1158 handler[ev.type](&ev);
1159 break;
1160 case MotionNotify:
1161 XSync(dpy, False);
1162 nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1163 nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1164
1165 if(snap && nw >= wx && nw <= wx + ww
1166 && nh >= wy && nh <= wy + wh) {
1167 if(!c->isfloating && lt[sellt]->arrange
1168 && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1169 togglefloating(NULL);
1170 }
1171 if(!lt[sellt]->arrange || c->isfloating)
1172 resize(c, c->x, c->y, nw, nh, True);
1173 break;
1174 }
1175 }
1176 }
1177
1178 void
1179 restack(void) {
1180 Client *c;
1181 XEvent ev;
1182 XWindowChanges wc;
1183
1184 drawbar();
1185 if(!sel)
1186 return;
1187 if(sel->isfloating || !lt[sellt]->arrange)
1188 XRaiseWindow(dpy, sel->win);
1189 if(lt[sellt]->arrange) {
1190 wc.stack_mode = Below;
1191 wc.sibling = barwin;
1192 for(c = stack; c; c = c->snext)
1193 if(!c->isfloating && ISVISIBLE(c)) {
1194 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1195 wc.sibling = c->win;
1196 }
1197 }
1198 XSync(dpy, False);
1199 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1200 }
1201
1202 void
1203 run(void) {
1204 char *p;
1205 char sbuf[sizeof stext];
1206 fd_set rd;
1207 int r, xfd;
1208 uint len, offset;
1209 XEvent ev;
1210
1211 /* main event loop, also reads status text from stdin */
1212 XSync(dpy, False);
1213 xfd = ConnectionNumber(dpy);
1214 readin = True;
1215 offset = 0;
1216 len = sizeof stext - 1;
1217 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1218 while(running) {
1219 FD_ZERO(&rd);
1220 if(readin)
1221 FD_SET(STDIN_FILENO, &rd);
1222 FD_SET(xfd, &rd);
1223 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1224 if(errno == EINTR)
1225 continue;
1226 eprint("select failed\n");
1227 }
1228 if(FD_ISSET(STDIN_FILENO, &rd)) {
1229 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1230 case -1:
1231 strncpy(stext, strerror(errno), len);
1232 readin = False;
1233 break;
1234 case 0:
1235 strncpy(stext, "EOF", 4);
1236 readin = False;
1237 break;
1238 default:
1239 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1240 if(*p == '\n' || *p == '\0') {
1241 *p = '\0';
1242 strncpy(stext, sbuf, len);
1243 p += r - 1; /* p is sbuf + offset + r - 1 */
1244 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1245 offset = r;
1246 if(r)
1247 memmove(sbuf, p - r + 1, r);
1248 break;
1249 }
1250 break;
1251 }
1252 drawbar();
1253 }
1254 while(XPending(dpy)) {
1255 XNextEvent(dpy, &ev);
1256 if(handler[ev.type])
1257 (handler[ev.type])(&ev); /* call handler */
1258 }
1259 }
1260 }
1261
1262 void
1263 scan(void) {
1264 uint i, num;
1265 Window *wins, d1, d2;
1266 XWindowAttributes wa;
1267
1268 wins = NULL;
1269 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1270 for(i = 0; i < num; i++) {
1271 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1272 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1273 continue;
1274 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1275 manage(wins[i], &wa);
1276 }
1277 for(i = 0; i < num; i++) { /* now the transients */
1278 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1279 continue;
1280 if(XGetTransientForHint(dpy, wins[i], &d1)
1281 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1282 manage(wins[i], &wa);
1283 }
1284 }
1285 if(wins)
1286 XFree(wins);
1287 }
1288
1289 void
1290 setclientstate(Client *c, long state) {
1291 long data[] = {state, None};
1292
1293 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1294 PropModeReplace, (unsigned char *)data, 2);
1295 }
1296
1297 void
1298 setlayout(const Arg *arg) {
1299 if(!arg || !arg->v || arg->v != lt[sellt])
1300 sellt ^= 1;
1301 if(arg && arg->v)
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 }