Xinqi Bao's Git

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