Xinqi Bao's Git

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