From http://www.jwz.org/xscreensaver/xscreensaver-5.37.tar.gz
[xscreensaver] / hacks / apple2-main.c
index 28fef9aa446cfc77a3ea5e890ecbb299f8495004..3063b58d787f720324f9d700d7948586d0f420b0 100644 (file)
@@ -1,4 +1,4 @@
-/* xscreensaver, Copyright (c) 1998-2006 Jamie Zawinski <jwz@jwz.org>
+/* xscreensaver, Copyright (c) 1998-2014 Jamie Zawinski <jwz@jwz.org>
  *
  * Permission to use, copy, modify, distribute, and sell this software and its
  * documentation for any purpose is hereby granted without fee, provided that
 # include <unistd.h>
 #endif
 
-#ifndef HAVE_COCOA
-# define XK_MISCELLANY
-# include <X11/keysymdef.h>
-# include <X11/Xutil.h>
-# include <X11/Intrinsic.h>
-#endif
-
-#ifdef HAVE_FORKPTY
-# include <sys/ioctl.h>
-# ifdef HAVE_PTY_H
-#  include <pty.h>
-# endif
-# ifdef HAVE_UTIL_H
-#  include <util.h>
-# endif
-#endif /* HAVE_FORKPTY */
-
 #include "screenhack.h"
 #include "apple2.h"
+#include "textclient.h"
+#include "utf8wc.h"
 
 #undef countof
 #define countof(x) (sizeof((x))/sizeof((*x)))
 #define SCREEN_COLS 40
 #define SCREEN_ROWS 24
 
-#define DEBUG
-
-static Time subproc_relaunch_delay = 3000;
-
 
 /* Given a bitmask, returns the position and width of the field.
  */
