Xinqi Bao's Git

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