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 print(getCurrentPromptContent());
273 if (promptRows > 1) {
276 String lineBuffer = getInput();
277 lineBuffer = lineBuffer.trim();
278 if (!"".equals(lineBuffer)) {
279 cmdHistory.add(lineBuffer);
280 cmdHistoryIndex = cmdHistory.size();
282 if (handler != null) {
283 handler.terminalInput(this, lineBuffer);
287 private boolean bufferIsEmpty() {
288 return !buffer.hasChildNodes();
291 private void setPromtActive(final boolean active) {
292 if (active && !isPromptActive()) {
293 prompt.getStyle().setDisplay(Display.BLOCK);
294 } else if (!active && isPromptActive()) {
295 prompt.getStyle().setDisplay(Display.NONE);
299 private boolean isPromptActive() {
300 return !Display.NONE.getCssName()
301 .equals(prompt.getStyle().getDisplay());
304 private boolean isFocused() {
308 public void setConfig(final TextConsoleConfig cfg) {
311 updateFontDimensions();
313 scrollbarW = getScrollbarWidth();
314 final String padStr = term.getStyle().getPadding();
315 if (padStr != null && padStr.endsWith("px")) {
317 .parseInt(padStr.substring(0, padStr.length() - 2));
319 // _log("using default padding: 1x2");
324 // _log("setConfig: font=" + fontW + "x" + fontH + ";scrollbar="
325 // + scrollbarW + ";cols=" + config.getCols() + ";rows="
326 // + config.getRows() + ";size=" + getWidth() + "x" + getHeight());
328 setPs(config.getPs());
329 setCols(config.getCols());
330 setRows(config.getRows());
331 setMaxBufferSize(config.getMaxBufferSize());
334 private void updateFontDimensions() {
336 // Test element for font size
337 DivElement test = Document.get().createDivElement();
338 test.setAttribute("style",
339 "position: absolute;");
340 test.setInnerHTML("X");
341 term.appendChild(test);
343 fontW = test.getClientWidth();
344 fontH = test.getClientHeight();
345 if (fontW <= 0 || fontW > 100) {
346 fontW = test.getOffsetWidth();
348 if (fontH <= 0|| fontH > 100) {
349 fontH = test.getOffsetHeight();
351 if (fontW <= 0 || fontW > 100) {
354 if (fontH <= 0|| fontH > 100) {
357 term.removeChild(test);
360 // Debug instrumentation. TODO: Remove.
361 // protected void _log(final String string) {
362 // ApplicationConnection.getConsole().log(string);
365 public TextConsoleConfig getConfig() {
369 private boolean bufferEndsWithNewLine() {
370 final Node last = buffer != null ? buffer.getLastChild() : null;
371 // _log("last node: " + (last != null ? last.getNodeName() : "<null>"));
372 return last != null && "br".equals(last.getNodeName().toLowerCase());
375 private Node createTextNode(final String text) {
376 return Document.get().createTextNode(text);
379 private Node createBr() {
380 return Document.get().createBRElement();
383 public void focusPrompt() {
387 public void focusPrompt(final int cursorPos) {
391 final String s = getInput();
392 if (s != null && s.length() > 0) {
393 setSelectionRange(input, s.length(), s.length());
397 private native void setSelectionRange(Element input, int selectionStart,
398 int selectionEnd)/*-{
399 if (input.setSelectionRange) {
401 input.setSelectionRange(selectionStart, selectionEnd);
403 else if (input.createTextRange) {
404 var range = input.createTextRange();
405 range.collapse(true);
406 range.moveEnd('character', selectionEnd);
407 range.moveStart('character', selectionStart);
412 private native int getScrollbarWidth()/*-{
414 var i = $doc.createElement('p');
415 i.style.width = '100%';
416 i.style.height = '200px';
417 var o = $doc.createElement('div');
418 o.style.position = 'absolute';
420 o.style.left = '0px';
421 o.style.visibility = 'hidden';
422 o.style.width = '200px';
423 o.style.height = '150px';
424 o.style.overflow = 'hidden';
426 $doc.body.appendChild(o);
427 var w1 = i.offsetWidth;
428 var h1 = i.offsetHeight;
429 o.style.overflow = 'scroll';
430 var w2 = i.offsetWidth;
431 var h2 = i.offsetHeight;
432 if (w1 == w2) w2 = o.clientWidth;
433 if (h1 == h2) h2 = o.clientWidth;
434 $doc.body.removeChild(o);
438 public void newLine() {
440 buffer.appendChild(createBr());
445 protected void setPs(final String string) {
446 cleanPs = Util.escapeHTML(string);
447 cleanPs = cleanPs.replaceAll(" ", " ");
450 public void prompt(final String inputText) {
451 setPromtActive(true);
453 ps.setInnerHTML(cleanPs);
457 public void focusInput(){
458 setPromtActive(true);
460 ps.setInnerHTML(cleanPs);
463 public void scrollToEnd() {
464 term.setScrollTop(BIG_NUMBER);
467 public void prompt() {
471 public void print(String string) {
472 if (isPromptActive()) {
473 setPromtActive(false);
474 if (!bufferIsEmpty() && !bufferEndsWithNewLine()) {
478 string = getCurrentPromptContent() + string;
480 final boolean doWrap = config.isWrap();
481 // _log("print original: '" + string + "' (" + doWrap + ")");
482 String str = string.replaceAll("\t", tabs);
484 // Continue to the last text node if available
485 final Node last = getLastTextNode();
488 // _log("print append to old node: '" + last.getNodeValue() + "'");
489 str = last.getNodeValue() + str;
490 buffer.removeChild(last);
494 // Split by the newlines anyway
495 int s = 0, e = str.indexOf('\n');
497 final String line = str.substring(s, e);
498 linesAdded += appendLine(buffer, line, doWrap ? cols : -1);
499 buffer.appendChild(createBr());
501 e = str.indexOf('\n', s);
504 // Print the remaining string
505 if (s < str.length()) {
506 linesAdded += appendLine(buffer, str.substring(s), doWrap ? cols
510 reducePrompt(linesAdded);
513 private String getCurrentPromptContent() {
514 return prompt.getInnerText() + getInput();
517 private void reducePrompt(final int rows) {
518 int newRows = promptRows - rows;
522 // _log("prompt reduced from " + promptRows + " to " + newRows);
523 setPromptHeight(newRows);
526 private void setPromptHeight(final int rows) {
528 final int max = getRows();
529 promptRows = rows < min ? min : (rows > max ? max : rows);
530 final int newHeight = fontH * rows;
531 // _log("Prompt height=" + newHeight);
532 promptWrap.getStyle().setHeight(newHeight, Unit.PX);
536 * Split long text based on length.
543 private int appendLine(final Node parent, String str, final int maxLine) {
545 final boolean doWrap = maxLine > 0;
547 parent.appendChild(createTextNode(str));
548 // _log("append: '" + str + "'");
551 while (str.length() > maxLine) {
552 final String piece = str.substring(0, maxLine);
553 parent.appendChild(createTextNode(piece));
554 parent.appendChild(createBr());
556 // _log("append: '" + piece + "'");
557 str = str.substring(maxLine);
559 parent.appendChild(createTextNode(str));
560 // _log("append rest: '" + str + "'");
564 // make sore we don't exceed the maximum buffer size
570 private void checkBufferLimit() {
572 // Buffer means only offscreen lines
573 final int maxb = maxBufferSize + (rows - promptRows);
574 while (getBufferSize() > maxb && buffer.hasChildNodes()) {
575 buffer.removeChild(buffer.getFirstChild());
580 private Node getLastTextNode() {
581 if (buffer == null) {
584 final Node l = buffer.getLastChild();
585 if (l != null && l.getNodeType() == Node.TEXT_NODE) {
591 public void println(final String string) {
592 print(string + "\n");
596 public void setHeight(final String height) {
597 final int oldh = term.getClientHeight();
598 super.setHeight(height);
599 final int newh = term.getClientHeight();
600 // _log("set height=" + height + " clientHeight="+oldh+" to "+newh);
602 calculateRowsFromHeight();
606 protected void calculateRowsFromHeight() {
607 final int h = term.getClientHeight() - (2 * padding);
609 config.setRows(rows);
611 // _log("calculateRowsFromHeight: font=" + fontW + "x" + fontH
612 // + ";scrollbar=" + scrollbarW + ";cols=" + cols + ";rows="
613 // + rows + ";size=" + getWidth() + "x" + getHeight());
617 protected void calculateHeightFromRows() {
618 super.setHeight((rows * fontH) + "px");
620 // _log("calculateHeightFromRows: font=" + fontW + "x" + fontH
621 // + ";scrollbar=" + scrollbarW + ";cols=" + cols + ";rows="
622 // + rows + ";size=" + getWidth() + "x" + getHeight());
626 protected void calculateColsFromWidth() {
627 final int w = term.getClientWidth();
628 cols = (w - 2 * paddingW) / fontW;
629 config.setCols(cols);
630 buffer.getStyle().setWidth((cols * fontW), Unit.PX);
631 prompt.getStyle().setWidth((cols * fontW), Unit.PX);
632 // _log("calculateColsFromWidth: font=" + fontW + "x" + fontH
633 // + ";scrollbar=" + scrollbarW + ";cols=" + cols + ";rows="
634 // + rows + ";size=" + getWidth() + "x" + getHeight());
638 protected void calculateWidthFromCols() {
639 final int w = cols * fontW;
640 super.setWidth((w + scrollbarW) + "px");
641 buffer.getStyle().setWidth(w, Unit.PX);
642 prompt.getStyle().setWidth(w, Unit.PX);
644 // _log("calculateWidthFromCols: font=" + fontW + "x" + fontH
645 // + ";scrollbar=" + scrollbarW + ";cols=" + cols + ";rows="
646 // + rows + ";size=" + getWidth() + "x" + getHeight());
650 public void setWidth(final String width) {
651 final int oldw = term.getClientWidth();
652 super.setWidth(width);
653 final int neww = term.getClientWidth();
654 // _log("set width=" + width + " clientWidth="+oldw+" to "+neww);
656 calculateColsFromWidth();
661 public void setFocus(final boolean focused) {
662 this.focused = focused;
663 super.setFocus(focused);
669 public void setHandler(final TextConsoleHandler handler) {
670 this.handler = handler;
674 public void setRows(final int rows) {
677 calculateHeightFromRows();
679 calculateRowsFromHeight();
683 public int getRows() {
687 public void setCols(final int cols) {
690 calculateWidthFromCols();
692 calculateColsFromWidth();
696 public int getCols() {
700 public void reset() {
701 setPromtActive(false);
703 setPromptHeight(getRows());
704 print(config.getGreeting());
708 public int getBufferSize() {
709 return (buffer.getClientHeight() / fontH);
712 public int getMaxBufferSize() {
713 return maxBufferSize;
716 public void setMaxBufferSize(final int maxBuffer) {
717 maxBufferSize = maxBuffer > 0 ? maxBuffer : 0;
721 public void clearBuffer() {
722 // Remove all children.
723 while (buffer.hasChildNodes()) {
724 buffer.removeChild(buffer.getFirstChild());
728 public void formFeed() {
729 for (int i = 0; i < promptRows; i++) {
732 setPromptHeight(getRows());
738 protected void clearCommandHistory() {
739 cmdHistory = new ArrayList<String>();
740 cmdHistoryIndex = -1;
743 public String getHeight() {
744 return (term.getClientHeight() - 2 * padding) + "px";
747 public String getWidth() {
748 return (term.getClientWidth() + scrollbarW - 2 * paddingW) + "px";
751 protected void bell() {
756 term.removeClassName("term-rev");
757 input.removeClassName("term-rev");
759 // Add styles and start the timer
760 input.addClassName("term-rev");
761 term.addClassName("term-rev");
762 timer = new Timer() {
766 term.removeClassName("term-rev");
767 input.removeClassName("term-rev");
774 protected void onUnload() {
777 if (clickHandler != null) {
778 clickHandler.removeHandler();
780 if (focusHandler != null) {
781 focusHandler.removeHandler();
783 if (keyHandler != null) {
784 keyHandler.removeHandler();