Xinqi Bao's Git

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