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.IJavaElement;
24 import net.sourceforge.phpdt.core.IJavaModelStatusConstants;
25 import net.sourceforge.phpdt.core.IOpenable;
26 import net.sourceforge.phpdt.core.IPackageFragmentRoot;
27 import net.sourceforge.phpdt.core.IParent;
28 import net.sourceforge.phpdt.core.JavaModelException;
30 import org.eclipse.core.resources.IContainer;
31 import org.eclipse.core.resources.IResource;
32 import org.eclipse.core.resources.IWorkspace;
33 import org.eclipse.core.resources.ResourcesPlugin;
34 import org.eclipse.core.runtime.IProgressMonitor;
37 * Abstract class for implementations of java elements which are IOpenable.
42 public abstract class Openable extends JavaElement implements IOpenable, IBufferChangedListener {
44 protected Openable(JavaElement parent, String name) {
48 * The buffer associated with this element has changed. Registers
49 * this element as being out of synch with its buffer's contents.
50 * If the buffer has been closed, this element is set as NOT out of
51 * synch with the contents.
53 * @see IBufferChangedListener
55 public void bufferChanged(BufferChangedEvent event) {
56 if (event.getBuffer().isClosed()) {
57 JavaModelManager.getJavaModelManager().getElementsOutOfSynchWithBuffers().remove(this);
58 getBufferManager().removeBuffer(event.getBuffer());
60 JavaModelManager.getJavaModelManager().getElementsOutOfSynchWithBuffers().put(this, this);
65 * Builds this element's structure and properties in the given
66 * info object, based on this element's current contents (reuse buffer
67 * contents if this element has an open buffer, or resource contents
68 * if this element does not have an open buffer). Children
69 * are placed in the given newElements table (note, this element
70 * has already been placed in the newElements table). Returns true
71 * if successful, or false if an error is encountered while determining
72 * the structure of this element.
74 protected abstract boolean buildStructure(OpenableElementInfo info, IProgressMonitor pm, Map newElements, IResource underlyingResource) throws JavaModelException;
77 // * Updates the info objects for this element and all of its children by
78 // * removing the current infos, generating new infos, and then placing
79 // * the new infos into the Java Model cache tables.
81 //protected void buildStructure(OpenableElementInfo info, IProgressMonitor monitor) throws JavaModelException {
83 // if (monitor != null && monitor.isCanceled()) return;
85 // // remove existing (old) infos
87 // HashMap newElements = new HashMap(11);
88 // info.setIsStructureKnown(generateInfos(info, monitor, newElements, getResource()));
89 // JavaModelManager.getJavaModelManager().getElementsOutOfSynchWithBuffers().remove(this);
90 // for (Iterator iter = newElements.keySet().iterator(); iter.hasNext();) {
91 // IJavaElement key = (IJavaElement) iter.next();
92 // Object value = newElements.get(key);
93 // JavaModelManager.getJavaModelManager().putInfo(key, value);
96 // // add the info for this at the end, to ensure that a getInfo cannot reply null in case the LRU cache needs
97 // // to be flushed. Might lead to performance issues.
98 // // see PR 1G2K5S7: ITPJCORE:ALL - NPE when accessing source for a binary type
99 // JavaModelManager.getJavaModelManager().putInfo(this, info);
102 * Returns whether this element can be removed from the Java model cache to make space.
104 public boolean canBeRemovedFromCache() {
106 return !hasUnsavedChanges();
107 } catch (JavaModelException e) {
112 * Returns whether the buffer of this element can be removed from the Java model cache to make space.
114 public boolean canBufferBeRemovedFromCache(IBuffer buffer) {
115 return !buffer.hasUnsavedChanges();
118 * Close the buffer associated with this element, if any.
120 protected void closeBuffer() {
121 if (!hasBuffer()) return; // nothing to do
122 IBuffer buffer = getBufferManager().getBuffer(this);
123 if (buffer != null) {
125 buffer.removeBufferChangedListener(this);
129 * Close the buffer associated with this element, if any.
131 protected void closeBuffer(OpenableElementInfo info) {
132 if (!hasBuffer()) return; // nothing to do
133 IBuffer buffer = null;
134 buffer = getBufferManager().getBuffer(this);
135 if (buffer != null) {
137 buffer.removeBufferChangedListener(this);
141 * This element is being closed. Do any necessary cleanup.
143 protected void closing(Object info) {
148 // * @see ICodeAssist
150 //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 {
151 // if (requestor == null) {
152 // throw new IllegalArgumentException(ProjectPrefUtil.bind("codeAssist.nullRequestor")); //$NON-NLS-1$
154 // IBuffer buffer = getBuffer();
155 // if (buffer == null) {
158 // if (position < -1 || position > buffer.getLength()) {
159 // throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INDEX_OUT_OF_BOUNDS));
161 // JavaProject project = (JavaProject) getJavaProject();
162 // SearchableEnvironment environment = (SearchableEnvironment) project.getSearchableNameEnvironment();
163 // NameLookup nameLookup = project.getNameLookup();
164 // environment.unitToSkip = unitToSkip;
166 // CompletionEngine engine = new CompletionEngine(environment, new CompletionRequestorWrapper(requestor,nameLookup), project.getOptions(true), project);
167 // engine.complete(cu, position, 0);
168 // environment.unitToSkip = null;
173 //protected IJavaElement[] codeSelect(net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit cu, int offset, int length) throws JavaModelException {
174 // SelectionRequestor requestor= new SelectionRequestor(((JavaProject)getJavaProject()).getNameLookup(), this);
175 // this.codeSelect(cu, offset, length, requestor);
176 // return requestor.getElements();
181 //protected void codeSelect(net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit cu, int offset, int length, ISelectionRequestor requestor) throws JavaModelException {
182 // IBuffer buffer = getBuffer();
183 // if (buffer == null) {
186 // int end= buffer.getLength();
187 // if (offset < 0 || length < 0 || offset + length > end ) {
188 // throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INDEX_OUT_OF_BOUNDS));
191 // // fix for 1FVGGKF
192 // JavaProject project = (JavaProject)getJavaProject();
193 // ISearchableNameEnvironment environment = project.getSearchableNameEnvironment();
195 // // fix for 1FVXGDK
196 // SelectionEngine engine = new SelectionEngine(environment, requestor, project.getOptions(true));
197 // engine.select(cu, offset, offset + length - 1);
200 * Returns a new element info for this element.
202 protected Object createElementInfo() {
203 return new OpenableElementInfo();
206 // * Builds this element's structure and properties in the given
207 // * info object, based on this element's current contents (reuse buffer
208 // * contents if this element has an open buffer, or resource contents
209 // * if this element does not have an open buffer). Children
210 // * are placed in the given newElements table (note, this element
211 // * has already been placed in the newElements table). Returns true
212 // * if successful, or false if an error is encountered while determining
213 // * the structure of this element.
215 //protected abstract boolean generateInfos(OpenableElementInfo info, IProgressMonitor pm, Map newElements, IResource underlyingResource) throws JavaModelException;
217 protected void generateInfos(Object info, HashMap newElements, IProgressMonitor monitor) throws JavaModelException {
219 if (JavaModelManager.VERBOSE){
220 System.out.println("OPENING Element ("+ Thread.currentThread()+"): " + this.toStringWithAncestors()); //$NON-NLS-1$//$NON-NLS-2$
223 // open the parent if necessary
224 openParent(info, newElements, monitor);
225 if (monitor != null && monitor.isCanceled()) return;
227 // puts the info before building the structure so that questions to the handle behave as if the element existed
228 // (case of compilation units becoming working copies)
229 newElements.put(this, info);
231 // build the structure of the openable (this will open the buffer if needed)
233 OpenableElementInfo openableElementInfo = (OpenableElementInfo)info;
234 boolean isStructureKnown = buildStructure(openableElementInfo, monitor, newElements, getResource());
235 openableElementInfo.setIsStructureKnown(isStructureKnown);
236 } catch (JavaModelException e) {
237 newElements.remove(this);
241 // remove out of sync buffer for this element
242 JavaModelManager.getJavaModelManager().getElementsOutOfSynchWithBuffers().remove(this);
244 if (JavaModelManager.VERBOSE) {
245 System.out.println("-> Package cache size = " + JavaModelManager.getJavaModelManager().cache.pkgSize()); //$NON-NLS-1$
246 System.out.println("-> Openable cache filling ratio = " + NumberFormat.getInstance().format(JavaModelManager.getJavaModelManager().cache.openableFillingRatio()) + "%"); //$NON-NLS-1$//$NON-NLS-2$
250 * Note: a buffer with no unsaved changes can be closed by the Java Model
251 * since it has a finite number of buffers allowed open at one time. If this
252 * is the first time a request is being made for the buffer, an attempt is
253 * made to create and fill this element's buffer. If the buffer has been
254 * closed since it was first opened, the buffer is re-created.
258 public IBuffer getBuffer() throws JavaModelException {
260 // ensure element is open
264 IBuffer buffer = getBufferManager().getBuffer(this);
265 if (buffer == null) {
266 // try to (re)open a buffer
267 buffer = openBuffer(null);
276 * Answers the buffer factory to use for creating new buffers
278 public IBufferFactory getBufferFactory(){
279 return getBufferManager().getDefaultBufferFactory();
283 * Returns the buffer manager for this element.
285 protected BufferManager getBufferManager() {
286 return BufferManager.getDefaultBufferManager();
289 * Return my underlying resource. Elements that may not have a
290 * corresponding resource must override this method.
294 public IResource getCorrespondingResource() throws JavaModelException {
295 return getUnderlyingResource();
300 public IOpenable getOpenable() {
309 public IResource getUnderlyingResource() throws JavaModelException {
310 IResource parentResource = parent.getUnderlyingResource();
311 if (parentResource == null) {
314 int type = parentResource.getType();
315 if (type == IResource.FOLDER || type == IResource.PROJECT) {
316 IContainer folder = (IContainer) parentResource;
317 IResource resource = folder.findMember(name);
318 if (resource == null) {
319 throw newNotPresentException();
324 return parentResource;
328 public boolean exists() {
330 IPackageFragmentRoot root = this.getPackageFragmentRoot();
331 if (root == null || root == this || !root.isArchive()) {
332 return parentExists() && resourceExists();
334 return super.exists();
339 * Returns true if this element may have an associated source buffer,
340 * otherwise false. Subclasses must override as required.
342 protected boolean hasBuffer() {
348 public boolean hasChildren() throws JavaModelException {
349 return getChildren().length > 0;
354 public boolean hasUnsavedChanges() throws JavaModelException{
356 if (isReadOnly() || !isOpen()) {
359 IBuffer buf = this.getBuffer();
360 if (buf != null && buf.hasUnsavedChanges()) {
363 // for package fragments, package fragment roots, and projects must check open buffers
364 // to see if they have an child with unsaved changes
365 int elementType = getElementType();
366 if (elementType == PACKAGE_FRAGMENT ||
367 elementType == PACKAGE_FRAGMENT_ROOT ||
368 elementType == JAVA_PROJECT ||
369 elementType == JAVA_MODEL) { // fix for 1FWNMHH
370 Enumeration openBuffers= getBufferManager().getOpenBuffers();
371 while (openBuffers.hasMoreElements()) {
372 IBuffer buffer= (IBuffer)openBuffers.nextElement();
373 if (buffer.hasUnsavedChanges()) {
374 IJavaElement owner= (IJavaElement)buffer.getOwner();
375 if (isAncestorOf(owner)) {
385 * Subclasses must override as required.
389 public boolean isConsistent() throws JavaModelException {
396 public boolean isOpen() {
397 synchronized(JavaModelManager.getJavaModelManager()){
398 return JavaModelManager.getJavaModelManager().getInfo(this) != null;
402 * Returns true if this represents a source element.
403 * Openable source elements have an associated buffer created
404 * when they are opened.
406 protected boolean isSourceElement() {
412 //public void makeConsistent(IProgressMonitor pm) throws JavaModelException {
413 // if (!isConsistent()) {
414 // buildStructure((OpenableElementInfo)getElementInfo(), pm);
420 public void makeConsistent(IProgressMonitor monitor) throws JavaModelException {
421 if (isConsistent()) return;
423 // create a new info and make it the current info
424 // (this will remove the info and its children just before storing the new infos)
425 JavaModelManager manager = JavaModelManager.getJavaModelManager();
426 boolean hadTemporaryCache = manager.hasTemporaryCache();
428 HashMap newElements = manager.getTemporaryCache();
429 openWhenClosed(newElements, monitor);
430 if (newElements.get(this) == null) {
431 // close any buffer that was opened for the new elements
432 Iterator iterator = newElements.keySet().iterator();
433 while (iterator.hasNext()) {
434 IJavaElement element = (IJavaElement)iterator.next();
435 if (element instanceof Openable) {
436 ((Openable)element).closeBuffer();
439 throw newNotPresentException();
441 if (!hadTemporaryCache) {
442 manager.putInfos(this, newElements);
445 if (!hadTemporaryCache) {
446 manager.resetTemporaryCache();
454 public void open(IProgressMonitor pm) throws JavaModelException {
458 * Opens a buffer on the contents of this element, and returns
459 * the buffer, or returns <code>null</code> if opening fails.
460 * By default, do nothing - subclasses that have buffers
461 * must override as required.
463 protected IBuffer openBuffer(IProgressMonitor pm) throws JavaModelException {
468 * Open the parent element if necessary.
470 protected void openParent(Object childInfo, HashMap newElements, IProgressMonitor pm) throws JavaModelException {
472 Openable openableParent = (Openable)getOpenableParent();
473 if (openableParent != null && !openableParent.isOpen()){
474 openableParent.generateInfos(openableParent.createElementInfo(), newElements, pm);
479 // * Open an <code>Openable</code> that is known to be closed (no check for <code>isOpen()</code>).
481 //protected void openWhenClosed(IProgressMonitor pm) throws JavaModelException {
484 // if (JavaModelManager.VERBOSE){
485 // System.out.println("OPENING Element ("+ Thread.currentThread()+"): " + this.toStringWithAncestors()); //$NON-NLS-1$//$NON-NLS-2$
488 // // 1) Parent must be open - open the parent if necessary
491 // // 2) create the new element info and open a buffer if needed
492 // OpenableElementInfo info = createElementInfo();
493 // if (isSourceElement()) {
494 // this.openBuffer(pm);
497 // // 3) build the structure of the openable
498 // buildStructure(info, pm);
500 // // 4) anything special
503 //// if (JavaModelManager.VERBOSE) {
504 //// System.out.println("-> Package cache size = " + JavaModelManager.getJavaModelManager().cache.pkgSize()); //$NON-NLS-1$
505 //// System.out.println("-> Openable cache filling ratio = " + JavaModelManager.getJavaModelManager().cache.openableFillingRatio() + "%"); //$NON-NLS-1$//$NON-NLS-2$
508 // // if any problems occuring openning the element, ensure that it's info
509 // // does not remain in the cache (some elements, pre-cache their info
510 // // as they are being opened).
511 // } catch (JavaModelException e) {
512 // JavaModelManager.getJavaModelManager().removeInfo(this);
518 * Answers true if the parent exists (null parent is answering true)
521 protected boolean parentExists(){
523 IJavaElement parent = this.getParent();
524 if (parent == null) return true;
525 return parent.exists();
529 * Returns whether the corresponding resource or associated file exists
531 protected boolean resourceExists() {
532 IWorkspace workspace = ResourcesPlugin.getWorkspace();
533 if (workspace == null) return false; // workaround for http://bugs.eclipse.org/bugs/show_bug.cgi?id=34069
537 this.getPath().makeRelative(), // ensure path is relative (see http://dev.eclipse.org/bugs/show_bug.cgi?id=22517)
544 public void save(IProgressMonitor pm, boolean force) throws JavaModelException {
545 if (isReadOnly() || this.getResource().isReadOnly()) {
546 throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.READ_ONLY, this));
548 IBuffer buf = getBuffer();
549 if (buf != null) { // some Openables (like a JavaProject) don't have a buffer
551 this.makeConsistent(pm); // update the element info of this element
556 * Find enclosing package fragment root if any
558 public PackageFragmentRoot getPackageFragmentRoot() {
559 IJavaElement current = this;
561 if (current instanceof PackageFragmentRoot) return (PackageFragmentRoot)current;
562 current = current.getParent();
563 } while(current != null);
567 // * @see ICodeAssist
568 // * @deprecated - use codeComplete(ICompilationUnit, ICompilationUnit, int, ICompletionRequestor) instead
570 //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 {
572 // if (requestor == null){
573 // codeComplete(cu, unitToSkip, position, (ICompletionRequestor)null);
580 // new ICompletionRequestor(){
581 // public void acceptAnonymousType(char[] superTypePackageName,char[] superTypeName,char[][] parameterPackageNames,char[][] parameterTypeNames,char[][] parameterNames,char[] completionName,int modifiers,int completionStart,int completionEnd, int relevance) {
583 // public void acceptClass(char[] packageName, char[] className, char[] completionName, int modifiers, int completionStart, int completionEnd, int relevance) {
584 // requestor.acceptClass(packageName, className, completionName, modifiers, completionStart, completionEnd);
586 // public void acceptError(IProblem error) {
587 // if (true) return; // was disabled in 1.0
590 // IMarker marker = ResourcesPlugin.getWorkspace().getRoot().createMarker(IJavaModelMarker.TRANSIENT_PROBLEM);
591 // marker.setAttribute(IJavaModelMarker.ID, error.getID());
592 // marker.setAttribute(IMarker.CHAR_START, error.getSourceStart());
593 // marker.setAttribute(IMarker.CHAR_END, error.getSourceEnd() + 1);
594 // marker.setAttribute(IMarker.LINE_NUMBER, error.getSourceLineNumber());
595 // marker.setAttribute(IMarker.MESSAGE, error.getMessage());
596 // marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR);
597 // requestor.acceptError(marker);
598 // } catch(CoreException e){
601 // public void acceptField(char[] declaringTypePackageName, char[] declaringTypeName, char[] name, char[] typePackageName, char[] typeName, char[] completionName, int modifiers, int completionStart, int completionEnd, int relevance) {
602 // requestor.acceptField(declaringTypePackageName, declaringTypeName, name, typePackageName, typeName, completionName, modifiers, completionStart, completionEnd);
604 // public void acceptInterface(char[] packageName,char[] interfaceName,char[] completionName,int modifiers,int completionStart,int completionEnd, int relevance) {
605 // requestor.acceptInterface(packageName, interfaceName, completionName, modifiers, completionStart, completionEnd);
607 // public void acceptKeyword(char[] keywordName,int completionStart,int completionEnd, int relevance){
608 // requestor.acceptKeyword(keywordName, completionStart, completionEnd);
610 // public void acceptLabel(char[] labelName,int completionStart,int completionEnd, int relevance){
611 // requestor.acceptLabel(labelName, completionStart, completionEnd);
613 // public void acceptLocalVariable(char[] name,char[] typePackageName,char[] typeName,int modifiers,int completionStart,int completionEnd, int relevance){
616 // 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){
617 // // skip parameter names
618 // requestor.acceptMethod(declaringTypePackageName, declaringTypeName, selector, parameterPackageNames, parameterTypeNames, returnTypePackageName, returnTypeName, completionName, modifiers, completionStart, completionEnd);
620 // 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){
623 // public void acceptModifier(char[] modifierName,int completionStart,int completionEnd, int relevance){
624 // requestor.acceptModifier(modifierName, completionStart, completionEnd);
626 // public void acceptPackage(char[] packageName,char[] completionName,int completionStart,int completionEnd, int relevance){
627 // requestor.acceptPackage(packageName, completionName, completionStart, completionEnd);
629 // public void acceptType(char[] packageName,char[] typeName,char[] completionName,int completionStart,int completionEnd, int relevance){
630 // requestor.acceptType(packageName, typeName, completionName, completionStart, completionEnd);
632 // public void acceptVariableName(char[] typePackageName,char[] typeName,char[] name,char[] completionName,int completionStart,int completionEnd, int relevance){