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

1426
LINES

< > BotCompany Repo | #1000420 // JavaX 18 Android running 1000419 (ImageView test)

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

1  
import java.security.NoSuchAlgorithmException;
2  
import java.security.MessageDigest;
3  
import java.lang.reflect.*;
4  
import java.net.*;
5  
import javax.swing.*;
6  
import java.util.regex.*;
7  
import java.util.*;
8  
9  
import android.widget.*;
10  
import android.view.*;
11  
import android.content.Context;
12  
import android.app.Activity;
13  
import java.util.Timer;
14  
import java.util.TimerTask;
15  
import java.io.*;
16  
17  
public class main {
18  
  static class Lg {
19  
    Activity context;
20  
    ScrollView sv;
21  
    TextView tv;
22  
    StringBuilder buf = new StringBuilder();
23  
    
24  
    Lg(Activity context) {
25  
      this.context = context;
26  
      sv = new ScrollView(context);
27  
      tv = new TextView(context);
28  
      tv.setText(buf.toString());
29  
      sv.addView(tv);
30  
    }
31  
    
32  
    View getView() {
33  
      return sv;
34  
    }
35  
    
36  
    void print(final String s) {
37  
      context.runOnUiThread(new Runnable() {
38  
        public void run() {
39  
          buf.append(s);
40  
          tv.setText(buf.toString());
41  
        }
42  
      });
43  
    }
44  
    
45  
    void println(String s) {
46  
      print(s + "\n");
47  
    }
48  
  }
49  
  
50  
  static Lg lg;
51  
  
52  
  public static View main(final Activity context) {
53  
    lg = new Lg(context);
54  
    
55  
    OutputStream outputStream = new OutputStream() {
56  
      public void write(int b) {
57  
        try {
58  
          lg.print(new String(new byte[] {(byte) b}, "UTF-8")); // This is crap
59  
        } catch (UnsupportedEncodingException e) {}
60  
      }
61  
      
62  
      @Override
63  
      public void write(byte[] b, int off, int len) {
64  
        try {
65  
          lg.print(new String(b, off, len, "UTF-8")); // This is crap
66  
        } catch (UnsupportedEncodingException e) {}
67  
      }
68  
    };
69  
    
70  
    PrintStream ps = new PrintStream(outputStream, true);
71  
    System.setOut(ps);
72  
    System.setErr(ps);
73  
    
74  
    new Thread() {
75  
      public void run() {
76  
        try {
77  
          _x18.androidContext = context;
78  
          //_x18.showSystemProperties();
79  
          String mainSnippet = "1000419";
80  
          _x18.main(new String[] {mainSnippet});
81  
        } catch (Throwable e) {
82  
          e.printStackTrace();
83  
        }
84  
      }
85  
    }.start();
86  
    
87  
    return lg.getView();
88  
  }
89  
}
90  
91  
/**
92  
 JavaX runner version 18
93  
94  
 Changes to v17:
95  
 -can run server-transpiled main programs for super-quick compilation
96  
  (no local transpiling except for nested solvers or something)
97  
 -making Android-aware (FileInputStream/FileOutputStream/other file stuff?)
98  
99  
 */
