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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971
  1. /*
  2. * Copyright 2000-2014 Vaadin Ltd.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.vaadin.ui;
  17. import java.io.Serializable;
  18. import java.lang.reflect.Method;
  19. import java.util.ArrayList;
  20. import java.util.Collection;
  21. import java.util.HashMap;
  22. import java.util.HashSet;
  23. import java.util.Iterator;
  24. import java.util.LinkedHashSet;
  25. import java.util.LinkedList;
  26. import java.util.Map;
  27. import java.util.Set;
  28. import java.util.Stack;
  29. import java.util.StringTokenizer;
  30. import org.jsoup.nodes.Element;
  31. import com.vaadin.data.Container;
  32. import com.vaadin.data.Item;
  33. import com.vaadin.data.util.ContainerHierarchicalWrapper;
  34. import com.vaadin.data.util.HierarchicalContainer;
  35. import com.vaadin.event.Action;
  36. import com.vaadin.event.Action.Handler;
  37. import com.vaadin.event.ContextClickEvent;
  38. import com.vaadin.event.DataBoundTransferable;
  39. import com.vaadin.event.ItemClickEvent;
  40. import com.vaadin.event.ItemClickEvent.ItemClickListener;
  41. import com.vaadin.event.ItemClickEvent.ItemClickNotifier;
  42. import com.vaadin.event.Transferable;
  43. import com.vaadin.event.dd.DragAndDropEvent;
  44. import com.vaadin.event.dd.DragSource;
  45. import com.vaadin.event.dd.DropHandler;
  46. import com.vaadin.event.dd.DropTarget;
  47. import com.vaadin.event.dd.TargetDetails;
  48. import com.vaadin.event.dd.acceptcriteria.ClientSideCriterion;
  49. import com.vaadin.event.dd.acceptcriteria.ServerSideCriterion;
  50. import com.vaadin.event.dd.acceptcriteria.TargetDetailIs;
  51. import com.vaadin.server.KeyMapper;
  52. import com.vaadin.server.PaintException;
  53. import com.vaadin.server.PaintTarget;
  54. import com.vaadin.server.Resource;
  55. import com.vaadin.shared.MouseEventDetails;
  56. import com.vaadin.shared.ui.MultiSelectMode;
  57. import com.vaadin.shared.ui.dd.VerticalDropLocation;
  58. import com.vaadin.shared.ui.tree.TreeConstants;
  59. import com.vaadin.shared.ui.tree.TreeServerRpc;
  60. import com.vaadin.ui.declarative.DesignAttributeHandler;
  61. import com.vaadin.ui.declarative.DesignContext;
  62. import com.vaadin.ui.declarative.DesignException;
  63. import com.vaadin.util.ReflectTools;
  64. /**
  65. * Tree component. A Tree can be used to select an item (or multiple items) from
  66. * a hierarchical set of items.
  67. *
  68. * @author Vaadin Ltd.
  69. * @since 3.0
  70. */
  71. @SuppressWarnings({ "serial", "deprecation" })
  72. public class Tree extends AbstractSelect implements Container.Hierarchical,
  73. Action.Container, ItemClickNotifier, DragSource, DropTarget {
  74. public static class TreeContextClickEvent extends ContextClickEvent {
  75. private final Object itemId;
  76. public TreeContextClickEvent(Tree source, Object itemId,
  77. MouseEventDetails mouseEventDetails) {
  78. super(source, mouseEventDetails);
  79. this.itemId = itemId;
  80. }
  81. @Override
  82. public Tree getComponent() {
  83. return (Tree) super.getComponent();
  84. }
  85. /**
  86. * Returns the item id of context clicked row.
  87. *
  88. * @return item id of clicked row; <code>null</code> if no row is
  89. * present at the location
  90. */
  91. public Object getItemId() {
  92. return itemId;
  93. }
  94. }
  95. /* Private members */
  96. private static final String NULL_ALT_EXCEPTION_MESSAGE = "Parameter 'altText' needs to be non null";
  97. /**
  98. * Item icons alt texts.
  99. */
  100. private final HashMap<Object, String> itemIconAlts = new HashMap<Object, String>();
  101. /**
  102. * Set of expanded nodes.
  103. */
  104. private HashSet<Object> expanded = new HashSet<Object>();
  105. /**
  106. * List of action handlers.
  107. */
  108. private LinkedList<Action.Handler> actionHandlers = null;
  109. /**
  110. * Action mapper.
  111. */
  112. private KeyMapper<Action> actionMapper = null;
  113. /**
  114. * Is the tree selectable on the client side.
  115. */
  116. private boolean selectable = true;
  117. /**
  118. * Flag to indicate sub-tree loading
  119. */
  120. private boolean partialUpdate = false;
  121. /**
  122. * Holds a itemId which was recently expanded
  123. */
  124. private Object expandedItemId;
  125. /**
  126. * a flag which indicates initial paint. After this flag set true partial
  127. * updates are allowed.
  128. */
  129. private boolean initialPaint = true;
  130. /**
  131. * Item tooltip generator
  132. */
  133. private ItemDescriptionGenerator itemDescriptionGenerator;
  134. /**
  135. * Supported drag modes for Tree.
  136. */
  137. public enum TreeDragMode {
  138. /**
  139. * When drag mode is NONE, dragging from Tree is not supported. Browsers
  140. * may still support selecting text/icons from Tree which can initiate
  141. * HTML 5 style drag and drop operation.
  142. */
  143. NONE,
  144. /**
  145. * When drag mode is NODE, users can initiate drag from Tree nodes that
  146. * represent {@link Item}s in from the backed {@link Container}.
  147. */
  148. NODE
  149. // , SUBTREE
  150. }
  151. private TreeDragMode dragMode = TreeDragMode.NONE;
  152. private MultiSelectMode multiSelectMode = MultiSelectMode.DEFAULT;
  153. /* Tree constructors */
  154. /**
  155. * Creates a new empty tree.
  156. */
  157. public Tree() {
  158. this(null);
  159. registerRpc(new TreeServerRpc() {
  160. @Override
  161. public void contextClick(String rowKey, MouseEventDetails details) {
  162. fireEvent(new TreeContextClickEvent(Tree.this,
  163. itemIdMapper.get(rowKey), details));
  164. }
  165. });
  166. }
  167. /**
  168. * Creates a new empty tree with caption.
  169. *
  170. * @param caption
  171. */
  172. public Tree(String caption) {
  173. this(caption, new HierarchicalContainer());
  174. }
  175. /**
  176. * Creates a new tree with caption and connect it to a Container.
  177. *
  178. * @param caption
  179. * @param dataSource
  180. */
  181. public Tree(String caption, Container dataSource) {
  182. super(caption, dataSource);
  183. }
  184. @Override
  185. public void setItemIcon(Object itemId, Resource icon) {
  186. setItemIcon(itemId, icon, "");
  187. }
  188. /**
  189. * Sets the icon for an item.
  190. *
  191. * @param itemId
  192. * the id of the item to be assigned an icon.
  193. * @param icon
  194. * the icon to use or null.
  195. *
  196. * @param altText
  197. * the alternative text for the icon
  198. */
  199. public void setItemIcon(Object itemId, Resource icon, String altText) {
  200. if (itemId != null) {
  201. super.setItemIcon(itemId, icon);
  202. if (icon == null) {
  203. itemIconAlts.remove(itemId);
  204. } else if (altText == null) {
  205. throw new IllegalArgumentException(NULL_ALT_EXCEPTION_MESSAGE);
  206. } else {
  207. itemIconAlts.put(itemId, altText);
  208. }
  209. markAsDirty();
  210. }
  211. }
  212. /**
  213. * Set the alternate text for an item.
  214. *
  215. * Used when the item has an icon.
  216. *
  217. * @param itemId
  218. * the id of the item to be assigned an icon.
  219. * @param altText
  220. * the alternative text for the icon
  221. */
  222. public void setItemIconAlternateText(Object itemId, String altText) {
  223. if (itemId != null) {
  224. if (altText == null) {
  225. throw new IllegalArgumentException(NULL_ALT_EXCEPTION_MESSAGE);
  226. } else {
  227. itemIconAlts.put(itemId, altText);
  228. }
  229. }
  230. }
  231. /**
  232. * Return the alternate text of an icon in a tree item.
  233. *
  234. * @param itemId
  235. * Object with the ID of the item
  236. * @return String with the alternate text of the icon, or null when no icon
  237. * was set
  238. */
  239. public String getItemIconAlternateText(Object itemId) {
  240. String storedAlt = itemIconAlts.get(itemId);
  241. return storedAlt == null ? "" : storedAlt;
  242. }
  243. /* Expanding and collapsing */
  244. /**
  245. * Check is an item is expanded
  246. *
  247. * @param itemId
  248. * the item id.
  249. * @return true iff the item is expanded.
  250. */
  251. public boolean isExpanded(Object itemId) {
  252. return expanded.contains(itemId);
  253. }
  254. /**
  255. * Expands an item.
  256. *
  257. * @param itemId
  258. * the item id.
  259. * @return True iff the expand operation succeeded
  260. */
  261. public boolean expandItem(Object itemId) {
  262. boolean success = expandItem(itemId, true);
  263. markAsDirty();
  264. return success;
  265. }
  266. /**
  267. * Expands an item.
  268. *
  269. * @param itemId
  270. * the item id.
  271. * @param sendChildTree
  272. * flag to indicate if client needs subtree or not (may be
  273. * cached)
  274. * @return True if the expand operation succeeded
  275. */
  276. private boolean expandItem(Object itemId, boolean sendChildTree) {
  277. // Succeeds if the node is already expanded
  278. if (isExpanded(itemId)) {
  279. return true;
  280. }
  281. // Nodes that can not have children are not expandable
  282. if (!areChildrenAllowed(itemId)) {
  283. return false;
  284. }
  285. // Expands
  286. expanded.add(itemId);
  287. expandedItemId = itemId;
  288. if (initialPaint) {
  289. markAsDirty();
  290. } else if (sendChildTree) {
  291. requestPartialRepaint();
  292. }
  293. fireExpandEvent(itemId);
  294. return true;
  295. }
  296. @Override
  297. public void markAsDirty() {
  298. super.markAsDirty();
  299. partialUpdate = false;
  300. }
  301. private void requestPartialRepaint() {
  302. super.markAsDirty();
  303. partialUpdate = true;
  304. }
  305. /**
  306. * Expands the items recursively
  307. *
  308. * Expands all the children recursively starting from an item. Operation
  309. * succeeds only if all expandable items are expanded.
  310. *
  311. * @param startItemId
  312. * @return True iff the expand operation succeeded
  313. */
  314. public boolean expandItemsRecursively(Object startItemId) {
  315. boolean result = true;
  316. // Initial stack
  317. final Stack<Object> todo = new Stack<Object>();
  318. todo.add(startItemId);
  319. // Expands recursively
  320. while (!todo.isEmpty()) {
  321. final Object id = todo.pop();
  322. if (areChildrenAllowed(id) && !expandItem(id, false)) {
  323. result = false;
  324. }
  325. if (hasChildren(id)) {
  326. todo.addAll(getChildren(id));
  327. }
  328. }
  329. markAsDirty();
  330. return result;
  331. }
  332. /**
  333. * Collapses an item.
  334. *
  335. * @param itemId
  336. * the item id.
  337. * @return True iff the collapse operation succeeded
  338. */
  339. public boolean collapseItem(Object itemId) {
  340. // Succeeds if the node is already collapsed
  341. if (!isExpanded(itemId)) {
  342. return true;
  343. }
  344. // Collapse
  345. expanded.remove(itemId);
  346. markAsDirty();
  347. fireCollapseEvent(itemId);
  348. return true;
  349. }
  350. /**
  351. * Collapses the items recursively.
  352. *
  353. * Collapse all the children recursively starting from an item. Operation
  354. * succeeds only if all expandable items are collapsed.
  355. *
  356. * @param startItemId
  357. * @return True iff the collapse operation succeeded
  358. */
  359. public boolean collapseItemsRecursively(Object startItemId) {
  360. boolean result = true;
  361. // Initial stack
  362. final Stack<Object> todo = new Stack<Object>();
  363. todo.add(startItemId);
  364. // Collapse recursively
  365. while (!todo.isEmpty()) {
  366. final Object id = todo.pop();
  367. if (areChildrenAllowed(id) && !collapseItem(id)) {
  368. result = false;
  369. }
  370. if (hasChildren(id)) {
  371. todo.addAll(getChildren(id));
  372. }
  373. }
  374. return result;
  375. }
  376. /**
  377. * Returns the current selectable state. Selectable determines if the a node
  378. * can be selected on the client side. Selectable does not affect
  379. * {@link #setValue(Object)} or {@link #select(Object)}.
  380. *
  381. * <p>
  382. * The tree is selectable by default.
  383. * </p>
  384. *
  385. * @return the current selectable state.
  386. */
  387. public boolean isSelectable() {
  388. return selectable;
  389. }
  390. /**
  391. * Sets the selectable state. Selectable determines if the a node can be
  392. * selected on the client side. Selectable does not affect
  393. * {@link #setValue(Object)} or {@link #select(Object)}.
  394. *
  395. * <p>
  396. * The tree is selectable by default.
  397. * </p>
  398. *
  399. * @param selectable
  400. * The new selectable state.
  401. */
  402. public void setSelectable(boolean selectable) {
  403. if (this.selectable != selectable) {
  404. this.selectable = selectable;
  405. markAsDirty();
  406. }
  407. }
  408. /**
  409. * Sets the behavior of the multiselect mode
  410. *
  411. * @param mode
  412. * The mode to set
  413. */
  414. public void setMultiselectMode(MultiSelectMode mode) {
  415. if (multiSelectMode != mode && mode != null) {
  416. multiSelectMode = mode;
  417. markAsDirty();
  418. }
  419. }
  420. /**
  421. * Returns the mode the multiselect is in. The mode controls how
  422. * multiselection can be done.
  423. *
  424. * @return The mode
  425. */
  426. public MultiSelectMode getMultiselectMode() {
  427. return multiSelectMode;
  428. }
  429. /* Component API */
  430. /*
  431. * (non-Javadoc)
  432. *
  433. * @see com.vaadin.ui.AbstractSelect#changeVariables(java.lang.Object,
  434. * java.util.Map)
  435. */
  436. @Override
  437. public void changeVariables(Object source, Map<String, Object> variables) {
  438. if (variables.containsKey("clickedKey")) {
  439. String key = (String) variables.get("clickedKey");
  440. Object id = itemIdMapper.get(key);
  441. MouseEventDetails details = MouseEventDetails
  442. .deSerialize((String) variables.get("clickEvent"));
  443. Item item = getItem(id);
  444. if (item != null) {
  445. fireEvent(new ItemClickEvent(this, item, id, null, details));
  446. }
  447. }
  448. if (!isSelectable() && variables.containsKey("selected")) {
  449. // Not-selectable is a special case, AbstractSelect does not support
  450. // TODO could be optimized.
  451. variables = new HashMap<String, Object>(variables);
  452. variables.remove("selected");
  453. }
  454. // Collapses the nodes
  455. if (variables.containsKey("collapse")) {
  456. final String[] keys = (String[]) variables.get("collapse");
  457. for (int i = 0; i < keys.length; i++) {
  458. final Object id = itemIdMapper.get(keys[i]);
  459. if (id != null && isExpanded(id)) {
  460. expanded.remove(id);
  461. if (expandedItemId == id) {
  462. expandedItemId = null;
  463. }
  464. fireCollapseEvent(id);
  465. }
  466. }
  467. }
  468. // Expands the nodes
  469. if (variables.containsKey("expand")) {
  470. boolean sendChildTree = false;
  471. if (variables.containsKey("requestChildTree")) {
  472. sendChildTree = true;
  473. }
  474. final String[] keys = (String[]) variables.get("expand");
  475. for (int i = 0; i < keys.length; i++) {
  476. final Object id = itemIdMapper.get(keys[i]);
  477. if (id != null) {
  478. expandItem(id, sendChildTree);
  479. }
  480. }
  481. }
  482. // AbstractSelect cannot handle multiselection so we handle
  483. // it ourself
  484. if (variables.containsKey("selected") && isMultiSelect()
  485. && multiSelectMode == MultiSelectMode.DEFAULT) {
  486. handleSelectedItems(variables);
  487. variables = new HashMap<String, Object>(variables);
  488. variables.remove("selected");
  489. }
  490. // Selections are handled by the select component
  491. super.changeVariables(source, variables);
  492. // Actions
  493. if (variables.containsKey("action")) {
  494. final StringTokenizer st = new StringTokenizer(
  495. (String) variables.get("action"), ",");
  496. if (st.countTokens() == 2) {
  497. final Object itemId = itemIdMapper.get(st.nextToken());
  498. final Action action = actionMapper.get(st.nextToken());
  499. if (action != null && (itemId == null || containsId(itemId))
  500. && actionHandlers != null) {
  501. for (Handler ah : actionHandlers) {
  502. ah.handleAction(action, this, itemId);
  503. }
  504. }
  505. }
  506. }
  507. }
  508. /**
  509. * Handles the selection
  510. *
  511. * @param variables
  512. * The variables sent to the server from the client
  513. */
  514. private void handleSelectedItems(Map<String, Object> variables) {
  515. final String[] ka = (String[]) variables.get("selected");
  516. // Converts the key-array to id-set
  517. final LinkedList<Object> s = new LinkedList<Object>();
  518. for (int i = 0; i < ka.length; i++) {
  519. final Object id = itemIdMapper.get(ka[i]);
  520. if (!isNullSelectionAllowed()
  521. && (id == null || id == getNullSelectionItemId())) {
  522. // skip empty selection if nullselection is not allowed
  523. markAsDirty();
  524. } else if (id != null && containsId(id)) {
  525. s.add(id);
  526. }
  527. }
  528. if (!isNullSelectionAllowed() && s.size() < 1) {
  529. // empty selection not allowed, keep old value
  530. markAsDirty();
  531. return;
  532. }
  533. setValue(s, true);
  534. }
  535. /**
  536. * Paints any needed component-specific things to the given UIDL stream.
  537. *
  538. * @see com.vaadin.ui.AbstractComponent#paintContent(PaintTarget)
  539. */
  540. @Override
  541. public void paintContent(PaintTarget target) throws PaintException {
  542. initialPaint = false;
  543. if (partialUpdate) {
  544. target.addAttribute("partialUpdate", true);
  545. target.addAttribute("rootKey", itemIdMapper.key(expandedItemId));
  546. } else {
  547. getCaptionChangeListener().clear();
  548. // The tab ordering number
  549. if (getTabIndex() > 0) {
  550. target.addAttribute("tabindex", getTabIndex());
  551. }
  552. // Paint tree attributes
  553. if (isSelectable()) {
  554. target.addAttribute("selectmode", (isMultiSelect() ? "multi"
  555. : "single"));
  556. if (isMultiSelect()) {
  557. target.addAttribute("multiselectmode",
  558. multiSelectMode.toString());
  559. }
  560. } else {
  561. target.addAttribute("selectmode", "none");
  562. }
  563. if (isNewItemsAllowed()) {
  564. target.addAttribute("allownewitem", true);
  565. }
  566. if (isNullSelectionAllowed()) {
  567. target.addAttribute("nullselect", true);
  568. }
  569. if (dragMode != TreeDragMode.NONE) {
  570. target.addAttribute("dragMode", dragMode.ordinal());
  571. }
  572. if (isHtmlContentAllowed()) {
  573. target.addAttribute(TreeConstants.ATTRIBUTE_HTML_ALLOWED, true);
  574. }
  575. }
  576. // Initialize variables
  577. final Set<Action> actionSet = new LinkedHashSet<Action>();
  578. // rendered selectedKeys
  579. LinkedList<String> selectedKeys = new LinkedList<String>();
  580. final LinkedList<String> expandedKeys = new LinkedList<String>();
  581. // Iterates through hierarchical tree using a stack of iterators
  582. final Stack<Iterator<?>> iteratorStack = new Stack<Iterator<?>>();
  583. Collection<?> ids;
  584. if (partialUpdate) {
  585. ids = getChildren(expandedItemId);
  586. } else {
  587. ids = rootItemIds();
  588. }
  589. if (ids != null) {
  590. iteratorStack.push(ids.iterator());
  591. }
  592. /*
  593. * Body actions - Actions which has the target null and can be invoked
  594. * by right clicking on the Tree body
  595. */
  596. if (actionHandlers != null) {
  597. final ArrayList<String> keys = new ArrayList<String>();
  598. for (Handler ah : actionHandlers) {
  599. // Getting action for the null item, which in this case
  600. // means the body item
  601. final Action[] aa = ah.getActions(null, this);
  602. if (aa != null) {
  603. for (int ai = 0; ai < aa.length; ai++) {
  604. final String akey = actionMapper.key(aa[ai]);
  605. actionSet.add(aa[ai]);
  606. keys.add(akey);
  607. }
  608. }
  609. }
  610. target.addAttribute("alb", keys.toArray());
  611. }
  612. while (!iteratorStack.isEmpty()) {
  613. // Gets the iterator for current tree level
  614. final Iterator<?> i = iteratorStack.peek();
  615. // If the level is finished, back to previous tree level
  616. if (!i.hasNext()) {
  617. // Removes used iterator from the stack
  618. iteratorStack.pop();
  619. // Closes node
  620. if (!iteratorStack.isEmpty()) {
  621. target.endTag("node");
  622. }
  623. }
  624. // Adds the item on current level
  625. else {
  626. final Object itemId = i.next();
  627. // Starts the item / node
  628. final boolean isNode = areChildrenAllowed(itemId);
  629. if (isNode) {
  630. target.startTag("node");
  631. } else {
  632. target.startTag("leaf");
  633. }
  634. if (itemStyleGenerator != null) {
  635. String stylename = itemStyleGenerator
  636. .getStyle(this, itemId);
  637. if (stylename != null) {
  638. target.addAttribute(TreeConstants.ATTRIBUTE_NODE_STYLE,
  639. stylename);
  640. }
  641. }
  642. if (itemDescriptionGenerator != null) {
  643. String description = itemDescriptionGenerator
  644. .generateDescription(this, itemId, null);
  645. if (description != null && !description.equals("")) {
  646. target.addAttribute("descr", description);
  647. }
  648. }
  649. // Adds the attributes
  650. target.addAttribute(TreeConstants.ATTRIBUTE_NODE_CAPTION,
  651. getItemCaption(itemId));
  652. final Resource icon = getItemIcon(itemId);
  653. if (icon != null) {
  654. target.addAttribute(TreeConstants.ATTRIBUTE_NODE_ICON,
  655. getItemIcon(itemId));
  656. target.addAttribute(TreeConstants.ATTRIBUTE_NODE_ICON_ALT,
  657. getItemIconAlternateText(itemId));
  658. }
  659. final String key = itemIdMapper.key(itemId);
  660. target.addAttribute("key", key);
  661. if (isSelected(itemId)) {
  662. target.addAttribute("selected", true);
  663. selectedKeys.add(key);
  664. }
  665. if (areChildrenAllowed(itemId) && isExpanded(itemId)) {
  666. target.addAttribute("expanded", true);
  667. expandedKeys.add(key);
  668. }
  669. // Add caption change listener
  670. getCaptionChangeListener().addNotifierForItem(itemId);
  671. // Actions
  672. if (actionHandlers != null) {
  673. final ArrayList<String> keys = new ArrayList<String>();
  674. final Iterator<Action.Handler> ahi = actionHandlers
  675. .iterator();
  676. while (ahi.hasNext()) {
  677. final Action[] aa = ahi.next().getActions(itemId, this);
  678. if (aa != null) {
  679. for (int ai = 0; ai < aa.length; ai++) {
  680. final String akey = actionMapper.key(aa[ai]);
  681. actionSet.add(aa[ai]);
  682. keys.add(akey);
  683. }
  684. }
  685. }
  686. target.addAttribute("al", keys.toArray());
  687. }
  688. // Adds the children if expanded, or close the tag
  689. if (isExpanded(itemId) && hasChildren(itemId)
  690. && areChildrenAllowed(itemId)) {
  691. iteratorStack.push(getChildren(itemId).iterator());
  692. } else {
  693. if (isNode) {
  694. target.endTag("node");
  695. } else {
  696. target.endTag("leaf");
  697. }
  698. }
  699. }
  700. }
  701. // Actions
  702. if (!actionSet.isEmpty()) {
  703. target.addVariable(this, "action", "");
  704. target.startTag("actions");
  705. final Iterator<Action> i = actionSet.iterator();
  706. while (i.hasNext()) {
  707. final Action a = i.next();
  708. target.startTag("action");
  709. if (a.getCaption() != null) {
  710. target.addAttribute(TreeConstants.ATTRIBUTE_ACTION_CAPTION,
  711. a.getCaption());
  712. }
  713. if (a.getIcon() != null) {
  714. target.addAttribute(TreeConstants.ATTRIBUTE_ACTION_ICON,
  715. a.getIcon());
  716. }
  717. target.addAttribute("key", actionMapper.key(a));
  718. target.endTag("action");
  719. }
  720. target.endTag("actions");
  721. }
  722. if (partialUpdate) {
  723. partialUpdate = false;
  724. } else {
  725. // Selected
  726. target.addVariable(this, "selected",
  727. selectedKeys.toArray(new String[selectedKeys.size()]));
  728. // Expand and collapse
  729. target.addVariable(this, "expand", new String[] {});
  730. target.addVariable(this, "collapse", new String[] {});
  731. // New items
  732. target.addVariable(this, "newitem", new String[] {});
  733. if (dropHandler != null) {
  734. dropHandler.getAcceptCriterion().paint(target);
  735. }
  736. }
  737. }
  738. /* Container.Hierarchical API */
  739. /**
  740. * Tests if the Item with given ID can have any children.
  741. *
  742. * @see com.vaadin.data.Container.Hierarchical#areChildrenAllowed(Object)
  743. */
  744. @Override
  745. public boolean areChildrenAllowed(Object itemId) {
  746. return ((Container.Hierarchical) items).areChildrenAllowed(itemId);
  747. }
  748. /**
  749. * Gets the IDs of all Items that are children of the specified Item.
  750. *
  751. * @see com.vaadin.data.Container.Hierarchical#getChildren(Object)
  752. */
  753. @Override
  754. public Collection<?> getChildren(Object itemId) {
  755. return ((Container.Hierarchical) items).getChildren(itemId);
  756. }
  757. /**
  758. * Gets the ID of the parent Item of the specified Item.
  759. *
  760. * @see com.vaadin.data.Container.Hierarchical#getParent(Object)
  761. */
  762. @Override
  763. public Object getParent(Object itemId) {
  764. return ((Container.Hierarchical) items).getParent(itemId);
  765. }
  766. /**
  767. * Tests if the Item specified with <code>itemId</code> has child Items.
  768. *
  769. * @see com.vaadin.data.Container.Hierarchical#hasChildren(Object)
  770. */
  771. @Override
  772. public boolean hasChildren(Object itemId) {
  773. return ((Container.Hierarchical) items).hasChildren(itemId);
  774. }
  775. /**
  776. * Tests if the Item specified with <code>itemId</code> is a root Item.
  777. *
  778. * @see com.vaadin.data.Container.Hierarchical#isRoot(Object)
  779. */
  780. @Override
  781. public boolean isRoot(Object itemId) {
  782. return ((Container.Hierarchical) items).isRoot(itemId);
  783. }
  784. /**
  785. * Gets the IDs of all Items in the container that don't have a parent.
  786. *
  787. * @see com.vaadin.data.Container.Hierarchical#rootItemIds()
  788. */
  789. @Override
  790. public Collection<?> rootItemIds() {
  791. return ((Container.Hierarchical) items).rootItemIds();
  792. }
  793. /**
  794. * Sets the given Item's capability to have children.
  795. *
  796. * @see com.vaadin.data.Container.Hierarchical#setChildrenAllowed(Object,
  797. * boolean)
  798. */
  799. @Override
  800. public boolean setChildrenAllowed(Object itemId, boolean areChildrenAllowed) {
  801. final boolean success = ((Container.Hierarchical) items)
  802. .setChildrenAllowed(itemId, areChildrenAllowed);
  803. if (success) {
  804. markAsDirty();
  805. }
  806. return success;
  807. }
  808. /*
  809. * (non-Javadoc)
  810. *
  811. * @see com.vaadin.data.Container.Hierarchical#setParent(java.lang.Object ,
  812. * java.lang.Object)
  813. */
  814. @Override
  815. public boolean setParent(Object itemId, Object newParentId) {
  816. final boolean success = ((Container.Hierarchical) items).setParent(
  817. itemId, newParentId);
  818. if (success) {
  819. markAsDirty();
  820. }
  821. return success;
  822. }
  823. /* Overriding select behavior */
  824. /**
  825. * Sets the Container that serves as the data source of the viewer.
  826. *
  827. * @see com.vaadin.data.Container.Viewer#setContainerDataSource(Container)
  828. */
  829. @Override
  830. public void setContainerDataSource(Container newDataSource) {
  831. if (newDataSource == null) {
  832. newDataSource = new HierarchicalContainer();
  833. }
  834. // Assure that the data source is ordered by making unordered
  835. // containers ordered by wrapping them
  836. if (Container.Hierarchical.class.isAssignableFrom(newDataSource
  837. .getClass())) {
  838. super.setContainerDataSource(newDataSource);
  839. } else {
  840. super.setContainerDataSource(new ContainerHierarchicalWrapper(
  841. newDataSource));
  842. }
  843. /*
  844. * Ensure previous expanded items are cleaned up if they don't exist in
  845. * the new container
  846. */
  847. if (expanded != null) {
  848. /*
  849. * We need to check that the expanded-field is not null since
  850. * setContainerDataSource() is called from the parent constructor
  851. * (AbstractSelect()) and at that time the expanded field is not yet
  852. * initialized.
  853. */
  854. cleanupExpandedItems();
  855. }
  856. }
  857. @Override
  858. public void containerItemSetChange(
  859. com.vaadin.data.Container.ItemSetChangeEvent event) {
  860. super.containerItemSetChange(event);
  861. if (getContainerDataSource() instanceof Filterable) {
  862. boolean hasFilters = !((Filterable) getContainerDataSource())
  863. .getContainerFilters().isEmpty();
  864. if (!hasFilters) {
  865. /*
  866. * If Container is not filtered then the itemsetchange is caused
  867. * by either adding or removing items to the container. To
  868. * prevent a memory leak we should cleanup the expanded list
  869. * from items which was removed.
  870. *
  871. * However, there will still be a leak if the container is
  872. * filtered to show only a subset of the items in the tree and
  873. * later unfiltered items are removed from the container. In
  874. * that case references to the unfiltered item ids will remain
  875. * in the expanded list until the Tree instance is removed and
  876. * the list is destroyed, or the container data source is
  877. * replaced/updated. To force the removal of the removed items
  878. * the application developer needs to a) remove the container
  879. * filters temporarly or b) re-apply the container datasource
  880. * using setContainerDataSource(getContainerDataSource())
  881. */
  882. cleanupExpandedItems();
  883. }
  884. }
  885. }
  886. /* Expand event and listener */
  887. /**
  888. * Event to fired when a node is expanded. ExapandEvent is fired when a node
  889. * is to be expanded. it can me used to dynamically fill the sub-nodes of
  890. * the node.
  891. *
  892. * @author Vaadin Ltd.
  893. * @since 3.0
  894. */
  895. public static class ExpandEvent extends Component.Event {
  896. private final Object expandedItemId;
  897. /**
  898. * New instance of options change event
  899. *
  900. * @param source
  901. * the Source of the event.
  902. * @param expandedItemId
  903. */
  904. public ExpandEvent(Component source, Object expandedItemId) {
  905. super(source);
  906. this.expandedItemId = expandedItemId;
  907. }
  908. /**
  909. * Node where the event occurred.
  910. *
  911. * @return the Source of the event.
  912. */
  913. public Object getItemId() {
  914. return expandedItemId;
  915. }
  916. }
  917. /**
  918. * Expand event listener.
  919. *
  920. * @author Vaadin Ltd.
  921. * @since 3.0
  922. */
  923. public interface ExpandListener extends Serializable {
  924. public static final Method EXPAND_METHOD = ReflectTools.findMethod(
  925. ExpandListener.class, "nodeExpand", ExpandEvent.class);
  926. /**
  927. * A node has been expanded.
  928. *
  929. * @param event
  930. * the Expand event.
  931. */
  932. public void nodeExpand(ExpandEvent event);
  933. }
  934. /**
  935. * Adds the expand listener.
  936. *
  937. * @param listener
  938. * the Listener to be added.
  939. */
  940. public void addExpandListener(ExpandListener listener) {
  941. addListener(ExpandEvent.class, listener, ExpandListener.EXPAND_METHOD);
  942. }
  943. /**
  944. * @deprecated As of 7.0, replaced by
  945. * {@link #addExpandListener(ExpandListener)}
  946. **/
  947. @Deprecated
  948. public void addListener(ExpandListener listener) {
  949. addExpandListener(listener);
  950. }
  951. /**
  952. * Removes the expand listener.
  953. *
  954. * @param listener
  955. * the Listener to be removed.
  956. */
  957. public void removeExpandListener(ExpandListener listener) {
  958. removeListener(ExpandEvent.class, listener,
  959. ExpandListener.EXPAND_METHOD);
  960. }
  961. /**
  962. * @deprecated As of 7.0, replaced by
  963. * {@link #removeExpandListener(ExpandListener)}
  964. **/
  965. @Deprecated
  966. public void removeListener(ExpandListener listener) {
  967. removeExpandListener(listener);
  968. }
  969. /**
  970. * Emits the expand event.
  971. *
  972. * @param itemId
  973. * the item id.
  974. */
  975. protected void fireExpandEvent(Object itemId) {
  976. fireEvent(new ExpandEvent(this, itemId));
  977. }
  978. /* Collapse event */
  979. /**
  980. * Collapse event
  981. *
  982. * @author Vaadin Ltd.
  983. * @since 3.0
  984. */
  985. public static class CollapseEvent extends Component.Event {
  986. private final Object collapsedItemId;
  987. /**
  988. * New instance of options change event.
  989. *
  990. * @param source
  991. * the Source of the event.
  992. * @param collapsedItemId
  993. */
  994. public CollapseEvent(Component source, Object collapsedItemId) {
  995. super(source);
  996. this.collapsedItemId = collapsedItemId;
  997. }
  998. /**
  999. * Gets tge Collapsed Item id.
  1000. *
  1001. * @return the collapsed item id.
  1002. */
  1003. public Object getItemId() {
  1004. return collapsedItemId;
  1005. }
  1006. }
  1007. /**
  1008. * Collapse event listener.
  1009. *
  1010. * @author Vaadin Ltd.
  1011. * @since 3.0
  1012. */
  1013. public interface CollapseListener extends Serializable {
  1014. public static final Method COLLAPSE_METHOD = ReflectTools.findMethod(
  1015. CollapseListener.class, "nodeCollapse", CollapseEvent.class);
  1016. /**
  1017. * A node has been collapsed.
  1018. *
  1019. * @param event
  1020. * the Collapse event.
  1021. */
  1022. public void nodeCollapse(CollapseEvent event);
  1023. }
  1024. /**
  1025. * Adds the collapse listener.
  1026. *
  1027. * @param listener
  1028. * the Listener to be added.
  1029. */
  1030. public void addCollapseListener(CollapseListener listener) {
  1031. addListener(CollapseEvent.class, listener,
  1032. CollapseListener.COLLAPSE_METHOD);
  1033. }
  1034. /**
  1035. * @deprecated As of 7.0, replaced by
  1036. * {@link #addCollapseListener(CollapseListener)}
  1037. **/
  1038. @Deprecated
  1039. public void addListener(CollapseListener listener) {
  1040. addCollapseListener(listener);
  1041. }
  1042. /**
  1043. * Removes the collapse listener.
  1044. *
  1045. * @param listener
  1046. * the Listener to be removed.
  1047. */
  1048. public void removeCollapseListener(CollapseListener listener) {
  1049. removeListener(CollapseEvent.class, listener,
  1050. CollapseListener.COLLAPSE_METHOD);
  1051. }
  1052. /**
  1053. * @deprecated As of 7.0, replaced by
  1054. * {@link #removeCollapseListener(CollapseListener)}
  1055. **/
  1056. @Deprecated
  1057. public void removeListener(CollapseListener listener) {
  1058. removeCollapseListener(listener);
  1059. }
  1060. /**
  1061. * Emits collapse event.
  1062. *
  1063. * @param itemId
  1064. * the item id.
  1065. */
  1066. protected void fireCollapseEvent(Object itemId) {
  1067. fireEvent(new CollapseEvent(this, itemId));
  1068. }
  1069. /* Action container */
  1070. /**
  1071. * Adds an action handler.
  1072. *
  1073. * @see com.vaadin.event.Action.Container#addActionHandler(Action.Handler)
  1074. */
  1075. @Override
  1076. public void addActionHandler(Action.Handler actionHandler) {
  1077. if (actionHandler != null) {
  1078. if (actionHandlers == null) {
  1079. actionHandlers = new LinkedList<Action.Handler>();
  1080. actionMapper = new KeyMapper<Action>();
  1081. }
  1082. if (!actionHandlers.contains(actionHandler)) {
  1083. actionHandlers.add(actionHandler);
  1084. markAsDirty();
  1085. }
  1086. }
  1087. }
  1088. /**
  1089. * Removes an action handler.
  1090. *
  1091. * @see com.vaadin.event.Action.Container#removeActionHandler(Action.Handler)
  1092. */
  1093. @Override
  1094. public void removeActionHandler(Action.Handler actionHandler) {
  1095. if (actionHandlers != null && actionHandlers.contains(actionHandler)) {
  1096. actionHandlers.remove(actionHandler);
  1097. if (actionHandlers.isEmpty()) {
  1098. actionHandlers = null;
  1099. actionMapper = null;
  1100. }
  1101. markAsDirty();
  1102. }
  1103. }
  1104. /**
  1105. * Removes all action handlers
  1106. */
  1107. public void removeAllActionHandlers() {
  1108. actionHandlers = null;
  1109. actionMapper = null;
  1110. markAsDirty();
  1111. }
  1112. /**
  1113. * Gets the visible item ids.
  1114. *
  1115. * @see com.vaadin.ui.Select#getVisibleItemIds()
  1116. */
  1117. @Override
  1118. public Collection<?> getVisibleItemIds() {
  1119. final LinkedList<Object> visible = new LinkedList<Object>();
  1120. // Iterates trough hierarchical tree using a stack of iterators
  1121. final Stack<Iterator<?>> iteratorStack = new Stack<Iterator<?>>();
  1122. final Collection<?> ids = rootItemIds();
  1123. if (ids != null) {
  1124. iteratorStack.push(ids.iterator());
  1125. }
  1126. while (!iteratorStack.isEmpty()) {
  1127. // Gets the iterator for current tree level
  1128. final Iterator<?> i = iteratorStack.peek();
  1129. // If the level is finished, back to previous tree level
  1130. if (!i.hasNext()) {
  1131. // Removes used iterator from the stack
  1132. iteratorStack.pop();
  1133. }
  1134. // Adds the item on current level
  1135. else {
  1136. final Object itemId = i.next();
  1137. visible.add(itemId);
  1138. // Adds children if expanded, or close the tag
  1139. if (isExpanded(itemId) && hasChildren(itemId)) {
  1140. iteratorStack.push(getChildren(itemId).iterator());
  1141. }
  1142. }
  1143. }
  1144. return visible;
  1145. }
  1146. /**
  1147. * Tree does not support <code>setNullSelectionItemId</code>.
  1148. *
  1149. * @see com.vaadin.ui.AbstractSelect#setNullSelectionItemId(java.lang.Object)
  1150. */
  1151. @Override
  1152. public void setNullSelectionItemId(Object nullSelectionItemId)
  1153. throws UnsupportedOperationException {
  1154. if (nullSelectionItemId != null) {
  1155. throw new UnsupportedOperationException();
  1156. }
  1157. }
  1158. /**
  1159. * Adding new items is not supported.
  1160. *
  1161. * @throws UnsupportedOperationException
  1162. * if set to true.
  1163. * @see com.vaadin.ui.Select#setNewItemsAllowed(boolean)
  1164. */
  1165. @Override
  1166. public void setNewItemsAllowed(boolean allowNewOptions)
  1167. throws UnsupportedOperationException {
  1168. if (allowNewOptions) {
  1169. throw new UnsupportedOperationException();
  1170. }
  1171. }
  1172. private ItemStyleGenerator itemStyleGenerator;
  1173. private DropHandler dropHandler;
  1174. private boolean htmlContentAllowed;
  1175. @Override
  1176. public void addItemClickListener(ItemClickListener listener) {
  1177. addListener(TreeConstants.ITEM_CLICK_EVENT_ID, ItemClickEvent.class,
  1178. listener, ItemClickEvent.ITEM_CLICK_METHOD);
  1179. }
  1180. /**
  1181. * @deprecated As of 7.0, replaced by
  1182. * {@link #addItemClickListener(ItemClickListener)}
  1183. **/
  1184. @Override
  1185. @Deprecated
  1186. public void addListener(ItemClickListener listener) {
  1187. addItemClickListener(listener);
  1188. }
  1189. @Override
  1190. public void removeItemClickListener(ItemClickListener listener) {
  1191. removeListener(TreeConstants.ITEM_CLICK_EVENT_ID, ItemClickEvent.class,
  1192. listener);
  1193. }
  1194. /**
  1195. * @deprecated As of 7.0, replaced by
  1196. * {@link #removeItemClickListener(ItemClickListener)}
  1197. **/
  1198. @Override
  1199. @Deprecated
  1200. public void removeListener(ItemClickListener listener) {
  1201. removeItemClickListener(listener);
  1202. }
  1203. /**
  1204. * Sets the {@link ItemStyleGenerator} to be used with this tree.
  1205. *
  1206. * @param itemStyleGenerator
  1207. * item style generator or null to remove generator
  1208. */
  1209. public void setItemStyleGenerator(ItemStyleGenerator itemStyleGenerator) {
  1210. if (this.itemStyleGenerator != itemStyleGenerator) {
  1211. this.itemStyleGenerator = itemStyleGenerator;
  1212. markAsDirty();
  1213. }
  1214. }
  1215. /**
  1216. * @return the current {@link ItemStyleGenerator} for this tree. Null if
  1217. * {@link ItemStyleGenerator} is not set.
  1218. */
  1219. public ItemStyleGenerator getItemStyleGenerator() {
  1220. return itemStyleGenerator;
  1221. }
  1222. /**
  1223. * ItemStyleGenerator can be used to add custom styles to tree items. The
  1224. * CSS class name that will be added to the cell content is
  1225. * <tt>v-tree-node-[style name]</tt>.
  1226. */
  1227. public interface ItemStyleGenerator extends Serializable {
  1228. /**
  1229. * Called by Tree when an item is painted.
  1230. *
  1231. * @param source
  1232. * the source Tree
  1233. * @param itemId
  1234. * The itemId of the item to be painted
  1235. * @return The style name to add to this item. (the CSS class name will
  1236. * be v-tree-node-[style name]
  1237. */
  1238. public abstract String getStyle(Tree source, Object itemId);
  1239. }
  1240. // Overriden so javadoc comes from Container.Hierarchical
  1241. @Override
  1242. public boolean removeItem(Object itemId)
  1243. throws UnsupportedOperationException {
  1244. return super.removeItem(itemId);
  1245. }
  1246. @Override
  1247. public DropHandler getDropHandler() {
  1248. return dropHandler;
  1249. }
  1250. public void setDropHandler(DropHandler dropHandler) {
  1251. this.dropHandler = dropHandler;
  1252. }
  1253. /**
  1254. * A {@link TargetDetails} implementation with Tree specific api.
  1255. *
  1256. * @since 6.3
  1257. */
  1258. public class TreeTargetDetails extends AbstractSelectTargetDetails {
  1259. TreeTargetDetails(Map<String, Object> rawVariables) {
  1260. super(rawVariables);
  1261. }
  1262. @Override
  1263. public Tree getTarget() {
  1264. return (Tree) super.getTarget();
  1265. }
  1266. /**
  1267. * If the event is on a node that can not have children (see
  1268. * {@link Tree#areChildrenAllowed(Object)}), this method returns the
  1269. * parent item id of the target item (see {@link #getItemIdOver()} ).
  1270. * The identifier of the parent node is also returned if the cursor is
  1271. * on the top part of node. Else this method returns the same as
  1272. * {@link #getItemIdOver()}.
  1273. * <p>
  1274. * In other words this method returns the identifier of the "folder"
  1275. * into the drag operation is targeted.
  1276. * <p>
  1277. * If the method returns null, the current target is on a root node or
  1278. * on other undefined area over the tree component.
  1279. * <p>
  1280. * The default Tree implementation marks the targetted tree node with
  1281. * CSS classnames v-tree-node-dragfolder and
  1282. * v-tree-node-caption-dragfolder (for the caption element).
  1283. */
  1284. public Object getItemIdInto() {
  1285. Object itemIdOver = getItemIdOver();
  1286. if (areChildrenAllowed(itemIdOver)
  1287. && getDropLocation() == VerticalDropLocation.MIDDLE) {
  1288. return itemIdOver;
  1289. }
  1290. return getParent(itemIdOver);
  1291. }
  1292. /**
  1293. * If drop is targeted into "folder node" (see {@link #getItemIdInto()}
  1294. * ), this method returns the item id of the node after the drag was
  1295. * targeted. This method is useful when implementing drop into specific
  1296. * location (between specific nodes) in tree.
  1297. *
  1298. * @return the id of the item after the user targets the drop or null if
  1299. * "target" is a first item in node list (or the first in root
  1300. * node list)
  1301. */
  1302. public Object getItemIdAfter() {
  1303. Object itemIdOver = getItemIdOver();
  1304. Object itemIdInto2 = getItemIdInto();
  1305. if (itemIdOver.equals(itemIdInto2)) {
  1306. return null;
  1307. }
  1308. VerticalDropLocation dropLocation = getDropLocation();
  1309. if (VerticalDropLocation.TOP == dropLocation) {
  1310. // if on top of the caption area, add before
  1311. Collection<?> children;
  1312. Object itemIdInto = getItemIdInto();
  1313. if (itemIdInto != null) {
  1314. // seek the previous from child list
  1315. children = getChildren(itemIdInto);
  1316. } else {
  1317. children = rootItemIds();
  1318. }
  1319. Object ref = null;
  1320. for (Object object : children) {
  1321. if (object.equals(itemIdOver)) {
  1322. return ref;
  1323. }
  1324. ref = object;
  1325. }
  1326. }
  1327. return itemIdOver;
  1328. }
  1329. }
  1330. /*
  1331. * (non-Javadoc)
  1332. *
  1333. * @see
  1334. * com.vaadin.event.dd.DropTarget#translateDropTargetDetails(java.util.Map)
  1335. */
  1336. @Override
  1337. public TreeTargetDetails translateDropTargetDetails(
  1338. Map<String, Object> clientVariables) {
  1339. return new TreeTargetDetails(clientVariables);
  1340. }
  1341. /**
  1342. * Helper API for {@link TreeDropCriterion}
  1343. *
  1344. * @param itemId
  1345. * @return
  1346. */
  1347. private String key(Object itemId) {
  1348. return itemIdMapper.key(itemId);
  1349. }
  1350. /**
  1351. * Sets the drag mode that controls how Tree behaves as a {@link DragSource}
  1352. * .
  1353. *
  1354. * @param dragMode
  1355. */
  1356. public void setDragMode(TreeDragMode dragMode) {
  1357. this.dragMode = dragMode;
  1358. markAsDirty();
  1359. }
  1360. /**
  1361. * @return the drag mode that controls how Tree behaves as a
  1362. * {@link DragSource}.
  1363. *
  1364. * @see TreeDragMode
  1365. */
  1366. public TreeDragMode getDragMode() {
  1367. return dragMode;
  1368. }
  1369. /**
  1370. * Concrete implementation of {@link DataBoundTransferable} for data
  1371. * transferred from a tree.
  1372. *
  1373. * @see {@link DataBoundTransferable}.
  1374. *
  1375. * @since 6.3
  1376. */
  1377. protected class TreeTransferable extends DataBoundTransferable {
  1378. public TreeTransferable(Component sourceComponent,
  1379. Map<String, Object> rawVariables) {
  1380. super(sourceComponent, rawVariables);
  1381. }
  1382. @Override
  1383. public Object getItemId() {
  1384. return getData("itemId");
  1385. }
  1386. @Override
  1387. public Object getPropertyId() {
  1388. return getItemCaptionPropertyId();
  1389. }
  1390. }
  1391. /*
  1392. * (non-Javadoc)
  1393. *
  1394. * @see com.vaadin.event.dd.DragSource#getTransferable(java.util.Map)
  1395. */
  1396. @Override
  1397. public Transferable getTransferable(Map<String, Object> payload) {
  1398. TreeTransferable transferable = new TreeTransferable(this, payload);
  1399. // updating drag source variables
  1400. Object object = payload.get("itemId");
  1401. if (object != null) {
  1402. transferable.setData("itemId", itemIdMapper.get((String) object));
  1403. }
  1404. return transferable;
  1405. }
  1406. /**
  1407. * Lazy loading accept criterion for Tree. Accepted target nodes are loaded
  1408. * from server once per drag and drop operation. Developer must override one
  1409. * method that decides accepted tree nodes for the whole Tree.
  1410. *
  1411. * <p>
  1412. * Initially pretty much no data is sent to client. On first required
  1413. * criterion check (per drag request) the client side data structure is
  1414. * initialized from server and no subsequent requests requests are needed
  1415. * during that drag and drop operation.
  1416. */
  1417. public static abstract class TreeDropCriterion extends ServerSideCriterion {
  1418. private Tree tree;
  1419. private Set<Object> allowedItemIds;
  1420. /*
  1421. * (non-Javadoc)
  1422. *
  1423. * @see
  1424. * com.vaadin.event.dd.acceptCriteria.ServerSideCriterion#getIdentifier
  1425. * ()
  1426. */
  1427. @Override
  1428. protected String getIdentifier() {
  1429. return TreeDropCriterion.class.getCanonicalName();
  1430. }
  1431. /*
  1432. * (non-Javadoc)
  1433. *
  1434. * @see
  1435. * com.vaadin.event.dd.acceptCriteria.AcceptCriterion#accepts(com.vaadin
  1436. * .event.dd.DragAndDropEvent)
  1437. */
  1438. @Override
  1439. public boolean accept(DragAndDropEvent dragEvent) {
  1440. AbstractSelectTargetDetails dropTargetData = (AbstractSelectTargetDetails) dragEvent
  1441. .getTargetDetails();
  1442. tree = (Tree) dragEvent.getTargetDetails().getTarget();
  1443. allowedItemIds = getAllowedItemIds(dragEvent, tree);
  1444. return allowedItemIds.contains(dropTargetData.getItemIdOver());
  1445. }
  1446. /*
  1447. * (non-Javadoc)
  1448. *
  1449. * @see
  1450. * com.vaadin.event.dd.acceptCriteria.AcceptCriterion#paintResponse(
  1451. * com.vaadin.server.PaintTarget)
  1452. */
  1453. @Override
  1454. public void paintResponse(PaintTarget target) throws PaintException {
  1455. /*
  1456. * send allowed nodes to client so subsequent requests can be
  1457. * avoided
  1458. */
  1459. Object[] array = allowedItemIds.toArray();
  1460. for (int i = 0; i < array.length; i++) {
  1461. String key = tree.key(array[i]);
  1462. array[i] = key;
  1463. }
  1464. target.addAttribute("allowedIds", array);
  1465. }
  1466. protected abstract Set<Object> getAllowedItemIds(
  1467. DragAndDropEvent dragEvent, Tree tree);
  1468. }
  1469. /**
  1470. * A criterion that accepts {@link Transferable} only directly on a tree
  1471. * node that can have children.
  1472. * <p>
  1473. * Class is singleton, use {@link TargetItemAllowsChildren#get()} to get the
  1474. * instance.
  1475. *
  1476. * @see Tree#setChildrenAllowed(Object, boolean)
  1477. *
  1478. * @since 6.3
  1479. */
  1480. public static class TargetItemAllowsChildren extends TargetDetailIs {
  1481. private static TargetItemAllowsChildren instance = new TargetItemAllowsChildren();
  1482. public static TargetItemAllowsChildren get() {
  1483. return instance;
  1484. }
  1485. private TargetItemAllowsChildren() {
  1486. super("itemIdOverIsNode", Boolean.TRUE);
  1487. }
  1488. /*
  1489. * Uses enhanced server side check
  1490. */
  1491. @Override
  1492. public boolean accept(DragAndDropEvent dragEvent) {
  1493. try {
  1494. // must be over tree node and in the middle of it (not top or
  1495. // bottom
  1496. // part)
  1497. TreeTargetDetails eventDetails = (TreeTargetDetails) dragEvent
  1498. .getTargetDetails();
  1499. Object itemIdOver = eventDetails.getItemIdOver();
  1500. if (!eventDetails.getTarget().areChildrenAllowed(itemIdOver)) {
  1501. return false;
  1502. }
  1503. // return true if directly over
  1504. return eventDetails.getDropLocation() == VerticalDropLocation.MIDDLE;
  1505. } catch (Exception e) {
  1506. return false;
  1507. }
  1508. }
  1509. }
  1510. /**
  1511. * An accept criterion that checks the parent node (or parent hierarchy) for
  1512. * the item identifier given in constructor. If the parent is found, content
  1513. * is accepted. Criterion can be used to accepts drags on a specific sub
  1514. * tree only.
  1515. * <p>
  1516. * The root items is also consider to be valid target.
  1517. */
  1518. public class TargetInSubtree extends ClientSideCriterion {
  1519. private Object rootId;
  1520. private int depthToCheck = -1;
  1521. /**
  1522. * Constructs a criteria that accepts the drag if the targeted Item is a
  1523. * descendant of Item identified by given id
  1524. *
  1525. * @param parentItemId
  1526. * the item identifier of the parent node
  1527. */
  1528. public TargetInSubtree(Object parentItemId) {
  1529. rootId = parentItemId;
  1530. }
  1531. /**
  1532. * Constructs a criteria that accepts drops within given level below the
  1533. * subtree root identified by given id.
  1534. *
  1535. * @param rootId
  1536. * the item identifier to be sought for
  1537. * @param depthToCheck
  1538. * the depth that tree is traversed upwards to seek for the
  1539. * parent, -1 means that the whole structure should be
  1540. * checked
  1541. */
  1542. public TargetInSubtree(Object rootId, int depthToCheck) {
  1543. this.rootId = rootId;
  1544. this.depthToCheck = depthToCheck;
  1545. }
  1546. @Override
  1547. public boolean accept(DragAndDropEvent dragEvent) {
  1548. try {
  1549. TreeTargetDetails eventDetails = (TreeTargetDetails) dragEvent
  1550. .getTargetDetails();
  1551. if (eventDetails.getItemIdOver() != null) {
  1552. Object itemId = eventDetails.getItemIdOver();
  1553. int i = 0;
  1554. while (itemId != null
  1555. && (depthToCheck == -1 || i <= depthToCheck)) {
  1556. if (itemId.equals(rootId)) {
  1557. return true;
  1558. }
  1559. itemId = getParent(itemId);
  1560. i++;
  1561. }
  1562. }
  1563. return false;
  1564. } catch (Exception e) {
  1565. return false;
  1566. }
  1567. }
  1568. @Override
  1569. public void paintContent(PaintTarget target) throws PaintException {
  1570. super.paintContent(target);
  1571. target.addAttribute("depth", depthToCheck);
  1572. target.addAttribute("key", key(rootId));
  1573. }
  1574. }
  1575. /**
  1576. * Set the item description generator which generates tooltips for the tree
  1577. * items
  1578. *
  1579. * @param generator
  1580. * The generator to use or null to disable
  1581. */
  1582. public void setItemDescriptionGenerator(ItemDescriptionGenerator generator) {
  1583. if (generator != itemDescriptionGenerator) {
  1584. itemDescriptionGenerator = generator;
  1585. markAsDirty();
  1586. }
  1587. }
  1588. /**
  1589. * Get the item description generator which generates tooltips for tree
  1590. * items
  1591. */
  1592. public ItemDescriptionGenerator getItemDescriptionGenerator() {
  1593. return itemDescriptionGenerator;
  1594. }
  1595. private void cleanupExpandedItems() {
  1596. Set<Object> removedItemIds = new HashSet<Object>();
  1597. for (Object expandedItemId : expanded) {
  1598. if (getItem(expandedItemId) == null) {
  1599. removedItemIds.add(expandedItemId);
  1600. if (this.expandedItemId == expandedItemId) {
  1601. this.expandedItemId = null;
  1602. }
  1603. }
  1604. }
  1605. expanded.removeAll(removedItemIds);
  1606. }
  1607. /**
  1608. * Reads an Item from a design and inserts it into the data source.
  1609. * Recursively handles any children of the item as well.
  1610. *
  1611. * @since 7.5.0
  1612. * @param node
  1613. * an element representing the item (tree node).
  1614. * @param selected
  1615. * A set accumulating selected items. If the item that is read is
  1616. * marked as selected, its item id should be added to this set.
  1617. * @param context
  1618. * the DesignContext instance used in parsing
  1619. * @return the item id of the new item
  1620. *
  1621. * @throws DesignException
  1622. * if the tag name of the {@code node} element is not
  1623. * {@code node}.
  1624. */
  1625. @Override
  1626. protected String readItem(Element node, Set<String> selected,
  1627. DesignContext context) {
  1628. if (!"node".equals(node.tagName())) {
  1629. throw new DesignException("Unrecognized child element in "
  1630. + getClass().getSimpleName() + ": " + node.tagName());
  1631. }
  1632. String itemId = node.attr("text");
  1633. addItem(itemId);
  1634. if (node.hasAttr("icon")) {
  1635. Resource icon = DesignAttributeHandler.readAttribute("icon",
  1636. node.attributes(), Resource.class);
  1637. setItemIcon(itemId, icon);
  1638. }
  1639. if (node.hasAttr("selected")) {
  1640. selected.add(itemId);
  1641. }
  1642. for (Element child : node.children()) {
  1643. String childItemId = readItem(child, selected, context);
  1644. setParent(childItemId, itemId);
  1645. }
  1646. return itemId;
  1647. }
  1648. /**
  1649. * Recursively writes the root items and their children to a design.
  1650. *
  1651. * @since 7.5.0
  1652. * @param design
  1653. * the element into which to insert the items
  1654. * @param context
  1655. * the DesignContext instance used in writing
  1656. */
  1657. @Override
  1658. protected void writeItems(Element design, DesignContext context) {
  1659. for (Object itemId : rootItemIds()) {
  1660. writeItem(design, itemId, context);
  1661. }
  1662. }
  1663. /**
  1664. * Recursively writes a data source Item and its children to a design.
  1665. *
  1666. * @since 7.5.0
  1667. * @param design
  1668. * the element into which to insert the item
  1669. * @param itemId
  1670. * the id of the item to write
  1671. * @param context
  1672. * the DesignContext instance used in writing
  1673. * @return
  1674. */
  1675. @Override
  1676. protected Element writeItem(Element design, Object itemId,
  1677. DesignContext context) {
  1678. Element element = design.appendElement("node");
  1679. element.attr("text", itemId.toString());
  1680. Resource icon = getItemIcon(itemId);
  1681. if (icon != null) {
  1682. DesignAttributeHandler.writeAttribute("icon", element.attributes(),
  1683. icon, null, Resource.class);
  1684. }
  1685. if (isSelected(itemId)) {
  1686. element.attr("selected", "");
  1687. }
  1688. Collection<?> children = getChildren(itemId);
  1689. if (children != null) {
  1690. // Yeah... see #5864
  1691. for (Object childItemId : children) {
  1692. writeItem(element, childItemId, context);
  1693. }
  1694. }
  1695. return element;
  1696. }
  1697. /**
  1698. * Sets whether html is allowed in the item captions. If set to
  1699. * <code>true</code>, the captions are passed to the browser as html and the
  1700. * developer is responsible for ensuring no harmful html is used. If set to
  1701. * <code>false</code>, the content is passed to the browser as plain text.
  1702. * The default setting is <code>false</code>
  1703. *
  1704. * @since 7.6
  1705. * @param htmlContentAllowed
  1706. * <code>true</code> if the captions are used as html,
  1707. * <code>false</code> if used as plain text
  1708. */
  1709. public void setHtmlContentAllowed(boolean htmlContentAllowed) {
  1710. this.htmlContentAllowed = htmlContentAllowed;
  1711. markAsDirty();
  1712. }
  1713. /**
  1714. * Checks whether captions are interpreted as html or plain text.
  1715. *
  1716. * @since 7.6
  1717. * @return <code>true</code> if the captions are displayed as html,
  1718. * <code>false</code> if displayed as plain text
  1719. * @see #setHtmlContentAllowed(boolean)
  1720. */
  1721. public boolean isHtmlContentAllowed() {
  1722. return htmlContentAllowed;
  1723. }
  1724. }