Xinqi Bao's Git

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