You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

VTextField.java 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. /*
  2. * Copyright 2000-2014 Vaadin Ltd.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.vaadin.client.ui;
  17. import com.google.gwt.core.client.Scheduler;
  18. import com.google.gwt.core.client.Scheduler.ScheduledCommand;
  19. import com.google.gwt.dom.client.Element;
  20. import com.google.gwt.event.dom.client.BlurEvent;
  21. import com.google.gwt.event.dom.client.BlurHandler;
  22. import com.google.gwt.event.dom.client.ChangeEvent;
  23. import com.google.gwt.event.dom.client.ChangeHandler;
  24. import com.google.gwt.event.dom.client.FocusEvent;
  25. import com.google.gwt.event.dom.client.FocusHandler;
  26. import com.google.gwt.event.dom.client.KeyCodes;
  27. import com.google.gwt.event.dom.client.KeyDownEvent;
  28. import com.google.gwt.event.dom.client.KeyDownHandler;
  29. import com.google.gwt.user.client.DOM;
  30. import com.google.gwt.user.client.Event;
  31. import com.google.gwt.user.client.Timer;
  32. import com.google.gwt.user.client.ui.TextBoxBase;
  33. import com.vaadin.client.ApplicationConnection;
  34. import com.vaadin.client.BrowserInfo;
  35. import com.vaadin.client.Util;
  36. import com.vaadin.shared.EventId;
  37. import com.vaadin.shared.ui.textfield.TextFieldConstants;
  38. /**
  39. * This class represents a basic text input field with one row.
  40. *
  41. * @author Vaadin Ltd.
  42. *
  43. */
  44. public class VTextField extends TextBoxBase implements Field, ChangeHandler,
  45. FocusHandler, BlurHandler, KeyDownHandler {
  46. /**
  47. * The input node CSS classname.
  48. */
  49. public static final String CLASSNAME = "v-textfield";
  50. /**
  51. * This CSS classname is added to the input node on hover.
  52. */
  53. public static final String CLASSNAME_FOCUS = "focus";
  54. /** For internal use only. May be removed or replaced in the future. */
  55. public String paintableId;
  56. /** For internal use only. May be removed or replaced in the future. */
  57. public ApplicationConnection client;
  58. /** For internal use only. May be removed or replaced in the future. */
  59. public String valueBeforeEdit = null;
  60. /**
  61. * Set to false if a text change event has been sent since the last value
  62. * change event. This means that {@link #valueBeforeEdit} should not be
  63. * trusted when determining whether a text change even should be sent.
  64. */
  65. private boolean valueBeforeEditIsSynced = true;
  66. private boolean immediate = false;
  67. private int maxLength = -1;
  68. private static final String CLASSNAME_PROMPT = "prompt";
  69. private static final String TEXTCHANGE_MODE_TIMEOUT = "TIMEOUT";
  70. private String inputPrompt = null;
  71. private boolean prompting = false;
  72. private int lastCursorPos = -1;
  73. // used while checking if FF has set input prompt as value
  74. private boolean possibleInputError = false;
  75. public VTextField() {
  76. this(DOM.createInputText());
  77. }
  78. protected VTextField(Element node) {
  79. super(node);
  80. setStyleName(CLASSNAME);
  81. addChangeHandler(this);
  82. if (BrowserInfo.get().isIE() || BrowserInfo.get().isFirefox()) {
  83. addKeyDownHandler(this);
  84. }
  85. addFocusHandler(this);
  86. addBlurHandler(this);
  87. }
  88. /**
  89. * For internal use only. May be removed or replaced in the future.
  90. * <p>
  91. * TODO When GWT adds ONCUT, add it there and remove workaround. See
  92. * http://code.google.com/p/google-web-toolkit/issues/detail?id=4030
  93. * <p>
  94. * Also note that the cut/paste are not totally crossbrowsers compatible.
  95. * E.g. in Opera mac works via context menu, but on via File->Paste/Cut.
  96. * Opera might need the polling method for 100% working textchanceevents.
  97. * Eager polling for a change is bit dum and heavy operation, so I guess we
  98. * should first try to survive without.
  99. */
  100. public static final int TEXTCHANGE_EVENTS = Event.ONPASTE | Event.KEYEVENTS
  101. | Event.ONMOUSEUP;
  102. @Override
  103. public void onBrowserEvent(Event event) {
  104. super.onBrowserEvent(event);
  105. if (listenTextChangeEvents
  106. && (event.getTypeInt() & TEXTCHANGE_EVENTS) == event
  107. .getTypeInt()) {
  108. deferTextChangeEvent();
  109. }
  110. }
  111. /*
  112. * TODO optimize this so that only changes are sent + make the value change
  113. * event just a flag that moves the current text to value
  114. */
  115. private String lastTextChangeString = null;
  116. private String getLastCommunicatedString() {
  117. return lastTextChangeString;
  118. }
  119. private void communicateTextValueToServer() {
  120. String text = getText();
  121. if (prompting) {
  122. // Input prompt visible, text is actually ""
  123. text = "";
  124. }
  125. if (!text.equals(getLastCommunicatedString())) {
  126. if (valueBeforeEditIsSynced && text.equals(valueBeforeEdit)) {
  127. /*
  128. * Value change for the current text has been enqueued since the
  129. * last text change event was sent, but we can't know that it
  130. * has been sent to the server. Ensure that all pending changes
  131. * are sent now. Sending a value change without a text change
  132. * will simulate a TextChangeEvent on the server.
  133. */
  134. client.sendPendingVariableChanges();
  135. } else {
  136. // Default case - just send an immediate text change message
  137. client.updateVariable(paintableId,
  138. TextFieldConstants.VAR_CUR_TEXT, text, true);
  139. // Shouldn't investigate valueBeforeEdit to avoid duplicate text
  140. // change events as the states are not in sync any more
  141. valueBeforeEditIsSynced = false;
  142. }
  143. lastTextChangeString = text;
  144. }
  145. }
  146. private Timer textChangeEventTrigger = new Timer() {
  147. @Override
  148. public void run() {
  149. if (isAttached()) {
  150. updateCursorPosition();
  151. communicateTextValueToServer();
  152. scheduled = false;
  153. }
  154. }
  155. };
  156. private boolean scheduled = false;
  157. /** For internal use only. May be removed or replaced in the future. */
  158. public boolean listenTextChangeEvents;
  159. /** For internal use only. May be removed or replaced in the future. */
  160. public String textChangeEventMode;
  161. public int textChangeEventTimeout;
  162. private void deferTextChangeEvent() {
  163. if (textChangeEventMode.equals(TEXTCHANGE_MODE_TIMEOUT) && scheduled) {
  164. return;
  165. } else {
  166. textChangeEventTrigger.cancel();
  167. }
  168. textChangeEventTrigger.schedule(getTextChangeEventTimeout());
  169. scheduled = true;
  170. }
  171. private int getTextChangeEventTimeout() {
  172. return textChangeEventTimeout;
  173. }
  174. @Override
  175. public void setReadOnly(boolean readOnly) {
  176. boolean wasReadOnly = isReadOnly();
  177. if (readOnly) {
  178. setTabIndex(-1);
  179. } else if (wasReadOnly && !readOnly && getTabIndex() == -1) {
  180. /*
  181. * Need to manually set tab index to 0 since server will not send
  182. * the tab index if it is 0.
  183. */
  184. setTabIndex(0);
  185. }
  186. super.setReadOnly(readOnly);
  187. }
  188. /** For internal use only. May be removed or replaced in the future. */
  189. public void updateFieldContent(final String text) {
  190. setPrompting(inputPrompt != null && focusedTextField != this
  191. && (text.equals("")));
  192. String fieldValue;
  193. if (prompting) {
  194. fieldValue = isReadOnly() ? "" : inputPrompt;
  195. addStyleDependentName(CLASSNAME_PROMPT);
  196. } else {
  197. fieldValue = text;
  198. removeStyleDependentName(CLASSNAME_PROMPT);
  199. }
  200. setText(fieldValue);
  201. lastTextChangeString = valueBeforeEdit = text;
  202. valueBeforeEditIsSynced = true;
  203. }
  204. protected void onCut() {
  205. if (listenTextChangeEvents) {
  206. deferTextChangeEvent();
  207. }
  208. }
  209. /** For internal use only. May be removed or replaced in the future. */
  210. public native void attachCutEventListener(Element el)
  211. /*-{
  212. var me = this;
  213. el.oncut = $entry(function() {
  214. me.@com.vaadin.client.ui.VTextField::onCut()();
  215. });
  216. }-*/;
  217. protected native void detachCutEventListener(Element el)
  218. /*-{
  219. el.oncut = null;
  220. }-*/;
  221. private void onDrop() {
  222. if (focusedTextField == this) {
  223. return;
  224. }
  225. updateText(false);
  226. }
  227. private void updateText(boolean blurred) {
  228. String text = getText();
  229. setPrompting(inputPrompt != null && (text == null || text.isEmpty()));
  230. if (prompting) {
  231. setText(isReadOnly() ? "" : inputPrompt);
  232. if (blurred) {
  233. addStyleDependentName(CLASSNAME_PROMPT);
  234. }
  235. }
  236. valueChange(blurred);
  237. }
  238. private void scheduleOnDropEvent() {
  239. Scheduler.get().scheduleDeferred(new ScheduledCommand() {
  240. @Override
  241. public void execute() {
  242. onDrop();
  243. }
  244. });
  245. }
  246. private native void attachDropEventListener(Element el)
  247. /*-{
  248. var me = this;
  249. el.ondrop = $entry(function() {
  250. me.@com.vaadin.client.ui.VTextField::scheduleOnDropEvent()();
  251. });
  252. }-*/;
  253. private native void detachDropEventListener(Element el)
  254. /*-{
  255. el.ondrop = null;
  256. }-*/;
  257. @Override
  258. protected void onDetach() {
  259. super.onDetach();
  260. detachCutEventListener(getElement());
  261. if (focusedTextField == this) {
  262. focusedTextField = null;
  263. }
  264. if (BrowserInfo.get().isFirefox()) {
  265. removeOnInputListener(getElement());
  266. detachDropEventListener(getElement());
  267. }
  268. }
  269. @Override
  270. protected void onAttach() {
  271. super.onAttach();
  272. if (listenTextChangeEvents) {
  273. detachCutEventListener(getElement());
  274. }
  275. if (BrowserInfo.get().isFirefox()) {
  276. // Workaround for FF setting input prompt as the value if esc is
  277. // pressed while the field is focused and empty (#8051).
  278. addOnInputListener(getElement());
  279. // Workaround for FF updating component's internal value after
  280. // having drag-and-dropped text from another element (#14056)
  281. attachDropEventListener(getElement());
  282. }
  283. }
  284. /** For internal use only. May be removed or replaced in the future. */
  285. public void setMaxLength(int newMaxLength) {
  286. if (newMaxLength == maxLength) {
  287. return;
  288. }
  289. maxLength = newMaxLength;
  290. updateMaxLength(maxLength);
  291. }
  292. /**
  293. * This method is responsible for updating the DOM or otherwise ensuring
  294. * that the given max length is enforced. Called when the max length for the
  295. * field has changed.
  296. *
  297. * @param maxLength
  298. * The new max length
  299. */
  300. protected void updateMaxLength(int maxLength) {
  301. if (maxLength >= 0) {
  302. getElement().setPropertyInt("maxLength", maxLength);
  303. } else {
  304. getElement().removeAttribute("maxLength");
  305. }
  306. setMaxLengthToElement(maxLength);
  307. }
  308. protected void setMaxLengthToElement(int newMaxLength) {
  309. if (newMaxLength >= 0) {
  310. getElement().setPropertyInt("maxLength", newMaxLength);
  311. } else {
  312. getElement().removeAttribute("maxLength");
  313. }
  314. }
  315. public int getMaxLength() {
  316. return maxLength;
  317. }
  318. @Override
  319. public void onChange(ChangeEvent event) {
  320. valueChange(false);
  321. }
  322. /**
  323. * Called when the field value might have changed and/or the field was
  324. * blurred. These are combined so the blur event is sent in the same batch
  325. * as a possible value change event (these are often connected).
  326. *
  327. * @param blurred
  328. * true if the field was blurred
  329. */
  330. public void valueChange(boolean blurred) {
  331. if (client != null && paintableId != null) {
  332. boolean sendBlurEvent = false;
  333. boolean sendValueChange = false;
  334. if (blurred && client.hasEventListeners(this, EventId.BLUR)) {
  335. sendBlurEvent = true;
  336. client.updateVariable(paintableId, EventId.BLUR, "", false);
  337. }
  338. String newText = getText();
  339. if (!prompting && newText != null
  340. && !newText.equals(valueBeforeEdit)) {
  341. sendValueChange = immediate;
  342. client.updateVariable(paintableId, "text", newText, false);
  343. valueBeforeEdit = newText;
  344. valueBeforeEditIsSynced = true;
  345. }
  346. /*
  347. * also send cursor position, no public api yet but for easier
  348. * extension
  349. */
  350. updateCursorPosition();
  351. if (sendBlurEvent || sendValueChange) {
  352. /*
  353. * Avoid sending text change event as we will simulate it on the
  354. * server side before value change events.
  355. */
  356. textChangeEventTrigger.cancel();
  357. scheduled = false;
  358. client.sendPendingVariableChanges();
  359. }
  360. }
  361. }
  362. /**
  363. * Updates the cursor position variable if it has changed since the last
  364. * update.
  365. *
  366. * @return true iff the value was updated
  367. */
  368. protected boolean updateCursorPosition() {
  369. if (Util.isAttachedAndDisplayed(this)) {
  370. int cursorPos = getCursorPos();
  371. if (lastCursorPos != cursorPos) {
  372. client.updateVariable(paintableId,
  373. TextFieldConstants.VAR_CURSOR, cursorPos, false);
  374. lastCursorPos = cursorPos;
  375. return true;
  376. }
  377. }
  378. return false;
  379. }
  380. private static VTextField focusedTextField;
  381. public static void flushChangesFromFocusedTextField() {
  382. if (focusedTextField != null) {
  383. focusedTextField.onChange(null);
  384. }
  385. }
  386. @Override
  387. public void onFocus(FocusEvent event) {
  388. addStyleDependentName(CLASSNAME_FOCUS);
  389. if (prompting) {
  390. setText("");
  391. removeStyleDependentName(CLASSNAME_PROMPT);
  392. setPrompting(false);
  393. }
  394. focusedTextField = this;
  395. if (client != null && client.hasEventListeners(this, EventId.FOCUS)) {
  396. client.updateVariable(paintableId, EventId.FOCUS, "", true);
  397. }
  398. }
  399. @Override
  400. public void onBlur(BlurEvent event) {
  401. // this is called twice on Chrome when e.g. changing tab while prompting
  402. // field focused - do not change settings on the second time
  403. if (focusedTextField != this) {
  404. return;
  405. }
  406. removeStyleDependentName(CLASSNAME_FOCUS);
  407. focusedTextField = null;
  408. updateText(true);
  409. }
  410. private void setPrompting(boolean prompting) {
  411. this.prompting = prompting;
  412. }
  413. public void setColumns(int columns) {
  414. if (columns <= 0) {
  415. return;
  416. }
  417. setWidth(columns + "em");
  418. }
  419. @Override
  420. public void onKeyDown(KeyDownEvent event) {
  421. if (BrowserInfo.get().isIE()
  422. && event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
  423. // IE does not send change events when pressing enter in a text
  424. // input so we handle it using a key listener instead
  425. valueChange(false);
  426. } else if (BrowserInfo.get().isFirefox()
  427. && event.getNativeKeyCode() == KeyCodes.KEY_ESCAPE
  428. && getText().equals("")) {
  429. // check after onInput event if inputPrompt has appeared as the
  430. // value of the field
  431. possibleInputError = true;
  432. }
  433. }
  434. public void setImmediate(boolean immediate) {
  435. this.immediate = immediate;
  436. }
  437. public void setInputPrompt(String inputPrompt) {
  438. this.inputPrompt = inputPrompt;
  439. }
  440. protected boolean isWordwrap() {
  441. String wrap = getElement().getAttribute("wrap");
  442. return !"off".equals(wrap);
  443. }
  444. private native void addOnInputListener(Element el)
  445. /*-{
  446. var self = this;
  447. el.oninput = $entry(function() {
  448. self.@com.vaadin.client.ui.VTextField::checkForInputError()();
  449. });
  450. }-*/;
  451. private native void removeOnInputListener(Element el)
  452. /*-{
  453. el.oninput = null;
  454. }-*/;
  455. private void checkForInputError() {
  456. if (possibleInputError && getText().equals(inputPrompt)) {
  457. setText("");
  458. }
  459. possibleInputError = false;
  460. }
  461. }