Xinqi Bao's Git

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