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

3458
LINES

< > BotCompany Repo | #1002665 // 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  
    // TODO: optimize if it's a loaded snippet anyway
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  
    if (!isDex(dexData))
1474  
      throw new RuntimeException("Dex generation error: " + dexData.length + " bytes - " + new String(dexData, "UTF-8"));
1475  
    System.out.println("Dex loaded: " + dexData.length + "b");
1476  
1477  
    File dexDir = TempDirMaker_make();
1478  
    File dexFile = new File(dexDir, System.currentTimeMillis() + ".dex");
1479  
    File dexOutputDir = TempDirMaker_makeDexCache();
1480  
1481  
    System.out.println("Saving dex to: " + dexDir.getAbsolutePath());
1482  
    try {
1483  
      saveBinaryFile(dexFile.getPath(), dexData);
1484  
    } catch (Throwable e) {
1485  
      System.out.println("Whoa!");
1486  
      throw new RuntimeException(e);
1487  
    }
1488  
1489  
    System.out.println("Getting parent class loader.");
1490  
    ClassLoader parentClassLoader =
1491  
      //ClassLoader.getSystemClassLoader(); // does not find support jar
1492  
      //getClass().getClassLoader(); // Let's try this...
1493  
      x27.class.getClassLoader().getParent(); // XXX !
1494  
1495  
    //System.out.println("Making DexClassLoader.");
1496  
    //DexClassLoader classLoader = new DexClassLoader(dexFile.getAbsolutePath(), dexOutputDir.getAbsolutePath(), null,
1497  
    //  parentClassLoader);
1498  
    Class dcl = Class.forName("dalvik.system.DexClassLoader");
1499  
    Object classLoader = dcl.getConstructors()[0].newInstance(dexFile.getAbsolutePath(), dexOutputDir.getAbsolutePath(), null,
1500  
      parentClassLoader);
1501  
1502  
    //System.out.println("Loading main class.");
1503  
    //Class<?> theClass = classLoader.loadClass(mainClassName);
1504  
    Class<?> theClass = (Class<?>) call(classLoader, "loadClass", "main");
1505  
    mainClass = theClass;
1506  
1507  
    //System.out.println("Main class loaded.");
1508  
    try {
1509  
      set(theClass, "androidContext", androidContext);
1510  
    } catch (Throwable e) {}
1511  
1512  
    setVars(theClass, programID);
1513  
1514  
    return theClass;
1515  
  }
1516  
1517  
  static void javax2android(File srcDir, String[] args, String programID) throws Exception {
1518  
    Class<?> theClass = loadx2android(srcDir, programID);
1519  
1520  
    Method main = null;
1521  
    try {
1522  
      main = call_findStaticMethod(theClass, "main", new Object[]{androidContext}, false);
1523  
    } catch (RuntimeException e) {
1524  
    }
1525  
1526  
    //System.out.println("main method for " + androidContext + " of " + theClass + ": " + main);
1527  
1528  
    if (main != null) {
1529  
      // old style main program that returns a View
1530  
      System.out.println("Calling main (old-style)");
1531  
      Object view = main.invoke(null, androidContext);
1532  
      System.out.println("Calling setContentView with " + view);
1533  
      call(Class.forName("main"), "setContentViewInUIThread", view);
1534  
      //call(androidContext, "setContentView", view);
1535  
      System.out.println("Done.");
1536  
    } else {
1537  
      System.out.println("New-style main method running.\n\n====\n");
1538  
      runMainMethod(args, theClass);
1539  
    }
1540  
  }
1541  
1542  
  static byte[] DEX_FILE_MAGIC = { 0x64, 0x65, 0x78, 0x0a, 0x30, 0x33, 0x35, 0x00 };
1543  
1544  
  static boolean isDex(byte[] dexData) {
1545  
    if (dexData.length < DEX_FILE_MAGIC.length) return false;
1546  
    for (int i = 0; i < DEX_FILE_MAGIC.length; i++)
1547  
      if (dexData[i] != DEX_FILE_MAGIC[i])
1548  
        return false;
1549  
    return true;
1550  
  }
1551  
1552  
  static byte[] doPostBinary(String urlParameters, URLConnection conn) throws IOException {
1553  
    // connect and do POST
1554  
    setHeaders(conn);
1555  
    conn.setDoOutput(true);
1556  
1557  
    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
1558  
    writer.write(urlParameters);
1559  
    writer.flush();
1560  
1561  
    byte[] contents = loadBinaryPage_noHeaders(conn);
1562  
    writer.close();
1563  
    return contents;
1564  
  }
1565  
1566  
  static String compileJava(File srcDir, List<File> libraries, File classesDir) throws IOException {
1567  
    javaCompilerOutput = null;
1568  
    ++compilations;
1569  
1570  
    // collect sources
1571  
1572  
    List<File> sources = new ArrayList<File>();
1573  
    if (verbose) System.out.println("Scanning for sources in " + srcDir.getPath());
1574  
    scanForSources(srcDir, sources, true);
1575  
    if (sources.isEmpty())
1576  
      throw new IOException("No sources found");
1577  
1578  
    // compile
1579  
1580  
    File optionsFile = File.createTempFile("javax", "");
1581  
    if (verbose) System.out.println("Compiling " + sources.size() + " source(s) to " + classesDir.getPath());
1582  
    if (verbose) System.out.println("Libraries: " + libraries);
1583  
    String options = "-d " + bashQuote(classesDir.getPath());
1584  
    writeOptions(sources, libraries, optionsFile, options);
1585  
    classesDir.mkdirs();
1586  
    return javaCompilerOutput = invokeJavaCompiler(optionsFile);
1587  
  }
1588  
1589  
  private static void runProgram(String javacOutput, File classesDir, File ioBaseDir,
1590  
                                 boolean silent, boolean runInProcess,
1591  
                                 List<File> libraries, String[] args, String cacheAs,
1592  
                                 String programID, Info info) throws Exception {
1593  
    // print javac output if compile failed and it hasn't been printed yet
1594  
    if (info != null) {
1595  
      info.programID = programID;
1596  
      info.programArgs = args;
1597  
    }
1598  
    boolean didNotCompile = !didCompile(classesDir);
1599  
    if (verbose || didNotCompile)
1600  
      System.out.println(javacOutput);
1601  
    if (didNotCompile)
1602  
      return;
1603  
1604  
    if (runInProcess
1605  
      || (ioBaseDir.getAbsolutePath().equals(new File(".").getAbsolutePath()) && !silent)) {
1606  
      runProgramQuick(classesDir, libraries, args, cacheAs, programID, info, ioBaseDir);
1607  
      return;
1608  
    }
1609  
1610  
    boolean echoOK = false;
1611  
    // TODO: add libraries to class path
1612  
    String bashCmd = "(cd " + bashQuote(ioBaseDir.getAbsolutePath()) + " && (java -cp "
1613  
      + bashQuote(classesDir.getAbsolutePath()) + " main" + (echoOK ? "; echo ok" : "") + "))";
1614  
    if (verbose) System.out.println(bashCmd);
1615  
    String output = backtick(bashCmd);
1616  
    lastOutput = output;
1617  
    if (verbose || !silent)
1618  
      System.out.println(output);
1619  
  }
1620  
1621  
  static boolean didCompile(File classesDir) {
1622  
    return hasFile(classesDir, "main.class");
1623  
  }
1624  
1625  
  private static void runProgramQuick(File classesDir, List<File> libraries,
1626  
                                      String[] args, String cacheAs,
1627  
                                      String programID, Info info,
1628  
                                      File ioBaseDir) throws Exception {
1629  
    // collect urls
1630  
    URL[] urls = new URL[libraries.size()+1];
1631  
    urls[0] = classesDir.toURI().toURL();
1632  
    for (int i = 0; i < libraries.size(); i++)
1633  
      urls[i+1] = libraries.get(i).toURI().toURL();
1634  
1635  
    // make class loader
1636  
    URLClassLoader classLoader = new URLClassLoader(urls);
1637  
1638  
    // load JavaX main class
1639  
    Class<?> mainClass = classLoader.loadClass("main");
1640  
    
1641  
    if (info != null)
1642  
      info.mainClass = mainClass;
1643  
      
1644  
    if (cacheAs != null)
1645  
      programCache.put(cacheAs, mainClass);
1646  
      
1647  
    // change baseDir
1648  
    try {
1649  
      //print("Changing base dir to " + ioBaseDir.getAbsolutePath());
1650  
      Class virtual = mainClass.getClassLoader().loadClass("virtual");
1651  
      set(virtual, "virtual_baseDir", ioBaseDir.getAbsolutePath());
1652  
    } catch (Throwable e) { /* whatever */ }
1653  
1654  
    setVars(mainClass, programID);
1655  
    runMainMethod(args, mainClass);
1656  
  }
1657  
1658  
  static void setVars(Class<?> theClass, String programID) {
1659  
    try {
1660  
      set(theClass, "programID", programID);
1661  
    } catch (Throwable e) {}
1662  
1663  
    try {
1664  
      set(theClass, "__javax", x27.class);
1665  
    } catch (Throwable e) {}
1666  
  }
1667  
1668  
1669  
  static void runMainMethod(Object args, Class<?> mainClass) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
1670  
    Method main = mainClass.getMethod("main", String[].class);
1671  
    main.invoke(null, args);
1672  
  }
1673  
1674  
  static String invokeJavaCompiler(File optionsFile) throws IOException {
1675  
    String output;
1676  
    if (hasEcj() && !javacOnly)
1677  
      output = invokeEcj(optionsFile);
1678  
    else
1679  
      output = invokeJavac(optionsFile);
1680  
    if (verbose) System.out.println(output);
1681  
    return output;
1682  
  }
