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