Xinqi Bao's Git

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