From http://www.jwz.org/xscreensaver/xscreensaver-5.30.tar.gz
[xscreensaver] / utils / textclient.c
1 /* xscreensaver, Copyright (c) 2012-2014 Jamie Zawinski <jwz@jwz.org>
2  *
3  * Permission to use, copy, modify, distribute, and sell this software and its
4  * documentation for any purpose is hereby granted without fee, provided that
5  * the above copyright notice appear in all copies and that both that
6  * copyright notice and this permission notice appear in supporting
7  * documentation.  No representations are made about the suitability of this
8  * software for any purpose.  It is provided "as is" without express or 
9  * implied warranty.
10  *
11  * Running programs under a pipe or pty and returning bytes from them.
12  * Uses these X resources:
13  * 
14  * program:             What to run.  Usually "xscreensaver-text".
15  * relaunchDelay: secs  How long after the command dies before restarting.
16  * usePty: bool         Whether to run the command interactively.
17  * metaSendsESC: bool   Whether to send Alt-x as ESC x in pty-mode.
18  * swapBSDEL: bool      Swap Backspace and Delete in pty-mode.
19  */
20
21 #include "utils.h"
22
23 #ifndef USE_IPHONE /* whole file -- see OSX/iostextclient.m */
24
25 #include "textclient.h"
26 #include "resources.h"
27
28 #ifndef HAVE_COCOA
29 # define XK_MISCELLANY
30 # include <X11/keysymdef.h>
31 # include <X11/Xatom.h>
32 # include <X11/Intrinsic.h>
33 #endif
34
35 #include <stdio.h>
36
37 #include <signal.h>
38 #include <sys/wait.h>
39
40 #ifdef HAVE_UNISTD_H
41 # include <unistd.h>
42 # include <fcntl.h>  /* for O_RDWR */
43 #endif
44
45 #ifdef HAVE_FORKPTY
46 # include <sys/ioctl.h>
47 # ifdef HAVE_PTY_H
48 #  include <pty.h>
49 # endif
50 # ifdef HAVE_UTIL_H
51 #  include <util.h>
52 # endif
53 #endif /* HAVE_FORKPTY */
54
55 #undef DEBUG
56
57 extern const char *progname;
58
59 struct text_data {
60   Display *dpy;
61   char *program;
62   int pix_w, pix_h, char_w, char_h;
63   int max_lines;
64
65   Bool pty_p;
66   XtIntervalId pipe_timer;
67   FILE *pipe;
68   pid_t pid;
69   XtInputId pipe_id;
70   Bool input_available_p;
71   Time subproc_relaunch_delay;
72   XComposeStatus compose;
73
74   Bool meta_sends_esc_p;
75   Bool swap_bs_del_p;
76   Bool meta_done_once;
77   unsigned int meta_mask;
78
79   const char *out_buffer;
80   int out_column;
81 };
82
83
84 static void
85 subproc_cb (XtPointer closure, int *source, XtInputId *id)
86 {
87   text_data *d = (text_data *) closure;
88 # ifdef DEBUG
89   if (! d->input_available_p)
90     fprintf (stderr, "%s: textclient: input available\n", progname);
91 # endif
92   d->input_available_p = True;
93 }
94
95
96 static void
97 launch_text_generator (text_data *d)
98 {
99   XtAppContext app = XtDisplayToApplicationContext (d->dpy);
100   char buf[255];
101   const char *oprogram = d->program;
102   char *program = (char *) malloc (strlen (oprogram) + 50);
103
104   strcpy (program, "( ");
105   strcat (program, oprogram);
106
107   /* Kludge!  Special-case "xscreensaver-text" to tell it how wide
108      the screen is.  We used to do this by just always feeding
109      `program' through sprintf() and setting the default value to
110      "xscreensaver-text --cols %d", but that makes things blow up
111      if someone ever uses a --program that includes a % anywhere.
112    */
113   if (!strcmp (oprogram, "xscreensaver-text"))
114     {
115       if (d->char_w)
116         sprintf (program + strlen(program), " --cols %d", d->char_w);
117       if (d->max_lines)
118         sprintf (program + strlen(program), " --lines %d", d->max_lines);
119     }
120
121   strcat (program, " ) 2>&1");
122
123 # ifdef DEBUG
124   fprintf (stderr, "%s: textclient: launch %s: %s\n", progname, 
125            (d->pty_p ? "pty" : "pipe"), program);
126 # endif
127
128 #ifdef HAVE_FORKPTY
129   if (d->pty_p)
130     {
131       int fd;
132       struct winsize ws;
133       
134       ws.ws_col = d->char_w;
135       ws.ws_row = d->char_h;
136       ws.ws_xpixel = d->pix_w;
137       ws.ws_ypixel = d->pix_h;
138       
139       d->pipe = 0;
140       if ((d->pid = forkpty(&fd, NULL, NULL, &ws)) < 0)
141         {
142           /* Unable to fork */
143           sprintf (buf, "%.100s: forkpty", progname);
144           perror (buf);
145         }
146       else if (!d->pid)
147         {
148           /* This is the child fork. */
149           char *av[10];
150           int i = 0;
151           if (putenv ("TERM=vt100"))
152             abort();
153           av[i++] = "/bin/sh";
154           av[i++] = "-c";
155           av[i++] = program;
156           av[i] = 0;
157           execvp (av[0], av);
158           sprintf (buf, "%.100s: %.100s", progname, oprogram);
159           perror (buf);
160           exit (1);
161         }
162       else
163         {
164           /* This is the parent fork. */
165           if (d->pipe) abort();
166           d->pipe = fdopen (fd, "r+");
167           if (d->pipe_id) abort();
168           d->pipe_id =
169             XtAppAddInput (app, fileno (d->pipe),
170                            (XtPointer) (XtInputReadMask | XtInputExceptMask),
171                            subproc_cb, (XtPointer) d);
172 # ifdef DEBUG
173           fprintf (stderr, "%s: textclient: pid = %d\n", progname, d->pid);
174 # endif
175         }
176     }
177   else
178 #endif /* HAVE_FORKPTY */
179     {
180       /* don't mess up controlling terminal on "-pipe -program tcsh". */
181       static int protected_stdin_p = 0;
182       if (! protected_stdin_p) {
183         fclose (stdin);
184         open ("/dev/null", O_RDWR); /* re-allocate fd 0 */
185         protected_stdin_p = 1;
186       }
187
188       if (d->pipe) abort();
189       if ((d->pipe = popen (program, "r")))
190         {
191           if (d->pipe_id) abort();
192           d->pipe_id =
193             XtAppAddInput (app, fileno (d->pipe),
194                            (XtPointer) (XtInputReadMask | XtInputExceptMask),
195                            subproc_cb, (XtPointer) d);
196 # ifdef DEBUG
197           fprintf (stderr, "%s: textclient: popen\n", progname);
198 # endif
199         }
200       else
201         {
202           sprintf (buf, "%.100s: %.100s", progname, program);
203           perror (buf);
204         }
205     }
206
207   free (program);
208 }
209
210
211 static void
212 relaunch_generator_timer (XtPointer closure, XtIntervalId *id)
213 {
214   text_data *d = (text_data *) closure;
215   /* if (!d->pipe_timer) abort(); */
216   d->pipe_timer = 0;
217 # ifdef DEBUG
218   fprintf (stderr, "%s: textclient: launch timer fired\n", progname);
219 # endif
220   launch_text_generator (d);
221 }
222
223
224 static void
225 start_timer (text_data *d)
226 {
227   XtAppContext app = XtDisplayToApplicationContext (d->dpy);
228
229 # ifdef DEBUG
230   fprintf (stderr, "%s: textclient: relaunching in %d\n", progname, 
231            (int) d->subproc_relaunch_delay);
232 # endif
233   if (d->pipe_timer)
234     XtRemoveTimeOut (d->pipe_timer);
235   d->pipe_timer =
236     XtAppAddTimeOut (app, d->subproc_relaunch_delay,
237                      relaunch_generator_timer,
238                      (XtPointer) d);
239 }
240
241
242 static void
243 close_pipe (text_data *d)
244 {
245   if (d->pid)
246     {
247 # ifdef DEBUG
248       fprintf (stderr, "%s: textclient: kill %d\n", progname, d->pid);
249 # endif
250       kill (d->pid, SIGTERM);
251     }
252   d->pid = 0;
253
254   if (d->pipe_id)
255     XtRemoveInput (d->pipe_id);
256   d->pipe_id = 0;
257
258   if (d->pipe)
259     {
260 # ifdef DEBUG
261       fprintf (stderr, "%s: textclient: pclose\n", progname);
262 # endif
263       pclose (d->pipe);
264     }
265   d->pipe = 0;
266
267
268 }
269
270
271 void
272 textclient_reshape (text_data *d,
273                     int pix_w, int pix_h,
274                     int char_w, int char_h,
275                     int max_lines)
276 {
277 # if defined(HAVE_FORKPTY) && defined(TIOCSWINSZ)
278
279   d->pix_w  = pix_w;
280   d->pix_h  = pix_h;
281   d->char_w = char_w;
282   d->char_h = char_h;
283   d->max_lines = max_lines;
284
285 # ifdef DEBUG
286   fprintf (stderr, "%s: textclient: reshape: %dx%d, %dx%d\n", progname,
287            pix_w, pix_h, char_w, char_h);
288 # endif
289
290   if (d->pid && d->pipe)
291     {
292       /* Tell the sub-process that the screen size has changed. */
293       struct winsize ws;
294       ws.ws_col = char_w;
295       ws.ws_row = char_h;
296       ws.ws_xpixel = pix_w;
297       ws.ws_ypixel = pix_h;
298       ioctl (fileno (d->pipe), TIOCSWINSZ, &ws);
299       kill (d->pid, SIGWINCH);
300     }
301 # endif /* HAVE_FORKPTY && TIOCSWINSZ */
302
303
304   /* If we're running xscreensaver-text, then kill and restart it any
305      time the window is resized so that it gets an updated --cols arg
306      right away.  But if we're running something else, leave it alone.
307    */
308   if (!strcmp (d->program, "xscreensaver-text"))
309     {
310       close_pipe (d);
311       d->input_available_p = False;
312       start_timer (d);
313     }
314 }
315
316
317 text_data *
318 textclient_open (Display *dpy)
319 {
320   text_data *d = (text_data *) calloc (1, sizeof (*d));
321
322 # ifdef DEBUG
323   fprintf (stderr, "%s: textclient: init\n", progname);
324 # endif
325
326   d->dpy = dpy;
327
328   if (get_boolean_resource (dpy, "usePty", "UsePty"))
329     {
330 # ifdef HAVE_FORKPTY
331       d->pty_p = True;
332 # else
333       fprintf (stderr,
334                "%s: no pty support on this system; using a pipe instead.\n",
335                progname);
336 # endif
337     }
338
339   d->subproc_relaunch_delay =
340     get_integer_resource (dpy, "relaunchDelay", "Time");
341   if (d->subproc_relaunch_delay < 1)
342     d->subproc_relaunch_delay = 1;
343   d->subproc_relaunch_delay *= 1000;
344
345
346   d->meta_sends_esc_p = get_boolean_resource (dpy, "metaSendsESC", "Boolean");
347   d->swap_bs_del_p    = get_boolean_resource (dpy, "swapBSDEL",    "Boolean");
348
349   d->program = get_string_resource (dpy, "program", "Program");
350
351
352 # ifdef HAVE_FORKPTY
353   /* Kludge for MacOS standalone mode: see OSX/SaverRunner.m. */
354   {
355     const char *s = getenv ("XSCREENSAVER_STANDALONE");
356     if (s && *s && strcmp(s, "0"))
357       {
358         d->pty_p = 1;
359         d->program = strdup (getenv ("SHELL"));
360       }
361   }
362 # endif
363
364   start_timer (d);
365
366   return d;
367 }
368
369
370 void
371 textclient_close (text_data *d)
372 {
373 # ifdef DEBUG
374   fprintf (stderr, "%s: textclient: free\n", progname);
375 # endif
376
377   close_pipe (d);
378   if (d->program)
379     free (d->program);
380   if (d->pipe_timer)
381     XtRemoveTimeOut (d->pipe_timer);
382   d->pipe_timer = 0;
383   memset (d, 0, sizeof (*d));
384   free (d);
385 }
386
387 int
388 textclient_getc (text_data *d)
389 {
390   XtAppContext app = XtDisplayToApplicationContext (d->dpy);
391   int ret = -1;
392
393   if (XtAppPending (app) & (XtIMTimer|XtIMAlternateInput))
394     XtAppProcessEvent (app, XtIMTimer|XtIMAlternateInput);
395
396   if (d->out_buffer && *d->out_buffer)
397     {
398       ret = *d->out_buffer;
399       d->out_buffer++;
400     }
401   else if (d->input_available_p && d->pipe)
402     {
403       unsigned char s[2];
404       int n = read (fileno (d->pipe), (void *) s, 1);
405       if (n > 0)
406         ret = s[0];
407       else              /* EOF */
408         {
409           if (d->pid)
410             {
411 # ifdef DEBUG
412               fprintf (stderr, "%s: textclient: waitpid %d\n",
413                        progname, d->pid);
414 # endif
415               waitpid (d->pid, NULL, 0);
416               d->pid = 0;
417             }
418
419           close_pipe (d);
420
421           if (d->out_column > 0)
422             {
423 # ifdef DEBUG
424               fprintf (stderr, "%s: textclient: adding blank line at EOF\n",
425                        progname);
426 # endif
427               d->out_buffer = "\r\n\r\n";
428             }
429
430           start_timer (d);
431         }
432       d->input_available_p = False;
433     }
434
435   if (ret == '\r' || ret == '\n')
436     d->out_column = 0;
437   else if (ret > 0)
438     d->out_column++;
439
440 # ifdef DEBUG
441   if (ret <= 0)
442     fprintf (stderr, "%s: textclient: getc: %d\n", progname, ret);
443   else if (ret < ' ')
444     fprintf (stderr, "%s: textclient: getc: %03o\n", progname, ret);
445   else
446     fprintf (stderr, "%s: textclient: getc: '%c'\n", progname, (char) ret);
447 # endif
448
449   return ret;
450 }
451
452
453 /* The interpretation of the ModN modifiers is dependent on what keys
454    are bound to them: Mod1 does not necessarily mean "meta".  It only
455    means "meta" if Meta_L or Meta_R are bound to it.  If Meta_L is on
456    Mod5, then Mod5 is the one that means Meta.  Oh, and Meta and Alt
457    aren't necessarily the same thing.  Icepicks in my forehead!
458  */
459 static unsigned int
460 do_icccm_meta_key_stupidity (Display *dpy)
461 {
462   unsigned int modbits = 0;
463 # ifndef HAVE_COCOA
464   int i, j, k;
465   XModifierKeymap *modmap = XGetModifierMapping (dpy);
466   for (i = 3; i < 8; i++)
467     for (j = 0; j < modmap->max_keypermod; j++)
468       {
469         int code = modmap->modifiermap[i * modmap->max_keypermod + j];
470         KeySym *syms;
471         int nsyms = 0;
472         if (code == 0) continue;
473         syms = XGetKeyboardMapping (dpy, code, 1, &nsyms);
474         for (k = 0; k < nsyms; k++)
475           if (syms[k] == XK_Meta_L || syms[k] == XK_Meta_R ||
476               syms[k] == XK_Alt_L  || syms[k] == XK_Alt_R)
477             modbits |= (1 << i);
478         XFree (syms);
479       }
480   XFreeModifiermap (modmap);
481 # endif /* HAVE_COCOA */
482   return modbits;
483 }
484
485
486 /* Returns a mask of the bit or bits of a KeyPress event that mean "meta". 
487  */
488 static unsigned int
489 meta_modifier (text_data *d)
490 {
491   if (!d->meta_done_once)
492     {
493       /* Really, we are supposed to recompute this if a KeymapNotify
494          event comes in, but fuck it. */
495       d->meta_done_once = True;
496       d->meta_mask = do_icccm_meta_key_stupidity (d->dpy);
497 # ifdef DEBUG
498       fprintf (stderr, "%s: textclient: ICCCM Meta is 0x%08X\n",
499                progname, d->meta_mask);
500 # endif
501     }
502   return d->meta_mask;
503 }
504
505
506 Bool
507 textclient_putc (text_data *d, XKeyEvent *k)
508 {
509   KeySym keysym;
510   unsigned char c = 0;
511   XLookupString (k, (char *) &c, 1, &keysym, &d->compose);
512   if (c != 0 && d->pipe)
513     {
514       if (!d->swap_bs_del_p) ;
515       else if (c == 127) c = 8;
516       else if (c == 8)   c = 127;
517
518       /* If meta was held down, send ESC, or turn on the high bit. */
519       if (k->state & meta_modifier (d))
520         {
521           if (d->meta_sends_esc_p)
522             fputc ('\033', d->pipe);
523           else
524             c |= 0x80;
525         }
526
527       fputc (c, d->pipe);
528       fflush (d->pipe);
529       k->type = 0;  /* don't interpret this event defaultly. */
530
531 # ifdef DEBUG
532       fprintf (stderr, "%s: textclient: putc '%c'\n", progname, (char) c);
533 # endif
534
535       return True;
536     }
537   return False;
538 }
539
540 #endif /* !USE_IPHONE -- whole file */