src/main/java/org/vaadin/console/client/ui/TextConsole.java
author indvdum
Tue, 17 May 2011 03:27:01 +0400
changeset 3 3eab4f9f42a9
parent 1 9b9d2f4b4ce0
child 4 27bd1032a5c6
permissions -rw-r--r--
+ client method append(String)
     1 package org.vaadin.console.client.ui;
     2 
     3 import java.util.ArrayList;
     4 import java.util.List;
     5 
     6 import com.google.gwt.dom.client.DivElement;
     7 import com.google.gwt.dom.client.Document;
     8 import com.google.gwt.dom.client.Element;
     9 import com.google.gwt.dom.client.InputElement;
    10 import com.google.gwt.dom.client.Node;
    11 import com.google.gwt.dom.client.Style.Display;
    12 import com.google.gwt.dom.client.Style.Unit;
    13 import com.google.gwt.dom.client.TableCellElement;
    14 import com.google.gwt.dom.client.TableElement;
    15 import com.google.gwt.dom.client.TableRowElement;
    16 import com.google.gwt.dom.client.TableSectionElement;
    17 import com.google.gwt.event.dom.client.ClickEvent;
    18 import com.google.gwt.event.dom.client.ClickHandler;
    19 import com.google.gwt.event.dom.client.KeyCodes;
    20 import com.google.gwt.event.dom.client.KeyDownEvent;
    21 import com.google.gwt.event.dom.client.KeyDownHandler;
    22 import com.google.gwt.event.shared.HandlerRegistration;
    23 import com.google.gwt.user.client.Timer;
    24 import com.google.gwt.user.client.ui.FocusWidget;
    25 import com.vaadin.terminal.gwt.client.Util;
    26 
    27 /**
    28  * GWT Console Widget.
    29  *
    30  * @author Sami Ekblad / Vaadin
    31  *
    32  */
    33 public class TextConsole extends FocusWidget {
    34 
    35     /* Control characters in http://en.wikipedia.org/wiki/Control_character */
    36 
    37     public static final char CTRL_BELL = 'G';
    38     public static final char CTRL_BACKSPACE = 'H';
    39     public static final char CTRL_TAB = 'I';
    40     public static final char CTRL_LINE_FEED = 'J';
    41     public static final char CTRL_FORM_FEED = 'L';
    42     public static final char CTRL_CARRIAGE_RETURN = 'M';
    43     public static final char CTRL_ESCAPE = '[';
    44     public static final char CTRL_DELETE = '?';
    45 
    46     private static final char[] CTRL = { CTRL_BELL, CTRL_BACKSPACE, CTRL_TAB,
    47             CTRL_LINE_FEED, CTRL_FORM_FEED, CTRL_CARRIAGE_RETURN, CTRL_ESCAPE,
    48             CTRL_DELETE };
    49 
    50     public static char getControlKey(final int kc) {
    51         for (final char c : CTRL) {
    52             if (kc == c) {
    53                 return c;
    54             }
    55         }
    56         return 0;
    57     }
    58 
    59     private static final String DEFAULT_TABS = "    ";
    60     private static final int BIG_NUMBER = 100000;
    61     private final DivElement term;
    62     private TextConsoleConfig config;
    63     private TextConsoleHandler handler;
    64     private final Element buffer;
    65     private final TableElement prompt;
    66     private final Element ps;
    67     private final InputElement input;
    68     private List<String> cmdHistory = new ArrayList<String>();
    69     private int cmdHistoryIndex = -1;
    70     private final HandlerRegistration clickHandler;
    71     private final HandlerRegistration keyHandler;
    72     private HandlerRegistration focusHandler;
    73     private int fontW = -1;
    74     private int fontH = -1;
    75     private int scrollbarW = -1;
    76     private int rows;
    77     private int cols;
    78     private String tabs = DEFAULT_TABS;
    79     private boolean focused;
    80     private int promptRows;
    81     private int padding;
    82     private final DivElement promptWrap;
    83     private Timer timer;
    84     private int maxBufferSize;
    85     private String cleanPs;
    86     private int paddingW;
    87 
    88     public TextConsole() {
    89 
    90         // Main element
    91         term = Document.get().createDivElement();
    92         term.addClassName("term");
    93         setElement(term);
    94         setTabIndex(0);
    95 
    96         // Buffer
    97         buffer = Document.get().createElement("pre");
    98         buffer.addClassName("b");
    99         term.appendChild(buffer);
   100 
   101         // Prompt elements
   102         promptWrap = Document.get().createDivElement();
   103         promptWrap.addClassName("pw");
   104         term.appendChild(promptWrap);
   105 
   106         prompt = Document.get().createTableElement();
   107         promptWrap.appendChild(prompt);
   108         prompt.setAttribute("cellpadding", "0");
   109         prompt.setAttribute("cellspacing", "0");
   110         prompt.setAttribute("border", "0");
   111         prompt.addClassName("p");
   112 
   113         final TableSectionElement tbody = Document.get().createTBodyElement();
   114         prompt.appendChild(tbody);
   115 
   116         final TableRowElement tr = Document.get().createTRElement();
   117         tbody.appendChild(tr);
   118 
   119         final TableCellElement psTd = Document.get().createTDElement();
   120         psTd.addClassName("psw");
   121         tr.appendChild(psTd);
   122 
   123         ps = Document.get().createElement("nobr");
   124         ps.addClassName("ps");
   125         psTd.appendChild(ps);
   126 
   127         final TableCellElement inputTd = Document.get().createTDElement();
   128         inputTd.addClassName("iw");
   129         tr.appendChild(inputTd);
   130 
   131         input = (InputElement) Document.get().createElement("input");
   132         inputTd.appendChild(input);
   133         input.addClassName("i");
   134         input.setTabIndex(-1);
   135         input.setAttribute("spellcheck", "false");
   136 
   137         config = TextConsoleConfig.newInstance();
   138 
   139         setPromtActive(false);
   140 
   141         clickHandler = addDomHandler(new ClickHandler() {
   142 
   143             public void onClick(final ClickEvent event) {
   144                 setFocus(true);
   145             }
   146         }, ClickEvent.getType());
   147 
   148         keyHandler = addDomHandler(new KeyDownHandler() {
   149 
   150             public void onKeyDown(final KeyDownEvent event) {
   151 
   152                 // (re-)show the prompt
   153                 setPromtActive(true);
   154 
   155                 if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
   156                     event.preventDefault();
   157                     carriageReturn();
   158                 } else if (event.getNativeKeyCode() == KeyCodes.KEY_UP
   159                         || event.getNativeKeyCode() == KeyCodes.KEY_DOWN) {
   160                     event.preventDefault();
   161                     handleCommandHistoryBrowse(event.getNativeKeyCode());
   162                 } else if (event.getNativeKeyCode() == KeyCodes.KEY_TAB) {
   163                     event.preventDefault();
   164                     suggest();
   165                 } else if (event.getNativeKeyCode() == KeyCodes.KEY_BACKSPACE
   166                         && getInputLenght() == 0) {
   167                     bell();
   168                 } else if (event.getNativeEvent().getCtrlKey()) {
   169                     final char ctrlChar = getControlKey(event.getNativeKeyCode());
   170                     if (ctrlChar > 0) {
   171                         event.preventDefault();
   172                         handleControlChar(ctrlChar);
   173                     }
   174                 }
   175 
   176             }
   177         }, KeyDownEvent.getType());
   178 
   179         updateFontDimensions();
   180     }
   181 
   182     protected int getInputLenght() {
   183         final String v = input.getValue();
   184         if (v != null) {
   185             return v.length();
   186         }
   187         return -1;
   188     }
   189 
   190     protected void handleControlChar(final char c) {
   191         switch (c) {
   192         case TextConsole.CTRL_BACKSPACE:
   193             backspace();
   194             break;
   195         case TextConsole.CTRL_BELL:
   196             bell();
   197             break;
   198         case TextConsole.CTRL_CARRIAGE_RETURN:
   199             carriageReturn();
   200             break;
   201         case TextConsole.CTRL_DELETE:
   202             bell(); // TODO: not supported yet
   203             break;
   204         case TextConsole.CTRL_ESCAPE:
   205             bell(); // TODO: not supported yet
   206             break;
   207         case TextConsole.CTRL_FORM_FEED:
   208             formFeed();
   209             break;
   210         case TextConsole.CTRL_LINE_FEED:
   211             lineFeed();
   212             break;
   213         case TextConsole.CTRL_TAB:
   214             tab();
   215             break;
   216 
   217         default:
   218             bell();
   219             break;
   220         }
   221     }
   222 
   223     protected void suggest() {
   224         // No suggest by default. Implement by subclassing.
   225     }
   226 
   227     protected void handleCommandHistoryBrowse(final int i) {
   228         cmdHistoryIndex = i == KeyCodes.KEY_UP ? cmdHistoryIndex - 1
   229                 : cmdHistoryIndex + 1;
   230         if (cmdHistoryIndex >= 0 && cmdHistoryIndex < cmdHistory.size()) {
   231             prompt(cmdHistory.get(cmdHistoryIndex));
   232         } else {
   233             prompt();
   234         }
   235     }
   236 
   237     public String getInput() {
   238         return input.getValue();
   239     }
   240 
   241     protected void setInput(final String inputText) {
   242         if (inputText != null) {
   243             input.setValue(inputText);
   244         } else {
   245             input.setValue("");
   246         }
   247         if (isFocused()) {
   248             focusPrompt();
   249         }
   250     }
   251 
   252     public void lineFeed() {
   253         carriageReturn();
   254     }
   255 
   256     protected void tab() {
   257         prompt(getInput() + "\t");
   258     }
   259 
   260     protected void backspace() {
   261         bell();
   262     }
   263 
   264     protected void carriageReturn() {
   265         setPromtActive(false);
   266         // Append newline first if not there yet
   267         if (!bufferIsEmpty() && !bufferEndsWithNewLine()) {
   268             newLine();
   269             reducePrompt(-1);
   270         }
   271         print(getCurrentPromptContent());
   272         newLine();
   273         if (promptRows > 1) {
   274             reducePrompt(-1);
   275         }
   276         String lineBuffer = getInput();
   277         lineBuffer = lineBuffer.trim();
   278         if (!"".equals(lineBuffer)) {
   279             cmdHistory.add(lineBuffer);
   280             cmdHistoryIndex = cmdHistory.size();
   281         }
   282         if (handler != null) {
   283             handler.terminalInput(this, lineBuffer);
   284         }
   285     }
   286 
   287     private boolean bufferIsEmpty() {
   288         return !buffer.hasChildNodes();
   289     }
   290 
   291     private void setPromtActive(final boolean active) {
   292         if (active && !isPromptActive()) {
   293             prompt.getStyle().setDisplay(Display.BLOCK);
   294         } else if (!active && isPromptActive()) {
   295             prompt.getStyle().setDisplay(Display.NONE);
   296         }
   297     }
   298 
   299     private boolean isPromptActive() {
   300         return !Display.NONE.getCssName()
   301                 .equals(prompt.getStyle().getDisplay());
   302     }
   303 
   304     private boolean isFocused() {
   305         return focused;
   306     }
   307 
   308     public void setConfig(final TextConsoleConfig cfg) {
   309         config = cfg;
   310 
   311         updateFontDimensions();
   312 
   313         scrollbarW = getScrollbarWidth();
   314         final String padStr = term.getStyle().getPadding();
   315         if (padStr != null && padStr.endsWith("px")) {
   316             padding = Integer
   317                     .parseInt(padStr.substring(0, padStr.length() - 2));
   318         } else {
   319             // _log("using default padding: 1x2");
   320             padding = 1;
   321             paddingW = 2;
   322         }
   323 
   324         // _log("setConfig: font=" + fontW + "x" + fontH + ";scrollbar="
   325         // + scrollbarW + ";cols=" + config.getCols() + ";rows="
   326         // + config.getRows() + ";size=" + getWidth() + "x" + getHeight());
   327 
   328         setPs(config.getPs());
   329         setCols(config.getCols());
   330         setRows(config.getRows());
   331         setMaxBufferSize(config.getMaxBufferSize());
   332     }
   333 
   334     private void updateFontDimensions() {
   335 
   336         // Test element for font size
   337         DivElement test = Document.get().createDivElement();
   338         test.setAttribute("style",
   339                 "position: absolute;");
   340         test.setInnerHTML("X");
   341         term.appendChild(test);
   342 
   343         fontW = test.getClientWidth();
   344         fontH = test.getClientHeight();
   345         if (fontW <= 0 || fontW > 100) {
   346             fontW = test.getOffsetWidth();
   347         }
   348         if (fontH <= 0|| fontH > 100) {
   349             fontH = test.getOffsetHeight();
   350         }
   351         if (fontW <= 0 || fontW > 100) {
   352             fontW = 1;
   353         }
   354         if (fontH <= 0|| fontH > 100) {
   355             fontH = 1;
   356         }
   357         term.removeChild(test);
   358     }
   359 
   360     // Debug instrumentation. TODO: Remove.
   361 //    protected void _log(final String string) {
   362 //        ApplicationConnection.getConsole().log(string);
   363 //    }
   364 
   365     public TextConsoleConfig getConfig() {
   366         return config;
   367     }
   368 
   369     private boolean bufferEndsWithNewLine() {
   370         final Node last = buffer != null ? buffer.getLastChild() : null;
   371         // _log("last node: " + (last != null ? last.getNodeName() : "<null>"));
   372         return last != null && "br".equals(last.getNodeName().toLowerCase());
   373     }
   374 
   375     private Node createTextNode(final String text) {
   376         return Document.get().createTextNode(text);
   377     }
   378 
   379     private Node createBr() {
   380         return Document.get().createBRElement();
   381     }
   382 
   383     public void focusPrompt() {
   384         focusPrompt(-1);
   385     }
   386 
   387     public void focusPrompt(final int cursorPos) {
   388         input.focus();
   389 
   390         // Focus to end
   391         final String s = getInput();
   392         if (s != null && s.length() > 0) {
   393             setSelectionRange(input, s.length(), s.length());
   394         }
   395     }
   396 
   397     private native void setSelectionRange(Element input, int selectionStart,
   398             int selectionEnd)/*-{
   399                              if (input.setSelectionRange) {
   400                              input.focus();
   401                              input.setSelectionRange(selectionStart, selectionEnd);
   402                              }
   403                              else if (input.createTextRange) {
   404                              var range = input.createTextRange();
   405                              range.collapse(true);
   406                              range.moveEnd('character', selectionEnd);
   407                              range.moveStart('character', selectionStart);
   408                              range.select();
   409                              }
   410                              }-*/;
   411 
   412     private native int getScrollbarWidth()/*-{
   413 
   414                                           var i = $doc.createElement('p');
   415                                           i.style.width = '100%';
   416                                           i.style.height = '200px';
   417                                           var o = $doc.createElement('div');
   418                                           o.style.position = 'absolute';
   419                                           o.style.top = '0px';
   420                                           o.style.left = '0px';
   421                                           o.style.visibility = 'hidden';
   422                                           o.style.width = '200px';
   423                                           o.style.height = '150px';
   424                                           o.style.overflow = 'hidden';
   425                                           o.appendChild(i);
   426                                           $doc.body.appendChild(o);
   427                                           var w1 = i.offsetWidth;
   428                                           var h1 = i.offsetHeight;
   429                                           o.style.overflow = 'scroll';
   430                                           var w2 = i.offsetWidth;
   431                                           var h2 = i.offsetHeight;
   432                                           if (w1 == w2) w2 = o.clientWidth;
   433                                           if (h1 == h2) h2 = o.clientWidth;
   434                                           $doc.body.removeChild(o);
   435                                           return w1-w2;
   436                                           }-*/;
   437 
   438     public void newLine() {
   439         // _log("newline");
   440         buffer.appendChild(createBr());
   441         checkBufferLimit();
   442         reducePrompt(1);
   443     }
   444 
   445     protected void setPs(final String string) {
   446         cleanPs = Util.escapeHTML(string);
   447         cleanPs = cleanPs.replaceAll(" ", "&nbsp;");
   448         ps.setInnerHTML(cleanPs);
   449     }
   450 
   451     public void prompt(final String inputText) {
   452         setPromtActive(true);
   453         scrollToEnd();
   454         ps.setInnerHTML(cleanPs);
   455         setInput(inputText);
   456     }
   457     
   458     public void focusInput(){
   459         setPromtActive(true);
   460         scrollToEnd();
   461         ps.setInnerHTML(cleanPs);
   462     }
   463 
   464     public void scrollToEnd() {
   465         term.setScrollTop(BIG_NUMBER);
   466     }
   467 
   468     public void prompt() {
   469         prompt(null);
   470     }
   471 
   472     public void print(String string) {
   473         if (isPromptActive()) {
   474             setPromtActive(false);
   475             if (!bufferIsEmpty() && !bufferEndsWithNewLine()) {
   476                 newLine();
   477                 reducePrompt(-1);
   478             }
   479             string = getCurrentPromptContent() + string;
   480         }
   481         final boolean doWrap = config.isWrap();
   482         // _log("print original: '" + string + "' (" + doWrap + ")");
   483         String str = string.replaceAll("\t", tabs);
   484 
   485         // Continue to the last text node if available
   486         final Node last = getLastTextNode();
   487         int linesAdded = 0;
   488         if (last != null) {
   489             // _log("print append to old node: '" + last.getNodeValue() + "'");
   490             str = last.getNodeValue() + str;
   491             buffer.removeChild(last);
   492             linesAdded--;
   493         }
   494 
   495         // Split by the newlines anyway
   496         int s = 0, e = str.indexOf('\n');
   497         while (e >= s) {
   498             final String line = str.substring(s, e);
   499             linesAdded += appendLine(buffer, line, doWrap ? cols : -1);
   500             buffer.appendChild(createBr());
   501             s = e + 1;
   502             e = str.indexOf('\n', s);
   503         }
   504 
   505         // Print the remaining string
   506         if (s < str.length()) {
   507             linesAdded += appendLine(buffer, str.substring(s), doWrap ? cols
   508                     : -1);
   509         }
   510 
   511         reducePrompt(linesAdded);
   512     }
   513     
   514 	public void append(String string) {
   515 		if (isPromptActive()) {
   516 			setPromtActive(false);
   517 		}
   518 		final boolean doWrap = config.isWrap();
   519 		// _log("print original: '" + string + "' (" + doWrap + ")");
   520 		String str = string.replaceAll("\t", tabs);
   521 
   522 		// Continue to the last text node if available
   523 		final Node last = getLastTextNode();
   524 		int linesAdded = 0;
   525 		if (last != null) {
   526 			// _log("print append to old node: '" + last.getNodeValue() + "'");
   527 			str = last.getNodeValue() + str;
   528 			buffer.removeChild(last);
   529 			linesAdded--;
   530 		}
   531 
   532 		// Split by the newlines anyway
   533 		int s = 0, e = str.indexOf('\n');
   534 		while (e >= s) {
   535 			final String line = str.substring(s, e);
   536 			linesAdded += appendLine(buffer, line, doWrap ? cols : -1);
   537 			buffer.appendChild(createBr());
   538 			s = e + 1;
   539 			e = str.indexOf('\n', s);
   540 		}
   541 
   542 		// Print the remaining string
   543 		if (s < str.length()) {
   544 			linesAdded += appendLine(buffer, str.substring(s), doWrap ? cols : -1);
   545 		}
   546 
   547 		reducePrompt(linesAdded);
   548 	}
   549 
   550     private String getCurrentPromptContent() {
   551         return prompt.getInnerText() + getInput();
   552     }
   553 
   554     private void reducePrompt(final int rows) {
   555         int newRows = promptRows - rows;
   556         if (newRows < 1) {
   557             newRows = 1;
   558         }
   559         // _log("prompt reduced from " + promptRows + " to " + newRows);
   560         setPromptHeight(newRows);
   561     }
   562 
   563     private void setPromptHeight(final int rows) {
   564         final int min = 1;
   565         final int max = getRows();
   566         promptRows = rows < min ? min : (rows > max ? max : rows);
   567         final int newHeight = fontH * rows;
   568         // _log("Prompt height=" + newHeight);
   569         promptWrap.getStyle().setHeight(newHeight, Unit.PX);
   570     }
   571 
   572     /**
   573      * Split long text based on length.
   574      *
   575      * @param parent
   576      * @param doWrap
   577      * @param str
   578      * @return
   579      */
   580     private int appendLine(final Node parent, String str, final int maxLine) {
   581         int linesAdded = 0;
   582         final boolean doWrap = maxLine > 0;
   583         if (!doWrap) {
   584             parent.appendChild(createTextNode(str));
   585             // _log("append: '" + str + "'");
   586             linesAdded++;
   587         } else {
   588             while (str.length() > maxLine) {
   589                 final String piece = str.substring(0, maxLine);
   590                 parent.appendChild(createTextNode(piece));
   591                 parent.appendChild(createBr());
   592                 linesAdded++;
   593                 // _log("append: '" + piece + "'");
   594                 str = str.substring(maxLine);
   595             }
   596             parent.appendChild(createTextNode(str));
   597             // _log("append rest: '" + str + "'");
   598             linesAdded++;
   599         }
   600 
   601         // make sore we don't exceed the maximum buffer size
   602         checkBufferLimit();
   603 
   604         return linesAdded;
   605     }
   606 
   607     private void checkBufferLimit() {
   608 
   609         // Buffer means only offscreen lines
   610         final int maxb = maxBufferSize + (rows - promptRows);
   611         while (getBufferSize() > maxb && buffer.hasChildNodes()) {
   612             buffer.removeChild(buffer.getFirstChild());
   613         }
   614 
   615     }
   616 
   617     private Node getLastTextNode() {
   618         if (buffer == null) {
   619             return null;
   620         }
   621         final Node l = buffer.getLastChild();
   622         if (l != null && l.getNodeType() == Node.TEXT_NODE) {
   623             return l;
   624         }
   625         return null;
   626     }
   627 
   628     public void println(final String string) {
   629         print(string + "\n");
   630     }
   631 
   632     @Override
   633     public void setHeight(final String height) {
   634         final int oldh = term.getClientHeight();
   635         super.setHeight(height);
   636         final int newh = term.getClientHeight();
   637         // _log("set height=" + height + " clientHeight="+oldh+" to "+newh);
   638         if (newh != oldh) {
   639             calculateRowsFromHeight();
   640         }
   641     }
   642 
   643     protected void calculateRowsFromHeight() {
   644         final int h = term.getClientHeight() - (2 * padding);
   645         rows = h / fontH;
   646         config.setRows(rows);
   647 
   648         // _log("calculateRowsFromHeight: font=" + fontW + "x" + fontH
   649         // + ";scrollbar=" + scrollbarW + ";cols=" + cols + ";rows="
   650         // + rows + ";size=" + getWidth() + "x" + getHeight());
   651 
   652     }
   653 
   654     protected void calculateHeightFromRows() {
   655         super.setHeight((rows * fontH) + "px");
   656 
   657         // _log("calculateHeightFromRows: font=" + fontW + "x" + fontH
   658         // + ";scrollbar=" + scrollbarW + ";cols=" + cols + ";rows="
   659         // + rows + ";size=" + getWidth() + "x" + getHeight());
   660 
   661     }
   662 
   663     protected void calculateColsFromWidth() {
   664         final int w = term.getClientWidth();
   665         cols = (w - 2 * paddingW) / fontW;
   666         config.setCols(cols);
   667         buffer.getStyle().setWidth((cols * fontW), Unit.PX);
   668         prompt.getStyle().setWidth((cols * fontW), Unit.PX);
   669         // _log("calculateColsFromWidth: font=" + fontW + "x" + fontH
   670         // + ";scrollbar=" + scrollbarW + ";cols=" + cols + ";rows="
   671         // + rows + ";size=" + getWidth() + "x" + getHeight());
   672 
   673     }
   674 
   675     protected void calculateWidthFromCols() {
   676         final int w = cols * fontW;
   677         super.setWidth((w + scrollbarW) + "px");
   678         buffer.getStyle().setWidth(w, Unit.PX);
   679         prompt.getStyle().setWidth(w, Unit.PX);
   680 
   681         // _log("calculateWidthFromCols: font=" + fontW + "x" + fontH
   682         // + ";scrollbar=" + scrollbarW + ";cols=" + cols + ";rows="
   683         // + rows + ";size=" + getWidth() + "x" + getHeight());
   684     }
   685 
   686     @Override
   687     public void setWidth(final String width) {
   688         final int oldw = term.getClientWidth();
   689         super.setWidth(width);
   690         final int neww = term.getClientWidth();
   691         // _log("set width=" + width + " clientWidth="+oldw+" to "+neww);
   692         if (neww != oldw) {
   693             calculateColsFromWidth();
   694         }
   695     }
   696 
   697     @Override
   698     public void setFocus(final boolean focused) {
   699         this.focused = focused;
   700         super.setFocus(focused);
   701         if (focused) {
   702             focusPrompt();
   703         }
   704     }
   705 
   706     public void setHandler(final TextConsoleHandler handler) {
   707         this.handler = handler;
   708 
   709     }
   710 
   711     public void setRows(final int rows) {
   712         if (rows > 0) {
   713             this.rows = rows;
   714             calculateHeightFromRows();
   715         } else {
   716             calculateRowsFromHeight();
   717         }
   718     }
   719 
   720     public int getRows() {
   721         return rows;
   722     }
   723 
   724     public void setCols(final int cols) {
   725         if (cols > 0) {
   726             this.cols = cols;
   727             calculateWidthFromCols();
   728         } else {
   729             calculateColsFromWidth();
   730         }
   731     }
   732 
   733     public int getCols() {
   734         return cols;
   735     }
   736 
   737     public void reset() {
   738         setPromtActive(false);
   739         clearBuffer();
   740         setPromptHeight(getRows());
   741         print(config.getGreeting());
   742         prompt();
   743     }
   744 
   745     public int getBufferSize() {
   746         return (buffer.getClientHeight() / fontH);
   747     }
   748 
   749     public int getMaxBufferSize() {
   750         return maxBufferSize;
   751     }
   752 
   753     public void setMaxBufferSize(final int maxBuffer) {
   754         maxBufferSize = maxBuffer > 0 ? maxBuffer : 0;
   755         checkBufferLimit();
   756     }
   757 
   758     public void clearBuffer() {
   759         // Remove all children.
   760         while (buffer.hasChildNodes()) {
   761             buffer.removeChild(buffer.getFirstChild());
   762         }
   763     }
   764 
   765     public void formFeed() {
   766         for (int i = 0; i < promptRows; i++) {
   767             newLine();
   768         }
   769         setPromptHeight(getRows());
   770         scrollToEnd();
   771 
   772         checkBufferLimit();
   773     }
   774 
   775     protected void clearCommandHistory() {
   776         cmdHistory = new ArrayList<String>();
   777         cmdHistoryIndex = -1;
   778     }
   779 
   780     public String getHeight() {
   781         return (term.getClientHeight() - 2 * padding) + "px";
   782     }
   783 
   784     public String getWidth() {
   785         return (term.getClientWidth() + scrollbarW - 2 * paddingW) + "px";
   786     }
   787 
   788     protected void bell() {
   789         // Clear previous
   790         if (timer != null) {
   791             timer.cancel();
   792             timer = null;
   793             term.removeClassName("term-rev");
   794             input.removeClassName("term-rev");
   795         }
   796         // Add styles and start the timer
   797         input.addClassName("term-rev");
   798         term.addClassName("term-rev");
   799         timer = new Timer() {
   800 
   801             @Override
   802             public void run() {
   803                 term.removeClassName("term-rev");
   804                 input.removeClassName("term-rev");
   805             }
   806         };
   807         timer.schedule(150);
   808     }
   809 
   810     @Override
   811     protected void onUnload() {
   812         super.onUnload();
   813 
   814         if (clickHandler != null) {
   815             clickHandler.removeHandler();
   816         }
   817         if (focusHandler != null) {
   818             focusHandler.removeHandler();
   819         }
   820         if (keyHandler != null) {
   821             keyHandler.removeHandler();
   822         }
   823     }
   824 }