Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

3460
LINES

< > BotCompany Repo | #1004087 // Default boot-up code for JavaX/Android 26 (testing, with x27) BACKUP

JavaX source code (Android) - run with: the app

1  
import javax.imageio.*;
2  
import java.security.NoSuchAlgorithmException;
3  
import java.security.MessageDigest;
4  
import java.lang.management.*;
5  
import java.lang.reflect.*;
6  
import java.net.*;
7  
import java.io.*;
8  
import java.util.concurrent.atomic.*;
9  
import java.util.concurrent.*;
10  
import java.util.regex.*;
11  
import java.util.List;
12  
import java.util.zip.*;
13  
import java.util.*;
14  
15  
import android.widget.*;
16  
import android.view.*;
17  
import android.view.View;
18  
import android.content.Context;
19  
import android.app.Activity;
20  
import android.view.inputmethod.*;
21  
import android.content.*;
22  
import android.text.*;
23  
24  
public class main {
25  
  static String leoID = "#1001297";
26  
  
27  
  static List<Prog> programsStarted = new ArrayList<Prog>();
28  
29  
  static class Prog {
30  
    String snippetID;
31  
    Thread thread;
32  
  }
33  
34  
  static class Lg {
35  
    static int maxBufferLength = 2048;
36  
    
37  
    Activity context;
38  
    ScrollView sv;
39  
    TextView tv;
40  
    StringBuilder buf = new StringBuilder();
41  
    
42  
    Lg(Activity context) {
43  
      this.context = context;
44  
      sv = new ScrollView(context);
45  
      tv = new TextView(context);
46  
      tv.setText(buf.toString());
47  
      sv.addView(tv);
48  
    }
49  
    
50  
    View getView() {
51  
      return sv;
52  
    }
53  
    
54  
    void shortenBuffer() {
55  
      while (buf.length() > maxBufferLength) {
56  
        String s = buf.toString();
57  
        int i = s.indexOf('\n');
58  
        if (i < 0) return;
59  
        buf = new StringBuilder(s.substring(i+1));
60  
      }
61  
    }
62  
    
63  
    void print(final String s) {
64  
      context.runOnUiThread(new Runnable() {
65  
        public void run() {
66  
          buf.append(s);
67  
          shortenBuffer();
68  
          tv.setText(buf.toString());
69  
          
70  
          sv.post(new Runnable() {
71  
            public void run() {
72  
              // This method works but animates the scrolling 
73  
              // which looks weird on first load
74  
              sv.fullScroll(View.FOCUS_DOWN);
75  
76  
              // This method works even better because there are no animations.
77  
              //sv.scrollTo(0, sv.getBottom());
78  
            }
79  
          });
80  
        }
81  
      });
82  
    }
83  
    
84  
    void println(String s) {
85  
      print(s + "\n");
86  
    }
87  
  }
88  
  
89  
  public static View main(final Activity context) throws Exception {
90  
    x27.androidContext = context;
91  
    final File defSnip = new File(x27.userHome(), ".javax/defsnip");
92  
    String id = x27.loadTextFile(defSnip.getPath(), "636");
93  
 final File defargs = new File(x27.userHome(), ".javax/defargs");
94  
    String arg = x27.loadTextFile(defargs.getPath(), "leo");
95  
96  
    ScrollView sv = new ScrollView(context);
97  
    LinearLayout ll = new LinearLayout(context);
98  
    ll.setOrientation(LinearLayout.VERTICAL);
99  
    
100  
    LinearLayout line1 = new LinearLayout(context);
101  
    
102  
    TextView label = new TextView(context);
103  
    label.setText("Run which snippet ID?");
104  
    line1.addView(label);
105  
    
106  
    final EditText tv = new EditText(context);
107  
    // BAD - tv.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
108  
    tv.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_CLASS_NUMBER);
109  
    tv.setText(id);
110  
    line1.addView(tv);
111  
    
112  
    Button btnGo = new Button(context);
113  
    btnGo.setText("Go");
114  
    line1.addView(btnGo);
115  
    
116  
    ll.addView(line1);
117  
    
118  
    LinearLayout line2 = new LinearLayout(context);
119  
    
120  
    label = new TextView(context);
121  
    label.setText("Program arguments:");
122  
    line2.addView(label);
123  
    
124  
    final EditText tvArgs = new EditText(context);
125  
    tvArgs.setText(arg);
126  
    line2.addView(tvArgs);
127  
    
128  
    ll.addView(line2);
129  
    
130  
    LinearLayout line3 = new LinearLayout(context);
131  
    
132  
    Button btnLeo = new Button(context);
133  
    btnLeo.setText("Sprechen mit Leo");
134  
    line3.addView(btnLeo);
135  
    
136  
    ll.addView(line3);
137  
    
138  
    btnGo.setOnClickListener(new View.OnClickListener() {
139  
      public void onClick(View v) {
140  
        hideKeyboard(context);
141  
        String snippetID = tv.getText().toString();
142  
        String text = "Running: " + snippetID;
143  
        Toast.makeText(context, text, 2000).show();
144  
        
145  
        try {
146  
          x27.saveTextFile(defSnip.getPath(), snippetID);
147  
          x27.saveTextFile(defargs.getPath(), tvArgs.getText().toString());
148  
        } catch (IOException e) {
149  
        }
150  
        run(context, snippetID, tvArgs.getText().toString().split(" +"));
151  
      }
152  
    });
153  
154  
    btnLeo.setOnClickListener(new View.OnClickListener() {
155  
      public void onClick(View v) {
156  
        run(context, leoID, new String[0]);
157  
      }
158  
    });
159  
160  
    sv.addView(ll);
161  
    return sv;
162  
  }
163  
  
164  
  static Lg lg;
165  
  
166  
  public static void run(final Activity context, final String mainSnippet, final String[] args) {
167  
    lg = new Lg(context);
168  
    
169  
    OutputStream outputStream = new OutputStream() {
170  
      public void write(int b) {
171  
        try {
172  
          lg.print(new String(new byte[] {(byte) b}, "UTF-8")); // This is crap
173  
        } catch (UnsupportedEncodingException e) {}
174  
      }
175  
      
176  
      @Override
177  
      public void write(byte[] b, int off, int len) {
178  
        try {
179  
          lg.print(new String(b, off, len, "UTF-8")); // This is crap
180  
        } catch (UnsupportedEncodingException e) {}
181  
      }
182  
    };
183  
    
184  
    PrintStream ps = new PrintStream(outputStream, true);
185  
    System.setOut(ps);
186  
    System.setErr(ps);
187  
    
188  
    Prog prog = new Prog();
189  
    prog.snippetID = mainSnippet;
190  
191  
    prog.thread = new Thread() {
192  
      public void run() {
193  
        try {
194  
          String[] a = new String[args.length+1];
195  
          System.arraycopy(args, 0, a, 1, args.length);
196  
          a[0] = mainSnippet;
197  
          x27.main(a);
198  
        } catch (Throwable e) {
199  
          System.out.println("Whoa!");
200  
          e.printStackTrace();
201  
        }
202  
      }
203  
    };
204  
    
205  
    programsStarted.add(prog);
206  
    prog.thread.start();
207  
    
208  
    context.setContentView(lg.getView());
209  
  }
210  
  
211  
  static void setContentViewInUIThread(final View view) {
212  
    ((Activity) x27.androidContext).runOnUiThread(new Runnable() {
213  
      public void run() {
214  
        ((Activity) x27.androidContext).setContentView(view);
215  
      }
216  
    });
217  
  }
218  
  
219  
  public static void hideKeyboard(Activity context) {   
220  
    View view = context.getCurrentFocus();
221  
    if (view != null) {
222  
        InputMethodManager inputManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
223  
        inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
224  
    }
225  
  }
226  
  
227  
  static void onActivityResult(int requestCode, int resultCode, Intent data) {
228  
    if (x27.mainClass != null)
229  
      x27.call(x27.mainClass, "onActivityResult", requestCode, resultCode, data);
230  
  }
