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