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