231  
}
232  
233  
class x27 {
234  
  static final String version = "JavaX 27";
235  
236  
  // If programs run longer than this, they might have their class files
237  
  // deleted.
238  
  static int tempFileRetentionTime = 24; // hours
239  
  
240  
  static boolean verbose = false, translate = false, list = false, virtualizeTranslators = true;
241  
  static String translateTo = null;
242  
  static boolean preferCached = false, noID = false, noPrefetch = false, noAWT = false;
243  
  static boolean safeOnly = false, safeTranslate = false, javacOnly = false, logOn = true;
244  
  static boolean runMainInProcess = true, consoleOn = true, hasHelloMessage = false;
245  
  static List<String[]> mainTranslators = new ArrayList<String[]>();
246  
  private static Map<Long, String> memSnippetCache = new HashMap<Long, String>();
247  
  private static int processesStarted, compilations;
248  
249  
  // snippet ID -> md5
250  
  private static HashMap<Long, String> prefetched = new HashMap<Long, String>();
251  
  private static File virtCache;
252  
253  
  // doesn't work yet
254  
  private static Map<String, Class<?>> programCache = new HashMap<String, Class<?>>();
255  
  static boolean cacheTranslators = false;
256  
257  
  // this should work (caches transpiled translators)
258  
  private static HashMap<Long, Object[]> translationCache = new HashMap<Long, Object[]>();
259  
  static boolean cacheTranspiledTranslators = true;
260  
261  
  // which snippets are available pre-transpiled server-side?
262  
  private static Set<Long> hasTranspiledSet = new HashSet<Long>();
263  
  static boolean useServerTranspiled = true;
264  
265  
  static Object androidContext;
266  
  static boolean android = isAndroid();
267  
  
268  
  // We stick to 1.7 for now to support android.
269  
  // Scripts like #1001155 might change to 1.6
270  
  static String javaTarget = System.getProperty("java.version").startsWith("1.6.") ? "1.6" : "1.7";
271  
272  
  // Translators currently being translated (to detect recursions)
273  
  private static Set<Long> translating = new HashSet<Long>();
274  
275  
  static String lastOutput;
276  
  static String[] fullArgs;
277  
278  
  static String javaCompilerOutput;
279  
280  
  public static void main(String[] args) {
281  
    try {
282  
      goMain(args);
283  
    } catch (Throwable e) {
284  
      e.printStackTrace();
285  
    }
286  
  }
287  
288  
static byte[] loadDataSnippetImpl(String snippetID) throws IOException {
289  
  byte[] data;
290  
  try {
291  
    URL url = new URL("http://eyeocr.sourceforge.net/filestore/filestore.php?cmd=serve&file=blob_"
292  
      + parseSnippetID(snippetID) + "&contentType=application/binary");
293  
    System.err.println("Loading library: " + url);
294  
    try {
295  
      data = loadBinaryPage(url.openConnection());
296  
    } catch (IOException e) {
297  
      data = null;
298  
    }
299  
    
300  
    if (data == null || data.length == 0) {
301  
      url = new URL("http://data.tinybrain.de/blobs/"
302  
        + parseSnippetID(snippetID));
303  
      System.err.println("Loading library: " + url);
304  
      data = loadBinaryPage(url.openConnection());
305  
    }
306  
    System.err.println("Bytes loaded: " + data.length);
307  
  } catch (FileNotFoundException e) {
308  
    throw new IOException("Binary snippet #" + snippetID + " not found or not public");
309  
  }
310  
  return data;
311  
}
312  
  
313  
  static void goMain(String[] args) throws Exception {
314  
    if (args.length != 0 && args[0].equals("-v")) verbose = true;
315  
316  
    for (String arg : args)
317  
      if (arg.equals("-noawt"))
318  
        noAWT = true;
319  
        
320  
    String autoReport = loadTextFile(new File(userHome(), ".javax/auto-report-to-chat").getPath(), "").trim();
321  
    //print("autoReport=" + autoReport);
322  
    if (!isChatServer(args) && autoReport.equals("1"))
323  
      autoReportToChat();
324  
325  
    if (!hasHelloMessage) {
326  
      hasHelloMessage = true;
327  
      //installHelloMessage(args.length == 0 ? "JavaX Start-Up VM" : "JavaX VM (" + smartJoin(args) + ")");
328  
      makeVMAndroid();
329  
    }
330  
    
331  
    File ioBaseDir = new File("."), inputDir = null, outputDir = null;
332  
    String src = null;
333  
    List<String> programArgs = new ArrayList<String>();
334  
    fullArgs = args;
335  
336  
    for (int i = 0; i < args.length; i++) {
337  
      String arg = args[i];
338  
339  
      if (arg.equals("-version")) {
340  
        showVersion();
341  
        System.exit(0);
342  
      }
343  
344  
      if (arg.equals("-sysprop")) {
345  
        showSystemProperties();
346  
        return;
347  
      }
348  
349  
      if (arg.equals("-v") || arg.equals("-verbose"))
350  
        verbose = true;
351  
      else if (arg.equals("-finderror"))
352  
        verbose = true;
353  
      else if (arg.equals("-offline") || arg.equalsIgnoreCase("-prefercached"))
354  
        preferCached = true;
355  
      else if (arg.equals("-novirt"))
356  
        virtualizeTranslators = false;
357  
      else if (arg.equals("-safeonly"))
358  
        safeOnly = true;
359  
      else if (arg.equals("-safetranslate"))
360  
        safeTranslate = true;
361  
      else if (arg.equals("-noawt"))
362  
        noAWT = true;
363  
      else if (arg.equals("-noid"))
364  
        noID = true;
365  
      else if (arg.equals("-nocachetranspiled"))
366  
        cacheTranspiledTranslators = false;
367  
      else if (arg.equals("-javac"))
368  
        javacOnly = true;
369  
      else if (arg.equals("-localtranspile"))
370  
        useServerTranspiled = false;
371  
      else if (arg.equals("translate") && src == null)
372  
        translate = true;
373  
      else if (arg.equals("list") && src == null) {
374  
        list = true;
375  
        virtualizeTranslators = false; // so they are silenced
376  
      } else if (arg.equals("run") && src == null) {
377  
        // it's the default command anyway
378  
      } else if (arg.startsWith("input="))
379  
        inputDir = new File(arg.substring(6));
380  
      else if (arg.startsWith("output="))
381  
        outputDir = new File(arg.substring(7));
382  
      else if (arg.equals("with"))
383  
        mainTranslators.add(new String[] {args[++i], null});
384  
      else if (translate && arg.equals("to"))
385  
        translateTo = args[++i];
386  
      else if (src == null) {
387  
        //System.out.println("src=" + arg);
388  
        src = arg;
389  
      } else
390  
        programArgs.add(arg);
391  
    }
392  
393  
    cleanCache();
394  
395  
    if (useServerTranspiled)
396  
      noPrefetch = true;
397  
398  
    if (src == null) src = ".";
399  
400  
    // Might actually want to write to 2 disk caches (global/per program).
401  
    if (virtualizeTranslators && !preferCached)
402  
      virtCache = TempDirMaker_make();
403  
404  
    if (inputDir != null) {
405  
      ioBaseDir = TempDirMaker_make();
406  
      System.out.println("Taking input from: " + inputDir.getAbsolutePath());
407  
      System.out.println("Output is in: " + new File(ioBaseDir, "output").getAbsolutePath());
408  
      copyInput(inputDir, new File(ioBaseDir, "input"));
409  
    }
410  
    
411  
    if (logOn)
412  
      logStart(args);
413  
414  
    javaxmain(src, ioBaseDir, translate, list, programArgs.toArray(new String[programArgs.size()]));
415  
416  
    if (outputDir != null) {
417  
      copyInput(new File(ioBaseDir, "output"), outputDir);
418  
      System.out.println("Output copied to: " + outputDir.getAbsolutePath());
419  
    }
420  
421  
    if (verbose) {
422  
      // print stats
423  
      System.out.println("Processes started: " + processesStarted + ", compilations: " + compilations);
424  
    }
425  
  }
426  
427  
  public static void javaxmain(String src, File ioDir, boolean translate, boolean list,
428  
                               String[] args) throws Exception {
429  
    String programID = isSnippetID(src) ? "" + parseSnippetID(src) : null;
430  
    
431  
    if (programID != null)
432  
      System.err.println("JavaX TRANSLATE " + programID + " " + smartJoin(args));
433  
    
434  
    List<File> libraries = new ArrayList<File>();
435  
    File X = transpileMain(src, libraries);
436  
    if (verbose)
437  
      print("After transpileMain: " + X);
438  
      
439  
    if (X == null) {
440  
      showVersion();
441  
      
442  
      if (fullArgs != null) {
443  
        String[] nargs;
444  
        if (fullArgs.length == 0)
445  
          nargs = new String[] {"1000825"}; // swing-start
446  
        else {
447  
          // forward to search
448  
          nargs = new String[fullArgs.length+1];
449  
          nargs[0] = "636";
450  
          // nargs[1] = "search-runnables";
451  
          System.arraycopy(fullArgs, 0, nargs, 1, fullArgs.length);
452  
        }
453  
        main(nargs); // Hopefully we get no infinite recursion :)
454  
        return;
455  
      }
456  
      
457  
      System.out.println("No main.java found, exiting");
458  
      return;
459  
    }
460  
    
461  
    info.transpiledSrc = X;
462  
463  
    // list or run
464  
465  
    if (translate) {
466  
      File to = X;
467  
      if (translateTo != null) {
468  
        StringBuilder buf = new StringBuilder();
469  
        for (File f : libraries) buf.append(f.getName()+"\n");
470  
        if (new File(translateTo).isDirectory()) {
471  
          to = new File(translateTo, "main.java");
472  
          saveTextFile(new File(translateTo, "libraries.txt").getPath(), buf.toString());
473  
        } else {
474  
          to = new File(translateTo);
475  
          saveTextFile(new File(translateTo + "_libraries").getPath(), buf.toString());
476  
        }
477  
      }
478  
      if (to != X)
479  
        copy(new File(X, "main.java"), to);
480  
      System.out.println("Program translated to: " + to.getAbsolutePath());
481  
    } else if (list)
482  
      System.out.println(loadTextFile(new File(X, "main.java").getPath(), null));
483  
    else {
484  
      if (programID != null)
485  
        System.err.println("JavaX RUN " + programID + " " + smartJoin(args));
486  
      System.err.println(); // Make empty line before actual program starts
487  
      
488  
      javax2(X, ioDir, false, runMainInProcess, libraries, args, null, programID, info);
489  
      
490  
      System.out.println("[main done]");
491  
      
492  
      // cleanup reportToChat thread
493  
      if (reportToChat_q != null) {
494  
        if (verbose) System.out.println("Closing reportToChat queue");
495  
        reportToChat_q.done();
496  
      }
497  
    }
498  
  }
499  
500  
  static File transpileMain(String src, List<File> libraries) throws Exception {
501  
    File srcDir;
502  
    boolean isTranspiled = false;
503  
    if (isSnippetID(src)) {
504  
      prefetch(src);
505  
      long id = parseSnippetID(src);
506  
      prefetched.remove(id); // hackfix to ensure transpiled main program is found.
507  
      srcDir = loadSnippetAsMainJava(src);
508  
      if (verbose)
509  
        System.err.println("hasTranspiledSet: " + hasTranspiledSet);
510  
      if (hasTranspiledSet.contains(id) && useServerTranspiled) {
511  
        //System.err.println("Trying pretranspiled main program: #" + id);
512  
        String transpiledSrc = getServerTranspiled("#" + id);
513  
        int i = transpiledSrc.indexOf('\n');
514  
        String libs = transpiledSrc.substring(0, Math.max(0, i));
515  
        transpiledSrc = transpiledSrc.substring(i+1);
516  
        if (!transpiledSrc.isEmpty()) {
517  
          srcDir = TempDirMaker_make();
518  
          saveTextFile(new File(srcDir, "main.java").getPath(), transpiledSrc);
519  
          isTranspiled = true;
520  
          //translationCache.put(id, new Object[] {srcDir, libraries});
521  
522  
          Matcher m = Pattern.compile("\\d+").matcher(libs);
523  
          while (m.find()) {
524  
            String libid = m.group();
525  
            File libraryFile = DiskSnippetCache_getLibrary(parseSnippetID(libid));
526  
            loadLibrary(libid, libraries, libraryFile);
527  
          }
528  
        }
529  
      }
530  
    } else {
531  
      srcDir = new File(src);
532  
533  
      // if the argument is a file, it is assumed to be main.java
534  
      if (srcDir.isFile()) {
535  
        srcDir = TempDirMaker_make();
536  
        copy(new File(src), new File(srcDir, "main.java"));
537  
      }
538  
539  
      if (!new File(srcDir, "main.java").exists())
540  
        return null;
541  
    }
542  
543  
    // translate
544  
545  
    File X = srcDir;
546  
547  
    if (!isTranspiled) {
548  
      X = topLevelTranslate(X, libraries);
549  
      System.err.println("Translated " + src);
550  
551  
      // save prefetch data
552  
      if (isSnippetID(src))
553  
        savePrefetchData(src);
554  
    }
555  
    return X;
556  
  }
557  
558  
  private static void prefetch(String mainSnippetID) throws IOException {
559  
    if (noPrefetch) return;
560  
561  
    long mainID = parseSnippetID(mainSnippetID);
562  
    String s = mainID + " " + loadTextFile(new File(userHome(), ".tinybrain/prefetch/" + mainID + ".txt").getPath(), "");
563  
    String[] ids = s.trim().split(" ");
564  
    if (ids.length > 1) {
565  
      String url = "http://tinybrain.de:8080/tb-int/prefetch.php?ids=" + URLEncoder.encode(s, "UTF-8");
566  
      String data = loadPage(new URL(url));
567  
      String[] split = data.split(" ");
568  
      if (split.length == ids.length)
569  
        for (int i = 0; i < ids.length; i++)
570  
          prefetched.put(parseSnippetID(ids[i]), split[i]);
571  
    }
572  
  }
573  
  
574  
  static String getDexCacheHome() {
575  
    return ((File) call(androidContext, "getFilesDir")).getAbsolutePath();
576  
  }
577  
578  
  static String _userHome;
579  
  static String userHome() {
580  
    if (_userHome == null) {
581  
      if (isAndroid())
582  
        _userHome = "/storage/sdcard0/";
583  
      else
584  
        _userHome = System.getProperty("user.home");
585  
      //System.out.println("userHome: " + _userHome);
586  
    }
587  
    return _userHome;
588  
  }
589  
590  
  private static void savePrefetchData(String mainSnippetID) throws IOException {
591  
    List<String> ids = new ArrayList<String>();
592  
    long mainID = parseSnippetID(mainSnippetID);
593  
594  
    for (long id : memSnippetCache.keySet())
595  
      if (id != mainID)
596  
        ids.add(String.valueOf(id));
597  
598  
    saveTextFile(new File(userHome(),".tinybrain/prefetch/" + mainID + ".txt").getPath(), join(" ", ids));
599  
  }
600  
601  
  static File topLevelTranslate(File srcDir, List<File> libraries_out) throws Exception {
602  
    File X = srcDir;
603  
    X = applyTranslators(X, mainTranslators, libraries_out); // translators supplied on command line (unusual)
604  
605  
    // actual inner translation of the JavaX source
606  
    X = defaultTranslate(X, libraries_out);
607  
    return X;
608  
  }
609  
610  
  private static File defaultTranslate(File x, List<File> libraries_out) throws Exception {
611  
    x = luaPrintToJavaPrint(x);
612  
    x = repeatAutoTranslate(x, libraries_out);
613  
    return x;
614  
  }
615  
616  
  private static File repeatAutoTranslate(File x, List<File> libraries_out) throws Exception {
617  
    List<String[]> postTranslators = new ArrayList<String[]>();
618  
    
619  
    while (true) {
620  
      String main = loadTextFile(new File(x, "main.java").getPath(), null);
621  
      List<String> lines = toLines(main);
622  
      List<String[]> t = findPostTranslators(lines);
623  
      postTranslators.addAll(t);
624  
      
625  
      if (!t.isEmpty()) {
626  
        main = fromLines(lines);
627  
        x = TempDirMaker_make();
628  
        saveTextFile(new File(x, "main.java").getPath(), main);
629  
      }
630  
631  
      File y = autoTranslate(x, libraries_out);
632  
      if (y == x)
633  
        break;
634  
      x = y;
635  
    }
636  
    
637  
    x = applyTranslators(x, postTranslators, libraries_out);
638  
    
639  
    return x;
640  
  }
641  
642  
  private static File autoTranslate(File x, List<File> libraries_out) throws Exception {
643  
    String main = loadTextFile(new File(x, "main.java").getPath(), null);
644  
    List<String> lines = toLines(main);
645  
    List<String[]> translators = findTranslators(lines);
646  
    if (translators.isEmpty())
647  
      return x;
648  
649  
    main = fromLines(lines);
650  
    File newDir = TempDirMaker_make();
651  
    saveTextFile(new File(newDir, "main.java").getPath(), main);
652  
    return applyTranslators(newDir, translators, libraries_out);
653  
  }
654  
655  
  static List<String[]> findTranslators(List<String> lines) {
656  
    List<String[]> translators = new ArrayList<String[]>();
657  
    Pattern pattern = Pattern.compile("^!([0-9# \t]+)");
658  
    Pattern pArgs = Pattern.compile("^\\s*\\((.*)\\)");
659  
    for (ListIterator<String> iterator = lines.listIterator(); iterator.hasNext(); ) {
660  
      String line = iterator.next();
661  
      line = line.trim();
662  
      Matcher matcher = pattern.matcher(line);
663  
      if (matcher.find()) {
664  
        String[] t = matcher.group(1).split("[ \t]+");
665  
        String rest = line.substring(matcher.end());
666  
        String arg = null;
667  
        if (t.length == 1) {
668  
          Matcher mArgs = pArgs.matcher(rest);
669  
          if (mArgs.find())
670  
            arg = mArgs.group(1);
671  
        }
672  
        for (String transi : t)
673  
          translators.add(new String[]{transi, arg});
674  
        iterator.remove();
675  
      }
676  
    }
677  
    return translators;
678  
  }
679  
680  
  static List<String[]> findPostTranslators(List<String> lines) {
681  
    List<String[]> translators = new ArrayList<String[]>();
682  
    Pattern pattern = Pattern.compile("^!post\\s*([0-9# \t]+)");
683  
    Pattern pArgs = Pattern.compile("^\\s*\\((.*)\\)");
684  
    for (ListIterator<String> iterator = lines.listIterator(); iterator.hasNext(); ) {
685  
      String line = iterator.next();
686  
      line = line.trim();
687  
      Matcher matcher = pattern.matcher(line);
688  
      if (matcher.find()) {
689  
        String[] t = matcher.group(1).split("[ \t]+");
690  
        String rest = line.substring(matcher.end());
691  
        String arg = null;
692  
        if (t.length == 1) {
693  
          Matcher mArgs = pArgs.matcher(rest);
694  
          if (mArgs.find())
695  
            arg = mArgs.group(1);
696  
        }
697  
        for (String transi : t)
698  
          translators.add(new String[]{transi, arg});
699  
        iterator.remove();
700  
      }
701  
    }
702  
    return translators;
703  
  }
704  
705  
  public static List<String> toLines(String s) {
706  
    List<String> lines = new ArrayList<String>();
707  
    int start = 0;
708  
    while (true) {
709  
      int i = toLines_nextLineBreak(s, start);
710  
      if (i < 0) {
711  
        if (s.length() > start) lines.add(s.substring(start));
712  
        break;
713  
      }
714  
715  
      lines.add(s.substring(start, i));
716  
      if (s.charAt(i) == '\r' && i+1 < s.length() && s.charAt(i+1) == '\n')
717  
        i += 2;
718  
      else
719  
        ++i;
720  
721  
      start = i;
722  
    }
723  
    return lines;
724  
  }
725  
726  
  private static int toLines_nextLineBreak(String s, int start) {
727  
    for (int i = start; i < s.length(); i++) {
728  
      char c = s.charAt(i);
729  
      if (c == '\r' || c == '\n')
730  
        return i;
731  
    }
732  
    return -1;
733  
  }
734  
735  
  public static String fromLines(List<String> lines) {
736  
    StringBuilder buf = new StringBuilder();
737  
    for (String line : lines) {
738  
      buf.append(line).append('\n');
739  
    }
740  
    return buf.toString();
741  
  }
742  
743  
  private static File applyTranslators(File x, List<String[]> translators, List<File> libraries_out) throws Exception {
744  
    for (String[] translator : translators)
745  
      x = applyTranslator(x, translator[0], translator[1], libraries_out);
746  
    return x;
747  
  }
748  
749  
  // also takes a library
750  
  private static File applyTranslator(File x, String translator, String arg, List<File> libraries_out) throws Exception {
751  
    if (verbose)
752  
      System.out.println("Using translator " + translator + " on sources in " + x.getPath());
753  
754  
    File newDir = runTranslatorOnInput(translator, null, arg, x, !verbose, libraries_out);
755  
756  
    if (!new File(newDir, "main.java").exists()) {
757  
      throw new Exception("Translator " + translator + " did not generate main.java");
758  
      // TODO: show translator output
759  
    }
760  
    if (verbose)
761  
      System.out.println("Translated with " + translator + " from " + x.getPath() + " to " + newDir.getPath());
762  
    x = newDir;
763  
    return x;
764  
  }
765  
766  
  private static File luaPrintToJavaPrint(File x) throws IOException {
767  
    File newDir = TempDirMaker_make();
768  
    String code = loadTextFile(new File(x, "main.java").getPath(), null);
769  
    code = luaPrintToJavaPrint(code);
770  
    saveTextFile(new File(newDir, "main.java").getPath(), code);
771  
    return newDir;
772  
  }
773  
774  
  public static String luaPrintToJavaPrint(String code) {
775  
    return ("\n" + code).replaceAll(
776  
      "(\n\\s*)print (\".*\")",
777  
      "$1System.out.println($2);").substring(1);
778  
  }
779  
780  
  public static File loadSnippetAsMainJava(String snippetID) throws IOException {
781  
    checkProgramSafety(snippetID);
782  
    File srcDir = TempDirMaker_make();
783  
    saveTextFile(new File(srcDir, "main.java").getPath(), loadSnippet(snippetID));
784  
    return srcDir;
785  
  }
786  
787  
  public static File loadSnippetAsMainJavaVerified(String snippetID, String hash) throws IOException {
788  
    checkProgramSafety(snippetID);
789  
    File srcDir = TempDirMaker_make();
790  
    saveTextFile(new File(srcDir, "main.java").getPath(), loadSnippetVerified(snippetID, hash));
791  
    return srcDir;
792  
  }
793  
794  
  @SuppressWarnings( "unchecked" )
795  
  /** returns output dir */
796  
  private static File runTranslatorOnInput(String snippetID, String hash, String arg, File input,
797  
                                           boolean silent,
798  
                                           List<File> libraries_out) throws Exception {
799  
    if (safeTranslate)
800  
      checkProgramSafetyImpl(snippetID);
801  
    long id = parseSnippetID(snippetID);
802  
803  
    // It's a library, not a translator.
804  
    File libraryFile = DiskSnippetCache_getLibrary(id);
805  
    if (verbose)
806  
      System.out.println("Library file for " + id + ": " + libraryFile);
807  
    if (libraryFile != null) {
808  
      loadLibrary(snippetID, libraries_out, libraryFile);
809  
      return input;
810  
    }
811  
812  
    String[] args = arg != null ? new String[]{arg} : new String[0];
813  
814  
    File srcDir = hash == null ? loadSnippetAsMainJava(snippetID)
815  
      : loadSnippetAsMainJavaVerified(snippetID, hash);
816  
    long mainJavaSize = new File(srcDir, "main.java").length();
817  
818  
    if (verbose)
819  
      System.out.println(snippetID + ": length = " + mainJavaSize);
820  
    if (mainJavaSize == 0) { // no text in snippet? assume it's a library
821  
      loadLibrary(snippetID, libraries_out, libraryFile);
822  
      return input;
823  
    }
824  
825  
    List<File> libraries = new ArrayList<File>();
826  
    Object[] cached = translationCache.get(id);
827  
    if (cached != null) {
828  
      //System.err.println("Taking translator " + snippetID + " from cache!");
829  
      srcDir = (File) cached[0];
830  
      libraries = (List<File>) cached[1];
831  
    } else if (hasTranspiledSet.contains(id) && useServerTranspiled) {
832  
      System.err.println("Trying pretranspiled translator: #" + snippetID);
833  
      String transpiledSrc = getServerTranspiled(snippetID);
834  
      transpiledSrc = transpiledSrc.substring(transpiledSrc.indexOf('\n')+1);
835  
      // TODO: check for libraries
836  
      if (!transpiledSrc.isEmpty()) {
837  
        srcDir = TempDirMaker_make();
838  
        saveTextFile(new File(srcDir, "main.java").getPath(), transpiledSrc);
839  
        translationCache.put(id, cached = new Object[] {srcDir, libraries});
840  
      }
841  
    }
842  
843  
    File ioBaseDir = TempDirMaker_make();
844  
845  
    /*Class<?> mainClass = programCache.get("" + parseSnippetID(snippetID));
846  
    if (mainClass != null)
847  
      return runCached(ioBaseDir, input, args);*/
848  
    // Doesn't work yet because virtualized directories are hardcoded in translator...
849  
850  
    if (cached == null) {
851  
      System.err.println("Translating translator #" + id);
852  
      if (translating.contains(id))
853  
        throw new RuntimeException("Recursive translator reference chain including #" + id);
854  
      translating.add(id);
855  
      try {
856  
        srcDir = defaultTranslate(srcDir, libraries);
857  
      } finally {
858  
        translating.remove(id);
859  
      }
860  
      System.err.println("Translated translator #" + id);
861  
      translationCache.put(id, new Object[]{srcDir, libraries});
862  
    }
863  
864  
    boolean runInProcess = false;
865  
866  
    if (virtualizeTranslators) {
867  
      if (verbose) System.out.println("Virtualizing translator");
868  
869  
      // TODO: don't virtualize class _javax (as included in, say, #636)
870  
871  
      //srcDir = applyTranslator(srcDir, "#2000351"); // I/O-virtualize the translator
872  
      // that doesn't work because it recurses infinitely...
873  
874  
      // So we do it right here:
875  
      String s = loadTextFile(new File(srcDir, "main.java").getPath(), null);
876  
      s = s.replaceAll("new\\s+File\\(", "virtual.newFile(");
877  
      s = s.replaceAll("new\\s+FileInputStream\\(", "virtual.newFileInputStream(");
878  
      s = s.replaceAll("new\\s+FileOutputStream\\(", "virtual.newFileOutputStream(");
879  
      s += "\n\n" + loadSnippet("#2000355"); // load class virtual
880  
881  
      // forward snippet cache (virtualized one)
882  
      File dir = virtCache != null ? virtCache : DiskSnippetCache_dir;
883  
      s = s.replace("static File DiskSnippetCache_dir" + ";",
884  
        "static File DiskSnippetCache_dir " + "= new File(" + javaQuote(dir.getAbsolutePath()) + ");"); // extra + is necessary for Dumb TinyBrain :)
885  
      s = s.replace("static boolean preferCached = false;", "static boolean preferCached = true;");
886  
887  
      if (verbose) {
888  
        System.out.println("==BEGIN VIRTUALIZED TRANSLATOR==");
889  
        System.out.println(s);
890  
        System.out.println("==END VIRTUALIZED TRANSLATOR==");
891  
      }
892  
      srcDir = TempDirMaker_make();
893  
      saveTextFile(new File(srcDir, "main.java").getPath(), s);
894  
895  
      // TODO: silence translator also
896  
      runInProcess = true;
897  
    }
898  
899  
    return runJavaX(ioBaseDir, srcDir, input, silent, runInProcess, libraries,
900  
      args, cacheTranslators ? "" + id : null, "" + id);
901  
  }
902  
903  
  private static String getServerTranspiled(String snippetID) throws IOException {
904  
    long id = parseSnippetID(snippetID);
905  
    URL url = new URL("http://tinybrain.de:8080/tb-int/get-transpiled.php?raw=1&withlibs=1&id=" + id);
906  
    return loadPage(url);
907  
  }
908  
909  
  static void checkProgramSafety(String snippetID) throws IOException {
910  
    if (!safeOnly) return;
911  
    checkProgramSafetyImpl(snippetID);
912  
  }
913  
914  
  static void checkProgramSafetyImpl(String snippetID) throws IOException {
915  
    URL url = new URL("http://tinybrain.de:8080/tb-int/is-javax-safe.php?id=" + parseSnippetID(snippetID));
916  
    String text = loadPage(url);
917  
    if (!text.startsWith("{\"safe\":\"1\"}"))
918  
      throw new RuntimeException("Program not safe: #" + parseSnippetID(snippetID));
919  
  }
920  
921  
  static void loadLibrary(String snippetID, List<File> libraries_out, File libraryFile) throws IOException {
922  
    if (verbose)
923  
      System.out.println("Assuming " + snippetID + " is a library.");
924  
925  
    if (libraryFile == null) {
926  
      byte[] data = loadDataSnippetImpl(snippetID);
927  
      DiskSnippetCache_putLibrary(parseSnippetID(snippetID), data);
928  
      libraryFile = DiskSnippetCache_getLibrary(parseSnippetID(snippetID));
929  
    }
930  
931  
    if (!libraries_out.contains(libraryFile))
932  
      libraries_out.add(libraryFile);
933  
  }
934  
935  
  private static byte[] loadDataSnippetImpl2(String snippetID) throws IOException {
936  
    byte[] data;
937  
    try {
938  
      URL url = new URL("http://eyeocr.sourceforge.net/filestore/filestore.php?cmd=serve&file=blob_"
939  
        + parseSnippetID(snippetID) + "&contentType=application/binary");
940  
      System.err.println("Loading library: " + url);
941  
      data = loadBinaryPage(url.openConnection());
942  
      if (verbose)
943  
        System.err.println("Bytes loaded: " + data.length);
944  
    } catch (FileNotFoundException e) {
945  
      throw new IOException("Binary snippet #" + snippetID + " not found or not public");
946  
    }
947  
    return data;
948  
  }
949  
950  
  /** returns output dir */
951  
  private static File runJavaX(File ioBaseDir, File originalSrcDir, File originalInput,
952  
                               boolean silent, boolean runInProcess,
953  
                               List<File> libraries, String[] args, String cacheAs,
954  
                               String programID) throws Exception {
955  
    File srcDir = new File(ioBaseDir, "src");
956  
    File inputDir = new File(ioBaseDir, "input");
957  
    File outputDir = new File(ioBaseDir, "output");
958  
    copyInput(originalSrcDir, srcDir);
959  
    copyInput(originalInput, inputDir);
960  
    javax2(srcDir, ioBaseDir, silent, runInProcess, libraries, args, cacheAs, programID, null);
961  
    return outputDir;
962  
  }
963  
964  
  private static void copyInput(File src, File dst) throws IOException {
965  
    copyDirectory(src, dst);
966  
  }
967  
968  
  public static boolean hasFile(File inputDir, String name) {
969  
    return new File(inputDir, name).exists();
970  
  }
971  
972  
  public static void copyDirectory(File src, File dst) throws IOException {
973  
    if (verbose) System.out.println("Copying " + src.getAbsolutePath() + " to " + dst.getAbsolutePath());
974  
    dst.mkdirs();
975  
    File[] files = src.listFiles();
976  
    if (files == null) return;
977  
    for (File file : files) {
978  
      File dst1 = new File(dst, file.getName());
979  
      if (file.isDirectory())
980  
        copyDirectory(file, dst1);
981  
      else {
982  
        if (verbose) System.out.println("Copying " + file.getAbsolutePath() + " to " + dst1.getAbsolutePath());
983  
        copy(file, dst1);
984  
      }
985  
    }
986  
  }
987  
988  
  /** Quickly copy a file without a progress bar or any other fancy GUI... :) */
989  
  public static void copy(File src, File dest) throws IOException {
990  
    FileInputStream inputStream = newFileInputStream(src);
991  
    FileOutputStream outputStream = newFileOutputStream(dest);
992  
    try {
993  
      copy(inputStream, outputStream);
994  
      inputStream.close();
995  
    } finally {
996  
      outputStream.close();
997  
    }
998  
  }
999  
1000  
  static Object call(Object o, String method, Object... args) {
1001  
    try {
1002  
      Method m = call_findMethod(o, method, args, false);
1003  
      m.setAccessible(true);
1004  
      return m.invoke(o, args);
1005  
    } catch (Exception e) {
1006  
      throw new RuntimeException(e);
1007  
    }
1008  
  }
1009  
1010  
  static Object call(Class c, String method, Object... args) {
1011  
    try {
1012  
      Method m = call_findStaticMethod(c, method, args, false);
1013  
      m.setAccessible(true);
1014  
      return m.invoke(null, args);
1015  
    } catch (Exception e) {
1016  
      throw new RuntimeException(e);
1017  
    }
1018  
  }
1019  
1020  
  static Method call_findStaticMethod(Class c, String method, Object[] args, boolean debug) {
1021  
    while (c != null) {
1022  
      for (Method m : c.getDeclaredMethods()) {
1023  
        if (debug)
1024  
          System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");;
1025  
        if (!m.getName().equals(method)) {
1026  
          if (debug) System.out.println("Method name mismatch: " + method);
1027  
          continue;
1028  
        }
1029  
1030  
        if ((m.getModifiers() & Modifier.STATIC) == 0 || !call_checkArgs(m, args, debug))
1031  
          continue;
1032  
1033  
        return m;
1034  
      }
1035  
      c = c.getSuperclass();
1036  
    }
1037  
    throw new RuntimeException("Method '" + method + "' (static) with " + args.length + " parameter(s) not found in " + c.getName());
1038  
  }
1039  
1040  
  static Method call_findMethod(Object o, String method, Object[] args, boolean debug) {
1041  
    Class c = o.getClass();
1042  
    while (c != null) {
1043  
      for (Method m : c.getDeclaredMethods()) {
1044  
        if (debug)
1045  
          System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");;
1046  
        if (m.getName().equals(method) && call_checkArgs(m, args, debug))
1047  
          return m;
1048  
      }
1049  
      c = c.getSuperclass();
1050  
    }
1051  
    throw new RuntimeException("Method '" + method + "' (non-static) with " + args.length + " parameter(s) not found in " + o.getClass().getName());
1052  
  }
1053  
1054  
  private static boolean call_checkArgs(Method m, Object[] args, boolean debug) {
1055  
    Class<?>[] types = m.getParameterTypes();
1056  
    if (types.length != args.length) {
1057  
      if (debug)
1058  
        System.out.println("checkArgs: Bad parameter length: " + args.length + " vs " + types.length);
1059  
      return false;
1060  
    }
1061  
    for (int i = 0; i < types.length; i++)
1062  
      if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
1063  
        if (debug)
1064  
          System.out.println("checkArgs: Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
1065  
        return false;
1066  
      }
1067  
    return true;
1068  
  }
1069  
1070  
  private static FileInputStream newFileInputStream(File f) throws FileNotFoundException {
1071  
    /*if (androidContext != null)
1072  
      return (FileInputStream) call(androidContext,
1073  
        "openFileInput", f.getPath());
1074  
    else*/
1075  
    return new // line break for Dumb TinyBrain :)
1076  
    FileInputStream(f);
1077  
  }
1078  
1079  
  private static FileOutputStream newFileOutputStream(File f) throws FileNotFoundException {
1080  
    /*if (androidContext != null)
1081  
      return (FileOutputStream) call(androidContext,
1082  
        "openFileOutput", f.getPath(), 0);
1083  
    else*/
1084  
    return new // line break for Dumb TinyBrain :)
1085  
    FileOutputStream(f);
1086  
  }
1087  
1088  
  public static void copy(InputStream in, OutputStream out) throws IOException {
1089  
    byte[] buf = new byte[65536];
1090  
    while (true) {
1091  
      int n = in.read(buf);
1092  
      if (n <= 0) return;
1093  
      out.write(buf, 0, n);
1094  
    }
1095  
  }
1096  
1097  
  /** writes safely (to temp file, then rename) */
1098  
  public static void saveTextFile(String fileName, String contents) throws IOException {
1099  
    File file = new File(fileName);
1100  
    File parentFile = file.getParentFile();
1101  
    if (parentFile != null)
1102  
      parentFile.mkdirs();
1103  
    String tempFileName = fileName + "_temp";
1104  
    FileOutputStream fileOutputStream = newFileOutputStream(new File(tempFileName));
1105  
    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, charsetForTextFiles);
1106  
    PrintWriter printWriter = new PrintWriter(outputStreamWriter);
1107  
    printWriter.print(contents);
1108  
    printWriter.close();
1109  
    if (file.exists() && !file.delete())
1110  
      throw new IOException("Can't delete " + fileName);
1111  
1112  
    if (!new File(tempFileName).renameTo(file))
1113  
      throw new IOException("Can't rename " + tempFileName + " to " + fileName);
1114  
  }
