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