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 boolean DEFAULT_PRINT_PROMPT_ON_INPUT= true;
46 private static final int MAX_COLS = 500;
47 private static final int MAX_ROWS = 200;
49 public boolean isWrap() {
53 public void setWrap(final boolean wrap) {
55 client.call("setWrap", wrap);
58 public boolean isPrintPromptOnInput(){
59 return config.isPrintPromptOnInput;
62 public void setPrintPromptOnInput(final boolean isPrintPromptOnInput){
63 config.isPrintPromptOnInput = isPrintPromptOnInput;
64 client.call("setPrintPromptOnInput", isPrintPromptOnInput);
67 private final ServerSideProxy client = new ServerSideProxy(
68 new ClientCallback());
71 * Inner class to handle client calls.
74 public class ClientCallback implements ServerSideHandler {
76 private static final long serialVersionUID = 3992611573500588703L;
78 public void requestRepaint() {
79 Console.this.requestRepaint();
82 public Object[] initRequestFromClient() {
83 return new Object[] { config.cols, config.rows,
84 config.maxBufferSize, config.wrap, config.isPrintPromptOnInput, config.greeting,
88 public void callFromClient(String method, Object[] params) {
89 // TODO Auto-generated method stub
96 * The tab order number of this field.
98 private int tabIndex = 0;
99 @SuppressWarnings("unused")
100 private Integer fontw;
101 @SuppressWarnings("unused")
102 private Integer fonth;
103 private PrintStream printStream;
104 private String lastSuggestInput;
105 private List<CommandProvider> commandProviders;
108 * An inner class for holding the configuration data.
110 public static class Config implements Serializable {
112 private static final long serialVersionUID = -812601232248504108L;
114 int maxBufferSize = DEFAULT_BUFFER;
115 int cols = DEFAULT_COLS;
116 int rows = DEFAULT_ROWS;
117 boolean wrap = DEFAULT_WRAP;
118 boolean isPrintPromptOnInput = DEFAULT_PRINT_PROMPT_ON_INPUT;
119 String ps = DEFAULT_PS;
120 String greeting = DEFAULT_GREETING;
125 * Console Handler interface.
127 * Handler provides a hook to handle various console related events and
128 * override the default processing.
131 public interface Handler extends Serializable {
134 * Called when user uses TAB to complete the command entered into the
141 Set<String> getSuggestions(Console console, String lastInput);
144 * Called when user has entered input to the Console and presses enter
150 void inputReceived(Console console, String lastInput);
153 * Handle an exception during a Command execution.
160 void handleException(Console console, Exception e, Command cmd,
164 * Handle situation where a command could not be found.
169 void commandNotFound(Console console, String[] argv);
174 * Commands that can be executed against the Component instance. They
175 * provide convenient string to method mapping. Basically, a Command is a
176 * method that that can be executed in Component. It can have parameters or
180 public interface Command extends Serializable {
183 * Execute a Command with arguments.
190 public Object execute(Console console, String[] argv) throws Exception;
193 * Get usage information about this command.
199 public String getUsage(Console console, String[] argv);
203 * Interface for providing Commands to the console. One can register a
204 * command providers to console instead of individual commands to provide a
208 public interface CommandProvider extends Serializable {
211 * List all available command from this provider.
216 Set<String> getAvailableCommands(Console console);
219 * Get Command instance based on command name.
225 Command getCommand(Console console, String commandName);
229 public void addCommandProvider(final CommandProvider commandProvider) {
230 if (commandProviders == null) {
231 commandProviders = new ArrayList<CommandProvider>();
233 commandProviders.add(commandProvider);
236 public void removeCommandProvider(final CommandProvider commandProvider) {
237 if (commandProviders == null) {
240 commandProviders.remove(commandProvider);
243 public void removeAllCommandProviders() {
244 if (commandProviders == null) {
247 commandProviders.clear();
250 public Console(final Console.Handler handler) {
257 setHandler(new DefaultConsoleHandler());
261 private void registerCallbacks() {
262 client.register("suggest", new Method() {
264 public void invoke(String methodName, Object[] params) {
265 handleSuggest((String) params[0]);
268 client.register("input", new Method() {
270 public void invoke(String methodName, Object[] params) {
271 handleInput((String) params[0]);
278 public void paintContent(final PaintTarget target) throws PaintException {
279 super.paintContent(target);
280 client.paintContent(target);
284 public void changeVariables(final Object source,
285 final Map<String, Object> variables) {
286 super.changeVariables(source, variables);
287 client.changeVariables(source, variables);
288 if (variables.containsKey("width")) {
289 setWidth((String) variables.get("width"));
291 if (variables.containsKey("height")) {
292 setHeight((String) variables.get("height"));
294 if (variables.containsKey("fontw")) {
295 fontw = (Integer) variables.get("fontw");
297 if (variables.containsKey("fonth")) {
298 fonth = (Integer) variables.get("fonth");
300 if (variables.containsKey("cols")) {
301 config.cols = (Integer) variables.get("cols");
303 if (variables.containsKey("rows")) {
304 config.rows = (Integer) variables.get("rows");
309 * Overridden to filter client-side calculation/changes and avoid loops.
313 public void setWidth(float width, int unit) {
314 if (width != getWidth() || unit != getWidthUnits()) {
315 super.setWidth(width, unit);
320 * Overridden to filter client-side calculation/changes and avoid loops.
324 public void setHeight(float height, int unit) {
325 if (height != getHeight() || unit != getHeightUnits()) {
326 super.setHeight(height, unit);
330 protected void handleSuggest(final String input) {
332 final boolean cancelIfNotASingleMatch = (input != null && !input
333 .equals(lastSuggestInput));
334 lastSuggestInput = input;
336 final Set<String> matches = handler.getSuggestions(this, input);
338 if (matches == null || matches.size() == 0) {
343 // Output the original
344 final String prefix = parseCommandPrefix(input);
345 String output = input.substring(0, input.lastIndexOf(prefix));
346 if (matches.size() == 1) {
347 // Output the only match
348 output += matches.iterator().next() + " "; // append the single
352 // We output until the common prefix
353 StringBuilder commonPrefix = new StringBuilder(prefix);
354 final int maxLen = matches.iterator().next().length();
355 for (int i = prefix.length(); i < maxLen; i++) {
357 boolean charMatch = true;
358 for (final String m : matches) {
361 } else if (i < m.length()) {
362 charMatch &= m.charAt(i) == c;
372 commonPrefix.append(c);
375 output += commonPrefix.toString();
376 if (prefix.equals(commonPrefix.toString())
377 && !cancelIfNotASingleMatch) {
378 final StringBuffer suggestions = new StringBuffer("\n");
379 for (final String m : matches) {
380 suggestions.append(" " + m);
382 print(suggestions.toString());
385 lastSuggestInput = output; // next suggest will not beep
397 protected void handleInput(final String input) {
399 // Ask registered handler
400 handler.inputReceived(this, input);
404 protected void parseAndExecuteCommand(final String input) {
405 final String[] argv = parseInput(input);
406 if (argv != null && argv.length > 0) {
407 final Command c = getCommand(argv[0]);
409 final String result = executeCommand(c, argv);
410 if (result != null) {
414 handler.commandNotFound(this, argv);
419 protected String executeCommand(final Command cmd, final String[] argv) {
421 final Object r = cmd.execute(this, argv);
422 return r != null ? "" + r : null;
423 } catch (final Exception e) {
424 handler.handleException(this, e, cmd, argv);
429 protected String parseCommandPrefix(final String input) {
433 if (!input.endsWith(" ")) {
434 final String[] argv = parseInput(input);
435 if (argv != null && argv.length > 0) {
436 return argv[argv.length - 1];
442 protected static String[] parseInput(final String input) {
443 if (input != null && !"".equals(input.trim())) {
444 final String[] temp = input.split(" ");
445 if (temp != null && temp.length > 0) {
446 final List<String> parsed = new ArrayList<String>(temp.length);
447 String current = null;
448 for (final String element : temp) {
449 final int quotCount = count(element, '\"');
450 if (quotCount > 0 && quotCount % 2 != 0) {
451 // uneven number of quotes star or end combining params
452 if (current != null) {
453 parsed.add(current + " "
454 + element.replaceAll("\"", "")); // end
457 current = element.replaceAll("\"", ""); // start
459 } else if (current != null) {
460 current += " " + element.replaceAll("\"", "");
462 parsed.add(element.replaceAll("\"", ""));
466 // TODO: actually this is not quite right: We have an open quote
467 // somewhere. Exception maybe?
468 if (current != null) {
469 parsed.add(current.replaceAll("\"", ""));
471 return parsed.toArray(new String[] {});
474 return new String[] {};
477 protected static int count(final String sourceString, final char lookFor) {
478 if (sourceString == null) {
482 for (int i = 0; i < sourceString.length(); i++) {
483 final char c = sourceString.charAt(i);
491 public void print(final String output) {
492 client.call("print", output);
495 public String getGreeting() {
496 return config.greeting;
499 public String getPs() {
503 public int getMaxBufferSize() {
504 return config.maxBufferSize;
507 public int getRows() {
511 public void setGreeting(final String greeting) {
512 config.greeting = greeting;
513 client.call("setGreeting", greeting);
516 public void setPs(final String ps) {
517 config.ps = ps == null ? DEFAULT_PS : ps;
518 client.call("setPs", config.ps);
521 public void setMaxBufferSize(final int lines) {
522 config.maxBufferSize = lines > 0 ? lines : 0;
523 client.call("setMaxBufferSize", config.maxBufferSize);
526 public void setRows(final int rows) {
528 if (config.rows < 1) {
531 if (config.rows > MAX_ROWS) {
532 config.rows = MAX_ROWS;
534 client.call("setRows", rows);
537 public int getCols() {
541 public void setCols(final int cols) {
543 if (config.cols < 1) {
546 if (config.cols > MAX_COLS) {
547 config.cols = MAX_COLS;
549 client.call("setCols", config.cols);
552 public void prompt() {
553 client.call("prompt");
556 public void prompt(final String initialInput) {
557 client.call("prompt", initialInput);
560 public void println(final String string) {
561 client.call("println", string);
564 public void append(final String string) {
565 client.call("append", string);
568 public void newLine() {
569 client.call("newLine");
572 public void reset() {
573 client.call("reset");
576 public void clear() {
580 public void formFeed() {
584 public void carriageReturn() {
588 public void lineFeed() {
592 public void clearCommandHistory() {
593 client.call("clearHistory");
596 public void clearBuffer() {
597 client.call("clearBuffer");
600 public void scrollToEnd() {
601 client.call("scrollToEnd");
604 public void focusInput() {
605 client.call("focusInput");
609 * Gets the Tabulator index of this Focusable component.
611 * @see com.vaadin.ui.Component.Focusable#getTabIndex()
613 public int getTabIndex() {
618 * Sets the Tabulator index of this Focusable component.
620 * @see com.vaadin.ui.Component.Focusable#setTabIndex(int)
622 public void setTabIndex(final int tabIndex) {
623 this.tabIndex = tabIndex;
630 public void focus() {
634 /* PrintStream implementation for console output. */
636 public PrintStream getPrintStream() {
637 if (printStream == null) {
638 printStream = new PrintStream(new OutputStream() {
640 ByteArrayOutputStream buffer = new ByteArrayOutputStream();
643 public void write(final int b) throws IOException {
652 public void flush() throws IOException {
655 Console.this.print(buffer.toString());
663 /* Generic command handling */
666 * Add a Command to this Console.
668 * This will override the any commands of the same name available via
669 * {@link CommandProvider}.
671 public void addCommand(final String name, final Command cmd) {
672 commands.put(name, cmd);
676 * Remove a command from this console.
678 * This does not remove Command available from {@link CommandProvider}.
682 public void removeCommand(final String cmdName) {
683 commands.remove(cmdName);
687 * Get a Command by its name.
692 public Command getCommand(final String cmdName) {
694 // Try directly registered command first
695 Command cmd = commands.get(cmdName);
700 // Ask from the providers
701 if (commandProviders != null) {
702 for (final CommandProvider cp : commandProviders) {
703 cmd = cp.getCommand(this, cmdName);
715 * Get the current Console Handler.
719 public Handler getHandler() {
724 * Set the handler for this console.
729 public void setHandler(final Handler handler) {
730 this.handler = handler != null ? handler : new DefaultConsoleHandler();
734 * Get map of available commands in this Console.
738 public Set<String> getCommands() {
739 final Set<String> res = new HashSet<String>();
740 if (commandProviders != null) {
741 for (final CommandProvider cp : commandProviders) {
742 res.addAll(cp.getAvailableCommands(this));
745 res.addAll(commands.keySet());
746 return Collections.unmodifiableSet(res);