Xinqi Bao's Git

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