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;
67 * @param isPrintPromptOnInput if true - entered by user text immediately will be printed to
68 * console, nothing happens otherwise
70 public void setPrintPromptOnInput(final boolean isPrintPromptOnInput) {
71 config.isPrintPromptOnInput = isPrintPromptOnInput;
72 client.call("setPrintPromptOnInput", isPrintPromptOnInput);
76 * @return true, if method scrollToEnd will only work if last scroll state was "end"
77 * (like Linux KDE console emulator "Konsole"), false otherwise (by default)
79 public boolean isSmartScrollToEnd() {
80 return config.isSmartScrollToEnd;
84 * @param isSmartScrollToEnd if true - method scrollToEnd will only work if last scroll
85 * state was "end" (like Linux KDE console emulator "Konsole"); false by default
87 public void setSmartScrollToEnd(final boolean isSmartScrollToEnd) {
88 config.isSmartScrollToEnd = isSmartScrollToEnd;
89 client.call("setSmartScrollToEnd", isSmartScrollToEnd);
92 private final ServerSideProxy client = new ServerSideProxy(
93 new ClientCallback());
96 * Inner class to handle client calls.
99 public class ClientCallback implements ServerSideHandler {
101 private static final long serialVersionUID = 3992611573500588703L;
103 public void requestRepaint() {
104 Console.this.requestRepaint();
107 public Object[] initRequestFromClient() {
108 return new Object[] {
111 config.maxBufferSize,
113 config.isPrintPromptOnInput,
114 config.isSmartScrollToEnd,
120 public void callFromClient(String method, Object[] params) {
121 // TODO Auto-generated method stub
128 * The tab order number of this field.
130 private int tabIndex = 0;
131 @SuppressWarnings("unused")
132 private Integer fontw;
133 @SuppressWarnings("unused")
134 private Integer fonth;
135 private PrintStream printStream;
136 private String lastSuggestInput;
137 private List<CommandProvider> commandProviders;
140 * An inner class for holding the configuration data.
142 public static class Config implements Serializable {
144 private static final long serialVersionUID = -812601232248504108L;
146 int maxBufferSize = DEFAULT_BUFFER;
147 int cols = DEFAULT_COLS;
148 int rows = DEFAULT_ROWS;
149 boolean wrap = DEFAULT_WRAP;
150 boolean isPrintPromptOnInput = DEFAULT_PRINT_PROMPT_ON_INPUT;
151 boolean isSmartScrollToEnd = DEFAULT_SMART_SCROLL_TO_END;
152 String ps = DEFAULT_PS;
153 String greeting = DEFAULT_GREETING;
158 * Console Handler interface.
160 * Handler provides a hook to handle various console related events and
161 * override the default processing.
164 public interface Handler extends Serializable {
167 * Called when user uses TAB to complete the command entered into the
174 Set<String> getSuggestions(Console console, String lastInput);
177 * Called when user has entered input to the Console and presses enter
183 void inputReceived(Console console, String lastInput);
186 * Handle an exception during a Command execution.
193 void handleException(Console console, Exception e, Command cmd,
197 * Handle situation where a command could not be found.
202 void commandNotFound(Console console, String[] argv);
207 * Commands that can be executed against the Component instance. They
208 * provide convenient string to method mapping. Basically, a Command is a
209 * method that that can be executed in Component. It can have parameters or
213 public interface Command extends Serializable {
216 * Execute a Command with arguments.
223 public Object execute(Console console, String[] argv) throws Exception;
226 * Get usage information about this command.
232 public String getUsage(Console console, String[] argv);
236 * Interface for providing Commands to the console. One can register a
237 * command providers to console instead of individual commands to provide a
241 public interface CommandProvider extends Serializable {
244 * List all available command from this provider.
249 Set<String> getAvailableCommands(Console console);
252 * Get Command instance based on command name.
258 Command getCommand(Console console, String commandName);
262 public void addCommandProvider(final CommandProvider commandProvider) {
263 if (commandProviders == null) {
264 commandProviders = new ArrayList<CommandProvider>();
266 commandProviders.add(commandProvider);
269 public void removeCommandProvider(final CommandProvider commandProvider) {
270 if (commandProviders == null) {
273 commandProviders.remove(commandProvider);
276 public void removeAllCommandProviders() {
277 if (commandProviders == null) {
280 commandProviders.clear();
283 public Console(final Console.Handler handler) {
290 setHandler(new DefaultConsoleHandler());
294 private void registerCallbacks() {
295 client.register("suggest", new Method() {
297 public void invoke(String methodName, Object[] params) {
298 handleSuggest((String) params[0]);
301 client.register("input", new Method() {
303 public void invoke(String methodName, Object[] params) {
304 handleInput((String) params[0]);
311 public void paintContent(final PaintTarget target) throws PaintException {
312 super.paintContent(target);
313 client.paintContent(target);
317 public void changeVariables(final Object source,
318 final Map<String, Object> variables) {
319 super.changeVariables(source, variables);
320 client.changeVariables(source, variables);
321 if (variables.containsKey("width")) {
322 setWidth((String) variables.get("width"));
324 if (variables.containsKey("height")) {
325 setHeight((String) variables.get("height"));
327 if (variables.containsKey("fontw")) {
328 fontw = (Integer) variables.get("fontw");
330 if (variables.containsKey("fonth")) {
331 fonth = (Integer) variables.get("fonth");
333 if (variables.containsKey("cols")) {
334 config.cols = (Integer) variables.get("cols");
336 if (variables.containsKey("rows")) {
337 config.rows = (Integer) variables.get("rows");
342 * Overridden to filter client-side calculation/changes and avoid loops.
346 public void setWidth(float width, int unit) {
347 if (width != getWidth() || unit != getWidthUnits()) {
348 super.setWidth(width, unit);
353 * Overridden to filter client-side calculation/changes and avoid loops.
357 public void setHeight(float height, int unit) {
358 if (height != getHeight() || unit != getHeightUnits()) {
359 super.setHeight(height, unit);
363 protected void handleSuggest(final String input) {
365 final boolean cancelIfNotASingleMatch = (input != null && !input
366 .equals(lastSuggestInput));
367 lastSuggestInput = input;
369 final Set<String> matches = handler.getSuggestions(this, input);
371 if (matches == null || matches.size() == 0) {
376 // Output the original
377 final String prefix = parseCommandPrefix(input);
378 String output = input.substring(0, input.lastIndexOf(prefix));
379 if (matches.size() == 1) {
380 // Output the only match
381 output += matches.iterator().next() + " "; // append the single
385 // We output until the common prefix
386 StringBuilder commonPrefix = new StringBuilder(prefix);
387 final int maxLen = matches.iterator().next().length();
388 for (int i = prefix.length(); i < maxLen; i++) {
390 boolean charMatch = true;
391 for (final String m : matches) {
394 } else if (i < m.length()) {
395 charMatch &= m.charAt(i) == c;
405 commonPrefix.append(c);
408 output += commonPrefix.toString();
409 if (prefix.equals(commonPrefix.toString())
410 && !cancelIfNotASingleMatch) {
411 final StringBuffer suggestions = new StringBuffer("\n");
412 for (final String m : matches) {
413 suggestions.append(" " + m);
415 print(suggestions.toString());
418 lastSuggestInput = output; // next suggest will not beep
430 protected void handleInput(final String input) {
432 // Ask registered handler
433 handler.inputReceived(this, input);
437 protected void parseAndExecuteCommand(final String input) {
438 final String[] argv = parseInput(input);
439 if (argv != null && argv.length > 0) {
440 final Command c = getCommand(argv[0]);
442 final String result = executeCommand(c, argv);
443 if (result != null) {
447 handler.commandNotFound(this, argv);
452 protected String executeCommand(final Command cmd, final String[] argv) {
454 final Object r = cmd.execute(this, argv);
455 return r != null ? "" + r : null;
456 } catch (final Exception e) {
457 handler.handleException(this, e, cmd, argv);
462 protected String parseCommandPrefix(final String input) {
466 if (!input.endsWith(" ")) {
467 final String[] argv = parseInput(input);
468 if (argv != null && argv.length > 0) {
469 return argv[argv.length - 1];
475 protected static String[] parseInput(final String input) {
476 if (input != null && !"".equals(input.trim())) {
477 final String[] temp = input.split(" ");
478 if (temp != null && temp.length > 0) {
479 final List<String> parsed = new ArrayList<String>(temp.length);
480 String current = null;
481 for (final String element : temp) {
482 final int quotCount = count(element, '\"');
483 if (quotCount > 0 && quotCount % 2 != 0) {
484 // uneven number of quotes star or end combining params
485 if (current != null) {
486 parsed.add(current + " "
487 + element.replaceAll("\"", "")); // end
490 current = element.replaceAll("\"", ""); // start
492 } else if (current != null) {
493 current += " " + element.replaceAll("\"", "");
495 parsed.add(element.replaceAll("\"", ""));
499 // TODO: actually this is not quite right: We have an open quote
500 // somewhere. Exception maybe?
501 if (current != null) {
502 parsed.add(current.replaceAll("\"", ""));
504 return parsed.toArray(new String[] {});
507 return new String[] {};
510 protected static int count(final String sourceString, final char lookFor) {
511 if (sourceString == null) {
515 for (int i = 0; i < sourceString.length(); i++) {
516 final char c = sourceString.charAt(i);
524 public void print(final String output) {
525 client.call("print", output);
529 * Print text with predefined in theme CSS class.
532 * @param className CSS class name for string
534 public void print(final String output, final String className) {
535 client.call("print", output, className);
538 public String getGreeting() {
539 return config.greeting;
542 public String getPs() {
546 public int getMaxBufferSize() {
547 return config.maxBufferSize;
550 public int getRows() {
554 public void setGreeting(final String greeting) {
555 config.greeting = greeting;
556 client.call("setGreeting", greeting);
559 public void setPs(final String ps) {
560 config.ps = ps == null ? DEFAULT_PS : ps;
561 client.call("setPs", config.ps);
564 public void setMaxBufferSize(final int lines) {
565 config.maxBufferSize = lines > 0 ? lines : 0;
566 client.call("setMaxBufferSize", config.maxBufferSize);
569 public void setRows(final int rows) {
571 if (config.rows < 1) {
574 if (config.rows > MAX_ROWS) {
575 config.rows = MAX_ROWS;
577 client.call("setRows", rows);
580 public int getCols() {
584 public void setCols(final int cols) {
586 if (config.cols < 1) {
589 if (config.cols > MAX_COLS) {
590 config.cols = MAX_COLS;
592 client.call("setCols", config.cols);
595 public void prompt() {
596 client.call("prompt");
599 public void prompt(final String initialInput) {
600 client.call("prompt", initialInput);
603 public void println(final String string) {
604 client.call("println", string);
608 * Print text with predefined in theme CSS class.
611 * @param className CSS class name for string
613 public void println(final String string, final String className) {
614 client.call("println", string, className);
618 * @param string text to append to the last printed line
620 public void append(final String string) {
621 client.call("append", string);
625 * Append text with predefined in theme CSS class.
627 * @param string text to append to the last printed line
628 * @param className CSS class name for string
630 public void append(final String string, final String className) {
631 client.call("append", string, className);
634 public void newLine() {
635 client.call("newLine");
639 * Print new line only if new line not exists at the end of console
641 public void newLineIfNotEndsWithNewLine() {
642 client.call("newLineIfNotEndsWithNewLine");
645 public void reset() {
646 client.call("reset");
649 public void clear() {
653 public void formFeed() {
657 public void carriageReturn() {
661 public void lineFeed() {
665 public void clearCommandHistory() {
666 client.call("clearHistory");
669 public void clearBuffer() {
670 client.call("clearBuffer");
673 public void scrollToEnd() {
674 client.call("scrollToEnd");
678 * Focus input element of console.
680 public void focusInput() {
681 client.call("focusInput");
685 * Gets the Tabulator index of this Focusable component.
687 * @see com.vaadin.ui.Component.Focusable#getTabIndex()
689 public int getTabIndex() {
694 * Sets the Tabulator index of this Focusable component.
696 * @see com.vaadin.ui.Component.Focusable#setTabIndex(int)
698 public void setTabIndex(final int tabIndex) {
699 this.tabIndex = tabIndex;
706 public void focus() {
710 /* PrintStream implementation for console output. */
712 public PrintStream getPrintStream() {
713 if (printStream == null) {
714 printStream = new PrintStream(new OutputStream() {
716 ByteArrayOutputStream buffer = new ByteArrayOutputStream();
719 public void write(final int b) throws IOException {
728 public void flush() throws IOException {
731 Console.this.print(buffer.toString());
739 /* Generic command handling */
742 * Add a Command to this Console.
744 * This will override the any commands of the same name available via
745 * {@link CommandProvider}.
747 public void addCommand(final String name, final Command cmd) {
748 commands.put(name, cmd);
752 * Remove a command from this console.
754 * This does not remove Command available from {@link CommandProvider}.
758 public void removeCommand(final String cmdName) {
759 commands.remove(cmdName);
763 * Get a Command by its name.
768 public Command getCommand(final String cmdName) {
770 // Try directly registered command first
771 Command cmd = commands.get(cmdName);
776 // Ask from the providers
777 if (commandProviders != null) {
778 for (final CommandProvider cp : commandProviders) {
779 cmd = cp.getCommand(this, cmdName);
791 * Get the current Console Handler.
795 public Handler getHandler() {
800 * Set the handler for this console.
805 public void setHandler(final Handler handler) {
806 this.handler = handler != null ? handler : new DefaultConsoleHandler();
810 * Get map of available commands in this Console.
814 public Set<String> getCommands() {
815 final Set<String> res = new HashSet<String>();
816 if (commandProviders != null) {
817 for (final CommandProvider cp : commandProviders) {
818 if(cp.getAvailableCommands(this) != null)
819 res.addAll(cp.getAvailableCommands(this));
822 res.addAll(commands.keySet());
823 return Collections.unmodifiableSet(res);