1115  
1116  
  /** writes safely (to temp file, then rename) */
1117  
  public static void saveBinaryFile(String fileName, byte[] contents) throws IOException {
1118  
    File file = new File(fileName);
1119  
    File parentFile = file.getParentFile();
1120  
    if (parentFile != null)
1121  
      parentFile.mkdirs();
1122  
    String tempFileName = fileName + "_temp";
1123  
    FileOutputStream fileOutputStream = newFileOutputStream(new File(tempFileName));
1124  
    fileOutputStream.write(contents);
1125  
    fileOutputStream.close();
1126  
    if (file.exists() && !file.delete())
1127  
      throw new IOException("Can't delete " + fileName);
1128  
1129  
    if (!new File(tempFileName).renameTo(file))
1130  
      throw new IOException("Can't rename " + tempFileName + " to " + fileName);
1131  
  }
1132  
1133  
    public static String loadTextFile(String fileName) {
1134  
    try {
1135  
      return loadTextFile(fileName, null);
1136  
    } catch (IOException e) {
1137  
      throw new RuntimeException(e);
1138  
    }
1139  
  }
1140  
  
1141  
  public static String loadTextFile(String fileName, String defaultContents) throws IOException {
1142  
    if (!new File(fileName).exists())
1143  
      return defaultContents;
1144  
1145  
    FileInputStream fileInputStream = new FileInputStream(fileName);
1146  
    InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
1147  
    return loadTextFile(inputStreamReader);
1148  
  }
1149  
  
1150  
  public static String loadTextFile(File fileName) {
1151  
    try {
1152  
      return loadTextFile(fileName, null);
1153  
    } catch (IOException e) {
1154  
      throw new RuntimeException(e);
1155  
    }
1156  
  }
1157  
1158  
  public static String loadTextFile(File fileName, String defaultContents) throws IOException {
1159  
    try {
1160  
      return loadTextFile(fileName.getPath(), defaultContents);
1161  
    } catch (IOException e) {
1162  
      throw new RuntimeException(e);
1163  
    }
1164  
  }
1165  
  
1166  
  public static String loadTextFile(Reader reader) throws IOException {
1167  
    StringBuilder builder = new StringBuilder();
1168  
    try {
1169  
      char[] buffer = new char[1024];
1170  
      int n;
1171  
      while (-1 != (n = reader.read(buffer)))
1172  
        builder.append(buffer, 0, n);
1173  
        
1174  
    } finally {
1175  
      reader.close();
1176  
    }
1177  
    return builder.toString();
1178  
  } // loadTextFile
1179  
  
1180  
  static File DiskSnippetCache_dir;
1181  
1182  
  public static void initDiskSnippetCache(File dir) {
1183  
    DiskSnippetCache_dir = dir;
1184  
    dir.mkdirs();
1185  
  }
1186  
1187  
  // Data files are immutable, use centralized cache
1188  
  public static synchronized File DiskSnippetCache_getLibrary(long snippetID) throws IOException {
1189  
    File file = new File(getGlobalCache(), "data_" + snippetID + ".jar");
1190  
    if (verbose)
1191  
      System.out.println("Checking data cache: " + file.getPath());
1192  
    return file.exists() ? file : null;
1193  
  }
1194  
1195  
  public static synchronized String DiskSnippetCache_get(long snippetID) throws IOException {
1196  
    return loadTextFile(DiskSnippetCache_getFile(snippetID).getPath(), null);
1197  
  }
1198  
1199  
  private static File DiskSnippetCache_getFile(long snippetID) {
1200  
    return new File(DiskSnippetCache_dir, "" + snippetID);
1201  
  }
1202  
1203  
  public static synchronized void DiskSnippetCache_put(long snippetID, String snippet) throws IOException {
1204  
    saveTextFile(DiskSnippetCache_getFile(snippetID).getPath(), snippet);
1205  
  }
1206  
1207  
  public static synchronized void DiskSnippetCache_putLibrary(long snippetID, byte[] data) throws IOException {
1208  
    saveBinaryFile(new File(getGlobalCache(), "data_" + snippetID).getPath() + ".jar", data);
1209  
  }
1210  
1211  
  public static File DiskSnippetCache_getDir() {
1212  
    return DiskSnippetCache_dir;
1213  
  }
1214  
1215  
  public static void initSnippetCache() {
1216  
    if (DiskSnippetCache_dir == null)
1217  
      initDiskSnippetCache(getGlobalCache());
1218  
  }
1219  
1220  
  private static File getGlobalCache() {
1221  
    File file = new File(userHome(), ".tinybrain/snippet-cache");
1222  
    file.mkdirs();
1223  
    return file;
1224  
  }
1225  
1226  
  public static String loadSnippetVerified(String snippetID, String hash) throws IOException {
1227  
    String text = loadSnippet(snippetID);
1228  
    String realHash = getHash(text.getBytes("UTF-8"));
1229  
    if (!realHash.equals(hash)) {
1230  
      String msg;
1231  
      if (hash.isEmpty())
1232  
        msg = "Here's your hash for " + snippetID + ", please put in your program: " + realHash;
1233  
      else
1234  
        msg = "Hash mismatch for " + snippetID + ": " + realHash + " (new) vs " + hash + " - has tinybrain.de been hacked??";
1235  
      throw new RuntimeException(msg);
1236  
    }
1237  
    return text;
1238  
  }
1239  
1240  
  public static String getHash(byte[] data) {
1241  
    return bytesToHex(getFullFingerprint(data));
1242  
  }
1243  
1244  
  public static byte[] getFullFingerprint(byte[] data) {
1245  
    try {
1246  
      return MessageDigest.getInstance("MD5").digest(data);
1247  
    } catch (NoSuchAlgorithmException e) {
1248  
      throw new RuntimeException(e);
1249  
    }
1250  
  }
1251  
1252  
  public static String bytesToHex(byte[] bytes) {
1253  
    return bytesToHex(bytes, 0, bytes.length);
1254  
  }
1255  
1256  
  public static String bytesToHex(byte[] bytes, int ofs, int len) {
1257  
    StringBuilder stringBuilder = new StringBuilder(len*2);
1258  
    for (int i = 0; i < len; i++) {
1259  
      String s = "0" + Integer.toHexString(bytes[ofs+i]);
1260  
      stringBuilder.append(s.substring(s.length()-2, s.length()));
1261  
    }
1262  
    return stringBuilder.toString();
1263  
  }
