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

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