選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

AbstractSelect.java 75KB

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