100  
101  
class _x18 {
102  
  static final String version = "JavaX 18";
103  
104  
  static boolean verbose = false, translate = false, list = false, virtualizeTranslators = true;
105  
  static String translateTo = null;
106  
  static boolean preferCached = false, safeOnly = false, noID = false, noPrefetch = false;
107  
  static List<String[]> mainTranslators = new ArrayList<String[]>();
108  
  private static Map<Long, String> memSnippetCache = new HashMap<Long, String>();
109  
  private static int processesStarted, compilations;
110  
111  
  // snippet ID -> md5
112  
  private static HashMap<Long, String> prefetched = new HashMap<Long, String>();
113  
  private static File virtCache;
114  
115  
  // doesn't work yet
116  
  private static Map<String, Class<?>> programCache = new HashMap<String, Class<?>>();
117  
  static boolean cacheTranslators = false;
118  
119  
  // this should work (caches transpiled translators)
120  
  private static HashMap<Long, Object[]> translationCache = new HashMap<Long, Object[]>();
121  
  static boolean cacheTranspiledTranslators = true;
122  
123  
  // which snippets are available pre-transpiled server-side?
124  
  private static Set<Long> hasTranspiledSet = new HashSet<Long>();
125  
  static boolean useServerTranspiled = true;
126  
127  
  static Object androidContext;
128  
  static boolean android = isAndroid();
129  
130  
  public static void main(String[] args) throws Exception {
131  
    File ioBaseDir = new File("."), inputDir = null, outputDir = null;
132  
    String src = null;
133  
    List<String> programArgs = new ArrayList<String>();
134  
135  
    for (int i = 0; i < args.length; i++) {
136  
      String arg = args[i];
137  
      
138  
      if (arg.equals("-version")) {
139  
        showVersion();
140  
        return;
141  
      }
142  
143  
      if (arg.equals("-sysprop")) {
144  
        showSystemProperties();
145  
        return;
146  
      }
147  
148  
      if (arg.equals("-v") || arg.equals("-verbose"))
149  
        verbose = true;
150  
      else if (arg.equals("-finderror"))
151  
        verbose = true;
152  
      else if (arg.equals("-offline") || arg.equalsIgnoreCase("-prefercached"))
153  
        preferCached = true;
154  
      else if (arg.equals("-novirt"))
155  
        virtualizeTranslators = false;
156  
      else if (arg.equals("-safeonly"))
157  
        safeOnly = true;
158  
      else if (arg.equals("-noid"))
159  
        noID = true;
160  
      else if (arg.equals("-nocachetranspiled"))
161  
        cacheTranspiledTranslators = false;
162  
      else if (arg.equals("-localtranspile"))
163  
        useServerTranspiled = false;
164  
      else if (arg.equals("translate"))
165  
        translate = true;
166  
      else if (arg.equals("list")) {
167  
        list = true;
168  
        virtualizeTranslators = false; // so they are silenced
169  
      } else if (arg.equals("run")) {
170  
        // it's the default command anyway
171  
      } else if (arg.startsWith("input="))
172  
        inputDir = new File(arg.substring(6));
173  
      else if (arg.startsWith("output="))
174  
        outputDir = new File(arg.substring(7));
175  
      else if (arg.equals("with"))
176  
        mainTranslators.add(new String[] {args[++i], null});
177  
      else if (translate && arg.equals("to"))
178  
        translateTo = args[++i];
179  
      else if (src == null) {
180  
        //System.out.println("src=" + arg);
181  
        src = arg;
182  
      } else
183  
        programArgs.add(arg);
184  
    }
185  
186  
    cleanCache();
187  
188  
    if (useServerTranspiled)
189  
      noPrefetch = true;
190  
191  
    if (src == null) src = ".";
192  
193  
    // Might actually want to write to 2 disk caches (global/per program).
194  
    if (virtualizeTranslators && !preferCached)
195  
      virtCache = TempDirMaker_make();
196  
197  
    if (inputDir != null) {
198  
      ioBaseDir = TempDirMaker_make();
199  
      System.out.println("Taking input from: " + inputDir.getAbsolutePath());
200  
      System.out.println("Output is in: " + new File(ioBaseDir, "output").getAbsolutePath());
201  
      copyInput(inputDir, new File(ioBaseDir, "input"));
202  
    }
203  
204  
    javaxmain(src, ioBaseDir, translate, list, programArgs.toArray(new String[programArgs.size()]));
205  
206  
    if (outputDir != null) {
207  
      copyInput(new File(ioBaseDir, "output"), outputDir);
208  
      System.out.println("Output copied to: " + outputDir.getAbsolutePath());
209  
    }
210  
211  
    if (verbose) {
212  
      // print stats
213  
      System.out.println("Processes started: " + processesStarted + ", compilations: " + compilations);
214  
    }
215  
  }
216  
217  
  public static void javaxmain(String src, File ioDir, boolean translate, boolean list,
218  
                               String[] args) throws Exception {
219  
    List<File> libraries = new ArrayList<File>();
220  
    File X = transpileMain(src, libraries);
221  
    if (X == null)
222  
       return;
223  
224  
    // list or run
225  
226  
    if (translate) {
227  
      File to = X;
228  
      if (translateTo != null)
229  
        if (new File(translateTo).isDirectory())
230  
          to = new File(translateTo, "main.java");
231  
        else
232  
          to = new File(translateTo);
233  
      if (to != X)
234  
        copy(new File(X, "main.java"), to);
235  
      System.out.println("Program translated to: " + to.getAbsolutePath());
236  
    } else if (list)
237  
      System.out.println(loadTextFile(new File(X, "main.java").getPath(), null));
238  
    else
239  
      javax2(X, ioDir, false, false, libraries, args, null);
240  
  }
241  
242  
  static File transpileMain(String src, List<File> libraries) throws Exception {
243  
    File srcDir;
244  
    boolean isTranspiled = false;
245  
    if (isSnippetID(src)) {
246  
      prefetch(src);
247  
      long id = parseSnippetID(src);
248  
      srcDir = loadSnippetAsMainJava(src);
249  
      if (hasTranspiledSet.contains(id)) {
250  
        System.err.println("Trying pretranspiled main program: #" + id);
251  
        String transpiledSrc = getServerTranspiled("#" + id);
252  
        if (!transpiledSrc.isEmpty()) {
253  
          srcDir = TempDirMaker_make();
254  
          saveTextFile(new File(srcDir, "main.java").getPath(), transpiledSrc);
255  
          isTranspiled = true;
256  
          //translationCache.put(id, new Object[] {srcDir, libraries});
257  
        }
258  
      }
259  
    } else {
260  
      srcDir = new File(src);
261  
262  
      // if the argument is a file, it is assumed to be main.java
263  
      if (srcDir.isFile()) {
264  
        srcDir = TempDirMaker_make();
265  
        copy(new File(src), new File(srcDir, "main.java"));
266  
      }
267  
268  
      if (!new File(srcDir, "main.java").exists()) {
269  
        showVersion();
270  
        System.out.println("No main.java found, exiting");
271  
        return null;
272  
      }
273  
    }
274  
275  
    // translate
276  
277  
    File X = srcDir;
278  
279  
    if (!isTranspiled) {
280  
      X = topLevelTranslate(X, libraries);
281  
      System.err.println("Translated " + src);
282  
283  
      // save prefetch data
284  
      if (isSnippetID(src))
285  
        savePrefetchData(src);
286  
    }
287  
    return X;
288  
  }
289  
290  
  private static void prefetch(String mainSnippetID) throws IOException {
291  
    if (noPrefetch) return;
292  
293  
    long mainID = parseSnippetID(mainSnippetID);
294  
    String s = mainID + " " + loadTextFile(new File(userHome(), ".tinybrain/prefetch/" + mainID + ".txt").getPath(), "");
295  
    String[] ids = s.trim().split(" ");
296  
    if (ids.length > 1) {
297  
      String url = "http://tinybrain.de:8080/tb-int/prefetch.php?ids=" + URLEncoder.encode(s, "UTF-8");
298  
      String data = loadPage(new URL(url));
299  
      String[] split = data.split(" ");
300  
      if (split.length == ids.length)
301  
        for (int i = 0; i < ids.length; i++)
302  
          prefetched.put(parseSnippetID(ids[i]), split[i]);
303  
    }
304  
  }
305  
306  
  private static String userHome() {
307  
    if (android)
308  
      return ((File) call(androidContext, "getFilesDir")).getAbsolutePath();
309  
    else
310  
      return System.getProperty("user.home");
311  
  }
312  
313  
  private static void savePrefetchData(String mainSnippetID) throws IOException {
314  
    List<String> ids = new ArrayList<String>();
315  
    long mainID = parseSnippetID(mainSnippetID);
316  
317  
    for (long id : memSnippetCache.keySet())
318  
      if (id != mainID)
319  
        ids.add(String.valueOf(id));
320  
321  
    saveTextFile(new File(userHome(),".tinybrain/prefetch/" + mainID + ".txt").getPath(), join(" ", ids));
322  
  }
323  
324  
  static File topLevelTranslate(File srcDir, List<File> libraries_out) throws Exception {
325  
    File X = srcDir;
326  
    X = applyTranslators(X, mainTranslators, libraries_out); // translators supplied on command line (unusual)
327  
328  
    // actual inner translation of the JavaX source
329  
    X = defaultTranslate(X, libraries_out);
330  
    return X;
331  
  }
332  
333  
  private static File defaultTranslate(File x, List<File> libraries_out) throws Exception {
334  
    x = luaPrintToJavaPrint(x);
335  
    x = repeatAutoTranslate(x, libraries_out);
336  
    return x;
337  
  }
338  
339  
  private static File repeatAutoTranslate(File x, List<File> libraries_out) throws Exception {
340  
    while (true) {
341  
      File y = autoTranslate(x, libraries_out);
342  
      if (y == x)
343  
        return x;
344  
      x = y;
345  
    }
346  
  }
347  
348  
  private static File autoTranslate(File x, List<File> libraries_out) throws Exception {
349  
    String main = loadTextFile(new File(x, "main.java").getPath(), null);
350  
    List<String> lines = toLines(main);
351  
    List<String[]> translators = findTranslators(lines);
352  
    if (translators.isEmpty())
353  
      return x;
354  
355  
    main = fromLines(lines);
356  
    File newDir = TempDirMaker_make();
357  
    saveTextFile(new File(newDir, "main.java").getPath(), main);
358  
    return applyTranslators(newDir, translators, libraries_out);
359  
  }
360  
361  
  private static List<String[]> findTranslators(List<String> lines) {
362  
    List<String[]> translators = new ArrayList<String[]>();
363  
    Pattern pattern = Pattern.compile("^!([0-9# \t]+)");
364  
    Pattern pArgs = Pattern.compile("^\\s*\\((.*)\\)");
365  
    for (ListIterator<String> iterator = lines.listIterator(); iterator.hasNext(); ) {
366  
      String line = iterator.next();
367  
      line = line.trim();
368  
      Matcher matcher = pattern.matcher(line);
369  
      if (matcher.find()) {
370  
        String[] t = matcher.group(1).split("[ \t]+");
371  
        String rest = line.substring(matcher.end());
372  
        String arg = null;
373  
        if (t.length == 1) {
374  
          Matcher mArgs = pArgs.matcher(rest);
375  
          if (mArgs.find())
376  
            arg = mArgs.group(1);
377  
        }
378  
        for (String transi : t)
379  
          translators.add(new String[]{transi, arg});
380  
        iterator.remove();
381  
      }
382  
    }
383  
    return translators;
384  
  }
385  
386  
  public static List<String> toLines(String s) {
387  
    List<String> lines = new ArrayList<String>();
388  
    int start = 0;
389  
    while (true) {
390  
      int i = toLines_nextLineBreak(s, start);
391  
      if (i < 0) {
392  
        if (s.length() > start) lines.add(s.substring(start));
393  
        break;
394  
      }
395  
396  
      lines.add(s.substring(start, i));
397  
      if (s.charAt(i) == '\r' && i+1 < s.length() && s.charAt(i+1) == '\n')
398  
        i += 2;
399  
      else
400  
        ++i;
401  
402  
      start = i;
403  
    }
404  
    return lines;
405  
  }
406  
407  
  private static int toLines_nextLineBreak(String s, int start) {
408  
    for (int i = start; i < s.length(); i++) {
409  
      char c = s.charAt(i);
410  
      if (c == '\r' || c == '\n')
411  
        return i;
412  
    }
413  
    return -1;
414  
  }
415  
416  
  public static String fromLines(List<String> lines) {
417  
    StringBuilder buf = new StringBuilder();
418  
    for (String line : lines) {
419  
      buf.append(line).append('\n');
420  
    }
421  
    return buf.toString();
422  
  }
423  
424  
  private static File applyTranslators(File x, List<String[]> translators, List<File> libraries_out) throws Exception {
425  
    for (String[] translator : translators)
426  
      x = applyTranslator(x, translator[0], translator[1], libraries_out);
427  
    return x;
428  
  }
429  
430  
  // also takes a library
431  
  private static File applyTranslator(File x, String translator, String arg, List<File> libraries_out) throws Exception {
432  
    if (verbose)
433  
      System.out.println("Using translator " + translator + " on sources in " + x.getPath());
434  
435  
    File newDir = runTranslatorOnInput(translator, null, arg, x, !verbose, libraries_out);
436  
437  
    if (!new File(newDir, "main.java").exists()) {
438  
      throw new Exception("Translator " + translator + " did not generate main.java");
439  
      // TODO: show translator output
440  
    }
441  
    if (verbose)
442  
      System.out.println("Translated with " + translator + " from " + x.getPath() + " to " + newDir.getPath());
443  
    x = newDir;
444  
    return x;
445  
  }
446  
447  
  private static File luaPrintToJavaPrint(File x) throws IOException {
448  
    File newDir = TempDirMaker_make();
449  
    String code = loadTextFile(new File(x, "main.java").getPath(), null);
450  
    code = luaPrintToJavaPrint(code);
451  
    if (verbose)
452  
      System.out.println(code);
453  
    saveTextFile(new File(newDir, "main.java").getPath(), code);
454  
    return newDir;
455  
  }
456  
457  
  public static String luaPrintToJavaPrint(String code) {
458  
    return ("\n" + code).replaceAll(
459  
      "(\n\\s*)print (\".*\")",
460  
      "$1System.out.println($2);").substring(1);
461  
  }
462  
463  
  public static File loadSnippetAsMainJava(String snippetID) throws IOException {
464  
    checkProgramSafety(snippetID);
465  
    File srcDir = TempDirMaker_make();
466  
    saveTextFile(new File(srcDir, "main.java").getPath(), loadSnippet(snippetID));
467  
    return srcDir;
468  
  }
469  
470  
  public static File loadSnippetAsMainJavaVerified(String snippetID, String hash) throws IOException {
471  
    checkProgramSafety(snippetID);
472  
    File srcDir = TempDirMaker_make();
473  
    saveTextFile(new File(srcDir, "main.java").getPath(), loadSnippetVerified(snippetID, hash));
474  
    return srcDir;
475  
  }
476  
477  
  /** returns output dir */
478  
  private static File runTranslatorOnInput(String snippetID, String hash, String arg, File input,
479  
                                           boolean silent,
480  
                                           List<File> libraries_out) throws Exception {
481  
    long id = parseSnippetID(snippetID);
482  
    File libraryFile = DiskSnippetCache_getLibrary(id);
483  
    if (libraryFile != null) {
484  
      loadLibrary(snippetID, libraries_out, libraryFile);
485  
      return input;
486  
    }
487  
488  
    String[] args = arg != null ? new String[]{arg} : new String[0];
489  
490  
    File srcDir = hash == null ? loadSnippetAsMainJava(snippetID)
491  
      : loadSnippetAsMainJavaVerified(snippetID, hash);
492  
    long mainJavaSize = new File(srcDir, "main.java").length();
493  
494  
    if (mainJavaSize == 0) { // no text in snippet? assume it's a library
495  
      loadLibrary(snippetID, libraries_out, libraryFile);
496  
      return input;
497  
    }
498  
499  
    List<File> libraries = new ArrayList<File>();
500  
    Object[] cached = translationCache.get(id);
501  
    if (cached != null) {
502  
      //System.err.println("Taking translator " + snippetID + " from cache!");
503  
      srcDir = (File) cached[0];
504  
      libraries = (List<File>) cached[1];
505  
    } else if (hasTranspiledSet.contains(id)) {
506  
      System.err.println("Trying pretranspiled translator: #" + snippetID);
507  
      String transpiledSrc = getServerTranspiled(snippetID);
508  
      if (!transpiledSrc.isEmpty()) {
509  
        srcDir = TempDirMaker_make();
510  
        saveTextFile(new File(srcDir, "main.java").getPath(), transpiledSrc);
511  
        translationCache.put(id, cached = new Object[] {srcDir, libraries});
512  
      }
513  
    }
514  
515  
    File ioBaseDir = TempDirMaker_make();
516  
517  
    /*Class<?> mainClass = programCache.get("" + parseSnippetID(snippetID));
518  
    if (mainClass != null)
519  
      return runCached(ioBaseDir, input, args);*/
520  
    // Doesn't work yet because virtualized directories are hardcoded in translator...
521  
522  
    if (cached == null) {
523  
      System.err.println("Translating translator #" + id);
524  
      srcDir = defaultTranslate(srcDir, libraries);
525  
      System.err.println("Translated translator #" + id);
526  
      if (cacheTranspiledTranslators)
527  
        translationCache.put(id, new Object[]{srcDir, libraries});
528  
    }
529  
530  
    boolean runInProcess = false;
531  
532  
    if (virtualizeTranslators) {
533  
      if (verbose) System.out.println("Virtualizing translator");
534  
535  
      //srcDir = applyTranslator(srcDir, "#2000351"); // I/O-virtualize the translator
536  
      // that doesn't work because it recurses infinitely...
537  
538  
      // So we do it right here:
539  
      String s = loadTextFile(new File(srcDir, "main.java").getPath(), null);
540  
      s = s.replaceAll("new\\s+File\\(", "virtual.newFile(");
541  
      s = s.replaceAll("new\\s+FileInputStream\\(", "virtual.newFileInputStream(");
542  
      s = s.replaceAll("new\\s+FileOutputStream\\(", "virtual.newFileOutputStream(");
543  
      s += "\n\n" + loadSnippet("#2000355"); // load class virtual
544  
545  
      // change baseDir
546  
      s = s.replace("virtual_baseDir = \"\";",
547  
        "virtual_baseDir = " + javaQuote(ioBaseDir.getAbsolutePath()) + ";");
548  
549  
      // forward snippet cache (virtualized one)
550  
      File dir = virtCache != null ? virtCache : DiskSnippetCache_dir;
551  
      s = s.replace("static File DiskSnippetCache_dir;",
552  
        "static File DiskSnippetCache_dir = new File(" + javaQuote(dir.getAbsolutePath()) + ");");
553  
      s = s.replace("static boolean preferCached = false;", "static boolean preferCached = true;");
554  
555  
      if (verbose) {
556  
        System.out.println("==BEGIN VIRTUALIZED TRANSLATOR==");
557  
        System.out.println(s);
558  
        System.out.println("==END VIRTUALIZED TRANSLATOR==");
559  
      }
560  
      srcDir = TempDirMaker_make();
561  
      saveTextFile(new File(srcDir, "main.java").getPath(), s);
562  
563  
      // TODO: silence translator also
564  
      runInProcess = true;
565  
    }
566  
567  
    return runJavaX(ioBaseDir, srcDir, input, silent, runInProcess, libraries,
568  
      args, cacheTranslators ? "" + id : null);
569  
  }
570  
571  
  private static String getServerTranspiled(String snippetID) throws IOException {
572  
    long id = parseSnippetID(snippetID);
573  
    URL url = new URL("http://tinybrain.de:8080/tb-int/get-transpiled.php?raw=1&id=" + id);
574  
    return loadPage(url);
575  
  }
576  
577  
  static void checkProgramSafety(String snippetID) throws IOException {
578  
    if (!safeOnly) return;
579  
    URL url = new URL("http://tinybrain.de:8080/tb-int/is-javax-safe.php?id=" + parseSnippetID(snippetID));
580  
    String text = loadPage(url);
581  
    if (!text.startsWith("{\"safe\":\"1\"}"))
582  
      throw new RuntimeException("Translator not safe: #" + parseSnippetID(snippetID));
583  
  }
584  
585  
  private static void loadLibrary(String snippetID, List<File> libraries_out, File libraryFile) throws IOException {
586  
    if (verbose)
587  
      System.out.println("Assuming " + snippetID + " is a library.");
588  
589  
    if (libraryFile == null) {
590  
      byte[] data = loadDataSnippetImpl(snippetID);
591  
      DiskSnippetCache_putLibrary(parseSnippetID(snippetID), data);
592  
      libraryFile = DiskSnippetCache_getLibrary(parseSnippetID(snippetID));
593  
    }
594  
595  
    if (!libraries_out.contains(libraryFile))
596  
      libraries_out.add(libraryFile);
597  
  }
598  
599  
  private static byte[] loadDataSnippetImpl(String snippetID) throws IOException {
600  
    byte[] data;
601  
    try {
602  
      URL url = new URL("http://eyeocr.sourceforge.net/filestore/filestore.php?cmd=serve&file=blob_"
603  
        + parseSnippetID(snippetID) + "&contentType=application/binary");
604  
      System.err.println("Loading library: " + url);
605  
      data = loadBinaryPage(url.openConnection());
606  
      if (verbose)
607  
        System.err.println("Bytes loaded: " + data.length);
608  
    } catch (FileNotFoundException e) {
609  
      throw new IOException("Binary snippet #" + snippetID + " not found or not public");
610  
    }
611  
    return data;
612  
  }
613  
614  
  /** returns output dir */
615  
  private static File runJavaX(File ioBaseDir, File originalSrcDir, File originalInput,
616  
                               boolean silent, boolean runInProcess,
617  
                               List<File> libraries, String[] args, String cacheAs) throws Exception {
618  
    File srcDir = new File(ioBaseDir, "src");
619  
    File inputDir = new File(ioBaseDir, "input");
620  
    File outputDir = new File(ioBaseDir, "output");
621  
    copyInput(originalSrcDir, srcDir);
622  
    copyInput(originalInput, inputDir);
623  
    javax2(srcDir, ioBaseDir, silent, runInProcess, libraries, args, cacheAs);
624  
    return outputDir;
625  
  }
626  
627  
  private static void copyInput(File src, File dst) throws IOException {
628  
    copyDirectory(src, dst);
629  
  }
630  
631  
  public static boolean hasFile(File inputDir, String name) {
632  
    return new File(inputDir, name).exists();
633  
  }
634  
635  
  public static void copyDirectory(File src, File dst) throws IOException {
636  
    if (verbose) System.out.println("Copying " + src.getAbsolutePath() + " to " + dst.getAbsolutePath());
637  
    dst.mkdirs();
638  
    File[] files = src.listFiles();
639  
    if (files == null) return;
640  
    for (File file : files) {
641  
      File dst1 = new File(dst, file.getName());
642  
      if (file.isDirectory())
643  
        copyDirectory(file, dst1);
644  
      else {
645  
        if (verbose) System.out.println("Copying " + file.getAbsolutePath() + " to " + dst1.getAbsolutePath());
646  
        copy(file, dst1);
647  
      }
648  
    }
649  
  }
650  
651  
  /** Quickly copy a file without a progress bar or any other fancy GUI... :) */
652  
  public static void copy(File src, File dest) throws IOException {
653  
    FileInputStream inputStream = newFileInputStream(src);
654  
    FileOutputStream outputStream = newFileOutputStream(dest);
655  
    try {
656  
      copy(inputStream, outputStream);
657  
      inputStream.close();
658  
    } finally {
659  
      outputStream.close();
660  
    }
661  
  }
662  
663  
  static Object call(Object o, String method, Object... args) {
664  
    try {
665  
      Method m = call_findMethod(o, method, args);
666  
      m.setAccessible(true);
667  
      return m.invoke(o, args);
668  
    } catch (Exception e) {
669  
      throw new RuntimeException(e);
670  
    }
671  
  }
672  
673  
  static Method call_findMethod(Object o, String method, Object[] args) {
674  
    Class c = o.getClass();
675  
    while (c != null) {
676  
      for (Method m : c.getDeclaredMethods())
677  
        if (m.getName().equals(method) && (m.getModifiers() & Modifier.STATIC) == 0 && m.getParameterTypes().length == args.length) // TODO: multicast
678  
          return m;
679  
      c = c.getSuperclass();
680  
    }
681  
    throw new RuntimeException("Method '" + method + "' with " + args.length + " parameter(s) not found in " + o.getClass().getName());
682  
  }
683  
684  
  private static FileInputStream newFileInputStream(File f) throws FileNotFoundException {
685  
    /*if (androidContext != null)
686  
      return (FileInputStream) call(androidContext,
687  
        "openFileInput", f.getPath());
688  
    else*/
689  
      return new FileInputStream(f);
690  
  }
691  
692  
  private static FileOutputStream newFileOutputStream(File f) throws FileNotFoundException {
693  
    /*if (androidContext != null)
694  
      return (FileOutputStream) call(androidContext,
695  
        "openFileOutput", f.getPath(), 0);
696  
    else*/
697  
      return new FileOutputStream(f);
698  
  }
699  
700  
  public static void copy(InputStream in, OutputStream out) throws IOException {
701  
    byte[] buf = new byte[65536];
702  
    while (true) {
703  
      int n = in.read(buf);
704  
      if (n <= 0) return;
705  
      out.write(buf, 0, n);
706  
    }
707  
  }
708  
709  
  /** writes safely (to temp file, then rename) */
710  
  public static void saveTextFile(String fileName, String contents) throws IOException {
711  
    File file = new File(fileName);
712  
    File parentFile = file.getParentFile();
713  
    if (parentFile != null)
714  
      parentFile.mkdirs();
715  
    String tempFileName = fileName + "_temp";
716  
    FileOutputStream fileOutputStream = newFileOutputStream(new File(tempFileName));
717  
    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, charsetForTextFiles);
718  
    PrintWriter printWriter = new PrintWriter(outputStreamWriter);
719  
    printWriter.print(contents);
720  
    printWriter.close();
721  
    if (file.exists() && !file.delete())
722  
      throw new IOException("Can't delete " + fileName);
723  
724  
    if (!new File(tempFileName).renameTo(file))
725  
      throw new IOException("Can't rename " + tempFileName + " to " + fileName);
726  
  }
