3m9 compatible;
[phpeclipse.git] / net.sourceforge.phpeclipse / src / net / sourceforge / phpdt / internal / core / JavaModelManager.java
index 4c295b7..16347d2 100644 (file)
@@ -18,6 +18,7 @@ import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
 import java.io.IOException;
+import java.text.NumberFormat;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.HashMap;
@@ -43,6 +44,7 @@ import net.sourceforge.phpdt.core.JavaCore;
 import net.sourceforge.phpdt.internal.ui.util.PHPFileUtil;
 import net.sourceforge.phpeclipse.PHPeclipsePlugin;
 import net.sourceforge.phpdt.internal.core.builder.PHPBuilder;
+import net.sourceforge.phpdt.internal.core.util.Util;
 
 import org.eclipse.core.resources.IFile;
 import org.eclipse.core.resources.IFolder;
@@ -67,6 +69,24 @@ import org.eclipse.core.runtime.Platform;
 import org.eclipse.core.runtime.Plugin;
 import org.eclipse.core.runtime.Preferences;
 import org.eclipse.core.runtime.Status;
+import net.sourceforge.phpdt.internal.core.BufferManager;
+
+import net.sourceforge.phpdt.internal.core.DefaultWorkingCopyOwner;
+
+import net.sourceforge.phpdt.internal.core.DeltaProcessingState;
+
+import net.sourceforge.phpdt.internal.core.DeltaProcessor;
+
+import net.sourceforge.phpdt.core.IParent;
+import net.sourceforge.phpdt.internal.core.JavaElementInfo;
+
+import net.sourceforge.phpdt.core.IProblemRequestor;
+import net.sourceforge.phpdt.core.WorkingCopyOwner;
+import net.sourceforge.phpdt.core.compiler.IProblem;
+import net.sourceforge.phpdt.internal.core.CompilationUnit;
+import net.sourceforge.phpdt.internal.core.JavaElement;
+import net.sourceforge.phpdt.internal.core.JavaElementDeltaBuilder;
+import net.sourceforge.phpdt.internal.core.JavaModelManager.PerWorkingCopyInfo;
 
 /**
  * The <code>JavaModelManager</code> manages instances of <code>IJavaModel</code>.
@@ -143,6 +163,11 @@ public class JavaModelManager implements ISaveParticipant {
        public final static IWorkingCopy[] NoWorkingCopy = new IWorkingCopy[0];
        
        /**
+        * Table from WorkingCopyOwner to a table of ICompilationUnit (working copy handle) to PerWorkingCopyInfo.
+        * NOTE: this object itself is used as a lock to synchronize creation/removal of per working copy infos
+        */
+       protected Map perWorkingCopyInfos = new HashMap(5);
+       /**
         * Returns whether the given full path (for a package) conflicts with the output location
         * of the given project.
         */
