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

332
LINES

< > BotCompany Repo | #1004180 // Boot-up code for JavaX/Android, loading x30 dynamically (dev.)

JavaX source code (Android) [tags: use-pretranspiled] - run with: the app

Libraryless. Click here for Pure Java version (895L/7K/23K).

!752

import java.util.*;
import java.util.zip.*;
import java.util.List;
import java.util.regex.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.io.*;
import java.net.*;
import java.lang.reflect.*;
import java.lang.ref.*;
import java.lang.management.*;
import java.security.*;
import java.security.spec.*;
import java.math.*;

import android.widget.*;
import android.view.*;
import android.view.View;
import android.widget.Button;
import android.content.Context;
import android.app.Activity;
import android.view.inputmethod.*;
import android.content.*;
import android.text.*;

public class main {
  static String awarenessID = "#1004078";
  
  static Class x30;
  
  static List<Prog> programsStarted = new ArrayList<Prog>();
  static File defSnip, defargs;

  static class Prog {
    String snippetID;
    Thread thread;
  }

  static class Lg {
    static int maxBufferLength = 2048;
    
    Activity context;
    ScrollView sv;
    TextView tv;
    StringBuilder buf = new StringBuilder();
    
    Lg(Activity context) {
      this.context = context;
      sv = new ScrollView(context);
      tv = new TextView(context);
      tv.setText(buf.toString());
      sv.addView(tv);
    }
    
    View getView() {
      return sv;
    }
    
    void shortenBuffer() {
      while (buf.length() > maxBufferLength) {
        String s = buf.toString();
        int i = s.indexOf('\n');
        if (i < 0) return;
        buf = new StringBuilder(s.substring(i+1));
      }
    }
    
    void print(final String s) {
      context.runOnUiThread(new Runnable() {
        public void run() {
          buf.append(s);
          shortenBuffer();
          tv.setText(buf.toString());
          
          sv.post(new Runnable() {
            public void run() {
              // This method works but animates the scrolling 
              // which looks weird on first load
              sv.fullScroll(View.FOCUS_DOWN);

              // This method works even better because there are no animations.
              //sv.scrollTo(0, sv.getBottom());
            }
          });
        }
      });
    }
    
    void println(String s) {
      print(s + "\n");
    }
  }
  
  public static String snippetToRun;
  static Context androidContext;

  public static View main(final Context _context) throws Exception {
    final Activity context = _context instanceof Activity ? (Activity) _context : null;
    
    System.out.println("676 context: " + _context);
    
    androidContext = _context;
    
    if (context == null) {
      if (snippetToRun != null) {
        new Thread() {
          public void run() {
            String[] a = { snippetToRun };
            callx30(a);
          }
        }.start();
      }
      return null;
    }
    
    defSnip = new File(userHome(), ".javax/defsnip");
    String id = loadTextFile(defSnip.getPath(), "636");
    defargs = new File(userHome(), ".javax/defargs");
    String arg = loadTextFile(defargs.getPath(), "");

    ScrollView sv = new ScrollView(context);
    LinearLayout ll = new LinearLayout(context);
    ll.setOrientation(LinearLayout.VERTICAL);
    
    LinearLayout line1 = new LinearLayout(context);
    
    TextView label = new TextView(context);
    label.setText("Run which snippet ID?");
    line1.addView(label);
    
    final EditText tv = new EditText(context);
    // BAD - tv.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
    tv.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_CLASS_NUMBER);
    tv.setText(id);
    line1.addView(tv);
    
    Button btnGo = new Button(context);
    btnGo.setText("Go");
    line1.addView(btnGo);
    
    ll.addView(line1);
    
    LinearLayout line2 = new LinearLayout(context);
    
    label = new TextView(context);
    label.setText("Program arguments:");
    line2.addView(label);
    
    final EditText tvArgs = new EditText(context);
    tvArgs.setText(arg);
    line2.addView(tvArgs);
    
    ll.addView(line2);
    
    LinearLayout line3 = new LinearLayout(context);
    
    /*Button btnLeo = new Button(context);
    btnLeo.setText("Sprechen mit Leo");
    line3.addView(btnLeo);*/
    
    Button btn = new Button(context);
    btn.setText("Start Awareness [" + awarenessID + "]");
    btn.setOnClickListener(new View.OnClickListener() {
      public void onClick(View v) {
        saveDef(awarenessID, "");
        run(context, awarenessID, new String[0]);
      }
    });
    line3.addView(btn);

    ll.addView(line3);
    
    btnGo.setOnClickListener(new View.OnClickListener() {
      public void onClick(View v) {
        hideKeyboard(context);
        String snippetID = tv.getText().toString();
        String text = "Running: " + snippetID;
        Toast.makeText(context, text, 2000).show();
        
        saveDef(snippetID, tvArgs.getText().toString());
        
        // TODO: quoted args
        run(context, snippetID, tvArgs.getText().toString().split(" +"));
      }
    });