727  
728  
  /** writes safely (to temp file, then rename) */
729  
  public static void saveBinaryFile(String fileName, byte[] contents) throws IOException {
730  
    File file = new File(fileName);
731  
    File parentFile = file.getParentFile();
732  
    if (parentFile != null)
733  
      parentFile.mkdirs();
734  
    String tempFileName = fileName + "_temp";
735  
    FileOutputStream fileOutputStream = newFileOutputStream(new File(tempFileName));
736  
    fileOutputStream.write(contents);
737  
    fileOutputStream.close();
738  
    if (file.exists() && !file.delete())
739  
      throw new IOException("Can't delete " + fileName);
740  
741  
    if (!new File(tempFileName).renameTo(file))
742  
      throw new IOException("Can't rename " + tempFileName + " to " + fileName);
743  
  }
744  
745  
  public static String loadTextFile(String fileName, String defaultContents) throws IOException {
746  
    if (!new File(fileName).exists())
747  
      return defaultContents;
748  
749  
    FileInputStream fileInputStream = newFileInputStream(new File(fileName));
750  
    InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, charsetForTextFiles);
751  
    return loadTextFile(inputStreamReader, (int) new File(fileName).length());
752  
  }
753  
754  
  public static String loadTextFile(Reader reader, int length) throws IOException {
755  
    try {
756  
      char[] chars = new char[length];
757  
      int n = reader.read(chars);
758  
      return new String(chars, 0, n);
759  
    } finally {
760  
      reader.close();
761  
    }
762  
  }
