src/main/java/org/vaadin/console/client/ui/TextConsole.java
changeset 0 c46bb04134cb
child 1 9b9d2f4b4ce0
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/src/main/java/org/vaadin/console/client/ui/TextConsole.java	Sun May 15 17:46:06 2011 +0400
     1.3 @@ -0,0 +1,781 @@
     1.4 +package org.vaadin.console.client.ui;
     1.5 +
     1.6 +import java.util.ArrayList;
     1.7 +import java.util.List;
     1.8 +
     1.9 +import com.google.gwt.dom.client.DivElement;
    1.10 +import com.google.gwt.dom.client.Document;
    1.11 +import com.google.gwt.dom.client.Element;
    1.12 +import com.google.gwt.dom.client.InputElement;
    1.13 +import com.google.gwt.dom.client.Node;
    1.14 +import com.google.gwt.dom.client.Style.Display;
    1.15 +import com.google.gwt.dom.client.Style.Unit;
    1.16 +import com.google.gwt.dom.client.TableCellElement;
    1.17 +import com.google.gwt.dom.client.TableElement;
    1.18 +import com.google.gwt.dom.client.TableRowElement;
    1.19 +import com.google.gwt.dom.client.TableSectionElement;
    1.20 +import com.google.gwt.event.dom.client.ClickEvent;
    1.21 +import com.google.gwt.event.dom.client.ClickHandler;
    1.22 +import com.google.gwt.event.dom.client.KeyCodes;
    1.23 +import com.google.gwt.event.dom.client.KeyDownEvent;
    1.24 +import com.google.gwt.event.dom.client.KeyDownHandler;
    1.25 +import com.google.gwt.event.shared.HandlerRegistration;
    1.26 +import com.google.gwt.user.client.Timer;
    1.27 +import com.google.gwt.user.client.ui.FocusWidget;
    1.28 +import com.vaadin.terminal.gwt.client.Util;
    1.29 +
    1.30 +/**
    1.31 + * GWT Console Widget.
    1.32 + *
    1.33 + * @author Sami Ekblad / Vaadin
    1.34 + *
    1.35 + */
    1.36 +public class TextConsole extends FocusWidget {
    1.37 +
    1.38 +    /* Control characters in http://en.wikipedia.org/wiki/Control_character */
    1.39 +
    1.40 +    public static final char CTRL_BELL = 'G';
    1.41 +    public static final char CTRL_BACKSPACE = 'H';
    1.42 +    public static final char CTRL_TAB = 'I';
    1.43 +    public static final char CTRL_LINE_FEED = 'J';
    1.44 +    public static final char CTRL_FORM_FEED = 'L';
    1.45 +    public static final char CTRL_CARRIAGE_RETURN = 'M';
    1.46 +    public static final char CTRL_ESCAPE = '[';
    1.47 +    public static final char CTRL_DELETE = '?';
    1.48 +
    1.49 +    private static final char[] CTRL = { CTRL_BELL, CTRL_BACKSPACE, CTRL_TAB,
    1.50 +            CTRL_LINE_FEED, CTRL_FORM_FEED, CTRL_CARRIAGE_RETURN, CTRL_ESCAPE,
    1.51 +            CTRL_DELETE };
    1.52 +
    1.53 +    public static char getControlKey(final int kc) {
    1.54 +        for (final char c : CTRL) {
    1.55 +            if (kc == c) {
    1.56 +                return c;
    1.57 +            }
    1.58 +        }
    1.59 +        return 0;
    1.60 +    }
    1.61 +
    1.62 +    private static final String DEFAULT_TABS = "    ";
    1.63 +    private static final int BIG_NUMBER = 100000;
    1.64 +    private final DivElement term;
    1.65 +    private TextConsoleConfig config;
    1.66 +    private TextConsoleHandler handler;
    1.67 +    private final Element buffer;
    1.68 +    private final TableElement prompt;
    1.69 +    private final Element ps;
    1.70 +    private final InputElement input;
    1.71 +    private List<String> cmdHistory = new ArrayList<String>();
    1.72 +    private int cmdHistoryIndex = -1;
    1.73 +    private final HandlerRegistration clickHandler;
    1.74 +    private final HandlerRegistration keyHandler;
    1.75 +    private HandlerRegistration focusHandler;
    1.76 +    private int fontW = -1;
    1.77 +    private int fontH = -1;
    1.78 +    private int scrollbarW = -1;
    1.79 +    private int rows;
    1.80 +    private int cols;
    1.81 +    private String tabs = DEFAULT_TABS;
    1.82 +    private boolean focused;
    1.83 +    private int promptRows;
    1.84 +    private int padding;
    1.85 +    private final DivElement promptWrap;
    1.86 +    private Timer timer;
    1.87 +    private int maxBufferSize;
    1.88 +    private String cleanPs;
    1.89 +    private int paddingW;
    1.90 +
    1.91 +    public TextConsole() {
    1.92 +
    1.93 +        // Main element
    1.94 +        term = Document.get().createDivElement();
    1.95 +        term.addClassName("term");
    1.96 +        setElement(term);
    1.97 +        setTabIndex(0);
    1.98 +
    1.99 +        // Buffer
   1.100 +        buffer = Document.get().createElement("pre");
   1.101 +        buffer.addClassName("b");
   1.102 +        term.appendChild(buffer);
   1.103 +
   1.104 +        // Prompt elements
   1.105 +        promptWrap = Document.get().createDivElement();
   1.106 +        promptWrap.addClassName("pw");
   1.107 +        term.appendChild(promptWrap);
   1.108 +
   1.109 +        prompt = Document.get().createTableElement();
   1.110 +        promptWrap.appendChild(prompt);
   1.111 +        prompt.setAttribute("cellpadding", "0");
   1.112 +        prompt.setAttribute("cellspacing", "0");
   1.113 +        prompt.setAttribute("border", "0");
   1.114 +        prompt.addClassName("p");
   1.115 +
   1.116 +        final TableSectionElement tbody = Document.get().createTBodyElement();
   1.117 +        prompt.appendChild(tbody);
   1.118 +
   1.119 +        final TableRowElement tr = Document.get().createTRElement();
   1.120 +        tbody.appendChild(tr);
   1.121 +
   1.122 +        final TableCellElement psTd = Document.get().createTDElement();
   1.123 +        psTd.addClassName("psw");
   1.124 +        tr.appendChild(psTd);
   1.125 +
   1.126 +        ps = Document.get().createElement("nobr");
   1.127 +        ps.addClassName("ps");
   1.128 +        psTd.appendChild(ps);
   1.129 +
   1.130 +        final TableCellElement inputTd = Document.get().createTDElement();
   1.131 +        inputTd.addClassName("iw");
   1.132 +        tr.appendChild(inputTd);
   1.133 +
   1.134 +        input = (InputElement) Document.get().createElement("input");
   1.135 +        inputTd.appendChild(input);
   1.136 +        input.addClassName("i");
   1.137 +        input.setTabIndex(-1);
   1.138 +        input.setAttribute("spellcheck", "false");
   1.139 +
   1.140 +        config = TextConsoleConfig.newInstance();
   1.141 +
   1.142 +        setPromtActive(false);
   1.143 +
   1.144 +        clickHandler = addDomHandler(new ClickHandler() {
   1.145 +
   1.146 +            public void onClick(final ClickEvent event) {
   1.147 +                setFocus(true);
   1.148 +            }
   1.149 +        }, ClickEvent.getType());
   1.150 +
   1.151 +        keyHandler = addDomHandler(new KeyDownHandler() {
   1.152 +
   1.153 +            public void onKeyDown(final KeyDownEvent event) {
   1.154 +
   1.155 +                // (re-)show the prompt
   1.156 +                setPromtActive(true);
   1.157 +
   1.158 +                if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
   1.159 +                    event.preventDefault();
   1.160 +                    carriageReturn();
   1.161 +                } else if (event.getNativeKeyCode() == KeyCodes.KEY_UP
   1.162 +                        || event.getNativeKeyCode() == KeyCodes.KEY_DOWN) {
   1.163 +                    event.preventDefault();
   1.164 +                    handleCommandHistoryBrowse(event.getNativeKeyCode());
   1.165 +                } else if (event.getNativeKeyCode() == KeyCodes.KEY_TAB) {
   1.166 +                    event.preventDefault();
   1.167 +                    suggest();
   1.168 +                } else if (event.getNativeKeyCode() == KeyCodes.KEY_BACKSPACE
   1.169 +                        && getInputLenght() == 0) {
   1.170 +                    bell();
   1.171 +                } else if (event.getNativeEvent().getCtrlKey()) {
   1.172 +                    final char ctrlChar = getControlKey(event.getNativeKeyCode());
   1.173 +                    if (ctrlChar > 0) {
   1.174 +                        event.preventDefault();
   1.175 +                        handleControlChar(ctrlChar);
   1.176 +                    }
   1.177 +                }
   1.178 +
   1.179 +            }
   1.180 +        }, KeyDownEvent.getType());
   1.181 +
   1.182 +        updateFontDimensions();
   1.183 +    }
   1.184 +
   1.185 +    protected int getInputLenght() {
   1.186 +        final String v = input.getValue();
   1.187 +        if (v != null) {
   1.188 +            return v.length();
   1.189 +        }
   1.190 +        return -1;
   1.191 +    }
   1.192 +
   1.193 +    protected void handleControlChar(final char c) {
   1.194 +        switch (c) {
   1.195 +        case TextConsole.CTRL_BACKSPACE:
   1.196 +            backspace();
   1.197 +            break;
   1.198 +        case TextConsole.CTRL_BELL:
   1.199 +            bell();
   1.200 +            break;
   1.201 +        case TextConsole.CTRL_CARRIAGE_RETURN:
   1.202 +            carriageReturn();
   1.203 +            break;
   1.204 +        case TextConsole.CTRL_DELETE:
   1.205 +            bell(); // TODO: not supported yet
   1.206 +            break;
   1.207 +        case TextConsole.CTRL_ESCAPE:
   1.208 +            bell(); // TODO: not supported yet
   1.209 +            break;
   1.210 +        case TextConsole.CTRL_FORM_FEED:
   1.211 +            formFeed();
   1.212 +            break;
   1.213 +        case TextConsole.CTRL_LINE_FEED:
   1.214 +            lineFeed();
   1.215 +            break;
   1.216 +        case TextConsole.CTRL_TAB:
   1.217 +            tab();
   1.218 +            break;
   1.219 +
   1.220 +        default:
   1.221 +            bell();
   1.222 +            break;
   1.223 +        }
   1.224 +    }
   1.225 +
   1.226 +    protected void suggest() {
   1.227 +        // No suggest by default. Implement by subclassing.
   1.228 +    }
   1.229 +
   1.230 +    protected void handleCommandHistoryBrowse(final int i) {
   1.231 +        cmdHistoryIndex = i == KeyCodes.KEY_UP ? cmdHistoryIndex - 1
   1.232 +                : cmdHistoryIndex + 1;
   1.233 +        if (cmdHistoryIndex >= 0 && cmdHistoryIndex < cmdHistory.size()) {
   1.234 +            prompt(cmdHistory.get(cmdHistoryIndex));
   1.235 +        } else {
   1.236 +            prompt();
   1.237 +        }
   1.238 +    }
   1.239 +
   1.240 +    public String getInput() {
   1.241 +        return input.getValue();
   1.242 +    }
   1.243 +
   1.244 +    protected void setInput(final String inputText) {
   1.245 +        if (inputText != null) {
   1.246 +            input.setValue(inputText);
   1.247 +        } else {
   1.248 +            input.setValue("");
   1.249 +        }
   1.250 +        if (isFocused()) {
   1.251 +            focusPrompt();
   1.252 +        }
   1.253 +    }
   1.254 +
   1.255 +    public void lineFeed() {
   1.256 +        carriageReturn();
   1.257 +    }
   1.258 +
   1.259 +    protected void tab() {
   1.260 +        prompt(getInput() + "\t");
   1.261 +    }
   1.262 +
   1.263 +    protected void backspace() {
   1.264 +        bell();
   1.265 +    }
   1.266 +
   1.267 +    protected void carriageReturn() {
   1.268 +        setPromtActive(false);
   1.269 +        // Append newline first if not there yet
   1.270 +        if (!bufferIsEmpty() && !bufferEndsWithNewLine()) {
   1.271 +            newLine();
   1.272 +            reducePrompt(-1);
   1.273 +        }
   1.274 +        print(getCurrentPromptContent());
   1.275 +        newLine();
   1.276 +        if (promptRows > 1) {
   1.277 +            reducePrompt(-1);
   1.278 +        }
   1.279 +        String lineBuffer = getInput();
   1.280 +        lineBuffer = lineBuffer.trim();
   1.281 +        if (!"".equals(lineBuffer)) {
   1.282 +            cmdHistory.add(lineBuffer);
   1.283 +            cmdHistoryIndex = cmdHistory.size();
   1.284 +        }
   1.285 +        if (handler != null) {
   1.286 +            handler.terminalInput(this, lineBuffer);
   1.287 +        }
   1.288 +    }
   1.289 +
   1.290 +    private boolean bufferIsEmpty() {
   1.291 +        return !buffer.hasChildNodes();
   1.292 +    }
   1.293 +
   1.294 +    private void setPromtActive(final boolean active) {
   1.295 +        if (active && !isPromptActive()) {
   1.296 +            prompt.getStyle().setDisplay(Display.BLOCK);
   1.297 +        } else if (!active && isPromptActive()) {
   1.298 +            prompt.getStyle().setDisplay(Display.NONE);
   1.299 +        }
   1.300 +    }
   1.301 +
   1.302 +    private boolean isPromptActive() {
   1.303 +        return !Display.NONE.getCssName()
   1.304 +                .equals(prompt.getStyle().getDisplay());
   1.305 +    }
   1.306 +
   1.307 +    private boolean isFocused() {
   1.308 +        return focused;
   1.309 +    }
   1.310 +
   1.311 +    public void setConfig(final TextConsoleConfig cfg) {
   1.312 +        config = cfg;
   1.313 +
   1.314 +        updateFontDimensions();
   1.315 +
   1.316 +        scrollbarW = getScrollbarWidth();
   1.317 +        final String padStr = term.getStyle().getPadding();
   1.318 +        if (padStr != null && padStr.endsWith("px")) {
   1.319 +            padding = Integer
   1.320 +                    .parseInt(padStr.substring(0, padStr.length() - 2));
   1.321 +        } else {
   1.322 +            // _log("using default padding: 1x2");
   1.323 +            padding = 1;
   1.324 +            paddingW = 2;
   1.325 +        }
   1.326 +
   1.327 +        // _log("setConfig: font=" + fontW + "x" + fontH + ";scrollbar="
   1.328 +        // + scrollbarW + ";cols=" + config.getCols() + ";rows="
   1.329 +        // + config.getRows() + ";size=" + getWidth() + "x" + getHeight());
   1.330 +
   1.331 +        setPs(config.getPs());
   1.332 +        setCols(config.getCols());
   1.333 +        setRows(config.getRows());
   1.334 +        setMaxBufferSize(config.getMaxBufferSize());
   1.335 +    }
   1.336 +
   1.337 +    private void updateFontDimensions() {
   1.338 +
   1.339 +        // Test element for font size
   1.340 +        DivElement test = Document.get().createDivElement();
   1.341 +        test.setAttribute("style",
   1.342 +                "position: absolute;");
   1.343 +        test.setInnerHTML("X");
   1.344 +        term.appendChild(test);
   1.345 +
   1.346 +        fontW = test.getClientWidth();
   1.347 +        fontH = test.getClientHeight();
   1.348 +        if (fontW <= 0 || fontW > 100) {
   1.349 +            fontW = test.getOffsetWidth();
   1.350 +        }
   1.351 +        if (fontH <= 0|| fontH > 100) {
   1.352 +            fontH = test.getOffsetHeight();
   1.353 +        }
   1.354 +        if (fontW <= 0 || fontW > 100) {
   1.355 +            fontW = 1;
   1.356 +        }
   1.357 +        if (fontH <= 0|| fontH > 100) {
   1.358 +            fontH = 1;
   1.359 +        }
   1.360 +        term.removeChild(test);
   1.361 +    }
   1.362 +
   1.363 +    // Debug instrumentation. TODO: Remove.
   1.364 +//    protected void _log(final String string) {
   1.365 +//        ApplicationConnection.getConsole().log(string);
   1.366 +//    }
   1.367 +
   1.368 +    public TextConsoleConfig getConfig() {
   1.369 +        return config;
   1.370 +    }
   1.371 +
   1.372 +    private boolean bufferEndsWithNewLine() {
   1.373 +        final Node last = buffer != null ? buffer.getLastChild() : null;
   1.374 +        // _log("last node: " + (last != null ? last.getNodeName() : "<null>"));
   1.375 +        return last != null && "br".equals(last.getNodeName().toLowerCase());
   1.376 +    }
   1.377 +
   1.378 +    private Node createTextNode(final String text) {
   1.379 +        return Document.get().createTextNode(text);
   1.380 +    }
   1.381 +
   1.382 +    private Node createBr() {
   1.383 +        return Document.get().createBRElement();
   1.384 +    }
   1.385 +
   1.386 +    public void focusPrompt() {
   1.387 +        focusPrompt(-1);
   1.388 +    }
   1.389 +
   1.390 +    public void focusPrompt(final int cursorPos) {
   1.391 +        input.focus();
   1.392 +
   1.393 +        // Focus to end
   1.394 +        final String s = getInput();
   1.395 +        if (s != null && s.length() > 0) {
   1.396 +            setSelectionRange(input, s.length(), s.length());
   1.397 +        }
   1.398 +    }
   1.399 +
   1.400 +    private native void setSelectionRange(Element input, int selectionStart,
   1.401 +            int selectionEnd)/*-{
   1.402 +                             if (input.setSelectionRange) {
   1.403 +                             input.focus();
   1.404 +                             input.setSelectionRange(selectionStart, selectionEnd);
   1.405 +                             }
   1.406 +                             else if (input.createTextRange) {
   1.407 +                             var range = input.createTextRange();
   1.408 +                             range.collapse(true);
   1.409 +                             range.moveEnd('character', selectionEnd);
   1.410 +                             range.moveStart('character', selectionStart);
   1.411 +                             range.select();
   1.412 +                             }
   1.413 +                             }-*/;
   1.414 +
   1.415 +    private native int getScrollbarWidth()/*-{
   1.416 +
   1.417 +                                          var i = $doc.createElement('p');
   1.418 +                                          i.style.width = '100%';
   1.419 +                                          i.style.height = '200px';
   1.420 +                                          var o = $doc.createElement('div');
   1.421 +                                          o.style.position = 'absolute';
   1.422 +                                          o.style.top = '0px';
   1.423 +                                          o.style.left = '0px';
   1.424 +                                          o.style.visibility = 'hidden';
   1.425 +                                          o.style.width = '200px';
   1.426 +                                          o.style.height = '150px';
   1.427 +                                          o.style.overflow = 'hidden';
   1.428 +                                          o.appendChild(i);
   1.429 +                                          $doc.body.appendChild(o);
   1.430 +                                          var w1 = i.offsetWidth;
   1.431 +                                          var h1 = i.offsetHeight;
   1.432 +                                          o.style.overflow = 'scroll';
   1.433 +                                          var w2 = i.offsetWidth;
   1.434 +                                          var h2 = i.offsetHeight;
   1.435 +                                          if (w1 == w2) w2 = o.clientWidth;
   1.436 +                                          if (h1 == h2) h2 = o.clientWidth;
   1.437 +                                          $doc.body.removeChild(o);
   1.438 +                                          return w1-w2;
   1.439 +                                          }-*/;
   1.440 +
   1.441 +    public void newLine() {
   1.442 +        // _log("newline");
   1.443 +        buffer.appendChild(createBr());
   1.444 +        checkBufferLimit();
   1.445 +        reducePrompt(1);
   1.446 +    }
   1.447 +
   1.448 +    protected void setPs(final String string) {
   1.449 +        cleanPs = Util.escapeHTML(string);
   1.450 +        cleanPs = cleanPs.replaceAll(" ", "&nbsp;");
   1.451 +    }
   1.452 +
   1.453 +    public void prompt(final String inputText) {
   1.454 +        setPromtActive(true);
   1.455 +        scrollToEnd();
   1.456 +        ps.setInnerHTML(cleanPs);
   1.457 +        setInput(inputText);
   1.458 +    }
   1.459 +
   1.460 +    public void scrollToEnd() {
   1.461 +        term.setScrollTop(BIG_NUMBER);
   1.462 +    }
   1.463 +
   1.464 +    public void prompt() {
   1.465 +        prompt(null);
   1.466 +    }
   1.467 +
   1.468 +    public void print(String string) {
   1.469 +        if (isPromptActive()) {
   1.470 +            setPromtActive(false);
   1.471 +            if (!bufferIsEmpty() && !bufferEndsWithNewLine()) {
   1.472 +                newLine();
   1.473 +                reducePrompt(-1);
   1.474 +            }
   1.475 +            string = getCurrentPromptContent() + string;
   1.476 +        }
   1.477 +        final boolean doWrap = config.isWrap();
   1.478 +        // _log("print original: '" + string + "' (" + doWrap + ")");
   1.479 +        String str = string.replaceAll("\t", tabs);
   1.480 +
   1.481 +        // Continue to the last text node if available
   1.482 +        final Node last = getLastTextNode();
   1.483 +        int linesAdded = 0;
   1.484 +        if (last != null) {
   1.485 +            // _log("print append to old node: '" + last.getNodeValue() + "'");
   1.486 +            str = last.getNodeValue() + str;
   1.487 +            buffer.removeChild(last);
   1.488 +            linesAdded--;
   1.489 +        }
   1.490 +
   1.491 +        // Split by the newlines anyway
   1.492 +        int s = 0, e = str.indexOf('\n');
   1.493 +        while (e >= s) {
   1.494 +            final String line = str.substring(s, e);
   1.495 +            linesAdded += appendLine(buffer, line, doWrap ? cols : -1);
   1.496 +            buffer.appendChild(createBr());
   1.497 +            s = e + 1;
   1.498 +            e = str.indexOf('\n', s);
   1.499 +        }
   1.500 +
   1.501 +        // Print the remaining string
   1.502 +        if (s < str.length()) {
   1.503 +            linesAdded += appendLine(buffer, str.substring(s), doWrap ? cols
   1.504 +                    : -1);
   1.505 +        }
   1.506 +
   1.507 +        reducePrompt(linesAdded);
   1.508 +    }
   1.509 +
   1.510 +    private String getCurrentPromptContent() {
   1.511 +        return prompt.getInnerText() + getInput();
   1.512 +    }
   1.513 +
   1.514 +    private void reducePrompt(final int rows) {
   1.515 +        int newRows = promptRows - rows;
   1.516 +        if (newRows < 1) {
   1.517 +            newRows = 1;
   1.518 +        }
   1.519 +        // _log("prompt reduced from " + promptRows + " to " + newRows);
   1.520 +        setPromptHeight(newRows);
   1.521 +    }
   1.522 +
   1.523 +    private void setPromptHeight(final int rows) {
   1.524 +        final int min = 1;
   1.525 +        final int max = getRows();
   1.526 +        promptRows = rows < min ? min : (rows > max ? max : rows);
   1.527 +        final int newHeight = fontH * rows;
   1.528 +        // _log("Prompt height=" + newHeight);
   1.529 +        promptWrap.getStyle().setHeight(newHeight, Unit.PX);
   1.530 +    }
   1.531 +
   1.532 +    /**
   1.533 +     * Split long text based on length.
   1.534 +     *
   1.535 +     * @param parent
   1.536 +     * @param doWrap
   1.537 +     * @param str
   1.538 +     * @return
   1.539 +     */
   1.540 +    private int appendLine(final Node parent, String str, final int maxLine) {
   1.541 +        int linesAdded = 0;
   1.542 +        final boolean doWrap = maxLine > 0;
   1.543 +        if (!doWrap) {
   1.544 +            parent.appendChild(createTextNode(str));
   1.545 +            // _log("append: '" + str + "'");
   1.546 +            linesAdded++;
   1.547 +        } else {
   1.548 +            while (str.length() > maxLine) {
   1.549 +                final String piece = str.substring(0, maxLine);
   1.550 +                parent.appendChild(createTextNode(piece));
   1.551 +                parent.appendChild(createBr());
   1.552 +                linesAdded++;
   1.553 +                // _log("append: '" + piece + "'");
   1.554 +                str = str.substring(maxLine);
   1.555 +            }
   1.556 +            parent.appendChild(createTextNode(str));
   1.557 +            // _log("append rest: '" + str + "'");
   1.558 +            linesAdded++;
   1.559 +        }
   1.560 +
   1.561 +        // make sore we don't exceed the maximum buffer size
   1.562 +        checkBufferLimit();
   1.563 +
   1.564 +        return linesAdded;
   1.565 +    }
   1.566 +
   1.567 +    private void checkBufferLimit() {
   1.568 +
   1.569 +        // Buffer means only offscreen lines
   1.570 +        final int maxb = maxBufferSize + (rows - promptRows);
   1.571 +        while (getBufferSize() > maxb && buffer.hasChildNodes()) {
   1.572 +            buffer.removeChild(buffer.getFirstChild());
   1.573 +        }
   1.574 +
   1.575 +    }
   1.576 +
   1.577 +    private Node getLastTextNode() {
   1.578 +        if (buffer == null) {
   1.579 +            return null;
   1.580 +        }
   1.581 +        final Node l = buffer.getLastChild();
   1.582 +        if (l != null && l.getNodeType() == Node.TEXT_NODE) {
   1.583 +            return l;
   1.584 +        }
   1.585 +        return null;
   1.586 +    }
   1.587 +
   1.588 +    public void println(final String string) {
   1.589 +        print(string + "\n");
   1.590 +    }
   1.591 +
   1.592 +    @Override
   1.593 +    public void setHeight(final String height) {
   1.594 +        final int oldh = term.getClientHeight();
   1.595 +        super.setHeight(height);
   1.596 +        final int newh = term.getClientHeight();
   1.597 +        // _log("set height=" + height + " clientHeight="+oldh+" to "+newh);
   1.598 +        if (newh != oldh) {
   1.599 +            calculateRowsFromHeight();
   1.600 +        }
   1.601 +    }
   1.602 +
   1.603 +    protected void calculateRowsFromHeight() {
   1.604 +        final int h = term.getClientHeight() - (2 * padding);
   1.605 +        rows = h / fontH;
   1.606 +        config.setRows(rows);
   1.607 +
   1.608 +        // _log("calculateRowsFromHeight: font=" + fontW + "x" + fontH
   1.609 +        // + ";scrollbar=" + scrollbarW + ";cols=" + cols + ";rows="
   1.610 +        // + rows + ";size=" + getWidth() + "x" + getHeight());
   1.611 +
   1.612 +    }
   1.613 +
   1.614 +    protected void calculateHeightFromRows() {
   1.615 +        super.setHeight((rows * fontH) + "px");
   1.616 +
   1.617 +        // _log("calculateHeightFromRows: font=" + fontW + "x" + fontH
   1.618 +        // + ";scrollbar=" + scrollbarW + ";cols=" + cols + ";rows="
   1.619 +        // + rows + ";size=" + getWidth() + "x" + getHeight());
   1.620 +
   1.621 +    }
   1.622 +
   1.623 +    protected void calculateColsFromWidth() {
   1.624 +        final int w = term.getClientWidth();
   1.625 +        cols = (w - 2 * paddingW) / fontW;
   1.626 +        config.setCols(cols);
   1.627 +        buffer.getStyle().setWidth((cols * fontW), Unit.PX);
   1.628 +        prompt.getStyle().setWidth((cols * fontW), Unit.PX);
   1.629 +        // _log("calculateColsFromWidth: font=" + fontW + "x" + fontH
   1.630 +        // + ";scrollbar=" + scrollbarW + ";cols=" + cols + ";rows="
   1.631 +        // + rows + ";size=" + getWidth() + "x" + getHeight());
   1.632 +
   1.633 +    }
   1.634 +
   1.635 +    protected void calculateWidthFromCols() {
   1.636 +        final int w = cols * fontW;
   1.637 +        super.setWidth((w + scrollbarW) + "px");
   1.638 +        buffer.getStyle().setWidth(w, Unit.PX);
   1.639 +        prompt.getStyle().setWidth(w, Unit.PX);
   1.640 +
   1.641 +        // _log("calculateWidthFromCols: font=" + fontW + "x" + fontH
   1.642 +        // + ";scrollbar=" + scrollbarW + ";cols=" + cols + ";rows="
   1.643 +        // + rows + ";size=" + getWidth() + "x" + getHeight());
   1.644 +    }
   1.645 +
   1.646 +    @Override
   1.647 +    public void setWidth(final String width) {
   1.648 +        final int oldw = term.getClientWidth();
   1.649 +        super.setWidth(width);
   1.650 +        final int neww = term.getClientWidth();
   1.651 +        // _log("set width=" + width + " clientWidth="+oldw+" to "+neww);
   1.652 +        if (neww != oldw) {
   1.653 +            calculateColsFromWidth();
   1.654 +        }
   1.655 +    }
   1.656 +
   1.657 +    @Override
   1.658 +    public void setFocus(final boolean focused) {
   1.659 +        this.focused = focused;
   1.660 +        super.setFocus(focused);
   1.661 +        if (focused) {
   1.662 +            focusPrompt();
   1.663 +        }
   1.664 +    }
   1.665 +
   1.666 +    public void setHandler(final TextConsoleHandler handler) {
   1.667 +        this.handler = handler;
   1.668 +
   1.669 +    }
   1.670 +
   1.671 +    public void setRows(final int rows) {
   1.672 +        if (rows > 0) {
   1.673 +            this.rows = rows;
   1.674 +            calculateHeightFromRows();
   1.675 +        } else {
   1.676 +            calculateRowsFromHeight();
   1.677 +        }
   1.678 +    }
   1.679 +
   1.680 +    public int getRows() {
   1.681 +        return rows;
   1.682 +    }
   1.683 +
   1.684 +    public void setCols(final int cols) {
   1.685 +        if (cols > 0) {
   1.686 +            this.cols = cols;
   1.687 +            calculateWidthFromCols();
   1.688 +        } else {
   1.689 +            calculateColsFromWidth();
   1.690 +        }
   1.691 +    }
   1.692 +
   1.693 +    public int getCols() {
   1.694 +        return cols;
   1.695 +    }
   1.696 +
   1.697 +    public void reset() {
   1.698 +        setPromtActive(false);
   1.699 +        clearBuffer();
   1.700 +        setPromptHeight(getRows());
   1.701 +        print(config.getGreeting());
   1.702 +        prompt();
   1.703 +    }
   1.704 +
   1.705 +    public int getBufferSize() {
   1.706 +        return (buffer.getClientHeight() / fontH);
   1.707 +    }
   1.708 +
   1.709 +    public int getMaxBufferSize() {
   1.710 +        return maxBufferSize;
   1.711 +    }
   1.712 +
   1.713 +    public void setMaxBufferSize(final int maxBuffer) {
   1.714 +        maxBufferSize = maxBuffer > 0 ? maxBuffer : 0;
   1.715 +        checkBufferLimit();
   1.716 +    }
   1.717 +
   1.718 +    public void clearBuffer() {
   1.719 +        // Remove all children.
   1.720 +        while (buffer.hasChildNodes()) {
   1.721 +            buffer.removeChild(buffer.getFirstChild());
   1.722 +        }
   1.723 +    }
   1.724 +
   1.725 +    public void formFeed() {
   1.726 +        for (int i = 0; i < promptRows; i++) {
   1.727 +            newLine();
   1.728 +        }
   1.729 +        setPromptHeight(getRows());
   1.730 +        scrollToEnd();
   1.731 +
   1.732 +        checkBufferLimit();
   1.733 +    }
   1.734 +
   1.735 +    protected void clearCommandHistory() {
   1.736 +        cmdHistory = new ArrayList<String>();
   1.737 +        cmdHistoryIndex = -1;
   1.738 +    }
   1.739 +
   1.740 +    public String getHeight() {
   1.741 +        return (term.getClientHeight() - 2 * padding) + "px";
   1.742 +    }
   1.743 +
   1.744 +    public String getWidth() {
   1.745 +        return (term.getClientWidth() + scrollbarW - 2 * paddingW) + "px";
   1.746 +    }
   1.747 +
   1.748 +    protected void bell() {
   1.749 +        // Clear previous
   1.750 +        if (timer != null) {
   1.751 +            timer.cancel();
   1.752 +            timer = null;
   1.753 +            term.removeClassName("term-rev");
   1.754 +            input.removeClassName("term-rev");
   1.755 +        }
   1.756 +        // Add styles and start the timer
   1.757 +        input.addClassName("term-rev");
   1.758 +        term.addClassName("term-rev");
   1.759 +        timer = new Timer() {
   1.760 +
   1.761 +            @Override
   1.762 +            public void run() {
   1.763 +                term.removeClassName("term-rev");
   1.764 +                input.removeClassName("term-rev");
   1.765 +            }
   1.766 +        };
   1.767 +        timer.schedule(150);
   1.768 +    }
   1.769 +
   1.770 +    @Override
   1.771 +    protected void onUnload() {
   1.772 +        super.onUnload();
   1.773 +
   1.774 +        if (clickHandler != null) {
   1.775 +            clickHandler.removeHandler();
   1.776 +        }
   1.777 +        if (focusHandler != null) {
   1.778 +            focusHandler.removeHandler();
   1.779 +        }
   1.780 +        if (keyHandler != null) {
   1.781 +            keyHandler.removeHandler();
   1.782 +        }
   1.783 +    }
   1.784 +}