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