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

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