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 boolean DEFAULT_SMART_SCROLL_TO_END = false;
47 private static final int MAX_COLS = 500;
48 private static final int MAX_ROWS = 200;
50 public boolean isWrap() {
54 public void setWrap(final boolean wrap) {
56 client.call("setWrap", wrap);
60 * @return true, if entered by user text immediately will print to console, false otherwise
62 public boolean isPrintPromptOnInput() {
63 return config.isPrintPromptOnInput;
66 public void setPrintPromptOnInput(final boolean isPrintPromptOnInput) {
67 config.isPrintPromptOnInput = isPrintPromptOnInput;
68 client.call("setPrintPromptOnInput", isPrintPromptOnInput);
72 * @return true, if method scrollToEnd will only work if last scroll state was "end"
73 * (like Linux KDE console emulator "Konsole"), false otherwise (by default)
75 public boolean isSmartScrollToEnd() {
76 return config.isSmartScrollToEnd;
80 * @param isSmartScrollToEnd if true - method scrollToEnd will only work if last scroll
81 * state was "end" (like Linux KDE console emulator "Konsole"); false by default
83 public void setSmartScrollToEnd(final boolean isSmartScrollToEnd) {
84 config.isSmartScrollToEnd = isSmartScrollToEnd;
85 client.call("setSmartScrollToEnd", isSmartScrollToEnd);
88 private final ServerSideProxy client = new ServerSideProxy(
89 new ClientCallback());
92 * Inner class to handle client calls.
95 public class ClientCallback implements ServerSideHandler {
97 private static final long serialVersionUID = 3992611573500588703L;
99 public void requestRepaint() {
100 Console.this.requestRepaint();
103 public Object[] initRequestFromClient() {
104 return new Object[] {
107 config.maxBufferSize,
109 config.isPrintPromptOnInput,
110 config.isSmartScrollToEnd,
116 public void callFromClient(String method, Object[] params) {
117 // TODO Auto-generated method stub
124 * The tab order number of this field.
126 private int tabIndex = 0;
127 @SuppressWarnings("unused")
128 private Integer fontw;
129 @SuppressWarnings("unused")
130 private Integer fonth;
131 private PrintStream printStream;
132 private String lastSuggestInput;
133 private List<CommandProvider> commandProviders;
136 * An inner class for holding the configuration data.
138 public static class Config implements Serializable {
140 private static final long serialVersionUID = -812601232248504108L;
142 int maxBufferSize = DEFAULT_BUFFER;
143 int cols = DEFAULT_COLS;
144 int rows = DEFAULT_ROWS;
145 boolean wrap = DEFAULT_WRAP;
146 boolean isPrintPromptOnInput = DEFAULT_PRINT_PROMPT_ON_INPUT;
147 boolean isSmartScrollToEnd = DEFAULT_SMART_SCROLL_TO_END;
148 String ps = DEFAULT_PS;
149 String greeting = DEFAULT_GREETING;
154 * Console Handler interface.
156 * Handler provides a hook to handle various console related events and
157 * override the default processing.
160 public interface Handler extends Serializable {
163 * Called when user uses TAB to complete the command entered into the
170 Set<String> getSuggestions(Console console, String lastInput);
173 * Called when user has entered input to the Console and presses enter
179 void inputReceived(Console console, String lastInput);
182 * Handle an exception during a Command execution.
189 void handleException(Console console, Exception e, Command cmd,
193 * Handle situation where a command could not be found.
198 void commandNotFound(Console console, String[] argv);
203 * Commands that can be executed against the Component instance. They
204 * provide convenient string to method mapping. Basically, a Command is a
205 * method that that can be executed in Component. It can have parameters or
209 public interface Command extends Serializable {
212 * Execute a Command with arguments.
219 public Object execute(Console console, String[] argv) throws Exception;
222 * Get usage information about this command.
228 public String getUsage(Console console, String[] argv);
232 * Interface for providing Commands to the console. One can register a
233 * command providers to console instead of individual commands to provide a
237 public interface CommandProvider extends Serializable {
240 * List all available command from this provider.
245 Set<String> getAvailableCommands(Console console);
248 * Get Command instance based on command name.
254 Command getCommand(Console console, String commandName);
258 public void addCommandProvider(final CommandProvider commandProvider) {
259 if (commandProviders == null) {
260 commandProviders = new ArrayList<CommandProvider>();
262 commandProviders.add(commandProvider);
265 public void removeCommandProvider(final CommandProvider commandProvider) {
266 if (commandProviders == null) {
269 commandProviders.remove(commandProvider);
272 public void removeAllCommandProviders() {
273 if (commandProviders == null) {
276 commandProviders.clear();
279 public Console(final Console.Handler handler) {
286 setHandler(new DefaultConsoleHandler());
290 private void registerCallbacks() {
291 client.register("suggest", new Method() {
293 public void invoke(String methodName, Object[] params) {
294 handleSuggest((String) params[0]);
297 client.register("input", new Method() {
299 public void invoke(String methodName, Object[] params) {
300 handleInput((String) params[0]);
307 public void paintContent(final PaintTarget target) throws PaintException {
308 super.paintContent(target);
309 client.paintContent(target);
313 public void changeVariables(final Object source,
314 final Map<String, Object> variables) {
315 super.changeVariables(source, variables);
316 client.changeVariables(source, variables);
317 if (variables.containsKey("width")) {
318 setWidth((String) variables.get("width"));
320 if (variables.containsKey("height")) {
321 setHeight((String) variables.get("height"));
323 if (variables.containsKey("fontw")) {
324 fontw = (Integer) variables.get("fontw");
326 if (variables.containsKey("fonth")) {
327 fonth = (Integer) variables.get("fonth");
329 if (variables.containsKey("cols")) {
330 config.cols = (Integer) variables.get("cols");
332 if (variables.containsKey("rows")) {
333 config.rows = (Integer) variables.get("rows");
338 * Overridden to filter client-side calculation/changes and avoid loops.
342 public void setWidth(float width, int unit) {
343 if (width != getWidth() || unit != getWidthUnits()) {
344 super.setWidth(width, unit);
349 * Overridden to filter client-side calculation/changes and avoid loops.
353 public void setHeight(float height, int unit) {
354 if (height != getHeight() || unit != getHeightUnits()) {
355 super.setHeight(height, unit);
359 protected void handleSuggest(final String input) {
361 final boolean cancelIfNotASingleMatch = (input != null && !input
362 .equals(lastSuggestInput));
363 lastSuggestInput = input;
365 final Set<String> matches = handler.getSuggestions(this, input);
367 if (matches == null || matches.size() == 0) {
372 // Output the original
373 final String prefix = parseCommandPrefix(input);
374 String output = input.substring(0, input.lastIndexOf(prefix));
375 if (matches.size() == 1) {
376 // Output the only match
377 output += matches.iterator().next() + " "; // append the single
381 // We output until the common prefix
382 StringBuilder commonPrefix = new StringBuilder(prefix);
383 final int maxLen = matches.iterator().next().length();
384 for (int i = prefix.length(); i < maxLen; i++) {
386 boolean charMatch = true;
387 for (final String m : matches) {
390 } else if (i < m.length()) {
391 charMatch &= m.charAt(i) == c;
401 commonPrefix.append(c);
404 output += commonPrefix.toString();
405 if (prefix.equals(commonPrefix.toString())
406 && !cancelIfNotASingleMatch) {
407 final StringBuffer suggestions = new StringBuffer("\n");
408 for (final String m : matches) {
409 suggestions.append(" " + m);
411 print(suggestions.toString());
414 lastSuggestInput = output; // next suggest will not beep
426 protected void handleInput(final String input) {
428 // Ask registered handler
429 handler.inputReceived(this, input);
433 protected void parseAndExecuteCommand(final String input) {
434 final String[] argv = parseInput(input);
435 if (argv != null && argv.length > 0) {
436 final Command c = getCommand(argv[0]);
438 final String result = executeCommand(c, argv);
439 if (result != null) {
443 handler.commandNotFound(this, argv);
448 protected String executeCommand(final Command cmd, final String[] argv) {
450 final Object r = cmd.execute(this, argv);
451 return r != null ? "" + r : null;
452 } catch (final Exception e) {
453 handler.handleException(this, e, cmd, argv);
458 protected String parseCommandPrefix(final String input) {
462 if (!input.endsWith(" ")) {
463 final String[] argv = parseInput(input);
464 if (argv != null && argv.length > 0) {
465 return argv[argv.length - 1];
471 protected static String[] parseInput(final String input) {
472 if (input != null && !"".equals(input.trim())) {
473 final String[] temp = input.split(" ");
474 if (temp != null && temp.length > 0) {
475 final List<String> parsed = new ArrayList<String>(temp.length);
476 String current = null;
477 for (final String element : temp) {
478 final int quotCount = count(element, '\"');
479 if (quotCount > 0 && quotCount % 2 != 0) {
480 // uneven number of quotes star or end combining params
481 if (current != null) {
482 parsed.add(current + " "
483 + element.replaceAll("\"", "")); // end
486 current = element.replaceAll("\"", ""); // start
488 } else if (current != null) {
489 current += " " + element.replaceAll("\"", "");
491 parsed.add(element.replaceAll("\"", ""));
495 // TODO: actually this is not quite right: We have an open quote
496 // somewhere. Exception maybe?
497 if (current != null) {
498 parsed.add(current.replaceAll("\"", ""));
500 return parsed.toArray(new String[] {});
503 return new String[] {};
506 protected static int count(final String sourceString, final char lookFor) {
507 if (sourceString == null) {
511 for (int i = 0; i < sourceString.length(); i++) {
512 final char c = sourceString.charAt(i);
520 public void print(final String output) {
521 client.call("print", output);
526 * @param className CSS class name for string
528 public void print(final String output, final String className) {
529 client.call("print", output, className);
532 public String getGreeting() {
533 return config.greeting;
536 public String getPs() {
540 public int getMaxBufferSize() {
541 return config.maxBufferSize;
544 public int getRows() {
548 public void setGreeting(final String greeting) {
549 config.greeting = greeting;
550 client.call("setGreeting", greeting);
553 public void setPs(final String ps) {
554 config.ps = ps == null ? DEFAULT_PS : ps;
555 client.call("setPs", config.ps);
558 public void setMaxBufferSize(final int lines) {
559 config.maxBufferSize = lines > 0 ? lines : 0;
560 client.call("setMaxBufferSize", config.maxBufferSize);
563 public void setRows(final int rows) {
565 if (config.rows < 1) {
568 if (config.rows > MAX_ROWS) {
569 config.rows = MAX_ROWS;
571 client.call("setRows", rows);
574 public int getCols() {
578 public void setCols(final int cols) {
580 if (config.cols < 1) {
583 if (config.cols > MAX_COLS) {
584 config.cols = MAX_COLS;
586 client.call("setCols", config.cols);
589 public void prompt() {
590 client.call("prompt");
593 public void prompt(final String initialInput) {
594 client.call("prompt", initialInput);
597 public void println(final String string) {
598 client.call("println", string);
603 * @param className CSS class name for string
605 public void println(final String string, final String className) {
606 client.call("println", string, className);
610 * @param string text to append to the last printed line
612 public void append(final String string) {
613 client.call("append", string);
617 * @param string text to append to the last printed line
618 * @param className CSS class name for string
620 public void append(final String string, final String className) {
621 client.call("append", string, className);
624 public void newLine() {
625 client.call("newLine");
628 public void newLineIfNotEndsWithNewLine() {
629 client.call("newLineIfNotEndsWithNewLine");
632 public void reset() {
633 client.call("reset");
636 public void clear() {
640 public void formFeed() {
644 public void carriageReturn() {
648 public void lineFeed() {
652 public void clearCommandHistory() {
653 client.call("clearHistory");
656 public void clearBuffer() {
657 client.call("clearBuffer");
660 public void scrollToEnd() {
661 client.call("scrollToEnd");
665 * Focus input element of console.
667 public void focusInput() {
668 client.call("focusInput");
672 * Gets the Tabulator index of this Focusable component.
674 * @see com.vaadin.ui.Component.Focusable#getTabIndex()
676 public int getTabIndex() {
681 * Sets the Tabulator index of this Focusable component.
683 * @see com.vaadin.ui.Component.Focusable#setTabIndex(int)
685 public void setTabIndex(final int tabIndex) {
686 this.tabIndex = tabIndex;
693 public void focus() {
697 /* PrintStream implementation for console output. */
699 public PrintStream getPrintStream() {
700 if (printStream == null) {
701 printStream = new PrintStream(new OutputStream() {
703 ByteArrayOutputStream buffer = new ByteArrayOutputStream();
706 public void write(final int b) throws IOException {
715 public void flush() throws IOException {
718 Console.this.print(buffer.toString());
726 /* Generic command handling */
729 * Add a Command to this Console.
731 * This will override the any commands of the same name available via
732 * {@link CommandProvider}.
734 public void addCommand(final String name, final Command cmd) {
735 commands.put(name, cmd);
739 * Remove a command from this console.
741 * This does not remove Command available from {@link CommandProvider}.
745 public void removeCommand(final String cmdName) {
746 commands.remove(cmdName);
750 * Get a Command by its name.
755 public Command getCommand(final String cmdName) {
757 // Try directly registered command first
758 Command cmd = commands.get(cmdName);
763 // Ask from the providers
764 if (commandProviders != null) {
765 for (final CommandProvider cp : commandProviders) {
766 cmd = cp.getCommand(this, cmdName);
778 * Get the current Console Handler.
782 public Handler getHandler() {
787 * Set the handler for this console.
792 public void setHandler(final Handler handler) {
793 this.handler = handler != null ? handler : new DefaultConsoleHandler();
797 * Get map of available commands in this Console.
801 public Set<String> getCommands() {
802 final Set<String> res = new HashSet<String>();
803 if (commandProviders != null) {
804 for (final CommandProvider cp : commandProviders) {
805 res.addAll(cp.getAvailableCommands(this));
808 res.addAll(commands.keySet());
809 return Collections.unmodifiableSet(res);