Applyed dwmfifo patch, now creates fifo instead of only opening it, added -f<file...
[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 linked client
15 * list on each monitor, the focus history is remembered through a stack list
16 * on each monitor. 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 <fcntl.h>
25 #include <locale.h>
26 #include <stdarg.h>
27 #include <signal.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <unistd.h>
32 #include <sys/select.h>
33 #include <sys/stat.h>
34 #include <sys/types.h>
35 #include <sys/wait.h>
36 #include <X11/cursorfont.h>
37 #include <X11/keysym.h>
38 #include <X11/Xatom.h>
39 #include <X11/Xlib.h>
40 #include <X11/Xproto.h>
41 #include <X11/Xutil.h>
42 #include <X11/Xft/Xft.h>
43 #include <pango/pango.h>
44 #include <pango/pangoxft.h>
45 #ifdef XINERAMA
46 #include <X11/extensions/Xinerama.h>
47 #endif /* XINERAMA */
48
49 /* macros */
50 #define BUTTONMASK (ButtonPressMask|ButtonReleaseMask)
51 #define CLEANMASK(mask) (mask & ~(numlockmask|LockMask) & (ShiftMask|ControlMask|Mod1Mask|Mod2Mask|Mod3Mask|Mod4Mask|Mod5Mask))
52 #define INTERSECT(x,y,w,h,m) (MAX(0, MIN((x)+(w),(m)->wx+(m)->ww) - MAX((x),(m)->wx)) \
53 * MAX(0, MIN((y)+(h),(m)->wy+(m)->wh) - MAX((y),(m)->wy)))
54 #define ISVISIBLE(C) ((C->tags & C->mon->tagset[C->mon->seltags]))
55 #define LENGTH(X) (sizeof X / sizeof X[0])
56 #ifndef MAX
57 #define MAX(A, B) ((A) > (B) ? (A) : (B))
58 #endif
59 #ifndef MIN
60 #define MIN(A, B) ((A) < (B) ? (A) : (B))
61 #endif
62 #define MOUSEMASK (BUTTONMASK|PointerMotionMask)
63 #define WIDTH(X) ((X)->w + 2 * (X)->bw)
64 #define HEIGHT(X) ((X)->h + 2 * (X)->bw)
65 #define TAGMASK ((1 << LENGTH(tags)) - 1)
66 #define TEXTW(X) (textnw(X, strlen(X)) + dc.font.height)
67
68 /* enums */
69 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
70 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
71 enum { NetSupported, NetWMName, NetWMState,
72 NetWMFullscreen, NetActiveWindow, NetWMWindowType,
73 NetWMWindowTypeDialog, NetLast }; /* EWMH atoms */
74 enum { WMProtocols, WMDelete, WMState, WMTakeFocus, WMLast }; /* default atoms */
75 enum { ClkTagBar, ClkLtSymbol, ClkStatusText, ClkWinTitle,
76 ClkClientWin, ClkRootWin, ClkLast }; /* clicks */
77
78 typedef union {
79 int i;
80 unsigned int ui;
81 float f;
82 const void *v;
83 } Arg;
84
85 typedef struct {
86 unsigned int click;
87 unsigned int mask;
88 unsigned int button;
89 void (*func)(const Arg *arg);
90 const Arg arg;
91 } Button;
92
93 typedef struct Monitor Monitor;
94 typedef struct Client Client;
95 struct Client {
96 char name[256];
97 float mina, maxa;
98 int x, y, w, h;
99 int oldx, oldy, oldw, oldh;
100 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
101 int bw, oldbw;
102 unsigned int tags;
103 Bool isfixed, isfloating, isurgent, neverfocus, oldstate, isfullscreen;
104 Client *next;
105 Client *snext;
106 Monitor *mon;
107 Window win;
108 };
109
110 typedef struct {
111 int x, y, w, h;
112 unsigned long norm[ColLast];
113 unsigned long sel[ColLast];
114 Drawable drawable;
115 GC gc;
116 struct {
117 XftColor norm[ColLast];
118 XftColor sel[ColLast];
119 XftDraw *drawable;
120 } xft;
121 struct {
122 int ascent;
123 int descent;
124 int height;
125 PangoLayout *layout;
126 } font;
127 } DC; /* draw context */
128
129 typedef struct {
130 unsigned int mod;
131 KeySym keysym;
132 void (*func)(const Arg *);
133 const Arg arg;
134 } Key;
135
136 typedef struct {
137 const char *symbol;
138 void (*arrange)(Monitor *);
139 } Layout;
140
141 typedef struct Pertag Pertag;
142 struct Monitor {
143 char ltsymbol[16];
144 float mfact;
145 int nmaster;
146 int num;
147 int by; /* bar geometry */
148 int mx, my, mw, mh; /* screen size */
149 int wx, wy, ww, wh; /* window area */
150 unsigned int seltags;
151 unsigned int sellt;
152 unsigned int tagset[2];
153 Bool showbar;
154 Bool topbar;
155 Client *clients;
156 Client *sel;
157 Client *stack;
158 Monitor *next;
159 Window barwin;
160 const Layout *lt[2];
161 Pertag *pertag;
162 };
163
164 typedef struct {
165 const char *class;
166 const char *instance;
167 const char *title;
168 unsigned int tags;
169 Bool isfloating;
170 int monitor;
171 } Rule;
172
173 typedef struct {
174 const char *name;
175 void (*func)(const Arg *arg);
176 const Arg arg;
177 } Command;
178
179 /* function declarations */
180 static void applyrules(Client *c);
181 static Bool applysizehints(Client *c, int *x, int *y, int *w, int *h, Bool interact);
182 static void arrange(Monitor *m);
183 static void arrangemon(Monitor *m);
184 static void attach(Client *c);
185 static void attachstack(Client *c);
186 static void buttonpress(XEvent *e);
187 static void checkotherwm(void);
188 static void cleanup(void);
189 static void cleanupmon(Monitor *mon);
190 static void clearurgent(Client *c);
191 static void clientmessage(XEvent *e);
192 static void configure(Client *c);
193 static void configurenotify(XEvent *e);
194 static void configurerequest(XEvent *e);
195 static Monitor *createmon(void);
196 static void destroynotify(XEvent *e);
197 static void detach(Client *c);
198 static void detachstack(Client *c);
199 static void die(const char *errstr, ...);
200 static Monitor *dirtomon(int dir);
201 static void dispatchcmd(void);
202 static void drawbar(Monitor *m);
203 static void drawbars(void);
204 static void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
205 static void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
206 static void enternotify(XEvent *e);
207 static Bool evpredicate();
208 static void expose(XEvent *e);
209 static void findwindow(const Arg *arg);
210 static void focus(Client *c);
211 static void focusin(XEvent *e);
212 static void focusmon(const Arg *arg);
213 static void focusstack(const Arg *arg);
214 static unsigned long getcolor(const char *colstr, XftColor *color);
215 static Bool getrootptr(int *x, int *y);
216 static long getstate(Window w);
217 static Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
218 static void grabbuttons(Client *c, Bool focused);
219 static void grabkeys(void);
220 static void incnmaster(const Arg *arg);
221 static void initfont(const char *fontstr);
222 static void keypress(XEvent *e);
223 static void killclient(const Arg *arg);
224 static void list_clients(const Arg *arg);
225 static void listclients(void);
226 static void manage(Window w, XWindowAttributes *wa);
227 static void mappingnotify(XEvent *e);
228 static void maprequest(XEvent *e);
229 static void monocle(Monitor *m);
230 static void motionnotify(XEvent *e);
231 static void movemouse(const Arg *arg);
232 static Client *nexttiled(Client *c);
233 static void pop(Client *);
234 static void propertynotify(XEvent *e);
235 static void quit(const Arg *arg);
236 static Monitor *recttomon(int x, int y, int w, int h);
237 static void resize(Client *c, int x, int y, int w, int h, Bool interact);
238 static void resizeclient(Client *c, int x, int y, int w, int h);
239 static void resizemouse(const Arg *arg);
240 static void restack(Monitor *m);
241 static void run(void);
242 static void scan(void);
243 static Bool sendevent(Client *c, Atom proto);
244 static void sendmon(Client *c, Monitor *m);
245 static void setclientstate(Client *c, long state);
246 static void setfocus(Client *c);
247 static void setfullscreen(Client *c, Bool fullscreen);
248 static void setlayout(const Arg *arg);
249 static void setmfact(const Arg *arg);
250 static void setup(void);
251 static void showhide(Client *c);
252 static void sigchld(int unused);
253 static void spawn(const Arg *arg);
254 static void tag(const Arg *arg);
255 static void tagmon(const Arg *arg);
256 static int textnw(const char *text, unsigned int len);
257 static void tile(Monitor *);
258 static void togglebar(const Arg *arg);
259 static void togglefloating(const Arg *arg);
260 static void toggletag(const Arg *arg);
261 static void toggleview(const Arg *arg);
262 static void unfocus(Client *c, Bool setfocus);
263 static void unmanage(Client *c, Bool destroyed);
264 static void unmapnotify(XEvent *e);
265 static Bool updategeom(void);
266 static void updatebarpos(Monitor *m);
267 static void updatebars(void);
268 static void updatenumlockmask(void);
269 static void updatesizehints(Client *c);
270 static void updatestatus(void);
271 static void updatewindowtype(Client *c);
272 static void updatetitle(Client *c);
273 static void updatewmhints(Client *c);
274 static void view(const Arg *arg);
275 static Client *wintoclient(Window w);
276 static Monitor *wintomon(Window w);
277 static int xerror(Display *dpy, XErrorEvent *ee);
278 static int xerrordummy(Display *dpy, XErrorEvent *ee);
279 static int xerrorstart(Display *dpy, XErrorEvent *ee);
280 static void zoom(const Arg *arg);
281
282 /* variables */
283 static const char broken[] = "broken";
284 static char stext[512];
285 static int screen;
286 static int sw, sh; /* X display screen geometry width, height */
287 static int bh, blw = 0; /* bar geometry */
288 static int (*xerrorxlib)(Display *, XErrorEvent *);
289 static unsigned int numlockmask = 0;
290 static void (*handler[LASTEvent]) (XEvent *) = {
291 [ButtonPress] = buttonpress,
292 [ClientMessage] = clientmessage,
293 [ConfigureRequest] = configurerequest,
294 [ConfigureNotify] = configurenotify,
295 [DestroyNotify] = destroynotify,
296 [EnterNotify] = enternotify,
297 [Expose] = expose,
298 [FocusIn] = focusin,
299 [KeyPress] = keypress,
300 [MappingNotify] = mappingnotify,
301 [MapRequest] = maprequest,
302 [MotionNotify] = motionnotify,
303 [PropertyNotify] = propertynotify,
304 [UnmapNotify] = unmapnotify
305 };
306 static Atom wmatom[WMLast], netatom[NetLast];
307 static Bool running = True;
308 static Cursor cursor[CurLast];
309 static Display *dpy;
310 static DC dc;
311 static Monitor *mons = NULL, *selmon = NULL;
312 static Window root;
313 static int fifofd;
314
315 /* configuration, allows nested code to access above variables */
316 #include "config.h"
317
318 struct Pertag {
319 unsigned int curtag, prevtag; /* current and previous tag */
320 int nmasters[LENGTH(tags) + 1]; /* number of windows in master area */
321 float mfacts[LENGTH(tags) + 1]; /* mfacts per tag */
322 unsigned int sellts[LENGTH(tags) + 1]; /* selected layouts */
323 const Layout *ltidxs[LENGTH(tags) + 1][2]; /* matrix of tags and layouts indexes */
324 Bool showbars[LENGTH(tags) + 1]; /* display bar for the current tag */
325 };
326
327 /* compile-time check if all tags fit into an unsigned int bit array. */
328 struct NumTags { char limitexceeded[LENGTH(tags) > 31 ? -1 : 1]; };
329
330
331
332 /* function implementations */
333 void
334 applyrules(Client *c) {
335 const char *class, *instance;
336 unsigned int i;
337 const Rule *r;
338 Monitor *m;
339 XClassHint ch = { NULL, NULL };
340
341 /* rule matching */
342 c->isfloating = c->tags = 0;
343 XGetClassHint(dpy, c->win, &ch);
344 class = ch.res_class ? ch.res_class : broken;
345 instance = ch.res_name ? ch.res_name : broken;
346
347 for(i = 0; i < LENGTH(rules); i++) {
348 r = &rules[i];
349 if((!r->title || strstr(c->name, r->title))
350 && (!r->class || strstr(class, r->class))
351 && (!r->instance || strstr(instance, r->instance)))
352 {
353 c->isfloating = r->isfloating;
354 c->tags |= r->tags;
355 for(m = mons; m && m->num != r->monitor; m = m->next);
356 if(m)
357 c->mon = m;
358 }
359 }
360 if(ch.res_class)
361 XFree(ch.res_class);
362 if(ch.res_name)
363 XFree(ch.res_name);
364 c->tags = c->tags & TAGMASK ? c->tags & TAGMASK : c->mon->tagset[c->mon->seltags];
365 }
366
367 Bool
368 applysizehints(Client *c, int *x, int *y, int *w, int *h, Bool interact) {
369 Bool baseismin;
370 Monitor *m = c->mon;
371
372 /* set minimum possible */
373 *w = MAX(1, *w);
374 *h = MAX(1, *h);
375 if(interact) {
376 if(*x > sw)
377 *x = sw - WIDTH(c);
378 if(*y > sh)
379 *y = sh - HEIGHT(c);
380 if(*x + *w + 2 * c->bw < 0)
381 *x = 0;
382 if(*y + *h + 2 * c->bw < 0)
383 *y = 0;
384 }
385 else {
386 if(*x >= m->wx + m->ww)
387 *x = m->wx + m->ww - WIDTH(c);
388 if(*y >= m->wy + m->wh)
389 *y = m->wy + m->wh - HEIGHT(c);
390 if(*x + *w + 2 * c->bw <= m->wx)
391 *x = m->wx;
392 if(*y + *h + 2 * c->bw <= m->wy)
393 *y = m->wy;
394 }
395 if(*h < bh)
396 *h = bh;
397 if(*w < bh)
398 *w = bh;
399 if(resizehints || c->isfloating || !c->mon->lt[c->mon->sellt]->arrange) {
400 /* see last two sentences in ICCCM 4.1.2.3 */
401 baseismin = c->basew == c->minw && c->baseh == c->minh;
402 if(!baseismin) { /* temporarily remove base dimensions */
403 *w -= c->basew;
404 *h -= c->baseh;
405 }
406 /* adjust for aspect limits */
407 if(c->mina > 0 && c->maxa > 0) {
408 if(c->maxa < (float)*w / *h)
409 *w = *h * c->maxa + 0.5;
410 else if(c->mina < (float)*h / *w)
411 *h = *w * c->mina + 0.5;
412 }
413 if(baseismin) { /* increment calculation requires this */
414 *w -= c->basew;
415 *h -= c->baseh;
416 }
417 /* adjust for increment value */
418 if(c->incw)
419 *w -= *w % c->incw;
420 if(c->inch)
421 *h -= *h % c->inch;
422 /* restore base dimensions */
423 *w = MAX(*w + c->basew, c->minw);
424 *h = MAX(*h + c->baseh, c->minh);
425 if(c->maxw)
426 *w = MIN(*w, c->maxw);
427 if(c->maxh)
428 *h = MIN(*h, c->maxh);
429 }
430 return *x != c->x || *y != c->y || *w != c->w || *h != c->h;
431 }
432
433 void
434 arrange(Monitor *m) {
435 if(m)
436 showhide(m->stack);
437 else for(m = mons; m; m = m->next)
438 showhide(m->stack);
439 if(m)
440 arrangemon(m);
441 else for(m = mons; m; m = m->next)
442 arrangemon(m);
443 }
444
445 void
446 arrangemon(Monitor *m) {
447 strncpy(m->ltsymbol, m->lt[m->sellt]->symbol, sizeof m->ltsymbol);
448 if(m->lt[m->sellt]->arrange)
449 m->lt[m->sellt]->arrange(m);
450 restack(m);
451 }
452
453 void
454 attach(Client *c) {
455 c->next = c->mon->clients;
456 c->mon->clients = c;
457 }
458
459 void
460 attachstack(Client *c) {
461 c->snext = c->mon->stack;
462 c->mon->stack = c;
463 }
464
465 void
466 buttonpress(XEvent *e) {
467 unsigned int i, x, click;
468 Arg arg = {0};
469 Client *c;
470 Monitor *m;
471 XButtonPressedEvent *ev = &e->xbutton;
472
473 click = ClkRootWin;
474 /* focus monitor if necessary */
475 if((m = wintomon(ev->window)) && m != selmon) {
476 unfocus(selmon->sel, True);
477 selmon = m;
478 focus(NULL);
479 }
480 if(ev->window == selmon->barwin) {
481 i = x = 0;
482 do
483 x += TEXTW(tags[i]);
484 while(ev->x >= x && ++i < LENGTH(tags));
485 if(i < LENGTH(tags)) {
486 click = ClkTagBar;
487 arg.ui = 1 << i;
488 }
489 else if(ev->x < x + blw)
490 click = ClkLtSymbol;
491 else if(ev->x > selmon->ww - TEXTW(stext))
492 click = ClkStatusText;
493 else
494 click = ClkWinTitle;
495 }
496 else if((c = wintoclient(ev->window))) {
497 focus(c);
498 click = ClkClientWin;
499 }
500 for(i = 0; i < LENGTH(buttons); i++)
501 if(click == buttons[i].click && buttons[i].func && buttons[i].button == ev->button
502 && CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
503 buttons[i].func(click == ClkTagBar && buttons[i].arg.i == 0 ? &arg : &buttons[i].arg);
504 }
505
506 void
507 checkotherwm(void) {
508 xerrorxlib = XSetErrorHandler(xerrorstart);
509 /* this causes an error if some other window manager is running */
510 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
511 XSync(dpy, False);
512 XSetErrorHandler(xerror);
513 XSync(dpy, False);
514 }
515
516 void
517 cleanup(void) {
518 Arg a = {.ui = ~0};
519 Layout foo = { "", NULL };
520 Monitor *m;
521 int i;
522
523 view(&a);
524 selmon->lt[selmon->sellt] = &foo;
525 for(m = mons; m; m = m->next)
526 while(m->stack)
527 unmanage(m->stack, False);
528 XUngrabKey(dpy, AnyKey, AnyModifier, root);
529 XFreePixmap(dpy, dc.drawable);
530 for(i = ColBorder; i < ColLast; i++) {
531 XftColorFree(dpy, DefaultVisual(dpy, screen), DefaultColormap(dpy, screen), dc.xft.norm + i);
532 XftColorFree(dpy, DefaultVisual(dpy, screen), DefaultColormap(dpy, screen), dc.xft.sel + i);
533 }
534 XftDrawDestroy(dc.xft.drawable);
535 g_object_unref(dc.font.layout);
536 XFreeGC(dpy, dc.gc);
537 XFreeCursor(dpy, cursor[CurNormal]);
538 XFreeCursor(dpy, cursor[CurResize]);
539 XFreeCursor(dpy, cursor[CurMove]);
540 while(mons)
541 cleanupmon(mons);
542 XSync(dpy, False);
543 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
544 XDeleteProperty(dpy, root, netatom[NetActiveWindow]);
545 close(fifofd);
546 }
547
548 void
549 cleanupmon(Monitor *mon) {
550 Monitor *m;
551
552 if(mon == mons)
553 mons = mons->next;
554 else {
555 for(m = mons; m && m->next != mon; m = m->next);
556 m->next = mon->next;
557 }
558 XUnmapWindow(dpy, mon->barwin);
559 XDestroyWindow(dpy, mon->barwin);
560 free(mon);
561 }
562
563 void
564 clearurgent(Client *c) {
565 XWMHints *wmh;
566
567 c->isurgent = False;
568 if(!(wmh = XGetWMHints(dpy, c->win)))
569 return;
570 wmh->flags &= ~XUrgencyHint;
571 XSetWMHints(dpy, c->win, wmh);
572 XFree(wmh);
573 }
574
575 void
576 clientmessage(XEvent *e) {
577 XClientMessageEvent *cme = &e->xclient;
578 Client *c = wintoclient(cme->window);
579
580 if(!c)
581 return;
582 if(cme->message_type == netatom[NetWMState]) {
583 if(cme->data.l[1] == netatom[NetWMFullscreen] || cme->data.l[2] == netatom[NetWMFullscreen])
584 setfullscreen(c, (cme->data.l[0] == 1 /* _NET_WM_STATE_ADD */
585 || (cme->data.l[0] == 2 /* _NET_WM_STATE_TOGGLE */ && !c->isfullscreen)));
586 }
587 else if(cme->message_type == netatom[NetActiveWindow]) {
588 if(!ISVISIBLE(c)) {
589 c->mon->seltags ^= 1;
590 c->mon->tagset[c->mon->seltags] = c->tags;
591 }
592 pop(c);
593 }
594 }
595
596 void
597 configure(Client *c) {
598 XConfigureEvent ce;
599
600 ce.type = ConfigureNotify;
601 ce.display = dpy;
602 ce.event = c->win;
603 ce.window = c->win;
604 ce.x = c->x;
605 ce.y = c->y;
606 ce.width = c->w;
607 ce.height = c->h;
608 ce.border_width = c->bw;
609 ce.above = None;
610 ce.override_redirect = False;
611 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
612 }
613
614 void
615 configurenotify(XEvent *e) {
616 Monitor *m;
617 XConfigureEvent *ev = &e->xconfigure;
618 Bool dirty;
619
620 if(ev->window == root) {
621 dirty = (sw != ev->width);
622 sw = ev->width;
623 sh = ev->height;
624 if(updategeom() || dirty) {
625 if(dc.drawable != 0)
626 XFreePixmap(dpy, dc.drawable);
627 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
628 XftDrawChange(dc.xft.drawable, dc.drawable);
629 updatebars();
630 for(m = mons; m; m = m->next)
631 XMoveResizeWindow(dpy, m->barwin, m->wx, m->by, m->ww, bh);
632 focus(NULL);
633 arrange(NULL);
634 }
635 }
636 }
637
638 void
639 configurerequest(XEvent *e) {
640 Client *c;
641 Monitor *m;
642 XConfigureRequestEvent *ev = &e->xconfigurerequest;
643 XWindowChanges wc;
644
645 if((c = wintoclient(ev->window))) {
646 if(ev->value_mask & CWBorderWidth)
647 c->bw = ev->border_width;
648 else if(c->isfloating || !selmon->lt[selmon->sellt]->arrange) {
649 m = c->mon;
650 if(ev->value_mask & CWX) {
651 c->oldx = c->x;
652 c->x = m->mx + ev->x;
653 }
654 if(ev->value_mask & CWY) {
655 c->oldy = c->y;
656 c->y = m->my + ev->y;
657 }
658 if(ev->value_mask & CWWidth) {
659 c->oldw = c->w;
660 c->w = ev->width;
661 }
662 if(ev->value_mask & CWHeight) {
663 c->oldh = c->h;
664 c->h = ev->height;
665 }
666 if((c->x + c->w) > m->mx + m->mw && c->isfloating)
667 c->x = m->mx + (m->mw / 2 - WIDTH(c) / 2); /* center in x direction */
668 if((c->y + c->h) > m->my + m->mh && c->isfloating)
669 c->y = m->my + (m->mh / 2 - HEIGHT(c) / 2); /* center in y direction */
670 if((ev->value_mask & (CWX|CWY)) && !(ev->value_mask & (CWWidth|CWHeight)))
671 configure(c);
672 if(ISVISIBLE(c))
673 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
674 }
675 else
676 configure(c);
677 }
678 else {
679 wc.x = ev->x;
680 wc.y = ev->y;
681 wc.width = ev->width;
682 wc.height = ev->height;
683 wc.border_width = ev->border_width;
684 wc.sibling = ev->above;
685 wc.stack_mode = ev->detail;
686 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
687 }
688 XSync(dpy, False);
689 }
690
691 Monitor *
692 createmon(void) {
693 Monitor *m;
694 int i;
695
696 if(!(m = (Monitor *)calloc(1, sizeof(Monitor))))
697 die("fatal: could not malloc() %u bytes\n", sizeof(Monitor));
698 m->tagset[0] = m->tagset[1] = 1;
699 m->mfact = mfact;
700 m->nmaster = nmaster;
701 m->showbar = showbar;
702 m->topbar = topbar;
703 m->lt[0] = &layouts[0];
704 m->lt[1] = &layouts[1 % LENGTH(layouts)];
705 strncpy(m->ltsymbol, layouts[0].symbol, sizeof m->ltsymbol);
706 if(!(m->pertag = (Pertag *)calloc(1, sizeof(Pertag))))
707 die("fatal: could not malloc() %u bytes\n", sizeof(Pertag));
708 m->pertag->curtag = m->pertag->prevtag = 1;
709 for(i=0; i <= LENGTH(tags); i++) {
710 /* init nmaster */
711 m->pertag->nmasters[i] = m->nmaster;
712
713 /* init mfacts */
714 m->pertag->mfacts[i] = m->mfact;
715
716 /* init layouts */
717 m->pertag->ltidxs[i][0] = m->lt[0];
718 m->pertag->ltidxs[i][1] = m->lt[1];
719 m->pertag->sellts[i] = m->sellt;
720
721 /* init showbar */
722 m->pertag->showbars[i] = m->showbar;
723 }
724 return m;
725 }
726
727 void
728 destroynotify(XEvent *e) {
729 Client *c;
730 XDestroyWindowEvent *ev = &e->xdestroywindow;
731
732 if((c = wintoclient(ev->window)))
733 unmanage(c, True);
734 }
735
736 void
737 detach(Client *c) {
738 Client **tc;
739
740 for(tc = &c->mon->clients; *tc && *tc != c; tc = &(*tc)->next);
741 *tc = c->next;
742 }
743
744 void
745 detachstack(Client *c) {
746 Client **tc, *t;
747
748 for(tc = &c->mon->stack; *tc && *tc != c; tc = &(*tc)->snext);
749 *tc = c->snext;
750
751 if(c == c->mon->sel) {
752 for(t = c->mon->stack; t && !ISVISIBLE(t); t = t->snext);
753 c->mon->sel = t;
754 }
755 }
756
757 void
758 die(const char *errstr, ...) {
759 va_list ap;
760
761 va_start(ap, errstr);
762 vfprintf(stderr, errstr, ap);
763 va_end(ap);
764 exit(EXIT_FAILURE);
765 }
766
767 Monitor *
768 dirtomon(int dir) {
769 Monitor *m = NULL;
770
771 if(dir > 0) {
772 if(!(m = selmon->next))
773 m = mons;
774 }
775 else if(selmon == mons)
776 for(m = mons; m->next; m = m->next);
777 else
778 for(m = mons; m->next != selmon; m = m->next);
779 return m;
780 }
781
782 void
783 dispatchcmd(void)
784 {
785 int i;
786 char buf[BUFSIZ];
787 ssize_t n;
788
789 n = read(fifofd, buf, sizeof(buf) - 1);
790 if (n == -1)
791 die("Failed to read() from DWM fifo %s:", dwmfifo);
792 buf[n] = '\0';
793 for (i = 0; i < LENGTH(commands); i++) {
794 if (strcmp(commands[i].name, buf) == 0) {
795 commands[i].func(&commands[i].arg);
796 break;
797 }
798 }
799 }
800
801
802 void
803 drawbar(Monitor *m) {
804 int x;
805 unsigned int i, occ = 0, urg = 0;
806 unsigned long *col;
807 Client *c;
808
809 for(c = m->clients; c; c = c->next) {
810 occ |= c->tags;
811 if(c->isurgent)
812 urg |= c->tags;
813 }
814 dc.x = 0;
815 for(i = 0; i < LENGTH(tags); i++) {
816 dc.w = TEXTW(tags[i]);
817 col = m->tagset[m->seltags] & 1 << i ? dc.sel : dc.norm;
818 drawtext(tags[i], col, urg & 1 << i);
819 drawsquare(m == selmon && selmon->sel && selmon->sel->tags & 1 << i,
820 occ & 1 << i, urg & 1 << i, col);
821 dc.x += dc.w;
822 }
823 dc.w = blw = TEXTW(m->ltsymbol);
824 drawtext(m->ltsymbol, dc.norm, False);
825 dc.x += dc.w;
826 x = dc.x;
827 if(m == selmon) { /* status is only drawn on selected monitor */
828 dc.w = TEXTW(stext);
829 dc.x = m->ww - dc.w;
830 if(dc.x < x) {
831 dc.x = x;
832 dc.w = m->ww - x;
833 }
834 drawtext(stext, dc.norm, False);
835 }
836 else
837 dc.x = m->ww;
838 if((dc.w = dc.x - x) > bh) {
839 dc.x = x;
840 if(m->sel) {
841 col = m == selmon ? dc.sel : dc.norm;
842 drawtext(m->sel->name, col, False);
843 drawsquare(m->sel->isfixed, m->sel->isfloating, False, col);
844 }
845 else
846 drawtext(NULL, dc.norm, False);
847 }
848 XCopyArea(dpy, dc.drawable, m->barwin, dc.gc, 0, 0, m->ww, bh, 0, 0);
849 XSync(dpy, False);
850 }
851
852 void
853 drawbars(void) {
854 Monitor *m;
855
856 for(m = mons; m; m = m->next)
857 drawbar(m);
858 }
859
860 void
861 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
862 int x;
863
864 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
865 x = (dc.font.ascent + dc.font.descent + 2) / 4;
866 if(filled)
867 XFillRectangle(dpy, dc.drawable, dc.gc, dc.x+1, dc.y+1, x+1, x+1);
868 else if(empty)
869 XDrawRectangle(dpy, dc.drawable, dc.gc, dc.x+1, dc.y+1, x, x);
870 }
871
872 void
873 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
874 char buf[512];
875 int i, x, y, h, len, olen;
876
877 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
878 XFillRectangle(dpy, dc.drawable, dc.gc, dc.x, dc.y, dc.w, dc.h);
879 if(!text)
880 return;
881 olen = strlen(text);
882 h = dc.font.ascent + dc.font.descent;
883 y = dc.y + (dc.h / 2) - (h / 2);
884 x = dc.x + (h / 2);
885 /* shorten text if necessary (this could wreak havoc with pango markup but fortunately
886 dc.w is adjusted to the width of the status text and not the other way around) */
887 for(len = MIN(olen, sizeof buf); len && textnw(text, len) > dc.w - h; len--);
888 if(!len)
889 return;
890 memcpy(buf, text, len);
891 if(len < olen)
892 for(i = len; i && i > len - 3; buf[--i] = '.');
893 if(text == stext && statusmarkup)
894 pango_layout_set_markup(dc.font.layout, buf, len);
895 else
896 pango_layout_set_text(dc.font.layout, buf, len);
897 pango_xft_render_layout(dc.xft.drawable,
898 (col == dc.norm ? dc.xft.norm : dc.xft.sel) + (invert ? ColBG : ColFG),
899 dc.font.layout, x * PANGO_SCALE, y * PANGO_SCALE);
900 if(text == stext && statusmarkup) /* clear markup attributes */
901 pango_layout_set_attributes(dc.font.layout, NULL);
902 }
903
904 void
905 enternotify(XEvent *e) {
906 Client *c;
907 Monitor *m;
908 XCrossingEvent *ev = &e->xcrossing;
909
910 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
911 return;
912 c = wintoclient(ev->window);
913 m = c ? c->mon : wintomon(ev->window);
914 if(m != selmon) {
915 unfocus(selmon->sel, True);
916 selmon = m;
917 }
918 else if(!c || c == selmon->sel)
919 return;
920 focus(c);
921 }
922
923 Bool
924 evpredicate()
925 {
926 return True;
927 }
928
929 void
930 expose(XEvent *e) {
931 Monitor *m;
932 XExposeEvent *ev = &e->xexpose;
933
934 if(ev->count == 0 && (m = wintomon(ev->window)))
935 drawbar(m);
936 }
937
938 void
939 findwindow (const Arg *arg) {
940 /* Tries to find an emacs instance. If it finds one,
941 it displays it. */
942 Arg a;
943 Monitor *m;
944 Client *c;
945 XClassHint ch = { NULL, NULL};
946 const char *class ;
947 for (m=mons; m; m = m->next)
948 for (c=m->clients; c; c=c->next) {
949 XGetClassHint(dpy, c->win, &ch);
950 class = ch.res_class ? ch.res_class : broken;
951 if (strstr(class,(char*)arg->v)) {
952 a.ui = c->tags;
953 view(&a);
954 unfocus(selmon->sel, True); /* this should focus the right monitor (not tested)*/
955 selmon = m;
956 focus(c);
957 restack(selmon);
958 if(ch.res_class)
959 XFree(ch.res_class);
960 if(ch.res_name)
961 XFree(ch.res_name);
962 return;
963 }
964 }
965 }
966
967 void
968 focus(Client *c) {
969 if(!c || !ISVISIBLE(c))
970 for(c = selmon->stack; c && !ISVISIBLE(c); c = c->snext);
971 /* was if(selmon->sel) */
972 if(selmon->sel && selmon->sel != c)
973 unfocus(selmon->sel, False);
974 if(c) {
975 if(c->mon != selmon)
976 selmon = c->mon;
977 if(c->isurgent)
978 clearurgent(c);
979 detachstack(c);
980 attachstack(c);
981 grabbuttons(c, True);
982 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
983 setfocus(c);
984 }
985 else
986 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
987 selmon->sel = c;
988 drawbars();
989 }
990
991 void
992 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
993 XFocusChangeEvent *ev = &e->xfocus;
994
995 if(selmon->sel && ev->window != selmon->sel->win)
996 setfocus(selmon->sel);
997 }
998
999 void
1000 focusmon(const Arg *arg) {
1001 Monitor *m;
1002
1003 if(!mons->next)
1004 return;
1005 if((m = dirtomon(arg->i)) == selmon)
1006 return;
1007 unfocus(selmon->sel, True);
1008 selmon = m;
1009 focus(NULL);
1010 }
1011
1012 void
1013 focusstack(const Arg *arg) {
1014 Client *c = NULL, *i;
1015
1016 if(!selmon->sel)
1017 return;
1018 if(arg->i > 0) {
1019 for(c = selmon->sel->next; c && !ISVISIBLE(c); c = c->next);
1020 if(!c)
1021 for(c = selmon->clients; c && !ISVISIBLE(c); c = c->next);
1022 }
1023 else {
1024 for(i = selmon->clients; i != selmon->sel; i = i->next)
1025 if(ISVISIBLE(i))
1026 c = i;
1027 if(!c)
1028 for(; i; i = i->next)
1029 if(ISVISIBLE(i))
1030 c = i;
1031 }
1032 if(c) {
1033 focus(c);
1034 restack(selmon);
1035 }
1036 }
1037
1038 Atom
1039 getatomprop(Client *c, Atom prop) {
1040 int di;
1041 unsigned long dl;
1042 unsigned char *p = NULL;
1043 Atom da, atom = None;
1044
1045 if(XGetWindowProperty(dpy, c->win, prop, 0L, sizeof atom, False, XA_ATOM,
1046 &da, &di, &dl, &dl, &p) == Success && p) {
1047 atom = *(Atom *)p;
1048 XFree(p);
1049 }
1050 return atom;
1051 }
1052
1053 unsigned long
1054 getcolor(const char *colstr, XftColor *color) {
1055 Colormap cmap = DefaultColormap(dpy, screen);
1056 Visual *vis = DefaultVisual(dpy, screen);
1057
1058 if(!XftColorAllocName(dpy, vis, cmap, colstr, color))
1059 die("error, cannot allocate color '%s'\n", colstr);
1060 return color->pixel;
1061 }
1062
1063 Bool
1064 getrootptr(int *x, int *y) {
1065 int di;
1066 unsigned int dui;
1067 Window dummy;
1068
1069 return XQueryPointer(dpy, root, &dummy, &dummy, x, y, &di, &di, &dui);
1070 }
1071
1072 long
1073 getstate(Window w) {
1074 int format;
1075 long result = -1;
1076 unsigned char *p = NULL;
1077 unsigned long n, extra;
1078 Atom real;
1079
1080 if(XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
1081 &real, &format, &n, &extra, (unsigned char **)&p) != Success)
1082 return -1;
1083 if(n != 0)
1084 result = *p;
1085 XFree(p);
1086 return result;
1087 }
1088
1089 Bool
1090 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
1091 char **list = NULL;
1092 int n;
1093 XTextProperty name;
1094
1095 if(!text || size == 0)
1096 return False;
1097 text[0] = '\0';
1098 XGetTextProperty(dpy, w, &name, atom);
1099 if(!name.nitems)
1100 return False;
1101 if(name.encoding == XA_STRING)
1102 strncpy(text, (char *)name.value, size - 1);
1103 else {
1104 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success && n > 0 && *list) {
1105 strncpy(text, *list, size - 1);
1106 XFreeStringList(list);
1107 }
1108 }
1109 text[size - 1] = '\0';
1110 XFree(name.value);
1111 return True;
1112 }
1113
1114 void
1115 grabbuttons(Client *c, Bool focused) {
1116 updatenumlockmask();
1117 {
1118 unsigned int i, j;
1119 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
1120 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1121 if(focused) {
1122 for(i = 0; i < LENGTH(buttons); i++)
1123 if(buttons[i].click == ClkClientWin)
1124 for(j = 0; j < LENGTH(modifiers); j++)
1125 XGrabButton(dpy, buttons[i].button,
1126 buttons[i].mask | modifiers[j],
1127 c->win, False, BUTTONMASK,
1128 GrabModeAsync, GrabModeSync, None, None);
1129 }
1130 else
1131 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
1132 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
1133 }
1134 }
1135
1136 void
1137 grabkeys(void) {
1138 updatenumlockmask();
1139 {
1140 unsigned int i, j;
1141 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
1142 KeyCode code;
1143
1144 XUngrabKey(dpy, AnyKey, AnyModifier, root);
1145 for(i = 0; i < LENGTH(keys); i++)
1146 if((code = XKeysymToKeycode(dpy, keys[i].keysym)))
1147 for(j = 0; j < LENGTH(modifiers); j++)
1148 XGrabKey(dpy, code, keys[i].mod | modifiers[j], root,
1149 True, GrabModeAsync, GrabModeAsync);
1150 }
1151 }
1152
1153 void
1154 incnmaster(const Arg *arg) {
1155 selmon->nmaster = selmon->pertag->nmasters[selmon->pertag->curtag] = MAX(selmon->nmaster + arg->i, 0);
1156 arrange(selmon);
1157 }
1158
1159 void
1160 initfont(const char *fontstr) {
1161 PangoFontMap *fontmap;
1162 PangoContext *context;
1163 PangoFontDescription *desc;
1164 PangoFontMetrics *metrics;
1165
1166 fontmap = pango_xft_get_font_map(dpy, screen);
1167 context = pango_font_map_create_context(fontmap);
1168 desc = pango_font_description_from_string(fontstr);
1169 dc.font.layout = pango_layout_new(context);
1170 pango_layout_set_font_description(dc.font.layout, desc);
1171
1172 metrics = pango_context_get_metrics(context, desc, NULL);
1173 dc.font.ascent = pango_font_metrics_get_ascent(metrics) / PANGO_SCALE;
1174 dc.font.descent = pango_font_metrics_get_descent(metrics) / PANGO_SCALE;
1175 dc.font.height = dc.font.ascent + dc.font.descent;
1176
1177 pango_font_metrics_unref(metrics);
1178 g_object_unref(context);
1179 }
1180
1181 #ifdef XINERAMA
1182 static Bool
1183 isuniquegeom(XineramaScreenInfo *unique, size_t n, XineramaScreenInfo *info) {
1184 while(n--)
1185 if(unique[n].x_org == info->x_org && unique[n].y_org == info->y_org
1186 && unique[n].width == info->width && unique[n].height == info->height)
1187 return False;
1188 return True;
1189 }
1190 #endif /* XINERAMA */
1191
1192 void
1193 keypress(XEvent *e) {
1194 unsigned int i;
1195 KeySym keysym;
1196 XKeyEvent *ev;
1197
1198 ev = &e->xkey;
1199 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
1200 for(i = 0; i < LENGTH(keys); i++)
1201 if(keysym == keys[i].keysym
1202 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
1203 && keys[i].func)
1204 keys[i].func(&(keys[i].arg));
1205 }
1206
1207 void
1208 killclient(const Arg *arg) {
1209 if(!selmon->sel)
1210 return;
1211 if(!sendevent(selmon->sel, wmatom[WMDelete])) {
1212 XGrabServer(dpy);
1213 XSetErrorHandler(xerrordummy);
1214 XSetCloseDownMode(dpy, DestroyAll);
1215 XKillClient(dpy, selmon->sel->win);
1216 XSync(dpy, False);
1217 XSetErrorHandler(xerror);
1218 XUngrabServer(dpy);
1219 }
1220 }
1221
1222 void
1223 list_clients(const Arg *arg) {
1224 /* wrapper function */
1225 listclients();
1226 }
1227 void
1228 listclients (void) {
1229 /* List the names of all clients */
1230 Monitor *m;
1231 FILE *clist;
1232 Client *c;
1233 clist = fopen("/tmp/clients", "w");
1234 for (m=mons; m; m = m->next)
1235 for (c=m->clients; c; c = c->next)
1236 fprintf(clist, "%s %o\n", c->name, c->tags);
1237 fclose(clist);
1238 }
1239
1240 void
1241 manage(Window w, XWindowAttributes *wa) {
1242 Client *c, *t = NULL;
1243 Window trans = None;
1244 XWindowChanges wc;
1245
1246 if(!(c = calloc(1, sizeof(Client))))
1247 die("fatal: could not malloc() %u bytes\n", sizeof(Client));
1248 c->win = w;
1249 updatetitle(c);
1250 if(XGetTransientForHint(dpy, w, &trans) && (t = wintoclient(trans))) {
1251 c->mon = t->mon;
1252 c->tags = t->tags;
1253 }
1254 else {
1255 c->mon = selmon;
1256 applyrules(c);
1257 }
1258 /* geometry */
1259 c->x = c->oldx = wa->x;
1260 c->y = c->oldy = wa->y;
1261 c->w = c->oldw = wa->width;
1262 c->h = c->oldh = wa->height;
1263 c->oldbw = wa->border_width;
1264
1265 if(c->x + WIDTH(c) > c->mon->mx + c->mon->mw)
1266 c->x = c->mon->mx + c->mon->mw - WIDTH(c);
1267 if(c->y + HEIGHT(c) > c->mon->my + c->mon->mh)
1268 c->y = c->mon->my + c->mon->mh - HEIGHT(c);
1269 c->x = MAX(c->x, c->mon->mx);
1270 /* only fix client y-offset, if the client center might cover the bar */
1271 c->y = MAX(c->y, ((c->mon->by == c->mon->my) && (c->x + (c->w / 2) >= c->mon->wx)
1272 && (c->x + (c->w / 2) < c->mon->wx + c->mon->ww)) ? bh : c->mon->my);
1273 c->bw = borderpx;
1274
1275 wc.border_width = c->bw;
1276 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1277 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1278 configure(c); /* propagates border_width, if size doesn't change */
1279 updatewindowtype(c);
1280 updatesizehints(c);
1281 updatewmhints(c);
1282 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
1283 grabbuttons(c, False);
1284 if(!c->isfloating)
1285 c->isfloating = c->oldstate = trans != None || c->isfixed;
1286 if(c->isfloating)
1287 XRaiseWindow(dpy, c->win);
1288 attach(c);
1289 attachstack(c);
1290 XMoveResizeWindow(dpy, c->win, c->x + 2 * sw, c->y, c->w, c->h); /* some windows require this */
1291 setclientstate(c, NormalState);
1292 if (c->mon == selmon)
1293 unfocus(selmon->sel, False);
1294 c->mon->sel = c;
1295 arrange(c->mon);
1296 XMapWindow(dpy, c->win);
1297 focus(NULL);
1298 }
1299
1300 void
1301 mappingnotify(XEvent *e) {
1302 XMappingEvent *ev = &e->xmapping;
1303
1304 XRefreshKeyboardMapping(ev);
1305 if(ev->request == MappingKeyboard)
1306 grabkeys();
1307 }
1308
1309 void
1310 maprequest(XEvent *e) {
1311 static XWindowAttributes wa;
1312 XMapRequestEvent *ev = &e->xmaprequest;
1313
1314 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1315 return;
1316 if(wa.override_redirect)
1317 return;
1318 if(!wintoclient(ev->window))
1319 manage(ev->window, &wa);
1320 }
1321
1322 void
1323 monocle(Monitor *m) {
1324 unsigned int n = 0;
1325 Client *c;
1326
1327 for(c = m->clients; c; c = c->next)
1328 if(ISVISIBLE(c))
1329 n++;
1330 if(n > 0) /* override layout symbol */
1331 snprintf(m->ltsymbol, sizeof m->ltsymbol, "[%d]", n);
1332 for(c = nexttiled(m->clients); c; c = nexttiled(c->next))
1333 resize(c, m->wx, m->wy, m->ww - 2 * c->bw, m->wh - 2 * c->bw, False);
1334 }
1335
1336 void
1337 motionnotify(XEvent *e) {
1338 static Monitor *mon = NULL;
1339 Monitor *m;
1340 XMotionEvent *ev = &e->xmotion;
1341
1342 if(ev->window != root)
1343 return;
1344 if((m = recttomon(ev->x_root, ev->y_root, 1, 1)) != mon && mon) {
1345 selmon = m;
1346 focus(NULL);
1347 }
1348 mon = m;
1349 }
1350
1351 void
1352 movemouse(const Arg *arg) {
1353 int x, y, ocx, ocy, nx, ny;
1354 Client *c;
1355 Monitor *m;
1356 XEvent ev;
1357
1358 if(!(c = selmon->sel))
1359 return;
1360 restack(selmon);
1361 ocx = c->x;
1362 ocy = c->y;
1363 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1364 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1365 return;
1366 if(!getrootptr(&x, &y))
1367 return;
1368 do {
1369 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1370 switch(ev.type) {
1371 case ConfigureRequest:
1372 case Expose:
1373 case MapRequest:
1374 handler[ev.type](&ev);
1375 break;
1376 case MotionNotify:
1377 nx = ocx + (ev.xmotion.x - x);
1378 ny = ocy + (ev.xmotion.y - y);
1379 if(nx >= selmon->wx && nx <= selmon->wx + selmon->ww
1380 && ny >= selmon->wy && ny <= selmon->wy + selmon->wh) {
1381 if(abs(selmon->wx - nx) < snap)
1382 nx = selmon->wx;
1383 else if(abs((selmon->wx + selmon->ww) - (nx + WIDTH(c))) < snap)
1384 nx = selmon->wx + selmon->ww - WIDTH(c);
1385 if(abs(selmon->wy - ny) < snap)
1386 ny = selmon->wy;
1387 else if(abs((selmon->wy + selmon->wh) - (ny + HEIGHT(c))) < snap)
1388 ny = selmon->wy + selmon->wh - HEIGHT(c);
1389 if(!c->isfloating && selmon->lt[selmon->sellt]->arrange
1390 && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
1391 togglefloating(NULL);
1392 }
1393 if(!selmon->lt[selmon->sellt]->arrange || c->isfloating)
1394 resize(c, nx, ny, c->w, c->h, True);
1395 break;
1396 }
1397 } while(ev.type != ButtonRelease);
1398 XUngrabPointer(dpy, CurrentTime);
1399 if((m = recttomon(c->x, c->y, c->w, c->h)) != selmon) {
1400 sendmon(c, m);
1401 selmon = m;
1402 focus(NULL);
1403 }
1404 }
1405
1406 Client *
1407 nexttiled(Client *c) {
1408 for(; c && (c->isfloating || !ISVISIBLE(c)); c = c->next);
1409 return c;
1410 }
1411
1412 void
1413 pop(Client *c) {
1414 detach(c);
1415 attach(c);
1416 focus(c);
1417 arrange(c->mon);
1418 }
1419
1420 void
1421 propertynotify(XEvent *e) {
1422 Client *c;
1423 Window trans;
1424 XPropertyEvent *ev = &e->xproperty;
1425
1426 if((ev->window == root) && (ev->atom == XA_WM_NAME))
1427 updatestatus();
1428 else if(ev->state == PropertyDelete)
1429 return; /* ignore */
1430 else if((c = wintoclient(ev->window))) {
1431 switch(ev->atom) {
1432 default: break;
1433 case XA_WM_TRANSIENT_FOR:
1434 if(!c->isfloating && (XGetTransientForHint(dpy, c->win, &trans)) &&
1435 (c->isfloating = (wintoclient(trans)) != NULL))
1436 arrange(c->mon);
1437 break;
1438 case XA_WM_NORMAL_HINTS:
1439 updatesizehints(c);
1440 break;
1441 case XA_WM_HINTS:
1442 updatewmhints(c);
1443 drawbars();
1444 break;
1445 }
1446 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1447 updatetitle(c);
1448 if(c == c->mon->sel)
1449 drawbar(c->mon);
1450 }
1451 if(ev->atom == netatom[NetWMWindowType])
1452 updatewindowtype(c);
1453 }
1454 }
1455
1456 void
1457 quit(const Arg *arg) {
1458 running = False;
1459 }
1460
1461 Monitor *
1462 recttomon(int x, int y, int w, int h) {
1463 Monitor *m, *r = selmon;
1464 int a, area = 0;
1465
1466 for(m = mons; m; m = m->next)
1467 if((a = INTERSECT(x, y, w, h, m)) > area) {
1468 area = a;
1469 r = m;
1470 }
1471 return r;
1472 }
1473
1474 void
1475 resize(Client *c, int x, int y, int w, int h, Bool interact) {
1476 if(applysizehints(c, &x, &y, &w, &h, interact))
1477 resizeclient(c, x, y, w, h);
1478 }
1479
1480 void
1481 resizeclient(Client *c, int x, int y, int w, int h) {
1482 XWindowChanges wc;
1483
1484 c->oldx = c->x; c->x = wc.x = x;
1485 c->oldy = c->y; c->y = wc.y = y;
1486 c->oldw = c->w; c->w = wc.width = w;
1487 c->oldh = c->h; c->h = wc.height = h;
1488 wc.border_width = c->bw;
1489 XConfigureWindow(dpy, c->win, CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1490 configure(c);
1491 XSync(dpy, False);
1492 }
1493
1494 void
1495 resizemouse(const Arg *arg) {
1496 int ocx, ocy;
1497 int nw, nh;
1498 Client *c;
1499 Monitor *m;
1500 XEvent ev;
1501
1502 if(!(c = selmon->sel))
1503 return;
1504 restack(selmon);
1505 ocx = c->x;
1506 ocy = c->y;
1507 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1508 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1509 return;
1510 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1511 do {
1512 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1513 switch(ev.type) {
1514 case ConfigureRequest:
1515 case Expose:
1516 case MapRequest:
1517 handler[ev.type](&ev);
1518 break;
1519 case MotionNotify:
1520 nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1521 nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1522 if(c->mon->wx + nw >= selmon->wx && c->mon->wx + nw <= selmon->wx + selmon->ww
1523 && c->mon->wy + nh >= selmon->wy && c->mon->wy + nh <= selmon->wy + selmon->wh)
1524 {
1525 if(!c->isfloating && selmon->lt[selmon->sellt]->arrange
1526 && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1527 togglefloating(NULL);
1528 }
1529 if(!selmon->lt[selmon->sellt]->arrange || c->isfloating)
1530 resize(c, c->x, c->y, nw, nh, True);
1531 break;
1532 }
1533 } while(ev.type != ButtonRelease);
1534 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1535 XUngrabPointer(dpy, CurrentTime);
1536 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1537 if((m = recttomon(c->x, c->y, c->w, c->h)) != selmon) {
1538 sendmon(c, m);
1539 selmon = m;
1540 focus(NULL);
1541 }
1542 }
1543
1544 void
1545 restack(Monitor *m) {
1546 Client *c;
1547 XEvent ev;
1548 XWindowChanges wc;
1549
1550 drawbar(m);
1551 if(!m->sel)
1552 return;
1553 if(m->sel->isfloating || !m->lt[m->sellt]->arrange)
1554 XRaiseWindow(dpy, m->sel->win);
1555 if(m->lt[m->sellt]->arrange) {
1556 wc.stack_mode = Below;
1557 wc.sibling = m->barwin;
1558 for(c = m->stack; c; c = c->snext)
1559 if(!c->isfloating && ISVISIBLE(c)) {
1560 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1561 wc.sibling = c->win;
1562 }
1563 }
1564 XSync(dpy, False);
1565 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1566 }
1567
1568 void
1569 run(void) {
1570 XEvent ev;
1571 fd_set rfds;
1572 int n;
1573 int dpyfd, maxfd;
1574 /* main event loop */
1575 XSync(dpy, False);
1576 dpyfd = ConnectionNumber(dpy);
1577 maxfd = fifofd;
1578 if (dpyfd > maxfd)
1579 maxfd = dpyfd;
1580 maxfd++;
1581 while (running) {
1582
1583 FD_ZERO(&rfds);
1584 FD_SET(fifofd, &rfds);
1585 FD_SET(dpyfd, &rfds);
1586 n = select(maxfd, &rfds, NULL, NULL, NULL);
1587 if (n > 0) {
1588 if (FD_ISSET(fifofd, &rfds))
1589 dispatchcmd();
1590 if (FD_ISSET(dpyfd, &rfds))
1591 while (XCheckIfEvent(dpy, &ev, evpredicate, NULL))
1592 if (handler[ev.type])
1593 handler[ev.type](&ev); /* call handler */
1594 }
1595 }
1596 }
1597
1598 void
1599 scan(void) {
1600 unsigned int i, num;
1601 Window d1, d2, *wins = NULL;
1602 XWindowAttributes wa;
1603
1604 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1605 for(i = 0; i < num; i++) {
1606 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1607 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1608 continue;
1609 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1610 manage(wins[i], &wa);
1611 }
1612 for(i = 0; i < num; i++) { /* now the transients */
1613 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1614 continue;
1615 if(XGetTransientForHint(dpy, wins[i], &d1)
1616 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1617 manage(wins[i], &wa);
1618 }
1619 if(wins)
1620 XFree(wins);
1621 }
1622 }
1623
1624 void
1625 sendmon(Client *c, Monitor *m) {
1626 if(c->mon == m)
1627 return;
1628 unfocus(c, True);
1629 detach(c);
1630 detachstack(c);
1631 c->mon = m;
1632 c->tags = m->tagset[m->seltags]; /* assign tags of target monitor */
1633 attach(c);
1634 attachstack(c);
1635 focus(NULL);
1636 arrange(NULL);
1637 }
1638
1639 void
1640 setclientstate(Client *c, long state) {
1641 long data[] = { state, None };
1642
1643 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1644 PropModeReplace, (unsigned char *)data, 2);
1645 }
1646
1647 Bool
1648 sendevent(Client *c, Atom proto) {
1649 int n;
1650 Atom *protocols;
1651 Bool exists = False;
1652 XEvent ev;
1653
1654 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
1655 while(!exists && n--)
1656 exists = protocols[n] == proto;
1657 XFree(protocols);
1658 }
1659 if(exists) {
1660 ev.type = ClientMessage;
1661 ev.xclient.window = c->win;
1662 ev.xclient.message_type = wmatom[WMProtocols];
1663 ev.xclient.format = 32;
1664 ev.xclient.data.l[0] = proto;
1665 ev.xclient.data.l[1] = CurrentTime;
1666 XSendEvent(dpy, c->win, False, NoEventMask, &ev);
1667 }
1668 return exists;
1669 }
1670
1671 void
1672 setfocus(Client *c) {
1673 if(!c->neverfocus)
1674 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
1675 sendevent(c, wmatom[WMTakeFocus]);
1676 }
1677
1678 void
1679 setfullscreen(Client *c, Bool fullscreen) {
1680 if(fullscreen) {
1681 XChangeProperty(dpy, c->win, netatom[NetWMState], XA_ATOM, 32,
1682 PropModeReplace, (unsigned char*)&netatom[NetWMFullscreen], 1);
1683 c->isfullscreen = True;
1684 c->oldstate = c->isfloating;
1685 c->oldbw = c->bw;
1686 c->bw = 0;
1687 c->isfloating = True;
1688 resizeclient(c, c->mon->mx, c->mon->my, c->mon->mw, c->mon->mh);
1689 XRaiseWindow(dpy, c->win);
1690 }
1691 else {
1692 XChangeProperty(dpy, c->win, netatom[NetWMState], XA_ATOM, 32,
1693 PropModeReplace, (unsigned char*)0, 0);
1694 c->isfullscreen = False;
1695 c->isfloating = c->oldstate;
1696 c->bw = c->oldbw;
1697 c->x = c->oldx;
1698 c->y = c->oldy;
1699 c->w = c->oldw;
1700 c->h = c->oldh;
1701 resizeclient(c, c->x, c->y, c->w, c->h);
1702 arrange(c->mon);
1703 }
1704 }
1705
1706 void
1707 setlayout(const Arg *arg) {
1708 if(!arg || !arg->v || arg->v != selmon->lt[selmon->sellt]) {
1709 selmon->pertag->sellts[selmon->pertag->curtag] ^= 1;
1710 selmon->sellt = selmon->pertag->sellts[selmon->pertag->curtag];
1711 }
1712 if(arg && arg->v)
1713 selmon->pertag->ltidxs[selmon->pertag->curtag][selmon->sellt] = (Layout *)arg->v;
1714 selmon->lt[selmon->sellt] = selmon->pertag->ltidxs[selmon->pertag->curtag][selmon->sellt];
1715 strncpy(selmon->ltsymbol, selmon->lt[selmon->sellt]->symbol, sizeof selmon->ltsymbol);
1716 if(selmon->sel)
1717 arrange(selmon);
1718 else
1719 drawbar(selmon);
1720 }
1721
1722 /* arg > 1.0 will set mfact absolutly */
1723 void
1724 setmfact(const Arg *arg) {
1725 float f;
1726
1727 if(!arg || !selmon->lt[selmon->sellt]->arrange)
1728 return;
1729 f = arg->f < 1.0 ? arg->f + selmon->mfact : arg->f - 1.0;
1730 if(f < 0.1 || f > 0.9)
1731 return;
1732 selmon->mfact = selmon->pertag->mfacts[selmon->pertag->curtag] = f;
1733 arrange(selmon);
1734 }
1735
1736 void
1737 setup(void) {
1738 XSetWindowAttributes wa;
1739
1740 /* clean up any zombies immediately */
1741 sigchld(0);
1742
1743 /* init screen */
1744 screen = DefaultScreen(dpy);
1745 root = RootWindow(dpy, screen);
1746 initfont(font);
1747 sw = DisplayWidth(dpy, screen);
1748 sh = DisplayHeight(dpy, screen);
1749 bh = dc.h = dc.font.height + 2;
1750 updategeom();
1751 /* init atoms */
1752 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1753 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1754 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1755 wmatom[WMTakeFocus] = XInternAtom(dpy, "WM_TAKE_FOCUS", False);
1756 netatom[NetActiveWindow] = XInternAtom(dpy, "_NET_ACTIVE_WINDOW", False);
1757 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1758 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1759 netatom[NetWMState] = XInternAtom(dpy, "_NET_WM_STATE", False);
1760 netatom[NetWMFullscreen] = XInternAtom(dpy, "_NET_WM_STATE_FULLSCREEN", False);
1761 netatom[NetWMWindowType] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE", False);
1762 netatom[NetWMWindowTypeDialog] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE_DIALOG", False);
1763 /* init cursors */
1764 cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1765 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1766 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1767 /* init appearance */
1768 dc.norm[ColBorder] = getcolor(normbordercolor, dc.xft.norm + ColBorder);
1769 dc.norm[ColBG] = getcolor(normbgcolor, dc.xft.norm + ColBG);
1770 dc.norm[ColFG] = getcolor(normfgcolor, dc.xft.norm + ColFG);
1771 dc.sel[ColBorder] = getcolor(selbordercolor, dc.xft.sel + ColBorder);
1772 dc.sel[ColBG] = getcolor(selbgcolor, dc.xft.sel + ColBG);
1773 dc.sel[ColFG] = getcolor(selfgcolor, dc.xft.sel + ColFG);
1774 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1775 dc.xft.drawable = XftDrawCreate(dpy, dc.drawable, DefaultVisual(dpy, screen), DefaultColormap(dpy, screen));
1776 dc.gc = XCreateGC(dpy, root, 0, NULL);
1777 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1778 /* init bars */
1779 updatebars();
1780 updatestatus();
1781 /* EWMH support per view */
1782 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1783 PropModeReplace, (unsigned char *) netatom, NetLast);
1784 /* select for events */
1785 wa.cursor = cursor[CurNormal];
1786 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask|ButtonPressMask|PointerMotionMask
1787 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask|PropertyChangeMask;
1788 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1789 XSelectInput(dpy, root, wa.event_mask);
1790 grabkeys();
1791 focus(NULL);
1792 // make fifo, if it exists: die.
1793 if (mkfifo(dwmfifo, S_IWUSR | S_IRUSR)<0) {
1794 die("Failed to create fifo %s", dwmfifo);
1795 }
1796
1797 fifofd = open(dwmfifo, O_RDWR | O_NONBLOCK);
1798 if (fifofd < 0)
1799 die("Failed to open() DWM fifo %s:", dwmfifo);
1800 }
1801
1802 void
1803 showhide(Client *c) {
1804 if(!c)
1805 return;
1806 if(ISVISIBLE(c)) { /* show clients top down */
1807 XMoveWindow(dpy, c->win, c->x, c->y);
1808 if((!c->mon->lt[c->mon->sellt]->arrange || c->isfloating) && !c->isfullscreen)
1809 resize(c, c->x, c->y, c->w, c->h, False);
1810 showhide(c->snext);
1811 }
1812 else { /* hide clients bottom up */
1813 showhide(c->snext);
1814 XMoveWindow(dpy, c->win, WIDTH(c) * -2, c->y);
1815 }
1816 }
1817
1818 void
1819 sigchld(int unused) {
1820 if(signal(SIGCHLD, sigchld) == SIG_ERR)
1821 die("Can't install SIGCHLD handler");
1822 while(0 < waitpid(-1, NULL, WNOHANG));
1823 }
1824
1825 void
1826 spawn(const Arg *arg) {
1827 if(fork() == 0) {
1828 if(dpy)
1829 close(ConnectionNumber(dpy));
1830 setsid();
1831 execvp(((char **)arg->v)[0], (char **)arg->v);
1832 fprintf(stderr, "dwm: execvp %s", ((char **)arg->v)[0]);
1833 perror(" failed");
1834 exit(EXIT_SUCCESS);
1835 }
1836 }
1837
1838 void
1839 tag(const Arg *arg) {
1840 if(selmon->sel && arg->ui & TAGMASK) {
1841 selmon->sel->tags = arg->ui & TAGMASK;
1842 focus(NULL);
1843 arrange(selmon);
1844 }
1845 }
1846
1847 void
1848 tagmon(const Arg *arg) {
1849 if(!selmon->sel || !mons->next)
1850 return;
1851 sendmon(selmon->sel, dirtomon(arg->i));
1852 }
1853
1854 int
1855 textnw(const char *text, unsigned int len) {
1856 PangoRectangle r;
1857 if(text == stext && statusmarkup)
1858 pango_layout_set_markup(dc.font.layout, text, len);
1859 else
1860 pango_layout_set_text(dc.font.layout, text, len);
1861 pango_layout_get_extents(dc.font.layout, 0, &r);
1862 if(text == stext && statusmarkup) /* clear markup attributes */
1863 pango_layout_set_attributes(dc.font.layout, NULL);
1864 return r.width / PANGO_SCALE;
1865 }
1866
1867 void
1868 tile(Monitor *m) {
1869 unsigned int i, n, h, mw, my, ty;
1870 Client *c;
1871
1872 for(n = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), n++);
1873 if(n == 0)
1874 return;
1875
1876 if(n > m->nmaster)
1877 mw = m->nmaster ? m->ww * m->mfact : 0;
1878 else
1879 mw = m->ww;
1880 for(i = my = ty = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), i++)
1881 if(i < m->nmaster) {
1882 h = (m->wh - my) / (MIN(n, m->nmaster) - i);
1883 resize(c, m->wx, m->wy + my, mw - (2*c->bw), h - (2*c->bw), False);
1884 my += HEIGHT(c);
1885 }
1886 else {
1887 h = (m->wh - ty) / (n - i);
1888 resize(c, m->wx + mw, m->wy + ty, m->ww - mw - (2*c->bw), h - (2*c->bw), False);
1889 ty += HEIGHT(c);
1890 }
1891 }
1892
1893 void
1894 togglebar(const Arg *arg) {
1895 selmon->showbar = selmon->pertag->showbars[selmon->pertag->curtag] = !selmon->showbar;
1896 updatebarpos(selmon);
1897 XMoveResizeWindow(dpy, selmon->barwin, selmon->wx, selmon->by, selmon->ww, bh);
1898 arrange(selmon);
1899 }
1900
1901 void
1902 togglefloating(const Arg *arg) {
1903 if(!selmon->sel)
1904 return;
1905 selmon->sel->isfloating = !selmon->sel->isfloating || selmon->sel->isfixed;
1906 if(selmon->sel->isfloating)
1907 resize(selmon->sel, selmon->sel->x, selmon->sel->y,
1908 selmon->sel->w, selmon->sel->h, False);
1909 arrange(selmon);
1910 }
1911
1912 void
1913 toggletag(const Arg *arg) {
1914 unsigned int newtags;
1915
1916 if(!selmon->sel)
1917 return;
1918 newtags = selmon->sel->tags ^ (arg->ui & TAGMASK);
1919 if(newtags) {
1920 selmon->sel->tags = newtags;
1921 focus(NULL);
1922 arrange(selmon);
1923 }
1924 }
1925
1926 void
1927 toggleview(const Arg *arg) {
1928 unsigned int newtagset = selmon->tagset[selmon->seltags] ^ (arg->ui & TAGMASK);
1929 int i;
1930
1931 if(newtagset) {
1932 if(newtagset == ~0) {
1933 selmon->pertag->prevtag = selmon->pertag->curtag;
1934 selmon->pertag->curtag = 0;
1935 }
1936 /* test if the user did not select the same tag */
1937 if(!(newtagset & 1 << (selmon->pertag->curtag - 1))) {
1938 selmon->pertag->prevtag = selmon->pertag->curtag;
1939 for (i=0; !(newtagset & 1 << i); i++) ;
1940 selmon->pertag->curtag = i + 1;
1941 }
1942 selmon->tagset[selmon->seltags] = newtagset;
1943
1944 /* apply settings for this view */
1945 selmon->nmaster = selmon->pertag->nmasters[selmon->pertag->curtag];
1946 selmon->mfact = selmon->pertag->mfacts[selmon->pertag->curtag];
1947 selmon->sellt = selmon->pertag->sellts[selmon->pertag->curtag];
1948 selmon->lt[selmon->sellt] = selmon->pertag->ltidxs[selmon->pertag->curtag][selmon->sellt];
1949 selmon->lt[selmon->sellt^1] = selmon->pertag->ltidxs[selmon->pertag->curtag][selmon->sellt^1];
1950 if (selmon->showbar != selmon->pertag->showbars[selmon->pertag->curtag])
1951 togglebar(NULL);
1952 focus(NULL);
1953 arrange(selmon);
1954 }
1955 }
1956
1957 void
1958 unfocus(Client *c, Bool setfocus) {
1959 if(!c)
1960 return;
1961 grabbuttons(c, False);
1962 XSetWindowBorder(dpy, c->win, dc.norm[ColBorder]);
1963 if(setfocus)
1964 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
1965 }
1966
1967 void
1968 unmanage(Client *c, Bool destroyed) {
1969 Monitor *m = c->mon;
1970 XWindowChanges wc;
1971
1972 /* The server grab construct avoids race conditions. */
1973 detach(c);
1974 detachstack(c);
1975 if(!destroyed) {
1976 wc.border_width = c->oldbw;
1977 XGrabServer(dpy);
1978 XSetErrorHandler(xerrordummy);
1979 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1980 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1981 setclientstate(c, WithdrawnState);
1982 XSync(dpy, False);
1983 XSetErrorHandler(xerror);
1984 XUngrabServer(dpy);
1985 }
1986 free(c);
1987 focus(NULL);
1988 arrange(m);
1989 }
1990
1991 void
1992 unmapnotify(XEvent *e) {
1993 Client *c;
1994 XUnmapEvent *ev = &e->xunmap;
1995
1996 if((c = wintoclient(ev->window))) {
1997 if(ev->send_event)
1998 setclientstate(c, WithdrawnState);
1999 else
2000 unmanage(c, False);
2001 }
2002 }
2003
2004 void
2005 updatebars(void) {
2006 Monitor *m;
2007 XSetWindowAttributes wa = {
2008 .override_redirect = True,
2009 .background_pixmap = ParentRelative,
2010 .event_mask = ButtonPressMask|ExposureMask
2011 };
2012 for(m = mons; m; m = m->next) {
2013 m->barwin = XCreateWindow(dpy, root, m->wx, m->by, m->ww, bh, 0, DefaultDepth(dpy, screen),
2014 CopyFromParent, DefaultVisual(dpy, screen),
2015 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
2016 XDefineCursor(dpy, m->barwin, cursor[CurNormal]);
2017 XMapRaised(dpy, m->barwin);
2018 }
2019 }
2020
2021 void
2022 updatebarpos(Monitor *m) {
2023 m->wy = m->my;
2024 m->wh = m->mh;
2025 if(m->showbar) {
2026 m->wh -= bh;
2027 m->by = m->topbar ? m->wy : m->wy + m->wh;
2028 m->wy = m->topbar ? m->wy + bh : m->wy;
2029 }
2030 else
2031 m->by = -bh;
2032 }
2033
2034 Bool
2035 updategeom(void) {
2036 Bool dirty = False;
2037
2038 #ifdef XINERAMA
2039 if(XineramaIsActive(dpy)) {
2040 int i, j, n, nn;
2041 Client *c;
2042 Monitor *m;
2043 XineramaScreenInfo *info = XineramaQueryScreens(dpy, &nn);
2044 XineramaScreenInfo *unique = NULL;
2045
2046 for(n = 0, m = mons; m; m = m->next, n++);
2047 /* only consider unique geometries as separate screens */
2048 if(!(unique = (XineramaScreenInfo *)malloc(sizeof(XineramaScreenInfo) * nn)))
2049 die("fatal: could not malloc() %u bytes\n", sizeof(XineramaScreenInfo) * nn);
2050 for(i = 0, j = 0; i < nn; i++)
2051 if(isuniquegeom(unique, j, &info[i]))
2052 memcpy(&unique[j++], &info[i], sizeof(XineramaScreenInfo));
2053 XFree(info);
2054 nn = j;
2055 if(n <= nn) {
2056 for(i = 0; i < (nn - n); i++) { /* new monitors available */
2057 for(m = mons; m && m->next; m = m->next);
2058 if(m)
2059 m->next = createmon();
2060 else
2061 mons = createmon();
2062 }
2063 for(i = 0, m = mons; i < nn && m; m = m->next, i++)
2064 if(i >= n
2065 || (unique[i].x_org != m->mx || unique[i].y_org != m->my
2066 || unique[i].width != m->mw || unique[i].height != m->mh))
2067 {
2068 dirty = True;
2069 m->num = i;
2070 m->mx = m->wx = unique[i].x_org;
2071 m->my = m->wy = unique[i].y_org;
2072 m->mw = m->ww = unique[i].width;
2073 m->mh = m->wh = unique[i].height;
2074 updatebarpos(m);
2075 }
2076 }
2077 else { /* less monitors available nn < n */
2078 for(i = nn; i < n; i++) {
2079 for(m = mons; m && m->next; m = m->next);
2080 while(m->clients) {
2081 dirty = True;
2082 c = m->clients;
2083 m->clients = c->next;
2084 detachstack(c);
2085 c->mon = mons;
2086 attach(c);
2087 attachstack(c);
2088 }
2089 if(m == selmon)
2090 selmon = mons;
2091 cleanupmon(m);
2092 }
2093 }
2094 free(unique);
2095 }
2096 else
2097 #endif /* XINERAMA */
2098 /* default monitor setup */
2099 {
2100 if(!mons)
2101 mons = createmon();
2102 if(mons->mw != sw || mons->mh != sh) {
2103 dirty = True;
2104 mons->mw = mons->ww = sw;
2105 mons->mh = mons->wh = sh;
2106 updatebarpos(mons);
2107 }
2108 }
2109 if(dirty) {
2110 selmon = mons;
2111 selmon = wintomon(root);
2112 }
2113 return dirty;
2114 }
2115
2116 void
2117 updatenumlockmask(void) {
2118 unsigned int i, j;
2119 XModifierKeymap *modmap;
2120
2121 numlockmask = 0;
2122 modmap = XGetModifierMapping(dpy);
2123 for(i = 0; i < 8; i++)
2124 for(j = 0; j < modmap->max_keypermod; j++)
2125 if(modmap->modifiermap[i * modmap->max_keypermod + j]
2126 == XKeysymToKeycode(dpy, XK_Num_Lock))
2127 numlockmask = (1 << i);
2128 XFreeModifiermap(modmap);
2129 }
2130
2131 void
2132 updatesizehints(Client *c) {
2133 long msize;
2134 XSizeHints size;
2135
2136 if(!XGetWMNormalHints(dpy, c->win, &size, &msize))
2137 /* size is uninitialized, ensure that size.flags aren't used */
2138 size.flags = PSize;
2139 if(size.flags & PBaseSize) {
2140 c->basew = size.base_width;
2141 c->baseh = size.base_height;
2142 }
2143 else if(size.flags & PMinSize) {
2144 c->basew = size.min_width;
2145 c->baseh = size.min_height;
2146 }
2147 else
2148 c->basew = c->baseh = 0;
2149 if(size.flags & PResizeInc) {
2150 c->incw = size.width_inc;
2151 c->inch = size.height_inc;
2152 }
2153 else
2154 c->incw = c->inch = 0;
2155 if(size.flags & PMaxSize) {
2156 c->maxw = size.max_width;
2157 c->maxh = size.max_height;
2158 }
2159 else
2160 c->maxw = c->maxh = 0;
2161 if(size.flags & PMinSize) {
2162 c->minw = size.min_width;
2163 c->minh = size.min_height;
2164 }
2165 else if(size.flags & PBaseSize) {
2166 c->minw = size.base_width;
2167 c->minh = size.base_height;
2168 }
2169 else
2170 c->minw = c->minh = 0;
2171 if(size.flags & PAspect) {
2172 c->mina = (float)size.min_aspect.y / size.min_aspect.x;
2173 c->maxa = (float)size.max_aspect.x / size.max_aspect.y;
2174 }
2175 else
2176 c->maxa = c->mina = 0.0;
2177 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
2178 && c->maxw == c->minw && c->maxh == c->minh);
2179 }
2180
2181 void
2182 updatetitle(Client *c) {
2183 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
2184 gettextprop(c->win, XA_WM_NAME, c->name, sizeof c->name);
2185 if(c->name[0] == '\0') /* hack to mark broken clients */
2186 strcpy(c->name, broken);
2187 }
2188
2189 void
2190 updatestatus(void) {
2191 if(!gettextprop(root, XA_WM_NAME, stext, sizeof(stext)))
2192 strcpy(stext, "dwm-"VERSION);
2193 drawbar(selmon);
2194 }
2195
2196 void
2197 updatewindowtype(Client *c) {
2198 Atom state = getatomprop(c, netatom[NetWMState]);
2199 Atom wtype = getatomprop(c, netatom[NetWMWindowType]);
2200
2201 if(state == netatom[NetWMFullscreen])
2202 setfullscreen(c, True);
2203
2204 if(wtype == netatom[NetWMWindowTypeDialog])
2205 c->isfloating = True;
2206 }
2207
2208 void
2209 updatewmhints(Client *c) {
2210 XWMHints *wmh;
2211
2212 if((wmh = XGetWMHints(dpy, c->win))) {
2213 if(c == selmon->sel && wmh->flags & XUrgencyHint) {
2214 wmh->flags &= ~XUrgencyHint;
2215 XSetWMHints(dpy, c->win, wmh);
2216 }
2217 else
2218 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
2219 if(wmh->flags & InputHint)
2220 c->neverfocus = !wmh->input;
2221 else
2222 c->neverfocus = False;
2223 XFree(wmh);
2224 }
2225 }
2226
2227 void
2228 view(const Arg *arg) {
2229 int i;
2230 unsigned int tmptag;
2231
2232 if((arg->ui & TAGMASK) == selmon->tagset[selmon->seltags])
2233 return;
2234 selmon->seltags ^= 1; /* toggle sel tagset */
2235 if(arg->ui & TAGMASK) {
2236 selmon->pertag->prevtag = selmon->pertag->curtag;
2237 selmon->tagset[selmon->seltags] = arg->ui & TAGMASK;
2238 if(arg->ui == ~0)
2239 selmon->pertag->curtag = 0;
2240 else {
2241 for (i=0; !(arg->ui & 1 << i); i++) ;
2242 selmon->pertag->curtag = i + 1;
2243 }
2244 } else {
2245 tmptag = selmon->pertag->prevtag;
2246 selmon->pertag->prevtag = selmon->pertag->curtag;
2247 selmon->pertag->curtag = tmptag;
2248 }
2249 selmon->nmaster = selmon->pertag->nmasters[selmon->pertag->curtag];
2250 selmon->mfact = selmon->pertag->mfacts[selmon->pertag->curtag];
2251 selmon->sellt = selmon->pertag->sellts[selmon->pertag->curtag];
2252 selmon->lt[selmon->sellt] = selmon->pertag->ltidxs[selmon->pertag->curtag][selmon->sellt];
2253 selmon->lt[selmon->sellt^1] = selmon->pertag->ltidxs[selmon->pertag->curtag][selmon->sellt^1];
2254 if (selmon->showbar != selmon->pertag->showbars[selmon->pertag->curtag])
2255 togglebar(NULL);
2256 focus(NULL);
2257 arrange(selmon);
2258 }
2259
2260 Client *
2261 wintoclient(Window w) {
2262 Client *c;
2263 Monitor *m;
2264
2265 for(m = mons; m; m = m->next)
2266 for(c = m->clients; c; c = c->next)
2267 if(c->win == w)
2268 return c;
2269 return NULL;
2270 }
2271
2272 Monitor *
2273 wintomon(Window w) {
2274 int x, y;
2275 Client *c;
2276 Monitor *m;
2277
2278 if(w == root && getrootptr(&x, &y))
2279 return recttomon(x, y, 1, 1);
2280 for(m = mons; m; m = m->next)
2281 if(w == m->barwin)
2282 return m;
2283 if((c = wintoclient(w)))
2284 return c->mon;
2285 return selmon;
2286 }
2287
2288 /* There's no way to check accesses to destroyed windows, thus those cases are
2289 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
2290 * default error handler, which may call exit. */
2291 int
2292 xerror(Display *dpy, XErrorEvent *ee) {
2293 if(ee->error_code == BadWindow
2294 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
2295 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
2296 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
2297 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
2298 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
2299 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
2300 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
2301 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
2302 return 0;
2303 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
2304 ee->request_code, ee->error_code);
2305 return xerrorxlib(dpy, ee); /* may call exit */
2306 }
2307
2308 int
2309 xerrordummy(Display *dpy, XErrorEvent *ee) {
2310 return 0;
2311 }
2312
2313 /* Startup Error handler to check if another window manager
2314 * is already running. */
2315 int
2316 xerrorstart(Display *dpy, XErrorEvent *ee) {
2317 die("dwm: another window manager is already running\n");
2318 return -1;
2319 }
2320
2321 void
2322 zoom(const Arg *arg) {
2323 Client *c = selmon->sel;
2324
2325 if(!selmon->lt[selmon->sellt]->arrange
2326 || (selmon->sel && selmon->sel->isfloating))
2327 return;
2328 if(c == nexttiled(selmon->clients))
2329 if(!c || !(c = nexttiled(c->next)))
2330 return;
2331 pop(c);
2332 }
2333
2334 int
2335 main(int argc, char *argv[]) {
2336 if(argc == 2 && !strcmp("-v", argv[1]))
2337 die("dwm-"VERSION", © 2006-2011 dwm engineers, see LICENSE for details\n");
2338 if(argc == 2 && !strncmp("-f", argv[1],2)) {
2339 argv[1]+=2;
2340 dwmfifo=argv[1];
2341 }
2342 else if(argc != 1)
2343 die("usage: dwm [-v]\n");
2344 if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
2345 fputs("warning: no locale support\n", stderr);
2346 if(!(dpy = XOpenDisplay(NULL)))
2347 die("dwm: cannot open display\n");
2348 checkotherwm();
2349 setup();
2350 scan();
2351 run();
2352 cleanup();
2353 XCloseDisplay(dpy);
2354 return EXIT_SUCCESS;
2355 }