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

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