# HG changeset patch # User indvdum # Date 1305467166 -14400 # Node ID c46bb04134cb3035e92c40197b8813d67d00dc76 + new project: vaadin-console-addon diff -r 000000000000 -r c46bb04134cb pom.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/pom.xml Sun May 15 17:46:06 2011 +0400 @@ -0,0 +1,165 @@ + + + + 4.0.0 + + org.vaadin.addons + console + 1.1.7-SNAPSHOT + jar + Vaadin Console add-on + + ru.bazon.think-easy-money + think-easy-money-all + 1.0-SNAPSHOT + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.6 + 1.6 + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.3.1 + + + true + + true + + true + + + + 1 + + + Apache License 2.0 + + + Vaadin Ltd + ${pom.name} + ${pom.version} + + + org.vaadin.console.ConsoleWidgetset + + + + + + + + + org.codehaus.mojo + gwt-maven-plugin + 2.2.0 + + + ${project.build.directory}/${project.build.finalName}/VAADIN/widgetsets + + + + -Xmx512M -Xss1024k + xsite + ${project.build.directory}/${project.build.finalName} + true + 8080 + false + + + + + resources + compile + + + + + + + + + + src/main/java + + + src/main/resources + + + + + + + updateWidgetset + + + + com.vaadin + vaadin-maven-plugin + 1.0.2 + + + + + + update-widgetset + + + + + + + + + + + + com.vaadin + vaadin + 6.6.0 + + + org.vaadin.addons + widget-rpc + 1.1.3 + + + com.google.gwt + gwt-user + 2.2.0 + provided + + + + diff -r 000000000000 -r c46bb04134cb src/main/java/org/vaadin/console/Console.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/vaadin/console/Console.java Sun May 15 17:46:06 2011 +0400 @@ -0,0 +1,730 @@ +package org.vaadin.console; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.io.PrintStream; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.vaadin.rpc.ServerSideHandler; +import org.vaadin.rpc.ServerSideProxy; +import org.vaadin.rpc.client.Method; + +import com.vaadin.terminal.PaintException; +import com.vaadin.terminal.PaintTarget; +import com.vaadin.ui.AbstractComponent; +import com.vaadin.ui.Component; + +/** + * Server side component for the VTextConsole widget. + * + * @author Sami Ekblad / Vaadin + * + */ +@com.vaadin.ui.ClientWidget(org.vaadin.console.client.ui.VTextConsole.class) +public class Console extends AbstractComponent implements Component.Focusable { + + private static final long serialVersionUID = 590258219352859644L; + private Handler handler; + private final HashMap commands = new HashMap(); + private final Config config = new Config(); + + private static final String DEFAULT_PS = "}> "; + private static final String DEFAULT_GREETING = "Console ready."; + private static final int DEFAULT_BUFFER = 0; + private static final int DEFAULT_COLS = -1; + private static final int DEFAULT_ROWS = -1; + private static final boolean DEFAULT_WRAP = true; + private static final int MAX_COLS = 500; + private static final int MAX_ROWS = 200; + + public boolean isWrap() { + return config.wrap; + } + + public void setWrap(final boolean wrap) { + config.wrap = wrap; + client.call("setWrap", wrap); + } + + private final ServerSideProxy client = new ServerSideProxy( + new ClientCallback()); + + /** + * Inner class to handle client calls. + * + */ + public class ClientCallback implements ServerSideHandler { + + private static final long serialVersionUID = 3992611573500588703L; + + public void requestRepaint() { + Console.this.requestRepaint(); + } + + public Object[] initRequestFromClient() { + return new Object[] { config.cols, config.rows, + config.maxBufferSize, config.wrap, config.greeting, + config.ps }; + } + + public void callFromClient(String method, Object[] params) { + // TODO Auto-generated method stub + + } + + } + + /** + * The tab order number of this field. + */ + private int tabIndex = 0; + @SuppressWarnings("unused") + private Integer fontw; + @SuppressWarnings("unused") + private Integer fonth; + private PrintStream printStream; + private String lastSuggestInput; + private List commandProviders; + + /** + * An inner class for holding the configuration data. + */ + public static class Config implements Serializable { + + private static final long serialVersionUID = -812601232248504108L; + + int maxBufferSize = DEFAULT_BUFFER; + int cols = DEFAULT_COLS; + int rows = DEFAULT_ROWS; + boolean wrap = DEFAULT_WRAP; + String ps = DEFAULT_PS; + String greeting = DEFAULT_GREETING; + + } + + /** + * Console Handler interface. + * + * Handler provides a hook to handle various console related events and + * override the default processing. + * + */ + public interface Handler extends Serializable { + + /** + * Called when user uses TAB to complete the command entered into the + * Console input. + * + * @param console + * @param lastInput + * @return + */ + Set getSuggestions(Console console, String lastInput); + + /** + * Called when user has entered input to the Console and presses enter + * to execute it. + * + * @param console + * @param lastInput + */ + void inputReceived(Console console, String lastInput); + + /** + * Handle an exception during a Command execution. + * + * @param console + * @param e + * @param cmd + * @param argv + */ + void handleException(Console console, Exception e, Command cmd, + String[] argv); + + /** + * Handle situation where a command could not be found. + * + * @param console + * @param argv + */ + void commandNotFound(Console console, String[] argv); + + } + + /** + * Commands that can be executed against the Component instance. They + * provide convenient string to method mapping. Basically, a Command is a + * method that that can be executed in Component. It can have parameters or + * not. + * + */ + public interface Command extends Serializable { + + /** + * Execute a Command with arguments. + * + * @param console + * @param argv + * @return + * @throws Exception + */ + public Object execute(Console console, String[] argv) throws Exception; + + /** + * Get usage information about this command. + * + * @param console + * @param argv + * @return + */ + public String getUsage(Console console, String[] argv); + } + + /** + * Interface for providing Commands to the console. One can register a + * command providers to console instead of individual commands to provide a + * lot of commands. + * + */ + public interface CommandProvider extends Serializable { + + /** + * List all available command from this provider. + * + * @param console + * @return + */ + Set getAvailableCommands(Console console); + + /** + * Get Command instance based on command name. + * + * @param console + * @param commandName + * @return + */ + Command getCommand(Console console, String commandName); + + } + + public void addCommandProvider(final CommandProvider commandProvider) { + if (commandProviders == null) { + commandProviders = new ArrayList(); + } + commandProviders.add(commandProvider); + } + + public void removeCommandProvider(final CommandProvider commandProvider) { + if (commandProviders == null) { + return; + } + commandProviders.remove(commandProvider); + } + + public void removeAllCommandProviders() { + if (commandProviders == null) { + return; + } + commandProviders.clear(); + } + + public Console(final Console.Handler handler) { + this(); + setHandler(handler); + } + + public Console() { + setImmediate(true); + setHandler(new DefaultConsoleHandler()); + registerCallbacks(); + } + + private void registerCallbacks() { + client.register("suggest", new Method() { + + public void invoke(String methodName, Object[] params) { + handleSuggest((String) params[0]); + } + }); + client.register("input", new Method() { + + public void invoke(String methodName, Object[] params) { + handleInput((String) params[0]); + } + }); + + } + + @Override + public void paintContent(final PaintTarget target) throws PaintException { + super.paintContent(target); + client.paintContent(target); + } + + @Override + public void changeVariables(final Object source, + final Map variables) { + super.changeVariables(source, variables); + client.changeVariables(source, variables); + if (variables.containsKey("width")) { + setWidth((String) variables.get("width")); + } + if (variables.containsKey("height")) { + setHeight((String) variables.get("height")); + } + if (variables.containsKey("fontw")) { + fontw = (Integer) variables.get("fontw"); + } + if (variables.containsKey("fonth")) { + fonth = (Integer) variables.get("fonth"); + } + if (variables.containsKey("cols")) { + config.cols = (Integer) variables.get("cols"); + } + if (variables.containsKey("rows")) { + config.rows = (Integer) variables.get("rows"); + } + } + + /** + * Overridden to filter client-side calculation/changes and avoid loops. + * + */ + @Override + public void setWidth(float width, int unit) { + if (width != getWidth() || unit != getWidthUnits()) { + super.setWidth(width, unit); + } + } + + /** + * Overridden to filter client-side calculation/changes and avoid loops. + * + */ + @Override + public void setHeight(float height, int unit) { + if (height != getHeight() || unit != getHeightUnits()) { + super.setHeight(height, unit); + } + } + + protected void handleSuggest(final String input) { + + final boolean cancelIfNotASingleMatch = (input != null && !input + .equals(lastSuggestInput)); + lastSuggestInput = input; + + final Set matches = handler.getSuggestions(this, input); + + if (matches == null || matches.size() == 0) { + bell(); + return; + } + + // Output the original + final String prefix = parseCommandPrefix(input); + String output = input.substring(0, input.lastIndexOf(prefix)); + if (matches.size() == 1) { + // Output the only match + output += matches.iterator().next() + " "; // append the single + // match + } else { + + // We output until the common prefix + StringBuilder commonPrefix = new StringBuilder(prefix); + final int maxLen = matches.iterator().next().length(); + for (int i = prefix.length(); i < maxLen; i++) { + char c = 0; + boolean charMatch = true; + for (final String m : matches) { + if (c == 0) { + c = m.charAt(i); + } else if (i < m.length()) { + charMatch &= m.charAt(i) == c; + if (!charMatch) { + break; + } + } else { + charMatch = false; + break; + } + } + if (charMatch) { + commonPrefix.append(c); + } + } + output += commonPrefix.toString(); + if (prefix.equals(commonPrefix.toString()) + && !cancelIfNotASingleMatch) { + final StringBuffer suggestions = new StringBuffer("\n"); + for (final String m : matches) { + suggestions.append(" " + m); + } + print(suggestions.toString()); + } else { + bell(); + lastSuggestInput = output; // next suggest will not beep + } + } + prompt(output); + focus(); + + } + + public void bell() { + client.call("bell"); + } + + protected void handleInput(final String input) { + + // Ask registered handler + handler.inputReceived(this, input); + + } + + protected void parseAndExecuteCommand(final String input) { + final String[] argv = parseInput(input); + if (argv != null && argv.length > 0) { + final Command c = getCommand(argv[0]); + if (c != null) { + final String result = executeCommand(c, argv); + if (result != null) { + print(result); + } + } else { + handler.commandNotFound(this, argv); + } + } + } + + protected String executeCommand(final Command cmd, final String[] argv) { + try { + final Object r = cmd.execute(this, argv); + return r != null ? "" + r : null; + } catch (final Exception e) { + handler.handleException(this, e, cmd, argv); + } + return null; + } + + protected String parseCommandPrefix(final String input) { + if (input == null) { + return null; + } + if (!input.endsWith(" ")) { + final String[] argv = parseInput(input); + if (argv != null && argv.length > 0) { + return argv[argv.length - 1]; + } + } + return ""; + } + + protected static String[] parseInput(final String input) { + if (input != null && !"".equals(input.trim())) { + final String[] temp = input.split(" "); + if (temp != null && temp.length > 0) { + final List parsed = new ArrayList(temp.length); + String current = null; + for (final String element : temp) { + final int quotCount = count(element, '\"'); + if (quotCount > 0 && quotCount % 2 != 0) { + // uneven number of quotes star or end combining params + if (current != null) { + parsed.add(current + " " + + element.replaceAll("\"", "")); // end + current = null; + } else { + current = element.replaceAll("\"", ""); // start + } + } else if (current != null) { + current += " " + element.replaceAll("\"", ""); + } else { + parsed.add(element.replaceAll("\"", "")); + } + } + + // TODO: actually this is not quite right: We have an open quote + // somewhere. Exception maybe? + if (current != null) { + parsed.add(current.replaceAll("\"", "")); + } + return parsed.toArray(new String[] {}); + } + } + return new String[] {}; + } + + protected static int count(final String sourceString, final char lookFor) { + if (sourceString == null) { + return -1; + } + int count = 0; + for (int i = 0; i < sourceString.length(); i++) { + final char c = sourceString.charAt(i); + if (c == lookFor) { + count++; + } + } + return count; + } + + public void print(final String output) { + client.call("print", output); + } + + public String getGreeting() { + return config.greeting; + } + + public String getPs() { + return config.ps; + } + + public int getMaxBufferSize() { + return config.maxBufferSize; + } + + public int getRows() { + return config.rows; + } + + public void setGreeting(final String greeting) { + config.greeting = greeting; + client.call("setGreeting", greeting); + } + + public void setPs(final String ps) { + config.ps = ps == null ? DEFAULT_PS : ps; + client.call("setPs", config.ps); + } + + public void setMaxBufferSize(final int lines) { + config.maxBufferSize = lines > 0 ? lines : 0; + client.call("setMaxBufferSize", config.maxBufferSize); + } + + public void setRows(final int rows) { + config.rows = rows; + if (config.rows < 1) { + config.rows = 1; + } + if (config.rows > MAX_ROWS) { + config.rows = MAX_ROWS; + } + client.call("setRows", rows); + } + + public int getCols() { + return config.cols; + } + + public void setCols(final int cols) { + config.cols = cols; + if (config.cols < 1) { + config.cols = 1; + } + if (config.cols > MAX_COLS) { + config.cols = MAX_COLS; + } + client.call("setCols", config.cols); + } + + public void prompt() { + client.call("prompt"); + } + + public void prompt(final String initialInput) { + client.call("prompt", initialInput); + } + + public void println(final String string) { + client.call("println", string); + } + + public void newLine() { + client.call("newLine"); + } + + public void reset() { + client.call("reset"); + } + + public void clear() { + formFeed(); + } + + public void formFeed() { + client.call("ff"); + } + + public void carriageReturn() { + client.call("cr"); + } + + public void lineFeed() { + client.call("lf"); + } + + public void clearCommandHistory() { + client.call("clearHistory"); + } + + public void clearBuffer() { + client.call("clearBuffer"); + } + + public void scrollToEnd() { + client.call("scrollToEnd"); + } + + /** + * Gets the Tabulator index of this Focusable component. + * + * @see com.vaadin.ui.Component.Focusable#getTabIndex() + */ + public int getTabIndex() { + return tabIndex; + } + + /** + * Sets the Tabulator index of this Focusable component. + * + * @see com.vaadin.ui.Component.Focusable#setTabIndex(int) + */ + public void setTabIndex(final int tabIndex) { + this.tabIndex = tabIndex; + } + + /** + * {@inheritDoc} + */ + @Override + public void focus() { + super.focus(); + } + + /* PrintStream implementation for console output. */ + + public PrintStream getPrintStream() { + if (printStream == null) { + printStream = new PrintStream(new OutputStream() { + + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + + @Override + public void write(final int b) throws IOException { + buffer.write(b); + // Line buffering + if (13 == b) { + flush(); + } + } + + @Override + public void flush() throws IOException { + super.flush(); + buffer.flush(); + Console.this.print(buffer.toString()); + buffer.reset(); + } + }, true); + } + return printStream; + } + + /* Generic command handling */ + + /** + * Add a Command to this Console. + * + * This will override the any commands of the same name available via + * {@link CommandProvider}. + */ + public void addCommand(final String name, final Command cmd) { + commands.put(name, cmd); + } + + /** + * Remove a command from this console. + * + * This does not remove Command available from {@link CommandProvider}. + * + * @param cmdName + */ + public void removeCommand(final String cmdName) { + commands.remove(cmdName); + } + + /** + * Get a Command by its name. + * + * @param cmdName + * @return + */ + public Command getCommand(final String cmdName) { + + // Try directly registered command first + Command cmd = commands.get(cmdName); + if (cmd != null) { + return cmd; + } + + // Ask from the providers + if (commandProviders != null) { + for (final CommandProvider cp : commandProviders) { + cmd = cp.getCommand(this, cmdName); + if (cmd != null) { + return cmd; + } + } + } + + // Not found + return null; + } + + /** + * Get the current Console Handler. + * + * @return + */ + public Handler getHandler() { + return handler; + } + + /** + * Set the handler for this console. + * + * @see Handler + * @param handler + */ + public void setHandler(final Handler handler) { + this.handler = handler != null ? handler : new DefaultConsoleHandler(); + } + + /** + * Get map of available commands in this Console. + * + * @return + */ + public Set getCommands() { + final Set res = new HashSet(); + if (commandProviders != null) { + for (final CommandProvider cp : commandProviders) { + res.addAll(cp.getAvailableCommands(this)); + } + } + res.addAll(commands.keySet()); + return Collections.unmodifiableSet(res); + } + +} diff -r 000000000000 -r c46bb04134cb src/main/java/org/vaadin/console/ConsoleWidgetset.gwt.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/vaadin/console/ConsoleWidgetset.gwt.xml Sun May 15 17:46:06 2011 +0400 @@ -0,0 +1,26 @@ + + + + + + + + + + + + diff -r 000000000000 -r c46bb04134cb src/main/java/org/vaadin/console/DefaultConsoleHandler.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/vaadin/console/DefaultConsoleHandler.java Sun May 15 17:46:06 2011 +0400 @@ -0,0 +1,48 @@ +package org.vaadin.console; + +import java.util.HashSet; +import java.util.Set; + +import org.vaadin.console.Console.Command; +import org.vaadin.console.Console.Handler; + +/** + * Default handler for console. + * + */ +public class DefaultConsoleHandler implements Handler { + + private static final long serialVersionUID = 1L; + + public void handleException(final Console console, final Exception e, + final Command cmd, final String[] argv) { + e.printStackTrace(); + console.println(e.getClass().getSimpleName() + ": " + e.getMessage()); + } + + public Set getSuggestions(final Console console, final String input) { + + final String prefix = console.parseCommandPrefix(input); + if (prefix != null) { + final Set matches = new HashSet(); + final Set cmds = console.getCommands(); + for (final String cmd : cmds) { + if (cmd.startsWith(prefix)) { + matches.add(cmd); + } + } + return matches; + } + return null; + } + + public void inputReceived(final Console console, final String lastInput) { + console.parseAndExecuteCommand(lastInput); + console.prompt(); + } + + public void commandNotFound(final Console console, final String[] argv) { + console.print("ERROR: " + argv[0] + ": command not found."); + } + +} diff -r 000000000000 -r c46bb04134cb src/main/java/org/vaadin/console/ObjectInspector.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/vaadin/console/ObjectInspector.java Sun May 15 17:46:06 2011 +0400 @@ -0,0 +1,420 @@ +package org.vaadin.console; + +import java.beans.BeanInfo; +import java.beans.Introspector; +import java.beans.PropertyDescriptor; +import java.io.Serializable; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.vaadin.console.Console.Command; + +import com.vaadin.ui.Component; + +/** + * Java object inspector. + * + * With object inspector you can simply wire methods from a class as commands to + * the Console. + * + * @author Sami Ekblad + * + */ +public class ObjectInspector implements Serializable, Console.CommandProvider { + private static final long serialVersionUID = -5001688079827306472L; + private static final List OBJECT_BLACKLIST = Arrays + .asList(new String[] { "equals", "class", "hashCode", "notify", + "notifyAll", "toString", "wait" }); + private static final List VAADIN_BLACKLIST = Arrays + .asList(new String[] { "addListener", "attach", "application", + "changeVariables", "childRequestedRepaint", + "componentError", "detach", "handleError", "paint", + "paintContent", "removeListener", "requestRepaint", + "requestRepaintRequests", "style", "tag" }); + + private Object theObject; + private final Map commands = new HashMap(); + private Set ignoredCommands = new HashSet(); + + public ObjectInspector(final Object obj) { + + // Default ignores + ignoredCommands.addAll(OBJECT_BLACKLIST); + if (obj instanceof Component) { + ignoredCommands.addAll(VAADIN_BLACKLIST); + } + + // Create bean information + setObject(obj); + + } + + private void setObject(final Object c) { + theObject = c; + listBeanPropertyCommands(); + listMethodCommands(); + } + + public Set getAvailableCommands() { + final List l = new ArrayList(); + l.addAll(commands.keySet()); + Collections.sort(l); + return new LinkedHashSet(l); + } + + + + private void listMethodCommands() { + + final Method[] methods = theObject.getClass().getMethods(); + for (final Method method : methods) { + final Method m = method; + if (!isBeanGetter(m) && !isBeanSetter(m)) { + + String un = m.getName(); + if (isIgnored(un) + || !isParamTypesOkForConsole(m.getParameterTypes())) { + continue; + } + + // Make unique. Try param names first. + if (commands.containsKey(un)) { + un += paramsToShortString(m.getParameterTypes()); + } + + // Fallback to appending number + int j = 1; + while (commands.containsKey(un)) { + un = m.getName() + (j++); + } + + final Caller cmd = m.getParameterTypes().length == 0 ? new Caller(theObject, + m.getName(), null, m.getParameterTypes()) : new Caller(theObject, + null, m.getName(), m.getParameterTypes()); + commands.put(un, cmd); + } + } + } + + private String paramsToShortString(final Class[] parameterTypes) { + StringBuilder s = new StringBuilder(); + if (parameterTypes != null) { + for (final Class c : parameterTypes) { + s.append(c.getSimpleName().substring(0, 3)); + } + } + return s.toString(); + } + + private boolean isBeanSetter(final Method m) { + if (m.getName().startsWith("set")) { + Method setMethod = null; + try { + final String n = "g" + m.getName().substring(1); + setMethod = m.getDeclaringClass().getMethod(n); + } catch (final SecurityException e) { + } catch (final NoSuchMethodException e) { + } + if (setMethod == null) { + try { + final String n = "is" + m.getName().substring(3); + setMethod = m.getDeclaringClass().getMethod(n); + } catch (final SecurityException e) { + } catch (final NoSuchMethodException e) { + } + } + return setMethod != null; + } + return false; + } + + private boolean isBeanGetter(final Method m) { + final String n = m.getName(); + return (n.startsWith("is") && n.length() > 2) + || (n.startsWith("get") && n.length() > 2); + } + + /** + *

