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.

ComboBoxConnector.java 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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.combobox;
  17. import java.util.ArrayList;
  18. import java.util.Iterator;
  19. import java.util.List;
  20. import com.vaadin.client.ApplicationConnection;
  21. import com.vaadin.client.Paintable;
  22. import com.vaadin.client.Profiler;
  23. import com.vaadin.client.UIDL;
  24. import com.vaadin.client.communication.RpcProxy;
  25. import com.vaadin.client.communication.StateChangeEvent;
  26. import com.vaadin.client.ui.AbstractFieldConnector;
  27. import com.vaadin.client.ui.SimpleManagedLayout;
  28. import com.vaadin.client.ui.VFilterSelect;
  29. import com.vaadin.client.ui.VFilterSelect.FilterSelectSuggestion;
  30. import com.vaadin.shared.EventId;
  31. import com.vaadin.shared.communication.FieldRpc.FocusAndBlurServerRpc;
  32. import com.vaadin.shared.ui.Connect;
  33. import com.vaadin.shared.ui.combobox.ComboBoxServerRpc;
  34. import com.vaadin.shared.ui.combobox.ComboBoxState;
  35. import com.vaadin.ui.ComboBox;
  36. @Connect(ComboBox.class)
  37. public class ComboBoxConnector extends AbstractFieldConnector implements
  38. Paintable, SimpleManagedLayout {
  39. protected ComboBoxServerRpc rpc = RpcProxy.create(ComboBoxServerRpc.class,
  40. this);
  41. protected FocusAndBlurServerRpc focusAndBlurRpc = RpcProxy.create(
  42. FocusAndBlurServerRpc.class, this);
  43. // oldSuggestionTextMatchTheOldSelection is used to detect when it's safe to
  44. // update textbox text by a changed item caption.
  45. private boolean oldSuggestionTextMatchTheOldSelection;
  46. private boolean immediate;
  47. @Override
  48. protected void init() {
  49. super.init();
  50. getWidget().connector = this;
  51. }
  52. @Override
  53. public void onStateChanged(StateChangeEvent stateChangeEvent) {
  54. super.onStateChanged(stateChangeEvent);
  55. Profiler.enter("ComboBoxConnector.onStateChanged update content");
  56. getWidget().readonly = isReadOnly();
  57. getWidget().updateReadOnly();
  58. immediate = getState().immediate;
  59. getWidget().setTextInputEnabled(getState().textInputAllowed);
  60. if (getState().inputPrompt != null) {
  61. getWidget().inputPrompt = getState().inputPrompt;
  62. } else {
  63. getWidget().inputPrompt = "";
  64. }
  65. getWidget().pageLength = getState().pageLength;
  66. getWidget().filteringmode = getState().filteringMode;
  67. Profiler.leave("ComboBoxConnector.onStateChanged update content");
  68. }
  69. /*
  70. * (non-Javadoc)
  71. *
  72. * @see com.vaadin.client.Paintable#updateFromUIDL(com.vaadin.client.UIDL,
  73. * com.vaadin.client.ApplicationConnection)
  74. */
  75. @Override
  76. public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
  77. if (!isRealUpdate(uidl)) {
  78. return;
  79. }
  80. // not a FocusWidget -> needs own tabindex handling
  81. getWidget().tb.setTabIndex(getState().tabIndex);
  82. getWidget().nullSelectionAllowed = uidl.hasAttribute("nullselect");
  83. getWidget().nullSelectItem = uidl.hasAttribute("nullselectitem")
  84. && uidl.getBooleanAttribute("nullselectitem");
  85. getWidget().currentPage = uidl.getIntVariable("page");
  86. if (uidl.hasAttribute("suggestionPopupWidth")) {
  87. getWidget().suggestionPopupWidth = uidl
  88. .getStringAttribute("suggestionPopupWidth");
  89. } else {
  90. getWidget().suggestionPopupWidth = null;
  91. }
  92. getWidget().suggestionPopup.updateStyleNames(getState());
  93. getWidget().allowNewItem = uidl.hasAttribute("allownewitem");
  94. getWidget().lastNewItemString = null;
  95. final UIDL options = uidl.getChildUIDL(0);
  96. if (uidl.hasAttribute("totalMatches")) {
  97. getWidget().totalMatches = uidl.getIntAttribute("totalMatches");
  98. } else {
  99. getWidget().totalMatches = 0;
  100. }
  101. List<FilterSelectSuggestion> newSuggestions = new ArrayList<FilterSelectSuggestion>();
  102. for (final Iterator<?> i = options.getChildIterator(); i.hasNext();) {
  103. final UIDL optionUidl = (UIDL) i.next();
  104. String key = optionUidl.getStringAttribute("key");
  105. String caption = optionUidl.getStringAttribute("caption");
  106. String style = optionUidl.getStringAttribute("style");
  107. String untranslatedIconUri = null;
  108. if (optionUidl.hasAttribute("icon")) {
  109. untranslatedIconUri = optionUidl.getStringAttribute("icon");
  110. }
  111. final FilterSelectSuggestion suggestion = getWidget().new FilterSelectSuggestion(
  112. key, caption, style, untranslatedIconUri);
  113. newSuggestions.add(suggestion);
  114. }
  115. // only close the popup if the suggestions list has actually changed
  116. boolean suggestionsChanged = !getWidget().initDone
  117. || !newSuggestions.equals(getWidget().currentSuggestions);
  118. // An ItemSetChangeEvent on server side clears the current suggestion
  119. // popup. Popup needs to be repopulated with suggestions from UIDL.
  120. boolean popupOpenAndCleared = false;
  121. oldSuggestionTextMatchTheOldSelection = false;
  122. if (suggestionsChanged) {
  123. oldSuggestionTextMatchTheOldSelection = isWidgetsCurrentSelectionTextInTextBox();
  124. getWidget().currentSuggestions.clear();
  125. if (!getWidget().isWaitingForFilteringResponse()) {
  126. /*
  127. * Clear the current suggestions as the server response always
  128. * includes the new ones. Exception is when filtering, then we
  129. * need to retain the value if the user does not select any of
  130. * the options matching the filter.
  131. */
  132. getWidget().currentSuggestion = null;
  133. /*
  134. * Also ensure no old items in menu. Unless cleared the old
  135. * values may cause odd effects on blur events. Suggestions in
  136. * menu might not necessary exist in select at all anymore.
  137. */
  138. getWidget().suggestionPopup.menu.clearItems();
  139. popupOpenAndCleared = getWidget().suggestionPopup.isAttached();
  140. }
  141. for (FilterSelectSuggestion suggestion : newSuggestions) {
  142. getWidget().currentSuggestions.add(suggestion);
  143. }
  144. }
  145. // handle selection (null or a single value)
  146. if (uidl.hasVariable("selected")
  147. // In case we're switching page no need to update the selection as the
  148. // selection process didn't finish.
  149. // && getWidget().selectPopupItemWhenResponseIsReceived ==
  150. // VFilterSelect.Select.NONE
  151. //
  152. ) {
  153. String[] selectedKeys = uidl.getStringArrayVariable("selected");
  154. // when filtering with empty filter, server sets the selected key
  155. // to "", which we don't select here. Otherwise we won't be able to
  156. // reset back to the item that was selected before filtering
  157. // started.
  158. if (selectedKeys.length > 0 && !selectedKeys[0].equals("")) {
  159. performSelection(selectedKeys[0]);
  160. } else if (!getWidget().isWaitingForFilteringResponse()
  161. && uidl.hasAttribute("selectedCaption")) {
  162. // scrolling to correct page is disabled, caption is passed as a
  163. // special parameter
  164. getWidget().tb.setText(uidl
  165. .getStringAttribute("selectedCaption"));
  166. } else {
  167. resetSelection();
  168. }
  169. }
  170. // TODO even this condition should probably be moved to the handler
  171. if ((getWidget().isWaitingForFilteringResponse() && getWidget().lastFilter
  172. .toLowerCase().equals(uidl.getStringVariable("filter")))
  173. || popupOpenAndCleared) {
  174. getWidget().getDataReceivedHandler().dataReceived();
  175. }
  176. // Calculate minimum textarea width
  177. getWidget().updateSuggestionPopupMinWidth();
  178. /*
  179. * if this is our first time we need to recalculate the root width.
  180. */
  181. if (!getWidget().initDone) {
  182. getWidget().updateRootWidth();
  183. }
  184. // Focus dependent style names are lost during the update, so we add
  185. // them here back again
  186. if (getWidget().focused) {
  187. getWidget().addStyleDependentName("focus");
  188. }
  189. getWidget().initDone = true;
  190. // TODO this should perhaps be moved to be a part of dataReceived()
  191. getWidget().getDataReceivedHandler().serverReplyHandled();
  192. }
  193. private void performSelection(String selectedKey) {
  194. // some item selected
  195. for (FilterSelectSuggestion suggestion : getWidget().currentSuggestions) {
  196. String suggestionKey = suggestion.getOptionKey();
  197. if (!suggestionKey.equals(selectedKey)) {
  198. continue;
  199. }
  200. if (!getWidget().isWaitingForFilteringResponse()
  201. || getWidget().getDataReceivedHandler()
  202. .isPopupOpenerClicked()) {
  203. if (!suggestionKey.equals(getWidget().selectedOptionKey)
  204. || suggestion.getReplacementString().equals(
  205. getWidget().tb.getText())
  206. || oldSuggestionTextMatchTheOldSelection) {
  207. // Update text field if we've got a new
  208. // selection
  209. // Also update if we've got the same text to
  210. // retain old text selection behavior
  211. // OR if selected item caption is changed.
  212. getWidget().setPromptingOff(
  213. suggestion.getReplacementString());
  214. getWidget().selectedOptionKey = suggestionKey;
  215. }
  216. }
  217. getWidget().currentSuggestion = suggestion;
  218. getWidget().setSelectedItemIcon(suggestion.getIconUri());
  219. // only a single item can be selected
  220. break;
  221. }
  222. }
  223. private boolean isWidgetsCurrentSelectionTextInTextBox() {
  224. return getWidget().currentSuggestion != null
  225. && getWidget().currentSuggestion.getReplacementString().equals(
  226. getWidget().tb.getText());
  227. }
  228. private void resetSelection() {
  229. if (!getWidget().isWaitingForFilteringResponse()
  230. || getWidget().getDataReceivedHandler().isPopupOpenerClicked()) {
  231. // select nulled
  232. if (!getWidget().focused) {
  233. /*
  234. * client.updateComponent overwrites all styles so we must
  235. * ALWAYS set the prompting style at this point, even though we
  236. * think it has been set already...
  237. */
  238. getWidget().setPromptingOff("");
  239. if (getWidget().enabled && !getWidget().readonly) {
  240. getWidget().setPromptingOn();
  241. }
  242. } else {
  243. // we have focus in field, prompting can't be set on, instead
  244. // just clear the input if the value has changed from something
  245. // else to null
  246. if (getWidget().selectedOptionKey != null
  247. || (getWidget().allowNewItem && !getWidget().tb
  248. .getValue().isEmpty())) {
  249. getWidget().tb.setValue("");
  250. }
  251. }
  252. getWidget().currentSuggestion = null; // #13217
  253. getWidget().setSelectedItemIcon(null);
  254. getWidget().selectedOptionKey = null;
  255. }
  256. }
  257. @Override
  258. public VFilterSelect getWidget() {
  259. return (VFilterSelect) super.getWidget();
  260. }
  261. @Override
  262. public ComboBoxState getState() {
  263. return (ComboBoxState) super.getState();
  264. }
  265. @Override
  266. public void layout() {
  267. VFilterSelect widget = getWidget();
  268. if (widget.initDone) {
  269. widget.updateRootWidth();
  270. }
  271. }
  272. @Override
  273. public void setWidgetEnabled(boolean widgetEnabled) {
  274. super.setWidgetEnabled(widgetEnabled);
  275. getWidget().enabled = widgetEnabled;
  276. getWidget().tb.setEnabled(widgetEnabled);
  277. }
  278. /*
  279. * These methods exist to move communications out of VFilterSelect, and may
  280. * be refactored/removed in the future
  281. */
  282. /**
  283. * Send a message about a newly created item to the server.
  284. *
  285. * This method is for internal use only and may be removed in future
  286. * versions.
  287. *
  288. * @since
  289. * @param itemValue
  290. * user entered string value for the new item
  291. */
  292. public void sendNewItem(String itemValue) {
  293. rpc.createNewItem(itemValue);
  294. afterSendRequestToServer();
  295. }
  296. /**
  297. * Send a message to the server to request the first page of items without
  298. * filtering or selection.
  299. *
  300. * This method is for internal use only and may be removed in future
  301. * versions.
  302. *
  303. * @since
  304. */
  305. public void requestFirstPage() {
  306. sendSelection(null);
  307. requestPage("", 0);
  308. }
  309. /**
  310. * Send a message to the server to request a page of items with a given
  311. * filter.
  312. *
  313. * This method is for internal use only and may be removed in future
  314. * versions.
  315. *
  316. * @since
  317. * @param filter
  318. * the current filter string
  319. * @param page
  320. * the page number to get
  321. */
  322. public void requestPage(String filter, int page) {
  323. rpc.requestPage(filter, page);
  324. afterSendRequestToServer();
  325. }
  326. /**
  327. * Send a message to the server updating the current selection.
  328. *
  329. * This method is for internal use only and may be removed in future
  330. * versions.
  331. *
  332. * @since
  333. * @param selection
  334. * the current selection
  335. */
  336. public void sendSelection(String selection) {
  337. rpc.setSelectedItem(selection);
  338. afterSendRequestToServer();
  339. }
  340. /**
  341. * Notify the server that the combo box received focus.
  342. *
  343. * For timing reasons, ConnectorFocusAndBlurHandler is not used at the
  344. * moment.
  345. *
  346. * This method is for internal use only and may be removed in future
  347. * versions.
  348. *
  349. * @since
  350. */
  351. public void sendFocusEvent() {
  352. boolean registeredListeners = hasEventListener(EventId.FOCUS);
  353. if (registeredListeners) {
  354. focusAndBlurRpc.focus();
  355. afterSendRequestToServer();
  356. }
  357. }
  358. /**
  359. * Notify the server that the combo box lost focus.
  360. *
  361. * For timing reasons, ConnectorFocusAndBlurHandler is not used at the
  362. * moment.
  363. *
  364. * This method is for internal use only and may be removed in future
  365. * versions.
  366. *
  367. * @since
  368. */
  369. public void sendBlurEvent() {
  370. boolean registeredListeners = hasEventListener(EventId.BLUR);
  371. if (registeredListeners) {
  372. focusAndBlurRpc.blur();
  373. afterSendRequestToServer();
  374. }
  375. }
  376. /*
  377. * Anything that should be set after the client updates the server.
  378. */
  379. private void afterSendRequestToServer() {
  380. // We need this here to be consistent with the all the calls.
  381. // Then set your specific selection type only after
  382. // a server request method call.
  383. getWidget().getDataReceivedHandler().anyRequestSentToServer();
  384. }
  385. }