JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
Remove comment.
[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 switchws(union arg *args)
156 {
157         int                     wsid = args->id;
158         struct ws_win           *win;
159         Window                  winfocus;
160
161         DNPRINTF(SWM_D_WS, "switchws: %d\n", wsid + 1);
162
163         if (wsid == current_ws)
164                 return;
165
166         /* map new window first to prevent ugly blinking */
167         TAILQ_FOREACH (win, &ws[wsid].winlist, entry)
168                 XMapWindow(display, win->id);
169         ws[wsid].visible = 1;
170
171         TAILQ_FOREACH (win, &ws[current_ws].winlist, entry)
172                 XUnmapWindow(display, win->id);
173         ws[current_ws].visible = 0;
174
175         current_ws = wsid;
176
177         ignore_enter = 1;
178         if (ws[wsid].focus != NULL) {
179                 DNPRINTF(SWM_D_WS, "switchws: focus %d\n", ws[wsid].focus);
180                 XSetInputFocus(display, ws[wsid].focus->id, RevertToPointerRoot,
181                     CurrentTime);
182         }
183         XSync(display, False);
184 }
185
186 void
187 focus(union arg *args)
188 {
189         Window                  winfocus, winlostfocus;
190
191         if (ws[current_ws].focus == NULL || ws[current_ws].winno == 0)
192                 return;
193
194         winlostfocus = ws[current_ws].focus->id;
195
196         switch (args->id) {
197         case SWM_ARG_ID_FOCUSPREV:
198                 if (ws[current_ws].focus ==
199                     TAILQ_FIRST(&ws[current_ws].winlist))
200                         ws[current_ws].focus =
201                             TAILQ_LAST(&ws[current_ws].winlist, ws_win_list);
202                 else
203                         ws[current_ws].focus =TAILQ_PREV(ws[current_ws].focus,
204                             ws_win_list, entry);
205                 break;
206
207         case SWM_ARG_ID_FOCUSNEXT:
208                 if (ws[current_ws].focus == TAILQ_LAST(&ws[current_ws].winlist,
209                     ws_win_list))
210                         ws[current_ws].focus =
211                             TAILQ_FIRST(&ws[current_ws].winlist);
212                 else
213                         ws[current_ws].focus =
214                             TAILQ_NEXT(ws[current_ws].focus, entry);
215                 break;
216
217         case SWM_ARG_ID_FOCUSMAIN:
218                 ws[current_ws].focus = TAILQ_FIRST(&ws[current_ws].winlist);;
219                 break;
220
221         default:
222                 return;
223         }
224
225         winfocus = ws[current_ws].focus->id;
226         XSetWindowBorder(display, winlostfocus, 0x888888);
227         XSetWindowBorder(display, winfocus, 0xff0000);
228         XSetInputFocus(display, winfocus, RevertToPointerRoot, CurrentTime);
229         XSync(display, False);
230 }
231
232 /* I know this sucks but it works well enough */
233 void
234 stack(void)
235 {
236         XWindowChanges          wc;
237         struct ws_win           *win;
238         Window                  winfocus = root;
239         int                     i, h, w, x, y, winno, hrh;
240
241         DNPRINTF(SWM_D_EVENT, "stack: workspace: %d\n", current_ws);
242
243         if (ws[current_ws].winno == 0)
244                 return;
245
246         if (ws[current_ws].winno > 1)
247                 w = width / 2;
248         else
249                 w = width;
250
251         if (ws[current_ws].winno > 2)
252                 hrh = height / (ws[current_ws].winno - 1);
253         else
254                 hrh = 0;
255
256         x = 0;
257         y = 0;
258         h = height;
259         i = 0;
260         TAILQ_FOREACH (win, &ws[current_ws].winlist, entry) {
261                 if (i == 1) {
262                         x += w + 2;
263                         w -= 2;
264                 }
265                 if (i != 0 && hrh != 0) {
266                         /* correct the last window for lost pixels */
267                         if (win == TAILQ_LAST(&ws[current_ws].winlist,
268                             ws_win_list)) {
269                                 h = height - (i * hrh);
270                                 if (h == 0)
271                                         h = hrh;
272                                 else
273                                         h += hrh;
274                                 y += hrh;
275                         } else {
276                                 h = hrh - 2;
277                                 /* leave first right hand window at y = 0 */
278                                 if (i > 1)
279                                         y += h + 2;
280                         }
281                 }
282
283                 bzero(&wc, sizeof wc);
284                 wc.x = x;
285                 wc.y = y;
286                 wc.width = w;
287                 wc.height = h;
288                 wc.border_width = 1;
289                 XConfigureWindow(display, win->id, CWX | CWY | CWWidth |
290                     CWHeight | CWBorderWidth, &wc);
291                 if (win == ws[current_ws].focus) {
292                         winfocus = win->id;
293                         XSetWindowBorder(display, win->id, 0xff0000);
294                 } else
295                         XSetWindowBorder(display, win->id, 0x888888);
296                 XMapWindow(display, win->id);
297                 i++;
298         }
299
300         XSetInputFocus(display, winfocus, RevertToPointerRoot, CurrentTime);
301         XSync(display, False);
302 }
303
304 void
305 swap_to_main(union arg *args)
306 {
307         struct ws_win           *tmpwin = TAILQ_FIRST(&ws[current_ws].winlist);
308
309         TAILQ_REMOVE(&ws[current_ws].winlist, tmpwin, entry);
310         TAILQ_INSERT_AFTER(&ws[current_ws].winlist, ws[current_ws].focus,
311             tmpwin, entry);
312         TAILQ_REMOVE(&ws[current_ws].winlist, ws[current_ws].focus, entry);
313         TAILQ_INSERT_HEAD(&ws[current_ws].winlist, ws[current_ws].focus, entry);
314         ws[current_ws].focus = TAILQ_FIRST(&ws[current_ws].winlist);
315         ignore_enter = 2;
316         stack();
317 }
318
319 /* key definitions */
320 struct key {
321         unsigned int            mod;
322         KeySym                  keysym;
323         void                    (*func)(union arg *);
324         union arg               args;
325 } keys[] = {
326         /* modifier             key     function                argument */
327         { MODKEY,               XK_Return,      swap_to_main,   {0} },
328         { MODKEY | ShiftMask,   XK_Return,      spawn,          {0} },
329         { MODKEY | ShiftMask,   XK_q,           quit,           {0} },
330         { MODKEY,               XK_m,           focus,          {.id = SWM_ARG_ID_FOCUSMAIN} },
331         { MODKEY,               XK_1,           switchws,       {.id = 0} },
332         { MODKEY,               XK_2,           switchws,       {.id = 1} },
333         { MODKEY,               XK_3,           switchws,       {.id = 2} },
334         { MODKEY,               XK_4,           switchws,       {.id = 3} },
335         { MODKEY,               XK_5,           switchws,       {.id = 4} },
336         { MODKEY,               XK_6,           switchws,       {.id = 5} },
337         { MODKEY,               XK_7,           switchws,       {.id = 6} },
338         { MODKEY,               XK_8,           switchws,       {.id = 7} },
339         { MODKEY,               XK_9,           switchws,       {.id = 8} },
340         { MODKEY,               XK_0,           switchws,       {.id = 9} },
341         { MODKEY,               XK_Tab,         focus,          {.id = SWM_ARG_ID_FOCUSNEXT} },
342         { MODKEY | ShiftMask,   XK_Tab,         focus,          {.id = SWM_ARG_ID_FOCUSPREV} },
343 };
344
345 void
346 updatenumlockmask(void)
347 {
348         unsigned int            i, j;
349         XModifierKeymap         *modmap;
350
351         numlockmask = 0;
352         modmap = XGetModifierMapping(display);
353         for (i = 0; i < 8; i++)
354                 for (j = 0; j < modmap->max_keypermod; j++)
355                         if (modmap->modifiermap[i * modmap->max_keypermod + j]
356                           == XKeysymToKeycode(display, XK_Num_Lock))
357                                 numlockmask = (1 << i);
358
359         XFreeModifiermap(modmap);
360 }
361
362 void
363 grabkeys(void)
364 {
365         unsigned int            i, j;
366         KeyCode                 code;
367         unsigned int            modifiers[] =
368             { 0, LockMask, numlockmask, numlockmask | LockMask };
369
370         updatenumlockmask();
371
372         XUngrabKey(display, AnyKey, AnyModifier, root);
373         for(i = 0; i < LENGTH(keys); i++) {
374                 if((code = XKeysymToKeycode(display, keys[i].keysym)))
375                         for(j = 0; j < LENGTH(modifiers); j++)
376                                 XGrabKey(display, code,
377                                     keys[i].mod | modifiers[j], root,
378                                     True, GrabModeAsync, GrabModeAsync);
379         }
380 }
381 void
382 expose(XEvent *e)
383 {
384         XExposeEvent            *ev = &e->xexpose;
385
386         DNPRINTF(SWM_D_EVENT, "expose: window: %d\n", ev->window);
387 }
388
389 void
390 keypress(XEvent *e)
391 {
392         unsigned int            i;
393         KeySym                  keysym;
394         XKeyEvent               *ev = &e->xkey;
395
396         DNPRINTF(SWM_D_EVENT, "keypress: window: %d\n", ev->window);
397
398         keysym = XKeycodeToKeysym(display, (KeyCode)ev->keycode, 0);
399         for(i = 0; i < LENGTH(keys); i++)
400                 if(keysym == keys[i].keysym
401                    && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
402                    && keys[i].func)
403                         keys[i].func(&(keys[i].args));
404 }
405
406 void
407 buttonpress(XEvent *e)
408 {
409         XButtonPressedEvent     *ev = &e->xbutton;
410         struct ws_win           *win;
411
412         DNPRINTF(SWM_D_EVENT, "buttonpress: window: %d\n", ev->window);
413
414         if (ev->window == root)
415                 return;
416         if (ev->window == ws[current_ws].focus->id)
417                 return;
418
419         TAILQ_FOREACH(win, &ws[current_ws].winlist, entry)
420                 if (win->id == ev->window) {
421                         /* focus in the clicked window */
422                         XSetWindowBorder(display, ev->window, 0xff0000);
423                         XSetWindowBorder(display,
424                             ws[current_ws].focus->id, 0x888888);
425                         XSetInputFocus(display, ev->window, RevertToPointerRoot,
426                             CurrentTime);
427                         ws[current_ws].focus = win;
428                         XSync(display, False);
429                         break;
430         }
431 }
432
433 void
434 configurerequest(XEvent *e)
435 {
436         XConfigureRequestEvent  *ev = &e->xconfigurerequest;
437         struct ws_win           *win;
438
439         DNPRINTF(SWM_D_EVENT, "configurerequest: window: %d\n", ev->window);
440
441         XSelectInput(display, ev->window, ButtonPressMask | EnterWindowMask |
442             FocusChangeMask);
443
444         if ((win = calloc(1, sizeof(struct ws_win))) == NULL)
445                 errx(1, "calloc: failed to allocate memory for new window");
446
447         win->id = ev->window;
448         TAILQ_INSERT_TAIL(&ws[current_ws].winlist, win, entry);
449         ws[current_ws].focus = win; /* make new win focused */
450         ws[current_ws].winno++;
451         stack();
452 }
453
454 void
455 configurenotify(XEvent *e)
456 {
457         XConfigureEvent         *ev = &e->xconfigure;
458
459         DNPRINTF(SWM_D_EVENT, "configurenotify: window: %d\n", ev->window);
460 }
461
462 void
463 destroynotify(XEvent *e)
464 {
465         size_t                   sz;
466         struct ws_win           *win;
467         XDestroyWindowEvent     *ev = &e->xdestroywindow;
468
469         DNPRINTF(SWM_D_EVENT, "destroynotify: window %d\n", ev->window);
470
471         TAILQ_FOREACH (win, &ws[current_ws].winlist, entry) {
472                 DNPRINTF(SWM_D_EVENT, "trying: %x\n", win->id);
473                 if (ev->window == win->id) {
474                         /* find a window to focus */
475                         ws[current_ws].focus =
476                             TAILQ_PREV(win, ws_win_list,entry);
477                         if (ws[current_ws].focus == NULL)
478                                 ws[current_ws].focus =
479                                     TAILQ_FIRST(&ws[current_ws].winlist);
480         
481                         TAILQ_REMOVE(&ws[current_ws].winlist, win, entry);
482                         free(win);
483                         ws[current_ws].winno--;
484                         break;
485                 }
486         }
487
488         stack();
489 }
490
491 void
492 enternotify(XEvent *e)
493 {
494         XCrossingEvent          *ev = &e->xcrossing;
495         struct ws_win           *win;
496
497         DNPRINTF(SWM_D_EVENT, "enternotify: window: %d\n", ev->window);
498
499         if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) &&
500             ev->window != root)
501                 return;
502         if (ignore_enter) {
503                 /* eat event(s) to prevent autofocus */
504                 ignore_enter--;
505                 return;
506         }
507         TAILQ_FOREACH (win, &ws[current_ws].winlist, entry) {
508                 if (win->id == ev->window) {
509                         XSetInputFocus(display, ev->window, RevertToPointerRoot,
510                             CurrentTime);
511                         XSetWindowBorder(display, ev->window, 0xff0000);
512                         ws[current_ws].focus = win;
513                 } else
514                         XSetWindowBorder(display, win->id, 0x888888);
515         }
516 }
517
518 void
519 focusin(XEvent *e)
520 {
521         XFocusChangeEvent       *ev = &e->xfocus;
522
523         DNPRINTF(SWM_D_EVENT, "focusin: window: %d\n", ev->window);
524
525         if (ev->window == root)
526                 return;
527
528         /*
529          * kill grab for now so that we can cut and paste , this screws up
530          * click to focus
531          */
532         /*
533         DNPRINTF(SWM_D_EVENT, "focusin: window: %d grabbing\n", ev->window);
534         XGrabButton(display, Button1, AnyModifier, ev->window, False,
535             ButtonPress, GrabModeAsync, GrabModeSync, None, None);
536         */
537 }
538
539 void
540 mappingnotify(XEvent *e)
541 {
542         XMappingEvent           *ev = &e->xmapping;
543
544         DNPRINTF(SWM_D_EVENT, "mappingnotify: window: %d\n", ev->window);
545
546         XRefreshKeyboardMapping(ev);
547         if(ev->request == MappingKeyboard)
548                 grabkeys();
549 }
550
551 void
552 maprequest(XEvent *e)
553 {
554         XMapRequestEvent        *ev = &e->xmaprequest;
555
556         DNPRINTF(SWM_D_EVENT, "maprequest: window: %d\n", ev->window);
557 }
558
559 void
560 propertynotify(XEvent *e)
561 {
562         XPropertyEvent          *ev = &e->xproperty;
563
564         DNPRINTF(SWM_D_EVENT, "propertynotify: window: %d\n", ev->window);
565 }
566
567 void
568 unmapnotify(XEvent *e)
569 {
570         XUnmapEvent             *ev = &e->xunmap;
571
572         DNPRINTF(SWM_D_EVENT, "unmapnotify: window: %d\n", ev->window);
573 }
574
575 void                    (*handler[LASTEvent])(XEvent *) = {
576                                 [Expose] = expose,
577                                 [KeyPress] = keypress,
578                                 [ButtonPress] = buttonpress,
579                                 [ConfigureRequest] = configurerequest,
580                                 [ConfigureNotify] = configurenotify,
581                                 [DestroyNotify] = destroynotify,
582                                 [EnterNotify] = enternotify,
583                                 [FocusIn] = focusin,
584                                 [MappingNotify] = mappingnotify,
585                                 [MapRequest] = maprequest,
586                                 [PropertyNotify] = propertynotify,
587                                 [UnmapNotify] = unmapnotify,
588 };
589
590 int
591 xerror_start(Display *d, XErrorEvent *ee)
592 {
593         other_wm = 1;
594         return (-1);
595 }
596
597 int
598 xerror(Display *d, XErrorEvent *ee)
599 {
600         fprintf(stderr, "error: %p %p\n", display, ee);
601
602         return (-1);
603 }
604
605 int
606 active_wm(void)
607 {
608         other_wm = 0;
609         xerrorxlib = XSetErrorHandler(xerror_start);
610
611         /* this causes an error if some other window manager is running */
612         XSelectInput(display, DefaultRootWindow(display),
613             SubstructureRedirectMask);
614         XSync(display, False);
615         if(other_wm)
616                 return (1);
617
618         XSetErrorHandler(xerror);
619         XSync(display, False);
620         return (0);
621 }
622
623 int
624 main(int argc, char *argv[])
625 {
626         XEvent                  e;
627         int                     i;
628
629         fprintf(stderr, "Welcome to scrotwm V%s\n", SWM_VERSION);
630         if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
631                 warnx("no locale support");
632
633         if(!(display = XOpenDisplay(0)))
634                 errx(1, "can not open display");
635
636         if (active_wm())
637                 errx(1, "other wm running");
638
639         screen = DefaultScreen(display);
640         root = RootWindow(display, screen);
641         width = DisplayWidth(display, screen) - 2;
642         height = DisplayHeight(display, screen) - 2;
643
644         /* make work space 1 active */
645         ws[0].visible = 1;
646         ws[0].focus = NULL;
647         ws[0].winno = 0;
648         TAILQ_INIT(&ws[0].winlist);
649         for (i = 1; i < SWM_WS_MAX; i++) {
650                 ws[i].visible = 0;
651                 ws[i].focus = NULL;
652                 ws[i].winno = 0;
653                 TAILQ_INIT(&ws[i].winlist);
654         }
655
656         XSelectInput(display, root, SubstructureRedirectMask |
657             SubstructureNotifyMask | ButtonPressMask | KeyPressMask |
658             EnterWindowMask | LeaveWindowMask | StructureNotifyMask |
659             FocusChangeMask | PropertyChangeMask);
660
661         grabkeys();
662
663         while (running) {
664                 XNextEvent(display, &e);
665                 if (handler[e.type])
666                         handler[e.type](&e);
667         }
668
669         XCloseDisplay(display);
670
671         return (0);
672 }