Debian Codegraph @

rhino/toolsrc/org/mozilla/javascript/tools/shell/ShellConsole.java

raw symbols SCIP
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 package org.mozilla.javascript.tools.shell;
6
7 import java.io.BufferedReader;
8 import java.io.IOException;
9 import java.io.InputStream;
10 import java.io.InputStreamReader;
11 import java.io.PrintStream;
12 import java.io.PrintWriter;
13 import java.lang.reflect.Constructor;
14 import java.lang.reflect.InvocationTargetException;
15 import java.lang.reflect.Method;
16 import java.lang.reflect.Proxy;
17 import java.nio.charset.Charset;
18 import java.util.List;
19
20 import org.mozilla.javascript.Function;
21 import org.mozilla.javascript.Kit;
22 import org.mozilla.javascript.Scriptable;
23 import org.mozilla.javascript.ScriptableObject;
24
25 /**
26 *
27 * @author André Bargull
28 */
29 public abstract class ShellConsole {
30
31 private final static Class[] NO_ARG = {};
32 private final static Class[] BOOLEAN_ARG = {Boolean.TYPE};
33 private final static Class[] STRING_ARG = {String.class};
34 private final static Class[] CHARSEQ_ARG = {CharSequence.class};
35
36 protected ShellConsole() {
37 }
38
39 /**
40 * Returns the underlying {@link InputStream}
41 */
42 public abstract InputStream getIn();
43
44 /**
45 * Reads a single line from the console
46 */
47 public abstract String readLine() throws IOException;
48
49 /**
50 * Reads a single line from the console and sets the console's prompt to
51 * {@code prompt}
52 */
53 public abstract String readLine(String prompt) throws IOException;
54
55 /**
56 * Flushes the console's output
57 */
58 public abstract void flush() throws IOException;
59
60 /**
61 * Prints a single string to the console
62 */
63 public abstract void print(String s) throws IOException;
64
65 /**
66 * Prints the newline character-sequence to the console
67 */
68 public abstract void println() throws IOException;
69
70 /**
71 * Prints a string and the newline character-sequence to the console
72 */
73 public abstract void println(String s) throws IOException;
74
75
76 private static Object tryInvoke(Object obj, String method,
77 Class[] paramTypes, Object... args) {
78 try {
79 Method m = obj.getClass().getDeclaredMethod(method, paramTypes);
80 if (m != null) {
81 return m.invoke(obj, args);
82 }
83 } catch (NoSuchMethodException e) {
84 } catch (IllegalArgumentException e) {
85 } catch (IllegalAccessException e) {
86 } catch (InvocationTargetException e) {
87 }
88 return null;
89 }
90
91 /**
92 * {@link ShellConsole} implementation for JLine v1
93 */
94 private static class JLineShellConsoleV1 extends ShellConsole {
95 private final Object reader;
96 private final InputStream in;
97
98 JLineShellConsoleV1(Object reader, Charset cs) {
99 this.reader = reader;
100 this.in = new ConsoleInputStream(this, cs);
101 }
102
103 @Override
104 public InputStream getIn() {
105 return in;
106 }
107
108 @Override
109 public String readLine() throws IOException {
110 return (String) tryInvoke(reader, "readLine", NO_ARG);
111 }
112
113 @Override
114 public String readLine(String prompt) throws IOException {
115 return (String) tryInvoke(reader, "readLine", STRING_ARG, prompt);
116 }
117
118 @Override
119 public void flush() throws IOException {
120 tryInvoke(reader, "flushConsole", NO_ARG);
121 }
122
123 @Override
124 public void print(String s) throws IOException {
125 tryInvoke(reader, "printString", STRING_ARG, s);
126 }
127
128 @Override
129 public void println() throws IOException {
130 tryInvoke(reader, "printNewline", NO_ARG);
131 }
132
133 @Override
134 public void println(String s) throws IOException {
135 tryInvoke(reader, "printString", STRING_ARG, s);
136 tryInvoke(reader, "printNewline", NO_ARG);
137 }
138 }
139
140 /**
141 * {@link ShellConsole} implementation for JLine v2
142 */
143 private static class JLineShellConsoleV2 extends ShellConsole {
144 private final Object reader;
145 private final InputStream in;
146
147 JLineShellConsoleV2(Object reader, Charset cs) {
148 this.reader = reader;
149 this.in = new ConsoleInputStream(this, cs);
150 }
151
152 @Override
153 public InputStream getIn() {
154 return in;
155 }
156
157 @Override
158 public String readLine() throws IOException {
159 return (String) tryInvoke(reader, "readLine", NO_ARG);
160 }
161
162 @Override
163 public String readLine(String prompt) throws IOException {
164 return (String) tryInvoke(reader, "readLine", STRING_ARG, prompt);
165 }
166
167 @Override
168 public void flush() throws IOException {
169 tryInvoke(reader, "flush", NO_ARG);
170 }
171
172 @Override
173 public void print(String s) throws IOException {
174 tryInvoke(reader, "print", CHARSEQ_ARG, s);
175 }
176
177 @Override
178 public void println() throws IOException {
179 tryInvoke(reader, "println", NO_ARG);
180 }
181
182 @Override
183 public void println(String s) throws IOException {
184 tryInvoke(reader, "println", CHARSEQ_ARG, s);
185 }
186 }
187
188 /**
189 * JLine's ConsoleReaderInputStream is no longer public, therefore we need
190 * to use our own implementation
191 */
192 private static class ConsoleInputStream extends InputStream {
193 private static final byte[] EMPTY = new byte[] {};
194 private final ShellConsole console;
195 private final Charset cs;
196 private byte[] buffer = EMPTY;
197 private int cursor = -1;
198 private boolean atEOF = false;
199
200 public ConsoleInputStream(ShellConsole console, Charset cs) {
201 this.console = console;
202 this.cs = cs;
203 }
204
205 @Override
206 public synchronized int read(byte[] b, int off, int len)
207 throws IOException {
208 if (b == null) {
209 throw new NullPointerException();
210 } else if (off < 0 || len < 0 || len > b.length - off) {
211 throw new IndexOutOfBoundsException();
212 } else if (len == 0) {
213 return 0;
214 }
215 if (!ensureInput()) {
216 return -1;
217 }
218 int n = Math.min(len, buffer.length - cursor);
219 for (int i = 0; i < n; ++i) {
220 b[off + i] = buffer[cursor + i];
221 }
222 if (n < len) {
223 b[off + n++] = '\n';
224 }
225 cursor += n;
226 return n;
227 }
228
229 @Override
230 public synchronized int read() throws IOException {
231 if (!ensureInput()) {
232 return -1;
233 }
234 if (cursor == buffer.length) {
235 cursor++;
236 return '\n';
237 }
238 return buffer[cursor++];
239 }
240
241 private boolean ensureInput() throws IOException {
242 if (atEOF) {
243 return false;
244 }
245 if (cursor < 0 || cursor > buffer.length) {
246 if (readNextLine() == -1) {
247 atEOF = true;
248 return false;
249 }
250 cursor = 0;
251 }
252 return true;
253 }
254
255 private int readNextLine() throws IOException {
256 String line = console.readLine(null);
257 if (line != null) {
258 buffer = line.getBytes(cs);
259 return buffer.length;
260 } else {
261 buffer = EMPTY;
262 return -1;
263 }
264 }
265 }
266
267 private static class SimpleShellConsole extends ShellConsole {
268 private final InputStream in;
269 private final PrintWriter out;
270 private final BufferedReader reader;
271
272 SimpleShellConsole(InputStream in, PrintStream ps, Charset cs) {
273 this.in = in;
274 this.out = new PrintWriter(ps);
275 this.reader = new BufferedReader(new InputStreamReader(in, cs));
276 }
277
278 @Override
279 public InputStream getIn() {
280 return in;
281 }
282
283 @Override
284 public String readLine() throws IOException {
285 return reader.readLine();
286 }
287
288 @Override
289 public String readLine(String prompt) throws IOException {
290 if (prompt != null) {
291 out.write(prompt);
292 out.flush();
293 }
294 return reader.readLine();
295 }
296
297 @Override
298 public void flush() throws IOException {
299 out.flush();
300 }
301
302 @Override
303 public void print(String s) throws IOException {
304 out.print(s);
305 }
306
307 @Override
308 public void println() throws IOException {
309 out.println();
310 }
311
312 @Override
313 public void println(String s) throws IOException {
314 out.println(s);
315 }
316 }
317
318 /**
319 * Returns a new {@link ShellConsole} which uses the supplied
320 * {@link InputStream} and {@link PrintStream} for its input/output
321 */
322 public static ShellConsole getConsole(InputStream in, PrintStream ps,
323 Charset cs) {
324 return new SimpleShellConsole(in, ps, cs);
325 }
326
327 /**
328 * Provides a specialized {@link ShellConsole} to handle line editing,
329 * history and completion. Relies on the JLine library (see
330 * <http://jline.sourceforge.net>).
331 */
332 public static ShellConsole getConsole(Scriptable scope, Charset cs) {
333 // We don't want a compile-time dependency on the JLine jar, so use
334 // reflection to load and reference the JLine classes.
335 ClassLoader classLoader = ShellConsole.class.getClassLoader();
336 if (classLoader == null) {
337 // If the attempt to get a class specific class loader above failed
338 // then fallback to the system class loader.
339 classLoader = ClassLoader.getSystemClassLoader();
340 }
341 if (classLoader == null) {
342 // If for some reason we still don't have a handle to a class
343 // loader then give up (avoid a NullPointerException).
344 return null;
345 }
346 try {
347 // first try to load JLine v2...
348 Class<?> readerClass = Kit.classOrNull(classLoader,
349 "jline.console.ConsoleReader");
350 if (readerClass != null) {
351 return getJLineShellConsoleV2(classLoader, readerClass, scope, cs);
352 }
353 // ...if that fails, try to load JLine v1
354 readerClass = Kit.classOrNull(classLoader, "jline.ConsoleReader");
355 if (readerClass != null) {
356 return getJLineShellConsoleV1(classLoader, readerClass, scope, cs);
357 }
358 } catch (NoSuchMethodException e) {
359 } catch (IllegalAccessException e) {
360 } catch (InstantiationException e) {
361 } catch (InvocationTargetException e) {
362 }
363 return null;
364 }
365
366 private static JLineShellConsoleV1 getJLineShellConsoleV1(
367 ClassLoader classLoader, Class<?> readerClass, Scriptable scope,
368 Charset cs) throws NoSuchMethodException, InstantiationException,
369 IllegalAccessException, InvocationTargetException {
370 // ConsoleReader reader = new ConsoleReader();
371 Constructor<?> c = readerClass.getConstructor();
372 Object reader = c.newInstance();
373
374 // reader.setBellEnabled(false);
375 tryInvoke(reader, "setBellEnabled", BOOLEAN_ARG, Boolean.FALSE);
376
377 // reader.addCompletor(new FlexibleCompletor(prefixes));
378 Class<?> completorClass = Kit.classOrNull(classLoader,
379 "jline.Completor");
380 Object completor = Proxy.newProxyInstance(classLoader,
381 new Class[] { completorClass },
382 new FlexibleCompletor(completorClass, scope));
383 tryInvoke(reader, "addCompletor", new Class[] {completorClass}, completor);
384
385 return new JLineShellConsoleV1(reader, cs);
386 }
387
388 private static JLineShellConsoleV2 getJLineShellConsoleV2(
389 ClassLoader classLoader, Class<?> readerClass, Scriptable scope,
390 Charset cs) throws NoSuchMethodException, InstantiationException,
391 IllegalAccessException, InvocationTargetException {
392 // ConsoleReader reader = new ConsoleReader();
393 Constructor<?> c = readerClass.getConstructor();
394 Object reader = c.newInstance();
395
396 // reader.setBellEnabled(false);
397 tryInvoke(reader, "setBellEnabled", BOOLEAN_ARG, Boolean.FALSE);
398
399 // reader.addCompleter(new FlexibleCompletor(prefixes));
400 Class<?> completorClass = Kit.classOrNull(classLoader,
401 "jline.console.completer.Completer");
402 Object completor = Proxy.newProxyInstance(classLoader,
403 new Class[] { completorClass },
404 new FlexibleCompletor(completorClass, scope));
405 tryInvoke(reader, "addCompleter", new Class[] {completorClass}, completor);
406
407 return new JLineShellConsoleV2(reader, cs);
408 }
409 }
410
411 /**
412 * The completors provided with JLine are pretty uptight, they only
413 * complete on a line that it can fully recognize (only composed of
414 * completed strings). This one completes whatever came before.
415 */
416 class FlexibleCompletor implements java.lang.reflect.InvocationHandler {
417 private Method completeMethod;
418 private Scriptable global;
419
420 FlexibleCompletor(Class<?> completorClass, Scriptable global)
421 throws NoSuchMethodException
422 {
423 this.global = global;
424 this.completeMethod = completorClass.getMethod("complete", String.class,
425 Integer.TYPE, List.class);
426 }
427
428 @SuppressWarnings({"unchecked"})
429 public Object invoke(Object proxy, Method method, Object[] args) {
430 if (method.equals(this.completeMethod)) {
431 int result = complete((String)args[0], ((Integer) args[1]).intValue(),
432 (List<String>) args[2]);
433 return Integer.valueOf(result);
434 }
435 throw new NoSuchMethodError(method.toString());
436 }
437
438 public int complete(String buffer, int cursor, List<String> candidates) {
439 // Starting from "cursor" at the end of the buffer, look backward
440 // and collect a list of identifiers separated by (possibly zero)
441 // dots. Then look up each identifier in turn until getting to the
442 // last, presumably incomplete fragment. Then enumerate all the
443 // properties of the last object and find any that have the
444 // fragment as a prefix and return those for autocompletion.
445 int m = cursor - 1;
446 while (m >= 0) {
447 char c = buffer.charAt(m);
448 if (!Character.isJavaIdentifierPart(c) && c != '.')
449 break;
450 m--;
451 }
452 String namesAndDots = buffer.substring(m+1, cursor);
453 String[] names = namesAndDots.split("\\.", -1);
454 Scriptable obj = this.global;
455 for (int i=0; i < names.length - 1; i++) {
456 Object val = obj.get(names[i], global);
457 if (val instanceof Scriptable)
458 obj = (Scriptable) val;
459 else {
460 return buffer.length(); // no matches
461 }
462 }
463 Object[] ids = (obj instanceof ScriptableObject)
464 ? ((ScriptableObject)obj).getAllIds()
465 : obj.getIds();
466 String lastPart = names[names.length-1];
467 for (int i=0; i < ids.length; i++) {
468 if (!(ids[i] instanceof String))
469 continue;
470 String id = (String)ids[i];
471 if (id.startsWith(lastPart)) {
472 if (obj.get(id, obj) instanceof Function)
473 id += "(";
474 candidates.add(id);
475 }
476 }
477 return buffer.length() - lastPart.length();
478 }
479 }