Xinqi Bao's Git

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