1264  
1265  
  public static String loadSnippet(String snippetID) throws IOException {
1266  
    return loadSnippet(parseSnippetID(snippetID));
1267  
  }
1268  
1269  
  public static long parseSnippetID(String snippetID) {
1270  
    return Long.parseLong(shortenSnippetID(snippetID));
1271  
  }
1272  
1273  
  private static String shortenSnippetID(String snippetID) {
1274  
    if (snippetID.startsWith("#"))
1275  
      snippetID = snippetID.substring(1);
1276  
    String httpBlaBla = "http://tinybrain.de/";
1277  
    if (snippetID.startsWith(httpBlaBla))
1278  
      snippetID = snippetID.substring(httpBlaBla.length());
1279  
    return snippetID;
1280  
  }
1281  
1282  
  public static boolean isSnippetID(String snippetID) {
1283  
    snippetID = shortenSnippetID(snippetID);
1284  
    return isInteger(snippetID) && Long.parseLong(snippetID) != 0;
1285  
  }
1286  
1287  
  public static boolean isInteger(String s) {
1288  
    return Pattern.matches("\\-?\\d+", s);
1289  
  }
1290  
1291  
  public static String loadSnippet(long snippetID) throws IOException {
1292  
    String text = memSnippetCache.get(snippetID);
1293  
    if (text != null) {
1294  
      if (verbose)
1295  
        System.out.println("Getting " + snippetID + " from mem cache");
1296  
      return text;
1297  
    }
1298  
1299  
    initSnippetCache();
1300  
    text = DiskSnippetCache_get(snippetID);
1301  
    if (preferCached && text != null) {
1302  
      if (verbose)
1303  
        System.out.println("Getting " + snippetID + " from disk cache (preferCached)");
1304  
      return text;
1305  
    }
1306  
1307  
    String md5 = text != null ? md5(text) : "-";
1308  
    if (text != null) {
1309  
      String hash = prefetched.get(snippetID);
1310  
      if (hash != null) {
1311  
        if (md5.equals(hash)) {
1312  
          memSnippetCache.put(snippetID, text);
1313  
          if (verbose)
1314  
            System.out.println("Getting " + snippetID + " from prefetched");
1315  
          return text;
1316  
        } else
1317  
          prefetched.remove(snippetID); // (maybe this is not necessary)
1318  
      }
1319  
    }
1320  
1321  
    try {
1322  
      /*URL url = new URL("http://tinybrain.de:8080/getraw.php?id=" + snippetID);
1323  
      text = loadPage(url);*/
1324  
      String theURL = "http://tinybrain.de:8080/getraw.php?id=" + snippetID + "&getmd5=1&utf8=1&usetranspiled=1";
1325  
      if (text != null) {
1326  
        //System.err.println("MD5: " + md5);
1327  
        theURL += "&md5=" + md5;
1328  
      }
1329  
      URL url = new URL(theURL);
1330  
      String page = loadPage(url);
1331  
1332  
      // parse & drop transpilation flag available line
1333  
      int i = page.indexOf('\n');
1334  
      boolean hasTranspiled = page.substring(0, i).trim().equals("1");
1335  
      if (hasTranspiled)
1336  
        hasTranspiledSet.add(snippetID);
1337  
      else
1338  
        hasTranspiledSet.remove(snippetID);
1339  
      page = page.substring(i+1);
1340  
1341  
      if (page.startsWith("==*#*==")) {
1342  
        // same, keep text
1343  
        //System.err.println("Snippet unchanged, keeping.");
1344  
      } else {
1345  
        // drop md5 line
1346  
        i = page.indexOf('\n');
1347  
        String hash = page.substring(0, i).trim();
1348  
        text = page.substring(i+1);
1349  
1350  
        String myHash = md5(text);
1351  
        if (myHash.equals(hash)) {
1352  
          //System.err.println("Hash match: " + hash);
1353  
        } else
1354  
          System.err.println("Hash mismatch");
1355  
      }
1356  
    } catch (FileNotFoundException e) {
1357  
      e.printStackTrace();
1358  
      throw new IOException("Snippet #" + snippetID + " not found or not public");
1359  
    }
1360  
1361  
    memSnippetCache.put(snippetID, text);
1362  
1363  
    try {
1364  
      initSnippetCache();
1365  
      DiskSnippetCache_put(snippetID, text);
1366  
    } catch (IOException e) {
1367  
      System.err.println("Minor warning: Couldn't save snippet to cache ("  + DiskSnippetCache_getDir() + ")");
1368  
    }
1369  
1370  
    return text;
1371  
  }
1372  
1373  
  private static String md5(String text) {
1374  
    try {
1375  
      return bytesToHex(md5impl(text.getBytes("UTF-8"))); // maybe different than the way PHP does it...
1376  
    } catch (UnsupportedEncodingException e) {
1377  
      throw new RuntimeException(e);
1378  
    }
1379  
  }
1380  
1381  
  public static byte[] md5impl(byte[] data) {
1382  
    try {
1383  
      return MessageDigest.getInstance("MD5").digest(data);
1384  
    } catch (NoSuchAlgorithmException e) {
1385  
      throw new RuntimeException(e);
1386  
    }
1387  
  }
1388  
1389  
  private static String loadPage(URL url) throws IOException {
1390  
    System.err.println("Loading: " + url.toExternalForm());
1391  
    URLConnection con = url.openConnection();
1392  
    return loadPage(con, url);
1393  
  }
1394  
1395  
  public static String loadPage(URLConnection con, URL url) throws IOException {
1396  
    setHeaders(con);
1397  
    String contentType = con.getContentType();
1398  
    if (contentType == null)
1399  
      throw new IOException("Page could not be read: " + url);
1400  
    //Log.info("Content-Type: " + contentType);
1401  
    String charset = guessCharset(contentType);
1402  
    //System.err.println("Charset: " + charset);
1403  
    Reader r = new InputStreamReader(con.getInputStream(), charset);
1404  
    StringBuilder buf = new StringBuilder();
1405  
    while (true) {
1406  
      int ch = r.read();
1407  
      if (ch < 0)
1408  
        break;
1409  
      //Log.info("Chars read: " + buf.length());
1410  
      buf.append((char) ch);
1411  
    }
1412  
    return buf.toString();
1413  
  }
1414  
1415  
  public static byte[] loadBinaryPage(URLConnection con) throws IOException {
1416  
    setHeaders(con);
1417  
    return loadBinaryPage_noHeaders(con);
1418  
  }
1419  
1420  
  private static byte[] loadBinaryPage_noHeaders(URLConnection con) throws IOException {
1421  
    ByteArrayOutputStream buf = new ByteArrayOutputStream();
1422  
    InputStream inputStream = con.getInputStream();
1423  
    while (true) {
1424  
      int ch = inputStream.read();
1425  
      if (ch < 0)
1426  
        break;
1427  
      buf.write(ch);
1428  
    }
1429  
    inputStream.close();
1430  
    return buf.toByteArray();
1431  
  }
1432  
1433  
  private static void setHeaders(URLConnection con) throws IOException {
1434  
    String computerID = getComputerID();
1435  
    if (computerID != null)
1436  
      con.setRequestProperty("X-ComputerID", computerID);
1437  
  }
1438  
1439  
  public static String guessCharset(String contentType) {
1440  
    Pattern p = Pattern.compile("text/html;\\s+charset=([^\\s]+)\\s*");
1441  
    Matcher m = p.matcher(contentType);
1442  
    /* If Content-Type doesn't match this pre-conception, choose default and hope for the best. */
1443  
    return m.matches() ? m.group(1) : "ISO-8859-1";
1444  
  }
1445  
1446  
  /** runs a transpiled set of sources */
1447  
  public static void javax2(File srcDir, File ioBaseDir, boolean silent, boolean runInProcess,
1448  
                            List<File> libraries, String[] args, String cacheAs,
1449  
                            String programID, Info info) throws Exception {
1450  
    if (android) {
1451  
      // TODO: no translator virtualization? huh?
1452  
      javax2android(srcDir, args, programID);
1453  
    } else {
1454  
      File classesDir = TempDirMaker_make();
1455  
      String javacOutput = compileJava(srcDir, libraries, classesDir);
1456  
1457  
      // run
1458  
1459  
      if (verbose) System.out.println("Running program (" + srcDir.getAbsolutePath()
1460  
        + ") on io dir " + ioBaseDir.getAbsolutePath() + (runInProcess ? "[in-process]" : "") + "\n");
1461  
      runProgram(javacOutput, classesDir, ioBaseDir, silent, runInProcess, libraries, args, cacheAs, programID, info);
1462  
    }
1463  
  }
1464  
  
1465  
  static Class<?> mainClass;
1466  
1467  
  static Class<?> loadx2android(File srcDir, String programID) throws Exception {
1468  
    /*
1469  
    URL url = new URL("http://tinybrain.de:8080/dexcompile.php");
1470  
    URLConnection conn = url.openConnection();
1471  
    String postData = "src=" + URLEncoder.encode(loadTextFile(new File(srcDir, "main.java").getPath(), null), "UTF-8");
1472  
    byte[] dexData = doPostBinary(postData, conn);*/
1473  
    
1474  
    byte[] dexData = loadBinaryPage(new URL("http://tinybrain.de:8080/dexcompile.php?id=" + parseSnippetID(programID)).openConnection());
1475  
    
1476  
    if (!isDex(dexData))
1477  
      throw new RuntimeException("Dex generation error: " + dexData.length + " bytes - " + new String(dexData, "UTF-8"));
1478  
    System.out.println("Dex loaded: " + dexData.length + "b");
1479  
1480  
    File dexDir = TempDirMaker_make();
1481  
    File dexFile = new File(dexDir, System.currentTimeMillis() + ".dex");
1482  
    File dexOutputDir = TempDirMaker_makeDexCache();
1483  
1484  
    System.out.println("Saving dex to: " + dexDir.getAbsolutePath());
1485  
    try {
1486  
      saveBinaryFile(dexFile.getPath(), dexData);
1487  
    } catch (Throwable e) {
1488  
      System.out.println("Whoa!");
1489  
      throw new RuntimeException(e);
1490  
    }
1491  
1492  
    System.out.println("Getting parent class loader.");
1493  
    ClassLoader parentClassLoader =
1494  
      //ClassLoader.getSystemClassLoader(); // does not find support jar
1495  
      //getClass().getClassLoader(); // Let's try this...
1496  
      x27.class.getClassLoader().getParent(); // XXX !
1497  
1498  
    //System.out.println("Making DexClassLoader.");
1499  
    //DexClassLoader classLoader = new DexClassLoader(dexFile.getAbsolutePath(), dexOutputDir.getAbsolutePath(), null,
1500  
    //  parentClassLoader);
1501  
    Class dcl = Class.forName("dalvik.system.DexClassLoader");
1502  
    Object classLoader = dcl.getConstructors()[0].newInstance(dexFile.getAbsolutePath(), dexOutputDir.getAbsolutePath(), null,
1503  
      parentClassLoader);
1504  
1505  
    //System.out.println("Loading main class.");
1506  
    //Class<?> theClass = classLoader.loadClass(mainClassName);
1507  
    Class<?> theClass = (Class<?>) call(classLoader, "loadClass", "main");
1508  
    mainClass = theClass;
1509  
1510  
    //System.out.println("Main class loaded.");
1511  
    try {
1512  
      set(theClass, "androidContext", androidContext);
1513  
    } catch (Throwable e) {}
1514  
1515  
    setVars(theClass, programID);
1516  
1517  
    return theClass;
1518  
  }
1519  
1520  
  static void javax2android(File srcDir, String[] args, String programID) throws Exception {
1521  
    Class<?> theClass = loadx2android(srcDir, programID);
1522  
1523  
    Method main = null;
1524  
    try {
1525  
      main = call_findStaticMethod(theClass, "main", new Object[]{androidContext}, false);
1526  
    } catch (RuntimeException e) {
1527  
    }
1528  
1529  
    //System.out.println("main method for " + androidContext + " of " + theClass + ": " + main);
1530  
1531  
    if (main != null) {
1532  
      // old style main program that returns a View
1533  
      System.out.println("Calling main (old-style)");
1534  
      Object view = main.invoke(null, androidContext);
1535  
      System.out.println("Calling setContentView with " + view);
1536  
      call(Class.forName("main"), "setContentViewInUIThread", view);
1537  
      //call(androidContext, "setContentView", view);
1538  
      System.out.println("Done.");
1539  
    } else {
1540  
      System.out.println("New-style main method running.\n\n====\n");
1541  
      runMainMethod(args, theClass);
1542  
    }
1543  
  }
1544  
1545  
  static byte[] DEX_FILE_MAGIC = { 0x64, 0x65, 0x78, 0x0a, 0x30, 0x33, 0x35, 0x00 };
1546  
1547  
  static boolean isDex(byte[] dexData) {
1548  
    if (dexData.length < DEX_FILE_MAGIC.length) return false;
1549  
    for (int i = 0; i < DEX_FILE_MAGIC.length; i++)
1550  
      if (dexData[i] != DEX_FILE_MAGIC[i])
1551  
        return false;
1552  
    return true;
1553  
  }
1554  
1555  
  static byte[] doPostBinary(String urlParameters, URLConnection conn) throws IOException {
1556  
    // connect and do POST
1557  
    setHeaders(conn);
1558  
    conn.setDoOutput(true);
1559  
1560  
    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
1561  
    writer.write(urlParameters);
1562  
    writer.flush();
1563  
1564  
    byte[] contents = loadBinaryPage_noHeaders(conn);
1565  
    writer.close();
1566  
    return contents;
1567  
  }
1568  
1569  
  static String compileJava(File srcDir, List<File> libraries, File classesDir) throws IOException {
1570  
    javaCompilerOutput = null;
1571  
    ++compilations;
1572  
1573  
    // collect sources
1574  
1575  
    List<File> sources = new ArrayList<File>();
1576  
    if (verbose) System.out.println("Scanning for sources in " + srcDir.getPath());
1577  
    scanForSources(srcDir, sources, true);
1578  
    if (sources.isEmpty())
1579  
      throw new IOException("No sources found");
1580  
1581  
    // compile
1582  
1583  
    File optionsFile = File.createTempFile("javax", "");
1584  
    if (verbose) System.out.println("Compiling " + sources.size() + " source(s) to " + classesDir.getPath());
1585  
    if (verbose) System.out.println("Libraries: " + libraries);
1586  
    String options = "-d " + bashQuote(classesDir.getPath());
1587  
    writeOptions(sources, libraries, optionsFile, options);
1588  
    classesDir.mkdirs();
1589  
    return javaCompilerOutput = invokeJavaCompiler(optionsFile);
1590  
  }
1591  
1592  
  private static void runProgram(String javacOutput, File classesDir, File ioBaseDir,
1593  
                                 boolean silent, boolean runInProcess,
1594  
                                 List<File> libraries, String[] args, String cacheAs,
1595  
                                 String programID, Info info) throws Exception {
1596  
    // print javac output if compile failed and it hasn't been printed yet
1597  
    if (info != null) {
1598  
      info.programID = programID;
1599  
      info.programArgs = args;
1600  
    }
1601  
    boolean didNotCompile = !didCompile(classesDir);
1602  
    if (verbose || didNotCompile)
1603  
      System.out.println(javacOutput);
1604  
    if (didNotCompile)
1605  
      return;
1606  
1607  
    if (runInProcess
1608  
      || (ioBaseDir.getAbsolutePath().equals(new File(".").getAbsolutePath()) && !silent)) {
1609  
      runProgramQuick(classesDir, libraries, args, cacheAs, programID, info, ioBaseDir);
1610  
      return;
1611  
    }
1612  
1613  
    boolean echoOK = false;
1614  
    // TODO: add libraries to class path
1615  
    String bashCmd = "(cd " + bashQuote(ioBaseDir.getAbsolutePath()) + " && (java -cp "
1616  
      + bashQuote(classesDir.getAbsolutePath()) + " main" + (echoOK ? "; echo ok" : "") + "))";
1617  
    if (verbose) System.out.println(bashCmd);
1618  
    String output = backtick(bashCmd);
1619  
    lastOutput = output;
1620  
    if (verbose || !silent)
1621  
      System.out.println(output);
1622  
  }
1623  
1624  
  static boolean didCompile(File classesDir) {
1625  
    return hasFile(classesDir, "main.class");
1626  
  }
1627  
1628  
  private static void runProgramQuick(File classesDir, List<File> libraries,
1629  
                                      String[] args, String cacheAs,
1630  
                                      String programID, Info info,
1631  
                                      File ioBaseDir) throws Exception {
1632  
    // collect urls
1633  
    URL[] urls = new URL[libraries.size()+1];
1634  
    urls[0] = classesDir.toURI().toURL();
1635  
    for (int i = 0; i < libraries.size(); i++)
1636  
      urls[i+1] = libraries.get(i).toURI().toURL();
1637  
1638  
    // make class loader
1639  
    URLClassLoader classLoader = new URLClassLoader(urls);
1640  
1641  
    // load JavaX main class
1642  
    Class<?> mainClass = classLoader.loadClass("main");
1643  
    
1644  
    if (info != null)
1645  
      info.mainClass = mainClass;
1646  
      
1647  
    if (cacheAs != null)
1648  
      programCache.put(cacheAs, mainClass);
1649  
      
1650  
    // change baseDir
1651  
    try {
1652  
      //print("Changing base dir to " + ioBaseDir.getAbsolutePath());
1653  
      Class virtual = mainClass.getClassLoader().loadClass("virtual");
1654  
      set(virtual, "virtual_baseDir", ioBaseDir.getAbsolutePath());
1655  
    } catch (Throwable e) { /* whatever */ }
1656  
1657  
    setVars(mainClass, programID);
1658  
    runMainMethod(args, mainClass);
1659  
  }
