Xinqi Bao's Git

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