763  
764  
  static File DiskSnippetCache_dir;
765  
766  
  public static void initDiskSnippetCache(File dir) {
767  
    DiskSnippetCache_dir = dir;
768  
    dir.mkdirs();
769  
  }
770  
771  
  // Data files are immutable, use centralized cache
772  
  public static synchronized File DiskSnippetCache_getLibrary(long snippetID) throws IOException {
773  
    File file = new File(getGlobalCache(), "data_" + snippetID + ".jar");
774  
    if (verbose)
775  
      System.out.println("Checking data cache: " + file.getPath());
776  
    return file.exists() ? file : null;
777  
  }
778  
779  
  public static synchronized String DiskSnippetCache_get(long snippetID) throws IOException {
780  
    return loadTextFile(DiskSnippetCache_getFile(snippetID).getPath(), null);
781  
  }
782  
783  
  private static File DiskSnippetCache_getFile(long snippetID) {
784  
    return new File(DiskSnippetCache_dir, "" + snippetID);
785  
  }
786  
787  
  public static synchronized void DiskSnippetCache_put(long snippetID, String snippet) throws IOException {
788  
    saveTextFile(DiskSnippetCache_getFile(snippetID).getPath(), snippet);
789  
  }
790  
791  
  public static synchronized void DiskSnippetCache_putLibrary(long snippetID, byte[] data) throws IOException {
792  
    saveBinaryFile(new File(getGlobalCache(), "data_" + snippetID).getPath() + ".jar", data);
793  
  }