1660  
1661  
  static void setVars(Class<?> theClass, String programID) {
1662  
    try {
1663  
      set(theClass, "programID", programID);
1664  
    } catch (Throwable e) {}
1665  
1666  
    try {
1667  
      set(theClass, "__javax", x27.class);
1668  
    } catch (Throwable e) {}
1669  
  }
1670  
1671  
1672  
  static void runMainMethod(Object args, Class<?> mainClass) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
1673  
    Method main = mainClass.getMethod("main", String[].class);
1674  
    main.invoke(null, args);
1675  
  }
1676  
1677  
  static String invokeJavaCompiler(File optionsFile) throws IOException {
1678  
    String output;
1679  
    if (hasEcj() && !javacOnly)
1680  
      output = invokeEcj(optionsFile);
1681  
    else
1682  
      output = invokeJavac(optionsFile);
1683  
    if (verbose) System.out.println(output);
1684  
    return output;
1685  
  }
1686  
1687  
  private static boolean hasEcj() {
1688  
    try {
1689  
      Class.forName("org.eclipse.jdt.internal.compiler.batch.Main");
1690  
      return true;
1691  
    } catch (ClassNotFoundException e) {
1692  
      return false;
1693  
    }
1694  
  }
1695  
1696  
  private static String invokeJavac(File optionsFile) throws IOException {
1697  
    String output;
1698  
    output = backtick("javac " + bashQuote("@" + optionsFile.getPath()));
1699  
    if (exitValue != 0) {
1700  
      System.out.println(output);
1701  
      throw new RuntimeException("javac returned errors.");
1702  
    }
1703  
    return output;
1704  
  }
1705  
1706  
  // throws ClassNotFoundException if ecj is not in classpath
1707  
  static String invokeEcj(File optionsFile) {
1708  
    try {
1709  
      StringWriter writer = new StringWriter();
1710  
      PrintWriter printWriter = new PrintWriter(writer);
1711  
1712  
      // add more eclipse options in the line below
1713  
1714  
      String[] args = {"@" + optionsFile.getPath(),
1715  
        "-source", javaTarget,
1716  
        "-target", javaTarget,
1717  
        "-nowarn"
1718  
      };
1719  
1720  
      Class ecjClass = Class.forName("org.eclipse.jdt.internal.compiler.batch.Main");
1721  
      Object main = newInstance(ecjClass, printWriter, printWriter, false);
1722  
      call(main, "compile", new Object[]{args});
1723  
      int errors = (Integer) get(main, "globalErrorsCount");
1724  
1725  
      String output = writer.toString();
1726  
      if (errors != 0) {
1727  
        System.out.println(output);
1728  
        throw new RuntimeException("Java compiler returned errors.");
1729  
      }
1730  
      return output;
1731  
    } catch (Exception e) {
1732  
      throw e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e);
1733  
    }
1734  
  }
1735  
1736  
  static Object newInstance(Class c, Object... args) { try {
1737  
    Constructor m = findConstructor(c, args);
1738  
    m.setAccessible(true);
1739  
    return m.newInstance(args);
1740  
  } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
1741  
1742  
  static Constructor findConstructor(Class c, Object... args) {
1743  
    for (Constructor m : c.getDeclaredConstructors()) {
1744  
      if (!checkArgs(m.getParameterTypes(), args, verbose))
1745  
        continue;
1746  
      return m;
1747  
    }
1748  
    throw new RuntimeException("Constructor with " + args.length + " matching parameter(s) not found in " + c.getName());
1749  
  }
1750  
1751  
  static boolean checkArgs(Class[] types, Object[] args, boolean debug) {
1752  
    if (types.length != args.length) {
1753  
      if (debug)
1754  
        System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
1755  
      return false;
1756  
    }
1757  
    for (int i = 0; i < types.length; i++)
1758  
      if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
1759  
        if (debug)
1760  
          System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
1761  
        return false;
1762  
      }
1763  
    return true;
1764  
  }
1765  
1766  
  // extended to handle primitive types
1767  
  private static boolean isInstanceX(Class type, Object arg) {
1768  
    if (type == boolean.class) return arg instanceof Boolean;
1769  
    if (type == int.class) return arg instanceof Integer;
1770  
    if (type == long.class) return arg instanceof Long;
1771  
    if (type == float.class) return arg instanceof Float;
1772  
    if (type == short.class) return arg instanceof Short;
1773  
    if (type == char.class) return arg instanceof Character;
1774  
    if (type == byte.class) return arg instanceof Byte;
1775  
    return type.isInstance(arg);
1776  
  }
1777  
1778  
  private static void writeOptions(List<File> sources, List<File> libraries,
1779  
                                   File optionsFile, String moreOptions) throws IOException {
1780  
    FileWriter writer = new FileWriter(optionsFile);
1781  
    for (File source : sources)
1782  
      writer.write(bashQuote(source.getPath()) + " ");
1783  
    if (!libraries.isEmpty()) {
1784  
      List<String> cp = new ArrayList<String>();
1785  
      for (File lib : libraries)
1786  
        cp.add(lib.getAbsolutePath());
1787  
      writer.write("-cp " + bashQuote(join(File.pathSeparator, cp)) + " ");
1788  
    }
1789  
    writer.write(moreOptions);
1790  
    writer.close();
1791  
  }
1792  
1793  
  static void scanForSources(File source, List<File> sources, boolean topLevel) {
1794  
    if (source.isFile() && source.getName().endsWith(".java"))
1795  
      sources.add(source);
1796  
    else if (source.isDirectory() && !isSkippedDirectoryName(source.getName(), topLevel)) {
1797  
      File[] files = source.listFiles();
1798  
      for (File file : files)
1799  
        scanForSources(file, sources, false);
1800  
    }
1801  
  }
1802  
1803  
  private static boolean isSkippedDirectoryName(String name, boolean topLevel) {
1804  
    if (topLevel) return false; // input or output ok as highest directory (intentionally specified by user, not just found by a directory scan in which case we probably don't want it. it's more like heuristics actually.)
1805  
    return name.equalsIgnoreCase("input") || name.equalsIgnoreCase("output");
1806  
  }
1807  
1808  
  static int exitValue;
1809  
  public static String backtick(String cmd) throws IOException {
1810  
    ++processesStarted;
1811  
    File outFile = File.createTempFile("_backtick", "");
1812  
    File scriptFile = File.createTempFile("_backtick", isWindows() ? ".bat" : "");
1813  
1814  
    String command = cmd + " >" + bashQuote(outFile.getPath()) + " 2>&1";
1815  
    //Log.info("[Backtick] " + command);
1816  
    try {
1817  
      saveTextFile(scriptFile.getPath(), command);
1818  
      String[] command2;
1819  
      if (isWindows())
1820  
        command2 = new String[] { scriptFile.getPath() };
1821  
      else
1822  
        command2 = new String[] { "/bin/bash", scriptFile.getPath() };
1823  
      Process process = Runtime.getRuntime().exec(command2);
1824  
      try {
1825  
        process.waitFor();
1826  
      } catch (InterruptedException e) {
1827  
        throw new RuntimeException(e);
1828  
      }
1829  
      exitValue = process.exitValue();
1830  
      if (verbose)
1831  
        System.out.println("Process return code: " + exitValue);
1832  
      return loadTextFile(outFile.getPath(), "");
1833  
    } finally {
1834  
      scriptFile.delete();
1835  
    }
1836  
  }
1837  
1838  
  /** possibly improvable */
1839  
  public static String javaQuote(String text) {
1840  
    return bashQuote(text);
1841  
  }
1842  
1843  
  /** possibly improvable */
1844  
  public static String bashQuote(String text) {
1845  
    if (text == null) return null;
1846  
    return "\"" + text
1847  
      .replace("\\", "\\\\")
1848  
      .replace("\"", "\\\"")
1849  
      .replace("\n", "\\n")
1850  
      .replace("\r", "\\r") + "\"";
1851  
  }
1852  
1853  
  public final static String charsetForTextFiles = "UTF8";
1854  
1855  
  static long TempDirMaker_lastValue;
1856  
1857  
  public static File TempDirMaker_makeDexCache() {
1858  
    File dir = new File(getDexCacheHome(), ".javax/" + TempDirMaker_newValue());
1859  
    dir.mkdirs();
1860  
    return dir;
1861  
  }
1862  
1863  
  public static File TempDirMaker_make() {
1864  
    File dir = new File(userHome(), ".javax/" + TempDirMaker_newValue());
1865  
    dir.mkdirs();
1866  
    return dir;
1867  
  }
1868  
1869  
  private static long TempDirMaker_newValue() {
1870  
    long value;
1871  
    do
1872  
      value = System.currentTimeMillis();
1873  
    while (value == TempDirMaker_lastValue);
1874  
    TempDirMaker_lastValue = value;
1875  
    return value;
1876  
  }
1877  
1878  
    public static String join(String glue, Iterable<String> strings) {
1879  
    StringBuilder buf = new StringBuilder();
1880  
    Iterator<String> i = strings.iterator();
1881  
    if (i.hasNext()) {
1882  
      buf.append(i.next());
1883  
      while (i.hasNext())
1884  
        buf.append(glue).append(i.next());
1885  
    }
1886  
    return buf.toString();
1887  
  }
1888  
  
1889  
  public static String join(String glue, String[] strings) {
1890  
    return join(glue, Arrays.asList(strings));
1891  
  }
1892  
  
1893  
  public static String join(Iterable<String> strings) {
1894  
    return join("", strings);
1895  
  }
1896  
  
1897  
  public static String join(String[] strings) {
1898  
    return join("", strings);
1899  
  }
1900  
 // join
1901  
  
1902  
  public static boolean isWindows() {
1903  
    return System.getProperty("os.name").contains("Windows");
1904  
  }
1905  
1906  
  public static String makeRandomID(int length) {
1907  
    Random random = new Random();
1908  
    char[] id = new char[length];
1909  
    for (int i = 0; i< id.length; i++)
1910  
      id[i] = (char) ((int) 'a' + random.nextInt(26));
1911  
    return new String(id);
1912  
  }
1913  
1914  
  static String computerID;
1915  
  public static String getComputerID() throws IOException {
1916  
    if (noID) return null;
1917  
    if (computerID == null) {
1918  
      File file = new File(userHome(), ".tinybrain/computer-id");
1919  
      computerID = loadTextFile(file.getPath(), null);
1920  
      if (computerID == null) {
1921  
        computerID = makeRandomID(12);
1922  
        saveTextFile(file.getPath(), computerID);
1923  
      }
1924  
      if (verbose)
1925  
        System.out.println("Local computer ID: " + computerID);
1926  
    }
1927  
    return computerID;
1928  
  }
1929  
1930  
  static int fileDeletions;
1931  
1932  
  static void cleanCache() {
1933  
    try {
1934  
      if (verbose)
1935  
        System.out.println("Cleaning cache");
1936  
      fileDeletions = 0;
1937  
      File javax = new File(userHome(), ".javax");
1938  
      long now = System.currentTimeMillis();
1939  
      File[] files = javax.listFiles();
1940  
      if (files != null) for (File dir : files) {
1941  
        if (dir.isDirectory() && Pattern.compile("\\d+").matcher(dir.getName()).matches()) {
1942  
          long time = Long.parseLong(dir.getName());
1943  
          long seconds = (now - time) / 1000;
1944  
          long minutes = seconds / 60;
1945  
          long hours = minutes / 60;
1946  
          if (hours >= tempFileRetentionTime) {
1947  
            //System.out.println("Can delete " + dir.getAbsolutePath() + ", age: " + hours + " h");
1948  
            removeDir(dir);
1949  
          }
1950  
        }
1951  
      }
1952  
      if (verbose && fileDeletions != 0)
1953  
        System.out.println("Cleaned cache. File deletions: " + fileDeletions);
1954  
    } catch (Throwable e) {
1955  
      e.printStackTrace();
1956  
    }
1957  
  }
1958  
1959  
  static void removeDir(File dir) {
1960  
    if (dir.getAbsolutePath().indexOf(".javax") < 0)  // security check!
1961  
      return;
1962  
    for (File f : dir.listFiles()) {
1963  
      if (f.isDirectory())
1964  
        removeDir(f);
1965  
      else {
1966  
        if (verbose)
1967  
          System.out.println("Deleting " + f.getAbsolutePath());
1968  
        f.delete();
1969  
        ++fileDeletions;
1970  
      }
1971  
    }
1972  
    dir.delete();
1973  
  }
1974  
1975  
  static void showSystemProperties() {
1976  
    System.out.println("System properties:\n");
1977  
    for (Map.Entry<Object, Object> entry : System.getProperties().entrySet()) {
1978  
      System.out.println("  " + entry.getKey() + " = " + entry.getValue());
1979  
    }
1980  
    System.out.println();
1981  
  }
1982  
1983  
  static void showVersion() {
1984  
    //showSystemProperties();
1985  
    boolean eclipseFound = hasEcj();
1986  
    //String platform = System.getProperty("java.vendor") + " " + System.getProperty("java.runtime.name") + " " + System.getProperty("java.version");
1987  
    String platform = System.getProperty("java.vm.name") + " " + System.getProperty("java.version");
1988  
    String os = System.getProperty("os.name"), arch = System.getProperty("os.arch");
1989  
    System.out.println("This is " + version + ".");
1990  
    System.out.println("[Details: " +
1991  
      (eclipseFound ? "Eclipse compiler (good)" : "javac (not so good)")
1992  
      + ", " + platform + ", " + arch + ", " + os + "]");
1993  
  }
1994  
1995  
  static boolean isAndroid() {
1996  
    return System.getProperty("java.vendor").toLowerCase().indexOf("android") >= 0;
1997  
  }
1998  
  
1999  
    static void set(Object o, String field, Object value) {
2000  
    if (o instanceof Class) set((Class) o, field, value);
2001  
    else try {
2002  
      Field f = set_findField(o.getClass(), field);
2003  
      f.setAccessible(true);
2004  
      f.set(o, value);
2005  
    } catch (Exception e) {
2006  
      throw new RuntimeException(e);
2007  
    }
2008  
  }
2009  
  
2010  
  static void set(Class c, String field, Object value) {
2011  
    try {
2012  
      Field f = set_findStaticField(c, field);
2013  
      f.setAccessible(true);
2014  
      f.set(null, value);
2015  
    } catch (Exception e) {
2016  
      throw new RuntimeException(e);
2017  
    }
2018  
  }
2019  
  
2020  
  static Field set_findField(Class<?> c, String field) {
2021  
    for (Field f : c.getDeclaredFields())
2022  
      if (f.getName().equals(field))
2023  
        return f;
2024  
    throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
2025  
  }
2026  
  
2027  
  static Field set_findStaticField(Class<?> c, String field) {
2028  
    for (Field f : c.getDeclaredFields())
2029  
      if (f.getName().equals(field) && (f.getModifiers() & Modifier.STATIC) != 0)
2030  
        return f;
2031  
    throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
2032  
  } // set function
2033  
2034  
  static String smartJoin(String[] args) {
2035  
    String[] a2 = new String[args.length];
2036  
    for (int i = 0; i < args.length; i++) {
2037  
      a2[i] = Pattern.compile("\\w+").matcher(args[i]).matches() ? args[i] : quote(args[i]);
2038  
    }
2039  
    return join(" ", a2);
2040  
  }
2041  
  
2042  
  static void logStart(String[] args) throws IOException {
2043  
    String line = smartJoin(args);
2044  
    appendToLog(new File(userHome(), ".javax/log.txt").getPath(), line);
2045  
  }
2046  
  
2047  
  static String quote(String s) {
2048  
    if (s == null) return "null";
2049  
    return "\"" + s.replace("\\", "\\\\").replace("\"", "\\\"").replace("\r", "\\r").replace("\n", "\\n") + "\"";
2050  
  }
2051  
  
2052  
  static void appendToLog(String path, String line) throws IOException {
2053  
    appendToFile(path, "\n" + line + "\n");
2054  
  }
2055  
  
2056  
  static void appendToFile(String path, String s) throws IOException {
2057  
    new File(path).getParentFile().mkdirs();
2058  
    Writer writer = new BufferedWriter(new OutputStreamWriter(
2059  
      new FileOutputStream(path, true), "UTF-8"));
2060  
    writer.write(s);
2061  
    writer.close();
2062  
  }
2063  
2064  
  static long now_virtualTime;
2065  
  static long now() {
2066  
    return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis();
2067  
  }
2068  
2069  
  static void print(Object o) {
2070  
    System.out.println(o);
2071  
  }
