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