Xinqi Bao's Git

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