Xinqi Bao's Git

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