Xinqi Bao's Git

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