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

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