src/main/java/org/vaadin/console/client/ui/TextConsole.java
author indvdum
Tue, 17 May 2011 18:50:45 +0400
changeset 4 27bd1032a5c6
parent 3 3eab4f9f42a9
child 5 01a04ffaf85f
permissions -rw-r--r--
+ new client option isPrintPromptOnInput
     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 		if (config.isPrintPromptOnInput()) {
   272 			print(getCurrentPromptContent());
   273 			newLine();
   274 		}
   275         if (promptRows > 1) {
   276             reducePrompt(-1);
   277         }
   278         String lineBuffer = getInput();
   279         lineBuffer = lineBuffer.trim();
   280         if (!"".equals(lineBuffer)) {
   281             cmdHistory.add(lineBuffer);
   282             cmdHistoryIndex = cmdHistory.size();
   283         }
   284         if (handler != null) {
   285             handler.terminalInput(this, lineBuffer);
   286         }
   287     }
   288 
   289     private boolean bufferIsEmpty() {
   290         return !buffer.hasChildNodes();
   291     }
   292 
   293     private void setPromtActive(final boolean active) {
   294         if (active && !isPromptActive()) {
   295             prompt.getStyle().setDisplay(Display.BLOCK);
   296         } else if (!active && isPromptActive()) {
   297             prompt.getStyle().setDisplay(Display.NONE);
   298         }
   299     }
   300 
   301     private boolean isPromptActive() {
   302         return !Display.NONE.getCssName()
   303                 .equals(prompt.getStyle().getDisplay());
   304     }
   305 
   306     private boolean isFocused() {
   307         return focused;
   308     }
   309 
   310     public void setConfig(final TextConsoleConfig cfg) {
   311         config = cfg;
   312 
   313         updateFontDimensions();
   314 
   315         scrollbarW = getScrollbarWidth();
   316         final String padStr = term.getStyle().getPadding();
   317         if (padStr != null && padStr.endsWith("px")) {
   318             padding = Integer
   319                     .parseInt(padStr.substring(0, padStr.length() - 2));
   320         } else {
   321             // _log("using default padding: 1x2");
   322             padding = 1;
   323             paddingW = 2;
   324         }
   325 
   326         // _log("setConfig: font=" + fontW + "x" + fontH + ";scrollbar="
   327         // + scrollbarW + ";cols=" + config.getCols() + ";rows="
   328         // + config.getRows() + ";size=" + getWidth() + "x" + getHeight());
   329 
   330         setPs(config.getPs());
   331         setCols(config.getCols());
   332         setRows(config.getRows());
   333         setMaxBufferSize(config.getMaxBufferSize());
   334     }
   335 
   336     private void updateFontDimensions() {
   337 
   338         // Test element for font size
   339         DivElement test = Document.get().createDivElement();
   340         test.setAttribute("style",
   341                 "position: absolute;");
   342         test.setInnerHTML("X");
   343         term.appendChild(test);
   344 
   345         fontW = test.getClientWidth();
   346         fontH = test.getClientHeight();
   347         if (fontW <= 0 || fontW > 100) {
   348             fontW = test.getOffsetWidth();
   349         }
   350         if (fontH <= 0|| fontH > 100) {
   351             fontH = test.getOffsetHeight();
   352         }
   353         if (fontW <= 0 || fontW > 100) {
   354             fontW = 1;
   355         }
   356         if (fontH <= 0|| fontH > 100) {
   357             fontH = 1;
   358         }
   359         term.removeChild(test);
   360     }
   361 
   362     // Debug instrumentation. TODO: Remove.
   363 //    protected void _log(final String string) {
   364 //        ApplicationConnection.getConsole().log(string);
   365 //    }
   366 
   367     public TextConsoleConfig getConfig() {
   368         return config;
   369     }
   370 
   371     private boolean bufferEndsWithNewLine() {
   372         final Node last = buffer != null ? buffer.getLastChild() : null;
   373         // _log("last node: " + (last != null ? last.getNodeName() : "<null>"));
   374         return last != null && "br".equals(last.getNodeName().toLowerCase());
   375     }
   376 
   377     private Node createTextNode(final String text) {
   378         return Document.get().createTextNode(text);
   379     }
   380 
   381     private Node createBr() {
   382         return Document.get().createBRElement();
   383     }
   384 
   385     public void focusPrompt() {
   386         focusPrompt(-1);
   387     }
   388 
   389     public void focusPrompt(final int cursorPos) {
   390         input.focus();
   391 
   392         // Focus to end
   393         final String s = getInput();
   394         if (s != null && s.length() > 0) {
   395             setSelectionRange(input, s.length(), s.length());
   396         }
   397     }
   398 
   399     private native void setSelectionRange(Element input, int selectionStart,
   400             int selectionEnd)/*-{
   401                              if (input.setSelectionRange) {
   402                              input.focus();
   403                              input.setSelectionRange(selectionStart, selectionEnd);
   404                              }
   405                              else if (input.createTextRange) {
   406                              var range = input.createTextRange();
   407                              range.collapse(true);
   408                              range.moveEnd('character', selectionEnd);
   409                              range.moveStart('character', selectionStart);
   410                              range.select();
   411                              }
   412                              }-*/;
   413 
   414     private native int getScrollbarWidth()/*-{
   415 
   416                                           var i = $doc.createElement('p');
   417                                           i.style.width = '100%';
   418                                           i.style.height = '200px';
   419                                           var o = $doc.createElement('div');
   420                                           o.style.position = 'absolute';
   421                                           o.style.top = '0px';
   422                                           o.style.left = '0px';
   423                                           o.style.visibility = 'hidden';
   424                                           o.style.width = '200px';
   425                                           o.style.height = '150px';
   426                                           o.style.overflow = 'hidden';
   427                                           o.appendChild(i);
   428                                           $doc.body.appendChild(o);
   429                                           var w1 = i.offsetWidth;
   430                                           var h1 = i.offsetHeight;
   431                                           o.style.overflow = 'scroll';
   432                                           var w2 = i.offsetWidth;
   433                                           var h2 = i.offsetHeight;
   434                                           if (w1 == w2) w2 = o.clientWidth;
   435                                           if (h1 == h2) h2 = o.clientWidth;
   436                                           $doc.body.removeChild(o);
   437                                           return w1-w2;
   438                                           }-*/;
   439 
   440     public void newLine() {
   441         // _log("newline");
   442         buffer.appendChild(createBr());
   443         checkBufferLimit();
   444         reducePrompt(1);
   445     }
   446 
   447     protected void setPs(final String string) {
   448         cleanPs = Util.escapeHTML(string);
   449         cleanPs = cleanPs.replaceAll(" ", "&nbsp;");
   450         ps.setInnerHTML(cleanPs);
   451     }
   452 
   453     public void prompt(final String inputText) {
   454         setPromtActive(true);
   455         scrollToEnd();
   456         ps.setInnerHTML(cleanPs);
   457         setInput(inputText);
   458     }
   459     
   460     public void focusInput(){
   461         setPromtActive(true);
   462         scrollToEnd();
   463         ps.setInnerHTML(cleanPs);
   464     }
   465 
   466     public void scrollToEnd() {
   467         term.setScrollTop(BIG_NUMBER);
   468     }
   469 
   470     public void prompt() {
   471         prompt(null);
   472     }
   473 
   474     public void print(String string) {
   475         if (isPromptActive()) {
   476             setPromtActive(false);
   477             if (!bufferIsEmpty() && !bufferEndsWithNewLine()) {
   478                 newLine();
   479                 reducePrompt(-1);
   480             }
   481             string = getCurrentPromptContent() + string;
   482         }
   483         final boolean doWrap = config.isWrap();
   484         // _log("print original: '" + string + "' (" + doWrap + ")");
   485         String str = string.replaceAll("\t", tabs);
   486 
   487         // Continue to the last text node if available
   488         final Node last = getLastTextNode();
   489         int linesAdded = 0;
   490         if (last != null) {
   491             // _log("print append to old node: '" + last.getNodeValue() + "'");
   492             str = last.getNodeValue() + str;
   493             buffer.removeChild(last);
   494             linesAdded--;
   495         }
   496 
   497         // Split by the newlines anyway
   498         int s = 0, e = str.indexOf('\n');
   499         while (e >= s) {
   500             final String line = str.substring(s, e);
   501             linesAdded += appendLine(buffer, line, doWrap ? cols : -1);
   502             buffer.appendChild(createBr());
   503             s = e + 1;
   504             e = str.indexOf('\n', s);
   505         }
   506 
   507         // Print the remaining string
   508         if (s < str.length()) {
   509             linesAdded += appendLine(buffer, str.substring(s), doWrap ? cols
   510                     : -1);
   511         }
   512 
   513         reducePrompt(linesAdded);
   514     }
   515     
   516 	public void append(String string) {
   517 		if (isPromptActive()) {
   518 			setPromtActive(false);
   519 		}
   520 		final boolean doWrap = config.isWrap();
   521 		// _log("print original: '" + string + "' (" + doWrap + ")");
   522 		String str = string.replaceAll("\t", tabs);
   523 
   524 		// Continue to the last text node if available
   525 		final Node last = getLastTextNode();
   526 		int linesAdded = 0;
   527 		if (last != null) {
   528 			// _log("print append to old node: '" + last.getNodeValue() + "'");
   529 			str = last.getNodeValue() + str;
   530 			buffer.removeChild(last);
   531 			linesAdded--;
   532 		}
   533 
   534 		// Split by the newlines anyway
   535 		int s = 0, e = str.indexOf('\n');
   536 		while (e >= s) {
   537 			final String line = str.substring(s, e);
   538 			linesAdded += appendLine(buffer, line, doWrap ? cols : -1);
   539 			buffer.appendChild(createBr());
   540 			s = e + 1;
   541 			e = str.indexOf('\n', s);
   542 		}
   543 
   544 		// Print the remaining string
   545 		if (s < str.length()) {
   546 			linesAdded += appendLine(buffer, str.substring(s), doWrap ? cols : -1);
   547 		}
   548 
   549 		reducePrompt(linesAdded);
   550 	}
   551 
   552     private String getCurrentPromptContent() {
   553         return prompt.getInnerText() + getInput();
   554     }
   555 
   556     private void reducePrompt(final int rows) {
   557         int newRows = promptRows - rows;
   558         if (newRows < 1) {
   559             newRows = 1;
   560         }
   561         // _log("prompt reduced from " + promptRows + " to " + newRows);
   562         setPromptHeight(newRows);
   563     }
   564 
   565     private void setPromptHeight(final int rows) {
   566         final int min = 1;
   567         final int max = getRows();
   568         promptRows = rows < min ? min : (rows > max ? max : rows);
   569         final int newHeight = fontH * rows;
   570         // _log("Prompt height=" + newHeight);
   571         promptWrap.getStyle().setHeight(newHeight, Unit.PX);
   572     }
   573 
   574     /**
   575      * Split long text based on length.
   576      *
   577      * @param parent
   578      * @param doWrap
   579      * @param str
   580      * @return
   581      */
   582     private int appendLine(final Node parent, String str, final int maxLine) {
   583         int linesAdded = 0;
   584         final boolean doWrap = maxLine > 0;
   585         if (!doWrap) {
   586             parent.appendChild(createTextNode(str));
   587             // _log("append: '" + str + "'");
   588             linesAdded++;
   589         } else {
   590             while (str.length() > maxLine) {
   591                 final String piece = str.substring(0, maxLine);
   592                 parent.appendChild(createTextNode(piece));
   593                 parent.appendChild(createBr());
   594                 linesAdded++;
   595                 // _log("append: '" + piece + "'");
   596                 str = str.substring(maxLine);
   597             }
   598             parent.appendChild(createTextNode(str));
   599             // _log("append rest: '" + str + "'");
   600             linesAdded++;
   601         }
   602 
   603         // make sore we don't exceed the maximum buffer size
   604         checkBufferLimit();
   605 
   606         return linesAdded;
   607     }
   608 
   609     private void checkBufferLimit() {
   610 
   611         // Buffer means only offscreen lines
   612         final int maxb = maxBufferSize + (rows - promptRows);
   613         while (getBufferSize() > maxb && buffer.hasChildNodes()) {
   614             buffer.removeChild(buffer.getFirstChild());
   615         }
   616 
   617     }
   618 
   619     private Node getLastTextNode() {
   620         if (buffer == null) {
   621             return null;
   622         }
   623         final Node l = buffer.getLastChild();
   624         if (l != null && l.getNodeType() == Node.TEXT_NODE) {
   625             return l;
   626         }
   627         return null;
   628     }
   629 
   630     public void println(final String string) {
   631         print(string + "\n");
   632     }
   633 
   634     @Override
   635     public void setHeight(final String height) {
   636         final int oldh = term.getClientHeight();
   637         super.setHeight(height);
   638         final int newh = term.getClientHeight();
   639         // _log("set height=" + height + " clientHeight="+oldh+" to "+newh);
   640         if (newh != oldh) {
   641             calculateRowsFromHeight();
   642         }
   643     }
   644 
   645     protected void calculateRowsFromHeight() {
   646         final int h = term.getClientHeight() - (2 * padding);
   647         rows = h / fontH;
   648         config.setRows(rows);
   649 
   650         // _log("calculateRowsFromHeight: font=" + fontW + "x" + fontH
   651         // + ";scrollbar=" + scrollbarW + ";cols=" + cols + ";rows="
   652         // + rows + ";size=" + getWidth() + "x" + getHeight());
   653 
   654     }
   655 
   656     protected void calculateHeightFromRows() {
   657         super.setHeight((rows * fontH) + "px");
   658 
   659         // _log("calculateHeightFromRows: font=" + fontW + "x" + fontH
   660         // + ";scrollbar=" + scrollbarW + ";cols=" + cols + ";rows="
   661         // + rows + ";size=" + getWidth() + "x" + getHeight());
   662 
   663     }
   664 
   665     protected void calculateColsFromWidth() {
   666         final int w = term.getClientWidth();
   667         cols = (w - 2 * paddingW) / fontW;
   668         config.setCols(cols);
   669         buffer.getStyle().setWidth((cols * fontW), Unit.PX);
   670         prompt.getStyle().setWidth((cols * fontW), Unit.PX);
   671         // _log("calculateColsFromWidth: font=" + fontW + "x" + fontH
   672         // + ";scrollbar=" + scrollbarW + ";cols=" + cols + ";rows="
   673         // + rows + ";size=" + getWidth() + "x" + getHeight());
   674 
   675     }
   676 
   677     protected void calculateWidthFromCols() {
   678         final int w = cols * fontW;
   679         super.setWidth((w + scrollbarW) + "px");
   680         buffer.getStyle().setWidth(w, Unit.PX);
   681         prompt.getStyle().setWidth(w, Unit.PX);
   682 
   683         // _log("calculateWidthFromCols: font=" + fontW + "x" + fontH
   684         // + ";scrollbar=" + scrollbarW + ";cols=" + cols + ";rows="
   685         // + rows + ";size=" + getWidth() + "x" + getHeight());
   686     }
   687 
   688     @Override
   689     public void setWidth(final String width) {
   690         final int oldw = term.getClientWidth();
   691         super.setWidth(width);
   692         final int neww = term.getClientWidth();
   693         // _log("set width=" + width + " clientWidth="+oldw+" to "+neww);
   694         if (neww != oldw) {
   695             calculateColsFromWidth();
   696         }
   697     }
   698 
   699     @Override
   700     public void setFocus(final boolean focused) {
   701         this.focused = focused;
   702         super.setFocus(focused);
   703         if (focused) {
   704             focusPrompt();
   705         }
   706     }
   707 
   708     public void setHandler(final TextConsoleHandler handler) {
   709         this.handler = handler;
   710 
   711     }
   712 
   713     public void setRows(final int rows) {
   714         if (rows > 0) {
   715             this.rows = rows;
   716             calculateHeightFromRows();
   717         } else {
   718             calculateRowsFromHeight();
   719         }
   720     }
   721 
   722     public int getRows() {
   723         return rows;
   724     }
   725 
   726     public void setCols(final int cols) {
   727         if (cols > 0) {
   728             this.cols = cols;
   729             calculateWidthFromCols();
   730         } else {
   731             calculateColsFromWidth();
   732         }
   733     }
   734 
   735     public int getCols() {
   736         return cols;
   737     }
   738 
   739     public void reset() {
   740         setPromtActive(false);
   741         clearBuffer();
   742         setPromptHeight(getRows());
   743         print(config.getGreeting());
   744         prompt();
   745     }
   746 
   747     public int getBufferSize() {
   748         return (buffer.getClientHeight() / fontH);
   749     }
   750 
   751     public int getMaxBufferSize() {
   752         return maxBufferSize;
   753     }
   754 
   755     public void setMaxBufferSize(final int maxBuffer) {
   756         maxBufferSize = maxBuffer > 0 ? maxBuffer : 0;
   757         checkBufferLimit();
   758     }
   759 
   760     public void clearBuffer() {
   761         // Remove all children.
   762         while (buffer.hasChildNodes()) {
   763             buffer.removeChild(buffer.getFirstChild());
   764         }
   765     }
   766 
   767     public void formFeed() {
   768         for (int i = 0; i < promptRows; i++) {
   769             newLine();
   770         }
   771         setPromptHeight(getRows());
   772         scrollToEnd();
   773 
   774         checkBufferLimit();
   775     }
   776 
   777     protected void clearCommandHistory() {
   778         cmdHistory = new ArrayList<String>();
   779         cmdHistoryIndex = -1;
   780     }
   781 
   782     public String getHeight() {
   783         return (term.getClientHeight() - 2 * padding) + "px";
   784     }
   785 
   786     public String getWidth() {
   787         return (term.getClientWidth() + scrollbarW - 2 * paddingW) + "px";
   788     }
   789 
   790     protected void bell() {
   791         // Clear previous
   792         if (timer != null) {
   793             timer.cancel();
   794             timer = null;
   795             term.removeClassName("term-rev");
   796             input.removeClassName("term-rev");
   797         }
   798         // Add styles and start the timer
   799         input.addClassName("term-rev");
   800         term.addClassName("term-rev");
   801         timer = new Timer() {
   802 
   803             @Override
   804             public void run() {
   805                 term.removeClassName("term-rev");
   806                 input.removeClassName("term-rev");
   807             }
   808         };
   809         timer.schedule(150);
   810     }
   811 
   812     @Override
   813     protected void onUnload() {
   814         super.onUnload();
   815 
   816         if (clickHandler != null) {
   817             clickHandler.removeHandler();
   818         }
   819         if (focusHandler != null) {
   820             focusHandler.removeHandler();
   821         }
   822         if (keyHandler != null) {
   823             keyHandler.removeHandler();
   824         }
   825     }
   826 }