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