Xinqi Bao's Git

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