JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
Consolidate all focus stuff into discrete functions.
[spectrwm.git] / scrotwm.c
1 /* $scrotwm$
2 /*
3  * Copyright (c) 2009 Marco Peereboom <marco@peereboom.us>
4  * Copyright (c) 2009 Ryan McBride <mcbride@countersiege.com>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 /*
19  * Much code and ideas taken from dwm under the following license:
20  * MIT/X Consortium License
21  * 
22  * 2006-2008 Anselm R Garbe <garbeam at gmail dot com>
23  * 2006-2007 Sander van Dijk <a dot h dot vandijk at gmail dot com>
24  * 2006-2007 Jukka Salmi <jukka at salmi dot ch>
25  * 2007 Premysl Hruby <dfenze at gmail dot com>
26  * 2007 Szabolcs Nagy <nszabolcs at gmail dot com>
27  * 2007 Christof Musik <christof at sendfax dot de>
28  * 2007-2008 Enno Gottox Boland <gottox at s01 dot de>
29  * 2007-2008 Peter Hartlich <sgkkr at hartlich dot com>
30  * 2008 Martin Hurton <martin dot hurton at gmail dot com>
31  * 
32  * Permission is hereby granted, free of charge, to any person obtaining a
33  * copy of this software and associated documentation files (the "Software"),
34  * to deal in the Software without restriction, including without limitation
35  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
36  * and/or sell copies of the Software, and to permit persons to whom the
37  * Software is furnished to do so, subject to the following conditions:
38  * 
39  * The above copyright notice and this permission notice shall be included in
40  * all copies or substantial portions of the Software.
41  * 
42  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
43  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
44  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
45  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
46  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
47  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
48  * DEALINGS IN THE SOFTWARE.
49  */
50
51 #define SWM_VERSION     "0.5"
52
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <err.h>
56 #include <locale.h>
57 #include <unistd.h>
58
59 #include <sys/types.h>
60 #include <sys/wait.h>
61 #include <sys/queue.h>
62
63 #include <X11/cursorfont.h>
64 #include <X11/keysym.h>
65 #include <X11/Xatom.h>
66 #include <X11/Xlib.h>
67 #include <X11/Xproto.h>
68 #include <X11/Xutil.h>
69
70 /* #define SWM_DEBUG */
71 #ifdef SWM_DEBUG
72 #define DPRINTF(x...)           do { if (swm_debug) fprintf(stderr, x); } while(0)
73 #define DNPRINTF(n,x...)        do { if (swm_debug & n) fprintf(stderr, x); } while(0)
74 #define SWM_D_EVENT             0x0001
75 #define SWM_D_WS                0x0002
76
77 uint32_t                swm_debug = 0
78                             | SWM_D_EVENT
79                             | SWM_D_WS
80                             ;
81 #else
82 #define DPRINTF(x...)
83 #define DNPRINTF(n,x...)
84 #endif
85
86 #define LENGTH(x)               (sizeof x / sizeof x[0])
87 #define MODKEY                  Mod1Mask
88 #define CLEANMASK(mask)         (mask & ~(numlockmask | LockMask))
89
90 int                     (*xerrorxlib)(Display *, XErrorEvent *);
91 int                     other_wm;
92 int                     screen;
93 int                     width, height;
94 int                     running = 1;
95 int                     ignore_enter = 0;
96 unsigned int            numlockmask = 0;
97 Display                 *display;
98 Window                  root;
99
100 struct ws_win {
101         TAILQ_ENTRY(ws_win)     entry;
102         Window                  id;
103 };
104
105 TAILQ_HEAD(ws_win_list, ws_win);
106
107 /* define work spaces */
108 #define SWM_WS_MAX              (10)
109 struct workspace {
110         int                      visible;       /* workspace visible */
111         struct ws_win           *focus;         /* which win has focus */
112         int                      winno;         /* total nr of windows */
113         struct ws_win_list       winlist;
114 } ws[SWM_WS_MAX];
115 int                     current_ws = 0;
116
117 /* args to functions */
118 union arg {
119         int             id;
120 #define SWM_ARG_ID_FOCUSNEXT    (0)
121 #define SWM_ARG_ID_FOCUSPREV    (1)
122 #define SWM_ARG_ID_FOCUSMAIN    (2)
123 };
124
125 void
126 quit(union arg *args)
127 {
128         running = 0;
129 }
130
131 void
132 spawn(union arg *args)
133 {
134         char                    *argv[] = { "xterm", NULL }; /* XXX make this in args */
135
136         /*
137          * The double-fork construct avoids zombie processes and keeps the code
138          * clean from stupid signal handlers.
139          */
140         if(fork() == 0) {
141                 if(fork() == 0) {
142                         if(display)
143                                 close(ConnectionNumber(display));
144                         setsid();
145                         execvp(argv[0], argv);
146                         fprintf(stderr, "execvp failed\n");
147                         perror(" failed");
148                 }
149                 exit(0);
150         }
151         wait(0);
152 }
153
154 void
155 focus_win(struct ws_win *win)
156 {
157         XSetWindowBorder(display, win->id, 0xff0000);
158         XSetInputFocus(display, win->id, RevertToPointerRoot, CurrentTime);
159         ws[current_ws].focus = win;
160 }
161
162 void
163 unfocus_win(struct ws_win *win)
164 {
165         XSetWindowBorder(display, win->id, 0x888888);
166         if (ws[current_ws].focus == win)
167                 ws[current_ws].focus = NULL;
168 }
169
170 void
171 switchws(union arg *args)
172 {
173         int                     wsid = args->id;
174         struct ws_win           *win;
175         Window                  winfocus;
176
177         DNPRINTF(SWM_D_WS, "switchws: %d\n", wsid + 1);
178
179         if (wsid == current_ws)
180                 return;
181
182         /* map new window first to prevent ugly blinking */
183         TAILQ_FOREACH (win, &ws[wsid].winlist, entry)
184                 XMapWindow(display, win->id);
185         ws[wsid].visible = 1;
186
187         TAILQ_FOREACH (win, &ws[current_ws].winlist, entry)
188                 XUnmapWindow(display, win->id);
189         ws[current_ws].visible = 0;
190
191         current_ws = wsid;
192
193         ignore_enter = 1;
194         if (ws[wsid].focus != NULL)
195                 focus_win(ws[wsid].focus);
196         XSync(display, False);
197 }
198
199 void
200 focus(union arg *args)
201 {
202         struct ws_win           *winfocus, *winlostfocus;
203
204         if (ws[current_ws].focus == NULL || ws[current_ws].winno == 0)
205                 return;
206
207         winlostfocus = ws[current_ws].focus;
208
209         switch (args->id) {
210         case SWM_ARG_ID_FOCUSPREV:
211                 if (ws[current_ws].focus ==
212                     TAILQ_FIRST(&ws[current_ws].winlist))
213                         ws[current_ws].focus =
214                             TAILQ_LAST(&ws[current_ws].winlist, ws_win_list);
215                 else
216                         ws[current_ws].focus =TAILQ_PREV(ws[current_ws].focus,
217                             ws_win_list, entry);
218                 break;
219
220         case SWM_ARG_ID_FOCUSNEXT:
221                 if (ws[current_ws].focus == TAILQ_LAST(&ws[current_ws].winlist,
222                     ws_win_list))
223                         ws[current_ws].focus =
224                             TAILQ_FIRST(&ws[current_ws].winlist);
225                 else
226                         ws[current_ws].focus =
227                             TAILQ_NEXT(ws[current_ws].focus, entry);
228                 break;
229
230         case SWM_ARG_ID_FOCUSMAIN:
231                 ws[current_ws].focus = TAILQ_FIRST(&ws[current_ws].winlist);;
232                 break;
233
234         default:
235                 return;
236         }
237
238         winfocus = ws[current_ws].focus;
239         unfocus_win(winlostfocus);
240         focus_win(winfocus);
241         XSync(display, False);
242 }
243
244 /* I know this sucks but it works well enough */
245 void
246 stack(void)
247 {
248         XWindowChanges          wc;
249         struct ws_win           wf, *win, *winfocus = &wf;
250         int                     i, h, w, x, y, winno, hrh;
251
252         DNPRINTF(SWM_D_EVENT, "stack: workspace: %d\n", current_ws);
253
254         winfocus->id = root;
255
256         if (ws[current_ws].winno == 0)
257                 return;
258
259         if (ws[current_ws].winno > 1)
260                 w = width / 2;
261         else
262                 w = width;
263
264         if (ws[current_ws].winno > 2)
265                 hrh = height / (ws[current_ws].winno - 1);
266         else
267                 hrh = 0;
268
269         x = 0;
270         y = 0;
271         h = height;
272         i = 0;
273         TAILQ_FOREACH (win, &ws[current_ws].winlist, entry) {
274                 if (i == 1) {
275                         x += w + 2;
276                         w -= 2;
277                 }
278                 if (i != 0 && hrh != 0) {
279                         /* correct the last window for lost pixels */
280                         if (win == TAILQ_LAST(&ws[current_ws].winlist,
281                             ws_win_list)) {
282                                 h = height - (i * hrh);
283                                 if (h == 0)
284                                         h = hrh;
285                                 else
286                                         h += hrh;
287                                 y += hrh;
288                         } else {
289                                 h = hrh - 2;
290                                 /* leave first right hand window at y = 0 */
291                                 if (i > 1)
292                                         y += h + 2;
293                         }
294                 }
295
296                 bzero(&wc, sizeof wc);
297                 wc.x = x;
298                 wc.y = y;
299                 wc.width = w;
300                 wc.height = h;
301                 wc.border_width = 1;
302                 XConfigureWindow(display, win->id, CWX | CWY | CWWidth |
303                     CWHeight | CWBorderWidth, &wc);
304                 if (win == ws[current_ws].focus)
305                         winfocus = win;
306                 else
307                         unfocus_win(win);
308                 XMapWindow(display, win->id);
309                 i++;
310         }
311
312         focus_win(winfocus);
313         XSync(display, False);
314 }
315
316 void
317 swap_to_main(union arg *args)
318 {
319         struct ws_win           *tmpwin = TAILQ_FIRST(&ws[current_ws].winlist);
320
321         TAILQ_REMOVE(&ws[current_ws].winlist, tmpwin, entry);
322         TAILQ_INSERT_AFTER(&ws[current_ws].winlist, ws[current_ws].focus,
323             tmpwin, entry);
324         TAILQ_REMOVE(&ws[current_ws].winlist, ws[current_ws].focus, entry);
325         TAILQ_INSERT_HEAD(&ws[current_ws].winlist, ws[current_ws].focus, entry);
326         ws[current_ws].focus = TAILQ_FIRST(&ws[current_ws].winlist);
327         ignore_enter = 2;
328         stack();
329 }
330
331 /* key definitions */
332 struct key {
333         unsigned int            mod;
334         KeySym                  keysym;
335         void                    (*func)(union arg *);
336         union arg               args;
337 } keys[] = {
338         /* modifier             key     function                argument */
339         { MODKEY,               XK_Return,      swap_to_main,   {0} },
340         { MODKEY | ShiftMask,   XK_Return,      spawn,          {0} },
341         { MODKEY | ShiftMask,   XK_q,           quit,           {0} },
342         { MODKEY,               XK_m,           focus,          {.id = SWM_ARG_ID_FOCUSMAIN} },
343         { MODKEY,               XK_1,           switchws,       {.id = 0} },
344         { MODKEY,               XK_2,           switchws,       {.id = 1} },
345         { MODKEY,               XK_3,           switchws,       {.id = 2} },
346         { MODKEY,               XK_4,           switchws,       {.id = 3} },
347         { MODKEY,               XK_5,           switchws,       {.id = 4} },
348         { MODKEY,               XK_6,           switchws,       {.id = 5} },
349         { MODKEY,               XK_7,           switchws,       {.id = 6} },
350         { MODKEY,               XK_8,           switchws,       {.id = 7} },
351         { MODKEY,               XK_9,           switchws,       {.id = 8} },
352         { MODKEY,               XK_0,           switchws,       {.id = 9} },
353         { MODKEY,               XK_Tab,         focus,          {.id = SWM_ARG_ID_FOCUSNEXT} },
354         { MODKEY | ShiftMask,   XK_Tab,         focus,          {.id = SWM_ARG_ID_FOCUSPREV} },
355 };
356
357 void
358 updatenumlockmask(void)
359 {
360         unsigned int            i, j;
361         XModifierKeymap         *modmap;
362
363         numlockmask = 0;
364         modmap = XGetModifierMapping(display);
365         for (i = 0; i < 8; i++)
366                 for (j = 0; j < modmap->max_keypermod; j++)
367                         if (modmap->modifiermap[i * modmap->max_keypermod + j]
368                           == XKeysymToKeycode(display, XK_Num_Lock))
369                                 numlockmask = (1 << i);
370
371         XFreeModifiermap(modmap);
372 }
373
374 void
375 grabkeys(void)
376 {
377         unsigned int            i, j;
378         KeyCode                 code;
379         unsigned int            modifiers[] =
380             { 0, LockMask, numlockmask, numlockmask | LockMask };
381
382         updatenumlockmask();
383
384         XUngrabKey(display, AnyKey, AnyModifier, root);
385         for(i = 0; i < LENGTH(keys); i++) {
386                 if((code = XKeysymToKeycode(display, keys[i].keysym)))
387                         for(j = 0; j < LENGTH(modifiers); j++)
388                                 XGrabKey(display, code,
389                                     keys[i].mod | modifiers[j], root,
390                                     True, GrabModeAsync, GrabModeAsync);
391         }
392 }
393 void
394 expose(XEvent *e)
395 {
396         XExposeEvent            *ev = &e->xexpose;
397
398         DNPRINTF(SWM_D_EVENT, "expose: window: %d\n", ev->window);
399 }
400
401 void
402 keypress(XEvent *e)
403 {
404         unsigned int            i;
405         KeySym                  keysym;
406         XKeyEvent               *ev = &e->xkey;
407
408         DNPRINTF(SWM_D_EVENT, "keypress: window: %d\n", ev->window);
409
410         keysym = XKeycodeToKeysym(display, (KeyCode)ev->keycode, 0);
411         for(i = 0; i < LENGTH(keys); i++)
412                 if(keysym == keys[i].keysym
413                    && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
414                    && keys[i].func)
415                         keys[i].func(&(keys[i].args));
416 }
417
418 void
419 buttonpress(XEvent *e)
420 {
421         XButtonPressedEvent     *ev = &e->xbutton;
422         struct ws_win           *win;
423
424         DNPRINTF(SWM_D_EVENT, "buttonpress: window: %d\n", ev->window);
425
426         if (ev->window == root)
427                 return;
428         if (ev->window == ws[current_ws].focus->id)
429                 return;
430 #if 0
431         TAILQ_FOREACH(win, &ws[current_ws].winlist, entry)
432                 if (win->id == ev->window) {
433                         /* focus in the clicked window */
434                         XSetWindowBorder(display, ev->window, 0xff0000);
435                         XSetWindowBorder(display,
436                             ws[current_ws].focus->id, 0x888888);
437                         XSetInputFocus(display, ev->window, RevertToPointerRoot,
438                             CurrentTime);
439                         ws[current_ws].focus = win;
440                         XSync(display, False);
441                         break;
442         }
443 #endif
444 }
445
446 void
447 configurerequest(XEvent *e)
448 {
449         XConfigureRequestEvent  *ev = &e->xconfigurerequest;
450         struct ws_win           *win;
451
452         DNPRINTF(SWM_D_EVENT, "configurerequest: window: %d\n", ev->window);
453
454         XSelectInput(display, ev->window, ButtonPressMask | EnterWindowMask |
455             FocusChangeMask);
456
457         if ((win = calloc(1, sizeof(struct ws_win))) == NULL)
458                 errx(1, "calloc: failed to allocate memory for new window");
459
460         win->id = ev->window;
461         TAILQ_INSERT_TAIL(&ws[current_ws].winlist, win, entry);
462         ws[current_ws].focus = win; /* make new win focused */
463         ws[current_ws].winno++;
464         stack();
465 }
466
467 void
468 configurenotify(XEvent *e)
469 {
470         XConfigureEvent         *ev = &e->xconfigure;
471
472         DNPRINTF(SWM_D_EVENT, "configurenotify: window: %d\n", ev->window);
473 }
474
475 void
476 destroynotify(XEvent *e)
477 {
478         size_t                   sz;
479         struct ws_win           *win;
480         XDestroyWindowEvent     *ev = &e->xdestroywindow;
481
482         DNPRINTF(SWM_D_EVENT, "destroynotify: window %d\n", ev->window);
483
484         TAILQ_FOREACH (win, &ws[current_ws].winlist, entry) {
485                 DNPRINTF(SWM_D_EVENT, "trying: %x\n", win->id);
486                 if (ev->window == win->id) {
487                         /* find a window to focus */
488                         ws[current_ws].focus =
489                             TAILQ_PREV(win, ws_win_list,entry);
490                         if (ws[current_ws].focus == NULL)
491                                 ws[current_ws].focus =
492                                     TAILQ_FIRST(&ws[current_ws].winlist);
493         
494                         TAILQ_REMOVE(&ws[current_ws].winlist, win, entry);
495                         free(win);
496                         ws[current_ws].winno--;
497                         break;
498                 }
499         }
500
501         stack();
502 }
503
504 void
505 enternotify(XEvent *e)
506 {
507         XCrossingEvent          *ev = &e->xcrossing;
508         struct ws_win           *win;
509
510         DNPRINTF(SWM_D_EVENT, "enternotify: window: %d\n", ev->window);
511
512         if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) &&
513             ev->window != root)
514                 return;
515         if (ignore_enter) {
516                 /* eat event(s) to prevent autofocus */
517                 ignore_enter--;
518                 return;
519         }
520         TAILQ_FOREACH (win, &ws[current_ws].winlist, entry) {
521                 if (win->id == ev->window)
522                         focus_win(win);
523                 else
524                         unfocus_win(win);
525         }
526 }
527
528 void
529 focusin(XEvent *e)
530 {
531         XFocusChangeEvent       *ev = &e->xfocus;
532
533         DNPRINTF(SWM_D_EVENT, "focusin: window: %d\n", ev->window);
534
535         if (ev->window == root)
536                 return;
537
538         /*
539          * kill grab for now so that we can cut and paste , this screws up
540          * click to focus
541          */
542         /*
543         DNPRINTF(SWM_D_EVENT, "focusin: window: %d grabbing\n", ev->window);
544         XGrabButton(display, Button1, AnyModifier, ev->window, False,
545             ButtonPress, GrabModeAsync, GrabModeSync, None, None);
546         */
547 }
548
549 void
550 mappingnotify(XEvent *e)
551 {
552         XMappingEvent           *ev = &e->xmapping;
553
554         DNPRINTF(SWM_D_EVENT, "mappingnotify: window: %d\n", ev->window);
555
556         XRefreshKeyboardMapping(ev);
557         if(ev->request == MappingKeyboard)
558                 grabkeys();
559 }
560
561 void
562 maprequest(XEvent *e)
563 {
564         XMapRequestEvent        *ev = &e->xmaprequest;
565
566         DNPRINTF(SWM_D_EVENT, "maprequest: window: %d\n", ev->window);
567 }
568
569 void
570 propertynotify(XEvent *e)
571 {
572         XPropertyEvent          *ev = &e->xproperty;
573
574         DNPRINTF(SWM_D_EVENT, "propertynotify: window: %d\n", ev->window);
575 }
576
577 void
578 unmapnotify(XEvent *e)
579 {
580         XUnmapEvent             *ev = &e->xunmap;
581
582         DNPRINTF(SWM_D_EVENT, "unmapnotify: window: %d\n", ev->window);
583 }
584
585 void                    (*handler[LASTEvent])(XEvent *) = {
586                                 [Expose] = expose,
587                                 [KeyPress] = keypress,
588                                 [ButtonPress] = buttonpress,
589                                 [ConfigureRequest] = configurerequest,
590                                 [ConfigureNotify] = configurenotify,
591                                 [DestroyNotify] = destroynotify,
592                                 [EnterNotify] = enternotify,
593                                 [FocusIn] = focusin,
594                                 [MappingNotify] = mappingnotify,
595                                 [MapRequest] = maprequest,
596                                 [PropertyNotify] = propertynotify,
597                                 [UnmapNotify] = unmapnotify,
598 };
599
600 int
601 xerror_start(Display *d, XErrorEvent *ee)
602 {
603         other_wm = 1;
604         return (-1);
605 }
606
607 int
608 xerror(Display *d, XErrorEvent *ee)
609 {
610         fprintf(stderr, "error: %p %p\n", display, ee);
611
612         return (-1);
613 }
614
615 int
616 active_wm(void)
617 {
618         other_wm = 0;
619         xerrorxlib = XSetErrorHandler(xerror_start);
620
621         /* this causes an error if some other window manager is running */
622         XSelectInput(display, DefaultRootWindow(display),
623             SubstructureRedirectMask);
624         XSync(display, False);
625         if(other_wm)
626                 return (1);
627
628         XSetErrorHandler(xerror);
629         XSync(display, False);
630         return (0);
631 }
632
633 int
634 main(int argc, char *argv[])
635 {
636         XEvent                  e;
637         int                     i;
638
639         fprintf(stderr, "Welcome to scrotwm V%s\n", SWM_VERSION);
640         if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
641                 warnx("no locale support");
642
643         if(!(display = XOpenDisplay(0)))
644                 errx(1, "can not open display");
645
646         if (active_wm())
647                 errx(1, "other wm running");
648
649         screen = DefaultScreen(display);
650         root = RootWindow(display, screen);
651         width = DisplayWidth(display, screen) - 2;
652         height = DisplayHeight(display, screen) - 2;
653
654         /* make work space 1 active */
655         ws[0].visible = 1;
656         ws[0].focus = NULL;
657         ws[0].winno = 0;
658         TAILQ_INIT(&ws[0].winlist);
659         for (i = 1; i < SWM_WS_MAX; i++) {
660                 ws[i].visible = 0;
661                 ws[i].focus = NULL;
662                 ws[i].winno = 0;
663                 TAILQ_INIT(&ws[i].winlist);
664         }
665
666         XSelectInput(display, root, SubstructureRedirectMask |
667             SubstructureNotifyMask | ButtonPressMask | KeyPressMask |
668             EnterWindowMask | LeaveWindowMask | StructureNotifyMask |
669             FocusChangeMask | PropertyChangeMask);
670
671         grabkeys();
672
673         while (running) {
674                 XNextEvent(display, &e);
675                 if (handler[e.type])
676                         handler[e.type](&e);
677         }
678
679         XCloseDisplay(display);
680
681         return (0);
682 }