Xinqi Bao's Git

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