1 11 package org.eclipse.ui.internal.texteditor; 12 13 import java.util.HashMap ; 14 import java.util.Iterator ; 15 import java.util.LinkedHashSet ; 16 import java.util.Map ; 17 import java.util.Set ; 18 19 import org.eclipse.core.runtime.Assert; 20 21 import org.eclipse.jface.preference.IPreferenceStore; 22 import org.eclipse.jface.util.IPropertyChangeListener; 23 import org.eclipse.jface.util.PropertyChangeEvent; 24 25 public final class PropertyEventDispatcher { 26 private final Map fHandlerMap= new HashMap (); 27 private final Map fReverseMap= new HashMap (); 28 private final IPreferenceStore fStore; 29 private final IPropertyChangeListener fListener= new IPropertyChangeListener() { 30 public void propertyChange(PropertyChangeEvent event) { 31 firePropertyChange(event); 32 } 33 }; 34 public PropertyEventDispatcher(IPreferenceStore store) { 35 Assert.isLegal(store != null); 36 fStore= store; 37 } 38 public void dispose() { 39 if (!fReverseMap.isEmpty()) 40 fStore.removePropertyChangeListener(fListener); 41 fReverseMap.clear(); 42 fHandlerMap.clear(); 43 } 44 private void firePropertyChange(PropertyChangeEvent event) { 45 Object value= fHandlerMap.get(event.getProperty()); 46 if (value instanceof IPropertyChangeListener) 47 ((IPropertyChangeListener) value).propertyChange(event); 48 else if (value instanceof Set ) 49 for (Iterator it= ((Set ) value).iterator(); it.hasNext(); ) 50 ((IPropertyChangeListener) it.next()).propertyChange(event); 51 } 52 public void addPropertyChangeListener(String property, IPropertyChangeListener listener) { 53 Assert.isLegal(property != null); 54 Assert.isLegal(listener != null); 55 56 if (fReverseMap.isEmpty()) 57 fStore.addPropertyChangeListener(fListener); 58 59 multiMapPut(fHandlerMap, property, listener); 60 multiMapPut(fReverseMap, listener, property); 61 } 62 private void multiMapPut(Map map, Object key, Object value) { 63 Object mapping= map.get(key); 64 if (mapping == null) { 65 map.put(key, value); 66 } else if (mapping instanceof Set ) { 67 ((Set ) mapping).add(value); 68 } else { 69 Set set= new LinkedHashSet (); 70 set.add(mapping); 71 set.add(value); 72 map.put(key, set); 73 } 74 } 75 private void multiMapRemove(Map map, Object key, Object value) { 76 Object mapping= map.get(key); 77 if (mapping instanceof Set ) { 78 ((Set ) mapping).remove(value); 79 } else if (mapping != null) { 80 map.remove(key); 81 } 82 } 83 public void removePropertyChangeListener(IPropertyChangeListener listener) { 84 Object value= fReverseMap.get(listener); 85 if (value == null) 86 return; 87 if (value instanceof String ) { 88 fReverseMap.remove(listener); 89 multiMapRemove(fHandlerMap, value, listener); 90 } else if (value instanceof Set ) { 91 fReverseMap.remove(listener); 92 for (Iterator it= ((Set ) value).iterator(); it.hasNext();) 93 multiMapRemove(fHandlerMap, it.next(), listener); 94 } 95 96 if (fReverseMap.isEmpty()) 97 fStore.removePropertyChangeListener(fListener); 98 } 99 } | Popular Tags |