1683  
1684  
  private static boolean hasEcj() {
1685  
    try {
1686  
      Class.forName("org.eclipse.jdt.internal.compiler.batch.Main");
1687  
      return true;
1688  
    } catch (ClassNotFoundException e) {
1689  
      return false;
1690  
    }
1691  
  }
1692  
1693  
  private static String invokeJavac(File optionsFile) throws IOException {
1694  
    String output;
1695  
    output = backtick("javac " + bashQuote("@" + optionsFile.getPath()));
1696  
    if (exitValue != 0) {
1697  
      System.out.println(output);
1698  
      throw new RuntimeException("javac returned errors.");
1699  
    }
1700  
    return output;
1701  
  }
1702  
1703  
  // throws ClassNotFoundException if ecj is not in classpath
1704  
  static String invokeEcj(File optionsFile) {
1705  
    try {
1706  
      StringWriter writer = new StringWriter();
1707  
      PrintWriter printWriter = new PrintWriter(writer);
1708  
1709  
      // add more eclipse options in the line below
1710  
1711  
      String[] args = {"@" + optionsFile.getPath(),
1712  
        "-source", javaTarget,
1713  
        "-target", javaTarget,
1714  
        "-nowarn"
1715  
      };
1716  
1717  
      Class ecjClass = Class.forName("org.eclipse.jdt.internal.compiler.batch.Main");
1718  
      Object main = newInstance(ecjClass, printWriter, printWriter, false);
1719  
      call(main, "compile", new Object[]{args});
1720  
      int errors = (Integer) get(main, "globalErrorsCount");
1721  
1722  
      String output = writer.toString();
1723  
      if (errors != 0) {
1724  
        System.out.println(output);
1725  
        throw new RuntimeException("Java compiler returned errors.");
1726  
      }
1727  
      return output;
1728  
    } catch (Exception e) {
1729  
      throw e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e);
1730  
    }
1731  
  }
1732  
1733  
  static Object newInstance(Class c, Object... args) { try {
1734  
    Constructor m = findConstructor(c, args);
1735  
    m.setAccessible(true);
1736  
    return m.newInstance(args);
1737  
  } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
1738  
1739  
  static Constructor findConstructor(Class c, Object... args) {
1740  
    for (Constructor m : c.getDeclaredConstructors()) {
1741  
      if (!checkArgs(m.getParameterTypes(), args, verbose))
1742  
        continue;
1743  
      return m;
1744  
    }
1745  
    throw new RuntimeException("Constructor with " + args.length + " matching parameter(s) not found in " + c.getName());
1746  
  }
1747  
1748  
  static boolean checkArgs(Class[] types, Object[] args, boolean debug) {
1749  
    if (types.length != args.length) {
1750  
      if (debug)
1751  
        System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
1752  
      return false;
1753  
    }
1754  
    for (int i = 0; i < types.length; i++)
1755  
      if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
1756  
        if (debug)
1757  
          System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
1758  
        return false;
1759  
      }
1760  
    return true;
1761  
  }
1762  
1763  
  // extended to handle primitive types
1764  
  private static boolean isInstanceX(Class type, Object arg) {
1765  
    if (type == boolean.class) return arg instanceof Boolean;
1766  
    if (type == int.class) return arg instanceof Integer;
1767  
    if (type == long.class) return arg instanceof Long;
1768  
    if (type == float.class) return arg instanceof Float;
1769  
    if (type == short.class) return arg instanceof Short;
1770  
    if (type == char.class) return arg instanceof Character;
1771  
    if (type == byte.class) return arg instanceof Byte;
1772  
    return type.isInstance(arg);
1773  
  }
1774  
1775  
  private static void writeOptions(List<File> sources, List<File> libraries,
1776  
                                   File optionsFile, String moreOptions) throws IOException {
1777  
    FileWriter writer = new FileWriter(optionsFile);
1778  
    for (File source : sources)
1779  
      writer.write(bashQuote(source.getPath()) + " ");
1780  
    if (!libraries.isEmpty()) {
1781  
      List<String> cp = new ArrayList<String>();
1782  
      for (File lib : libraries)
1783  
        cp.add(lib.getAbsolutePath());
1784  
      writer.write("-cp " + bashQuote(join(File.pathSeparator, cp)) + " ");
1785  
    }
1786  
    writer.write(moreOptions);
1787  
    writer.close();
1788  
  }
1789  
1790  
  static void scanForSources(File source, List<File> sources, boolean topLevel) {
1791  
    if (source.isFile() && source.getName().endsWith(".java"))
1792  
      sources.add(source);
1793  
    else if (source.isDirectory() && !isSkippedDirectoryName(source.getName(), topLevel)) {
1794  
      File[] files = source.listFiles();
1795  
      for (File file : files)
1796  
        scanForSources(file, sources, false);
1797  
    }
1798  
  }
1799  
1800  
  private static boolean isSkippedDirectoryName(String name, boolean topLevel) {
1801  
    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.)
1802  
    return name.equalsIgnoreCase("input") || name.equalsIgnoreCase("output");
1803  
  }
1804  
1805  
  static int exitValue;
1806  
  public static String backtick(String cmd) throws IOException {
1807  
    ++processesStarted;
1808  
    File outFile = File.createTempFile("_backtick", "");
1809  
    File scriptFile = File.createTempFile("_backtick", isWindows() ? ".bat" : "");
1810  
1811  
    String command = cmd + " >" + bashQuote(outFile.getPath()) + " 2>&1";
1812  
    //Log.info("[Backtick] " + command);
1813  
    try {
1814  
      saveTextFile(scriptFile.getPath(), command);
1815  
      String[] command2;
1816  
      if (isWindows())
1817  
        command2 = new String[] { scriptFile.getPath() };
1818  
      else
1819  
        command2 = new String[] { "/bin/bash", scriptFile.getPath() };
1820  
      Process process = Runtime.getRuntime().exec(command2);
1821  
      try {
1822  
        process.waitFor();
1823  
      } catch (InterruptedException e) {
1824  
        throw new RuntimeException(e);
1825  
      }
1826  
      exitValue = process.exitValue();
1827  
      if (verbose)
1828  
        System.out.println("Process return code: " + exitValue);
1829  
      return loadTextFile(outFile.getPath(), "");
1830  
    } finally {
1831  
      scriptFile.delete();
1832  
    }
1833  
  }
1834  
1835  
  /** possibly improvable */
1836  
  public static String javaQuote(String text) {
1837  
    return bashQuote(text);
1838  
  }
1839  
1840  
  /** possibly improvable */
1841  
  public static String bashQuote(String text) {
1842  
    if (text == null) return null;
1843  
    return "\"" + text
1844  
      .replace("\\", "\\\\")
1845  
      .replace("\"", "\\\"")
1846  
      .replace("\n", "\\n")
1847  
      .replace("\r", "\\r") + "\"";
1848  
  }
1849  
1850  
  public final static String charsetForTextFiles = "UTF8";
1851  
1852  
  static long TempDirMaker_lastValue;
1853  
1854  
  public static File TempDirMaker_makeDexCache() {
1855  
    File dir = new File(getDexCacheHome(), ".javax/" + TempDirMaker_newValue());
1856  
    dir.mkdirs();
1857  
    return dir;
1858  
  }
1859  
1860  
  public static File TempDirMaker_make() {
1861  
    File dir = new File(userHome(), ".javax/" + TempDirMaker_newValue());
1862  
    dir.mkdirs();
1863  
    return dir;
1864  
  }
1865  
1866  
  private static long TempDirMaker_newValue() {
1867  
    long value;
1868  
    do
1869  
      value = System.currentTimeMillis();
1870  
    while (value == TempDirMaker_lastValue);
1871  
    TempDirMaker_lastValue = value;
1872  
    return value;
1873  
  }
1874  
1875  
    public static String join(String glue, Iterable<String> strings) {
1876  
    StringBuilder buf = new StringBuilder();
1877  
    Iterator<String> i = strings.iterator();
1878  
    if (i.hasNext()) {
1879  
      buf.append(i.next());
1880  
      while (i.hasNext())
1881  
        buf.append(glue).append(i.next());
1882  
    }
1883  
    return buf.toString();
1884  
  }
1885  
  
1886  
  public static String join(String glue, String[] strings) {
1887  
    return join(glue, Arrays.asList(strings));
1888  
  }
1889  
  
1890  
  public static String join(Iterable<String> strings) {
1891  
    return join("", strings);
1892  
  }
1893  
  
1894  
  public static String join(String[] strings) {
1895  
    return join("", strings);
1896  
  }
1897  
 // join
1898  
  
1899  
  public static boolean isWindows() {
1900  
    return System.getProperty("os.name").contains("Windows");
1901  
  }
1902  
1903  
  public static String makeRandomID(int length) {
1904  
    Random random = new Random();
1905  
    char[] id = new char[length];
1906  
    for (int i = 0; i< id.length; i++)
1907  
      id[i] = (char) ((int) 'a' + random.nextInt(26));
1908  
    return new String(id);
1909  
  }
1910  
1911  
  static String computerID;
1912  
  public static String getComputerID() throws IOException {
1913  
    if (noID) return null;
1914  
    if (computerID == null) {
1915  
      File file = new File(userHome(), ".tinybrain/computer-id");
1916  
      computerID = loadTextFile(file.getPath(), null);
1917  
      if (computerID == null) {
1918  
        computerID = makeRandomID(12);
1919  
        saveTextFile(file.getPath(), computerID);
1920  
      }
1921  
      if (verbose)
1922  
        System.out.println("Local computer ID: " + computerID);
1923  
    }
1924  
    return computerID;
1925  
  }
