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