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 17KB

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