Xinqi Bao's Git

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