Xinqi Bao's Git

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