Xinqi Bao's Git

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