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

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