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.

AbstractSelect.java 77KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354
  1. /*
  2. * Copyright 2000-2016 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.v7.ui;
  17. import java.io.Serializable;
  18. import java.util.ArrayList;
  19. import java.util.Collection;
  20. import java.util.Collections;
  21. import java.util.EventObject;
  22. import java.util.HashMap;
  23. import java.util.HashSet;
  24. import java.util.Iterator;
  25. import java.util.LinkedHashSet;
  26. import java.util.LinkedList;
  27. import java.util.List;
  28. import java.util.Map;
  29. import java.util.Set;
  30. import org.jsoup.nodes.Element;
  31. import com.vaadin.event.Transferable;
  32. import com.vaadin.event.dd.DragAndDropEvent;
  33. import com.vaadin.event.dd.DropTarget;
  34. import com.vaadin.event.dd.TargetDetailsImpl;
  35. import com.vaadin.event.dd.acceptcriteria.ClientSideCriterion;
  36. import com.vaadin.event.dd.acceptcriteria.ContainsDataFlavor;
  37. import com.vaadin.event.dd.acceptcriteria.TargetDetailIs;
  38. import com.vaadin.server.KeyMapper;
  39. import com.vaadin.server.PaintException;
  40. import com.vaadin.server.PaintTarget;
  41. import com.vaadin.server.Resource;
  42. import com.vaadin.server.VaadinSession;
  43. import com.vaadin.shared.ui.dd.VerticalDropLocation;
  44. import com.vaadin.ui.Component;
  45. import com.vaadin.ui.LegacyComponent;
  46. import com.vaadin.ui.declarative.DesignAttributeHandler;
  47. import com.vaadin.ui.declarative.DesignContext;
  48. import com.vaadin.ui.declarative.DesignException;
  49. import com.vaadin.ui.declarative.DesignFormatter;
  50. import com.vaadin.v7.data.Container;
  51. import com.vaadin.v7.data.Item;
  52. import com.vaadin.v7.data.Property;
  53. import com.vaadin.v7.data.Validator.InvalidValueException;
  54. import com.vaadin.v7.data.util.IndexedContainer;
  55. import com.vaadin.v7.data.util.converter.Converter;
  56. import com.vaadin.v7.data.util.converter.Converter.ConversionException;
  57. import com.vaadin.v7.data.util.converter.ConverterUtil;
  58. import com.vaadin.v7.event.DataBoundTransferable;
  59. import com.vaadin.v7.shared.ui.combobox.FilteringMode;
  60. import com.vaadin.v7.shared.ui.select.AbstractSelectState;
  61. /**
  62. * <p>
  63. * A class representing a selection of items the user has selected in a UI. The
  64. * set of choices is presented as a set of {@link com.com.vaadin.v7.data.Item}s
  65. * in a {@link com.com.vaadin.v7.data.Container}.
  66. * </p>
  67. *
  68. * <p>
  69. * A <code>Select</code> component may be in single- or multiselect mode.
  70. * Multiselect mode means that more than one item can be selected
  71. * simultaneously.
  72. * </p>
  73. *
  74. * @author Vaadin Ltd.
  75. * @since 5.0
  76. */
  77. @SuppressWarnings("serial")
  78. // TODO currently cannot specify type more precisely in case of multi-select
  79. public abstract class AbstractSelect extends AbstractField<Object> implements
  80. Container, Container.Viewer, Container.PropertySetChangeListener,
  81. Container.PropertySetChangeNotifier, Container.ItemSetChangeNotifier,
  82. Container.ItemSetChangeListener, LegacyComponent {
  83. public enum ItemCaptionMode {
  84. /**
  85. * Item caption mode: Item's ID converted to a String using
  86. * {@link VaadinSession#getConverterFactory()} is used as caption.
  87. */
  88. ID,
  89. /**
  90. * Item caption mode: Item's ID's <code>String</code> representation is
  91. * used as caption.
  92. *
  93. * @since 7.5.6
  94. */
  95. ID_TOSTRING,
  96. /**
  97. * Item caption mode: Item's <code>String</code> representation is used
  98. * as caption.
  99. */
  100. ITEM,
  101. /**
  102. * Item caption mode: Index of the item is used as caption. The index
  103. * mode can only be used with the containers implementing the
  104. * {@link com.vaadin.data.Container.Indexed} interface.
  105. */
  106. INDEX,
  107. /**
  108. * Item caption mode: If an Item has a caption it's used, if not, Item's
  109. * ID converted to a String using
  110. * {@link VaadinSession#getConverterFactory()} is used as caption.
  111. * <b>This is the default</b>.
  112. */
  113. EXPLICIT_DEFAULTS_ID,
  114. /**
  115. * Item caption mode: Captions must be explicitly specified.
  116. */
  117. EXPLICIT,
  118. /**
  119. * Item caption mode: Only icons are shown, captions are hidden.
  120. */
  121. ICON_ONLY,
  122. /**
  123. * Item caption mode: Item captions are read from property specified
  124. * with <code>setItemCaptionPropertyId</code>.
  125. */
  126. PROPERTY;
  127. }
  128. /**
  129. * @deprecated As of 7.0, use {@link ItemCaptionMode#ID} instead
  130. */
  131. @Deprecated
  132. public static final ItemCaptionMode ITEM_CAPTION_MODE_ID = ItemCaptionMode.ID;
  133. /**
  134. * @deprecated As of 7.0, use {@link ItemCaptionMode#ITEM} instead
  135. */
  136. @Deprecated
  137. public static final ItemCaptionMode ITEM_CAPTION_MODE_ITEM = ItemCaptionMode.ITEM;
  138. /**
  139. * @deprecated As of 7.0, use {@link ItemCaptionMode#INDEX} instead
  140. */
  141. @Deprecated
  142. public static final ItemCaptionMode ITEM_CAPTION_MODE_INDEX = ItemCaptionMode.INDEX;
  143. /**
  144. * @deprecated As of 7.0, use {@link ItemCaptionMode#EXPLICIT_DEFAULTS_ID}
  145. * instead
  146. */
  147. @Deprecated
  148. public static final ItemCaptionMode ITEM_CAPTION_MODE_EXPLICIT_DEFAULTS_ID = ItemCaptionMode.EXPLICIT_DEFAULTS_ID;
  149. /**
  150. * @deprecated As of 7.0, use {@link ItemCaptionMode#EXPLICIT} instead
  151. */
  152. @Deprecated
  153. public static final ItemCaptionMode ITEM_CAPTION_MODE_EXPLICIT = ItemCaptionMode.EXPLICIT;
  154. /**
  155. * @deprecated As of 7.0, use {@link ItemCaptionMode#ICON_ONLY} instead
  156. */
  157. @Deprecated
  158. public static final ItemCaptionMode ITEM_CAPTION_MODE_ICON_ONLY = ItemCaptionMode.ICON_ONLY;
  159. /**
  160. * @deprecated As of 7.0, use {@link ItemCaptionMode#PROPERTY} instead
  161. */
  162. @Deprecated
  163. public static final ItemCaptionMode ITEM_CAPTION_MODE_PROPERTY = ItemCaptionMode.PROPERTY;
  164. /**
  165. * Interface for option filtering, used to filter options based on user
  166. * entered value. The value is matched to the item caption.
  167. * <code>FilteringMode.OFF</code> (0) turns the filtering off.
  168. * <code>FilteringMode.STARTSWITH</code> (1) matches from the start of the
  169. * caption. <code>FilteringMode.CONTAINS</code> (1) matches anywhere in the
  170. * caption.
  171. */
  172. public interface Filtering extends Serializable {
  173. /**
  174. * @deprecated As of 7.0, use {@link FilteringMode#OFF} instead
  175. */
  176. @Deprecated
  177. public static final FilteringMode FILTERINGMODE_OFF = FilteringMode.OFF;
  178. /**
  179. * @deprecated As of 7.0, use {@link FilteringMode#STARTSWITH} instead
  180. */
  181. @Deprecated
  182. public static final FilteringMode FILTERINGMODE_STARTSWITH = FilteringMode.STARTSWITH;
  183. /**
  184. * @deprecated As of 7.0, use {@link FilteringMode#CONTAINS} instead
  185. */
  186. @Deprecated
  187. public static final FilteringMode FILTERINGMODE_CONTAINS = FilteringMode.CONTAINS;
  188. /**
  189. * Sets the option filtering mode.
  190. *
  191. * @param filteringMode
  192. * the filtering mode to use
  193. */
  194. public void setFilteringMode(FilteringMode filteringMode);
  195. /**
  196. * Gets the current filtering mode.
  197. *
  198. * @return the filtering mode in use
  199. */
  200. public FilteringMode getFilteringMode();
  201. }
  202. /**
  203. * Select options.
  204. */
  205. protected Container items;
  206. /**
  207. * Is the user allowed to add new options?
  208. */
  209. private boolean allowNewOptions;
  210. /**
  211. * Keymapper used to map key values.
  212. */
  213. protected KeyMapper<Object> itemIdMapper = new KeyMapper<Object>();
  214. /**
  215. * Item icons.
  216. */
  217. private final HashMap<Object, Resource> itemIcons = new HashMap<Object, Resource>();
  218. /**
  219. * Item captions.
  220. */
  221. private final HashMap<Object, String> itemCaptions = new HashMap<Object, String>();
  222. /**
  223. * Item caption mode.
  224. */
  225. private ItemCaptionMode itemCaptionMode = ItemCaptionMode.EXPLICIT_DEFAULTS_ID;
  226. /**
  227. * Item caption source property id.
  228. */
  229. private Object itemCaptionPropertyId = null;
  230. /**
  231. * Item icon source property id.
  232. */
  233. private Object itemIconPropertyId = null;
  234. /**
  235. * List of property set change event listeners.
  236. */
  237. private Set<Container.PropertySetChangeListener> propertySetEventListeners = null;
  238. /**
  239. * List of item set change event listeners.
  240. */
  241. private Set<Container.ItemSetChangeListener> itemSetEventListeners = null;
  242. /**
  243. * Item id that represents null selection of this select.
  244. *
  245. * <p>
  246. * Data interface does not support nulls as item ids. Selecting the item
  247. * identified by this id is the same as selecting no items at all. This
  248. * setting only affects the single select mode.
  249. * </p>
  250. */
  251. private Object nullSelectionItemId = null;
  252. // Null (empty) selection is enabled by default
  253. private boolean nullSelectionAllowed = true;
  254. private NewItemHandler newItemHandler;
  255. // Caption (Item / Property) change listeners
  256. CaptionChangeListener captionChangeListener;
  257. /* Constructors */
  258. /**
  259. * Creates an empty Select. The caption is not used.
  260. */
  261. public AbstractSelect() {
  262. setContainerDataSource(new IndexedContainer());
  263. }
  264. /**
  265. * Creates an empty Select with caption.
  266. */
  267. public AbstractSelect(String caption) {
  268. setContainerDataSource(new IndexedContainer());
  269. setCaption(caption);
  270. }
  271. /**
  272. * Creates a new select that is connected to a data-source.
  273. *
  274. * @param caption
  275. * the Caption of the component.
  276. * @param dataSource
  277. * the Container datasource to be selected from by this select.
  278. */
  279. public AbstractSelect(String caption, Container dataSource) {
  280. setCaption(caption);
  281. setContainerDataSource(dataSource);
  282. }
  283. /**
  284. * Creates a new select that is filled from a collection of option values.
  285. *
  286. * @param caption
  287. * the Caption of this field.
  288. * @param options
  289. * the Collection containing the options.
  290. */
  291. public AbstractSelect(String caption, Collection<?> options) {
  292. // Creates the options container and add given options to it
  293. final Container c = new IndexedContainer();
  294. if (options != null) {
  295. for (final Iterator<?> i = options.iterator(); i.hasNext();) {
  296. c.addItem(i.next());
  297. }
  298. }
  299. setCaption(caption);
  300. setContainerDataSource(c);
  301. }
  302. /* Component methods */
  303. /**
  304. * Paints the content of this component.
  305. *
  306. * @param target
  307. * the Paint Event.
  308. * @throws PaintException
  309. * if the paint operation failed.
  310. */
  311. @Override
  312. public void paintContent(PaintTarget target) throws PaintException {
  313. // Paints select attributes
  314. if (isNewItemsAllowed()) {
  315. target.addAttribute("allownewitem", true);
  316. }
  317. if (isNullSelectionAllowed()) {
  318. target.addAttribute("nullselect", true);
  319. if (getNullSelectionItemId() != null) {
  320. target.addAttribute("nullselectitem", true);
  321. }
  322. }
  323. // Constructs selected keys array
  324. String[] selectedKeys;
  325. if (isMultiSelect()) {
  326. selectedKeys = new String[((Set<?>) getValue()).size()];
  327. } else {
  328. selectedKeys = new String[(getValue() == null
  329. && getNullSelectionItemId() == null ? 0 : 1)];
  330. }
  331. // ==
  332. // first remove all previous item/property listeners
  333. getCaptionChangeListener().clear();
  334. // Paints the options and create array of selected id keys
  335. target.startTag("options");
  336. int keyIndex = 0;
  337. // Support for external null selection item id
  338. final Collection<?> ids = getItemIds();
  339. if (isNullSelectionAllowed() && getNullSelectionItemId() != null
  340. && !ids.contains(getNullSelectionItemId())) {
  341. final Object id = getNullSelectionItemId();
  342. // Paints option
  343. target.startTag("so");
  344. paintItem(target, id);
  345. if (isSelected(id)) {
  346. selectedKeys[keyIndex++] = itemIdMapper.key(id);
  347. }
  348. target.endTag("so");
  349. }
  350. final Iterator<?> i = getItemIds().iterator();
  351. // Paints the available selection options from data source
  352. while (i.hasNext()) {
  353. // Gets the option attribute values
  354. final Object id = i.next();
  355. if (!isNullSelectionAllowed() && id != null
  356. && id.equals(getNullSelectionItemId())) {
  357. // Remove item if it's the null selection item but null
  358. // selection is not allowed
  359. continue;
  360. }
  361. final String key = itemIdMapper.key(id);
  362. // add listener for each item, to cause repaint if an item changes
  363. getCaptionChangeListener().addNotifierForItem(id);
  364. target.startTag("so");
  365. paintItem(target, id);
  366. if (isSelected(id) && keyIndex < selectedKeys.length) {
  367. selectedKeys[keyIndex++] = key;
  368. }
  369. target.endTag("so");
  370. }
  371. target.endTag("options");
  372. // ==
  373. // Paint variables
  374. target.addVariable(this, "selected", selectedKeys);
  375. if (isNewItemsAllowed()) {
  376. target.addVariable(this, "newitem", "");
  377. }
  378. }
  379. protected void paintItem(PaintTarget target, Object itemId)
  380. throws PaintException {
  381. final String key = itemIdMapper.key(itemId);
  382. final String caption = getItemCaption(itemId);
  383. final Resource icon = getItemIcon(itemId);
  384. if (icon != null) {
  385. target.addAttribute("icon", icon);
  386. }
  387. target.addAttribute("caption", caption);
  388. if (itemId != null && itemId.equals(getNullSelectionItemId())) {
  389. target.addAttribute("nullselection", true);
  390. }
  391. target.addAttribute("key", key);
  392. if (isSelected(itemId)) {
  393. target.addAttribute("selected", true);
  394. }
  395. }
  396. /**
  397. * Invoked when the value of a variable has changed.
  398. *
  399. * @see com.vaadin.ui.AbstractComponent#changeVariables(java.lang.Object,
  400. * java.util.Map)
  401. */
  402. @Override
  403. public void changeVariables(Object source, Map<String, Object> variables) {
  404. // New option entered (and it is allowed)
  405. if (isNewItemsAllowed()) {
  406. final String newitem = (String) variables.get("newitem");
  407. if (newitem != null && newitem.length() > 0) {
  408. getNewItemHandler().addNewItem(newitem);
  409. }
  410. }
  411. // Selection change
  412. if (variables.containsKey("selected")) {
  413. final String[] clientSideSelectedKeys = (String[]) variables
  414. .get("selected");
  415. // Multiselect mode
  416. if (isMultiSelect()) {
  417. // TODO Optimize by adding repaintNotNeeded when applicable
  418. // Converts the key-array to id-set
  419. final LinkedList<Object> acceptedSelections = new LinkedList<Object>();
  420. for (int i = 0; i < clientSideSelectedKeys.length; i++) {
  421. final Object id = itemIdMapper
  422. .get(clientSideSelectedKeys[i]);
  423. if (!isNullSelectionAllowed()
  424. && (id == null || id == getNullSelectionItemId())) {
  425. // skip empty selection if nullselection is not allowed
  426. markAsDirty();
  427. } else if (id != null && containsId(id)) {
  428. acceptedSelections.add(id);
  429. }
  430. }
  431. if (!isNullSelectionAllowed()
  432. && acceptedSelections.size() < 1) {
  433. // empty selection not allowed, keep old value
  434. markAsDirty();
  435. return;
  436. }
  437. // Limits the deselection to the set of visible items
  438. // (non-visible items can not be deselected)
  439. Collection<?> visibleNotSelected = getVisibleItemIds();
  440. if (visibleNotSelected != null) {
  441. visibleNotSelected = new HashSet<Object>(
  442. visibleNotSelected);
  443. // Don't remove those that will be added to preserve order
  444. visibleNotSelected.removeAll(acceptedSelections);
  445. @SuppressWarnings("unchecked")
  446. Set<Object> newsel = (Set<Object>) getValue();
  447. if (newsel == null) {
  448. newsel = new LinkedHashSet<Object>();
  449. } else {
  450. newsel = new LinkedHashSet<Object>(newsel);
  451. }
  452. newsel.removeAll(visibleNotSelected);
  453. newsel.addAll(acceptedSelections);
  454. setValue(newsel, true);
  455. }
  456. } else {
  457. // Single select mode
  458. if (!isNullSelectionAllowed()
  459. && (clientSideSelectedKeys.length == 0
  460. || clientSideSelectedKeys[0] == null
  461. || clientSideSelectedKeys[0] == getNullSelectionItemId())) {
  462. markAsDirty();
  463. return;
  464. }
  465. if (clientSideSelectedKeys.length == 0) {
  466. // Allows deselection only if the deselected item is
  467. // visible
  468. final Object current = getValue();
  469. final Collection<?> visible = getVisibleItemIds();
  470. if (visible != null && visible.contains(current)) {
  471. setValue(null, true);
  472. }
  473. } else {
  474. String clientSelectedKey = clientSideSelectedKeys[0];
  475. if ("null".equals(clientSelectedKey)
  476. || itemIdMapper.containsKey(clientSelectedKey)) {
  477. // Happens to work for nullselection
  478. // (get ("null") -> null))
  479. final Object id = itemIdMapper.get(clientSelectedKey);
  480. if (!isNullSelectionAllowed() && id == null) {
  481. markAsDirty();
  482. } else if (id != null
  483. && id.equals(getNullSelectionItemId())) {
  484. setValue(null, true);
  485. } else {
  486. setValue(id, true);
  487. }
  488. }
  489. }
  490. }
  491. }
  492. }
  493. /**
  494. * TODO refine doc Setter for new item handler that is called when user adds
  495. * new item in newItemAllowed mode.
  496. *
  497. * @param newItemHandler
  498. */
  499. public void setNewItemHandler(NewItemHandler newItemHandler) {
  500. this.newItemHandler = newItemHandler;
  501. }
  502. /**
  503. * TODO refine doc
  504. *
  505. * @return
  506. */
  507. public NewItemHandler getNewItemHandler() {
  508. if (newItemHandler == null) {
  509. newItemHandler = new DefaultNewItemHandler();
  510. }
  511. return newItemHandler;
  512. }
  513. public interface NewItemHandler extends Serializable {
  514. void addNewItem(String newItemCaption);
  515. }
  516. /**
  517. * TODO refine doc
  518. *
  519. * This is a default class that handles adding new items that are typed by
  520. * user to selects container.
  521. *
  522. * By extending this class one may implement some logic on new item addition
  523. * like database inserts.
  524. *
  525. */
  526. public class DefaultNewItemHandler implements NewItemHandler {
  527. @Override
  528. public void addNewItem(String newItemCaption) {
  529. // Checks for readonly
  530. if (isReadOnly()) {
  531. throw new Property.ReadOnlyException();
  532. }
  533. // Adds new option
  534. if (addItem(newItemCaption) != null) {
  535. // Sets the caption property, if used
  536. if (getItemCaptionPropertyId() != null) {
  537. getContainerProperty(newItemCaption,
  538. getItemCaptionPropertyId())
  539. .setValue(newItemCaption);
  540. }
  541. if (isMultiSelect()) {
  542. Set values = new HashSet((Collection) getValue());
  543. values.add(newItemCaption);
  544. setValue(values);
  545. } else {
  546. setValue(newItemCaption);
  547. }
  548. }
  549. }
  550. }
  551. /**
  552. * Gets the visible item ids. In Select, this returns list of all item ids,
  553. * but can be overriden in subclasses if they paint only part of the items
  554. * to the terminal or null if no items is visible.
  555. */
  556. public Collection<?> getVisibleItemIds() {
  557. return getItemIds();
  558. }
  559. /* Property methods */
  560. /**
  561. * Returns the type of the property. <code>getValue</code> and
  562. * <code>setValue</code> methods must be compatible with this type: one can
  563. * safely cast <code>getValue</code> to given type and pass any variable
  564. * assignable to this type as a parameter to <code>setValue</code>.
  565. *
  566. * @return the Type of the property.
  567. */
  568. @Override
  569. public Class<?> getType() {
  570. if (isMultiSelect()) {
  571. return Set.class;
  572. } else {
  573. return Object.class;
  574. }
  575. }
  576. /**
  577. * Gets the selected item id or in multiselect mode a set of selected ids.
  578. *
  579. * @see com.vaadin.v7.ui.AbstractField#getValue()
  580. */
  581. @Override
  582. public Object getValue() {
  583. final Object retValue = super.getValue();
  584. if (isMultiSelect()) {
  585. // If the return value is not a set
  586. if (retValue == null) {
  587. return new HashSet<Object>();
  588. }
  589. if (retValue instanceof Set) {
  590. return Collections.unmodifiableSet((Set<?>) retValue);
  591. } else if (retValue instanceof Collection) {
  592. return new HashSet<Object>((Collection<?>) retValue);
  593. } else {
  594. final Set<Object> s = new HashSet<Object>();
  595. if (items.containsId(retValue)) {
  596. s.add(retValue);
  597. }
  598. return s;
  599. }
  600. } else {
  601. return retValue;
  602. }
  603. }
  604. /**
  605. * Sets the visible value of the property.
  606. *
  607. * <p>
  608. * The value of the select is the selected item id. If the select is in
  609. * multiselect-mode, the value is a set of selected item keys. In
  610. * multiselect mode all collections of id:s can be assigned.
  611. * </p>
  612. *
  613. * @param newValue
  614. * the New selected item or collection of selected items.
  615. * @see com.vaadin.v7.ui.AbstractField#setValue(java.lang.Object)
  616. */
  617. @Override
  618. public void setValue(Object newValue) throws Property.ReadOnlyException {
  619. if (newValue == getNullSelectionItemId()) {
  620. newValue = null;
  621. }
  622. setValue(newValue, false);
  623. }
  624. /**
  625. * Sets the visible value of the property.
  626. *
  627. * <p>
  628. * The value of the select is the selected item id. If the select is in
  629. * multiselect-mode, the value is a set of selected item keys. In
  630. * multiselect mode all collections of id:s can be assigned.
  631. * </p>
  632. *
  633. * @since 7.5.7
  634. * @param newValue
  635. * the New selected item or collection of selected items.
  636. * @param repaintIsNotNeeded
  637. * True if caller is sure that repaint is not needed.
  638. * @param ignoreReadOnly
  639. * True if read-only check should be omitted.
  640. * @see com.vaadin.v7.ui.AbstractField#setValue(java.lang.Object,
  641. * java.lang.Boolean)
  642. */
  643. @Override
  644. protected void setValue(Object newFieldValue, boolean repaintIsNotNeeded,
  645. boolean ignoreReadOnly)
  646. throws com.vaadin.v7.data.Property.ReadOnlyException,
  647. ConversionException, InvalidValueException {
  648. if (isMultiSelect()) {
  649. if (newFieldValue == null) {
  650. super.setValue(new LinkedHashSet<Object>(), repaintIsNotNeeded,
  651. ignoreReadOnly);
  652. } else if (Collection.class
  653. .isAssignableFrom(newFieldValue.getClass())) {
  654. super.setValue(
  655. new LinkedHashSet<Object>(
  656. (Collection<?>) newFieldValue),
  657. repaintIsNotNeeded, ignoreReadOnly);
  658. }
  659. } else if (newFieldValue == null || items.containsId(newFieldValue)) {
  660. super.setValue(newFieldValue, repaintIsNotNeeded, ignoreReadOnly);
  661. }
  662. }
  663. /* Container methods */
  664. /**
  665. * Gets the item from the container with given id. If the container does not
  666. * contain the requested item, null is returned.
  667. *
  668. * @param itemId
  669. * the item id.
  670. * @return the item from the container.
  671. */
  672. @Override
  673. public Item getItem(Object itemId) {
  674. return items.getItem(itemId);
  675. }
  676. /**
  677. * Gets the item Id collection from the container.
  678. *
  679. * @return the Collection of item ids.
  680. */
  681. @Override
  682. public Collection<?> getItemIds() {
  683. return items.getItemIds();
  684. }
  685. /**
  686. * Gets the property Id collection from the container.
  687. *
  688. * @return the Collection of property ids.
  689. */
  690. @Override
  691. public Collection<?> getContainerPropertyIds() {
  692. return items.getContainerPropertyIds();
  693. }
  694. /**
  695. * Gets the property type.
  696. *
  697. * @param propertyId
  698. * the Id identifying the property.
  699. * @see com.com.vaadin.v7.data.Container#getType(java.lang.Object)
  700. */
  701. @Override
  702. public Class<?> getType(Object propertyId) {
  703. return items.getType(propertyId);
  704. }
  705. /*
  706. * Gets the number of items in the container.
  707. *
  708. * @return the Number of items in the container.
  709. *
  710. * @see com.vaadin.data.Container#size()
  711. */
  712. @Override
  713. public int size() {
  714. int size = items.size();
  715. assert size >= 0;
  716. return size;
  717. }
  718. /**
  719. * Tests, if the collection contains an item with given id.
  720. *
  721. * @param itemId
  722. * the Id the of item to be tested.
  723. */
  724. @Override
  725. public boolean containsId(Object itemId) {
  726. if (itemId != null) {
  727. return items.containsId(itemId);
  728. } else {
  729. return false;
  730. }
  731. }
  732. /**
  733. * Gets the Property identified by the given itemId and propertyId from the
  734. * Container
  735. *
  736. * @see com.com.vaadin.v7.data.Container#getContainerProperty(Object,
  737. * Object)
  738. */
  739. @Override
  740. public Property getContainerProperty(Object itemId, Object propertyId) {
  741. return items.getContainerProperty(itemId, propertyId);
  742. }
  743. /**
  744. * Adds the new property to all items. Adds a property with given id, type
  745. * and default value to all items in the container.
  746. *
  747. * This functionality is optional. If the function is unsupported, it always
  748. * returns false.
  749. *
  750. * @return True if the operation succeeded.
  751. * @see com.com.vaadin.v7.data.Container#addContainerProperty(java.lang.Object,
  752. * java.lang.Class, java.lang.Object)
  753. */
  754. @Override
  755. public boolean addContainerProperty(Object propertyId, Class<?> type,
  756. Object defaultValue) throws UnsupportedOperationException {
  757. final boolean retval = items.addContainerProperty(propertyId, type,
  758. defaultValue);
  759. if (retval && !(items instanceof Container.PropertySetChangeNotifier)) {
  760. firePropertySetChange();
  761. }
  762. return retval;
  763. }
  764. /**
  765. * Removes all items from the container.
  766. *
  767. * This functionality is optional. If the function is unsupported, it always
  768. * returns false.
  769. *
  770. * @return True if the operation succeeded.
  771. * @see com.com.vaadin.v7.data.Container#removeAllItems()
  772. */
  773. @Override
  774. public boolean removeAllItems() throws UnsupportedOperationException {
  775. final boolean retval = items.removeAllItems();
  776. itemIdMapper.removeAll();
  777. if (retval) {
  778. setValue(null);
  779. if (!(items instanceof Container.ItemSetChangeNotifier)) {
  780. fireItemSetChange();
  781. }
  782. }
  783. return retval;
  784. }
  785. /**
  786. * Creates a new item into container with container managed id. The id of
  787. * the created new item is returned. The item can be fetched with getItem()
  788. * method. if the creation fails, null is returned.
  789. *
  790. * @return the Id of the created item or null in case of failure.
  791. * @see com.com.vaadin.v7.data.Container#addItem()
  792. */
  793. @Override
  794. public Object addItem() throws UnsupportedOperationException {
  795. final Object retval = items.addItem();
  796. if (retval != null
  797. && !(items instanceof Container.ItemSetChangeNotifier)) {
  798. fireItemSetChange();
  799. }
  800. return retval;
  801. }
  802. /**
  803. * Create a new item into container. The created new item is returned and
  804. * ready for setting property values. if the creation fails, null is
  805. * returned. In case the container already contains the item, null is
  806. * returned.
  807. *
  808. * This functionality is optional. If the function is unsupported, it always
  809. * returns null.
  810. *
  811. * @param itemId
  812. * the Identification of the item to be created.
  813. * @return the Created item with the given id, or null in case of failure.
  814. * @see com.com.vaadin.v7.data.Container#addItem(java.lang.Object)
  815. */
  816. @Override
  817. public Item addItem(Object itemId) throws UnsupportedOperationException {
  818. final Item retval = items.addItem(itemId);
  819. if (retval != null
  820. && !(items instanceof Container.ItemSetChangeNotifier)) {
  821. fireItemSetChange();
  822. }
  823. return retval;
  824. }
  825. /**
  826. * Adds given items with given item ids to container.
  827. *
  828. * @since 7.2
  829. * @param itemId
  830. * item identifiers to be added to underlying container
  831. * @throws UnsupportedOperationException
  832. * if the underlying container don't support adding items with
  833. * identifiers
  834. */
  835. public void addItems(Object... itemId)
  836. throws UnsupportedOperationException {
  837. for (Object id : itemId) {
  838. addItem(id);
  839. }
  840. }
  841. /**
  842. * Adds given items with given item ids to container.
  843. *
  844. * @since 7.2
  845. * @param itemIds
  846. * item identifiers to be added to underlying container
  847. * @throws UnsupportedOperationException
  848. * if the underlying container don't support adding items with
  849. * identifiers
  850. */
  851. public void addItems(Collection<?> itemIds)
  852. throws UnsupportedOperationException {
  853. addItems(itemIds.toArray());
  854. }
  855. /*
  856. * (non-Javadoc)
  857. *
  858. * @see com.vaadin.data.Container#removeItem(java.lang.Object)
  859. */
  860. @Override
  861. public boolean removeItem(Object itemId)
  862. throws UnsupportedOperationException {
  863. unselect(itemId);
  864. final boolean retval = items.removeItem(itemId);
  865. itemIdMapper.remove(itemId);
  866. if (retval && !(items instanceof Container.ItemSetChangeNotifier)) {
  867. fireItemSetChange();
  868. }
  869. return retval;
  870. }
  871. /**
  872. * Checks that the current selection is valid, i.e. the selected item ids
  873. * exist in the container. Updates the selection if one or several selected
  874. * item ids are no longer available in the container.
  875. */
  876. @SuppressWarnings("unchecked")
  877. public void sanitizeSelection() {
  878. Object value = getValue();
  879. if (value == null) {
  880. return;
  881. }
  882. boolean changed = false;
  883. if (isMultiSelect()) {
  884. Collection<Object> valueAsCollection = (Collection<Object>) value;
  885. List<Object> newSelection = new ArrayList<Object>(
  886. valueAsCollection.size());
  887. for (Object subValue : valueAsCollection) {
  888. if (containsId(subValue)) {
  889. newSelection.add(subValue);
  890. } else {
  891. changed = true;
  892. }
  893. }
  894. if (changed) {
  895. setValue(newSelection);
  896. }
  897. } else {
  898. if (!containsId(value)) {
  899. setValue(null);
  900. }
  901. }
  902. }
  903. /**
  904. * Removes the property from all items. Removes a property with given id
  905. * from all the items in the container.
  906. *
  907. * This functionality is optional. If the function is unsupported, it always
  908. * returns false.
  909. *
  910. * @return True if the operation succeeded.
  911. * @see com.com.vaadin.v7.data.Container#removeContainerProperty(java.lang.Object)
  912. */
  913. @Override
  914. public boolean removeContainerProperty(Object propertyId)
  915. throws UnsupportedOperationException {
  916. final boolean retval = items.removeContainerProperty(propertyId);
  917. if (retval && !(items instanceof Container.PropertySetChangeNotifier)) {
  918. firePropertySetChange();
  919. }
  920. return retval;
  921. }
  922. /* Container.Viewer methods */
  923. /**
  924. * Sets the Container that serves as the data source of the viewer.
  925. *
  926. * As a side-effect the fields value (selection) is set to null due old
  927. * selection not necessary exists in new Container.
  928. *
  929. * @see com.com.vaadin.v7.data.Container.Viewer#setContainerDataSource(Container)
  930. *
  931. * @param newDataSource
  932. * the new data source.
  933. */
  934. @Override
  935. public void setContainerDataSource(Container newDataSource) {
  936. if (newDataSource == null) {
  937. newDataSource = new IndexedContainer();
  938. }
  939. getCaptionChangeListener().clear();
  940. if (items != newDataSource) {
  941. // Removes listeners from the old datasource
  942. if (items != null) {
  943. if (items instanceof Container.ItemSetChangeNotifier) {
  944. ((Container.ItemSetChangeNotifier) items)
  945. .removeItemSetChangeListener(this);
  946. }
  947. if (items instanceof Container.PropertySetChangeNotifier) {
  948. ((Container.PropertySetChangeNotifier) items)
  949. .removePropertySetChangeListener(this);
  950. }
  951. }
  952. // Assigns new data source
  953. items = newDataSource;
  954. // Clears itemIdMapper also
  955. itemIdMapper.removeAll();
  956. // Adds listeners
  957. if (items != null) {
  958. if (items instanceof Container.ItemSetChangeNotifier) {
  959. ((Container.ItemSetChangeNotifier) items)
  960. .addItemSetChangeListener(this);
  961. }
  962. if (items instanceof Container.PropertySetChangeNotifier) {
  963. ((Container.PropertySetChangeNotifier) items)
  964. .addPropertySetChangeListener(this);
  965. }
  966. }
  967. /*
  968. * We expect changing the data source should also clean value. See
  969. * #810, #4607, #5281
  970. */
  971. setValue(null);
  972. markAsDirty();
  973. }
  974. }
  975. /**
  976. * Gets the viewing data-source container.
  977. *
  978. * @see com.com.vaadin.v7.data.Container.Viewer#getContainerDataSource()
  979. */
  980. @Override
  981. public Container getContainerDataSource() {
  982. return items;
  983. }
  984. /* Select attributes */
  985. /**
  986. * Is the select in multiselect mode? In multiselect mode
  987. *
  988. * @return the Value of property multiSelect.
  989. */
  990. public boolean isMultiSelect() {
  991. return getState(false).multiSelect;
  992. }
  993. /**
  994. * Sets the multiselect mode. Setting multiselect mode false may lose
  995. * selection information: if selected items set contains one or more
  996. * selected items, only one of the selected items is kept as selected.
  997. *
  998. * Subclasses of AbstractSelect can choose not to support changing the
  999. * multiselect mode, and may throw {@link UnsupportedOperationException}.
  1000. *
  1001. * @param multiSelect
  1002. * the New value of property multiSelect.
  1003. */
  1004. public void setMultiSelect(boolean multiSelect) {
  1005. if (multiSelect && getNullSelectionItemId() != null) {
  1006. throw new IllegalStateException(
  1007. "Multiselect and NullSelectionItemId can not be set at the same time.");
  1008. }
  1009. if (multiSelect != getState(false).multiSelect) {
  1010. // Selection before mode change
  1011. final Object oldValue = getValue();
  1012. getState().multiSelect = multiSelect;
  1013. // Convert the value type
  1014. if (multiSelect) {
  1015. final Set<Object> s = new HashSet<Object>();
  1016. if (oldValue != null) {
  1017. s.add(oldValue);
  1018. }
  1019. setValue(s);
  1020. } else {
  1021. final Set<?> s = (Set<?>) oldValue;
  1022. if (s == null || s.isEmpty()) {
  1023. setValue(null);
  1024. } else {
  1025. // Set the single select to contain only the first
  1026. // selected value in the multiselect
  1027. setValue(s.iterator().next());
  1028. }
  1029. }
  1030. markAsDirty();
  1031. }
  1032. }
  1033. /**
  1034. * Does the select allow adding new options by the user. If true, the new
  1035. * options can be added to the Container. The text entered by the user is
  1036. * used as id. Note that data-source must allow adding new items.
  1037. *
  1038. * @return True if additions are allowed.
  1039. */
  1040. public boolean isNewItemsAllowed() {
  1041. return allowNewOptions;
  1042. }
  1043. /**
  1044. * Enables or disables possibility to add new options by the user.
  1045. *
  1046. * @param allowNewOptions
  1047. * the New value of property allowNewOptions.
  1048. */
  1049. public void setNewItemsAllowed(boolean allowNewOptions) {
  1050. // Only handle change requests
  1051. if (this.allowNewOptions != allowNewOptions) {
  1052. this.allowNewOptions = allowNewOptions;
  1053. markAsDirty();
  1054. }
  1055. }
  1056. /**
  1057. * Override the caption of an item. Setting caption explicitly overrides id,
  1058. * item and index captions.
  1059. *
  1060. * @param itemId
  1061. * the id of the item to be recaptioned.
  1062. * @param caption
  1063. * the New caption.
  1064. */
  1065. public void setItemCaption(Object itemId, String caption) {
  1066. if (itemId != null) {
  1067. itemCaptions.put(itemId, caption);
  1068. markAsDirty();
  1069. }
  1070. }
  1071. /**
  1072. * Gets the caption of an item. The caption is generated as specified by the
  1073. * item caption mode. See <code>setItemCaptionMode()</code> for more
  1074. * details.
  1075. *
  1076. * @param itemId
  1077. * the id of the item to be queried.
  1078. * @return the caption for specified item.
  1079. */
  1080. public String getItemCaption(Object itemId) {
  1081. // Null items can not be found
  1082. if (itemId == null) {
  1083. return null;
  1084. }
  1085. String caption = null;
  1086. switch (getItemCaptionMode()) {
  1087. case ID:
  1088. caption = idToCaption(itemId);
  1089. break;
  1090. case ID_TOSTRING:
  1091. caption = itemId.toString();
  1092. break;
  1093. case INDEX:
  1094. if (items instanceof Container.Indexed) {
  1095. caption = String
  1096. .valueOf(((Container.Indexed) items).indexOfId(itemId));
  1097. } else {
  1098. caption = "ERROR: Container is not indexed";
  1099. }
  1100. break;
  1101. case ITEM:
  1102. final Item i = getItem(itemId);
  1103. if (i != null) {
  1104. caption = i.toString();
  1105. }
  1106. break;
  1107. case EXPLICIT:
  1108. caption = itemCaptions.get(itemId);
  1109. break;
  1110. case EXPLICIT_DEFAULTS_ID:
  1111. caption = itemCaptions.get(itemId);
  1112. if (caption == null) {
  1113. caption = idToCaption(itemId);
  1114. }
  1115. break;
  1116. case PROPERTY:
  1117. final Property<?> p = getContainerProperty(itemId,
  1118. getItemCaptionPropertyId());
  1119. if (p != null) {
  1120. Object value = p.getValue();
  1121. if (value != null) {
  1122. caption = value.toString();
  1123. }
  1124. }
  1125. break;
  1126. }
  1127. // All items must have some captions
  1128. return caption != null ? caption : "";
  1129. }
  1130. private String idToCaption(Object itemId) {
  1131. try {
  1132. Converter<String, Object> c = (Converter<String, Object>) ConverterUtil
  1133. .getConverter(String.class, itemId.getClass(),
  1134. getSession());
  1135. return ConverterUtil.convertFromModel(itemId, String.class, c,
  1136. getLocale());
  1137. } catch (Exception e) {
  1138. return itemId.toString();
  1139. }
  1140. }
  1141. /**
  1142. * Sets the icon for an item.
  1143. *
  1144. * @param itemId
  1145. * the id of the item to be assigned an icon.
  1146. * @param icon
  1147. * the icon to use or null.
  1148. */
  1149. public void setItemIcon(Object itemId, Resource icon) {
  1150. if (itemId != null) {
  1151. if (icon == null) {
  1152. itemIcons.remove(itemId);
  1153. } else {
  1154. itemIcons.put(itemId, icon);
  1155. }
  1156. markAsDirty();
  1157. }
  1158. }
  1159. /**
  1160. * Gets the item icon.
  1161. *
  1162. * @param itemId
  1163. * the id of the item to be assigned an icon.
  1164. * @return the icon for the item or null, if not specified.
  1165. */
  1166. public Resource getItemIcon(Object itemId) {
  1167. final Resource explicit = itemIcons.get(itemId);
  1168. if (explicit != null) {
  1169. return explicit;
  1170. }
  1171. if (getItemIconPropertyId() == null) {
  1172. return null;
  1173. }
  1174. final Property<?> ip = getContainerProperty(itemId,
  1175. getItemIconPropertyId());
  1176. if (ip == null) {
  1177. return null;
  1178. }
  1179. final Object icon = ip.getValue();
  1180. if (icon instanceof Resource) {
  1181. return (Resource) icon;
  1182. }
  1183. return null;
  1184. }
  1185. /**
  1186. * Sets the item caption mode.
  1187. *
  1188. * See {@link ItemCaptionMode} for a description of the modes.
  1189. * <p>
  1190. * {@link ItemCaptionMode#EXPLICIT_DEFAULTS_ID} is the default mode.
  1191. * </p>
  1192. *
  1193. * @param mode
  1194. * the One of the modes listed above.
  1195. */
  1196. public void setItemCaptionMode(ItemCaptionMode mode) {
  1197. if (mode != null) {
  1198. itemCaptionMode = mode;
  1199. markAsDirty();
  1200. }
  1201. }
  1202. /**
  1203. * Gets the item caption mode.
  1204. *
  1205. * <p>
  1206. * The mode can be one of the following ones:
  1207. * <ul>
  1208. * <li><code>ITEM_CAPTION_MODE_EXPLICIT_DEFAULTS_ID</code> : Items
  1209. * Id-objects <code>toString</code> is used as item caption. If caption is
  1210. * explicitly specified, it overrides the id-caption.
  1211. * <li><code>ITEM_CAPTION_MODE_ID</code> : Items Id-objects
  1212. * <code>toString</code> is used as item caption.</li>
  1213. * <li><code>ITEM_CAPTION_MODE_ITEM</code> : Item-objects
  1214. * <code>toString</code> is used as item caption.</li>
  1215. * <li><code>ITEM_CAPTION_MODE_INDEX</code> : The index of the item is used
  1216. * as item caption. The index mode can only be used with the containers
  1217. * implementing <code>Container.Indexed</code> interface.</li>
  1218. * <li><code>ITEM_CAPTION_MODE_EXPLICIT</code> : The item captions must be
  1219. * explicitly specified.</li>
  1220. * <li><code>ITEM_CAPTION_MODE_PROPERTY</code> : The item captions are read
  1221. * from property, that must be specified with
  1222. * <code>setItemCaptionPropertyId</code>.</li>
  1223. * </ul>
  1224. * The <code>ITEM_CAPTION_MODE_EXPLICIT_DEFAULTS_ID</code> is the default
  1225. * mode.
  1226. * </p>
  1227. *
  1228. * @return the One of the modes listed above.
  1229. */
  1230. public ItemCaptionMode getItemCaptionMode() {
  1231. return itemCaptionMode;
  1232. }
  1233. /**
  1234. * Sets the item caption property.
  1235. *
  1236. * <p>
  1237. * Setting the id to a existing property implicitly sets the item caption
  1238. * mode to <code>ITEM_CAPTION_MODE_PROPERTY</code>. If the object is in
  1239. * <code>ITEM_CAPTION_MODE_PROPERTY</code> mode, setting caption property id
  1240. * null resets the item caption mode to
  1241. * <code>ITEM_CAPTION_EXPLICIT_DEFAULTS_ID</code>.
  1242. * </p>
  1243. * <p>
  1244. * Note that the type of the property used for caption must be String
  1245. * </p>
  1246. * <p>
  1247. * Setting the property id to null disables this feature. The id is null by
  1248. * default
  1249. * </p>
  1250. * .
  1251. *
  1252. * @param propertyId
  1253. * the id of the property.
  1254. *
  1255. */
  1256. public void setItemCaptionPropertyId(Object propertyId) {
  1257. if (propertyId != null) {
  1258. itemCaptionPropertyId = propertyId;
  1259. setItemCaptionMode(ITEM_CAPTION_MODE_PROPERTY);
  1260. markAsDirty();
  1261. } else {
  1262. itemCaptionPropertyId = null;
  1263. if (getItemCaptionMode() == ITEM_CAPTION_MODE_PROPERTY) {
  1264. setItemCaptionMode(ITEM_CAPTION_MODE_EXPLICIT_DEFAULTS_ID);
  1265. }
  1266. markAsDirty();
  1267. }
  1268. }
  1269. /**
  1270. * Gets the item caption property.
  1271. *
  1272. * @return the Id of the property used as item caption source.
  1273. */
  1274. public Object getItemCaptionPropertyId() {
  1275. return itemCaptionPropertyId;
  1276. }
  1277. /**
  1278. * Sets the item icon property.
  1279. *
  1280. * <p>
  1281. * If the property id is set to a valid value, each item is given an icon
  1282. * got from the given property of the items. The type of the property must
  1283. * be assignable to Resource.
  1284. * </p>
  1285. *
  1286. * <p>
  1287. * Note : The icons set with <code>setItemIcon</code> function override the
  1288. * icons from the property.
  1289. * </p>
  1290. *
  1291. * <p>
  1292. * Setting the property id to null disables this feature. The id is null by
  1293. * default
  1294. * </p>
  1295. * .
  1296. *
  1297. * @param propertyId
  1298. * the id of the property that specifies icons for items or null
  1299. * @throws IllegalArgumentException
  1300. * If the propertyId is not in the container or is not of a
  1301. * valid type
  1302. */
  1303. public void setItemIconPropertyId(Object propertyId)
  1304. throws IllegalArgumentException {
  1305. if (propertyId == null) {
  1306. itemIconPropertyId = null;
  1307. } else if (!getContainerPropertyIds().contains(propertyId)) {
  1308. throw new IllegalArgumentException(
  1309. "Property id not found in the container");
  1310. } else if (Resource.class.isAssignableFrom(getType(propertyId))) {
  1311. itemIconPropertyId = propertyId;
  1312. } else {
  1313. throw new IllegalArgumentException(
  1314. "Property type must be assignable to Resource");
  1315. }
  1316. markAsDirty();
  1317. }
  1318. /**
  1319. * Gets the item icon property.
  1320. *
  1321. * <p>
  1322. * If the property id is set to a valid value, each item is given an icon
  1323. * got from the given property of the items. The type of the property must
  1324. * be assignable to Icon.
  1325. * </p>
  1326. *
  1327. * <p>
  1328. * Note : The icons set with <code>setItemIcon</code> function override the
  1329. * icons from the property.
  1330. * </p>
  1331. *
  1332. * <p>
  1333. * Setting the property id to null disables this feature. The id is null by
  1334. * default
  1335. * </p>
  1336. * .
  1337. *
  1338. * @return the Id of the property containing the item icons.
  1339. */
  1340. public Object getItemIconPropertyId() {
  1341. return itemIconPropertyId;
  1342. }
  1343. /**
  1344. * Tests if an item is selected.
  1345. *
  1346. * <p>
  1347. * In single select mode testing selection status of the item identified by
  1348. * {@link #getNullSelectionItemId()} returns true if the value of the
  1349. * property is null.
  1350. * </p>
  1351. *
  1352. * @param itemId
  1353. * the Id the of the item to be tested.
  1354. * @see #getNullSelectionItemId()
  1355. * @see #setNullSelectionItemId(Object)
  1356. *
  1357. */
  1358. public boolean isSelected(Object itemId) {
  1359. if (itemId == null) {
  1360. return false;
  1361. }
  1362. if (isMultiSelect()) {
  1363. return ((Set<?>) getValue()).contains(itemId);
  1364. } else {
  1365. final Object value = getValue();
  1366. return itemId
  1367. .equals(value == null ? getNullSelectionItemId() : value);
  1368. }
  1369. }
  1370. /**
  1371. * Selects an item.
  1372. *
  1373. * <p>
  1374. * In single select mode selecting item identified by
  1375. * {@link #getNullSelectionItemId()} sets the value of the property to null.
  1376. * </p>
  1377. *
  1378. * @param itemId
  1379. * the identifier of Item to be selected.
  1380. * @see #getNullSelectionItemId()
  1381. * @see #setNullSelectionItemId(Object)
  1382. *
  1383. */
  1384. public void select(Object itemId) {
  1385. if (!isMultiSelect()) {
  1386. setValue(itemId);
  1387. } else if (!isSelected(itemId) && itemId != null
  1388. && items.containsId(itemId)) {
  1389. final Set<Object> s = new HashSet<Object>((Set<?>) getValue());
  1390. s.add(itemId);
  1391. setValue(s);
  1392. }
  1393. }
  1394. /**
  1395. * Unselects an item.
  1396. *
  1397. * @param itemId
  1398. * the identifier of the Item to be unselected.
  1399. * @see #getNullSelectionItemId()
  1400. * @see #setNullSelectionItemId(Object)
  1401. *
  1402. */
  1403. public void unselect(Object itemId) {
  1404. if (isSelected(itemId)) {
  1405. if (isMultiSelect()) {
  1406. final Set<Object> s = new HashSet<Object>((Set<?>) getValue());
  1407. s.remove(itemId);
  1408. setValue(s);
  1409. } else {
  1410. setValue(null);
  1411. }
  1412. }
  1413. }
  1414. /**
  1415. * Notifies this listener that the Containers contents has changed.
  1416. *
  1417. * @see com.com.vaadin.v7.data.Container.PropertySetChangeListener#containerPropertySetChange(com.com.vaadin.v7.data.Container.PropertySetChangeEvent)
  1418. */
  1419. @Override
  1420. public void containerPropertySetChange(
  1421. Container.PropertySetChangeEvent event) {
  1422. firePropertySetChange();
  1423. }
  1424. /**
  1425. * Adds a new Property set change listener for this Container.
  1426. *
  1427. * @see com.com.vaadin.v7.data.Container.PropertySetChangeNotifier#addListener(com.com.vaadin.v7.data.Container.PropertySetChangeListener)
  1428. */
  1429. @Override
  1430. public void addPropertySetChangeListener(
  1431. Container.PropertySetChangeListener listener) {
  1432. if (propertySetEventListeners == null) {
  1433. propertySetEventListeners = new LinkedHashSet<Container.PropertySetChangeListener>();
  1434. }
  1435. propertySetEventListeners.add(listener);
  1436. }
  1437. /**
  1438. * @deprecated As of 7.0, replaced by
  1439. * {@link #addPropertySetChangeListener(com.com.vaadin.v7.data.Container.PropertySetChangeListener)}
  1440. **/
  1441. @Override
  1442. @Deprecated
  1443. public void addListener(Container.PropertySetChangeListener listener) {
  1444. addPropertySetChangeListener(listener);
  1445. }
  1446. /**
  1447. * Removes a previously registered Property set change listener.
  1448. *
  1449. * @see com.com.vaadin.v7.data.Container.PropertySetChangeNotifier#removeListener(com.com.vaadin.v7.data.Container.PropertySetChangeListener)
  1450. */
  1451. @Override
  1452. public void removePropertySetChangeListener(
  1453. Container.PropertySetChangeListener listener) {
  1454. if (propertySetEventListeners != null) {
  1455. propertySetEventListeners.remove(listener);
  1456. if (propertySetEventListeners.isEmpty()) {
  1457. propertySetEventListeners = null;
  1458. }
  1459. }
  1460. }
  1461. /**
  1462. * @deprecated As of 7.0, replaced by
  1463. * {@link #removePropertySetChangeListener(com.com.vaadin.v7.data.Container.PropertySetChangeListener)}
  1464. **/
  1465. @Override
  1466. @Deprecated
  1467. public void removeListener(Container.PropertySetChangeListener listener) {
  1468. removePropertySetChangeListener(listener);
  1469. }
  1470. /**
  1471. * Adds an Item set change listener for the object.
  1472. *
  1473. * @see com.com.vaadin.v7.data.Container.ItemSetChangeNotifier#addListener(com.com.vaadin.v7.data.Container.ItemSetChangeListener)
  1474. */
  1475. @Override
  1476. public void addItemSetChangeListener(
  1477. Container.ItemSetChangeListener listener) {
  1478. if (itemSetEventListeners == null) {
  1479. itemSetEventListeners = new LinkedHashSet<Container.ItemSetChangeListener>();
  1480. }
  1481. itemSetEventListeners.add(listener);
  1482. }
  1483. /**
  1484. * @deprecated As of 7.0, replaced by
  1485. * {@link #addItemSetChangeListener(com.com.vaadin.v7.data.Container.ItemSetChangeListener)}
  1486. **/
  1487. @Override
  1488. @Deprecated
  1489. public void addListener(Container.ItemSetChangeListener listener) {
  1490. addItemSetChangeListener(listener);
  1491. }
  1492. /**
  1493. * Removes the Item set change listener from the object.
  1494. *
  1495. * @see com.com.vaadin.v7.data.Container.ItemSetChangeNotifier#removeListener(com.com.vaadin.v7.data.Container.ItemSetChangeListener)
  1496. */
  1497. @Override
  1498. public void removeItemSetChangeListener(
  1499. Container.ItemSetChangeListener listener) {
  1500. if (itemSetEventListeners != null) {
  1501. itemSetEventListeners.remove(listener);
  1502. if (itemSetEventListeners.isEmpty()) {
  1503. itemSetEventListeners = null;
  1504. }
  1505. }
  1506. }
  1507. /**
  1508. * @deprecated As of 7.0, replaced by
  1509. * {@link #removeItemSetChangeListener(com.com.vaadin.v7.data.Container.ItemSetChangeListener)}
  1510. **/
  1511. @Override
  1512. @Deprecated
  1513. public void removeListener(Container.ItemSetChangeListener listener) {
  1514. removeItemSetChangeListener(listener);
  1515. }
  1516. @Override
  1517. public Collection<?> getListeners(Class<?> eventType) {
  1518. if (Container.ItemSetChangeEvent.class.isAssignableFrom(eventType)) {
  1519. if (itemSetEventListeners == null) {
  1520. return Collections.EMPTY_LIST;
  1521. } else {
  1522. return Collections
  1523. .unmodifiableCollection(itemSetEventListeners);
  1524. }
  1525. } else if (Container.PropertySetChangeEvent.class
  1526. .isAssignableFrom(eventType)) {
  1527. if (propertySetEventListeners == null) {
  1528. return Collections.EMPTY_LIST;
  1529. } else {
  1530. return Collections
  1531. .unmodifiableCollection(propertySetEventListeners);
  1532. }
  1533. }
  1534. return super.getListeners(eventType);
  1535. }
  1536. /**
  1537. * Lets the listener know a Containers Item set has changed.
  1538. *
  1539. * @see com.com.vaadin.v7.data.Container.ItemSetChangeListener#containerItemSetChange(com.com.vaadin.v7.data.Container.ItemSetChangeEvent)
  1540. */
  1541. @Override
  1542. public void containerItemSetChange(Container.ItemSetChangeEvent event) {
  1543. // Clears the item id mapping table
  1544. itemIdMapper.removeAll();
  1545. // Notify all listeners
  1546. fireItemSetChange();
  1547. }
  1548. /**
  1549. * Fires the property set change event.
  1550. */
  1551. protected void firePropertySetChange() {
  1552. if (propertySetEventListeners != null
  1553. && !propertySetEventListeners.isEmpty()) {
  1554. final Container.PropertySetChangeEvent event = new PropertySetChangeEvent(
  1555. this);
  1556. final Object[] listeners = propertySetEventListeners.toArray();
  1557. for (int i = 0; i < listeners.length; i++) {
  1558. ((Container.PropertySetChangeListener) listeners[i])
  1559. .containerPropertySetChange(event);
  1560. }
  1561. }
  1562. markAsDirty();
  1563. }
  1564. /**
  1565. * Fires the item set change event.
  1566. */
  1567. protected void fireItemSetChange() {
  1568. if (itemSetEventListeners != null && !itemSetEventListeners.isEmpty()) {
  1569. final Container.ItemSetChangeEvent event = new ItemSetChangeEvent(
  1570. this);
  1571. final Object[] listeners = itemSetEventListeners.toArray();
  1572. for (int i = 0; i < listeners.length; i++) {
  1573. ((Container.ItemSetChangeListener) listeners[i])
  1574. .containerItemSetChange(event);
  1575. }
  1576. }
  1577. markAsDirty();
  1578. }
  1579. /**
  1580. * Implementation of item set change event.
  1581. */
  1582. private static class ItemSetChangeEvent extends EventObject
  1583. implements Serializable, Container.ItemSetChangeEvent {
  1584. private ItemSetChangeEvent(Container source) {
  1585. super(source);
  1586. }
  1587. /**
  1588. * Gets the Property where the event occurred.
  1589. *
  1590. * @see com.com.vaadin.v7.data.Container.ItemSetChangeEvent#getContainer()
  1591. */
  1592. @Override
  1593. public Container getContainer() {
  1594. return (Container) getSource();
  1595. }
  1596. }
  1597. /**
  1598. * Implementation of property set change event.
  1599. */
  1600. private static class PropertySetChangeEvent extends EventObject
  1601. implements Container.PropertySetChangeEvent, Serializable {
  1602. private PropertySetChangeEvent(Container source) {
  1603. super(source);
  1604. }
  1605. /**
  1606. * Retrieves the Container whose contents have been modified.
  1607. *
  1608. * @see com.com.vaadin.v7.data.Container.PropertySetChangeEvent#getContainer()
  1609. */
  1610. @Override
  1611. public Container getContainer() {
  1612. return (Container) getSource();
  1613. }
  1614. }
  1615. /**
  1616. * For multi-selectable fields, also an empty collection of values is
  1617. * considered to be an empty field.
  1618. *
  1619. * @see LegacyAbstractField#isEmpty().
  1620. */
  1621. @Override
  1622. public boolean isEmpty() {
  1623. if (!isMultiSelect()) {
  1624. return super.isEmpty();
  1625. } else {
  1626. Object value = getValue();
  1627. return super.isEmpty() || (value instanceof Collection
  1628. && ((Collection<?>) value).isEmpty());
  1629. }
  1630. }
  1631. /**
  1632. * Allow or disallow empty selection by the user. If the select is in
  1633. * single-select mode, you can make an item represent the empty selection by
  1634. * calling <code>setNullSelectionItemId()</code>. This way you can for
  1635. * instance set an icon and caption for the null selection item.
  1636. *
  1637. * @param nullSelectionAllowed
  1638. * whether or not to allow empty selection
  1639. * @see #setNullSelectionItemId(Object)
  1640. * @see #isNullSelectionAllowed()
  1641. */
  1642. public void setNullSelectionAllowed(boolean nullSelectionAllowed) {
  1643. if (nullSelectionAllowed != this.nullSelectionAllowed) {
  1644. this.nullSelectionAllowed = nullSelectionAllowed;
  1645. markAsDirty();
  1646. }
  1647. }
  1648. /**
  1649. * Checks if null empty selection is allowed by the user.
  1650. *
  1651. * @return whether or not empty selection is allowed
  1652. * @see #setNullSelectionAllowed(boolean)
  1653. */
  1654. public boolean isNullSelectionAllowed() {
  1655. return nullSelectionAllowed;
  1656. }
  1657. /**
  1658. * Returns the item id that represents null value of this select in single
  1659. * select mode.
  1660. *
  1661. * <p>
  1662. * Data interface does not support nulls as item ids. Selecting the item
  1663. * identified by this id is the same as selecting no items at all. This
  1664. * setting only affects the single select mode.
  1665. * </p>
  1666. *
  1667. * @return the Object Null value item id.
  1668. * @see #setNullSelectionItemId(Object)
  1669. * @see #isSelected(Object)
  1670. * @see #select(Object)
  1671. */
  1672. public Object getNullSelectionItemId() {
  1673. return nullSelectionItemId;
  1674. }
  1675. /**
  1676. * Sets the item id that represents null value of this select.
  1677. *
  1678. * <p>
  1679. * Data interface does not support nulls as item ids. Selecting the item
  1680. * identified by this id is the same as selecting no items at all. This
  1681. * setting only affects the single select mode.
  1682. * </p>
  1683. *
  1684. * @param nullSelectionItemId
  1685. * the nullSelectionItemId to set.
  1686. * @see #getNullSelectionItemId()
  1687. * @see #isSelected(Object)
  1688. * @see #select(Object)
  1689. */
  1690. public void setNullSelectionItemId(Object nullSelectionItemId) {
  1691. if (nullSelectionItemId != null && isMultiSelect()) {
  1692. throw new IllegalStateException(
  1693. "Multiselect and NullSelectionItemId can not be set at the same time.");
  1694. }
  1695. this.nullSelectionItemId = nullSelectionItemId;
  1696. }
  1697. /**
  1698. * Notifies the component that it is connected to an application.
  1699. *
  1700. * @see com.vaadin.v7.ui.AbstractField#attach()
  1701. */
  1702. @Override
  1703. public void attach() {
  1704. super.attach();
  1705. }
  1706. /**
  1707. * Detaches the component from application.
  1708. *
  1709. * @see com.vaadin.ui.AbstractComponent#detach()
  1710. */
  1711. @Override
  1712. public void detach() {
  1713. getCaptionChangeListener().clear();
  1714. super.detach();
  1715. }
  1716. // Caption change listener
  1717. protected CaptionChangeListener getCaptionChangeListener() {
  1718. if (captionChangeListener == null) {
  1719. captionChangeListener = new CaptionChangeListener();
  1720. }
  1721. return captionChangeListener;
  1722. }
  1723. /**
  1724. * This is a listener helper for Item and Property changes that should cause
  1725. * a repaint. It should be attached to all items that are displayed, and the
  1726. * default implementation does this in paintContent(). Especially
  1727. * "lazyloading" components should take care to add and remove listeners as
  1728. * appropriate. Call addNotifierForItem() for each painted item (and
  1729. * remember to clear).
  1730. *
  1731. * NOTE: singleton, use getCaptionChangeListener().
  1732. *
  1733. */
  1734. protected class CaptionChangeListener implements
  1735. Item.PropertySetChangeListener, Property.ValueChangeListener {
  1736. // TODO clean this up - type is either Item.PropertySetChangeNotifier or
  1737. // Property.ValueChangeNotifier
  1738. HashSet<Object> captionChangeNotifiers = new HashSet<Object>();
  1739. public void addNotifierForItem(Object itemId) {
  1740. switch (getItemCaptionMode()) {
  1741. case ITEM:
  1742. final Item i = getItem(itemId);
  1743. if (i == null) {
  1744. return;
  1745. }
  1746. if (i instanceof Item.PropertySetChangeNotifier) {
  1747. ((Item.PropertySetChangeNotifier) i)
  1748. .addPropertySetChangeListener(
  1749. getCaptionChangeListener());
  1750. captionChangeNotifiers.add(i);
  1751. }
  1752. Collection<?> pids = i.getItemPropertyIds();
  1753. if (pids != null) {
  1754. for (Iterator<?> it = pids.iterator(); it.hasNext();) {
  1755. Property<?> p = i.getItemProperty(it.next());
  1756. if (p != null
  1757. && p instanceof Property.ValueChangeNotifier) {
  1758. ((Property.ValueChangeNotifier) p)
  1759. .addValueChangeListener(
  1760. getCaptionChangeListener());
  1761. captionChangeNotifiers.add(p);
  1762. }
  1763. }
  1764. }
  1765. break;
  1766. case PROPERTY:
  1767. final Property<?> p = getContainerProperty(itemId,
  1768. getItemCaptionPropertyId());
  1769. if (p != null && p instanceof Property.ValueChangeNotifier) {
  1770. ((Property.ValueChangeNotifier) p)
  1771. .addValueChangeListener(getCaptionChangeListener());
  1772. captionChangeNotifiers.add(p);
  1773. }
  1774. break;
  1775. }
  1776. if (getItemIconPropertyId() != null) {
  1777. final Property p = getContainerProperty(itemId,
  1778. getItemIconPropertyId());
  1779. if (p != null && p instanceof Property.ValueChangeNotifier) {
  1780. ((Property.ValueChangeNotifier) p)
  1781. .addValueChangeListener(getCaptionChangeListener());
  1782. captionChangeNotifiers.add(p);
  1783. }
  1784. }
  1785. }
  1786. public void clear() {
  1787. for (Iterator<Object> it = captionChangeNotifiers.iterator(); it
  1788. .hasNext();) {
  1789. Object notifier = it.next();
  1790. if (notifier instanceof Item.PropertySetChangeNotifier) {
  1791. ((Item.PropertySetChangeNotifier) notifier)
  1792. .removePropertySetChangeListener(
  1793. getCaptionChangeListener());
  1794. } else {
  1795. ((Property.ValueChangeNotifier) notifier)
  1796. .removeValueChangeListener(
  1797. getCaptionChangeListener());
  1798. }
  1799. }
  1800. captionChangeNotifiers.clear();
  1801. }
  1802. @Override
  1803. public void valueChange(
  1804. com.vaadin.v7.data.Property.ValueChangeEvent event) {
  1805. markAsDirty();
  1806. }
  1807. @Override
  1808. public void itemPropertySetChange(
  1809. com.vaadin.v7.data.Item.PropertySetChangeEvent event) {
  1810. markAsDirty();
  1811. }
  1812. }
  1813. /**
  1814. * Criterion which accepts a drop only if the drop target is (one of) the
  1815. * given Item identifier(s). Criterion can be used only on a drop targets
  1816. * that extends AbstractSelect like {@link Table} and {@link Tree}. The
  1817. * target and identifiers of valid Items are given in constructor.
  1818. *
  1819. * @since 6.3
  1820. */
  1821. public static class TargetItemIs extends AbstractItemSetCriterion {
  1822. /**
  1823. * @param select
  1824. * the select implementation that is used as a drop target
  1825. * @param itemId
  1826. * the identifier(s) that are valid drop locations
  1827. */
  1828. public TargetItemIs(AbstractSelect select, Object... itemId) {
  1829. super(select, itemId);
  1830. }
  1831. @Override
  1832. public boolean accept(DragAndDropEvent dragEvent) {
  1833. AbstractSelectTargetDetails dropTargetData = (AbstractSelectTargetDetails) dragEvent
  1834. .getTargetDetails();
  1835. if (dropTargetData.getTarget() != select) {
  1836. return false;
  1837. }
  1838. return itemIds.contains(dropTargetData.getItemIdOver());
  1839. }
  1840. }
  1841. /**
  1842. * Abstract helper class to implement item id based criterion.
  1843. *
  1844. * Note, inner class used not to open itemIdMapper for public access.
  1845. *
  1846. * @since 6.3
  1847. *
  1848. */
  1849. private static abstract class AbstractItemSetCriterion
  1850. extends ClientSideCriterion {
  1851. protected final Collection<Object> itemIds = new HashSet<Object>();
  1852. protected AbstractSelect select;
  1853. public AbstractItemSetCriterion(AbstractSelect select,
  1854. Object... itemId) {
  1855. if (itemIds == null || select == null) {
  1856. throw new IllegalArgumentException(
  1857. "Accepted item identifiers must be accepted.");
  1858. }
  1859. Collections.addAll(itemIds, itemId);
  1860. this.select = select;
  1861. }
  1862. @Override
  1863. public void paintContent(PaintTarget target) throws PaintException {
  1864. super.paintContent(target);
  1865. String[] keys = new String[itemIds.size()];
  1866. int i = 0;
  1867. for (Object itemId : itemIds) {
  1868. String key = select.itemIdMapper.key(itemId);
  1869. keys[i++] = key;
  1870. }
  1871. target.addAttribute("keys", keys);
  1872. target.addAttribute("s", select);
  1873. }
  1874. }
  1875. /**
  1876. * This criterion accepts a only a {@link Transferable} that contains given
  1877. * Item (practically its identifier) from a specific AbstractSelect.
  1878. *
  1879. * @since 6.3
  1880. */
  1881. public static class AcceptItem extends AbstractItemSetCriterion {
  1882. /**
  1883. * @param select
  1884. * the select from which the item id's are checked
  1885. * @param itemId
  1886. * the item identifier(s) of the select that are accepted
  1887. */
  1888. public AcceptItem(AbstractSelect select, Object... itemId) {
  1889. super(select, itemId);
  1890. }
  1891. @Override
  1892. public boolean accept(DragAndDropEvent dragEvent) {
  1893. DataBoundTransferable transferable = (DataBoundTransferable) dragEvent
  1894. .getTransferable();
  1895. if (transferable.getSourceComponent() != select) {
  1896. return false;
  1897. }
  1898. return itemIds.contains(transferable.getItemId());
  1899. }
  1900. /**
  1901. * A simple accept criterion which ensures that {@link Transferable}
  1902. * contains an {@link Item} (or actually its identifier). In other words
  1903. * the criterion check that drag is coming from a {@link Container} like
  1904. * {@link Tree} or {@link Table}.
  1905. */
  1906. public static final ClientSideCriterion ALL = new ContainsDataFlavor(
  1907. "itemId");
  1908. }
  1909. /**
  1910. * TargetDetails implementation for subclasses of {@link AbstractSelect}
  1911. * that implement {@link DropTarget}.
  1912. *
  1913. * @since 6.3
  1914. */
  1915. public class AbstractSelectTargetDetails extends TargetDetailsImpl {
  1916. /**
  1917. * The item id over which the drag event happened.
  1918. */
  1919. protected Object idOver;
  1920. /**
  1921. * Constructor that automatically converts itemIdOver key to
  1922. * corresponding item Id
  1923. *
  1924. */
  1925. protected AbstractSelectTargetDetails(
  1926. Map<String, Object> rawVariables) {
  1927. super(rawVariables, (DropTarget) AbstractSelect.this);
  1928. // eagar fetch itemid, mapper may be emptied
  1929. String keyover = (String) getData("itemIdOver");
  1930. if (keyover != null) {
  1931. idOver = itemIdMapper.get(keyover);
  1932. }
  1933. }
  1934. /**
  1935. * If the drag operation is currently over an {@link Item}, this method
  1936. * returns the identifier of that {@link Item}.
  1937. *
  1938. */
  1939. public Object getItemIdOver() {
  1940. return idOver;
  1941. }
  1942. /**
  1943. * Returns a detailed vertical location where the drop happened on Item.
  1944. */
  1945. public VerticalDropLocation getDropLocation() {
  1946. String detail = (String) getData("detail");
  1947. if (detail == null) {
  1948. return null;
  1949. }
  1950. return VerticalDropLocation.valueOf(detail);
  1951. }
  1952. }
  1953. /**
  1954. * An accept criterion to accept drops only on a specific vertical location
  1955. * of an item.
  1956. * <p>
  1957. * This accept criterion is currently usable in Tree and Table
  1958. * implementations.
  1959. */
  1960. public static class VerticalLocationIs extends TargetDetailIs {
  1961. public static VerticalLocationIs TOP = new VerticalLocationIs(
  1962. VerticalDropLocation.TOP);
  1963. public static VerticalLocationIs BOTTOM = new VerticalLocationIs(
  1964. VerticalDropLocation.BOTTOM);
  1965. public static VerticalLocationIs MIDDLE = new VerticalLocationIs(
  1966. VerticalDropLocation.MIDDLE);
  1967. private VerticalLocationIs(VerticalDropLocation l) {
  1968. super("detail", l.name());
  1969. }
  1970. }
  1971. /**
  1972. * Implement this interface and pass it to Tree.setItemDescriptionGenerator
  1973. * or Table.setItemDescriptionGenerator to generate mouse over descriptions
  1974. * ("tooltips") for the rows and cells in Table or for the items in Tree.
  1975. */
  1976. public interface ItemDescriptionGenerator extends Serializable {
  1977. /**
  1978. * Called by Table when a cell (and row) is painted or a item is painted
  1979. * in Tree
  1980. *
  1981. * @param source
  1982. * The source of the generator, the Tree or Table the
  1983. * generator is attached to
  1984. * @param itemId
  1985. * The itemId of the painted cell
  1986. * @param propertyId
  1987. * The propertyId of the cell, null when getting row
  1988. * description
  1989. * @return The description or "tooltip" of the item.
  1990. */
  1991. public String generateDescription(Component source, Object itemId,
  1992. Object propertyId);
  1993. }
  1994. @Override
  1995. public void readDesign(Element design, DesignContext context) {
  1996. // handle default attributes
  1997. super.readDesign(design, context);
  1998. // handle children specifying selectable items (<option>)
  1999. readItems(design, context);
  2000. }
  2001. protected void readItems(Element design, DesignContext context) {
  2002. Set<String> selected = new HashSet<String>();
  2003. for (Element child : design.children()) {
  2004. readItem(child, selected, context);
  2005. }
  2006. if (!selected.isEmpty()) {
  2007. if (isMultiSelect()) {
  2008. setValue(selected, false, true);
  2009. } else if (selected.size() == 1) {
  2010. setValue(selected.iterator().next(), false, true);
  2011. } else {
  2012. throw new DesignException(
  2013. "Multiple values selected for a single select component");
  2014. }
  2015. }
  2016. }
  2017. /**
  2018. * Reads an Item from a design and inserts it into the data source.
  2019. * Hierarchical select components should override this method to recursively
  2020. * recursively read any child items as well.
  2021. *
  2022. * @since 7.5.0
  2023. * @param child
  2024. * a child element representing the item
  2025. * @param selected
  2026. * A set accumulating selected items. If the item that is read is
  2027. * marked as selected, its item id should be added to this set.
  2028. * @param context
  2029. * the DesignContext instance used in parsing
  2030. * @return the item id of the new item
  2031. *
  2032. * @throws DesignException
  2033. * if the tag name of the {@code child} element is not
  2034. * {@code option}.
  2035. */
  2036. protected Object readItem(Element child, Set<String> selected,
  2037. DesignContext context) {
  2038. if (!"option".equals(child.tagName())) {
  2039. throw new DesignException("Unrecognized child element in "
  2040. + getClass().getSimpleName() + ": " + child.tagName());
  2041. }
  2042. String itemId;
  2043. String caption = DesignFormatter.decodeFromTextNode(child.html());
  2044. if (child.hasAttr("item-id")) {
  2045. itemId = child.attr("item-id");
  2046. addItem(itemId);
  2047. setItemCaption(itemId, caption);
  2048. } else {
  2049. addItem(itemId = caption);
  2050. }
  2051. if (child.hasAttr("icon")) {
  2052. setItemIcon(itemId, DesignAttributeHandler.readAttribute("icon",
  2053. child.attributes(), Resource.class));
  2054. }
  2055. if (child.hasAttr("selected")) {
  2056. selected.add(itemId);
  2057. }
  2058. return itemId;
  2059. }
  2060. @Override
  2061. public void writeDesign(Element design, DesignContext context) {
  2062. // Write default attributes
  2063. super.writeDesign(design, context);
  2064. // Write options if warranted
  2065. if (context.shouldWriteData(this)) {
  2066. writeItems(design, context);
  2067. }
  2068. }
  2069. /**
  2070. * Writes the data source items to a design. Hierarchical select components
  2071. * should override this method to only write the root items.
  2072. *
  2073. * @since 7.5.0
  2074. * @param design
  2075. * the element into which to insert the items
  2076. * @param context
  2077. * the DesignContext instance used in writing
  2078. */
  2079. protected void writeItems(Element design, DesignContext context) {
  2080. for (Object itemId : getItemIds()) {
  2081. writeItem(design, itemId, context);
  2082. }
  2083. }
  2084. /**
  2085. * Writes a data source Item to a design. Hierarchical select components
  2086. * should override this method to recursively write any child items as well.
  2087. *
  2088. * @since 7.5.0
  2089. * @param design
  2090. * the element into which to insert the item
  2091. * @param itemId
  2092. * the id of the item to write
  2093. * @param context
  2094. * the DesignContext instance used in writing
  2095. * @return
  2096. */
  2097. protected Element writeItem(Element design, Object itemId,
  2098. DesignContext context) {
  2099. Element element = design.appendElement("option");
  2100. String caption = getItemCaption(itemId);
  2101. if (caption != null && !caption.equals(itemId.toString())) {
  2102. element.html(DesignFormatter.encodeForTextNode(caption));
  2103. element.attr("item-id", itemId.toString());
  2104. } else {
  2105. element.html(DesignFormatter.encodeForTextNode(itemId.toString()));
  2106. }
  2107. Resource icon = getItemIcon(itemId);
  2108. if (icon != null) {
  2109. DesignAttributeHandler.writeAttribute("icon", element.attributes(),
  2110. icon, null, Resource.class);
  2111. }
  2112. if (isSelected(itemId)) {
  2113. element.attr("selected", "");
  2114. }
  2115. return element;
  2116. }
  2117. @Override
  2118. protected AbstractSelectState getState() {
  2119. return (AbstractSelectState) super.getState();
  2120. }
  2121. @Override
  2122. protected AbstractSelectState getState(boolean markAsDirty) {
  2123. return (AbstractSelectState) super.getState(markAsDirty);
  2124. }
  2125. }