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 setPromtActive(false);
266 // Append newline first if not there yet
267 if (!bufferIsEmpty() && !bufferEndsWithNewLine()) {
271 if (config.isPrintPromptOnInput()) {
272 print(getCurrentPromptContent());
275 if (promptRows > 1) {
278 String lineBuffer = getInput();
279 lineBuffer = lineBuffer.trim();
280 if (!"".equals(lineBuffer)) {
281 cmdHistory.add(lineBuffer);
282 cmdHistoryIndex = cmdHistory.size();
284 if (handler != null) {
285 handler.terminalInput(this, lineBuffer);
289 private boolean bufferIsEmpty() {
290 return !buffer.hasChildNodes();
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);
301 private boolean isPromptActive() {
302 return !Display.NONE.getCssName()
303 .equals(prompt.getStyle().getDisplay());
306 private boolean isFocused() {
310 public void setConfig(final TextConsoleConfig cfg) {
313 updateFontDimensions();
315 scrollbarW = getScrollbarWidth();
316 final String padStr = term.getStyle().getPadding();
317 if (padStr != null && padStr.endsWith("px")) {
319 .parseInt(padStr.substring(0, padStr.length() - 2));
321 // _log("using default padding: 1x2");
326 // _log("setConfig: font=" + fontW + "x" + fontH + ";scrollbar="
327 // + scrollbarW + ";cols=" + config.getCols() + ";rows="
328 // + config.getRows() + ";size=" + getWidth() + "x" + getHeight());
330 setPs(config.getPs());
331 setCols(config.getCols());
332 setRows(config.getRows());
333 setMaxBufferSize(config.getMaxBufferSize());
336 private void updateFontDimensions() {
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);
345 fontW = test.getClientWidth();
346 fontH = test.getClientHeight();
347 if (fontW <= 0 || fontW > 100) {
348 fontW = test.getOffsetWidth();
350 if (fontH <= 0|| fontH > 100) {
351 fontH = test.getOffsetHeight();
353 if (fontW <= 0 || fontW > 100) {
356 if (fontH <= 0|| fontH > 100) {
359 term.removeChild(test);
362 // Debug instrumentation. TODO: Remove.
363 // protected void _log(final String string) {
364 // ApplicationConnection.getConsole().log(string);
367 public TextConsoleConfig getConfig() {
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());
377 private Node createTextNode(final String text) {
378 return Document.get().createTextNode(text);
381 private Node createBr() {
382 return Document.get().createBRElement();
385 public void focusPrompt() {
389 public void focusPrompt(final int cursorPos) {
393 final String s = getInput();
394 if (s != null && s.length() > 0) {
395 setSelectionRange(input, s.length(), s.length());
399 private native void setSelectionRange(Element input, int selectionStart,
400 int selectionEnd)/*-{
401 if (input.setSelectionRange) {
403 input.setSelectionRange(selectionStart, selectionEnd);
405 else if (input.createTextRange) {
406 var range = input.createTextRange();
407 range.collapse(true);
408 range.moveEnd('character', selectionEnd);
409 range.moveStart('character', selectionStart);
414 private native int getScrollbarWidth()/*-{
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';
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';
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);
440 public void newLine() {
442 buffer.appendChild(createBr());
447 protected void setPs(final String string) {
448 cleanPs = Util.escapeHTML(string);
449 cleanPs = cleanPs.replaceAll(" ", " ");
450 ps.setInnerHTML(cleanPs);
453 public void prompt(final String inputText) {
454 setPromtActive(true);
456 ps.setInnerHTML(cleanPs);
460 public void focusInput(){
461 setPromtActive(true);
463 ps.setInnerHTML(cleanPs);
466 public void scrollToEnd() {
467 term.setScrollTop(BIG_NUMBER);
470 public void prompt() {
474 public void print(String string) {
475 if (isPromptActive()) {
476 setPromtActive(false);
477 if (!bufferIsEmpty() && !bufferEndsWithNewLine()) {
481 string = getCurrentPromptContent() + string;
483 final boolean doWrap = config.isWrap();
484 // _log("print original: '" + string + "' (" + doWrap + ")");
485 String str = string.replaceAll("\t", tabs);
487 // Continue to the last text node if available
488 final Node last = getLastTextNode();
491 // _log("print append to old node: '" + last.getNodeValue() + "'");
492 str = last.getNodeValue() + str;
493 buffer.removeChild(last);
497 // Split by the newlines anyway
498 int s = 0, e = str.indexOf('\n');
500 final String line = str.substring(s, e);
501 linesAdded += appendLine(buffer, line, doWrap ? cols : -1);
502 buffer.appendChild(createBr());
504 e = str.indexOf('\n', s);
507 // Print the remaining string
508 if (s < str.length()) {
509 linesAdded += appendLine(buffer, str.substring(s), doWrap ? cols
513 reducePrompt(linesAdded);
516 public void append(String string) {
517 if (isPromptActive()) {
518 setPromtActive(false);
520 final boolean doWrap = config.isWrap();
521 // _log("print original: '" + string + "' (" + doWrap + ")");
522 String str = string.replaceAll("\t", tabs);
524 // Continue to the last text node if available
525 final Node last = getLastTextNode();
528 // _log("print append to old node: '" + last.getNodeValue() + "'");
529 str = last.getNodeValue() + str;
530 buffer.removeChild(last);
534 // Split by the newlines anyway
535 int s = 0, e = str.indexOf('\n');
537 final String line = str.substring(s, e);
538 linesAdded += appendLine(buffer, line, doWrap ? cols : -1);
539 buffer.appendChild(createBr());
541 e = str.indexOf('\n', s);
544 // Print the remaining string
545 if (s < str.length()) {
546 linesAdded += appendLine(buffer, str.substring(s), doWrap ? cols : -1);
549 reducePrompt(linesAdded);
552 private String getCurrentPromptContent() {
553 return prompt.getInnerText() + getInput();
556 private void reducePrompt(final int rows) {
557 int newRows = promptRows - rows;
561 // _log("prompt reduced from " + promptRows + " to " + newRows);
562 setPromptHeight(newRows);
565 private void setPromptHeight(final int rows) {
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);
575 * Split long text based on length.
582 private int appendLine(final Node parent, String str, final int maxLine) {
584 final boolean doWrap = maxLine > 0;
586 parent.appendChild(createTextNode(str));
587 // _log("append: '" + str + "'");
590 while (str.length() > maxLine) {
591 final String piece = str.substring(0, maxLine);
592 parent.appendChild(createTextNode(piece));
593 parent.appendChild(createBr());
595 // _log("append: '" + piece + "'");
596 str = str.substring(maxLine);
598 parent.appendChild(createTextNode(str));
599 // _log("append rest: '" + str + "'");
603 // make sore we don't exceed the maximum buffer size
609 private void checkBufferLimit() {
611 // Buffer means only offscreen lines
612 final int maxb = maxBufferSize + (rows - promptRows);
613 while (getBufferSize() > maxb && buffer.hasChildNodes()) {
614 buffer.removeChild(buffer.getFirstChild());
619 private Node getLastTextNode() {
620 if (buffer == null) {
623 final Node l = buffer.getLastChild();
624 if (l != null && l.getNodeType() == Node.TEXT_NODE) {
630 public void println(final String string) {
631 print(string + "\n");
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);
641 calculateRowsFromHeight();
645 protected void calculateRowsFromHeight() {
646 final int h = term.getClientHeight() - (2 * padding);
648 config.setRows(rows);
650 // _log("calculateRowsFromHeight: font=" + fontW + "x" + fontH
651 // + ";scrollbar=" + scrollbarW + ";cols=" + cols + ";rows="
652 // + rows + ";size=" + getWidth() + "x" + getHeight());
656 protected void calculateHeightFromRows() {
657 super.setHeight((rows * fontH) + "px");
659 // _log("calculateHeightFromRows: font=" + fontW + "x" + fontH
660 // + ";scrollbar=" + scrollbarW + ";cols=" + cols + ";rows="
661 // + rows + ";size=" + getWidth() + "x" + getHeight());
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());
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);
683 // _log("calculateWidthFromCols: font=" + fontW + "x" + fontH
684 // + ";scrollbar=" + scrollbarW + ";cols=" + cols + ";rows="
685 // + rows + ";size=" + getWidth() + "x" + getHeight());
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);
695 calculateColsFromWidth();
700 public void setFocus(final boolean focused) {
701 this.focused = focused;
702 super.setFocus(focused);
708 public void setHandler(final TextConsoleHandler handler) {
709 this.handler = handler;
713 public void setRows(final int rows) {
716 calculateHeightFromRows();
718 calculateRowsFromHeight();
722 public int getRows() {
726 public void setCols(final int cols) {
729 calculateWidthFromCols();
731 calculateColsFromWidth();
735 public int getCols() {
739 public void reset() {
740 setPromtActive(false);
742 setPromptHeight(getRows());
743 print(config.getGreeting());
747 public int getBufferSize() {
748 return (buffer.getClientHeight() / fontH);
751 public int getMaxBufferSize() {
752 return maxBufferSize;
755 public void setMaxBufferSize(final int maxBuffer) {
756 maxBufferSize = maxBuffer > 0 ? maxBuffer : 0;
760 public void clearBuffer() {
761 // Remove all children.
762 while (buffer.hasChildNodes()) {
763 buffer.removeChild(buffer.getFirstChild());
767 public void formFeed() {
768 for (int i = 0; i < promptRows; i++) {
771 setPromptHeight(getRows());
777 protected void clearCommandHistory() {
778 cmdHistory = new ArrayList<String>();
779 cmdHistoryIndex = -1;
782 public String getHeight() {
783 return (term.getClientHeight() - 2 * padding) + "px";
786 public String getWidth() {
787 return (term.getClientWidth() + scrollbarW - 2 * paddingW) + "px";
790 protected void bell() {
795 term.removeClassName("term-rev");
796 input.removeClassName("term-rev");
798 // Add styles and start the timer
799 input.addClassName("term-rev");
800 term.addClassName("term-rev");
801 timer = new Timer() {
805 term.removeClassName("term-rev");
806 input.removeClassName("term-rev");
813 protected void onUnload() {
816 if (clickHandler != null) {
817 clickHandler.removeHandler();
819 if (focusHandler != null) {
820 focusHandler.removeHandler();
822 if (keyHandler != null) {
823 keyHandler.removeHandler();