Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

Tree.java 61KB

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