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