JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
made restack, drawbar also Monitor-related only
[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 Client Client;
64 struct Client {
65         char name[256];
66         int x, y, w, h;
67         int basew, baseh, incw, inch, maxw, maxh, minw, minh;
68         int minax, maxax, minay, maxay;
69         long flags;
70         unsigned int border, oldborder;
71         Bool isbanned, isfixed, isfloating, isurgent;
72         Bool *tags;
73         Client *next;
74         Client *prev;
75         Client *snext;
76         Window win;
77         int monitor;
78 };
79
80 typedef struct {
81         int x, y, w, h;
82         unsigned long norm[ColLast];
83         unsigned long sel[ColLast];
84         Drawable drawable;
85         GC gc;
86         struct {
87                 int ascent;
88                 int descent;
89                 int height;
90                 XFontSet set;
91                 XFontStruct *xfont;
92         } font;
93 } DC; /* draw context */
94
95 typedef struct {
96         unsigned long mod;
97         KeySym keysym;
98         void (*func)(const char *arg);
99         const char *arg;
100 } Key;
101
102 typedef struct Monitor Monitor;
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(unsigned int monitor, unsigned int t);
169 Bool isprotodel(Client *c);
170 Bool isurgent(unsigned int monitor, unsigned int t);
171 Bool isvisible(Client *c, int monitor);
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 void movemouse(Client *c);
178 Client *nexttiled(Client *c, int monitor);
179 void propertynotify(XEvent *e);
180 void quit(const char *arg);
181 void reapply(const char *arg);
182 void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
183 void resizemouse(Client *c);
184 void restack(Monitor *m);
185 void run(void);
186 void scan(void);
187 void setclientstate(Client *c, long state);
188 void setlayout(const char *arg);
189 void setmwfact(const char *arg);
190 void setup(void);
191 void spawn(const char *arg);
192 void tag(const char *arg);
193 unsigned int textnw(const char *text, unsigned int len);
194 unsigned int textw(const char *text);
195 void tile(Monitor *m);
196 void togglebar(const char *arg);
197 void togglefloating(const char *arg);
198 void toggletag(const char *arg);
199 void toggleview(const char *arg);
200 void unban(Client *c);
201 void unmanage(Client *c);
202 void unmapnotify(XEvent *e);
203 void updatebarpos(Monitor *m);
204 void updatesizehints(Client *c);
205 void updatetitle(Client *c);
206 void updatewmhints(Client *c);
207 void view(const char *arg);
208 void viewprevtag(const char *arg);      /* views previous selected tags */
209 int xerror(Display *dpy, XErrorEvent *ee);
210 int xerrordummy(Display *dsply, XErrorEvent *ee);
211 int xerrorstart(Display *dsply, XErrorEvent *ee);
212 void zoom(const char *arg);
213 int monitorat(void);
214 void movetomonitor(const char *arg);
215 void selectmonitor(const char *arg);
216
217 /* variables */
218 char stext[256];
219 int mcount = 1;
220 int selmonitor = 0;
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 = 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, monitors[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         monitors[selmonitor].layout->arrange(&monitors[selmonitor]);
312         focus(NULL);
313         restack(&monitors[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 * monitors[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 = &monitors[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(&monitors[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(&monitors[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 = &monitors[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 = &monitors[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->id); 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->id, j));
576                         drawsquare(m, c && c->tags[j] && c->monitor == m->id,
577                                         isoccupied(m->id, j), isurgent(m->id, j), dc.sel);
578                 }
579                 else {
580                         drawtext(m, tags[j], dc.norm, isurgent(m->id, j));
581                         drawsquare(m, c && c->tags[j] && c->monitor == m->id,
582                                         isoccupied(m->id, j), isurgent(m->id, 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->id == 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);
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->id))
727                         resize(c, c->x, c->y, c->w, c->h, True);
728 }
729
730 void
731 focus(Client *c) {
732         Monitor *m;
733
734         if(c)
735                 selmonitor = c->monitor;
736         m = &monitors[selmonitor];
737         if(!c || (c && !isvisible(c, selmonitor)))
738                 for(c = stack; c && !isvisible(c, c->monitor); c = c->snext);
739         if(sel && sel != c) {
740                 grabbuttons(sel, False);
741                 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
742         }
743         if(c) {
744                 detachstack(c);
745                 attachstack(c);
746                 grabbuttons(c, True);
747         }
748         sel = c;
749         if(c) {
750                 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
751                 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
752                 selmonitor = c->monitor;
753         }
754         else
755                 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
756         drawbar(&monitors[selmonitor]);
757 }
758
759 void
760 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
761         XFocusChangeEvent *ev = &e->xfocus;
762
763         if(sel && ev->window != sel->win)
764                 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
765 }
766
767 void
768 focusnext(const char *arg) {
769         Client *c;
770
771         if(!sel)
772                 return;
773         for(c = sel->next; c && !isvisible(c, selmonitor); c = c->next);
774         if(!c)
775                 for(c = clients; c && !isvisible(c, selmonitor); c = c->next);
776         if(c) {
777                 focus(c);
778                 restack(&monitors[c->monitor]);
779         }
780 }
781
782 void
783 focusprev(const char *arg) {
784         Client *c;
785
786         if(!sel)
787                 return;
788         for(c = sel->prev; c && !isvisible(c, selmonitor); c = c->prev);
789         if(!c) {
790                 for(c = clients; c && c->next; c = c->next);
791                 for(; c && !isvisible(c, selmonitor); c = c->prev);
792         }
793         if(c) {
794                 focus(c);
795                 restack(&monitors[c->monitor]);
796         }
797 }
798
799 Client *
800 getclient(Window w) {
801         Client *c;
802
803         for(c = clients; c && c->win != w; c = c->next);
804         return c;
805 }
806
807 unsigned long
808 getcolor(const char *colstr) {
809         Colormap cmap = DefaultColormap(dpy, screen);
810         XColor color;
811
812         if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
813                 eprint("error, cannot allocate color '%s'\n", colstr);
814         return color.pixel;
815 }
816
817 Monitor *
818 getmonitor(Window barwin) {
819         unsigned int i;
820
821         for(i = 0; i < mcount; i++)
822                 if(monitors[i].barwin == barwin)
823                         return &monitors[i];
824         return NULL;
825 }
826
827 long
828 getstate(Window w) {
829         int format, status;
830         long result = -1;
831         unsigned char *p = NULL;
832         unsigned long n, extra;
833         Atom real;
834
835         status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
836                         &real, &format, &n, &extra, (unsigned char **)&p);
837         if(status != Success)
838                 return -1;
839         if(n != 0)
840                 result = *p;
841         XFree(p);
842         return result;
843 }
844
845 Bool
846 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
847         char **list = NULL;
848         int n;
849         XTextProperty name;
850
851         if(!text || size == 0)
852                 return False;
853         text[0] = '\0';
854         XGetTextProperty(dpy, w, &name, atom);
855         if(!name.nitems)
856                 return False;
857         if(name.encoding == XA_STRING)
858                 strncpy(text, (char *)name.value, size - 1);
859         else {
860                 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
861                 && n > 0 && *list) {
862                         strncpy(text, *list, size - 1);
863                         XFreeStringList(list);
864                 }
865         }
866         text[size - 1] = '\0';
867         XFree(name.value);
868         return True;
869 }
870
871 void
872 grabbuttons(Client *c, Bool focused) {
873         XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
874
875         if(focused) {
876                 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
877                                 GrabModeAsync, GrabModeSync, None, None);
878                 XGrabButton(dpy, Button1, MODKEY | LockMask, c->win, False, BUTTONMASK,
879                                 GrabModeAsync, GrabModeSync, None, None);
880                 XGrabButton(dpy, Button1, MODKEY | numlockmask, c->win, False, BUTTONMASK,
881                                 GrabModeAsync, GrabModeSync, None, None);
882                 XGrabButton(dpy, Button1, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
883                                 GrabModeAsync, GrabModeSync, None, None);
884
885                 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
886                                 GrabModeAsync, GrabModeSync, None, None);
887                 XGrabButton(dpy, Button2, MODKEY | LockMask, c->win, False, BUTTONMASK,
888                                 GrabModeAsync, GrabModeSync, None, None);
889                 XGrabButton(dpy, Button2, MODKEY | numlockmask, c->win, False, BUTTONMASK,
890                                 GrabModeAsync, GrabModeSync, None, None);
891                 XGrabButton(dpy, Button2, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
892                                 GrabModeAsync, GrabModeSync, None, None);
893
894                 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
895                                 GrabModeAsync, GrabModeSync, None, None);
896                 XGrabButton(dpy, Button3, MODKEY | LockMask, c->win, False, BUTTONMASK,
897                                 GrabModeAsync, GrabModeSync, None, None);
898                 XGrabButton(dpy, Button3, MODKEY | numlockmask, c->win, False, BUTTONMASK,
899                                 GrabModeAsync, GrabModeSync, None, None);
900                 XGrabButton(dpy, Button3, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
901                                 GrabModeAsync, GrabModeSync, None, None);
902         }
903         else
904                 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
905                                 GrabModeAsync, GrabModeSync, None, None);
906 }
907
908 void
909 grabkeys(void)  {
910         unsigned int i, j;
911         KeyCode code;
912         XModifierKeymap *modmap;
913
914         /* init modifier map */
915         modmap = XGetModifierMapping(dpy);
916         for(i = 0; i < 8; i++)
917                 for(j = 0; j < modmap->max_keypermod; j++) {
918                         if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
919                                 numlockmask = (1 << i);
920                 }
921         XFreeModifiermap(modmap);
922
923         XUngrabKey(dpy, AnyKey, AnyModifier, root);
924         for(i = 0; i < LENGTH(keys); i++) {
925                 code = XKeysymToKeycode(dpy, keys[i].keysym);
926                 XGrabKey(dpy, code, keys[i].mod, root, True,
927                                 GrabModeAsync, GrabModeAsync);
928                 XGrabKey(dpy, code, keys[i].mod | LockMask, root, True,
929                                 GrabModeAsync, GrabModeAsync);
930                 XGrabKey(dpy, code, keys[i].mod | numlockmask, root, True,
931                                 GrabModeAsync, GrabModeAsync);
932                 XGrabKey(dpy, code, keys[i].mod | numlockmask | LockMask, root, True,
933                                 GrabModeAsync, GrabModeAsync);
934         }
935 }
936
937 unsigned int
938 idxoftag(const char *tag) {
939         unsigned int i;
940
941         for(i = 0; (i < LENGTH(tags)) && (tags[i] != tag); i++);
942         return (i < LENGTH(tags)) ? i : 0;
943 }
944
945 void
946 initfont(const char *fontstr) {
947         char *def, **missing;
948         int i, n;
949
950         missing = NULL;
951         if(dc.font.set)
952                 XFreeFontSet(dpy, dc.font.set);
953         dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
954         if(missing) {
955                 while(n--)
956                         fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
957                 XFreeStringList(missing);
958         }
959         if(dc.font.set) {
960                 XFontSetExtents *font_extents;
961                 XFontStruct **xfonts;
962                 char **font_names;
963                 dc.font.ascent = dc.font.descent = 0;
964                 font_extents = XExtentsOfFontSet(dc.font.set);
965                 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
966                 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
967                         if(dc.font.ascent < (*xfonts)->ascent)
968                                 dc.font.ascent = (*xfonts)->ascent;
969                         if(dc.font.descent < (*xfonts)->descent)
970                                 dc.font.descent = (*xfonts)->descent;
971                         xfonts++;
972                 }
973         }
974         else {
975                 if(dc.font.xfont)
976                         XFreeFont(dpy, dc.font.xfont);
977                 dc.font.xfont = NULL;
978                 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
979                 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
980                         eprint("error, cannot load font: '%s'\n", fontstr);
981                 dc.font.ascent = dc.font.xfont->ascent;
982                 dc.font.descent = dc.font.xfont->descent;
983         }
984         dc.font.height = dc.font.ascent + dc.font.descent;
985 }
986
987 Bool
988 isoccupied(unsigned int monitor, unsigned int t) {
989         Client *c;
990
991         for(c = clients; c; c = c->next)
992                 if(c->tags[t] && c->monitor == monitor)
993                         return True;
994         return False;
995 }
996
997 Bool
998 isprotodel(Client *c) {
999         int i, n;
1000         Atom *protocols;
1001         Bool ret = False;
1002
1003         if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
1004                 for(i = 0; !ret && i < n; i++)
1005                         if(protocols[i] == wmatom[WMDelete])
1006                                 ret = True;
1007                 XFree(protocols);
1008         }
1009         return ret;
1010 }
1011
1012 Bool
1013 isurgent(unsigned int monitor, unsigned int t) {
1014         Client *c;
1015
1016         for(c = clients; c; c = c->next)
1017                 if(c->monitor == monitor && c->isurgent && c->tags[t])
1018                         return True;
1019         return False;
1020 }
1021
1022 Bool
1023 isvisible(Client *c, int monitor) {
1024         unsigned int i;
1025
1026         if(c->monitor != monitor)
1027                 return False;
1028         for(i = 0; i < LENGTH(tags); i++)
1029                 if(c->tags[i] && monitors[c->monitor].seltags[i])
1030                         return True;
1031         return False;
1032 }
1033
1034 void
1035 keypress(XEvent *e) {
1036         unsigned int i;
1037         KeySym keysym;
1038         XKeyEvent *ev;
1039
1040         ev = &e->xkey;
1041         keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
1042         for(i = 0; i < LENGTH(keys); i++)
1043                 if(keysym == keys[i].keysym
1044                 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
1045                 {
1046                         if(keys[i].func)
1047                                 keys[i].func(keys[i].arg);
1048                 }
1049 }
1050
1051 void
1052 killclient(const char *arg) {
1053         XEvent ev;
1054
1055         if(!sel)
1056                 return;
1057         if(isprotodel(sel)) {
1058                 ev.type = ClientMessage;
1059                 ev.xclient.window = sel->win;
1060                 ev.xclient.message_type = wmatom[WMProtocols];
1061                 ev.xclient.format = 32;
1062                 ev.xclient.data.l[0] = wmatom[WMDelete];
1063                 ev.xclient.data.l[1] = CurrentTime;
1064                 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
1065         }
1066         else
1067                 XKillClient(dpy, sel->win);
1068 }
1069
1070 void
1071 manage(Window w, XWindowAttributes *wa) {
1072         Client *c, *t = NULL;
1073         Monitor *m;
1074         Status rettrans;
1075         Window trans;
1076         XWindowChanges wc;
1077
1078         c = emallocz(sizeof(Client));
1079         c->tags = emallocz(sizeof initags);
1080         c->win = w;
1081
1082         applyrules(c);
1083
1084         m = &monitors[c->monitor];
1085
1086         c->x = wa->x + m->sx;
1087         c->y = wa->y + m->sy;
1088         c->w = wa->width;
1089         c->h = wa->height;
1090         c->oldborder = wa->border_width;
1091
1092         if(c->w == m->sw && c->h == m->sh) {
1093                 c->x = m->sx;
1094                 c->y = m->sy;
1095                 c->border = wa->border_width;
1096         }
1097         else {
1098                 if(c->x + c->w + 2 * c->border > m->wax + m->waw)
1099                         c->x = m->wax + m->waw - c->w - 2 * c->border;
1100                 if(c->y + c->h + 2 * c->border > m->way + m->wah)
1101                         c->y = m->way + m->wah - c->h - 2 * c->border;
1102                 if(c->x < m->wax)
1103                         c->x = m->wax;
1104                 if(c->y < m->way)
1105                         c->y = m->way;
1106                 c->border = BORDERPX;
1107         }
1108         wc.border_width = c->border;
1109         XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1110         XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1111         configure(c); /* propagates border_width, if size doesn't change */
1112         updatesizehints(c);
1113         XSelectInput(dpy, w, EnterWindowMask | FocusChangeMask | PropertyChangeMask | StructureNotifyMask);
1114         grabbuttons(c, False);
1115         updatetitle(c);
1116         if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
1117                 for(t = clients; t && t->win != trans; t = t->next);
1118         if(t)
1119                 memcpy(c->tags, t->tags, sizeof initags);
1120         if(!c->isfloating)
1121                 c->isfloating = (rettrans == Success) || c->isfixed;
1122         attach(c);
1123         attachstack(c);
1124         XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
1125         ban(c);
1126         XMapWindow(dpy, c->win);
1127         setclientstate(c, NormalState);
1128         arrange();
1129 }
1130
1131 void
1132 mappingnotify(XEvent *e) {
1133         XMappingEvent *ev = &e->xmapping;
1134
1135         XRefreshKeyboardMapping(ev);
1136         if(ev->request == MappingKeyboard)
1137                 grabkeys();
1138 }
1139
1140 void
1141 maprequest(XEvent *e) {
1142         static XWindowAttributes wa;
1143         XMapRequestEvent *ev = &e->xmaprequest;
1144
1145         if(!XGetWindowAttributes(dpy, ev->window, &wa))
1146                 return;
1147         if(wa.override_redirect)
1148                 return;
1149         if(!getclient(ev->window))
1150                 manage(ev->window, &wa);
1151 }
1152
1153 int
1154 monitorat() {
1155         int i, x, y;
1156         Window win;
1157         unsigned int mask;
1158
1159         XQueryPointer(dpy, root, &win, &win, &x, &y, &i, &i, &mask);
1160         for(i = 0; i < mcount; i++) {
1161                 if((x >= monitors[i].sx && x < monitors[i].sx + monitors[i].sw)
1162                 && (y >= monitors[i].sy && y < monitors[i].sy + monitors[i].sh)) {
1163                         return i;
1164                 }
1165         }
1166         return 0;
1167 }
1168
1169 void
1170 movemouse(Client *c) {
1171         int x1, y1, ocx, ocy, di, nx, ny;
1172         unsigned int dui;
1173         Monitor *m;
1174         Window dummy;
1175         XEvent ev;
1176
1177         ocx = nx = c->x;
1178         ocy = ny = c->y;
1179         m = &monitors[c->monitor];
1180         if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1181                         None, cursor[CurMove], CurrentTime) != GrabSuccess)
1182                 return;
1183         XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1184         for(;;) {
1185                 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask, &ev);
1186                 switch (ev.type) {
1187                 case ButtonRelease:
1188                         XUngrabPointer(dpy, CurrentTime);
1189                         return;
1190                 case ConfigureRequest:
1191                 case Expose:
1192                 case MapRequest:
1193                         handler[ev.type](&ev);
1194                         break;
1195                 case MotionNotify:
1196                         XSync(dpy, False);
1197                         nx = ocx + (ev.xmotion.x - x1);
1198                         ny = ocy + (ev.xmotion.y - y1);
1199                         if(abs(m->wax - nx) < SNAP)
1200                                 nx = m->wax;
1201                         else if(abs((m->wax + m->waw) - (nx + c->w + 2 * c->border)) < SNAP)
1202                                 nx = m->wax + m->waw - c->w - 2 * c->border;
1203                         if(abs(m->way - ny) < SNAP)
1204                                 ny = m->way;
1205                         else if(abs((m->way + m->wah) - (ny + c->h + 2 * c->border)) < SNAP)
1206                                 ny = m->way + m->wah - c->h - 2 * c->border;
1207                         if((m->layout->arrange != floating) && (abs(nx - c->x) > SNAP || abs(ny - c->y) > SNAP))
1208                                 togglefloating(NULL);
1209                         if((m->layout->arrange == floating) || c->isfloating)
1210                                 resize(c, nx, ny, c->w, c->h, False);
1211                         break;
1212                 }
1213         }
1214 }
1215
1216 Client *
1217 nexttiled(Client *c, int monitor) {
1218         for(; c && (c->isfloating || !isvisible(c, monitor)); c = c->next);
1219         return c;
1220 }
1221
1222 void
1223 propertynotify(XEvent *e) {
1224         Client *c;
1225         Window trans;
1226         XPropertyEvent *ev = &e->xproperty;
1227
1228         if(ev->state == PropertyDelete)
1229                 return; /* ignore */
1230         if((c = getclient(ev->window))) {
1231                 switch (ev->atom) {
1232                 default: break;
1233                 case XA_WM_TRANSIENT_FOR:
1234                         XGetTransientForHint(dpy, c->win, &trans);
1235                         if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1236                                 arrange();
1237                         break;
1238                 case XA_WM_NORMAL_HINTS:
1239                         updatesizehints(c);
1240                         break;
1241                 case XA_WM_HINTS:
1242                         updatewmhints(c);
1243                         drawbar(&monitors[c->monitor]);
1244                         break;
1245                 }
1246                 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1247                         updatetitle(c);
1248                         if(c == sel)
1249                                 drawbar(&monitors[c->monitor]);
1250                 }
1251         }
1252 }
1253
1254 void
1255 quit(const char *arg) {
1256         readin = running = False;
1257 }
1258
1259 void
1260 reapply(const char *arg) {
1261         static Bool zerotags[LENGTH(tags)] = { 0 };
1262         Client *c;
1263
1264         for(c = clients; c; c = c->next) {
1265                 memcpy(c->tags, zerotags, sizeof zerotags);
1266                 applyrules(c);
1267         }
1268         arrange();
1269 }
1270
1271 void
1272 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1273         Monitor *m;
1274         XWindowChanges wc;
1275
1276         m = &monitors[c->monitor];
1277
1278         if(sizehints) {
1279                 /* set minimum possible */
1280                 if (w < 1)
1281                         w = 1;
1282                 if (h < 1)
1283                         h = 1;
1284
1285                 /* temporarily remove base dimensions */
1286                 w -= c->basew;
1287                 h -= c->baseh;
1288
1289                 /* adjust for aspect limits */
1290                 if (c->minay > 0 && c->maxay > 0 && c->minax > 0 && c->maxax > 0) {
1291                         if (w * c->maxay > h * c->maxax)
1292                                 w = h * c->maxax / c->maxay;
1293                         else if (w * c->minay < h * c->minax)
1294                                 h = w * c->minay / c->minax;
1295                 }
1296
1297                 /* adjust for increment value */
1298                 if(c->incw)
1299                         w -= w % c->incw;
1300                 if(c->inch)
1301                         h -= h % c->inch;
1302
1303                 /* restore base dimensions */
1304                 w += c->basew;
1305                 h += c->baseh;
1306
1307                 if(c->minw > 0 && w < c->minw)
1308                         w = c->minw;
1309                 if(c->minh > 0 && h < c->minh)
1310                         h = c->minh;
1311                 if(c->maxw > 0 && w > c->maxw)
1312                         w = c->maxw;
1313                 if(c->maxh > 0 && h > c->maxh)
1314                         h = c->maxh;
1315         }
1316         if(w <= 0 || h <= 0)
1317                 return;
1318         if(x > m->sw)
1319                 x = m->sw - w - 2 * c->border;
1320         if(y > m->sh)
1321                 y = m->sh - h - 2 * c->border;
1322         if(x + w + 2 * c->border < m->sx)
1323                 x = m->sx;
1324         if(y + h + 2 * c->border < m->sy)
1325                 y = m->sy;
1326         if(c->x != x || c->y != y || c->w != w || c->h != h) {
1327                 c->x = wc.x = x;
1328                 c->y = wc.y = y;
1329                 c->w = wc.width = w;
1330                 c->h = wc.height = h;
1331                 wc.border_width = c->border;
1332                 XConfigureWindow(dpy, c->win, CWX | CWY | CWWidth | CWHeight | CWBorderWidth, &wc);
1333                 configure(c);
1334                 XSync(dpy, False);
1335         }
1336 }
1337
1338 void
1339 resizemouse(Client *c) {
1340         int ocx, ocy;
1341         int nw, nh;
1342         Monitor *m;
1343         XEvent ev;
1344
1345         ocx = c->x;
1346         ocy = c->y;
1347         m = &monitors[c->monitor];
1348         if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1349                         None, cursor[CurResize], CurrentTime) != GrabSuccess)
1350                 return;
1351         XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
1352         for(;;) {
1353                 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask , &ev);
1354                 switch(ev.type) {
1355                 case ButtonRelease:
1356                         XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1357                                         c->w + c->border - 1, c->h + c->border - 1);
1358                         XUngrabPointer(dpy, CurrentTime);
1359                         while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1360                         return;
1361                 case ConfigureRequest:
1362                 case Expose:
1363                 case MapRequest:
1364                         handler[ev.type](&ev);
1365                         break;
1366                 case MotionNotify:
1367                         XSync(dpy, False);
1368                         if((nw = ev.xmotion.x - ocx - 2 * c->border + 1) <= 0)
1369                                 nw = 1;
1370                         if((nh = ev.xmotion.y - ocy - 2 * c->border + 1) <= 0)
1371                                 nh = 1;
1372                         if((m->layout->arrange != floating) && (abs(nw - c->w) > SNAP || abs(nh - c->h) > SNAP))
1373                                 togglefloating(NULL);
1374                         if((m->layout->arrange == floating) || c->isfloating)
1375                                 resize(c, c->x, c->y, nw, nh, True);
1376                         break;
1377                 }
1378         }
1379 }
1380
1381 void
1382 restack(Monitor *m) {
1383         Client *c;
1384         XEvent ev;
1385         XWindowChanges wc;
1386
1387         drawbar(m);
1388         if(!sel)
1389                 return;
1390         if(sel->isfloating || (m->layout->arrange == floating))
1391                 XRaiseWindow(dpy, sel->win);
1392         if(m->layout->arrange != floating) {
1393                 wc.stack_mode = Below;
1394                 wc.sibling = m->barwin;
1395                 if(!sel->isfloating) {
1396                         XConfigureWindow(dpy, sel->win, CWSibling | CWStackMode, &wc);
1397                         wc.sibling = sel->win;
1398                 }
1399                 for(c = nexttiled(clients, m->id); c; c = nexttiled(c->next, m->id)) {
1400                         if(c == sel)
1401                                 continue;
1402                         XConfigureWindow(dpy, c->win, CWSibling | CWStackMode, &wc);
1403                         wc.sibling = c->win;
1404                 }
1405         }
1406         XSync(dpy, False);
1407         while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1408 }
1409
1410 void
1411 run(void) {
1412         char *p;
1413         char buf[sizeof stext];
1414         fd_set rd;
1415         int r, xfd;
1416         unsigned int len, offset;
1417         XEvent ev;
1418
1419         /* main event loop, also reads status text from stdin */
1420         XSync(dpy, False);
1421         xfd = ConnectionNumber(dpy);
1422         readin = True;
1423         offset = 0;
1424         len = sizeof stext - 1;
1425         buf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1426         while(running) {
1427                 FD_ZERO(&rd);
1428                 if(readin)
1429                         FD_SET(STDIN_FILENO, &rd);
1430                 FD_SET(xfd, &rd);
1431                 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1432                         if(errno == EINTR)
1433                                 continue;
1434                         eprint("select failed\n");
1435                 }
1436                 if(FD_ISSET(STDIN_FILENO, &rd)) {
1437                         switch((r = read(STDIN_FILENO, buf + offset, len - offset))) {
1438                         case -1:
1439                                 strncpy(stext, strerror(errno), len);
1440                                 readin = False;
1441                                 break;
1442                         case 0:
1443                                 strncpy(stext, "EOF", 4);
1444                                 readin = False;
1445                                 break;
1446                         default:
1447                                 for(p = buf + offset; r > 0; p++, r--, offset++)
1448                                         if(*p == '\n' || *p == '\0') {
1449                                                 *p = '\0';
1450                                                 strncpy(stext, buf, len);
1451                                                 p += r - 1; /* p is buf + offset + r - 1 */
1452                                                 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1453                                                 offset = r;
1454                                                 if(r)
1455                                                         memmove(buf, p - r + 1, r);
1456                                                 break;
1457                                         }
1458                                 break;
1459                         }
1460                         drawbar(&monitors[selmonitor]);
1461                 }
1462                 while(XPending(dpy)) {
1463                         XNextEvent(dpy, &ev);
1464                         if(handler[ev.type])
1465                                 (handler[ev.type])(&ev); /* call handler */
1466                 }
1467         }
1468 }
1469
1470 void
1471 scan(void) {
1472         unsigned int i, num;
1473         Window *wins, d1, d2;
1474         XWindowAttributes wa;
1475
1476         wins = NULL;
1477         if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1478                 for(i = 0; i < num; i++) {
1479                         if(!XGetWindowAttributes(dpy, wins[i], &wa)
1480                                         || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1481                                 continue;
1482                         if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1483                                 manage(wins[i], &wa);
1484                 }
1485                 for(i = 0; i < num; i++) { /* now the transients */
1486                         if(!XGetWindowAttributes(dpy, wins[i], &wa))
1487                                 continue;
1488                         if(XGetTransientForHint(dpy, wins[i], &d1)
1489                                         && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1490                                 manage(wins[i], &wa);
1491                 }
1492         }
1493         if(wins)
1494                 XFree(wins);
1495 }
1496
1497 void
1498 setclientstate(Client *c, long state) {
1499         long data[] = {state, None};
1500
1501         XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1502                         PropModeReplace, (unsigned char *)data, 2);
1503 }
1504
1505 void
1506 setlayout(const char *arg) {
1507         unsigned int i;
1508         Monitor *m = &monitors[monitorat()];
1509
1510         if(!arg) {
1511                 m->layout++;
1512                 if(m->layout == &layouts[LENGTH(layouts)])
1513                         m->layout = &layouts[0];
1514         }
1515         else {
1516                 for(i = 0; i < LENGTH(layouts); i++)
1517                         if(!strcmp(arg, layouts[i].symbol))
1518                                 break;
1519                 if(i == LENGTH(layouts))
1520                         return;
1521                 m->layout = &layouts[i];
1522         }
1523         if(sel)
1524                 arrange();
1525         else
1526                 drawbar(m);
1527 }
1528
1529 void
1530 setmwfact(const char *arg) {
1531         double delta;
1532
1533         Monitor *m = &monitors[monitorat()];
1534
1535         if(!domwfact)
1536                 return;
1537         /* arg handling, manipulate mwfact */
1538         if(arg == NULL)
1539                 m->mwfact = MWFACT;
1540         else if(sscanf(arg, "%lf", &delta) == 1) {
1541                 if(arg[0] == '+' || arg[0] == '-')
1542                         m->mwfact += delta;
1543                 else
1544                         m->mwfact = delta;
1545                 if(m->mwfact < 0.1)
1546                         m->mwfact = 0.1;
1547                 else if(m->mwfact > 0.9)
1548                         m->mwfact = 0.9;
1549         }
1550         arrange();
1551 }
1552
1553 void
1554 setup(void) {
1555         unsigned int i;
1556         Monitor *m;
1557         XSetWindowAttributes wa;
1558         XineramaScreenInfo *info = NULL;
1559
1560         /* init atoms */
1561         wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1562         wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1563         wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1564         wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1565         netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1566         netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1567
1568         /* init cursors */
1569         wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1570         cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1571         cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1572
1573         // init screens/monitors first
1574         mcount = 1;
1575         if((isxinerama = XineramaIsActive(dpy)))
1576                 info = XineramaQueryScreens(dpy, &mcount);
1577         monitors = emallocz(mcount * sizeof(Monitor));
1578
1579         screen = DefaultScreen(dpy);
1580         root = RootWindow(dpy, screen);
1581
1582         /* init appearance */
1583         dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1584         dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1585         dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1586         dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1587         dc.sel[ColBG] = getcolor(SELBGCOLOR);
1588         dc.sel[ColFG] = getcolor(SELFGCOLOR);
1589         initfont(FONT);
1590         dc.h = bh = dc.font.height + 2;
1591         dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1592         dc.gc = XCreateGC(dpy, root, 0, 0);
1593         XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1594         if(!dc.font.set)
1595                 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1596
1597         for(blw = i = 0; i < LENGTH(layouts); i++) {
1598                 i = textw(layouts[i].symbol);
1599                 if(i > blw)
1600                         blw = i;
1601         }
1602         for(i = 0; i < mcount; i++) {
1603                 /* init geometry */
1604                 m = &monitors[i];
1605                 m->id = i;
1606
1607                 if (mcount != 1 && isxinerama) {
1608                         m->sx = info[i].x_org;
1609                         m->sy = info[i].y_org;
1610                         m->sw = info[i].width;
1611                         m->sh = info[i].height;
1612                         fprintf(stderr, "monitor[%d]: %d,%d,%d,%d\n", i, m->sx, m->sy, m->sw, m->sh);
1613                 }
1614                 else {
1615                         m->sx = 0;
1616                         m->sy = 0;
1617                         m->sw = DisplayWidth(dpy, screen);
1618                         m->sh = DisplayHeight(dpy, screen);
1619                 }
1620
1621                 m->seltags = emallocz(sizeof initags);
1622                 m->prevtags = emallocz(sizeof initags);
1623
1624                 memcpy(m->seltags, initags, sizeof initags);
1625                 memcpy(m->prevtags, initags, sizeof initags);
1626
1627                 /* init layouts */
1628                 m->mwfact = MWFACT;
1629                 m->layout = &layouts[0];
1630
1631                 // TODO: bpos per screen?
1632                 bpos = BARPOS;
1633                 wa.override_redirect = 1;
1634                 wa.background_pixmap = ParentRelative;
1635                 wa.event_mask = ButtonPressMask | ExposureMask;
1636
1637                 /* init bars */
1638                 m->barwin = XCreateWindow(dpy, root, m->sx, m->sy, m->sw, bh, 0,
1639                                 DefaultDepth(dpy, screen), CopyFromParent, DefaultVisual(dpy, screen),
1640                                 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
1641                 XDefineCursor(dpy, m->barwin, cursor[CurNormal]);
1642                 updatebarpos(m);
1643                 XMapRaised(dpy, m->barwin);
1644                 strcpy(stext, "dwm-"VERSION);
1645
1646                 /* EWMH support per monitor */
1647                 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1648                                 PropModeReplace, (unsigned char *) netatom, NetLast);
1649
1650                 /* select for events */
1651                 wa.event_mask = SubstructureRedirectMask | SubstructureNotifyMask
1652                                 | EnterWindowMask | LeaveWindowMask | StructureNotifyMask;
1653                 XChangeWindowAttributes(dpy, root, CWEventMask | CWCursor, &wa);
1654                 XSelectInput(dpy, root, wa.event_mask);
1655
1656                 drawbar(m);
1657         }
1658         if(info)
1659                 XFree(info);
1660
1661         /* grab keys */
1662         grabkeys();
1663
1664         /* init tags */
1665         compileregs();
1666
1667         selmonitor = monitorat();
1668         fprintf(stderr, "selmonitor == %d\n", selmonitor);
1669 }
1670
1671 void
1672 spawn(const char *arg) {
1673         static char *shell = NULL;
1674
1675         if(!shell && !(shell = getenv("SHELL")))
1676                 shell = "/bin/sh";
1677         if(!arg)
1678                 return;
1679         /* The double-fork construct avoids zombie processes and keeps the code
1680          * clean from stupid signal handlers. */
1681         if(fork() == 0) {
1682                 if(fork() == 0) {
1683                         if(dpy)
1684                                 close(ConnectionNumber(dpy));
1685                         setsid();
1686                         execl(shell, shell, "-c", arg, (char *)NULL);
1687                         fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1688                         perror(" failed");
1689                 }
1690                 exit(0);
1691         }
1692         wait(0);
1693 }
1694
1695 void
1696 tag(const char *arg) {
1697         unsigned int i;
1698
1699         if(!sel)
1700                 return;
1701         for(i = 0; i < LENGTH(tags); i++)
1702                 sel->tags[i] = (NULL == arg);
1703         sel->tags[idxoftag(arg)] = True;
1704         arrange();
1705 }
1706
1707 unsigned int
1708 textnw(const char *text, unsigned int len) {
1709         XRectangle r;
1710
1711         if(dc.font.set) {
1712                 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1713                 return r.width;
1714         }
1715         return XTextWidth(dc.font.xfont, text, len);
1716 }
1717
1718 unsigned int
1719 textw(const char *text) {
1720         return textnw(text, strlen(text)) + dc.font.height;
1721 }
1722
1723 void
1724 tile(Monitor *m) {
1725         unsigned int i, n, nx, ny, nw, nh, mw, th;
1726         Client *c, *mc;
1727
1728         domwfact = dozoom = True;
1729
1730         nx = ny = nw = 0; /* gcc stupidity requires this */
1731
1732         for(n = 0, c = nexttiled(clients, m->id); c; c = nexttiled(c->next, m->id))
1733                 n++;
1734
1735         /* window geoms */
1736         mw = (n == 1) ? m->waw : m->mwfact * m->waw;
1737         th = (n > 1) ? m->wah / (n - 1) : 0;
1738         if(n > 1 && th < bh)
1739                 th = m->wah;
1740
1741         for(i = 0, c = mc = nexttiled(clients, m->id); c; c = nexttiled(c->next, m->id)) {
1742                 if(i == 0) { /* master */
1743                         nx = m->wax;
1744                         ny = m->way;
1745                         nw = mw - 2 * c->border;
1746                         nh = m->wah - 2 * c->border;
1747                 }
1748                 else {  /* tile window */
1749                         if(i == 1) {
1750                                 ny = m->way;
1751                                 nx += mc->w + 2 * mc->border;
1752                                 nw = m->waw - mw - 2 * c->border;
1753                         }
1754                         if(i + 1 == n) /* remainder */
1755                                 nh = (m->way + m->wah) - ny - 2 * c->border;
1756                         else
1757                                 nh = th - 2 * c->border;
1758                 }
1759                 resize(c, nx, ny, nw, nh, RESIZEHINTS);
1760                 if((RESIZEHINTS) && ((c->h < bh) || (c->h > nh) || (c->w < bh) || (c->w > nw)))
1761                         /* client doesn't accept size constraints */
1762                         resize(c, nx, ny, nw, nh, False);
1763                 if(n > 1 && th != m->wah)
1764                         ny = c->y + c->h + 2 * c->border;
1765
1766                 i++;
1767         }
1768 }
1769 void
1770 togglebar(const char *arg) {
1771         if(bpos == BarOff)
1772                 bpos = (BARPOS == BarOff) ? BarTop : BARPOS;
1773         else
1774                 bpos = BarOff;
1775         updatebarpos(&monitors[monitorat()]);
1776         arrange();
1777 }
1778
1779 void
1780 togglefloating(const char *arg) {
1781         if(!sel)
1782                 return;
1783         sel->isfloating = !sel->isfloating;
1784         if(sel->isfloating)
1785                 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1786         arrange();
1787 }
1788
1789 void
1790 toggletag(const char *arg) {
1791         unsigned int i, j;
1792
1793         if(!sel)
1794                 return;
1795         i = idxoftag(arg);
1796         sel->tags[i] = !sel->tags[i];
1797         for(j = 0; j < LENGTH(tags) && !sel->tags[j]; j++);
1798         if(j == LENGTH(tags))
1799                 sel->tags[i] = True; /* at least one tag must be enabled */
1800         arrange();
1801 }
1802
1803 void
1804 toggleview(const char *arg) {
1805         unsigned int i, j;
1806
1807         Monitor *m = &monitors[monitorat()];
1808
1809         i = idxoftag(arg);
1810         m->seltags[i] = !m->seltags[i];
1811         for(j = 0; j < LENGTH(tags) && !m->seltags[j]; j++);
1812         if(j == LENGTH(tags))
1813                 m->seltags[i] = True; /* at least one tag must be viewed */
1814         arrange();
1815 }
1816
1817 void
1818 unban(Client *c) {
1819         if(!c->isbanned)
1820                 return;
1821         XMoveWindow(dpy, c->win, c->x, c->y);
1822         c->isbanned = False;
1823 }
1824
1825 void
1826 unmanage(Client *c) {
1827         XWindowChanges wc;
1828
1829         wc.border_width = c->oldborder;
1830         /* The server grab construct avoids race conditions. */
1831         XGrabServer(dpy);
1832         XSetErrorHandler(xerrordummy);
1833         XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1834         detach(c);
1835         detachstack(c);
1836         if(sel == c)
1837                 focus(NULL);
1838         XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1839         setclientstate(c, WithdrawnState);
1840         free(c->tags);
1841         free(c);
1842         XSync(dpy, False);
1843         XSetErrorHandler(xerror);
1844         XUngrabServer(dpy);
1845         arrange();
1846 }
1847
1848 void
1849 unmapnotify(XEvent *e) {
1850         Client *c;
1851         XUnmapEvent *ev = &e->xunmap;
1852
1853         if((c = getclient(ev->window)))
1854                 unmanage(c);
1855 }
1856
1857 void
1858 updatebarpos(Monitor *m) {
1859         XEvent ev;
1860
1861         m->wax = m->sx;
1862         m->way = m->sy;
1863         m->wah = m->sh;
1864         m->waw = m->sw;
1865         switch(bpos) {
1866         default:
1867                 m->wah -= bh;
1868                 m->way += bh;
1869                 XMoveWindow(dpy, m->barwin, m->sx, m->sy);
1870                 break;
1871         case BarBot:
1872                 m->wah -= bh;
1873                 XMoveWindow(dpy, m->barwin, m->sx, m->sy + m->wah);
1874                 break;
1875         case BarOff:
1876                 XMoveWindow(dpy, m->barwin, m->sx, m->sy - bh);
1877                 break;
1878         }
1879         XSync(dpy, False);
1880         while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1881 }
1882
1883 void
1884 updatesizehints(Client *c) {
1885         long msize;
1886         XSizeHints size;
1887
1888         if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1889                 size.flags = PSize;
1890         c->flags = size.flags;
1891         if(c->flags & PBaseSize) {
1892                 c->basew = size.base_width;
1893                 c->baseh = size.base_height;
1894         }
1895         else if(c->flags & PMinSize) {
1896                 c->basew = size.min_width;
1897                 c->baseh = size.min_height;
1898         }
1899         else
1900                 c->basew = c->baseh = 0;
1901         if(c->flags & PResizeInc) {
1902                 c->incw = size.width_inc;
1903                 c->inch = size.height_inc;
1904         }
1905         else
1906                 c->incw = c->inch = 0;
1907         if(c->flags & PMaxSize) {
1908                 c->maxw = size.max_width;
1909                 c->maxh = size.max_height;
1910         }
1911         else
1912                 c->maxw = c->maxh = 0;
1913         if(c->flags & PMinSize) {
1914                 c->minw = size.min_width;
1915                 c->minh = size.min_height;
1916         }
1917         else if(c->flags & PBaseSize) {
1918                 c->minw = size.base_width;
1919                 c->minh = size.base_height;
1920         }
1921         else
1922                 c->minw = c->minh = 0;
1923         if(c->flags & PAspect) {
1924                 c->minax = size.min_aspect.x;
1925                 c->maxax = size.max_aspect.x;
1926                 c->minay = size.min_aspect.y;
1927                 c->maxay = size.max_aspect.y;
1928         }
1929         else
1930                 c->minax = c->maxax = c->minay = c->maxay = 0;
1931         c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1932                         && c->maxw == c->minw && c->maxh == c->minh);
1933 }
1934
1935 void
1936 updatetitle(Client *c) {
1937         if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1938                 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1939 }
1940
1941 void
1942 updatewmhints(Client *c) {
1943         XWMHints *wmh;
1944
1945         if((wmh = XGetWMHints(dpy, c->win))) {
1946                 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1947                 XFree(wmh);
1948         }
1949 }
1950
1951 /* There's no way to check accesses to destroyed windows, thus those cases are
1952  * ignored (especially on UnmapNotify's).  Other types of errors call Xlibs
1953  * default error handler, which may call exit.  */
1954 int
1955 xerror(Display *dpy, XErrorEvent *ee) {
1956         if(ee->error_code == BadWindow
1957         || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1958         || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1959         || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1960         || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1961         || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1962         || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1963         || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1964                 return 0;
1965         fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1966                 ee->request_code, ee->error_code);
1967         return xerrorxlib(dpy, ee); /* may call exit */
1968 }
1969
1970 int
1971 xerrordummy(Display *dsply, XErrorEvent *ee) {
1972         return 0;
1973 }
1974
1975 /* Startup Error handler to check if another window manager
1976  * is already running. */
1977 int
1978 xerrorstart(Display *dsply, XErrorEvent *ee) {
1979         otherwm = True;
1980         return -1;
1981 }
1982
1983 void
1984 view(const char *arg) {
1985         unsigned int i;
1986         Bool tmp[LENGTH(tags)];
1987         Monitor *m = &monitors[monitorat()];
1988
1989         for(i = 0; i < LENGTH(tags); i++)
1990                 tmp[i] = (NULL == arg);
1991         tmp[idxoftag(arg)] = True;
1992         if(memcmp(m->seltags, tmp, sizeof initags) != 0) {
1993                 memcpy(m->prevtags, m->seltags, sizeof initags);
1994                 memcpy(m->seltags, tmp, sizeof initags);
1995                 arrange();
1996         }
1997 }
1998
1999 void
2000 viewprevtag(const char *arg) {
2001         static Bool tmp[LENGTH(tags)];
2002
2003         Monitor *m = &monitors[monitorat()];
2004
2005         memcpy(tmp, m->seltags, sizeof initags);
2006         memcpy(m->seltags, m->prevtags, sizeof initags);
2007         memcpy(m->prevtags, tmp, sizeof initags);
2008         arrange();
2009 }
2010
2011 void
2012 zoom(const char *arg) {
2013         Client *c = sel;
2014
2015         if(!sel || !dozoom || sel->isfloating)
2016                 return;
2017         if(c == nexttiled(clients, c->monitor))
2018                 if(!(c = nexttiled(c->next, c->monitor)))
2019                         return;
2020         detach(c);
2021         attach(c);
2022         focus(c);
2023         arrange();
2024 }
2025
2026 void
2027 movetomonitor(const char *arg) {
2028         if (sel) {
2029                 sel->monitor = arg ? atoi(arg) : (sel->monitor+1) % mcount;
2030
2031                 memcpy(sel->tags, monitors[sel->monitor].seltags, sizeof initags);
2032                 resize(sel, monitors[sel->monitor].wax, monitors[sel->monitor].way, sel->w, sel->h, True);
2033                 arrange();
2034         }
2035 }
2036
2037 void
2038 selectmonitor(const char *arg) {
2039         Monitor *m = &monitors[arg ? atoi(arg) : (monitorat()+1) % mcount];
2040
2041         XWarpPointer(dpy, None, root, 0, 0, 0, 0, m->wax+m->waw/2, m->way+m->wah/2);
2042         focus(NULL);
2043 }
2044
2045
2046 int
2047 main(int argc, char *argv[]) {
2048         if(argc == 2 && !strcmp("-v", argv[1]))
2049                 eprint("dwm-"VERSION", © 2006-2008 Anselm R. Garbe, Sander van Dijk, "
2050                        "Jukka Salmi, Premysl Hruby, Szabolcs Nagy, Christof Musik\n");
2051         else if(argc != 1)
2052                 eprint("usage: dwm [-v]\n");
2053
2054         setlocale(LC_CTYPE, "");
2055         if(!(dpy = XOpenDisplay(0)))
2056                 eprint("dwm: cannot open display\n");
2057
2058         checkotherwm();
2059         setup();
2060         scan();
2061         run();
2062         cleanup();
2063
2064         XCloseDisplay(dpy);
2065         return 0;
2066 }