1926  
1927  
  static int fileDeletions;
1928  
1929  
  static void cleanCache() {
1930  
    try {
1931  
      if (verbose)
1932  
        System.out.println("Cleaning cache");
1933  
      fileDeletions = 0;
1934  
      File javax = new File(userHome(), ".javax");
1935  
      long now = System.currentTimeMillis();
1936  
      File[] files = javax.listFiles();
1937  
      if (files != null) for (File dir : files) {
1938  
        if (dir.isDirectory() && Pattern.compile("\\d+").matcher(dir.getName()).matches()) {
1939  
          long time = Long.parseLong(dir.getName());
1940  
          long seconds = (now - time) / 1000;
1941  
          long minutes = seconds / 60;
1942  
          long hours = minutes / 60;
1943  
          if (hours >= tempFileRetentionTime) {
1944  
            //System.out.println("Can delete " + dir.getAbsolutePath() + ", age: " + hours + " h");
1945  
            removeDir(dir);
1946  
          }
1947  
        }
1948  
      }
1949  
      if (verbose && fileDeletions != 0)
1950  
        System.out.println("Cleaned cache. File deletions: " + fileDeletions);
1951  
    } catch (Throwable e) {
1952  
      e.printStackTrace();
1953  
    }
1954  
  }
1955  
1956  
  static void removeDir(File dir) {
1957  
    if (dir.getAbsolutePath().indexOf(".javax") < 0)  // security check!
1958  
      return;
1959  
    for (File f : dir.listFiles()) {
1960  
      if (f.isDirectory())
1961  
        removeDir(f);
1962  
      else {
1963  
        if (verbose)
1964  
          System.out.println("Deleting " + f.getAbsolutePath());
1965  
        f.delete();
1966  
        ++fileDeletions;
1967  
      }
1968  
    }
1969  
    dir.delete();
1970  
  }
1971  
1972  
  static void showSystemProperties() {
1973  
    System.out.println("System properties:\n");
1974  
    for (Map.Entry<Object, Object> entry : System.getProperties().entrySet()) {
1975  
      System.out.println("  " + entry.getKey() + " = " + entry.getValue());
1976  
    }
1977  
    System.out.println();
1978  
  }
1979  
1980  
  static void showVersion() {
1981  
    //showSystemProperties();
1982  
    boolean eclipseFound = hasEcj();
1983  
    //String platform = System.getProperty("java.vendor") + " " + System.getProperty("java.runtime.name") + " " + System.getProperty("java.version");
1984  
    String platform = System.getProperty("java.vm.name") + " " + System.getProperty("java.version");
1985  
    String os = System.getProperty("os.name"), arch = System.getProperty("os.arch");
1986  
    System.out.println("This is " + version + ".");
1987  
    System.out.println("[Details: " +
1988  
      (eclipseFound ? "Eclipse compiler (good)" : "javac (not so good)")
1989  
      + ", " + platform + ", " + arch + ", " + os + "]");
1990  
  }
1991  
1992  
  static boolean isAndroid() {
1993  
    return System.getProperty("java.vendor").toLowerCase().indexOf("android") >= 0;
1994  
  }
1995  
  
1996  
    static void set(Object o, String field, Object value) {
1997  
    if (o instanceof Class) set((Class) o, field, value);
1998  
    else try {
1999  
      Field f = set_findField(o.getClass(), field);
2000  
      f.setAccessible(true);
2001  
      f.set(o, value);
2002  
    } catch (Exception e) {
2003  
      throw new RuntimeException(e);
2004  
    }
2005  
  }
2006  
  
2007  
  static void set(Class c, String field, Object value) {
2008  
    try {
2009  
      Field f = set_findStaticField(c, field);
2010  
      f.setAccessible(true);
2011  
      f.set(null, value);
2012  
    } catch (Exception e) {
2013  
      throw new RuntimeException(e);
2014  
    }
2015  
  }
2016  
  
2017  
  static Field set_findField(Class<?> c, String field) {
2018  
    for (Field f : c.getDeclaredFields())
2019  
      if (f.getName().equals(field))
2020  
        return f;
2021  
    throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
2022  
  }
2023  
  
2024  
  static Field set_findStaticField(Class<?> c, String field) {
2025  
    for (Field f : c.getDeclaredFields())
2026  
      if (f.getName().equals(field) && (f.getModifiers() & Modifier.STATIC) != 0)
2027  
        return f;
2028  
    throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
2029  
  } // set function
2030  
2031  
  static String smartJoin(String[] args) {
2032  
    String[] a2 = new String[args.length];
2033  
    for (int i = 0; i < args.length; i++) {
2034  
      a2[i] = Pattern.compile("\\w+").matcher(args[i]).matches() ? args[i] : quote(args[i]);
2035  
    }
2036  
    return join(" ", a2);
2037  
  }
2038  
  
2039  
  static void logStart(String[] args) throws IOException {
2040  
    String line = smartJoin(args);
2041  
    appendToLog(new File(userHome(), ".javax/log.txt").getPath(), line);
2042  
  }
2043  
  
2044  
  static String quote(String s) {
2045  
    if (s == null) return "null";
2046  
    return "\"" + s.replace("\\", "\\\\").replace("\"", "\\\"").replace("\r", "\\r").replace("\n", "\\n") + "\"";
2047  
  }
2048  
  
2049  
  static void appendToLog(String path, String line) throws IOException {
2050  
    appendToFile(path, "\n" + line + "\n");
2051  
  }
2052  
  
2053  
  static void appendToFile(String path, String s) throws IOException {
2054  
    new File(path).getParentFile().mkdirs();
2055  
    Writer writer = new BufferedWriter(new OutputStreamWriter(
2056  
      new FileOutputStream(path, true), "UTF-8"));
2057  
    writer.write(s);
2058  
    writer.close();
2059  
  }
2060  
2061  
  static long now_virtualTime;
2062  
  static long now() {
2063  
    return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis();
2064  
  }
2065  
2066  
  static void print(Object o) {
2067  
    System.out.println(o);
2068  
  }
2069  
2070  
  static void nohupJavax(String javaxargs) {
2071  
    try {
2072  
      File xfile = new File(userHome(), ".javax/x27.jar");
2073  
      if (!xfile.isFile()) {
2074  
        String url = "http://tinybrain.de/x27.jar";
2075  
        byte[] data = loadBinaryPage(new URL(url).openConnection());
2076  
        if (data.length < 1000000)
2077  
          throw new RuntimeException("Could not load " + url);
2078  
        saveBinaryFile(xfile.getPath(), data);
2079  
      }
2080  
      String jarPath = xfile.getPath();
2081  
      nohup("java -jar " + (isWindows() ? winQuote(jarPath) : bashQuote(jarPath)) + " " + javaxargs);
2082  
    } catch (Exception e) { throw new RuntimeException(e); }
2083  
  }
2084  
2085  
  /** possibly improvable */
2086  
  public static String winQuote(String text) {
2087  
    if (text == null) return null;
2088  
    return "\"" + text
2089  
      .replace("\\", "\\\\")
2090  
      .replace("\"", "\\\"")
2091  
      .replace("\n", "\\n")
2092  
      .replace("\r", "\\r") + "\"";
2093  
  }
2094  
2095  
  public static File nohup(String cmd) throws IOException {
2096  
    File outFile = File.createTempFile("nohup_" + nohup_sanitize(cmd), ".out");
2097  
    nohup(cmd, outFile, false);
2098  
    return outFile;
2099  
  }
2100  
2101  
  static String nohup_sanitize(String s) {
2102  
    return s.replaceAll("[^a-zA-Z0-9\\-_]", "");
2103  
  }
2104  
2105  
  /** outFile takes stdout and stderr. */
2106  
  public static void nohup(String cmd, File outFile, boolean append) throws IOException {
2107  
    String command = nohup_makeNohupCommand(cmd, outFile, append);
2108  
2109  
    File scriptFile = File.createTempFile("_realnohup", isWindows() ? ".bat" : "");
2110  
    System.out.println("[Nohup] " + command);
2111  
    try {
2112  
      //System.out.println("[RealNohup] Script file: " + scriptFile.getPath());
2113  
      saveTextFile(scriptFile.getPath(), command);
2114  
      String[] command2;
2115  
      if (isWindows())
2116  
        command2 = new String[] {"cmd", "/c", "start", "/b", scriptFile.getPath() };
2117  
      else
2118  
        command2 = new String[] {"/bin/bash", scriptFile.getPath() };
2119  
2120  
      Process process = Runtime.getRuntime().exec(command2);
2121  
      try {
2122  
        process.waitFor();
2123  
      } catch (InterruptedException e) {
2124  
        throw new RuntimeException(e);
2125  
      }
2126  
      int value = process.exitValue();
2127  
      //System.out.println("exit value: " + value);
2128  
    } finally {
2129  
      if (!isWindows())
2130  
        scriptFile.delete();
2131  
    }
2132  
  }
2133  
2134  
  public static String nohup_makeNohupCommand(String cmd, File outFile, boolean append) {
2135  
    mkdirsForFile(outFile);
2136  
2137  
    String command;
2138  
    if (isWindows())
2139  
      command = cmd + (append ? " >>" : " >") + winQuote(outFile.getPath()) + " 2>&1";
2140  
    else
2141  
      command = "nohup " + cmd + (append ? " >>" : " >") + bashQuote(outFile.getPath()) + " 2>&1 &";
2142  
    return command;
2143  
  }
2144  
2145  
  public static void mkdirsForFile(File file) {
2146  
    File dir = file.getParentFile();
2147  
    if (dir != null) // is null if file is in current dir
2148  
      dir.mkdirs();
2149  
  }
2150  
 
