Xinqi Bao's Git

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