Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

* Issue #6 Port to Ruboto Core

* Removed the jruby-jars
* Added WriterOutputStream since it is not available form the jruby jars
* Started using EntryPointActivity
  • Loading branch information...
commit 82a2b2765f7c1a480398860c49da6f862c1bc152 1 parent 17744d9
@donv donv authored
View
11 .project
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>ruboto-irb</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ </buildSpec>
+ <natures>
+ </natures>
+</projectDescription>
View
25 Rakefile
@@ -30,6 +30,8 @@ RESOURCE_FILES = Dir[File.expand_path 'res/**/*']
JAVA_SOURCE_FILES = Dir[File.expand_path 'src/**/*.java']
RUBY_SOURCE_FILES = Dir[File.expand_path 'src/**/*.rb']
APK_DEPENDENCIES = [MANIFEST_FILE, RUBOTO_CONFIG_FILE, BUNDLE_JAR] + JRUBY_JARS + JAVA_SOURCE_FILES + RESOURCE_FILES + RUBY_SOURCE_FILES
+KEYSTORE_FILE = (key_store = File.readlines('ant.properties').grep(/^key.store=/).first) ? key_store.chomp.sub(/^key.store=/, '') : "#{build_project_name}.keystore"
+KEYSTORE_ALIAS = (key_alias = File.readlines('ant.properties').grep(/^key.alias=/).first) ? key_alias.chomp.sub(/^key.alias=/, '') : build_project_name
CLEAN.include('bin')
@@ -80,10 +82,21 @@ end
desc 'Build APK for release'
task :release => RELEASE_APK_FILE
-file RELEASE_APK_FILE => APK_DEPENDENCIES do |t|
+file RELEASE_APK_FILE => [KEYSTORE_FILE] + APK_DEPENDENCIES do |t|
build_apk(t, true)
end
+desc 'Create a keystore for signing the release APK'
+file KEYSTORE_FILE do
+ unless File.read('ant.properties') =~ /^key.store=/
+ File.open('ant.properties', 'a'){|f| f << "\nkey.store=#{KEYSTORE_FILE}\n"}
+ end
+ unless File.read('ant.properties') =~ /^key.alias=/
+ File.open('ant.properties', 'a'){|f| f << "\nkey.alias=#{KEYSTORE_ALIAS}\n"}
+ end
+ sh "keytool -genkey -v -keystore #{KEYSTORE_FILE} -alias #{KEYSTORE_ALIAS} -keyalg RSA -keysize 2048 -validity 10000"
+end
+
desc 'Tag this working copy with the current version'
task :tag => :release do
unless `git branch` =~ /^\* master$/
@@ -144,11 +157,10 @@ end
namespace :update_scripts do
desc 'Copy scripts to emulator and restart the app'
task :restart => APK_DEPENDENCIES do |t|
- if stop_app
- update_scripts
- else
- build_apk(t, false)
+ if build_apk(t, false) || !stop_app
install_apk
+ else
+ update_scripts
end
start_app
end
@@ -334,7 +346,7 @@ def build_apk(t, release)
changed_prereqs = t.prerequisites.select do |p|
File.file?(p) && !Dir[p].empty? && Dir[p].map { |f| File.mtime(f) }.max > File.mtime(APK_FILE)
end
- return if changed_prereqs.empty?
+ return false if changed_prereqs.empty?
changed_prereqs.each { |f| puts "#{f} changed." }
puts "Forcing rebuild of #{apk_file}."
end
@@ -343,6 +355,7 @@ def build_apk(t, release)
else
sh 'ant debug'
end
+ return true
end
def install_apk
View
BIN  libs/jruby-core-1.7.0.dev.jar
Binary file not shown
View
BIN  libs/jruby-stdlib-1.7.0.dev.jar
Binary file not shown
View
23 src/irb.rb
@@ -0,0 +1,23 @@
+#require 'ruboto/activity'
+#require 'ruboto/widget'
+#require 'ruboto/util/toast'
+#
+#ruboto_import_widgets :Button, :LinearLayout, :TextView
+#
+#$activity.start_ruboto_activity "$sample_activity" do
+# setTitle 'This is the Title'
+#
+# def on_create(bundle)
+# self.content_view =
+# linear_layout(:orientation => :vertical) do
+# @text_view = text_view :text => 'What hath Matz wrought?', :id => 42
+# button :text => 'M-x butterfly', :width => :wrap_content, :id => 43,
+# :on_click_listener => @handle_click
+# end
+# end
+#
+# @handle_click = proc do |view|
+# @text_view.text = 'What hath Matz wrought!'
+# toast 'Flipped a bit via butterfly'
+# end
+#end
View
214 src/org/jruby/embed/io/WriterOutputStream.java
@@ -0,0 +1,214 @@
+/**
+ * **** BEGIN LICENSE BLOCK *****
+ * Version: CPL 1.0/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Common Public
+ * License Version 1.0 (the "License"); you may not use this file
+ * except in compliance with the License. You may obtain a copy of
+ * the License at http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Software distributed under the License is distributed on an "AS
+ * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
+ * implied. See the License for the specific language governing
+ * rights and limitations under the License.
+ *
+ * Copyright (C) 2009 Yoko Harada <yokolet@gmail.com>
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either of the GNU General Public License Version 2 or later (the "GPL"),
+ * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the CPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the CPL, the GPL or the LGPL.
+ * **** END LICENSE BLOCK *****
+ */
+package org.jruby.embed.io;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.io.Writer;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.Charset;
+import java.nio.charset.CharsetDecoder;
+import java.nio.charset.CoderResult;
+import java.nio.charset.CodingErrorAction;
+
+/**
+ * A WriterOutputStream converts java.io.Writer to java.io.OutputStream.
+ *
+ * @author Yoko Harada <yokolet@gmail.com>
+ */
+public class WriterOutputStream extends OutputStream {
+
+ private final Writer writer;
+ private boolean isOpen = true;
+ private CharsetDecoder decoder;
+
+ /**
+ * Creates WriterOutputStream from given java.io.Writer object with a default encoding.
+ *
+ * @param writer java.io.Writer object to be converted to.
+ */
+ public WriterOutputStream(Writer writer) {
+ this(writer, null);
+ }
+
+ /**
+ * Creates WriterOutputStream from given java.io.Writer object with a specified encoding.
+ *
+ * @param writer java.io.Writer object to be converted to.
+ */
+ public WriterOutputStream(Writer writer, String encoding) {
+ this.writer = writer;
+ if (encoding == null && writer instanceof OutputStreamWriter) {
+ // this encoding might be null when writer has been closed
+ encoding = ((OutputStreamWriter) writer).getEncoding();
+ }
+ if (encoding == null) {
+ encoding = Charset.defaultCharset().name();
+ } else if (!Charset.isSupported(encoding)) {
+ throw new IllegalArgumentException(encoding + " is not supported");
+ }
+ decoder = Charset.forName(encoding).newDecoder();
+ decoder.onMalformedInput(CodingErrorAction.REPLACE);
+ decoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
+ }
+
+ /**
+ * Closes this output stream and releases any system resources
+ * associated with this stream. The general contract of <code>close</code>
+ * is that it closes the output stream. A closed stream cannot perform
+ * output operations and cannot be reopened.
+ * <p>
+ *
+ * @exception IOException if an I/O error occurs.
+ */
+ @Override
+ public void close() throws IOException {
+ synchronized (writer) {
+ if (!isOpen) {
+ throw new IOException("This stream has been already closed.");
+ }
+ isOpen = false;
+ decoder = null;
+ writer.close();
+ }
+ }
+
+ /**
+ * Flushes this output stream and forces any buffered output bytes
+ * to be written out. The general contract of <code>flush</code> is
+ * that calling it is an indication that, if any bytes previously
+ * written have been buffered by the implementation of the output
+ * stream, such bytes should immediately be written to their
+ * intended destination.
+ * <p>
+ * If the intended destination of this stream is an abstraction provided by
+ * the underlying operating system, for example a file, then flushing the
+ * stream guarantees only that bytes previously written to the stream are
+ * passed to the operating system for writing; it does not guarantee that
+ * they are actually written to a physical device such as a disk drive.
+ * <p>
+ *
+ * @exception IOException if an I/O error occurs.
+ */
+ @Override
+ public void flush() throws IOException {
+ synchronized (writer) {
+ if (!isOpen) {
+ return;
+ }
+ writer.flush();
+ }
+ }
+
+ /**
+ * Writes the specified byte to this output stream. The general
+ * contract for <code>write</code> is that one byte is written
+ * to the output stream. The byte to be written is the eight
+ * low-order bits of the argument <code>b</code>. The 24
+ * high-order bits of <code>b</code> are ignored.
+ *
+ * @param b the <code>byte</code>.
+ * @exception IOException if an I/O error occurs. In particular,
+ * an <code>IOException</code> may be thrown if the
+ * output stream has been closed.
+ */
+ @Override
+ public void write(int b) throws IOException {
+ byte[] bb = new byte[]{(byte) b};
+ write(bb, 0, 1);
+ }
+
+ /**
+ * Writes <code>b.length</code> bytes from the specified byte array
+ * to this output stream. The general contract for <code>write(b)</code>
+ * is that it should have exactly the same effect as the call
+ * <code>write(b, 0, b.length)</code>.
+ *
+ * @param b the data.
+ * @exception IOException if an I/O error occurs.
+ * @see java.io.OutputStream#write(byte[], int, int)
+ */
+ @Override
+ public void write(byte[] b) throws IOException {
+ write(b, 0, b.length);
+ }
+
+ /**
+ * Writes <code>len</code> bytes from the specified byte array
+ * starting at offset <code>off</code> to this output stream.
+ * The general contract for <code>write(b, off, len)</code> is that
+ * some of the bytes in the array <code>b</code> are written to the
+ * output stream in order; element <code>b[off]</code> is the first
+ * byte written and <code>b[off+len-1]</code> is the last byte written
+ * by this operation.
+ * <p>
+ * If <code>off</code> is negative, or <code>len</code> is negative, or
+ * <code>off+len</code> is greater than the length of the array
+ * <code>b</code>, then an <tt>IndexOutOfBoundsException</tt> is thrown.
+ *
+ * @param b the data.
+ * @param off the start offset in the data.
+ * @param len the number of bytes to write.
+ * @exception IOException if an I/O error occurs. In particular,
+ * an <code>IOException</code> is thrown if the output
+ * stream is closed.
+ */
+ @Override
+ public void write(byte[] b, int off, int len) throws IOException {
+ synchronized (writer) {
+ if (!isOpen) {
+ return;
+ }
+ if (off < 0 || len <= 0 || (off + len) > b.length) {
+ throw new IndexOutOfBoundsException();
+ }
+ ByteBuffer bytes = ByteBuffer.wrap(b, off, len);
+ CharBuffer chars = CharBuffer.allocate(len);
+ byte2char(bytes, chars);
+ char[] cbuf = new char[chars.length()];
+ chars.get(cbuf, 0, chars.length());
+ writer.write(cbuf);
+ writer.flush();
+ }
+ }
+
+ private void byte2char(ByteBuffer bytes, CharBuffer chars) throws IOException {
+ decoder.reset();
+ chars.clear();
+ CoderResult result = decoder.decode(bytes, chars, true);
+ if (result.isError() || result.isOverflow()) {
+ throw new IOException(result.toString());
+ } else if (result.isUnderflow()) {
+ chars.flip();
+ }
+ }
+}
View
2  src/org/ruboto/Script.java
@@ -322,7 +322,7 @@ public static Boolean configDir(String scriptsDir) {
if (new File(scriptsDir).exists()) {
Log.i(TAG, "Found extra scripts dir: " + scriptsDir);
setDir(scriptsDir);
- exec("$:.unshift '" + scriptsDir + "' ; $:.uniq! ; p $:");
+ exec("$:.unshift '" + scriptsDir + "' ; $:.uniq!");
return true;
} else {
Log.i(TAG, "Extra scripts dir not present: " + scriptsDir);
View
1,411 src/org/ruboto/irb/IRB.java
@@ -1,6 +1,5 @@
package org.ruboto.irb;
-
-
+
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
@@ -45,678 +44,754 @@
import android.widget.TabWidget;
import android.widget.TextView;
import android.widget.Toast;
-
- public class IRB extends Activity implements OnItemClickListener, OnTabChangeListener {
- public static final String TAG = "Ruboto-IRB";
- public static final String SDCARD_SCRIPTS_DIR = "/sdcard/jruby";
-
- private TabHost tabs;
- private TabWidget tabWidget;
- private final Handler handler = new Handler();
-
- /* IRB_Tab Elements */
- public static TextView currentIrbOutput;
- private TextView irbOutput;
- private HistoryEditText irbInput;
-
- /* Edit_Tab Elements */
- private ScrollView scrollView;
- private LineNumberEditText sourceEditor;
- private TextView fnameTextView;
- private IRBScript currentScript;
-
- /* Script_Tab Elements */
- private ArrayAdapter<String> adapter;
- private List<String> scripts;
-
- /* Tab identifiers */
- private static final int IRB_TAB = 0;
- private static final int EDITOR_TAB = 1;
- private static final int SCRIPTS_TAB = 2;
-
- /* Menu option identifiers */
- private static final int SAVE_MENU = 1;
- private static final int RUN_MENU = 2;
- private static final int NEW_MENU = 3;
- private static final int HISTORY_MENU = 4;
- private static final int ABOUT_MENU = 5;
- private static final int RESCAN_MENU = 6;
- private static final int RELOAD_DEMOS_MENU = 7;
- private static final int CLEAR_IRB_MENU = 8;
- private static final int EDIT_IRB_MENU = 9;
- private static final int MAX_SCREEN_MENU = 10;
- private static final int LINE_NUMBERS_MENU = 11;
- private static final int GOTO_MENU = 12;
-
- /* Context menu option identifiers for script list */
- private static final int EDIT_MENU = 20;
- private static final int EXECUTE_MENU = 21;
- private static final int DELETE_MENU = 22;
-
- private static final String DEMO_SCRIPTS = "demo-scripts";
-
- /*********************************************************************************************
- *
- * Setup
- */
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
-
- SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
- if (prefs.getBoolean("HideTitle", false)) requestWindowFeature(Window.FEATURE_NO_TITLE);
- if (prefs.getBoolean("Fullscreen", false)) getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
-
- setContentView(R.layout.main);
-
- tabs = (TabHost) findViewById(R.id.tabhost);
- tabs.setOnTabChangedListener(this);
- tabs.setup();
-
- tabWidget = (TabWidget) findViewById(android.R.id.tabs);
- tabWidget.setVisibility(prefs.getBoolean("HideTabs", false) ? View.GONE : View.VISIBLE);
-
- irbSetUp();
- configScriptsDir();
- editorSetUp();
- scriptsListSetUp();
- setUpJRuby();
- }
-
- private void irbSetUp() {
- tabs.addTab(tabs.newTabSpec("irb")
- .setContent(R.id.tab1)
- .setIndicator(getString(R.string.IRB_Tab),
+
+public class IRB extends org.ruboto.EntryPointActivity implements OnItemClickListener,
+ OnTabChangeListener {
+ public static final String TAG = "Ruboto-IRB";
+ public static final String SDCARD_SCRIPTS_DIR = "/sdcard/jruby";
+
+ private TabHost tabs;
+ private TabWidget tabWidget;
+ private final Handler handler = new Handler();
+
+ /* IRB_Tab Elements */
+ public static TextView currentIrbOutput;
+ private TextView irbOutput;
+ private HistoryEditText irbInput;
+
+ /* Edit_Tab Elements */
+ private ScrollView scrollView;
+ private LineNumberEditText sourceEditor;
+ private TextView fnameTextView;
+ private IRBScript currentScript;
+
+ /* Script_Tab Elements */
+ private ArrayAdapter<String> adapter;
+ private List<String> scripts;
+
+ /* Tab identifiers */
+ private static final int IRB_TAB = 0;
+ private static final int EDITOR_TAB = 1;
+ private static final int SCRIPTS_TAB = 2;
+
+ /* Menu option identifiers */
+ private static final int SAVE_MENU = 1;
+ private static final int RUN_MENU = 2;
+ private static final int NEW_MENU = 3;
+ private static final int HISTORY_MENU = 4;
+ private static final int ABOUT_MENU = 5;
+ private static final int RESCAN_MENU = 6;
+ private static final int RELOAD_DEMOS_MENU = 7;
+ private static final int CLEAR_IRB_MENU = 8;
+ private static final int EDIT_IRB_MENU = 9;
+ private static final int MAX_SCREEN_MENU = 10;
+ private static final int LINE_NUMBERS_MENU = 11;
+ private static final int GOTO_MENU = 12;
+
+ /* Context menu option identifiers for script list */
+ private static final int EDIT_MENU = 20;
+ private static final int EXECUTE_MENU = 21;
+ private static final int DELETE_MENU = 22;
+
+ private static final String DEMO_SCRIPTS = "demo-scripts";
+
+ /*********************************************************************************************
+ *
+ * Setup
+ */
+
+ @Override
+ public void onCreate(Bundle savedInstanceState) {
+ setScriptName("irb.rb");
+ super.onCreate(savedInstanceState);
+
+ SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
+ if (prefs.getBoolean("HideTitle", false))
+ requestWindowFeature(Window.FEATURE_NO_TITLE);
+ if (prefs.getBoolean("Fullscreen", false))
+ getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
+
+ setContentView(R.layout.main);
+
+ tabs = (TabHost) findViewById(R.id.tabhost);
+ tabs.setOnTabChangedListener(this);
+ tabs.setup();
+
+ tabWidget = (TabWidget) findViewById(android.R.id.tabs);
+ tabWidget.setVisibility(prefs.getBoolean("HideTabs", false) ? View.GONE
+ : View.VISIBLE);
+
+ irbSetUp();
+ configScriptsDir();
+ editorSetUp();
+ scriptsListSetUp();
+ // setUpJRuby();
+ }
+
+ private void irbSetUp() {
+ tabs.addTab(tabs
+ .newTabSpec("irb")
+ .setContent(R.id.tab1)
+ .setIndicator(getString(R.string.IRB_Tab),
getResources().getDrawable(R.drawable.ic_tab_irb)));
-
- irbInput = (HistoryEditText) findViewById(R.id.irb_edittext);
- irbOutput = (TextView) findViewById(R.id.irb_textview);
- irbOutput.setMovementMethod(new android.text.method.ScrollingMovementMethod());
- currentIrbOutput = irbOutput;
-
- irbInput.setLineListener(new HistoryEditText.LineListener() {
- public void onNewLine(String rubyCode) {
- irbOutput.append(rubyCode + "\n");
- try {
- irbOutput.append("=> ");
- irbOutput.append(IRBScript.execute(rubyCode));
- } catch (RuntimeException e) {
- }
- irbOutput.append("\n>> ");
- irbInput.setText("");
- }
- });
- }
-
- private void editorSetUp() {
- tabs.addTab(tabs.newTabSpec("editor")
- .setContent(R.id.tab2)
- .setIndicator(getString(R.string.Editor_Tab),
+
+ irbInput = (HistoryEditText) findViewById(R.id.irb_edittext);
+ irbOutput = (TextView) findViewById(R.id.irb_textview);
+ irbOutput
+ .setMovementMethod(new android.text.method.ScrollingMovementMethod());
+ currentIrbOutput = irbOutput;
+
+ irbInput.setLineListener(new HistoryEditText.LineListener() {
+ public void onNewLine(String rubyCode) {
+ irbOutput.append(rubyCode + "\n");
+ try {
+ irbOutput.append("=> ");
+ irbOutput.append(IRBScript.execute(rubyCode));
+ } catch (RuntimeException e) {
+ }
+ irbOutput.append("\n>> ");
+ irbInput.setText("");
+ }
+ });
+ }
+
+ private void editorSetUp() {
+ tabs.addTab(tabs
+ .newTabSpec("editor")
+ .setContent(R.id.tab2)
+ .setIndicator(getString(R.string.Editor_Tab),
getResources().getDrawable(R.drawable.ic_tab_editor)));
-
- scrollView = (ScrollView) findViewById(R.id.editor_scroll_view);
- sourceEditor = (LineNumberEditText) findViewById(R.id.source_editor);
- fnameTextView = (TextView) findViewById(R.id.fname_textview);
-
- editScript(IRBScript.UNTITLED_RB, false);
- }
-
- private void scriptsListSetUp() {
- tabs.addTab(tabs.newTabSpec("scripts")
- .setContent(R.id.tab3)
- .setIndicator(getString(R.string.Scripts_Tab),
+
+ scrollView = (ScrollView) findViewById(R.id.editor_scroll_view);
+ sourceEditor = (LineNumberEditText) findViewById(R.id.source_editor);
+ fnameTextView = (TextView) findViewById(R.id.fname_textview);
+
+ editScript(IRBScript.UNTITLED_RB, false);
+ }
+
+ private void scriptsListSetUp() {
+ tabs.addTab(tabs
+ .newTabSpec("scripts")
+ .setContent(R.id.tab3)
+ .setIndicator(getString(R.string.Scripts_Tab),
getResources().getDrawable(R.drawable.ic_tab_scripts)));
- ListView scriptsList = (ListView) findViewById(R.id.scripts_listview);
-
- scripts = IRBScript.list();
- adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, scripts);
- scriptsList.setAdapter(adapter);
- TextView emptyView = new TextView(this);
- emptyView.setText(R.string.No_scripts);
- scriptsList.setEmptyView(emptyView);
- scriptsList.setOnItemClickListener(this);
- registerForContextMenu(scriptsList);
- }
-
- /* Initializes jruby in its own thread */
- private void setUpJRuby() {
- if (!IRBScript.isInitialized()) {
- IRBScript.setLocalVariableBehavior("PERSISTENT");
- irbOutput.append("Initializing JRuby...");
- new Thread("JRuby-init") {
- public void run() {
- // try to avoid ANR's
- Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
- IRBScript.setUpJRuby(IRB.this, new PrintStream(new WriterOutputStream(new Writer() {
- @Override
- public void write(final char[] chars, final int start, final int length) throws IOException {
- IRB.this.runOnUiThread(new Runnable() {
- public void run() {
- IRB.appendToIRB(new String(chars, start, length));
- }
- });
- }
- @Override
- public void flush() throws IOException {
- // no buffer
- }
- @Override
- public void close() throws IOException {
- // meaningless
- }
- })));
- handler.post(notifyComplete);
- }
- }.start();
- } else {
- notifyComplete.run();
- }
- }
-
- /* Called when jruby finishes loading */
- protected final Runnable notifyComplete = new Runnable() {
- public void run() {
- IRBScript.defineGlobalVariable("$context", IRB.this);
- IRBScript.defineGlobalVariable("$activity", IRB.this);
- irbOutput.append("Done\n>> ");
- configScriptsDir();
- autoLoadScript();
- }
- };
-
- /* Static method needed to get to the current irbOutput after the Activity reloads */
- public static void appendToIRB(String string) {
- currentIrbOutput.append(string);
- }
-
- /* Loads the script specified in the Intent (if supplied) */
- public void autoLoadScript() {
- if (getIntent().getData() != null) {
- IRBScript script = IRBScript.fromURL(getIntent().getData().toString());
- if (script != null) editScript(script, true);
+ ListView scriptsList = (ListView) findViewById(R.id.scripts_listview);
+
+ scripts = IRBScript.list();
+ adapter = new ArrayAdapter<String>(this,
+ android.R.layout.simple_list_item_1, scripts);
+ scriptsList.setAdapter(adapter);
+ TextView emptyView = new TextView(this);
+ emptyView.setText(R.string.No_scripts);
+ scriptsList.setEmptyView(emptyView);
+ scriptsList.setOnItemClickListener(this);
+ registerForContextMenu(scriptsList);
+ }
+
+ /* Initializes jruby in its own thread */
+ private void setUpJRuby() {
+ if (!IRBScript.isInitialized()) {
+ IRBScript.setLocalVariableBehavior("PERSISTENT");
+ irbOutput.append("Initializing JRuby...");
+ new Thread("JRuby-init") {
+ public void run() {
+ // try to avoid ANR's
+ Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
+ IRBScript.setUpJRuby(IRB.this, new PrintStream(
+ new WriterOutputStream(new Writer() {
+ @Override
+ public void write(final char[] chars,
+ final int start, final int length)
+ throws IOException {
+ IRB.this.runOnUiThread(new Runnable() {
+ public void run() {
+ IRB.appendToIRB(new String(chars,
+ start, length));
+ }
+ });
+ }
+
+ @Override
+ public void flush() throws IOException {
+ // no buffer
+ }
+
+ @Override
+ public void close() throws IOException {
+ // meaningless
+ }
+ })));
+ handler.post(notifyComplete);
+ }
+ }.start();
+ } else {
+ notifyComplete.run();
+ }
+ }
+
+ /* Called when jruby finishes loading */
+ protected final Runnable notifyComplete = new Runnable() {
+ public void run() {
+ IRBScript.defineGlobalVariable("$context", IRB.this);
+ IRBScript.defineGlobalVariable("$activity", IRB.this);
+ irbOutput.append("Done\n>> ");
+ configScriptsDir();
+ autoLoadScript();
+ }
+ };
+
+ /*
+ * Static method needed to get to the current irbOutput after the Activity
+ * reloads
+ */
+ public static void appendToIRB(String string) {
+ currentIrbOutput.append(string);
+ }
+
+ /* Loads the script specified in the Intent (if supplied) */
+ public void autoLoadScript() {
+ if (getIntent().getData() != null) {
+ IRBScript script = IRBScript.fromURL(getIntent().getData()
+ .toString());
+ if (script != null)
+ editScript(script, true);
+ }
+ }
+
+ /* Common method for copying stacktrace to irbOutput */
+ private void reportExecption(Exception e) {
+ // TODO: Compact or highlight some levels
+ for (java.lang.StackTraceElement ste : e.getStackTrace()) {
+ irbOutput.append(ste.toString() + "\n");
+ }
+ }
+
+ /*********************************************************************************************
+ *
+ * Saving and recalling state
+ */
+
+ @Override
+ public void onSaveInstanceState(Bundle savedInstanceState) {
+ super.onSaveInstanceState(savedInstanceState);
+ savedInstanceState.putCharSequence("irbOutput", irbOutput.getText());
+ irbInput.onSaveInstanceState(savedInstanceState);
+ savedInstanceState.putInt("tab", tabs.getCurrentTab());
+ savedInstanceState.putBoolean("lineNumbers",
+ sourceEditor.getShowLineNumbers());
+ }
+
+ @Override
+ public void onRestoreInstanceState(Bundle savedInstanceState) {
+ super.onRestoreInstanceState(savedInstanceState);
+ if (savedInstanceState.containsKey("irbOutput"))
+ irbOutput.setText(savedInstanceState.getCharSequence("irbOutput"));
+ irbInput.onRestoreInstanceState(savedInstanceState);
+ if (savedInstanceState.containsKey("tab"))
+ tabs.setCurrentTab(savedInstanceState.getInt("tab"));
+ if (savedInstanceState.containsKey("lineNumbers"))
+ sourceEditor.setShowLineNumbers(savedInstanceState
+ .getBoolean("lineNumbers"));
+ }
+
+ /*********************************************************************************************
+ *
+ * TabHost Listener
+ */
+
+ public void onTabChanged(String tabId) {
+ if (tabId.equals("scripts")) {
+ ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE))
+ .hideSoftInputFromWindow(tabs.getWindowToken(), 0);
+ if (IRBScript.scriptsDirChanged())
+ scanScripts();
+ }
+ }
+
+ /*********************************************************************************************
+ *
+ * Menu Setup
+ */
+
+ /* Set up context menus */
+ @Override
+ public boolean onCreateOptionsMenu(Menu menu) {
+ super.onCreateOptionsMenu(menu);
+ menu.add(0, SAVE_MENU, 0, R.string.Menu_save).setIcon(
+ android.R.drawable.ic_menu_save);
+ menu.add(0, RUN_MENU, 0, R.string.Menu_run).setIcon(
+ R.drawable.ic_menu_play);
+ menu.add(0, NEW_MENU, 0, R.string.Menu_new).setIcon(
+ android.R.drawable.ic_menu_add);
+ menu.add(0, HISTORY_MENU, 0, R.string.Menu_history).setIcon(
+ android.R.drawable.ic_menu_recent_history);
+ menu.add(0, ABOUT_MENU, 0, R.string.Menu_about).setIcon(
+ android.R.drawable.ic_menu_info_details);
+ menu.add(0, RESCAN_MENU, 0, R.string.Menu_rescan);
+ menu.add(0, RELOAD_DEMOS_MENU, 0, R.string.Menu_reload);
+ menu.add(0, CLEAR_IRB_MENU, 0, R.string.Menu_clear_irb);
+ menu.add(0, EDIT_IRB_MENU, 0, R.string.Menu_edit_irb);
+ menu.add(0, MAX_SCREEN_MENU, 0, R.string.Menu_max_screen);
+ menu.add(0, LINE_NUMBERS_MENU, 0, R.string.Menu_line_numbers);
+ menu.add(0, GOTO_MENU, 0, R.string.Menu_goto);
+ return true;
+ }
+
+ /* Called when a menu item clicked */
+ @Override
+ public boolean onMenuItemSelected(int featureId, MenuItem item) {
+ SharedPreferences prefs = null;
+ SharedPreferences.Editor prefsEditor = null;
+
+ switch (item.getItemId()) {
+ case SAVE_MENU:
+ saveEditorScript();
+ return true;
+ case RUN_MENU:
+ runEditorScript();
+ return true;
+ case NEW_MENU:
+ editScript(IRBScript.UNTITLED_RB, true);
+ return true;
+ case HISTORY_MENU:
+ editScript(
+ new IRBScript(IRBScript.UNTITLED_RB,
+ irbInput.getHistoryString()), true);
+ return true;
+ case ABOUT_MENU:
+ aboutDialog();
+ return true;
+ case RESCAN_MENU:
+ scanScripts();
+ tabs.setCurrentTab(SCRIPTS_TAB);
+ return true;
+ case RELOAD_DEMOS_MENU:
+ Toast.makeText(this,
+ recopyDemoScripts(DEMO_SCRIPTS, IRBScript.getDirFile()),
+ Toast.LENGTH_SHORT).show();
+ scanScripts();
+ tabs.setCurrentTab(SCRIPTS_TAB);
+ return true;
+ case CLEAR_IRB_MENU:
+ irbOutput.setText(">> ");
+ tabs.setCurrentTab(IRB_TAB);
+ return true;
+ case EDIT_IRB_MENU:
+ editScript(new IRBScript(IRBScript.UNTITLED_RB, irbOutput.getText()
+ .toString()), true);
+ tabs.setCurrentTab(EDITOR_TAB);
+ return true;
+ case MAX_SCREEN_MENU:
+ prefs = getPreferences(Context.MODE_PRIVATE);
+ prefsEditor = prefs.edit();
+
+ tabWidget
+ .setVisibility(tabWidget.getVisibility() == View.VISIBLE ? View.GONE
+ : View.VISIBLE);
+ if (prefs.getBoolean("Fullscreen", false)) {
+ getWindow().clearFlags(
+ WindowManager.LayoutParams.FLAG_FULLSCREEN);
+ } else {
+ getWindow()
+ .addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
- }
-
- /* Common method for copying stacktrace to irbOutput */
- private void reportExecption(Exception e) {
- // TODO: Compact or highlight some levels
- for (java.lang.StackTraceElement ste : e.getStackTrace()) {
- irbOutput.append(ste.toString() + "\n");
- }
- }
-
- /*********************************************************************************************
- *
- * Saving and recalling state
- */
-
- @Override
- public void onSaveInstanceState(Bundle savedInstanceState) {
- super.onSaveInstanceState(savedInstanceState);
- savedInstanceState.putCharSequence("irbOutput", irbOutput.getText());
- irbInput.onSaveInstanceState(savedInstanceState);
- savedInstanceState.putInt("tab", tabs.getCurrentTab());
- savedInstanceState.putBoolean("lineNumbers", sourceEditor.getShowLineNumbers());
- }
-
- @Override
- public void onRestoreInstanceState(Bundle savedInstanceState) {
- super.onRestoreInstanceState(savedInstanceState);
- if (savedInstanceState.containsKey("irbOutput"))
- irbOutput.setText(savedInstanceState.getCharSequence("irbOutput"));
- irbInput.onRestoreInstanceState(savedInstanceState);
- if (savedInstanceState.containsKey("tab")) tabs.setCurrentTab(savedInstanceState.getInt("tab"));
- if (savedInstanceState.containsKey("lineNumbers")) sourceEditor.setShowLineNumbers(savedInstanceState.getBoolean("lineNumbers"));
- }
-
- /*********************************************************************************************
- *
- * TabHost Listener
- */
-
- public void onTabChanged (String tabId) {
- if (tabId.equals("scripts") ) {
- ((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE))
- .hideSoftInputFromWindow(tabs.getWindowToken(), 0);
- if (IRBScript.scriptsDirChanged()) scanScripts();
- }
- }
-
- /*********************************************************************************************
- *
- * Menu Setup
- */
-
- /* Set up context menus */
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- super.onCreateOptionsMenu(menu);
- menu.add(0, SAVE_MENU, 0, R.string.Menu_save).setIcon(android.R.drawable.ic_menu_save);
- menu.add(0, RUN_MENU, 0, R.string.Menu_run).setIcon(R.drawable.ic_menu_play);
- menu.add(0, NEW_MENU, 0, R.string.Menu_new).setIcon(android.R.drawable.ic_menu_add);
- menu.add(0, HISTORY_MENU, 0, R.string.Menu_history).setIcon(android.R.drawable.ic_menu_recent_history);
- menu.add(0, ABOUT_MENU, 0, R.string.Menu_about).setIcon(android.R.drawable.ic_menu_info_details);
- menu.add(0, RESCAN_MENU, 0, R.string.Menu_rescan);
- menu.add(0, RELOAD_DEMOS_MENU, 0, R.string.Menu_reload);
- menu.add(0, CLEAR_IRB_MENU, 0, R.string.Menu_clear_irb);
- menu.add(0, EDIT_IRB_MENU, 0, R.string.Menu_edit_irb);
- menu.add(0, MAX_SCREEN_MENU, 0, R.string.Menu_max_screen);
- menu.add(0, LINE_NUMBERS_MENU, 0, R.string.Menu_line_numbers);
- menu.add(0, GOTO_MENU, 0, R.string.Menu_goto);
- return true;
- }
-
- /* Called when a menu item clicked */
- @Override
- public boolean onMenuItemSelected(int featureId, MenuItem item) {
- SharedPreferences prefs = null;
- SharedPreferences.Editor prefsEditor = null;
-
- switch (item.getItemId()) {
- case SAVE_MENU:
- saveEditorScript();
- return true;
- case RUN_MENU:
- runEditorScript();
- return true;
- case NEW_MENU:
- editScript(IRBScript.UNTITLED_RB, true);
- return true;
- case HISTORY_MENU:
- editScript(new IRBScript(IRBScript.UNTITLED_RB, irbInput.getHistoryString()), true);
- return true;
- case ABOUT_MENU:
- aboutDialog();
- return true;
- case RESCAN_MENU:
- scanScripts();
- tabs.setCurrentTab(SCRIPTS_TAB);
- return true;
- case RELOAD_DEMOS_MENU:
- Toast.makeText(this,
- recopyDemoScripts(DEMO_SCRIPTS, IRBScript.getDirFile()),
- Toast.LENGTH_SHORT).show();
- scanScripts();
- tabs.setCurrentTab(SCRIPTS_TAB);
- return true;
- case CLEAR_IRB_MENU:
- irbOutput.setText(">> ");
- tabs.setCurrentTab(IRB_TAB);
- return true;
- case EDIT_IRB_MENU:
- editScript(new IRBScript(IRBScript.UNTITLED_RB, irbOutput.getText().toString()), true);
- tabs.setCurrentTab(EDITOR_TAB);
- return true;
- case MAX_SCREEN_MENU:
- prefs = getPreferences(Context.MODE_PRIVATE);
- prefsEditor = prefs.edit();
-
- tabWidget.setVisibility(tabWidget.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
- if (prefs.getBoolean("Fullscreen", false)) {
- getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
- } else {
- getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
- }
-
- prefsEditor.putBoolean("HideTabs", tabWidget.getVisibility() == View.GONE);
- prefsEditor.putBoolean("Fullscreen", !prefs.getBoolean("Fullscreen", false));
- prefsEditor.putBoolean("HideTitle", !prefs.getBoolean("HideTitle", false));
- prefsEditor.commit();
-
- displayDialog("Title Visibility Change", "Reorient the screen for this to take effect.", null, null);
-
- return true;
- case LINE_NUMBERS_MENU:
- sourceEditor.setShowLineNumbers(!sourceEditor.getShowLineNumbers());
- tabs.setCurrentTab(EDITOR_TAB);
- return true;
- case GOTO_MENU:
- tabs.setCurrentTab(EDITOR_TAB);
- gotoDialog();
- return true;
- }
-
- return super.onMenuItemSelected(featureId, item);
- }
-
- /* Set up context menus for script list */
- @Override
- public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
- super.onCreateContextMenu(menu, v, menuInfo);
- menu.add(0, EDIT_MENU, 0, R.string.Menu_edit);
- menu.add(0, EXECUTE_MENU, 0, R.string.Menu_run);
- menu.add(0, DELETE_MENU, 0, R.string.Menu_delete);
- }
-
- /* Called when an entry in the Script List is long clicked */
- public boolean onContextItemSelected(MenuItem item) {
- switch (item.getItemId()) {
- case EDIT_MENU:
- editScript(scripts.get(((AdapterContextMenuInfo) item.getMenuInfo()).position), true);
- return true;
- case EXECUTE_MENU:
- executeScript(scripts.get(((AdapterContextMenuInfo) item.getMenuInfo()).position));
- return true;
- case DELETE_MENU:
- confirmDelete(scripts.get(((AdapterContextMenuInfo) item.getMenuInfo()).position));
- return true;
- default:
- return false;
- }
- }
-
- /* Called when an entry in the Script List is clicked */
- public void onItemClick(AdapterView<?> av, View v, int pos, long id) {
- editScript(scripts.get(pos), true);
- }
-
- /************************************************************************************
- *
- * Script actions
- */
-
- /* Reload the list of scripts */
- private void scanScripts() {
- try {
- scripts = IRBScript.list(scripts);
- adapter.notifyDataSetChanged();
- }
- catch (SecurityException se) {
- Toast.makeText(this, "Could not create " + IRBScript.getDir(), Toast.LENGTH_SHORT);
- }
- }
-
- /* Run the script currently in the editor */
- private void runEditorScript() {
- irbOutput.append("[Running editor script (" + currentScript.getName() + ")]\n");
- try {
- irbOutput.append("=> ");
- irbOutput.append(IRBScript.execute(sourceEditor.getText().toString()));
- } catch (RuntimeException e) {
- reportExecption(e);
- }
- irbOutput.append("\n>> ");
-
- tabs.setCurrentTab(IRB_TAB);
- }
-
- /* Save the script currently in the editor */
- private void saveEditorScript() {
- try {
- IRBScript tmp = (IRBScript)(currentScript.setName(fnameTextView.getText().toString()));
- tmp.setContents(sourceEditor.getText().toString()).save();
- scanScripts();
- Toast.makeText(this, "Saved " + currentScript.getName(), Toast.LENGTH_SHORT).show();
- tabs.setCurrentTab(SCRIPTS_TAB);
- }
- catch (IOException e) {
- Toast.makeText(this, "Could not write " + currentScript.getName(), Toast.LENGTH_SHORT).show();
- }
- }
-
- /* Load script into editor and switch to editor view */
- private void editScript(IRBScript script, Boolean switchTab) {
- try {
- currentScript = script;
- fnameTextView.setText(script.getName());
- sourceEditor.setText(script.getFile().exists() ? script.getContents() : "");
- scrollView.scrollTo(0, 0);
- if (switchTab) tabs.setCurrentTab(EDITOR_TAB);
- } catch (IOException e) {
- Toast.makeText(this, "Could not open " + script.getName(), Toast.LENGTH_SHORT).show();
- }
- }
-
- private void editScript(String name, Boolean switchTab) {
- editScript(new IRBScript(name), switchTab);
- }
-
- /* Execute the script and switch to IRB tab*/
- private void executeScript(String name) {
- try {
- irbOutput.append("[Running " + name + "]\n");
- irbOutput.append("=> ");
- irbOutput.append(new IRBScript(name).execute());
- } catch (IOException e) {
- Toast.makeText(this, "Could not open " + name, Toast.LENGTH_SHORT).show();
- } catch (RuntimeException e) {
- reportExecption(e);
- }
- irbOutput.append("\n>> ");
-
- tabs.setCurrentTab(IRB_TAB);
- }
-
- /* Delete script and reload scripts list */
- private void deleteScript(String fname) {
- if (new IRBScript(fname).delete()) {
- Toast.makeText(this, fname + " deleted!", Toast.LENGTH_SHORT).show();
- } else {
- Toast.makeText(this, "Could not delete " + fname, Toast.LENGTH_SHORT).show();
- }
- scanScripts();
- }
-
- /************************************************************************************
- *
- * Dialogs
- */
-
- /*
- * Generic dialogs
- */
-
- private void displayDialog(String title, Object messageOrView,
- DialogInterface.OnClickListener positive, DialogInterface.OnClickListener negative) {
- AlertDialog.Builder builder = new AlertDialog.Builder(this);
- builder.setTitle(title);
- if (messageOrView instanceof String) {
- builder.setMessage((String)messageOrView);
- } else {
- builder.setView((View)messageOrView);
- }
- if (positive == null) {
- builder.setPositiveButton(R.string.Dialog_ok, new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int id) {}
- });
- } else {
- builder.setPositiveButton(R.string.Dialog_ok, positive);
- }
- if (negative != null) {
- builder.setNegativeButton(R.string.Dialog_cancel, negative);
- }
- builder.create().show();
- }
-
- /*
- * Script deletion dialog
- */
- private void confirmDelete(final String fname) {
- displayDialog("Confirm", "Delete " + fname + "?",
- new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int id) {deleteScript(fname);}
- },
- new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int id) {dialog.cancel();}
- });
- }
-
- /*
- * About dialog
- */
-
- private void aboutDialog() {
- ScrollView sv = new ScrollView(this);
- TextView tv = new TextView(this);
- tv.setPadding(5, 5, 5, 5);
- tv.setText(R.string.About_text);
- Linkify.addLinks(tv, Linkify.ALL);
- sv.addView(tv);
-
- displayDialog(getString(R.string.app_name) + " v " + getString(R.string.version_name), sv, null, null);
- }
-
- /*
- * Goto dialog
- */
-
- private void gotoDialog() {
- final EditText et = new EditText(this);
-
- displayDialog("Go to", et,
+
+ prefsEditor.putBoolean("HideTabs",
+ tabWidget.getVisibility() == View.GONE);
+ prefsEditor.putBoolean("Fullscreen",
+ !prefs.getBoolean("Fullscreen", false));
+ prefsEditor.putBoolean("HideTitle",
+ !prefs.getBoolean("HideTitle", false));
+ prefsEditor.commit();
+
+ displayDialog("Title Visibility Change",
+ "Reorient the screen for this to take effect.", null, null);
+
+ return true;
+ case LINE_NUMBERS_MENU:
+ sourceEditor.setShowLineNumbers(!sourceEditor.getShowLineNumbers());
+ tabs.setCurrentTab(EDITOR_TAB);
+ return true;
+ case GOTO_MENU:
+ tabs.setCurrentTab(EDITOR_TAB);
+ gotoDialog();
+ return true;
+ }
+
+ return super.onMenuItemSelected(featureId, item);
+ }
+
+ /* Set up context menus for script list */
+ @Override
+ public void onCreateContextMenu(ContextMenu menu, View v,
+ ContextMenuInfo menuInfo) {
+ super.onCreateContextMenu(menu, v, menuInfo);
+ menu.add(0, EDIT_MENU, 0, R.string.Menu_edit);
+ menu.add(0, EXECUTE_MENU, 0, R.string.Menu_run);
+ menu.add(0, DELETE_MENU, 0, R.string.Menu_delete);
+ }
+
+ /* Called when an entry in the Script List is long clicked */
+ public boolean onContextItemSelected(MenuItem item) {
+ switch (item.getItemId()) {
+ case EDIT_MENU:
+ editScript(
+ scripts.get(((AdapterContextMenuInfo) item.getMenuInfo()).position),
+ true);
+ return true;
+ case EXECUTE_MENU:
+ executeScript(scripts.get(((AdapterContextMenuInfo) item
+ .getMenuInfo()).position));
+ return true;
+ case DELETE_MENU:
+ confirmDelete(scripts.get(((AdapterContextMenuInfo) item
+ .getMenuInfo()).position));
+ return true;
+ default:
+ return false;
+ }
+ }
+
+ /* Called when an entry in the Script List is clicked */
+ public void onItemClick(AdapterView<?> av, View v, int pos, long id) {
+ editScript(scripts.get(pos), true);
+ }
+
+ /************************************************************************************
+ *
+ * Script actions
+ */
+
+ /* Reload the list of scripts */
+ private void scanScripts() {
+ try {
+ scripts = IRBScript.list(scripts);
+ adapter.notifyDataSetChanged();
+ } catch (SecurityException se) {
+ Toast.makeText(this, "Could not create " + IRBScript.getDir(),
+ Toast.LENGTH_SHORT);
+ }
+ }
+
+ /* Run the script currently in the editor */
+ private void runEditorScript() {
+ irbOutput.append("[Running editor script (" + currentScript.getName()
+ + ")]\n");
+ try {
+ irbOutput.append("=> ");
+ irbOutput.append(IRBScript.execute(sourceEditor.getText()
+ .toString()));
+ } catch (RuntimeException e) {
+ reportExecption(e);
+ }
+ irbOutput.append("\n>> ");
+
+ tabs.setCurrentTab(IRB_TAB);
+ }
+
+ /* Save the script currently in the editor */
+ private void saveEditorScript() {
+ try {
+ IRBScript tmp = (IRBScript) (currentScript.setName(fnameTextView
+ .getText().toString()));
+ tmp.setContents(sourceEditor.getText().toString()).save();
+ scanScripts();
+ Toast.makeText(this, "Saved " + currentScript.getName(),
+ Toast.LENGTH_SHORT).show();
+ tabs.setCurrentTab(SCRIPTS_TAB);
+ } catch (IOException e) {
+ Toast.makeText(this, "Could not write " + currentScript.getName(),
+ Toast.LENGTH_SHORT).show();
+ }
+ }
+
+ /* Load script into editor and switch to editor view */
+ private void editScript(IRBScript script, Boolean switchTab) {
+ try {
+ currentScript = script;
+ fnameTextView.setText(script.getName());
+ sourceEditor.setText(script.getFile().exists() ? script
+ .getContents() : "");
+ scrollView.scrollTo(0, 0);
+ if (switchTab)
+ tabs.setCurrentTab(EDITOR_TAB);
+ } catch (IOException e) {
+ Toast.makeText(this, "Could not open " + script.getName(),
+ Toast.LENGTH_SHORT).show();
+ }
+ }
+
+ private void editScript(String name, Boolean switchTab) {
+ editScript(new IRBScript(name), switchTab);
+ }
+
+ /* Execute the script and switch to IRB tab */
+ private void executeScript(String name) {
+ try {
+ irbOutput.append("[Running " + name + "]\n");
+ irbOutput.append("=> ");
+ irbOutput.append(new IRBScript(name).execute());
+ } catch (IOException e) {
+ Toast.makeText(this, "Could not open " + name, Toast.LENGTH_SHORT)
+ .show();
+ } catch (RuntimeException e) {
+ reportExecption(e);
+ }
+ irbOutput.append("\n>> ");
+
+ tabs.setCurrentTab(IRB_TAB);
+ }
+
+ /* Delete script and reload scripts list */
+ private void deleteScript(String fname) {
+ if (new IRBScript(fname).delete()) {
+ Toast.makeText(this, fname + " deleted!", Toast.LENGTH_SHORT)
+ .show();
+ } else {
+ Toast.makeText(this, "Could not delete " + fname,
+ Toast.LENGTH_SHORT).show();
+ }
+ scanScripts();
+ }
+
+ /************************************************************************************
+ *
+ * Dialogs
+ */
+
+ /*
+ * Generic dialogs
+ */
+
+ private void displayDialog(String title, Object messageOrView,
+ DialogInterface.OnClickListener positive,
+ DialogInterface.OnClickListener negative) {
+ AlertDialog.Builder builder = new AlertDialog.Builder(this);
+ builder.setTitle(title);
+ if (messageOrView instanceof String) {
+ builder.setMessage((String) messageOrView);
+ } else {
+ builder.setView((View) messageOrView);
+ }
+ if (positive == null) {
+ builder.setPositiveButton(R.string.Dialog_ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
- try {
- int i = Integer.valueOf(et.getText().toString());
- scrollView.scrollTo(0, (i-1) * sourceEditor.getLineHeight());
- } catch (Exception e) {}
}
- },
- new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int id) {dialog.cancel();}
- });
- }
-
- /*********************************************************************************************
- *
- * Activity Results: Make activity result available to Ruby
- */
-
- @Override
- public void onActivityResult(int requestCode, int resultCode, Intent data) {
- super.onActivityResult(requestCode, resultCode, data);
- IRBScript.defineGlobalVariable("$last_activity_result", new ActivityResult(requestCode, resultCode, data));
- }
-
- public static class ActivityResult {
- public int requestCode, resultCode;
- public Intent data;
-
- public ActivityResult(int req, int res, Intent dat) {
- requestCode = req;
- resultCode = res;
- data = dat;
- }
- }
-
- protected static String scriptsDirName(Activity context) {
- if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
- return Environment.getExternalStorageDirectory().getAbsolutePath() + "/jruby";
- } else {
- return context.getFilesDir().getAbsolutePath() + "/scripts";
- }
- }
-
- private void configScriptsDir() {
- IRBScript.setDir(IRB.scriptsDirName(this));
- if (!IRBScript.getDirFile().exists()) {
- // on first install init directory + copy sample scripts
- copyDemoScripts(DEMO_SCRIPTS, IRBScript.getDirFile());
- } else if (!checkVersionString()) {
- // Scripts exist but need updating
- confirmUpdate();
- }
- }
-
- private void copyDemoScripts(String from, File to) {
- IRBScript.getDirFile().mkdirs();
- try {
- byte[] buffer = new byte[8192];
- for (String f : getAssets().list(from)) {
- File dest = new File(to, f);
-
- if (dest.exists())
- continue;
-
- Log.d(TAG, "copying file " + f);
-
- if (getAssets().list(from + "/" + f).length == 0) {
- InputStream is = getAssets().open(from+ "/" +f);
- OutputStream fos = new BufferedOutputStream(new FileOutputStream(dest), 8192);
-
- int n;
- while ((n = is.read(buffer, 0, buffer.length)) != -1)
- fos.write(buffer, 0, n);
-
- is.close();
- fos.close();
- } else {
- dest.mkdir();
- copyDemoScripts(from + "/" + f, dest);
- }
- }
-
- updateVersionString();
- } catch (IOException iox) {
- Log.e(TAG, "error copying demo scripts", iox);
- }
- }
-
- public String recopyDemoScripts(String from, File to) {
- String rv = "";
- try {
- byte[] buffer = new byte[8192];
- for (String f : getAssets().list(from)) {
- File dest = new File(to, f);
-
- if (dest.exists()) {
- Log.d(TAG, "replacing file " + f);
- } else {
- Log.d(TAG, "copying file " + f);
- }
-
- if (getAssets().list(from + "/" + f).length == 0) {
- InputStream is = getAssets().open(from+ "/" +f);
- OutputStream fos = new BufferedOutputStream(new FileOutputStream(dest), 8192);
-
- int n;
- while ((n = is.read(buffer, 0, buffer.length)) != -1)
- fos.write(buffer, 0, n);
-
- is.close();
- fos.close();
- rv += "\nCopied:" + f;
- } else {
- dest.mkdir();
- rv += "\n" + recopyDemoScripts(from + "/" + f, dest);
- }
- }
-
- updateVersionString();
- } catch (IOException iox) {
- Log.e(TAG, "error copying demo scripts", iox);
- rv = "Copy failed";
- }
- return rv;
- }
-
- private boolean checkVersionString() {
- return getPreferences(Context.MODE_PRIVATE).
- getString("Ruboto_script_version", "0").
- equals(getString(R.string.ruboto_script_version));
- }
-
- private void updateVersionString() {
- if (!checkVersionString()) {
- SharedPreferences.Editor prefsEditor = getPreferences(Context.MODE_PRIVATE).edit();
- prefsEditor.putString("Ruboto_script_version", getString(R.string.ruboto_script_version));
- prefsEditor.commit();
- }
- }
-
- private void confirmUpdate() {
- displayDialog("Update Scripts", getString(R.string.Script_update_text),
- new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int id) {
- Toast.makeText(IRB.this,
- IRB.this.recopyDemoScripts(DEMO_SCRIPTS, IRBScript.getDirFile()),
- Toast.LENGTH_SHORT).show();
- }
- },
- new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int id) {dialog.cancel();}
- });
- }
+ });
+ } else {
+ builder.setPositiveButton(R.string.Dialog_ok, positive);
+ }
+ if (negative != null) {
+ builder.setNegativeButton(R.string.Dialog_cancel, negative);
+ }
+ builder.create().show();
+ }
+
+ /*
+ * Script deletion dialog
+ */
+ private void confirmDelete(final String fname) {
+ displayDialog("Confirm", "Delete " + fname + "?",
+ new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog, int id) {
+ deleteScript(fname);
+ }
+ }, new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog, int id) {
+ dialog.cancel();
+ }
+ });
+ }
+
+ /*
+ * About dialog
+ */
+
+ private void aboutDialog() {
+ ScrollView sv = new ScrollView(this);
+ TextView tv = new TextView(this);
+ tv.setPadding(5, 5, 5, 5);
+ tv.setText(R.string.About_text);
+ Linkify.addLinks(tv, Linkify.ALL);
+ sv.addView(tv);
+
+ displayDialog(getString(R.string.app_name) + " v "
+ + getString(R.string.version_name), sv, null, null);
+ }
+
+ /*
+ * Goto dialog
+ */
+
+ private void gotoDialog() {
+ final EditText et = new EditText(this);
+
+ displayDialog("Go to", et, new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog, int id) {
+ try {
+ int i = Integer.valueOf(et.getText().toString());
+ scrollView.scrollTo(0,
+ (i - 1) * sourceEditor.getLineHeight());
+ } catch (Exception e) {
+ }
+ }
+ }, new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog, int id) {
+ dialog.cancel();
+ }
+ });
+ }
+
+ /*********************************************************************************************
+ *
+ * Activity Results: Make activity result available to Ruby
+ */
+
+ @Override
+ public void onActivityResult(int requestCode, int resultCode, Intent data) {
+ super.onActivityResult(requestCode, resultCode, data);
+ IRBScript.defineGlobalVariable("$last_activity_result",
+ new ActivityResult(requestCode, resultCode, data));
+ }
+
+ public static class ActivityResult {
+ public int requestCode, resultCode;
+ public Intent data;
+
+ public ActivityResult(int req, int res, Intent dat) {
+ requestCode = req;
+ resultCode = res;
+ data = dat;
+ }
+ }
+
+ protected static String scriptsDirName(Activity context) {
+ if (Environment.getExternalStorageState().equals(
+ Environment.MEDIA_MOUNTED)) {
+ return Environment.getExternalStorageDirectory().getAbsolutePath()
+ + "/jruby";
+ } else {
+ return context.getFilesDir().getAbsolutePath() + "/scripts";
+ }
+ }
+
+ private void configScriptsDir() {
+ IRBScript.setDir(IRB.scriptsDirName(this));
+ if (!IRBScript.getDirFile().exists()) {
+ // on first install init directory + copy sample scripts
+ copyDemoScripts(DEMO_SCRIPTS, IRBScript.getDirFile());
+ } else if (!checkVersionString()) {
+ // Scripts exist but need updating
+ confirmUpdate();
+ }
+ }
+
+ private void copyDemoScripts(String from, File to) {
+ IRBScript.getDirFile().mkdirs();
+ try {
+ byte[] buffer = new byte[8192];
+ for (String f : getAssets().list(from)) {
+ File dest = new File(to, f);
+
+ if (dest.exists())
+ continue;
+
+ Log.d(TAG, "copying file " + f);
+
+ if (getAssets().list(from + "/" + f).length == 0) {
+ InputStream is = getAssets().open(from + "/" + f);
+ OutputStream fos = new BufferedOutputStream(
+ new FileOutputStream(dest), 8192);
+
+ int n;
+ while ((n = is.read(buffer, 0, buffer.length)) != -1)
+ fos.write(buffer, 0, n);
+
+ is.close();
+ fos.close();
+ } else {
+ dest.mkdir();
+ copyDemoScripts(from + "/" + f, dest);
+ }
+ }
+
+ updateVersionString();
+ } catch (IOException iox) {
+ Log.e(TAG, "error copying demo scripts", iox);
+ }
+ }
+
+ public String recopyDemoScripts(String from, File to) {
+ String rv = "";
+ try {
+ byte[] buffer = new byte[8192];
+ for (String f : getAssets().list(from)) {
+ File dest = new File(to, f);
+
+ if (dest.exists()) {
+ Log.d(TAG, "replacing file " + f);
+ } else {
+ Log.d(TAG, "copying file " + f);
+ }
+
+ if (getAssets().list(from + "/" + f).length == 0) {
+ InputStream is = getAssets().open(from + "/" + f);
+ OutputStream fos = new BufferedOutputStream(
+ new FileOutputStream(dest), 8192);
+
+ int n;
+ while ((n = is.read(buffer, 0, buffer.length)) != -1)
+ fos.write(buffer, 0, n);
+
+ is.close();
+ fos.close();
+ rv += "\nCopied:" + f;
+ } else {
+ dest.mkdir();
+ rv += "\n" + recopyDemoScripts(from + "/" + f, dest);
+ }
+ }
+
+ updateVersionString();
+ } catch (IOException iox) {
+ Log.e(TAG, "error copying demo scripts", iox);
+ rv = "Copy failed";
+ }
+ return rv;
+ }
+
+ private boolean checkVersionString() {
+ return getPreferences(Context.MODE_PRIVATE).getString(
+ "Ruboto_script_version", "0").equals(
+ getString(R.string.ruboto_script_version));
+ }
+
+ private void updateVersionString() {
+ if (!checkVersionString()) {
+ SharedPreferences.Editor prefsEditor = getPreferences(
+ Context.MODE_PRIVATE).edit();
+ prefsEditor.putString("Ruboto_script_version",
+ getString(R.string.ruboto_script_version));
+ prefsEditor.commit();
+ }
+ }
+
+ private void confirmUpdate() {
+ displayDialog("Update Scripts", getString(R.string.Script_update_text),
+ new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog, int id) {
+ Toast.makeText(
+ IRB.this,
+ IRB.this.recopyDemoScripts(DEMO_SCRIPTS,
+ IRBScript.getDirFile()),
+ Toast.LENGTH_SHORT).show();
+ }
+ }, new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog, int id) {
+ dialog.cancel();
+ }
+ });
}
+}
View
2  src/ruboto/service.rb
@@ -26,7 +26,7 @@ def initialize_ruboto()
self
end
- def start_ruboto_service(global_variable_name, klass=RubotoService, &block)
+ def start_ruboto_service(global_variable_name = '$service', klass=RubotoService, &block)
$context_init_block = block
$new_context_global = global_variable_name
View
2  src/ruboto/version.rb
@@ -1,3 +1,3 @@
module Ruboto
- VERSION = '0.5.3.dev'
+ VERSION = '0.5.3'
end
View
21 test/src/irb_test.rb
@@ -0,0 +1,21 @@
+activity Java::org.ruboto.irb.IRB
+
+setup do |activity|
+ start = Time.now
+ loop do
+ @text_view = activity.findViewById(42)
+ break if @text_view || (Time.now - start > 60)
+ sleep 1
+ end
+ assert @text_view
+end
+
+test('initial setup') do |activity|
+ assert_equal "What hath Matz wrought?", @text_view.text
+end
+
+test('button changes text') do |activity|
+ button = activity.findViewById(43)
+ button.performClick
+ assert_equal "What hath Matz wrought!", @text_view.text
+end
View
8 test/src/org/ruboto/test/ActivityTest.java
@@ -2,7 +2,6 @@
import android.app.Activity;
import android.app.ProgressDialog;
-import android.content.Intent;
import android.test.ActivityInstrumentationTestCase2;
import android.util.Log;
import java.io.BufferedReader;
@@ -17,14 +16,12 @@
import org.ruboto.Script;
public class ActivityTest extends ActivityInstrumentationTestCase2 {
- private final String script;
private final Object setup;
private final Object block;
private final String filename;
- public ActivityTest(Class activityClass, String script, String filename, Object setup, String name, Object block) {
+ public ActivityTest(Class activityClass, String filename, Object setup, String name, Object block) {
super(activityClass.getPackage().getName(), activityClass);
- this.script = script;
this.filename = filename;
this.setup = setup;
setName(filename + "#" + name);
@@ -35,9 +32,6 @@ public ActivityTest(Class activityClass, String script, String filename, Object
public void runTest() throws Exception {
Log.i(getClass().getName(), "runTest");
Log.i(getClass().getName(), "runTest: " + getName());
- Intent i = new Intent();
- i.putExtra("org.ruboto.extra.SCRIPT_NAME", script);
- setActivityIntent(i);
if (Script.setUpJRuby(getActivity())) {
Log.i(getClass().getName(), "ruby ok");
try {
View
6 test/src/org/ruboto/test/InstrumentationTestRunner.java
@@ -28,7 +28,6 @@
public class InstrumentationTestRunner extends android.test.InstrumentationTestRunner {
private Class activityClass;
- private String script;
private Object setup;
private TestSuite suite;
@@ -69,9 +68,8 @@ public TestSuite getAllTests() {
return suite;
}
- public void activity(Class activityClass, String script) {
+ public void activity(Class activityClass) {
this.activityClass = activityClass;
- this.script = script;
}
public void setup(Object block) {
@@ -82,7 +80,7 @@ public void test(String name, Object block) {
if (android.os.Build.VERSION.SDK_INT <= 8) {
name ="runTest";
}
- Test test = new ActivityTest(activityClass, script, Script.getScriptFilename(), setup, name, block);
+ Test test = new ActivityTest(activityClass, Script.getScriptFilename(), setup, name, block);
suite.addTest(test);
Log.d(getClass().getName(), "Made test instance: " + test);
}
Please sign in to comment.
Something went wrong with that request. Please try again.