+ new option - setSmartScrollToEnd: scrollToEnd work only if last scroll state is was "end"
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);
59 public boolean isPrintPromptOnInput() {
60 return config.isPrintPromptOnInput;
63 public void setPrintPromptOnInput(final boolean isPrintPromptOnInput) {
64 config.isPrintPromptOnInput = isPrintPromptOnInput;
65 client.call("setPrintPromptOnInput", isPrintPromptOnInput);
68 public boolean isSmartScrollToEnd() {
69 return config.isSmartScrollToEnd;
72 public void setSmartScrollToEnd(final boolean isSmartScrollToEnd) {
73 config.isSmartScrollToEnd = isSmartScrollToEnd;
74 client.call("setSmartScrollToEnd", isSmartScrollToEnd);
77 private final ServerSideProxy client = new ServerSideProxy(
78 new ClientCallback());
81 * Inner class to handle client calls.
84 public class ClientCallback implements ServerSideHandler {
86 private static final long serialVersionUID = 3992611573500588703L;
88 public void requestRepaint() {
89 Console.this.requestRepaint();
92 public Object[] initRequestFromClient() {
98 config.isPrintPromptOnInput,
99 config.isSmartScrollToEnd,
105 public void callFromClient(String method, Object[] params) {
106 // TODO Auto-generated method stub
113 * The tab order number of this field.
115 private int tabIndex = 0;
116 @SuppressWarnings("unused")
117 private Integer fontw;
118 @SuppressWarnings("unused")
119 private Integer fonth;
120 private PrintStream printStream;
121 private String lastSuggestInput;
122 private List<CommandProvider> commandProviders;
125 * An inner class for holding the configuration data.
127 public static class Config implements Serializable {
129 private static final long serialVersionUID = -812601232248504108L;
131 int maxBufferSize = DEFAULT_BUFFER;
132 int cols = DEFAULT_COLS;
133 int rows = DEFAULT_ROWS;
134 boolean wrap = DEFAULT_WRAP;
135 boolean isPrintPromptOnInput = DEFAULT_PRINT_PROMPT_ON_INPUT;
136 boolean isSmartScrollToEnd = DEFAULT_SMART_SCROLL_TO_END;
137 String ps = DEFAULT_PS;
138 String greeting = DEFAULT_GREETING;
143 * Console Handler interface.
145 * Handler provides a hook to handle various console related events and
146 * override the default processing.
149 public interface Handler extends Serializable {
152 * Called when user uses TAB to complete the command entered into the
159 Set<String> getSuggestions(Console console, String lastInput);
162 * Called when user has entered input to the Console and presses enter
168 void inputReceived(Console console, String lastInput);
171 * Handle an exception during a Command execution.
178 void handleException(Console console, Exception e, Command cmd,
182 * Handle situation where a command could not be found.
187 void commandNotFound(Console console, String[] argv);
192 * Commands that can be executed against the Component instance. They
193 * provide convenient string to method mapping. Basically, a Command is a
194 * method that that can be executed in Component. It can have parameters or
198 public interface Command extends Serializable {
201 * Execute a Command with arguments.
208 public Object execute(Console console, String[] argv) throws Exception;
211 * Get usage information about this command.
217 public String getUsage(Console console, String[] argv);
221 * Interface for providing Commands to the console. One can register a
222 * command providers to console instead of individual commands to provide a
226 public interface CommandProvider extends Serializable {
229 * List all available command from this provider.
234 Set<String> getAvailableCommands(Console console);
237 * Get Command instance based on command name.
243 Command getCommand(Console console, String commandName);
247 public void addCommandProvider(final CommandProvider commandProvider) {
248 if (commandProviders == null) {
249 commandProviders = new ArrayList<CommandProvider>();
251 commandProviders.add(commandProvider);
254 public void removeCommandProvider(final CommandProvider commandProvider) {
255 if (commandProviders == null) {
258 commandProviders.remove(commandProvider);
261 public void removeAllCommandProviders() {
262 if (commandProviders == null) {
265 commandProviders.clear();
268 public Console(final Console.Handler handler) {
275 setHandler(new DefaultConsoleHandler());
279 private void registerCallbacks() {
280 client.register("suggest", new Method() {
282 public void invoke(String methodName, Object[] params) {
283 handleSuggest((String) params[0]);
286 client.register("input", new Method() {
288 public void invoke(String methodName, Object[] params) {
289 handleInput((String) params[0]);
296 public void paintContent(final PaintTarget target) throws PaintException {
297 super.paintContent(target);
298 client.paintContent(target);
302 public void changeVariables(final Object source,
303 final Map<String, Object> variables) {
304 super.changeVariables(source, variables);
305 client.changeVariables(source, variables);
306 if (variables.containsKey("width")) {
307 setWidth((String) variables.get("width"));
309 if (variables.containsKey("height")) {
310 setHeight((String) variables.get("height"));
312 if (variables.containsKey("fontw")) {
313 fontw = (Integer) variables.get("fontw");
315 if (variables.containsKey("fonth")) {
316 fonth = (Integer) variables.get("fonth");
318 if (variables.containsKey("cols")) {
319 config.cols = (Integer) variables.get("cols");
321 if (variables.containsKey("rows")) {
322 config.rows = (Integer) variables.get("rows");
327 * Overridden to filter client-side calculation/changes and avoid loops.
331 public void setWidth(float width, int unit) {
332 if (width != getWidth() || unit != getWidthUnits()) {
333 super.setWidth(width, unit);
338 * Overridden to filter client-side calculation/changes and avoid loops.
342 public void setHeight(float height, int unit) {
343 if (height != getHeight() || unit != getHeightUnits()) {
344 super.setHeight(height, unit);
348 protected void handleSuggest(final String input) {
350 final boolean cancelIfNotASingleMatch = (input != null && !input
351 .equals(lastSuggestInput));
352 lastSuggestInput = input;
354 final Set<String> matches = handler.getSuggestions(this, input);
356 if (matches == null || matches.size() == 0) {
361 // Output the original
362 final String prefix = parseCommandPrefix(input);
363 String output = input.substring(0, input.lastIndexOf(prefix));
364 if (matches.size() == 1) {
365 // Output the only match
366 output += matches.iterator().next() + " "; // append the single
370 // We output until the common prefix
371 StringBuilder commonPrefix = new StringBuilder(prefix);
372 final int maxLen = matches.iterator().next().length();
373 for (int i = prefix.length(); i < maxLen; i++) {
375 boolean charMatch = true;
376 for (final String m : matches) {
379 } else if (i < m.length()) {
380 charMatch &= m.charAt(i) == c;
390 commonPrefix.append(c);
393 output += commonPrefix.toString();
394 if (prefix.equals(commonPrefix.toString())
395 && !cancelIfNotASingleMatch) {
396 final StringBuffer suggestions = new StringBuffer("\n");
397 for (final String m : matches) {
398 suggestions.append(" " + m);
400 print(suggestions.toString());
403 lastSuggestInput = output; // next suggest will not beep
415 protected void handleInput(final String input) {
417 // Ask registered handler
418 handler.inputReceived(this, input);
422 protected void parseAndExecuteCommand(final String input) {
423 final String[] argv = parseInput(input);
424 if (argv != null && argv.length > 0) {
425 final Command c = getCommand(argv[0]);
427 final String result = executeCommand(c, argv);
428 if (result != null) {
432 handler.commandNotFound(this, argv);
437 protected String executeCommand(final Command cmd, final String[] argv) {
439 final Object r = cmd.execute(this, argv);
440 return r != null ? "" + r : null;
441 } catch (final Exception e) {
442 handler.handleException(this, e, cmd, argv);
447 protected String parseCommandPrefix(final String input) {
451 if (!input.endsWith(" ")) {
452 final String[] argv = parseInput(input);
453 if (argv != null && argv.length > 0) {
454 return argv[argv.length - 1];
460 protected static String[] parseInput(final String input) {
461 if (input != null && !"".equals(input.trim())) {
462 final String[] temp = input.split(" ");
463 if (temp != null && temp.length > 0) {
464 final List<String> parsed = new ArrayList<String>(temp.length);
465 String current = null;
466 for (final String element : temp) {
467 final int quotCount = count(element, '\"');
468 if (quotCount > 0 && quotCount % 2 != 0) {
469 // uneven number of quotes star or end combining params
470 if (current != null) {
471 parsed.add(current + " "
472 + element.replaceAll("\"", "")); // end
475 current = element.replaceAll("\"", ""); // start
477 } else if (current != null) {
478 current += " " + element.replaceAll("\"", "");
480 parsed.add(element.replaceAll("\"", ""));
484 // TODO: actually this is not quite right: We have an open quote
485 // somewhere. Exception maybe?
486 if (current != null) {
487 parsed.add(current.replaceAll("\"", ""));
489 return parsed.toArray(new String[] {});
492 return new String[] {};
495 protected static int count(final String sourceString, final char lookFor) {
496 if (sourceString == null) {
500 for (int i = 0; i < sourceString.length(); i++) {
501 final char c = sourceString.charAt(i);
509 public void print(final String output) {
510 client.call("print", output);
515 * @param className CSS class name for string
517 public void print(final String output, final String className) {
518 client.call("print", output, className);
521 public String getGreeting() {
522 return config.greeting;
525 public String getPs() {
529 public int getMaxBufferSize() {
530 return config.maxBufferSize;
533 public int getRows() {
537 public void setGreeting(final String greeting) {
538 config.greeting = greeting;
539 client.call("setGreeting", greeting);
542 public void setPs(final String ps) {
543 config.ps = ps == null ? DEFAULT_PS : ps;
544 client.call("setPs", config.ps);
547 public void setMaxBufferSize(final int lines) {
548 config.maxBufferSize = lines > 0 ? lines : 0;
549 client.call("setMaxBufferSize", config.maxBufferSize);
552 public void setRows(final int rows) {
554 if (config.rows < 1) {
557 if (config.rows > MAX_ROWS) {
558 config.rows = MAX_ROWS;
560 client.call("setRows", rows);
563 public int getCols() {
567 public void setCols(final int cols) {
569 if (config.cols < 1) {
572 if (config.cols > MAX_COLS) {
573 config.cols = MAX_COLS;
575 client.call("setCols", config.cols);
578 public void prompt() {
579 client.call("prompt");
582 public void prompt(final String initialInput) {
583 client.call("prompt", initialInput);
586 public void println(final String string) {
587 client.call("println", string);
592 * @param className CSS class name for string
594 public void println(final String string, final String className) {
595 client.call("println", string, className);
598 public void append(final String string) {
599 client.call("append", string);
604 * @param className CSS class name for string
606 public void append(final String string, final String className) {
607 client.call("append", string, className);
610 public void newLine() {
611 client.call("newLine");
614 public void newLineIfNotEndsWithNewLine() {
615 client.call("newLineIfNotEndsWithNewLine");
618 public void reset() {
619 client.call("reset");
622 public void clear() {
626 public void formFeed() {
630 public void carriageReturn() {
634 public void lineFeed() {
638 public void clearCommandHistory() {
639 client.call("clearHistory");
642 public void clearBuffer() {
643 client.call("clearBuffer");
646 public void scrollToEnd() {
647 client.call("scrollToEnd");
650 public void focusInput() {
651 client.call("focusInput");
655 * Gets the Tabulator index of this Focusable component.
657 * @see com.vaadin.ui.Component.Focusable#getTabIndex()
659 public int getTabIndex() {
664 * Sets the Tabulator index of this Focusable component.
666 * @see com.vaadin.ui.Component.Focusable#setTabIndex(int)
668 public void setTabIndex(final int tabIndex) {
669 this.tabIndex = tabIndex;
676 public void focus() {
680 /* PrintStream implementation for console output. */
682 public PrintStream getPrintStream() {
683 if (printStream == null) {
684 printStream = new PrintStream(new OutputStream() {
686 ByteArrayOutputStream buffer = new ByteArrayOutputStream();
689 public void write(final int b) throws IOException {
698 public void flush() throws IOException {
701 Console.this.print(buffer.toString());
709 /* Generic command handling */
712 * Add a Command to this Console.
714 * This will override the any commands of the same name available via
715 * {@link CommandProvider}.
717 public void addCommand(final String name, final Command cmd) {
718 commands.put(name, cmd);
722 * Remove a command from this console.
724 * This does not remove Command available from {@link CommandProvider}.
728 public void removeCommand(final String cmdName) {
729 commands.remove(cmdName);
733 * Get a Command by its name.
738 public Command getCommand(final String cmdName) {
740 // Try directly registered command first
741 Command cmd = commands.get(cmdName);
746 // Ask from the providers
747 if (commandProviders != null) {
748 for (final CommandProvider cp : commandProviders) {
749 cmd = cp.getCommand(this, cmdName);
761 * Get the current Console Handler.
765 public Handler getHandler() {
770 * Set the handler for this console.
775 public void setHandler(final Handler handler) {
776 this.handler = handler != null ? handler : new DefaultConsoleHandler();
780 * Get map of available commands in this Console.
784 public Set<String> getCommands() {
785 final Set<String> res = new HashSet<String>();
786 if (commandProviders != null) {
787 for (final CommandProvider cp : commandProviders) {
788 res.addAll(cp.getAvailableCommands(this));
791 res.addAll(commands.keySet());
792 return Collections.unmodifiableSet(res);