    sv.addView(ll);
    return sv;
  }
  
  static void saveDef(String snippetID, String args) {
    try {
      saveTextFile(defSnip.getPath(), snippetID);
      saveTextFile(defargs.getPath(), args);
    } catch (IOException e) {
    }
  }
  
  static Lg lg;
  
  public static void run(final Activity context, final String mainSnippet, final String[] args) {
    lg = new Lg(context);
    
    OutputStream outputStream = new OutputStream() {
      public void write(int b) {
        try {
          lg.print(new String(new byte[] {(byte) b}, "UTF-8")); // This is crap
        } catch (UnsupportedEncodingException e) {}
      }
      
      @Override
      public void write(byte[] b, int off, int len) {
        try {
          lg.print(new String(b, off, len, "UTF-8")); // This is crap
        } catch (UnsupportedEncodingException e) {}
      }
    };
    
    PrintStream ps = new PrintStream(outputStream, true);
    System.setOut(ps);
    System.setErr(ps);
    
    Prog prog = new Prog();
    prog.snippetID = mainSnippet;

    prog.thread = new Thread() {
      public void run() {
        try {
          String[] a = new String[args.length+1];
          System.arraycopy(args, 0, a, 1, args.length);
          a[0] = mainSnippet;
          callx30(a);
        } catch (Throwable e) {
          System.out.println("Whoa!");
          e.printStackTrace();
        }
      }
    };
    
    programsStarted.add(prog);
    prog.thread.start();
    
    context.setContentView(lg.getView());
  }
  
  static void setContentViewInUIThread(final View view) {
    ((Activity) androidContext).runOnUiThread(new Runnable() {
      public void run() {
        ((Activity) androidContext).setContentView(view);
      }
    });
  }
  
  public static void hideKeyboard(Activity context) {   
    View view = context.getCurrentFocus();
    if (view != null) {
        InputMethodManager inputManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }
  }
  
  static void onActivityResult(int requestCode, int resultCode, Intent data) {
    /* TODO?
    if (x30.mainClass != null)
      x30.call(x30.mainClass, "onActivityResult", requestCode, resultCode, data);*/
  }
  
  static void callx30(S[] args) {
    getx30();
    callMain(x30, args);
  }
  
  static synchronized void getx30() {
    if (x30 == null)
      x30 = loadDex("#1004182");
  }
  
  static Class<?> loadDex(String programID) ctex {
    S url = "http://tinybrain.de:8080/dexcompile.php?id=" + parseSnippetID(programID);
    byte[] dexData = loadBinaryPage(url);
    if (!isDex(dexData))
      throw new RuntimeException("Dex generation error");
    System.out.println("Dex loaded: " + dexData.length + "b");

    File dexDir = makeAndroidTempDir();
    File dexFile = new File(dexDir, System.currentTimeMillis() + ".dex");
    File dexOutputDir = makeAndroidTempDir();

    System.out.println("Saving dex to: " + dexDir.getAbsolutePath());
    try {
      saveBinaryFile(dexFile.getPath(), dexData);
    } catch (Throwable e) {
      System.out.println("Whoa!");
      throw new RuntimeException(e);
    }

    System.out.println("Getting parent class loader.");
    ClassLoader parentClassLoader =
      main.class.getClassLoader().getParent();

    //System.out.println("Making DexClassLoader.");
    //DexClassLoader classLoader = new DexClassLoader(dexFile.getAbsolutePath(), dexOutputDir.getAbsolutePath(), null,
    //  parentClassLoader);
    Class dcl = Class.forName("dalvik.system.DexClassLoader");
    Object classLoader = dcl.getConstructors()[0].newInstance(dexFile.getAbsolutePath(), dexOutputDir.getAbsolutePath(), null,
      parentClassLoader);

    //System.out.println("Loading main class.");
    //Class<?> theClass = classLoader.loadClass(mainClassName);
    Class<?> theClass = (Class<?>) call(classLoader, "loadClass", "main");

    //System.out.println("Main class loaded.");
    try {
      set(theClass, "androidContext", androidContext);
    } catch (Throwable e) {}

    setVars(theClass, programID);
    return theClass;
  }
  
  static void setVars(Class<?> theClass, String programID) {
    try {
      set(theClass, "programID", programID);
    } catch (Throwable e) {}

    try {
      set(theClass, "__javax", x30);
    } catch (Throwable e) {}
  }
}

Author comment

Began life as a copy of #676

download  show line numbers  debug dex  old transpilations   

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

No comments. add comment

Snippet ID: #1004180
Snippet name: Boot-up code for JavaX/Android, loading x30 dynamically (dev.)
Eternal ID of this version: #1004180/1
Text MD5: 8f28190571215c818b4133fada21794f
Transpilation MD5: 77ba85a1f144f22c5b45ffa622c4490c
Author: stefan
Category: javax
Type: JavaX source code (Android)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2016-08-09 15:26:37
Source code size: 9694 bytes / 332 lines
Pitched / IR pitched: No / No
Views / Downloads: 516 / 532
Referenced in: [show references]