1 /*******************************************************************************
2 * Copyright (c) 2000, 2003 IBM Corporation and others.
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the Common Public License v1.0
5 * which accompanies this distribution, and is available at
6 * http://www.eclipse.org/legal/cpl-v10.html
9 * IBM Corporation - initial API and implementation
10 *******************************************************************************/
11 package net.sourceforge.phpdt.internal.core;
13 import java.text.NumberFormat;
14 import java.util.Enumeration;
15 import java.util.HashMap;
16 import java.util.Iterator;
19 import net.sourceforge.phpdt.core.BufferChangedEvent;
20 import net.sourceforge.phpdt.core.IBuffer;
21 import net.sourceforge.phpdt.core.IBufferChangedListener;
22 import net.sourceforge.phpdt.core.IBufferFactory;
23 import net.sourceforge.phpdt.core.ICodeAssist;
24 import net.sourceforge.phpdt.core.IJavaElement;
25 import net.sourceforge.phpdt.core.IJavaModelStatusConstants;
26 import net.sourceforge.phpdt.core.IOpenable;
27 import net.sourceforge.phpdt.core.IPackageFragmentRoot;
28 import net.sourceforge.phpdt.core.IParent;
29 import net.sourceforge.phpdt.core.JavaModelException;
31 import org.eclipse.core.resources.IContainer;
32 import org.eclipse.core.resources.IResource;
33 import org.eclipse.core.resources.IWorkspace;
34 import org.eclipse.core.resources.ResourcesPlugin;
35 import org.eclipse.core.runtime.IProgressMonitor;
38 * Abstract class for implementations of java elements which are IOpenable.
43 public abstract class Openable extends JavaElement implements IOpenable, IBufferChangedListener {
45 protected Openable(JavaElement parent, String name) {
49 * The buffer associated with this element has changed. Registers
50 * this element as being out of synch with its buffer's contents.
51 * If the buffer has been closed, this element is set as NOT out of
52 * synch with the contents.
54 * @see IBufferChangedListener
56 public void bufferChanged(BufferChangedEvent event) {
57 if (event.getBuffer().isClosed()) {
58 JavaModelManager.getJavaModelManager().getElementsOutOfSynchWithBuffers().remove(this);
59 getBufferManager().removeBuffer(event.getBuffer());
61 JavaModelManager.getJavaModelManager().getElementsOutOfSynchWithBuffers().put(this, this);
66 * Builds this element's structure and properties in the given
67 * info object, based on this element's current contents (reuse buffer
68 * contents if this element has an open buffer, or resource contents
69 * if this element does not have an open buffer). Children
70 * are placed in the given newElements table (note, this element
71 * has already been placed in the newElements table). Returns true
72 * if successful, or false if an error is encountered while determining
73 * the structure of this element.
75 protected abstract boolean buildStructure(OpenableElementInfo info, IProgressMonitor pm, Map newElements, IResource underlyingResource) throws JavaModelException;
78 // * Updates the info objects for this element and all of its children by
79 // * removing the current infos, generating new infos, and then placing
80 // * the new infos into the Java Model cache tables.
82 //protected void buildStructure(OpenableElementInfo info, IProgressMonitor monitor) throws JavaModelException {
84 // if (monitor != null && monitor.isCanceled()) return;
86 // // remove existing (old) infos
88 // HashMap newElements = new HashMap(11);
89 // info.setIsStructureKnown(generateInfos(info, monitor, newElements, getResource()));
90 // JavaModelManager.getJavaModelManager().getElementsOutOfSynchWithBuffers().remove(this);
91 // for (Iterator iter = newElements.keySet().iterator(); iter.hasNext();) {
92 // IJavaElement key = (IJavaElement) iter.next();
93 // Object value = newElements.get(key);
94 // JavaModelManager.getJavaModelManager().putInfo(key, value);
97 // // add the info for this at the end, to ensure that a getInfo cannot reply null in case the LRU cache needs
98 // // to be flushed. Might lead to performance issues.
99 // // see PR 1G2K5S7: ITPJCORE:ALL - NPE when accessing source for a binary type
100 // JavaModelManager.getJavaModelManager().putInfo(this, info);
103 * Returns whether this element can be removed from the Java model cache to make space.
105 public boolean canBeRemovedFromCache() {
107 return !hasUnsavedChanges();
108 } catch (JavaModelException e) {
113 * Returns whether the buffer of this element can be removed from the Java model cache to make space.
115 public boolean canBufferBeRemovedFromCache(IBuffer buffer) {
116 return !buffer.hasUnsavedChanges();
119 * Close the buffer associated with this element, if any.
121 protected void closeBuffer() {
122 if (!hasBuffer()) return; // nothing to do
123 IBuffer buffer = getBufferManager().getBuffer(this);
124 if (buffer != null) {
126 buffer.removeBufferChangedListener(this);
130 * Close the buffer associated with this element, if any.
132 protected void closeBuffer(OpenableElementInfo info) {
133 if (!hasBuffer()) return; // nothing to do
134 IBuffer buffer = null;
135 buffer = getBufferManager().getBuffer(this);
136 if (buffer != null) {
138 buffer.removeBufferChangedListener(this);
142 * This element is being closed. Do any necessary cleanup.
144 protected void closing(Object info) {
149 // * @see ICodeAssist
151 //protected void codeComplete(net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit cu, net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit unitToSkip, int position, ICompletionRequestor requestor) throws JavaModelException {
152 // if (requestor == null) {
153 // throw new IllegalArgumentException(ProjectPrefUtil.bind("codeAssist.nullRequestor")); //$NON-NLS-1$
155 // IBuffer buffer = getBuffer();
156 // if (buffer == null) {
159 // if (position < -1 || position > buffer.getLength()) {
160 // throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INDEX_OUT_OF_BOUNDS));
162 // JavaProject project = (JavaProject) getJavaProject();
163 // SearchableEnvironment environment = (SearchableEnvironment) project.getSearchableNameEnvironment();
164 // NameLookup nameLookup = project.getNameLookup();
165 // environment.unitToSkip = unitToSkip;
167 // CompletionEngine engine = new CompletionEngine(environment, new CompletionRequestorWrapper(requestor,nameLookup), project.getOptions(true), project);
168 // engine.complete(cu, position, 0);
169 // environment.unitToSkip = null;
174 //protected IJavaElement[] codeSelect(net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit cu, int offset, int length) throws JavaModelException {
175 // SelectionRequestor requestor= new SelectionRequestor(((JavaProject)getJavaProject()).getNameLookup(), this);
176 // this.codeSelect(cu, offset, length, requestor);
177 // return requestor.getElements();
182 //protected void codeSelect(net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit cu, int offset, int length, ISelectionRequestor requestor) throws JavaModelException {
183 // IBuffer buffer = getBuffer();
184 // if (buffer == null) {
187 // int end= buffer.getLength();
188 // if (offset < 0 || length < 0 || offset + length > end ) {
189 // throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INDEX_OUT_OF_BOUNDS));
192 // // fix for 1FVGGKF
193 // JavaProject project = (JavaProject)getJavaProject();
194 // ISearchableNameEnvironment environment = project.getSearchableNameEnvironment();
196 // // fix for 1FVXGDK
197 // SelectionEngine engine = new SelectionEngine(environment, requestor, project.getOptions(true));
198 // engine.select(cu, offset, offset + length - 1);
201 * Returns a new element info for this element.
203 protected Object createElementInfo() {
204 return new OpenableElementInfo();
207 // * Builds this element's structure and properties in the given
208 // * info object, based on this element's current contents (reuse buffer
209 // * contents if this element has an open buffer, or resource contents
210 // * if this element does not have an open buffer). Children
211 // * are placed in the given newElements table (note, this element
212 // * has already been placed in the newElements table). Returns true
213 // * if successful, or false if an error is encountered while determining
214 // * the structure of this element.
216 //protected abstract boolean generateInfos(OpenableElementInfo info, IProgressMonitor pm, Map newElements, IResource underlyingResource) throws JavaModelException;
218 protected void generateInfos(Object info, HashMap newElements, IProgressMonitor monitor) throws JavaModelException {
220 if (JavaModelManager.VERBOSE){
221 System.out.println("OPENING Element ("+ Thread.currentThread()+"): " + this.toStringWithAncestors()); //$NON-NLS-1$//$NON-NLS-2$
224 // open the parent if necessary
225 openParent(info, newElements, monitor);
226 if (monitor != null && monitor.isCanceled()) return;
228 // puts the info before building the structure so that questions to the handle behave as if the element existed
229 // (case of compilation units becoming working copies)
230 newElements.put(this, info);
232 // build the structure of the openable (this will open the buffer if needed)
234 OpenableElementInfo openableElementInfo = (OpenableElementInfo)info;
235 boolean isStructureKnown = buildStructure(openableElementInfo, monitor, newElements, getResource());
236 openableElementInfo.setIsStructureKnown(isStructureKnown);
237 } catch (JavaModelException e) {
238 newElements.remove(this);
242 // remove out of sync buffer for this element
243 JavaModelManager.getJavaModelManager().getElementsOutOfSynchWithBuffers().remove(this);
245 if (JavaModelManager.VERBOSE) {
246 System.out.println("-> Package cache size = " + JavaModelManager.getJavaModelManager().cache.pkgSize()); //$NON-NLS-1$
247 System.out.println("-> Openable cache filling ratio = " + NumberFormat.getInstance().format(JavaModelManager.getJavaModelManager().cache.openableFillingRatio()) + "%"); //$NON-NLS-1$//$NON-NLS-2$
251 * Note: a buffer with no unsaved changes can be closed by the Java Model
252 * since it has a finite number of buffers allowed open at one time. If this
253 * is the first time a request is being made for the buffer, an attempt is
254 * made to create and fill this element's buffer. If the buffer has been
255 * closed since it was first opened, the buffer is re-created.
259 public IBuffer getBuffer() throws JavaModelException {
261 // ensure element is open
265 IBuffer buffer = getBufferManager().getBuffer(this);
266 if (buffer == null) {
267 // try to (re)open a buffer
268 buffer = openBuffer(null);
277 * Answers the buffer factory to use for creating new buffers
279 public IBufferFactory getBufferFactory(){
280 return getBufferManager().getDefaultBufferFactory();
284 * Returns the buffer manager for this element.
286 protected BufferManager getBufferManager() {
287 return BufferManager.getDefaultBufferManager();
290 * Return my underlying resource. Elements that may not have a
291 * corresponding resource must override this method.
295 public IResource getCorrespondingResource() throws JavaModelException {
296 return getUnderlyingResource();
301 public IOpenable getOpenable() {
310 public IResource getUnderlyingResource() throws JavaModelException {
311 IResource parentResource = parent.getUnderlyingResource();
312 if (parentResource == null) {
315 int type = parentResource.getType();
316 if (type == IResource.FOLDER || type == IResource.PROJECT) {
317 IContainer folder = (IContainer) parentResource;
318 IResource resource = folder.findMember(name);
319 if (resource == null) {
320 throw newNotPresentException();
325 return parentResource;
329 public boolean exists() {
331 IPackageFragmentRoot root = this.getPackageFragmentRoot();
332 if (root == null || root == this || !root.isArchive()) {
333 return parentExists() && resourceExists();
335 return super.exists();
340 * Returns true if this element may have an associated source buffer,
341 * otherwise false. Subclasses must override as required.
343 protected boolean hasBuffer() {
349 public boolean hasChildren() throws JavaModelException {
350 return getChildren().length > 0;
355 public boolean hasUnsavedChanges() throws JavaModelException{
357 if (isReadOnly() || !isOpen()) {
360 IBuffer buf = this.getBuffer();
361 if (buf != null && buf.hasUnsavedChanges()) {
364 // for package fragments, package fragment roots, and projects must check open buffers
365 // to see if they have an child with unsaved changes
366 int elementType = getElementType();
367 if (elementType == PACKAGE_FRAGMENT ||
368 elementType == PACKAGE_FRAGMENT_ROOT ||
369 elementType == JAVA_PROJECT ||
370 elementType == JAVA_MODEL) { // fix for 1FWNMHH
371 Enumeration openBuffers= getBufferManager().getOpenBuffers();
372 while (openBuffers.hasMoreElements()) {
373 IBuffer buffer= (IBuffer)openBuffers.nextElement();
374 if (buffer.hasUnsavedChanges()) {
375 IJavaElement owner= (IJavaElement)buffer.getOwner();
376 if (isAncestorOf(owner)) {
386 * Subclasses must override as required.
390 public boolean isConsistent() throws JavaModelException {
397 public boolean isOpen() {
398 synchronized(JavaModelManager.getJavaModelManager()){
399 return JavaModelManager.getJavaModelManager().getInfo(this) != null;
403 * Returns true if this represents a source element.
404 * Openable source elements have an associated buffer created
405 * when they are opened.
407 protected boolean isSourceElement() {
413 //public void makeConsistent(IProgressMonitor pm) throws JavaModelException {
414 // if (!isConsistent()) {
415 // buildStructure((OpenableElementInfo)getElementInfo(), pm);
421 public void makeConsistent(IProgressMonitor monitor) throws JavaModelException {
422 if (isConsistent()) return;
424 // create a new info and make it the current info
425 // (this will remove the info and its children just before storing the new infos)
426 JavaModelManager manager = JavaModelManager.getJavaModelManager();
427 boolean hadTemporaryCache = manager.hasTemporaryCache();
429 HashMap newElements = manager.getTemporaryCache();
430 openWhenClosed(newElements, monitor);
431 if (newElements.get(this) == null) {
432 // close any buffer that was opened for the new elements
433 Iterator iterator = newElements.keySet().iterator();
434 while (iterator.hasNext()) {
435 IJavaElement element = (IJavaElement)iterator.next();
436 if (element instanceof Openable) {
437 ((Openable)element).closeBuffer();
440 throw newNotPresentException();
442 if (!hadTemporaryCache) {
443 manager.putInfos(this, newElements);
446 if (!hadTemporaryCache) {
447 manager.resetTemporaryCache();
455 public void open(IProgressMonitor pm) throws JavaModelException {
459 * Opens a buffer on the contents of this element, and returns
460 * the buffer, or returns <code>null</code> if opening fails.
461 * By default, do nothing - subclasses that have buffers
462 * must override as required.
464 protected IBuffer openBuffer(IProgressMonitor pm) throws JavaModelException {
469 * Open the parent element if necessary.
471 protected void openParent(Object childInfo, HashMap newElements, IProgressMonitor pm) throws JavaModelException {
473 Openable openableParent = (Openable)getOpenableParent();
474 if (openableParent != null && !openableParent.isOpen()){
475 openableParent.generateInfos(openableParent.createElementInfo(), newElements, pm);
480 // * Open an <code>Openable</code> that is known to be closed (no check for <code>isOpen()</code>).
482 //protected void openWhenClosed(IProgressMonitor pm) throws JavaModelException {
485 // if (JavaModelManager.VERBOSE){
486 // System.out.println("OPENING Element ("+ Thread.currentThread()+"): " + this.toStringWithAncestors()); //$NON-NLS-1$//$NON-NLS-2$
489 // // 1) Parent must be open - open the parent if necessary
492 // // 2) create the new element info and open a buffer if needed
493 // OpenableElementInfo info = createElementInfo();
494 // if (isSourceElement()) {
495 // this.openBuffer(pm);
498 // // 3) build the structure of the openable
499 // buildStructure(info, pm);
501 // // 4) anything special
504 //// if (JavaModelManager.VERBOSE) {
505 //// System.out.println("-> Package cache size = " + JavaModelManager.getJavaModelManager().cache.pkgSize()); //$NON-NLS-1$
506 //// System.out.println("-> Openable cache filling ratio = " + JavaModelManager.getJavaModelManager().cache.openableFillingRatio() + "%"); //$NON-NLS-1$//$NON-NLS-2$
509 // // if any problems occuring openning the element, ensure that it's info
510 // // does not remain in the cache (some elements, pre-cache their info
511 // // as they are being opened).
512 // } catch (JavaModelException e) {
513 // JavaModelManager.getJavaModelManager().removeInfo(this);
519 * Answers true if the parent exists (null parent is answering true)
522 protected boolean parentExists(){
524 IJavaElement parent = this.getParent();
525 if (parent == null) return true;
526 return parent.exists();
530 * Returns whether the corresponding resource or associated file exists
532 protected boolean resourceExists() {
533 IWorkspace workspace = ResourcesPlugin.getWorkspace();
534 if (workspace == null) return false; // workaround for http://bugs.eclipse.org/bugs/show_bug.cgi?id=34069
538 this.getPath().makeRelative(), // ensure path is relative (see http://dev.eclipse.org/bugs/show_bug.cgi?id=22517)
545 public void save(IProgressMonitor pm, boolean force) throws JavaModelException {
546 if (isReadOnly() || this.getResource().isReadOnly()) {
547 throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.READ_ONLY, this));
549 IBuffer buf = getBuffer();
550 if (buf != null) { // some Openables (like a JavaProject) don't have a buffer
552 this.makeConsistent(pm); // update the element info of this element
557 * Find enclosing package fragment root if any
559 public PackageFragmentRoot getPackageFragmentRoot() {
560 IJavaElement current = this;
562 if (current instanceof PackageFragmentRoot) return (PackageFragmentRoot)current;
563 current = current.getParent();
564 } while(current != null);
568 // * @see ICodeAssist
569 // * @deprecated - use codeComplete(ICompilationUnit, ICompilationUnit, int, ICompletionRequestor) instead
571 //protected void codeComplete(net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit cu, net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit unitToSkip, int position, final ICodeCompletionRequestor requestor) throws JavaModelException {
573 // if (requestor == null){
574 // codeComplete(cu, unitToSkip, position, (ICompletionRequestor)null);
581 // new ICompletionRequestor(){
582 // public void acceptAnonymousType(char[] superTypePackageName,char[] superTypeName,char[][] parameterPackageNames,char[][] parameterTypeNames,char[][] parameterNames,char[] completionName,int modifiers,int completionStart,int completionEnd, int relevance) {
584 // public void acceptClass(char[] packageName, char[] className, char[] completionName, int modifiers, int completionStart, int completionEnd, int relevance) {
585 // requestor.acceptClass(packageName, className, completionName, modifiers, completionStart, completionEnd);
587 // public void acceptError(IProblem error) {
588 // if (true) return; // was disabled in 1.0
591 // IMarker marker = ResourcesPlugin.getWorkspace().getRoot().createMarker(IJavaModelMarker.TRANSIENT_PROBLEM);
592 // marker.setAttribute(IJavaModelMarker.ID, error.getID());
593 // marker.setAttribute(IMarker.CHAR_START, error.getSourceStart());
594 // marker.setAttribute(IMarker.CHAR_END, error.getSourceEnd() + 1);
595 // marker.setAttribute(IMarker.LINE_NUMBER, error.getSourceLineNumber());
596 // marker.setAttribute(IMarker.MESSAGE, error.getMessage());
597 // marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR);
598 // requestor.acceptError(marker);
599 // } catch(CoreException e){
602 // public void acceptField(char[] declaringTypePackageName, char[] declaringTypeName, char[] name, char[] typePackageName, char[] typeName, char[] completionName, int modifiers, int completionStart, int completionEnd, int relevance) {
603 // requestor.acceptField(declaringTypePackageName, declaringTypeName, name, typePackageName, typeName, completionName, modifiers, completionStart, completionEnd);
605 // public void acceptInterface(char[] packageName,char[] interfaceName,char[] completionName,int modifiers,int completionStart,int completionEnd, int relevance) {
606 // requestor.acceptInterface(packageName, interfaceName, completionName, modifiers, completionStart, completionEnd);
608 // public void acceptKeyword(char[] keywordName,int completionStart,int completionEnd, int relevance){
609 // requestor.acceptKeyword(keywordName, completionStart, completionEnd);
611 // public void acceptLabel(char[] labelName,int completionStart,int completionEnd, int relevance){
612 // requestor.acceptLabel(labelName, completionStart, completionEnd);
614 // public void acceptLocalVariable(char[] name,char[] typePackageName,char[] typeName,int modifiers,int completionStart,int completionEnd, int relevance){
617 // public void acceptMethod(char[] declaringTypePackageName,char[] declaringTypeName,char[] selector,char[][] parameterPackageNames,char[][] parameterTypeNames,char[][] parameterNames,char[] returnTypePackageName,char[] returnTypeName,char[] completionName,int modifiers,int completionStart,int completionEnd, int relevance){
618 // // skip parameter names
619 // requestor.acceptMethod(declaringTypePackageName, declaringTypeName, selector, parameterPackageNames, parameterTypeNames, returnTypePackageName, returnTypeName, completionName, modifiers, completionStart, completionEnd);
621 // public void acceptMethodDeclaration(char[] declaringTypePackageName,char[] declaringTypeName,char[] selector,char[][] parameterPackageNames,char[][] parameterTypeNames,char[][] parameterNames,char[] returnTypePackageName,char[] returnTypeName,char[] completionName,int modifiers,int completionStart,int completionEnd, int relevance){
624 // public void acceptModifier(char[] modifierName,int completionStart,int completionEnd, int relevance){
625 // requestor.acceptModifier(modifierName, completionStart, completionEnd);
627 // public void acceptPackage(char[] packageName,char[] completionName,int completionStart,int completionEnd, int relevance){
628 // requestor.acceptPackage(packageName, completionName, completionStart, completionEnd);
630 // public void acceptType(char[] packageName,char[] typeName,char[] completionName,int completionStart,int completionEnd, int relevance){
631 // requestor.acceptType(packageName, typeName, completionName, completionStart, completionEnd);
633 // public void acceptVariableName(char[] typePackageName,char[] typeName,char[] name,char[] completionName,int completionStart,int completionEnd, int relevance){