Xinqi Bao's Git

504b78b0dcaa7ed40c19e2714b0bbe1e71532e78
[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 { BarTop, BarBot, BarOff, BarLast }; /* bar appearance */
54 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
55 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
56 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
57 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
58
59 /* typedefs */
60 typedef struct Client Client;
61 struct Client {
62 char name[256];
63 int x, y, w, h;
64 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
65 int minax, maxax, minay, maxay;
66 long flags;
67 unsigned int bw, oldbw;
68 Bool isbanned, isfixed, isfloating, isurgent;
69 Bool *tags;
70 Client *next;
71 Client *prev;
72 Client *snext;
73 Window win;
74 };
75
76 typedef struct {
77 int x, y, w, h;
78 unsigned long norm[ColLast];
79 unsigned long sel[ColLast];
80 Drawable drawable;
81 GC gc;
82 struct {
83 int ascent;
84 int descent;
85 int height;
86 XFontSet set;
87 XFontStruct *xfont;
88 } font;
89 } DC; /* draw context */
90
91 typedef struct {
92 unsigned long mod;
93 KeySym keysym;
94 void (*func)(const char *arg);
95 const char *arg;
96 } Key;
97
98 typedef struct {
99 const char *symbol;
100 void (*arrange)(void);
101 void (*updategeom)(void);
102 } Layout;
103
104 typedef struct {
105 const char *class;
106 const char *instance;
107 const char *title;
108 const char *tag;
109 Bool isfloating;
110 } Rule;
111
112 /* function declarations */
113 void applyrules(Client *c);
114 void arrange(void);
115 void attach(Client *c);
116 void attachstack(Client *c);
117 void ban(Client *c);
118 void buttonpress(XEvent *e);
119 void checkotherwm(void);
120 void cleanup(void);
121 void configure(Client *c);
122 void configurenotify(XEvent *e);
123 void configurerequest(XEvent *e);
124 void destroynotify(XEvent *e);
125 void detach(Client *c);
126 void detachstack(Client *c);
127 void drawbar(void);
128 void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
129 void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
130 void *emallocz(unsigned int size);
131 void enternotify(XEvent *e);
132 void eprint(const char *errstr, ...);
133 void expose(XEvent *e);
134 void focus(Client *c);
135 void focusin(XEvent *e);
136 void focusnext(const char *arg);
137 void focusprev(const char *arg);
138 Client *getclient(Window w);
139 unsigned long getcolor(const char *colstr);
140 long getstate(Window w);
141 Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
142 void grabbuttons(Client *c, Bool focused);
143 void grabkeys(void);
144 unsigned int idxoftag(const char *t);
145 void initfont(const char *fontstr);
146 Bool isoccupied(unsigned int t);
147 Bool isprotodel(Client *c);
148 Bool isurgent(unsigned int t);
149 Bool isvisible(Client *c);
150 void keypress(XEvent *e);
151 void killclient(const char *arg);
152 void manage(Window w, XWindowAttributes *wa);
153 void mappingnotify(XEvent *e);
154 void maprequest(XEvent *e);
155 void movemouse(Client *c);
156 Client *nextunfloating(Client *c);
157 void propertynotify(XEvent *e);
158 void quit(const char *arg);
159 void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
160 void resizemouse(Client *c);
161 void restack(void);
162 void run(void);
163 void scan(void);
164 void setclientstate(Client *c, long state);
165 void setup(void);
166 void spawn(const char *arg);
167 void tag(const char *arg);
168 unsigned int textnw(const char *text, unsigned int len);
169 unsigned int textw(const char *text);
170 void togglebar(const char *arg);
171 void togglefloating(const char *arg);
172 void togglelayout(const char *arg);
173 void toggletag(const char *arg);
174 void toggleview(const char *arg);
175 void unban(Client *c);
176 void unmanage(Client *c);
177 void unmapnotify(XEvent *e);
178 void updatebar(void);
179 void updategeom(void);
180 void updatesizehints(Client *c);
181 void updatetitle(Client *c);
182 void updatewmhints(Client *c);
183 void view(const char *arg);
184 void viewprevtag(const char *arg);
185 int xerror(Display *dpy, XErrorEvent *ee);
186 int xerrordummy(Display *dpy, XErrorEvent *ee);
187 int xerrorstart(Display *dpy, XErrorEvent *ee);
188 void zoom(const char *arg);
189
190 /* variables */
191 char stext[256];
192 int screen, sx, sy, sw, sh;
193 int bx, by, bw, bh, blw, wx, wy, ww, wh;
194 int seltags = 0;
195 int (*xerrorxlib)(Display *, XErrorEvent *);
196 unsigned int numlockmask = 0;
197 void (*handler[LASTEvent]) (XEvent *) = {
198 [ButtonPress] = buttonpress,
199 [ConfigureRequest] = configurerequest,
200 [ConfigureNotify] = configurenotify,
201 [DestroyNotify] = destroynotify,
202 [EnterNotify] = enternotify,
203 [Expose] = expose,
204 [FocusIn] = focusin,
205 [KeyPress] = keypress,
206 [MappingNotify] = mappingnotify,
207 [MapRequest] = maprequest,
208 [PropertyNotify] = propertynotify,
209 [UnmapNotify] = unmapnotify
210 };
211 Atom wmatom[WMLast], netatom[NetLast];
212 Bool otherwm, readin;
213 Bool running = True;
214 Bool *tagset[2];
215 Client *clients = NULL;
216 Client *sel = NULL;
217 Client *stack = NULL;
218 Cursor cursor[CurLast];
219 Display *dpy;
220 DC dc = {0};
221 Layout layouts[];
222 Layout *lt = layouts;
223 Window root, barwin;
224
225 /* configuration, allows nested code to access above variables */
226 #include "config.h"
227 #define TAGSZ (LENGTH(tags) * sizeof(Bool))
228
229 /* function implementations */
230
231 void
232 applyrules(Client *c) {
233 unsigned int i;
234 Bool matched = False;
235 Rule *r;
236 XClassHint ch = { 0 };
237
238 /* rule matching */
239 XGetClassHint(dpy, c->win, &ch);
240 for(i = 0; i < LENGTH(rules); i++) {
241 r = &rules[i];
242 if((!r->title || strstr(c->name, r->title))
243 && (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
244 && (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
245 c->isfloating = r->isfloating;
246 if(r->tag) {
247 c->tags[idxoftag(r->tag)] = True;
248 matched = True;
249 }
250 }
251 }
252 if(ch.res_class)
253 XFree(ch.res_class);
254 if(ch.res_name)
255 XFree(ch.res_name);
256 if(!matched)
257 memcpy(c->tags, tagset[seltags], TAGSZ);
258 }
259
260 void
261 arrange(void) {
262 Client *c;
263
264 for(c = clients; c; c = c->next)
265 if(isvisible(c)) {
266 unban(c);
267 if(!lt->arrange || c->isfloating)
268 resize(c, c->x, c->y, c->w, c->h, True);
269 }
270 else
271 ban(c);
272
273 focus(NULL);
274 if(lt->arrange)
275 lt->arrange();
276 restack();
277 }
278
279 void
280 attach(Client *c) {
281 if(clients)
282 clients->prev = c;
283 c->next = clients;
284 clients = c;
285 }
286
287 void
288 attachstack(Client *c) {
289 c->snext = stack;
290 stack = c;
291 }
292
293 void
294 ban(Client *c) {
295 if(c->isbanned)
296 return;
297 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
298 c->isbanned = True;
299 }
300
301 void
302 buttonpress(XEvent *e) {
303 unsigned int i, x;
304 Client *c;
305 XButtonPressedEvent *ev = &e->xbutton;
306
307 if(ev->window == barwin) {
308 x = 0;
309 for(i = 0; i < LENGTH(tags); i++) {
310 x += textw(tags[i]);
311 if(ev->x < x) {
312 if(ev->button == Button1) {
313 if(ev->state & MODKEY)
314 tag(tags[i]);
315 else
316 view(tags[i]);
317 }
318 else if(ev->button == Button3) {
319 if(ev->state & MODKEY)
320 toggletag(tags[i]);
321 else
322 toggleview(tags[i]);
323 }
324 return;
325 }
326 }
327 if((ev->x < x + blw) && ev->button == Button1)
328 togglelayout(NULL);
329 }
330 else if((c = getclient(ev->window))) {
331 focus(c);
332 if(CLEANMASK(ev->state) != MODKEY)
333 return;
334 if(ev->button == Button1) {
335 restack();
336 movemouse(c);
337 }
338 else if(ev->button == Button2) {
339 if(lt->arrange && c->isfloating)
340 togglefloating(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(snap && nx >= wx && nx <= wx + ww
1043 && ny >= wy && ny <= wy + wh) {
1044 if(abs(wx - nx) < snap)
1045 nx = wx;
1046 else if(abs((wx + ww) - (nx + c->w + 2 * c->bw)) < snap)
1047 nx = wx + ww - c->w - 2 * c->bw;
1048 if(abs(wy - ny) < snap)
1049 ny = wy;
1050 else if(abs((wy + wh) - (ny + c->h + 2 * c->bw)) < snap)
1051 ny = wy + wh - c->h - 2 * c->bw;
1052 if(!c->isfloating && lt->arrange && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
1053 togglefloating(NULL);
1054 }
1055 if(!lt->arrange || c->isfloating)
1056 resize(c, nx, ny, c->w, c->h, False);
1057 break;
1058 }
1059 }
1060 }
1061
1062 Client *
1063 nextunfloating(Client *c) {
1064 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1065 return c;
1066 }
1067
1068 void
1069 propertynotify(XEvent *e) {
1070 Client *c;
1071 Window trans;
1072 XPropertyEvent *ev = &e->xproperty;
1073
1074 if(ev->state == PropertyDelete)
1075 return; /* ignore */
1076 if((c = getclient(ev->window))) {
1077 switch (ev->atom) {
1078 default: break;
1079 case XA_WM_TRANSIENT_FOR:
1080 XGetTransientForHint(dpy, c->win, &trans);
1081 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1082 arrange();
1083 break;
1084 case XA_WM_NORMAL_HINTS:
1085 updatesizehints(c);
1086 break;
1087 case XA_WM_HINTS:
1088 updatewmhints(c);
1089 drawbar();
1090 break;
1091 }
1092 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1093 updatetitle(c);
1094 if(c == sel)
1095 drawbar();
1096 }
1097 }
1098 }
1099
1100 void
1101 quit(const char *arg) {
1102 readin = running = False;
1103 }
1104
1105 void
1106 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1107 XWindowChanges wc;
1108
1109 if(sizehints) {
1110 /* set minimum possible */
1111 w = MAX(1, w);
1112 h = MAX(1, h);
1113
1114 /* temporarily remove base dimensions */
1115 w -= c->basew;
1116 h -= c->baseh;
1117
1118 /* adjust for aspect limits */
1119 if(c->minax != c->maxax && c->minay != c->maxay
1120 && c->minax > 0 && c->maxax > 0 && c->minay > 0 && c->maxay > 0) {
1121 if(w * c->maxay > h * c->maxax)
1122 w = h * c->maxax / c->maxay;
1123 else if(w * c->minay < h * c->minax)
1124 h = w * c->minay / c->minax;
1125 }
1126
1127 /* adjust for increment value */
1128 if(c->incw)
1129 w -= w % c->incw;
1130 if(c->inch)
1131 h -= h % c->inch;
1132
1133 /* restore base dimensions */
1134 w += c->basew;
1135 h += c->baseh;
1136
1137 w = MAX(w, c->minw);
1138 h = MAX(h, c->minh);
1139
1140 if (c->maxw)
1141 w = MIN(w, c->maxw);
1142
1143 if (c->maxh)
1144 h = MIN(h, c->maxh);
1145 }
1146 if(w <= 0 || h <= 0)
1147 return;
1148 if(x > sx + sw)
1149 x = sw - w - 2 * c->bw;
1150 if(y > sy + sh)
1151 y = sh - h - 2 * c->bw;
1152 if(x + w + 2 * c->bw < sx)
1153 x = sx;
1154 if(y + h + 2 * c->bw < sy)
1155 y = sy;
1156 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1157 c->x = wc.x = x;
1158 c->y = wc.y = y;
1159 c->w = wc.width = w;
1160 c->h = wc.height = h;
1161 wc.border_width = c->bw;
1162 XConfigureWindow(dpy, c->win,
1163 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1164 configure(c);
1165 XSync(dpy, False);
1166 }
1167 }
1168
1169 void
1170 resizemouse(Client *c) {
1171 int ocx, ocy;
1172 int nw, nh;
1173 XEvent ev;
1174
1175 ocx = c->x;
1176 ocy = c->y;
1177 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1178 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1179 return;
1180 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1181 for(;;) {
1182 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1183 switch(ev.type) {
1184 case ButtonRelease:
1185 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1186 c->w + c->bw - 1, c->h + c->bw - 1);
1187 XUngrabPointer(dpy, CurrentTime);
1188 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1189 return;
1190 case ConfigureRequest:
1191 case Expose:
1192 case MapRequest:
1193 handler[ev.type](&ev);
1194 break;
1195 case MotionNotify:
1196 XSync(dpy, False);
1197 nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1198 nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1199
1200 if(snap && nw >= wx && nw <= wx + ww
1201 && nh >= wy && nh <= wy + wh) {
1202 if(!c->isfloating && lt->arrange
1203 && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1204 togglefloating(NULL);
1205 }
1206 if(!lt->arrange || c->isfloating)
1207 resize(c, c->x, c->y, nw, nh, True);
1208 break;
1209 }
1210 }
1211 }
1212
1213 void
1214 restack(void) {
1215 Client *c;
1216 XEvent ev;
1217 XWindowChanges wc;
1218
1219 drawbar();
1220 if(!sel)
1221 return;
1222 if(sel->isfloating || !lt->arrange)
1223 XRaiseWindow(dpy, sel->win);
1224 if(lt->arrange) {
1225 wc.stack_mode = Below;
1226 wc.sibling = barwin;
1227 for(c = stack; c; c = c->snext)
1228 if(!c->isfloating && isvisible(c)) {
1229 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1230 wc.sibling = c->win;
1231 }
1232 }
1233 XSync(dpy, False);
1234 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1235 }
1236
1237 void
1238 run(void) {
1239 char *p;
1240 char sbuf[sizeof stext];
1241 fd_set rd;
1242 int r, xfd;
1243 unsigned int len, offset;
1244 XEvent ev;
1245
1246 /* main event loop, also reads status text from stdin */
1247 XSync(dpy, False);
1248 xfd = ConnectionNumber(dpy);
1249 readin = True;
1250 offset = 0;
1251 len = sizeof stext - 1;
1252 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1253 while(running) {
1254 FD_ZERO(&rd);
1255 if(readin)
1256 FD_SET(STDIN_FILENO, &rd);
1257 FD_SET(xfd, &rd);
1258 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1259 if(errno == EINTR)
1260 continue;
1261 eprint("select failed\n");
1262 }
1263 if(FD_ISSET(STDIN_FILENO, &rd)) {
1264 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1265 case -1:
1266 strncpy(stext, strerror(errno), len);
1267 readin = False;
1268 break;
1269 case 0:
1270 strncpy(stext, "EOF", 4);
1271 readin = False;
1272 break;
1273 default:
1274 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1275 if(*p == '\n' || *p == '\0') {
1276 *p = '\0';
1277 strncpy(stext, sbuf, len);
1278 p += r - 1; /* p is sbuf + offset + r - 1 */
1279 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1280 offset = r;
1281 if(r)
1282 memmove(sbuf, p - r + 1, r);
1283 break;
1284 }
1285 break;
1286 }
1287 drawbar();
1288 }
1289 while(XPending(dpy)) {
1290 XNextEvent(dpy, &ev);
1291 if(handler[ev.type])
1292 (handler[ev.type])(&ev); /* call handler */
1293 }
1294 }
1295 }
1296
1297 void
1298 scan(void) {
1299 unsigned int i, num;
1300 Window *wins, d1, d2;
1301 XWindowAttributes wa;
1302
1303 wins = NULL;
1304 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1305 for(i = 0; i < num; i++) {
1306 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1307 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1308 continue;
1309 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1310 manage(wins[i], &wa);
1311 }
1312 for(i = 0; i < num; i++) { /* now the transients */
1313 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1314 continue;
1315 if(XGetTransientForHint(dpy, wins[i], &d1)
1316 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1317 manage(wins[i], &wa);
1318 }
1319 }
1320 if(wins)
1321 XFree(wins);
1322 }
1323
1324 void
1325 setclientstate(Client *c, long state) {
1326 long data[] = {state, None};
1327
1328 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1329 PropModeReplace, (unsigned char *)data, 2);
1330 }
1331
1332 void
1333 setup(void) {
1334 unsigned int i, w;
1335 XSetWindowAttributes wa;
1336
1337 /* init screen */
1338 screen = DefaultScreen(dpy);
1339 root = RootWindow(dpy, screen);
1340 initfont(FONT);
1341 sx = 0;
1342 sy = 0;
1343 sw = DisplayWidth(dpy, screen);
1344 sh = DisplayHeight(dpy, screen);
1345 bh = dc.font.height + 2;
1346 updategeom();
1347
1348 /* init atoms */
1349 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1350 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1351 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1352 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1353 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1354 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1355
1356 /* init cursors */
1357 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1358 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1359 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1360
1361 /* init appearance */
1362 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1363 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1364 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1365 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1366 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1367 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1368 initfont(FONT);
1369 dc.h = bh;
1370 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1371 dc.gc = XCreateGC(dpy, root, 0, 0);
1372 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1373 if(!dc.font.set)
1374 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1375
1376 /* init tags */
1377 tagset[0] = emallocz(TAGSZ);
1378 tagset[1] = emallocz(TAGSZ);
1379 tagset[0][0] = tagset[1][0] = True;
1380
1381 /* init bar */
1382 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1383 w = textw(layouts[i].symbol);
1384 blw = MAX(blw, w);
1385 }
1386
1387 wa.override_redirect = 1;
1388 wa.background_pixmap = ParentRelative;
1389 wa.event_mask = ButtonPressMask|ExposureMask;
1390
1391 barwin = XCreateWindow(dpy, root, bx, by, bw, bh, 0, DefaultDepth(dpy, screen),
1392 CopyFromParent, DefaultVisual(dpy, screen),
1393 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1394 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1395 XMapRaised(dpy, barwin);
1396 strcpy(stext, "dwm-"VERSION);
1397 drawbar();
1398
1399 /* EWMH support per view */
1400 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1401 PropModeReplace, (unsigned char *) netatom, NetLast);
1402
1403 /* select for events */
1404 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1405 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1406 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1407 XSelectInput(dpy, root, wa.event_mask);
1408
1409
1410 /* grab keys */
1411 grabkeys();
1412 }
1413
1414 void
1415 spawn(const char *arg) {
1416 static char *shell = NULL;
1417
1418 if(!shell && !(shell = getenv("SHELL")))
1419 shell = "/bin/sh";
1420 if(!arg)
1421 return;
1422 /* The double-fork construct avoids zombie processes and keeps the code
1423 * clean from stupid signal handlers. */
1424 if(fork() == 0) {
1425 if(fork() == 0) {
1426 if(dpy)
1427 close(ConnectionNumber(dpy));
1428 setsid();
1429 execl(shell, shell, "-c", arg, (char *)NULL);
1430 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1431 perror(" failed");
1432 }
1433 exit(0);
1434 }
1435 wait(0);
1436 }
1437
1438 void
1439 tag(const char *arg) {
1440 unsigned int i;
1441
1442 if(!sel)
1443 return;
1444 for(i = 0; i < LENGTH(tags); i++)
1445 sel->tags[i] = (arg == NULL);
1446 sel->tags[idxoftag(arg)] = True;
1447 arrange();
1448 }
1449
1450 unsigned int
1451 textnw(const char *text, unsigned int len) {
1452 XRectangle r;
1453
1454 if(dc.font.set) {
1455 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1456 return r.width;
1457 }
1458 return XTextWidth(dc.font.xfont, text, len);
1459 }
1460
1461 unsigned int
1462 textw(const char *text) {
1463 return textnw(text, strlen(text)) + dc.font.height;
1464 }
1465
1466 void
1467 togglebar(const char *arg) {
1468 showbar = !showbar;
1469 updategeom();
1470 updatebar();
1471 arrange();
1472 }
1473
1474 void
1475 togglefloating(const char *arg) {
1476 if(!sel)
1477 return;
1478 sel->isfloating = !sel->isfloating;
1479 if(sel->isfloating)
1480 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1481 arrange();
1482 }
1483
1484 void
1485 togglelayout(const char *arg) {
1486 unsigned int i;
1487
1488 if(!arg) {
1489 if(++lt == &layouts[LENGTH(layouts)])
1490 lt = &layouts[0];
1491 }
1492 else {
1493 for(i = 0; i < LENGTH(layouts); i++)
1494 if(!strcmp(arg, layouts[i].symbol))
1495 break;
1496 if(i == LENGTH(layouts))
1497 return;
1498 lt = &layouts[i];
1499 }
1500 if(sel)
1501 arrange();
1502 else
1503 drawbar();
1504 }
1505
1506 void
1507 toggletag(const char *arg) {
1508 unsigned int i, j;
1509
1510 if(!sel)
1511 return;
1512 i = idxoftag(arg);
1513 sel->tags[i] = !sel->tags[i];
1514 for(j = 0; j < LENGTH(tags) && !sel->tags[j]; j++);
1515 if(j == LENGTH(tags))
1516 sel->tags[i] = True; /* at least one tag must be enabled */
1517 arrange();
1518 }
1519
1520 void
1521 toggleview(const char *arg) {
1522 unsigned int i, j;
1523
1524 i = idxoftag(arg);
1525 tagset[seltags][i] = !tagset[seltags][i];
1526 for(j = 0; j < LENGTH(tags) && !tagset[seltags][j]; j++);
1527 if(j == LENGTH(tags))
1528 tagset[seltags][i] = True; /* at least one tag must be viewed */
1529 arrange();
1530 }
1531
1532 void
1533 unban(Client *c) {
1534 if(!c->isbanned)
1535 return;
1536 XMoveWindow(dpy, c->win, c->x, c->y);
1537 c->isbanned = False;
1538 }
1539
1540 void
1541 unmanage(Client *c) {
1542 XWindowChanges wc;
1543
1544 wc.border_width = c->oldbw;
1545 /* The server grab construct avoids race conditions. */
1546 XGrabServer(dpy);
1547 XSetErrorHandler(xerrordummy);
1548 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1549 detach(c);
1550 detachstack(c);
1551 if(sel == c)
1552 focus(NULL);
1553 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1554 setclientstate(c, WithdrawnState);
1555 free(c->tags);
1556 free(c);
1557 XSync(dpy, False);
1558 XSetErrorHandler(xerror);
1559 XUngrabServer(dpy);
1560 arrange();
1561 }
1562
1563 void
1564 unmapnotify(XEvent *e) {
1565 Client *c;
1566 XUnmapEvent *ev = &e->xunmap;
1567
1568 if((c = getclient(ev->window)))
1569 unmanage(c);
1570 }
1571
1572 void
1573 updatebar(void) {
1574 if(dc.drawable != 0)
1575 XFreePixmap(dpy, dc.drawable);
1576 dc.drawable = XCreatePixmap(dpy, root, bw, bh, DefaultDepth(dpy, screen));
1577 XMoveResizeWindow(dpy, barwin, bx, by, bw, bh);
1578 }
1579
1580 void
1581 updategeom(void) {
1582 unsigned int i;
1583
1584 #ifdef CUSTOMGEOM /* define your own if you are Xinerama user */
1585 CUSTOMGEOM
1586 #else
1587 /* bar geometry*/
1588 bx = 0;
1589 by = showbar ? (topbar ? 0 : sh - bh) : -bh;
1590 bw = sw;
1591
1592 /* window area geometry */
1593 wx = sx;
1594 wy = showbar && topbar ? sy + bh : sy;
1595 ww = sw;
1596 wh = showbar ? sh - bh : sh;
1597 #endif
1598
1599 /* update layout geometries */
1600 for(i = 0; i < LENGTH(layouts); i++)
1601 if(layouts[i].updategeom)
1602 layouts[i].updategeom();
1603 }
1604
1605 void
1606 updatesizehints(Client *c) {
1607 long msize;
1608 XSizeHints size;
1609
1610 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1611 size.flags = PSize;
1612 c->flags = size.flags;
1613 if(c->flags & PBaseSize) {
1614 c->basew = size.base_width;
1615 c->baseh = size.base_height;
1616 }
1617 else if(c->flags & PMinSize) {
1618 c->basew = size.min_width;
1619 c->baseh = size.min_height;
1620 }
1621 else
1622 c->basew = c->baseh = 0;
1623 if(c->flags & PResizeInc) {
1624 c->incw = size.width_inc;
1625 c->inch = size.height_inc;
1626 }
1627 else
1628 c->incw = c->inch = 0;
1629 if(c->flags & PMaxSize) {
1630 c->maxw = size.max_width;
1631 c->maxh = size.max_height;
1632 }
1633 else
1634 c->maxw = c->maxh = 0;
1635 if(c->flags & PMinSize) {
1636 c->minw = size.min_width;
1637 c->minh = size.min_height;
1638 }
1639 else if(c->flags & PBaseSize) {
1640 c->minw = size.base_width;
1641 c->minh = size.base_height;
1642 }
1643 else
1644 c->minw = c->minh = 0;
1645 if(c->flags & PAspect) {
1646 c->minax = size.min_aspect.x;
1647 c->maxax = size.max_aspect.x;
1648 c->minay = size.min_aspect.y;
1649 c->maxay = size.max_aspect.y;
1650 }
1651 else
1652 c->minax = c->maxax = c->minay = c->maxay = 0;
1653 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1654 && c->maxw == c->minw && c->maxh == c->minh);
1655 }
1656
1657 void
1658 updatetitle(Client *c) {
1659 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1660 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1661 }
1662
1663 void
1664 updatewmhints(Client *c) {
1665 XWMHints *wmh;
1666
1667 if((wmh = XGetWMHints(dpy, c->win))) {
1668 if(c == sel)
1669 sel->isurgent = False;
1670 else
1671 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1672 XFree(wmh);
1673 }
1674 }
1675
1676 void
1677 view(const char *arg) {
1678 seltags ^= 1; /* toggle sel tagset */
1679 memset(tagset[seltags], (NULL == arg), TAGSZ);
1680 tagset[seltags][idxoftag(arg)] = True;
1681 arrange();
1682 }
1683
1684 void
1685 viewprevtag(const char *arg) {
1686 seltags ^= 1; /* toggle sel tagset */
1687 arrange();
1688 }
1689
1690 /* There's no way to check accesses to destroyed windows, thus those cases are
1691 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1692 * default error handler, which may call exit. */
1693 int
1694 xerror(Display *dpy, XErrorEvent *ee) {
1695 if(ee->error_code == BadWindow
1696 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1697 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1698 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1699 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1700 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1701 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1702 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1703 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1704 return 0;
1705 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1706 ee->request_code, ee->error_code);
1707 return xerrorxlib(dpy, ee); /* may call exit */
1708 }
1709
1710 int
1711 xerrordummy(Display *dpy, XErrorEvent *ee) {
1712 return 0;
1713 }
1714
1715 /* Startup Error handler to check if another window manager
1716 * is already running. */
1717 int
1718 xerrorstart(Display *dpy, XErrorEvent *ee) {
1719 otherwm = True;
1720 return -1;
1721 }
1722
1723 int
1724 main(int argc, char *argv[]) {
1725 if(argc == 2 && !strcmp("-v", argv[1]))
1726 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1727 else if(argc != 1)
1728 eprint("usage: dwm [-v]\n");
1729
1730 setlocale(LC_CTYPE, "");
1731 if(!(dpy = XOpenDisplay(0)))
1732 eprint("dwm: cannot open display\n");
1733
1734 checkotherwm();
1735 setup();
1736 scan();
1737 run();
1738 cleanup();
1739
1740 XCloseDisplay(dpy);
1741 return 0;
1742 }