src/main/java/org/vaadin/console/Console.java
author indvdum
Wed, 18 May 2011 00:43:34 +0400
changeset 5 01a04ffaf85f
parent 4 27bd1032a5c6
child 6 8a7e51bd3ddb
permissions -rw-r--r--
*
     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     public String getGreeting() {
   496         return config.greeting;
   497     }
   498 
   499     public String getPs() {
   500         return config.ps;
   501     }
   502 
   503     public int getMaxBufferSize() {
   504         return config.maxBufferSize;
   505     }
   506 
   507     public int getRows() {
   508         return config.rows;
   509     }
   510 
   511     public void setGreeting(final String greeting) {
   512         config.greeting = greeting;
   513         client.call("setGreeting", greeting);
   514     }
   515 
   516     public void setPs(final String ps) {
   517         config.ps = ps == null ? DEFAULT_PS : ps;
   518         client.call("setPs", config.ps);
   519     }
   520 
   521     public void setMaxBufferSize(final int lines) {
   522         config.maxBufferSize = lines > 0 ? lines : 0;
   523         client.call("setMaxBufferSize", config.maxBufferSize);
   524     }
   525 
   526     public void setRows(final int rows) {
   527         config.rows = rows;
   528         if (config.rows < 1) {
   529             config.rows = 1;
   530         }
   531         if (config.rows > MAX_ROWS) {
   532             config.rows = MAX_ROWS;
   533         }
   534         client.call("setRows", rows);
   535     }
   536 
   537     public int getCols() {
   538         return config.cols;
   539     }
   540 
   541     public void setCols(final int cols) {
   542         config.cols = cols;
   543         if (config.cols < 1) {
   544             config.cols = 1;
   545         }
   546         if (config.cols > MAX_COLS) {
   547             config.cols = MAX_COLS;
   548         }
   549         client.call("setCols", config.cols);
   550     }
   551 
   552     public void prompt() {
   553         client.call("prompt");
   554     }
   555 
   556     public void prompt(final String initialInput) {
   557         client.call("prompt", initialInput);
   558     }
   559 
   560     public void println(final String string) {
   561         client.call("println", string);
   562     }
   563     
   564     public void append(final String string) {
   565     	client.call("append", string);
   566     }
   567 
   568     public void newLine() {
   569         client.call("newLine");
   570     }
   571 
   572     public void reset() {
   573         client.call("reset");
   574     }
   575 
   576     public void clear() {
   577         formFeed();
   578     }
   579 
   580     public void formFeed() {
   581         client.call("ff");
   582     }
   583 
   584     public void carriageReturn() {
   585         client.call("cr");
   586     }
   587 
   588     public void lineFeed() {
   589         client.call("lf");
   590     }
   591 
   592     public void clearCommandHistory() {
   593         client.call("clearHistory");
   594     }
   595 
   596     public void clearBuffer() {
   597         client.call("clearBuffer");
   598     }
   599 
   600     public void scrollToEnd() {
   601         client.call("scrollToEnd");
   602     }
   603     
   604     public void focusInput() {
   605     	client.call("focusInput");
   606     }
   607 
   608     /**
   609      * Gets the Tabulator index of this Focusable component.
   610      *
   611      * @see com.vaadin.ui.Component.Focusable#getTabIndex()
   612      */
   613     public int getTabIndex() {
   614         return tabIndex;
   615     }
   616 
   617     /**
   618      * Sets the Tabulator index of this Focusable component.
   619      *
   620      * @see com.vaadin.ui.Component.Focusable#setTabIndex(int)
   621      */
   622     public void setTabIndex(final int tabIndex) {
   623         this.tabIndex = tabIndex;
   624     }
   625 
   626     /**
   627      * {@inheritDoc}
   628      */
   629     @Override
   630     public void focus() {
   631         super.focus();
   632     }
   633 
   634     /* PrintStream implementation for console output. */
   635 
   636     public PrintStream getPrintStream() {
   637         if (printStream == null) {
   638             printStream = new PrintStream(new OutputStream() {
   639 
   640                 ByteArrayOutputStream buffer = new ByteArrayOutputStream();
   641 
   642                 @Override
   643                 public void write(final int b) throws IOException {
   644                     buffer.write(b);
   645                     // Line buffering
   646                     if (13 == b) {
   647                         flush();
   648                     }
   649                 }
   650 
   651                 @Override
   652                 public void flush() throws IOException {
   653                     super.flush();
   654                     buffer.flush();
   655                     Console.this.print(buffer.toString());
   656                     buffer.reset();
   657                 }
   658             }, true);
   659         }
   660         return printStream;
   661     }
   662 
   663     /* Generic command handling */
   664 
   665     /**
   666      * Add a Command to this Console.
   667      *
   668      * This will override the any commands of the same name available via
   669      * {@link CommandProvider}.
   670      */
   671     public void addCommand(final String name, final Command cmd) {
   672         commands.put(name, cmd);
   673     }
   674 
   675     /**
   676      * Remove a command from this console.
   677      *
   678      * This does not remove Command available from {@link CommandProvider}.
   679      *
   680      * @param cmdName
   681      */
   682     public void removeCommand(final String cmdName) {
   683         commands.remove(cmdName);
   684     }
   685 
   686     /**
   687      * Get a Command by its name.
   688      *
   689      * @param cmdName
   690      * @return
   691      */
   692     public Command getCommand(final String cmdName) {
   693 
   694         // Try directly registered command first
   695         Command cmd = commands.get(cmdName);
   696         if (cmd != null) {
   697             return cmd;
   698         }
   699 
   700         // Ask from the providers
   701         if (commandProviders != null) {
   702             for (final CommandProvider cp : commandProviders) {
   703                 cmd = cp.getCommand(this, cmdName);
   704                 if (cmd != null) {
   705                     return cmd;
   706                 }
   707             }
   708         }
   709 
   710         // Not found
   711         return null;
   712     }
   713 
   714     /**
   715      * Get the current Console Handler.
   716      *
   717      * @return
   718      */
   719     public Handler getHandler() {
   720         return handler;
   721     }
   722 
   723     /**
   724      * Set the handler for this console.
   725      *
   726      * @see Handler
   727      * @param handler
   728      */
   729     public void setHandler(final Handler handler) {
   730         this.handler = handler != null ? handler : new DefaultConsoleHandler();
   731     }
   732 
   733     /**
   734      * Get map of available commands in this Console.
   735      *
   736      * @return
   737      */
   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));
   743             }
   744         }
   745         res.addAll(commands.keySet());
   746         return Collections.unmodifiableSet(res);
   747     }
   748 
   749 }