+ * Perform introspection on a Java Bean class to find its properties. + *

+ * + *

+ * Note : This version only supports introspectable bean properties and + * their getter and setter methods. Stand-alone is and + * are methods are not supported. + *

+ * + * @param beanClass + * the Java Bean class to get properties for. + * @return an ordered map from property names to property descriptors + */ + static LinkedHashMap getPropertyDescriptors( + final Class beanClass) { + final LinkedHashMap pdMap = new LinkedHashMap(); + + // Try to introspect, if it fails, we just have an empty Item + try { + final BeanInfo info = Introspector.getBeanInfo(beanClass); + final PropertyDescriptor[] pds = info.getPropertyDescriptors(); + + // Add all the bean properties as MethodProperties to this Item + for (final PropertyDescriptor pd : pds) { + final Method getMethod = pd.getReadMethod(); + if ((getMethod != null) + && getMethod.getDeclaringClass() != Object.class) { + pdMap.put(pd.getName(), pd); + } + } + } catch (final java.beans.IntrospectionException ignored) { + } + + return pdMap; + } + + /** + * List commands for the theObject. + * + * @return + */ + private void listBeanPropertyCommands() { + + final LinkedHashMap beanProperties = getPropertyDescriptors(theObject + .getClass()); + // bean properties + for (final PropertyDescriptor p : beanProperties.values()) { + + // Make unique + final String name = p.getName(); + if (isIgnored(name)) { + continue; + } + + commands.put(name, + new Caller(theObject,p.getReadMethod().getName(), + p.getWriteMethod() != null ? p.getWriteMethod() + .getName() : null, + p.getWriteMethod() != null ? p.getWriteMethod() + .getParameterTypes() : null)); + + // beanCommands.put(un, p); + } + } + + public static boolean isParamTypesOkForConsole(final Class[] cls) { + if (cls == null) { + return true; + } + for (int i = 0; i < cls.length; i++) { + if (!isParamTypeOkForConsole(cls[i])) { + return false; + } + } + return true; + } + + public static boolean isParamTypeOkForConsole(final Class cls) { + return cls.isEnum() || cls == Boolean.class || cls == boolean.class + || cls == long.class || cls == Long.class || cls == int.class + || cls == Integer.class || cls == byte.class + || cls == Byte.class || cls == float.class + || cls == Float.class || cls == double.class + || cls == Double.class || cls == String.class; + } + + public boolean isIgnored(final String commandName) { + return getIgnoredCommands().contains(commandName); + } + + protected static Object[] argvToParams(final String[] argv, + final Class[] pt) { + if (pt.length != argv.length - 1) { + throw new IllegalArgumentException("Invalid number of parameters"); + } + final Object[] args = new Object[argv.length - 1]; + for (int j = 1; j < argv.length; j++) { + if (pt[j - 1] == String.class) { + args[j - 1] = argv[j]; + } else if (pt[j - 1] == Byte.class || pt[j - 1] == byte.class) { + args[j - 1] = Byte.parseByte(argv[j]); + } else if (pt[j - 1] == Character.class || pt[j - 1] == char.class) { + args[j - 1] = argv[j].charAt(0); + } else if (pt[j - 1] == Long.class || pt[j - 1] == long.class) { + args[j - 1] = Long.parseLong(argv[j]); + } else if (pt[j - 1] == Integer.class || pt[j - 1] == int.class) { + args[j - 1] = Integer.parseInt(argv[j]); + } else if (pt[j - 1] == Boolean.class || pt[j - 1] == boolean.class) { + args[j - 1] = Boolean.parseBoolean(argv[j]); + } else if (pt[j - 1] == Float.class || pt[j - 1] == float.class) { + args[j - 1] = Float.parseFloat(argv[j]); + } else if (pt[j - 1] == Double.class || pt[j - 1] == double.class) { + args[j - 1] = Float.parseFloat(argv[j]); + } else if (pt[j - 1].isEnum()) { + Field e; + try { + e = pt[j - 1].getDeclaredField(argv[j].toUpperCase()); + args[j - 1] = e.get(null); + } catch (final Exception e1) { + throw new IllegalArgumentException("Enum not found: " + + argv[j].toUpperCase(), e1); + } + } + } + return args; + } + + public Class[] getCommandParams(final String method) { + if (commands.containsKey(method)) { + final Caller m = commands.get(method); + return m.getParameterTypes() != null ? m.getParameterTypes() + : new Class[] {}; + } + return new Class[] {}; + } + + public void setIgnoredCommands(final Set ignoredCommands) { + this.ignoredCommands = ignoredCommands; + } + + public Set getIgnoredCommands() { + return ignoredCommands; + } + + /** + * Method wrapper that serializes nicely. + * + */ + private static class Caller implements Console.Command, Serializable { + + private static final long serialVersionUID = -810707579200844512L; + + private final Object theObject; + private final String readMethod; + private final String writeMethod; + private final Class[] paramTypes; + + transient private Method rm; + transient private Method wm; + + private Caller(final Object obj, final String read, final String write, + final Class[] params) { + theObject = obj; + readMethod = read; + writeMethod = write; + paramTypes = params; + } + + private boolean isWritable() { + return writeMethod != null && paramTypes != null + && paramTypes.length > 0; + } + + public boolean isReadable() { + return readMethod != null; + } + + public Object write(final Object[] params) throws SecurityException, + NoSuchMethodException, IllegalArgumentException, + IllegalAccessException, InvocationTargetException { + if (wm == null) { + wm = theObject.getClass().getMethod(writeMethod, paramTypes); + } + return wm.invoke(theObject, params); + } + + public Object read() throws SecurityException, NoSuchMethodException, + IllegalArgumentException, IllegalAccessException, + InvocationTargetException { + if (rm == null) { + rm = theObject.getClass().getMethod(readMethod, + new Class[] {}); + } + return rm.invoke(theObject); + } + + public Object write(final String[] argv) throws SecurityException, + NoSuchMethodException, IllegalArgumentException, + IllegalAccessException, InvocationTargetException { + return write(parseWriteParams(argv)); + } + + private Class[] getParameterTypes() { + return paramTypes; + } + + private Object[] parseWriteParams(final String[] argv) + throws SecurityException, NoSuchMethodException { + if (wm == null) { + wm = theObject.getClass().getMethod(writeMethod, paramTypes); + } + return argvToParams(argv, wm.getParameterTypes()); + } + + public Object execute(final Console console, final String[] argv) + throws Exception { +// public Object execute(final String[] argv) throws Exception { + + if (argv == null || argv.length < 1) { + throw new IllegalArgumentException("Missing command"); + } + + if (argv.length > 1 + && !isParamTypesOkForConsole(getParameterTypes())) { + throw new IllegalArgumentException("Unsupported parameter types"); + } + + if (argv.length == 1 && isReadable()) { + // Read + return read(); + } else if (isWritable()) { + // Write + if (isReadable()) { + write(argv); + return read(); // Return the read method instead + } else { + return write(argv); // return whatever is returned + } + + } + + return null; + } + public String getUsage(final Console console, final String[] argv) { + return null; + } + } + + public String getCommandUsage(final String[] argv) { + return argv[0] + " " + paramsToString(getCommandParams(argv[0])); + } + + private static String paramsToString(final Class[] paramTypes) { + StringBuilder res = new StringBuilder(); + if (paramTypes != null) { + for (final Class paramType : paramTypes) { + res.append("<" + paramType.getSimpleName() + "> "); + } + } + return res.toString(); + } + + public Set getAvailableCommands(final Console console) { + return getAvailableCommands(); + } + + public Command getCommand(final Console console, final String commandName) { + return commands.get(commandName); + } + +} diff -r 000000000000 -r c46bb04134cb src/main/java/org/vaadin/console/client/ui/TextConsole.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/vaadin/console/client/ui/TextConsole.java Sun May 15 17:46:06 2011 +0400 @@ -0,0 +1,781 @@ +package org.vaadin.console.client.ui; + +import java.util.ArrayList; +import java.util.List; + +import com.google.gwt.dom.client.DivElement; +import com.google.gwt.dom.client.Document; +import com.google.gwt.dom.client.Element; +import com.google.gwt.dom.client.InputElement; +import com.google.gwt.dom.client.Node; +import com.google.gwt.dom.client.Style.Display; +import com.google.gwt.dom.client.Style.Unit; +import com.google.gwt.dom.client.TableCellElement; +import com.google.gwt.dom.client.TableElement; +import com.google.gwt.dom.client.TableRowElement; +import com.google.gwt.dom.client.TableSectionElement; +import com.google.gwt.event.dom.client.ClickEvent; +import com.google.gwt.event.dom.client.ClickHandler; +import com.google.gwt.event.dom.client.KeyCodes; +import com.google.gwt.event.dom.client.KeyDownEvent; +import com.google.gwt.event.dom.client.KeyDownHandler; +import com.google.gwt.event.shared.HandlerRegistration; +import com.google.gwt.user.client.Timer; +import com.google.gwt.user.client.ui.FocusWidget; +import com.vaadin.terminal.gwt.client.Util; + +/** + * GWT Console Widget. + * + * @author Sami Ekblad / Vaadin + * + */ +public class TextConsole extends FocusWidget { + + /* Control characters in http://en.wikipedia.org/wiki/Control_character */ + + public static final char CTRL_BELL = 'G'; + public static final char CTRL_BACKSPACE = 'H'; + public static final char CTRL_TAB = 'I'; + public static final char CTRL_LINE_FEED = 'J'; + public static final char CTRL_FORM_FEED = 'L'; + public static final char CTRL_CARRIAGE_RETURN = 'M'; + public static final char CTRL_ESCAPE = '['; + public static final char CTRL_DELETE = '?'; + + private static final char[] CTRL = { CTRL_BELL, CTRL_BACKSPACE, CTRL_TAB, + CTRL_LINE_FEED, CTRL_FORM_FEED, CTRL_CARRIAGE_RETURN, CTRL_ESCAPE, + CTRL_DELETE }; + + public static char getControlKey(final int kc) { + for (final char c : CTRL) { + if (kc == c) { + return c; + } + } + return 0; + } + + private static final String DEFAULT_TABS = " "; + private static final int BIG_NUMBER = 100000; + private final DivElement term; + private TextConsoleConfig config; + private TextConsoleHandler handler; + private final Element buffer; + private final TableElement prompt; + private final Element ps; + private final InputElement input; + private List cmdHistory = new ArrayList(); + private int cmdHistoryIndex = -1; + private final HandlerRegistration clickHandler; + private final HandlerRegistration keyHandler; + private HandlerRegistration focusHandler; + private int fontW = -1; + private int fontH = -1; + private int scrollbarW = -1; + private int rows; + private int cols; + private String tabs = DEFAULT_TABS; + private boolean focused; + private int promptRows; + private int padding; + private final DivElement promptWrap; + private Timer timer; + private int maxBufferSize; + private String cleanPs; + private int paddingW; + + public TextConsole() { + + // Main element + term = Document.get().createDivElement(); + term.addClassName("term"); + setElement(term); + setTabIndex(0); + + // Buffer + buffer = Document.get().createElement("pre"); + buffer.addClassName("b"); + term.appendChild(buffer); + + // Prompt elements + promptWrap = Document.get().createDivElement(); + promptWrap.addClassName("pw"); + term.appendChild(promptWrap); + + prompt = Document.get().createTableElement(); + promptWrap.appendChild(prompt); + prompt.setAttribute("cellpadding", "0"); + prompt.setAttribute("cellspacing", "0"); + prompt.setAttribute("border", "0"); + prompt.addClassName("p"); + + final TableSectionElement tbody = Document.get().createTBodyElement(); + prompt.appendChild(tbody); + + final TableRowElement tr = Document.get().createTRElement(); + tbody.appendChild(tr); + + final TableCellElement psTd = Document.get().createTDElement(); + psTd.addClassName("psw"); + tr.appendChild(psTd); + + ps = Document.get().createElement("nobr"); + ps.addClassName("ps"); + psTd.appendChild(ps); + + final TableCellElement inputTd = Document.get().createTDElement(); + inputTd.addClassName("iw"); + tr.appendChild(inputTd); + + input = (InputElement) Document.get().createElement("input"); + inputTd.appendChild(input); + input.addClassName("i"); + input.setTabIndex(-1); + input.setAttribute("spellcheck", "false"); + + config = TextConsoleConfig.newInstance(); + + setPromtActive(false); + + clickHandler = addDomHandler(new ClickHandler() { + + public void onClick(final ClickEvent event) { + setFocus(true); + } + }, ClickEvent.getType()); + + keyHandler = addDomHandler(new KeyDownHandler() { + + public void onKeyDown(final KeyDownEvent event) { + + // (re-)show the prompt + setPromtActive(true); + + if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) { + event.preventDefault(); + carriageReturn(); + } else if (event.getNativeKeyCode() == KeyCodes.KEY_UP + || event.getNativeKeyCode() == KeyCodes.KEY_DOWN) { + event.preventDefault(); + handleCommandHistoryBrowse(event.getNativeKeyCode()); + } else if (event.getNativeKeyCode() == KeyCodes.KEY_TAB) { + event.preventDefault(); + suggest(); + } else if (event.getNativeKeyCode() == KeyCodes.KEY_BACKSPACE + && getInputLenght() == 0) { + bell(); + } else if (event.getNativeEvent().getCtrlKey()) { + final char ctrlChar = getControlKey(event.getNativeKeyCode()); + if (ctrlChar > 0) { + event.preventDefault(); + handleControlChar(ctrlChar); + } + } + + } + }, KeyDownEvent.getType()); + + updateFontDimensions(); + } + + protected int getInputLenght() { + final String v = input.getValue(); + if (v != null) { + return v.length(); + } + return -1; + } + + protected void handleControlChar(final char c) { + switch (c) { + case TextConsole.CTRL_BACKSPACE: + backspace(); + break; + case TextConsole.CTRL_BELL: + bell(); + break; + case TextConsole.CTRL_CARRIAGE_RETURN: + carriageReturn(); + break; + case TextConsole.CTRL_DELETE: + bell(); // TODO: not supported yet + break; + case TextConsole.CTRL_ESCAPE: + bell(); // TODO: not supported yet + break; + case TextConsole.CTRL_FORM_FEED: + formFeed(); + break; + case TextConsole.CTRL_LINE_FEED: + lineFeed(); + break; + case TextConsole.CTRL_TAB: + tab(); + break; + + default: + bell(); + break; + } + } + + protected void suggest() { + // No suggest by default. Implement by subclassing. + } + + protected void handleCommandHistoryBrowse(final int i) { + cmdHistoryIndex = i == KeyCodes.KEY_UP ? cmdHistoryIndex - 1 + : cmdHistoryIndex + 1; + if (cmdHistoryIndex >= 0 && cmdHistoryIndex < cmdHistory.size()) { + prompt(cmdHistory.get(cmdHistoryIndex)); + } else { + prompt(); + } + } + + public String getInput() { + return input.getValue(); + } + + protected void setInput(final String inputText) { + if (inputText != null) { + input.setValue(inputText); + } else { + input.setValue(""); + } + if (isFocused()) { + focusPrompt(); + } + } + + public void lineFeed() { + carriageReturn(); + } + + protected void tab() { + prompt(getInput() + "\t"); + } + + protected void backspace() { + bell(); + } + + protected void carriageReturn() { + setPromtActive(false); + // Append newline first if not there yet + if (!bufferIsEmpty() && !bufferEndsWithNewLine()) { + newLine(); + reducePrompt(-1); + } + print(getCurrentPromptContent()); + newLine(); + if (promptRows > 1) { + reducePrompt(-1); + } + String lineBuffer = getInput(); + lineBuffer = lineBuffer.trim(); + if (!"".equals(lineBuffer)) { + cmdHistory.add(lineBuffer); + cmdHistoryIndex = cmdHistory.size(); + } + if (handler != null) { + handler.terminalInput(this, lineBuffer); + } + } + + private boolean bufferIsEmpty() { + return !buffer.hasChildNodes(); + } + + private void setPromtActive(final boolean active) { + if (active && !isPromptActive()) { + prompt.getStyle().setDisplay(Display.BLOCK); + } else if (!active && isPromptActive()) { + prompt.getStyle().setDisplay(Display.NONE); + } + } + + private boolean isPromptActive() { + return !Display.NONE.getCssName() + .equals(prompt.getStyle().getDisplay()); + } + + private boolean isFocused() { + return focused; + } + + public void setConfig(final TextConsoleConfig cfg) { + config = cfg; + + updateFontDimensions(); + + scrollbarW = getScrollbarWidth(); + final String padStr = term.getStyle().getPadding(); + if (padStr != null && padStr.endsWith("px")) { + padding = Integer + .parseInt(padStr.substring(0, padStr.length() - 2)); + } else { + // _log("using default padding: 1x2"); + padding = 1; + paddingW = 2; + } + + // _log("setConfig: font=" + fontW + "x" + fontH + ";scrollbar=" + // + scrollbarW + ";cols=" + config.getCols() + ";rows=" + // + config.getRows() + ";size=" + getWidth() + "x" + getHeight()); + + setPs(config.getPs()); + setCols(config.getCols()); + setRows(config.getRows()); + setMaxBufferSize(config.getMaxBufferSize()); + } + + private void updateFontDimensions() { + + // Test element for font size + DivElement test = Document.get().createDivElement(); + test.setAttribute("style", + "position: absolute;"); + test.setInnerHTML("X"); + term.appendChild(test); + + fontW = test.getClientWidth(); + fontH = test.getClientHeight(); + if (fontW <= 0 || fontW > 100) { + fontW = test.getOffsetWidth(); + } + if (fontH <= 0|| fontH > 100) { + fontH = test.getOffsetHeight(); + } + if (fontW <= 0 || fontW > 100) { + fontW = 1; + } + if (fontH <= 0|| fontH > 100) { + fontH = 1; + } + term.removeChild(test); + } + + // Debug instrumentation. TODO: Remove. +// protected void _log(final String string) { +// ApplicationConnection.getConsole().log(string); +// } + + public TextConsoleConfig getConfig() { + return config; + } + + private boolean bufferEndsWithNewLine() { + final Node last = buffer != null ? buffer.getLastChild() : null; + // _log("last node: " + (last != null ? last.getNodeName() : "")); + return last != null && "br".equals(last.getNodeName().toLowerCase()); + } + + private Node createTextNode(final String text) { + return Document.get().createTextNode(text); + } + + private Node createBr() { + return Document.get().createBRElement(); + } + + public void focusPrompt() { + focusPrompt(-1); + } + + public void focusPrompt(final int cursorPos) { + input.focus(); + + // Focus to end + final String s = getInput(); + if (s != null && s.length() > 0) { + setSelectionRange(input, s.length(), s.length()); + } + } + + private native void setSelectionRange(Element input, int selectionStart, + int selectionEnd)/*-{ + if (input.setSelectionRange) { + input.focus(); + input.setSelectionRange(selectionStart, selectionEnd); + } + else if (input.createTextRange) { + var range = input.createTextRange(); + range.collapse(true); + range.moveEnd('character', selectionEnd); + range.moveStart('character', selectionStart); + range.select(); + } + }-*/; + + private native int getScrollbarWidth()/*-{ + + var i = $doc.createElement('p'); + i.style.width = '100%'; + i.style.height = '200px'; + var o = $doc.createElement('div'); + o.style.position = 'absolute'; + o.style.top = '0px'; + o.style.left = '0px'; + o.style.visibility = 'hidden'; + o.style.width = '200px'; + o.style.height = '150px'; + o.style.overflow = 'hidden'; + o.appendChild(i); + $doc.body.appendChild(o); + var w1 = i.offsetWidth; + var h1 = i.offsetHeight; + o.style.overflow = 'scroll'; + var w2 = i.offsetWidth; + var h2 = i.offsetHeight; + if (w1 == w2) w2 = o.clientWidth; + if (h1 == h2) h2 = o.clientWidth; + $doc.body.removeChild(o); + return w1-w2; + }-*/; + + public void newLine() { + // _log("newline"); + buffer.appendChild(createBr()); + checkBufferLimit(); + reducePrompt(1); + } + + protected void setPs(final String string) { + cleanPs = Util.escapeHTML(string); + cleanPs = cleanPs.replaceAll(" ", " "); + } + + public void prompt(final String inputText) { + setPromtActive(true); + scrollToEnd(); + ps.setInnerHTML(cleanPs); + setInput(inputText); + } + + public void scrollToEnd() { + term.setScrollTop(BIG_NUMBER); + } + + public void prompt() { + prompt(null); + } + + public void print(String string) { + if (isPromptActive()) { + setPromtActive(false); + if (!bufferIsEmpty() && !bufferEndsWithNewLine()) { + newLine(); + reducePrompt(-1); + } + string = getCurrentPromptContent() + string; + } + final boolean doWrap = config.isWrap(); + // _log("print original: '" + string + "' (" + doWrap + ")"); + String str = string.replaceAll("\t", tabs); + + // Continue to the last text node if available + final Node last = getLastTextNode(); + int linesAdded = 0; + if (last != null) { + // _log("print append to old node: '" + last.getNodeValue() + "'"); + str = last.getNodeValue() + str; + buffer.removeChild(last); + linesAdded--; + } + + // Split by the newlines anyway + int s = 0, e = str.indexOf('\n'); + while (e >= s) { + final String line = str.substring(s, e); + linesAdded += appendLine(buffer, line, doWrap ? cols : -1); + buffer.appendChild(createBr()); + s = e + 1; + e = str.indexOf('\n', s); + } + + // Print the remaining string + if (s < str.length()) { + linesAdded += appendLine(buffer, str.substring(s), doWrap ? cols + : -1); + } + + reducePrompt(linesAdded); + } + + private String getCurrentPromptContent() { + return prompt.getInnerText() + getInput(); + } + + private void reducePrompt(final int rows) { + int newRows = promptRows - rows; + if (newRows < 1) { + newRows = 1; + } + // _log("prompt reduced from " + promptRows + " to " + newRows); + setPromptHeight(newRows); + } + + private void setPromptHeight(final int rows) { + final int min = 1; + final int max = getRows(); + promptRows = rows < min ? min : (rows > max ? max : rows); + final int newHeight = fontH * rows; + // _log("Prompt height=" + newHeight); + promptWrap.getStyle().setHeight(newHeight, Unit.PX); + } + + /** + * Split long text based on length. + * + * @param parent + * @param doWrap + * @param str + * @return + */ + private int appendLine(final Node parent, String str, final int maxLine) { + int linesAdded = 0; + final boolean doWrap = maxLine > 0; + if (!doWrap) { + parent.appendChild(createTextNode(str)); + // _log("append: '" + str + "'"); + linesAdded++; + } else { + while (str.length() > maxLine) { + final String piece = str.substring(0, maxLine); + parent.appendChild(createTextNode(piece)); + parent.appendChild(createBr()); + linesAdded++; + // _log("append: '" + piece + "'"); + str = str.substring(maxLine); + } + parent.appendChild(createTextNode(str)); + // _log("append rest: '" + str + "'"); + linesAdded++; + } + + // make sore we don't exceed the maximum buffer size + checkBufferLimit(); + + return linesAdded; + } + + private void checkBufferLimit() { + + // Buffer means only offscreen lines + final int maxb = maxBufferSize + (rows - promptRows); + while (getBufferSize() > maxb && buffer.hasChildNodes()) { + buffer.removeChild(buffer.getFirstChild()); + } + + } + + private Node getLastTextNode() { + if (buffer == null) { + return null; + } + final Node l = buffer.getLastChild(); + if (l != null && l.getNodeType() == Node.TEXT_NODE) { + return l; + } + return null; + } + + public void println(final String string) { + print(string + "\n"); + } + + @Override + public void setHeight(final String height) { + final int oldh = term.getClientHeight(); + super.setHeight(height); + final int newh = term.getClientHeight(); + // _log("set height=" + height + " clientHeight="+oldh+" to "+newh); + if (newh != oldh) { + calculateRowsFromHeight(); + } + } + + protected void calculateRowsFromHeight() { + final int h = term.getClientHeight() - (2 * padding); + rows = h / fontH; + config.setRows(rows); + + // _log("calculateRowsFromHeight: font=" + fontW + "x" + fontH + // + ";scrollbar=" + scrollbarW + ";cols=" + cols + ";rows=" + // + rows + ";size=" + getWidth() + "x" + getHeight()); + + } + + protected void calculateHeightFromRows() { + super.setHeight((rows * fontH) + "px"); + + // _log("calculateHeightFromRows: font=" + fontW + "x" + fontH + // + ";scrollbar=" + scrollbarW + ";cols=" + cols + ";rows=" + // + rows + ";size=" + getWidth() + "x" + getHeight()); + + } + + protected void calculateColsFromWidth() { + final int w = term.getClientWidth(); + cols = (w - 2 * paddingW) / fontW; + config.setCols(cols); + buffer.getStyle().setWidth((cols * fontW), Unit.PX); + prompt.getStyle().setWidth((cols * fontW), Unit.PX); + // _log("calculateColsFromWidth: font=" + fontW + "x" + fontH + // + ";scrollbar=" + scrollbarW + ";cols=" + cols + ";rows=" + // + rows + ";size=" + getWidth() + "x" + getHeight()); + + } + + protected void calculateWidthFromCols() { + final int w = cols * fontW; + super.setWidth((w + scrollbarW) + "px"); + buffer.getStyle().setWidth(w, Unit.PX); + prompt.getStyle().setWidth(w, Unit.PX); + + // _log("calculateWidthFromCols: font=" + fontW + "x" + fontH + // + ";scrollbar=" + scrollbarW + ";cols=" + cols + ";rows=" + // + rows + ";size=" + getWidth() + "x" + getHeight()); + } + + @Override + public void setWidth(final String width) { + final int oldw = term.getClientWidth(); + super.setWidth(width); + final int neww = term.getClientWidth(); + // _log("set width=" + width + " clientWidth="+oldw+" to "+neww); + if (neww != oldw) { + calculateColsFromWidth(); + } + } + + @Override + public void setFocus(final boolean focused) { + this.focused = focused; + super.setFocus(focused); + if (focused) { + focusPrompt(); + } + } + + public void setHandler(final TextConsoleHandler handler) { + this.handler = handler; + + } + + public void setRows(final int rows) { + if (rows > 0) { + this.rows = rows; + calculateHeightFromRows(); + } else { + calculateRowsFromHeight(); + } + } + + public int getRows() { + return rows; + } + + public void setCols(final int cols) { + if (cols > 0) { + this.cols = cols; + calculateWidthFromCols(); + } else { + calculateColsFromWidth(); + } + } + + public int getCols() { + return cols; + } + + public void reset() { + setPromtActive(false); + clearBuffer(); + setPromptHeight(getRows()); + print(config.getGreeting()); + prompt(); + } + + public int getBufferSize() { + return (buffer.getClientHeight() / fontH); + } + + public int getMaxBufferSize() { + return maxBufferSize; + } + + public void setMaxBufferSize(final int maxBuffer) { + maxBufferSize = maxBuffer > 0 ? maxBuffer : 0; + checkBufferLimit(); + } + + public void clearBuffer() { + // Remove all children. + while (buffer.hasChildNodes()) { + buffer.removeChild(buffer.getFirstChild()); + } + } + + public void formFeed() { + for (int i = 0; i < promptRows; i++) { + newLine(); + } + setPromptHeight(getRows()); + scrollToEnd(); + + checkBufferLimit(); + } + + protected void clearCommandHistory() { + cmdHistory = new ArrayList(); + cmdHistoryIndex = -1; + } + + public String getHeight() { + return (term.getClientHeight() - 2 * padding) + "px"; + } + + public String getWidth() { + return (term.getClientWidth() + scrollbarW - 2 * paddingW) + "px"; + } + + protected void bell() { + // Clear previous + if (timer != null) { + timer.cancel(); + timer = null; + term.removeClassName("term-rev"); + input.removeClassName("term-rev"); + } + // Add styles and start the timer + input.addClassName("term-rev"); + term.addClassName("term-rev"); + timer = new Timer() { + + @Override + public void run() { + term.removeClassName("term-rev"); + input.removeClassName("term-rev"); + } + }; + timer.schedule(150); + } + + @Override + protected void onUnload() { + super.onUnload(); + + if (clickHandler != null) { + clickHandler.removeHandler(); + } + if (focusHandler != null) { + focusHandler.removeHandler(); + } + if (keyHandler != null) { + keyHandler.removeHandler(); + } + } +} diff -r 000000000000 -r c46bb04134cb src/main/java/org/vaadin/console/client/ui/TextConsoleConfig.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/vaadin/console/client/ui/TextConsoleConfig.java Sun May 15 17:46:06 2011 +0400 @@ -0,0 +1,62 @@ +package org.vaadin.console.client.ui; + +import com.google.gwt.core.client.JavaScriptObject; + +public class TextConsoleConfig extends JavaScriptObject { + + public static TextConsoleConfig newInstance() { + return JavaScriptObject.createObject().cast(); + } + + protected TextConsoleConfig() { + } + + public final native int getCols() /*-{ + return this.cols; + }-*/; + + public final native void setCols(int cols) /*-{ + this.cols = cols; + }-*/; + + public final native int getRows() /*-{ + return this.rows; + }-*/; + + public final native void setRows(int rows) /*-{ + this.rows = rows; + }-*/; + + public final native void setGreeting(String greeting) /*-{ + this.greeting = greeting; + }-*/; + + public final native String getGreeting() /*-{ + return this.greeting; + }-*/; + + public final native void setWrap(boolean w) /*-{ + this.wrap = w; + }-*/; + + public final native boolean isWrap() /*-{ + return this.wrap; + }-*/; + + public final native void setPs(String ps) /*-{ + this.ps = ps; + }-*/; + + public final native String getPs() /*-{ + return this.ps; + }-*/; + + public final native int getMaxBufferSize() /*-{ + return this.bufferRows; + }-*/; + + public final native void setMaxBufferSize(int rows) /*-{ + this.bufferRows = rows; + }-*/; + +} diff -r 000000000000 -r c46bb04134cb src/main/java/org/vaadin/console/client/ui/TextConsoleHandler.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/vaadin/console/client/ui/TextConsoleHandler.java Sun May 15 17:46:06 2011 +0400 @@ -0,0 +1,7 @@ +package org.vaadin.console.client.ui; + +public interface TextConsoleHandler { + + public void terminalInput(TextConsole term, String input); + +} diff -r 000000000000 -r c46bb04134cb src/main/java/org/vaadin/console/client/ui/VTextConsole.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/vaadin/console/client/ui/VTextConsole.java Sun May 15 17:46:06 2011 +0400 @@ -0,0 +1,252 @@ +package org.vaadin.console.client.ui; + +import org.vaadin.rpc.client.ClientSideHandler; +import org.vaadin.rpc.client.ClientSideProxy; +import org.vaadin.rpc.client.ClientSideProxy.Transcation; +import org.vaadin.rpc.client.Method; + +import com.vaadin.terminal.gwt.client.ApplicationConnection; +import com.vaadin.terminal.gwt.client.Paintable; +import com.vaadin.terminal.gwt.client.UIDL; +import com.vaadin.terminal.gwt.client.Util; + +/** + * Vaadin client-side integration to Console GWT Widget. + * + * @author Sami Ekblad / Vaadin + * + */ +public class VTextConsole extends TextConsole implements Paintable, + TextConsoleHandler, ClientSideHandler { + + private static final String CSS_CLASS_NAME = "v-console"; + + private final ClientSideProxy comm = new ClientSideProxy("VTextConsole", + this); + + /** + * The constructor should first call super() to initialize the component and + * then handle any initialization relevant to Vaadin. + */ + public VTextConsole() { + super(); + getElement().addClassName(CSS_CLASS_NAME); + setHandler(this); + + // Register all server-driven functions + registerServerCallbacks(); + } + + private void registerServerCallbacks() { + comm.register("setGreeting", new Method() { + public void invoke(final String methodName, final Object[] data) { + getConfig().setGreeting((String) data[0]); + } + }); + comm.register("setPs", new Method() { + public void invoke(final String methodName, final Object[] data) { + setPs((String) data[0]); + } + }); + comm.register("setWrap", new Method() { + public void invoke(final String methodName, final Object[] data) { + getConfig().setWrap((Boolean) data[0]); + } + }); + comm.register("setRows", new Method() { + public void invoke(final String methodName, final Object[] data) { + getConfig().setRows((Integer) data[0]); + setRows((Integer) data[0]); + } + }); + comm.register("setCols", new Method() { + public void invoke(final String methodName, final Object[] data) { + getConfig().setCols((Integer) data[0]); + setCols((Integer) data[0]); + } + }); + comm.register("print", new Method() { + public void invoke(final String methodName, final Object[] data) { + print((String) data[0]); + } + }); + comm.register("println", new Method() { + public void invoke(final String methodName, final Object[] data) { + println((String) data[0]); + } + }); + comm.register("println", new Method() { + public void invoke(final String methodName, final Object[] data) { + println((String) data[0]); + } + }); + comm.register("prompt", new Method() { + public void invoke(final String methodName, final Object[] data) { + prompt((String) (data.length > 0 ? data[0] : null)); + } + }); + comm.register("ff", new Method() { + public void invoke(final String methodName, final Object[] data) { + formFeed(); + } + }); + comm.register("cr", new Method() { + public void invoke(final String methodName, final Object[] data) { + carriageReturn(); + } + }); + comm.register("lf", new Method() { + public void invoke(final String methodName, final Object[] data) { + carriageReturn(); + } + }); + comm.register("clearBuffer", new Method() { + public void invoke(final String methodName, final Object[] data) { + clearBuffer(); + } + }); + comm.register("reset", new Method() { + public void invoke(final String methodName, final Object[] data) { + reset(); + } + }); + comm.register("newLine", new Method() { + public void invoke(final String methodName, final Object[] data) { + newLine(); + } + }); + comm.register("scrollToEnd", new Method() { + public void invoke(final String methodName, final Object[] data) { + scrollToEnd(); + } + }); + comm.register("bell", new Method() { + public void invoke(final String methodName, final Object[] data) { + bell(); + } + }); + comm.register("setMaxBufferSize", new Method() { + public void invoke(final String methodName, final Object[] data) { + getConfig().setMaxBufferSize((Integer) data[0]); + setMaxBufferSize((Integer) data[0]); + } + }); + comm.register("clearHistory", new Method() { + public void invoke(final String methodName, final Object[] data) { + clearCommandHistory(); + } + }); + } + + /** + * Called whenever an update is received from the server + */ + public void updateFromUIDL(final UIDL serverData, + final ApplicationConnection appConn) { + comm.update(this,serverData, appConn); + + } + + private void sendSizeToServer() { + if (comm.isClientInitialized()) { + final Transcation tx = comm.startTx(); + tx.send("height", getHeight()); + tx.send("width", getWidth()); + tx.commit(); + } + + } + + public void terminalInput(final TextConsole term, final String input) { + if (comm.isClientInitialized()) { + comm.call("input", input); + } + } + + @Override + protected void calculateColsFromWidth() { + final int oldCols = getCols(); + super.calculateColsFromWidth(); + + if (comm.isClientInitialized() && getCols() != oldCols) { + final Transcation tx = comm.startTx(); + tx.send("cols", getCols()); + tx.commit(); + } + } + + @Override + protected void calculateRowsFromHeight() { + final int oldRows = getRows(); + super.calculateRowsFromHeight(); + + if (comm.isClientInitialized() && getRows() != oldRows) { + final Transcation tx = comm.startTx(); + tx.send("rows", getRows()); + tx.commit(); + + } + + } + + @Override + protected void calculateHeightFromRows() { + super.calculateHeightFromRows(); + notifyPaintableSizeChange(); + sendSizeToServer(); + } + + @Override + protected void calculateWidthFromCols() { + super.calculateWidthFromCols(); + notifyPaintableSizeChange(); + sendSizeToServer(); + } + + private void notifyPaintableSizeChange() { + Util.notifyParentOfSizeChange(this, false); + } + + @Override + protected void suggest() { + if (comm.isClientInitialized()) { + comm.call("suggest", getInput()); + } + } + + @Override + public void setConfig(final TextConsoleConfig cfg) { + // Wrap everything to a single tx + final Transcation tx = comm.startTx(); + super.setConfig(cfg); + tx.commit(); + } + + /** + * Initialize the Console synchronously. + * + */ + public boolean initWidget(Object[] params) { + + // Console configuration + final TextConsoleConfig cfg = getConfig(); + int i = 0; + cfg.setCols((Integer) params[i++]); + cfg.setRows((Integer) params[i++]); + cfg.setMaxBufferSize((Integer) params[i++]); + cfg.setWrap((Boolean) params[i++]); + cfg.setGreeting((String) params[i++]); + cfg.setPs((String) params[i++]); + comm.d("init: '" + cfg.getGreeting() + "';" + cfg.getCols() + "x" + + cfg.getRows() + ""); + setConfig(cfg); + + reset(); + return false; // Not an async initialization + } + + public void handleCallFromServer(String method, Object[] params) { + comm.d("Unknown method called: " + method); + } + +} diff -r 000000000000 -r c46bb04134cb src/main/java/org/vaadin/console/public/console/styles.css --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/vaadin/console/public/console/styles.css Sun May 15 17:46:06 2011 +0400 @@ -0,0 +1,70 @@ +.term { + background-color: #000; + color: #f0f0f0; + /* color: #33d011; */ + padding: 1px; + padding-left: 2px; + padding-right: 2px; + font-family: monospace;; + font-size: 10pt; + overflow: scroll; + overflow-x: hidden; +} + +.term-rev, .term input.term-rev { + background-color: #f0f0f0; + color: #000; +} + +.term .b { + margin: 0; + padding: 0; +} + +.term .pw { + margin: 0; + padding: 0; +} + +.term .pw .p { + border-collapse: collapse; + margin: 0; + padding: 0; + height: 1em; +} + +.term .pw .psw { + margin: 0; + padding: 0; + width: auto; +} + +.term .pw .iw { + margin: 0; + padding: 0; + width: 100%; +} + +.term .i { + border: none; + outline: none; + border-width: 0; + width: 100%; + height: 1em; + margin: 0; + padding: 0; + font-family: monospace;; + font-size: 10pt; + word-wrap:break-word; + background-color: #000; + color: #f0f0f0; +} + + +/** Coloring sample +.term, .term .i { + background-color: #F5F5F5 !important; + color: #222222 !important; +} + + **/ \ No newline at end of file diff -r 000000000000 -r c46bb04134cb src/main/java/org/vaadin/console/sample/ConsoleSampleApplication.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/vaadin/console/sample/ConsoleSampleApplication.java Sun May 15 17:46:06 2011 +0400 @@ -0,0 +1,193 @@ +package org.vaadin.console.sample; + +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.Arrays; + +import org.vaadin.console.Console; +import org.vaadin.console.Console.Command; +import org.vaadin.console.ObjectInspector; + +import com.vaadin.Application; +import com.vaadin.ui.Button; +import com.vaadin.ui.Button.ClickEvent; +import com.vaadin.ui.HorizontalLayout; +import com.vaadin.ui.Label; +import com.vaadin.ui.Panel; +import com.vaadin.ui.TextField; +import com.vaadin.ui.Window; + +public class ConsoleSampleApplication extends Application { + private static final long serialVersionUID = 4009702916419936660L; + protected static final String HELP = "Sample Vaadin shell. Following command are available:\n"; + private ObjectInspector inspector; + + @Override + public void init() { + Window mainWindow = new Window("Vaadin Console Demo"); + setMainWindow(mainWindow); + + Panel intro = new Panel("Vaadin Console Demo"); + intro + .addComponent(new Label( + "This console implements a test environment for itself.
All methods in console class are exposed as commands in the console itself.", + Label.CONTENT_RAW)); + intro + .addComponent(new Label( + "Type 'help' to list all available commands and 'help ' to get parameter help.'")); + + // # 1 + + // Create a console + final Console console = new Console(); + mainWindow.addComponent(console); + + // Size and greeting + console.setPs("}> "); + console.setCols(80); + console.setRows(24); + console.setMaxBufferSize(24); + console.setGreeting("Welcome to Vaadin console demo."); + console.reset(); + console.focus(); + + // Publish the methods in the Console class itself for testing purposes. + console.addCommandProvider(inspector = new ObjectInspector(console)); + + // Add help command + Command helpCommand = new Console.Command() { + private static final long serialVersionUID = 2838665604270727844L; + + public String getUsage(Console console, String[] argv) { + return argv[0] + " "; + } + + public Object execute(Console console, String[] argv) + throws Exception { + if (argv.length == 2) { + Command hc = console.getCommand(argv[1]); + ArrayList cmdArgv = new ArrayList(Arrays + .asList(argv)); + cmdArgv.remove(0); + return "Usage: " + + hc.getUsage(console, cmdArgv + .toArray(new String[] {})); + } + return listAvailableCommands(); + } + }; + + // Bind the same command with multiple names + console.addCommand("help", helpCommand); + console.addCommand("info", helpCommand); + console.addCommand("man", helpCommand); + // # + + // # 2 + Command systemCommand = new Command() { + private static final long serialVersionUID = -5733237166568671987L; + + public Object execute(Console console, String[] argv) + throws Exception { + Process p = Runtime.getRuntime().exec(argv); + InputStream in = p.getInputStream(); + StringBuilder o = new StringBuilder(); + InputStreamReader r = new InputStreamReader(in); + int c = -1; + try { + while ((c = r.read()) != -1) { + o.append((char) c); + } + } catch (IOException e) { + o.append("[truncated]"); + } finally { + if (r != null) { + r.close(); + } + } + return o.toString(); + } + + public String getUsage(Console console, String[] argv) { + // TODO Auto-generated method stub + return null; + } + }; + + // # + console.addCommand("ls", systemCommand); + + // Add sample command + DummyCmd dummy = new DummyCmd(); + console.addCommand("dir", dummy); + console.addCommand("cd", dummy); + console.addCommand("mkdir", dummy); + console.addCommand("rm", dummy); + console.addCommand("pwd", dummy); + console.addCommand("more", dummy); + console.addCommand("less", dummy); + console.addCommand("exit", dummy); + + HorizontalLayout pl = new HorizontalLayout(); + pl.setSpacing(true); + mainWindow.addComponent(pl); + final TextField input = new TextField(null, "print this"); + pl.addComponent(input); + pl.addComponent(new Button("print", new Button.ClickListener() { + private static final long serialVersionUID = 1L; + + public void buttonClick(ClickEvent event) { + console.print("" + input.getValue()); + } + })); + + pl.addComponent(new Button("println", new Button.ClickListener() { + private static final long serialVersionUID = 1L; + + public void buttonClick(ClickEvent event) { + console.println("" + input.getValue()); + } + })); + + } + + protected String readToString(InputStream in) { + StringBuilder o = new StringBuilder(); + InputStreamReader r = new InputStreamReader(in); + int c = -1; + try { + while ((c = r.read()) != -1) { + o.append((char) c); + } + } catch (IOException e) { + o.append("[truncated]"); + } + return o.toString(); + } + + public static class DummyCmd implements Console.Command { + private static final long serialVersionUID = -7725047596507450670L; + + public Object execute(Console console, String[] argv) throws Exception { + return "Sorry, this is not a real shell and '" + argv[0] + + "' is unsupported. Try 'help' instead."; + } + + public String getUsage(Console console, String[] argv) { + return "Sorry, this is not a real shell and '" + argv[0] + + "' is unsupported. Try 'help' instead."; + } + } + + protected String listAvailableCommands() { + StringBuilder res = new StringBuilder(); + for (String cmd : inspector.getAvailableCommands()) { + res.append(" "); + res.append(cmd); + } + return res.toString().trim(); + } + +}