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