794  
795  
  public static File DiskSnippetCache_getDir() {
796  
    return DiskSnippetCache_dir;
797  
  }
798  
799  
  public static void initSnippetCache() {
800  
    if (DiskSnippetCache_dir == null)
801  
      initDiskSnippetCache(getGlobalCache());
802  
  }
803  
804  
  private static File getGlobalCache() {
805  
    File file = new File(userHome(), ".tinybrain/snippet-cache");
806  
    file.mkdirs();
807  
    return file;
808  
  }
809  
810  
  public static String loadSnippetVerified(String snippetID, String hash) throws IOException {
811  
    String text = loadSnippet(snippetID);
812  
    String realHash = getHash(text.getBytes("UTF-8"));
813  
    if (!realHash.equals(hash)) {
814  
      String msg;
815  
      if (hash.isEmpty())
816  
        msg = "Here's your hash for " + snippetID + ", please put in your program: " + realHash;
817  
      else
818  
        msg = "Hash mismatch for " + snippetID + ": " + realHash + " (new) vs " + hash + " - has tinybrain.de been hacked??";
819  
      throw new RuntimeException(msg);
820  
    }
821  
    return text;
822  
  }
823  
824  
  public static String getHash(byte[] data) {
825  
    return bytesToHex(getFullFingerprint(data));
826  
  }
827  
828  
  public static byte[] getFullFingerprint(byte[] data) {
829  
    try {
830  
      return MessageDigest.getInstance("MD5").digest(data);
831  
    } catch (NoSuchAlgorithmException e) {
832  
      throw new RuntimeException(e);
833  
    }
834  
  }
835  
836  
  public static String bytesToHex(byte[] bytes) {
837  
    return bytesToHex(bytes, 0, bytes.length);
838  
  }
839  
840  
  public static String bytesToHex(byte[] bytes, int ofs, int len) {
841  
    StringBuilder stringBuilder = new StringBuilder(len*2);
842  
    for (int i = 0; i < len; i++) {
843  
      String s = "0" + Integer.toHexString(bytes[ofs+i]);
844  
      stringBuilder.append(s.substring(s.length()-2, s.length()));
845  
    }
846  
    return stringBuilder.toString();
847  
  }
848  
849  
  public static String loadSnippet(String snippetID) throws IOException {
850  
    return loadSnippet(parseSnippetID(snippetID));
851  
  }
852  
853  
  public static long parseSnippetID(String snippetID) {
854  
    return Long.parseLong(shortenSnippetID(snippetID));
855  
  }
856  
857  
  private static String shortenSnippetID(String snippetID) {
858  
    if (snippetID.startsWith("#"))
859  
      snippetID = snippetID.substring(1);
860  
    String httpBlaBla = "http://tinybrain.de/";
861  
    if (snippetID.startsWith(httpBlaBla))
862  
      snippetID = snippetID.substring(httpBlaBla.length());
863  
    return snippetID;
864  
  }
865  
866  
  public static boolean isSnippetID(String snippetID) {
867  
    snippetID = shortenSnippetID(snippetID);
868  
    return isInteger(snippetID) && Long.parseLong(snippetID) != 0;
869  
  }
870  
871  
  public static boolean isInteger(String s) {
872  
    return Pattern.matches("\\-?\\d+", s);
873  
  }
874  
875  
  public static String loadSnippet(long snippetID) throws IOException {
876  
    String text = memSnippetCache.get(snippetID);
877  
    if (text != null)
878  
      return text;
879  
880  
    initSnippetCache();
881  
    text = DiskSnippetCache_get(snippetID);
882  
    if (preferCached && text != null)
883  
      return text;
884  
885  
    String md5 = text != null ? md5(text) : "-";
886  
    if (text != null) {
887  
      String hash = prefetched.get(snippetID);
888  
      if (hash != null) {
889  
        if (md5.equals(hash)) {
890  
          memSnippetCache.put(snippetID, text);
891  
          return text;
892  
        } else
893  
          prefetched.remove(snippetID); // (maybe this is not necessary)
894  
      }
895  
    }
896  
897  
    try {
898  
      /*URL url = new URL("http://tinybrain.de:8080/getraw.php?id=" + snippetID);
899  
      text = loadPage(url);*/
900  
      String theURL = "http://tinybrain.de:8080/getraw.php?id=" + snippetID + "&getmd5=1&utf8=1&usetranspiled=1";
901  
      if (text != null) {
902  
        //System.err.println("MD5: " + md5);
903  
        theURL += "&md5=" + md5;
904  
      }
905  
      URL url = new URL(theURL);
906  
      String page = loadPage(url);
907  
908  
      // parse & drop transpilation flag available line
909  
      int i = page.indexOf('\n');
910  
      boolean hasTranspiled = page.substring(0, i).trim().equals("1");
911  
      if (hasTranspiled)
912  
        hasTranspiledSet.add(snippetID);
913  
      else
914  
        hasTranspiledSet.remove(snippetID);
915  
      page = page.substring(i+1);
916  
917  
      if (page.startsWith("==*#*==")) {
918  
        // same, keep text
919  
        //System.err.println("Snippet unchanged, keeping.");
920  
      } else {
921  
        // drop md5 line
922  
        i = page.indexOf('\n');
923  
        String hash = page.substring(0, i).trim();
924  
        text = page.substring(i+1);
925  
926  
        String myHash = md5(text);
927  
        if (myHash.equals(hash)) {
928  
          //System.err.println("Hash match: " + hash);
929  
        } else
930  
          System.err.println("Hash mismatch");
931  
      }
932  
    } catch (FileNotFoundException e) {
933  
      e.printStackTrace();
934  
      throw new IOException("Snippet #" + snippetID + " not found or not public");
935  
    }
936  
937  
    memSnippetCache.put(snippetID, text);
938  
939  
    try {
940  
      initSnippetCache();
941  
      DiskSnippetCache_put(snippetID, text);
942  
    } catch (IOException e) {
943  
      System.err.println("Minor warning: Couldn't save snippet to cache ("  + DiskSnippetCache_getDir() + ")");
944  
    }
945  
946  
    return text;
947  
  }
