/
TiWebViewBinding.java
350 lines (308 loc) Β· 8.69 KB
/
TiWebViewBinding.java
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
/**
* Appcelerator Titanium Mobile
* Copyright (c) 2009-2012 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
package ti.modules.titanium.ui.widget.webview;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Stack;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.appcelerator.kroll.KrollDict;
import org.appcelerator.kroll.KrollEventCallback;
import org.appcelerator.kroll.KrollLogging;
import org.appcelerator.kroll.KrollModule;
import org.appcelerator.kroll.common.Log;
import org.appcelerator.titanium.TiApplication;
import org.appcelerator.titanium.TiContext;
import org.appcelerator.titanium.util.TiConvert;
import org.json.JSONException;
import org.json.JSONObject;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
public class TiWebViewBinding
{
private static final String TAG = "TiWebViewBinding";
// This is based on binding.min.js. If you have to change anything...
// - change binding.js
// - minify binding.js to create binding.min.js
protected final static String SCRIPT_INJECTION_ID = "__ti_injection";
protected final static String INJECTION_CODE;
protected final static String SCRIPT_TAG_INJECTION_CODE;
// This is based on polling.min.js. If you have to change anything...
// - change polling.js
// - minify polling.js to create polling.min.js
protected static String POLLING_CODE = "";
static {
StringBuilder jsonCode = readResourceFile("json2.js");
StringBuilder tiCode = readResourceFile("binding.min.js");
StringBuilder pollingCode = readResourceFile("polling.min.js");
if (pollingCode == null) {
Log.w(TAG, "Unable to read polling code");
} else {
POLLING_CODE = pollingCode.toString();
}
StringBuilder scriptCode = new StringBuilder();
StringBuilder injectionCode = new StringBuilder();
scriptCode.append("\n<script id=\"" + SCRIPT_INJECTION_ID + "\">\n");
if (jsonCode == null) {
Log.w(TAG, "Unable to read JSON code for injection");
} else {
scriptCode.append(jsonCode);
injectionCode.append(jsonCode);
}
if (tiCode == null) {
Log.w(TAG, "Unable to read Titanium binding code for injection");
} else {
scriptCode.append("\n");
scriptCode.append(tiCode.toString());
injectionCode.append(tiCode.toString());
}
scriptCode.append("\n</script>\n");
jsonCode = null;
tiCode = null;
SCRIPT_TAG_INJECTION_CODE = scriptCode.toString();
INJECTION_CODE = injectionCode.toString();
scriptCode = null;
injectionCode = null;
}
private Stack<String> codeSnippets;
private boolean destroyed;
private ApiBinding apiBinding;
private AppBinding appBinding;
public TiWebViewBinding(WebView webView)
{
codeSnippets = new Stack<String>();
apiBinding = new ApiBinding();
appBinding = new AppBinding();
webView.addJavascriptInterface(appBinding, "TiApp");
webView.addJavascriptInterface(apiBinding, "TiAPI");
webView.addJavascriptInterface(new TiReturn(), "_TiReturn");
}
public TiWebViewBinding(TiContext tiContext, WebView webView)
{
this(webView);
}
public void destroy()
{
// remove any event listener that have already been added to the Ti.APP through
// this web view instance
appBinding.clearEventListeners();
returnSemaphore.release();
codeSnippets.clear();
destroyed = true;
}
private static StringBuilder readResourceFile(String fileName)
{
InputStream stream = TiWebViewBinding.class.getClassLoader().getResourceAsStream(
"ti/modules/titanium/ui/widget/webview/" + fileName);
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
StringBuilder code = new StringBuilder();
try {
for (String line = reader.readLine(); line != null; line = reader.readLine()) {
code.append(line + "\n");
}
} catch (IOException e) {
Log.e(TAG, "Error reading input stream", e);
return null;
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
Log.w(TAG, "Problem closing input stream.", e);
}
}
}
return code;
}
private Semaphore returnSemaphore = new Semaphore(0);
private String returnValue;
synchronized public String getJSValue(String expression)
{
// Don't try to evaluate js code again if the binding has already been destroyed
if (!destroyed) {
// see if this is an expression or a statement block
// Match ; followed by 0 or even quotes
Pattern pattern = Pattern.compile(";(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
Matcher matcher = pattern.matcher(expression);
if (matcher.find()) {
String lastStmt = expression.substring(matcher.end(matcher.groupCount() - 1));
String stmtBlock = expression.substring(0, matcher.end(matcher.groupCount() - 1));
expression = stmtBlock + " return " + lastStmt;
} else {
expression = " return " + expression;
}
String code = "_TiReturn.setValue((function(){try{" + expression + "+\"\";}catch(ti_eval_err){return '';}})());";
Log.d(TAG, "getJSValue:" + code, Log.DEBUG_MODE);
returnSemaphore.drainPermits();
synchronized (codeSnippets) {
codeSnippets.push(code);
}
try {
if (!returnSemaphore.tryAcquire(3500, TimeUnit.MILLISECONDS)) {
synchronized (codeSnippets) {
codeSnippets.removeElement(code);
}
Log.w(TAG, "Timeout waiting to evaluate JS");
}
return returnValue;
} catch (InterruptedException e) {
Log.e(TAG, "Interrupted", e);
}
}
return null;
}
@SuppressWarnings("unused")
private class TiReturn
{
@JavascriptInterface
public void setValue(String value)
{
if (value != null) {
returnValue = value;
}
returnSemaphore.release();
}
}
private class WebViewCallback implements KrollEventCallback
{
private int id;
public WebViewCallback(int id)
{
this.id = id;
}
public void call(Object data)
{
String dataString;
if (data == null) {
dataString = "";
} else if (data instanceof HashMap) {
JSONObject json = TiConvert.toJSON((HashMap) data);
dataString = ", " + String.valueOf(json);
} else {
dataString = ", " + String.valueOf(data);
}
String code = "Ti.executeListener(" + id + dataString + ");";
synchronized (codeSnippets) {
codeSnippets.push(code);
}
}
}
@SuppressWarnings("unused")
private class AppBinding
{
private KrollModule module;
private HashMap<String, Integer> appListeners = new HashMap<String, Integer>();
private int counter = 0;
private String code = null;
public AppBinding()
{
module = TiApplication.getInstance().getModuleByName("App");
}
@JavascriptInterface
public void fireEvent(String event, String json)
{
try {
KrollDict dict = new KrollDict();
if (json != null && !json.equals("undefined")) {
dict = new KrollDict(new JSONObject(json));
}
module.fireEvent(event, dict);
} catch (JSONException e) {
Log.e(TAG, "Error parsing event JSON", e);
}
}
@JavascriptInterface
public int addEventListener(String event, int id)
{
WebViewCallback callback = new WebViewCallback(id);
int result = module.addEventListener(event, callback);
appListeners.put(event, result);
return result;
}
@JavascriptInterface
public void removeEventListener(String event, int id)
{
module.removeEventListener(event, id);
}
@JavascriptInterface
public void clearEventListeners()
{
for (String event : appListeners.keySet()) {
removeEventListener(event, appListeners.get(event));
}
}
@JavascriptInterface
public String getJSCode()
{
if (destroyed) {
return null;
}
return code;
}
@JavascriptInterface
public int hasResult()
{
if (destroyed) {
return -1;
}
int result = 0;
synchronized (codeSnippets) {
if(codeSnippets.empty()) {
code = "";
} else {
result = 1;
code = codeSnippets.pop();
}
}
return result;
}
}
@SuppressWarnings("unused")
private class ApiBinding
{
private KrollLogging logging;
public ApiBinding()
{
logging = KrollLogging.getDefault();
}
@JavascriptInterface
public void log(String level, String arg)
{
logging.log(level, arg);
}
@JavascriptInterface
public void info(String arg)
{
logging.info(arg);
}
@JavascriptInterface
public void debug(String arg)
{
logging.debug(arg);
}
@JavascriptInterface
public void error(String arg)
{
logging.error(arg);
}
@JavascriptInterface
public void trace(String arg)
{
logging.trace(arg);
}
@JavascriptInterface
public void warn(String arg)
{
logging.warn(arg);
}
}
}