@@ -412,7 +437,7 @@ public class JavaModelManager implements ISaveParticipant {
                IPath resourcePath = resource.getFullPath();
                try {
                        IClasspathEntry[] entries = 
-                               Util.isJavaFileName(resourcePath.lastSegment())
+                               net.sourceforge.phpdt.internal.compiler.util.Util.isJavaFileName(resourcePath.lastSegment())
                                        ? project.getRawClasspath() // JAVA file can only live inside SRC folder (on the raw path)
                                        : ((JavaProject)project).getResolvedClasspath(true);
                                
@@ -460,11 +485,18 @@ public class JavaModelManager implements ISaveParticipant {
         */
        protected JavaModelCache cache = new JavaModelCache();
 
+       /*
+        * Temporary cache of newly opened elements
+        */
+       private ThreadLocal temporaryCache = new ThreadLocal();
        /**
         * Set of elements which are out of sync with their buffers.
         */
        protected Map elementsOutOfSynchWithBuffers = new HashMap(11);
-       
+       /**
+        * Holds the state used for delta processing.
+        */
+       public DeltaProcessingState deltaState = new DeltaProcessingState();
        /**
         * Turns delta firing on/off. By default it is on.
         */
@@ -496,7 +528,7 @@ public class JavaModelManager implements ISaveParticipant {
        /**
         * Used to convert <code>IResourceDelta</code>s into <code>IJavaElementDelta</code>s.
         */
-       public final DeltaProcessor deltaProcessor = new DeltaProcessor(this);
+//     public final DeltaProcessor deltaProcessor = new DeltaProcessor(this);
        /**
         * Used to update the JavaModel for <code>IJavaElementDelta</code>s.
         */
@@ -540,6 +572,43 @@ public class JavaModelManager implements ISaveParticipant {
                        this.project = project;
                }
        }
+       public static class PerWorkingCopyInfo implements IProblemRequestor {
+               int useCount = 0;
+               IProblemRequestor problemRequestor;
+               ICompilationUnit workingCopy;
+               public PerWorkingCopyInfo(ICompilationUnit workingCopy, IProblemRequestor problemRequestor) {
+                       this.workingCopy = workingCopy;
+                       this.problemRequestor = problemRequestor;
+               }
+               public void acceptProblem(IProblem problem) {
+                       if (this.problemRequestor == null) return;
+                       this.problemRequestor.acceptProblem(problem);
+               }
+               public void beginReporting() {
+                       if (this.problemRequestor == null) return;
+                       this.problemRequestor.beginReporting();
+               }
+               public void endReporting() {
+                       if (this.problemRequestor == null) return;
+                       this.problemRequestor.endReporting();
+               }
+               public ICompilationUnit getWorkingCopy() {
+                       return this.workingCopy;
+               }
+               public boolean isActive() {
+                       return this.problemRequestor != null && this.problemRequestor.isActive();
+               }
+               public String toString() {
+                       StringBuffer buffer = new StringBuffer();
+                       buffer.append("Info for "); //$NON-NLS-1$
+                       buffer.append(((JavaElement)workingCopy).toStringWithAncestors());
+                       buffer.append("\nUse count = "); //$NON-NLS-1$
+                       buffer.append(this.useCount);
+                       buffer.append("\nProblem requestor:\n  "); //$NON-NLS-1$
+                       buffer.append(this.problemRequestor);
+                       return buffer.toString();
+               }
+       }
        public static boolean VERBOSE = true;
        public static boolean CP_RESOLVE_VERBOSE = false;
        public static boolean ZIP_ACCESS_VERBOSE = false;
@@ -571,7 +640,7 @@ public class JavaModelManager implements ISaveParticipant {
                                        Variables.remove(varName);
                                }
                        }
-//             TODO khartlage temp-del
+//             TODO jsurfer temp-del
 //                     if (propertyName.startsWith(CP_CONTAINER_PREFERENCES_PREFIX)) {
 //                             recreatePersistedContainer(propertyName, (String)event.getNewValue(), false);
 //                     }
@@ -656,7 +725,8 @@ public class JavaModelManager implements ISaveParticipant {
         */
        public void configurePluginDebugOptions(){
                if(JavaCore.getPlugin().isDebugging()){
-//             TODO khartlage temp-del
+//             TODO jsurfer temp-del
+                       
                        String option = Platform.getDebugOption(BUILDER_DEBUG);
 //                     if(option != null) JavaBuilder.DEBUG = option.equalsIgnoreCase("true") ; //$NON-NLS-1$
 //                     
@@ -690,15 +760,60 @@ public class JavaModelManager implements ISaveParticipant {
 //                     option = Platform.getDebugOption(SELECTION_DEBUG);
 //                     if(option != null) SelectionEngine.DEBUG = option.equalsIgnoreCase("true") ; //$NON-NLS-1$
 
-                       option = Platform.getDebugOption(SHARED_WC_DEBUG);
-                       if(option != null) CompilationUnit.SHARED_WC_VERBOSE = option.equalsIgnoreCase("true") ; //$NON-NLS-1$
-
                        option = Platform.getDebugOption(ZIP_ACCESS_DEBUG);
                        if(option != null) JavaModelManager.ZIP_ACCESS_VERBOSE = option.equalsIgnoreCase("true") ; //$NON-NLS-1$
                }
        }
        
 
+       /*
+        * Discards the per working copy info for the given working copy (making it a compilation unit)
+        * if its use count was 1. Otherwise, just decrement the use count.
+        * If the working copy is primary, computes the delta between its state and the original compilation unit
+        * and register it.
+        * Close the working copy, its buffer and remove it from the shared working copy table.
+        * Ignore if no per-working copy info existed.
+        * NOTE: it must be synchronized as it may interact with the element info cache (if useCount is decremented to 0), see bug 50667.
+        * Returns the new use count (or -1 if it didn't exist).
+        */
+       public synchronized int discardPerWorkingCopyInfo(CompilationUnit workingCopy) throws JavaModelException {
+               synchronized(perWorkingCopyInfos) {
+                       WorkingCopyOwner owner = workingCopy.owner;
+                       Map workingCopyToInfos = (Map)this.perWorkingCopyInfos.get(owner);
+                       if (workingCopyToInfos == null) return -1;
+                       
+                       PerWorkingCopyInfo info = (PerWorkingCopyInfo)workingCopyToInfos.get(workingCopy);
+                       if (info == null) return -1;
+                       
+                       if (--info.useCount == 0) {
+                               // create the delta builder (this remembers the current content of the working copy)
+                               JavaElementDeltaBuilder deltaBuilder = null;
+                               if (workingCopy.isPrimary()) {
+                                       deltaBuilder = new JavaElementDeltaBuilder(workingCopy);
+                               }
+
+                               // remove per working copy info
+                               workingCopyToInfos.remove(workingCopy);
+                               if (workingCopyToInfos.isEmpty()) {
+                                       this.perWorkingCopyInfos.remove(owner);
+                               }
+
+                               // remove infos + close buffer (since no longer working copy)
+                               removeInfoAndChildren(workingCopy);
+                               workingCopy.closeBuffer();
+
+                               // compute the delta if needed and register it if there are changes
+                               if (deltaBuilder != null) {
+                                       deltaBuilder.buildDeltas();
+                                       if ((deltaBuilder.delta != null) && (deltaBuilder.delta.getAffectedChildren().length > 0)) {
+                                               getDeltaProcessor().registerJavaModelDelta(deltaBuilder.delta);
+                                       }
+                               }
+                               
+                       }
+                       return info.useCount;
+               }
+       }
        
        /**
         * @see ISaveParticipant
@@ -868,7 +983,9 @@ public class JavaModelManager implements ISaveParticipant {
        }
        
 
-       
+       public DeltaProcessor getDeltaProcessor() {
+               return this.deltaState.getDeltaProcessor();
+       }
        /** 
         * Returns the set of elements which are out of synch with their buffers.
         */
@@ -1006,7 +1123,30 @@ public class JavaModelManager implements ISaveParticipant {
                }
                return info;
        }
+       /*
+        * Returns the per-working copy info for the given working copy at the given path.
+        * If it doesn't exist and if create, add a new per-working copy info with the given problem requestor.
+        * If recordUsage, increment the per-working copy info's use count.
+        * Returns null if it doesn't exist and not create.
+        */
+       public PerWorkingCopyInfo getPerWorkingCopyInfo(CompilationUnit workingCopy,boolean create, boolean recordUsage, IProblemRequestor problemRequestor) {
+               synchronized(perWorkingCopyInfos) { // use the perWorkingCopyInfo collection as its own lock
+                       WorkingCopyOwner owner = workingCopy.owner;
+                       Map workingCopyToInfos = (Map)this.perWorkingCopyInfos.get(owner);
+                       if (workingCopyToInfos == null && create) {
+                               workingCopyToInfos = new HashMap();
+                               this.perWorkingCopyInfos.put(owner, workingCopyToInfos);
+                       }
 
+                       PerWorkingCopyInfo info = workingCopyToInfos == null ? null : (PerWorkingCopyInfo) workingCopyToInfos.get(workingCopy);
+                       if (info == null && create) {
+                               info= new PerWorkingCopyInfo(workingCopy, problemRequestor);
+                               workingCopyToInfos.put(workingCopy, info);
+                       }
+                       if (info != null && recordUsage) info.useCount++;
+                       return info;
+               }
+       }       
        /**
         * Returns the name of the variables for which an CP variable initializer is registered through an extension point
         */
@@ -1066,7 +1206,18 @@ public class JavaModelManager implements ISaveParticipant {
                IPath workingLocation= project.getPluginWorkingLocation(descr);
                return workingLocation.append("state.dat").toFile(); //$NON-NLS-1$
        }
-
+       /*
+        * Returns the temporary cache for newly opened elements for the current thread.
+        * Creates it if not already created.
+        */
+       public HashMap getTemporaryCache() {
+               HashMap result = (HashMap)this.temporaryCache.get();
+               if (result == null) {
+                       result = new HashMap();
+                       this.temporaryCache.set(result);
+               }
+               return result;
+       }
        /**
         * Returns the open ZipFile at the given location. If the ZipFile
         * does not yet exist, it is created, opened, and added to the cache
@@ -1126,7 +1277,12 @@ public class JavaModelManager implements ISaveParticipant {
                        }
                }
        }
-
+       /*
+        * Returns whether there is a temporary cache for the current thread.
+        */
+       public boolean hasTemporaryCache() {
+               return this.temporaryCache.get() != null;
+       }
 //     public void loadVariablesAndContainers() throws CoreException {
 //
 //             // backward compatibility, consider persistent property 
@@ -1286,7 +1442,35 @@ public class JavaModelManager implements ISaveParticipant {
        protected void putInfo(IJavaElement element, Object info) {
                this.cache.putInfo(element, info);
        }
-
+       /*
+        * Puts the infos in the given map (keys are IJavaElements and values are JavaElementInfos)
+        * in the Java model cache in an atomic way.
+        * First checks that the info for the opened element (or one of its ancestors) has not been 
+        * added to the cache. If it is the case, another thread has opened the element (or one of
+        * its ancestors). So returns without updating the cache.
+        */
+       protected synchronized void putInfos(IJavaElement openedElement, Map newElements) {
+               // remove children
+               Object existingInfo = this.cache.peekAtInfo(openedElement);
+               if (openedElement instanceof IParent && existingInfo instanceof JavaElementInfo) {
+                       IJavaElement[] children = ((JavaElementInfo)existingInfo).getChildren();
+                       for (int i = 0, size = children.length; i < size; ++i) {
+                               JavaElement child = (JavaElement) children[i];
+                               try {
+                                       child.close();
+                               } catch (JavaModelException e) {
+                                       // ignore
+                               }
+                       }
+               }
+       
+               Iterator iterator = newElements.keySet().iterator();
+               while (iterator.hasNext()) {
+                       IJavaElement element = (IJavaElement)iterator.next();
+                       Object info = newElements.get(element);
+                       this.cache.putInfo(element, info);
+               }
+       }
        /**
         * Reads the build state for the relevant project.
         */
@@ -1412,10 +1596,44 @@ public class JavaModelManager implements ISaveParticipant {
                }
        }
        
-       protected void removeInfo(IJavaElement element) {
-               this.cache.removeInfo(element);
-       }
-
+//     PROTECTED VOID REMOVEINFO(IJAVAELEMENT ELEMENT) {
+//             THIS.CACHE.REMOVEINFO(ELEMENT);
+//     }
+       /*
+        * Removes all cached info for the given element (including all children)
+        * from the cache.
+        * Returns the info for the given element, or null if it was closed.
+        */
+       public synchronized Object removeInfoAndChildren(JavaElement element) throws JavaModelException {
+               Object info = this.cache.peekAtInfo(element);
+               if (info != null) {
+                       boolean wasVerbose = false;
+                       try {
+                               if (VERBOSE) {
+                                       System.out.println("CLOSING Element ("+ Thread.currentThread()+"): " + element.toStringWithAncestors());  //$NON-NLS-1$//$NON-NLS-2$
+                                       wasVerbose = true;
+                                       VERBOSE = false;
+                               }
+                               element.closing(info);
+                               if (element instanceof IParent && info instanceof JavaElementInfo) {
+                                       IJavaElement[] children = ((JavaElementInfo)info).getChildren();
+                                       for (int i = 0, size = children.length; i < size; ++i) {
+                                               JavaElement child = (JavaElement) children[i];
+                                               child.close();
+                                       }
+                               }
+                               this.cache.removeInfo(element);
+                               if (wasVerbose) {
+                                       System.out.println("-> Package cache size = " + this.cache.pkgSize()); //$NON-NLS-1$
+                                       System.out.println("-> Openable cache filling ratio = " + NumberFormat.getInstance().format(this.cache.openableFillingRatio()) + "%"); //$NON-NLS-1$//$NON-NLS-2$
+                               }
+                       } finally {
+                               JavaModelManager.VERBOSE = wasVerbose;
+                       }
+                       return info;
+               }
+               return null;
+       }       
        public void removePerProjectInfo(JavaProject javaProject) {
                synchronized(perProjectInfo) { // use the perProjectInfo collection as its own lock
                        IProject project = javaProject.getProject();
@@ -1425,7 +1643,12 @@ public class JavaModelManager implements ISaveParticipant {
                        }
                }
        }
-
+       /*
+        * Resets the temporary cache for newly created elements to null.
+        */
+       public void resetTemporaryCache() {
+               this.temporaryCache.set(null);
+       }
        /**
         * @see ISaveParticipant
         */
@@ -1668,4 +1891,30 @@ public class JavaModelManager implements ISaveParticipant {
                preferences.setValue(variableKey, variableString);
                JavaCore.getPlugin().savePluginPreferences();
        }
+       /*
+        * Returns all the working copies which have the given owner.
+        * Adds the working copies of the primary owner if specified.
+        * Returns null if it has none.
+        */
+       public ICompilationUnit[] getWorkingCopies(WorkingCopyOwner owner, boolean addPrimary) {
+               synchronized(perWorkingCopyInfos) {
+                       ICompilationUnit[] primaryWCs = addPrimary && owner != DefaultWorkingCopyOwner.PRIMARY 
+                               ? getWorkingCopies(DefaultWorkingCopyOwner.PRIMARY, false) 
+                               : null;
+                       Map workingCopyToInfos = (Map)perWorkingCopyInfos.get(owner);
+                       if (workingCopyToInfos == null) return primaryWCs;
+                       int primaryLength = primaryWCs == null ? 0 : primaryWCs.length;
+                       int size = workingCopyToInfos.size(); // note size is > 0 otherwise pathToPerWorkingCopyInfos would be null
+                       ICompilationUnit[] result = new ICompilationUnit[primaryLength + size];
+                       if (primaryWCs != null) {
+                               System.arraycopy(primaryWCs, 0, result, 0, primaryLength);
+                       }
+                       Iterator iterator = workingCopyToInfos.values().iterator();
+                       int index = primaryLength;
+                       while(iterator.hasNext()) {
+                               result[index++] = ((JavaModelManager.PerWorkingCopyInfo)iterator.next()).getWorkingCopy();
+                       }
+                       return result;
+               }               
+       }
 }