Xinqi Bao's Git

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