948  
949  
  private static String md5(String text) {
950  
    try {
951  
      return bytesToHex(md5impl(text.getBytes("UTF-8"))); // maybe different than the way PHP does it...
952  
    } catch (UnsupportedEncodingException e) {
953  
      throw new RuntimeException(e);
954  
    }
955  
  }
956  
957  
  public static byte[] md5impl(byte[] data) {
958  
    try {
959  
      return MessageDigest.getInstance("MD5").digest(data);
960  
    } catch (NoSuchAlgorithmException e) {
961  
      throw new RuntimeException(e);
962  
    }
963  
  }
964  
965  
  private static String loadPage(URL url) throws IOException {
966  
    System.err.println("Loading: " + url.toExternalForm());
967  
    URLConnection con = url.openConnection();
968  
    return loadPage(con, url);
969  
  }
970  
971  
  public static String loadPage(URLConnection con, URL url) throws IOException {
972  
    setHeaders(con);
973  
    String contentType = con.getContentType();
974  
    if (contentType == null)
975  
      throw new IOException("Page could not be read: " + url);
976  
    //Log.info("Content-Type: " + contentType);
977  
    String charset = guessCharset(contentType);
978  
    //System.err.println("Charset: " + charset);
979  
    Reader r = new InputStreamReader(con.getInputStream(), charset);
980  
    StringBuilder buf = new StringBuilder();
981  
    while (true) {
982  
      int ch = r.read();
983  
      if (ch < 0)
984  
        break;
985  
      //Log.info("Chars read: " + buf.length());
986  
      buf.append((char) ch);
987  
    }
988  
    return buf.toString();
989  
  }
990  
991  
  public static byte[] loadBinaryPage(URLConnection con) throws IOException {
992  
    setHeaders(con);
993  
    return loadBinaryPage_noHeaders(con);
994  
  }
995  
996  
  private static byte[] loadBinaryPage_noHeaders(URLConnection con) throws IOException {
997  
    ByteArrayOutputStream buf = new ByteArrayOutputStream();
998  
    InputStream inputStream = con.getInputStream();
999  
    while (true) {
1000  
      int ch = inputStream.read();
1001  
      if (ch < 0)
1002  
        break;
1003  
      buf.write(ch);
1004  
    }
1005  
    inputStream.close();
1006  
    return buf.toByteArray();
1007  
  }
1008  
1009  
  private static void setHeaders(URLConnection con) throws IOException {
1010  
    String computerID = getComputerID();
1011  
    if (computerID != null)
1012  
      con.setRequestProperty("X-ComputerID", computerID);
1013  
  }
1014  
1015  
  public static String guessCharset(String contentType) {
1016  
    Pattern p = Pattern.compile("text/html;\\s+charset=([^\\s]+)\\s*");
1017  
    Matcher m = p.matcher(contentType);
1018  
    /* If Content-Type doesn't match this pre-conception, choose default and hope for the best. */
1019  
    return m.matches() ? m.group(1) : "ISO-8859-1";
1020  
  }
1021  
1022  
  /** runs a transpiled set of sources */
1023  
  public static void javax2(File srcDir, File ioBaseDir, boolean silent, boolean runInProcess,
1024  
                            List<File> libraries, String[] args, String cacheAs) throws Exception {
1025  
    if (android) {
1026  
      // TODO: optimize if it's a loaded snippet anyway
1027  
      URL url = new URL("http://tinybrain.de:8080/dexcompile.php");
1028  
      URLConnection conn = url.openConnection();
1029  
      String postData = "src=" + URLEncoder.encode(loadTextFile(new File(srcDir, "main.java").getPath(), null), "UTF-8");
1030  
      byte[] dexData = doPostBinary(postData, conn, url);
1031  
      if (!isDex(dexData))
1032  
        throw new RuntimeException("Dex generation error: " + dexData.length + " bytes - " + new String(dexData, "UTF-8"));
1033  
1034  
      File dexDir = TempDirMaker_make();
1035  
      File dexFile = new File(dexDir, System.currentTimeMillis() + ".dex");
1036  
      File dexOutputDir = TempDirMaker_make();
1037  
1038  
      saveBinaryFile(dexFile.getPath(), dexData);
1039  
1040  
      ClassLoader parentClassLoader =
1041  
        //ClassLoader.getSystemClassLoader(); // does not find support jar
1042  
        //getClass().getClassLoader(); // Let's try this...
1043  
        _x18.class.getClassLoader().getParent(); // XXX !
1044  
1045  
      //DexClassLoader classLoader = new DexClassLoader(dexFile.getAbsolutePath(), dexOutputDir.getAbsolutePath(), null,
1046  
      //  parentClassLoader);
1047  
      Class dcl = Class.forName("dalvik.system.DexClassLoader");
1048  
      Object classLoader = dcl.getConstructors()[0].newInstance(dexFile.getAbsolutePath(), dexOutputDir.getAbsolutePath(), null,
1049  
        parentClassLoader);
1050  
1051  
      //Class<?> theClass = classLoader.loadClass(mainClassName);
1052  
      Class<?> theClass = (Class<?>) call(classLoader, "loadClass", "main");
1053  
1054  
      try {
1055  
        set(theClass, "androidContext", androidContext);
1056  
      } catch (Throwable e) {}
1057  
      
1058  
      runMainMethod(args, theClass);
1059  
    } else {
1060  
      File classesDir = TempDirMaker_make();
1061  
      String javacOutput = compileJava(srcDir, libraries, classesDir);
1062  
1063  
      // run
1064  
1065  
      if (verbose) System.out.println("Running program (" + srcDir.getAbsolutePath()
1066  
        + ") on io dir " + ioBaseDir.getAbsolutePath() + (runInProcess ? "[in-process]" : "") + "\n");
1067  
      runProgram(javacOutput, classesDir, ioBaseDir, silent, runInProcess, libraries, args, cacheAs);
1068  
    }
1069  
  }
1070  
1071  
  static byte[] DEX_FILE_MAGIC = { 0x64, 0x65, 0x78, 0x0a, 0x30, 0x33, 0x35, 0x00 };
1072  
1073  
  static boolean isDex(byte[] dexData) {
1074  
    if (dexData.length < DEX_FILE_MAGIC.length) return false;
1075  
    for (int i = 0; i < DEX_FILE_MAGIC.length; i++)
1076  
      if (dexData[i] != DEX_FILE_MAGIC[i])
1077  
        return false;
1078  
    return true;
1079  
  }
