src/main/java/org/vaadin/console/Console.java
author indvdum
Thu, 19 May 2011 00:52:44 +0400
changeset 8 1f4c68061547
parent 7 a778386e297f
child 9 dbc3bbf10535
permissions -rw-r--r--
* no hide prompt at append
     1 package org.vaadin.console;
     2 
     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;
    13 import java.util.Map;
    14 import java.util.Set;
    15 
    16 import org.vaadin.rpc.ServerSideHandler;
    17 import org.vaadin.rpc.ServerSideProxy;
    18 import org.vaadin.rpc.client.Method;
    19 
    20 import com.vaadin.terminal.PaintException;
    21 import com.vaadin.terminal.PaintTarget;
    22 import com.vaadin.ui.AbstractComponent;
    23 import com.vaadin.ui.Component;
    24 
    25 /**
    26  * Server side component for the VTextConsole widget.
    27  *
    28  * @author Sami Ekblad / Vaadin
    29  *
    30  */
    31 @com.vaadin.ui.ClientWidget(org.vaadin.console.client.ui.VTextConsole.class)
    32 public class Console extends AbstractComponent implements Component.Focusable {
    33 
    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();
    38 
    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;
    48 
    49     public boolean isWrap() {
    50         return config.wrap;
    51     }
    52 
    53     public void setWrap(final boolean wrap) {
    54         config.wrap = wrap;
    55         client.call("setWrap", wrap);
    56     }
    57     
    58     public boolean isPrintPromptOnInput(){
    59     	return config.isPrintPromptOnInput;
    60     }
    61     
    62     public void setPrintPromptOnInput(final boolean isPrintPromptOnInput){
    63     	config.isPrintPromptOnInput = isPrintPromptOnInput;
    64     	client.call("setPrintPromptOnInput", isPrintPromptOnInput);
    65     }
    66 
    67     private final ServerSideProxy client = new ServerSideProxy(
    68             new ClientCallback());
    69 
    70     /**
    71      * Inner class to handle client calls.
    72      *
    73      */
    74     public class ClientCallback implements ServerSideHandler {
    75 
    76         private static final long serialVersionUID = 3992611573500588703L;
    77 
    78         public void requestRepaint() {
    79             Console.this.requestRepaint();
    80         }
    81 
    82         public Object[] initRequestFromClient() {
    83             return new Object[] { config.cols, config.rows,
    84                     config.maxBufferSize, config.wrap, config.isPrintPromptOnInput, config.greeting,
    85                     config.ps };
    86         }
    87 
    88         public void callFromClient(String method, Object[] params) {
    89             // TODO Auto-generated method stub
    90 
    91         }
    92 
    93     }
    94 
    95     /**
    96      * The tab order number of this field.
    97      */
    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;
   106 
   107     /**
   108      * An inner class for holding the configuration data.
   109      */
   110     public static class Config implements Serializable {
   111 
   112         private static final long serialVersionUID = -812601232248504108L;
   113 
   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;
   121 
   122     }
   123 
   124     /**
   125      * Console Handler interface.
   126      *
   127      * Handler provides a hook to handle various console related events and
   128      * override the default processing.
   129      *
   130      */
   131     public interface Handler extends Serializable {
   132 
   133         /**
   134          * Called when user uses TAB to complete the command entered into the
   135          * Console input.
   136          *
   137          * @param console
   138          * @param lastInput
   139          * @return
   140          */
   141         Set<String> getSuggestions(Console console, String lastInput);
   142 
   143         /**
   144          * Called when user has entered input to the Console and presses enter
   145          * to execute it.
   146          *
   147          * @param console
   148          * @param lastInput
   149          */
   150         void inputReceived(Console console, String lastInput);
   151 
   152         /**
   153          * Handle an exception during a Command execution.
   154          *
   155          * @param console
   156          * @param e
   157          * @param cmd
   158          * @param argv
   159          */
   160         void handleException(Console console, Exception e, Command cmd,
   161                 String[] argv);
   162 
   163         /**
   164          * Handle situation where a command could not be found.
   165          *
   166          * @param console
   167          * @param argv
   168          */
   169         void commandNotFound(Console console, String[] argv);
   170 
   171     }
   172 
   173     /**
   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
   177      * not.
   178      *
   179      */
   180     public interface Command extends Serializable {
   181 
   182         /**
   183          * Execute a Command with arguments.
   184          *
   185          * @param console
   186          * @param argv
   187          * @return
   188          * @throws Exception
   189          */
   190         public Object execute(Console console, String[] argv) throws Exception;
   191 
   192         /**
   193          * Get usage information about this command.
   194          *
   195          * @param console
   196          * @param argv
   197          * @return
   198          */
   199         public String getUsage(Console console, String[] argv);
   200     }
   201 
   202     /**
   203      * Interface for providing Commands to the console. One can register a
   204      * command providers to console instead of individual commands to provide a
   205      * lot of commands.
   206      *
   207      */
   208     public interface CommandProvider extends Serializable {
   209 
   210         /**
   211          * List all available command from this provider.
   212          *
   213          * @param console
   214          * @return
   215          */
   216         Set<String> getAvailableCommands(Console console);
   217 
   218         /**
   219          * Get Command instance based on command name.
   220          *
   221          * @param console
   222          * @param commandName
   223          * @return
   224          */
   225         Command getCommand(Console console, String commandName);
   226 
   227     }
   228 
   229     public void addCommandProvider(final CommandProvider commandProvider) {
   230         if (commandProviders == null) {
   231             commandProviders = new ArrayList<CommandProvider>();
   232         }
   233         commandProviders.add(commandProvider);
   234     }
   235 
   236     public void removeCommandProvider(final CommandProvider commandProvider) {
   237         if (commandProviders == null) {
   238             return;
   239         }
   240         commandProviders.remove(commandProvider);
   241     }
   242 
   243     public void removeAllCommandProviders() {
   244         if (commandProviders == null) {
   245             return;
   246         }
   247         commandProviders.clear();
   248     }
   249 
   250     public Console(final Console.Handler handler) {
   251         this();
   252         setHandler(handler);
   253     }
   254 
   255     public Console() {
   256         setImmediate(true);
   257         setHandler(new DefaultConsoleHandler());
   258         registerCallbacks();
   259     }
   260 
   261     private void registerCallbacks() {
   262         client.register("suggest", new Method() {
   263 
   264             public void invoke(String methodName, Object[] params) {
   265                 handleSuggest((String) params[0]);
   266             }
   267         });
   268         client.register("input", new Method() {
   269 
   270             public void invoke(String methodName, Object[] params) {
   271                 handleInput((String) params[0]);
   272             }
   273         });
   274 
   275     }
   276 
   277     @Override
   278     public void paintContent(final PaintTarget target) throws PaintException {
   279         super.paintContent(target);
   280         client.paintContent(target);
   281     }
   282 
   283     @Override
   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"));
   290         }
   291         if (variables.containsKey("height")) {
   292             setHeight((String) variables.get("height"));
   293         }
   294         if (variables.containsKey("fontw")) {
   295             fontw = (Integer) variables.get("fontw");
   296         }
   297         if (variables.containsKey("fonth")) {
   298             fonth = (Integer) variables.get("fonth");
   299         }
   300         if (variables.containsKey("cols")) {
   301             config.cols = (Integer) variables.get("cols");
   302         }
   303         if (variables.containsKey("rows")) {
   304             config.rows = (Integer) variables.get("rows");
   305         }
   306     }
   307 
   308     /**
   309      * Overridden to filter client-side calculation/changes and avoid loops.
   310      *
   311      */
   312     @Override
   313     public void setWidth(float width, int unit) {
   314         if (width != getWidth() || unit != getWidthUnits()) {
   315             super.setWidth(width, unit);
   316         }
   317     }
   318 
   319     /**
   320      * Overridden to filter client-side calculation/changes and avoid loops.
   321      *
   322      */
   323     @Override
   324     public void setHeight(float height, int unit) {
   325         if (height != getHeight() || unit != getHeightUnits()) {
   326             super.setHeight(height, unit);
   327         }
   328     }
   329 
   330     protected void handleSuggest(final String input) {
   331 
   332         final boolean cancelIfNotASingleMatch = (input != null && !input
   333                 .equals(lastSuggestInput));
   334         lastSuggestInput = input;
   335 
   336         final Set<String> matches = handler.getSuggestions(this, input);
   337 
   338         if (matches == null || matches.size() == 0) {
   339             bell();
   340             return;
   341         }
   342 
   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
   349             // match
   350         } else {
   351 
   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++) {
   356                 char c = 0;
   357                 boolean charMatch = true;
   358                 for (final String m : matches) {
   359                     if (c == 0) {
   360                         c = m.charAt(i);
   361                     } else if (i < m.length()) {
   362                         charMatch &= m.charAt(i) == c;
   363                         if (!charMatch) {
   364                             break;
   365                         }
   366                     } else {
   367                         charMatch = false;
   368                         break;
   369                     }
   370                 }
   371                 if (charMatch) {
   372                     commonPrefix.append(c);
   373                 }
   374             }
   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);
   381                 }
   382                 print(suggestions.toString());
   383             } else {
   384                 bell();
   385                 lastSuggestInput = output; // next suggest will not beep
   386             }
   387         }
   388         prompt(output);
   389         focus();
   390 
   391     }
   392 
   393     public void bell() {
   394         client.call("bell");
   395     }
   396 
   397     protected void handleInput(final String input) {
   398 
   399         // Ask registered handler
   400         handler.inputReceived(this, input);
   401 
   402     }
   403 
   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]);
   408             if (c != null) {
   409                 final String result = executeCommand(c, argv);
   410                 if (result != null) {
   411                     print(result);
   412                 }
   413             } else {
   414                 handler.commandNotFound(this, argv);
   415             }
   416         }
   417     }
   418 
   419     protected String executeCommand(final Command cmd, final String[] argv) {
   420         try {
   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);
   425         }
   426         return null;
   427     }
   428 
   429     protected String parseCommandPrefix(final String input) {
   430         if (input == null) {
   431             return null;
   432         }
   433         if (!input.endsWith(" ")) {
   434             final String[] argv = parseInput(input);
   435             if (argv != null && argv.length > 0) {
   436                 return argv[argv.length - 1];
   437             }
   438         }
   439         return "";
   440     }
   441 
   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
   455                             current = null;
   456                         } else {
   457                             current = element.replaceAll("\"", ""); // start
   458                         }
   459                     } else if (current != null) {
   460                         current += " " + element.replaceAll("\"", "");
   461                     } else {
   462                         parsed.add(element.replaceAll("\"", ""));
   463                     }
   464                 }
   465 
   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("\"", ""));
   470                 }
   471                 return parsed.toArray(new String[] {});
   472             }
   473         }
   474         return new String[] {};
   475     }
   476 
   477     protected static int count(final String sourceString, final char lookFor) {
   478         if (sourceString == null) {
   479             return -1;
   480         }
   481         int count = 0;
   482         for (int i = 0; i < sourceString.length(); i++) {
   483             final char c = sourceString.charAt(i);
   484             if (c == lookFor) {
   485                 count++;
   486             }
   487         }
   488         return count;
   489     }
   490 
   491     public void print(final String output) {
   492         client.call("print", output);
   493     }
   494 
   495 	/**
   496 	 * @param output
   497 	 * @param className CSS class name for string
   498 	 */
   499 	public void print(final String output, final String className) {
   500 		client.call("print", output, className);
   501 	}
   502 
   503     public String getGreeting() {
   504         return config.greeting;
   505     }
   506 
   507     public String getPs() {
   508         return config.ps;
   509     }
   510 
   511     public int getMaxBufferSize() {
   512         return config.maxBufferSize;
   513     }
   514 
   515     public int getRows() {
   516         return config.rows;
   517     }
   518 
   519     public void setGreeting(final String greeting) {
   520         config.greeting = greeting;
   521         client.call("setGreeting", greeting);
   522     }
   523 
   524     public void setPs(final String ps) {
   525         config.ps = ps == null ? DEFAULT_PS : ps;
   526         client.call("setPs", config.ps);
   527     }
   528 
   529     public void setMaxBufferSize(final int lines) {
   530         config.maxBufferSize = lines > 0 ? lines : 0;
   531         client.call("setMaxBufferSize", config.maxBufferSize);
   532     }
   533 
   534     public void setRows(final int rows) {
   535         config.rows = rows;
   536         if (config.rows < 1) {
   537             config.rows = 1;
   538         }
   539         if (config.rows > MAX_ROWS) {
   540             config.rows = MAX_ROWS;
   541         }
   542         client.call("setRows", rows);
   543     }
   544 
   545     public int getCols() {
   546         return config.cols;
   547     }
   548 
   549     public void setCols(final int cols) {
   550         config.cols = cols;
   551         if (config.cols < 1) {
   552             config.cols = 1;
   553         }
   554         if (config.cols > MAX_COLS) {
   555             config.cols = MAX_COLS;
   556         }
   557         client.call("setCols", config.cols);
   558     }
   559 
   560     public void prompt() {
   561         client.call("prompt");
   562     }
   563 
   564     public void prompt(final String initialInput) {
   565         client.call("prompt", initialInput);
   566     }
   567 
   568     public void println(final String string) {
   569         client.call("println", string);
   570     }
   571 
   572 	/**
   573 	 * @param string
   574 	 * @param className CSS class name for string
   575 	 */
   576 	public void println(final String string, final String className) {
   577 		client.call("println", string, className);
   578 	}
   579     
   580     public void append(final String string) {
   581     	client.call("append", string);
   582     }
   583 
   584 	/**
   585 	 * @param string
   586 	 * @param className CSS class name for string
   587 	 */
   588 	public void append(final String string, final String className) {
   589 		client.call("append", string, className);
   590 	}
   591 
   592     public void newLine() {
   593         client.call("newLine");
   594     }
   595 
   596 	public void newLineIfNotEndsWithNewLine() {
   597 		client.call("newLineIfNotEndsWithNewLine");
   598 	}
   599 
   600     public void reset() {
   601         client.call("reset");
   602     }
   603 
   604     public void clear() {
   605         formFeed();
   606     }
   607 
   608     public void formFeed() {
   609         client.call("ff");
   610     }
   611 
   612     public void carriageReturn() {
   613         client.call("cr");
   614     }
   615 
   616     public void lineFeed() {
   617         client.call("lf");
   618     }
   619 
   620     public void clearCommandHistory() {
   621         client.call("clearHistory");
   622     }
   623 
   624     public void clearBuffer() {
   625         client.call("clearBuffer");
   626     }
   627 
   628     public void scrollToEnd() {
   629         client.call("scrollToEnd");
   630     }
   631     
   632     public void focusInput() {
   633     	client.call("focusInput");
   634     }
   635 
   636     /**
   637      * Gets the Tabulator index of this Focusable component.
   638      *
   639      * @see com.vaadin.ui.Component.Focusable#getTabIndex()
   640      */
   641     public int getTabIndex() {
   642         return tabIndex;
   643     }
   644 
   645     /**
   646      * Sets the Tabulator index of this Focusable component.
   647      *
   648      * @see com.vaadin.ui.Component.Focusable#setTabIndex(int)
   649      */
   650     public void setTabIndex(final int tabIndex) {
   651         this.tabIndex = tabIndex;
   652     }
   653 
   654     /**
   655      * {@inheritDoc}
   656      */
   657     @Override
   658     public void focus() {
   659         super.focus();
   660     }
   661 
   662     /* PrintStream implementation for console output. */
   663 
   664     public PrintStream getPrintStream() {
   665         if (printStream == null) {
   666             printStream = new PrintStream(new OutputStream() {
   667 
   668                 ByteArrayOutputStream buffer = new ByteArrayOutputStream();
   669 
   670                 @Override
   671                 public void write(final int b) throws IOException {
   672                     buffer.write(b);
   673                     // Line buffering
   674                     if (13 == b) {
   675                         flush();
   676                     }
   677                 }
   678 
   679                 @Override
   680                 public void flush() throws IOException {
   681                     super.flush();
   682                     buffer.flush();
   683                     Console.this.print(buffer.toString());
   684                     buffer.reset();
   685                 }
   686             }, true);
   687         }
   688         return printStream;
   689     }
   690 
   691     /* Generic command handling */
   692 
   693     /**
   694      * Add a Command to this Console.
   695      *
   696      * This will override the any commands of the same name available via
   697      * {@link CommandProvider}.
   698      */
   699     public void addCommand(final String name, final Command cmd) {
   700         commands.put(name, cmd);
   701     }
   702 
   703     /**
   704      * Remove a command from this console.
   705      *
   706      * This does not remove Command available from {@link CommandProvider}.
   707      *
   708      * @param cmdName
   709      */
   710     public void removeCommand(final String cmdName) {
   711         commands.remove(cmdName);
   712     }
   713 
   714     /**
   715      * Get a Command by its name.
   716      *
   717      * @param cmdName
   718      * @return
   719      */
   720     public Command getCommand(final String cmdName) {
   721 
   722         // Try directly registered command first
   723         Command cmd = commands.get(cmdName);
   724         if (cmd != null) {
   725             return cmd;
   726         }
   727 
   728         // Ask from the providers
   729         if (commandProviders != null) {
   730             for (final CommandProvider cp : commandProviders) {
   731                 cmd = cp.getCommand(this, cmdName);
   732                 if (cmd != null) {
   733                     return cmd;
   734                 }
   735             }
   736         }
   737 
   738         // Not found
   739         return null;
   740     }
   741 
   742     /**
   743      * Get the current Console Handler.
   744      *
   745      * @return
   746      */
   747     public Handler getHandler() {
   748         return handler;
   749     }
   750 
   751     /**
   752      * Set the handler for this console.
   753      *
   754      * @see Handler
   755      * @param handler
   756      */
   757     public void setHandler(final Handler handler) {
   758         this.handler = handler != null ? handler : new DefaultConsoleHandler();
   759     }
   760 
   761     /**
   762      * Get map of available commands in this Console.
   763      *
   764      * @return
   765      */
   766     public Set<String> getCommands() {
   767         final Set<String> res = new HashSet<String>();
   768         if (commandProviders != null) {
   769             for (final CommandProvider cp : commandProviders) {
   770                 res.addAll(cp.getAvailableCommands(this));
   771             }
   772         }
   773         res.addAll(commands.keySet());
   774         return Collections.unmodifiableSet(res);
   775     }
   776 
   777 }