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