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.

Tree.java 46KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553
  1. /*
  2. @ITMillApache2LicenseForJavaFiles@
  3. */
  4. package com.vaadin.ui;
  5. import java.io.Serializable;
  6. import java.lang.reflect.Method;
  7. import java.util.ArrayList;
  8. import java.util.Collection;
  9. import java.util.HashMap;
  10. import java.util.HashSet;
  11. import java.util.Iterator;
  12. import java.util.LinkedHashSet;
  13. import java.util.LinkedList;
  14. import java.util.Map;
  15. import java.util.Set;
  16. import java.util.Stack;
  17. import java.util.StringTokenizer;
  18. import com.vaadin.data.Container;
  19. import com.vaadin.data.Item;
  20. import com.vaadin.data.util.ContainerHierarchicalWrapper;
  21. import com.vaadin.data.util.IndexedContainer;
  22. import com.vaadin.event.Action;
  23. import com.vaadin.event.DataBoundTransferable;
  24. import com.vaadin.event.ItemClickEvent;
  25. import com.vaadin.event.ItemClickEvent.ItemClickListener;
  26. import com.vaadin.event.ItemClickEvent.ItemClickSource;
  27. import com.vaadin.event.Transferable;
  28. import com.vaadin.event.dd.DragAndDropEvent;
  29. import com.vaadin.event.dd.DragSource;
  30. import com.vaadin.event.dd.DropHandler;
  31. import com.vaadin.event.dd.DropTarget;
  32. import com.vaadin.event.dd.TargetDetails;
  33. import com.vaadin.event.dd.acceptcriteria.ClientCriterion;
  34. import com.vaadin.event.dd.acceptcriteria.ClientSideCriterion;
  35. import com.vaadin.event.dd.acceptcriteria.ServerSideCriterion;
  36. import com.vaadin.event.dd.acceptcriteria.TargetDetailIs;
  37. import com.vaadin.terminal.KeyMapper;
  38. import com.vaadin.terminal.PaintException;
  39. import com.vaadin.terminal.PaintTarget;
  40. import com.vaadin.terminal.Resource;
  41. import com.vaadin.terminal.gwt.client.MouseEventDetails;
  42. import com.vaadin.terminal.gwt.client.ui.VTree;
  43. import com.vaadin.terminal.gwt.client.ui.dd.VLazyInitItemIdentifiers;
  44. import com.vaadin.terminal.gwt.client.ui.dd.VTargetInSubtree;
  45. import com.vaadin.terminal.gwt.client.ui.dd.VerticalDropLocation;
  46. import com.vaadin.tools.ReflectTools;
  47. /**
  48. * Tree component. A Tree can be used to select an item (or multiple items) from
  49. * a hierarchical set of items.
  50. *
  51. * @author IT Mill Ltd.
  52. * @version
  53. * @VERSION@
  54. * @since 3.0
  55. */
  56. @SuppressWarnings("serial")
  57. @ClientWidget(VTree.class)
  58. public class Tree extends AbstractSelect implements Container.Hierarchical,
  59. Action.Container, ItemClickSource, DragSource, DropTarget {
  60. /* Private members */
  61. /**
  62. * Set of expanded nodes.
  63. */
  64. private final HashSet<Object> expanded = new HashSet<Object>();
  65. /**
  66. * List of action handlers.
  67. */
  68. private LinkedList<Action.Handler> actionHandlers = null;
  69. /**
  70. * Action mapper.
  71. */
  72. private KeyMapper actionMapper = null;
  73. /**
  74. * Is the tree selectable on the client side.
  75. */
  76. private boolean selectable = true;
  77. /**
  78. * Flag to indicate sub-tree loading
  79. */
  80. private boolean partialUpdate = false;
  81. /**
  82. * Holds a itemId which was recently expanded
  83. */
  84. private Object expandedItemId;
  85. /**
  86. * a flag which indicates initial paint. After this flag set true partial
  87. * updates are allowed.
  88. */
  89. private boolean initialPaint = true;
  90. /**
  91. * Supported drag modes for Tree.
  92. */
  93. public enum TreeDragMode {
  94. /**
  95. * When drag mode is NONE, draggin from Tree is not supported. Browsers
  96. * may still support selecting text/icons from Tree which can initiate
  97. * HTML 5 style drag and drop operation.
  98. */
  99. NONE,
  100. /**
  101. * When drag mode is NODE, users can initiate drag from Tree nodes that
  102. * represent {@link Item}s in from the backed {@link Container}.
  103. */
  104. NODE
  105. // , SUBTREE
  106. }
  107. private TreeDragMode dragMode = TreeDragMode.NONE;
  108. private MultiSelectMode multiSelectMode = MultiSelectMode.DEFAULT;
  109. /* Tree constructors */
  110. /**
  111. * Creates a new empty tree.
  112. */
  113. public Tree() {
  114. }
  115. /**
  116. * Creates a new empty tree with caption.
  117. *
  118. * @param caption
  119. */
  120. public Tree(String caption) {
  121. setCaption(caption);
  122. }
  123. /**
  124. * Creates a new tree with caption and connect it to a Container.
  125. *
  126. * @param caption
  127. * @param dataSource
  128. */
  129. public Tree(String caption, Container dataSource) {
  130. setCaption(caption);
  131. setContainerDataSource(dataSource);
  132. }
  133. /* Expanding and collapsing */
  134. /**
  135. * Check is an item is expanded
  136. *
  137. * @param itemId
  138. * the item id.
  139. * @return true iff the item is expanded.
  140. */
  141. public boolean isExpanded(Object itemId) {
  142. return expanded.contains(itemId);
  143. }
  144. /**
  145. * Expands an item.
  146. *
  147. * @param itemId
  148. * the item id.
  149. * @return True iff the expand operation succeeded
  150. */
  151. public boolean expandItem(Object itemId) {
  152. boolean success = expandItem(itemId, true);
  153. requestRepaint();
  154. return success;
  155. }
  156. /**
  157. * Expands an item.
  158. *
  159. * @param itemId
  160. * the item id.
  161. * @param sendChildTree
  162. * flag to indicate if client needs subtree or not (may be
  163. * cached)
  164. * @return True iff the expand operation succeeded
  165. */
  166. private boolean expandItem(Object itemId, boolean sendChildTree) {
  167. // Succeeds if the node is already expanded
  168. if (isExpanded(itemId)) {
  169. return true;
  170. }
  171. // Nodes that can not have children are not expandable
  172. if (!areChildrenAllowed(itemId)) {
  173. return false;
  174. }
  175. // Expands
  176. expanded.add(itemId);
  177. expandedItemId = itemId;
  178. if (initialPaint) {
  179. requestRepaint();
  180. } else if (sendChildTree) {
  181. requestPartialRepaint();
  182. }
  183. fireExpandEvent(itemId);
  184. return true;
  185. }
  186. @Override
  187. public void requestRepaint() {
  188. super.requestRepaint();
  189. partialUpdate = false;
  190. }
  191. private void requestPartialRepaint() {
  192. super.requestRepaint();
  193. partialUpdate = true;
  194. }
  195. /**
  196. * Expands the items recursively
  197. *
  198. * Expands all the children recursively starting from an item. Operation
  199. * succeeds only if all expandable items are expanded.
  200. *
  201. * @param startItemId
  202. * @return True iff the expand operation succeeded
  203. */
  204. public boolean expandItemsRecursively(Object startItemId) {
  205. boolean result = true;
  206. // Initial stack
  207. final Stack todo = new Stack();
  208. todo.add(startItemId);
  209. // Expands recursively
  210. while (!todo.isEmpty()) {
  211. final Object id = todo.pop();
  212. if (areChildrenAllowed(id) && !expandItem(id, false)) {
  213. result = false;
  214. }
  215. if (hasChildren(id)) {
  216. todo.addAll(getChildren(id));
  217. }
  218. }
  219. requestRepaint();
  220. return result;
  221. }
  222. /**
  223. * Collapses an item.
  224. *
  225. * @param itemId
  226. * the item id.
  227. * @return True iff the collapse operation succeeded
  228. */
  229. public boolean collapseItem(Object itemId) {
  230. // Succeeds if the node is already collapsed
  231. if (!isExpanded(itemId)) {
  232. return true;
  233. }
  234. // Collapse
  235. expanded.remove(itemId);
  236. requestRepaint();
  237. fireCollapseEvent(itemId);
  238. return true;
  239. }
  240. /**
  241. * Collapses the items recursively.
  242. *
  243. * Collapse all the children recursively starting from an item. Operation
  244. * succeeds only if all expandable items are collapsed.
  245. *
  246. * @param startItemId
  247. * @return True iff the collapse operation succeeded
  248. */
  249. public boolean collapseItemsRecursively(Object startItemId) {
  250. boolean result = true;
  251. // Initial stack
  252. final Stack todo = new Stack();
  253. todo.add(startItemId);
  254. // Collapse recursively
  255. while (!todo.isEmpty()) {
  256. final Object id = todo.pop();
  257. if (areChildrenAllowed(id) && !collapseItem(id)) {
  258. result = false;
  259. }
  260. if (hasChildren(id)) {
  261. todo.addAll(getChildren(id));
  262. }
  263. }
  264. return result;
  265. }
  266. /**
  267. * Returns the current selectable state. Selectable determines if the a node
  268. * can be selected on the client side. Selectable does not affect
  269. * {@link #setValue(Object)} or {@link #select(Object)}.
  270. *
  271. * <p>
  272. * The tree is selectable by default.
  273. * </p>
  274. *
  275. * @return the current selectable state.
  276. */
  277. public boolean isSelectable() {
  278. return selectable;
  279. }
  280. /**
  281. * Sets the selectable state. Selectable determines if the a node can be
  282. * selected on the client side. Selectable does not affect
  283. * {@link #setValue(Object)} or {@link #select(Object)}.
  284. *
  285. * <p>
  286. * The tree is selectable by default.
  287. * </p>
  288. *
  289. * @param selectable
  290. * The new selectable state.
  291. */
  292. public void setSelectable(boolean selectable) {
  293. if (this.selectable != selectable) {
  294. this.selectable = selectable;
  295. requestRepaint();
  296. }
  297. }
  298. /**
  299. * Sets the behavior of the multiselect mode
  300. *
  301. * @param mode
  302. * The mode to set
  303. */
  304. public void setMultiselectMode(MultiSelectMode mode) {
  305. if (multiSelectMode != mode && mode != null) {
  306. multiSelectMode = mode;
  307. requestRepaint();
  308. }
  309. }
  310. /**
  311. * Returns the mode the multiselect is in. The mode controls how
  312. * multiselection can be done.
  313. *
  314. * @return The mode
  315. */
  316. public MultiSelectMode getMultiselectMode() {
  317. return multiSelectMode;
  318. }
  319. /* Component API */
  320. /*
  321. * (non-Javadoc)
  322. *
  323. * @see com.vaadin.ui.AbstractSelect#changeVariables(java.lang.Object,
  324. * java.util.Map)
  325. */
  326. @Override
  327. public void changeVariables(Object source, Map variables) {
  328. if (variables.containsKey("clickedKey")) {
  329. String key = (String) variables.get("clickedKey");
  330. Object id = itemIdMapper.get(key);
  331. MouseEventDetails details = MouseEventDetails
  332. .deSerialize((String) variables.get("clickEvent"));
  333. Item item = getItem(id);
  334. if (item != null) {
  335. fireEvent(new ItemClickEvent(this, item, id, null, details));
  336. }
  337. }
  338. if (!isSelectable() && variables.containsKey("selected")) {
  339. // Not-selectable is a special case, AbstractSelect does not support
  340. // TODO could be optimized.
  341. variables = new HashMap(variables);
  342. variables.remove("selected");
  343. }
  344. // Collapses the nodes
  345. if (variables.containsKey("collapse")) {
  346. final String[] keys = (String[]) variables.get("collapse");
  347. for (int i = 0; i < keys.length; i++) {
  348. final Object id = itemIdMapper.get(keys[i]);
  349. if (id != null && isExpanded(id)) {
  350. expanded.remove(id);
  351. fireCollapseEvent(id);
  352. }
  353. }
  354. }
  355. // Expands the nodes
  356. if (variables.containsKey("expand")) {
  357. boolean sendChildTree = false;
  358. if (variables.containsKey("requestChildTree")) {
  359. sendChildTree = true;
  360. }
  361. final String[] keys = (String[]) variables.get("expand");
  362. for (int i = 0; i < keys.length; i++) {
  363. final Object id = itemIdMapper.get(keys[i]);
  364. if (id != null) {
  365. expandItem(id, sendChildTree);
  366. }
  367. }
  368. }
  369. // AbstractSelect cannot handle multiselection so we handle
  370. // it ourself
  371. if (variables.containsKey("selected") && isMultiSelect()
  372. && multiSelectMode == MultiSelectMode.DEFAULT) {
  373. handleSelectedItems(variables);
  374. variables = new HashMap<String, Object>(variables);
  375. variables.remove("selected");
  376. }
  377. // Selections are handled by the select component
  378. super.changeVariables(source, variables);
  379. // Actions
  380. if (variables.containsKey("action")) {
  381. final StringTokenizer st = new StringTokenizer(
  382. (String) variables.get("action"), ",");
  383. if (st.countTokens() == 2) {
  384. final Object itemId = itemIdMapper.get(st.nextToken());
  385. final Action action = (Action) actionMapper.get(st.nextToken());
  386. if (action != null && containsId(itemId)
  387. && actionHandlers != null) {
  388. for (final Iterator<Action.Handler> i = actionHandlers
  389. .iterator(); i.hasNext();) {
  390. i.next().handleAction(action, this, itemId);
  391. }
  392. }
  393. }
  394. }
  395. }
  396. /**
  397. * Handles the selection
  398. *
  399. * @param variables
  400. * The variables sent to the server from the client
  401. */
  402. private void handleSelectedItems(Map<String, Object> variables) {
  403. final String[] ka = (String[]) variables.get("selected");
  404. // Converts the key-array to id-set
  405. final LinkedList s = new LinkedList();
  406. for (int i = 0; i < ka.length; i++) {
  407. final Object id = itemIdMapper.get(ka[i]);
  408. if (!isNullSelectionAllowed()
  409. && (id == null || id == getNullSelectionItemId())) {
  410. // skip empty selection if nullselection is not allowed
  411. requestRepaint();
  412. } else if (id != null && containsId(id)) {
  413. s.add(id);
  414. }
  415. }
  416. if (!isNullSelectionAllowed() && s.size() < 1) {
  417. // empty selection not allowed, keep old value
  418. requestRepaint();
  419. return;
  420. }
  421. setValue(s, true);
  422. }
  423. /**
  424. * Paints any needed component-specific things to the given UIDL stream.
  425. *
  426. * @see com.vaadin.ui.AbstractComponent#paintContent(PaintTarget)
  427. */
  428. @Override
  429. public void paintContent(PaintTarget target) throws PaintException {
  430. initialPaint = false;
  431. if (partialUpdate) {
  432. target.addAttribute("partialUpdate", true);
  433. target.addAttribute("rootKey", itemIdMapper.key(expandedItemId));
  434. } else {
  435. getCaptionChangeListener().clear();
  436. // The tab ordering number
  437. if (getTabIndex() > 0) {
  438. target.addAttribute("tabindex", getTabIndex());
  439. }
  440. // Paint tree attributes
  441. if (isSelectable()) {
  442. target.addAttribute("selectmode", (isMultiSelect() ? "multi"
  443. : "single"));
  444. if (isMultiSelect()) {
  445. target.addAttribute("multiselectmode",
  446. multiSelectMode.ordinal());
  447. }
  448. } else {
  449. target.addAttribute("selectmode", "none");
  450. }
  451. if (isNewItemsAllowed()) {
  452. target.addAttribute("allownewitem", true);
  453. }
  454. if (isNullSelectionAllowed()) {
  455. target.addAttribute("nullselect", true);
  456. }
  457. if (dragMode != TreeDragMode.NONE) {
  458. target.addAttribute("dragMode", dragMode.ordinal());
  459. }
  460. }
  461. // Initialize variables
  462. final Set<Action> actionSet = new LinkedHashSet<Action>();
  463. // rendered selectedKeys
  464. LinkedList<String> selectedKeys = new LinkedList<String>();
  465. final LinkedList<String> expandedKeys = new LinkedList<String>();
  466. // Iterates through hierarchical tree using a stack of iterators
  467. final Stack<Iterator> iteratorStack = new Stack<Iterator>();
  468. Collection ids;
  469. if (partialUpdate) {
  470. ids = getChildren(expandedItemId);
  471. } else {
  472. ids = rootItemIds();
  473. }
  474. if (ids != null) {
  475. iteratorStack.push(ids.iterator());
  476. }
  477. while (!iteratorStack.isEmpty()) {
  478. // Gets the iterator for current tree level
  479. final Iterator i = iteratorStack.peek();
  480. // If the level is finished, back to previous tree level
  481. if (!i.hasNext()) {
  482. // Removes used iterator from the stack
  483. iteratorStack.pop();
  484. // Closes node
  485. if (!iteratorStack.isEmpty()) {
  486. target.endTag("node");
  487. }
  488. }
  489. // Adds the item on current level
  490. else {
  491. final Object itemId = i.next();
  492. // Starts the item / node
  493. final boolean isNode = areChildrenAllowed(itemId);
  494. if (isNode) {
  495. target.startTag("node");
  496. } else {
  497. target.startTag("leaf");
  498. }
  499. if (itemStyleGenerator != null) {
  500. String stylename = itemStyleGenerator.getStyle(itemId);
  501. if (stylename != null) {
  502. target.addAttribute("style", stylename);
  503. }
  504. }
  505. // Adds the attributes
  506. target.addAttribute("caption", getItemCaption(itemId));
  507. final Resource icon = getItemIcon(itemId);
  508. if (icon != null) {
  509. target.addAttribute("icon", getItemIcon(itemId));
  510. }
  511. final String key = itemIdMapper.key(itemId);
  512. target.addAttribute("key", key);
  513. if (isSelected(itemId)) {
  514. target.addAttribute("selected", true);
  515. selectedKeys.add(key);
  516. }
  517. if (areChildrenAllowed(itemId) && isExpanded(itemId)) {
  518. target.addAttribute("expanded", true);
  519. expandedKeys.add(key);
  520. }
  521. // Add caption change listener
  522. getCaptionChangeListener().addNotifierForItem(itemId);
  523. // Actions
  524. if (actionHandlers != null) {
  525. final ArrayList<String> keys = new ArrayList<String>();
  526. final Iterator<Action.Handler> ahi = actionHandlers
  527. .iterator();
  528. while (ahi.hasNext()) {
  529. final Action[] aa = ahi.next().getActions(itemId, this);
  530. if (aa != null) {
  531. for (int ai = 0; ai < aa.length; ai++) {
  532. final String akey = actionMapper.key(aa[ai]);
  533. actionSet.add(aa[ai]);
  534. keys.add(akey);
  535. }
  536. }
  537. }
  538. target.addAttribute("al", keys.toArray());
  539. }
  540. // Adds the children if expanded, or close the tag
  541. if (isExpanded(itemId) && hasChildren(itemId)
  542. && areChildrenAllowed(itemId)) {
  543. iteratorStack.push(getChildren(itemId).iterator());
  544. } else {
  545. if (isNode) {
  546. target.endTag("node");
  547. } else {
  548. target.endTag("leaf");
  549. }
  550. }
  551. }
  552. }
  553. // Actions
  554. if (!actionSet.isEmpty()) {
  555. target.addVariable(this, "action", "");
  556. target.startTag("actions");
  557. final Iterator<Action> i = actionSet.iterator();
  558. while (i.hasNext()) {
  559. final Action a = i.next();
  560. target.startTag("action");
  561. if (a.getCaption() != null) {
  562. target.addAttribute("caption", a.getCaption());
  563. }
  564. if (a.getIcon() != null) {
  565. target.addAttribute("icon", a.getIcon());
  566. }
  567. target.addAttribute("key", actionMapper.key(a));
  568. target.endTag("action");
  569. }
  570. target.endTag("actions");
  571. }
  572. if (partialUpdate) {
  573. partialUpdate = false;
  574. } else {
  575. // Selected
  576. target.addVariable(this, "selected",
  577. selectedKeys.toArray(new String[selectedKeys.size()]));
  578. // Expand and collapse
  579. target.addVariable(this, "expand", new String[] {});
  580. target.addVariable(this, "collapse", new String[] {});
  581. // New items
  582. target.addVariable(this, "newitem", new String[] {});
  583. if (dropHandler != null) {
  584. dropHandler.getAcceptCriterion().paint(target);
  585. }
  586. }
  587. }
  588. /* Container.Hierarchical API */
  589. /**
  590. * Tests if the Item with given ID can have any children.
  591. *
  592. * @see com.vaadin.data.Container.Hierarchical#areChildrenAllowed(Object)
  593. */
  594. public boolean areChildrenAllowed(Object itemId) {
  595. return ((Container.Hierarchical) items).areChildrenAllowed(itemId);
  596. }
  597. /**
  598. * Gets the IDs of all Items that are children of the specified Item.
  599. *
  600. * @see com.vaadin.data.Container.Hierarchical#getChildren(Object)
  601. */
  602. public Collection getChildren(Object itemId) {
  603. return ((Container.Hierarchical) items).getChildren(itemId);
  604. }
  605. /**
  606. * Gets the ID of the parent Item of the specified Item.
  607. *
  608. * @see com.vaadin.data.Container.Hierarchical#getParent(Object)
  609. */
  610. public Object getParent(Object itemId) {
  611. return ((Container.Hierarchical) items).getParent(itemId);
  612. }
  613. /**
  614. * Tests if the Item specified with <code>itemId</code> has child Items.
  615. *
  616. * @see com.vaadin.data.Container.Hierarchical#hasChildren(Object)
  617. */
  618. public boolean hasChildren(Object itemId) {
  619. return ((Container.Hierarchical) items).hasChildren(itemId);
  620. }
  621. /**
  622. * Tests if the Item specified with <code>itemId</code> is a root Item.
  623. *
  624. * @see com.vaadin.data.Container.Hierarchical#isRoot(Object)
  625. */
  626. public boolean isRoot(Object itemId) {
  627. return ((Container.Hierarchical) items).isRoot(itemId);
  628. }
  629. /**
  630. * Gets the IDs of all Items in the container that don't have a parent.
  631. *
  632. * @see com.vaadin.data.Container.Hierarchical#rootItemIds()
  633. */
  634. public Collection rootItemIds() {
  635. return ((Container.Hierarchical) items).rootItemIds();
  636. }
  637. /**
  638. * Sets the given Item's capability to have children.
  639. *
  640. * @see com.vaadin.data.Container.Hierarchical#setChildrenAllowed(Object,
  641. * boolean)
  642. */
  643. public boolean setChildrenAllowed(Object itemId, boolean areChildrenAllowed) {
  644. final boolean success = ((Container.Hierarchical) items)
  645. .setChildrenAllowed(itemId, areChildrenAllowed);
  646. if (success) {
  647. fireValueChange(false);
  648. }
  649. return success;
  650. }
  651. /*
  652. * (non-Javadoc)
  653. *
  654. * @see com.vaadin.data.Container.Hierarchical#setParent(java.lang.Object ,
  655. * java.lang.Object)
  656. */
  657. public boolean setParent(Object itemId, Object newParentId) {
  658. final boolean success = ((Container.Hierarchical) items).setParent(
  659. itemId, newParentId);
  660. if (success) {
  661. requestRepaint();
  662. }
  663. return success;
  664. }
  665. /* Overriding select behavior */
  666. /**
  667. * Sets the Container that serves as the data source of the viewer.
  668. *
  669. * @see com.vaadin.data.Container.Viewer#setContainerDataSource(Container)
  670. */
  671. @Override
  672. public void setContainerDataSource(Container newDataSource) {
  673. if (newDataSource == null) {
  674. // Note: using wrapped IndexedContainer to match constructor (super
  675. // creates an IndexedContainer, which is then wrapped).
  676. newDataSource = new ContainerHierarchicalWrapper(
  677. new IndexedContainer());
  678. }
  679. // Assure that the data source is ordered by making unordered
  680. // containers ordered by wrapping them
  681. if (Container.Hierarchical.class.isAssignableFrom(newDataSource
  682. .getClass())) {
  683. super.setContainerDataSource(newDataSource);
  684. } else {
  685. super.setContainerDataSource(new ContainerHierarchicalWrapper(
  686. newDataSource));
  687. }
  688. }
  689. /* Expand event and listener */
  690. /**
  691. * Event to fired when a node is expanded. ExapandEvent is fired when a node
  692. * is to be expanded. it can me used to dynamically fill the sub-nodes of
  693. * the node.
  694. *
  695. * @author IT Mill Ltd.
  696. * @version
  697. * @VERSION@
  698. * @since 3.0
  699. */
  700. public class ExpandEvent extends Component.Event {
  701. private final Object expandedItemId;
  702. /**
  703. * New instance of options change event
  704. *
  705. * @param source
  706. * the Source of the event.
  707. * @param expandedItemId
  708. */
  709. public ExpandEvent(Component source, Object expandedItemId) {
  710. super(source);
  711. this.expandedItemId = expandedItemId;
  712. }
  713. /**
  714. * Node where the event occurred.
  715. *
  716. * @return the Source of the event.
  717. */
  718. public Object getItemId() {
  719. return expandedItemId;
  720. }
  721. }
  722. /**
  723. * Expand event listener.
  724. *
  725. * @author IT Mill Ltd.
  726. * @version
  727. * @VERSION@
  728. * @since 3.0
  729. */
  730. public interface ExpandListener extends Serializable {
  731. public static final Method EXPAND_METHOD = ReflectTools.findMethod(
  732. ExpandListener.class, "nodeExpand", ExpandEvent.class);
  733. /**
  734. * A node has been expanded.
  735. *
  736. * @param event
  737. * the Expand event.
  738. */
  739. public void nodeExpand(ExpandEvent event);
  740. }
  741. /**
  742. * Adds the expand listener.
  743. *
  744. * @param listener
  745. * the Listener to be added.
  746. */
  747. public void addListener(ExpandListener listener) {
  748. addListener(ExpandEvent.class, listener, ExpandListener.EXPAND_METHOD);
  749. }
  750. /**
  751. * Removes the expand listener.
  752. *
  753. * @param listener
  754. * the Listener to be removed.
  755. */
  756. public void removeListener(ExpandListener listener) {
  757. removeListener(ExpandEvent.class, listener,
  758. ExpandListener.EXPAND_METHOD);
  759. }
  760. /**
  761. * Emits the expand event.
  762. *
  763. * @param itemId
  764. * the item id.
  765. */
  766. protected void fireExpandEvent(Object itemId) {
  767. fireEvent(new ExpandEvent(this, itemId));
  768. }
  769. /* Collapse event */
  770. /**
  771. * Collapse event
  772. *
  773. * @author IT Mill Ltd.
  774. * @version
  775. * @VERSION@
  776. * @since 3.0
  777. */
  778. public class CollapseEvent extends Component.Event {
  779. private final Object collapsedItemId;
  780. /**
  781. * New instance of options change event.
  782. *
  783. * @param source
  784. * the Source of the event.
  785. * @param collapsedItemId
  786. */
  787. public CollapseEvent(Component source, Object collapsedItemId) {
  788. super(source);
  789. this.collapsedItemId = collapsedItemId;
  790. }
  791. /**
  792. * Gets tge Collapsed Item id.
  793. *
  794. * @return the collapsed item id.
  795. */
  796. public Object getItemId() {
  797. return collapsedItemId;
  798. }
  799. }
  800. /**
  801. * Collapse event listener.
  802. *
  803. * @author IT Mill Ltd.
  804. * @version
  805. * @VERSION@
  806. * @since 3.0
  807. */
  808. public interface CollapseListener extends Serializable {
  809. public static final Method COLLAPSE_METHOD = ReflectTools.findMethod(
  810. CollapseListener.class, "nodeCollapse", CollapseEvent.class);
  811. /**
  812. * A node has been collapsed.
  813. *
  814. * @param event
  815. * the Collapse event.
  816. */
  817. public void nodeCollapse(CollapseEvent event);
  818. }
  819. /**
  820. * Adds the collapse listener.
  821. *
  822. * @param listener
  823. * the Listener to be added.
  824. */
  825. public void addListener(CollapseListener listener) {
  826. addListener(CollapseEvent.class, listener,
  827. CollapseListener.COLLAPSE_METHOD);
  828. }
  829. /**
  830. * Removes the collapse listener.
  831. *
  832. * @param listener
  833. * the Listener to be removed.
  834. */
  835. public void removeListener(CollapseListener listener) {
  836. removeListener(CollapseEvent.class, listener,
  837. CollapseListener.COLLAPSE_METHOD);
  838. }
  839. /**
  840. * Emits collapse event.
  841. *
  842. * @param itemId
  843. * the item id.
  844. */
  845. protected void fireCollapseEvent(Object itemId) {
  846. fireEvent(new CollapseEvent(this, itemId));
  847. }
  848. /* Action container */
  849. /**
  850. * Adds an action handler.
  851. *
  852. * @see com.vaadin.event.Action.Container#addActionHandler(Action.Handler)
  853. */
  854. public void addActionHandler(Action.Handler actionHandler) {
  855. if (actionHandler != null) {
  856. if (actionHandlers == null) {
  857. actionHandlers = new LinkedList<Action.Handler>();
  858. actionMapper = new KeyMapper();
  859. }
  860. if (!actionHandlers.contains(actionHandler)) {
  861. actionHandlers.add(actionHandler);
  862. requestRepaint();
  863. }
  864. }
  865. }
  866. /**
  867. * Removes an action handler.
  868. *
  869. * @see com.vaadin.event.Action.Container#removeActionHandler(Action.Handler)
  870. */
  871. public void removeActionHandler(Action.Handler actionHandler) {
  872. if (actionHandlers != null && actionHandlers.contains(actionHandler)) {
  873. actionHandlers.remove(actionHandler);
  874. if (actionHandlers.isEmpty()) {
  875. actionHandlers = null;
  876. actionMapper = null;
  877. }
  878. requestRepaint();
  879. }
  880. }
  881. /**
  882. * Removes all action handlers
  883. */
  884. public void removeAllActionHandlers() {
  885. actionHandlers = null;
  886. actionMapper = null;
  887. requestRepaint();
  888. }
  889. /**
  890. * Gets the visible item ids.
  891. *
  892. * @see com.vaadin.ui.Select#getVisibleItemIds()
  893. */
  894. @Override
  895. public Collection getVisibleItemIds() {
  896. final LinkedList visible = new LinkedList();
  897. // Iterates trough hierarchical tree using a stack of iterators
  898. final Stack<Iterator> iteratorStack = new Stack<Iterator>();
  899. final Collection ids = rootItemIds();
  900. if (ids != null) {
  901. iteratorStack.push(ids.iterator());
  902. }
  903. while (!iteratorStack.isEmpty()) {
  904. // Gets the iterator for current tree level
  905. final Iterator i = iteratorStack.peek();
  906. // If the level is finished, back to previous tree level
  907. if (!i.hasNext()) {
  908. // Removes used iterator from the stack
  909. iteratorStack.pop();
  910. }
  911. // Adds the item on current level
  912. else {
  913. final Object itemId = i.next();
  914. visible.add(itemId);
  915. // Adds children if expanded, or close the tag
  916. if (isExpanded(itemId) && hasChildren(itemId)) {
  917. iteratorStack.push(getChildren(itemId).iterator());
  918. }
  919. }
  920. }
  921. return visible;
  922. }
  923. /**
  924. * Tree does not support <code>setNullSelectionItemId</code>.
  925. *
  926. * @see com.vaadin.ui.AbstractSelect#setNullSelectionItemId(java.lang.Object)
  927. */
  928. @Override
  929. public void setNullSelectionItemId(Object nullSelectionItemId)
  930. throws UnsupportedOperationException {
  931. if (nullSelectionItemId != null) {
  932. throw new UnsupportedOperationException();
  933. }
  934. }
  935. /**
  936. * Adding new items is not supported.
  937. *
  938. * @throws UnsupportedOperationException
  939. * if set to true.
  940. * @see com.vaadin.ui.Select#setNewItemsAllowed(boolean)
  941. */
  942. @Override
  943. public void setNewItemsAllowed(boolean allowNewOptions)
  944. throws UnsupportedOperationException {
  945. if (allowNewOptions) {
  946. throw new UnsupportedOperationException();
  947. }
  948. }
  949. /**
  950. * Focusing to this component is not supported.
  951. *
  952. * @throws UnsupportedOperationException
  953. * if invoked.
  954. * @see com.vaadin.ui.AbstractField#focus()
  955. */
  956. @Override
  957. public void focus() throws UnsupportedOperationException {
  958. throw new UnsupportedOperationException();
  959. }
  960. /**
  961. * Tree does not support lazy options loading mode. Setting this true will
  962. * throw UnsupportedOperationException.
  963. *
  964. * @see com.vaadin.ui.Select#setLazyLoading(boolean)
  965. */
  966. public void setLazyLoading(boolean useLazyLoading) {
  967. if (useLazyLoading) {
  968. throw new UnsupportedOperationException(
  969. "Lazy options loading is not supported by Tree.");
  970. }
  971. }
  972. private ItemStyleGenerator itemStyleGenerator;
  973. private DropHandler dropHandler;
  974. public void addListener(ItemClickListener listener) {
  975. addListener(VTree.ITEM_CLICK_EVENT_ID, ItemClickEvent.class, listener,
  976. ItemClickEvent.ITEM_CLICK_METHOD);
  977. }
  978. public void removeListener(ItemClickListener listener) {
  979. removeListener(VTree.ITEM_CLICK_EVENT_ID, ItemClickEvent.class,
  980. listener);
  981. }
  982. /**
  983. * Sets the {@link ItemStyleGenerator} to be used with this tree.
  984. *
  985. * @param itemStyleGenerator
  986. * item style generator or null to remove generator
  987. */
  988. public void setItemStyleGenerator(ItemStyleGenerator itemStyleGenerator) {
  989. if (this.itemStyleGenerator != itemStyleGenerator) {
  990. this.itemStyleGenerator = itemStyleGenerator;
  991. requestRepaint();
  992. }
  993. }
  994. /**
  995. * @return the current {@link ItemStyleGenerator} for this tree. Null if
  996. * {@link ItemStyleGenerator} is not set.
  997. */
  998. public ItemStyleGenerator getItemStyleGenerator() {
  999. return itemStyleGenerator;
  1000. }
  1001. /**
  1002. * ItemStyleGenerator can be used to add custom styles to tree items. The
  1003. * CSS class name that will be added to the cell content is
  1004. * <tt>v-tree-node-[style name]</tt>.
  1005. */
  1006. public interface ItemStyleGenerator extends Serializable {
  1007. /**
  1008. * Called by Tree when an item is painted.
  1009. *
  1010. * @param itemId
  1011. * The itemId of the item to be painted
  1012. * @return The style name to add to this item. (the CSS class name will
  1013. * be v-tree-node-[style name]
  1014. */
  1015. public abstract String getStyle(Object itemId);
  1016. }
  1017. // Overriden so javadoc comes from Container.Hierarchical
  1018. @Override
  1019. public boolean removeItem(Object itemId)
  1020. throws UnsupportedOperationException {
  1021. return super.removeItem(itemId);
  1022. }
  1023. public DropHandler getDropHandler() {
  1024. return dropHandler;
  1025. }
  1026. public void setDropHandler(DropHandler dropHandler) {
  1027. this.dropHandler = dropHandler;
  1028. }
  1029. /**
  1030. * A {@link TargetDetails} implementation with Tree specific api.
  1031. *
  1032. * @since 6.3
  1033. */
  1034. public class TreeTargetDetails extends AbstractSelectTargetDetails {
  1035. TreeTargetDetails(Map<String, Object> rawVariables) {
  1036. super(rawVariables);
  1037. }
  1038. @Override
  1039. public Tree getTarget() {
  1040. return (Tree) super.getTarget();
  1041. }
  1042. /**
  1043. * If the event is on a node that can not have children (see
  1044. * {@link Tree#areChildrenAllowed(Object)}), this method returns the
  1045. * parent item id of the target item (see {@link #getItemIdOver()} ).
  1046. * The identifier of the parent node is also returned if the cursor is
  1047. * on the top part of node. Else this method returns the same as
  1048. * {@link #getItemIdOver()}.
  1049. * <p>
  1050. * In other words this method returns the identifier of the "folder"
  1051. * into the drag operation is targeted.
  1052. * <p>
  1053. * If the method returns null, the current target is on a root node or
  1054. * on other undefined area over the tree component.
  1055. * <p>
  1056. * The default Tree implementation marks the targetted tree node with
  1057. * CSS classnames v-tree-node-dragfolder and
  1058. * v-tree-node-caption-dragfolder (for the caption element).
  1059. */
  1060. public Object getItemIdInto() {
  1061. Object itemIdOver = getItemIdOver();
  1062. if (areChildrenAllowed(itemIdOver)
  1063. && getDropLocation() == VerticalDropLocation.MIDDLE) {
  1064. return itemIdOver;
  1065. }
  1066. return getParent(itemIdOver);
  1067. }
  1068. /**
  1069. * If drop is targeted into "folder node" (see {@link #getItemIdInto()}
  1070. * ), this method returns the item id of the node after the drag was
  1071. * targeted. This method is useful when implementing drop into specific
  1072. * location (between specific nodes) in tree.
  1073. *
  1074. * @return the id of the item after the user targets the drop or null if
  1075. * "target" is a first item in node list (or the first in root
  1076. * node list)
  1077. */
  1078. public Object getItemIdAfter() {
  1079. Object itemIdOver = getItemIdOver();
  1080. Object itemIdInto2 = getItemIdInto();
  1081. if (itemIdOver.equals(itemIdInto2)) {
  1082. return null;
  1083. }
  1084. VerticalDropLocation dropLocation = getDropLocation();
  1085. if (VerticalDropLocation.TOP == dropLocation) {
  1086. // if on top of the caption area, add before
  1087. Collection children;
  1088. Object itemIdInto = getItemIdInto();
  1089. if (itemIdInto != null) {
  1090. // seek the previous from child list
  1091. children = getChildren(itemIdInto);
  1092. } else {
  1093. children = rootItemIds();
  1094. }
  1095. Object ref = null;
  1096. for (Object object : children) {
  1097. if (object.equals(itemIdOver)) {
  1098. return ref;
  1099. }
  1100. ref = object;
  1101. }
  1102. }
  1103. return itemIdOver;
  1104. }
  1105. }
  1106. /*
  1107. * (non-Javadoc)
  1108. *
  1109. * @see
  1110. * com.vaadin.event.dd.DropTarget#translateDropTargetDetails(java.util.Map)
  1111. */
  1112. public TreeTargetDetails translateDropTargetDetails(
  1113. Map<String, Object> clientVariables) {
  1114. return new TreeTargetDetails(clientVariables);
  1115. }
  1116. /**
  1117. * Helper API for {@link TreeDropCriterion}
  1118. *
  1119. * @param itemId
  1120. * @return
  1121. */
  1122. private String key(Object itemId) {
  1123. return itemIdMapper.key(itemId);
  1124. }
  1125. /**
  1126. * Sets the drag mode that controls how Tree behaves as a {@link DragSource}
  1127. * .
  1128. *
  1129. * @param dragMode
  1130. */
  1131. public void setDragMode(TreeDragMode dragMode) {
  1132. this.dragMode = dragMode;
  1133. }
  1134. /**
  1135. * @return the drag mode that controls how Tree behaves as a
  1136. * {@link DragSource}.
  1137. *
  1138. * @see TreeDragMode
  1139. */
  1140. public TreeDragMode getDragMode() {
  1141. return dragMode;
  1142. }
  1143. /**
  1144. * Concrete implementation of {@link DataBoundTransferable} for data
  1145. * transferred from a tree.
  1146. *
  1147. * @see {@link DataBoundTransferable}.
  1148. *
  1149. * @since 6.3
  1150. */
  1151. protected class TreeTransferable extends DataBoundTransferable {
  1152. public TreeTransferable(Component sourceComponent,
  1153. Map<String, Object> rawVariables) {
  1154. super(sourceComponent, rawVariables);
  1155. }
  1156. @Override
  1157. public Object getItemId() {
  1158. return getData("itemId");
  1159. }
  1160. @Override
  1161. public Object getPropertyId() {
  1162. return getItemCaptionPropertyId();
  1163. }
  1164. }
  1165. /*
  1166. * (non-Javadoc)
  1167. *
  1168. * @see com.vaadin.event.dd.DragSource#getTransferable(java.util.Map)
  1169. */
  1170. public Transferable getTransferable(Map<String, Object> payload) {
  1171. TreeTransferable transferable = new TreeTransferable(this, payload);
  1172. // updating drag source variables
  1173. Object object = payload.get("itemId");
  1174. if (object != null) {
  1175. transferable.setData("itemId", itemIdMapper.get((String) object));
  1176. }
  1177. return transferable;
  1178. }
  1179. /**
  1180. * Lazy loading accept criterion for Tree. Accepted target nodes are loaded
  1181. * from server once per drag and drop operation. Developer must override one
  1182. * method that decides accepted tree nodes for the whole Tree.
  1183. *
  1184. * <p>
  1185. * Initially pretty much no data is sent to client. On first required
  1186. * criterion check (per drag request) the client side data structure is
  1187. * initialized from server and no subsequent requests requests are needed
  1188. * during that drag and drop operation.
  1189. */
  1190. @ClientCriterion(VLazyInitItemIdentifiers.class)
  1191. public static abstract class TreeDropCriterion extends ServerSideCriterion {
  1192. private Tree tree;
  1193. private Set<Object> allowedItemIds;
  1194. /*
  1195. * (non-Javadoc)
  1196. *
  1197. * @see
  1198. * com.vaadin.event.dd.acceptCriteria.ServerSideCriterion#getIdentifier
  1199. * ()
  1200. */
  1201. @Override
  1202. protected String getIdentifier() {
  1203. return TreeDropCriterion.class.getCanonicalName();
  1204. }
  1205. /*
  1206. * (non-Javadoc)
  1207. *
  1208. * @see
  1209. * com.vaadin.event.dd.acceptCriteria.AcceptCriterion#accepts(com.vaadin
  1210. * .event.dd.DragAndDropEvent)
  1211. */
  1212. public boolean accept(DragAndDropEvent dragEvent) {
  1213. AbstractSelectTargetDetails dropTargetData = (AbstractSelectTargetDetails) dragEvent
  1214. .getTargetDetails();
  1215. tree = (Tree) dragEvent.getTargetDetails().getTarget();
  1216. allowedItemIds = getAllowedItemIds(dragEvent, tree);
  1217. return allowedItemIds.contains(dropTargetData.getItemIdOver());
  1218. }
  1219. /*
  1220. * (non-Javadoc)
  1221. *
  1222. * @see
  1223. * com.vaadin.event.dd.acceptCriteria.AcceptCriterion#paintResponse(
  1224. * com.vaadin.terminal.PaintTarget)
  1225. */
  1226. @Override
  1227. public void paintResponse(PaintTarget target) throws PaintException {
  1228. /*
  1229. * send allowed nodes to client so subsequent requests can be
  1230. * avoided
  1231. */
  1232. Object[] array = allowedItemIds.toArray();
  1233. for (int i = 0; i < array.length; i++) {
  1234. String key = tree.key(array[i]);
  1235. array[i] = key;
  1236. }
  1237. target.addAttribute("allowedIds", array);
  1238. }
  1239. protected abstract Set<Object> getAllowedItemIds(
  1240. DragAndDropEvent dragEvent, Tree tree);
  1241. }
  1242. /**
  1243. * A criterion that accepts {@link Transferable} only directly on a tree
  1244. * node that can have children.
  1245. * <p>
  1246. * Class is singleton, use {@link TargetItemAllowsChildren#get()} to get the
  1247. * instance.
  1248. *
  1249. * @see Tree#setChildrenAllowed(Object, boolean)
  1250. *
  1251. * @since 6.3
  1252. */
  1253. public static class TargetItemAllowsChildren extends TargetDetailIs {
  1254. private static TargetItemAllowsChildren instance = new TargetItemAllowsChildren();
  1255. public static TargetItemAllowsChildren get() {
  1256. return instance;
  1257. }
  1258. private TargetItemAllowsChildren() {
  1259. super("itemIdOverIsNode", Boolean.TRUE);
  1260. }
  1261. /*
  1262. * Uses enhanced server side check
  1263. */
  1264. @Override
  1265. public boolean accept(DragAndDropEvent dragEvent) {
  1266. try {
  1267. // must be over tree node and in the middle of it (not top or
  1268. // bottom
  1269. // part)
  1270. TreeTargetDetails eventDetails = (TreeTargetDetails) dragEvent
  1271. .getTargetDetails();
  1272. Object itemIdOver = eventDetails.getItemIdOver();
  1273. if (!eventDetails.getTarget().areChildrenAllowed(itemIdOver)) {
  1274. return false;
  1275. }
  1276. // return true if directly over
  1277. return eventDetails.getDropLocation() == VerticalDropLocation.MIDDLE;
  1278. } catch (Exception e) {
  1279. return false;
  1280. }
  1281. }
  1282. }
  1283. /**
  1284. * An accept criterion that checks the parent node (or parent hierarchy) for
  1285. * the item identifier given in constructor. If the parent is found, content
  1286. * is accepted. Criterion can be used to accepts drags on a specific sub
  1287. * tree only.
  1288. * <p>
  1289. * The root items is also consider to be valid target.
  1290. */
  1291. @ClientCriterion(VTargetInSubtree.class)
  1292. public class TargetInSubtree extends ClientSideCriterion {
  1293. private Object rootId;
  1294. private int depthToCheck = -1;
  1295. /**
  1296. * Constructs a criteria that accepts the drag if the targeted Item is a
  1297. * descendant of Item identified by given id
  1298. *
  1299. * @param parentItemId
  1300. * the item identifier of the parent node
  1301. */
  1302. public TargetInSubtree(Object parentItemId) {
  1303. rootId = parentItemId;
  1304. }
  1305. /**
  1306. * Constructs a criteria that accepts drops within given level below the
  1307. * subtree root identified by given id.
  1308. *
  1309. * @param rootId
  1310. * the item identifier to be sought for
  1311. * @param depthToCheck
  1312. * the depth that tree is traversed upwards to seek for the
  1313. * parent, -1 means that the whole structure should be
  1314. * checked
  1315. */
  1316. public TargetInSubtree(Object rootId, int depthToCheck) {
  1317. this.rootId = rootId;
  1318. this.depthToCheck = depthToCheck;
  1319. }
  1320. public boolean accept(DragAndDropEvent dragEvent) {
  1321. try {
  1322. TreeTargetDetails eventDetails = (TreeTargetDetails) dragEvent
  1323. .getTargetDetails();
  1324. if (eventDetails.getItemIdOver() != null) {
  1325. Object itemId = eventDetails.getItemIdOver();
  1326. int i = 0;
  1327. while (itemId != null
  1328. && (depthToCheck == -1 || i <= depthToCheck)) {
  1329. if (itemId.equals(rootId)) {
  1330. return true;
  1331. }
  1332. itemId = getParent(itemId);
  1333. i++;
  1334. }
  1335. }
  1336. return false;
  1337. } catch (Exception e) {
  1338. return false;
  1339. }
  1340. }
  1341. @Override
  1342. public void paintContent(PaintTarget target) throws PaintException {
  1343. super.paintContent(target);
  1344. target.addAttribute("depth", depthToCheck);
  1345. target.addAttribute("key", key(rootId));
  1346. }
  1347. }
  1348. }