2151  
  static void autoReportToChat() {
2152  
    // TODO: put back in
2153  
  }
2154  
  
2155  
  static class Q {
2156  
    LinkedBlockingQueue<Runnable> q = new LinkedBlockingQueue<Runnable>();
2157  
    
2158  
    static class Done extends RuntimeException {}
2159  
    
2160  
    Q() {}
2161  
    
2162  
    Q(String name, boolean startThread) {
2163  
      if (startThread)
2164  
        new Thread(name) {
2165  
          public void run() {
2166  
            Q.this.run();
2167  
          }
2168  
        }.start();
2169  
    }
2170  
    
2171  
    Iterable<Runnable> master() {
2172  
      return new Iterable<Runnable>() {
2173  
        public Iterator<Runnable> iterator() {
2174  
          return new Iterator<Runnable>() {
2175  
            Runnable x;
2176  
            
2177  
            public boolean hasNext() { try {
2178  
   
2179  
              //debug("hasNext");
2180  
              while (x == null)
2181  
                x = q.poll(1, TimeUnit.DAYS);
2182  
              //debug("hasNext true");
2183  
              return true;
2184  
            
2185  
  } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
2186  
            
2187  
            public Runnable next() {
2188  
              //debug("next");
2189  
              hasNext();
2190  
              Runnable _x = x;
2191  
              x = null;
2192  
              //debug("next " + structure(x));
2193  
              return _x;
2194  
            }
2195  
            
2196  
            public void remove() {
2197  
            }
2198  
          };
2199  
        }
2200  
      };
2201  
    }
2202  
    
2203  
    void add(Runnable r) {
2204  
      q.add(r);
2205  
    }
2206  
    
2207  
    void run() {
2208  
      for (Runnable r : master()) {
2209  
        try {
2210  
          r.run();
2211  
        } catch (Done e) {
2212  
          return; // break signal
2213  
        } catch (Throwable e) {
2214  
          e.printStackTrace();
2215  
        }
2216  
      }
2217  
    }
2218  
    
2219  
    void done() {
2220  
      add(new Runnable() {
2221  
        public void run() {
2222  
          throw new Done();
2223  
        }
2224  
      });
2225  
    }
2226  
  } // class Q
2227  
2228  
static void reportToChat(final String s, boolean silent) {
2229  
    if (s == null || s.length() == 0) return;
2230  
    if (!silent)
2231  
      print("reportToChat: " + quote(s));
2232  
    reportToChat_getChatThread().add(new Runnable() {
2233  
    public void run() { try {
2234  
        startChatServerIfNotUp();
2235  
        waitForChatServer();
2236  
        chatSend(s);
2237  
    } catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}});
2238  
   }
2239  
  
2240  
  static Q reportToChat_q;
2241  
  
2242  
  static Q reportToChat_getChatThread() {
2243  
    if (reportToChat_q == null)
2244  
      reportToChat_q = new Q("reportToChat", true);
2245  
    return reportToChat_q;
2246  
  }
2247  
  
2248  
  static void startChatServerIfNotUp() {
2249  
    if (portIsBound(9751)) {
2250  
      //print("Chat seems to be up.");
2251  
    } else {
2252  
      nohupJavax("1000867");
2253  
      print("Chat server should be coming up any minute now.");
2254  
    }
2255  
  }
2256  
  
2257  
  static void waitForChatServer() {
2258  
    if (!portIsBound(9751)) {
2259  
      //System.out.print("Waiting for chat server... ");
2260  
      do {
2261  
        sleep(1000);
2262  
      } while (!portIsBound(9751));
2263  
      //print("OK.");
2264  
    }
2265  
  }
2266  
2267  
  static boolean portIsBound(int port) {
2268  
    try {
2269  
      ServerSocket s = new ServerSocket(port);
2270  
      s.close();
2271  
      return false;
2272  
    } catch (IOException e) {
2273  
      return true;
2274  
    }
2275  
  }
2276  
  
2277  
  static class LineBuf {
2278  
    StringBuffer buf = new StringBuffer();
2279  
    
2280  
    void append(String s) {
2281  
      buf.append(s);
2282  
    }
2283  
    
2284  
    String nextLine() {
2285  
      int i = buf.indexOf("\n");
2286  
      if (i >= 0) {
2287  
        String s = buf.substring(0, i > 0 && buf.charAt(i-1) == '\r' ? i-1 : i);
2288  
        buf.delete(0, i+1);
2289  
        return s;
2290  
      }
2291  
      return null;
2292  
    }
2293  
  } // LineBuf
2294  
2295  
  static void sleep(long ms) {
2296  
    try {
2297  
      Thread.sleep(ms);
2298  
    } catch (Exception e) { throw new RuntimeException(e); }
2299  
  }
2300  
2301  
2302  
static int chatSend_chatPort = 9751;
2303  
2304  
  static abstract class DialogIO {
2305  
    abstract boolean isStillConnected();
2306  
    abstract String readLineNoBlock();
2307  
    abstract boolean waitForLine();
2308  
    abstract void sendLine(String line);
2309  
    abstract boolean isLocalConnection();
2310  
    abstract Socket getSocket();
2311  
  }
2312  
  
2313  
  static abstract class DialogHandler {
2314  
    abstract void run(DialogIO io);
2315  
  } // DialogIO
2316  
2317  
static DialogIO chatSend_dialog;
2318  
static String chatSend_id;
2319  
2320  
static void chatSend(String line) { try {
2321  
 
2322  
  if (chatSend_dialog == null) {
2323  
    chatSend_dialog = talkTo("localhost", chatSend_chatPort);    
2324  
    chatSend_dialog.waitForLine();
2325  
    String l = chatSend_dialog.readLineNoBlock();
2326  
    if (l.startsWith("Your ID: "))
2327  
      chatSend_id = l.substring("Your ID: ".length());
2328  
  }
2329  
2330  
  chatSend_dialog.sendLine(line);
2331  
2332  
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} // chatSend
2333  
2334  
  static class TeeOutputStream extends OutputStream {
2335  
    
2336  
    protected OutputStream out, branch;
2337  
2338  
    public TeeOutputStream( OutputStream out, OutputStream branch ) {
2339  
      this.out = out;
2340  
      this.branch = branch;
2341  
    }
2342  
2343  
    @Override
2344  
    public synchronized void write(byte[] b) throws IOException {
2345  
      write(b, 0, b.length);
2346  
    }
2347  
2348  
    @Override
2349  
    public synchronized void write(byte[] b, int off, int len) throws IOException {
2350  
      //if (verbose) oldOut.println("Tee write " + new String(b, "UTF-8"));
2351  
      out.write(b, off, len);
2352  
      this.branch.write(b, off, len);
2353  
    }
2354  
2355  
    @Override
2356  
    public synchronized void write(int b) throws IOException {
2357  
      write(new byte[] {(byte) b});
2358  
    }
2359  
2360  
    /**
2361  
     * Flushes both streams.
2362  
     * @throws IOException if an I/O error occurs
2363  
     */
2364  
    @Override
2365  
    public void flush() throws IOException {
2366  
      out.flush();
2367  
      this.branch.flush();
2368  
    }
2369  
2370  
    /**
2371  
     * Closes both streams.
2372  
     * @throws IOException if an I/O error occurs
2373  
     */
2374  
    @Override
2375  
    public void close() throws IOException {
2376  
      out.close();
2377  
      this.branch.close();
2378  
    }
2379  
  }
2380  
  
2381  
  static boolean isChatServer(String[] args) {
2382  
    for (int i = 0; i < args.length; i++)
2383  
      if (isSnippetID(args[i]))
2384  
        return parseSnippetID(args[i]) == 1000867;
2385  
    return false;
2386  
  }
2387  
  
2388  
  static String getSnippetTitle(String id) {
2389  
    try {
2390  
      return loadPage(new URL("http://tinybrain.de:8080/tb-int/getfield.php?id=" + parseSnippetID(id) + "&field=title"));
2391  
    } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }
2392  
  }
2393  
  
2394  
  static void listUserThreadsWithStackTraces() {
2395  
    print("");
2396  
    Map<Thread, StackTraceElement[]> threadMap = Thread.getAllStackTraces();
2397  
    int n = 0;
2398  
    for (Thread t : threadMap.keySet()) {
2399  
      ThreadGroup g = t.getThreadGroup();
2400  
      if (g != null && g.getName().equals("system")) continue;
2401  
      ++n;
2402  
      print(t);
2403  
      for (StackTraceElement e : threadMap.get(t)) {
2404  
        print("  " + e);
2405  
      }
2406  
      print("");
2407  
    }
2408  
    print(n + " user threads.");
2409  
  }
2410  
  
2411  
  static void killMyself() {
2412  
    print("Killing myself. (insert overall feeling here)");
2413  
    System.exit(0);
2414  
  }
2415  
  
2416  
  static void makeVMAndroid() {
2417  
    makeAndroidNoConsoleDaemon("This is a JavaX VM.", new StrF() {
2418  
public String get(String s) {
2419  
try { return  answer(s) ; } catch (Exception _e) {
2420  
  throw _e instanceof RuntimeException ? (RuntimeException) _e : new RuntimeException(_e); } }
2421  
});
2422  
  }
2423  
  
2424  
  static class Info {
2425  
    String programID;
2426  
    String[] programArgs;
2427  
    File transpiledSrc;
2428  
    Class mainClass;
2429  
  }
2430  
  
2431  
  static Info info = new Info();
2432  
  
2433  
  static synchronized String answer(String s) {
2434  
    Matches m = new Matches();
2435  
    
2436  
    if (match3("kill!", s)) {
2437  
      killMyself();
2438  
      return "ok";
2439  
    }
2440  
    if (match3("What is your process ID?", s) || match3("what is your pid?", s))
2441  
      return getPID();
2442  
    if (match3("what is your program id?", s))
2443  
      return info.programID;
2444  
    if (match3("what are your program arguments?", s))
2445  
      return structure(info.programArgs);
2446  
    if (match3("get fields of main class", s))
2447  
      return structure(listFields(info.mainClass));
2448  
    if (match3("get field * of main class", s, m))
2449  
      return structure(get(info.mainClass, m.m[0]));
2450  
    if (match3("invoke function * of main class", s, m))
2451  
      return structure(call(info.mainClass, m.m[0]));
2452  
    if (match3("set field * of main class to *", s, m)) {
2453  
      set(info.mainClass, m.m[0], unstructure(m.m[1]));
2454  
      return "ok";
2455  
    }
2456  
    if (match3("how much memory are you consuming", s))
2457  
      return "Java heap size: " + (Runtime.getRuntime().totalMemory()+1024*1024-1)/1024/1024 + " MB";
2458  
    if (match3("how much memory is used after GC?", s)) {
2459  
      System.gc();
2460  
      return "Java heap used: " + (Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory()+1024*1024-1)/1024/1024 + " MB";
2461  
    }
2462  
    if (match3("how much memory is used?", s))
2463  
      return "Java heap used: " + (Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory()+1024*1024-1)/1024/1024 + " MB";
2464  
    return null;
2465  
  }
2466  
  
2467  
static class Android {
2468  
  int port;
2469  
  DialogHandler handler;
2470  
}
2471  
2472  
static int makeAndroid(final String greeting) {
2473  
  return makeAndroid(greeting, new StrF() {
2474  
public String get(String s) {
2475  
try { return 
2476  
    (String) call(getMainClass(), "answer", s)
2477  
  ; } catch (Exception _e) {
2478  
  throw _e instanceof RuntimeException ? (RuntimeException) _e : new RuntimeException(_e); } }
2479  
});
2480  
}
2481  
2482  
static int makeAndroidNoConsole(final String greeting, final StrF f) {
2483  
  return makeAndroid(greeting, f, false, false);
2484  
}
2485  
2486  
static int makeAndroidNoConsoleDaemon(final String greeting, final StrF f) {
2487  
  return makeAndroid(greeting, f, false, true);
2488  
}
2489  
2490  
static int makeAndroid(final String greeting, final StrF f) {
2491  
  return makeAndroid(greeting, f, true, false);
2492  
}
2493  
2494  
static int makeAndroid(final String greeting, final StrF f, boolean console, boolean daemon) {
2495  
  print(greeting);
2496  
  final Android a = new Android();
2497  
  a.handler = makeAndroid_makeDialogHandler(greeting, f);
2498  
  a.port = daemon 
2499  
    ? startDialogServerOnPortAboveDaemon(5000, a.handler)
2500  
    : startDialogServerOnPortAbove(5000, a.handler);
2501  
  
2502  
  if (console) {
2503  
    print("You may also type on this console.");
2504  
    Thread _t_0 = new Thread() {
2505  
public void run() {
2506  
try {
2507  
2508  
      String line;
2509  
      while ((line = readLine()) != null) {
2510  
        if ("bye".equals(line))
2511  
          print("> bye stranger");
2512  
        else
2513  
          makeAndroid_getAnswer(line, f); // prints answer on console too
2514  
      }
2515  
    } catch (Exception _e) {
2516  
  throw _e instanceof RuntimeException ? (RuntimeException) _e : new RuntimeException(_e); } }
2517  
};
2518  
_t_0.start();
2519  
  }
2520  
  
2521  
  record(a);
2522  
  return a.port;
2523  
}
2524  
2525  
static DialogHandler makeAndroid_makeDialogHandler(final String greeting, final StrF f) {
2526  
  return new DialogHandler() {
2527  
public void run(final DialogIO io) {
2528  
2529  
    if (!(publicCommOn() || io.isLocalConnection())) {
2530  
      io.sendLine("Sorry, not allowed");
2531  
      return;
2532  
    }
2533  
    
2534  
    String dialogID = randomID(8);
2535  
    
2536  
    io.sendLine(greeting + " / Your ID: " + dialogID);
2537  
    
2538  
    while (io.isStillConnected()) {
2539  
      if (io.waitForLine()) {
2540  
        final String line = io.readLineNoBlock();
2541  
        String s = dialogID + " at " + now() + ": " + quote(line);
2542  
        print(s);
2543  
        if ("bye".equals(line)) {
2544  
          io.sendLine("bye stranger");
2545  
          return;
2546  
        }
2547  
        String answer = makeAndroid_getAnswer(line, f);
2548  
        io.sendLine(answer == null ? "null" : answer);
2549  
        //appendToLog(logFile, s);
2550  
      }
2551  
    }
2552  
  
2553  
}};
2554  
}
2555  
2556  
static String makeAndroid_getAnswer(String line, StrF f) {
2557  
  String answer;
2558  
  try {
2559  
    answer = makeAndroid_fallback(line, f.get(line));
2560  
  } catch (Throwable e) {
2561  
    e = getInnerException(e);
2562  
    e.printStackTrace();
2563  
    answer = e.toString();
2564  
  }
2565  
  print("> " + answer);
2566  
  return answer;
2567  
}
2568  
2569  
static String makeAndroid_fallback(String s, String answer) {
2570  
  if (answer == null)
2571  
    answer = (String) call(getJavaX(), "answer", s); // fall back to VM android
2572  
  if (answer.indexOf('\n') >= 0 || answer.indexOf('\r') >= 0)
2573  
    answer = quote(answer);
2574  
  return answer == null ? "?" : answer;
2575  
}
2576  
 // makeAndroid / makeAndroidNoConsole
2577  
  static BufferedReader readLine_reader;
2578  
2579  
static String readLine() { try {
2580  
 
2581  
  if (readLine_reader == null)
2582  
    readLine_reader = new BufferedReader(new InputStreamReader(System.in, "UTF-8"));
2583  
  String s = readLine_reader.readLine();
2584  
  if (s != null)
2585  
    print(s);
2586  
  return s;
2587  
2588  
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} // readLine
2589  
    static void setOpt(Class c, String field, Object value) {
2590  
    try {
2591  
      Field f = setOpt_findStaticField(c, field);
2592  
      if (f == null) return;
2593  
      f.setAccessible(true);
2594  
      f.set(null, value);
2595  
    } catch (Exception e) {
2596  
      throw new RuntimeException(e);
2597  
    }
2598  
  }
2599  
  
2600  
  static Field setOpt_findStaticField(Class<?> c, String field) {
2601  
    for (Field f : c.getDeclaredFields())
2602  
      if (f.getName().equals(field) && (f.getModifiers() & Modifier.STATIC) != 0)
2603  
        return f;
2604  
    return null;
2605  
  } // setOpt
2606  
  static Object get(Object o, String field) {
2607  
  if (o instanceof Class) return get((Class) o, field);
2608  
  try {
2609  
    Field f = get_findField(o.getClass(), field);
2610  
    f.setAccessible(true);
2611  
    return f.get(o);
2612  
  } catch (Exception e) {
2613  
    throw new RuntimeException(e);
2614  
  }
2615  
}
2616  
2617  
static Object get(Class c, String field) {
2618  
  try {
2619  
    Field f = get_findStaticField(c, field);
2620  
    f.setAccessible(true);
2621  
    return f.get(null);
2622  
  } catch (Exception e) {
2623  
    throw new RuntimeException(e);
2624  
  }
2625  
}
2626  
2627  
static Field get_findStaticField(Class<?> c, String field) {
2628  
  for (Field f : c.getDeclaredFields())
2629  
    if (f.getName().equals(field) && (f.getModifiers() & Modifier.STATIC) != 0)
2630  
      return f;
2631  
  throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
2632  
}
2633  
2634  
static Field get_findField(Class<?> c, String field) {
2635  
  for (Field f : c.getDeclaredFields())
2636  
    if (f.getName().equals(field))
2637  
      return f;
2638  
  throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
2639  
} // get
2640  
  static Class getMainClass() { try {
2641  
 
2642  
  return Class.forName("main");
2643  
2644  
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} // getMainClass
2645  
2646  
static Throwable getInnerException(Throwable e) {
2647  
  while (e.getCause() != null)
2648  
    e = e.getCause();
2649  
  return e;
2650  
}
2651  
2652  
static boolean publicCommOn() {
2653  
  return "1".equals(loadTextFile(new File(userHome(), ".javax/public-communication")));
2654  
}
2655  
2656  
static List<Object> record_list = synchroList();
2657  
2658  
static void record(Object o) {
2659  
  record_list.add(o);
2660  
}
2661  
2662  
static Set<String> listFields(Class<?> c) {
2663  
  Set<String> fields = new TreeSet<String>();
2664  
  for (Field f : c.getDeclaredFields())
2665  
    fields.add(f.getName());
2666  
  return fields;
2667  
}
2668  
2669  
// try to get our current process ID
2670  
static String getPID() {
2671  
  String name = ManagementFactory.getRuntimeMXBean().getName();
2672  
  return name.replaceAll("@.*", "");
2673  
}
2674  
2675  
  static AtomicInteger dialogServer_clients = new AtomicInteger();
2676  
  
2677  
  static int startDialogServerOnPortAbove(int port, DialogHandler handler) {
2678  
    while (!startDialogServerIfPortAvailable(port, handler))
2679  
      ++port;
2680  
    return port;
2681  
  }
2682  
  
2683  
  static int startDialogServerOnPortAboveDaemon(int port, DialogHandler handler) {
2684  
    while (!startDialogServerIfPortAvailable(port, handler, true))
2685  
      ++port;
2686  
    return port;
2687  
  }
2688  
  
2689  
  static void startDialogServer(int port, DialogHandler handler) {
2690  
    if (!startDialogServerIfPortAvailable(port, handler))
2691  
      fail("Can't start dialog server on port " + port);
2692  
  }
2693  
  
2694  
  static boolean startDialogServerIfPortAvailable(int port, final DialogHandler handler) {
2695  
    return startDialogServerIfPortAvailable(port, handler, false);
2696  
  }
2697  
    
2698  
  static boolean startDialogServerIfPortAvailable(int port, final DialogHandler handler, boolean daemon) {
2699  
    ServerSocket serverSocket = null;
2700  
    try {
2701  
      serverSocket = new ServerSocket(port);
2702  
    } catch (IOException e) {
2703  
      // probably the port number is used - let's assume there already is a chat server.
2704  
      return false;
2705  
    }
2706  
    final ServerSocket _serverSocket = serverSocket;
2707  
2708  
    Thread thread = new Thread() { public void run() {
2709  
     try {
2710  
      while (true) {
2711  
        try {
2712  
          final Socket s = _serverSocket.accept();
2713  
          print("connect - clients: " + dialogServer_clients.incrementAndGet());
2714  
          Thread _t_1 = new Thread() {
2715  
public void run() {
2716  
try {
2717  
2718  
            try {
2719  
              final Writer w = new OutputStreamWriter(s.getOutputStream(), "UTF-8");
2720  
              final BufferedReader in = new BufferedReader(
2721  
                new InputStreamReader(s.getInputStream(), "UTF-8"));
2722  
              DialogIO io = new DialogIO() {
2723  
                String line;
2724  
                boolean buff;
2725  
                
2726  
                Socket getSocket() { return s; }
2727  
                
2728  
                // local means localhost - todo: test
2729  
                boolean isLocalConnection() {
2730  
                  return s.getInetAddress().isLoopbackAddress();
2731  
                }
2732  
                
2733  
                boolean isStillConnected() {
2734  
                  return !(buff || s.isClosed());
2735  
                }
2736  
                
2737  
                String readLineNoBlock() {
2738  
                  String l = line;
2739  
                  line = null;
2740  
                  return l;
2741  
                }
2742  
                
2743  
                boolean waitForLine() { try {
2744  
 
2745  
                  if (line != null) return true;
2746  
                  //print("Readline");
2747  
                  line = in.readLine();
2748  
                  //print("Readline done: " + line);
2749  
                  if (line == null) buff = true;
2750  
                  return line != null;
2751  
                
2752  
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
2753  
                
2754  
                void sendLine(String line) { try {
2755  
 
2756  
                  w.write(line + "\n");
2757  
                  w.flush();
2758  
                
2759  
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
2760  
              };
2761  
              
2762  
              try {
2763  
                handler.run(io);
2764  
              } finally {
2765  
                s.close();
2766  
              }
2767  
            } finally {
2768  
              print("client disconnect - " + dialogServer_clients.decrementAndGet() + " remaining");
2769  
            }
2770  
          } catch (Exception _e) {
2771  
  throw _e instanceof RuntimeException ? (RuntimeException) _e : new RuntimeException(_e); } }
2772  
};
2773  
_t_1.start();
2774  
        } catch (SocketTimeoutException e) {
2775  
        }
2776  
      }   
2777  
     } catch (IOException e) { throw new RuntimeException(e); }  
2778  
    }};
2779  
    if (daemon) thread.setDaemon(true);
2780  
    thread.start();
2781  
   
2782  
    print("Dialog server on port " + port + " started."); 
2783  
    return true;
2784  
  }
2785  
2786  
  static class Matches { String[] m; }
2787  
  
2788  
  static boolean match3(String pat, String s) {
2789  
    return match3(pat, s, null);
2790  
  }
2791  
  
2792  
  static boolean match3(String pat, String s, Matches matches) {
2793  
    List<String> tokpat = parse3(pat), toks = parse3(s);
2794  
    String[] m = match2(tokpat, toks);
2795  
    //print(structure(tokpat) + " on " + structure(toks) + " => " + structure(m));
2796  
    if (m == null)
2797  
      return false;
2798  
    else {
2799  
      if (matches != null) matches.m = m;
2800  
      return true;
2801  
    }
2802  
  }
2803  
  
2804  
  static List<String> parse3(String s) {
2805  
    return dropPunctuation(javaTokPlusPeriod(s));
2806  
  }
2807  
2808  
static DialogIO talkTo(String ip, int port) { try {
2809  
 
2810  
  print("Talking to " + ip + ":" + port);
2811  
  final Socket s = new Socket(ip, port);    
2812  
2813  
  final Writer w = new OutputStreamWriter(s.getOutputStream(), "UTF-8");
2814  
  final BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream(), "UTF-8"));
2815  
  return new DialogIO() {
2816  
    String line;
2817  
    boolean buff;
2818  
    
2819  
    boolean isLocalConnection() {
2820  
      return s.getInetAddress().isLoopbackAddress();
2821  
    }
2822  
    
2823  
    boolean isStillConnected() {
2824  
      return !(buff || s.isClosed());
2825  
    }
2826  
    
2827  
    String readLineNoBlock() {
2828  
      String l = line;
2829  
      line = null;
2830  
      return l;
2831  
    }
2832  
    
2833  
    boolean waitForLine() { try {
2834  
 
2835  
      if (line != null) return true;
2836  
      //print("Readline");
2837  
      line = in.readLine();
2838  
      //print("Readline done: " + line);
2839  
      if (line == null) buff = true;
2840  
      return line != null;
2841  
    
2842  
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
2843  
    
2844  
    void sendLine(String line) { try {
2845  
 
2846  
      w.write(line + "\n");
2847  
      w.flush();
2848  
    
2849  
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
2850  
    
2851  
    void close() { try {
2852  
 
2853  
      s.close();
2854  
    
2855  
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
2856  
    
2857  
    Socket getSocket() {
2858  
      return s;
2859  
    }
2860  
  };
2861  
2862  
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
2863  
2864  
// actually it's now almost the same as jsonDecode :)
2865  
static Object unstructure(String text) {
2866  
  final List<String> tok = javaTok(text);
2867  
  
2868  
  class X {
2869  
    int i = 1;
2870  
2871  
    Object parse() {
2872  
      String t = tok.get(i);
2873  
      if (t.startsWith("\"")) {
2874  
        String s = unquote(tok.get(i));
2875  
        i += 2;
2876  
        return s;
2877  
      }
2878  
      if (t.equals("{"))
2879  
        return parseMap();
2880  
      if (t.equals("["))
2881  
        return parseList();
2882  
      if (t.equals("null")) {
2883  
        i += 2; return null;
2884  
      }
2885  
      if (t.equals("false")) {
2886  
        i += 2; return false;
2887  
      }
2888  
      if (t.equals("true")) {
2889  
        i += 2; return true;
2890  
      }
2891  
      if (isInteger(t)) {
2892  
        i += 2; return Long.parseLong(t);
2893  
      }
2894  
      if (isJavaIdentifier(t)) {
2895  
        Class c = findClass(t);
2896  
        Object o = nuObject(c);
2897  
        i += 2;
2898  
        if (i < tok.size() && tok.get(i).equals("(")) {
2899  
          consume("(");
2900  
          while (!tok.get(i).equals(")")) {
2901  
            // It's like parsing a map.
2902  
            String key = unquote(tok.get(i));
2903  
            i += 2;
2904  
            consume("=");
2905  
            Object value = parse();
2906  
            set(o, key, value);
2907  
            if (tok.get(i).equals(",")) i += 2;
2908  
          }
2909  
          consume(")");
2910  
        }
2911  
        return o;
2912  
      }
2913  
      throw new RuntimeException("Unknown token " + (i+1) + ": " + t);
2914  
    }
2915  
    
2916  
    Object parseList() {
2917  
      consume("[");
2918  
      List list = new ArrayList();
2919  
      while (!tok.get(i).equals("]")) {
2920  
        list.add(parse());
2921  
        if (tok.get(i).equals(",")) i += 2;
2922  
      }
2923  
      consume("]");
2924  
      return list;
2925  
    }
2926  
    
2927  
    Object parseMap() {
2928  
      consume("{");
2929  
      Map map = new TreeMap();
2930  
      while (!tok.get(i).equals("}")) {
2931  
        String key = unquote(tok.get(i));
2932  
        i += 2;
2933  
        consume("=");
2934  
        Object value = parse();
2935  
        map.put(key, value);
2936  
        if (tok.get(i).equals(",")) i += 2;
2937  
      }
2938  
      consume("}");
2939  
      return map;
2940  
    }
2941  
    
2942  
    void consume(String s) {
2943  
      if (!tok.get(i).equals(s)) {
2944  
        String prevToken = i-2 >= 0 ? tok.get(i-2) : "";
2945  
        String nextTokens = join(tok.subList(i, Math.min(i+4, tok.size())));
2946  
        fail(quote(s) + " expected: " + prevToken + " " + nextTokens + " (" + i + "/" + tok.size() + ")");
2947  
      }
2948  
      i += 2;
2949  
    }
2950  
  }
2951  
  
2952  
  return new X().parse();
2953  
}
2954  
2955  
static Matcher matcher(String pattern, String string) {
2956  
  return Pattern.compile(pattern).matcher(string);
2957  
}
2958  
2959  
static Class __javax;
2960  
2961  
static Class getJavaX() {
2962  
  return __javax;
2963  
}
2964  
2965  
static String randomID(int length) {
2966  
  return makeRandomID(length);
2967  
}
2968  
2969  
static Object process(String processorID, Object in) {
2970  
  return process(processorID, in, "in");
2971  
}
2972  
2973  
static Object process(String processorID, Object in, String outVar) {
2974  
  try {
2975  
    Class processor = hotwire(processorID);
2976  
    set(processor, "in", in);
2977  
    call(processor, "main", new Object[] {new String[0]});
2978  
    return get(processor, outVar);
2979  
  } catch (Exception e) {
2980  
    throw new RuntimeException("Error in #" + parseSnippetID(processorID), e);
2981  
  }
2982  
}
2983  
2984  
static String _computerID;
2985  
public static String computerID() throws IOException {
2986  
  if (_computerID == null) {
2987  
    File file = new File(userHome(), ".tinybrain/computer-id");
2988  
    _computerID = loadTextFile(file.getPath(), null);
2989  
    if (_computerID == null) {
2990  
      _computerID = makeRandomID(12);
2991  
      saveTextFile(file.getPath(), _computerID);
2992  
    }
2993  
  }
2994  
  return _computerID;
2995  
}
2996  
2997  
static String structure(Object o) {
2998  
  return structure(o, 0);
2999  
}
3000  
  
3001  
static String structure(Object o, int stringSizeLimit) {
3002  
  if (o == null) return "null";
3003  
  String name = o.getClass().getName();
3004  
  
3005  
  StringBuilder buf = new StringBuilder();
3006  
  
3007  
  if (o instanceof Collection) {
3008  
    for (Object x : (Collection) o) {
3009  
      if (buf.length() != 0) buf.append(", ");
3010  
      buf.append(structure(x, stringSizeLimit));
3011  
    }
3012  
    return "[" + buf + "]";
3013  
  }
3014  
  
3015  
  if (o instanceof Map) {
3016  
    for (Object e : ((Map) o).entrySet()) {
3017  
      if (buf.length() != 0) buf.append(", ");
3018  
      buf.append(structure(((Map.Entry) e).getKey(), stringSizeLimit));
3019  
      buf.append("=");
3020  
      buf.append(structure(((Map.Entry) e).getValue(), stringSizeLimit));
3021  
    }
3022  
    return "{" + buf + "}";
3023  
  }
3024  
  
3025  
  if (o.getClass().isArray()) {
3026  
    int n = Array.getLength(o);
3027  
    for (int i = 0; i < n; i++) {
3028  
      if (buf.length() != 0) buf.append(", ");
3029  
      buf.append(structure(Array.get(o, i), stringSizeLimit));
3030  
    }
3031  
    return "{" + buf + "}";
3032  
  }
3033  
3034  
  if (o instanceof String)
3035  
    return quote(stringSizeLimit != 0 ? shorten((String) o, stringSizeLimit) : (String) o);
3036  
  
3037  
  // Need more cases? This should cover all library classes...
3038  
  if (name.startsWith("java.") || name.startsWith("javax."))
3039  
    return String.valueOf(o);
3040  
    
3041  
  String shortName = o.getClass().getName().replaceAll("^main\\$", "");
3042  
3043  
  // TODO: go to superclasses too
3044  
  Field[] fields = o.getClass().getDeclaredFields();
3045  
  int numFields = 0;
3046  
  String fieldName = "";
3047  
  for (Field field : fields) {
3048  
    if ((field.getModifiers() & Modifier.STATIC) != 0)
3049  
      continue;
3050  
    Object value;
3051  
    try {
3052  
      value = field.get(o);
3053  
    } catch (Exception e) {
3054  
      value = "?";
3055  
    }
3056  
    
3057  
    fieldName = field.getName();
3058  
    
3059  
    // put special cases here...
3060  
3061  
    if (value != null) {
3062  
      if (buf.length() != 0) buf.append(", ");
3063  
      buf.append(fieldName + "=" + structure(value, stringSizeLimit));
3064  
    }
3065  
    ++numFields;
3066  
  }
3067  
  String b = buf.toString();
3068  
  if (numFields == 1)
3069  
    b = b.replaceAll("^" + fieldName + "=", ""); // drop field name if only one
3070  
  String s = shortName;
3071  
  if (buf.length() != 0)
3072  
    s += "(" + b + ")";
3073  
  return s;
3074  
}
3075  
3076  
static boolean isJavaIdentifier(String s) {
3077  
  if (s.length() == 0 || !Character.isJavaIdentifierStart(s.charAt(0)))
3078  
    return false;
3079  
  for (int i = 1; i < s.length(); i++)
3080  
    if (!Character.isJavaIdentifierPart(s.charAt(i)))
3081  
      return false;
3082  
  return true;
3083  
}
3084  
3085  
// currently finds only inner classes of class "main"
3086  
// returns null on not found
3087  
// this is the simple version that is not case-tolerant
3088  
static Class findClass(String name) {
3089  
  try {
3090  
    return Class.forName("main$" + name);
3091  
  } catch (ClassNotFoundException e) {
3092  
    return null;
3093  
  }
3094  
}
3095  
3096  
static Object nuObject(Class c, Object... args) { try {
3097  
 
3098  
  Constructor m = nuObject_findConstructor(c, args);
3099  
  m.setAccessible(true);
3100  
  return m.newInstance(args);
3101  
3102  
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
3103  
3104  
static Constructor nuObject_findConstructor(Class c, Object... args) {
3105  
  for (Constructor m : c.getDeclaredConstructors()) {
3106  
    if (!nuObject_checkArgs(m.getParameterTypes(), args, false))
3107  
      continue;
3108  
    return m;
3109  
  }
3110  
  throw new RuntimeException("Constructor with " + args.length + " matching parameter(s) not found in " + c.getName());
3111  
}
3112  
3113  
 static boolean nuObject_checkArgs(Class[] types, Object[] args, boolean debug) {
3114  
    if (types.length != args.length) {
3115  
      if (debug)
3116  
        System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
3117  
      return false;
3118  
    }
3119  
    for (int i = 0; i < types.length; i++)
3120  
      if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
3121  
        if (debug)
3122  
          System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
3123  
        return false;
3124  
      }
3125  
    return true;
3126  
  }
3127  
3128  
static <A> List<A> synchroList() {
3129  
  return Collections.synchronizedList(new ArrayList<A>());
3130  
}
3131  
3132  
static <A> List<A> synchroList(List<A> l) {
3133  
  return Collections.synchronizedList(l);
3134  
}
3135  
3136  
3137  
static List<String> dropPunctuation(List<String> tok) {
3138  
  tok = new ArrayList<String>(tok);
3139  
  for (int i = 1; i < tok.size(); i += 2) {
3140  
    String t = tok.get(i);
3141  
    if (t.length() == 1 && !Character.isLetter(t.charAt(0)) && !Character.isDigit(t.charAt(0)) && !t.equals("*")) {
3142  
      tok.set(i-1, tok.get(i-1) + tok.get(i+1));
3143  
      tok.remove(i);
3144  
      tok.remove(i);
3145  
      i -= 2;
3146  
    }
3147  
  }
3148  
  return tok;
3149  
}
3150  
3151  
// match2 matches multiple "*" (matches a single token) wildcards and zero or one "..." wildcards (matches multiple tokens)
3152  
3153  
static String[] match2(List<String> pat, List<String> tok) {
3154  
  // standard case (no ...)
3155  
  int i = pat.indexOf("...");
3156  
  if (i < 0) return match2_match(pat, tok);
3157  
  
3158  
  
3159  
  pat = new ArrayList<String>(pat); // We're modifying it, so copy first
3160  
  pat.set(i, "*");
3161  
  int expand = 0;
3162  
  while (pat.size() < tok.size()) {
3163  
    ++expand;
3164  
    pat.add(i, "*");
3165  
    pat.add(i+1, ""); // doesn't matter
3166  
  }
3167  
  
3168  
  return match2_match(pat, tok);
3169  
}
3170  
3171  
static String[] match2_match(List<String> pat, List<String> tok) {
3172  
  List<String> result = new ArrayList<String>();
3173  
  if (pat.size() != tok.size()) {
3174  
    /*if (debug)
3175  
      print("Size mismatch: " + structure(pat) + " vs " + structure(tok));*/
3176  
    return null;
3177  
  }
3178  
  for (int i = 1; i < pat.size(); i += 2) {
3179  
    String p = pat.get(i), t = tok.get(i);
3180  
    /*if (debug)
3181  
      print("Checking " + p + " against " + t);*/
3182  
    if ("*".equals(p))
3183  
      result.add(t);
3184  
    else if (!p.equalsIgnoreCase(t))
3185  
      return null;
3186  
  }
3187  
  return result.toArray(new String[result.size()]);
3188  
}
3189  
3190  
3191  
// javaTok extended with "..." token.
3192  
3193  
static List<String> javaTokPlusPeriod(String s) {
3194  
  List<String> tok = new ArrayList<String>();
3195  
  int l = s.length();
3196  
  
3197  
  int i = 0;
3198  
  while (i < l) {
3199  
    int j = i;
3200  
    char c; String cc;
3201  
    
3202  
    // scan for whitespace
3203  
    while (j < l) {
3204  
      c = s.charAt(j);
3205  
      cc = s.substring(j, Math.min(j+2, l));
3206  
      if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
3207  
        ++j;
3208  
      else if (cc.equals("/*")) {
3209  
        do ++j; while (j < l && !s.substring(j, Math.min(j+2, l)).equals("*/"));
3210  
        j = Math.min(j+2, l);
3211  
      } else if (cc.equals("//")) {
3212  
        do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
3213  
      } else
3214  
        break;
3215  
    }
3216  
    
3217  
    tok.add(s.substring(i, j));
3218  
    i = j;
3219  
    if (i >= l) break;
3220  
    c = s.charAt(i); // cc is not needed in rest of loop body
3221  
    cc = s.substring(i, Math.min(i+2, l));
3222  
3223  
    // scan for non-whitespace
3224  
    if (c == '\'' || c == '"') {
3225  
      char opener = c;
3226  
      ++j;
3227  
      while (j < l) {
3228  
        if (s.charAt(j) == opener) {
3229  
          ++j;
3230  
          break;
3231  
        } else if (s.charAt(j) == '\\' && j+1 < l)
3232  
          j += 2;
3233  
        else
3234  
          ++j;
3235  
      }
3236  
    } else if (Character.isJavaIdentifierStart(c))
3237  
      do ++j; while (j < l && Character.isJavaIdentifierPart(s.charAt(j)));
3238  
    else if (Character.isDigit(c))
3239  
      do ++j; while (j < l && Character.isDigit(s.charAt(j)));
3240  
    else if (cc.equals("[[")) {
3241  
      do ++j; while (j+1 < l && !s.substring(j, j+2).equals("]]"));
3242  
      j = Math.min(j+2, l);
3243  
    } else if (s.substring(j, Math.min(j+3, l)).equals("..."))
3244  
      j += 3;
3245  
    else
3246  
      ++j;
3247  
3248  
    tok.add(s.substring(i, j));
3249  
    i = j;
3250  
  }
3251  
  
3252  
  if ((tok.size() % 2) == 0) tok.add("");
3253  
  return tok;
3254  
}
3255  
3256  
3257  
// replacement for class JavaTok
3258  
// maybe incomplete, might want to add floating point numbers
3259  
// todo also: extended multi-line strings
3260  
3261  
static List<String> javaTok(String s) {
3262  
  List<String> tok = new ArrayList<String>();
3263  
  int l = s.length();
3264  
  
3265  
  int i = 0;
3266  
  while (i < l) {
3267  
    int j = i;
3268  
    char c; String cc;
3269  
    
3270  
    // scan for whitespace
3271  
    while (j < l) {
3272  
      c = s.charAt(j);
3273  
      cc = s.substring(j, Math.min(j+2, l));
3274  
      if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
3275  
        ++j;
3276  
      else if (cc.equals("/*")) {
3277  
        do ++j; while (j < l && !s.substring(j, Math.min(j+2, l)).equals("*/"));
3278  
        j = Math.min(j+2, l);
3279  
      } else if (cc.equals("//")) {
3280  
        do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
3281  
      } else
3282  
        break;
3283  
    }
3284  
    
3285  
    tok.add(s.substring(i, j));
3286  
    i = j;
3287  
    if (i >= l) break;
3288  
    c = s.charAt(i); // cc is not needed in rest of loop body
3289  
    cc = s.substring(i, Math.min(i+2, l));
3290  
3291  
    // scan for non-whitespace
3292  
    if (c == '\'' || c == '"') {
3293  
      char opener = c;
3294  
      ++j;
3295  
      while (j < l) {
3296  
        if (s.charAt(j) == opener) {
3297  
          ++j;
3298  
          break;
3299  
        } else if (s.charAt(j) == '\\' && j+1 < l)
3300  
          j += 2;
3301  
        else
3302  
          ++j;
3303  
      }
3304  
    } else if (Character.isJavaIdentifierStart(c))
3305  
      do ++j; while (j < l && Character.isJavaIdentifierPart(s.charAt(j)));
3306  
    else if (Character.isDigit(c))
3307  
      do ++j; while (j < l && Character.isDigit(s.charAt(j)));
3308  
    else if (cc.equals("[[")) {
3309  
      do ++j; while (j+1 < l && !s.substring(j, j+2).equals("]]"));
3310  
      j = Math.min(j+2, l);
3311  
    } else
3312  
      ++j;
3313  
3314  
    tok.add(s.substring(i, j));
3315  
    i = j;
3316  
  }
3317  
  
3318  
  if ((tok.size() % 2) == 0) tok.add("");
3319  
  return tok;
3320  
}
3321  
3322  
3323  
  public static String unquote(String s) {
3324  
    if (s.startsWith("[")) {
3325  
      int i = 1;
3326  
      while (i < s.length() && s.charAt(i) == '=') ++i;
3327  
      if (i < s.length() && s.charAt(i) == '[') {
3328  
        String m = s.substring(1, i);
3329  
        if (s.endsWith("]" + m + "]"))
3330  
          return s.substring(i+1, s.length()-i-1);
3331  
      }
3332  
    }
3333  
    
3334  
    if (s.startsWith("\"") && s.endsWith("\"") && s.length() > 1) {
3335  
      String st = s.substring(1, s.length()-1);
3336  
      StringBuilder sb = new StringBuilder(st.length());
3337  
  
3338  
      for (int i = 0; i < st.length(); i++) {
3339  
        char ch = st.charAt(i);
3340  
        if (ch == '\\') {
3341  
          char nextChar = (i == st.length() - 1) ? '\\' : st
3342  
                  .charAt(i + 1);
3343  
          // Octal escape?
3344  
          if (nextChar >= '0' && nextChar <= '7') {
3345  
              String code = "" + nextChar;
3346  
              i++;
3347  
              if ((i < st.length() - 1) && st.charAt(i + 1) >= '0'
3348  
                      && st.charAt(i + 1) <= '7') {
3349  
                  code += st.charAt(i + 1);
3350  
                  i++;
3351  
                  if ((i < st.length() - 1) && st.charAt(i + 1) >= '0'
3352  
                          && st.charAt(i + 1) <= '7') {
3353  
                      code += st.charAt(i + 1);
3354  
                      i++;
3355  
                  }
3356  
              }
3357  
              sb.append((char) Integer.parseInt(code, 8));
3358  
              continue;
3359  
          }
3360  
          switch (nextChar) {
3361  
          case '\\':
3362  
              ch = '\\';
3363  
              break;
3364  
          case 'b':
3365  
              ch = '\b';
3366  
              break;
3367  
          case 'f':
3368  
              ch = '\f';
3369  
              break;
3370  
          case 'n':
3371  
              ch = '\n';
3372  
              break;
3373  
          case 'r':
3374  
              ch = '\r';
3375  
              break;
3376  
          case 't':
3377  
              ch = '\t';
3378  
              break;
3379  
          case '\"':
3380  
              ch = '\"';
3381  
              break;
3382  
          case '\'':
3383  
              ch = '\'';
3384  
              break;
3385  
          // Hex Unicode: u????
3386  
          case 'u':
3387  
              if (i >= st.length() - 5) {
3388  
                  ch = 'u';
3389  
                  break;
3390  
              }
3391  
              int code = Integer.parseInt(
3392  
                      "" + st.charAt(i + 2) + st.charAt(i + 3)
3393  
                              + st.charAt(i + 4) + st.charAt(i + 5), 16);
3394  
              sb.append(Character.toChars(code));
3395  
              i += 5;
3396  
              continue;
3397  
          }
3398  
          i++;
3399  
        }
3400  
        sb.append(ch);
3401  
      }
3402  
      return sb.toString();      
3403  
    } else
3404  
      return s; // return original
3405  
  }
3406  
3407  
  // compile JavaX source, load classes & return main class
3408  
  // src can be a snippet ID or actual source code
3409  
  
3410  
  static Class<?> hotwire(String src) {
3411  
    try {
3412  
      Class j = getJavaX();
3413  
3414  
      List<File> libraries = new ArrayList<File>();
3415  
      File srcDir = (File) call(j, "transpileMain", src, libraries);
3416  
      
3417  
      Object androidContext = get(j, "androidContext");
3418  
      if (androidContext != null)
3419  
        return (Class) call(j, "loadx2android", srcDir, src);
3420  
        
3421  
      File classesDir = (File) call(j, "TempDirMaker_make");
3422  
      String javacOutput = (String) call(j, "compileJava", srcDir, libraries, classesDir);
3423  
      System.out.println(javacOutput);
3424  
      
3425  
      URL[] urls = new URL[libraries.size()+1];
3426  
      urls[0] = classesDir.toURI().toURL();
3427  
      for (int i = 0; i < libraries.size(); i++)
3428  
        urls[i+1] = libraries.get(i).toURI().toURL();
3429  
3430  
      // make class loader
3431  
      URLClassLoader classLoader = new URLClassLoader(urls);
3432  
  
3433  
      // load & return main class
3434  
      Class<?> theClass = classLoader.loadClass("main");
3435  
      
3436  
      call(j, "setVars", theClass, isSnippetID(src) ? src: null);
3437  
3438  
      return theClass;
3439  
    } catch (Exception e) {
3440  
      throw e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e);
3441  
    }
3442  
  }
3443  
3444  
  static RuntimeException fail() {
3445  
    throw new RuntimeException("fail");
3446  
  }
3447  
  
3448  
  static RuntimeException fail(String msg) {
3449  
    throw new RuntimeException(msg);
3450  
  }
3451  
3452  
static String shorten(String s, int max) {
3453  
  return s.length() <= max ? s : s.substring(0, Math.min(s.length(), max)) + "...";
3454  
}
3455  
}
3456  
interface StrF {
3457  
  String get(String s);
3458  
}

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: #1002665
Snippet name: Default boot-up code for JavaX/Android 26 (testing, with x27) BACKUP
Eternal ID of this version: #1002665/1
Text MD5: 8a001b93d1e12357e261faacd0dad6c3
Author: stefan
Category: javax
Type: JavaX source code (Android)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2016-02-11 00:15:23
Source code size: 114733 bytes / 3458 lines
Pitched / IR pitched: No / No
Views / Downloads: 973 / 852
Referenced in: [show references]