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.

ComboBox.java 32KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951
  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.ui;
  17. import java.io.Serializable;
  18. import java.util.ArrayList;
  19. import java.util.Collection;
  20. import java.util.Iterator;
  21. import java.util.LinkedList;
  22. import java.util.List;
  23. import java.util.Map;
  24. import com.vaadin.data.Container;
  25. import com.vaadin.data.util.filter.SimpleStringFilter;
  26. import com.vaadin.event.FieldEvents;
  27. import com.vaadin.event.FieldEvents.BlurEvent;
  28. import com.vaadin.event.FieldEvents.BlurListener;
  29. import com.vaadin.event.FieldEvents.FocusAndBlurServerRpcImpl;
  30. import com.vaadin.event.FieldEvents.FocusEvent;
  31. import com.vaadin.event.FieldEvents.FocusListener;
  32. import com.vaadin.server.PaintException;
  33. import com.vaadin.server.PaintTarget;
  34. import com.vaadin.server.Resource;
  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. /**
  39. * A filtering dropdown single-select. Suitable for newItemsAllowed, but it's
  40. * turned of by default to avoid mistakes. Items are filtered based on user
  41. * input, and loaded dynamically ("lazy-loading") from the server. You can turn
  42. * on newItemsAllowed and change filtering mode (and also turn it off), but you
  43. * can not turn on multi-select mode.
  44. *
  45. */
  46. @SuppressWarnings("serial")
  47. public class ComboBox extends AbstractSelect implements
  48. AbstractSelect.Filtering, FieldEvents.BlurNotifier,
  49. FieldEvents.FocusNotifier {
  50. /**
  51. * ItemStyleGenerator can be used to add custom styles to combo box items
  52. * shown in the popup. The CSS class name that will be added to the item
  53. * style names is <tt>v-filterselect-item-[style name]</tt>.
  54. *
  55. * @since 7.5.6
  56. * @see ComboBox#setItemStyleGenerator(ItemStyleGenerator)
  57. */
  58. public interface ItemStyleGenerator extends Serializable {
  59. /**
  60. * Called by ComboBox when an item is painted.
  61. *
  62. * @param source
  63. * the source combo box
  64. * @param itemId
  65. * The itemId of the item to be painted. Can be
  66. * <code>null</code> if null selection is allowed.
  67. * @return The style name to add to this item. (the CSS class name will
  68. * be v-filterselect-item-[style name]
  69. */
  70. public String getStyle(ComboBox source, Object itemId);
  71. }
  72. private ComboBoxServerRpc rpc = new ComboBoxServerRpc() {
  73. @Override
  74. public void createNewItem(String itemValue) {
  75. if (isNewItemsAllowed()) {
  76. // New option entered (and it is allowed)
  77. if (itemValue != null && itemValue.length() > 0) {
  78. getNewItemHandler().addNewItem(itemValue);
  79. // rebuild list
  80. filterstring = null;
  81. prevfilterstring = null;
  82. }
  83. }
  84. }
  85. @Override
  86. public void setSelectedItem(String item) {
  87. if (item == null) {
  88. setValue(null, true);
  89. } else {
  90. final Object id = itemIdMapper.get(item);
  91. if (id != null && id.equals(getNullSelectionItemId())) {
  92. setValue(null, true);
  93. } else {
  94. setValue(id, true);
  95. }
  96. }
  97. }
  98. };
  99. FocusAndBlurServerRpcImpl focusBlurRpc = new FocusAndBlurServerRpcImpl(this) {
  100. @Override
  101. protected void fireEvent(LegacyEvent event) {
  102. ComboBox.this.fireEvent(event);
  103. }
  104. };
  105. // Current page when the user is 'paging' trough options
  106. private int currentPage = -1;
  107. private String filterstring;
  108. private String prevfilterstring;
  109. /**
  110. * Number of options that pass the filter, excluding the null item if any.
  111. */
  112. private int filteredSize;
  113. /**
  114. * Cache of filtered options, used only by the in-memory filtering system.
  115. */
  116. private List<Object> filteredOptions;
  117. /**
  118. * Flag to indicate that request repaint is called by filter request only
  119. */
  120. private boolean optionRequest;
  121. /**
  122. * True while painting to suppress item set change notifications that could
  123. * be caused by temporary filtering.
  124. */
  125. private boolean isPainting;
  126. /**
  127. * Flag to indicate whether to scroll the selected item visible (select the
  128. * page on which it is) when opening the popup or not. Only applies to
  129. * single select mode.
  130. *
  131. * This requires finding the index of the item, which can be expensive in
  132. * many large lazy loading containers.
  133. */
  134. private boolean scrollToSelectedItem = true;
  135. private String suggestionPopupWidth = null;
  136. /**
  137. * If text input is not allowed, the ComboBox behaves like a pretty
  138. * NativeSelect - the user can not enter any text and clicking the text
  139. * field opens the drop down with options
  140. */
  141. private boolean textInputAllowed = true;
  142. private ItemStyleGenerator itemStyleGenerator = null;
  143. public ComboBox() {
  144. init();
  145. }
  146. public ComboBox(String caption, Collection<?> options) {
  147. super(caption, options);
  148. init();
  149. }
  150. public ComboBox(String caption, Container dataSource) {
  151. super(caption, dataSource);
  152. init();
  153. }
  154. public ComboBox(String caption) {
  155. super(caption);
  156. init();
  157. }
  158. /**
  159. * Initialize the ComboBox with default settings and register client to
  160. * server RPC implementation.
  161. */
  162. private void init() {
  163. registerRpc(rpc);
  164. registerRpc(focusBlurRpc);
  165. setNewItemsAllowed(false);
  166. setImmediate(true);
  167. }
  168. /**
  169. * Gets the current input prompt.
  170. *
  171. * @see #setInputPrompt(String)
  172. * @return the current input prompt, or null if not enabled
  173. */
  174. public String getInputPrompt() {
  175. return getState(false).inputPrompt;
  176. }
  177. /**
  178. * Sets the input prompt - a textual prompt that is displayed when the
  179. * select would otherwise be empty, to prompt the user for input.
  180. *
  181. * @param inputPrompt
  182. * the desired input prompt, or null to disable
  183. */
  184. public void setInputPrompt(String inputPrompt) {
  185. getState().inputPrompt = inputPrompt;
  186. }
  187. private boolean isFilteringNeeded() {
  188. return filterstring != null && filterstring.length() > 0
  189. && getFilteringMode() != FilteringMode.OFF;
  190. }
  191. @Override
  192. public void paintContent(PaintTarget target) throws PaintException {
  193. isPainting = true;
  194. try {
  195. // clear caption change listeners
  196. getCaptionChangeListener().clear();
  197. // If the field is modified, but not committed, set modified
  198. // attribute
  199. if (isModified()) {
  200. target.addAttribute("modified", true);
  201. }
  202. if (isNewItemsAllowed()) {
  203. target.addAttribute("allownewitem", true);
  204. }
  205. boolean needNullSelectOption = false;
  206. if (isNullSelectionAllowed()) {
  207. target.addAttribute("nullselect", true);
  208. needNullSelectOption = (getNullSelectionItemId() == null);
  209. if (!needNullSelectOption) {
  210. target.addAttribute("nullselectitem", true);
  211. }
  212. }
  213. // Constructs selected keys array
  214. String[] selectedKeys = new String[(getValue() == null
  215. && getNullSelectionItemId() == null ? 0 : 1)];
  216. if (suggestionPopupWidth != null) {
  217. target.addAttribute("suggestionPopupWidth",
  218. suggestionPopupWidth);
  219. }
  220. // Paints the options and create array of selected id keys
  221. int keyIndex = 0;
  222. target.startTag("options");
  223. if (currentPage < 0) {
  224. optionRequest = false;
  225. currentPage = 0;
  226. filterstring = "";
  227. }
  228. boolean nullFilteredOut = isFilteringNeeded();
  229. // null option is needed and not filtered out, even if not on
  230. // current page
  231. boolean nullOptionVisible = needNullSelectOption
  232. && !nullFilteredOut;
  233. // first try if using container filters is possible
  234. List<?> options = getOptionsWithFilter(nullOptionVisible);
  235. if (null == options) {
  236. // not able to use container filters, perform explicit in-memory
  237. // filtering
  238. options = getFilteredOptions();
  239. filteredSize = options.size();
  240. options = sanitetizeList(options, nullOptionVisible);
  241. }
  242. final boolean paintNullSelection = needNullSelectOption
  243. && currentPage == 0 && !nullFilteredOut;
  244. if (paintNullSelection) {
  245. target.startTag("so");
  246. target.addAttribute("caption", "");
  247. target.addAttribute("key", "");
  248. paintItemStyle(target, null);
  249. target.endTag("so");
  250. }
  251. final Iterator<?> i = options.iterator();
  252. // Paints the available selection options from data source
  253. while (i.hasNext()) {
  254. final Object id = i.next();
  255. if (!isNullSelectionAllowed() && id != null
  256. && id.equals(getNullSelectionItemId())
  257. && !isSelected(id)) {
  258. continue;
  259. }
  260. // Gets the option attribute values
  261. final String key = itemIdMapper.key(id);
  262. final String caption = getItemCaption(id);
  263. final Resource icon = getItemIcon(id);
  264. getCaptionChangeListener().addNotifierForItem(id);
  265. // Paints the option
  266. target.startTag("so");
  267. if (icon != null) {
  268. target.addAttribute("icon", icon);
  269. }
  270. target.addAttribute("caption", caption);
  271. if (id != null && id.equals(getNullSelectionItemId())) {
  272. target.addAttribute("nullselection", true);
  273. }
  274. target.addAttribute("key", key);
  275. if (keyIndex < selectedKeys.length && isSelected(id)) {
  276. // at most one item can be selected at a time
  277. selectedKeys[keyIndex++] = key;
  278. }
  279. paintItemStyle(target, id);
  280. target.endTag("so");
  281. }
  282. target.endTag("options");
  283. target.addAttribute("totalitems", size()
  284. + (needNullSelectOption ? 1 : 0));
  285. if (filteredSize > 0 || nullOptionVisible) {
  286. target.addAttribute("totalMatches", filteredSize
  287. + (nullOptionVisible ? 1 : 0));
  288. }
  289. // Paint variables
  290. target.addVariable(this, "selected", selectedKeys);
  291. if (getValue() != null && selectedKeys[0] == null) {
  292. // not always available, e.g. scrollToSelectedIndex=false
  293. // Give the caption for selected item still, not to make it look
  294. // like there is no selection at all
  295. target.addAttribute("selectedCaption",
  296. getItemCaption(getValue()));
  297. }
  298. if (isNewItemsAllowed()) {
  299. target.addVariable(this, "newitem", "");
  300. }
  301. target.addVariable(this, "filter", filterstring);
  302. target.addVariable(this, "page", currentPage);
  303. currentPage = -1; // current page is always set by client
  304. optionRequest = true;
  305. } finally {
  306. isPainting = false;
  307. }
  308. }
  309. private void paintItemStyle(PaintTarget target, Object itemId)
  310. throws PaintException {
  311. if (itemStyleGenerator != null) {
  312. String style = itemStyleGenerator.getStyle(this, itemId);
  313. if (style != null && !style.isEmpty()) {
  314. target.addAttribute("style", style);
  315. }
  316. }
  317. }
  318. /**
  319. * Sets whether it is possible to input text into the field or whether the
  320. * field area of the component is just used to show what is selected. By
  321. * disabling text input, the comboBox will work in the same way as a
  322. * {@link NativeSelect}
  323. *
  324. * @see #isTextInputAllowed()
  325. *
  326. * @param textInputAllowed
  327. * true to allow entering text, false to just show the current
  328. * selection
  329. */
  330. public void setTextInputAllowed(boolean textInputAllowed) {
  331. getState().textInputAllowed = textInputAllowed;
  332. }
  333. /**
  334. * Returns true if the user can enter text into the field to either filter
  335. * the selections or enter a new value if {@link #isNewItemsAllowed()}
  336. * returns true. If text input is disabled, the comboBox will work in the
  337. * same way as a {@link NativeSelect}
  338. *
  339. * @return
  340. */
  341. public boolean isTextInputAllowed() {
  342. return getState(false).textInputAllowed;
  343. }
  344. @Override
  345. protected ComboBoxState getState() {
  346. return (ComboBoxState) super.getState();
  347. }
  348. @Override
  349. protected ComboBoxState getState(boolean markAsDirty) {
  350. return (ComboBoxState) super.getState(markAsDirty);
  351. }
  352. /**
  353. * Returns the filtered options for the current page using a container
  354. * filter.
  355. *
  356. * As a size effect, {@link #filteredSize} is set to the total number of
  357. * items passing the filter.
  358. *
  359. * The current container must be {@link Filterable} and {@link Indexed}, and
  360. * the filtering mode must be suitable for container filtering (tested with
  361. * {@link #canUseContainerFilter()}).
  362. *
  363. * Use {@link #getFilteredOptions()} and
  364. * {@link #sanitetizeList(List, boolean)} if this is not the case.
  365. *
  366. * @param needNullSelectOption
  367. * @return filtered list of options (may be empty) or null if cannot use
  368. * container filters
  369. */
  370. protected List<?> getOptionsWithFilter(boolean needNullSelectOption) {
  371. Container container = getContainerDataSource();
  372. if (getPageLength() == 0 && !isFilteringNeeded()) {
  373. // no paging or filtering: return all items
  374. filteredSize = container.size();
  375. assert filteredSize >= 0;
  376. return new ArrayList<Object>(container.getItemIds());
  377. }
  378. if (!(container instanceof Filterable)
  379. || !(container instanceof Indexed)
  380. || getItemCaptionMode() != ITEM_CAPTION_MODE_PROPERTY) {
  381. return null;
  382. }
  383. Filterable filterable = (Filterable) container;
  384. Filter filter = buildFilter(filterstring, getFilteringMode());
  385. // adding and removing filters leads to extraneous item set
  386. // change events from the underlying container, but the ComboBox does
  387. // not process or propagate them based on the flag filteringContainer
  388. if (filter != null) {
  389. filterable.addContainerFilter(filter);
  390. }
  391. // try-finally to ensure that the filter is removed from container even
  392. // if a exception is thrown...
  393. try {
  394. Indexed indexed = (Indexed) container;
  395. int indexToEnsureInView = -1;
  396. // if not an option request (item list when user changes page), go
  397. // to page with the selected item after filtering if accepted by
  398. // filter
  399. Object selection = getValue();
  400. if (isScrollToSelectedItem() && !optionRequest && selection != null) {
  401. // ensure proper page
  402. indexToEnsureInView = indexed.indexOfId(selection);
  403. }
  404. filteredSize = container.size();
  405. assert filteredSize >= 0;
  406. currentPage = adjustCurrentPage(currentPage, needNullSelectOption,
  407. indexToEnsureInView, filteredSize);
  408. int first = getFirstItemIndexOnCurrentPage(needNullSelectOption,
  409. filteredSize);
  410. int last = getLastItemIndexOnCurrentPage(needNullSelectOption,
  411. filteredSize, first);
  412. // Compute the number of items to fetch from the indexes given or
  413. // based on the filtered size of the container
  414. int lastItemToFetch = Math.min(last, filteredSize - 1);
  415. int nrOfItemsToFetch = (lastItemToFetch + 1) - first;
  416. List<?> options = indexed.getItemIds(first, nrOfItemsToFetch);
  417. return options;
  418. } finally {
  419. // to the outside, filtering should not be visible
  420. if (filter != null) {
  421. filterable.removeContainerFilter(filter);
  422. }
  423. }
  424. }
  425. /**
  426. * Constructs a filter instance to use when using a Filterable container in
  427. * the <code>ITEM_CAPTION_MODE_PROPERTY</code> mode.
  428. *
  429. * Note that the client side implementation expects the filter string to
  430. * apply to the item caption string it sees, so changing the behavior of
  431. * this method can cause problems.
  432. *
  433. * @param filterString
  434. * @param filteringMode
  435. * @return
  436. */
  437. protected Filter buildFilter(String filterString,
  438. FilteringMode filteringMode) {
  439. Filter filter = null;
  440. if (null != filterString && !"".equals(filterString)) {
  441. switch (filteringMode) {
  442. case OFF:
  443. break;
  444. case STARTSWITH:
  445. filter = new SimpleStringFilter(getItemCaptionPropertyId(),
  446. filterString, true, true);
  447. break;
  448. case CONTAINS:
  449. filter = new SimpleStringFilter(getItemCaptionPropertyId(),
  450. filterString, true, false);
  451. break;
  452. }
  453. }
  454. return filter;
  455. }
  456. @Override
  457. public void containerItemSetChange(Container.ItemSetChangeEvent event) {
  458. if (!isPainting) {
  459. super.containerItemSetChange(event);
  460. }
  461. }
  462. /**
  463. * Makes correct sublist of given list of options.
  464. *
  465. * If paint is not an option request (affected by page or filter change),
  466. * page will be the one where possible selection exists.
  467. *
  468. * Detects proper first and last item in list to return right page of
  469. * options. Also, if the current page is beyond the end of the list, it will
  470. * be adjusted.
  471. *
  472. * @param options
  473. * @param needNullSelectOption
  474. * flag to indicate if nullselect option needs to be taken into
  475. * consideration
  476. */
  477. private List<?> sanitetizeList(List<?> options, boolean needNullSelectOption) {
  478. if (getPageLength() != 0 && options.size() > getPageLength()) {
  479. int indexToEnsureInView = -1;
  480. // if not an option request (item list when user changes page), go
  481. // to page with the selected item after filtering if accepted by
  482. // filter
  483. Object selection = getValue();
  484. if (isScrollToSelectedItem() && !optionRequest && selection != null) {
  485. // ensure proper page
  486. indexToEnsureInView = options.indexOf(selection);
  487. }
  488. int size = options.size();
  489. currentPage = adjustCurrentPage(currentPage, needNullSelectOption,
  490. indexToEnsureInView, size);
  491. int first = getFirstItemIndexOnCurrentPage(needNullSelectOption,
  492. size);
  493. int last = getLastItemIndexOnCurrentPage(needNullSelectOption,
  494. size, first);
  495. return options.subList(first, last + 1);
  496. } else {
  497. return options;
  498. }
  499. }
  500. /**
  501. * Returns the index of the first item on the current page. The index is to
  502. * the underlying (possibly filtered) contents. The null item, if any, does
  503. * not have an index but takes up a slot on the first page.
  504. *
  505. * @param needNullSelectOption
  506. * true if a null option should be shown before any other options
  507. * (takes up the first slot on the first page, not counted in
  508. * index)
  509. * @param size
  510. * number of items after filtering (not including the null item,
  511. * if any)
  512. * @return first item to show on the UI (index to the filtered list of
  513. * options, not taking the null item into consideration if any)
  514. */
  515. private int getFirstItemIndexOnCurrentPage(boolean needNullSelectOption,
  516. int size) {
  517. // Not all options are visible, find out which ones are on the
  518. // current "page".
  519. int first = currentPage * getPageLength();
  520. if (needNullSelectOption && currentPage > 0) {
  521. first--;
  522. }
  523. return first;
  524. }
  525. /**
  526. * Returns the index of the last item on the current page. The index is to
  527. * the underlying (possibly filtered) contents. If needNullSelectOption is
  528. * true, the null item takes up the first slot on the first page,
  529. * effectively reducing the first page size by one.
  530. *
  531. * @param needNullSelectOption
  532. * true if a null option should be shown before any other options
  533. * (takes up the first slot on the first page, not counted in
  534. * index)
  535. * @param size
  536. * number of items after filtering (not including the null item,
  537. * if any)
  538. * @param first
  539. * index in the filtered view of the first item of the page
  540. * @return index in the filtered view of the last item on the page
  541. */
  542. private int getLastItemIndexOnCurrentPage(boolean needNullSelectOption,
  543. int size, int first) {
  544. // page length usable for non-null items
  545. int effectivePageLength = getPageLength()
  546. - (needNullSelectOption && (currentPage == 0) ? 1 : 0);
  547. return Math.min(size - 1, first + effectivePageLength - 1);
  548. }
  549. /**
  550. * Adjusts the index of the current page if necessary: make sure the current
  551. * page is not after the end of the contents, and optionally go to the page
  552. * containg a specific item. There are no side effects but the adjusted page
  553. * index is returned.
  554. *
  555. * @param page
  556. * page number to use as the starting point
  557. * @param needNullSelectOption
  558. * true if a null option should be shown before any other options
  559. * (takes up the first slot on the first page, not counted in
  560. * index)
  561. * @param indexToEnsureInView
  562. * index of an item that should be included on the page (in the
  563. * data set, not counting the null item if any), -1 for none
  564. * @param size
  565. * number of items after filtering (not including the null item,
  566. * if any)
  567. */
  568. private int adjustCurrentPage(int page, boolean needNullSelectOption,
  569. int indexToEnsureInView, int size) {
  570. if (indexToEnsureInView != -1) {
  571. int newPage = (indexToEnsureInView + (needNullSelectOption ? 1 : 0))
  572. / getPageLength();
  573. page = newPage;
  574. }
  575. // adjust the current page if beyond the end of the list
  576. if (page * getPageLength() > size) {
  577. page = (size + (needNullSelectOption ? 1 : 0)) / getPageLength();
  578. }
  579. return page;
  580. }
  581. /**
  582. * Filters the options in memory and returns the full filtered list.
  583. *
  584. * This can be less efficient than using container filters, so use
  585. * {@link #getOptionsWithFilter(boolean)} if possible (filterable container
  586. * and suitable item caption mode etc.).
  587. *
  588. * @return
  589. */
  590. protected List<?> getFilteredOptions() {
  591. if (!isFilteringNeeded()) {
  592. prevfilterstring = null;
  593. filteredOptions = new LinkedList<Object>(getItemIds());
  594. return filteredOptions;
  595. }
  596. if (filterstring.equals(prevfilterstring)) {
  597. return filteredOptions;
  598. }
  599. Collection<?> items;
  600. if (prevfilterstring != null
  601. && filterstring.startsWith(prevfilterstring)) {
  602. items = filteredOptions;
  603. } else {
  604. items = getItemIds();
  605. }
  606. prevfilterstring = filterstring;
  607. filteredOptions = new LinkedList<Object>();
  608. for (final Iterator<?> it = items.iterator(); it.hasNext();) {
  609. final Object itemId = it.next();
  610. String caption = getItemCaption(itemId);
  611. if (caption == null || caption.equals("")) {
  612. continue;
  613. } else {
  614. caption = caption.toLowerCase(getLocale());
  615. }
  616. switch (getFilteringMode()) {
  617. case CONTAINS:
  618. if (caption.indexOf(filterstring) > -1) {
  619. filteredOptions.add(itemId);
  620. }
  621. break;
  622. case STARTSWITH:
  623. default:
  624. if (caption.startsWith(filterstring)) {
  625. filteredOptions.add(itemId);
  626. }
  627. break;
  628. }
  629. }
  630. return filteredOptions;
  631. }
  632. /**
  633. * Invoked when the value of a variable has changed.
  634. *
  635. * @see com.vaadin.ui.AbstractComponent#changeVariables(java.lang.Object,
  636. * java.util.Map)
  637. */
  638. @Override
  639. public void changeVariables(Object source, Map<String, Object> variables) {
  640. // Not calling super.changeVariables due the history of select
  641. // component hierarchy
  642. String newFilter;
  643. if ((newFilter = (String) variables.get("filter")) != null) {
  644. // this is a filter request
  645. currentPage = ((Integer) variables.get("page")).intValue();
  646. filterstring = newFilter;
  647. if (filterstring != null) {
  648. filterstring = filterstring.toLowerCase(getLocale());
  649. }
  650. requestRepaint();
  651. }
  652. }
  653. @Override
  654. public void setFilteringMode(FilteringMode filteringMode) {
  655. getState().filteringMode = filteringMode;
  656. }
  657. @Override
  658. public FilteringMode getFilteringMode() {
  659. return getState(false).filteringMode;
  660. }
  661. @Override
  662. public void addBlurListener(BlurListener listener) {
  663. addListener(BlurEvent.EVENT_ID, BlurEvent.class, listener,
  664. BlurListener.blurMethod);
  665. }
  666. /**
  667. * @deprecated As of 7.0, replaced by {@link #addBlurListener(BlurListener)}
  668. **/
  669. @Override
  670. @Deprecated
  671. public void addListener(BlurListener listener) {
  672. addBlurListener(listener);
  673. }
  674. @Override
  675. public void removeBlurListener(BlurListener listener) {
  676. removeListener(BlurEvent.EVENT_ID, BlurEvent.class, listener);
  677. }
  678. /**
  679. * @deprecated As of 7.0, replaced by
  680. * {@link #removeBlurListener(BlurListener)}
  681. **/
  682. @Override
  683. @Deprecated
  684. public void removeListener(BlurListener listener) {
  685. removeBlurListener(listener);
  686. }
  687. @Override
  688. public void addFocusListener(FocusListener listener) {
  689. addListener(FocusEvent.EVENT_ID, FocusEvent.class, listener,
  690. FocusListener.focusMethod);
  691. }
  692. /**
  693. * @deprecated As of 7.0, replaced by
  694. * {@link #addFocusListener(FocusListener)}
  695. **/
  696. @Override
  697. @Deprecated
  698. public void addListener(FocusListener listener) {
  699. addFocusListener(listener);
  700. }
  701. @Override
  702. public void removeFocusListener(FocusListener listener) {
  703. removeListener(FocusEvent.EVENT_ID, FocusEvent.class, listener);
  704. }
  705. /**
  706. * @deprecated As of 7.0, replaced by
  707. * {@link #removeFocusListener(FocusListener)}
  708. **/
  709. @Override
  710. @Deprecated
  711. public void removeListener(FocusListener listener) {
  712. removeFocusListener(listener);
  713. }
  714. /**
  715. * ComboBox does not support multi select mode.
  716. *
  717. * @deprecated As of 7.0, use {@link ListSelect}, {@link OptionGroup} or
  718. * {@link TwinColSelect} instead
  719. * @see com.vaadin.ui.AbstractSelect#setMultiSelect(boolean)
  720. * @throws UnsupportedOperationException
  721. * if trying to activate multiselect mode
  722. */
  723. @Deprecated
  724. @Override
  725. public void setMultiSelect(boolean multiSelect) {
  726. if (multiSelect) {
  727. throw new UnsupportedOperationException("Multiselect not supported");
  728. }
  729. }
  730. /**
  731. * ComboBox does not support multi select mode.
  732. *
  733. * @deprecated As of 7.0, use {@link ListSelect}, {@link OptionGroup} or
  734. * {@link TwinColSelect} instead
  735. *
  736. * @see com.vaadin.ui.AbstractSelect#isMultiSelect()
  737. *
  738. * @return false
  739. */
  740. @Deprecated
  741. @Override
  742. public boolean isMultiSelect() {
  743. return false;
  744. }
  745. /**
  746. * Returns the page length of the suggestion popup.
  747. *
  748. * @return the pageLength
  749. */
  750. public int getPageLength() {
  751. return getState(false).pageLength;
  752. }
  753. /**
  754. * Returns the suggestion pop-up's width as a CSS string.
  755. *
  756. * @see #setPopupWidth
  757. * @since 7.7
  758. */
  759. public String getPopupWidth() {
  760. return suggestionPopupWidth;
  761. }
  762. /**
  763. * Sets the page length for the suggestion popup. Setting the page length to
  764. * 0 will disable suggestion popup paging (all items visible).
  765. *
  766. * @param pageLength
  767. * the pageLength to set
  768. */
  769. public void setPageLength(int pageLength) {
  770. getState().pageLength = pageLength;
  771. }
  772. /**
  773. * Sets the suggestion pop-up's width as a CSS string. By using relative
  774. * units (e.g. "50%") it's possible to set the popup's width relative to the
  775. * ComboBox itself.
  776. *
  777. * @see #getPopupWidth()
  778. * @since 7.7
  779. * @param width
  780. * the width
  781. */
  782. public void setPopupWidth(String width) {
  783. suggestionPopupWidth = width;
  784. markAsDirty();
  785. }
  786. /**
  787. * Sets whether to scroll the selected item visible (directly open the page
  788. * on which it is) when opening the combo box popup or not. Only applies to
  789. * single select mode.
  790. *
  791. * This requires finding the index of the item, which can be expensive in
  792. * many large lazy loading containers.
  793. *
  794. * @param scrollToSelectedItem
  795. * true to find the page with the selected item when opening the
  796. * selection popup
  797. */
  798. public void setScrollToSelectedItem(boolean scrollToSelectedItem) {
  799. this.scrollToSelectedItem = scrollToSelectedItem;
  800. }
  801. /**
  802. * Returns true if the select should find the page with the selected item
  803. * when opening the popup (single select combo box only).
  804. *
  805. * @see #setScrollToSelectedItem(boolean)
  806. *
  807. * @return true if the page with the selected item will be shown when
  808. * opening the popup
  809. */
  810. public boolean isScrollToSelectedItem() {
  811. return scrollToSelectedItem;
  812. }
  813. /**
  814. * Sets the item style generator that is used to produce custom styles for
  815. * showing items in the popup. The CSS class name that will be added to the
  816. * item style names is <tt>v-filterselect-item-[style name]</tt>.
  817. *
  818. * @param itemStyleGenerator
  819. * the item style generator to set, or <code>null</code> to not
  820. * use any custom item styles
  821. * @since 7.5.6
  822. */
  823. public void setItemStyleGenerator(ItemStyleGenerator itemStyleGenerator) {
  824. this.itemStyleGenerator = itemStyleGenerator;
  825. markAsDirty();
  826. }
  827. /**
  828. * Gets the currently used item style generator.
  829. *
  830. * @return the itemStyleGenerator the currently used item style generator,
  831. * or <code>null</code> if no generator is used
  832. * @since 7.5.6
  833. */
  834. public ItemStyleGenerator getItemStyleGenerator() {
  835. return itemStyleGenerator;
  836. }
  837. }