2072  
2073  
  static void nohupJavax(String javaxargs) {
2074  
    try {
2075  
      File xfile = new File(userHome(), ".javax/x27.jar");
2076  
      if (!xfile.isFile()) {
2077  
        String url = "http://tinybrain.de/x27.jar";
2078  
        byte[] data = loadBinaryPage(new URL(url).openConnection());
2079  
        if (data.length < 1000000)
2080  
          throw new RuntimeException("Could not load " + url);
2081  
        saveBinaryFile(xfile.getPath(), data);
2082  
      }
2083  
      String jarPath = xfile.getPath();
2084  
      nohup("java -jar " + (isWindows() ? winQuote(jarPath) : bashQuote(jarPath)) + " " + javaxargs);
2085  
    } catch (Exception e) { throw new RuntimeException(e); }
2086  
  }
2087  
2088  
  /** possibly improvable */
2089  
  public static String winQuote(String text) {
2090  
    if (text == null) return null;
2091  
    return "\"" + text
2092  
      .replace("\\", "\\\\")
2093  
      .replace("\"", "\\\"")
2094  
      .replace("\n", "\\n")
2095  
      .replace("\r", "\\r") + "\"";
2096  
  }
2097  
2098  
  public static File nohup(String cmd) throws IOException {
2099  
    File outFile = File.createTempFile("nohup_" + nohup_sanitize(cmd), ".out");
2100  
    nohup(cmd, outFile, false);
2101  
    return outFile;
2102  
  }
2103  
2104  
  static String nohup_sanitize(String s) {
2105  
    return s.replaceAll("[^a-zA-Z0-9\\-_]", "");
2106  
  }
2107  
2108  
  /** outFile takes stdout and stderr. */
2109  
  public static void nohup(String cmd, File outFile, boolean append) throws IOException {
2110  
    String command = nohup_makeNohupCommand(cmd, outFile, append);
2111  
2112  
    File scriptFile = File.createTempFile("_realnohup", isWindows() ? ".bat" : "");
2113  
    System.out.println("[Nohup] " + command);
2114  
    try {
2115  
      //System.out.println("[RealNohup] Script file: " + scriptFile.getPath());
2116  
      saveTextFile(scriptFile.getPath(), command);
2117  
      String[] command2;
2118  
      if (isWindows())
2119  
        command2 = new String[] {"cmd", "/c", "start", "/b", scriptFile.getPath() };
2120  
      else
2121  
        command2 = new String[] {"/bin/bash", scriptFile.getPath() };
2122  
2123  
      Process process = Runtime.getRuntime().exec(command2);
2124  
      try {
2125  
        process.waitFor();
2126  
      } catch (InterruptedException e) {
2127  
        throw new RuntimeException(e);
2128  
      }
2129  
      int value = process.exitValue();
2130  
      //System.out.println("exit value: " + value);
2131  
    } finally {
2132  
      if (!isWindows())
2133  
        scriptFile.delete();
2134  
    }
2135  
  }
2136  
2137  
  public static String nohup_makeNohupCommand(String cmd, File outFile, boolean append) {
2138  
    mkdirsForFile(outFile);
2139  
2140  
    String command;
2141  
    if (isWindows())
2142  
      command = cmd + (append ? " >>" : " >") + winQuote(outFile.getPath()) + " 2>&1";
2143  
    else
2144  
      command = "nohup " + cmd + (append ? " >>" : " >") + bashQuote(outFile.getPath()) + " 2>&1 &";
2145  
    return command;
2146  
  }
2147  
2148  
  public static void mkdirsForFile(File file) {
2149  
    File dir = file.getParentFile();
2150  
    if (dir != null) // is null if file is in current dir
2151  
      dir.mkdirs();
2152  
  }
2153  
 
2154  
  static void autoReportToChat() {
2155  
    // TODO: put back in
2156  
  }
2157  
  
