Xinqi Bao's Git

af0763804620812d5903392033fef1e682867bce
[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 * Calls to fetch an X event from the event queue are blocking. Due reading
10 * status text from standard input, a select()-driven main loop has been
11 * implemented which selects for reads on the X connection and STDIN_FILENO to
12 * handle all data smoothly. The event handlers of dwm are organized in an
13 * array which is accessed whenever a new event has been fetched. This allows
14 * event dispatching in O(1) time.
15 *
16 * Each child of the root window is called a client, except windows which have
17 * set the override_redirect flag. Clients are organized in a global
18 * doubly-linked client list, the focus history is remembered through a global
19 * stack list. Each client contains an array of Bools of the same size as the
20 * global tags array to indicate the tags of a client. For each client dwm
21 * creates a small title window, which is resized whenever the (_NET_)WM_NAME
22 * properties are updated or the client is moved/resized.
23 *
24 * Keys and tagging rules are organized as arrays and defined in config.h.
25 *
26 * To understand everything else, start reading main().
27 */
28 #include "dwm.h"
29
30 #include <errno.h>
31 #include <locale.h>
32 #include <stdarg.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <unistd.h>
37 #include <sys/select.h>
38 #include <sys/types.h>
39 #include <sys/wait.h>
40 #include <regex.h>
41 #include <X11/cursorfont.h>
42 #include <X11/keysym.h>
43 #include <X11/Xatom.h>
44 #include <X11/Xproto.h>
45 #include <X11/Xutil.h>
46
47 /* macros */
48 #define BUTTONMASK (ButtonPressMask | ButtonReleaseMask)
49 #define CLEANMASK(mask) (mask & ~(numlockmask | LockMask))
50 #define MOUSEMASK (BUTTONMASK | PointerMotionMask)
51
52 /* enums */
53 enum { BarTop, BarBot, BarOff }; /* bar position */
54 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
55 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
56 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
57 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
58
59 /* typedefs */
60 typedef struct {
61 int x, y, w, h;
62 unsigned long norm[ColLast];
63 unsigned long sel[ColLast];
64 Drawable drawable;
65 GC gc;
66 struct {
67 int ascent;
68 int descent;
69 int height;
70 XFontSet set;
71 XFontStruct *xfont;
72 } font;
73 } DC; /* draw context */
74
75 typedef struct {
76 unsigned long mod;
77 KeySym keysym;
78 void (*func)(const char *arg);
79 const char *arg;
80 } Key;
81
82 typedef struct {
83 const char *symbol;
84 void (*arrange)(void);
85 } Layout;
86
87 typedef struct {
88 const char *prop;
89 const char *tags;
90 Bool isfloating;
91 } Rule;
92
93 typedef struct {
94 regex_t *propregex;
95 regex_t *tagregex;
96 } Regs;
97
98 /* forward declarations */
99 void applyrules(Client *c);
100 void arrange(void);
101 void attach(Client *c);
102 void attachstack(Client *c);
103 void ban(Client *c);
104 void buttonpress(XEvent *e);
105 void checkotherwm(void);
106 void cleanup(void);
107 void compileregs(void);
108 void configure(Client *c);
109 void configurenotify(XEvent *e);
110 void configurerequest(XEvent *e);
111 void destroynotify(XEvent *e);
112 void detach(Client *c);
113 void detachstack(Client *c);
114 void drawbar(void);
115 void drawsquare(Bool filled, Bool empty, unsigned long col[ColLast]);
116 void drawtext(const char *text, unsigned long col[ColLast]);
117 void *emallocz(unsigned int size);
118 void enternotify(XEvent *e);
119 void eprint(const char *errstr, ...);
120 void expose(XEvent *e);
121 void floating(void); /* default floating layout */
122 void focus(Client *c);
123 void focusnext(const char *arg);
124 void focusprev(const char *arg);
125 Client *getclient(Window w);
126 unsigned long getcolor(const char *colstr);
127 long getstate(Window w);
128 Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
129 void grabbuttons(Client *c, Bool focused);
130 unsigned int idxoftag(const char *tag);
131 void initfont(const char *fontstr);
132 Bool isarrange(void (*func)());
133 Bool isoccupied(unsigned int t);
134 Bool isprotodel(Client *c);
135 Bool isvisible(Client *c);
136 void keypress(XEvent *e);
137 void killclient(const char *arg);
138 void leavenotify(XEvent *e);
139 void manage(Window w, XWindowAttributes *wa);
140 void mappingnotify(XEvent *e);
141 void maprequest(XEvent *e);
142 void movemouse(Client *c);
143 Client *nexttiled(Client *c);
144 void propertynotify(XEvent *e);
145 void quit(const char *arg);
146 void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
147 void resizemouse(Client *c);
148 void restack(void);
149 void run(void);
150 void scan(void);
151 void setclientstate(Client *c, long state);
152 void setlayout(const char *arg);
153 void setmwfact(const char *arg);
154 void setup(void);
155 void spawn(const char *arg);
156 void tag(const char *arg);
157 unsigned int textnw(const char *text, unsigned int len);
158 unsigned int textw(const char *text);
159 void tile(void);
160 void togglebar(const char *arg);
161 void togglefloating(const char *arg);
162 void togglemax(const char *arg);
163 void toggletag(const char *arg);
164 void toggleview(const char *arg);
165 void unban(Client *c);
166 void unmanage(Client *c);
167 void unmapnotify(XEvent *e);
168 void updatebarpos(void);
169 void updatesizehints(Client *c);
170 void updatetitle(Client *c);
171 void view(const char *arg);
172 void viewprevtag(const char *arg); /* views previous selected tags */
173 int xerror(Display *dpy, XErrorEvent *ee);
174 int xerrordummy(Display *dsply, XErrorEvent *ee);
175 int xerrorstart(Display *dsply, XErrorEvent *ee);
176 void zoom(const char *arg);
177
178 /* variables */
179 char stext[256];
180 double mwfact;
181 int screen, sx, sy, sw, sh, wax, way, waw, wah;
182 int (*xerrorxlib)(Display *, XErrorEvent *);
183 unsigned int bh, bpos;
184 unsigned int blw = 0;
185 unsigned int ltidx = 0; /* default */
186 unsigned int nlayouts = 0;
187 unsigned int nrules = 0;
188 unsigned int numlockmask = 0;
189 void (*handler[LASTEvent]) (XEvent *) = {
190 [ButtonPress] = buttonpress,
191 [ConfigureRequest] = configurerequest,
192 [ConfigureNotify] = configurenotify,
193 [DestroyNotify] = destroynotify,
194 [EnterNotify] = enternotify,
195 [LeaveNotify] = leavenotify,
196 [Expose] = expose,
197 [KeyPress] = keypress,
198 [MappingNotify] = mappingnotify,
199 [MapRequest] = maprequest,
200 [PropertyNotify] = propertynotify,
201 [UnmapNotify] = unmapnotify
202 };
203 Atom wmatom[WMLast], netatom[NetLast];
204 Bool otherwm, readin;
205 Bool running = True;
206 Bool selscreen = True;
207 Client *clients = NULL;
208 Client *sel = NULL;
209 Client *stack = NULL;
210 Cursor cursor[CurLast];
211 Display *dpy;
212 DC dc = {0};
213 Window barwin, root;
214 Regs *regs = NULL;
215
216 /* configuration, allows nested code to access above variables */
217 #include "config.h"
218
219 /* Statically define the number of tags. */
220 unsigned int ntags = sizeof tags / sizeof tags[0];
221 Bool seltags[sizeof tags / sizeof tags[0]] = {[0] = True};
222 Bool prevtags[sizeof tags / sizeof tags[0]] = {[0] = True};
223
224 /* functions*/
225 void
226 applyrules(Client *c) {
227 static char buf[512];
228 unsigned int i, j;
229 regmatch_t tmp;
230 Bool matched = False;
231 XClassHint ch = { 0 };
232
233 /* rule matching */
234 XGetClassHint(dpy, c->win, &ch);
235 snprintf(buf, sizeof buf, "%s:%s:%s",
236 ch.res_class ? ch.res_class : "",
237 ch.res_name ? ch.res_name : "", c->name);
238 for(i = 0; i < nrules; i++)
239 if(regs[i].propregex && !regexec(regs[i].propregex, buf, 1, &tmp, 0)) {
240 c->isfloating = rules[i].isfloating;
241 for(j = 0; regs[i].tagregex && j < ntags; j++) {
242 if(!regexec(regs[i].tagregex, tags[j], 1, &tmp, 0)) {
243 matched = True;
244 c->tags[j] = True;
245 }
246 }
247 }
248 if(ch.res_class)
249 XFree(ch.res_class);
250 if(ch.res_name)
251 XFree(ch.res_name);
252 if(!matched)
253 memcpy(c->tags, seltags, sizeof seltags);
254 }
255
256 void
257 arrange(void) {
258 Client *c;
259
260 for(c = clients; c; c = c->next)
261 if(isvisible(c))
262 unban(c);
263 else
264 ban(c);
265 layouts[ltidx].arrange();
266 focus(NULL);
267 restack();
268 }
269
270 void
271 attach(Client *c) {
272 if(clients)
273 clients->prev = c;
274 c->next = clients;
275 clients = c;
276 }
277
278 void
279 attachstack(Client *c) {
280 c->snext = stack;
281 stack = c;
282 }
283
284 void
285 ban(Client *c) {
286 if(c->isbanned)
287 return;
288 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
289 c->isbanned = True;
290 }
291
292 void
293 buttonpress(XEvent *e) {
294 unsigned int i, x;
295 Client *c;
296 XButtonPressedEvent *ev = &e->xbutton;
297
298 if(barwin == ev->window) {
299 x = 0;
300 for(i = 0; i < ntags; i++) {
301 x += textw(tags[i]);
302 if(ev->x < x) {
303 if(ev->button == Button1) {
304 if(ev->state & MODKEY)
305 tag(tags[i]);
306 else
307 view(tags[i]);
308 }
309 else if(ev->button == Button3) {
310 if(ev->state & MODKEY)
311 toggletag(tags[i]);
312 else
313 toggleview(tags[i]);
314 }
315 return;
316 }
317 }
318 if((ev->x < x + blw) && ev->button == Button1)
319 setlayout(NULL);
320 }
321 else if((c = getclient(ev->window))) {
322 focus(c);
323 if(CLEANMASK(ev->state) != MODKEY)
324 return;
325 if(ev->button == Button1) {
326 if(isarrange(floating) || c->isfloating)
327 restack();
328 else
329 togglefloating(NULL);
330 movemouse(c);
331 }
332 else if(ev->button == Button2) {
333 if(ISTILE && !c->isfixed && c->isfloating)
334 togglefloating(NULL);
335 else
336 zoom(NULL);
337 }
338 else if(ev->button == Button3 && !c->isfixed) {
339 if(isarrange(floating) || c->isfloating)
340 restack();
341 else
342 togglefloating(NULL);
343 resizemouse(c);
344 }
345 }
346 }
347
348 void
349 checkotherwm(void) {
350 otherwm = False;
351 XSetErrorHandler(xerrorstart);
352
353 /* this causes an error if some other window manager is running */
354 XSelectInput(dpy, root, SubstructureRedirectMask);
355 XSync(dpy, False);
356 if(otherwm)
357 eprint("dwm: another window manager is already running\n");
358 XSync(dpy, False);
359 XSetErrorHandler(NULL);
360 xerrorxlib = XSetErrorHandler(xerror);
361 XSync(dpy, False);
362 }
363
364 void
365 cleanup(void) {
366 close(STDIN_FILENO);
367 while(stack) {
368 unban(stack);
369 unmanage(stack);
370 }
371 if(dc.font.set)
372 XFreeFontSet(dpy, dc.font.set);
373 else
374 XFreeFont(dpy, dc.font.xfont);
375 XUngrabKey(dpy, AnyKey, AnyModifier, root);
376 XFreePixmap(dpy, dc.drawable);
377 XFreeGC(dpy, dc.gc);
378 XDestroyWindow(dpy, barwin);
379 XFreeCursor(dpy, cursor[CurNormal]);
380 XFreeCursor(dpy, cursor[CurResize]);
381 XFreeCursor(dpy, cursor[CurMove]);
382 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
383 XSync(dpy, False);
384 }
385
386 void
387 compileregs(void) {
388 unsigned int i;
389 regex_t *reg;
390
391 if(regs)
392 return;
393 nrules = sizeof rules / sizeof rules[0];
394 regs = emallocz(nrules * sizeof(Regs));
395 for(i = 0; i < nrules; i++) {
396 if(rules[i].prop) {
397 reg = emallocz(sizeof(regex_t));
398 if(regcomp(reg, rules[i].prop, REG_EXTENDED))
399 free(reg);
400 else
401 regs[i].propregex = reg;
402 }
403 if(rules[i].tags) {
404 reg = emallocz(sizeof(regex_t));
405 if(regcomp(reg, rules[i].tags, REG_EXTENDED))
406 free(reg);
407 else
408 regs[i].tagregex = reg;
409 }
410 }
411 }
412
413 void
414 configure(Client *c) {
415 XConfigureEvent ce;
416
417 ce.type = ConfigureNotify;
418 ce.display = dpy;
419 ce.event = c->win;
420 ce.window = c->win;
421 ce.x = c->x;
422 ce.y = c->y;
423 ce.width = c->w;
424 ce.height = c->h;
425 ce.border_width = c->border;
426 ce.above = None;
427 ce.override_redirect = False;
428 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
429 }
430
431 void
432 configurenotify(XEvent *e) {
433 XConfigureEvent *ev = &e->xconfigure;
434
435 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
436 sw = ev->width;
437 sh = ev->height;
438 XFreePixmap(dpy, dc.drawable);
439 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
440 XResizeWindow(dpy, barwin, sw, bh);
441 updatebarpos();
442 arrange();
443 }
444 }
445
446 void
447 configurerequest(XEvent *e) {
448 Client *c;
449 XConfigureRequestEvent *ev = &e->xconfigurerequest;
450 XWindowChanges wc;
451
452 if((c = getclient(ev->window))) {
453 c->ismax = False;
454 if(ev->value_mask & CWBorderWidth)
455 c->border = ev->border_width;
456 if(c->isfixed || c->isfloating || isarrange(floating)) {
457 if(ev->value_mask & CWX)
458 c->x = ev->x;
459 if(ev->value_mask & CWY)
460 c->y = ev->y;
461 if(ev->value_mask & CWWidth)
462 c->w = ev->width;
463 if(ev->value_mask & CWHeight)
464 c->h = ev->height;
465 if((c->x + c->w) > sw && c->isfloating)
466 c->x = sw / 2 - c->w / 2; /* center in x direction */
467 if((c->y + c->h) > sh && c->isfloating)
468 c->y = sh / 2 - c->h / 2; /* center in y direction */
469 if((ev->value_mask & (CWX | CWY))
470 && !(ev->value_mask & (CWWidth | CWHeight)))
471 configure(c);
472 if(isvisible(c))
473 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
474 }
475 else
476 configure(c);
477 }
478 else {
479 wc.x = ev->x;
480 wc.y = ev->y;
481 wc.width = ev->width;
482 wc.height = ev->height;
483 wc.border_width = ev->border_width;
484 wc.sibling = ev->above;
485 wc.stack_mode = ev->detail;
486 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
487 }
488 XSync(dpy, False);
489 }
490
491 void
492 destroynotify(XEvent *e) {
493 Client *c;
494 XDestroyWindowEvent *ev = &e->xdestroywindow;
495
496 if((c = getclient(ev->window)))
497 unmanage(c);
498 }
499
500 void
501 detach(Client *c) {
502 if(c->prev)
503 c->prev->next = c->next;
504 if(c->next)
505 c->next->prev = c->prev;
506 if(c == clients)
507 clients = c->next;
508 c->next = c->prev = NULL;
509 }
510
511 void
512 detachstack(Client *c) {
513 Client **tc;
514
515 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
516 *tc = c->snext;
517 }
518
519 void
520 drawbar(void) {
521 int i, x;
522
523 dc.x = dc.y = 0;
524 for(i = 0; i < ntags; i++) {
525 dc.w = textw(tags[i]);
526 if(seltags[i]) {
527 drawtext(tags[i], dc.sel);
528 drawsquare(sel && sel->tags[i], isoccupied(i), dc.sel);
529 }
530 else {
531 drawtext(tags[i], dc.norm);
532 drawsquare(sel && sel->tags[i], isoccupied(i), dc.norm);
533 }
534 dc.x += dc.w;
535 }
536 dc.w = blw;
537 drawtext(layouts[ltidx].symbol, dc.norm);
538 x = dc.x + dc.w;
539 dc.w = textw(stext);
540 dc.x = sw - dc.w;
541 if(dc.x < x) {
542 dc.x = x;
543 dc.w = sw - x;
544 }
545 drawtext(stext, dc.norm);
546 if((dc.w = dc.x - x) > bh) {
547 dc.x = x;
548 if(sel) {
549 drawtext(sel->name, dc.sel);
550 drawsquare(sel->ismax, sel->isfloating, dc.sel);
551 }
552 else
553 drawtext(NULL, dc.norm);
554 }
555 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, sw, bh, 0, 0);
556 XSync(dpy, False);
557 }
558
559 void
560 drawsquare(Bool filled, Bool empty, unsigned long col[ColLast]) {
561 int x;
562 XGCValues gcv;
563 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
564
565 gcv.foreground = col[ColFG];
566 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
567 x = (dc.font.ascent + dc.font.descent + 2) / 4;
568 r.x = dc.x + 1;
569 r.y = dc.y + 1;
570 if(filled) {
571 r.width = r.height = x + 1;
572 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
573 }
574 else if(empty) {
575 r.width = r.height = x;
576 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
577 }
578 }
579
580 void
581 drawtext(const char *text, unsigned long col[ColLast]) {
582 int x, y, w, h;
583 static char buf[256];
584 unsigned int len, olen;
585 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
586
587 XSetForeground(dpy, dc.gc, col[ColBG]);
588 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
589 if(!text)
590 return;
591 w = 0;
592 olen = len = strlen(text);
593 if(len >= sizeof buf)
594 len = sizeof buf - 1;
595 memcpy(buf, text, len);
596 buf[len] = 0;
597 h = dc.font.ascent + dc.font.descent;
598 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
599 x = dc.x + (h / 2);
600 /* shorten text if necessary */
601 while(len && (w = textnw(buf, len)) > dc.w - h)
602 buf[--len] = 0;
603 if(len < olen) {
604 if(len > 1)
605 buf[len - 1] = '.';
606 if(len > 2)
607 buf[len - 2] = '.';
608 if(len > 3)
609 buf[len - 3] = '.';
610 }
611 if(w > dc.w)
612 return; /* too long */
613 XSetForeground(dpy, dc.gc, col[ColFG]);
614 if(dc.font.set)
615 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
616 else
617 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
618 }
619
620 void *
621 emallocz(unsigned int size) {
622 void *res = calloc(1, size);
623
624 if(!res)
625 eprint("fatal: could not malloc() %u bytes\n", size);
626 return res;
627 }
628
629 void
630 enternotify(XEvent *e) {
631 Client *c;
632 XCrossingEvent *ev = &e->xcrossing;
633
634 if(ev->mode != NotifyNormal || ev->detail == NotifyInferior)
635 return;
636 if((c = getclient(ev->window)))
637 focus(c);
638 else if(ev->window == root) {
639 selscreen = True;
640 focus(NULL);
641 }
642 }
643
644 void
645 eprint(const char *errstr, ...) {
646 va_list ap;
647
648 va_start(ap, errstr);
649 vfprintf(stderr, errstr, ap);
650 va_end(ap);
651 exit(EXIT_FAILURE);
652 }
653
654 void
655 expose(XEvent *e) {
656 XExposeEvent *ev = &e->xexpose;
657
658 if(ev->count == 0) {
659 if(barwin == ev->window)
660 drawbar();
661 }
662 }
663
664 void
665 floating(void) { /* default floating layout */
666 Client *c;
667
668 for(c = clients; c; c = c->next)
669 if(isvisible(c))
670 resize(c, c->x, c->y, c->w, c->h, True);
671 }
672
673 void
674 focus(Client *c) {
675 if((!c && selscreen) || (c && !isvisible(c)))
676 for(c = stack; c && !isvisible(c); c = c->snext);
677 if(sel && sel != c) {
678 grabbuttons(sel, False);
679 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
680 }
681 if(c) {
682 detachstack(c);
683 attachstack(c);
684 grabbuttons(c, True);
685 }
686 sel = c;
687 drawbar();
688 if(!selscreen)
689 return;
690 if(c) {
691 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
692 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
693 }
694 else
695 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
696 }
697
698 void
699 focusnext(const char *arg) {
700 Client *c;
701
702 if(!sel)
703 return;
704 for(c = sel->next; c && !isvisible(c); c = c->next);
705 if(!c)
706 for(c = clients; c && !isvisible(c); c = c->next);
707 if(c) {
708 focus(c);
709 restack();
710 }
711 }
712
713 void
714 focusprev(const char *arg) {
715 Client *c;
716
717 if(!sel)
718 return;
719 for(c = sel->prev; c && !isvisible(c); c = c->prev);
720 if(!c) {
721 for(c = clients; c && c->next; c = c->next);
722 for(; c && !isvisible(c); c = c->prev);
723 }
724 if(c) {
725 focus(c);
726 restack();
727 }
728 }
729
730 Client *
731 getclient(Window w) {
732 Client *c;
733
734 for(c = clients; c && c->win != w; c = c->next);
735 return c;
736 }
737
738 unsigned long
739 getcolor(const char *colstr) {
740 Colormap cmap = DefaultColormap(dpy, screen);
741 XColor color;
742
743 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
744 eprint("error, cannot allocate color '%s'\n", colstr);
745 return color.pixel;
746 }
747
748 long
749 getstate(Window w) {
750 int format, status;
751 long result = -1;
752 unsigned char *p = NULL;
753 unsigned long n, extra;
754 Atom real;
755
756 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
757 &real, &format, &n, &extra, (unsigned char **)&p);
758 if(status != Success)
759 return -1;
760 if(n != 0)
761 result = *p;
762 XFree(p);
763 return result;
764 }
765
766 Bool
767 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
768 char **list = NULL;
769 int n;
770 XTextProperty name;
771
772 if(!text || size == 0)
773 return False;
774 text[0] = '\0';
775 XGetTextProperty(dpy, w, &name, atom);
776 if(!name.nitems)
777 return False;
778 if(name.encoding == XA_STRING)
779 strncpy(text, (char *)name.value, size - 1);
780 else {
781 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
782 && n > 0 && *list)
783 {
784 strncpy(text, *list, size - 1);
785 XFreeStringList(list);
786 }
787 }
788 text[size - 1] = '\0';
789 XFree(name.value);
790 return True;
791 }
792
793 void
794 grabbuttons(Client *c, Bool focused) {
795 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
796
797 if(focused) {
798 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
799 GrabModeAsync, GrabModeSync, None, None);
800 XGrabButton(dpy, Button1, MODKEY | LockMask, c->win, False, BUTTONMASK,
801 GrabModeAsync, GrabModeSync, None, None);
802 XGrabButton(dpy, Button1, MODKEY | numlockmask, c->win, False, BUTTONMASK,
803 GrabModeAsync, GrabModeSync, None, None);
804 XGrabButton(dpy, Button1, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
805 GrabModeAsync, GrabModeSync, None, None);
806
807 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
808 GrabModeAsync, GrabModeSync, None, None);
809 XGrabButton(dpy, Button2, MODKEY | LockMask, c->win, False, BUTTONMASK,
810 GrabModeAsync, GrabModeSync, None, None);
811 XGrabButton(dpy, Button2, MODKEY | numlockmask, c->win, False, BUTTONMASK,
812 GrabModeAsync, GrabModeSync, None, None);
813 XGrabButton(dpy, Button2, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
814 GrabModeAsync, GrabModeSync, None, None);
815
816 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
817 GrabModeAsync, GrabModeSync, None, None);
818 XGrabButton(dpy, Button3, MODKEY | LockMask, c->win, False, BUTTONMASK,
819 GrabModeAsync, GrabModeSync, None, None);
820 XGrabButton(dpy, Button3, MODKEY | numlockmask, c->win, False, BUTTONMASK,
821 GrabModeAsync, GrabModeSync, None, None);
822 XGrabButton(dpy, Button3, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
823 GrabModeAsync, GrabModeSync, None, None);
824 }
825 else
826 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
827 GrabModeAsync, GrabModeSync, None, None);
828 }
829
830 unsigned int
831 idxoftag(const char *tag) {
832 unsigned int i;
833
834 for(i = 0; i < ntags; i++)
835 if(tags[i] == tag)
836 return i;
837 return 0;
838 }
839
840 void
841 initfont(const char *fontstr) {
842 char *def, **missing;
843 int i, n;
844
845 missing = NULL;
846 if(dc.font.set)
847 XFreeFontSet(dpy, dc.font.set);
848 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
849 if(missing) {
850 while(n--)
851 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
852 XFreeStringList(missing);
853 }
854 if(dc.font.set) {
855 XFontSetExtents *font_extents;
856 XFontStruct **xfonts;
857 char **font_names;
858 dc.font.ascent = dc.font.descent = 0;
859 font_extents = XExtentsOfFontSet(dc.font.set);
860 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
861 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
862 if(dc.font.ascent < (*xfonts)->ascent)
863 dc.font.ascent = (*xfonts)->ascent;
864 if(dc.font.descent < (*xfonts)->descent)
865 dc.font.descent = (*xfonts)->descent;
866 xfonts++;
867 }
868 }
869 else {
870 if(dc.font.xfont)
871 XFreeFont(dpy, dc.font.xfont);
872 dc.font.xfont = NULL;
873 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
874 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
875 eprint("error, cannot load font: '%s'\n", fontstr);
876 dc.font.ascent = dc.font.xfont->ascent;
877 dc.font.descent = dc.font.xfont->descent;
878 }
879 dc.font.height = dc.font.ascent + dc.font.descent;
880 }
881
882 Bool
883 isarrange(void (*func)())
884 {
885 return func == layouts[ltidx].arrange;
886 }
887
888 Bool
889 isoccupied(unsigned int t) {
890 Client *c;
891
892 for(c = clients; c; c = c->next)
893 if(c->tags[t])
894 return True;
895 return False;
896 }
897
898 Bool
899 isprotodel(Client *c) {
900 int i, n;
901 Atom *protocols;
902 Bool ret = False;
903
904 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
905 for(i = 0; !ret && i < n; i++)
906 if(protocols[i] == wmatom[WMDelete])
907 ret = True;
908 XFree(protocols);
909 }
910 return ret;
911 }
912
913 Bool
914 isvisible(Client *c) {
915 unsigned int i;
916
917 for(i = 0; i < ntags; i++)
918 if(c->tags[i] && seltags[i])
919 return True;
920 return False;
921 }
922
923 void
924 keypress(XEvent *e) {
925 KEYS
926 unsigned int len = sizeof keys / sizeof keys[0];
927 unsigned int i;
928 KeyCode code;
929 KeySym keysym;
930 XKeyEvent *ev;
931
932 if(!e) { /* grabkeys */
933 XUngrabKey(dpy, AnyKey, AnyModifier, root);
934 for(i = 0; i < len; i++) {
935 code = XKeysymToKeycode(dpy, keys[i].keysym);
936 XGrabKey(dpy, code, keys[i].mod, root, True,
937 GrabModeAsync, GrabModeAsync);
938 XGrabKey(dpy, code, keys[i].mod | LockMask, root, True,
939 GrabModeAsync, GrabModeAsync);
940 XGrabKey(dpy, code, keys[i].mod | numlockmask, root, True,
941 GrabModeAsync, GrabModeAsync);
942 XGrabKey(dpy, code, keys[i].mod | numlockmask | LockMask, root, True,
943 GrabModeAsync, GrabModeAsync);
944 }
945 return;
946 }
947 ev = &e->xkey;
948 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
949 for(i = 0; i < len; i++)
950 if(keysym == keys[i].keysym
951 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
952 {
953 if(keys[i].func)
954 keys[i].func(keys[i].arg);
955 }
956 }
957
958 void
959 killclient(const char *arg) {
960 XEvent ev;
961
962 if(!sel)
963 return;
964 if(isprotodel(sel)) {
965 ev.type = ClientMessage;
966 ev.xclient.window = sel->win;
967 ev.xclient.message_type = wmatom[WMProtocols];
968 ev.xclient.format = 32;
969 ev.xclient.data.l[0] = wmatom[WMDelete];
970 ev.xclient.data.l[1] = CurrentTime;
971 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
972 }
973 else
974 XKillClient(dpy, sel->win);
975 }
976
977 void
978 leavenotify(XEvent *e) {
979 XCrossingEvent *ev = &e->xcrossing;
980
981 if((ev->window == root) && !ev->same_screen) {
982 selscreen = False;
983 focus(NULL);
984 }
985 }
986
987 void
988 manage(Window w, XWindowAttributes *wa) {
989 Client *c, *t = NULL;
990 Window trans;
991 Status rettrans;
992 XWindowChanges wc;
993
994 c = emallocz(sizeof(Client));
995 c->tags = emallocz(sizeof seltags);
996 c->win = w;
997 c->x = wa->x;
998 c->y = wa->y;
999 c->w = wa->width;
1000 c->h = wa->height;
1001 c->oldborder = wa->border_width;
1002 if(c->w == sw && c->h == sh) {
1003 c->x = sx;
1004 c->y = sy;
1005 c->border = wa->border_width;
1006 }
1007 else {
1008 if(c->x + c->w + 2 * c->border > wax + waw)
1009 c->x = wax + waw - c->w - 2 * c->border;
1010 if(c->y + c->h + 2 * c->border > way + wah)
1011 c->y = way + wah - c->h - 2 * c->border;
1012 if(c->x < wax)
1013 c->x = wax;
1014 if(c->y < way)
1015 c->y = way;
1016 c->border = BORDERPX;
1017 }
1018 wc.border_width = c->border;
1019 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1020 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1021 configure(c); /* propagates border_width, if size doesn't change */
1022 updatesizehints(c);
1023 XSelectInput(dpy, w,
1024 StructureNotifyMask | PropertyChangeMask | EnterWindowMask);
1025 grabbuttons(c, False);
1026 updatetitle(c);
1027 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
1028 for(t = clients; t && t->win != trans; t = t->next);
1029 if(t)
1030 memcpy(c->tags, t->tags, sizeof seltags);
1031 applyrules(c);
1032 if(!c->isfloating)
1033 c->isfloating = (rettrans == Success) || c->isfixed;
1034 attach(c);
1035 attachstack(c);
1036 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
1037 ban(c);
1038 XMapWindow(dpy, c->win);
1039 setclientstate(c, NormalState);
1040 arrange();
1041 }
1042
1043 void
1044 mappingnotify(XEvent *e) {
1045 XMappingEvent *ev = &e->xmapping;
1046
1047 XRefreshKeyboardMapping(ev);
1048 if(ev->request == MappingKeyboard)
1049 keypress(NULL);
1050 }
1051
1052 void
1053 maprequest(XEvent *e) {
1054 static XWindowAttributes wa;
1055 XMapRequestEvent *ev = &e->xmaprequest;
1056
1057 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1058 return;
1059 if(wa.override_redirect)
1060 return;
1061 if(!getclient(ev->window))
1062 manage(ev->window, &wa);
1063 }
1064
1065 void
1066 movemouse(Client *c) {
1067 int x1, y1, ocx, ocy, di, nx, ny;
1068 unsigned int dui;
1069 Window dummy;
1070 XEvent ev;
1071
1072 ocx = nx = c->x;
1073 ocy = ny = c->y;
1074 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1075 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1076 return;
1077 c->ismax = False;
1078 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1079 for(;;) {
1080 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask, &ev);
1081 switch (ev.type) {
1082 case ButtonRelease:
1083 XUngrabPointer(dpy, CurrentTime);
1084 return;
1085 case ConfigureRequest:
1086 case Expose:
1087 case MapRequest:
1088 handler[ev.type](&ev);
1089 break;
1090 case MotionNotify:
1091 XSync(dpy, False);
1092 nx = ocx + (ev.xmotion.x - x1);
1093 ny = ocy + (ev.xmotion.y - y1);
1094 if(abs(wax + nx) < SNAP)
1095 nx = wax;
1096 else if(abs((wax + waw) - (nx + c->w + 2 * c->border)) < SNAP)
1097 nx = wax + waw - c->w - 2 * c->border;
1098 if(abs(way - ny) < SNAP)
1099 ny = way;
1100 else if(abs((way + wah) - (ny + c->h + 2 * c->border)) < SNAP)
1101 ny = way + wah - c->h - 2 * c->border;
1102 resize(c, nx, ny, c->w, c->h, False);
1103 break;
1104 }
1105 }
1106 }
1107
1108 Client *
1109 nexttiled(Client *c) {
1110 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1111 return c;
1112 }
1113
1114 void
1115 propertynotify(XEvent *e) {
1116 Client *c;
1117 Window trans;
1118 XPropertyEvent *ev = &e->xproperty;
1119
1120 if(ev->state == PropertyDelete)
1121 return; /* ignore */
1122 if((c = getclient(ev->window))) {
1123 switch (ev->atom) {
1124 default: break;
1125 case XA_WM_TRANSIENT_FOR:
1126 XGetTransientForHint(dpy, c->win, &trans);
1127 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1128 arrange();
1129 break;
1130 case XA_WM_NORMAL_HINTS:
1131 updatesizehints(c);
1132 break;
1133 }
1134 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1135 updatetitle(c);
1136 if(c == sel)
1137 drawbar();
1138 }
1139 }
1140 }
1141
1142 void
1143 quit(const char *arg) {
1144 readin = running = False;
1145 }
1146
1147 void
1148 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1149 double dx, dy, max, min, ratio;
1150 XWindowChanges wc;
1151
1152 if(sizehints) {
1153 if(c->minay > 0 && c->maxay > 0 && (h - c->baseh) > 0 && (w - c->basew) > 0) {
1154 dx = (double)(w - c->basew);
1155 dy = (double)(h - c->baseh);
1156 min = (double)(c->minax) / (double)(c->minay);
1157 max = (double)(c->maxax) / (double)(c->maxay);
1158 ratio = dx / dy;
1159 if(max > 0 && min > 0 && ratio > 0) {
1160 if(ratio < min) {
1161 dy = (dx * min + dy) / (min * min + 1);
1162 dx = dy * min;
1163 w = (int)dx + c->basew;
1164 h = (int)dy + c->baseh;
1165 }
1166 else if(ratio > max) {
1167 dy = (dx * min + dy) / (max * max + 1);
1168 dx = dy * min;
1169 w = (int)dx + c->basew;
1170 h = (int)dy + c->baseh;
1171 }
1172 }
1173 }
1174 if(c->minw && w < c->minw)
1175 w = c->minw;
1176 if(c->minh && h < c->minh)
1177 h = c->minh;
1178 if(c->maxw && w > c->maxw)
1179 w = c->maxw;
1180 if(c->maxh && h > c->maxh)
1181 h = c->maxh;
1182 if(c->incw)
1183 w -= (w - c->basew) % c->incw;
1184 if(c->inch)
1185 h -= (h - c->baseh) % c->inch;
1186 }
1187 if(w <= 0 || h <= 0)
1188 return;
1189 /* offscreen appearance fixes */
1190 if(x > sw)
1191 x = sw - w - 2 * c->border;
1192 if(y > sh)
1193 y = sh - h - 2 * c->border;
1194 if(x + w + 2 * c->border < sx)
1195 x = sx;
1196 if(y + h + 2 * c->border < sy)
1197 y = sy;
1198 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1199 c->x = wc.x = x;
1200 c->y = wc.y = y;
1201 c->w = wc.width = w;
1202 c->h = wc.height = h;
1203 wc.border_width = c->border;
1204 XConfigureWindow(dpy, c->win, CWX | CWY | CWWidth | CWHeight | CWBorderWidth, &wc);
1205 configure(c);
1206 XSync(dpy, False);
1207 }
1208 }
1209
1210 void
1211 resizemouse(Client *c) {
1212 int ocx, ocy;
1213 int nw, nh;
1214 XEvent ev;
1215
1216 ocx = c->x;
1217 ocy = c->y;
1218 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1219 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1220 return;
1221 c->ismax = False;
1222 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
1223 for(;;) {
1224 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask , &ev);
1225 switch(ev.type) {
1226 case ButtonRelease:
1227 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1228 c->w + c->border - 1, c->h + c->border - 1);
1229 XUngrabPointer(dpy, CurrentTime);
1230 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1231 return;
1232 case ConfigureRequest:
1233 case Expose:
1234 case MapRequest:
1235 handler[ev.type](&ev);
1236 break;
1237 case MotionNotify:
1238 XSync(dpy, False);
1239 if((nw = ev.xmotion.x - ocx - 2 * c->border + 1) <= 0)
1240 nw = 1;
1241 if((nh = ev.xmotion.y - ocy - 2 * c->border + 1) <= 0)
1242 nh = 1;
1243 resize(c, c->x, c->y, nw, nh, True);
1244 break;
1245 }
1246 }
1247 }
1248
1249 void
1250 restack(void) {
1251 Client *c;
1252 XEvent ev;
1253 XWindowChanges wc;
1254
1255 drawbar();
1256 if(!sel)
1257 return;
1258 if(sel->isfloating || isarrange(floating))
1259 XRaiseWindow(dpy, sel->win);
1260 if(!isarrange(floating)) {
1261 wc.stack_mode = Below;
1262 wc.sibling = barwin;
1263 if(!sel->isfloating) {
1264 XConfigureWindow(dpy, sel->win, CWSibling | CWStackMode, &wc);
1265 wc.sibling = sel->win;
1266 }
1267 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
1268 if(c == sel)
1269 continue;
1270 XConfigureWindow(dpy, c->win, CWSibling | CWStackMode, &wc);
1271 wc.sibling = c->win;
1272 }
1273 }
1274 XSync(dpy, False);
1275 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1276 }
1277
1278 void
1279 run(void) {
1280 char *p;
1281 int r, xfd;
1282 fd_set rd;
1283 XEvent ev;
1284
1285 /* main event loop, also reads status text from stdin */
1286 XSync(dpy, False);
1287 xfd = ConnectionNumber(dpy);
1288 readin = True;
1289 while(running) {
1290 FD_ZERO(&rd);
1291 if(readin)
1292 FD_SET(STDIN_FILENO, &rd);
1293 FD_SET(xfd, &rd);
1294 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1295 if(errno == EINTR)
1296 continue;
1297 eprint("select failed\n");
1298 }
1299 if(FD_ISSET(STDIN_FILENO, &rd)) {
1300 switch(r = read(STDIN_FILENO, stext, sizeof stext - 1)) {
1301 case -1:
1302 strncpy(stext, strerror(errno), sizeof stext - 1);
1303 stext[sizeof stext - 1] = '\0';
1304 readin = False;
1305 break;
1306 case 0:
1307 strncpy(stext, "EOF", 4);
1308 readin = False;
1309 break;
1310 default:
1311 for(stext[r] = '\0', p = stext + strlen(stext) - 1; p >= stext && *p == '\n'; *p-- = '\0');
1312 for(; p >= stext && *p != '\n'; --p);
1313 if(p > stext)
1314 strncpy(stext, p + 1, sizeof stext);
1315 }
1316 drawbar();
1317 }
1318 while(XPending(dpy)) {
1319 XNextEvent(dpy, &ev);
1320 if(handler[ev.type])
1321 (handler[ev.type])(&ev); /* call handler */
1322 }
1323 }
1324 }
1325
1326 void
1327 scan(void) {
1328 unsigned int i, num;
1329 Window *wins, d1, d2;
1330 XWindowAttributes wa;
1331
1332 wins = NULL;
1333 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1334 for(i = 0; i < num; i++) {
1335 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1336 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1337 continue;
1338 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1339 manage(wins[i], &wa);
1340 }
1341 for(i = 0; i < num; i++) { /* now the transients */
1342 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1343 continue;
1344 if(XGetTransientForHint(dpy, wins[i], &d1)
1345 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1346 manage(wins[i], &wa);
1347 }
1348 }
1349 if(wins)
1350 XFree(wins);
1351 }
1352
1353 void
1354 setclientstate(Client *c, long state) {
1355 long data[] = {state, None};
1356
1357 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1358 PropModeReplace, (unsigned char *)data, 2);
1359 }
1360
1361 void
1362 setlayout(const char *arg) {
1363 unsigned int i;
1364
1365 if(!arg) {
1366 if(++ltidx == nlayouts)
1367 ltidx = 0;;
1368 }
1369 else {
1370 for(i = 0; i < nlayouts; i++)
1371 if(!strcmp(arg, layouts[i].symbol))
1372 break;
1373 if(i == nlayouts)
1374 return;
1375 ltidx = i;
1376 }
1377 if(sel)
1378 arrange();
1379 else
1380 drawbar();
1381 }
1382
1383 void
1384 setmwfact(const char *arg) {
1385 double delta;
1386
1387 if(!ISTILE)
1388 return;
1389 /* arg handling, manipulate mwfact */
1390 if(arg == NULL)
1391 mwfact = MWFACT;
1392 else if(1 == sscanf(arg, "%lf", &delta)) {
1393 if(arg[0] == '+' || arg[0] == '-')
1394 mwfact += delta;
1395 else
1396 mwfact = delta;
1397 if(mwfact < 0.1)
1398 mwfact = 0.1;
1399 else if(mwfact > 0.9)
1400 mwfact = 0.9;
1401 }
1402 arrange();
1403 }
1404
1405 void
1406 setup(void) {
1407 int d;
1408 unsigned int i, j, mask;
1409 Window w;
1410 XModifierKeymap *modmap;
1411 XSetWindowAttributes wa;
1412
1413 /* init atoms */
1414 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1415 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1416 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1417 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1418 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1419 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1420 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1421 PropModeReplace, (unsigned char *) netatom, NetLast);
1422
1423 /* init cursors */
1424 cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1425 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1426 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1427
1428 /* init geometry */
1429 sx = sy = 0;
1430 sw = DisplayWidth(dpy, screen);
1431 sh = DisplayHeight(dpy, screen);
1432
1433 /* init modifier map */
1434 modmap = XGetModifierMapping(dpy);
1435 for(i = 0; i < 8; i++)
1436 for(j = 0; j < modmap->max_keypermod; j++) {
1437 if(modmap->modifiermap[i * modmap->max_keypermod + j]
1438 == XKeysymToKeycode(dpy, XK_Num_Lock))
1439 numlockmask = (1 << i);
1440 }
1441 XFreeModifiermap(modmap);
1442
1443 /* select for events */
1444 wa.event_mask = SubstructureRedirectMask | SubstructureNotifyMask
1445 | EnterWindowMask | LeaveWindowMask | StructureNotifyMask;
1446 wa.cursor = cursor[CurNormal];
1447 XChangeWindowAttributes(dpy, root, CWEventMask | CWCursor, &wa);
1448 XSelectInput(dpy, root, wa.event_mask);
1449
1450 /* grab keys */
1451 keypress(NULL);
1452
1453 /* init tags */
1454 compileregs();
1455
1456 /* init appearance */
1457 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1458 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1459 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1460 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1461 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1462 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1463 initfont(FONT);
1464 dc.h = bh = dc.font.height + 2;
1465
1466 /* init layouts */
1467 mwfact = MWFACT;
1468 nlayouts = sizeof layouts / sizeof layouts[0];
1469 for(blw = i = 0; i < nlayouts; i++) {
1470 j = textw(layouts[i].symbol);
1471 if(j > blw)
1472 blw = j;
1473 }
1474
1475 /* init bar */
1476 bpos = BARPOS;
1477 wa.override_redirect = 1;
1478 wa.background_pixmap = ParentRelative;
1479 wa.event_mask = ButtonPressMask | ExposureMask;
1480 barwin = XCreateWindow(dpy, root, sx, sy, sw, bh, 0,
1481 DefaultDepth(dpy, screen), CopyFromParent, DefaultVisual(dpy, screen),
1482 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
1483 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1484 updatebarpos();
1485 XMapRaised(dpy, barwin);
1486 strcpy(stext, "dwm-"VERSION);
1487 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
1488 dc.gc = XCreateGC(dpy, root, 0, 0);
1489 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1490 if(!dc.font.set)
1491 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1492
1493 /* multihead support */
1494 selscreen = XQueryPointer(dpy, root, &w, &w, &d, &d, &d, &d, &mask);
1495 }
1496
1497 void
1498 spawn(const char *arg) {
1499 static char *shell = NULL;
1500
1501 if(!shell && !(shell = getenv("SHELL")))
1502 shell = "/bin/sh";
1503 if(!arg)
1504 return;
1505 /* The double-fork construct avoids zombie processes and keeps the code
1506 * clean from stupid signal handlers. */
1507 if(fork() == 0) {
1508 if(fork() == 0) {
1509 if(dpy)
1510 close(ConnectionNumber(dpy));
1511 setsid();
1512 execl(shell, shell, "-c", arg, (char *)NULL);
1513 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1514 perror(" failed");
1515 }
1516 exit(0);
1517 }
1518 wait(0);
1519 }
1520
1521 void
1522 tag(const char *arg) {
1523 unsigned int i;
1524
1525 if(!sel)
1526 return;
1527 for(i = 0; i < ntags; i++)
1528 sel->tags[i] = arg == NULL;
1529 i = idxoftag(arg);
1530 if(i >= 0 && i < ntags)
1531 sel->tags[i] = True;
1532 arrange();
1533 }
1534
1535 unsigned int
1536 textnw(const char *text, unsigned int len) {
1537 XRectangle r;
1538
1539 if(dc.font.set) {
1540 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1541 return r.width;
1542 }
1543 return XTextWidth(dc.font.xfont, text, len);
1544 }
1545
1546 unsigned int
1547 textw(const char *text) {
1548 return textnw(text, strlen(text)) + dc.font.height;
1549 }
1550
1551 void
1552 tile(void) {
1553 unsigned int i, n, nx, ny, nw, nh, mw, th;
1554 Client *c, *mc;
1555
1556 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next))
1557 n++;
1558
1559 /* window geoms */
1560 mw = (n == 1) ? waw : mwfact * waw;
1561 th = (n > 1) ? wah / (n - 1) : 0;
1562 if(n > 1 && th < bh)
1563 th = wah;
1564
1565 nx = wax;
1566 ny = way;
1567 nw = 0; /* gcc stupidity requires this */
1568 for(i = 0, c = mc = nexttiled(clients); c; c = nexttiled(c->next), i++) {
1569 c->ismax = False;
1570 if(i == 0) { /* master */
1571 nw = mw - 2 * c->border;
1572 nh = wah - 2 * c->border;
1573 }
1574 else { /* tile window */
1575 if(i == 1) {
1576 ny = way;
1577 nx += mc->w + 2 * mc->border;
1578 nw = waw - nx - 2 * c->border;
1579 }
1580 if(i + 1 == n) /* remainder */
1581 nh = (way + wah) - ny - 2 * c->border;
1582 else
1583 nh = th - 2 * c->border;
1584 }
1585 resize(c, nx, ny, nw, nh, RESIZEHINTS);
1586 if(n > 1 && th != wah)
1587 ny = c->y + c->h + 2 * c->border;
1588 }
1589 }
1590
1591 void
1592 togglebar(const char *arg) {
1593 if(bpos == BarOff)
1594 bpos = (BARPOS == BarOff) ? BarTop : BARPOS;
1595 else
1596 bpos = BarOff;
1597 updatebarpos();
1598 arrange();
1599 }
1600
1601 void
1602 togglefloating(const char *arg) {
1603 if(!sel)
1604 return;
1605 sel->isfloating = !sel->isfloating;
1606 if(sel->isfloating)
1607 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1608 arrange();
1609 }
1610
1611 void
1612 togglemax(const char *arg) {
1613 XEvent ev;
1614
1615 if(!sel || sel->isfixed)
1616 return;
1617 if((sel->ismax = !sel->ismax)) {
1618 if(isarrange(floating) || sel->isfloating)
1619 sel->wasfloating = True;
1620 else {
1621 togglefloating(NULL);
1622 sel->wasfloating = False;
1623 }
1624 sel->rx = sel->x;
1625 sel->ry = sel->y;
1626 sel->rw = sel->w;
1627 sel->rh = sel->h;
1628 resize(sel, wax, way, waw - 2 * sel->border, wah - 2 * sel->border, True);
1629 }
1630 else {
1631 resize(sel, sel->rx, sel->ry, sel->rw, sel->rh, True);
1632 if(!sel->wasfloating)
1633 togglefloating(NULL);
1634 }
1635 drawbar();
1636 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1637 }
1638
1639 void
1640 toggletag(const char *arg) {
1641 unsigned int i, j;
1642
1643 if(!sel)
1644 return;
1645 i = idxoftag(arg);
1646 sel->tags[i] = !sel->tags[i];
1647 for(j = 0; j < ntags && !sel->tags[j]; j++);
1648 if(j == ntags)
1649 sel->tags[i] = True;
1650 arrange();
1651 }
1652
1653 void
1654 toggleview(const char *arg) {
1655 unsigned int i, j;
1656
1657 i = idxoftag(arg);
1658 seltags[i] = !seltags[i];
1659 for(j = 0; j < ntags && !seltags[j]; j++);
1660 if(j == ntags)
1661 seltags[i] = True; /* at least one tag must be viewed */
1662 arrange();
1663 }
1664
1665 void
1666 unban(Client *c) {
1667 if(!c->isbanned)
1668 return;
1669 XMoveWindow(dpy, c->win, c->x, c->y);
1670 c->isbanned = False;
1671 }
1672
1673 void
1674 unmanage(Client *c) {
1675 XWindowChanges wc;
1676
1677 wc.border_width = c->oldborder;
1678 /* The server grab construct avoids race conditions. */
1679 XGrabServer(dpy);
1680 XSetErrorHandler(xerrordummy);
1681 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1682 detach(c);
1683 detachstack(c);
1684 if(sel == c)
1685 focus(NULL);
1686 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1687 setclientstate(c, WithdrawnState);
1688 free(c->tags);
1689 free(c);
1690 XSync(dpy, False);
1691 XSetErrorHandler(xerror);
1692 XUngrabServer(dpy);
1693 arrange();
1694 }
1695
1696 void
1697 unmapnotify(XEvent *e) {
1698 Client *c;
1699 XUnmapEvent *ev = &e->xunmap;
1700
1701 if((c = getclient(ev->window)))
1702 unmanage(c);
1703 }
1704
1705 void
1706 updatebarpos(void) {
1707 XEvent ev;
1708
1709 wax = sx;
1710 way = sy;
1711 wah = sh;
1712 waw = sw;
1713 switch(bpos) {
1714 default:
1715 wah -= bh;
1716 way += bh;
1717 XMoveWindow(dpy, barwin, sx, sy);
1718 break;
1719 case BarBot:
1720 wah -= bh;
1721 XMoveWindow(dpy, barwin, sx, sy + wah);
1722 break;
1723 case BarOff:
1724 XMoveWindow(dpy, barwin, sx, sy - bh);
1725 break;
1726 }
1727 XSync(dpy, False);
1728 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1729 }
1730
1731 void
1732 updatesizehints(Client *c) {
1733 long msize;
1734 XSizeHints size;
1735
1736 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1737 size.flags = PSize;
1738 c->flags = size.flags;
1739 if(c->flags & PBaseSize) {
1740 c->basew = size.base_width;
1741 c->baseh = size.base_height;
1742 }
1743 else if(c->flags & PMinSize) {
1744 c->basew = size.min_width;
1745 c->baseh = size.min_height;
1746 }
1747 else
1748 c->basew = c->baseh = 0;
1749 if(c->flags & PResizeInc) {
1750 c->incw = size.width_inc;
1751 c->inch = size.height_inc;
1752 }
1753 else
1754 c->incw = c->inch = 0;
1755 if(c->flags & PMaxSize) {
1756 c->maxw = size.max_width;
1757 c->maxh = size.max_height;
1758 }
1759 else
1760 c->maxw = c->maxh = 0;
1761 if(c->flags & PMinSize) {
1762 c->minw = size.min_width;
1763 c->minh = size.min_height;
1764 }
1765 else if(c->flags & PBaseSize) {
1766 c->minw = size.base_width;
1767 c->minh = size.base_height;
1768 }
1769 else
1770 c->minw = c->minh = 0;
1771 if(c->flags & PAspect) {
1772 c->minax = size.min_aspect.x;
1773 c->maxax = size.max_aspect.x;
1774 c->minay = size.min_aspect.y;
1775 c->maxay = size.max_aspect.y;
1776 }
1777 else
1778 c->minax = c->maxax = c->minay = c->maxay = 0;
1779 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1780 && c->maxw == c->minw && c->maxh == c->minh);
1781 }
1782
1783 void
1784 updatetitle(Client *c) {
1785 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1786 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1787 }
1788
1789 /* There's no way to check accesses to destroyed windows, thus those cases are
1790 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1791 * default error handler, which may call exit. */
1792 int
1793 xerror(Display *dpy, XErrorEvent *ee) {
1794 if(ee->error_code == BadWindow
1795 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1796 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1797 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1798 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1799 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1800 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1801 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1802 return 0;
1803 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1804 ee->request_code, ee->error_code);
1805 return xerrorxlib(dpy, ee); /* may call exit */
1806 }
1807
1808 int
1809 xerrordummy(Display *dsply, XErrorEvent *ee) {
1810 return 0;
1811 }
1812
1813 /* Startup Error handler to check if another window manager
1814 * is already running. */
1815 int
1816 xerrorstart(Display *dsply, XErrorEvent *ee) {
1817 otherwm = True;
1818 return -1;
1819 }
1820
1821 void
1822 view(const char *arg) {
1823 unsigned int i;
1824
1825 memcpy(prevtags, seltags, sizeof seltags);
1826 for(i = 0; i < ntags; i++)
1827 seltags[i] = arg == NULL;
1828 i = idxoftag(arg);
1829 if(i >= 0 && i < ntags)
1830 seltags[i] = True;
1831 arrange();
1832 }
1833
1834 void
1835 viewprevtag(const char *arg) {
1836 static Bool tmptags[sizeof tags / sizeof tags[0]];
1837
1838 memcpy(tmptags, seltags, sizeof seltags);
1839 memcpy(seltags, prevtags, sizeof seltags);
1840 memcpy(prevtags, tmptags, sizeof seltags);
1841 arrange();
1842 }
1843
1844 void
1845 zoom(const char *arg) {
1846 Client *c;
1847
1848 if(!sel || !ISTILE || sel->isfloating)
1849 return;
1850 if((c = sel) == nexttiled(clients))
1851 if(!(c = nexttiled(c->next)))
1852 return;
1853 detach(c);
1854 attach(c);
1855 focus(c);
1856 arrange();
1857 }
1858
1859 int
1860 main(int argc, char *argv[]) {
1861 if(argc == 2 && !strcmp("-v", argv[1]))
1862 eprint("dwm-"VERSION", © 2006-2007 A. R. Garbe, S. van Dijk, J. Salmi, P. Hruby, S. Nagy\n");
1863 else if(argc != 1)
1864 eprint("usage: dwm [-v]\n");
1865
1866 setlocale(LC_CTYPE, "");
1867 if(!(dpy = XOpenDisplay(0)))
1868 eprint("dwm: cannot open display\n");
1869 screen = DefaultScreen(dpy);
1870 root = RootWindow(dpy, screen);
1871
1872 checkotherwm();
1873 setup();
1874 drawbar();
1875 scan();
1876 run();
1877 cleanup();
1878
1879 XCloseDisplay(dpy);
1880 return 0;
1881 }