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

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