@@ -106,7 +87,7 @@ scale_image (Display *dpy, Window window, XImage *in,
   int x, y, i;
   unsigned int rpos=0, gpos=0, bpos=0; /* bitfield positions */
   unsigned int rsiz=0, gsiz=0, bsiz=0;
-  unsigned int rmsk=0, gmsk=0, bmsk=0;
+  unsigned long rmsk=0, gmsk=0, bmsk=0;
   unsigned char spread_map[3][256];
   XWindowAttributes xgwa;
   XColor *colors = 0;
@@ -131,9 +112,7 @@ scale_image (Display *dpy, Window window, XImage *in,
     }
   else
     {
-      rmsk = xgwa.visual->red_mask;
-      gmsk = xgwa.visual->green_mask;
-      bmsk = xgwa.visual->blue_mask;
+      visual_rgb_masks (xgwa.screen, xgwa.visual, &rmsk, &gmsk, &bmsk);
       decode_mask (rmsk, &rpos, &rsiz);
       decode_mask (gmsk, &gpos, &gsiz);
       decode_mask (bmsk, &bpos, &bsiz);
@@ -278,7 +257,6 @@ a2_dither (unsigned int *in, unsigned char *out, int w, int h)
   long *temp_err;
   int fs_scale = 1024;
   int brightness = 75;
-  int fs_direction;
 
 #if 0
   {
@@ -319,7 +297,6 @@ a2_dither (unsigned int *in, unsigned char *out, int w, int h)
       this_berr[x] = random() % (fs_scale * 2) - fs_scale;
       /* (random errors in [-1 .. 1]) */
     }
-  fs_direction = 1;
 
   for (y = 0; y < h; y++)
     for (x = 0; x < w; x++)
@@ -568,6 +545,9 @@ image_loaded_cb (Screen *screen, Window window, Drawable p,
      image (regardless of whether it started as TrueColor/PseudoColor.)
    */
   pick_a2_subimage (dpy, window, image, buf32, w, h);
+  free(image->data);
+  image->data = 0;
+  XDestroyImage(image);
 
   /* Then dither the 32bpp image to a 6-color Apple][ colormap.
    */
@@ -704,7 +684,7 @@ static void slideshow_controller(apple2_sim_t *sim, int *stepno,
           basename = slash+1;
         }
       {
-        char *dot=strchr(basename,'.');
+        char *dot=strrchr(basename,'.');
         if (dot) *dot=0;
       }
       if (strlen(basename)>20) basename[20]=0;
@@ -779,10 +759,25 @@ static void slideshow_controller(apple2_sim_t *sim, int *stepno,
     *stepno=10;
     break;
 
+  case 80:
+    /* Do nothing, just wait */
+    *next_actiontime += 2.0;
+    *stepno = A2CONTROLLER_FREE;
+    break;
+
   case A2CONTROLLER_FREE:
+    /* It is possible that still image is being loaded,
+       in that case mine cannot be freed, because
+       callback function tries to use it, so wait.
+    */
+    if (mine->image_loading_p) {
+      *stepno = 80;
+      break;
+    }
     free(mine->render_img);
     free(mine->img_filename);
     free(mine);
+    mine = 0;
     return;
 
   }
@@ -792,22 +787,17 @@ static void slideshow_controller(apple2_sim_t *sim, int *stepno,
 
 struct terminal_controller_data {
   Display *dpy;
-  FILE *pipe;
-  XtInputId pipe_id;
-  pid_t pid;
-  int input_available_p;
-  XtIntervalId timeout_id;
   char curword[256];
   unsigned char lastc;
-  int fake_nl;
   double last_emit_time;
-  XComposeStatus compose;
+  text_data *tc;
 
   int escstate;
   int csiparam[NPAR];
   int curparam;
   int cursor_x, cursor_y;
   int saved_x,  saved_y;
+  int unicruds; char unicrud[7];
   union {
     struct {
       unsigned int bold : 1;
@@ -816,206 +806,42 @@ struct terminal_controller_data {
     } bf;
     int w;
   } termattrib;
-  Bool meta_sends_esc_p;
-  Bool swap_bs_del_p;
   Bool fast_p;
 
 };
 
-static void
-subproc_cb (XtPointer closure, int *source, XtInputId *id)
-{
-  struct terminal_controller_data *mine =
-    (struct terminal_controller_data *) closure;
-  mine->input_available_p = True;
-}
 
-static void
-launch_text_generator (struct terminal_controller_data *mine)
-{
-  XtAppContext app = XtDisplayToApplicationContext (mine->dpy);
-  char buf[255];
-  char *oprogram = get_string_resource (mine->dpy, "program", "Program");
-  char *program = (char *) malloc (strlen (oprogram) + 10);
-
-  strcpy (program, "( ");
-  strcat (program, oprogram);
-  strcat (program, " ) 2>&1");
-
-  if (mine->pipe) abort();
-
-# ifdef HAVE_FORKPTY
-  if (get_boolean_resource (mine->dpy, "usePty", "Boolean"))
-    {
-      int fd;
-      struct winsize ws;
-
-      ws.ws_col = SCREEN_COLS;
-      ws.ws_row = SCREEN_ROWS;
-      ws.ws_xpixel = ws.ws_col * 6;
-      ws.ws_ypixel = ws.ws_row * 8;
-      
-      mine->pipe = NULL;
-      if((mine->pid = forkpty(&fd, NULL, NULL, &ws)) < 0)
-       {
-          /* Unable to fork */
-          sprintf (buf, "%.100s: forkpty", progname);
-         perror(buf);
-       }
-      else if(!mine->pid)
-       {
-          /* This is the child fork. */
-          char *av[10];
-          int i = 0;
-         if (putenv("TERM=vt100"))
-            abort();
-          av[i++] = "/bin/sh";
-          av[i++] = "-c";
-          av[i++] = oprogram;
-          av[i] = 0;
-          execvp (av[0], av);
-          sprintf (buf, "%.100s: %.100s", progname, oprogram);
-         perror(buf);
-         exit(1);
-       }
-      else
-       {
-          /* This is the parent fork. */
-         mine->pipe = fdopen(fd, "r+");
-         mine->pipe_id =
-           XtAppAddInput (app, fileno (mine->pipe),
-                          (XtPointer) (XtInputReadMask | XtInputExceptMask),
-                          subproc_cb, (XtPointer) mine);
-       }
-    }
-  else
-# endif /* HAVE_FORKPTY */
-
-  if ((mine->pipe = popen (program, "r")))
-    {
-      if (mine->pipe_id) abort();
-      mine->pipe_id =
-        XtAppAddInput (app, fileno (mine->pipe),
-                       (XtPointer) (XtInputReadMask | XtInputExceptMask),
-                       subproc_cb, (XtPointer) mine);
-    }
-  else
-    {
-      sprintf (buf, "%.100s: %.100s", progname, program);
-      perror(buf);
-    }
-}
+/* The structure of closure linkage throughout this code is so amazingly
+   baroque that I can't get to the 'struct state' from where I need it. */
+static const char *global_program;
+static Bool global_fast_p;
 
-static void
-relaunch_generator_timer (XtPointer closure, XtIntervalId *id)
-{
-  struct terminal_controller_data *mine =
-    (struct terminal_controller_data *) closure;
-  mine->timeout_id=0;
-  launch_text_generator (mine);
-}
 
 static void
 terminal_closegen(struct terminal_controller_data *mine)
 {
-  if (mine->pipe_id) {
-    XtRemoveInput (mine->pipe_id);
-    mine->pipe_id = 0;
-  }
-  if (mine->pipe) {
-    pclose (mine->pipe);
-    mine->pipe = 0;
-  }
-  if (mine->timeout_id) {
-    XtRemoveTimeOut(mine->timeout_id);
-    mine->timeout_id=0;
+  if (mine->tc) {
+    textclient_close (mine->tc);
+    mine->tc = 0;
   }
 }
 
 static int
 terminal_read(struct terminal_controller_data *mine, unsigned char *buf, int n)
 {
-  XtAppContext app = XtDisplayToApplicationContext (mine->dpy);
-  int rc;
-  if (mine->fake_nl) {
-    buf[0]='\n';
-    mine->fake_nl=0;
-    return 1;
-  }
-
-  if (!mine->input_available_p) return 0;
-
-  rc=read (fileno (mine->pipe), (void *) buf, n);
-  if (rc>0) mine->lastc=buf[rc-1];
-
-  if (rc<=0)
-    {
-      terminal_closegen(mine);
-
-      if (mine->lastc != '\n') { /* add a newline at eof if there wasn't one */
-        mine->fake_nl=1;
-      }
-
-      /* Set up a timer to re-launch the subproc in a bit. */
-      mine->timeout_id =
-        XtAppAddTimeOut(app, subproc_relaunch_delay,
-                        relaunch_generator_timer,
-                        (XtPointer) mine);
-    }
-
-  mine->input_available_p = False;
-
-  return rc;
-}
-
-
-/* The interpretation of the ModN modifiers is dependent on what keys
-   are bound to them: Mod1 does not necessarily mean "meta".  It only
-   means "meta" if Meta_L or Meta_R are bound to it.  If Meta_L is on
-   Mod5, then Mod5 is the one that means Meta.  Oh, and Meta and Alt
-   aren't necessarily the same thing.  Icepicks in my forehead!
- */
-static unsigned int
-do_icccm_meta_key_stupidity (Display *dpy)
-{
-  unsigned int modbits = 0;
-# ifndef HAVE_COCOA
-  int i, j, k;
-  XModifierKeymap *modmap = XGetModifierMapping (dpy);
-  for (i = 3; i < 8; i++)
-    for (j = 0; j < modmap->max_keypermod; j++)
-      {
-        int code = modmap->modifiermap[i * modmap->max_keypermod + j];
-        KeySym *syms;
-        int nsyms = 0;
-        if (code == 0) continue;
-        syms = XGetKeyboardMapping (dpy, code, 1, &nsyms);
-        for (k = 0; k < nsyms; k++)
-          if (syms[k] == XK_Meta_L || syms[k] == XK_Meta_R ||
-              syms[k] == XK_Alt_L  || syms[k] == XK_Alt_R)
-            modbits |= (1 << i);
-        XFree (syms);
-      }
-  XFreeModifiermap (modmap);
-# endif /* HAVE_COCOA */
-  return modbits;
-}
-
-/* Returns a mask of the bit or bits of a KeyPress event that mean "meta". 
- */
-static unsigned int
-meta_modifier (Display *dpy)
-{
-  static Bool done_once = False;
-  static unsigned int mask = 0;
-  if (!done_once)
-    {
-      /* Really, we are supposed to recompute this if a KeymapNotify
-         event comes in, but fuck it. */
-      done_once = True;
-      mask = do_icccm_meta_key_stupidity (dpy);
+  if (!mine || !mine->tc) {
+    return 0;
+  } else {
+    int i, count = 0;
+    for (i = 0; i < n; i++) {
+      int c = textclient_getc (mine->tc);
+      if (c <= 0) break;
+      buf[i] = c;
+      mine->lastc = c;
+      count++;
     }
-  return mask;
+    return count;
+  }
 }
 
 
@@ -1024,31 +850,9 @@ terminal_keypress_handler (Display *dpy, XEvent *event, void *data)
 {
   struct terminal_controller_data *mine =
     (struct terminal_controller_data *) data;
-  KeySym keysym;
-  unsigned char c = 0;
-  XLookupString (&event->xkey, (char *) &c, 1, &keysym, &mine->compose);
-  if (c == 0 || !mine->pipe)
-    return 0;
-
-  if (!mine->swap_bs_del_p) ;
-  else if (c == 127) c = 8;
-  else if (c == 8)   c = 127;
-
-  /* If meta was held down, send ESC, or turn on the high bit. */
-  if (event->xkey.state & meta_modifier (dpy))
-    {
-      if (mine->meta_sends_esc_p)
-        fputc ('\033', mine->pipe);
-      else
-        c |= 0x80;
-    }
-
-  fputc (c, mine->pipe);
-  fflush (mine->pipe);
-
-  event->xany.type = 0;  /* do not process this event further */
-
   mine->dpy = dpy;
+  if (event->xany.type == KeyPress && mine->tc)
+    return textclient_putc (mine->tc, &event->xkey);
   return 0;
 }
 
@@ -1095,6 +899,8 @@ a2_vt100_printc (apple2_sim_t *sim, struct terminal_controller_data *state,
   int i;
   int start, end;
 
+  /* Mostly duplicated in phosphor.c */
+
   switch (state->escstate)
     {
     case 0:
@@ -1123,6 +929,9 @@ a2_vt100_printc (apple2_sim_t *sim, struct terminal_controller_data *state,
             }
           break;
         case 10: /* LF */
+# ifndef HAVE_FORKPTY
+          state->cursor_x = 0; /* No ptys on iPhone; assume CRLF. */
+# endif
         case 11: /* VT */
         case 12: /* FF */
           if (state->cursor_y < rows - 1)
@@ -1155,6 +964,38 @@ a2_vt100_printc (apple2_sim_t *sim, struct terminal_controller_data *state,
           state->curparam = 0;
           break;
         default:
+
+          /* states 102-106 are for UTF-8 decoding */
+
+          if ((c & 0xE0) == 0xC0) {        /* 110xxxxx - 11 bits, 2 bytes */
+            state->unicruds = 1;
+            state->unicrud[0] = c;
+            state->escstate = 102;
+            break;
+          } else if ((c & 0xF0) == 0xE0) { /* 1110xxxx - 16 bits, 3 bytes */
+            state->unicruds = 1;
+            state->unicrud[0] = c;
+            state->escstate = 103;
+            break;
+          } else if ((c & 0xF8) == 0xF0) { /* 11110xxx - 21 bits, 4 bytes */
+            state->unicruds = 1;
+            state->unicrud[0] = c;
+            state->escstate = 104;
+            break;
+          } else if ((c & 0xFC) == 0xF8) { /* 111110xx - 26 bits, 5 bytes */
+            state->unicruds = 1;
+            state->unicrud[0] = c;
+            state->escstate = 105;
+            break;
+          } else if ((c & 0xFE) == 0xFC) { /* 1111110x - 31 bits, 6 bytes */
+            state->unicruds = 1;
+            state->unicrud[0] = c;
+            state->escstate = 106;
+            break;
+          }
+
+        PRINT:
+
           /* If the cursor is in column 39 and we print a character, then
              that character shows up in column 39, and the cursor is no longer
              visible on the screen (it's in "column 40".)  If another character
@@ -1229,9 +1070,13 @@ a2_vt100_printc (apple2_sim_t *sim, struct terminal_controller_data *state,
           state->curparam = 0;
           break;
         case '%': /* Select charset */
-          /* No, I don't support UTF-8, since the apple2 font
-             isn't even Unicode anyway. We must still catch the
-             last byte, though. */
+          /* @: Select default (ISO 646 / ISO 8859-1)
+             G: Select UTF-8
+             8: Select UTF-8 (obsolete)
+
+             We can just ignore this and always process UTF-8, I think?
+             We must still catch the last byte, though.
+           */
         case '(':
         case ')':
           /* I don't support different fonts either - see above
@@ -1441,6 +1286,39 @@ a2_vt100_printc (apple2_sim_t *sim, struct terminal_controller_data *state,
     case 3:
       state->escstate = 0;
       break;
+
+    case 102:
+    case 103:
+    case 104:
+    case 105:
+    case 106:
+      {
+        int total = state->escstate - 100;  /* see what I did there */
+        if (state->unicruds < total) {
+          /* Buffer more bytes of the UTF-8 sequence */
+          state->unicrud[state->unicruds++] = c;
+        }
+
+        if (state->unicruds >= total) {
+          /* Done! Convert it to ASCII and print that. */
+          char *s;
+          state->unicrud[state->unicruds] = 0;
+          s = utf8_to_latin1 ((const char *) state->unicrud, True);
+          state->unicruds = 0;
+          state->escstate = 0;
+          if (s) {
+            c = s[0];
+            free (s);
+            goto PRINT;
+          } else {
+            /* c = 0; */
+          }
+        }
+      }
+      break;
+
+    default:
+      abort();
     }
   a2_goto(st, state->cursor_y, state->cursor_x);
 }
@@ -1465,11 +1343,7 @@ terminal_controller(apple2_sim_t *sim, int *stepno, double *next_actiontime)
   mine=(struct terminal_controller_data *) sim->controller_data;
   mine->dpy = sim->dpy;
 
-  mine->meta_sends_esc_p = get_boolean_resource (mine->dpy, "metaSendsESC",
-                                                 "Boolean");
-  mine->swap_bs_del_p    = get_boolean_resource (mine->dpy, "swapBSDEL", 
-                                                 "Boolean");
-  mine->fast_p           = get_boolean_resource (mine->dpy, "fast", "Boolean");
+  mine->fast_p           = global_fast_p;
 
   switch(*stepno) {
 
@@ -1483,35 +1357,52 @@ terminal_controller(apple2_sim_t *sim, int *stepno, double *next_actiontime)
     a2_goto(st,2,0);
     mine->cursor_y = 2;
 
-    if (! mine->pipe)
-      launch_text_generator(mine);
+    if (! mine->tc) {
+      mine->tc = textclient_open (mine->dpy);
+      textclient_reshape (mine->tc,
+                          SCREEN_COLS, SCREEN_ROWS,
+                          SCREEN_COLS, SCREEN_ROWS,
+                          0);
+    }
 
     if (! mine->fast_p)
       *next_actiontime += 4.0;
     *stepno = 10;
+
+    mine->last_emit_time = sim->curtime;
     break;
 
   case 10:
+  case 11:
     {
+      Bool first_line_p = (*stepno == 10);
       unsigned char buf[1024];
       int nr,nwant;
       double elapsed;
 
       elapsed=sim->curtime - mine->last_emit_time;
-      mine->last_emit_time=sim->curtime;
-      nwant=elapsed*25.0;
-      if (elapsed>1.0) nwant=1;
-      if (nwant<1) nwant=1;
-      if (nwant>4) nwant=4;
+
+      nwant = elapsed * 25.0;   /* characters per second */
+
+      if (first_line_p) {
+        *stepno = 11;
+        nwant = 1;
+      }
+
+      if (nwant > 40) nwant = 40;
 
       if (mine->fast_p)
         nwant = sizeof(buf)-1;
 
+      if (nwant <= 0) break;
+
+      mine->last_emit_time = sim->curtime;
+
       nr=terminal_read(mine, buf, nwant);
       for (i=0; i<nr; i++) {
         c=buf[i];
 
-        if (mine->pid)
+        if (mine->tc)
           a2_vt100_printc (sim, mine, c);
         else
           a2_ascii_printc (st, c, False, False, False, True);
@@ -1522,6 +1413,7 @@ terminal_controller(apple2_sim_t *sim, int *stepno, double *next_actiontime)
   case A2CONTROLLER_FREE:
     terminal_closegen(mine);
     free(mine);
+    mine = 0;
     return;
   }
 }
@@ -1884,6 +1776,7 @@ basic_controller(apple2_sim_t *sim, int *stepno, double *next_actiontime)
 
   case A2CONTROLLER_FREE:
     free(mine);
+    mine = 0;
     break;
   }
 
@@ -1896,8 +1789,6 @@ static void (* const controllers[]) (apple2_sim_t *sim, int *stepno,
   basic_controller
 };
 
-
-
 struct state {
   int duration;
   Bool random_p;
@@ -1934,6 +1825,23 @@ apple2_init (Display *dpy, Window window)
     }
   if (s) free (s);
 
+  global_program = get_string_resource (dpy, "program", "Program");
+  global_fast_p = get_boolean_resource (dpy, "fast", "Boolean");
+
+
+  /* Kludge for MacOS standalone mode: see OSX/SaverRunner.m. */
+  {
+    const char *s = getenv ("XSCREENSAVER_STANDALONE");
+    if (s && *s && strcmp(s, "0"))
+      {
+        st->controller = terminal_controller;
+        st->random_p   = False;
+        global_program = getenv ("SHELL");
+        global_fast_p  = True;
+      }
+  }
+
+
   if (! st->random_p) {
     if (st->controller == terminal_controller ||
         st->controller == slideshow_controller)
@@ -1958,7 +1866,11 @@ apple2_draw (Display *dpy, Window window, void *closure)
     st->sim = 0;
   }
 
-  return 10000;
+#ifdef HAVE_MOBILE
+  return 0;
+#else
+  return 5000;
+#endif
 }
 
 static void
@@ -1966,7 +1878,8 @@ apple2_reshape (Display *dpy, Window window, void *closure,
                  unsigned int w, unsigned int h)
 {
   struct state *st = (struct state *) closure;
-  analogtv_reconfigure (st->sim->dec);
+  if (st->sim)
+    analogtv_reconfigure (st->sim->dec);
 }
 
 static Bool
@@ -1974,7 +1887,8 @@ apple2_event (Display *dpy, Window window, void *closure, XEvent *event)
 {
   struct state *st = (struct state *) closure;
 
-  if (st->controller == terminal_controller &&
+  if (st->sim &&
+      st->controller == terminal_controller &&
       event->xany.type == KeyPress) {
     terminal_keypress_handler (dpy, event, st->sim->controller_data);
     return True;