1 package org.vaadin.console;
3 import java.io.ByteArrayOutputStream;
4 import java.io.IOException;
5 import java.io.OutputStream;
6 import java.io.PrintStream;
7 import java.io.Serializable;
8 import java.util.ArrayList;
9 import java.util.Collections;
10 import java.util.HashMap;
11 import java.util.HashSet;
12 import java.util.List;
16 import org.vaadin.rpc.ServerSideHandler;
17 import org.vaadin.rpc.ServerSideProxy;
18 import org.vaadin.rpc.client.Method;
20 import com.vaadin.terminal.PaintException;
21 import com.vaadin.terminal.PaintTarget;
22 import com.vaadin.ui.AbstractComponent;
23 import com.vaadin.ui.Component;
26 * Server side component for the VTextConsole widget.
28 * @author Sami Ekblad / Vaadin
31 @com.vaadin.ui.ClientWidget(org.vaadin.console.client.ui.VTextConsole.class)
32 public class Console extends AbstractComponent implements Component.Focusable {
34 private static final long serialVersionUID = 590258219352859644L;
35 private Handler handler;
36 private final HashMap<String, Command> commands = new HashMap<String, Command>();
37 private final Config config = new Config();
39 private static final String DEFAULT_PS = "}> ";
40 private static final String DEFAULT_GREETING = "Console ready.";
41 private static final int DEFAULT_BUFFER = 0;
42 private static final int DEFAULT_COLS = -1;
43 private static final int DEFAULT_ROWS = -1;
44 private static final boolean DEFAULT_WRAP = true;
45 private static final int MAX_COLS = 500;
46 private static final int MAX_ROWS = 200;
48 public boolean isWrap() {
52 public void setWrap(final boolean wrap) {
54 client.call("setWrap", wrap);
57 private final ServerSideProxy client = new ServerSideProxy(
58 new ClientCallback());
61 * Inner class to handle client calls.
64 public class ClientCallback implements ServerSideHandler {
66 private static final long serialVersionUID = 3992611573500588703L;
68 public void requestRepaint() {
69 Console.this.requestRepaint();
72 public Object[] initRequestFromClient() {
73 return new Object[] { config.cols, config.rows,
74 config.maxBufferSize, config.wrap, config.greeting,
78 public void callFromClient(String method, Object[] params) {
79 // TODO Auto-generated method stub
86 * The tab order number of this field.
88 private int tabIndex = 0;
89 @SuppressWarnings("unused")
90 private Integer fontw;
91 @SuppressWarnings("unused")
92 private Integer fonth;
93 private PrintStream printStream;
94 private String lastSuggestInput;
95 private List<CommandProvider> commandProviders;
98 * An inner class for holding the configuration data.
100 public static class Config implements Serializable {
102 private static final long serialVersionUID = -812601232248504108L;
104 int maxBufferSize = DEFAULT_BUFFER;
105 int cols = DEFAULT_COLS;
106 int rows = DEFAULT_ROWS;
107 boolean wrap = DEFAULT_WRAP;
108 String ps = DEFAULT_PS;
109 String greeting = DEFAULT_GREETING;
114 * Console Handler interface.
116 * Handler provides a hook to handle various console related events and
117 * override the default processing.
120 public interface Handler extends Serializable {
123 * Called when user uses TAB to complete the command entered into the
130 Set<String> getSuggestions(Console console, String lastInput);
133 * Called when user has entered input to the Console and presses enter
139 void inputReceived(Console console, String lastInput);
142 * Handle an exception during a Command execution.
149 void handleException(Console console, Exception e, Command cmd,
153 * Handle situation where a command could not be found.
158 void commandNotFound(Console console, String[] argv);
163 * Commands that can be executed against the Component instance. They
164 * provide convenient string to method mapping. Basically, a Command is a
165 * method that that can be executed in Component. It can have parameters or
169 public interface Command extends Serializable {
172 * Execute a Command with arguments.
179 public Object execute(Console console, String[] argv) throws Exception;
182 * Get usage information about this command.
188 public String getUsage(Console console, String[] argv);
192 * Interface for providing Commands to the console. One can register a
193 * command providers to console instead of individual commands to provide a
197 public interface CommandProvider extends Serializable {
200 * List all available command from this provider.
205 Set<String> getAvailableCommands(Console console);
208 * Get Command instance based on command name.
214 Command getCommand(Console console, String commandName);
218 public void addCommandProvider(final CommandProvider commandProvider) {
219 if (commandProviders == null) {
220 commandProviders = new ArrayList<CommandProvider>();
222 commandProviders.add(commandProvider);
225 public void removeCommandProvider(final CommandProvider commandProvider) {
226 if (commandProviders == null) {
229 commandProviders.remove(commandProvider);
232 public void removeAllCommandProviders() {
233 if (commandProviders == null) {
236 commandProviders.clear();
239 public Console(final Console.Handler handler) {
246 setHandler(new DefaultConsoleHandler());
250 private void registerCallbacks() {
251 client.register("suggest", new Method() {
253 public void invoke(String methodName, Object[] params) {
254 handleSuggest((String) params[0]);
257 client.register("input", new Method() {
259 public void invoke(String methodName, Object[] params) {
260 handleInput((String) params[0]);
267 public void paintContent(final PaintTarget target) throws PaintException {
268 super.paintContent(target);
269 client.paintContent(target);
273 public void changeVariables(final Object source,
274 final Map<String, Object> variables) {
275 super.changeVariables(source, variables);
276 client.changeVariables(source, variables);
277 if (variables.containsKey("width")) {
278 setWidth((String) variables.get("width"));
280 if (variables.containsKey("height")) {
281 setHeight((String) variables.get("height"));
283 if (variables.containsKey("fontw")) {
284 fontw = (Integer) variables.get("fontw");
286 if (variables.containsKey("fonth")) {
287 fonth = (Integer) variables.get("fonth");
289 if (variables.containsKey("cols")) {
290 config.cols = (Integer) variables.get("cols");
292 if (variables.containsKey("rows")) {
293 config.rows = (Integer) variables.get("rows");
298 * Overridden to filter client-side calculation/changes and avoid loops.
302 public void setWidth(float width, int unit) {
303 if (width != getWidth() || unit != getWidthUnits()) {
304 super.setWidth(width, unit);
309 * Overridden to filter client-side calculation/changes and avoid loops.
313 public void setHeight(float height, int unit) {
314 if (height != getHeight() || unit != getHeightUnits()) {
315 super.setHeight(height, unit);
319 protected void handleSuggest(final String input) {
321 final boolean cancelIfNotASingleMatch = (input != null && !input
322 .equals(lastSuggestInput));
323 lastSuggestInput = input;
325 final Set<String> matches = handler.getSuggestions(this, input);
327 if (matches == null || matches.size() == 0) {
332 // Output the original
333 final String prefix = parseCommandPrefix(input);
334 String output = input.substring(0, input.lastIndexOf(prefix));
335 if (matches.size() == 1) {
336 // Output the only match
337 output += matches.iterator().next() + " "; // append the single
341 // We output until the common prefix
342 StringBuilder commonPrefix = new StringBuilder(prefix);
343 final int maxLen = matches.iterator().next().length();
344 for (int i = prefix.length(); i < maxLen; i++) {
346 boolean charMatch = true;
347 for (final String m : matches) {
350 } else if (i < m.length()) {
351 charMatch &= m.charAt(i) == c;
361 commonPrefix.append(c);
364 output += commonPrefix.toString();
365 if (prefix.equals(commonPrefix.toString())
366 && !cancelIfNotASingleMatch) {
367 final StringBuffer suggestions = new StringBuffer("\n");
368 for (final String m : matches) {
369 suggestions.append(" " + m);
371 print(suggestions.toString());
374 lastSuggestInput = output; // next suggest will not beep
386 protected void handleInput(final String input) {
388 // Ask registered handler
389 handler.inputReceived(this, input);
393 protected void parseAndExecuteCommand(final String input) {
394 final String[] argv = parseInput(input);
395 if (argv != null && argv.length > 0) {
396 final Command c = getCommand(argv[0]);
398 final String result = executeCommand(c, argv);
399 if (result != null) {
403 handler.commandNotFound(this, argv);
408 protected String executeCommand(final Command cmd, final String[] argv) {
410 final Object r = cmd.execute(this, argv);
411 return r != null ? "" + r : null;
412 } catch (final Exception e) {
413 handler.handleException(this, e, cmd, argv);
418 protected String parseCommandPrefix(final String input) {
422 if (!input.endsWith(" ")) {
423 final String[] argv = parseInput(input);
424 if (argv != null && argv.length > 0) {
425 return argv[argv.length - 1];
431 protected static String[] parseInput(final String input) {
432 if (input != null && !"".equals(input.trim())) {
433 final String[] temp = input.split(" ");
434 if (temp != null && temp.length > 0) {
435 final List<String> parsed = new ArrayList<String>(temp.length);
436 String current = null;
437 for (final String element : temp) {
438 final int quotCount = count(element, '\"');
439 if (quotCount > 0 && quotCount % 2 != 0) {
440 // uneven number of quotes star or end combining params
441 if (current != null) {
442 parsed.add(current + " "
443 + element.replaceAll("\"", "")); // end
446 current = element.replaceAll("\"", ""); // start
448 } else if (current != null) {
449 current += " " + element.replaceAll("\"", "");
451 parsed.add(element.replaceAll("\"", ""));
455 // TODO: actually this is not quite right: We have an open quote
456 // somewhere. Exception maybe?
457 if (current != null) {
458 parsed.add(current.replaceAll("\"", ""));
460 return parsed.toArray(new String[] {});
463 return new String[] {};
466 protected static int count(final String sourceString, final char lookFor) {
467 if (sourceString == null) {
471 for (int i = 0; i < sourceString.length(); i++) {
472 final char c = sourceString.charAt(i);
480 public void print(final String output) {
481 client.call("print", output);
484 public String getGreeting() {
485 return config.greeting;
488 public String getPs() {
492 public int getMaxBufferSize() {
493 return config.maxBufferSize;
496 public int getRows() {
500 public void setGreeting(final String greeting) {
501 config.greeting = greeting;
502 client.call("setGreeting", greeting);
505 public void setPs(final String ps) {
506 config.ps = ps == null ? DEFAULT_PS : ps;
507 client.call("setPs", config.ps);
510 public void setMaxBufferSize(final int lines) {
511 config.maxBufferSize = lines > 0 ? lines : 0;
512 client.call("setMaxBufferSize", config.maxBufferSize);
515 public void setRows(final int rows) {
517 if (config.rows < 1) {
520 if (config.rows > MAX_ROWS) {
521 config.rows = MAX_ROWS;
523 client.call("setRows", rows);
526 public int getCols() {
530 public void setCols(final int cols) {
532 if (config.cols < 1) {
535 if (config.cols > MAX_COLS) {
536 config.cols = MAX_COLS;
538 client.call("setCols", config.cols);
541 public void prompt() {
542 client.call("prompt");
545 public void prompt(final String initialInput) {
546 client.call("prompt", initialInput);
549 public void println(final String string) {
550 client.call("println", string);
553 public void newLine() {
554 client.call("newLine");
557 public void reset() {
558 client.call("reset");
561 public void clear() {
565 public void formFeed() {
569 public void carriageReturn() {
573 public void lineFeed() {
577 public void clearCommandHistory() {
578 client.call("clearHistory");
581 public void clearBuffer() {
582 client.call("clearBuffer");
585 public void scrollToEnd() {
586 client.call("scrollToEnd");
590 * Gets the Tabulator index of this Focusable component.
592 * @see com.vaadin.ui.Component.Focusable#getTabIndex()
594 public int getTabIndex() {
599 * Sets the Tabulator index of this Focusable component.
601 * @see com.vaadin.ui.Component.Focusable#setTabIndex(int)
603 public void setTabIndex(final int tabIndex) {
604 this.tabIndex = tabIndex;
611 public void focus() {
615 /* PrintStream implementation for console output. */
617 public PrintStream getPrintStream() {
618 if (printStream == null) {
619 printStream = new PrintStream(new OutputStream() {
621 ByteArrayOutputStream buffer = new ByteArrayOutputStream();
624 public void write(final int b) throws IOException {
633 public void flush() throws IOException {
636 Console.this.print(buffer.toString());
644 /* Generic command handling */
647 * Add a Command to this Console.
649 * This will override the any commands of the same name available via
650 * {@link CommandProvider}.
652 public void addCommand(final String name, final Command cmd) {
653 commands.put(name, cmd);
657 * Remove a command from this console.
659 * This does not remove Command available from {@link CommandProvider}.
663 public void removeCommand(final String cmdName) {
664 commands.remove(cmdName);
668 * Get a Command by its name.
673 public Command getCommand(final String cmdName) {
675 // Try directly registered command first
676 Command cmd = commands.get(cmdName);
681 // Ask from the providers
682 if (commandProviders != null) {
683 for (final CommandProvider cp : commandProviders) {
684 cmd = cp.getCommand(this, cmdName);
696 * Get the current Console Handler.
700 public Handler getHandler() {
705 * Set the handler for this console.
710 public void setHandler(final Handler handler) {
711 this.handler = handler != null ? handler : new DefaultConsoleHandler();
715 * Get map of available commands in this Console.
719 public Set<String> getCommands() {
720 final Set<String> res = new HashSet<String>();
721 if (commandProviders != null) {
722 for (final CommandProvider cp : commandProviders) {
723 res.addAll(cp.getAvailableCommands(this));
726 res.addAll(commands.keySet());
727 return Collections.unmodifiableSet(res);