Xinqi Bao's Git

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