(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();
+ }
+
+}