-
Notifications
You must be signed in to change notification settings - Fork 299
Expand file tree
/
Copy pathMain.java
More file actions
276 lines (242 loc) · 6.99 KB
/
Copy pathMain.java
File metadata and controls
276 lines (242 loc) · 6.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
package sk.kottman.androlua;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import org.keplerproject.luajava.JavaFunction;
import org.keplerproject.luajava.LuaException;
import org.keplerproject.luajava.LuaState;
import org.keplerproject.luajava.LuaStateFactory;
import android.app.Activity;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.util.*;
import android.os.Handler;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Main extends Activity implements OnClickListener,
OnLongClickListener {
private final static int LISTEN_PORT = 3333;
Button execute;
// public so we can play with these from Lua
public EditText source;
public TextView status;
public LuaState L;
final StringBuilder output = new StringBuilder();
Handler handler;
ServerThread serverThread;
private static byte[] readAll(InputStream input) throws Exception {
ByteArrayOutputStream output = new ByteArrayOutputStream(4096);
byte[] buffer = new byte[4096];
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
return output.toByteArray();
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
execute = (Button) findViewById(R.id.executeBtn);
execute.setOnClickListener(this);
source = (EditText) findViewById(R.id.source);
source.setOnLongClickListener(this);
source.setText("require 'import'\nprint(Math:sin(2.3))\n");
status = (TextView) findViewById(R.id.statusText);
status.setMovementMethod(ScrollingMovementMethod.getInstance());
status.setTextIsSelectable(true);
handler = new Handler();
L = LuaStateFactory.newLuaState();
L.openLibs();
try {
L.pushJavaObject(this);
L.setGlobal("activity");
JavaFunction print = new JavaFunction(L) {
@Override
public int execute() throws LuaException {
for (int i = 2; i <= L.getTop(); i++) {
int type = L.type(i);
String stype = L.typeName(type);
String val = null;
if (stype.equals("userdata")) {
Object obj = L.toJavaObject(i);
if (obj != null)
val = obj.toString();
} else if (stype.equals("boolean")) {
val = L.toBoolean(i) ? "true" : "false";
} else {
val = L.toString(i);
}
if (val == null)
val = stype;
output.append(val);
output.append("\t");
}
output.append("\n");
return 0;
}
};
print.register("print");
JavaFunction assetLoader = new JavaFunction(L) {
@Override
public int execute() throws LuaException {
String name = L.toString(-1);
AssetManager am = getAssets();
try {
InputStream is = am.open(name + ".lua");
byte[] bytes = readAll(is);
L.LloadBuffer(bytes, name);
return 1;
} catch (Exception e) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
e.printStackTrace(new PrintStream(os));
L.pushString("Cannot load module "+name+":\n"+os.toString());
return 1;
}
}
};
L.getGlobal("package"); // package
L.getField(-1, "loaders"); // package loaders
int nLoaders = L.objLen(-1); // package loaders
L.pushJavaFunction(assetLoader); // package loaders loader
L.rawSetI(-2, nLoaders + 1); // package loaders
L.pop(1); // package
L.getField(-1, "path"); // package path
String customPath = getFilesDir() + "/?.lua";
L.pushString(";" + customPath); // package path custom
L.concat(2); // package pathCustom
L.setField(-2, "path"); // package
L.pop(1);
} catch (Exception e) {
status.setText("Cannot override print");
}
}
@Override
protected void onResume() {
super.onResume();
serverThread = new ServerThread();
serverThread.start();
}
@Override
protected void onPause() {
super.onPause();
serverThread.stopped = true;
}
private class ServerThread extends Thread {
public boolean stopped;
@Override
public void run() {
stopped = false;
try {
ServerSocket server = new ServerSocket(LISTEN_PORT);
show("Server started on port " + LISTEN_PORT);
while (!stopped) {
Socket client = server.accept();
BufferedReader in = new BufferedReader(
new InputStreamReader(client.getInputStream()));
final PrintWriter out = new PrintWriter(client.getOutputStream());
String line = null;
while (!stopped && (line = in.readLine()) != null) {
final String s = line.replace('\001', '\n');
if (s.startsWith("--mod:")) {
int i1 = s.indexOf(':'), i2 = s.indexOf('\n');
String mod = s.substring(i1+1,i2);
String file = getFilesDir()+"/"+mod.replace('.', '/')+".lua";
FileWriter fw = new FileWriter(file);
fw.write(s);
fw.close();
// package.loaded[mod] = nil
L.getGlobal("package");
L.getField(-1, "loaded");
L.pushNil();
L.setField(-2, mod);
out.println("wrote " + file + "\n");
out.flush();
} else {
handler.post(new Runnable() {
public void run() {
String res = safeEvalLua(s);
res = res.replace('\n', '\001');
out.println(res);
out.flush();
}
});
}
}
}
server.close();
} catch (Exception e) {
show(e.toString());
}
}
private void show(final String s) {
handler.post(new Runnable() {
public void run() {
status.setText(s);
}
});
}
}
String safeEvalLua(String src) {
String res = null;
try {
res = evalLua(src);
} catch(LuaException e) {
res = e.getMessage()+"\n";
}
return res;
}
String evalLua(String src) throws LuaException {
L.setTop(0);
int ok = L.LloadString(src);
if (ok == 0) {
L.getGlobal("debug");
L.getField(-1, "traceback");
L.remove(-2);
L.insert(-2);
ok = L.pcall(0, 0, -2);
if (ok == 0) {
String res = output.toString();
output.setLength(0);
return res;
}
}
throw new LuaException(errorReason(ok) + ": " + L.toString(-1));
//return null;
}
public void onClick(View view) {
String src = source.getText().toString();
status.setText("");
try {
String res = evalLua(src);
status.append(res);
status.append("Finished succesfully");
} catch(LuaException e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
private String errorReason(int error) {
switch (error) {
case 4:
return "Out of memory";
case 3:
return "Syntax error";
case 2:
return "Runtime error";
case 1:
return "Yield error";
}
return "Unknown error " + error;
}
public boolean onLongClick(View view) {
source.setText("");
return true;
}
}