Xinqi Bao's Git

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