1080  
1081  
  static byte[] doPostBinary(String urlParameters, URLConnection conn, URL url) throws IOException {
1082  
    // connect and do POST
1083  
    setHeaders(conn);
1084  
    conn.setDoOutput(true);
1085  
1086  
    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
1087  
    writer.write(urlParameters);
1088  
    writer.flush();
1089  
1090  
    byte[] contents = loadBinaryPage_noHeaders(conn);
1091  
    writer.close();
1092  
    return contents;
1093  
  }
1094  
1095  
  static String compileJava(File srcDir, List<File> libraries, File classesDir) throws IOException {
1096  
    ++compilations;
1097  
1098  
    // collect sources
1099  
1100  
    List<File> sources = new ArrayList<File>();
1101  
    if (verbose) System.out.println("Scanning for sources in " + srcDir.getPath());
1102  
    scanForSources(srcDir, sources, true);
1103  
    if (sources.isEmpty())
1104  
      throw new IOException("No sources found");
1105  
1106  
    // compile
1107  
1108  
    File optionsFile = File.createTempFile("javax", "");
1109  
    if (verbose) System.out.println("Compiling " + sources.size() + " source(s) to " + classesDir.getPath());
1110  
    String options = "-d " + bashQuote(classesDir.getPath());
1111  
    writeOptions(sources, libraries, optionsFile, options);
1112  
    classesDir.mkdirs();
1113  
    return invokeJavac(optionsFile);
1114  
  }
1115  
1116  
  private static void runProgram(String javacOutput, File classesDir, File ioBaseDir,
1117  
                                 boolean silent, boolean runInProcess,
1118  
                                 List<File> libraries, String[] args, String cacheAs) throws Exception {
1119  
    // print javac output if compile failed and it hasn't been printed yet
1120  
    boolean didNotCompile = !didCompile(classesDir);
1121  
    if (verbose || didNotCompile)
1122  
      System.out.println(javacOutput);
1123  
    if (didNotCompile)
1124  
      return;
1125  
1126  
    if (runInProcess
1127  
      || (ioBaseDir.getAbsolutePath().equals(new File(".").getAbsolutePath()) && !silent)) {
1128  
      runProgramQuick(classesDir, libraries, args, cacheAs);
1129  
      return;
1130  
    }
1131  
1132  
    boolean echoOK = false;
1133  
    // TODO: add libraries to class path
1134  
    String bashCmd = "(cd " + bashQuote(ioBaseDir.getAbsolutePath()) + " && (java -cp "
1135  
      + bashQuote(classesDir.getAbsolutePath()) + " main" + (echoOK ? "; echo ok" : "") + "))";
1136  
    if (verbose) System.out.println(bashCmd);
1137  
    String output = backtick(bashCmd);
1138  
    if (verbose || !silent)
1139  
      System.out.println(output);
1140  
  }
1141  
1142  
  static boolean didCompile(File classesDir) {
1143  
    return hasFile(classesDir, "main.class");
1144  
  }
1145  
1146  
  private static void runProgramQuick(File classesDir, List<File> libraries,
1147  
                                      String[] args, String cacheAs) throws Exception {
1148  
    // collect urls
1149  
    URL[] urls = new URL[libraries.size()+1];
1150  
    urls[0] = classesDir.toURI().toURL();
1151  
    for (int i = 0; i < libraries.size(); i++)
1152  
      urls[i+1] = libraries.get(i).toURI().toURL();
1153  
1154  
    // make class loader
1155  
    URLClassLoader classLoader = new URLClassLoader(urls);
1156  
1157  
    // load JavaX main class
1158  
    Class<?> mainClass = classLoader.loadClass("main");
1159  
1160  
    if (cacheAs != null)
1161  
      programCache.put(cacheAs, mainClass);
1162  
1163  
    runMainMethod(args, mainClass);
1164  
  }
1165  
1166  
  static void runMainMethod(Object args, Class<?> mainClass) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
1167  
    Method main = mainClass.getMethod("main", String[].class);
1168  
    main.invoke(null, args);
1169  
  }
1170  
1171  
  private static String invokeJavac(File optionsFile) throws IOException {
1172  
    String output;
1173  
    try {
1174  
      output = invokeEcj(optionsFile);
1175  
    } catch (Exception e) {
1176  
      if (verbose) {
1177  
        System.err.println("ecj not found or misconfigured - using javac");
1178  
        e.printStackTrace();
1179  
      }
1180  
      output = backtick("javac " + bashQuote("@" + optionsFile.getPath()));
1181  
    }
1182  
    if (verbose) System.out.println(output);
1183  
    return output;
1184  
  }
1185  
1186  
  // throws ClassNotFoundException if ecj is not in classpath
1187  
  static String invokeEcj(File optionsFile) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
1188  
    Class batchCompiler = getEclipseCompiler();
1189  
1190  
    StringWriter writer = new StringWriter();
1191  
    PrintWriter printWriter = new PrintWriter(writer);
1192  
1193  
    // add more eclipse options in the line below
1194  
1195  
    String[] args = { "@" + optionsFile.getPath(),
1196  
      "-source", "1.7",
1197  
      "-nowarn"
1198  
    };
1199  
    Method compile = batchCompiler.getDeclaredMethod("compile", args.getClass(), PrintWriter.class, PrintWriter.class,
1200  
      Class.forName("org.eclipse.jdt.core.compiler.CompilationProgress"));
1201  
    compile.invoke(null, args, printWriter, printWriter, null);
1202  
    return writer.toString();
1203  
  }
1204  
1205  
  private static Class<?> getEclipseCompiler() throws ClassNotFoundException {
1206  
    return Class.forName("org.eclipse.jdt.core.compiler.batch.BatchCompiler");
1207  
  }
1208  
1209  
  private static void writeOptions(List<File> sources, List<File> libraries,
1210  
                                   File optionsFile, String moreOptions) throws IOException {
1211  
    FileWriter writer = new FileWriter(optionsFile);
1212  
    for (File source : sources)
1213  
      writer.write(bashQuote(source.getPath()) + " ");
1214  
    if (!libraries.isEmpty()) {
1215  
      List<String> cp = new ArrayList<String>();
1216  
      for (File lib : libraries)
1217  
        cp.add(lib.getAbsolutePath());
1218  
      writer.write("-cp " + bashQuote(join(File.pathSeparator, cp)) + " ");
1219  
    }
1220  
    writer.write(moreOptions);
1221  
    writer.close();
1222  
  }
1223  
1224  
  static void scanForSources(File source, List<File> sources, boolean topLevel) {
1225  
    if (source.isFile() && source.getName().endsWith(".java"))
1226  
      sources.add(source);
1227  
    else if (source.isDirectory() && !isSkippedDirectoryName(source.getName(), topLevel)) {
1228  
      File[] files = source.listFiles();
1229  
      for (File file : files)
1230  
        scanForSources(file, sources, false);
1231  
    }
1232  
  }
1233  
1234  
  private static boolean isSkippedDirectoryName(String name, boolean topLevel) {
1235  
    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.)
1236  
    return name.equalsIgnoreCase("input") || name.equalsIgnoreCase("output");
1237  
  }
1238  
1239  
  public static String backtick(String cmd) throws IOException {
1240  
    ++processesStarted;
1241  
    File outFile = File.createTempFile("_backtick", "");
1242  
    File scriptFile = File.createTempFile("_backtick", isWindows() ? ".bat" : "");
1243  
1244  
    String command = cmd + ">" + bashQuote(outFile.getPath()) + " 2>&1";
1245  
    //Log.info("[Backtick] " + command);
1246  
    try {
1247  
      saveTextFile(scriptFile.getPath(), command);
1248  
      String[] command2;
1249  
      if (isWindows())
1250  
        command2 = new String[] { scriptFile.getPath() };
1251  
      else
1252  
        command2 = new String[] { "/bin/bash", scriptFile.getPath() };
1253  
      Process process = Runtime.getRuntime().exec(command2);
1254  
      try {
1255  
        process.waitFor();
1256  
      } catch (InterruptedException e) {
1257  
        throw new RuntimeException(e);
1258  
      }
1259  
      process.exitValue();
1260  
      return loadTextFile(outFile.getPath(), "");
1261  
    } finally {
1262  
      scriptFile.delete();
1263  
    }
1264  
  }
