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

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