Xinqi Bao's Git

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