2158  
  static class Q {
2159  
    LinkedBlockingQueue<Runnable> q = new LinkedBlockingQueue<Runnable>();
2160  
    
2161  
    static class Done extends RuntimeException {}
2162  
    
2163  
    Q() {}
2164  
    
2165  
    Q(String name, boolean startThread) {
2166  
      if (startThread)
2167  
        new Thread(name) {
2168  
          public void run() {
2169  
            Q.this.run();
2170  
          }
2171  
        }.start();
2172  
    }
2173  
    
2174  
    Iterable<Runnable> master() {
2175  
      return new Iterable<Runnable>() {
2176  
        public Iterator<Runnable> iterator() {
2177  
          return new Iterator<Runnable>() {
2178  
            Runnable x;
2179  
            
2180  
            public boolean hasNext() { try {
2181  
   
2182  
              //debug("hasNext");
2183  
              while (x == null)
2184  
                x = q.poll(1, TimeUnit.DAYS);
2185  
              //debug("hasNext true");
2186  
              return true;
2187  
            
2188  
  } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
2189  
            
2190  
            public Runnable next() {
2191  
              //debug("next");
2192  
              hasNext();
2193  
              Runnable _x = x;
2194  
              x = null;
2195  
              //debug("next " + structure(x));
2196  
              return _x;
2197  
            }
2198  
            
2199  
            public void remove() {
2200  
            }
2201  
          };
2202  
        }
2203  
      };
2204  
    }
2205  
    
2206  
    void add(Runnable r) {
2207  
      q.add(r);
2208  
    }
2209  
    
2210  
    void run() {
2211  
      for (Runnable r : master()) {
2212  
        try {
2213  
          r.run();
2214  
        } catch (Done e) {
2215  
          return; // break signal
2216  
        } catch (Throwable e) {
2217  
          e.printStackTrace();
2218  
        }
2219  
      }
2220  
    }
2221  
    
2222  
    void done() {
2223  
      add(new Runnable() {
2224  
        public void run() {
2225  
          throw new Done();
2226  
        }
2227  
      });
2228  
    }
2229  
  } // class Q
2230  
2231  
static void reportToChat(final String s, boolean silent) {
2232  
    if (s == null || s.length() == 0) return;
2233  
    if (!silent)
2234  
      print("reportToChat: " + quote(s));
2235  
    reportToChat_getChatThread().add(new Runnable() {
2236  
    public void run() { try {
2237  
        startChatServerIfNotUp();
2238  
        waitForChatServer();
2239  
        chatSend(s);
2240  
    } catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}});
2241  
   }
2242  
  
2243  
  static Q reportToChat_q;
2244  
  
2245  
  static Q reportToChat_getChatThread() {
2246  
    if (reportToChat_q == null)
2247  
      reportToChat_q = new Q("reportToChat", true);
2248  
    return reportToChat_q;
2249  
  }
2250  
  
2251  
  static void startChatServerIfNotUp() {
2252  
    if (portIsBound(9751)) {
2253  
      //print("Chat seems to be up.");
2254  
    } else {
2255  
      nohupJavax("1000867");
2256  
      print("Chat server should be coming up any minute now.");
2257  
    }
2258  
  }
2259  
  
2260  
  static void waitForChatServer() {
2261  
    if (!portIsBound(9751)) {
2262  
      //System.out.print("Waiting for chat server... ");
2263  
      do {
2264  
        sleep(1000);
2265  
      } while (!portIsBound(9751));
2266  
      //print("OK.");
2267  
    }
2268  
  }
2269  
2270  
  static boolean portIsBound(int port) {
2271  
    try {
2272  
      ServerSocket s = new ServerSocket(port);
2273  
      s.close();
2274  
      return false;
2275  
    } catch (IOException e) {
2276  
      return true;
2277  
    }
2278  
  }
2279  
  
2280  
  static class LineBuf {
2281  
    StringBuffer buf = new StringBuffer();
2282  
    
2283  
    void append(String s) {
2284  
      buf.append(s);
2285  
    }
2286  
    
2287  
    String nextLine() {
2288  
      int i = buf.indexOf("\n");
2289  
      if (i >= 0) {
2290  
        String s = buf.substring(0, i > 0 && buf.charAt(i-1) == '\r' ? i-1 : i);
2291  
        buf.delete(0, i+1);
2292  
        return s;
2293  
      }
2294  
      return null;
2295  
    }
2296  
  } // LineBuf
2297  
2298  
  static void sleep(long ms) {
2299  
    try {
2300  
      Thread.sleep(ms);
2301  
    } catch (Exception e) { throw new RuntimeException(e); }
2302  
  }
2303  
2304  
2305  
static int chatSend_chatPort = 9751;
2306  
2307  
  static abstract class DialogIO {
2308  
    abstract boolean isStillConnected();
2309  
    abstract String readLineNoBlock();
2310  
    abstract boolean waitForLine();
2311  
    abstract void sendLine(String line);
2312  
    abstract boolean isLocalConnection();
2313  
    abstract Socket getSocket();
2314  
  }
2315  
  
2316  
  static abstract class DialogHandler {
2317  
    abstract void run(DialogIO io);
2318  
  } // DialogIO
2319  
2320  
static DialogIO chatSend_dialog;
2321  
static String chatSend_id;
2322  
2323  
static void chatSend(String line) { try {
2324  
 
2325  
  if (chatSend_dialog == null) {
2326  
    chatSend_dialog = talkTo("localhost", chatSend_chatPort);    
2327  
    chatSend_dialog.waitForLine();
2328  
    String l = chatSend_dialog.readLineNoBlock();
2329  
    if (l.startsWith("Your ID: "))
2330  
      chatSend_id = l.substring("Your ID: ".length());
2331  
  }
2332  
2333  
  chatSend_dialog.sendLine(line);
2334  
2335  
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} // chatSend
2336  
2337  
  static class TeeOutputStream extends OutputStream {
2338  
    
2339  
    protected OutputStream out, branch;
2340  
2341  
    public TeeOutputStream( OutputStream out, OutputStream branch ) {
2342  
      this.out = out;
2343  
      this.branch = branch;
2344  
    }
2345  
2346  
    @Override
2347  
    public synchronized void write(byte[] b) throws IOException {
2348  
      write(b, 0, b.length);
2349  
    }
2350  
2351  
    @Override
2352  
    public synchronized void write(byte[] b, int off, int len) throws IOException {
2353  
      //if (verbose) oldOut.println("Tee write " + new String(b, "UTF-8"));
2354  
      out.write(b, off, len);
2355  
      this.branch.write(b, off, len);
2356  
    }
2357  
2358  
    @Override
2359  
    public synchronized void write(int b) throws IOException {
2360  
      write(new byte[] {(byte) b});
2361  
    }
2362  
2363  
    /**
2364  
     * Flushes both streams.
2365  
     * @throws IOException if an I/O error occurs
2366  
     */
2367  
    @Override
2368  
    public void flush() throws IOException {
2369  
      out.flush();
2370  
      this.branch.flush();
2371  
    }
2372  
2373  
    /**
2374  
     * Closes both streams.
2375  
     * @throws IOException if an I/O error occurs
2376  
     */
2377  
    @Override
2378  
    public void close() throws IOException {
2379  
      out.close();
2380  
      this.branch.close();
2381  
    }
2382  
  }
2383  
  
2384  
  static boolean isChatServer(String[] args) {
2385  
    for (int i = 0; i < args.length; i++)
2386  
      if (isSnippetID(args[i]))
2387  
        return parseSnippetID(args[i]) == 1000867;
2388  
    return false;
2389  
  }
2390  
  
2391  
  static String getSnippetTitle(String id) {
2392  
    try {
2393  
      return loadPage(new URL("http://tinybrain.de:8080/tb-int/getfield.php?id=" + parseSnippetID(id) + "&field=title"));
2394  
    } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }
2395  
  }
2396  
  
2397  
  static void listUserThreadsWithStackTraces() {
2398  
    print("");
2399  
    Map<Thread, StackTraceElement[]> threadMap = Thread.getAllStackTraces();
2400  
    int n = 0;
2401  
    for (Thread t : threadMap.keySet()) {
2402  
      ThreadGroup g = t.getThreadGroup();
2403  
      if (g != null && g.getName().equals("system")) continue;
2404  
      ++n;
2405  
      print(t);
2406  
      for (StackTraceElement e : threadMap.get(t)) {
2407  
        print("  " + e);
2408  
      }
2409  
      print("");
2410  
    }
2411  
    print(n + " user threads.");
2412  
  }
2413  
  
2414  
  static void killMyself() {
2415  
    print("Killing myself. (insert overall feeling here)");
2416  
    System.exit(0);
2417  
  }
2418  
  
2419  
  static void makeVMAndroid() {
2420  
    makeAndroidNoConsoleDaemon("This is a JavaX VM.", new StrF() {
2421  
public String get(String s) {
2422  
try { return  answer(s) ; } catch (Exception _e) {
2423  
  throw _e instanceof RuntimeException ? (RuntimeException) _e : new RuntimeException(_e); } }
2424  
});
2425  
  }
2426  
  
2427  
  static class Info {
2428  
    String programID;
2429  
    String[] programArgs;
2430  
    File transpiledSrc;
2431  
    Class mainClass;
2432  
  }
2433  
  
2434  
  static Info info = new Info();
2435  
  
2436  
  static synchronized String answer(String s) {
2437  
    Matches m = new Matches();
2438  
    
2439  
    if (match3("kill!", s)) {
2440  
      killMyself();
2441  
      return "ok";
2442  
    }
2443  
    if (match3("What is your process ID?", s) || match3("what is your pid?", s))
2444  
      return getPID();
2445  
    if (match3("what is your program id?", s))
2446  
      return info.programID;
2447  
    if (match3("what are your program arguments?", s))
2448  
      return structure(info.programArgs);
2449  
    if (match3("get fields of main class", s))
2450  
      return structure(listFields(info.mainClass));
2451  
    if (match3("get field * of main class", s, m))
2452  
      return structure(get(info.mainClass, m.m[0]));
2453  
    if (match3("invoke function * of main class", s, m))
2454  
      return structure(call(info.mainClass, m.m[0]));
2455  
    if (match3("set field * of main class to *", s, m)) {
2456  
      set(info.mainClass, m.m[0], unstructure(m.m[1]));
2457  
      return "ok";
2458  
    }
2459  
    if (match3("how much memory are you consuming", s))
2460  
      return "Java heap size: " + (Runtime.getRuntime().totalMemory()+1024*1024-1)/1024/1024 + " MB";
2461  
    if (match3("how much memory is used after GC?", s)) {
2462  
      System.gc();
2463  
      return "Java heap used: " + (Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory()+1024*1024-1)/1024/1024 + " MB";
2464  
    }
2465  
    if (match3("how much memory is used?", s))
2466  
      return "Java heap used: " + (Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory()+1024*1024-1)/1024/1024 + " MB";
2467  
    return null;
2468  
  }
2469  
  
2470  
static class Android {
2471  
  int port;
2472  
  DialogHandler handler;
2473  
}
2474  
2475  
static int makeAndroid(final String greeting) {
2476  
  return makeAndroid(greeting, new StrF() {
2477  
public String get(String s) {
2478  
try { return 
2479  
    (String) call(getMainClass(), "answer", s)
2480  
  ; } catch (Exception _e) {
2481  
  throw _e instanceof RuntimeException ? (RuntimeException) _e : new RuntimeException(_e); } }
2482  
});
2483  
}
2484  
2485  
static int makeAndroidNoConsole(final String greeting, final StrF f) {
2486  
  return makeAndroid(greeting, f, false, false);
2487  
}
2488  
2489  
static int makeAndroidNoConsoleDaemon(final String greeting, final StrF f) {
2490  
  return makeAndroid(greeting, f, false, true);
2491  
}
2492  
2493  
static int makeAndroid(final String greeting, final StrF f) {
2494  
  return makeAndroid(greeting, f, true, false);
2495  
}
2496  
2497  
static int makeAndroid(final String greeting, final StrF f, boolean console, boolean daemon) {
2498  
  print(greeting);
2499  
  final Android a = new Android();
2500  
  a.handler = makeAndroid_makeDialogHandler(greeting, f);
2501  
  a.port = daemon 
2502  
    ? startDialogServerOnPortAboveDaemon(5000, a.handler)
2503  
    : startDialogServerOnPortAbove(5000, a.handler);
2504  
  
2505  
  if (console) {
2506  
    print("You may also type on this console.");
2507  
    Thread _t_0 = new Thread() {
2508  
public void run() {
2509  
try {
2510  
2511  
      String line;
2512  
      while ((line = readLine()) != null) {
2513  
        if ("bye".equals(line))
2514  
          print("> bye stranger");
2515  
        else
2516  
          makeAndroid_getAnswer(line, f); // prints answer on console too
2517  
      }
2518  
    } catch (Exception _e) {
2519  
  throw _e instanceof RuntimeException ? (RuntimeException) _e : new RuntimeException(_e); } }
2520  
};
2521  
_t_0.start();
2522  
  }
2523  
  
2524  
  record(a);
2525  
  return a.port;
2526  
}
2527  
2528  
static DialogHandler makeAndroid_makeDialogHandler(final String greeting, final StrF f) {
2529  
  return new DialogHandler() {
2530  
public void run(final DialogIO io) {
2531  
2532  
    if (!(publicCommOn() || io.isLocalConnection())) {
2533  
      io.sendLine("Sorry, not allowed");
2534  
      return;
2535  
    }
2536  
    
2537  
    String dialogID = randomID(8);
2538  
    
2539  
    io.sendLine(greeting + " / Your ID: " + dialogID);
2540  
    
2541  
    while (io.isStillConnected()) {
2542  
      if (io.waitForLine()) {
2543  
        final String line = io.readLineNoBlock();
2544  
        String s = dialogID + " at " + now() + ": " + quote(line);
2545  
        print(s);
2546  
        if ("bye".equals(line)) {
2547  
          io.sendLine("bye stranger");
2548  
          return;
2549  
        }
2550  
        String answer = makeAndroid_getAnswer(line, f);
2551  
        io.sendLine(answer == null ? "null" : answer);
2552  
        //appendToLog(logFile, s);
2553  
      }
2554  
    }
2555  
  
2556  
}};
2557  
}
2558  
2559  
static String makeAndroid_getAnswer(String line, StrF f) {
2560  
  String answer;
2561  
  try {
2562  
    answer = makeAndroid_fallback(line, f.get(line));
2563  
  } catch (Throwable e) {
2564  
    e = getInnerException(e);
2565  
    e.printStackTrace();
2566  
    answer = e.toString();
2567  
  }
2568  
  print("> " + answer);
2569  
  return answer;
2570  
}
2571  
2572  
static String makeAndroid_fallback(String s, String answer) {
2573  
  if (answer == null) return "?";
2574  
  if (answer.indexOf('\n') >= 0 || answer.indexOf('\r') >= 0)
2575  
    answer = quote(answer);
2576  
  return answer;
2577  
}
2578  
 // makeAndroid / makeAndroidNoConsole
2579  
  static BufferedReader readLine_reader;
2580  
2581  
static String readLine() { try {
2582  
 
2583  
  if (readLine_reader == null)
2584  
    readLine_reader = new BufferedReader(new InputStreamReader(System.in, "UTF-8"));
2585  
  String s = readLine_reader.readLine();
2586  
  if (s != null)
2587  
    print(s);
2588  
  return s;
2589  
2590  
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} // readLine
2591  
    static void setOpt(Class c, String field, Object value) {
2592  
    try {
2593  
      Field f = setOpt_findStaticField(c, field);
2594  
      if (f == null) return;
2595  
      f.setAccessible(true);
2596  
      f.set(null, value);
2597  
    } catch (Exception e) {
2598  
      throw new RuntimeException(e);
2599  
    }
2600  
  }
2601  
  
2602  
  static Field setOpt_findStaticField(Class<?> c, String field) {
2603  
    for (Field f : c.getDeclaredFields())
2604  
      if (f.getName().equals(field) && (f.getModifiers() & Modifier.STATIC) != 0)
2605  
        return f;
2606  
    return null;
2607  
  } // setOpt
2608  
  static Object get(Object o, String field) {
2609  
  if (o instanceof Class) return get((Class) o, field);
2610  
  try {
2611  
    Field f = get_findField(o.getClass(), field);
2612  
    f.setAccessible(true);
2613  
    return f.get(o);
2614  
  } catch (Exception e) {
2615  
    throw new RuntimeException(e);
2616  
  }
2617  
}
2618  
2619  
static Object get(Class c, String field) {
2620  
  try {
2621  
    Field f = get_findStaticField(c, field);
2622  
    f.setAccessible(true);
2623  
    return f.get(null);
2624  
  } catch (Exception e) {
2625  
    throw new RuntimeException(e);
2626  
  }
2627  
}
2628  
2629  
static Field get_findStaticField(Class<?> c, String field) {
2630  
  for (Field f : c.getDeclaredFields())
2631  
    if (f.getName().equals(field) && (f.getModifiers() & Modifier.STATIC) != 0)
2632  
      return f;
2633  
  throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
2634  
}
2635  
2636  
static Field get_findField(Class<?> c, String field) {
2637  
  for (Field f : c.getDeclaredFields())
2638  
    if (f.getName().equals(field))
2639  
      return f;
2640  
  throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
2641  
} // get
2642  
  static Class getMainClass() { try {
2643  
 
2644  
  return Class.forName("main");
2645  
2646  
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} // getMainClass
2647  
2648  
static Throwable getInnerException(Throwable e) {
2649  
  while (e.getCause() != null)
2650  
    e = e.getCause();
2651  
  return e;
2652  
}
2653  
2654  
static boolean publicCommOn() {
2655  
  return "1".equals(loadTextFile(new File(userHome(), ".javax/public-communication")));
2656  
}
2657  
2658  
static List<Object> record_list = synchroList();
2659  
2660  
static void record(Object o) {
2661  
  record_list.add(o);
2662  
}
2663  
2664  
static Set<String> listFields(Class<?> c) {
2665  
  Set<String> fields = new TreeSet<String>();
2666  
  for (Field f : c.getDeclaredFields())
2667  
    fields.add(f.getName());
2668  
  return fields;
2669  
}
2670  
2671  
// try to get our current process ID
2672  
static String getPID() {
2673  
  String name = ManagementFactory.getRuntimeMXBean().getName();
2674  
  return name.replaceAll("@.*", "");
2675  
}
2676  
2677  
  static AtomicInteger dialogServer_clients = new AtomicInteger();
2678  
  
2679  
  static int startDialogServerOnPortAbove(int port, DialogHandler handler) {
2680  
    while (!startDialogServerIfPortAvailable(port, handler))
2681  
      ++port;
2682  
    return port;
2683  
  }
2684  
  
2685  
  static int startDialogServerOnPortAboveDaemon(int port, DialogHandler handler) {
2686  
    while (!startDialogServerIfPortAvailable(port, handler, true))
2687  
      ++port;
2688  
    return port;
2689  
  }
2690  
  
2691  
  static void startDialogServer(int port, DialogHandler handler) {
2692  
    if (!startDialogServerIfPortAvailable(port, handler))
2693  
      fail("Can't start dialog server on port " + port);
2694  
  }
2695  
  
2696  
  static boolean startDialogServerIfPortAvailable(int port, final DialogHandler handler) {
2697  
    return startDialogServerIfPortAvailable(port, handler, false);
2698  
  }
2699  
    
2700  
  static boolean startDialogServerIfPortAvailable(int port, final DialogHandler handler, boolean daemon) {
2701  
    ServerSocket serverSocket = null;
2702  
    try {
2703  
      serverSocket = new ServerSocket(port);
2704  
    } catch (IOException e) {
2705  
      // probably the port number is used - let's assume there already is a chat server.
2706  
      return false;
2707  
    }
2708  
    final ServerSocket _serverSocket = serverSocket;
2709  
2710  
    Thread thread = new Thread() { public void run() {
2711  
     try {
2712  
      while (true) {
2713  
        try {
2714  
          final Socket s = _serverSocket.accept();
2715  
          print("connect - clients: " + dialogServer_clients.incrementAndGet());
2716  
          Thread _t_1 = new Thread() {
2717  
public void run() {
2718  
try {
2719  
2720  
            try {
2721  
              final Writer w = new OutputStreamWriter(s.getOutputStream(), "UTF-8");
2722  
              final BufferedReader in = new BufferedReader(
2723  
                new InputStreamReader(s.getInputStream(), "UTF-8"));
2724  
              DialogIO io = new DialogIO() {
2725  
                String line;
2726  
                boolean buff;
2727  
                
2728  
                Socket getSocket() { return s; }
2729  
                
2730  
                // local means localhost - todo: test
2731  
                boolean isLocalConnection() {
2732  
                  return s.getInetAddress().isLoopbackAddress();
2733  
                }
2734  
                
2735  
                boolean isStillConnected() {
2736  
                  return !(buff || s.isClosed());
2737  
                }
2738  
                
2739  
                String readLineNoBlock() {
2740  
                  String l = line;
2741  
                  line = null;
2742  
                  return l;
2743  
                }
2744  
                
2745  
                boolean waitForLine() { try {
2746  
 
2747  
                  if (line != null) return true;
2748  
                  //print("Readline");
2749  
                  line = in.readLine();
2750  
                  //print("Readline done: " + line);
2751  
                  if (line == null) buff = true;
2752  
                  return line != null;
2753  
                
2754  
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
2755  
                
2756  
                void sendLine(String line) { try {
2757  
 
2758  
                  w.write(line + "\n");
2759  
                  w.flush();
2760  
                
2761  
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
2762  
              };
2763  
              
2764  
              try {
2765  
                handler.run(io);
2766  
              } finally {
2767  
                s.close();
2768  
              }
2769  
            } finally {
2770  
              print("client disconnect - " + dialogServer_clients.decrementAndGet() + " remaining");
2771  
            }
2772  
          } catch (Exception _e) {
2773  
  throw _e instanceof RuntimeException ? (RuntimeException) _e : new RuntimeException(_e); } }
2774  
};
2775  
_t_1.start();
2776  
        } catch (SocketTimeoutException e) {
2777  
        }
2778  
      }   
2779  
     } catch (IOException e) { throw new RuntimeException(e); }  
2780  
    }};
2781  
    if (daemon) thread.setDaemon(true);
2782  
    thread.start();
2783  
   
2784  
    print("Dialog server on port " + port + " started."); 
2785  
    return true;
2786  
  }
2787  
2788  
  static class Matches { String[] m; }
2789  
  
2790  
  static boolean match3(String pat, String s) {
2791  
    return match3(pat, s, null);
2792  
  }
2793  
  
2794  
  static boolean match3(String pat, String s, Matches matches) {
2795  
    List<String> tokpat = parse3(pat), toks = parse3(s);
2796  
    String[] m = match2(tokpat, toks);
2797  
    //print(structure(tokpat) + " on " + structure(toks) + " => " + structure(m));
2798  
    if (m == null)
2799  
      return false;
2800  
    else {
2801  
      if (matches != null) matches.m = m;
2802  
      return true;
2803  
    }
2804  
  }
2805  
  
2806  
  static List<String> parse3(String s) {
2807  
    return dropPunctuation(javaTokPlusPeriod(s));
2808  
  }
2809  
2810  
static DialogIO talkTo(String ip, int port) { try {
2811  
 
2812  
  print("Talking to " + ip + ":" + port);
2813  
  final Socket s = new Socket(ip, port);    
2814  
2815  
  final Writer w = new OutputStreamWriter(s.getOutputStream(), "UTF-8");
2816  
  final BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream(), "UTF-8"));
2817  
  return new DialogIO() {
2818  
    String line;
2819  
    boolean buff;
2820  
    
2821  
    boolean isLocalConnection() {
2822  
      return s.getInetAddress().isLoopbackAddress();
2823  
    }
2824  
    
2825  
    boolean isStillConnected() {
2826  
      return !(buff || s.isClosed());
2827  
    }
2828  
    
2829  
    String readLineNoBlock() {
2830  
      String l = line;
2831  
      line = null;
2832  
      return l;
2833  
    }
2834  
    
2835  
    boolean waitForLine() { try {
2836  
 
2837  
      if (line != null) return true;
2838  
      //print("Readline");
2839  
      line = in.readLine();
2840  
      //print("Readline done: " + line);
2841  
      if (line == null) buff = true;
2842  
      return line != null;
2843  
    
2844  
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
2845  
    
2846  
    void sendLine(String line) { try {
2847  
 
2848  
      w.write(line + "\n");
2849  
      w.flush();
2850  
    
2851  
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
2852  
    
2853  
    void close() { try {
2854  
 
2855  
      s.close();
2856  
    
2857  
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
2858  
    
2859  
    Socket getSocket() {
2860  
      return s;
2861  
    }
2862  
  };
2863  
2864  
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
2865  
2866  
// actually it's now almost the same as jsonDecode :)
2867  
static Object unstructure(String text) {
2868  
  final List<String> tok = javaTok(text);
2869  
  
2870  
  class X {
2871  
    int i = 1;
2872  
2873  
    Object parse() {
2874  
      String t = tok.get(i);
2875  
      if (t.startsWith("\"")) {
2876  
        String s = unquote(tok.get(i));
2877  
        i += 2;
2878  
        return s;
2879  
      }
2880  
      if (t.equals("{"))
2881  
        return parseMap();
2882  
      if (t.equals("["))
2883  
        return parseList();
2884  
      if (t.equals("null")) {
2885  
        i += 2; return null;
2886  
      }
2887  
      if (t.equals("false")) {
2888  
        i += 2; return false;
2889  
      }
2890  
      if (t.equals("true")) {
2891  
        i += 2; return true;
2892  
      }
2893  
      if (isInteger(t)) {
2894  
        i += 2; return Long.parseLong(t);
2895  
      }
2896  
      if (isJavaIdentifier(t)) {
2897  
        Class c = findClass(t);
2898  
        Object o = nuObject(c);
2899  
        i += 2;
2900  
        if (i < tok.size() && tok.get(i).equals("(")) {
2901  
          consume("(");
2902  
          while (!tok.get(i).equals(")")) {
2903  
            // It's like parsing a map.
2904  
            String key = unquote(tok.get(i));
2905  
            i += 2;
2906  
            consume("=");
2907  
            Object value = parse();
2908  
            set(o, key, value);
2909  
            if (tok.get(i).equals(",")) i += 2;
2910  
          }
2911  
          consume(")");
2912  
        }
2913  
        return o;
2914  
      }
2915  
      throw new RuntimeException("Unknown token " + (i+1) + ": " + t);
2916  
    }
2917  
    
2918  
    Object parseList() {
2919  
      consume("[");
2920  
      List list = new ArrayList();
2921  
      while (!tok.get(i).equals("]")) {
2922  
        list.add(parse());
2923  
        if (tok.get(i).equals(",")) i += 2;
2924  
      }
2925  
      consume("]");
2926  
      return list;
2927  
    }
2928  
    
2929  
    Object parseMap() {
2930  
      consume("{");
2931  
      Map map = new TreeMap();
2932  
      while (!tok.get(i).equals("}")) {
2933  
        String key = unquote(tok.get(i));
2934  
        i += 2;
2935  
        consume("=");
2936  
        Object value = parse();
2937  
        map.put(key, value);
2938  
        if (tok.get(i).equals(",")) i += 2;
2939  
      }
2940  
      consume("}");
2941  
      return map;
2942  
    }
2943  
    
2944  
    void consume(String s) {
2945  
      if (!tok.get(i).equals(s)) {
2946  
        String prevToken = i-2 >= 0 ? tok.get(i-2) : "";
2947  
        String nextTokens = join(tok.subList(i, Math.min(i+4, tok.size())));
2948  
        fail(quote(s) + " expected: " + prevToken + " " + nextTokens + " (" + i + "/" + tok.size() + ")");
2949  
      }
2950  
      i += 2;
2951  
    }
2952  
  }
2953  
  
2954  
  return new X().parse();
2955  
}
2956  
2957  
static Matcher matcher(String pattern, String string) {
2958  
  return Pattern.compile(pattern).matcher(string);
2959  
}
2960  
2961  
static Class __javax;
2962  
2963  
static Class getJavaX() {
2964  
  return __javax;
2965  
}
2966  
2967  
static String randomID(int length) {
2968  
  return makeRandomID(length);
2969  
}
2970  
2971  
static Object process(String processorID, Object in) {
2972  
  return process(processorID, in, "in");
2973  
}
2974  
2975  
static Object process(String processorID, Object in, String outVar) {
2976  
  try {
2977  
    Class processor = hotwire(processorID);
2978  
    set(processor, "in", in);
2979  
    call(processor, "main", new Object[] {new String[0]});
2980  
    return get(processor, outVar);
2981  
  } catch (Exception e) {
2982  
    throw new RuntimeException("Error in #" + parseSnippetID(processorID), e);
2983  
  }
2984  
}
2985  
2986  
static String _computerID;
2987  
public static String computerID() throws IOException {
2988  
  if (_computerID == null) {
2989  
    File file = new File(userHome(), ".tinybrain/computer-id");
2990  
    _computerID = loadTextFile(file.getPath(), null);
2991  
    if (_computerID == null) {
2992  
      _computerID = makeRandomID(12);
2993  
      saveTextFile(file.getPath(), _computerID);
2994  
    }
2995  
  }
2996  
  return _computerID;
2997  
}
2998  
2999  
static String structure(Object o) {
3000  
  return structure(o, 0);
3001  
}
3002  
  
3003  
static String structure(Object o, int stringSizeLimit) {
3004  
  if (o == null) return "null";
3005  
  String name = o.getClass().getName();
3006  
  
3007  
  StringBuilder buf = new StringBuilder();
3008  
  
3009  
  if (o instanceof Collection) {
3010  
    for (Object x : (Collection) o) {
3011  
      if (buf.length() != 0) buf.append(", ");
3012  
      buf.append(structure(x, stringSizeLimit));
3013  
    }
3014  
    return "[" + buf + "]";
3015  
  }
3016  
  
3017  
  if (o instanceof Map) {
3018  
    for (Object e : ((Map) o).entrySet()) {
3019  
      if (buf.length() != 0) buf.append(", ");
3020  
      buf.append(structure(((Map.Entry) e).getKey(), stringSizeLimit));
3021  
      buf.append("=");
3022  
      buf.append(structure(((Map.Entry) e).getValue(), stringSizeLimit));
3023  
    }
3024  
    return "{" + buf + "}";
3025  
  }
3026  
  
3027  
  if (o.getClass().isArray()) {
3028  
    int n = Array.getLength(o);
3029  
    for (int i = 0; i < n; i++) {
3030  
      if (buf.length() != 0) buf.append(", ");
3031  
      buf.append(structure(Array.get(o, i), stringSizeLimit));
3032  
    }
3033  
    return "{" + buf + "}";
3034  
  }
3035  
3036  
  if (o instanceof String)
3037  
    return quote(stringSizeLimit != 0 ? shorten((String) o, stringSizeLimit) : (String) o);
3038  
  
3039  
  // Need more cases? This should cover all library classes...
3040  
  if (name.startsWith("java.") || name.startsWith("javax."))
3041  
    return String.valueOf(o);
3042  
    
3043  
  String shortName = o.getClass().getName().replaceAll("^main\\$", "");
3044  
3045  
  // TODO: go to superclasses too
3046  
  Field[] fields = o.getClass().getDeclaredFields();
3047  
  int numFields = 0;
3048  
  String fieldName = "";
3049  
  for (Field field : fields) {
3050  
    if ((field.getModifiers() & Modifier.STATIC) != 0)
3051  
      continue;
3052  
    Object value;
3053  
    try {
3054  
      value = field.get(o);
3055  
    } catch (Exception e) {
3056  
      value = "?";
3057  
    }
3058  
    
3059  
    fieldName = field.getName();
3060  
    
3061  
    // put special cases here...
3062  
3063  
    if (value != null) {
3064  
      if (buf.length() != 0) buf.append(", ");
3065  
      buf.append(fieldName + "=" + structure(value, stringSizeLimit));
3066  
    }
3067  
    ++numFields;
3068  
  }
3069  
  String b = buf.toString();
3070  
  if (numFields == 1)
3071  
    b = b.replaceAll("^" + fieldName + "=", ""); // drop field name if only one
3072  
  String s = shortName;
3073  
  if (buf.length() != 0)
3074  
    s += "(" + b + ")";
3075  
  return s;
3076  
}
3077  
3078  
static boolean isJavaIdentifier(String s) {
3079  
  if (s.length() == 0 || !Character.isJavaIdentifierStart(s.charAt(0)))
3080  
    return false;
3081  
  for (int i = 1; i < s.length(); i++)
3082  
    if (!Character.isJavaIdentifierPart(s.charAt(i)))
3083  
      return false;
3084  
  return true;
3085  
}
3086  
3087  
// currently finds only inner classes of class "main"
3088  
// returns null on not found
3089  
// this is the simple version that is not case-tolerant
3090  
static Class findClass(String name) {
3091  
  try {
3092  
    return Class.forName("main$" + name);
3093  
  } catch (ClassNotFoundException e) {
3094  
    return null;
3095  
  }
3096  
}
3097  
3098  
static Object nuObject(Class c, Object... args) { try {
3099  
 
3100  
  Constructor m = nuObject_findConstructor(c, args);
3101  
  m.setAccessible(true);
3102  
  return m.newInstance(args);
3103  
3104  
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
3105  
3106  
static Constructor nuObject_findConstructor(Class c, Object... args) {
3107  
  for (Constructor m : c.getDeclaredConstructors()) {
3108  
    if (!nuObject_checkArgs(m.getParameterTypes(), args, false))
3109  
      continue;
3110  
    return m;
3111  
  }
3112  
  throw new RuntimeException("Constructor with " + args.length + " matching parameter(s) not found in " + c.getName());
3113  
}
3114  
3115  
 static boolean nuObject_checkArgs(Class[] types, Object[] args, boolean debug) {
3116  
    if (types.length != args.length) {
3117  
      if (debug)
3118  
        System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
3119  
      return false;
3120  
    }
3121  
    for (int i = 0; i < types.length; i++)
3122  
      if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
3123  
        if (debug)
3124  
          System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
3125  
        return false;
3126  
      }
3127  
    return true;
3128  
  }
3129  
3130  
static <A> List<A> synchroList() {
3131  
  return Collections.synchronizedList(new ArrayList<A>());
3132  
}
3133  
3134  
static <A> List<A> synchroList(List<A> l) {
3135  
  return Collections.synchronizedList(l);
3136  
}
3137  
3138  
3139  
static List<String> dropPunctuation(List<String> tok) {
3140  
  tok = new ArrayList<String>(tok);
3141  
  for (int i = 1; i < tok.size(); i += 2) {
3142  
    String t = tok.get(i);
3143  
    if (t.length() == 1 && !Character.isLetter(t.charAt(0)) && !Character.isDigit(t.charAt(0)) && !t.equals("*")) {
3144  
      tok.set(i-1, tok.get(i-1) + tok.get(i+1));
3145  
      tok.remove(i);
3146  
      tok.remove(i);
3147  
      i -= 2;
3148  
    }
3149  
  }
3150  
  return tok;
3151  
}
3152  
3153  
// match2 matches multiple "*" (matches a single token) wildcards and zero or one "..." wildcards (matches multiple tokens)
3154  
3155  
static String[] match2(List<String> pat, List<String> tok) {
3156  
  // standard case (no ...)
3157  
  int i = pat.indexOf("...");
3158  
  if (i < 0) return match2_match(pat, tok);
3159  
  
3160  
  
3161  
  pat = new ArrayList<String>(pat); // We're modifying it, so copy first
3162  
  pat.set(i, "*");
3163  
  int expand = 0;
3164  
  while (pat.size() < tok.size()) {
3165  
    ++expand;
3166  
    pat.add(i, "*");
3167  
    pat.add(i+1, ""); // doesn't matter
3168  
  }
3169  
  
3170  
  return match2_match(pat, tok);
3171  
}
3172  
3173  
static String[] match2_match(List<String> pat, List<String> tok) {
3174  
  List<String> result = new ArrayList<String>();
3175  
  if (pat.size() != tok.size()) {
3176  
    /*if (debug)
3177  
      print("Size mismatch: " + structure(pat) + " vs " + structure(tok));*/
3178  
    return null;
3179  
  }
3180  
  for (int i = 1; i < pat.size(); i += 2) {
3181  
    String p = pat.get(i), t = tok.get(i);
3182  
    /*if (debug)
3183  
      print("Checking " + p + " against " + t);*/
3184  
    if ("*".equals(p))
3185  
      result.add(t);
3186  
    else if (!p.equalsIgnoreCase(t))
3187  
      return null;
3188  
  }
3189  
  return result.toArray(new String[result.size()]);
3190  
}
3191  
3192  
3193  
// javaTok extended with "..." token.
3194  
3195  
static List<String> javaTokPlusPeriod(String s) {
3196  
  List<String> tok = new ArrayList<String>();
3197  
  int l = s.length();
3198  
  
3199  
  int i = 0;
3200  
  while (i < l) {
3201  
    int j = i;
3202  
    char c; String cc;
3203  
    
3204  
    // scan for whitespace
3205  
    while (j < l) {
3206  
      c = s.charAt(j);
3207  
      cc = s.substring(j, Math.min(j+2, l));
3208  
      if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
3209  
        ++j;
3210  
      else if (cc.equals("/*")) {
3211  
        do ++j; while (j < l && !s.substring(j, Math.min(j+2, l)).equals("*/"));
3212  
        j = Math.min(j+2, l);
3213  
      } else if (cc.equals("//")) {
3214  
        do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
3215  
      } else
3216  
        break;
3217  
    }
3218  
    
3219  
    tok.add(s.substring(i, j));
3220  
    i = j;
3221  
    if (i >= l) break;
3222  
    c = s.charAt(i); // cc is not needed in rest of loop body
3223  
    cc = s.substring(i, Math.min(i+2, l));
3224  
3225  
    // scan for non-whitespace
3226  
    if (c == '\'' || c == '"') {
3227  
      char opener = c;
3228  
      ++j;
3229  
      while (j < l) {
3230  
        if (s.charAt(j) == opener) {
3231  
          ++j;
3232  
          break;
3233  
        } else if (s.charAt(j) == '\\' && j+1 < l)
3234  
          j += 2;
3235  
        else
3236  
          ++j;
3237  
      }
3238  
    } else if (Character.isJavaIdentifierStart(c))
3239  
      do ++j; while (j < l && Character.isJavaIdentifierPart(s.charAt(j)));
3240  
    else if (Character.isDigit(c))
3241  
      do ++j; while (j < l && Character.isDigit(s.charAt(j)));
3242  
    else if (cc.equals("[[")) {
3243  
      do ++j; while (j+1 < l && !s.substring(j, j+2).equals("]]"));
3244  
      j = Math.min(j+2, l);
3245  
    } else if (s.substring(j, Math.min(j+3, l)).equals("..."))
3246  
      j += 3;
3247  
    else
3248  
      ++j;
3249  
3250  
    tok.add(s.substring(i, j));
3251  
    i = j;
3252  
  }
3253  
  
3254  
  if ((tok.size() % 2) == 0) tok.add("");
3255  
  return tok;
3256  
}
3257  
3258  
3259  
// replacement for class JavaTok
3260  
// maybe incomplete, might want to add floating point numbers
3261  
// todo also: extended multi-line strings
3262  
3263  
static List<String> javaTok(String s) {
3264  
  List<String> tok = new ArrayList<String>();
3265  
  int l = s.length();
3266  
  
3267  
  int i = 0;
3268  
  while (i < l) {
3269  
    int j = i;
3270  
    char c; String cc;
3271  
    
3272  
    // scan for whitespace
3273  
    while (j < l) {
3274  
      c = s.charAt(j);
3275  
      cc = s.substring(j, Math.min(j+2, l));
3276  
      if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
3277  
        ++j;
3278  
      else if (cc.equals("/*")) {
3279  
        do ++j; while (j < l && !s.substring(j, Math.min(j+2, l)).equals("*/"));
3280  
        j = Math.min(j+2, l);
3281  
      } else if (cc.equals("//")) {
3282  
        do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
3283  
      } else
3284  
        break;
3285  
    }
3286  
    
3287  
    tok.add(s.substring(i, j));
3288  
    i = j;
3289  
    if (i >= l) break;
3290  
    c = s.charAt(i); // cc is not needed in rest of loop body
3291  
    cc = s.substring(i, Math.min(i+2, l));
3292  
3293  
    // scan for non-whitespace
3294  
    if (c == '\'' || c == '"') {
3295  
      char opener = c;
3296  
      ++j;
3297  
      while (j < l) {
3298  
        if (s.charAt(j) == opener) {
3299  
          ++j;
3300  
          break;
3301  
        } else if (s.charAt(j) == '\\' && j+1 < l)
3302  
          j += 2;
3303  
        else
3304  
          ++j;
3305  
      }
3306  
    } else if (Character.isJavaIdentifierStart(c))
3307  
      do ++j; while (j < l && Character.isJavaIdentifierPart(s.charAt(j)));
3308  
    else if (Character.isDigit(c))
3309  
      do ++j; while (j < l && Character.isDigit(s.charAt(j)));
3310  
    else if (cc.equals("[[")) {
3311  
      do ++j; while (j+1 < l && !s.substring(j, j+2).equals("]]"));
3312  
      j = Math.min(j+2, l);
3313  
    } else
3314  
      ++j;
3315  
3316  
    tok.add(s.substring(i, j));
3317  
    i = j;
3318  
  }
3319  
  
3320  
  if ((tok.size() % 2) == 0) tok.add("");
3321  
  return tok;
3322  
}
3323  
3324  
3325  
  public static String unquote(String s) {
3326  
    if (s.startsWith("[")) {
3327  
      int i = 1;
3328  
      while (i < s.length() && s.charAt(i) == '=') ++i;
3329  
      if (i < s.length() && s.charAt(i) == '[') {
3330  
        String m = s.substring(1, i);
3331  
        if (s.endsWith("]" + m + "]"))
3332  
          return s.substring(i+1, s.length()-i-1);
3333  
      }
3334  
    }
3335  
    
3336  
    if (s.startsWith("\"") && s.endsWith("\"") && s.length() > 1) {
3337  
      String st = s.substring(1, s.length()-1);
3338  
      StringBuilder sb = new StringBuilder(st.length());
3339  
  
3340  
      for (int i = 0; i < st.length(); i++) {
3341  
        char ch = st.charAt(i);
3342  
        if (ch == '\\') {
3343  
          char nextChar = (i == st.length() - 1) ? '\\' : st
3344  
                  .charAt(i + 1);
3345  
          // Octal escape?
3346  
          if (nextChar >= '0' && nextChar <= '7') {
3347  
              String code = "" + nextChar;
3348  
              i++;
3349  
              if ((i < st.length() - 1) && st.charAt(i + 1) >= '0'
3350  
                      && st.charAt(i + 1) <= '7') {
3351  
                  code += st.charAt(i + 1);
3352  
                  i++;
3353  
                  if ((i < st.length() - 1) && st.charAt(i + 1) >= '0'
3354  
                          && st.charAt(i + 1) <= '7') {
3355  
                      code += st.charAt(i + 1);
3356  
                      i++;
3357  
                  }
3358  
              }
3359  
              sb.append((char) Integer.parseInt(code, 8));
3360  
              continue;
3361  
          }
3362  
          switch (nextChar) {
3363  
          case '\\':
3364  
              ch = '\\';
3365  
              break;
3366  
          case 'b':
3367  
              ch = '\b';
3368  
              break;
3369  
          case 'f':
3370  
              ch = '\f';
3371  
              break;
3372  
          case 'n':
3373  
              ch = '\n';
3374  
              break;
3375  
          case 'r':
3376  
              ch = '\r';
3377  
              break;
3378  
          case 't':
3379  
              ch = '\t';
3380  
              break;
3381  
          case '\"':
3382  
              ch = '\"';
3383  
              break;
3384  
          case '\'':
3385  
              ch = '\'';
3386  
              break;
3387  
          // Hex Unicode: u????
3388  
          case 'u':
3389  
              if (i >= st.length() - 5) {
3390  
                  ch = 'u';
3391  
                  break;
3392  
              }
3393  
              int code = Integer.parseInt(
3394  
                      "" + st.charAt(i + 2) + st.charAt(i + 3)
3395  
                              + st.charAt(i + 4) + st.charAt(i + 5), 16);
3396  
              sb.append(Character.toChars(code));
3397  
              i += 5;
3398  
              continue;
3399  
          }
3400  
          i++;
3401  
        }
3402  
        sb.append(ch);
3403  
      }
3404  
      return sb.toString();      
3405  
    } else
3406  
      return s; // return original
3407  
  }
3408  
3409  
  // compile JavaX source, load classes & return main class
3410  
  // src can be a snippet ID or actual source code
3411  
  
3412  
  static Class<?> hotwire(String src) {
3413  
    try {
3414  
      Class j = getJavaX();
3415  
3416  
      List<File> libraries = new ArrayList<File>();
3417  
      File srcDir = (File) call(j, "transpileMain", src, libraries);
3418  
      
3419  
      Object androidContext = get(j, "androidContext");
3420  
      if (androidContext != null)
3421  
        return (Class) call(j, "loadx2android", srcDir, src);
3422  
        
3423  
      File classesDir = (File) call(j, "TempDirMaker_make");
3424  
      String javacOutput = (String) call(j, "compileJava", srcDir, libraries, classesDir);
3425  
      System.out.println(javacOutput);
3426  
      
3427  
      URL[] urls = new URL[libraries.size()+1];
3428  
      urls[0] = classesDir.toURI().toURL();
3429  
      for (int i = 0; i < libraries.size(); i++)
3430  
        urls[i+1] = libraries.get(i).toURI().toURL();
3431  
3432  
      // make class loader
3433  
      URLClassLoader classLoader = new URLClassLoader(urls);
3434  
  
3435  
      // load & return main class
3436  
      Class<?> theClass = classLoader.loadClass("main");
3437  
      
3438  
      call(j, "setVars", theClass, isSnippetID(src) ? src: null);
3439  
3440  
      return theClass;
3441  
    } catch (Exception e) {
3442  
      throw e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e);
3443  
    }
3444  
  }
3445  
3446  
  static RuntimeException fail() {
3447  
    throw new RuntimeException("fail");
3448  
  }
3449  
  
3450  
  static RuntimeException fail(String msg) {
3451  
    throw new RuntimeException(msg);
3452  
  }
3453  
3454  
static String shorten(String s, int max) {
3455  
  return s.length() <= max ? s : s.substring(0, Math.min(s.length(), max)) + "...";
3456  
}
3457  
}
3458  
interface StrF {
3459  
  String get(String s);
3460  
}

Author comment

Began life as a copy of #676

download  show line numbers  debug dex  old transpilations   

Travelled to 13 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt

No comments. add comment

Snippet ID: #1004087
Snippet name: Default boot-up code for JavaX/Android 26 (testing, with x27) BACKUP
Eternal ID of this version: #1004087/1
Text MD5: 9896000635ef5a9559875e47533a3e21
Author: stefan
Category: javax
Type: JavaX source code (Android)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2016-08-06 12:36:57
Source code size: 114747 bytes / 3460 lines
Pitched / IR pitched: No / No
Views / Downloads: 655 / 556
Referenced in: [show references]