Xinqi Bao's Git

8da3b6fb070a150b759df2771b0a61e3131b3611
[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, 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 fd_set rd;
1291 int r, xfd;
1292 unsigned int len, offset;
1293 XEvent ev;
1294
1295 /* main event loop, also reads status text from stdin */
1296 XSync(dpy, False);
1297 xfd = ConnectionNumber(dpy);
1298 readin = True;
1299 offset = 0;
1300 len = sizeof stext - 1;
1301 stext[len] = '\0'; /* 0-terminator is never touched */
1302 while(running) {
1303 FD_ZERO(&rd);
1304 if(readin)
1305 FD_SET(STDIN_FILENO, &rd);
1306 FD_SET(xfd, &rd);
1307 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1308 if(errno == EINTR)
1309 continue;
1310 eprint("select failed\n");
1311 }
1312 if(FD_ISSET(STDIN_FILENO, &rd)) {
1313 switch((r = read(STDIN_FILENO, stext + offset, len - offset))) {
1314 case -1:
1315 strncpy(stext, strerror(errno), len);
1316 readin = False;
1317 break;
1318 case 0:
1319 strncpy(stext, "EOF", 4);
1320 readin = False;
1321 break;
1322 default:
1323 stext[offset + r] = '\0';
1324 for(p = stext; *p && *p != '\n'; p++);
1325 if(*p == '\n') {
1326 *p = '\0';
1327 offset = 0;
1328 }
1329 else
1330 offset = (offset + r < len - 1) ? offset + r : 0;
1331 }
1332 drawbar();
1333 }
1334 while(XPending(dpy)) {
1335 XNextEvent(dpy, &ev);
1336 if(handler[ev.type])
1337 (handler[ev.type])(&ev); /* call handler */
1338 }
1339 }
1340 }
1341
1342 void
1343 scan(void) {
1344 unsigned int i, num;
1345 Window *wins, d1, d2;
1346 XWindowAttributes wa;
1347
1348 wins = NULL;
1349 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1350 for(i = 0; i < num; i++) {
1351 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1352 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1353 continue;
1354 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1355 manage(wins[i], &wa);
1356 }
1357 for(i = 0; i < num; i++) { /* now the transients */
1358 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1359 continue;
1360 if(XGetTransientForHint(dpy, wins[i], &d1)
1361 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1362 manage(wins[i], &wa);
1363 }
1364 }
1365 if(wins)
1366 XFree(wins);
1367 }
1368
1369 void
1370 setclientstate(Client *c, long state) {
1371 long data[] = {state, None};
1372
1373 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1374 PropModeReplace, (unsigned char *)data, 2);
1375 }
1376
1377 void
1378 setlayout(const char *arg) {
1379 unsigned int i;
1380
1381 if(!arg) {
1382 if(++layout == &layouts[LENGTH(layouts)])
1383 layout = &layouts[0];
1384 }
1385 else {
1386 for(i = 0; i < LENGTH(layouts); i++)
1387 if(!strcmp(arg, layouts[i].symbol))
1388 break;
1389 if(i == LENGTH(layouts))
1390 return;
1391 layout = &layouts[i];
1392 }
1393 if(sel)
1394 arrange();
1395 else
1396 drawbar();
1397 }
1398
1399 void
1400 setmwfact(const char *arg) {
1401 double delta;
1402
1403 if(!domwfact)
1404 return;
1405 /* arg handling, manipulate mwfact */
1406 if(arg == NULL)
1407 mwfact = MWFACT;
1408 else if(sscanf(arg, "%lf", &delta) == 1) {
1409 if(arg[0] == '+' || arg[0] == '-')
1410 mwfact += delta;
1411 else
1412 mwfact = delta;
1413 if(mwfact < 0.1)
1414 mwfact = 0.1;
1415 else if(mwfact > 0.9)
1416 mwfact = 0.9;
1417 }
1418 arrange();
1419 }
1420
1421 void
1422 setup(void) {
1423 int d;
1424 unsigned int i, j, mask;
1425 Window w;
1426 XModifierKeymap *modmap;
1427 XSetWindowAttributes wa;
1428
1429 /* init atoms */
1430 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1431 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1432 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1433 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1434 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1435 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1436 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1437 PropModeReplace, (unsigned char *) netatom, NetLast);
1438
1439 /* init cursors */
1440 cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1441 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1442 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1443
1444 /* init geometry */
1445 sx = sy = 0;
1446 sw = DisplayWidth(dpy, screen);
1447 sh = DisplayHeight(dpy, screen);
1448
1449 /* init modifier map */
1450 modmap = XGetModifierMapping(dpy);
1451 for(i = 0; i < 8; i++)
1452 for(j = 0; j < modmap->max_keypermod; j++) {
1453 if(modmap->modifiermap[i * modmap->max_keypermod + j]
1454 == XKeysymToKeycode(dpy, XK_Num_Lock))
1455 numlockmask = (1 << i);
1456 }
1457 XFreeModifiermap(modmap);
1458
1459 /* select for events */
1460 wa.event_mask = SubstructureRedirectMask | SubstructureNotifyMask
1461 | EnterWindowMask | LeaveWindowMask | StructureNotifyMask;
1462 wa.cursor = cursor[CurNormal];
1463 XChangeWindowAttributes(dpy, root, CWEventMask | CWCursor, &wa);
1464 XSelectInput(dpy, root, wa.event_mask);
1465
1466 /* grab keys */
1467 grabkeys();
1468
1469 /* init tags */
1470 memcpy(prevtags, seltags, sizeof seltags);
1471 compileregs();
1472
1473 /* init appearance */
1474 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1475 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1476 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1477 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1478 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1479 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1480 initfont(FONT);
1481 dc.h = bh = dc.font.height + 2;
1482
1483 /* init layouts */
1484 mwfact = MWFACT;
1485 layout = &layouts[0];
1486 for(blw = i = 0; i < LENGTH(layouts); i++) {
1487 j = textw(layouts[i].symbol);
1488 if(j > blw)
1489 blw = j;
1490 }
1491
1492 /* init bar */
1493 bpos = BARPOS;
1494 wa.override_redirect = 1;
1495 wa.background_pixmap = ParentRelative;
1496 wa.event_mask = ButtonPressMask | ExposureMask;
1497 barwin = XCreateWindow(dpy, root, sx, sy, sw, bh, 0,
1498 DefaultDepth(dpy, screen), CopyFromParent, DefaultVisual(dpy, screen),
1499 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
1500 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1501 updatebarpos();
1502 XMapRaised(dpy, barwin);
1503 strcpy(stext, "dwm-"VERSION);
1504 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
1505 dc.gc = XCreateGC(dpy, root, 0, 0);
1506 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1507 if(!dc.font.set)
1508 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1509
1510 /* multihead support */
1511 selscreen = XQueryPointer(dpy, root, &w, &w, &d, &d, &d, &d, &mask);
1512 }
1513
1514 void
1515 spawn(const char *arg) {
1516 static char *shell = NULL;
1517
1518 if(!shell && !(shell = getenv("SHELL")))
1519 shell = "/bin/sh";
1520 if(!arg)
1521 return;
1522 /* The double-fork construct avoids zombie processes and keeps the code
1523 * clean from stupid signal handlers. */
1524 if(fork() == 0) {
1525 if(fork() == 0) {
1526 if(dpy)
1527 close(ConnectionNumber(dpy));
1528 setsid();
1529 execl(shell, shell, "-c", arg, (char *)NULL);
1530 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1531 perror(" failed");
1532 }
1533 exit(0);
1534 }
1535 wait(0);
1536 }
1537
1538 void
1539 tag(const char *arg) {
1540 unsigned int i;
1541
1542 if(!sel)
1543 return;
1544 for(i = 0; i < LENGTH(tags); i++)
1545 sel->tags[i] = (NULL == arg);
1546 sel->tags[idxoftag(arg)] = True;
1547 arrange();
1548 }
1549
1550 unsigned int
1551 textnw(const char *text, unsigned int len) {
1552 XRectangle r;
1553
1554 if(dc.font.set) {
1555 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1556 return r.width;
1557 }
1558 return XTextWidth(dc.font.xfont, text, len);
1559 }
1560
1561 unsigned int
1562 textw(const char *text) {
1563 return textnw(text, strlen(text)) + dc.font.height;
1564 }
1565
1566 void
1567 tile(void) {
1568 unsigned int i, n, nx, ny, nw, nh, mw, th;
1569 Client *c, *mc;
1570
1571 domwfact = dozoom = True;
1572 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next))
1573 n++;
1574
1575 /* window geoms */
1576 mw = (n == 1) ? waw : mwfact * waw;
1577 th = (n > 1) ? wah / (n - 1) : 0;
1578 if(n > 1 && th < bh)
1579 th = wah;
1580
1581 nx = wax;
1582 ny = way;
1583 nw = 0; /* gcc stupidity requires this */
1584 for(i = 0, c = mc = nexttiled(clients); c; c = nexttiled(c->next), i++) {
1585 c->ismax = False;
1586 if(i == 0) { /* master */
1587 nw = mw - 2 * c->border;
1588 nh = wah - 2 * c->border;
1589 }
1590 else { /* tile window */
1591 if(i == 1) {
1592 ny = way;
1593 nx += mc->w + 2 * mc->border;
1594 nw = waw - nx - 2 * c->border;
1595 }
1596 if(i + 1 == n) /* remainder */
1597 nh = (way + wah) - ny - 2 * c->border;
1598 else
1599 nh = th - 2 * c->border;
1600 }
1601 resize(c, nx, ny, nw, nh, RESIZEHINTS);
1602 if((RESIZEHINTS) && ((c->h < bh) || (c->h > nh) || (c->w < bh) || (c->w > nw)))
1603 /* client doesn't accept size constraints */
1604 resize(c, nx, ny, nw, nh, False);
1605 if(n > 1 && th != wah)
1606 ny = c->y + c->h + 2 * c->border;
1607 }
1608 }
1609
1610 void
1611 togglebar(const char *arg) {
1612 if(bpos == BarOff)
1613 bpos = (BARPOS == BarOff) ? BarTop : BARPOS;
1614 else
1615 bpos = BarOff;
1616 updatebarpos();
1617 arrange();
1618 }
1619
1620 void
1621 togglefloating(const char *arg) {
1622 if(!sel)
1623 return;
1624 sel->isfloating = !sel->isfloating;
1625 if(sel->isfloating)
1626 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1627 arrange();
1628 }
1629
1630 void
1631 togglemax(const char *arg) {
1632 XEvent ev;
1633
1634 if(!sel || sel->isfixed)
1635 return;
1636 if((sel->ismax = !sel->ismax)) {
1637 if((layout->arrange == floating) || sel->isfloating)
1638 sel->wasfloating = True;
1639 else {
1640 togglefloating(NULL);
1641 sel->wasfloating = False;
1642 }
1643 sel->rx = sel->x;
1644 sel->ry = sel->y;
1645 sel->rw = sel->w;
1646 sel->rh = sel->h;
1647 resize(sel, wax, way, waw - 2 * sel->border, wah - 2 * sel->border, True);
1648 }
1649 else {
1650 resize(sel, sel->rx, sel->ry, sel->rw, sel->rh, True);
1651 if(!sel->wasfloating)
1652 togglefloating(NULL);
1653 }
1654 drawbar();
1655 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1656 }
1657
1658 void
1659 toggletag(const char *arg) {
1660 unsigned int i, j;
1661
1662 if(!sel)
1663 return;
1664 i = idxoftag(arg);
1665 sel->tags[i] = !sel->tags[i];
1666 for(j = 0; j < LENGTH(tags) && !sel->tags[j]; j++);
1667 if(j == LENGTH(tags))
1668 sel->tags[i] = True; /* at least one tag must be enabled */
1669 arrange();
1670 }
1671
1672 void
1673 toggleview(const char *arg) {
1674 unsigned int i, j;
1675
1676 i = idxoftag(arg);
1677 seltags[i] = !seltags[i];
1678 for(j = 0; j < LENGTH(tags) && !seltags[j]; j++);
1679 if(j == LENGTH(tags))
1680 seltags[i] = True; /* at least one tag must be viewed */
1681 arrange();
1682 }
1683
1684 void
1685 unban(Client *c) {
1686 if(!c->isbanned)
1687 return;
1688 XMoveWindow(dpy, c->win, c->x, c->y);
1689 c->isbanned = False;
1690 }
1691
1692 void
1693 unmanage(Client *c) {
1694 XWindowChanges wc;
1695
1696 wc.border_width = c->oldborder;
1697 /* The server grab construct avoids race conditions. */
1698 XGrabServer(dpy);
1699 XSetErrorHandler(xerrordummy);
1700 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1701 detach(c);
1702 detachstack(c);
1703 if(sel == c)
1704 focus(NULL);
1705 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1706 setclientstate(c, WithdrawnState);
1707 free(c->tags);
1708 free(c);
1709 XSync(dpy, False);
1710 XSetErrorHandler(xerror);
1711 XUngrabServer(dpy);
1712 arrange();
1713 }
1714
1715 void
1716 unmapnotify(XEvent *e) {
1717 Client *c;
1718 XUnmapEvent *ev = &e->xunmap;
1719
1720 if((c = getclient(ev->window)))
1721 unmanage(c);
1722 }
1723
1724 void
1725 updatebarpos(void) {
1726 XEvent ev;
1727
1728 wax = sx;
1729 way = sy;
1730 wah = sh;
1731 waw = sw;
1732 switch(bpos) {
1733 default:
1734 wah -= bh;
1735 way += bh;
1736 XMoveWindow(dpy, barwin, sx, sy);
1737 break;
1738 case BarBot:
1739 wah -= bh;
1740 XMoveWindow(dpy, barwin, sx, sy + wah);
1741 break;
1742 case BarOff:
1743 XMoveWindow(dpy, barwin, sx, sy - bh);
1744 break;
1745 }
1746 XSync(dpy, False);
1747 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1748 }
1749
1750 void
1751 updatesizehints(Client *c) {
1752 long msize;
1753 XSizeHints size;
1754
1755 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1756 size.flags = PSize;
1757 c->flags = size.flags;
1758 if(c->flags & PBaseSize) {
1759 c->basew = size.base_width;
1760 c->baseh = size.base_height;
1761 }
1762 else if(c->flags & PMinSize) {
1763 c->basew = size.min_width;
1764 c->baseh = size.min_height;
1765 }
1766 else
1767 c->basew = c->baseh = 0;
1768 if(c->flags & PResizeInc) {
1769 c->incw = size.width_inc;
1770 c->inch = size.height_inc;
1771 }
1772 else
1773 c->incw = c->inch = 0;
1774 if(c->flags & PMaxSize) {
1775 c->maxw = size.max_width;
1776 c->maxh = size.max_height;
1777 }
1778 else
1779 c->maxw = c->maxh = 0;
1780 if(c->flags & PMinSize) {
1781 c->minw = size.min_width;
1782 c->minh = size.min_height;
1783 }
1784 else if(c->flags & PBaseSize) {
1785 c->minw = size.base_width;
1786 c->minh = size.base_height;
1787 }
1788 else
1789 c->minw = c->minh = 0;
1790 if(c->flags & PAspect) {
1791 c->minax = size.min_aspect.x;
1792 c->maxax = size.max_aspect.x;
1793 c->minay = size.min_aspect.y;
1794 c->maxay = size.max_aspect.y;
1795 }
1796 else
1797 c->minax = c->maxax = c->minay = c->maxay = 0;
1798 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1799 && c->maxw == c->minw && c->maxh == c->minh);
1800 }
1801
1802 void
1803 updatetitle(Client *c) {
1804 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1805 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1806 }
1807
1808 /* There's no way to check accesses to destroyed windows, thus those cases are
1809 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1810 * default error handler, which may call exit. */
1811 int
1812 xerror(Display *dpy, XErrorEvent *ee) {
1813 if(ee->error_code == BadWindow
1814 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1815 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1816 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1817 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1818 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1819 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1820 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1821 return 0;
1822 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1823 ee->request_code, ee->error_code);
1824 return xerrorxlib(dpy, ee); /* may call exit */
1825 }
1826
1827 int
1828 xerrordummy(Display *dsply, XErrorEvent *ee) {
1829 return 0;
1830 }
1831
1832 /* Startup Error handler to check if another window manager
1833 * is already running. */
1834 int
1835 xerrorstart(Display *dsply, XErrorEvent *ee) {
1836 otherwm = True;
1837 return -1;
1838 }
1839
1840 void
1841 view(const char *arg) {
1842 unsigned int i;
1843
1844 memcpy(prevtags, seltags, sizeof seltags);
1845 for(i = 0; i < LENGTH(tags); i++)
1846 seltags[i] = (NULL == arg);
1847 seltags[idxoftag(arg)] = True;
1848 arrange();
1849 }
1850
1851 void
1852 viewprevtag(const char *arg) {
1853 static Bool tmp[LENGTH(tags)];
1854
1855 memcpy(tmp, seltags, sizeof seltags);
1856 memcpy(seltags, prevtags, sizeof seltags);
1857 memcpy(prevtags, tmp, sizeof seltags);
1858 arrange();
1859 }
1860
1861 void
1862 zoom(const char *arg) {
1863 Client *c;
1864
1865 if(!sel || !dozoom || sel->isfloating)
1866 return;
1867 if((c = sel) == nexttiled(clients))
1868 if(!(c = nexttiled(c->next)))
1869 return;
1870 detach(c);
1871 attach(c);
1872 focus(c);
1873 arrange();
1874 }
1875
1876 int
1877 main(int argc, char *argv[]) {
1878 if(argc == 2 && !strcmp("-v", argv[1]))
1879 eprint("dwm-"VERSION", © 2006-2007 Anselm R. Garbe, Sander van Dijk, "
1880 "Jukka Salmi, Premysl Hruby, Szabolcs Nagy\n");
1881 else if(argc != 1)
1882 eprint("usage: dwm [-v]\n");
1883
1884 setlocale(LC_CTYPE, "");
1885 if(!(dpy = XOpenDisplay(0)))
1886 eprint("dwm: cannot open display\n");
1887 screen = DefaultScreen(dpy);
1888 root = RootWindow(dpy, screen);
1889
1890 checkotherwm();
1891 setup();
1892 drawbar();
1893 scan();
1894 run();
1895 cleanup();
1896
1897 XCloseDisplay(dpy);
1898 return 0;
1899 }