Xinqi Bao's Git

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