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