1265  
1266  
  /** possibly improvable */
1267  
  public static String javaQuote(String text) {
1268  
    return bashQuote(text);
1269  
  }
1270  
1271  
  /** possibly improvable */
1272  
  public static String bashQuote(String text) {
1273  
    if (text == null) return null;
1274  
    return "\"" + text
1275  
      .replace("\\", "\\\\")
1276  
      .replace("\"", "\\\"")
1277  
      .replace("\n", "\\n")
1278  
      .replace("\r", "\\r") + "\"";
1279  
  }
1280  
1281  
  public final static String charsetForTextFiles = "UTF8";
1282  
1283  
  static long TempDirMaker_lastValue;
1284  
1285  
  public static File TempDirMaker_make() {
1286  
    File dir = new File(userHome(), ".javax/" + TempDirMaker_newValue());
1287  
    dir.mkdirs();
1288  
    return dir;
1289  
  }
1290  
1291  
  private static long TempDirMaker_newValue() {
1292  
    long value;
1293  
    do
1294  
      value = System.currentTimeMillis();
1295  
    while (value == TempDirMaker_lastValue);
1296  
    TempDirMaker_lastValue = value;
1297  
    return value;
1298  
  }
1299  
1300  
  public static String join(String glue, Iterable<String> strings) {
1301  
    StringBuilder buf = new StringBuilder();
1302  
    Iterator<String> i = strings.iterator();
1303  
    if (i.hasNext()) {
1304  
      buf.append(i.next());
1305  
      while (i.hasNext())
1306  
        buf.append(glue).append(i.next());
1307  
    }
1308  
    return buf.toString();
1309  
  }
1310  
1311  
  public static boolean isWindows() {
1312  
    return System.getProperty("os.name").contains("Windows");
1313  
  }
1314  
1315  
  public static String makeRandomID(int length) {
1316  
    Random random = new Random();
1317  
    char[] id = new char[length];
1318  
    for (int i = 0; i< id.length; i++)
1319  
      id[i] = (char) ((int) 'a' + random.nextInt(26));
1320  
    return new String(id);
1321  
  }
1322  
1323  
  static String computerID;
1324  
  public static String getComputerID() throws IOException {
1325  
    if (noID) return null;
1326  
    if (computerID == null) {
1327  
      File file = new File(userHome(), ".tinybrain/computer-id");
1328  
      computerID = loadTextFile(file.getPath(), null);
1329  
      if (computerID == null) {
1330  
        computerID = makeRandomID(12);
1331  
        saveTextFile(file.getPath(), computerID);
1332  
      }
1333  
      if (verbose)
1334  
        System.out.println("Local computer ID: " + computerID);
1335  
    }
1336  
    return computerID;
1337  
  }
1338  
1339  
  static int fileDeletions;
1340  
1341  
  static void cleanCache() {
1342  
    if (verbose)
1343  
      System.out.println("Cleaning cache");
1344  
    fileDeletions = 0;
1345  
    File javax = new File(userHome(), ".javax");
1346  
    long now = System.currentTimeMillis();
1347  
    File[] files = javax.listFiles();
1348  
    if (files != null) for (File dir : files) {
1349  
      if (dir.isDirectory() && Pattern.compile("\\d+").matcher(dir.getName()).matches()) {
1350  
        long time = Long.parseLong(dir.getName());
1351  
        long seconds = (now - time) / 1000;
1352  
        long minutes = seconds / 60;
1353  
        long hours = minutes / 60;
1354  
        if (hours >= 1) {
1355  
          //System.out.println("Can delete " + dir.getAbsolutePath() + ", age: " + hours + " h");
1356  
          removeDir(dir);
1357  
        }
1358  
      }
1359  
    }
1360  
    if (verbose && fileDeletions != 0)
1361  
      System.out.println("Cleaned cache. File deletions: " + fileDeletions);
1362  
  }
1363  
1364  
  static void removeDir(File dir) {
1365  
    if (dir.getAbsolutePath().indexOf(".javax") < 0)  // security check!
1366  
      return;
1367  
    for (File f : dir.listFiles()) {
1368  
      if (f.isDirectory())
1369  
        removeDir(f);
1370  
      else {
1371  
        if (verbose)
1372  
          System.out.println("Deleting " + f.getAbsolutePath());
1373  
        f.delete();
1374  
        ++fileDeletions;
1375  
      }
1376  
    }
1377  
    dir.delete();
1378  
  }
1379  
1380  
  static void showSystemProperties() {
1381  
    System.out.println("System properties:\n");
1382  
    for (Map.Entry<Object, Object> entry : System.getProperties().entrySet()) {
1383  
      System.out.println("  " + entry.getKey() + " = " + entry.getValue());
1384  
    }
1385  
    System.out.println();
1386  
  }
1387  
  
1388  
  static void showVersion() {
1389  
    //showSystemProperties();
1390  
    boolean eclipseFound = hasEclipseCompiler();
1391  
    //String platform = System.getProperty("java.vendor") + " " + System.getProperty("java.runtime.name") + " " + System.getProperty("java.version");
1392  
    String platform = System.getProperty("java.vm.name") + " " + System.getProperty("java.version");
1393  
    String os = System.getProperty("os.name"), arch = System.getProperty("os.arch");
1394  
    System.out.println("This is " + version + ".");
1395  
    System.out.println("[Details: " +
1396  
      (eclipseFound ? "Eclipse compiler (good)" : "javac (not so good)")
1397  
      + ", " + platform + ", " + arch + ", " + os + "]");
1398  
  }
1399  
1400  
  private static boolean hasEclipseCompiler() {
1401  
    boolean compilerFound = false;
1402  
    try { getEclipseCompiler(); compilerFound = true; } catch (ClassNotFoundException e) {}
1403  
    return compilerFound;
1404  
  }
1405  
1406  
  static boolean isAndroid() {
1407  
    return System.getProperty("java.vendor").toLowerCase().indexOf("android") >= 0;
1408  
  }
1409  
  
1410  
  static void set(Class c, String field, Object value) {
1411  
    try {
1412  
      Field f = set_findStaticField(c, field);
1413  
      f.setAccessible(true);
1414  
      f.set(null, value);
1415  
    } catch (Exception e) {
1416  
      throw new RuntimeException(e);
1417  
    }
1418  
  }
1419  
  
1420  
  static Field set_findStaticField(Class<?> c, String field) {
1421  
    for (Field f : c.getDeclaredFields())
1422  
      if (f.getName().equals(field) && (f.getModifiers() & Modifier.STATIC) != 0)
1423  
        return f;
1424  
    throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
1425  
  }
1426  
}

Author comment

Began life as a copy of #1000413

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: #1000420
Snippet name: JavaX 18 Android running 1000419 (ImageView test)
Eternal ID of this version: #1000420/1
Text MD5: 77240a64629239bef68c9e515528ad30
Author: stefan
Category: javax android
Type: JavaX source code (Android)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2015-08-04 02:05:21
Source code size: 51069 bytes / 1426 lines
Pitched / IR pitched: No / Yes
Views / Downloads: 625 / 519
Referenced in: [show references]