+ new option - setSmartScrollToEnd: scrollToEnd work only if last scroll state is was "end"
1 package org.vaadin.console.client.ui;
3 import java.util.ArrayList;
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;
30 * @author Sami Ekblad / Vaadin
33 public class TextConsole extends FocusWidget {
35 /* Control characters in http://en.wikipedia.org/wiki/Control_character */
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 = '?';
46 private static final char[] CTRL = { CTRL_BELL, CTRL_BACKSPACE, CTRL_TAB,
47 CTRL_LINE_FEED, CTRL_FORM_FEED, CTRL_CARRIAGE_RETURN, CTRL_ESCAPE,
50 public static char getControlKey(final int kc) {
51 for (final char c : CTRL) {
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;
78 private String tabs = DEFAULT_TABS;
79 private boolean focused;
80 private int promptRows;
82 private final DivElement promptWrap;
84 private int maxBufferSize;
85 private String cleanPs;
88 public TextConsole() {
91 term = Document.get().createDivElement();
92 term.addClassName("term");
97 buffer = Document.get().createElement("pre");
98 buffer.addClassName("b");
99 term.appendChild(buffer);
102 promptWrap = Document.get().createDivElement();
103 promptWrap.addClassName("pw");
104 term.appendChild(promptWrap);
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");
113 final TableSectionElement tbody = Document.get().createTBodyElement();
114 prompt.appendChild(tbody);
116 final TableRowElement tr = Document.get().createTRElement();
117 tbody.appendChild(tr);
119 final TableCellElement psTd = Document.get().createTDElement();
120 psTd.addClassName("psw");
121 tr.appendChild(psTd);
123 ps = Document.get().createElement("nobr");
124 ps.addClassName("ps");
125 psTd.appendChild(ps);
127 final TableCellElement inputTd = Document.get().createTDElement();
128 inputTd.addClassName("iw");
129 tr.appendChild(inputTd);
131 input = (InputElement) Document.get().createElement("input");
132 inputTd.appendChild(input);
133 input.addClassName("i");
134 input.setTabIndex(-1);
135 input.setAttribute("spellcheck", "false");
137 config = TextConsoleConfig.newInstance();
139 setPromtActive(false);
141 clickHandler = addDomHandler(new ClickHandler() {
143 public void onClick(final ClickEvent event) {
146 }, ClickEvent.getType());
148 keyHandler = addDomHandler(new KeyDownHandler() {
150 public void onKeyDown(final KeyDownEvent event) {
152 // (re-)show the prompt
153 setPromtActive(true);
155 if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
156 event.preventDefault();
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();
165 } else if (event.getNativeKeyCode() == KeyCodes.KEY_BACKSPACE
166 && getInputLenght() == 0) {
168 } else if (event.getNativeEvent().getCtrlKey()) {
169 final char ctrlChar = getControlKey(event.getNativeKeyCode());
171 event.preventDefault();
172 handleControlChar(ctrlChar);
177 }, KeyDownEvent.getType());
179 updateFontDimensions();
182 protected int getInputLenght() {
183 final String v = input.getValue();
190 protected void handleControlChar(final char c) {
192 case TextConsole.CTRL_BACKSPACE:
195 case TextConsole.CTRL_BELL:
198 case TextConsole.CTRL_CARRIAGE_RETURN:
201 case TextConsole.CTRL_DELETE:
202 bell(); // TODO: not supported yet
204 case TextConsole.CTRL_ESCAPE:
205 bell(); // TODO: not supported yet
207 case TextConsole.CTRL_FORM_FEED:
210 case TextConsole.CTRL_LINE_FEED:
213 case TextConsole.CTRL_TAB:
223 protected void suggest() {
224 // No suggest by default. Implement by subclassing.
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));
237 public String getInput() {
238 return input.getValue();
241 protected void setInput(final String inputText) {
242 if (inputText != null) {
243 input.setValue(inputText);
252 public void lineFeed() {
256 protected void tab() {
257 prompt(getInput() + "\t");
260 protected void backspace() {
264 protected void carriageReturn() {
265 if (config.isPrintPromptOnInput()) {
266 setPromtActive(false);
267 // Append newline first if not there yet
268 if (!bufferIsEmpty() && !bufferEndsWithNewLine()) {
272 print(getCurrentPromptContent());
274 if (promptRows > 1) {
278 if (!bufferIsEmpty() && !bufferEndsWithNewLine()) {
280 if (promptRows > 1) {
285 String lineBuffer = getInput();
286 lineBuffer = lineBuffer.trim();
287 if (!"".equals(lineBuffer)) {
288 cmdHistory.add(lineBuffer);
289 cmdHistoryIndex = cmdHistory.size();
291 if (handler != null) {
292 handler.terminalInput(this, lineBuffer);
296 private boolean bufferIsEmpty() {
297 return !buffer.hasChildNodes();
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);
308 private boolean isPromptActive() {
309 return !Display.NONE.getCssName()
310 .equals(prompt.getStyle().getDisplay());
313 private boolean isFocused() {
317 public void setConfig(final TextConsoleConfig cfg) {
320 updateFontDimensions();
322 scrollbarW = getScrollbarWidth();
323 final String padStr = term.getStyle().getPadding();
324 if (padStr != null && padStr.endsWith("px")) {
326 .parseInt(padStr.substring(0, padStr.length() - 2));
328 // _log("using default padding: 1x2");
333 // _log("setConfig: font=" + fontW + "x" + fontH + ";scrollbar="
334 // + scrollbarW + ";cols=" + config.getCols() + ";rows="
335 // + config.getRows() + ";size=" + getWidth() + "x" + getHeight());
337 setPs(config.getPs());
338 setCols(config.getCols());
339 setRows(config.getRows());
340 setMaxBufferSize(config.getMaxBufferSize());
343 private void updateFontDimensions() {
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);
352 fontW = test.getClientWidth();
353 fontH = test.getClientHeight();
354 if (fontW <= 0 || fontW > 100) {
355 fontW = test.getOffsetWidth();
357 if (fontH <= 0|| fontH > 100) {
358 fontH = test.getOffsetHeight();
360 if (fontW <= 0 || fontW > 100) {
363 if (fontH <= 0|| fontH > 100) {
366 term.removeChild(test);
369 // Debug instrumentation. TODO: Remove.
370 // protected void _log(final String string) {
371 // ApplicationConnection.getConsole().log(string);
374 public TextConsoleConfig getConfig() {
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());
384 private Node createTextNode(final String text) {
385 return Document.get().createTextNode(text);
388 private Node createBr() {
389 return Document.get().createBRElement();
392 public void focusPrompt() {
396 public void focusPrompt(final int cursorPos) {
400 final String s = getInput();
401 if (s != null && s.length() > 0) {
402 setSelectionRange(input, s.length(), s.length());
406 private native void setSelectionRange(Element input, int selectionStart,
407 int selectionEnd)/*-{
408 if (input.setSelectionRange) {
410 input.setSelectionRange(selectionStart, selectionEnd);
412 else if (input.createTextRange) {
413 var range = input.createTextRange();
414 range.collapse(true);
415 range.moveEnd('character', selectionEnd);
416 range.moveStart('character', selectionStart);
421 private native int getScrollbarWidth()/*-{
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';
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';
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);
447 public void newLine() {
449 beforeChangeTerminal();
450 buffer.appendChild(createBr());
455 public void newLineIfNotEndsWithNewLine() {
456 if (!bufferIsEmpty() && !bufferEndsWithNewLine()) {
458 beforeChangeTerminal();
459 buffer.appendChild(createBr());
465 protected void setPs(final String string) {
466 cleanPs = Util.escapeHTML(string);
467 cleanPs = cleanPs.replaceAll(" ", " ");
468 ps.setInnerHTML(cleanPs);
471 public void prompt(final String inputText) {
472 setPromtActive(true);
474 ps.setInnerHTML(cleanPs);
478 public void focusInput() {
480 setPromtActive(true);
482 ps.setInnerHTML(cleanPs);
485 private boolean isCheckedScrollState = false;
487 public void scrollToEnd() {
488 if (config.isSmartScrollToEnd()) {
489 if (config.isScrolledToEnd())
490 term.setScrollTop(BIG_NUMBER);
492 term.setScrollTop(BIG_NUMBER);
493 isCheckedScrollState = false;
496 private void beforeChangeTerminal(){
497 if(!isCheckedScrollState){
498 config.setScrolledToEnd(term.getScrollTop() >= term.getScrollHeight() - term.getClientHeight());
499 isCheckedScrollState = true;
503 public void prompt() {
507 public void print(String string) {
508 beforeChangeTerminal();
509 if (isPromptActive()) {
510 setPromtActive(false);
511 if (!bufferIsEmpty() && !bufferEndsWithNewLine()) {
515 string = getCurrentPromptContent() + string;
517 final boolean doWrap = config.isWrap();
518 // _log("print original: '" + string + "' (" + doWrap + ")");
519 String str = string.replaceAll("\t", tabs);
521 // Continue to the last text node if available
522 final Node last = getLastTextNode();
525 // _log("print append to old node: '" + last.getNodeValue() + "'");
526 str = last.getNodeValue() + str;
527 buffer.removeChild(last);
531 // Split by the newlines anyway
532 int s = 0, e = str.indexOf('\n');
534 final String line = str.substring(s, e);
535 linesAdded += appendLine(buffer, line, doWrap ? cols : -1);
536 buffer.appendChild(createBr());
538 e = str.indexOf('\n', s);
541 // Print the remaining string
542 if (s < str.length()) {
543 linesAdded += appendLine(buffer, str.substring(s), doWrap ? cols
547 reducePrompt(linesAdded);
550 public void print(String string, String className) {
551 beforeChangeTerminal();
552 if (isPromptActive()) {
553 setPromtActive(false);
554 if (!bufferIsEmpty() && !bufferEndsWithNewLine()) {
558 string = getCurrentPromptContent() + string;
560 final boolean doWrap = config.isWrap();
561 // _log("print original: '" + string + "' (" + doWrap + ")");
562 String str = string.replaceAll("\t", tabs);
565 Element classedChild = Document.get().createElement("span");
566 classedChild.addClassName(className);
567 buffer.appendChild(classedChild);
568 // Split by the newlines anyway
569 int s = 0, e = str.indexOf('\n');
571 final String line = str.substring(s, e);
572 linesAdded += appendLine(classedChild, line, doWrap ? cols : -1);
573 classedChild.appendChild(createBr());
575 e = str.indexOf('\n', s);
578 // Print the remaining string
579 if (s < str.length()) {
580 linesAdded += appendLine(classedChild, str.substring(s), doWrap ? cols : -1);
583 reducePrompt(linesAdded);
586 public void append(String string) {
587 beforeChangeTerminal();
588 final boolean doWrap = config.isWrap();
589 // _log("print original: '" + string + "' (" + doWrap + ")");
590 String str = string.replaceAll("\t", tabs);
592 // Continue to the last text node if available
593 final Node last = getLastTextNode();
596 // _log("print append to old node: '" + last.getNodeValue() + "'");
597 str = last.getNodeValue() + str;
598 buffer.removeChild(last);
602 // Split by the newlines anyway
603 int s = 0, e = str.indexOf('\n');
605 final String line = str.substring(s, e);
606 linesAdded += appendLine(buffer, line, doWrap ? cols : -1);
607 buffer.appendChild(createBr());
609 e = str.indexOf('\n', s);
612 // Print the remaining string
613 if (s < str.length()) {
614 linesAdded += appendLine(buffer, str.substring(s), doWrap ? cols : -1);
617 reducePrompt(linesAdded);
620 public void append(String string, String className) {
621 beforeChangeTerminal();
622 final boolean doWrap = config.isWrap();
623 // _log("print original: '" + string + "' (" + doWrap + ")");
624 String str = string.replaceAll("\t", tabs);
627 Element classedChild = Document.get().createElement("span");
628 classedChild.addClassName(className);
629 buffer.appendChild(classedChild);
630 // Split by the newlines anyway
631 int s = 0, e = str.indexOf('\n');
633 final String line = str.substring(s, e);
634 linesAdded += appendLine(classedChild, line, doWrap ? cols : -1);
635 classedChild.appendChild(createBr());
637 e = str.indexOf('\n', s);
640 // Print the remaining string
641 if (s < str.length()) {
642 linesAdded += appendLine(classedChild, str.substring(s), doWrap ? cols : -1);
645 reducePrompt(linesAdded);
648 private String getCurrentPromptContent() {
649 return prompt.getInnerText() + getInput();
652 private void reducePrompt(final int rows) {
653 int newRows = promptRows - rows;
657 // _log("prompt reduced from " + promptRows + " to " + newRows);
658 setPromptHeight(newRows);
661 private void setPromptHeight(final int rows) {
663 final int max = getRows();
664 promptRows = rows < min ? min : (rows > max ? max : rows);
665 final int newHeight = fontH * rows;
666 // _log("Prompt height=" + newHeight);
667 promptWrap.getStyle().setHeight(newHeight, Unit.PX);
671 * Split long text based on length.
678 private int appendLine(final Node parent, String str, final int maxLine) {
680 final boolean doWrap = maxLine > 0;
682 parent.appendChild(createTextNode(str));
683 // _log("append: '" + str + "'");
686 while (str.length() > maxLine) {
687 final String piece = str.substring(0, maxLine);
688 parent.appendChild(createTextNode(piece));
689 parent.appendChild(createBr());
691 // _log("append: '" + piece + "'");
692 str = str.substring(maxLine);
694 parent.appendChild(createTextNode(str));
695 // _log("append rest: '" + str + "'");
699 // make sore we don't exceed the maximum buffer size
705 private void checkBufferLimit() {
707 // Buffer means only offscreen lines
708 final int maxb = maxBufferSize + (rows - promptRows);
709 while (getBufferSize() > maxb && buffer.hasChildNodes()) {
710 buffer.removeChild(buffer.getFirstChild());
715 private Node getLastTextNode() {
716 if (buffer == null) {
719 final Node l = buffer.getLastChild();
720 if (l != null && l.getNodeType() == Node.TEXT_NODE) {
726 public void println(final String string) {
727 print(string + "\n");
730 public void println(final String string, final String className) {
731 print(string + "\n", className);
735 public void setHeight(final String height) {
736 final int oldh = term.getClientHeight();
737 super.setHeight(height);
738 final int newh = term.getClientHeight();
739 // _log("set height=" + height + " clientHeight="+oldh+" to "+newh);
741 calculateRowsFromHeight();
745 protected void calculateRowsFromHeight() {
746 final int h = term.getClientHeight() - (2 * padding);
748 config.setRows(rows);
750 // _log("calculateRowsFromHeight: font=" + fontW + "x" + fontH
751 // + ";scrollbar=" + scrollbarW + ";cols=" + cols + ";rows="
752 // + rows + ";size=" + getWidth() + "x" + getHeight());
756 protected void calculateHeightFromRows() {
757 super.setHeight((rows * fontH) + "px");
759 // _log("calculateHeightFromRows: font=" + fontW + "x" + fontH
760 // + ";scrollbar=" + scrollbarW + ";cols=" + cols + ";rows="
761 // + rows + ";size=" + getWidth() + "x" + getHeight());
765 protected void calculateColsFromWidth() {
766 final int w = term.getClientWidth();
767 cols = (w - 2 * paddingW) / fontW;
768 config.setCols(cols);
769 buffer.getStyle().setWidth((cols * fontW), Unit.PX);
770 prompt.getStyle().setWidth((cols * fontW), Unit.PX);
771 // _log("calculateColsFromWidth: font=" + fontW + "x" + fontH
772 // + ";scrollbar=" + scrollbarW + ";cols=" + cols + ";rows="
773 // + rows + ";size=" + getWidth() + "x" + getHeight());
777 protected void calculateWidthFromCols() {
778 final int w = cols * fontW;
779 super.setWidth((w + scrollbarW) + "px");
780 buffer.getStyle().setWidth(w, Unit.PX);
781 prompt.getStyle().setWidth(w, Unit.PX);
783 // _log("calculateWidthFromCols: font=" + fontW + "x" + fontH
784 // + ";scrollbar=" + scrollbarW + ";cols=" + cols + ";rows="
785 // + rows + ";size=" + getWidth() + "x" + getHeight());
789 public void setWidth(final String width) {
790 final int oldw = term.getClientWidth();
791 super.setWidth(width);
792 final int neww = term.getClientWidth();
793 // _log("set width=" + width + " clientWidth="+oldw+" to "+neww);
795 calculateColsFromWidth();
800 public void setFocus(final boolean focused) {
801 this.focused = focused;
802 super.setFocus(focused);
808 public void setHandler(final TextConsoleHandler handler) {
809 this.handler = handler;
813 public void setRows(final int rows) {
816 calculateHeightFromRows();
818 calculateRowsFromHeight();
822 public int getRows() {
826 public void setCols(final int cols) {
829 calculateWidthFromCols();
831 calculateColsFromWidth();
835 public int getCols() {
839 public void reset() {
840 beforeChangeTerminal();
841 setPromtActive(false);
843 setPromptHeight(getRows());
844 print(config.getGreeting());
848 public int getBufferSize() {
849 return (buffer.getClientHeight() / fontH);
852 public int getMaxBufferSize() {
853 return maxBufferSize;
856 public void setMaxBufferSize(final int maxBuffer) {
857 maxBufferSize = maxBuffer > 0 ? maxBuffer : 0;
861 public void clearBuffer() {
862 // Remove all children.
863 while (buffer.hasChildNodes()) {
864 buffer.removeChild(buffer.getFirstChild());
868 public void formFeed() {
869 for (int i = 0; i < promptRows; i++) {
872 setPromptHeight(getRows());
878 protected void clearCommandHistory() {
879 cmdHistory = new ArrayList<String>();
880 cmdHistoryIndex = -1;
883 public String getHeight() {
884 return (term.getClientHeight() - 2 * padding) + "px";
887 public String getWidth() {
888 return (term.getClientWidth() + scrollbarW - 2 * paddingW) + "px";
891 protected void bell() {
896 term.removeClassName("term-rev");
897 input.removeClassName("term-rev");
899 // Add styles and start the timer
900 input.addClassName("term-rev");
901 term.addClassName("term-rev");
902 timer = new Timer() {
906 term.removeClassName("term-rev");
907 input.removeClassName("term-rev");
914 protected void onUnload() {
917 if (clickHandler != null) {
918 clickHandler.removeHandler();
920 if (focusHandler != null) {
921 focusHandler.removeHandler();
923 if (keyHandler != null) {
924 keyHandler.removeHandler();