Xinqi Bao's Git

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