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