001 package net.sf.tacos.components.tree; 002 003 import java.io.Serializable; 004 import java.util.Collection; 005 import java.util.Iterator; 006 import java.util.Set; 007 import net.sf.tacos.model.IKeyProvider; 008 import net.sf.tacos.model.ITreeContentProvider; 009 import org.apache.hivemind.util.Defense; 010 011 /** 012 * @author phraktle 013 */ 014 public class TreeManager implements ITreeManager { 015 016 private final Set state; 017 private final ITreeContentProvider contentProvider; 018 private final IKeyProvider keyProvider; 019 020 /** 021 * Creates tree manager. 022 * @param state 023 * @param contentProvider 024 * @param keyProvider 025 */ 026 public TreeManager(Set state, ITreeContentProvider contentProvider, 027 IKeyProvider keyProvider) 028 { 029 Defense.notNull(state, "tree state"); 030 Defense.notNull(contentProvider, "tree contentProvider"); 031 Defense.notNull(keyProvider, "tree keyProvider"); 032 033 this.state = state; 034 this.contentProvider = contentProvider; 035 this.keyProvider = keyProvider; 036 } 037 038 /** 039 * 040 * {@inheritDoc} 041 */ 042 public boolean isExpanded(Object element) 043 { 044 return isExpandedKey(keyProvider.getKey(element)); 045 } 046 047 /** 048 * 049 * {@inheritDoc} 050 */ 051 public boolean isExpandedKey(Serializable key) 052 { 053 return state.contains(key); 054 } 055 056 /** 057 * 058 * {@inheritDoc} 059 */ 060 public void setExpanded(Object element, boolean open) 061 { 062 setExpandedKey(keyProvider.getKey(element), open); 063 } 064 065 /** 066 * 067 * {@inheritDoc} 068 */ 069 public void setExpandedKey(Serializable key, boolean open) 070 { 071 if (open) { 072 state.add(key); 073 } else { 074 state.remove(key); 075 } 076 } 077 078 /** 079 * 080 * @return 081 */ 082 public Set getState() 083 { 084 return state; 085 } 086 087 /** 088 * 089 * {@inheritDoc} 090 */ 091 public void collapseAll() 092 { 093 state.clear(); 094 } 095 096 /** 097 * 098 * {@inheritDoc} 099 */ 100 public Object reveal(Object element) 101 { 102 Object parent = contentProvider.getParent(element); 103 if (parent != null) { 104 setExpanded(parent, true); 105 return reveal(parent); 106 } else return element; 107 } 108 109 /** 110 * 111 * {@inheritDoc} 112 */ 113 public void expandAll() 114 { 115 expand(contentProvider.getElements()); 116 } 117 118 /** 119 * Expands all elements 120 * @param rootElements 121 */ 122 private void expand(Collection rootElements) 123 { 124 for(Iterator i = rootElements.iterator(); i.hasNext();) { 125 Object element = i.next(); 126 setExpanded(element, true); 127 if (contentProvider.hasChildren(element)) { 128 expand(contentProvider.getChildren(element)); 129 } 130 } 131 } 132 133 }