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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  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. private Runnable pageChangeCallback;
  50. /**
  51. * Set true when popupopened has been clicked. Cleared on each UIDL-update.
  52. * This handles the special case where are not filtering yet and the
  53. * selected value has changed on the server-side. See #2119
  54. * <p>
  55. * For internal use only. May be removed or replaced in the future.
  56. */
  57. private boolean popupOpenerClicked;
  58. @Override
  59. protected void init() {
  60. super.init();
  61. getWidget().connector = this;
  62. }
  63. @Override
  64. public void onStateChanged(StateChangeEvent stateChangeEvent) {
  65. super.onStateChanged(stateChangeEvent);
  66. Profiler.enter("ComboBoxConnector.onStateChanged update content");
  67. getWidget().readonly = isReadOnly();
  68. getWidget().updateReadOnly();
  69. immediate = getState().immediate;
  70. getWidget().setTextInputEnabled(getState().textInputAllowed);
  71. if (getState().inputPrompt != null) {
  72. getWidget().inputPrompt = getState().inputPrompt;
  73. } else {
  74. getWidget().inputPrompt = "";
  75. }
  76. getWidget().pageLength = getState().pageLength;
  77. getWidget().filteringmode = getState().filteringMode;
  78. Profiler.leave("ComboBoxConnector.onStateChanged update content");
  79. }
  80. /*
  81. * (non-Javadoc)
  82. *
  83. * @see com.vaadin.client.Paintable#updateFromUIDL(com.vaadin.client.UIDL,
  84. * com.vaadin.client.ApplicationConnection)
  85. */
  86. @Override
  87. public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
  88. if (!isRealUpdate(uidl)) {
  89. return;
  90. }
  91. // not a FocusWidget -> needs own tabindex handling
  92. getWidget().tb.setTabIndex(getState().tabIndex);
  93. getWidget().nullSelectionAllowed = uidl.hasAttribute("nullselect");
  94. getWidget().nullSelectItem = uidl.hasAttribute("nullselectitem")
  95. && uidl.getBooleanAttribute("nullselectitem");
  96. getWidget().currentPage = uidl.getIntVariable("page");
  97. if (uidl.hasAttribute("suggestionPopupWidth")) {
  98. getWidget().suggestionPopupWidth = uidl
  99. .getStringAttribute("suggestionPopupWidth");
  100. } else {
  101. getWidget().suggestionPopupWidth = null;
  102. }
  103. getWidget().suggestionPopup.updateStyleNames(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. String key = optionUidl.getStringAttribute("key");
  116. String caption = optionUidl.getStringAttribute("caption");
  117. String style = optionUidl.getStringAttribute("style");
  118. String untranslatedIconUri = null;
  119. if (optionUidl.hasAttribute("icon")) {
  120. untranslatedIconUri = optionUidl.getStringAttribute("icon");
  121. }
  122. final FilterSelectSuggestion suggestion = getWidget().new FilterSelectSuggestion(
  123. key, caption, style, untranslatedIconUri);
  124. newSuggestions.add(suggestion);
  125. }
  126. // only close the popup if the suggestions list has actually changed
  127. boolean suggestionsChanged = !getWidget().initDone
  128. || !newSuggestions.equals(getWidget().currentSuggestions);
  129. // An ItemSetChangeEvent on server side clears the current suggestion
  130. // popup. Popup needs to be repopulated with suggestions from UIDL.
  131. boolean popupOpenAndCleared = false;
  132. oldSuggestionTextMatchTheOldSelection = false;
  133. if (suggestionsChanged) {
  134. oldSuggestionTextMatchTheOldSelection = isWidgetsCurrentSelectionTextInTextBox();
  135. getWidget().currentSuggestions.clear();
  136. if (!getWidget().isWaitingForFilteringResponse()) {
  137. /*
  138. * Clear the current suggestions as the server response always
  139. * includes the new ones. Exception is when filtering, then we
  140. * need to retain the value if the user does not select any of
  141. * the options matching the filter.
  142. */
  143. getWidget().currentSuggestion = null;
  144. /*
  145. * Also ensure no old items in menu. Unless cleared the old
  146. * values may cause odd effects on blur events. Suggestions in
  147. * menu might not necessary exist in select at all anymore.
  148. */
  149. getWidget().suggestionPopup.menu.clearItems();
  150. popupOpenAndCleared = getWidget().suggestionPopup.isAttached();
  151. }
  152. for (FilterSelectSuggestion suggestion : newSuggestions) {
  153. getWidget().currentSuggestions.add(suggestion);
  154. }
  155. }
  156. // handle selection (null or a single value)
  157. if (uidl.hasVariable("selected")
  158. // In case we're switching page no need to update the selection as the
  159. // selection process didn't finish.
  160. // && getWidget().selectPopupItemWhenResponseIsReceived ==
  161. // VFilterSelect.Select.NONE
  162. //
  163. ) {
  164. String[] selectedKeys = uidl.getStringArrayVariable("selected");
  165. // when filtering with empty filter, server sets the selected key
  166. // to "", which we don't select here. Otherwise we won't be able to
  167. // reset back to the item that was selected before filtering
  168. // started.
  169. if (selectedKeys.length > 0 && !selectedKeys[0].equals("")) {
  170. performSelection(selectedKeys[0]);
  171. } else if (!getWidget().isWaitingForFilteringResponse()
  172. && uidl.hasAttribute("selectedCaption")) {
  173. // scrolling to correct page is disabled, caption is passed as a
  174. // special parameter
  175. getWidget().tb.setText(uidl
  176. .getStringAttribute("selectedCaption"));
  177. } else {
  178. resetSelection();
  179. }
  180. }
  181. if ((getWidget().isWaitingForFilteringResponse() && getWidget().lastFilter
  182. .toLowerCase().equals(uidl.getStringVariable("filter")))
  183. || popupOpenAndCleared) {
  184. getWidget().suggestionPopup.showSuggestions(
  185. getWidget().currentSuggestions, getWidget().currentPage,
  186. getWidget().totalMatches);
  187. getWidget().setWaitingForFilteringResponse(false);
  188. if (!popupOpenerClicked) {
  189. navigateItemAfterPageChange();
  190. }
  191. if (getWidget().isUpdateSelectionWhenReponseIsReceived()) {
  192. getWidget().suggestionPopup.menu
  193. .doPostFilterSelectedItemAction();
  194. }
  195. }
  196. // Calculate minimum textarea width
  197. getWidget().updateSuggestionPopupMinWidth();
  198. 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 (pageChangeCallback != null) {
  222. // pageChangeCallback is not reset here but after any server request
  223. // in case you are in between two requests both changing the page
  224. // back and forth
  225. // we're paging w/ arrows
  226. Scheduler.get().scheduleDeferred(new ScheduledCommand() {
  227. @Override
  228. public void execute() {
  229. if (pageChangeCallback != null) {
  230. pageChangeCallback.run();
  231. }
  232. }
  233. });
  234. }
  235. }
  236. private void performSelection(String selectedKey) {
  237. // some item selected
  238. for (FilterSelectSuggestion suggestion : getWidget().currentSuggestions) {
  239. String suggestionKey = suggestion.getOptionKey();
  240. if (!suggestionKey.equals(selectedKey)) {
  241. continue;
  242. }
  243. if (!getWidget().isWaitingForFilteringResponse()
  244. || popupOpenerClicked) {
  245. if (!suggestionKey.equals(getWidget().selectedOptionKey)
  246. || suggestion.getReplacementString().equals(
  247. getWidget().tb.getText())
  248. || oldSuggestionTextMatchTheOldSelection) {
  249. // Update text field if we've got a new
  250. // selection
  251. // Also update if we've got the same text to
  252. // retain old text selection behavior
  253. // OR if selected item caption is changed.
  254. getWidget().setPromptingOff(
  255. suggestion.getReplacementString());
  256. getWidget().selectedOptionKey = suggestionKey;
  257. }
  258. }
  259. getWidget().currentSuggestion = suggestion;
  260. getWidget().setSelectedItemIcon(suggestion.getIconUri());
  261. // only a single item can be selected
  262. break;
  263. }
  264. }
  265. private boolean isWidgetsCurrentSelectionTextInTextBox() {
  266. return getWidget().currentSuggestion != null
  267. && getWidget().currentSuggestion.getReplacementString().equals(
  268. getWidget().tb.getText());
  269. }
  270. private void resetSelection() {
  271. if (!getWidget().isWaitingForFilteringResponse() || popupOpenerClicked) {
  272. // select nulled
  273. if (!getWidget().focused) {
  274. /*
  275. * client.updateComponent overwrites all styles so we must
  276. * ALWAYS set the prompting style at this point, even though we
  277. * think it has been set already...
  278. */
  279. getWidget().setPromptingOff("");
  280. if (getWidget().enabled && !getWidget().readonly) {
  281. getWidget().setPromptingOn();
  282. }
  283. } else {
  284. // we have focus in field, prompting can't be set on, instead
  285. // just clear the input if the value has changed from something
  286. // else to null
  287. if (getWidget().selectedOptionKey != null
  288. || (getWidget().allowNewItem && !getWidget().tb
  289. .getValue().isEmpty())) {
  290. getWidget().tb.setValue("");
  291. }
  292. }
  293. getWidget().currentSuggestion = null; // #13217
  294. getWidget().setSelectedItemIcon(null);
  295. getWidget().selectedOptionKey = null;
  296. }
  297. }
  298. @Override
  299. public VFilterSelect getWidget() {
  300. return (VFilterSelect) super.getWidget();
  301. }
  302. @Override
  303. public ComboBoxState getState() {
  304. return (ComboBoxState) super.getState();
  305. }
  306. @Override
  307. public void layout() {
  308. VFilterSelect widget = getWidget();
  309. if (widget.initDone) {
  310. widget.updateRootWidth();
  311. }
  312. }
  313. @Override
  314. public void setWidgetEnabled(boolean widgetEnabled) {
  315. super.setWidgetEnabled(widgetEnabled);
  316. getWidget().enabled = widgetEnabled;
  317. getWidget().tb.setEnabled(widgetEnabled);
  318. }
  319. /*
  320. * These methods exist to move communications out of VFilterSelect, and may
  321. * be refactored/removed in the future
  322. */
  323. /**
  324. * Send a message about a newly created item to the server.
  325. *
  326. * This method is for internal use only and may be removed in future
  327. * versions.
  328. *
  329. * @since
  330. * @param itemValue
  331. * user entered string value for the new item
  332. */
  333. public void sendNewItem(String itemValue) {
  334. rpc.createNewItem(itemValue);
  335. afterSendRequestToServer();
  336. }
  337. /**
  338. * Send a message to the server to request the first page of items without
  339. * filtering or selection.
  340. *
  341. * This method is for internal use only and may be removed in future
  342. * versions.
  343. *
  344. * @since
  345. */
  346. public void requestFirstPage() {
  347. sendSelection(null);
  348. requestPage("", 0);
  349. }
  350. /**
  351. * Send a message to the server to request a page of items with a given
  352. * filter.
  353. *
  354. * This method is for internal use only and may be removed in future
  355. * versions.
  356. *
  357. * @since
  358. * @param filter
  359. * the current filter string
  360. * @param page
  361. * the page number to get
  362. */
  363. public void requestPage(String filter, int page) {
  364. rpc.requestPage(filter, page);
  365. afterSendRequestToServer();
  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. rpc.setSelectedItem(selection);
  379. afterSendRequestToServer();
  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. */
  392. public void sendFocusEvent() {
  393. boolean registeredListeners = hasEventListener(EventId.FOCUS);
  394. if (registeredListeners) {
  395. focusAndBlurRpc.focus();
  396. afterSendRequestToServer();
  397. }
  398. }
  399. /**
  400. * Notify the server that the combo box lost focus.
  401. *
  402. * For timing reasons, ConnectorFocusAndBlurHandler is not used at the
  403. * moment.
  404. *
  405. * This method is for internal use only and may be removed in future
  406. * versions.
  407. *
  408. * @since
  409. */
  410. public void sendBlurEvent() {
  411. boolean registeredListeners = hasEventListener(EventId.BLUR);
  412. if (registeredListeners) {
  413. focusAndBlurRpc.blur();
  414. afterSendRequestToServer();
  415. }
  416. }
  417. /**
  418. * Set a callback that is invoked when a page change occurs if there have
  419. * not been intervening requests to the server. The callback is reset when
  420. * any additional request is made to the server.
  421. *
  422. * @since
  423. * @param callback
  424. */
  425. public void setNavigateAfterPageReceivedCallback(Runnable callback) {
  426. pageChangeCallback = callback;
  427. }
  428. /*
  429. * Anything that should be set after the client updates the server.
  430. */
  431. private void afterSendRequestToServer() {
  432. // We need this here to be consistent with the all the calls.
  433. // Then set your specific selection type only after
  434. // a server request method call.
  435. pageChangeCallback = null;
  436. }
  437. /**
  438. * Record that the popup opener has been clicked and the popup should be
  439. * opened on the next request.
  440. *
  441. * This handles the special case where are not filtering yet and the
  442. * selected value has changed on the server-side. See #2119. The flag is
  443. * cleared on each UIDL reply.
  444. *
  445. * @since
  446. */
  447. public void popupOpenerClicked() {
  448. popupOpenerClicked = true;
  449. }
  450. }