From: khartlage
+ * A variable initializer is automatically activated whenever a variable value
+ * is needed and none has been recorded so far. The implementation of
+ * the initializer can set the corresponding variable using
+ *
+ * A classpath entry can refer to any of the following:initialize
.
+ *
+ * @see IClasspathEntry
+ * @since 2.0
+ */
+public abstract class ClasspathVariableInitializer {
+
+ /**
+ * Creates a new classpath variable initializer.
+ */
+ public ClasspathVariableInitializer() {
+ }
+
+ /**
+ * Binds a value to the workspace classpath variable with the given name,
+ * or fails silently if this cannot be done.
+ * JavaCore#setClasspathVariable
.
+ *
+ * @param variable the name of the workspace classpath variable
+ * that requires a binding
+ *
+ * @see JavaCore#getClasspathVariable(String)
+ * @see JavaCore#setClasspathVariable(String, IPath, IProgressMonitor)
+ * @see JavaCore#setClasspathVariables(String[], IPath[], IProgressMonitor)
+ */
+ public abstract void initialize(String variable);
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/Flags.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/Flags.java
index 3fcf33a..fefe486 100644
--- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/Flags.java
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/Flags.java
@@ -80,12 +80,12 @@ public final class Flags {
* Interface property flag. See The Java Virtual Machine Specification for more details.
* @since 2.0
*/
-// public static final int AccInterface = IConstants.AccInterface;
+ public static final int AccInterface = IConstants.AccInterface;
/**
* Abstract property flag. See The Java Virtual Machine Specification for more details.
* @since 2.0
*/
-// public static final int AccAbstract = IConstants.AccAbstract;
+ public static final int AccAbstract = IConstants.AccAbstract;
/**
* Strictfp property flag. See The Java Virtual Machine Specification for more details.
* @since 2.0
@@ -105,7 +105,7 @@ public final class Flags {
* Deprecated property flag. See The Java Virtual Machine Specification for more details.
* @since 2.0
*/
-// public static final int AccDeprecated = IConstants.AccDeprecated;
+ public static final int AccDeprecated = IConstants.AccDeprecated;
/**
* Not instantiable.
@@ -118,9 +118,9 @@ public final class Flags {
* @param flags the flags
* @return true
if the abstract
modifier is included
*/
-// public static boolean isAbstract(int flags) {
-// return (flags & AccAbstract) != 0;
-// }
+ public static boolean isAbstract(int flags) {
+ return (flags & AccAbstract) != 0;
+ }
/**
* Returns whether the given integer includes the indication that the
* element is deprecated (@deprecated
tag in Javadoc comment).
@@ -128,9 +128,9 @@ public final class Flags {
* @param flags the flags
* @return true
if the element is marked as deprecated
*/
-// public static boolean isDeprecated(int flags) {
-// return (flags & AccDeprecated) != 0;
-// }
+ public static boolean isDeprecated(int flags) {
+ return (flags & AccDeprecated) != 0;
+ }
/**
* Returns whether the given integer includes the final
modifier.
*
@@ -147,9 +147,9 @@ public final class Flags {
* @return true
if the interface
modifier is included
* @since 2.0
*/
-// public static boolean isInterface(int flags) {
-// return (flags & AccInterface) != 0;
-// }
+ public static boolean isInterface(int flags) {
+ return (flags & AccInterface) != 0;
+ }
/**
* Returns whether the given integer includes the native
modifier.
*
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IBufferFactory.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IBufferFactory.java
index 45389b6..15b61e6 100644
--- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IBufferFactory.java
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IBufferFactory.java
@@ -28,6 +28,6 @@ public interface IBufferFactory {
* @param owner the owner of the buffer
* @see IBuffer
*/
-// IBuffer createBuffer(IOpenable owner);
+ IBuffer createBuffer(IOpenable owner);
}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IClasspathEntry.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IClasspathEntry.java
new file mode 100644
index 0000000..83de070
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IClasspathEntry.java
@@ -0,0 +1,370 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.core;
+
+import org.eclipse.core.runtime.IPath;
+
+/**
+ * An entry on a Java project classpath identifying one or more package fragment
+ * roots. A classpath entry has a content kind (either source,
+ * K_SOURCE
, or binary, K_BINARY
), which is inherited
+ * by each package fragment root and package fragment associated with the entry.
+ *
+ *
+ *
+ * .java
source files. The root folder itself represents a default
+ * package, subfolders represent package fragments, and .java
files
+ * represent compilation units. All compilation units will be compiled when
+ * the project is built. The classpath entry must specify the
+ * absolute path to the root folder. Entries of this kind are
+ * associated with the CPE_SOURCE
constant.
+ * Source classpath entries can carry patterns to exclude selected files.
+ * Excluded .java
source files do not appear as compilation
+ * units and are not compiled when the project is built.
+ * .class
files. The classpath entry
+ * must specify the absolute path to the JAR (or root folder), and in case it refers
+ * to an external JAR, then there is no associated resource in the workbench. Entries
+ * of this kind are associated with the CPE_LIBRARY
constant..class
files when building). When performing other
+ * "development" operations - such as code assist, code resolve, type hierarchy
+ * creation, etc. - the source code of the project is referred to. Thus, development
+ * is performed against a required project's source code, and compilation is
+ * performed against a required project's last built state. The
+ * classpath entry must specify the absolute path to the
+ * project. Entries of this kind are associated with the CPE_PROJECT
+ * constant.
+ * Note: referencing a required project with a classpath entry refers to the source
+ * code or associated .class
files located in its output location.
+ * It will also automatically include any other libraries or projects that the required project's classpath
+ * refers to, iff the corresponding classpath entries are tagged as being exported
+ * (IClasspathEntry#isExported
).
+ * Unless exporting some classpath entries, classpaths are not chained by default -
+ * each project must specify its own classpath in its entirety.CPE_VARIABLE
constant.
+ * Classpath variables are created using JavaCore#setClasspathVariable
,
+ * and gets resolved, to either a project or library entry, using
+ * JavaCore#getResolvedClasspathVariable
.
+ * It is also possible to register an automatic initializer (ClasspathVariableInitializer
),
+ * which will be invoked through the extension point "org.eclipse.jdt.core.classpathVariableInitializer".
+ * After resolution, a classpath variable entry may either correspond to a project or a library entry. CPE_CONTAINER
. Typically, a classpath container can
+ * be used to describe a complex library composed of multiple JARs, projects or classpath variables,
+ * considering also that containers can be mapped differently on each project. Several projects can
+ * reference the same generic container path, but have each of them actually bound to a different
+ * container object.
+ * The container path is a formed by a first ID segment followed with extra segments,
+ * which can be used as additional hints for resolving this container reference. If no container was ever
+ * recorded for this container path onto this project (using setClasspathContainer
,
+ * then a ClasspathContainerInitializer
will be activated if any was registered for this
+ * container ID onto the extension point "org.eclipse.jdt.core.classpathContainerInitializer".
+ * A classpath container entry can be resolved explicitly using JavaCore#getClasspathContainer
+ * and the resulting container entries can contain any non-container entry. In particular, it may contain variable
+ * entries, which in turn needs to be resolved before being directly used.
+ *
Also note that the container resolution APIs include an IJavaProject argument, so as to allow the same
+ * container path to be interpreted in different ways for different projects.
IJavaProject#getResolvedClasspath
will have all entries of type
+ * CPE_VARIABLE
and CPE_CONTAINER
resolved to a set of
+ * CPE_SOURCE
, CPE_LIBRARY
or CPE_PROJECT
+ * classpath entries.
+ *
+ * Any classpath entry other than a source folder (kind CPE_SOURCE
) can
+ * be marked as being exported. Exported entries are automatically contributed to
+ * dependent projects, along with the project's default output folder, which is
+ * implicitly exported, and any auxiliary output folders specified on source
+ * classpath entries. The project's output folder(s) are always listed first,
+ * followed by the any exported entries.
+ *
+ * This interface is not intended to be implemented by clients.
+ * Classpath entries can be created via methods on JavaCore
.
+ *
IPackageFragmentRoot.K_SOURCE
for files containing
+ * source code, and IPackageFragmentRoot.K_BINARY
for binary
+ * class files.
+ * There is no specified value for an entry denoting a variable (CPE_VARIABLE
)
+ * or a classpath container (CPE_CONTAINER
).
+ */
+ int getContentKind();
+
+ /**
+ * Returns the kind of this classpath entry.
+ *
+ * @return one of:
+ * CPE_SOURCE
- this entry describes a source root in
+ its project
+ * CPE_LIBRARY
- this entry describes a folder or JAR
+ containing binaries
+ * CPE_PROJECT
- this entry describes another project
+ *
+ * CPE_VARIABLE
- this entry describes a project or library
+ * indirectly via a classpath variable in the first segment of the path
+ * *
+ * CPE_CONTAINER
- this entry describes set of entries
+ * referenced indirectly via a classpath container
+ * + * Exclusion patterns allow specified portions of the resource tree rooted + * at this source entry's path to be filtered out. If no exclusion patterns + * are specified, this source entry includes all relevent files. Each path + * specified must be a relative path, and will be interpreted relative + * to this source entry's path. File patterns are case-sensitive. A file + * matched by one or more of these patterns is excluded from the + * corresponding package fragment root. + *
+ *+ * Note that there is no need to supply a pattern to exclude ".class" files + * because a source entry filters these out automatically. + *
+ *+ * The pattern mechanism is similar to Ant's. Each pattern is represented as + * a relative path. The path segments can be regular file or folder names or simple patterns + * involving standard wildcard characters. + *
+ *
+ * '*' matches 0 or more characters within a segment. So
+ * *.java
matches .java
, a.java
+ * and Foo.java
, but not Foo.properties
+ * (does not end with .java
).
+ *
+ * '?' matches 1 character within a segment. So ?.java
+ * matches a.java
, A.java
,
+ * but not .java
or xyz.java
(neither have
+ * just one character before .java
).
+ *
+ * Combinations of *'s and ?'s are allowed. + *
+ *
+ * The special pattern '**' matches zero or more segments. A path
+ * like tests/
that ends in a trailing separator is interpreted
+ * as tests/**
, and would match all files under the
+ * the folder named tests
.
+ *
+ * Examples: + *
tests/**
(or simply tests/
)
+ * matches all files under a root folder
+ * named tests
. This includes tests/Foo.java
+ * and tests/com/example/Foo.java
, but not
+ * com/example/tests/Foo.java
(not under a root folder named
+ * tests
).
+ * tests/*
matches all files directly below a root
+ * folder named tests
. This includes tests/Foo.java
+ * and tests/FooHelp.java
+ * but not tests/com/example/Foo.java
(not directly under
+ * a folder named tests
) or
+ * com/Foo.java
(not under a folder named tests
).
+ * **/tests/**
matches all files under any
+ * folder named tests
. This includes tests/Foo.java
,
+ * com/examples/tests/Foo.java
, and
+ * com/examples/tests/unit/Foo.java
, but not
+ * com/example/Foo.java
(not under a folder named
+ * tests
).
+ * null
for other
+ * kinds of classpath entries
+ * @since 2.1
+ */
+ IPath[] getExclusionPatterns();
+
+ /**
+ * Returns the full path to the specific location where the builder writes
+ * .class
files generated for this source entry
+ * (entry kind CPE_SOURCE
).
+ *
+ * Source entries can optionally be associated with a specific output location.
+ * If none is provided, the source entry will be implicitly associated with its project
+ * default output location (see IJavaProject#getOutputLocation
).
+ *
+ * NOTE: A specific output location cannot coincidate with another source/library entry. + *
+ * + * @return the full path to the specific location where the builder writes + *.class
files for this source entry, or null
+ * if using default output folder
+ * @since 2.1
+ */
+ IPath getOutputLocation();
+
+ /**
+ * Returns the path of this classpath entry.
+ *
+ * The meaning of the path of a classpath entry depends on its entry kind:CPE_SOURCE
) -
+ * The path associated with this entry is the absolute path to the root folder. CPE_LIBRARY
) - the path
+ * associated with this entry is the absolute path to the JAR (or root folder), and
+ * in case it refers to an external JAR, then there is no associated resource in
+ * the workbench.
+ * CPE_PROJECT
) - the path of the entry denotes the
+ * path to the corresponding project resource.CPE_VARIABLE
) - the first segment of the path
+ * is the name of a classpath variable. If this classpath variable
+ * is bound to the path CPE_CONTAINER
) - the path of the entry
+ * is the name of the classpath container, which can be bound indirectly to a set of classpath
+ * entries after resolution. The containerPath is a formed by a first ID segment followed with
+ * extra segments that can be used as additional hints for resolving this container
+ * reference (also see IClasspathContainer
).
+ * null
if this classpath entry has no
+ * source attachment.
+ * + * Only library and variable classpath entries may have source attachments. + * For library classpath entries, the result path (if present) locates a source + * archive or folder. This archive or folder can be located in a project of the + * workspace or outside thr workspace. For variable classpath entries, the + * result path (if present) has an analogous form and meaning as the + * variable path, namely the first segment is the name of a classpath variable. + *
+ * + * @return the path to the source archive or folder, ornull
if none
+ */
+ IPath getSourceAttachmentPath();
+
+ /**
+ * Returns the path within the source archive or folder where package fragments
+ * are located. An empty path indicates that packages are located at
+ * the root of the source archive or folder. Returns a non-null
value
+ * if and only if getSourceAttachmentPath
returns
+ * a non-null
value.
+ *
+ * @return the path within the source archive or folder, or null
if
+ * not applicable
+ */
+ IPath getSourceAttachmentRootPath();
+
+ /**
+ * Returns whether this entry is exported to dependent projects.
+ * Always returns false
for source entries (kind
+ * CPE_SOURCE
), which cannot be exported.
+ *
+ * @return true
if exported, and false
otherwise
+ * @since 2.0
+ */
+ boolean isExported();
+
+ /**
+ * This is a helper method, which returns the resolved classpath entry denoted
+ * by an entry (if it is a variable entry). It is obtained by resolving the variable
+ * reference in the first segment. Returns null
null
+ * Variable source attachment is also resolved and recorded in the resulting classpath entry. + *
+ * @return the resolved library or project classpath entry, or null
+ * if the given path could not be resolved to a classpath entry
+ *
+ * Note that this deprecated API doesn't handle CPE_CONTAINER entries.
+ *
+ * @deprecated - use JavaCore.getResolvedClasspathEntry(...)
+ */
+ IClasspathEntry getResolvedEntry();
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ICompilationUnit.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ICompilationUnit.java
index 94f7f88..5bcfd3f 100644
--- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ICompilationUnit.java
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ICompilationUnit.java
@@ -11,6 +11,7 @@
package net.sourceforge.phpdt.core;
+
/**
* Represents an entire Java compilation unit (.java
source file).
* Compilation unit elements need to be opened before they can be navigated or manipulated.
@@ -23,8 +24,8 @@ package net.sourceforge.phpdt.core;
*
* This interface is not intended to be implemented by clients. *
- */ -public interface ICompilationUnit extends IJavaElement, IParent, IOpenable { + */ +public interface ICompilationUnit extends IJavaElement, ISourceReference, IParent, IOpenable, IWorkingCopy, ISourceManipulation { //extends IJavaElement, ISourceReference, IParent, IOpenable, IWorkingCopy, ISourceManipulation, ICodeAssist { /** * Creates and returns an import declaration in this compilation unit @@ -122,7 +123,7 @@ public interface ICompilationUnit extends IJavaElement, IParent, IOpenable { * @exception JavaModelException if this element does not exist or if an * exception occurs while accessing its corresponding resource */ -//IType[] getAllTypes() throws JavaModelException; +IType[] getAllTypes() throws JavaModelException; /** * Returns the smallest element within this compilation unit that * includes the given source position (that is, a method, field, etc.), or @@ -136,7 +137,7 @@ public interface ICompilationUnit extends IJavaElement, IParent, IOpenable { * @exception JavaModelException if the compilation unit does not exist or if an * exception occurs while accessing its corresponding resource */ -//IJavaElement getElementAt(int position) throws JavaModelException; +IJavaElement getElementAt(int position) throws JavaModelException; /** * Returns the first import declaration in this compilation unit with the given name. * This is a handle-only method. The import declaration may or may not exist. This @@ -174,7 +175,7 @@ public interface ICompilationUnit extends IJavaElement, IParent, IOpenable { * * @param name the name of the package declaration as defined by JLS2 7.4. (For example,"java.lang"
)
*/
-//IPackageDeclaration getPackageDeclaration(String name);
+IPackageDeclaration getPackageDeclaration(String name);
/**
* Returns the package declarations in this compilation unit
* in the order in which they appear in the source.
@@ -195,7 +196,7 @@ public interface ICompilationUnit extends IJavaElement, IParent, IOpenable {
* @return a handle onto the corresponding type. The type may or may not exist.
* @see JavaConventions#validateCompilationUnitName(String name)
*/
-//IType getType(String name);
+IType getType(String name);
/**
* Returns the top-level types declared in this compilation unit
* in the order in which they appear in the source.
@@ -203,6 +204,6 @@ public interface ICompilationUnit extends IJavaElement, IParent, IOpenable {
* @exception JavaModelException if this element does not exist or if an
* exception occurs while accessing its corresponding resource
*/
-//IType[] getTypes() throws JavaModelException;
+IType[] getTypes() throws JavaModelException;
}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaElement.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaElement.java
index 318061a..0f4693a 100644
--- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaElement.java
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaElement.java
@@ -12,6 +12,7 @@ package net.sourceforge.phpdt.core;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IAdaptable;
+import org.eclipse.core.runtime.IPath;
/**
* Common protocol for all elements provided by the Java model.
@@ -129,7 +130,7 @@ public interface IJavaElement extends IAdaptable {
* @return true
if this element exists in the Java model, and
* false
if this element does not exist
*/
-// boolean exists();
+ boolean exists();
/**
* Returns the first ancestor of this Java element that has the given type.
@@ -160,7 +161,7 @@ public interface IJavaElement extends IAdaptable {
* @exception JavaModelException if this element does not exist or if an
* exception occurs while accessing its corresponding resource
*/
-// IResource getCorrespondingResource() throws JavaModelException;
+ IResource getCorrespondingResource() throws JavaModelException;
/**
* Returns the name of this element. This is a handle-only method.
@@ -208,7 +209,7 @@ public interface IJavaElement extends IAdaptable {
* @return the containing Java project, or null
if this element is
* not contained in a Java project
*/
-// IJavaProject getJavaProject();
+ IJavaProject getJavaProject();
/**
* Returns the first openable parent. If this element is openable, the element
@@ -243,7 +244,7 @@ public interface IJavaElement extends IAdaptable {
* @return the path to the innermost resource enclosing this element
* @since 2.0
*/
-// IPath getPath();
+ IPath getPath();
/**
* Returns the innermost resource enclosing this element.
@@ -299,5 +300,5 @@ public interface IJavaElement extends IAdaptable {
* @exception JavaModelException if this element does not exist or if an
* exception occurs while accessing its corresponding resource
*/
-// boolean isStructureKnown() throws JavaModelException;
+ boolean isStructureKnown() throws JavaModelException;
}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaModel.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaModel.java
index a4ff657..f8cf1d8 100644
--- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaModel.java
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaModel.java
@@ -10,7 +10,9 @@
*******************************************************************************/
package net.sourceforge.phpdt.core;
+import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
+import org.eclipse.core.runtime.IProgressMonitor;
/**
* Represent the root Java element corresponding to the workspace.
@@ -47,7 +49,7 @@ public interface IJavaModel extends IJavaElement, IOpenable, IParent {
* @return true if the resource is accessible through the Java model
* @since 2.1
*/
-//boolean contains(IResource resource);
+boolean contains(IResource resource);
/**
* Copies the given elements to the specified container(s).
* If one container is specified, all elements are copied to that
@@ -94,7 +96,7 @@ public interface IJavaModel extends IJavaElement, IOpenable, IParent {
* READ_ONLY
) READ_ONLY
) null
*/
-//void move(IJavaElement[] elements, IJavaElement[] containers, IJavaElement[] siblings, String[] renamings, boolean replace, IProgressMonitor monitor) throws JavaModelException;
+void move(IJavaElement[] elements, IJavaElement[] containers, IJavaElement[] siblings, String[] renamings, boolean replace, IProgressMonitor monitor) throws JavaModelException;
/**
* Triggers an update of the JavaModel with respect to the referenced external archives.
@@ -249,6 +251,6 @@ IWorkspace getWorkspace();
* READ_ONLY
)
*
*/
-//void rename(IJavaElement[] elements, IJavaElement[] destinations, String[] names, boolean replace, IProgressMonitor monitor) throws JavaModelException;
+void rename(IJavaElement[] elements, IJavaElement[] destinations, String[] names, boolean replace, IProgressMonitor monitor) throws JavaModelException;
}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaModelMarker.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaModelMarker.java
new file mode 100644
index 0000000..22cce48
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaModelMarker.java
@@ -0,0 +1,95 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.core;
+
+import net.sourceforge.phpeclipse.PHPCore;
+
+/**
+ * Markers used by the Java model.
+ * + * This interface declares constants only; it is not intended to be implemented + * or extended. + *
+ */ +public interface IJavaModelMarker { + + /** + * Java model problem marker type (value"org.eclipse.jdt.core.problem"
).
+ * This can be used to recognize those markers in the workspace that flag problems
+ * detected by the Java tooling during compilation.
+ */
+ public static final String JAVA_MODEL_PROBLEM_MARKER = PHPCore.PLUGIN_ID + ".problem"; //$NON-NLS-1$
+
+
+ /**
+ * Java model transient problem marker type (value "org.eclipse.jdt.core.transient_problem"
).
+ * This can be used to recognize those markers in the workspace that flag transient
+ * problems detected by the Java tooling (such as a problem
+ * detected by the outliner, or a problem detected during a code completion)
+ */
+ public static final String TRANSIENT_PROBLEM = PHPCore.PLUGIN_ID + ".transient_problem"; //$NON-NLS-1$
+
+ /**
+ * Java model task marker type (value "org.eclipse.jdt.core.task"
).
+ * This can be used to recognize task markers in the workspace that correspond to tasks
+ * specified in Java source comments and detected during compilation (for example, 'TO-DO: ...').
+ * Tasks are identified by a task tag, which can be customized through PHPCore
+ * option "org.eclipse.jdt.core.compiler.taskTag"
.
+ * @since 2.1
+ */
+ public static final String TASK_MARKER = PHPCore.PLUGIN_ID + ".task"; //$NON-NLS-1$
+
+
+ /**
+ * Id marker attribute (value "arguments"
).
+ * Arguments are concatenated into one String, prefixed with an argument count (followed with colon
+ * separator) and separated with '#' characters. For example:
+ * { "foo", "bar" } is encoded as "2:foo#bar",
+ * { } is encoded as "0: "
+ * @since 2.0
+ */
+ public static final String ARGUMENTS = "arguments"; //$NON-NLS-1$
+
+ /**
+ * Id marker attribute (value "id"
).
+ */
+ public static final String ID = "id"; //$NON-NLS-1$
+
+ /**
+ * Flags marker attribute (value "flags"
).
+ * Reserved for future use.
+ */
+ public static final String FLAGS = "flags"; //$NON-NLS-1$
+
+ /**
+ * Cycle detected marker attribute (value "cycleDetected"
).
+ * Used only on buildpath problem markers.
+ * The value of this attribute is either "true" or "false".
+ */
+ public static final String CYCLE_DETECTED = "cycleDetected"; //$NON-NLS-1$
+
+ /**
+ * Build path problem marker type (value "org.eclipse.jdt.core.buildpath_problem"
).
+ * This can be used to recognize those markers in the workspace that flag problems
+ * detected by the Java tooling during classpath setting.
+ */
+ public static final String BUILDPATH_PROBLEM_MARKER = PHPCore.PLUGIN_ID + ".buildpath_problem"; //$NON-NLS-1$
+
+ /**
+ * Classpath file format marker attribute (value "classpathFileFormat"
).
+ * Used only on buildpath problem markers.
+ * The value of this attribute is either "true" or "false".
+ *
+ * @since 2.0
+ */
+ public static final String CLASSPATH_FILE_FORMAT = "classpathFileFormat"; //$NON-NLS-1$
+
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaProject.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaProject.java
index 612ff56..8bf235a 100644
--- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaProject.java
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IJavaProject.java
@@ -14,7 +14,12 @@
*******************************************************************************/
package net.sourceforge.phpdt.core;
+import java.util.Map;
+
import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.core.runtime.IProgressMonitor;
/**
@@ -70,7 +75,7 @@ public interface IJavaProject extends IParent, IJavaElement, IOpenable {
* classpath-relative path, or null
if no such
* IJavaElement
is found
*/
-// IJavaElement findElement(IPath path) throws JavaModelException;
+ IJavaElement findElement(IPath path) throws JavaModelException;
/**
* Returns the first existing package fragment on this project's classpath
@@ -102,8 +107,8 @@ public interface IJavaProject extends IParent, IJavaElement, IOpenable {
* whose path matches the given (absolute) path, or null
if
* one does not exist
*/
-// IPackageFragmentRoot findPackageFragmentRoot(IPath path)
-// throws JavaModelException;
+ IPackageFragmentRoot findPackageFragmentRoot(IPath path)
+ throws JavaModelException;
/**
* Returns the existing package fragment roots identified by the given entry.
* Note that a classpath entry that refers to another project may
@@ -122,7 +127,7 @@ public interface IJavaProject extends IParent, IJavaElement, IOpenable {
* @see IClasspathContainer
* @since 2.1
*/
-// IPackageFragmentRoot[] findPackageFragmentRoots(IClasspathEntry entry);
+ IPackageFragmentRoot[] findPackageFragmentRoots(IClasspathEntry entry);
/**
* Returns the first type found following this project's classpath
* with the given fully qualified name or null
if none is found.
@@ -182,7 +187,7 @@ public interface IJavaProject extends IParent, IJavaElement, IOpenable {
* @exception JavaModelException if this element does not exist or if an
* exception occurs while accessing its corresponding resource
*/
-// IPackageFragmentRoot[] getAllPackageFragmentRoots() throws JavaModelException;
+ IPackageFragmentRoot[] getAllPackageFragmentRoots() throws JavaModelException;
/**
* Returns an array of non-Java resources directly contained in this project.
@@ -216,7 +221,7 @@ public interface IJavaProject extends IParent, IJavaElement, IOpenable {
* @see JavaCore#getDefaultOptions
* @since 2.1
*/
-// String getOption(String optionName, boolean inheritJavaCoreOptions);
+ String getOption(String optionName, boolean inheritJavaCoreOptions);
/**
* Returns the table of the current custom options for this project. Projects remember their custom options,
@@ -254,7 +259,7 @@ public interface IJavaProject extends IParent, IJavaElement, IOpenable {
* @see #setOutputLocation
* @see IClasspathEntry#getOutputLocation
*/
-// IPath getOutputLocation() throws JavaModelException;
+ IPath getOutputLocation() throws JavaModelException;
/**
* Returns a package fragment root for the JAR at the specified file system path.
@@ -278,7 +283,7 @@ public interface IJavaProject extends IParent, IJavaElement, IOpenable {
* must either be a folder representing the top of a package hierarchy,
* or a .jar
or .zip
file
*/
-// IPackageFragmentRoot getPackageFragmentRoot(IResource resource);
+ IPackageFragmentRoot getPackageFragmentRoot(IResource resource);
/**
* Returns all of the package fragment roots contained in this
@@ -293,7 +298,7 @@ public interface IJavaProject extends IParent, IJavaElement, IOpenable {
* @exception JavaModelException if this element does not exist or if an
* exception occurs while accessing its corresponding resource
*/
-// IPackageFragmentRoot[] getPackageFragmentRoots() throws JavaModelException;
+ IPackageFragmentRoot[] getPackageFragmentRoots() throws JavaModelException;
/**
* Returns the existing package fragment roots identified by the given entry.
@@ -313,7 +318,7 @@ public interface IJavaProject extends IParent, IJavaElement, IOpenable {
* @see IClasspathContainer
* @deprecated Use IJavaProject#findPackageFragmentRoots instead
*/
-// IPackageFragmentRoot[] getPackageFragmentRoots(IClasspathEntry entry);
+ IPackageFragmentRoot[] getPackageFragmentRoots(IClasspathEntry entry);
/**
* Returns all package fragments in all package fragment roots contained
@@ -327,7 +332,7 @@ public interface IJavaProject extends IParent, IJavaElement, IOpenable {
* @exception JavaModelException if this element does not exist or if an
* exception occurs while accessing its corresponding resource
*/
-// IPackageFragment[] getPackageFragments() throws JavaModelException;
+ IPackageFragment[] getPackageFragments() throws JavaModelException;
/**
* Returns the IProject
on which this IJavaProject
@@ -356,7 +361,7 @@ public interface IJavaProject extends IParent, IJavaElement, IOpenable {
* exception occurs while accessing its corresponding resource
* @see IClasspathEntry
*/
-// IClasspathEntry[] getRawClasspath() throws JavaModelException;
+ IClasspathEntry[] getRawClasspath() throws JavaModelException;
/**
* Returns the names of the projects that are directly required by this
@@ -369,7 +374,7 @@ public interface IJavaProject extends IParent, IJavaElement, IOpenable {
* @exception JavaModelException if this element does not exist or if an
* exception occurs while accessing its corresponding resource
*/
-// String[] getRequiredProjectNames() throws JavaModelException;
+ String[] getRequiredProjectNames() throws JavaModelException;
/**
* This is a helper method returning the resolved classpath for the project
@@ -403,14 +408,14 @@ public interface IJavaProject extends IParent, IJavaElement, IOpenable {
*
* @see IClasspathEntry
*/
-// IClasspathEntry[] getResolvedClasspath(boolean ignoreUnresolvedEntry)
-// throws JavaModelException;
+ IClasspathEntry[] getResolvedClasspath(boolean ignoreUnresolvedEntry)
+ throws JavaModelException;
/**
* Returns whether this project has been built at least once and thus whether it has a build state.
* @return true if this project has been built at least once, false otherwise
*/
-// boolean hasBuildState();
+ boolean hasBuildState();
/**
* Returns whether setting this project's classpath to the given classpath entries
@@ -422,7 +427,7 @@ public interface IJavaProject extends IParent, IJavaElement, IOpenable {
* @param entries the given classpath entries
* @return true if the given classpath entries would result in a cycle, false otherwise
*/
-// boolean hasClasspathCycle(IClasspathEntry[] entries);
+ boolean hasClasspathCycle(IClasspathEntry[] entries);
/**
* Returns whether the given element is on the classpath of this project,
* that is, referenced from a classpath entry and not explicitly excluded
@@ -503,7 +508,7 @@ public interface IJavaProject extends IParent, IJavaElement, IOpenable {
* @see JavaCore#getDefaultOptions
* @since 2.1
*/
-// void setOptions(Map newOptions);
+ void setOptions(Map newOptions);
/**
* Sets the default output location of this project to the location
@@ -535,8 +540,8 @@ public interface IJavaProject extends IParent, IJavaElement, IOpenable {
* @see #getOutputLocation
* @see IClasspathEntry#getOutputLocation
*/
-// void setOutputLocation(IPath path, IProgressMonitor monitor)
-// throws JavaModelException;
+ void setOutputLocation(IPath path, IProgressMonitor monitor)
+ throws JavaModelException;
/**
* Sets the classpath of this project using a list of classpath entries. In particular such a classpath may contain
@@ -566,8 +571,8 @@ public interface IJavaProject extends IParent, IJavaElement, IOpenable {
*
* @see IClasspathEntry
*/
-// void setRawClasspath(IClasspathEntry[] entries, IProgressMonitor monitor)
-// throws JavaModelException;
+ void setRawClasspath(IClasspathEntry[] entries, IProgressMonitor monitor)
+ throws JavaModelException;
/**
* Sets the both the classpath of this project and its default output
@@ -614,6 +619,6 @@ public interface IJavaProject extends IParent, IJavaElement, IOpenable {
* @see IClasspathEntry
* @since 2.0
*/
-// void setRawClasspath(IClasspathEntry[] entries, IPath outputLocation, IProgressMonitor monitor)
-// throws JavaModelException;
+ void setRawClasspath(IClasspathEntry[] entries, IPath outputLocation, IProgressMonitor monitor)
+ throws JavaModelException;
}
\ No newline at end of file
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IMember.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IMember.java
index 8494bd8..68446bd 100644
--- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IMember.java
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IMember.java
@@ -45,7 +45,7 @@ ICompilationUnit getCompilationUnit();
* @return the type in which this member is declared, or null
* if this member is not declared in a type (for example, a top-level type)
*/
-//IType getDeclaringType();
+ IType getDeclaringType();
/**
* Returns the modifier flags for this member. The flags can be examined using class
* Flags
.
@@ -73,7 +73,7 @@ int getFlags() throws JavaModelException;
* (for example, an initializer), or if this member does not have
* associated source code (for example, a binary type)
*/
-//ISourceRange getNameRange() throws JavaModelException;
+ISourceRange getNameRange() throws JavaModelException;
/**
* Returns whether this member is from a class file.
* This is a handle-only method.
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IOpenable.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IOpenable.java
index 9409305..4df0499 100644
--- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IOpenable.java
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IOpenable.java
@@ -10,6 +10,8 @@
*******************************************************************************/
package net.sourceforge.phpdt.core;
+import org.eclipse.core.runtime.IProgressMonitor;
+
/**
* Common protocol for Java elements that must be opened before they can be
@@ -52,7 +54,7 @@ public interface IOpenable {
*
* @exception JavaModelException if an error occurs closing this element
*/
-//public void close() throws JavaModelException;
+public void close() throws JavaModelException;
/**
* Returns the buffer opened for this element, or null
* if this element does not have a buffer.
@@ -82,7 +84,7 @@ public IBuffer getBuffer() throws JavaModelException;
* element's children and has not yet destroyed
*
*/
-//boolean hasUnsavedChanges() throws JavaModelException;
+boolean hasUnsavedChanges() throws JavaModelException;
/**
* Returns whether the element is consistent with its underlying resource or buffer.
* The element is consistent when opened, and is consistent if the underlying resource
@@ -116,7 +118,7 @@ boolean isOpen();
*
* @see IOpenable#isConsistent
*/
-//void makeConsistent(IProgressMonitor progress) throws JavaModelException;
+void makeConsistent(IProgressMonitor progress) throws JavaModelException;
/**
* Opens this element and all parent elements that are not already open.
* For compilation units, a buffer is opened on the contents of the underlying resource.
@@ -132,7 +134,7 @@ boolean isOpen();
* + * This interface is not intended to be implemented by clients. + *
+ */ +public interface IPackageDeclaration extends IJavaElement, ISourceReference { +/** + * Returns the name of the package the statement refers to. + * This is a handle-only method. + */ +String getElementName(); +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IPackageFragment.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IPackageFragment.java index 131d36f..2d832d5 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IPackageFragment.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IPackageFragment.java @@ -112,7 +112,7 @@ public interface IPackageFragment extends IParent, IJavaElement, IOpenable { * exception occurs while accessing its corresponding resource. * @return all of the compilation units in this package fragment */ -// ICompilationUnit[] getCompilationUnits() throws JavaModelException; + ICompilationUnit[] getCompilationUnits() throws JavaModelException; /** * Returns the dot-separated package name of this fragment, for example *"java.lang"
, or ""
(the empty string),
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IPackageFragmentRoot.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IPackageFragmentRoot.java
index ba8d7ea..9e9fb02 100644
--- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IPackageFragmentRoot.java
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IPackageFragmentRoot.java
@@ -256,7 +256,7 @@ public interface IPackageFragmentRoot
* exception occurs while accessing its corresponding resource.
* @return this package fragment root's kind encoded as an integer
*/
-// int getKind() throws JavaModelException;
+ int getKind() throws JavaModelException;
/**
* Returns an array of non-Java resources contained in this package fragment root.
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IParent.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IParent.java
index 2a31793..f1571c5 100644
--- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IParent.java
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IParent.java
@@ -26,7 +26,7 @@ public interface IParent {
* exception occurs while accessing its corresponding resource
* @return the immediate children of this element
*/
-//IJavaElement[] getChildren() throws JavaModelException;
+IJavaElement[] getChildren() throws JavaModelException;
/**
* Returns whether this element has one or more immediate children.
* This is a convenience method, and may be more efficient than
@@ -36,5 +36,5 @@ public interface IParent {
* exception occurs while accessing its corresponding resource
* @return true if the immediate children of this element, false otherwise
*/
-//boolean hasChildren() throws JavaModelException;
+boolean hasChildren() throws JavaModelException;
}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ISourceManipulation.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ISourceManipulation.java
index 2747a52..449f6bb 100644
--- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ISourceManipulation.java
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/ISourceManipulation.java
@@ -47,7 +47,7 @@ public interface ISourceManipulation {
*
* @exception IllegalArgumentException if container is null
*/
-void copy(IJavaElement container, IJavaElement sibling, String rename, boolean replace, IProgressMonitor monitor) throws JavaModelException;
+//void copy(IJavaElement container, IJavaElement sibling, String rename, boolean replace, IProgressMonitor monitor) throws JavaModelException;
/**
* Deletes this element, forcing if specified and necessary.
*
@@ -62,7 +62,7 @@ void copy(IJavaElement container, IJavaElement sibling, String rename, boolean r
* null
*/
-void move(IJavaElement container, IJavaElement sibling, String rename, boolean replace, IProgressMonitor monitor) throws JavaModelException;
+//void move(IJavaElement container, IJavaElement sibling, String rename, boolean replace, IProgressMonitor monitor) throws JavaModelException;
/**
* Renames this element to the given name.
*
@@ -109,5 +109,5 @@ void move(IJavaElement container, IJavaElement sibling, String rename, boolean r
* null
if unable to find any matching type
*/
- String[][] resolveType(String typeName) throws JavaModelException;
+// String[][] resolveType(String typeName) throws JavaModelException;
}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IWorkingCopy.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IWorkingCopy.java
index d364b32..72f4a48 100644
--- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IWorkingCopy.java
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/IWorkingCopy.java
@@ -160,7 +160,7 @@ public interface IWorkingCopy {
* @return the found primary type of this compilation unit, or null
if no such a type exists
* @since 2.0
*/
-// IType findPrimaryType();
+ IType findPrimaryType();
/**
* Returns a shared working copy on this element using the given factory to create
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/JavaCore.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/JavaCore.java
deleted file mode 100644
index 6e8531b..0000000
--- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/JavaCore.java
+++ /dev/null
@@ -1,3238 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2003 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Common Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- * IBM Corporation - added the following constants:
- * COMPILER_PB_DEPRECATION_IN_DEPRECATED_CODE
- * COMPILER_PB_STATIC_ACCESS_RECEIVER
- * COMPILER_TASK_TAGS
- * CORE_CIRCULAR_CLASSPATH
- * CORE_INCOMPLETE_CLASSPATH
- * IBM Corporation - added run(IWorkspaceRunnable, IProgressMonitor)
- * IBM Corporation - added exclusion patterns to source classpath entries
- * IBM Corporation - added specific output location to source classpath entries
- * IBM Corporation - added the following constants:
- * CORE_JAVA_BUILD_CLEAN_OUTPUT_FOLDER
- * CLEAN
- * IBM Corporation - added getClasspathContainerInitializer(String)
- * IBM Corporation - added the following constants:
- * CODEASSIST_ARGUMENT_PREFIXES
- * CODEASSIST_ARGUMENT_SUFFIXES
- * CODEASSIST_FIELD_PREFIXES
- * CODEASSIST_FIELD_SUFFIXES
- * CODEASSIST_LOCAL_PREFIXES
- * CODEASSIST_LOCAL_SUFFIXES
- * CODEASSIST_STATIC_FIELD_PREFIXES
- * CODEASSIST_STATIC_FIELD_SUFFIXES
- * COMPILER_PB_CHAR_ARRAY_IN_STRING_CONCATENATION
- *******************************************************************************/
-package net.sourceforge.phpdt.core;
-
-import java.util.Collection;
-import java.util.Enumeration;
-import java.util.HashSet;
-import java.util.Hashtable;
-import java.util.Map;
-
-import net.sourceforge.phpdt.internal.core.BatchOperation;
-import net.sourceforge.phpdt.internal.core.BufferManager;
-import net.sourceforge.phpdt.internal.core.JavaModel;
-import net.sourceforge.phpdt.internal.core.JavaModelManager;
-import net.sourceforge.phpdt.internal.core.Region;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IMarkerDelta;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceChangeEvent;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.IWorkspaceRunnable;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IConfigurationElement;
-import org.eclipse.core.runtime.IExecutableExtension;
-import org.eclipse.core.runtime.IPluginDescriptor;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.Plugin;
-import org.eclipse.core.runtime.Preferences;
-
-
-/**
- * The plug-in runtime class for the Java model plug-in containing the core
- * (UI-free) support for Java projects.
- *
- * Like all plug-in runtime classes (subclasses of Plugin
), this
- * class is automatically instantiated by the platform when the plug-in gets
- * activated. Clients must not attempt to instantiate plug-in runtime classes
- * directly.
- *
- * The single instance of this class can be accessed from any plug-in declaring
- * the Java model plug-in as a prerequisite via
- * JavaCore.getJavaCore()
. The Java model plug-in will be activated
- * automatically if not already active.
- *
"org.eclipse.jdt.core"
).
- */
- public static final String PLUGIN_ID = "org.eclipse.jdt.core" ; //$NON-NLS-1$
-
- /**
- * The identifier for the Java builder
- * (value "org.eclipse.jdt.core.javabuilder"
).
- */
- public static final String BUILDER_ID = PLUGIN_ID + ".javabuilder" ; //$NON-NLS-1$
-
- /**
- * The identifier for the Java model
- * (value "org.eclipse.jdt.core.javamodel"
).
- */
- public static final String MODEL_ID = PLUGIN_ID + ".javamodel" ; //$NON-NLS-1$
-
- /**
- * The identifier for the Java nature
- * (value "org.eclipse.jdt.core.javanature"
).
- * The presence of this nature on a project indicates that it is
- * Java-capable.
- *
- * @see org.eclipse.core.resources.IProject#hasNature(java.lang.String)
- */
- public static final String NATURE_ID = PLUGIN_ID + ".javanature" ; //$NON-NLS-1$
-
- /**
- * Name of the handle id attribute in a Java marker.
- */
- protected static final String ATT_HANDLE_ID =
- "org.eclipse.jdt.internal.core.JavaModelManager.handleId" ; //$NON-NLS-1$
-
- // *************** Possible IDs for configurable options. ********************
-
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_LOCAL_VARIABLE_ATTR = PLUGIN_ID + ".compiler.debug.localVariable"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions()
- */
- public static final String COMPILER_LINE_NUMBER_ATTR = PLUGIN_ID + ".compiler.debug.lineNumber"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- */
- public static final String COMPILER_SOURCE_FILE_ATTR = PLUGIN_ID + ".compiler.debug.sourceFile"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- */
- public static final String COMPILER_CODEGEN_UNUSED_LOCAL = PLUGIN_ID + ".compiler.codegen.unusedLocal"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- */
- public static final String COMPILER_CODEGEN_TARGET_PLATFORM = PLUGIN_ID + ".compiler.codegen.targetPlatform"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- */
- public static final String COMPILER_PB_UNREACHABLE_CODE = PLUGIN_ID + ".compiler.problem.unreachableCode"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- */
- public static final String COMPILER_PB_INVALID_IMPORT = PLUGIN_ID + ".compiler.problem.invalidImport"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- */
- public static final String COMPILER_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD = PLUGIN_ID + ".compiler.problem.overridingPackageDefaultMethod"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- */
- public static final String COMPILER_PB_METHOD_WITH_CONSTRUCTOR_NAME = PLUGIN_ID + ".compiler.problem.methodWithConstructorName"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- */
- public static final String COMPILER_PB_DEPRECATION = PLUGIN_ID + ".compiler.problem.deprecation"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- * @since 2.1
- */
- public static final String COMPILER_PB_DEPRECATION_IN_DEPRECATED_CODE = PLUGIN_ID + ".compiler.problem.deprecationInDeprecatedCode"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- */
- public static final String COMPILER_PB_HIDDEN_CATCH_BLOCK = PLUGIN_ID + ".compiler.problem.hiddenCatchBlock"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- */
- public static final String COMPILER_PB_UNUSED_LOCAL = PLUGIN_ID + ".compiler.problem.unusedLocal"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- */
- public static final String COMPILER_PB_UNUSED_PARAMETER = PLUGIN_ID + ".compiler.problem.unusedParameter"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- * @since 2.1
- */
- public static final String COMPILER_PB_UNUSED_PARAMETER_WHEN_IMPLEMENTING_ABSTRACT = PLUGIN_ID + ".compiler.problem.unusedParameterWhenImplementingAbstract"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- * @since 2.1
- */
- public static final String COMPILER_PB_UNUSED_PARAMETER_WHEN_OVERRIDING_CONCRETE = PLUGIN_ID + ".compiler.problem.unusedParameterWhenOverridingConcrete"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- * @since 2.0
- */
- public static final String COMPILER_PB_UNUSED_IMPORT = PLUGIN_ID + ".compiler.problem.unusedImport"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- */
- public static final String COMPILER_PB_SYNTHETIC_ACCESS_EMULATION = PLUGIN_ID + ".compiler.problem.syntheticAccessEmulation"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- * @since 2.0
- */
- public static final String COMPILER_PB_NON_NLS_STRING_LITERAL = PLUGIN_ID + ".compiler.problem.nonExternalizedStringLiteral"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- * @since 2.0
- */
- public static final String COMPILER_PB_ASSERT_IDENTIFIER = PLUGIN_ID + ".compiler.problem.assertIdentifier"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- * @since 2.1
- */
- public static final String COMPILER_PB_STATIC_ACCESS_RECEIVER = PLUGIN_ID + ".compiler.problem.staticAccessReceiver"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- * @since 2.1
- */
- public static final String COMPILER_PB_NO_EFFECT_ASSIGNMENT = PLUGIN_ID + ".compiler.problem.noEffectAssignment"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- * @since 2.1
- */
- public static final String COMPILER_PB_INCOMPATIBLE_NON_INHERITED_INTERFACE_METHOD = PLUGIN_ID + ".compiler.problem.incompatibleNonInheritedInterfaceMethod"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- * @since 2.1
- */
- public static final String COMPILER_PB_UNUSED_PRIVATE_MEMBER = PLUGIN_ID + ".compiler.problem.unusedPrivateMember"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- * @since 2.1
- */
- public static final String COMPILER_PB_CHAR_ARRAY_IN_STRING_CONCATENATION = PLUGIN_ID + ".compiler.problem.noImplicitStringConversion"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- * @since 2.0
- */
- public static final String COMPILER_PB_MAX_PER_UNIT = PLUGIN_ID + ".compiler.maxProblemPerUnit"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- * @since 2.0
- */
- public static final String COMPILER_SOURCE = PLUGIN_ID + ".compiler.source"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- * @since 2.0
- */
- public static final String COMPILER_COMPLIANCE = PLUGIN_ID + ".compiler.compliance"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- * @since 2.1
- */
- public static final String COMPILER_TASK_PRIORITIES = PLUGIN_ID + ".compiler.taskPriorities"; //$NON-NLS-1$
- /**
- * Possible configurable option value for COMPILER_TASK_PRIORITIES.
- * @see #getDefaultOptions
- * @since 2.1
- */
- public static final String COMPILER_TASK_PRIORITY_HIGH = "HIGH"; //$NON-NLS-1$
- /**
- * Possible configurable option value for COMPILER_TASK_PRIORITIES.
- * @see #getDefaultOptions
- * @since 2.1
- */
- public static final String COMPILER_TASK_PRIORITY_LOW = "LOW"; //$NON-NLS-1$
- /**
- * Possible configurable option value for COMPILER_TASK_PRIORITIES.
- * @see #getDefaultOptions
- * @since 2.1
- */
- public static final String COMPILER_TASK_PRIORITY_NORMAL = "NORMAL"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- * @since 2.1
- */
- public static final String COMPILER_TASK_TAGS = PLUGIN_ID + ".compiler.taskTags"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- */
- public static final String CORE_JAVA_BUILD_ORDER = PLUGIN_ID + ".computeJavaBuildOrder"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- * @since 2.0
- */
- public static final String CORE_JAVA_BUILD_RESOURCE_COPY_FILTER = PLUGIN_ID + ".builder.resourceCopyExclusionFilter"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- * @since 2.1
- */
- public static final String CORE_JAVA_BUILD_DUPLICATE_RESOURCE = PLUGIN_ID + ".builder.duplicateResourceTask"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- * @since 2.1
- */
- public static final String CORE_JAVA_BUILD_CLEAN_OUTPUT_FOLDER = PLUGIN_ID + ".builder.cleanOutputFolder"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- * @since 2.1
- */
- public static final String CORE_INCOMPLETE_CLASSPATH = PLUGIN_ID + ".incompleteClasspath"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- * @since 2.1
- */
- public static final String CORE_CIRCULAR_CLASSPATH = PLUGIN_ID + ".circularClasspath"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- * @since 2.0
- */
- public static final String CORE_JAVA_BUILD_INVALID_CLASSPATH = PLUGIN_ID + ".builder.invalidClasspath"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- * @since 2.0
- */
- public static final String CORE_ENCODING = PLUGIN_ID + ".encoding"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- * @since 2.1
- */
- public static final String CORE_ENABLE_CLASSPATH_EXCLUSION_PATTERNS = PLUGIN_ID + ".classpath.exclusionPatterns"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- * @since 2.1
- */
- public static final String CORE_ENABLE_CLASSPATH_MULTIPLE_OUTPUT_LOCATIONS = PLUGIN_ID + ".classpath.multipleOutputLocations"; //$NON-NLS-1$
- /**
- * Default task tag
- * @since 2.1
- */
- public static final String DEFAULT_TASK_TAG = "TODO"; //$NON-NLS-1$
- /**
- * Default task priority
- * @since 2.1
- */
- public static final String DEFAULT_TASK_PRIORITY = "NORMAL"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- * @since 2.0
- */
- public static final String FORMATTER_NEWLINE_OPENING_BRACE = PLUGIN_ID + ".formatter.newline.openingBrace"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- * @since 2.0
- */
- public static final String FORMATTER_NEWLINE_CONTROL = PLUGIN_ID + ".formatter.newline.controlStatement"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- * @since 2.0
- */
- public static final String FORMATTER_NEWLINE_ELSE_IF = PLUGIN_ID + ".formatter.newline.elseIf"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- * @since 2.0
- */
- public static final String FORMATTER_NEWLINE_EMPTY_BLOCK = PLUGIN_ID + ".formatter.newline.emptyBlock"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- * @since 2.0
- */
- public static final String FORMATTER_CLEAR_BLANK_LINES = PLUGIN_ID + ".formatter.newline.clearAll"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- * @since 2.0
- */
- public static final String FORMATTER_LINE_SPLIT = PLUGIN_ID + ".formatter.lineSplit"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- * @since 2.0
- */
- public static final String FORMATTER_COMPACT_ASSIGNMENT = PLUGIN_ID + ".formatter.style.assignment"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- * @since 2.0
- */
- public static final String FORMATTER_TAB_CHAR = PLUGIN_ID + ".formatter.tabulation.char"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- * @since 2.0
- */
- public static final String FORMATTER_TAB_SIZE = PLUGIN_ID + ".formatter.tabulation.size"; //$NON-NLS-1$
- /**
- * Possible configurable option ID
- * @see #getDefaultOptions
- * @since 2.1
- */
- public static final String FORMATTER_SPACE_CASTEXPRESSION = PLUGIN_ID + ".formatter.space.castexpression"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- * @since 2.0
- */
- public static final String CODEASSIST_VISIBILITY_CHECK = PLUGIN_ID + ".codeComplete.visibilityCheck"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- * @since 2.0
- */
- public static final String CODEASSIST_IMPLICIT_QUALIFICATION = PLUGIN_ID + ".codeComplete.forceImplicitQualification"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- * @since 2.1
- */
- public static final String CODEASSIST_FIELD_PREFIXES = PLUGIN_ID + ".codeComplete.fieldPrefixes"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- * @since 2.1
- */
- public static final String CODEASSIST_STATIC_FIELD_PREFIXES = PLUGIN_ID + ".codeComplete.staticFieldPrefixes"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- * @since 2.1
- */
- public static final String CODEASSIST_LOCAL_PREFIXES = PLUGIN_ID + ".codeComplete.localPrefixes"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- * @since 2.1
- */
- public static final String CODEASSIST_ARGUMENT_PREFIXES = PLUGIN_ID + ".codeComplete.argumentPrefixes"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- * @since 2.1
- */
- public static final String CODEASSIST_FIELD_SUFFIXES = PLUGIN_ID + ".codeComplete.fieldSuffixes"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- * @since 2.1
- */
- public static final String CODEASSIST_STATIC_FIELD_SUFFIXES = PLUGIN_ID + ".codeComplete.staticFieldSuffixes"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- * @since 2.1
- */
- public static final String CODEASSIST_LOCAL_SUFFIXES = PLUGIN_ID + ".codeComplete.localSuffixes"; //$NON-NLS-1$
- /**
- * Possible configurable option ID.
- * @see #getDefaultOptions
- * @since 2.1
- */
- public static final String CODEASSIST_ARGUMENT_SUFFIXES = PLUGIN_ID + ".codeComplete.argumentSuffixes"; //$NON-NLS-1$
-
- // *************** Possible values for configurable options. ********************
-
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions
- */
- public static final String GENERATE = "generate"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions
- */
- public static final String DO_NOT_GENERATE = "do not generate"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions
- */
- public static final String PRESERVE = "preserve"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions
- */
- public static final String OPTIMIZE_OUT = "optimize out"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions
- */
- public static final String VERSION_1_1 = "1.1"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions
- */
- public static final String VERSION_1_2 = "1.2"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions
- * @since 2.0
- */
- public static final String VERSION_1_3 = "1.3"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions
- * @since 2.0
- */
- public static final String VERSION_1_4 = "1.4"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions
- * @since 2.0
- */
- public static final String ABORT = "abort"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions
- */
- public static final String ERROR = "error"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions
- */
- public static final String WARNING = "warning"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions
- */
- public static final String IGNORE = "ignore"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions
- */
- public static final String COMPUTE = "compute"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions
- * @since 2.0
- */
- public static final String INSERT = "insert"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions
- * @since 2.0
- */
- public static final String DO_NOT_INSERT = "do not insert"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions
- * @since 2.0
- */
- public static final String PRESERVE_ONE = "preserve one"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions
- * @since 2.0
- */
- public static final String CLEAR_ALL = "clear all"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions
- * @since 2.0
- */
- public static final String NORMAL = "normal"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions
- * @since 2.0
- */
- public static final String COMPACT = "compact"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions
- * @since 2.0
- */
- public static final String TAB = "tab"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions
- * @since 2.0
- */
- public static final String SPACE = "space"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions
- * @since 2.0
- */
- public static final String ENABLED = "enabled"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions
- * @since 2.0
- */
- public static final String DISABLED = "disabled"; //$NON-NLS-1$
- /**
- * Possible configurable option value.
- * @see #getDefaultOptions
- * @since 2.1
- */
- public static final String CLEAN = "clean"; //$NON-NLS-1$
-
- /**
- * Creates the Java core plug-in.
- * @since 2.1
- */
- public JavaCore(IPluginDescriptor pluginDescriptor) {
- super(pluginDescriptor);
- JAVA_CORE_PLUGIN = this;
- }
-
- /**
- * Adds the given listener for changes to Java elements.
- * Has no effect if an identical listener is already registered.
- *
- * This listener will only be notified during the POST_CHANGE resource change notification
- * and any reconcile operation (POST_RECONCILE).
- * For finer control of the notification, use addElementChangedListener(IElementChangedListener,int)
,
- * which allows to specify a different eventMask.
- *
- * @see ElementChangedEvent
- * @param listener the listener
- */
- public static void addElementChangedListener(IElementChangedListener listener) {
- addElementChangedListener(listener, ElementChangedEvent.POST_CHANGE | ElementChangedEvent.POST_RECONCILE);
- }
-
- /**
- * Adds the given listener for changes to Java elements.
- * Has no effect if an identical listener is already registered.
- * After completion of this method, the given listener will be registered for exactly
- * the specified events. If they were previously registered for other events, they
- * will be deregistered.
- * - * Once registered, a listener starts receiving notification of changes to - * java elements in the model. The listener continues to receive - * notifications until it is replaced or removed. - *
- *
- * Listeners can listen for several types of event as defined in ElementChangeEvent
.
- * Clients are free to register for any number of event types however if they register
- * for more than one, it is their responsibility to ensure they correctly handle the
- * case where the same java element change shows up in multiple notifications.
- * Clients are guaranteed to receive only the events for which they are registered.
- *
String
,
- * value type: String
)
- * @param element the Java element for which the marker needs to be configured
- */
- public static void addJavaElementMarkerAttributes(
- Map attributes,
- IJavaElement element) {
-// if (element instanceof IMember)
-// element = ((IMember) element).getClassFile();
- if (attributes != null && element != null)
- attributes.put(ATT_HANDLE_ID, element.getHandleIdentifier());
- }
-
- /**
- * Configures the given marker for the given Java element.
- * Used for markers, which denote a Java element rather than a resource.
- *
- * @param marker the marker to be configured
- * @param element the Java element for which the marker needs to be configured
- * @exception CoreException if the IMarker.setAttribute
on the marker fails
- */
- public void configureJavaElementMarker(IMarker marker, IJavaElement element)
- throws CoreException {
-// if (element instanceof IMember)
-// element = ((IMember) element).getClassFile();
- if (marker != null && element != null)
- marker.setAttribute(ATT_HANDLE_ID, element.getHandleIdentifier());
- }
-
- /**
- * Returns the Java model element corresponding to the given handle identifier
- * generated by IJavaElement.getHandleIdentifier()
, or
- * null
if unable to create the associated element.
- */
- public static IJavaElement create(String handleIdentifier) {
- if (handleIdentifier == null) {
- return null;
- }
- try {
- return JavaModelManager.getJavaModelManager().getHandleFromMemento(handleIdentifier);
- } catch (JavaModelException e) {
- return null;
- }
- }
- /**
- * Returns the Java element corresponding to the given file, or
- * null
if unable to associate the given file
- * with a Java element.
- *
- * The file must be one of:
.java
file - the element returned is the corresponding ICompilationUnit
.class
file - the element returned is the corresponding IClassFile
.jar
file - the element returned is the corresponding IPackageFragmentRoot
- * Creating a Java element has the side effect of creating and opening all of the
- * element's parents if they are not yet open.
- *
- * @param the given file
- * @return the Java element corresponding to the given file, or
- * null
if unable to associate the given file
- * with a Java element
- */
- public static IJavaElement create(IFile file) {
- return JavaModelManager.create(file, null);
- }
- /**
- * Returns the package fragment or package fragment root corresponding to the given folder, or
- * null
if unable to associate the given folder with a Java element.
- *
- * Note that a package fragment root is returned rather than a default package. - *
- * Creating a Java element has the side effect of creating and opening all of the
- * element's parents if they are not yet open.
- *
- * @param the given folder
- * @return the package fragment or package fragment root corresponding to the given folder, or
- * null
if unable to associate the given folder with a Java element
- */
- public static IJavaElement create(IFolder folder) {
- return JavaModelManager.create(folder, null);
- }
- /**
- * Returns the Java project corresponding to the given project.
- *
- * Creating a Java Project has the side effect of creating and opening all of the - * project's parents if they are not yet open. - *
- * Note that no check is done at this time on the existence or the java nature of this project.
- *
- * @param project the given project
- * @return the Java project corresponding to the given project, null if the given project is null
- */
- public static IJavaProject create(IProject project) {
- if (project == null) {
- return null;
- }
- JavaModel javaModel = JavaModelManager.getJavaModelManager().getJavaModel();
- return javaModel.getJavaProject(project);
- }
- /**
- * Returns the Java element corresponding to the given resource, or
- * null
if unable to associate the given resource
- * with a Java element.
- *
- * The resource must be one of:
IJavaProject
.java
file - the element returned is the corresponding ICompilationUnit
.class
file - the element returned is the corresponding IClassFile
.jar
file - the element returned is the corresponding IPackageFragmentRoot
IPackageFragmentRoot
- * or IPackageFragment
IJavaModel
- * Creating a Java element has the side effect of creating and opening all of the
- * element's parents if they are not yet open.
- *
- * @param resource the given resource
- * @return the Java element corresponding to the given resource, or
- * null
if unable to associate the given resource
- * with a Java element
- */
- public static IJavaElement create(IResource resource) {
- return JavaModelManager.create(resource, null);
- }
- /**
- * Returns the Java model.
- *
- * @param root the given root
- * @return the Java model, or null
if the root is null
- */
- public static IJavaModel create(IWorkspaceRoot root) {
- if (root == null) {
- return null;
- }
- return JavaModelManager.getJavaModelManager().getJavaModel();
- }
- /**
- * Creates and returns a class file element for
- * the given .class
file. Returns null
if unable
- * to recognize the class file.
- *
- * @param file the given .class
file
- * @return a class file element for the given .class
file, or null
if unable
- * to recognize the class file
- */
-// public static IClassFile createClassFileFrom(IFile file) {
-// return JavaModelManager.createClassFileFrom(file, null);
-// }
- /**
- * Creates and returns a compilation unit element for
- * the given .java
file. Returns null
if unable
- * to recognize the compilation unit.
- *
- * @param file the given .java
file
- * @return a compilation unit element for the given .java
file, or null
if unable
- * to recognize the compilation unit
- */
- public static ICompilationUnit createCompilationUnitFrom(IFile file) {
- return JavaModelManager.createCompilationUnitFrom(file, null);
- }
- /**
- * Creates and returns a handle for the given JAR file.
- * The Java model associated with the JAR's project may be
- * created as a side effect.
- *
- * @param file the given JAR file
- * @return a handle for the given JAR file, or null
if unable to create a JAR package fragment root.
- * (for example, if the JAR file represents a non-Java resource)
- */
-// public static IPackageFragmentRoot createJarPackageFragmentRootFrom(IFile file) {
-// return JavaModelManager.createJarPackageFragmentRootFrom(file, null);
-// }
-
- /**
- * Answers the project specific value for a given classpath container.
- * In case this container path could not be resolved, then will answer null
.
- * Both the container path and the project context are supposed to be non-null.
- *
- * The containerPath is a formed by a first ID segment followed with extra segments, which can be
- * used as additional hints for resolution. If no container was ever recorded for this container path
- * onto this project (using setClasspathContainer
, then a
- * ClasspathContainerInitializer
will be activated if any was registered for this container
- * ID onto the extension point "org.eclipse.jdt.core.classpathContainerInitializer".
- *
- * There is no assumption that the returned container must answer the exact same containerPath
- * when requested IClasspathContainer#getPath
.
- * Indeed, the containerPath is just an indication for resolving it to an actual container object.
- *
- * Classpath container values are persisted locally to the workspace, but
- * are not preserved from a session to another. It is thus highly recommended to register a
- * ClasspathContainerInitializer
for each referenced container
- * (through the extension point "org.eclipse.jdt.core.ClasspathContainerInitializer").
- *
- * @param containerPath the name of the container, which needs to be resolved
- * @param project a specific project in which the container is being resolved
- * @return the corresponding classpath container or null
if unable to find one.
- *
- * @exception JavaModelException if an exception occurred while resolving the container, or if the resolved container
- * contains illegal entries (contains CPE_CONTAINER entries or null entries).
- *
- * @see ClasspathContainerInitializer
- * @see IClasspathContainer
- * @see #setClasspathContainer(IPath, IJavaProject[], IClasspathContainer[], IProgressMonitor)
- * @since 2.0
- */
-// public static IClasspathContainer getClasspathContainer(final IPath containerPath, final IJavaProject project) throws JavaModelException {
-//
-// IClasspathContainer container = JavaModelManager.containerGet(project, containerPath);
-// if (container == JavaModelManager.ContainerInitializationInProgress) return null; // break cycle
-//
-// if (container == null){
-// final ClasspathContainerInitializer initializer = JavaCore.getClasspathContainerInitializer(containerPath.segment(0));
-// if (initializer != null){
-// if (JavaModelManager.CP_RESOLVE_VERBOSE){
-// System.out.println("CPContainer INIT - triggering initialization of: ["+project.getElementName()+"] " + containerPath + " using initializer: "+ initializer); //$NON-NLS-1$ //$NON-NLS-2$//$NON-NLS-3$
-// new Exception("FAKE exception for dumping current CPContainer (["+project.getElementName()+"] "+ containerPath+ ")INIT invocation stack trace").printStackTrace(); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
-// }
-// JavaModelManager.containerPut(project, containerPath, JavaModelManager.ContainerInitializationInProgress); // avoid initialization cycles
-// boolean ok = false;
-// try {
-// // wrap initializer call with Safe runnable in case initializer would be causing some grief
-// Platform.run(new ISafeRunnable() {
-// public void handleException(Throwable exception) {
-// Util.log(exception, "Exception occurred in classpath container initializer: "+initializer); //$NON-NLS-1$
-// }
-// public void run() throws Exception {
-// initializer.initialize(containerPath, project);
-// }
-// });
-//
-// // retrieve value (if initialization was successful)
-// container = JavaModelManager.containerGet(project, containerPath);
-// if (container == JavaModelManager.ContainerInitializationInProgress) return null; // break cycle
-// ok = true;
-// } finally {
-// if (!ok) JavaModelManager.containerPut(project, containerPath, null); // flush cache
-// }
-// if (JavaModelManager.CP_RESOLVE_VERBOSE){
-// System.out.print("CPContainer INIT - after resolution: ["+project.getElementName()+"] " + containerPath + " --> "); //$NON-NLS-2$//$NON-NLS-1$//$NON-NLS-3$
-// if (container != null){
-// System.out.print("container: "+container.getDescription()+" {"); //$NON-NLS-2$//$NON-NLS-1$
-// IClasspathEntry[] entries = container.getClasspathEntries();
-// if (entries != null){
-// for (int i = 0; i < entries.length; i++){
-// if (i > 0) System.out.println(", ");//$NON-NLS-1$
-// System.out.println(entries[i]);
-// }
-// }
-// System.out.println("}");//$NON-NLS-1$
-// } else {
-// System.out.println("{unbound}");//$NON-NLS-1$
-// }
-// }
-// } else {
-// if (JavaModelManager.CP_RESOLVE_VERBOSE){
-// System.out.println("CPContainer INIT - no initializer found for: "+project.getElementName()+"] " + containerPath); //$NON-NLS-1$ //$NON-NLS-2$
-// }
-// }
-// }
-// return container;
-// }
-
- /**
- * Helper method finding the classpath container initializer registered for a given classpath container ID
- * or null
if none was found while iterating over the contributions to extension point to
- * the extension point "org.eclipse.jdt.core.classpathContainerInitializer".
- *
- * A containerID is the first segment of any container path, used to identify the registered container initializer. - *
- * @param String - a containerID identifying a registered initializer
- * @return ClasspathContainerInitializer - the registered classpath container initializer or
- * Classpath variable values are persisted locally to the workspace, and
- * are preserved from session to session.
- *
- * Note that classpath variables can be contributed registered initializers for,
- * using the extension point "org.eclipse.jdt.core.classpathVariableInitializer".
- * If an initializer is registered for a variable, its persisted value will be ignored:
- * its initializer will thus get the opportunity to rebind the variable differently on
- * each session.
- *
- * @param variableName the name of the classpath variable
- * @return the path, or
- * @param the given variable
- * @return ClasspathVariableInitializer - the registered classpath variable initializer or
- * Classpath variable values are persisted locally to the workspace, and
- * are preserved from session to session.
- *
- *
- * @return the list of classpath variable names
- * @see #setClasspathVariable
- */
-// public static String[] getClasspathVariableNames() {
-// return JavaModelManager.variableNames();
-// }
-
- /**
- * Returns a table of all known configurable options with their default values.
- * These options allow to configure the behaviour of the underlying components.
- * The client may safely use the result as a template that they can modify and
- * then pass to
- * For a complete description of the configurable options, see
- * For a complete description of the configurable options, see
- * Variable source attachment path and root path are also resolved and recorded in the resulting classpath entry.
- *
- * NOTE: This helper method does not handle classpath containers, for which should rather be used
- *
- *
- * @param entry the given variable entry
- * @return the resolved library or project classpath entry, or
- * A container entry allows to express indirect references to a set of libraries, projects and variable entries,
- * which can be interpreted differently for each Java project where it is used.
- * A classpath container entry can be resolved using
- * A container is exclusively resolved by a
- * A container path must be formed of at least one segment, where:
- * Example of an ClasspathContainerInitializer for a classpath container denoting a default JDK container:
- *
- * containerEntry = JavaCore.newContainerEntry(new Path("MyProvidedJDK/default"));
- *
- *
- * Note that this operation does not attempt to validate classpath containers
- * or access the resources at the given paths.
- *
- * The resulting entry is not exported to dependent projects. This method is equivalent to
- *
- * @param containerPath the path identifying the container, it must be formed of two
- * segments
- * @return a new container classpath entry
- *
- * @see JavaCore#getClasspathContainer(IPath, IJavaProject)
- * @see JavaCore#newContainerEntry(IPath, boolean)
- * @since 2.0
- */
-// public static IClasspathEntry newContainerEntry(IPath containerPath) {
-//
-// return newContainerEntry(containerPath, false);
-// }
-
- /**
- * Creates and returns a new classpath entry of kind
- * A container entry allows to express indirect references to a set of libraries, projects and variable entries,
- * which can be interpreted differently for each Java project where it is used.
- * A classpath container entry can be resolved using
- * A container is exclusively resolved by a
- * A container path must be formed of at least one segment, where:
- * Example of an ClasspathContainerInitializer for a classpath container denoting a default JDK container:
- *
- * containerEntry = JavaCore.newContainerEntry(new Path("MyProvidedJDK/default"));
- *
- *
- * Note that this operation does not attempt to validate classpath containers
- * or access the resources at the given paths.
- *
- * @param containerPath the path identifying the container, it must be formed of at least
- * one segment (ID+hints)
- * @param isExported a boolean indicating whether this entry is contributed to dependent
- * projects in addition to the output location
- * @return a new container classpath entry
- *
- * @see JavaCore#getClasspathContainer(IPath, IJavaProject)
- * @see JavaCore#setClasspathContainer(IPath, IJavaProject[], IClasspathContainer[], IProgressMonitor)
- * @see JavaCore#newContainerEntry(IPath, boolean)
- * @since 2.0
- */
-// public static IClasspathEntry newContainerEntry(IPath containerPath, boolean isExported) {
-//
-// if (containerPath == null || containerPath.segmentCount() < 1) {
-// Assert.isTrue(
-// false,
-// "Illegal classpath container path: \'" + containerPath.makeRelative().toString() + "\', must have at least one segment (containerID+hints)"); //$NON-NLS-1$//$NON-NLS-2$
-// }
-// return new ClasspathEntry(
-// IPackageFragmentRoot.K_SOURCE,
-// IClasspathEntry.CPE_CONTAINER,
-// containerPath,
-// ClasspathEntry.NO_EXCLUSION_PATTERNS,
-// null, // source attachment
-// null, // source attachment root
-// null, // specific output folder
-// isExported);
-// }
-
- /**
- * Creates and returns a new non-exported classpath entry of kind
- * A library entry is used to denote a prerequisite JAR or root folder containing binaries.
- * The target JAR or folder can either be defined internally to the workspace (absolute path relative
- * to the workspace root) or externally to the workspace (absolute path in the file system).
- *
- * e.g. Here are some examples of binary path usage
- * The resulting entry is not exported to dependent projects. This method is equivalent to
- *
- *
- * @param path the absolute path of the binary archive
- * @param sourceAttachmentPath the absolute path of the corresponding source archive or folder,
- * or
- * A library entry is used to denote a prerequisite JAR or root folder containing binaries.
- * The target JAR or folder can either be defined internally to the workspace (absolute path relative
- * to the workspace root) or externally to the workspace (absolute path in the file system).
- *
- * e.g. Here are some examples of binary path usage
- *
- * @param path the absolute path of the binary archive
- * @param sourceAttachmentPath the absolute path of the corresponding source archive or folder,
- * or
- * A project entry is used to denote a prerequisite project on a classpath.
- * The referenced project will be contributed as a whole, either as sources (in the Java Model, it
- * contributes all its package fragment roots) or as binaries (when building, it contributes its
- * whole output location).
- *
- * A project reference allows to indirect through another project, independently from its internal layout.
- *
- * The prerequisite project is referred to using an absolute path relative to the workspace root.
- *
- * The resulting entry is not exported to dependent projects. This method is equivalent to
- *
- *
- * @param path the absolute path of the binary archive
- * @return a new project classpath entry
- *
- * @see JavaCore#newProjectEntry(IPath, boolean)
- */
-// public static IClasspathEntry newProjectEntry(IPath path) {
-// return newProjectEntry(path, false);
-// }
-
- /**
- * Creates and returns a new classpath entry of kind
- * A project entry is used to denote a prerequisite project on a classpath.
- * The referenced project will be contributed as a whole, either as sources (in the Java Model, it
- * contributes all its package fragment roots) or as binaries (when building, it contributes its
- * whole output location).
- *
- * A project reference allows to indirect through another project, independently from its internal layout.
- *
- * The prerequisite project is referred to using an absolute path relative to the workspace root.
- *
- *
- * @param path the absolute path of the prerequisite project
- * @param isExported indicates whether this entry is contributed to dependent
- * projects in addition to the output location
- * @return a new project classpath entry
- * @since 2.0
- */
-// public static IClasspathEntry newProjectEntry(IPath path, boolean isExported) {
-//
-// if (!path.isAbsolute()) Assert.isTrue(false, "Path for IClasspathEntry must be absolute"); //$NON-NLS-1$
-//
-// return new ClasspathEntry(
-// IPackageFragmentRoot.K_SOURCE,
-// IClasspathEntry.CPE_PROJECT,
-// path,
-// ClasspathEntry.NO_EXCLUSION_PATTERNS,
-// null, // source attachment
-// null, // source attachment root
-// null, // specific output folder
-// isExported);
-// }
-
- /**
- * Returns a new empty region.
- *
- * @return a new empty region
- */
- public static IRegion newRegion() {
- return new Region();
- }
-
- /**
- * Creates and returns a new classpath entry of kind
- * The source folder is referred to using an absolute path relative to the
- * workspace root, e.g.
- * The source classpath entry created by this method includes all source
- * files below the given workspace-relative path. To selectively exclude
- * some of these source files, use the factory method
- *
- * Note that all sources/binaries inside a project are contributed as a whole through
- * a project entry (see
- * The source folder is referred to using an absolute path relative to the
- * workspace root, e.g.
- * The source classpath entry created by this method includes all source
- * files below the given workspace-relative path except for those matched
- * by one (or more) of the given exclusion patterns. Each exclusion pattern
- * is represented by a relative path, which is interpreted as relative to
- * the source folder. For example, if the source folder path is
- *
- * Note that all sources/binaries inside a project are contributed as a whole through
- * a project entry (see
- * The source folder is referred to using an absolute path relative to the
- * workspace root, e.g.
- * The source classpath entry created by this method includes all source
- * files below the given workspace-relative path except for those matched
- * by one (or more) of the given exclusion patterns. Each exclusion pattern
- * is represented by a relative path, which is interpreted as relative to
- * the source folder. For example, if the source folder path is
- *
- * Additionally, a source entry can be associated with a specific output location.
- * By doing so, the Java builder will ensure that the generated ".class" files will
- * be issued inside this output location, as opposed to be generated into the
- * project default output location (when output location is
- * Also note that all sources/binaries inside a project are contributed as a whole through
- * a project entry (see
- * A variable entry allows to express indirect references on a classpath to other projects or libraries,
- * depending on what the classpath variable is referring.
- *
- * It is possible to register an automatic initializer (null
if
- * none was found.
- * @since 2.1
- */
-// public static ClasspathContainerInitializer getClasspathContainerInitializer(String containerID){
-//
-// Plugin jdtCorePlugin = JavaCore.getPlugin();
-// if (jdtCorePlugin == null) return null;
-//
-// IExtensionPoint extension = jdtCorePlugin.getDescriptor().getExtensionPoint(JavaModelManager.CPCONTAINER_INITIALIZER_EXTPOINT_ID);
-// if (extension != null) {
-// IExtension[] extensions = extension.getExtensions();
-// for(int i = 0; i < extensions.length; i++){
-// IConfigurationElement [] configElements = extensions[i].getConfigurationElements();
-// for(int j = 0; j < configElements.length; j++){
-// String initializerID = configElements[j].getAttribute("id"); //$NON-NLS-1$
-// if (initializerID != null && initializerID.equals(containerID)){
-// if (JavaModelManager.CP_RESOLVE_VERBOSE) {
-// System.out.println("CPContainer INIT - found initializer: "+containerID +" --> " + configElements[j].getAttribute("class"));//$NON-NLS-3$//$NON-NLS-2$//$NON-NLS-1$
-// }
-// try {
-// Object execExt = configElements[j].createExecutableExtension("class"); //$NON-NLS-1$
-// if (execExt instanceof ClasspathContainerInitializer){
-// return (ClasspathContainerInitializer)execExt;
-// }
-// } catch(CoreException e) {
-// }
-// }
-// }
-// }
-// }
-// return null;
-// }
-
- /**
- * Returns the path held in the given classpath variable.
- * Returns null
if none
- * @see #setClasspathVariable
- */
-// public static IPath getClasspathVariable(final String variableName) {
-//
-// IPath variablePath = JavaModelManager.variableGet(variableName);
-// if (variablePath == JavaModelManager.VariableInitializationInProgress) return null; // break cycle
-//
-// if (variablePath != null) {
-// return variablePath;
-// }
-//
-// // even if persisted value exists, initializer is given priority, only if no initializer is found the persisted value is reused
-// final ClasspathVariableInitializer initializer = JavaCore.getClasspathVariableInitializer(variableName);
-// if (initializer != null){
-// if (JavaModelManager.CP_RESOLVE_VERBOSE){
-// System.out.println("CPVariable INIT - triggering initialization of: " + variableName+ " using initializer: "+ initializer); //$NON-NLS-1$ //$NON-NLS-2$
-// new Exception("FAKE exception for dumping current CPVariable ("+variableName+ ")INIT invocation stack trace").printStackTrace(); //$NON-NLS-1$//$NON-NLS-2$
-// }
-// JavaModelManager.variablePut(variableName, JavaModelManager.VariableInitializationInProgress); // avoid initialization cycles
-// boolean ok = false;
-// try {
-// // wrap initializer call with Safe runnable in case initializer would be causing some grief
-// Platform.run(new ISafeRunnable() {
-// public void handleException(Throwable exception) {
-// Util.log(exception, "Exception occurred in classpath variable initializer: "+initializer+" while initializing variable: "+variableName); //$NON-NLS-1$ //$NON-NLS-2$
-// }
-// public void run() throws Exception {
-// initializer.initialize(variableName);
-// }
-// });
-// variablePath = (IPath) JavaModelManager.variableGet(variableName); // initializer should have performed side-effect
-// if (variablePath == JavaModelManager.VariableInitializationInProgress) return null; // break cycle (initializer did not init or reentering call)
-// if (JavaModelManager.CP_RESOLVE_VERBOSE){
-// System.out.println("CPVariable INIT - after initialization: " + variableName + " --> " + variablePath); //$NON-NLS-2$//$NON-NLS-1$
-// }
-// ok = true;
-// } finally {
-// if (!ok) JavaModelManager.variablePut(variableName, null); // flush cache
-// }
-// } else {
-// if (JavaModelManager.CP_RESOLVE_VERBOSE){
-// System.out.println("CPVariable INIT - no initializer found for: " + variableName); //$NON-NLS-1$
-// }
-// }
-// return variablePath;
-// }
-
- /**
- * Helper method finding the classpath variable initializer registered for a given classpath variable name
- * or null
if none was found while iterating over the contributions to extension point to
- * the extension point "org.eclipse.jdt.core.classpathVariableInitializer".
- * null
if
- * none was found.
- * @since 2.1
- */
-// public static ClasspathVariableInitializer getClasspathVariableInitializer(String variable){
-//
-// Plugin jdtCorePlugin = JavaCore.getPlugin();
-// if (jdtCorePlugin == null) return null;
-//
-// IExtensionPoint extension = jdtCorePlugin.getDescriptor().getExtensionPoint(JavaModelManager.CPVARIABLE_INITIALIZER_EXTPOINT_ID);
-// if (extension != null) {
-// IExtension[] extensions = extension.getExtensions();
-// for(int i = 0; i < extensions.length; i++){
-// IConfigurationElement [] configElements = extensions[i].getConfigurationElements();
-// for(int j = 0; j < configElements.length; j++){
-// try {
-// String varAttribute = configElements[j].getAttribute("variable"); //$NON-NLS-1$
-// if (variable.equals(varAttribute)) {
-// if (JavaModelManager.CP_RESOLVE_VERBOSE) {
-// System.out.println("CPVariable INIT - found initializer: "+variable+" --> " + configElements[j].getAttribute("class"));//$NON-NLS-3$//$NON-NLS-2$//$NON-NLS-1$
-// }
-// Object execExt = configElements[j].createExecutableExtension("class"); //$NON-NLS-1$
-// if (execExt instanceof ClasspathVariableInitializer){
-// return (ClasspathVariableInitializer)execExt;
-// }
-// }
-// } catch(CoreException e){
-// }
-// }
-// }
-// }
-// return null;
-// }
-
- /**
- * Returns the names of all known classpath variables.
- * setOptions
.
- *
- * Helper constants have been defined on JavaCore for each of the option ID and
- * their possible constant values.
- *
- * Note: more options might be added in further releases.
- *
- * RECOGNIZED OPTIONS:
- * COMPILER / Generating Local Variable Debug Attribute
- * When generated, this attribute will enable local variable names
- * to be displayed in debugger, only in place where variables are
- * definitely assigned (.class file is then bigger)
- * - option id: "org.eclipse.jdt.core.compiler.debug.localVariable"
- * - possible values: { "generate", "do not generate" }
- * - default: "generate"
- *
- * COMPILER / Generating Line Number Debug Attribute
- * When generated, this attribute will enable source code highlighting in debugger
- * (.class file is then bigger).
- * - option id: "org.eclipse.jdt.core.compiler.debug.lineNumber"
- * - possible values: { "generate", "do not generate" }
- * - default: "generate"
- *
- * COMPILER / Generating Source Debug Attribute
- * When generated, this attribute will enable the debugger to present the
- * corresponding source code.
- * - option id: "org.eclipse.jdt.core.compiler.debug.sourceFile"
- * - possible values: { "generate", "do not generate" }
- * - default: "generate"
- *
- * COMPILER / Preserving Unused Local Variables
- * Unless requested to preserve unused local variables (that is, never read), the
- * compiler will optimize them out, potentially altering debugging
- * - option id: "org.eclipse.jdt.core.compiler.codegen.unusedLocal"
- * - possible values: { "preserve", "optimize out" }
- * - default: "preserve"
- *
- * COMPILER / Defining Target Java Platform
- * For binary compatibility reason, .class files can be tagged to with certain VM versions and later.
- * Note that "1.4" target require to toggle compliance mode to "1.4" too.
- * - option id: "org.eclipse.jdt.core.compiler.codegen.targetPlatform"
- * - possible values: { "1.1", "1.2", "1.3", "1.4" }
- * - default: "1.1"
- *
- * COMPILER / Reporting Unreachable Code
- * Unreachable code can optionally be reported as an error, warning or simply
- * ignored. The bytecode generation will always optimized it out.
- * - option id: "org.eclipse.jdt.core.compiler.problem.unreachableCode"
- * - possible values: { "error", "warning", "ignore" }
- * - default: "error"
- *
- * COMPILER / Reporting Invalid Import
- * An import statement that cannot be resolved might optionally be reported
- * as an error, as a warning or ignored.
- * - option id: "org.eclipse.jdt.core.compiler.problem.invalidImport"
- * - possible values: { "error", "warning", "ignore" }
- * - default: "error"
- *
- * COMPILER / Reporting Attempt to Override Package-Default Method
- * A package default method is not visible in a different package, and thus
- * cannot be overridden. When enabling this option, the compiler will signal
- * such scenarii either as an error or a warning.
- * - option id: "org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod"
- * - possible values: { "error", "warning", "ignore" }
- * - default: "warning"
- *
- * COMPILER / Reporting Method With Constructor Name
- * Naming a method with a constructor name is generally considered poor
- * style programming. When enabling this option, the compiler will signal such
- * scenarii either as an error or a warning.
- * - option id: "org.eclipse.jdt.core.compiler.problem.methodWithConstructorName"
- * - possible values: { "error", "warning", "ignore" }
- * - default: "warning"
- *
- * COMPILER / Reporting Deprecation
- * When enabled, the compiler will signal use of deprecated API either as an
- * error or a warning.
- * - option id: "org.eclipse.jdt.core.compiler.problem.deprecation"
- * - possible values: { "error", "warning", "ignore" }
- * - default: "warning"
- *
- * COMPILER / Reporting Deprecation Inside Deprecated Code
- * When enabled, the compiler will signal use of deprecated API inside deprecated code.
- * The severity of the problem is controlled with option "org.eclipse.jdt.core.compiler.problem.deprecation".
- * - option id: "org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode"
- * - possible values: { "enabled", "disabled" }
- * - default: "disabled"
- *
- * COMPILER / Reporting Hidden Catch Block
- * Locally to a try statement, some catch blocks may hide others . For example,
- * try { throw new java.io.CharConversionException();
- * } catch (java.io.CharConversionException e) {
- * } catch (java.io.IOException e) {}.
- * When enabling this option, the compiler will issue an error or a warning for hidden
- * catch blocks corresponding to checked exceptions
- * - option id: "org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock"
- * - possible values: { "error", "warning", "ignore" }
- * - default: "warning"
- *
- * COMPILER / Reporting Unused Local
- * When enabled, the compiler will issue an error or a warning for unused local
- * variables (that is, variables never read from)
- * - option id: "org.eclipse.jdt.core.compiler.problem.unusedLocal"
- * - possible values: { "error", "warning", "ignore" }
- * - default: "ignore"
- *
- * COMPILER / Reporting Unused Parameter
- * When enabled, the compiler will issue an error or a warning for unused method
- * parameters (that is, parameters never read from)
- * - option id: "org.eclipse.jdt.core.compiler.problem.unusedParameter"
- * - possible values: { "error", "warning", "ignore" }
- * - default: "ignore"
- *
- * COMPILER / Reporting Unused Parameter if Implementing Abstract Method
- * When enabled, the compiler will signal unused parameters in abstract method implementations.
- * The severity of the problem is controlled with option "org.eclipse.jdt.core.compiler.problem.unusedParameter".
- * - option id: "org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract"
- * - possible values: { "enabled", "disabled" }
- * - default: "disabled"
- *
- * COMPILER / Reporting Unused Parameter if Overriding Concrete Method
- * When enabled, the compiler will signal unused parameters in methods overriding concrete ones.
- * The severity of the problem is controlled with option "org.eclipse.jdt.core.compiler.problem.unusedParameter".
- * - option id: "org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete"
- * - possible values: { "enabled", "disabled" }
- * - default: "disabled"
- *
- * COMPILER / Reporting Unused Import
- * When enabled, the compiler will issue an error or a warning for unused import
- * reference
- * - option id: "org.eclipse.jdt.core.compiler.problem.unusedImport"
- * - possible values: { "error", "warning", "ignore" }
- * - default: "warning"
- *
- * COMPILER / Reporting Unused Private Members
- * When enabled, the compiler will issue an error or a warning whenever a private
- * method or field is declared but never used within the same unit.
- * - option id: "org.eclipse.jdt.core.compiler.problem.unusedPrivateMember"
- * - possible values: { "error", "warning", "ignore" }
- * - default: "ignore"
- *
- * COMPILER / Reporting Synthetic Access Emulation
- * When enabled, the compiler will issue an error or a warning whenever it emulates
- * access to a non-accessible member of an enclosing type. Such access can have
- * performance implications.
- * - option id: "org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation"
- * - possible values: { "error", "warning", "ignore" }
- * - default: "ignore"
- *
- * COMPILER / Reporting Non-Externalized String Literal
- * When enabled, the compiler will issue an error or a warning for non externalized
- * String literal (that is, not tagged with //$NON-NLS-
- *
- * @return a mutable table containing the default settings of all known options
- * (key type: String
; value type: String
)
- * @see #setOptions
- */
- public static Hashtable getDefaultOptions(){
-
- Hashtable defaultOptions = new Hashtable(10);
-
- // see #initializeDefaultPluginPreferences() for changing default settings
- Preferences preferences = getPlugin().getPluginPreferences();
- HashSet optionNames = JavaModelManager.OptionNames;
-
- // get preferences set to their default
- String[] defaultPropertyNames = preferences.defaultPropertyNames();
- for (int i = 0; i < defaultPropertyNames.length; i++){
- String propertyName = defaultPropertyNames[i];
- if (optionNames.contains(propertyName)) {
- defaultOptions.put(propertyName, preferences.getDefaultString(propertyName));
- }
- }
- // get preferences not set to their default
- String[] propertyNames = preferences.propertyNames();
- for (int i = 0; i < propertyNames.length; i++){
- String propertyName = propertyNames[i];
- if (optionNames.contains(propertyName)) {
- defaultOptions.put(propertyName, preferences.getDefaultString(propertyName));
- }
- }
- // get encoding through resource plugin
- defaultOptions.put(CORE_ENCODING, ResourcesPlugin.getEncoding());
-
- return defaultOptions;
- }
-
- /**
- * Returns the single instance of the Java core plug-in runtime class.
- * Equivalent to (JavaCore) getPlugin()
.
- *
- * @return the single instance of the Java core plug-in runtime class
- */
- public static JavaCore getJavaCore() {
- return (JavaCore) getPlugin();
- }
-
- /**
- * Helper method for returning one option value only. Equivalent to (String)JavaCore.getOptions().get(optionName)
- * Note that it may answer null
if this option does not exist.
- * getDefaultOptions
.
- * getDefaultOptions
.
- * String
; value type: String
)
- * @see JavaCore#getDefaultOptions
- */
- public static Hashtable getOptions() {
-
- Hashtable options = new Hashtable(10);
-
- // see #initializeDefaultPluginPreferences() for changing default settings
- Plugin plugin = getPlugin();
- if (plugin != null) {
- Preferences preferences = getPlugin().getPluginPreferences();
- HashSet optionNames = JavaModelManager.OptionNames;
-
- // get preferences set to their default
- String[] defaultPropertyNames = preferences.defaultPropertyNames();
- for (int i = 0; i < defaultPropertyNames.length; i++){
- String propertyName = defaultPropertyNames[i];
- if (optionNames.contains(propertyName)){
- options.put(propertyName, preferences.getDefaultString(propertyName));
- }
- }
- // get preferences not set to their default
- String[] propertyNames = preferences.propertyNames();
- for (int i = 0; i < propertyNames.length; i++){
- String propertyName = propertyNames[i];
- if (optionNames.contains(propertyName)){
- options.put(propertyName, preferences.getString(propertyName).trim());
- }
- }
- // get encoding through resource plugin
- options.put(CORE_ENCODING, ResourcesPlugin.getEncoding());
- }
- return options;
- }
-
- /**
- * Returns the single instance of the Java core plug-in runtime class.
- *
- * @return the single instance of the Java core plug-in runtime class
- */
- public static Plugin getPlugin() {
- return JAVA_CORE_PLUGIN;
- }
-
- /**
- * This is a helper method, which returns the resolved classpath entry denoted
- * by a given entry (if it is a variable entry). It is obtained by resolving the variable
- * reference in the first segment. Returns
- *
- * null
null
JavaCore#getClasspathContainer(IPath, IJavaProject)
.
- * null
- * if the given variable entry could not be resolved to a valid classpath entry
- */
-// public static IClasspathEntry getResolvedClasspathEntry(IClasspathEntry entry) {
-//
-// if (entry.getEntryKind() != IClasspathEntry.CPE_VARIABLE)
-// return entry;
-//
-// IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
-// IPath resolvedPath = JavaCore.getResolvedVariablePath(entry.getPath());
-// if (resolvedPath == null)
-// return null;
-//
-// Object target = JavaModel.getTarget(workspaceRoot, resolvedPath, false);
-// if (target == null)
-// return null;
-//
-// // inside the workspace
-// if (target instanceof IResource) {
-// IResource resolvedResource = (IResource) target;
-// if (resolvedResource != null) {
-// switch (resolvedResource.getType()) {
-//
-// case IResource.PROJECT :
-// // internal project
-// return JavaCore.newProjectEntry(resolvedPath, entry.isExported());
-//
-// case IResource.FILE :
-// if (Util.isArchiveFileName(resolvedResource.getName())) {
-// // internal binary archive
-// return JavaCore.newLibraryEntry(
-// resolvedPath,
-// getResolvedVariablePath(entry.getSourceAttachmentPath()),
-// getResolvedVariablePath(entry.getSourceAttachmentRootPath()),
-// entry.isExported());
-// }
-// break;
-//
-// case IResource.FOLDER :
-// // internal binary folder
-// return JavaCore.newLibraryEntry(
-// resolvedPath,
-// getResolvedVariablePath(entry.getSourceAttachmentPath()),
-// getResolvedVariablePath(entry.getSourceAttachmentRootPath()),
-// entry.isExported());
-// }
-// }
-// }
-// // outside the workspace
-// if (target instanceof File) {
-// File externalFile = (File) target;
-// if (externalFile.isFile()) {
-// String fileName = externalFile.getName().toLowerCase();
-// if (fileName.endsWith(".jar" //$NON-NLS-1$
-// ) || fileName.endsWith(".zip" //$NON-NLS-1$
-// )) { // external binary archive
-// return JavaCore.newLibraryEntry(
-// resolvedPath,
-// getResolvedVariablePath(entry.getSourceAttachmentPath()),
-// getResolvedVariablePath(entry.getSourceAttachmentRootPath()),
-// entry.isExported());
-// }
-// } else { // external binary folder
-// if (resolvedPath.isAbsolute()){
-// return JavaCore.newLibraryEntry(
-// resolvedPath,
-// getResolvedVariablePath(entry.getSourceAttachmentPath()),
-// getResolvedVariablePath(entry.getSourceAttachmentRootPath()),
-// entry.isExported());
-// }
-// }
-// }
-// return null;
-// }
-
-
- /**
- * Resolve a variable path (helper method).
- *
- * @param variablePath the given variable path
- * @return the resolved variable path or null
if none
- */
-// public static IPath getResolvedVariablePath(IPath variablePath) {
-//
-// if (variablePath == null)
-// return null;
-// int count = variablePath.segmentCount();
-// if (count == 0)
-// return null;
-//
-// // lookup variable
-// String variableName = variablePath.segment(0);
-// IPath resolvedPath = JavaCore.getClasspathVariable(variableName);
-// if (resolvedPath == null)
-// return null;
-//
-// // append path suffix
-// if (count > 1) {
-// resolvedPath = resolvedPath.append(variablePath.removeFirstSegments(1));
-// }
-// return resolvedPath;
-// }
-
- /**
- * Answers the shared working copies currently registered for this buffer factory.
- * Working copies can be shared by several clients using the same buffer factory,see
- * IWorkingCopy.getSharedWorkingCopy
.
- *
- * @param factory the given buffer factory
- * @return the list of shared working copies for a given buffer factory
- * @see IWorkingCopy
- * @since 2.0
- */
- public static IWorkingCopy[] getSharedWorkingCopies(IBufferFactory factory){
-
- // if factory is null, default factory must be used
- if (factory == null) factory = BufferManager.getDefaultBufferManager().getDefaultBufferFactory();
- Map sharedWorkingCopies = JavaModelManager.getJavaModelManager().sharedWorkingCopies;
-
- Map perFactoryWorkingCopies = (Map) sharedWorkingCopies.get(factory);
- if (perFactoryWorkingCopies == null) return JavaModelManager.NoWorkingCopy;
- Collection copies = perFactoryWorkingCopies.values();
- IWorkingCopy[] result = new IWorkingCopy[copies.size()];
- copies.toArray(result);
- return result;
- }
-
- /**
- * Initializes the default preferences settings for this plug-in.
- */
- protected void initializeDefaultPluginPreferences() {
-
- Preferences preferences = getPluginPreferences();
- HashSet optionNames = JavaModelManager.OptionNames;
-
- // Compiler settings
- preferences.setDefault(COMPILER_LOCAL_VARIABLE_ATTR, GENERATE);
- optionNames.add(COMPILER_LOCAL_VARIABLE_ATTR);
-
- preferences.setDefault(COMPILER_LINE_NUMBER_ATTR, GENERATE);
- optionNames.add(COMPILER_LINE_NUMBER_ATTR);
-
- preferences.setDefault(COMPILER_SOURCE_FILE_ATTR, GENERATE);
- optionNames.add(COMPILER_SOURCE_FILE_ATTR);
-
- preferences.setDefault(COMPILER_CODEGEN_UNUSED_LOCAL, PRESERVE);
- optionNames.add(COMPILER_CODEGEN_UNUSED_LOCAL);
-
- preferences.setDefault(COMPILER_CODEGEN_TARGET_PLATFORM, VERSION_1_1);
- optionNames.add(COMPILER_CODEGEN_TARGET_PLATFORM);
-
- preferences.setDefault(COMPILER_PB_UNREACHABLE_CODE, ERROR);
- optionNames.add(COMPILER_PB_UNREACHABLE_CODE);
-
- preferences.setDefault(COMPILER_PB_INVALID_IMPORT, ERROR);
- optionNames.add(COMPILER_PB_INVALID_IMPORT);
-
- preferences.setDefault(COMPILER_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD, WARNING);
- optionNames.add(COMPILER_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD);
-
- preferences.setDefault(COMPILER_PB_METHOD_WITH_CONSTRUCTOR_NAME, WARNING);
- optionNames.add(COMPILER_PB_METHOD_WITH_CONSTRUCTOR_NAME);
-
- preferences.setDefault(COMPILER_PB_DEPRECATION, WARNING);
- optionNames.add(COMPILER_PB_DEPRECATION);
-
- preferences.setDefault(COMPILER_PB_DEPRECATION_IN_DEPRECATED_CODE, DISABLED);
- optionNames.add(COMPILER_PB_DEPRECATION_IN_DEPRECATED_CODE);
-
- preferences.setDefault(COMPILER_PB_HIDDEN_CATCH_BLOCK, WARNING);
- optionNames.add(COMPILER_PB_HIDDEN_CATCH_BLOCK);
-
- preferences.setDefault(COMPILER_PB_UNUSED_LOCAL, IGNORE);
- optionNames.add(COMPILER_PB_UNUSED_LOCAL);
-
- preferences.setDefault(COMPILER_PB_UNUSED_PARAMETER, IGNORE);
- optionNames.add(COMPILER_PB_UNUSED_PARAMETER);
-
- preferences.setDefault(COMPILER_PB_UNUSED_PARAMETER_WHEN_IMPLEMENTING_ABSTRACT, DISABLED);
- optionNames.add(COMPILER_PB_UNUSED_PARAMETER_WHEN_IMPLEMENTING_ABSTRACT);
-
- preferences.setDefault(COMPILER_PB_UNUSED_PARAMETER_WHEN_OVERRIDING_CONCRETE, DISABLED);
- optionNames.add(COMPILER_PB_UNUSED_PARAMETER_WHEN_OVERRIDING_CONCRETE);
-
- preferences.setDefault(COMPILER_PB_UNUSED_IMPORT, WARNING);
- optionNames.add(COMPILER_PB_UNUSED_IMPORT);
-
- preferences.setDefault(COMPILER_PB_UNUSED_PRIVATE_MEMBER, IGNORE);
- optionNames.add(COMPILER_PB_UNUSED_PRIVATE_MEMBER);
-
- preferences.setDefault(COMPILER_PB_SYNTHETIC_ACCESS_EMULATION, IGNORE);
- optionNames.add(COMPILER_PB_SYNTHETIC_ACCESS_EMULATION);
-
- preferences.setDefault(COMPILER_PB_NON_NLS_STRING_LITERAL, IGNORE);
- optionNames.add(COMPILER_PB_NON_NLS_STRING_LITERAL);
-
- preferences.setDefault(COMPILER_PB_ASSERT_IDENTIFIER, IGNORE);
- optionNames.add(COMPILER_PB_ASSERT_IDENTIFIER);
-
- preferences.setDefault(COMPILER_PB_STATIC_ACCESS_RECEIVER, WARNING);
- optionNames.add(COMPILER_PB_STATIC_ACCESS_RECEIVER);
-
- preferences.setDefault(COMPILER_PB_NO_EFFECT_ASSIGNMENT, WARNING);
- optionNames.add(COMPILER_PB_NO_EFFECT_ASSIGNMENT);
-
- preferences.setDefault(COMPILER_PB_INCOMPATIBLE_NON_INHERITED_INTERFACE_METHOD, WARNING);
- optionNames.add(COMPILER_PB_INCOMPATIBLE_NON_INHERITED_INTERFACE_METHOD);
-
- preferences.setDefault(COMPILER_PB_CHAR_ARRAY_IN_STRING_CONCATENATION, WARNING);
- optionNames.add(COMPILER_PB_CHAR_ARRAY_IN_STRING_CONCATENATION);
-
- preferences.setDefault(COMPILER_TASK_TAGS, DEFAULT_TASK_TAG); //$NON-NLS-1$
- optionNames.add(COMPILER_TASK_TAGS);
-
- preferences.setDefault(COMPILER_TASK_PRIORITIES, DEFAULT_TASK_PRIORITY); //$NON-NLS-1$
- optionNames.add(COMPILER_TASK_PRIORITIES);
-
- preferences.setDefault(COMPILER_SOURCE, VERSION_1_3);
- optionNames.add(COMPILER_SOURCE);
-
- preferences.setDefault(COMPILER_COMPLIANCE, VERSION_1_3);
- optionNames.add(COMPILER_COMPLIANCE);
-
- preferences.setDefault(COMPILER_PB_MAX_PER_UNIT, "100"); //$NON-NLS-1$
- optionNames.add(COMPILER_PB_MAX_PER_UNIT);
-
- // Builder settings
- preferences.setDefault(CORE_JAVA_BUILD_RESOURCE_COPY_FILTER, ""); //$NON-NLS-1$
- optionNames.add(CORE_JAVA_BUILD_RESOURCE_COPY_FILTER);
-
- preferences.setDefault(CORE_JAVA_BUILD_INVALID_CLASSPATH, ABORT);
- optionNames.add(CORE_JAVA_BUILD_INVALID_CLASSPATH);
-
- preferences.setDefault(CORE_JAVA_BUILD_DUPLICATE_RESOURCE, WARNING);
- optionNames.add(CORE_JAVA_BUILD_DUPLICATE_RESOURCE);
-
- preferences.setDefault(CORE_JAVA_BUILD_CLEAN_OUTPUT_FOLDER, CLEAN);
- optionNames.add(CORE_JAVA_BUILD_CLEAN_OUTPUT_FOLDER);
-
- // JavaCore settings
- preferences.setDefault(CORE_JAVA_BUILD_ORDER, IGNORE);
- optionNames.add(CORE_JAVA_BUILD_ORDER);
-
- preferences.setDefault(CORE_CIRCULAR_CLASSPATH, ERROR);
- optionNames.add(CORE_CIRCULAR_CLASSPATH);
-
- preferences.setDefault(CORE_INCOMPLETE_CLASSPATH, ERROR);
- optionNames.add(CORE_INCOMPLETE_CLASSPATH);
-
- preferences.setDefault(CORE_ENABLE_CLASSPATH_EXCLUSION_PATTERNS, ENABLED);
- optionNames.add(CORE_ENABLE_CLASSPATH_EXCLUSION_PATTERNS);
-
- preferences.setDefault(CORE_ENABLE_CLASSPATH_MULTIPLE_OUTPUT_LOCATIONS, ENABLED);
- optionNames.add(CORE_ENABLE_CLASSPATH_MULTIPLE_OUTPUT_LOCATIONS);
-
- // encoding setting comes from resource plug-in
- optionNames.add(CORE_ENCODING);
-
- // Formatter settings
- preferences.setDefault(FORMATTER_NEWLINE_OPENING_BRACE, DO_NOT_INSERT);
- optionNames.add(FORMATTER_NEWLINE_OPENING_BRACE);
-
- preferences.setDefault(FORMATTER_NEWLINE_CONTROL, DO_NOT_INSERT);
- optionNames.add(FORMATTER_NEWLINE_CONTROL);
-
- preferences.setDefault(FORMATTER_CLEAR_BLANK_LINES, PRESERVE_ONE);
- optionNames.add(FORMATTER_CLEAR_BLANK_LINES);
-
- preferences.setDefault(FORMATTER_NEWLINE_ELSE_IF, DO_NOT_INSERT);
- optionNames.add(FORMATTER_NEWLINE_ELSE_IF);
-
- preferences.setDefault(FORMATTER_NEWLINE_EMPTY_BLOCK, INSERT);
- optionNames.add(FORMATTER_NEWLINE_EMPTY_BLOCK);
-
- preferences.setDefault(FORMATTER_LINE_SPLIT, "80"); //$NON-NLS-1$
- optionNames.add(FORMATTER_LINE_SPLIT);
-
- preferences.setDefault(FORMATTER_COMPACT_ASSIGNMENT, NORMAL);
- optionNames.add(FORMATTER_COMPACT_ASSIGNMENT);
-
- preferences.setDefault(FORMATTER_TAB_CHAR, TAB);
- optionNames.add(FORMATTER_TAB_CHAR);
-
- preferences.setDefault(FORMATTER_TAB_SIZE, "4"); //$NON-NLS-1$
- optionNames.add(FORMATTER_TAB_SIZE);
-
- preferences.setDefault(FORMATTER_SPACE_CASTEXPRESSION, INSERT); //$NON-NLS-1$
- optionNames.add(FORMATTER_SPACE_CASTEXPRESSION);
-
- // CodeAssist settings
- preferences.setDefault(CODEASSIST_VISIBILITY_CHECK, DISABLED); //$NON-NLS-1$
- optionNames.add(CODEASSIST_VISIBILITY_CHECK);
-
- preferences.setDefault(CODEASSIST_IMPLICIT_QUALIFICATION, DISABLED); //$NON-NLS-1$
- optionNames.add(CODEASSIST_IMPLICIT_QUALIFICATION);
-
- preferences.setDefault(CODEASSIST_FIELD_PREFIXES, ""); //$NON-NLS-1$
- optionNames.add(CODEASSIST_FIELD_PREFIXES);
-
- preferences.setDefault(CODEASSIST_STATIC_FIELD_PREFIXES, ""); //$NON-NLS-1$
- optionNames.add(CODEASSIST_STATIC_FIELD_PREFIXES);
-
- preferences.setDefault(CODEASSIST_LOCAL_PREFIXES, ""); //$NON-NLS-1$
- optionNames.add(CODEASSIST_LOCAL_PREFIXES);
-
- preferences.setDefault(CODEASSIST_ARGUMENT_PREFIXES, ""); //$NON-NLS-1$
- optionNames.add(CODEASSIST_ARGUMENT_PREFIXES);
-
- preferences.setDefault(CODEASSIST_FIELD_SUFFIXES, ""); //$NON-NLS-1$
- optionNames.add(CODEASSIST_FIELD_SUFFIXES);
-
- preferences.setDefault(CODEASSIST_STATIC_FIELD_SUFFIXES, ""); //$NON-NLS-1$
- optionNames.add(CODEASSIST_STATIC_FIELD_SUFFIXES);
-
- preferences.setDefault(CODEASSIST_LOCAL_SUFFIXES, ""); //$NON-NLS-1$
- optionNames.add(CODEASSIST_LOCAL_SUFFIXES);
-
- preferences.setDefault(CODEASSIST_ARGUMENT_SUFFIXES, ""); //$NON-NLS-1$
- optionNames.add(CODEASSIST_ARGUMENT_SUFFIXES);
- }
-
- /**
- * Returns whether the given marker references the given Java element.
- * Used for markers, which denote a Java element rather than a resource.
- *
- * @param element the element
- * @param marker the marker
- * @return true
if the marker references the element, false otherwise
- * @exception CoreException if the IMarker.getAttribute
on the marker fails
- */
- public static boolean isReferencedBy(IJavaElement element, IMarker marker) throws CoreException {
-
- // only match units or classfiles
- if (element instanceof IMember){
- IMember member = (IMember) element;
- if (member.isBinary()){
- element = null; //member.getClassFile();
- } else {
- element = member.getCompilationUnit();
- }
- }
- if (element == null) return false;
- if (marker == null) return false;
-
- String markerHandleId = (String)marker.getAttribute(ATT_HANDLE_ID);
- if (markerHandleId == null) return false;
-
- IJavaElement markerElement = JavaCore.create(markerHandleId);
-// while (true){
- if (element.equals(markerElement)) return true; // external elements may still be equal with different handleIDs.
-
- // cycle through enclosing types in case marker is associated with a classfile (15568)
-// if (markerElement instanceof IClassFile){
-// IType enclosingType = ((IClassFile)markerElement).getType().getDeclaringType();
-// if (enclosingType != null){
-// markerElement = enclosingType.getClassFile(); // retry with immediate enclosing classfile
-// continue;
-// }
-// }
-// break;
-// }
- return false;
- }
-
- /**
- * Returns whether the given marker delta references the given Java element.
- * Used for markers deltas, which denote a Java element rather than a resource.
- *
- * @param element the element
- * @param markerDelta the marker delta
- * @return true
if the marker delta references the element
- * @exception CoreException if the IMarkerDelta.getAttribute
on the marker delta fails
- */
- public static boolean isReferencedBy(IJavaElement element, IMarkerDelta markerDelta) throws CoreException {
-
- // only match units or classfiles
- if (element instanceof IMember){
- IMember member = (IMember) element;
- if (member.isBinary()){
- element = null; //member.getClassFile();
- } else {
- element = member.getCompilationUnit();
- }
- }
- if (element == null) return false;
- if (markerDelta == null) return false;
-
- String markerDeltarHandleId = (String)markerDelta.getAttribute(ATT_HANDLE_ID);
- if (markerDeltarHandleId == null) return false;
-
- IJavaElement markerElement = JavaCore.create(markerDeltarHandleId);
-// while (true){
- if (element.equals(markerElement)) return true; // external elements may still be equal with different handleIDs.
-
- // cycle through enclosing types in case marker is associated with a classfile (15568)
-// if (markerElement instanceof IClassFile){
-// IType enclosingType = ((IClassFile)markerElement).getType().getDeclaringType();
-// if (enclosingType != null){
-// markerElement = enclosingType.getClassFile(); // retry with immediate enclosing classfile
-// continue;
-// }
-// }
-// break;
-// }
- return false;
- }
-
- /**
- * Creates and returns a new classpath entry of kind CPE_CONTAINER
- * for the given path. The path of the container will be used during resolution so as to map this
- * container entry to a set of other classpath entries the container is acting for.
- * JavaCore.getResolvedClasspathContainer
,
- * and updated with JavaCore.classpathContainerChanged
- * ClasspathContainerInitializer
registered onto the
- * extension point "org.eclipse.jdt.core.classpathContainerInitializer".
- *
- *
- * newContainerEntry(-,false)
.
- * CPE_CONTAINER
- * for the given path. The path of the container will be used during resolution so as to map this
- * container entry to a set of other classpath entries the container is acting for.
- * JavaCore.getResolvedClasspathContainer
,
- * and updated with JavaCore.classpathContainerChanged
- * ClasspathContainerInitializer
registered onto the
- * extension point "org.eclipse.jdt.core.classpathContainerInitializer".
- *
- *
- * CPE_LIBRARY
for the
- * JAR or folder identified by the given absolute path. This specifies that all package fragments
- * within the root will have children of type IClassFile
.
- *
- *
- * Note that this operation does not attempt to validate or access the
- * resources at the given paths.
- * "c:/jdk1.2.2/jre/lib/rt.jar"
- reference to an external JAR "/Project/someLib.jar"
- reference to an internal JAR "c:/classes/"
- reference to an external binary foldernewLibraryEntry(-,-,-,false)
.
- * null
if none
- * @param sourceAttachmentRootPath the location of the root within the source archive or folder
- * or null
if this location should be automatically detected.
- * @return a new library classpath entry
- *
- * @see #newLibraryEntry(IPath, IPath, IPath, boolean)
- */
-// public static IClasspathEntry newLibraryEntry(
-// IPath path,
-// IPath sourceAttachmentPath,
-// IPath sourceAttachmentRootPath) {
-//
-// return newLibraryEntry(path, sourceAttachmentPath, sourceAttachmentRootPath, false);
-// }
-
- /**
- * Creates and returns a new classpath entry of kind CPE_LIBRARY
for the JAR or folder
- * identified by the given absolute path. This specifies that all package fragments within the root
- * will have children of type IClassFile
.
- *
- *
- * Note that this operation does not attempt to validate or access the
- * resources at the given paths.
- * "c:/jdk1.2.2/jre/lib/rt.jar"
- reference to an external JAR "/Project/someLib.jar"
- reference to an internal JAR "c:/classes/"
- reference to an external binary foldernull
if none
- * @param sourceAttachmentRootPath the location of the root within the source archive or folder
- * or null
if this location should be automatically detected.
- * @param isExported indicates whether this entry is contributed to dependent
- * projects in addition to the output location
- * @return a new library classpath entry
- * @since 2.0
- */
-// public static IClasspathEntry newLibraryEntry(
-// IPath path,
-// IPath sourceAttachmentPath,
-// IPath sourceAttachmentRootPath,
-// boolean isExported) {
-//
-// if (!path.isAbsolute()) Assert.isTrue(false, "Path for IClasspathEntry must be absolute"); //$NON-NLS-1$
-//
-// return new ClasspathEntry(
-// IPackageFragmentRoot.K_BINARY,
-// IClasspathEntry.CPE_LIBRARY,
-// JavaProject.canonicalizedPath(path),
-// ClasspathEntry.NO_EXCLUSION_PATTERNS,
-// sourceAttachmentPath,
-// sourceAttachmentRootPath,
-// null, // specific output folder
-// isExported);
-// }
-
- /**
- * Creates and returns a new non-exported classpath entry of kind CPE_PROJECT
- * for the project identified by the given absolute path.
- * newProjectEntry(_,false)
.
- * CPE_PROJECT
- * for the project identified by the given absolute path.
- * CPE_SOURCE
- * for the project's source folder identified by the given absolute
- * workspace-relative path. This specifies that all package fragments
- * within the root will have children of type ICompilationUnit
.
- * /Project/src
. A project's source
- * folders are located with that project. That is, a source classpath
- * entry specifying the path /P1/src
is only usable for
- * project P1
.
- * JavaCore.newSourceEntry(IPath,IPath[])
instead.
- * JavaCore.newProjectEntry
). Particular
- * source entries cannot be selectively exported.
- * CPE_SOURCE
- * for the project's source folder identified by the given absolute
- * workspace-relative path but excluding all source files with paths
- * matching any of the given patterns. This specifies that all package
- * fragments within the root will have children of type
- * ICompilationUnit
.
- * /Project/src
. A project's source
- * folders are located with that project. That is, a source classpath
- * entry specifying the path /P1/src
is only usable for
- * project P1
.
- * /Project/src
and the exclusion pattern is
- * com/xyz/tests/**
, then source files
- * like /Project/src/com/xyz/Foo.java
- * and /Project/src/com/xyz/utils/Bar.java
would be included,
- * whereas /Project/src/com/xyz/tests/T1.java
- * and /Project/src/com/xyz/tests/quick/T2.java
would be
- * excluded. Exclusion patterns can contain can contain '**', '*' or '?'
- * wildcards; see IClasspathEntry.getExclusionPatterns
- * for the full description of the syntax and semantics of exclusion
- * patterns.
- * JavaCore.newSourceEntry(IPath)
.
- * JavaCore.newProjectEntry
). Particular
- * source entries cannot be selectively exported.
- * CPE_SOURCE
- * for the project's source folder identified by the given absolute
- * workspace-relative path but excluding all source files with paths
- * matching any of the given patterns, and associated with a specific output location
- * (that is, ".class" files are not going to the project default output location).
- * All package fragments within the root will have children of type
- * ICompilationUnit
.
- * /Project/src
. A project's source
- * folders are located with that project. That is, a source classpath
- * entry specifying the path /P1/src
is only usable for
- * project P1
.
- * /Project/src
and the exclusion pattern is
- * com/xyz/tests/**
, then source files
- * like /Project/src/com/xyz/Foo.java
- * and /Project/src/com/xyz/utils/Bar.java
would be included,
- * whereas /Project/src/com/xyz/tests/T1.java
- * and /Project/src/com/xyz/tests/quick/T2.java
would be
- * excluded. Exclusion patterns can contain can contain '**', '*' or '?'
- * wildcards; see IClasspathEntry.getExclusionPatterns
- * for the full description of the syntax and semantics of exclusion
- * patterns.
- * JavaCore.newSourceEntry(IPath)
.
- * null
).
- * Note that multiple source entries may target the same output location.
- * The output location is referred to using an absolute path relative to the
- * workspace root, e.g. "/Project/bin"
, it must be located inside
- * the same project as the source folder.
- * JavaCore.newProjectEntry
). Particular
- * source entries cannot be selectively exported.
- * null
if using project default ouput location)
- * @return a new source classpath entry with the given exclusion patterns
- * @see #newSourceEntry(org.eclipse.core.runtime.IPath)
- * @see IClasspathEntry#getExclusionPatterns
- * @see IClasspathEntry#getOutputLocation()
- *
- * @since 2.1
- */
-// public static IClasspathEntry newSourceEntry(IPath path, IPath[] exclusionPatterns, IPath specificOutputLocation) {
-//
-// if (!path.isAbsolute()) Assert.isTrue(false, "Path for IClasspathEntry must be absolute"); //$NON-NLS-1$
-// if (exclusionPatterns == null) Assert.isTrue(false, "Exclusion pattern set cannot be null"); //$NON-NLS-1$
-//
-// return new ClasspathEntry(
-// IPackageFragmentRoot.K_SOURCE,
-// IClasspathEntry.CPE_SOURCE,
-// path,
-// exclusionPatterns,
-// null, // source attachment
-// null, // source attachment root
-// specificOutputLocation, // custom output location
-// false);
-// }
-
- /**
- * Creates and returns a new non-exported classpath entry of kind CPE_VARIABLE
- * for the given path. The first segment of the path is the name of a classpath variable.
- * The trailing segments of the path will be appended to resolved variable path.
- * ClasspathVariableInitializer
),
- * which will be invoked through the extension point "org.eclipse.jdt.core.classpathVariableInitializer".
- * After resolution, a classpath variable entry may either correspond to a project or a library entry.
- * e.g. Here are some examples of variable path usage
JDTCORE
is
- * bound to "c:/jars/jdtcore.jar". The resolved classpath entry is denoting the library "c:\jars\jdtcore.jar"JDTCORE
is
- * bound to "/Project_JDTCORE". The resolved classpath entry is denoting the project "/Project_JDTCORE"PLUGINS
- * is bound to "c:/eclipse/plugins". The resolved classpath entry is denoting the library "c:/eclipse/plugins/com.example/example.jar"
- * The resulting entry is not exported to dependent projects. This method is equivalent to
- * newVariableEntry(-,-,-,false)
.
- *
- *
- * @param variablePath the path of the binary archive; first segment is the
- * name of a classpath variable
- * @param variableSourceAttachmentPath the path of the corresponding source archive,
- * or null
if none; if present, the first segment is the
- * name of a classpath variable (not necessarily the same variable
- * as the one that begins variablePath
)
- * @param sourceAttachmentRootPath the location of the root within the source archive
- * or null
if archivePath
is also null
- * @return a new library classpath entry
- *
- * @see JavaCore#newVariableEntry(IPath, IPath, IPath, boolean)
- */
-// public static IClasspathEntry newVariableEntry(
-// IPath variablePath,
-// IPath variableSourceAttachmentPath,
-// IPath sourceAttachmentRootPath) {
-//
-// return newVariableEntry(variablePath, variableSourceAttachmentPath, sourceAttachmentRootPath, false);
-// }
-
- /**
- * Creates and returns a new non-exported classpath entry of kind CPE_VARIABLE
- * for the given path. The first segment of the path is the name of a classpath variable.
- * The trailing segments of the path will be appended to resolved variable path.
- *
- * A variable entry allows to express indirect references on a classpath to other projects or libraries, - * depending on what the classpath variable is referring. - *
- * It is possible to register an automatic initializer (ClasspathVariableInitializer
),
- * which will be invoked through the extension point "org.eclipse.jdt.core.classpathVariableInitializer".
- * After resolution, a classpath variable entry may either correspond to a project or a library entry.
- *
- * e.g. Here are some examples of variable path usage
JDTCORE
is
- * bound to "c:/jars/jdtcore.jar". The resolved classpath entry is denoting the library "c:\jars\jdtcore.jar"JDTCORE
is
- * bound to "/Project_JDTCORE". The resolved classpath entry is denoting the project "/Project_JDTCORE"PLUGINS
- * is bound to "c:/eclipse/plugins". The resolved classpath entry is denoting the library "c:/eclipse/plugins/com.example/example.jar"
- *
- * @param variablePath the path of the binary archive; first segment is the
- * name of a classpath variable
- * @param variableSourceAttachmentPath the path of the corresponding source archive,
- * or null
if none; if present, the first segment is the
- * name of a classpath variable (not necessarily the same variable
- * as the one that begins variablePath
)
- * @param sourceAttachmentRootPath the location of the root within the source archive
- * or null
if archivePath
is also null
- * @param isExported indicates whether this entry is contributed to dependent
- * projects in addition to the output location
- * @return a new variable classpath entry
- * @since 2.0
- */
-// public static IClasspathEntry newVariableEntry(
-// IPath variablePath,
-// IPath variableSourceAttachmentPath,
-// IPath variableSourceAttachmentRootPath,
-// boolean isExported) {
-//
-// if (variablePath == null || variablePath.segmentCount() < 1) {
-// Assert.isTrue(
-// false,
-// "Illegal classpath variable path: \'" + variablePath.makeRelative().toString() + "\', must have at least one segment"); //$NON-NLS-1$//$NON-NLS-2$
-// }
-//
-// return new ClasspathEntry(
-// IPackageFragmentRoot.K_SOURCE,
-// IClasspathEntry.CPE_VARIABLE,
-// variablePath,
-// ClasspathEntry.NO_EXCLUSION_PATTERNS,
-// variableSourceAttachmentPath, // source attachment
-// variableSourceAttachmentRootPath, // source attachment root
-// null, // specific output folder
-// isExported);
-// }
-
- /**
- * Removed the given classpath variable. Does nothing if no value was
- * set for this classpath variable.
- *
- * This functionality cannot be used while the resource tree is locked. - *
- * Classpath variable values are persisted locally to the workspace, and - * are preserved from session to session. - *
- * - * @param variableName the name of the classpath variable - * @see #setClasspathVariable - * - * @deprecated - use version with extra IProgressMonitor - */ -// public static void removeClasspathVariable(String variableName) { -// removeClasspathVariable(variableName, null); -// } - - /** - * Removed the given classpath variable. Does nothing if no value was - * set for this classpath variable. - *
- * This functionality cannot be used while the resource tree is locked. - *
- * Classpath variable values are persisted locally to the workspace, and - * are preserved from session to session. - *
- * - * @param variableName the name of the classpath variable - * @param monitor the progress monitor to report progress - * @see #setClasspathVariable - */ -// public static void removeClasspathVariable( -// String variableName, -// IProgressMonitor monitor) { -// -// try { -// updateVariableValues(new String[]{ variableName}, new IPath[]{ null }, monitor); -// } catch (JavaModelException e) { -// } -// } - - /** - * Removes the given element changed listener. - * Has no affect if an identical listener is not registered. - * - * @param listener the listener - */ - public static void removeElementChangedListener(IElementChangedListener listener) { - JavaModelManager.getJavaModelManager().removeElementChangedListener(listener); - } - /** - * Runs the given action as an atomic Java model operation. - *
- * After running a method that modifies Java elements, - * registered listeners receive after-the-fact notification of - * what just transpired, in the form of a element changed event. - * This method allows clients to call a number of - * methods that modify java elements and only have element - * changed event notifications reported at the end of the entire - * batch. - *
- *- * If this method is called outside the dynamic scope of another such - * call, this method runs the action and then reports a single - * element changed event describing the net effect of all changes - * done to java elements by the action. - *
- *- * If this method is called in the dynamic scope of another such - * call, this method simply runs the action. - *
- * - * @param action the action to perform - * @param monitor a progress monitor, ornull
if progress
- * reporting and cancellation are not desired
- * @exception CoreException if the operation failed.
- * @since 2.1
- */
- public static void run(IWorkspaceRunnable action, IProgressMonitor monitor) throws CoreException {
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
- if (workspace.isTreeLocked()) {
- new BatchOperation(action).run(monitor);
- } else {
- // use IWorkspace.run(...) to ensure that a build will be done in autobuild mode
- workspace.run(new BatchOperation(action), monitor);
- }
- }
- /**
- * Bind a container reference path to some actual containers (IClasspathContainer
).
- * This API must be invoked whenever changes in container need to be reflected onto the JavaModel.
- * Containers can have distinct values in different projects, therefore this API considers a
- * set of projects with their respective containers.
- *
- * containerPath
is the path under which these values can be referenced through
- * container classpath entries (IClasspathEntry#CPE_CONTAINER
). A container path
- * is formed by a first ID segment followed with extra segments, which can be used as additional hints
- * for the resolution. The container ID is used to identify a ClasspathContainerInitializer
- * registered on the extension point "org.eclipse.jdt.core.classpathContainerInitializer".
- *
- * There is no assumption that each individual container value passed in argument
- * (respectiveContainers
) must answer the exact same path when requested
- * IClasspathContainer#getPath
.
- * Indeed, the containerPath is just an indication for resolving it to an actual container object. It can be
- * delegated to a ClasspathContainerInitializer
, which can be activated through the extension
- * point "org.eclipse.jdt.core.ClasspathContainerInitializer").
- *
- * In reaction to changing container values, the JavaModel will be updated to reflect the new - * state of the updated container. - *
- * This functionality cannot be used while the resource tree is locked. - *
- * Classpath container values are persisted locally to the workspace, but
- * are not preserved from a session to another. It is thus highly recommended to register a
- * ClasspathContainerInitializer
for each referenced container
- * (through the extension point "org.eclipse.jdt.core.ClasspathContainerInitializer").
- *
- * Note: setting a container to null
will cause it to be lazily resolved again whenever
- * its value is required. In particular, this will cause a registered initializer to be invoked
- * again.
- *
- * @param containerPath - the name of the container reference, which is being updated
- * @param affectedProjects - the set of projects for which this container is being bound
- * @param respectiveContainers - the set of respective containers for the affected projects
- * @param monitor a monitor to report progress
- *
- * @see ClasspathContainerInitializer
- * @see #getClasspathContainer(IPath, IJavaProject)
- * @see IClasspathContainer
- * @since 2.0
- */
-// public static void setClasspathContainer(final IPath containerPath, IJavaProject[] affectedProjects, IClasspathContainer[] respectiveContainers, IProgressMonitor monitor) throws JavaModelException {
-//
-// if (affectedProjects.length != respectiveContainers.length) Assert.isTrue(false, "Projects and containers collections should have the same size"); //$NON-NLS-1$
-//
-// if (monitor != null && monitor.isCanceled()) return;
-//
-// if (JavaModelManager.CP_RESOLVE_VERBOSE){
-// System.out.println("CPContainer SET - setting container: ["+containerPath+"] for projects: {" //$NON-NLS-1$ //$NON-NLS-2$
-// + (Util.toString(affectedProjects,
-// new Util.Displayable(){
-// public String displayString(Object o) { return ((IJavaProject) o).getElementName(); }
-// }))
-// + "} with values: " //$NON-NLS-1$
-// + (Util.toString(respectiveContainers,
-// new Util.Displayable(){
-// public String displayString(Object o) { return ((IClasspathContainer) o).getDescription(); }
-// }))
-// );
-// }
-//
-// final int projectLength = affectedProjects.length;
-// final IJavaProject[] modifiedProjects;
-// System.arraycopy(affectedProjects, 0, modifiedProjects = new IJavaProject[projectLength], 0, projectLength);
-// final IClasspathEntry[][] oldResolvedPaths = new IClasspathEntry[projectLength][];
-//
-// // filter out unmodified project containers
-// int remaining = 0;
-// for (int i = 0; i < projectLength; i++){
-//
-// if (monitor != null && monitor.isCanceled()) return;
-//
-// IJavaProject affectedProject = affectedProjects[i];
-// IClasspathContainer newContainer = respectiveContainers[i];
-// if (newContainer == null) newContainer = JavaModelManager.ContainerInitializationInProgress; // 30920 - prevent infinite loop
-// boolean found = false;
-// if (JavaProject.hasJavaNature(affectedProject.getProject())){
-// IClasspathEntry[] rawClasspath = affectedProject.getRawClasspath();
-// for (int j = 0, cpLength = rawClasspath.length; j
- * Classpath variable values are persisted locally to the workspace, and
- * are preserved from session to session.
- *
- *
- * @param variableName the name of the classpath variable
- * @param path the path
- * @see #getClasspathVariable
- *
- * @deprecated - use API with IProgressMonitor
- */
-// public static void setClasspathVariable(String variableName, IPath path)
-// throws JavaModelException {
-//
-// setClasspathVariable(variableName, path, null);
-// }
-
- /**
- * Sets the value of the given classpath variable.
- * The path must not be null.
- *
- * This functionality cannot be used while the resource tree is locked.
- *
- * Classpath variable values are persisted locally to the workspace, and
- * are preserved from session to session.
- *
- * Updating a variable with the same value has no effect.
- *
- * @param variableName the name of the classpath variable
- * @param path the path
- * @param monitor a monitor to report progress
- * @see #getClasspathVariable
- */
-// public static void setClasspathVariable(
-// String variableName,
-// IPath path,
-// IProgressMonitor monitor)
-// throws JavaModelException {
-//
-// if (path == null) Assert.isTrue(false, "Variable path cannot be null"); //$NON-NLS-1$
-// setClasspathVariables(new String[]{variableName}, new IPath[]{ path }, monitor);
-// }
-
- /**
- * Sets the values of all the given classpath variables at once.
- * Null paths can be used to request corresponding variable removal.
- *
- * This functionality cannot be used while the resource tree is locked.
- *
- * Classpath variable values are persisted locally to the workspace, and
- * are preserved from session to session.
- *
- * Updating a variable with the same value has no effect.
- *
- * @param variableNames an array of names for the updated classpath variables
- * @param paths an array of path updates for the modified classpath variables (null
- * meaning that the corresponding value will be removed
- * @param monitor a monitor to report progress
- * @see #getClasspathVariable
- * @since 2.0
- */
-// public static void setClasspathVariables(
-// String[] variableNames,
-// IPath[] paths,
-// IProgressMonitor monitor)
-// throws JavaModelException {
-//
-// if (variableNames.length != paths.length) Assert.isTrue(false, "Variable names and paths collections should have the same size"); //$NON-NLS-1$
-// //TODO: should check that null cannot be used as variable paths
-// updateVariableValues(variableNames, paths, monitor);
-// }
-
- /* (non-Javadoc)
- * Method declared on IExecutableExtension.
- * Record any necessary initialization data from the plugin.
- */
- public void setInitializationData(
- IConfigurationElement cfig,
- String propertyName,
- Object data)
- throws CoreException {
- }
-
- /**
- * Sets the current table of options. All and only the options explicitly included in the given table
- * are remembered; all previous option settings are forgotten, including ones not explicitly
- * mentioned.
- *
- * For a complete description of the configurable options, see
- * De-registers the JavaModelManager as a resource changed listener and save participant.
- *
- * @see org.eclipse.core.runtime.Plugin#shutdown()
- */
- public void shutdown() {
-
- savePluginPreferences();
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
- workspace.removeResourceChangeListener(JavaModelManager.getJavaModelManager().deltaProcessor);
- workspace.removeSaveParticipant(this);
-
- ((JavaModelManager) JavaModelManager.getJavaModelManager()).shutdown();
- }
-
- /**
- * Initiate the background indexing process.
- * This should be deferred after the plugin activation.
- */
-// private void startIndexing() {
-//
-// JavaModelManager.getJavaModelManager().getIndexManager().reset();
-// }
-
- /**
- * Startup of the JavaCore plug-in.
- *
- * Registers the JavaModelManager as a resource changed listener and save participant.
- * Starts the background indexing, and restore saved classpath variable values.
- *
- * @see org.eclipse.core.runtime.Plugin#startup()
- */
- public void startup() {
-
- JavaModelManager manager = JavaModelManager.getJavaModelManager();
- try {
- manager.configurePluginDebugOptions();
-
- // request state folder creation (workaround 19885)
- JavaCore.getPlugin().getStateLocation();
-
- // retrieve variable values
- JavaCore.getPlugin().getPluginPreferences().addPropertyChangeListener(new JavaModelManager.PluginPreferencesListener());
-// TODO khartlage temp-del
-// manager.loadVariablesAndContainers();
-
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
- workspace.addResourceChangeListener(
- manager.deltaProcessor,
- IResourceChangeEvent.PRE_AUTO_BUILD
- | IResourceChangeEvent.POST_AUTO_BUILD
- | IResourceChangeEvent.POST_CHANGE
- | IResourceChangeEvent.PRE_DELETE
- | IResourceChangeEvent.PRE_CLOSE);
-
-// startIndexing();
- workspace.addSaveParticipant(this, manager);
-
- } catch (CoreException e) {
- } catch (RuntimeException e) {
- manager.shutdown();
- throw e;
- }
- }
-
-
- /**
- * Internal updating of a variable values (null path meaning removal), allowing to change multiple variable values at once.
- */
-// private static void updateVariableValues(
-// String[] variableNames,
-// IPath[] variablePaths,
-// IProgressMonitor monitor) throws JavaModelException {
-//
-// if (monitor != null && monitor.isCanceled()) return;
-//
-// if (JavaModelManager.CP_RESOLVE_VERBOSE){
-// System.out.println("CPVariable SET - setting variables: {" + Util.toString(variableNames) //$NON-NLS-1$
-// + "} with values: " + Util.toString(variablePaths)); //$NON-NLS-1$
-// }
-//
-// int varLength = variableNames.length;
-//
-// // gather classpath information for updating
-// final HashMap affectedProjects = new HashMap(5);
-// JavaModelManager manager = JavaModelManager.getJavaModelManager();
-// IJavaModel model = manager.getJavaModel();
-//
-// // filter out unmodified variables
-// int discardCount = 0;
-// for (int i = 0; i < varLength; i++){
-// String variableName = variableNames[i];
-// IPath oldPath = (IPath)JavaModelManager.variableGet(variableName); // if reentering will provide previous session value
-// if (oldPath == JavaModelManager.VariableInitializationInProgress){
-// IPath previousPath = (IPath)JavaModelManager.PreviousSessionVariables.get(variableName);
-// if (previousPath != null){
-// if (JavaModelManager.CP_RESOLVE_VERBOSE){
-// System.out.println("CPVariable INIT - reentering access to variable: " + variableName+ " during its initialization, will see previous value: "+ previousPath); //$NON-NLS-1$ //$NON-NLS-2$
-// }
-// JavaModelManager.variablePut(variableName, previousPath); // replace value so reentering calls are seeing old value
-// }
-// oldPath = null; //33695 - cannot filter out restored variable, must update affected project to reset cached CP
-// }
-// if (oldPath != null && oldPath.equals(variablePaths[i])){
-// variableNames[i] = null;
-// discardCount++;
-// }
-// }
-// if (discardCount > 0){
-// if (discardCount == varLength) return;
-// int changedLength = varLength - discardCount;
-// String[] changedVariableNames = new String[changedLength];
-// IPath[] changedVariablePaths = new IPath[changedLength];
-// for (int i = 0, index = 0; i < varLength; i++){
-// if (variableNames[i] != null){
-// changedVariableNames[index] = variableNames[i];
-// changedVariablePaths[index] = variablePaths[i];
-// index++;
-// }
-// }
-// variableNames = changedVariableNames;
-// variablePaths = changedVariablePaths;
-// varLength = changedLength;
-// }
-//
-// if (monitor != null && monitor.isCanceled()) return;
-//
-// if (model != null) {
-// IJavaProject[] projects = model.getJavaProjects();
-// nextProject : for (int i = 0, projectLength = projects.length; i < projectLength; i++){
-// IJavaProject project = projects[i];
-//
-// // check to see if any of the modified variables is present on the classpath
-// IClasspathEntry[] classpath = project.getRawClasspath();
-// for (int j = 0, cpLength = classpath.length; j < cpLength; j++){
-//
-// IClasspathEntry entry = classpath[j];
-// for (int k = 0; k < varLength; k++){
-//
-// String variableName = variableNames[k];
-// if (entry.getEntryKind() == IClasspathEntry.CPE_VARIABLE){
-//
-// if (variableName.equals(entry.getPath().segment(0))){
-// affectedProjects.put(project, project.getResolvedClasspath(true));
-// continue nextProject;
-// }
-// IPath sourcePath, sourceRootPath;
-// if (((sourcePath = entry.getSourceAttachmentPath()) != null && variableName.equals(sourcePath.segment(0)))
-// || ((sourceRootPath = entry.getSourceAttachmentRootPath()) != null && variableName.equals(sourceRootPath.segment(0)))) {
-//
-// affectedProjects.put(project, project.getResolvedClasspath(true));
-// continue nextProject;
-// }
-// }
-// }
-// }
-// }
-// }
-// // update variables
-// for (int i = 0; i < varLength; i++){
-// JavaModelManager.variablePut(variableNames[i], variablePaths[i]);
-// }
-// final String[] dbgVariableNames = variableNames;
-//
-// // update affected project classpaths
-// if (!affectedProjects.isEmpty()) {
-// try {
-// JavaCore.run(
-// new IWorkspaceRunnable() {
-// public void run(IProgressMonitor monitor) throws CoreException {
-// // propagate classpath change
-// Iterator projectsToUpdate = affectedProjects.keySet().iterator();
-// while (projectsToUpdate.hasNext()) {
-//
-// if (monitor != null && monitor.isCanceled()) return;
-//
-// JavaProject project = (JavaProject) projectsToUpdate.next();
-//
-// if (JavaModelManager.CP_RESOLVE_VERBOSE){
-// System.out.println("CPVariable SET - updating affected project: ["+project.getElementName()+"] due to setting variables: "+ Util.toString(dbgVariableNames)); //$NON-NLS-1$ //$NON-NLS-2$
-// }
-//
-// project
-// .setRawClasspath(
-// project.getRawClasspath(),
-// SetClasspathOperation.ReuseOutputLocation,
-// null, // don't call beginTask on the monitor (see http://bugs.eclipse.org/bugs/show_bug.cgi?id=3717)
-// !ResourcesPlugin.getWorkspace().isTreeLocked(), // can change resources
-// (IClasspathEntry[]) affectedProjects.get(project),
-// false, // updating - no validation
-// false); // updating - no need to save
-// }
-// }
-// },
-// monitor);
-// } catch (CoreException e) {
-// if (JavaModelManager.CP_RESOLVE_VERBOSE){
-// System.out.println("CPVariable SET - FAILED DUE TO EXCEPTION: "+Util.toString(dbgVariableNames)); //$NON-NLS-1$
-// e.printStackTrace();
-// }
-// if (e instanceof JavaModelException) {
-// throw (JavaModelException)e;
-// } else {
-// throw new JavaModelException(e);
-// }
-// }
-// }
-// }
-}
\ No newline at end of file
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/JavaModelException.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/JavaModelException.java
index a8d59f9..cc88627 100644
--- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/JavaModelException.java
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/JavaModelException.java
@@ -105,10 +105,10 @@ public IJavaModelStatus getJavaModelStatus() {
* @see IJavaModelStatus#isDoesNotExist
* @see IJavaModelStatusConstants#ELEMENT_DOES_NOT_EXIST
*/
-//public boolean isDoesNotExist() {
-// IJavaModelStatus javaModelStatus = getJavaModelStatus();
-// return javaModelStatus != null && javaModelStatus.isDoesNotExist();
-//}
+public boolean isDoesNotExist() {
+ IJavaModelStatus javaModelStatus = getJavaModelStatus();
+ return javaModelStatus != null && javaModelStatus.isDoesNotExist();
+}
/**
* Returns a printable representation of this exception suitable for debugging
* purposes only.
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/Signature.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/Signature.java
new file mode 100644
index 0000000..97eb0fd
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/Signature.java
@@ -0,0 +1,1433 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.core;
+
+import net.sourceforge.phpdt.core.compiler.CharOperation;
+
+/**
+ * Provides methods for encoding and decoding type and method signature strings.
+ *
+ * The syntax for a type signature is:
+ * getDefaultOptions
.
- * String
; value type: String
),
- * or null
to reset all options to their default values
- * @see JavaCore#getDefaultOptions
- */
- public static void setOptions(Hashtable newOptions) {
-
- // see #initializeDefaultPluginPreferences() for changing default settings
- Preferences preferences = getPlugin().getPluginPreferences();
-
- if (newOptions == null){
- newOptions = JavaCore.getDefaultOptions();
- }
- Enumeration keys = newOptions.keys();
- while (keys.hasMoreElements()){
- String key = (String)keys.nextElement();
- if (!JavaModelManager.OptionNames.contains(key)) continue; // unrecognized option
- if (key.equals(CORE_ENCODING)) continue; // skipped, contributed by resource prefs
- String value = (String)newOptions.get(key);
- preferences.setValue(key, value);
- }
-
- // persist options
- getPlugin().savePluginPreferences();
- }
-
- /**
- * Shutdown the JavaCore plug-in.
- *
+ * typeSignature ::=
+ * "B" // byte
+ * | "C" // char
+ * | "D" // double
+ * | "F" // float
+ * | "I" // int
+ * | "J" // long
+ * | "S" // short
+ * | "V" // void
+ * | "Z" // boolean
+ * | "L" + binaryTypeName + ";" // resolved named type (in compiled code)
+ * | "Q" + sourceTypeName + ";" // unresolved named type (in source code)
+ * | "[" + typeSignature // array of type denoted by typeSignature
+ *
+ *
+ * Examples: + *
"[[I"
denotes int[][]
"Ljava.lang.String;"
denotes java.lang.String
in compiled code"QString"
denotes String
in source code"Qjava.lang.String"
denotes java.lang.String
in source code"[QString"
denotes String[]
in source code+ * The syntax for a method signature is: + *
+ * methodSignature ::= "(" + paramTypeSignature* + ")" + returnTypeSignature + * paramTypeSignature ::= typeSignature + * returnTypeSignature ::= typeSignature + *+ *
+ * Examples: + *
"()I"
denotes int foo()
"([Ljava.lang.String;)V"
denotes void foo(java.lang.String[])
in compiled code"(QString;)QObject;"
denotes Object foo(String)
in source code+ * This class provides static methods and constants only; it is not intended to be + * instantiated or subclassed by clients. + *
+ */ +public final class Signature { + + /** + * Character constant indicating the primitive type boolean in a signature. + * Value is'Z'
.
+ */
+ public static final char C_BOOLEAN = 'Z';
+
+ /**
+ * Character constant indicating the primitive type byte in a signature.
+ * Value is 'B'
.
+ */
+ public static final char C_BYTE = 'B';
+
+ /**
+ * Character constant indicating the primitive type char in a signature.
+ * Value is 'C'
.
+ */
+ public static final char C_CHAR = 'C';
+
+ /**
+ * Character constant indicating the primitive type double in a signature.
+ * Value is 'D'
.
+ */
+ public static final char C_DOUBLE = 'D';
+
+ /**
+ * Character constant indicating the primitive type float in a signature.
+ * Value is 'F'
.
+ */
+ public static final char C_FLOAT = 'F';
+
+ /**
+ * Character constant indicating the primitive type int in a signature.
+ * Value is 'I'
.
+ */
+ public static final char C_INT = 'I';
+
+ /**
+ * Character constant indicating the semicolon in a signature.
+ * Value is ';'
.
+ */
+ public static final char C_SEMICOLON = ';';
+
+ /**
+ * Character constant indicating the primitive type long in a signature.
+ * Value is 'J'
.
+ */
+ public static final char C_LONG = 'J';
+
+ /**
+ * Character constant indicating the primitive type short in a signature.
+ * Value is 'S'
.
+ */
+ public static final char C_SHORT = 'S';
+
+ /**
+ * Character constant indicating result type void in a signature.
+ * Value is 'V'
.
+ */
+ public static final char C_VOID = 'V';
+
+ /**
+ * Character constant indicating the dot in a signature.
+ * Value is '.'
.
+ */
+ public static final char C_DOT = '.';
+
+ /**
+ * Character constant indicating the dollar in a signature.
+ * Value is '$'
.
+ */
+ public static final char C_DOLLAR = '$';
+
+ /**
+ * Character constant indicating an array type in a signature.
+ * Value is '['
.
+ */
+ public static final char C_ARRAY = '[';
+
+ /**
+ * Character constant indicating the start of a resolved, named type in a
+ * signature. Value is 'L'
.
+ */
+ public static final char C_RESOLVED = 'L';
+
+ /**
+ * Character constant indicating the start of an unresolved, named type in a
+ * signature. Value is 'Q'
.
+ */
+ public static final char C_UNRESOLVED = 'Q';
+
+ /**
+ * Character constant indicating the end of a named type in a signature.
+ * Value is ';'
.
+ */
+ public static final char C_NAME_END = ';';
+
+ /**
+ * Character constant indicating the start of a parameter type list in a
+ * signature. Value is '('
.
+ */
+ public static final char C_PARAM_START = '(';
+
+ /**
+ * Character constant indicating the end of a parameter type list in a
+ * signature. Value is ')'
.
+ */
+ public static final char C_PARAM_END = ')';
+
+ /**
+ * String constant for the signature of the primitive type boolean.
+ * Value is "Z"
.
+ */
+ public static final String SIG_BOOLEAN = "Z"; //$NON-NLS-1$
+
+ /**
+ * String constant for the signature of the primitive type byte.
+ * Value is "B"
.
+ */
+ public static final String SIG_BYTE = "B"; //$NON-NLS-1$
+
+ /**
+ * String constant for the signature of the primitive type char.
+ * Value is "C"
.
+ */
+ public static final String SIG_CHAR = "C"; //$NON-NLS-1$
+
+ /**
+ * String constant for the signature of the primitive type double.
+ * Value is "D"
.
+ */
+ public static final String SIG_DOUBLE = "D"; //$NON-NLS-1$
+
+ /**
+ * String constant for the signature of the primitive type float.
+ * Value is "F"
.
+ */
+ public static final String SIG_FLOAT = "F"; //$NON-NLS-1$
+
+ /**
+ * String constant for the signature of the primitive type int.
+ * Value is "I"
.
+ */
+ public static final String SIG_INT = "I"; //$NON-NLS-1$
+
+ /**
+ * String constant for the signature of the primitive type long.
+ * Value is "J"
.
+ */
+ public static final String SIG_LONG = "J"; //$NON-NLS-1$
+
+ /**
+ * String constant for the signature of the primitive type short.
+ * Value is "S"
.
+ */
+ public static final String SIG_SHORT = "S"; //$NON-NLS-1$
+
+ /** String constant for the signature of result type void.
+ * Value is "V"
.
+ */
+ public static final String SIG_VOID = "V"; //$NON-NLS-1$
+
+ private static final char[] BOOLEAN = {'b', 'o', 'o', 'l', 'e', 'a', 'n'};
+ private static final char[] BYTE = {'b', 'y', 't', 'e'};
+ private static final char[] CHAR = {'c', 'h', 'a', 'r'};
+ private static final char[] DOUBLE = {'d', 'o', 'u', 'b', 'l', 'e'};
+ private static final char[] FLOAT = {'f', 'l', 'o', 'a', 't'};
+ private static final char[] INT = {'i', 'n', 't'};
+ private static final char[] LONG = {'l', 'o', 'n', 'g'};
+ private static final char[] SHORT = {'s', 'h', 'o', 'r', 't'};
+ private static final char[] VOID = {'v', 'o', 'i', 'd'};
+
+ private static final String EMPTY = new String(CharOperation.NO_CHAR);
+
+/**
+ * Not instantiable.
+ */
+private Signature() {}
+
+private static long copyType(char[] signature, int sigPos, char[] dest, int index, boolean fullyQualifyTypeNames) {
+ int arrayCount = 0;
+ loop: while (true) {
+ switch (signature[sigPos++]) {
+ case C_ARRAY :
+ arrayCount++;
+ break;
+ case C_BOOLEAN :
+ int length = BOOLEAN.length;
+ System.arraycopy(BOOLEAN, 0, dest, index, length);
+ index += length;
+ break loop;
+ case C_BYTE :
+ length = BYTE.length;
+ System.arraycopy(BYTE, 0, dest, index, length);
+ index += length;
+ break loop;
+ case C_CHAR :
+ length = CHAR.length;
+ System.arraycopy(CHAR, 0, dest, index, length);
+ index += length;
+ break loop;
+ case C_DOUBLE :
+ length = DOUBLE.length;
+ System.arraycopy(DOUBLE, 0, dest, index, length);
+ index += length;
+ break loop;
+ case C_FLOAT :
+ length = FLOAT.length;
+ System.arraycopy(FLOAT, 0, dest, index, length);
+ index += length;
+ break loop;
+ case C_INT :
+ length = INT.length;
+ System.arraycopy(INT, 0, dest, index, length);
+ index += length;
+ break loop;
+ case C_LONG :
+ length = LONG.length;
+ System.arraycopy(LONG, 0, dest, index, length);
+ index += length;
+ break loop;
+ case C_SHORT :
+ length = SHORT.length;
+ System.arraycopy(SHORT, 0, dest, index, length);
+ index += length;
+ break loop;
+ case C_VOID :
+ length = VOID.length;
+ System.arraycopy(VOID, 0, dest, index, length);
+ index += length;
+ break loop;
+ case C_RESOLVED :
+ case C_UNRESOLVED :
+ int end = CharOperation.indexOf(C_SEMICOLON, signature, sigPos);
+ if (end == -1) throw new IllegalArgumentException();
+ int start;
+ if (fullyQualifyTypeNames) {
+ start = sigPos;
+ } else {
+ start = CharOperation.lastIndexOf(C_DOT, signature, sigPos, end)+1;
+ if (start == 0) start = sigPos;
+ }
+ length = end-start;
+ System.arraycopy(signature, start, dest, index, length);
+ sigPos = end+1;
+ index += length;
+ break loop;
+ }
+ }
+ while (arrayCount-- > 0) {
+ dest[index++] = '[';
+ dest[index++] = ']';
+ }
+ return (((long) index) << 32) + sigPos;
+}
+/**
+ * Creates a new type signature with the given amount of array nesting added
+ * to the given type signature.
+ *
+ * @param typeSignature the type signature
+ * @param arrayCount the desired number of levels of array nesting
+ * @return the encoded array type signature
+ *
+ * @since 2.0
+ */
+public static char[] createArraySignature(char[] typeSignature, int arrayCount) {
+ if (arrayCount == 0) return typeSignature;
+ int sigLength = typeSignature.length;
+ char[] result = new char[arrayCount + sigLength];
+ for (int i = 0; i < arrayCount; i++) {
+ result[i] = C_ARRAY;
+ }
+ System.arraycopy(typeSignature, 0, result, arrayCount, sigLength);
+ return result;
+}
+/**
+ * Creates a new type signature with the given amount of array nesting added
+ * to the given type signature.
+ *
+ * @param typeSignature the type signature
+ * @param arrayCount the desired number of levels of array nesting
+ * @return the encoded array type signature
+ */
+public static String createArraySignature(String typeSignature, int arrayCount) {
+ return new String(createArraySignature(typeSignature.toCharArray(), arrayCount));
+}
+/**
+ * Creates a method signature from the given parameter and return type
+ * signatures. The encoded method signature is dot-based.
+ *
+ * @param parameterTypes the list of parameter type signatures
+ * @param returnType the return type signature
+ * @return the encoded method signature
+ *
+ * @since 2.0
+ */
+public static char[] createMethodSignature(char[][] parameterTypes, char[] returnType) {
+ int parameterTypesLength = parameterTypes.length;
+ int parameterLength = 0;
+ for (int i = 0; i < parameterTypesLength; i++) {
+ parameterLength += parameterTypes[i].length;
+
+ }
+ int returnTypeLength = returnType.length;
+ char[] result = new char[1 + parameterLength + 1 + returnTypeLength];
+ result[0] = C_PARAM_START;
+ int index = 1;
+ for (int i = 0; i < parameterTypesLength; i++) {
+ char[] parameterType = parameterTypes[i];
+ int length = parameterType.length;
+ System.arraycopy(parameterType, 0, result, index, length);
+ index += length;
+ }
+ result[index] = C_PARAM_END;
+ System.arraycopy(returnType, 0, result, index+1, returnTypeLength);
+ return result;
+}
+/**
+ * Creates a method signature from the given parameter and return type
+ * signatures. The encoded method signature is dot-based.
+ *
+ * @param parameterTypes the list of parameter type signatures
+ * @param returnType the return type signature
+ * @return the encoded method signature
+ */
+public static String createMethodSignature(String[] parameterTypes, String returnType) {
+ int parameterTypesLenth = parameterTypes.length;
+ char[][] parameters = new char[parameterTypesLenth][];
+ for (int i = 0; i < parameterTypesLenth; i++) {
+ parameters[i] = parameterTypes[i].toCharArray();
+ }
+ return new String(createMethodSignature(parameters, returnType.toCharArray()));
+}
+/**
+ * Creates a new type signature from the given type name encoded as a character
+ * array. This method is equivalent to
+ * createTypeSignature(new String(typeName),isResolved)
, although
+ * more efficient for callers with character arrays rather than strings. If the
+ * type name is qualified, then it is expected to be dot-based.
+ *
+ * @param typeName the possibly qualified type name
+ * @param isResolved true
if the type name is to be considered
+ * resolved (for example, a type name from a binary class file), and
+ * false
if the type name is to be considered unresolved
+ * (for example, a type name found in source code)
+ * @return the encoded type signature
+ * @see #createTypeSignature(java.lang.String,boolean)
+ */
+public static String createTypeSignature(char[] typeName, boolean isResolved) {
+ return new String(createCharArrayTypeSignature(typeName, isResolved));
+}
+/**
+ * Creates a new type signature from the given type name encoded as a character
+ * array. This method is equivalent to
+ * createTypeSignature(new String(typeName),isResolved).toCharArray()
, although
+ * more efficient for callers with character arrays rather than strings. If the
+ * type name is qualified, then it is expected to be dot-based.
+ *
+ * @param typeName the possibly qualified type name
+ * @param isResolved true
if the type name is to be considered
+ * resolved (for example, a type name from a binary class file), and
+ * false
if the type name is to be considered unresolved
+ * (for example, a type name found in source code)
+ * @return the encoded type signature
+ * @see #createTypeSignature(java.lang.String,boolean)
+ *
+ * @since 2.0
+ */
+public static char[] createCharArrayTypeSignature(char[] typeName, boolean isResolved) {
+
+ if (typeName == null) throw new IllegalArgumentException("null"); //$NON-NLS-1$
+ int length = typeName.length;
+ if (length == 0) throw new IllegalArgumentException(new String(typeName));
+
+ int arrayCount = CharOperation.occurencesOf('[', typeName);
+ char[] sig;
+
+ switch (typeName[0]) {
+ // primitive type?
+ case 'b' :
+ if (CharOperation.fragmentEquals(BOOLEAN, typeName, 0, true)) {
+ sig = new char[arrayCount+1];
+ sig[arrayCount] = C_BOOLEAN;
+ break;
+ } else if (CharOperation.fragmentEquals(BYTE, typeName, 0, true)) {
+ sig = new char[arrayCount+1];
+ sig[arrayCount] = C_BYTE;
+ break;
+ }
+ case 'c':
+ if (CharOperation.fragmentEquals(CHAR, typeName, 0, true)) {
+ sig = new char[arrayCount+1];
+ sig[arrayCount] = C_CHAR;
+ break;
+ }
+ case 'd':
+ if (CharOperation.fragmentEquals(DOUBLE, typeName, 0, true)) {
+ sig = new char[arrayCount+1];
+ sig[arrayCount] = C_DOUBLE;
+ break;
+ }
+ case 'f':
+ if (CharOperation.fragmentEquals(FLOAT, typeName, 0, true)) {
+ sig = new char[arrayCount+1];
+ sig[arrayCount] = C_FLOAT;
+ break;
+ }
+ case 'i':
+ if (CharOperation.fragmentEquals(INT, typeName, 0, true)) {
+ sig = new char[arrayCount+1];
+ sig[arrayCount] = C_INT;
+ break;
+ }
+ case 'l':
+ if (CharOperation.fragmentEquals(LONG, typeName, 0, true)) {
+ sig = new char[arrayCount+1];
+ sig[arrayCount] = C_LONG;
+ break;
+ }
+ case 's':
+ if (CharOperation.fragmentEquals(SHORT, typeName, 0, true)) {
+ sig = new char[arrayCount+1];
+ sig[arrayCount] = C_SHORT;
+ break;
+ }
+ case 'v':
+ if (CharOperation.fragmentEquals(VOID, typeName, 0, true)) {
+ sig = new char[arrayCount+1];
+ sig[arrayCount] = C_VOID;
+ break;
+ }
+ default:
+ // non primitive type
+ int sigLength = arrayCount + 1 + length + 1; // for example '[[[Ljava.lang.String;'
+ sig = new char[sigLength];
+ int sigIndex = arrayCount+1; // index in sig
+ int startID = 0; // start of current ID in typeName
+ int index = 0; // index in typeName
+ while (index < length) {
+ char currentChar = typeName[index];
+ switch (currentChar) {
+ case '.':
+ if (startID == -1) throw new IllegalArgumentException(new String(typeName));
+ if (startID < index) {
+ sig = CharOperation.append(sig, sigIndex, typeName, startID, index);
+ sigIndex += index-startID;
+ }
+ sig[sigIndex++] = C_DOT;
+ index++;
+ startID = index;
+ break;
+ case '[':
+ if (startID != -1) {
+ if (startID < index) {
+ sig = CharOperation.append(sig, sigIndex, typeName, startID, index);
+ sigIndex += index-startID;
+ }
+ startID = -1; // no more id after []
+ }
+ index++;
+ break;
+ default :
+ if (startID != -1 && CharOperation.isWhitespace(currentChar)) {
+ if (startID < index) {
+ sig = CharOperation.append(sig, sigIndex, typeName, startID, index);
+ sigIndex += index-startID;
+ }
+ startID = index+1;
+ }
+ index++;
+ break;
+ }
+ }
+ // last id
+ if (startID != -1 && startID < index) {
+ sig = CharOperation.append(sig, sigIndex, typeName, startID, index);
+ sigIndex += index-startID;
+ }
+
+ // add L (or Q) at the beigininig and ; at the end
+ sig[arrayCount] = isResolved ? C_RESOLVED : C_UNRESOLVED;
+ sig[sigIndex++] = C_NAME_END;
+
+ // resize if needed
+ if (sigLength > sigIndex) {
+ System.arraycopy(sig, 0, sig = new char[sigIndex], 0, sigIndex);
+ }
+ }
+
+ // add array info
+ for (int i = 0; i < arrayCount; i++) {
+ sig[i] = C_ARRAY;
+ }
+
+ return sig;
+}
+/**
+ * Creates a new type signature from the given type name. If the type name is qualified,
+ * then it is expected to be dot-based.
+ * + * For example: + *
+ *
+ * createTypeSignature("int", hucairz) -> "I"
+ * createTypeSignature("java.lang.String", true) -> "Ljava.lang.String;"
+ * createTypeSignature("String", false) -> "QString;"
+ * createTypeSignature("java.lang.String", false) -> "Qjava.lang.String;"
+ * createTypeSignature("int []", false) -> "[I"
+ *
+ *
+ *
+ *
+ * @param typeName the possibly qualified type name
+ * @param isResolved true
if the type name is to be considered
+ * resolved (for example, a type name from a binary class file), and
+ * false
if the type name is to be considered unresolved
+ * (for example, a type name found in source code)
+ * @return the encoded type signature
+ */
+public static String createTypeSignature(String typeName, boolean isResolved) {
+ return createTypeSignature(typeName == null ? null : typeName.toCharArray(), isResolved);
+}
+/**
+ * Returns the array count (array nesting depth) of the given type signature.
+ *
+ * @param typeSignature the type signature
+ * @return the array nesting depth, or 0 if not an array
+ * @exception IllegalArgumentException if the signature is not syntactically
+ * correct
+ *
+ * @since 2.0
+ */
+public static int getArrayCount(char[] typeSignature) throws IllegalArgumentException {
+ try {
+ int count = 0;
+ while (typeSignature[count] == C_ARRAY) {
+ ++count;
+ }
+ return count;
+ } catch (ArrayIndexOutOfBoundsException e) { // signature is syntactically incorrect if last character is C_ARRAY
+ throw new IllegalArgumentException();
+ }
+}
+/**
+ * Returns the array count (array nesting depth) of the given type signature.
+ *
+ * @param typeSignature the type signature
+ * @return the array nesting depth, or 0 if not an array
+ * @exception IllegalArgumentException if the signature is not syntactically
+ * correct
+ */
+public static int getArrayCount(String typeSignature) throws IllegalArgumentException {
+ return getArrayCount(typeSignature.toCharArray());
+}
+/**
+ * Returns the type signature without any array nesting.
+ * + * For example: + *
+ *
+ * getElementType({'[', '[', 'I'}) --> {'I'}.
+ *
+ *
+ *
+ *
+ * @param typeSignature the type signature
+ * @return the type signature without arrays
+ * @exception IllegalArgumentException if the signature is not syntactically
+ * correct
+ *
+ * @since 2.0
+ */
+public static char[] getElementType(char[] typeSignature) throws IllegalArgumentException {
+ int count = getArrayCount(typeSignature);
+ if (count == 0) return typeSignature;
+ int length = typeSignature.length;
+ char[] result = new char[length-count];
+ System.arraycopy(typeSignature, count, result, 0, length-count);
+ return result;
+}
+/**
+ * Returns the type signature without any array nesting.
+ * + * For example: + *
+ *
+ * getElementType("[[I") --> "I".
+ *
+ *
+ *
+ *
+ * @param typeSignature the type signature
+ * @return the type signature without arrays
+ * @exception IllegalArgumentException if the signature is not syntactically
+ * correct
+ */
+public static String getElementType(String typeSignature) throws IllegalArgumentException {
+ return new String(getElementType(typeSignature.toCharArray()));
+}
+/**
+ * Returns the number of parameter types in the given method signature.
+ *
+ * @param methodSignature the method signature
+ * @return the number of parameters
+ * @exception IllegalArgumentException if the signature is not syntactically
+ * correct
+ * @since 2.0
+ */
+public static int getParameterCount(char[] methodSignature) throws IllegalArgumentException {
+ try {
+ int count = 0;
+ int i = CharOperation.indexOf(C_PARAM_START, methodSignature) + 1;
+ if (i == 0)
+ throw new IllegalArgumentException();
+ for (;;) {
+ char c = methodSignature[i++];
+ switch (c) {
+ case C_ARRAY :
+ break;
+ case C_BOOLEAN :
+ case C_BYTE :
+ case C_CHAR :
+ case C_DOUBLE :
+ case C_FLOAT :
+ case C_INT :
+ case C_LONG :
+ case C_SHORT :
+ case C_VOID :
+ ++count;
+ break;
+ case C_RESOLVED :
+ case C_UNRESOLVED :
+ i = CharOperation.indexOf(C_SEMICOLON, methodSignature, i) + 1;
+ if (i == 0)
+ throw new IllegalArgumentException();
+ ++count;
+ break;
+ case C_PARAM_END :
+ return count;
+ default :
+ throw new IllegalArgumentException();
+ }
+ }
+ } catch (ArrayIndexOutOfBoundsException e) {
+ throw new IllegalArgumentException();
+ }
+}
+/**
+ * Returns the number of parameter types in the given method signature.
+ *
+ * @param methodSignature the method signature
+ * @return the number of parameters
+ * @exception IllegalArgumentException if the signature is not syntactically
+ * correct
+ */
+public static int getParameterCount(String methodSignature) throws IllegalArgumentException {
+ return getParameterCount(methodSignature.toCharArray());
+}
+/**
+ * Extracts the parameter type signatures from the given method signature.
+ * The method signature is expected to be dot-based.
+ *
+ * @param methodSignature the method signature
+ * @return the list of parameter type signatures
+ * @exception IllegalArgumentException if the signature is syntactically
+ * incorrect
+ *
+ * @since 2.0
+ */
+public static char[][] getParameterTypes(char[] methodSignature) throws IllegalArgumentException {
+ try {
+ int count = getParameterCount(methodSignature);
+ char[][] result = new char[count][];
+ if (count == 0)
+ return result;
+ int i = CharOperation.indexOf(C_PARAM_START, methodSignature) + 1;
+ count = 0;
+ int start = i;
+ for (;;) {
+ char c = methodSignature[i++];
+ switch (c) {
+ case C_ARRAY :
+ // array depth is i - start;
+ break;
+ case C_BOOLEAN :
+ case C_BYTE :
+ case C_CHAR :
+ case C_DOUBLE :
+ case C_FLOAT :
+ case C_INT :
+ case C_LONG :
+ case C_SHORT :
+ case C_VOID :
+ // common case of base types
+ if (i - start == 1) {
+ switch (c) {
+ case C_BOOLEAN :
+ result[count++] = new char[] {C_BOOLEAN};
+ break;
+ case C_BYTE :
+ result[count++] = new char[] {C_BYTE};
+ break;
+ case C_CHAR :
+ result[count++] = new char[] {C_CHAR};
+ break;
+ case C_DOUBLE :
+ result[count++] = new char[] {C_DOUBLE};
+ break;
+ case C_FLOAT :
+ result[count++] = new char[] {C_FLOAT};
+ break;
+ case C_INT :
+ result[count++] = new char[] {C_INT};
+ break;
+ case C_LONG :
+ result[count++] = new char[] {C_LONG};
+ break;
+ case C_SHORT :
+ result[count++] = new char[] {C_SHORT};
+ break;
+ case C_VOID :
+ result[count++] = new char[] {C_VOID};
+ break;
+ }
+ } else {
+ result[count++] = CharOperation.subarray(methodSignature, start, i);
+ }
+ start = i;
+ break;
+ case C_RESOLVED :
+ case C_UNRESOLVED :
+ i = CharOperation.indexOf(C_SEMICOLON, methodSignature, i) + 1;
+ if (i == 0)
+ throw new IllegalArgumentException();
+ result[count++] = CharOperation.subarray(methodSignature, start, i);
+ start = i;
+ break;
+ case C_PARAM_END:
+ return result;
+ default :
+ throw new IllegalArgumentException();
+ }
+ }
+ } catch (ArrayIndexOutOfBoundsException e) {
+ throw new IllegalArgumentException();
+ }
+}
+/**
+ * Extracts the parameter type signatures from the given method signature.
+ * The method signature is expected to be dot-based.
+ *
+ * @param methodSignature the method signature
+ * @return the list of parameter type signatures
+ * @exception IllegalArgumentException if the signature is syntactically
+ * incorrect
+ */
+public static String[] getParameterTypes(String methodSignature) throws IllegalArgumentException {
+ char[][] parameterTypes = getParameterTypes(methodSignature.toCharArray());
+ int length = parameterTypes.length;
+ String[] result = new String[length];
+ for (int i = 0; i < length; i++) {
+ result[i] = new String(parameterTypes[i]);
+ }
+ return result;
+}
+/**
+ * Returns a char array containing all but the last segment of the given
+ * dot-separated qualified name. Returns the empty char array if it is not qualified.
+ * + * For example: + *
+ *
+ * getQualifier({'j', 'a', 'v', 'a', '.', 'l', 'a', 'n', 'g', '.', 'O', 'b', 'j', 'e', 'c', 't'}) -> {'j', 'a', 'v', 'a', '.', 'l', 'a', 'n', 'g'}
+ * getQualifier({'O', 'u', 't', 'e', 'r', '.', 'I', 'n', 'n', 'e', 'r'}) -> {'O', 'u', 't', 'e', 'r'}
+ *
+ *
+ *
+ *
+ * @param name the name
+ * @return the qualifier prefix, or the empty char array if the name contains no
+ * dots
+ * @exception NullPointerException if name is null
+ * @since 2.0
+ */
+public static char[] getQualifier(char[] name) {
+ int lastDot = CharOperation.lastIndexOf(C_DOT, name);
+ if (lastDot == -1) {
+ return CharOperation.NO_CHAR;
+ }
+ return CharOperation.subarray(name, 0, lastDot);
+}
+/**
+ * Returns a string containing all but the last segment of the given
+ * dot-separated qualified name. Returns the empty string if it is not qualified.
+ * + * For example: + *
+ *
+ * getQualifier("java.lang.Object") -> "java.lang"
+ * getQualifier("Outer.Inner") -> "Outer"
+ *
+ *
+ *
+ *
+ * @param name the name
+ * @return the qualifier prefix, or the empty string if the name contains no
+ * dots
+ * @exception NullPointerException if name is null
+ */
+public static String getQualifier(String name) {
+ int lastDot = name.lastIndexOf(C_DOT);
+ if (lastDot == -1) {
+ return EMPTY;
+ }
+ return name.substring(0, lastDot);
+}
+/**
+ * Extracts the return type from the given method signature. The method signature is
+ * expected to be dot-based.
+ *
+ * @param methodSignature the method signature
+ * @return the type signature of the return type
+ * @exception IllegalArgumentException if the signature is syntactically
+ * incorrect
+ *
+ * @since 2.0
+ */
+public static char[] getReturnType(char[] methodSignature) throws IllegalArgumentException {
+ int i = CharOperation.lastIndexOf(C_PARAM_END, methodSignature);
+ if (i == -1) {
+ throw new IllegalArgumentException();
+ }
+ return CharOperation.subarray(methodSignature, i + 1, methodSignature.length);
+}
+/**
+ * Extracts the return type from the given method signature. The method signature is
+ * expected to be dot-based.
+ *
+ * @param methodSignature the method signature
+ * @return the type signature of the return type
+ * @exception IllegalArgumentException if the signature is syntactically
+ * incorrect
+ */
+public static String getReturnType(String methodSignature) throws IllegalArgumentException {
+ return new String(getReturnType(methodSignature.toCharArray()));
+}
+/**
+ * Returns the last segment of the given dot-separated qualified name.
+ * Returns the given name if it is not qualified.
+ * + * For example: + *
+ *
+ * getSimpleName({'j', 'a', 'v', 'a', '.', 'l', 'a', 'n', 'g', '.', 'O', 'b', 'j', 'e', 'c', 't'}) -> {'O', 'b', 'j', 'e', 'c', 't'}
+ *
+ *
+ *
+ *
+ * @param name the name
+ * @return the last segment of the qualified name
+ * @exception NullPointerException if name is null
+ * @since 2.0
+ */
+public static char[] getSimpleName(char[] name) {
+ int lastDot = CharOperation.lastIndexOf(C_DOT, name);
+ if (lastDot == -1) {
+ return name;
+ }
+ return CharOperation.subarray(name, lastDot + 1, name.length);
+}
+/**
+ * Returns the last segment of the given dot-separated qualified name.
+ * Returns the given name if it is not qualified.
+ * + * For example: + *
+ *
+ * getSimpleName("java.lang.Object") -> "Object"
+ *
+ *
+ *
+ *
+ * @param name the name
+ * @return the last segment of the qualified name
+ * @exception NullPointerException if name is null
+ */
+public static String getSimpleName(String name) {
+ int lastDot = name.lastIndexOf(C_DOT);
+ if (lastDot == -1) {
+ return name;
+ }
+ return name.substring(lastDot + 1, name.length());
+}
+/**
+ * Returns all segments of the given dot-separated qualified name.
+ * Returns an array with only the given name if it is not qualified.
+ * Returns an empty array if the name is empty.
+ * + * For example: + *
+ *
+ * getSimpleNames({'j', 'a', 'v', 'a', '.', 'l', 'a', 'n', 'g', '.', 'O', 'b', 'j', 'e', 'c', 't'}) -> {{'j', 'a', 'v', 'a'}, {'l', 'a', 'n', 'g'}, {'O', 'b', 'j', 'e', 'c', 't'}}
+ * getSimpleNames({'O', 'b', 'j', 'e', 'c', 't'}) -> {{'O', 'b', 'j', 'e', 'c', 't'}}
+ * getSimpleNames("") -> {}
+ *
+ *
+ *
+ * @param name the name
+ * @return the list of simple names, possibly empty
+ * @exception NullPointerException if name is null
+ * @since 2.0
+ */
+public static char[][] getSimpleNames(char[] name) {
+ if (name.length == 0) {
+ return CharOperation.NO_CHAR_CHAR;
+ }
+ int dot = CharOperation.indexOf(C_DOT, name);
+ if (dot == -1) {
+ return new char[][] {name};
+ }
+ int n = 1;
+ while ((dot = CharOperation.indexOf(C_DOT, name, dot + 1)) != -1) {
+ ++n;
+ }
+ char[][] result = new char[n + 1][];
+ int segStart = 0;
+ for (int i = 0; i < n; ++i) {
+ dot = CharOperation.indexOf(C_DOT, name, segStart);
+ result[i] = CharOperation.subarray(name, segStart, dot);
+ segStart = dot + 1;
+ }
+ result[n] = CharOperation.subarray(name, segStart, name.length);
+ return result;
+}
+/**
+ * Returns all segments of the given dot-separated qualified name.
+ * Returns an array with only the given name if it is not qualified.
+ * Returns an empty array if the name is empty.
+ * + * For example: + *
+ *
+ * getSimpleNames("java.lang.Object") -> {"java", "lang", "Object"}
+ * getSimpleNames("Object") -> {"Object"}
+ * getSimpleNames("") -> {}
+ *
+ *
+ *
+ * @param name the name
+ * @return the list of simple names, possibly empty
+ * @exception NullPointerException if name is null
+ */
+public static String[] getSimpleNames(String name) {
+ char[][] simpleNames = getSimpleNames(name.toCharArray());
+ int length = simpleNames.length;
+ String[] result = new String[length];
+ for (int i = 0; i < length; i++) {
+ result[i] = new String(simpleNames[i]);
+ }
+ return result;
+}
+/**
+ * Converts the given method signature to a readable form. The method signature is expected to
+ * be dot-based.
+ * + * For example: + *
+ *
+ * toString("([Ljava.lang.String;)V", "main", new String[] {"args"}, false, true) -> "void main(String[] args)"
+ *
+ *
+ *
+ *
+ * @param methodSignature the method signature to convert
+ * @param methodName the name of the method to insert in the result, or
+ * null
if no method name is to be included
+ * @param parameterNames the parameter names to insert in the result, or
+ * null
if no parameter names are to be included; if supplied,
+ * the number of parameter names must match that of the method signature
+ * @param fullyQualifyTypeNames true
if type names should be fully
+ * qualified, and false
to use only simple names
+ * @param includeReturnType true
if the return type is to be
+ * included
+ * @return the char array representation of the method signature
+ *
+ * @since 2.0
+ */
+public static char[] toCharArray(char[] methodSignature, char[] methodName, char[][] parameterNames, boolean fullyQualifyTypeNames, boolean includeReturnType) {
+ try {
+ int firstParen = CharOperation.indexOf(C_PARAM_START, methodSignature);
+ if (firstParen == -1) throw new IllegalArgumentException();
+
+ int sigLength = methodSignature.length;
+
+ // compute result length
+
+ // method signature
+ int paramCount = 0;
+ int lastParen = -1;
+ int resultLength = 0;
+ signature: for (int i = firstParen; i < sigLength; i++) {
+ switch (methodSignature[i]) {
+ case C_ARRAY :
+ resultLength += 2; // []
+ continue signature;
+ case C_BOOLEAN :
+ resultLength += BOOLEAN.length;
+ break;
+ case C_BYTE :
+ resultLength += BYTE.length;
+ break;
+ case C_CHAR :
+ resultLength += CHAR.length;
+ break;
+ case C_DOUBLE :
+ resultLength += DOUBLE.length;
+ break;
+ case C_FLOAT :
+ resultLength += FLOAT.length;
+ break;
+ case C_INT :
+ resultLength += INT.length;
+ break;
+ case C_LONG :
+ resultLength += LONG.length;
+ break;
+ case C_SHORT :
+ resultLength += SHORT.length;
+ break;
+ case C_VOID :
+ resultLength += VOID.length;
+ break;
+ case C_RESOLVED :
+ case C_UNRESOLVED :
+ int end = CharOperation.indexOf(C_SEMICOLON, methodSignature, i);
+ if (end == -1) throw new IllegalArgumentException();
+ int start;
+ if (fullyQualifyTypeNames) {
+ start = i+1;
+ } else {
+ start = CharOperation.lastIndexOf(C_DOT, methodSignature, i, end) + 1;
+ if (start == 0) start = i+1;
+ }
+ resultLength += end-start;
+ i = end;
+ break;
+ case C_PARAM_START :
+ // add space for "("
+ resultLength++;
+ continue signature;
+ case C_PARAM_END :
+ lastParen = i;
+ if (includeReturnType) {
+ if (paramCount > 0) {
+ // remove space for ", " that was added with last parameter and remove space that is going to be added for ", " after return type
+ // and add space for ") "
+ resultLength -= 2;
+ } //else
+ // remove space that is going to be added for ", " after return type
+ // and add space for ") "
+ // -> noop
+
+ // decrement param count because it is going to be added for return type
+ paramCount--;
+ continue signature;
+ } else {
+ if (paramCount > 0) {
+ // remove space for ", " that was added with last parameter and add space for ")"
+ resultLength--;
+ } else {
+ // add space for ")"
+ resultLength++;
+ }
+ break signature;
+ }
+ default :
+ throw new IllegalArgumentException();
+ }
+ resultLength += 2; // add space for ", "
+ paramCount++;
+ }
+
+ // parameter names
+ int parameterNamesLength = parameterNames == null ? 0 : parameterNames.length;
+ for (int i = 0; i + * For example: + *
+ *
+ * toString({'[', 'L', 'j', 'a', 'v', 'a', '.', 'l', 'a', 'n', 'g', '.', 'S', 't', 'r', 'i', 'n', 'g', ';'}) -> {'j', 'a', 'v', 'a', '.', 'l', 'a', 'n', 'g', '.', 'S', 't', 'r', 'i', 'n', 'g', '[', ']'}
+ * toString({'I'}) -> {'i', 'n', 't'}
+ *
+ *
+ *
+ *
+ * Note: This method assumes that a type signature containing a '$'
+ * is an inner type signature. While this is correct in most cases, someone could
+ * define a non-inner type name containing a '$'
. Handling this
+ * correctly in all cases would have required resolving the signature, which
+ * generally not feasible.
+ *
+ * For example: + *
+ *
+ * toQualifiedName({{'j', 'a', 'v', 'a'}, {'l', 'a', 'n', 'g'}, {'O', 'b', 'j', 'e', 'c', 't'}}) -> {'j', 'a', 'v', 'a', '.', 'l', 'a', 'n', 'g', '.', 'O', 'b', 'j', 'e', 'c', 't'}
+ * toQualifiedName({{'O', 'b', 'j', 'e', 'c', 't'}}) -> {'O', 'b', 'j', 'e', 'c', 't'}
+ * toQualifiedName({{}}) -> {}
+ *
+ *
+ *
+ *
+ * @param segments the list of name segments, possibly empty
+ * @return the dot-separated qualified name, or the empty string
+ *
+ * @since 2.0
+ */
+public static char[] toQualifiedName(char[][] segments) {
+ int length = segments.length;
+ if (length == 0) return CharOperation.NO_CHAR;
+ if (length == 1) return segments[0];
+
+ int resultLength = 0;
+ for (int i = 0; i < length; i++) {
+ resultLength += segments[i].length+1;
+ }
+ resultLength--;
+ char[] result = new char[resultLength];
+ int index = 0;
+ for (int i = 0; i < length; i++) {
+ char[] segment = segments[i];
+ int segmentLength = segment.length;
+ System.arraycopy(segment, 0, result, index, segmentLength);
+ index += segmentLength;
+ if (i != length-1) {
+ result[index++] = C_DOT;
+ }
+ }
+ return result;
+}
+/**
+ * Converts the given array of qualified name segments to a qualified name.
+ * + * For example: + *
+ *
+ * toQualifiedName(new String[] {"java", "lang", "Object"}) -> "java.lang.Object"
+ * toQualifiedName(new String[] {"Object"}) -> "Object"
+ * toQualifiedName(new String[0]) -> ""
+ *
+ *
+ *
+ *
+ * @param segments the list of name segments, possibly empty
+ * @return the dot-separated qualified name, or the empty string
+ */
+public static String toQualifiedName(String[] segments) {
+ int length = segments.length;
+ char[][] charArrays = new char[length][];
+ for (int i = 0; i < length; i++) {
+ charArrays[i] = segments[i].toCharArray();
+ }
+ return new String(toQualifiedName(charArrays));
+}
+/**
+ * Converts the given type signature to a readable string. The signature is expected to
+ * be dot-based.
+ *
+ * + * For example: + *
+ *
+ * toString("[Ljava.lang.String;") -> "java.lang.String[]"
+ * toString("I") -> "int"
+ *
+ *
+ *
+ *
+ * Note: This method assumes that a type signature containing a '$'
+ * is an inner type signature. While this is correct in most cases, someone could
+ * define a non-inner type name containing a '$'
. Handling this
+ * correctly in all cases would have required resolving the signature, which
+ * generally not feasible.
+ *
+ * For example: + *
+ *
+ * toString("([Ljava.lang.String;)V", "main", new String[] {"args"}, false, true) -> "void main(String[] args)"
+ *
+ *
+ *
+ *
+ * @param methodSignature the method signature to convert
+ * @param methodName the name of the method to insert in the result, or
+ * null
if no method name is to be included
+ * @param parameterNames the parameter names to insert in the result, or
+ * null
if no parameter names are to be included; if supplied,
+ * the number of parameter names must match that of the method signature
+ * @param fullyQualifyTypeNames true
if type names should be fully
+ * qualified, and false
to use only simple names
+ * @param includeReturnType true
if the return type is to be
+ * included
+ * @return the string representation of the method signature
+ */
+public static String toString(String methodSignature, String methodName, String[] parameterNames, boolean fullyQualifyTypeNames, boolean includeReturnType) {
+ char[][] params;
+ if (parameterNames == null) {
+ params = null;
+ } else {
+ int paramLength = parameterNames.length;
+ params = new char[paramLength][];
+ for (int i = 0; i < paramLength; i++) {
+ params[i] = parameterNames[i].toCharArray();
+ }
+ }
+ return new String(toCharArray(methodSignature.toCharArray(), methodName == null ? null : methodName.toCharArray(), params, fullyQualifyTypeNames, includeReturnType));
+}
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/compiler/IProblem.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/compiler/IProblem.java
deleted file mode 100644
index 903396b..0000000
--- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/compiler/IProblem.java
+++ /dev/null
@@ -1,519 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2002 IBM Corp. and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Common Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/cpl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- * IBM Corporation - added the following constants
- * NonStaticAccessToStaticField
- * NonStaticAccessToStaticMethod
- * Task
- * NoOpAssignment
- * IBM Corporation - added the following constants
- * TooManySyntheticArgumentSlots
- * TooManyArrayDimensions
- * TooManyBytesForStringConstant
- * TooManyMethods
- * TooManyFields
- * NonBlankFinalLocalAssignment
- * ObjectCannotHaveSuperTypes
- * MissingSemiColon
- * InvalidExpressionAsName
- ****************************************************************************/
-package net.sourceforge.phpdt.core.compiler;
-
-import net.sourceforge.phpdt.internal.compiler.lookup.ProblemReasons;
-
-/**
- * Description of a Java problem, as detected by the compiler or some of the underlying
- * technology reusing the compiler.
- * A problem provides access to:
- * IDOMFactory
, and the only means
+ * of creating JDOMs and document fragments.
+ * + * This class may be instantiated; it is not intended to be subclassed. + *
+ */ +public class DOMFactory implements IDOMFactory { +/** + * Creates a new DOM factory. + */ +public DOMFactory() {} +/* (non-Javadoc) + * Method declared on IDOMFactory. + */ +public IDOMCompilationUnit createCompilationUnit() { + return (new DOMBuilder()).createCompilationUnit(); +} +/* (non-Javadoc) + * Method declared on IDOMFactory. + */ +public IDOMCompilationUnit createCompilationUnit(char[] sourceCode, String name) { + if(sourceCode == null) { + return null; + } + return (new SimpleDOMBuilder()).createCompilationUnit(sourceCode, name.toCharArray()); +} +/* (non-Javadoc) + * Method declared on IDOMFactory. + */ +public IDOMCompilationUnit createCompilationUnit(String sourceCode, String name) { + if(sourceCode == null) { + return null; + } + return (new SimpleDOMBuilder()).createCompilationUnit(sourceCode.toCharArray(), name.toCharArray()); +} +/* (non-Javadoc) + * Method declared on IDOMFactory. + */ +//public IDOMField createField() { +// return createField("Object aField;"+ Util.LINE_SEPARATOR); //$NON-NLS-1$ +//} +///* (non-Javadoc) +// * Method declared on IDOMFactory. +// */ +//public IDOMField createField(String sourceCode) { +// if(sourceCode == null) { +// return null; +// } +// return (new DOMBuilder()).createField(sourceCode.toCharArray()); +//} +/* (non-Javadoc) + * Method declared on IDOMFactory. + */ +//public IDOMImport createImport() { +// return (new DOMBuilder()).createImport(); +//} +///* (non-Javadoc) +// * Method declared on IDOMFactory. +// */ +//public IDOMImport createImport(String sourceCode) { +// if(sourceCode == null) { +// return null; +// } +// return (new DOMBuilder()).createImport(sourceCode.toCharArray()); +//} +/* (non-Javadoc) + * Method declared on IDOMFactory. + */ +//public IDOMInitializer createInitializer() { +// return createInitializer("static {}"+ Util.LINE_SEPARATOR); //$NON-NLS-1$ +//} +///* (non-Javadoc) +// * Method declared on IDOMFactory. +// */ +//public IDOMInitializer createInitializer(String sourceCode) { +// if(sourceCode == null) { +// return null; +// } +// return (new DOMBuilder()).createInitializer(sourceCode.toCharArray()); +//} +/* (non-Javadoc) + * Method declared on IDOMFactory. + */ +//public IDOMMethod createMethod() { +// return createMethod("public void newMethod() {"+ Util.LINE_SEPARATOR+"}"+ Util.LINE_SEPARATOR); //$NON-NLS-2$ //$NON-NLS-1$ +//} +///* (non-Javadoc) +// * Method declared on IDOMFactory. +// */ +//public IDOMMethod createMethod(String sourceCode) { +// if(sourceCode == null) { +// return null; +// } +// return (new DOMBuilder()).createMethod(sourceCode.toCharArray()); +//} +/* (non-Javadoc) + * Method declared on IDOMFactory. + */ +public IDOMPackage createPackage() { + return (new DOMBuilder()).createPackage(); +} +/* (non-Javadoc) + * Method declared on IDOMFactory. + */ +//public IDOMPackage createPackage(String sourceCode) { +// if(sourceCode == null) { +// return null; +// } +// return (new DOMBuilder()).createPackage(sourceCode.toCharArray()); +//} +///* (non-Javadoc) +// * Method declared on IDOMFactory. +// */ +//public IDOMType createType() { +// return createType("public class AClass {"+ Util.LINE_SEPARATOR +"}"+ Util.LINE_SEPARATOR); //$NON-NLS-2$ //$NON-NLS-1$ +//} +/* (non-Javadoc) + * Method declared on IDOMFactory. + */ +//public IDOMType createClass() { +// return createType("public class AClass {"+ Util.LINE_SEPARATOR +"}"+ Util.LINE_SEPARATOR); //$NON-NLS-2$ //$NON-NLS-1$ +//} +///* (non-Javadoc) +// * Method declared on IDOMFactory. +// */ +//public IDOMType createInterface() { +// return createType("public interface AnInterface {"+ Util.LINE_SEPARATOR +"}"+ Util.LINE_SEPARATOR); //$NON-NLS-2$ //$NON-NLS-1$ +//} +/* (non-Javadoc) + * Method declared on IDOMFactory. + */ +//public IDOMType createType(String sourceCode) { +// if(sourceCode == null) { +// return null; +// } +// return (new DOMBuilder()).createType(sourceCode.toCharArray()); +//} +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMCompilationUnit.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMCompilationUnit.java new file mode 100644 index 0000000..37f0537 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMCompilationUnit.java @@ -0,0 +1,64 @@ +/******************************************************************************* + * Copyright (c) 2000, 2003 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.core.jdom; + +/** + * Represents a Java compilation unit (.java
source file).
+ * The corresponding syntactic unit is CompilationUnit (JLS2 7.3).
+ * Allowable child types for a compilation unit are IDOMPackage
, IDOMImport
,
+ * and IDOMType
.
+ * + * This interface is not intended to be implemented by clients. + *
+ */ +public interface IDOMCompilationUnit extends IDOMNode { +/** + * Returns the header comment for this compilation unit. The header comment + * appears before the first declaration in a compilation unit. + * The syntax for a comment corresponds to Comments (JLS2 3.7), including + * comment delimiters. + * + * @return the header comment for this compilation unit, ornull
if
+ * no header comment is present
+ */
+public String getHeader();
+/**
+ * The IDOMCompilationNode
refinement of this IDOMNode
+ * method returns the name of this compilation unit.
+ *
+ * The name of a compilation unit is the name of the first top-level public type + * defined in the compilation unit, suffixed with ".java". For example, if the first + * top-level public type defined in this compilation unit has the name "Hanoi", + * then name of this compilation unit is "Hanoi.java".
+ * + *In the absence of a public top-level type, the name of the first top-level
+ * type is used. In the absence of any type, the name of the compilation unit
+ * is null
.
null
if none
+ */
+public String getName();
+/**
+ * Sets the header comment for this compilation unit. The header comment
+ * appears before the first declaration in a compilation unit.
+ * The syntax for a comment corresponds to Comments (JLS2 3.7), including
+ * comment delimiters.
+ *
+ * @param comment the header comment for this compilation unit, or null
if
+ * indicating no header comment
+ */
+public void setHeader(String comment);
+/**
+ * The IDOMCompilationNode
refinement of this IDOMNode
+ * method has no effect (the name is computed from the types declared within it).
+ */
+public void setName(String name);
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMFactory.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMFactory.java
new file mode 100644
index 0000000..eea0df1
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMFactory.java
@@ -0,0 +1,197 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.core.jdom;
+
+/**
+ * A factory used to create document fragment (DF) nodes. An
+ * IDOMCompilationUnit
represents the root of a complete JDOM (that
+ * is, a ".java" file). Other node types represent fragments of a compilation
+ * unit.
+ *
+ * The factory can be used to create empty DFs or it can create DFs from source
+ * strings. All DFs created empty are assigned default values as required, such
+ * that a call to IDOMNode.getContents
will generate a valid source
+ * string. See individual create
methods for details on the default
+ * values supplied. The factory does its best to recognize Java structures in
+ * the source provided. If the factory is completely unable to recognize source
+ * constructs, the factory method returns null
.
+ *
+ * Even if a DF is created successfully from source code, it does not guarantee + * that the source code will compile error free. Similarly, the contents of a DF + * are not guaranteed to compile error free. However, syntactically correct + * source code is guaranteed to be recognized and successfully generate a DF. + * Similarly, if all of the fragments of a JDOM are syntactically correct, the + * contents of the entire document will be correct too. + *
+ *+ * The factory does not perform or provide any code formatting. Document + * fragments created on source strings must be pre-formatted. The JDOM attempts + * to maintain the formatting of documents as best as possible. For this reason, + * document fragments created for nodes that are to be strung together should + * end with a new-line character. Failing to do so will result in a document + * that has elements strung together on the same line. This is especially + * important if a source string ends with a // comment. In this case, it would + * be syntactically incorrect to omit the new line character. + *
+ *+ * This interface is not intended to be implemented by clients. + *
+ * + * @see IDOMNode + */ +public interface IDOMFactory { +/** + * Creates and return an empty JDOM. The initial content is an empty string. + * + * @return the new compilation unit + */ +public IDOMCompilationUnit createCompilationUnit(); +/** + * Creates a JDOM on the given source code. The syntax for the given source + * code corresponds to CompilationUnit (JLS2 7.3). + * + * @param sourceCode the source code character array, ornull
+ * @param name the name of the compilation unit
+ * @return the new compilation unit, or null
if unable to recognize
+ * the source code, or if the source code is null
+ */
+public IDOMCompilationUnit createCompilationUnit(char[] sourceCode, String name);
+/**
+ * Creates a JDOM on the given source code. The syntax for the given source
+ * code corresponds to CompilationUnit (JLS2 7.3).
+ *
+ * @param sourceCode the source code string, or null
+ * @param name the name of the compilation unit
+ * @return the new compilation unit, or null
if unable to recognize
+ * the source code, or if the source code is null
+ */
+public IDOMCompilationUnit createCompilationUnit(String sourceCode, String name);
+/**
+ * Creates a default field document fragment. Initially the field will have
+ * default protection, type "Object"
, name "aField"
,
+ * no comment, and no initializer.
+ *
+ * @return the new field
+ */
+//public IDOMField createField();
+/**
+ * Creates a field document fragment on the given source code. The given source
+ * string corresponds to FieldDeclaration (JLS2 8.3) and ConstantDeclaration
+ * (JLS2 9.3) restricted to a single VariableDeclarator clause.
+ *
+ * @param sourceCode the source code
+ * @return the new field, or null
if unable to recognize
+ * the source code, if the source code is null
, or when the source
+ * contains more than one VariableDeclarator clause
+ */
+//public IDOMField createField(String sourceCode);
+/**
+ * Creates an empty import document fragment. Initially the import will have
+ * name "java.lang.*"
.
+ *
+ * @return the new import
+ */
+//public IDOMImport createImport();
+/**
+ * Creates an import document fragment on the given source code. The syntax for
+ * the given source string corresponds to ImportDeclaration (JLS2 7.5).
+ *
+ * @param sourceCode the source code
+ * @return the new import, or null
if unable to recognize
+ * the source code, or if the source code is null
+ */
+//public IDOMImport createImport(String sourceCode);
+/**
+ * Creates an empty initializer document fragment. Initially the initializer
+ * will be static and have no body or comment.
+ *
+ * @return the new initializer
+ */
+//public IDOMInitializer createInitializer();
+/**
+ * Creates an initializer document fragment from the given source code. The
+ * syntax for the given source string corresponds to InstanceInitializer
+ * (JLS2 8.6) and StaticDeclaration (JLS2 8.7).
+ *
+ * @param sourceCode the source code
+ * @return the new initializer, or null
if unable to recognize
+ * the source code, or if the source code is null
+ */
+//public IDOMInitializer createInitializer(String sourceCode);
+/**
+ * Creates a default method document fragment. Initially the method
+ * will have public visibility, return type "void"
, be named
+ * "newMethod"
, have no parameters, no comment, and an empty body.
+ *
+ * @return the new method
+ */
+//public IDOMMethod createMethod();
+/**
+ * Creates a method document fragment on the given source code. The syntax for
+ * the given source string corresponds to MethodDeclaration (JLS2 8.4),
+ * ConstructorDeclaration (JLS2 8.8), and AbstractMethodDeclaration (JLS2 9.4).
+ *
+ * @param sourceCode the source code
+ * @return the new method, or null
if unable to recognize
+ * the source code, or if the source code is null
+ */
+//public IDOMMethod createMethod(String sourceCode);
+/**
+ * Creates an empty package document fragment. Initially the package
+ * declaration will have no name.
+ *
+ * @return the new package
+ */
+//public IDOMPackage createPackage();
+/**
+ * Creates a package document fragment on the given source code. The syntax for
+ * the given source string corresponds to PackageDeclaration (JLS2 7.4).
+ *
+ * @param sourceCode the source code
+ * @return the new package, or null
if unable to recognize
+ * the source code, or if the source code is null
+ */
+//public IDOMPackage createPackage(String sourceCode);
+/**
+ * Creates a default type document fragment. Initially the type will be
+ * a public class named "AClass"
, with no members or comment.
+ *
+ * @return the new type
+ */
+//public IDOMType createType();
+/**
+ * Creates a default type document fragment. Initially the type will be
+ * a public class named "AClass"
, with no members or comment.
+ *
+ * @return the new class
+ * @since 2.0
+ */
+//public IDOMType createClass();
+/**
+ * Creates a default type document fragment. Initially the type will be
+ * a public interface named "AnInterface"
, with no members or comment.
+ *
+ * @return the new interface
+ * @since 2.0
+ */
+//public IDOMType createInterface();
+/**
+ * Creates a type document fragment on the given source code. The syntax for the
+ * given source string corresponds to ClassDeclaration (JLS2 8.1) and
+ * InterfaceDeclaration (JLS2 9.1).
+ *
+ * @param sourceCode the source code
+ * @return the new type, or null
if unable to recognize
+ * the source code, or if the source code is null
+ */
+//public IDOMType createType(String sourceCode);
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMField.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMField.java
new file mode 100644
index 0000000..72de2a6
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMField.java
@@ -0,0 +1,76 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.core.jdom;
+
+/**
+ * Represents a field declaration. The corresponding
+ * syntactic units are FieldDeclaration (JLS2 8.3) and ConstantDeclaration
+ * (JLS2 9.3) restricted to a single VariableDeclarator clause.
+ * A field has no children. The parent of a field is a type.
+ * + * This interface is not intended to be implemented by clients. + *
+ */ +public interface IDOMField extends IDOMMember { +/** + * Returns the initializer expression for this field. + * The syntax for an initializer corresponds to VariableInitializer (JLS2 8.3). + *
+ * Note: The expression does not include a "=
".
+ *
null
if this field does
+ * not have an initializer
+ */
+public String getInitializer();
+/**
+ * The IDOMField
refinement of this IDOMNode
+ * method returns the name of this field. The syntax for the name of a field
+ * corresponds to VariableDeclaratorId (JLS2 8.3).
+ */
+public String getName();
+/**
+ * Returns the type name of this field. The syntax for a type name of a field
+ * corresponds to Type in Field Declaration (JLS2 8.3).
+ *
+ * @return the type name
+ */
+public String getType();
+/**
+ * Sets the initializer expression for this field.
+ * The syntax for an initializer corresponds to VariableInitializer (JLS2 8.3).
+ *
+ * Note: The expression does not include a "=
".
+ *
null
indicating
+ * the field does not have an initializer
+ */
+public void setInitializer(String initializer);
+/**
+ * The IDOMField
refinement of this IDOMNode
+ * method sets the name of this field. The syntax for the name of a field
+ * corresponds to VariableDeclaratorId (JLS2 8.3).
+ *
+ * @exception IllegalArgumentException if null
is specified
+ */
+public void setName(String name) throws IllegalArgumentException;
+/**
+ * Sets the type name of this field. The syntax for a type name of a field
+ * corresponds to Type in Field Declaration (JLS2 8.3). Type names must be
+ * specified as they should appear in source code. For example:
+ * "String"
, "int[]"
, or "java.io.File"
.
+ *
+ * @param typeName the type name
+ * @exception IllegalArgumentException if null
is specified
+ */
+public void setType(String typeName) throws IllegalArgumentException;
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMImport.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMImport.java
new file mode 100644
index 0000000..47a6ffa
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMImport.java
@@ -0,0 +1,44 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.core.jdom;
+
+/**
+ * Represents an import declaration.
+ * The corresponding syntactic unit is ImportDeclaration (JLS2 7.5).
+ * An import has no children and its parent is a compilation unit.
+ * + * This interface is not intended to be implemented by clients. + *
+ */ +public interface IDOMImport extends IDOMNode { +/** + * TheIDOMImport
refinement of this IDOMNode
+ * method returns the name of this import. The syntax for an import name
+ * corresponds to a fully qualified type name, or to an on-demand package name
+ * as defined by ImportDeclaration (JLS2 7.5).
+ */
+public String getName();
+/**
+ * Returns whether this import declaration ends with ".*"
.
+ *
+ * @return true
if this in an on-demand import
+ */
+public boolean isOnDemand();
+/**
+ * The IDOMImport
refinement of this IDOMNode
+ * method sets the name of this import. The syntax for an import name
+ * corresponds to a fully qualified type name, or to an on-demand package name
+ * as defined by ImportDeclaration (JLS2 7.5).
+ *
+ * @exception IllegalArgumentException if null
is specified
+ */
+public void setName(String name);
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMInitializer.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMInitializer.java
new file mode 100644
index 0000000..96c612e
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMInitializer.java
@@ -0,0 +1,49 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.core.jdom;
+
+/**
+ * Represents an initializer. The corresponding syntactic
+ * units are InstanceInitializer (JLS2 8.6) and StaticDeclaration (JLS2 8.7).
+ * An initializer has no children and its parent is a type.
+ * + * This interface is not intended to be implemented by clients. + *
+ */ +public interface IDOMInitializer extends IDOMMember { +/** + * Returns the body of this initializer. The syntax for a body corresponds to + * InstanceInitializer (JLS2 8.6) and StaticDeclaration (JLS2 8.7). + * + * @return an initializer body, including braces, ornull
if
+ * no body is present
+ */
+public String getBody();
+/**
+ * The IDOMInitializer
refinement of this IDOMNode
+ * method returns null
. An initializer does not have a name.
+ */
+public String getName();
+/**
+ * Sets the body of this initializer. The syntax for a body corresponds to
+ * InstanceInitializer (JLS2 8.6) and StaticDeclaration (JLS2 8.7). No formatting
+ * or syntax checking is performed on the body. Braces must be included.
+ *
+ * @param body an initializer body, including braces, or null
+ * indicating no body
+ */
+public void setBody(String body);
+/**
+ * The IDOMInitializer
refinement of this IDOMNode
+ * method does nothing.
+ */
+public void setName(String name);
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMMember.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMMember.java
new file mode 100644
index 0000000..da5ea6b
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMMember.java
@@ -0,0 +1,61 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.core.jdom;
+
+/**
+ * An IDOMMember
defines functionality common to nodes, which
+ * can be members of types.
+ * + * This interface is not intended to be implemented by clients. + *
+ * + * @see IDOMType + * @see IDOMMethod + * @see IDOMField + * @see IDOMInitializer + */ +public interface IDOMMember extends IDOMNode { +/** + * Returns the comment associated with this member (including comment delimiters). + * + * @return the comment, ornull
if this member has no associated
+ * comment
+ */
+public String getComment();
+/**
+ * Returns the flags for this member. The flags can be examined using the
+ * Flags
class.
+ *
+ * @return the flags
+ * @see org.eclipse.jdt.core.Flags
+ */
+public int getFlags();
+/**
+ * Sets the comment associated with this member. The comment will appear
+ * before the member in the source. The comment must be properly formatted, including
+ * delimiters. A null
comment indicates no comment. This member's
+ * deprecated flag is automatically set to reflect the deprecated tag in the
+ * comment.
+ *
+ * @param comment the comment, including comment delimiters, or
+ * null
indicating this member should have no associated comment
+ * @see #setFlags
+ */
+public void setComment(String comment);
+/**
+ * Sets the flags for this member. The flags can be examined using the
+ * Flags
class. The deprecated flag passed in is ignored.
+ *
+ * @param flags the flags
+ * @see org.eclipse.jdt.core.Flags
+ */
+public void setFlags(int flags);
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMMethod.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMMethod.java
new file mode 100644
index 0000000..4845a80
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMMethod.java
@@ -0,0 +1,182 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.core.jdom;
+
+/**
+ * Represents a method declaration.
+ * The corresponding syntactic units are MethodDeclaration (JLS2 8.4),
+ * ConstructorDeclaration (JLS2 8.8), and AbstractMethodDeclaration (JLS2 9.4).
+ * A method has no children and its parent is a type.
+ * Local classes are considered to be part of the body of a method, not a child.
+ * + * This interface is not intended to be implemented by clients. + *
+ */ +public interface IDOMMethod extends IDOMMember { +/** + * Adds the given exception to the end of the list of exceptions this method + * is declared to throw. + * The syntax for an exception type name is defined by Method Throws (JLS2 8.4.4). + * Type names must be specified as they would appear in source code. For + * example:"IOException"
or "java.io.IOException"
.
+ * This is a convenience method for setExceptions
.
+ *
+ * @param exceptionType the exception type
+ * @exception IllegalArgumentException if null
is specified
+ * @see #setExceptions
+ */
+public void addException(String exceptionType) throws IllegalArgumentException;
+/**
+ * Adds the given parameter to the end of the parameter list.
+ * This is a convenience method for setParameters
.
+ * The syntax for parameter names is defined by Formal Parameters (JLS2 8.4.1).
+ * The syntax for type names is defined by Formal Parameters (JLS2 8.4.1).
+ * Type names must be specified as they would appear in source code. For
+ * example: "File"
, "java.io.File"
, or
+ * "int[]"
.
+ *
+ * @param type the type name
+ * @param name the parameter name
+ * @exception IllegalArgumentException if null
is specified for
+ * either the type or the name
+ * @see #setParameters
+ */
+public void addParameter(String type, String name) throws IllegalArgumentException;
+/**
+ * Returns the body of this method. The method body includes all code following
+ * the method declaration, including the enclosing braces.
+ *
+ * @return the body, or null
if the method has no body (for
+ * example, for an abstract or native method)
+ */
+public String getBody();
+/**
+ * Returns the names of the exception types this method throws
+ * in the order in which they are declared in the source, or an empty array
+ * if this method declares no exception types.
+ * The syntax for an exception type name is defined by Method Throws (JLS2 8.4.4).
+ * Type names appear as they would in source code. For example:
+ * "IOException"
or "java.io.IOException"
.
+ *
+ * @return the list of exception types
+ */
+public String[] getExceptions();
+/**
+ * The IDOMMethod
refinement of this IDOMNode
+ * method returns the name of this method. Returns null
for
+ * constructors. The syntax for a method name is defined by Identifier
+ * of MethodDeclarator (JLS2 8.4).
+ */
+public String getName();
+/**
+ * Returns the names of parameters in this method in the order they are declared,
+ * or null
if no parameters are declared.
+ * The syntax for parameter names is defined by Formal Parameters (JLS2 8.4.1).
+ *
+ * @return the list of parameter names, or null
if no parameters
+ * are declared
+ */
+public String[] getParameterNames();
+/**
+ * Returns the type names for the parameters of this method in the order they are declared,
+ * or null
if no parameters are declared.
+ * The syntax for type names is defined by Formal Parameters (JLS2 8.4.1).
+ * Type names must be specified as they would appear in source code. For
+ * example: "File"
, "java.io.File"
, or
+ * "int[]"
.
+ *
+ * @return the list of parameter types, or null
if no parameters
+ * are declared
+ */
+public String[] getParameterTypes();
+/**
+ * Returns the return type name, or null
.
+ * Returns null
for constructors.
+ * The syntax for return type name corresponds to ReturnType in
+ * MethodDeclaration (JLS2 8.4). Names are returned as they appear in the source
+ * code; for example: "File"
, "java.io.File"
,
+ * "int[]"
, or "void"
.
+ *
+ * @return the return type
+ */
+public String getReturnType();
+/**
+ * Returns whether this method is a constructor.
+ *
+ * @return true
for constructors, and false
for methods
+ */
+public boolean isConstructor();
+/**
+ * Sets the body of this method. The method body includes all code following
+ * the method declaration, including the enclosing braces. No formatting or
+ * syntax checking is performed on the body.
+ *
+ * @return the body, or null
indicating the method has no body (for
+ * example, for an abstract or native method)
+ */
+public void setBody(String body);
+/**
+ * Sets whether this method represents a constructor.
+ *
+ * @param b true
for constructors, and false
for methods
+ */
+public void setConstructor(boolean b);
+/**
+ * Sets the names of the exception types this method throws,
+ * in the order in which they are declared in the source. An empty array
+ * indicates this method declares no exception types.
+ * The syntax for an exception type name is defined by Method Throws (JLS2 8.4.4).
+ * Type names must be specified as they would appear in source code. For
+ * example: "IOException"
or "java.io.IOException"
.
+ *
+ * @param exceptionTypes the list of exception types
+ */
+public void setExceptions(String[] exceptionTypes);
+/**
+ * The IDOMMethod
refinement of this IDOMNode
+ * method sets the name of this method. The syntax for a method
+ * name is defined by Identifer of MethodDeclarator (JLS2 8.4).
+ *
+ * The name of a constructor is always null
and thus it
+ * must not be set.
+ *
null
is specified
+ */
+public void setName(String name) throws IllegalArgumentException;
+/**
+ * Sets the types and names of parameters in this method in the order they are
+ * to be declared. If both types
and names
are null
+ * this indicates that this method has no parameters.
+ * The syntax for parameter names is defined by Formal Parameters (JLS2 8.4.1).
+ * The syntax for type names is defined by Formal Parameters (JLS2 8.4.1).
+ * Type names must be specified as they would appear in source code. For
+ * example: "File"
, "java.io.File"
, or
+ * "int[]"
.
+ *
+ * @param types the list of type names
+ * @param names the list of parameter name
+ * @exception IllegalArgumentException if the number of types and names do not
+ * match, or if either argument is null
+ */
+public void setParameters(String[] types, String[] names) throws IllegalArgumentException;
+/**
+ * Sets the return type name. This has no effect on constructors.
+ * The syntax for return type name corresponds to ReturnType in
+ * MethodDeclaration (JLS2 8.4). Type names are specified as they appear in the
+ * source code; for example: "File"
, "java.io.File"
,
+ * "int[]"
, or "void"
.
+ *
+ * @param type the return type
+ * @exception IllegalArgumentException if null
is specified
+ */
+public void setReturnType(String type) throws IllegalArgumentException;
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMNode.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMNode.java
new file mode 100644
index 0000000..9c61412
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMNode.java
@@ -0,0 +1,278 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.core.jdom;
+
+import java.util.Enumeration;
+
+import net.sourceforge.phpdt.core.IJavaElement;
+
+
+/**
+ * Nodes represent structural fragments of a Java source file, also known as document fragments. Their implementation
+ * is known as a DOM (Document Object Model) - in this case a JDOM (Java DOM). A root node (node
+ * with no parent or siblings) represents the root of a document fragment (DF). A complete Java document is
+ * represented by a compilation unit node (IDOMCompilationUnit
). In this way, a DF is
+ * comprised of DFs, and a document itself (compilation unit) is also a DF.
+ *
+ * A DF may be created empty and programmatically filled, or it may be created from
+ * a source code string. The IDOMFactory
allows the creation of all kinds
+ * of nodes from source code strings. Manipulations performed on a DF are immediately
+ * reflected in the DF's contents.
+ *
+ * Children fragments are represented as a linked list of nodes. Children are inserted via their parent node, and + * are automatically linked up with previous and next nodes. + *
+ *+ * The contents of any node (DF) may be retrieved at any time. In this way it is possible to retrieve + * source code representing fragments of the compilation unit (for example, a type or a method), since + * the contents of any node (not just the root node) may be obtained. + *
+ *+ * The following manipulations on DFs are distinct: + *
+ * Wherever types are specified in DOM APIs, type names must be specified as they would appear
+ * in source code. The DOM does not have a notion of type signatures, only raw text. Example type
+ * names are "Object"
, "java.io.File"
, and "int[]"
.
+ *
+ * This interface is not intended to be implemented by clients. + *
+ */ +public interface IDOMNode extends Cloneable { + + /** + * Node type constant indicating a compilation unit. + * Nodes of this type maybe by safely cast toIDOMCompilationUnit
.
+ * @see #getNodeType
+ */
+ public static int COMPILATION_UNIT= 1;
+
+ /**
+ * Node type constant indicating a package declaration.
+ * Nodes of this type maybe by safely cast to IDOMPackage
.
+ * @see #getNodeType
+ */
+ public static int PACKAGE= 2;
+
+ /**
+ * Node type constant indicating an import declaration.
+ * Nodes of this type maybe by safely cast to IDOMImport
.
+ * @see #getNodeType
+ */
+ public static int IMPORT= 3;
+
+ /**
+ * Node type constant indicating a type declaration.
+ * Nodes of this type maybe by safely cast to IDOMType
.
+ * @see #getNodeType
+ */
+ public static int TYPE= 4;
+
+ /**
+ * Node type constant indicating a field declaration.
+ * Nodes of this type maybe by safely cast to IDOMField
.
+ * @see #getNodeType
+ */
+ public static int FIELD= 5;
+
+ /**
+ * Node type constant indicating a method (or constructor) declaration.
+ * Nodes of this type maybe by safely cast to IDOMMethod
.
+ * @see #getNodeType
+ */
+ public static int METHOD= 6;
+
+ /**
+ * Node type constant indicating an initializer declaration.
+ * Nodes of this type maybe by safely cast to IDOMInitializer
.
+ * @see #getNodeType
+ */
+ public static int INITIALIZER= 7;
+
+/**
+ * Adds the given un-parented node (document fragment) as the last child of this node.
+ *
+ * @param child the new child node
+ * @exception DOMException if any of the following conditions hold:null
+ *
+ * @see #insertSibling
+ * @see #remove
+ */
+public void addChild(IDOMNode child) throws DOMException, IllegalArgumentException;
+/**
+ * Returns whether this node is allowed to have children.
+ *
+ * @return true
if this node can have children
+ */
+public boolean canHaveChildren();
+/**
+ * Returns a stand-alone copy of the document fragment represented by this node that
+ * is in no way dependent on the document this node is part of.
+ *
+ * @return a copy of type IDOMNode
+ * @see #addChild
+ * @see #insertSibling
+ * @see #remove
+ */
+public Object clone();
+/**
+ * Returns the current contents of this document fragment as a character array.
+ * + * Note: To obtain complete source for the ".java" file, ask a compilation unit + * node for its contents. + *
+ * + * @return the contents, ornull
if this node has no contents
+ */
+public char[] getCharacters();
+/**
+ * Returns the first named child of this node with the given name.
+ *
+ * @param name the name
+ * @return the child node, or null
if no such child exists
+ */
+public IDOMNode getChild(String name);
+/**
+ * Returns an enumeration of children of this node. Returns an empty enumeration
+ * if this node has no children (including nodes that cannot have children).
+ * Children appear in the order in which they are declared in the source code.
+ *
+ * @return an enumeration of the children
+ */
+public Enumeration getChildren();
+/**
+ * Returns the current contents of this document fragment.
+ * + * Note: To obtain complete source for the ".java" file, ask a compilation unit + * node for its contents. + *
+ * + * @return the contents, ornull
if this node has no contents
+ */
+public String getContents();
+/**
+ * Returns the first child of this node.
+ * Children appear in the order in which they exist in the source code.
+ *
+ * @return the first child, or null
if this node has no children
+ * @see #getChildren
+ */
+public IDOMNode getFirstChild();
+/**
+ * Returns a handle for the Java element associated with this
+ * document fragment, based on the parent Java element.
+ *
+ * @param parent the parent Java element
+ * @exception IllegalArgumentException if the parent element is not
+ * of a valid parent type for this node
+ */
+public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException;
+/**
+ * Returns the name of this node.
+ * More details are provided in each of the subtypes.
+ *
+ * @return the name, or null
if it has no name
+ */
+public String getName();
+/**
+ * Returns the sibling node immediately following this node.
+ *
+ * @return the next node, or null
if there is no following node
+ */
+public IDOMNode getNextNode();
+/**
+ * Returns the type of this node.
+ *
+ * @return one of the node type constants defined in IDOMNode
+ */
+public int getNodeType();
+/**
+ * Returns the parent of this node.
+ *
+ * @return the parent node, or null
if this node does not have a
+ * parent
+ */
+public IDOMNode getParent();
+/**
+ * Returns the sibling node immediately preceding this node.
+ *
+ * @return the previous node, or null
if there is no preceding node
+ */
+public IDOMNode getPreviousNode();
+/**
+ * Inserts the given un-parented node as a sibling of this node, immediately before
+ * this node.
+ *
+ * @param sibling the new sibling node
+ * @exception DOMException if any of the following conditions hold:null
+ *
+ * @see #addChild
+ * @see #clone
+ * @see #remove
+ */
+public void insertSibling(IDOMNode sibling) throws DOMException, IllegalArgumentException;
+/**
+ * Returns whether the given node is an allowable child for this node.
+ *
+ * @param node the potential child node
+ * @return true
if the given node is an allowable child
+ */
+public boolean isAllowableChild(IDOMNode node);
+/**
+ * Returns whether this node's signature is equivalent to the given
+ * node's signature. In other words, if the nodes were siblings,
+ * would the declarations collide because they represent the same declaration.
+ *
+ * @param node the other node
+ * @return true
if the nodes have equivalent signatures
+ */
+public boolean isSignatureEqual(IDOMNode node);
+/**
+ * Separates this node from its parent and siblings, maintaining any ties that this node
+ * has to the underlying document fragment. A document fragment that is removed
+ * from its host document may still be dependent on that host document until it is
+ * inserted into a different document. Removing a root node has no effect.
+ *
+ * @see #addChild
+ * @see #clone
+ * @see #insertSibling
+ */
+public void remove();
+/**
+ * Sets the name of this node. Name format depends on node type.
+ * More details are provided in each of the subtypes.
+ *
+ * @param name the name, or null
to clear the name
+ */
+public void setName(String name);
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMPackage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMPackage.java
new file mode 100644
index 0000000..49333c8
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMPackage.java
@@ -0,0 +1,36 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.core.jdom;
+/**
+ * Represents a package declaration.
+ * The corresponding syntactic unit is PackageDeclaration (JLS2 7.4).
+ * A Package has no children, and its parent is a compilation unit.
+ * + * This interface is not intended to be implemented by clients. + *
+ */ +public interface IDOMPackage extends IDOMNode { +/** + * TheIDOMPackage
refinement of this IDOMNode
+ * method returns the name of this package declaration, or null
+ * if it has none. The syntax for a package name corresponds to PackageName
+ * as defined by PackageDeclaration (JLS2 7.4).
+ */
+public String getName();
+/**
+ * The IDOMPackage
refinement of this IDOMNode
+ * method sets the name of this package declaration. The syntax for a package
+ * name corresponds to PackageName as defined by PackageDeclaration (JLS2 7.4).
+ * A null
name indicates an empty package declaration; that is,
+ * getContents
returns the empty string.
+ */
+public void setName(String name);
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMType.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMType.java
new file mode 100644
index 0000000..5a4c62e
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/IDOMType.java
@@ -0,0 +1,127 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.core.jdom;
+
+/**
+ * Represents a source type in a compilation unit, either as a top-level type or a member type.
+ * The corresponding syntactic units are ClassDeclaration (JLS2 8.1) and InterfaceDeclaration (JLS2 9.1).
+ *
+ * Allowable child types for a type are IDOMType
, IDOMField
,
+ * IDOMMethod
, and IDOMInitializer
.
+ * Children are listed in the order in which they appear in the source. The parent of a type
+ * is a type (in the case of a member type) or a compilation unit (in the case of a top-level type).
+ *
+ * This interface is not intended to be implemented by clients. + *
+ */ +public interface IDOMType extends IDOMMember { +/** + * Adds the given interface name to the names of interfaces that this type implements or extends + * (the name will be added after the existing interface names). This is a convenience method. + * + * For classes, this represents the interfaces that this class implements. + * For interfaces, this represents the interfaces that this interface extends. + * The name may or may not be fully qualified. + * + * @param interfaceName the syntax for an interface name is defined by + * Interfaces in ClassDeclaration (JLS2 8.1). Type names must be specified as they would + * appear in source code. For example: "Cloneable", "java.io.Serializable". + * + * @exception IllegalArgumentException ifnull
is specified
+ */
+public void addSuperInterface(String interfaceName) throws IllegalArgumentException;
+/**
+ * The IDOMType
refinement of this IDOMNode
+ * method returns the name of this type. The name of a class is defined by
+ * ClassDeclaration (JLS2 8.1); the name of an interface is defined by
+ * InterfaceDeclaration (JLS2 9.1).
+ */
+public String getName();
+/**
+ * Returns the name of this type's superclass. The syntax for a superclass name
+ * is specified by Super in ClassDeclaration (JLS2 8.1). Type names must be
+ * specified as they would appear in source code. For example:
+ * "Object"
, or "java.io.File"
.
+ *
+ * @return the superclass name, or null
if this type represents
+ * an interface or if no superclass has been assigned to this class
+ */
+public String getSuperclass();
+/**
+ * Returns the names of interfaces that this type implements or extends,
+ * in the order in which they are listed in the source, or an empty array
+ * if no superinterfaces are present. The syntax for interface names is
+ * defined by Interfaces in ClassDeclaration (JLS2 8.1). Type names appear
+ * as they would in source code. For example: "Cloneable"
,
+ * or "java.io.Serializable"
.
+ * + * For classes, this method returns the interfaces that this class implements. + * For interfaces, this method returns the interfaces that this interface extends. + *
+ * + * @return the list of interface names + */ +public String[] getSuperInterfaces(); +/** + * Returns whether this type is a class. + * + * @returntrue
for classes, and false
for interfaces
+ */
+public boolean isClass();
+/**
+ * Sets whether this type is a class or an interface. If this type is
+ * a class, and is changed to an interface, this type's superclass
+ * becomes null
. When a class becomes an interface or an
+ * interface becomes a class, superinterfaces remain (as part of an
+ * implements
clause for classes, or an extends
+ * clause for interfaces).
+ *
+ * @param b true
for classes, and false
for interfaces
+ */
+public void setClass(boolean b);
+/**
+ * The IDOMType
refinement of this IDOMNode
+ * method sets the name of this type. The name of a class is defined by
+ * ClassDeclaration (JLS2 8.1); the name of an interface is defined by
+ * InterfaceDeclaration (JLS2 9.1).
+ *
+ * @exception IllegalArgumentException if null
is specified
+ */
+public void setName(String name) throws IllegalArgumentException;
+/**
+ * Sets the name of this type's superclass. Has no effect if this type
+ * represents an interface. A null
name indicates that no
+ * superclass name (extends clause) should appear in the source code.
+ * The syntax for a superclass name is specified by Super in ClassDeclaration
+ * (JLS2 8.1). Type names must be specified as they would appear in source code.
+ * For example: "Object"
, or "java.io.File"
.
+ *
+ * @param superclassName the superclass name, or null
if this type
+ * should have to no explicitly specified superclass
+ */
+public void setSuperclass(String superclassName);
+/**
+ * Sets the names of interfaces that this type implements or extends,
+ * in the order in which they are to be listed in the source. An empty array
+ * parameter indicates that no superinterfaces are present. The syntax for
+ * interface names is defined by Interfaces in ClassDeclaration (JLS2 8.1).
+ * Type names appear as they would in source code. For example:
+ * "Cloneable"
, or "java.io.Serializable"
.
+ * + * For classes, this method sets the interfaces that this class implements. + * For interfaces, this method sets the interfaces that this interface extends. + *
+ * + * @param interfaceNames the list of interface names + */ +public void setSuperInterfaces(String[] interfaceNames); +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/package.html b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/package.html new file mode 100644 index 0000000..4fa6750 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/jdom/package.html @@ -0,0 +1,17 @@ + + + + + + ++ * This interface defines the constants used by the search engine. + *
+ *+ * This interface declares constants only; it is not intended to be implemented. + *
+ * @see org.eclipse.jdt.core.search.SearchEngine + */ +public interface IJavaSearchConstants { + + /** + * The nature of searched element or the nature + * of match in unknown. + */ + int UNKNOWN = -1; + + /* Nature of searched element */ + + /** + * The searched element is a type. + */ + int TYPE= 0; + + /** + * The searched element is a method. + */ + int METHOD= 1; + + /** + * The searched element is a package. + */ + int PACKAGE= 2; + + /** + * The searched element is a constructor. + */ + int CONSTRUCTOR= 3; + + /** + * The searched element is a field. + */ + int FIELD= 4; + + /** + * The searched element is a class. + * More selective than using TYPE + */ + int CLASS= 5; + + /** + * The searched element is an interface. + * More selective than using TYPE + */ + int INTERFACE= 6; + + /* Nature of match */ + + /** + * The search result is a declaration. + * Can be used in conjunction with any of the nature of searched elements + * so as to better narrow down the search. + */ + int DECLARATIONS= 0; + + /** + * The search result is a type that implements an interface. + * Used in conjunction with either TYPE or CLASS or INTERFACE, it will + * respectively search for any type implementing/extending an interface, or + * rather exclusively search for classes implementing an interface, or interfaces + * extending an interface. + */ + int IMPLEMENTORS= 1; + + /** + * The search result is a reference. + * Can be used in conjunction with any of the nature of searched elements + * so as to better narrow down the search. + * References can contain implementers since they are more generic kind + * of matches. + */ + int REFERENCES= 2; + + /** + * The search result is a declaration, a reference, or an implementer + * of an interface. + * Can be used in conjunction with any of the nature of searched elements + * so as to better narrow down the search. + */ + int ALL_OCCURRENCES= 3; + + /** + * When searching for field matches, it will exclusively find read accesses, as + * opposed to write accesses. Note that some expressions are considered both + * as field read/write accesses: for example, x++; x+= 1; + * + * @since 2.0 + */ + int READ_ACCESSES = 4; + + /** + * When searching for field matches, it will exclusively find write accesses, as + * opposed to read accesses. Note that some expressions are considered both + * as field read/write accesses: for example, x++; x+= 1; + * + * @since 2.0 + */ + int WRITE_ACCESSES = 5; + + /* Syntactic match modes */ + + /** + * The search pattern matches exactly the search result, + * that is, the source of the search result equals the search pattern. + */ + int EXACT_MATCH = 0; + /** + * The search pattern is a prefix of the search result. + */ + int PREFIX_MATCH = 1; + /** + * The search pattern contains one or more wild cards ('*') where a + * wild-card can replace 0 or more characters in the search result. + */ + int PATTERN_MATCH = 2; + + + /* Case sensitivity */ + + /** + * The search pattern matches the search result only + * if cases are the same. + */ + boolean CASE_SENSITIVE = true; + /** + * The search pattern ignores cases in the search result. + */ + boolean CASE_INSENSITIVE = false; + + + /* Waiting policies */ + +// /** +// * The search operation starts immediately, even if the underlying indexer +// * has not finished indexing the workspace. Results will more likely +// * not contain all the matches. +// */ +// int FORCE_IMMEDIATE_SEARCH = IJob.ForceImmediate; +// /** +// * The search operation throws anorg.eclipse.core.runtime.OperationCanceledException
+// * if the underlying indexer has not finished indexing the workspace.
+// */
+// int CANCEL_IF_NOT_READY_TO_SEARCH = IJob.CancelIfNotReady;
+// /**
+// * The search operation waits for the underlying indexer to finish indexing
+// * the workspace before starting the search.
+// */
+// int WAIT_UNTIL_READY_TO_SEARCH = IJob.WaitUntilReady;
+
+
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/search/ITypeNameRequestor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/search/ITypeNameRequestor.java
new file mode 100644
index 0000000..2a092b8
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/search/ITypeNameRequestor.java
@@ -0,0 +1,61 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.core.search;
+
+/**
+ * A ITypeNameRequestor
collects search results from a searchAllTypeNames
+ * query to a SearchEngine
. Clients must implement this interface and pass
+ * an instance to the searchAllTypeNames(...)
method. Only top-level and
+ * member types are reported. Local types are not reported.
+ * + * This interface may be implemented by clients. + *
+ */ +public interface ITypeNameRequestor { +/** + * Accepts a top-level or a member class. + * + * @param packageName the dot-separated name of the package of the class + * @param simpleTypeName the simple name of the class + * @param enclosingTypeNames if the class is a member type, + * the simple names of the enclosing types from the outer-most to the + * direct parent of the class (for example, if the class is x.y.A$B$C then + * the enclosing types are [A, B]. This is an empty array if the class + * is a top-level type. + * @param path the full path to the resource containing the class. If the resource is a .class file + * or a .java file, this is the full path in the workspace to this resource. If the + * resource is an archive (that is, a .zip or .jar file), the path is composed of 2 paths separated + * byIJavaSearchScope.JAR_FILE_ENTRY_SEPARATOR
:
+ * the first path is the full OS path to the archive (if it is an external archive),
+ * or the workspace relative IPath
to the archive (if it is an internal archive),
+ * the second path is the path to the resource inside the archive.
+ */
+void acceptClass(char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames, String path);
+/**
+ * Accepts a top-level or a member interface.
+ *
+ * @param packageName the dot-separated name of the package of the interface
+ * @param simpleTypeName the simple name of the interface
+ * @param enclosingTypeNames if the interface is a member type,
+ * the simple names of the enclosing types from the outer-most to the
+ * direct parent of the interface (for example, if the interface is x.y.A$B$I then
+ * the enclosing types are [A, B]. This is an empty array if the interface
+ * is a top-level type.
+ * @param path the full path to the resource containing the interface. If the resource is a .class file
+ * or a .java file, this is the full path in the workspace to this resource. If the
+ * resource is an archive (that is, a .zip or .jar file), the path is composed of 2 paths separated
+ * by IJavaSearchScope.JAR_FILE_ENTRY_SEPARATOR
:
+ * the first path is the full OS path to the archive (if it is an external archive),
+ * or the workspace relative IPath
to the archive (if it is an internal archive),
+ * the second path is the path to the resource inside the archive.
+ * */
+void acceptInterface(char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames, String path);
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/externaltools/internal/model/ToolMessages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/externaltools/internal/model/ToolMessages.java
new file mode 100644
index 0000000..c2b9bf7
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/externaltools/internal/model/ToolMessages.java
@@ -0,0 +1,61 @@
+package net.sourceforge.phpdt.externaltools.internal.model;
+
+/**********************************************************************
+Copyright (c) 2002 IBM Corp. and others. All rights reserved.
+This file is made available under the terms of the Common Public License v1.0
+which accompanies this distribution, and is available at
+http://www.eclipse.org/legal/cpl-v10.html
+Â
+Contributors:
+**********************************************************************/
+
+import java.text.MessageFormat;
+import java.util.MissingResourceException;
+import java.util.ResourceBundle;
+
+/**
+ * Utility class which helps managing messages
+ */
+public final class ToolMessages {
+ private static final String RESOURCE_BUNDLE= "net.sourceforge.phpdt.externaltools.internal.model.messages"; //$NON-NLS-1$
+ private static ResourceBundle bundle = ResourceBundle.getBundle(RESOURCE_BUNDLE);
+
+ private ToolMessages(){
+ // prevent instantiation of class
+ }
+
+ /**
+ * Returns the formatted message for the given key in
+ * the resource bundle.
+ *
+ * @param key the message name
+ * @param args the message arguments
+ * @return the formatted message
+ */
+ public static String format(String key, Object[] args) {
+ return MessageFormat.format(getString(key), args);
+ }
+
+ /**
+ * Returns the message with the given key in
+ * the resource bundle. If there isn't any value under
+ * the given key, the key is returned.
+ *
+ * @param key the message name
+ * @return the message
+ */
+ public static String getString(String key) {
+ try {
+ return bundle.getString(key);
+ } catch (MissingResourceException e) {
+ return key;
+ }
+ }
+
+ /**
+ * Returns the resource bundle for the plug-in
+ */
+ public static ResourceBundle getResourceBundle() {
+ return bundle;
+ }
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/externaltools/internal/model/messages.properties b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/externaltools/internal/model/messages.properties
new file mode 100644
index 0000000..875ed09
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/externaltools/internal/model/messages.properties
@@ -0,0 +1,332 @@
+# ======================================================================
+# Copyright (c) 2002 IBM Corp. and others. All rights reserved.
+# This file is made available under the terms of the Common Public License v1.0
+# which accompanies this distribution, and is available at
+# http://www.eclipse.org/legal/cpl-v10.html
+# Â
+# Contributors:
+# ======================================================================
+
+# =======================================================================
+# Base External Tool
+# =======================================================================
+
+ExternalTool.nameMustContainOneChar = The external tool name must contain at least one letter or number.
+ExternalTool.nameContainsInvalidChar = The external tool name must contain only letters, numbers, hyphens, and spaces.
+
+ToolUtil.dirLocVarBetweenText = The variable for the directory location cannot have any other text before or after itself.
+ToolUtil.dirLocVarFormatWrong = The variable for the directory location is not in a valid format.
+ToolUtil.dirLocVarMissing = The variable named ''{0}'' for the directory location does not exist.
+ToolUtil.dirLocVarExpandFailed = The variable named ''{0}'' for the directory location could not be expanded.
+ToolUtil.fileLocVarBetweenText = The variable for the file location cannot have any other text before or after itself.
+ToolUtil.fileLocVarFormatWrong = The variable for the file location is not in a valid format.
+ToolUtil.fileLocVarMissing = The variable named ''{0}'' for the file location does not exist.
+ToolUtil.fileLocVarExpandFailed = The variable named ''{0}'' for the file location could not be expanded.
+ToolUtil.argumentVarFormatWrong = A variable for the arguments is not in a valid format.
+ToolUtil.argumentVarMissing = The variable named ''{0}'' for the arguments does not exist.
+ToolUtil.argumentVarExpandFailed = The variable named ''{0}'' for the arguments could not be expanded.
+
+ExternalToolRegistry.loadToolFailure = Press the Details button for more information.
+ExternalToolRegistry.fileNotFoundError = Could not find external tool storage file.
+ExternalToolRegistry.ioLoadError = Problems reading external tool storage file.
+ExternalToolRegistry.ioSaveError = Problems writing external tool storage file.
+ExternalToolRegistry.loadErrorTitle = Problem Loading External Tools.
+ExternalToolRegistry.loadErrorMessage = Could not load all external tools.
+ExternalToolRegistry.noToolFilename = External tool filename for storage not specified.
+ExternalToolRegistry.deleteToolFileFailed = Could not delete external tool file ''{0}''.
+
+ExternalToolStorage.deleteErrorTitle = Problem Deleting External Tool.
+ExternalToolStorage.deleteErrorMessage = Could not delete external tool. Refresh list and try again.
+ExternalToolStorage.reloadErrorTitle = Problem Refreshing External Tools
+ExternalToolStorage.reloadErrorMessage = Could not load all external tools.
+ExternalToolStorage.saveErrorTitle = Problem Saving External Tool.
+ExternalToolStorage.saveErrorMessage = Could not save external tool. Please try again.
+
+NewExternalToolAction.text = &New
+NewExternalToolAction.toolTip = New External Tool Wizard
+
+CopyExternalToolAction.text = &Copy
+CopyExternalToolAction.toolTip = Copy External Tool
+
+PasteExternalToolAction.text = &Paste
+PasteExternalToolAction.toolTip = Paste External Tool
+
+DeleteExternalToolAction.text = &Delete
+DeleteExternalToolAction.toolTip = Delete External Tool
+DeleteExternalToolAction.confirmToolDeleteTitle = Confirm External Tool Delete
+DeleteExternalToolAction.confirmToolDeleteMsg = Are you sure want to delete ''{0}''?
+
+RenameExternalToolAction.text = Rena&me
+RenameExternalToolAction.toolTip = Rename External Tool
+
+RefreshViewAction.text = Re&fresh
+RefreshViewAction.toolTip = Refresh External Tool View
+
+RunExternalToolAction.text = R&un
+RunExternalToolAction.toolTip = Run External Tool
+
+RunWithExternalToolAction.text = Run &With...
+RunWithExternalToolAction.toolTip = Prompt for Arguments and Run External Tool
+
+EditExternalToolPropertiesAction.text = P&roperties
+EditExternalToolPropertiesAction.toolTip = Edit External Tool Properties
+
+ExternalToolMainGroup.locationLabel = &Location:
+ExternalToolMainGroup.locationBrowseLabel = B&rowse...
+ExternalToolMainGroup.descriptionLabel = D&escription:
+ExternalToolMainGroup.nameLabel = Na&me:
+ExternalToolMainGroup.workDirLabel = &Working Directory:
+ExternalToolMainGroup.workDirBrowseLabel = Br&owse...
+ExternalToolMainGroup.nameRequired = External tool name cannot be empty.
+ExternalToolMainGroup.nameAlreadyExist = Another external tool exists with the same name.
+ExternalToolMainGroup.locationRequired = External tool location cannot be empty.
+ExternalToolMainGroup.invalidLocation = External tool location does not exist or is invalid.
+ExternalToolMainGroup.invalidWorkDir = External tool working directory does not exist or is invalid.
+
+ExternalToolOptionGroup.captureOutputLabel = &Capture output messages from running tool
+ExternalToolOptionGroup.showConsoleLabel = &Show console when tool is run
+ExternalToolOptionGroup.runBackgroundLabel = &Run tool in background
+ExternalToolOptionGroup.openPerspLabel = &Open perspective when tool is run:
+ExternalToolOptionGroup.argumentLabel = Ar&guments:
+ExternalToolOptionGroup.argumentInstruction = Note: Enclose an argument containing spaces using double-quotes ("). Not\napplicable for variables.
+ExternalToolOptionGroup.argumentVariableLabel = &Variables...
+ExternalToolOptionGroup.promptArgLabel = &Prompt for arguments before running tool
+ExternalToolOptionGroup.showInMenuLabel = S&how in Run > External Tools menu
+ExternalToolOptionGroup.saveDirtyEditorsLabel = Save dirty &editors before running tool
+
+ExternalToolRefreshGroup.refreshLabel = &Refresh resources after running tool
+ExternalToolRefreshGroup.recursiveLabel = Recursively &include sub-folders
+ExternalToolRefreshGroup.scopeLabel = Choose &Scope Variable:
+
+ExternalToolNewWizard.shellTitle = New External Tool
+ExternalToolNewWizard.optionPageTitle = Options
+ExternalToolNewWizard.optionPageDescription = Configure the options when the external tool is run.
+ExternalToolNewWizard.refreshPageTitle = Refresh Scope
+ExternalToolNewWizard.refreshPageDescription = Specify which resources to refresh after the external tool is run.
+
+ExternalToolVariable.componentErrorMessage = Problem displaying UI component of selected variable.
+
+ResourceComponent.selectedResLabel = &Use selected resource
+ResourceComponent.specificResLabel = Us&e specific resource:
+ResourceComponent.selectionRequired = A specific resource must be selected from the list.
+
+RunExternalToolAction.openPerspProblem = Failed to open the perspective.
+RunExternalToolAction.openPerspTitle = Open Perspective Problem
+RunExternalToolAction.runProblem = Could not run the external tool.
+RunExternalToolAction.runErrorTitle = Run Tool Problem
+RunExternalToolAction.internalError = External tool runner internal error
+
+DefaultRunnerContext.runningExternalTool = Running external tool...
+DefaultRunnerContext.invalidLocation = The file does not exist for the external tool named {0}.
+DefaultRunnerContext.invalidDirectory = The working directory does not exist for the external tool named {0}.
+DefaultRunnerContext.refreshResources = Refresh resources...
+DefaultRunnerContext.noToolRunner = The no valid runner provided for the external tool named {0}.
+DefaultRunnerContext.invalidRefreshVarFormat = Invalid refresh scope variable format for the external tool named {0}.
+DefaultRunnerContext.noRefreshVarNamed = Could not find refresh scope variable called ''{1}'' for the external tool named {0}.
+
+ExternalToolMenuDelegate.showView = Show External Tools View
+ExternalToolMenuDelegate.runRecent = Run Last Tool
+ExternalToolMenuDelegate.configure = Configure...
+
+
+# =======================================================================
+# Program External Tool Type
+# =======================================================================
+
+ProgramRunner.runningToolLabel = Running external tool: {0}
+ProgramRunner.internalErrorMessage = Internal error
+ProgramRunner.callingRuntimeExec = Calling runtime exec with:\n
+ProgramRunner.program = Program: {0}\n
+ProgramRunner.argument = Argument: {0}\n
+ProgramRunner.workDir = Working Directory: {0}\n
+
+
+# =======================================================================
+# Ant Build File External Tool Type
+# =======================================================================
+
+AntFileRunner.callingAntRunner = Calling Ant runner with:\n
+AntFileRunner.antFile = Ant build file: {0}\n
+AntFileRunner.argument = Argument: {0}\n
+AntFileRunner.target = Target: {0}\n
+
+AntTargetsGroup.availableTargetsLabel = A&vailable targets:
+AntTargetsGroup.activeTargetsLabel = A&ctive targets:
+AntTargetsGroup.addLabel = >
+AntTargetsGroup.removeLabel = <
+AntTargetsGroup.addAllLabel = >>
+AntTargetsGroup.removeAllLabel = <<
+AntTargetsGroup.descriptionLabel = &Target description:
+AntTargetsGroup.upLabel = U&p
+AntTargetsGroup.downLabel = D&own
+AntTargetsGroup.getTargetsTitle = Problem retrieving targets
+AntTargetsGroup.getTargetsProblem = Could not retrieve targets.
+AntTargetsGroup.runDefaultTargetLabel = R&un default target ({0})
+AntTargetsGroup.runDefaultTargetUnknownLabel = R&un default target
+AntTargetsGroup.showSubTargetsLabel = S&how sub-targets
+
+AntExternalToolNewWizard.antTargetsPageTitle = Ant Targets
+AntExternalToolNewWizard.antTargetsPageDescription = Specify which Ant targets to execute when the external tool is run.
+AntExternalToolNewWizard.promptForArgumentLabel = &Prompt for targets and arguments before running tool
+
+AntOptionGroupPropertyPage.promptForArgumentLabel = &Prompt for targets and arguments before running tool
+
+
+
+# =======================================================================
+# OLD STUFF
+# =======================================================================
+
+ConfigurationDialog.shellTitle = External Tools Configuration
+ConfigurationDialog.dialogTitle = External Tools
+ConfigurationDialog.dialogMessage = Configure an external tool to run a program, batch file, or Ant build file.
+ConfigurationDialog.toolList = &Tools:
+ConfigurationDialog.newButton = &New...
+ConfigurationDialog.editButton = &Edit...
+ConfigurationDialog.removeButton = &Remove
+ConfigurationDialog.upButton = &Up
+ConfigurationDialog.downButton = &Down
+ConfigurationDialog.details = Det&ails:
+ConfigurationDialog.detailMessage = Location: {0}\nArguments: {1}\nDirectory: {2}
+
+EditDialog.newShellTitle = New External Tool
+EditDialog.editShellTitle = Edit External Tool
+EditDialog.dialogTitle = External Tool
+EditDialog.newDialogMessage = Create an external tool to run a program, batch file, or Ant build file.
+EditDialog.editDialogMessage = Edit an external tool to run a program, batch file, or Ant build file.
+EditDialog.howToSelectAntTargets = To choose Ant targets, press the ''Browse Variables'' button and select ''Ant targets''.
+EditDialog.nameLabel = &Name:
+EditDialog.locationLabel = Tool &Location:
+EditDialog.argumentLabel = Tool &Arguments:
+EditDialog.dirLabel = Working &Directory:
+EditDialog.refreshOption = After running, &refresh:
+EditDialog.browseWkspButton1 = Browse &Workspace...
+EditDialog.browseFileSysButton1 = Browse &File System...
+EditDialog.browseVarsButton = Browse &Variables...
+EditDialog.directoryBrowseButton = Browse &Options...
+EditDialog.refreshOptionButton = Browse O&ptions...
+EditDialog.browseWorkspaceTitle = Browse Workspace
+EditDialog.selectTool = &Select the external tool to use:
+EditDialog.selectResource = &Select the resource to use:
+EditDialog.selectContainer = &Select the container to use:
+EditDialog.selectDirectory = &Select the working directory to use:
+EditDialog.selectTargets = &Select the Ant targets to use:
+EditDialog.selectFolder = &Select the folder to use:
+EditDialog.browseVarTitle = Browse Variables
+EditDialog.browseDirTitle = Browse Working Directory Options
+EditDialog.selectVar = &Select a variable to use:
+EditDialog.selectDir = &Select a working directory option:
+EditDialog.dirBrowseWorkspace = Browse workspace
+EditDialog.dirBrowseFileSystem = Browse file system
+EditDialog.varWorkspaceLocLabel = Workspace location
+EditDialog.varProjectLocLabel = Selected resource's project location
+EditDialog.varContainerLocLabel = Selected resource's container location
+EditDialog.varResourceLocLabel = Selected resource location
+EditDialog.varProjectPathLabel = Selected resource's project full path
+EditDialog.varContainerPathLabel = Selected resource's container full path
+EditDialog.varResourcePathLabel = Selected resource full path
+EditDialog.varProjectNameLabel = Selected resource's project name
+EditDialog.varContainerNameLabel = Selected resource's container name
+EditDialog.varResourceNameLabel = Selected resource name
+EditDialog.varProjectXLocLabel = Specific resource's project location
+EditDialog.varContainerXLocLabel = Specific resource's container location
+EditDialog.varResourceXLocLabel = Specific resource location
+EditDialog.varProjectXPathLabel = Specific resource's project full path
+EditDialog.varContainerXPathLabel = Specific resource's container full path
+EditDialog.varResourceXPathLabel = Specific resource full path
+EditDialog.varProjectXNameLabel = Specific resource's project name
+EditDialog.varContainerXNameLabel = Specific resource's container name
+EditDialog.varResourceXNameLabel = Specific resource name
+EditDialog.varBuildTypeNameLabel = Build type
+EditDialog.varAntTargetLabel = Ant targets
+EditDialog.browseProjectTitle = Browse Projects
+EditDialog.selectProject = &Select a project to use:
+EditDialog.noToolName = Enter a name for the tool
+EditDialog.noToolLocation = Enter a location for the tool
+EditDialog.missingToolLocation = Tool location does not exist or is invalid
+EditDialog.missingToolDirectory = Tool working directory does not exist or is invalid
+EditDialog.refreshScopeNone = Nothing
+EditDialog.refreshScopeWorkspace = Workspace
+EditDialog.refreshScopeProject = Current project
+EditDialog.refreshScopeProjectX = Project named {0}
+EditDialog.refreshScopeWorkingSet = Working set named {0}
+EditDialog.browseRefreshTitle = Browse Refresh Scopes
+EditDialog.selectRefresh = &Select the refresh scope to use:
+EditDialog.refreshNothingLabel = Nothing
+EditDialog.refreshWorkspaceLabel = Current workspace
+EditDialog.refreshProjectLabel = Current project
+EditDialog.refreshProjectXLabel = Specific project
+EditDialog.refreshWorkingSetLabel = Specific working set
+EditDialog.showLogLabel = S&how execution log on console
+EditDialog.errorTitle = Edit External Tool Problem
+EditDialog.errorReadAntFile = Problems reading Ant build file: {0}
+EditDialog.noAntTargets = Could not find any targets in Ant build file: {0}
+
+ExternalToolsRegistry.saveStateErrorTitle = Problem Saving External Tool
+ExternalToolsRegistry.saveStateError = Could not write external tool configurations to disk.\n\nPlease try again.
+
+BuilderPropertyPage.description = Add external tools to the build order.
+BuilderPropertyPage.newButton = &New...
+BuilderPropertyPage.editButton = &Edit...
+BuilderPropertyPage.removeButton = &Remove
+BuilderPropertyPage.upButton = &Up
+BuilderPropertyPage.downButton = &Down
+BuilderPropertyPage.statusMessage = Internal error
+BuilderPropertyPage.errorTitle = External Tool Builder Problem
+BuilderPropertyPage.errorMessage = Internal error
+BuilderPropertyPage.invalidBuildTool = Invalid External Tool Builder
+BuilderPropertyPage.missingBuilder = Missing builder ({0})
+
+ExternalToolsAction.configure = &Configure...
+
+LogConsoleDocument.externalTool = External Tool
+
+LogConsoleView.copy = &Copy@Ctrl+C
+LogConsoleView.expandAll = &Expand All
+LogConsoleView.selectAll = Select &All@Ctrl+A
+LogConsoleView.clearOutput = Clear Output
+LogConsoleView.hideOutputStructureTree = Hide Output Structure Tree
+LogConsoleView.showOutputStructureTree = Show Output Structure Tree
+LogConsoleView.showTree = &Show Tree
+LogConsoleView.showSelectedElementOnly = Show Output of Selected Element Only
+LogConsoleView.showCompleteOutput = Show Complete Output
+LogConsoleView.findAction.label = Find/Replace
+
+LogTreeLabelProvider.invalidItemName = Invalid item name
+
+ToolsPreferencePage.errorColor = &Error:
+ToolsPreferencePage.warningColor = &Warning:
+ToolsPreferencePage.infoColor = I&nformation:
+ToolsPreferencePage.verboseColor = Ve&rbose:
+ToolsPreferencePage.debugColor = Deb&ug:
+ToolsPreferencePage.font = Console font setting:
+ToolsPreferencePage.description = Console text color settings.
+
+BuildCanceledException.canceled = Canceled
+
+AntUtil.antFileNotFound = Could not open Ant build file.
+AntUtil.parserConfigError = Internal parser configuration error.
+AntUtil.ioError = Could not read content of Ant build file.
+AntUtil.formatError = Could not parse content of Ant build file.
+AntUtil.invalidAntBuildFile = Invalid content format of Ant build file.
+
+AntAction.runErrorTitle = Run Ant Problem
+AntAction.errorReadAntFile = Problems reading Ant build file: {0}
+AntAction.noAntTargets = Could not find any targets in Ant build file: {0}
+
+AntLaunchWizard.shellTitle = Run Ant
+AntLaunchWizard.dialogTitle = Run
+AntLaunchWizard.dialogDescription = Run an Ant build file
+AntLaunchWizard.runningAnt = Running Ant
+AntLaunchWizard.runAntProblem = A problem occurred executing the Ant file. See the log console for details.
+AntLaunchWizard.runErrorTitle = Run Ant Problem
+AntLaunchWizard.internalAntError = Ant runner internal error
+
+AntLaunchWizardPage.targetLabel = Available &targets:
+AntLaunchWizardPage.argsLabel = &Arguments:
+AntLaunchWizardPage.showLogLabel = S&how execution log in console
+
+AntTargetLabelProvider.defaultTarget = Default
+
+ExternalToolsDialog.External_Tools_1=External Tools
+ExternalToolsDialog.Create,_manage,_and_run_external_tools_2=Create, manage, and run external tools
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/ISearchRequestor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/ISearchRequestor.java
new file mode 100644
index 0000000..e430c5b
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/ISearchRequestor.java
@@ -0,0 +1,60 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.codeassist;
+
+/**
+ * This is the internal requestor passed to the searchable name environment
+ * so as to process the multiple search results as they are discovered.
+ *
+ * It is used to allow the code assist engine to add some more information
+ * to the raw name environment results before answering them to the UI.
+ */
+public interface ISearchRequestor {
+
+ /**
+ * One result of the search consists of a new class.
+ *
+ * NOTE - All package and type names are presented in their readable form:
+ * Package names are in the form "a.b.c".
+ * Nested type names are in the qualified form "A.M".
+ * The default package is represented by an empty array.
+ */
+ public void acceptClass(char[] packageName, char[] typeName, int modifiers);
+
+ /**
+ * One result of the search consists of a new interface.
+ *
+ * NOTE - All package and type names are presented in their readable form:
+ * Package names are in the form "a.b.c".
+ * Nested type names are in the qualified form "A.I".
+ * The default package is represented by an empty array.
+ */
+ public void acceptInterface(char[] packageName, char[] typeName, int modifiers);
+
+ /**
+ * One result of the search consists of a new package.
+ *
+ * NOTE - All package names are presented in their readable form:
+ * Package names are in the form "a.b.c".
+ * The default package is represented by an empty array.
+ */
+ public void acceptPackage(char[] packageName);
+
+ /**
+ * One result of the search consists of a new type.
+ *
+ * NOTE - All package and type names are presented in their readable form:
+ * Package names are in the form "a.b.c".
+ * Nested type names are in the qualified form "A.M".
+ * The default package is represented by an empty array.
+ */
+ public void acceptType(char[] packageName, char[] typeName);
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/ISearchableNameEnvironment.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/ISearchableNameEnvironment.java
new file mode 100644
index 0000000..57cfbd5
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/codeassist/ISearchableNameEnvironment.java
@@ -0,0 +1,48 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.codeassist;
+
+import net.sourceforge.phpdt.internal.compiler.env.INameEnvironment;
+
+/**
+ * This interface defines the API that may be used to implement any
+ * search-based tool (such as a CodeAssist, a Finder, ...).
+ * It is mainly used to hide from the search tool the implementation
+ * of the underlying environment and its constructions.
+ */
+public interface ISearchableNameEnvironment extends INameEnvironment {
+
+ /**
+ * Find the packages that start with the given prefix.
+ * A valid prefix is a qualified name separated by periods
+ * (ex. java.util).
+ * The packages found are passed to:
+ * ISearchRequestor.acceptPackage(char[][] packageName)
+ */
+ void findPackages(char[] prefix, ISearchRequestor requestor);
+
+ /**
+ * Find the top-level types (classes and interfaces) that are defined
+ * in the current environment and whose name starts with the
+ * given prefix. The prefix is a qualified name separated by periods
+ * or a simple name (ex. java.util.V or V).
+ *
+ * The types found are passed to one of the following methods (if additional
+ * information is known about the types):
+ * ISearchRequestor.acceptType(char[][] packageName, char[] typeName)
+ * ISearchRequestor.acceptClass(char[][] packageName, char[] typeName, int modifiers)
+ * ISearchRequestor.acceptInterface(char[][] packageName, char[] typeName, int modifiers)
+ *
+ * This method can not be used to find member types... member
+ * types are found relative to their enclosing type.
+ */
+ void findTypes(char[] prefix, ISearchRequestor requestor);
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/AbstractSyntaxTreeVisitorAdapter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/AbstractSyntaxTreeVisitorAdapter.java
new file mode 100644
index 0000000..3185e97
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/AbstractSyntaxTreeVisitorAdapter.java
@@ -0,0 +1,569 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.compiler;
+
+import net.sourceforge.phpdt.core.compiler.IProblem;
+import net.sourceforge.phpdt.internal.compiler.lookup.BlockScope;
+import net.sourceforge.phpdt.internal.compiler.lookup.ClassScope;
+import net.sourceforge.phpdt.internal.compiler.lookup.CompilationUnitScope;
+import net.sourceforge.phpdt.internal.compiler.lookup.MethodScope;
+import net.sourceforge.phpeclipse.internal.compiler.ast.AND_AND_Expression;
+import net.sourceforge.phpeclipse.internal.compiler.ast.AllocationExpression;
+import net.sourceforge.phpeclipse.internal.compiler.ast.AnonymousLocalTypeDeclaration;
+import net.sourceforge.phpeclipse.internal.compiler.ast.Argument;
+import net.sourceforge.phpeclipse.internal.compiler.ast.ArrayAllocationExpression;
+import net.sourceforge.phpeclipse.internal.compiler.ast.ArrayInitializer;
+import net.sourceforge.phpeclipse.internal.compiler.ast.ArrayQualifiedTypeReference;
+import net.sourceforge.phpeclipse.internal.compiler.ast.ArrayReference;
+import net.sourceforge.phpeclipse.internal.compiler.ast.ArrayTypeReference;
+import net.sourceforge.phpeclipse.internal.compiler.ast.AssertStatement;
+import net.sourceforge.phpeclipse.internal.compiler.ast.Assignment;
+import net.sourceforge.phpeclipse.internal.compiler.ast.BinaryExpression;
+import net.sourceforge.phpeclipse.internal.compiler.ast.Block;
+import net.sourceforge.phpeclipse.internal.compiler.ast.Break;
+import net.sourceforge.phpeclipse.internal.compiler.ast.Case;
+import net.sourceforge.phpeclipse.internal.compiler.ast.CastExpression;
+import net.sourceforge.phpeclipse.internal.compiler.ast.CharLiteral;
+import net.sourceforge.phpeclipse.internal.compiler.ast.ClassLiteralAccess;
+import net.sourceforge.phpeclipse.internal.compiler.ast.Clinit;
+import net.sourceforge.phpeclipse.internal.compiler.ast.CompilationUnitDeclaration;
+import net.sourceforge.phpeclipse.internal.compiler.ast.CompoundAssignment;
+import net.sourceforge.phpeclipse.internal.compiler.ast.ConditionalExpression;
+import net.sourceforge.phpeclipse.internal.compiler.ast.ConstructorDeclaration;
+import net.sourceforge.phpeclipse.internal.compiler.ast.Continue;
+import net.sourceforge.phpeclipse.internal.compiler.ast.DefaultCase;
+import net.sourceforge.phpeclipse.internal.compiler.ast.DoStatement;
+import net.sourceforge.phpeclipse.internal.compiler.ast.DoubleLiteral;
+import net.sourceforge.phpeclipse.internal.compiler.ast.EmptyStatement;
+import net.sourceforge.phpeclipse.internal.compiler.ast.EqualExpression;
+import net.sourceforge.phpeclipse.internal.compiler.ast.ExplicitConstructorCall;
+import net.sourceforge.phpeclipse.internal.compiler.ast.ExtendedStringLiteral;
+import net.sourceforge.phpeclipse.internal.compiler.ast.FalseLiteral;
+import net.sourceforge.phpeclipse.internal.compiler.ast.FieldDeclaration;
+import net.sourceforge.phpeclipse.internal.compiler.ast.FieldReference;
+import net.sourceforge.phpeclipse.internal.compiler.ast.FloatLiteral;
+import net.sourceforge.phpeclipse.internal.compiler.ast.ForStatement;
+import net.sourceforge.phpeclipse.internal.compiler.ast.IfStatement;
+import net.sourceforge.phpeclipse.internal.compiler.ast.ImportReference;
+import net.sourceforge.phpeclipse.internal.compiler.ast.Initializer;
+import net.sourceforge.phpeclipse.internal.compiler.ast.InstanceOfExpression;
+import net.sourceforge.phpeclipse.internal.compiler.ast.IntLiteral;
+import net.sourceforge.phpeclipse.internal.compiler.ast.LabeledStatement;
+import net.sourceforge.phpeclipse.internal.compiler.ast.LocalDeclaration;
+import net.sourceforge.phpeclipse.internal.compiler.ast.LocalTypeDeclaration;
+import net.sourceforge.phpeclipse.internal.compiler.ast.LongLiteral;
+import net.sourceforge.phpeclipse.internal.compiler.ast.MemberTypeDeclaration;
+import net.sourceforge.phpeclipse.internal.compiler.ast.MessageSend;
+import net.sourceforge.phpeclipse.internal.compiler.ast.MethodDeclaration;
+import net.sourceforge.phpeclipse.internal.compiler.ast.NullLiteral;
+import net.sourceforge.phpeclipse.internal.compiler.ast.OR_OR_Expression;
+import net.sourceforge.phpeclipse.internal.compiler.ast.PostfixExpression;
+import net.sourceforge.phpeclipse.internal.compiler.ast.PrefixExpression;
+import net.sourceforge.phpeclipse.internal.compiler.ast.QualifiedAllocationExpression;
+import net.sourceforge.phpeclipse.internal.compiler.ast.QualifiedNameReference;
+import net.sourceforge.phpeclipse.internal.compiler.ast.QualifiedSuperReference;
+import net.sourceforge.phpeclipse.internal.compiler.ast.QualifiedThisReference;
+import net.sourceforge.phpeclipse.internal.compiler.ast.QualifiedTypeReference;
+import net.sourceforge.phpeclipse.internal.compiler.ast.ReturnStatement;
+import net.sourceforge.phpeclipse.internal.compiler.ast.SingleNameReference;
+import net.sourceforge.phpeclipse.internal.compiler.ast.SingleTypeReference;
+import net.sourceforge.phpeclipse.internal.compiler.ast.StringLiteral;
+import net.sourceforge.phpeclipse.internal.compiler.ast.SuperReference;
+import net.sourceforge.phpeclipse.internal.compiler.ast.SwitchStatement;
+import net.sourceforge.phpeclipse.internal.compiler.ast.SynchronizedStatement;
+import net.sourceforge.phpeclipse.internal.compiler.ast.ThisReference;
+import net.sourceforge.phpeclipse.internal.compiler.ast.ThrowStatement;
+import net.sourceforge.phpeclipse.internal.compiler.ast.TrueLiteral;
+import net.sourceforge.phpeclipse.internal.compiler.ast.TryStatement;
+import net.sourceforge.phpeclipse.internal.compiler.ast.TypeDeclaration;
+import net.sourceforge.phpeclipse.internal.compiler.ast.UnaryExpression;
+import net.sourceforge.phpeclipse.internal.compiler.ast.WhileStatement;
+
+
+/**
+ * An adapter class for interating through the parse tree.
+ */
+
+public class AbstractSyntaxTreeVisitorAdapter implements IAbstractSyntaxTreeVisitor {
+
+ public void acceptProblem(IProblem problem) {}
+ public void endVisit(
+ AllocationExpression allocationExpression,
+ BlockScope scope) {
+ }
+ public void endVisit(AND_AND_Expression and_and_Expression, BlockScope scope) {
+ }
+ public void endVisit(
+ AnonymousLocalTypeDeclaration anonymousTypeDeclaration,
+ BlockScope scope) {
+ }
+ public void endVisit(Argument argument, BlockScope scope) {
+ }
+ public void endVisit(
+ ArrayAllocationExpression arrayAllocationExpression,
+ BlockScope scope) {
+ }
+ public void endVisit(ArrayInitializer arrayInitializer, BlockScope scope) {
+ }
+ public void endVisit(
+ ArrayQualifiedTypeReference arrayQualifiedTypeReference,
+ BlockScope scope) {
+ }
+ public void endVisit(
+ ArrayQualifiedTypeReference arrayQualifiedTypeReference,
+ ClassScope scope) {
+ }
+ public void endVisit(ArrayReference arrayReference, BlockScope scope) {
+ }
+ public void endVisit(ArrayTypeReference arrayTypeReference, BlockScope scope) {
+ }
+ public void endVisit(ArrayTypeReference arrayTypeReference, ClassScope scope) {
+ }
+ public void endVisit(Assignment assignment, BlockScope scope) {
+ }
+ public void endVisit(AssertStatement assertStatement, BlockScope scope) {
+ }
+ public void endVisit(BinaryExpression binaryExpression, BlockScope scope) {
+ }
+ public void endVisit(Block block, BlockScope scope) {
+ }
+ public void endVisit(Break breakStatement, BlockScope scope) {
+ }
+ public void endVisit(Case caseStatement, BlockScope scope) {
+ }
+ public void endVisit(CastExpression castExpression, BlockScope scope) {
+ }
+ public void endVisit(CharLiteral charLiteral, BlockScope scope) {
+ }
+ public void endVisit(ClassLiteralAccess classLiteral, BlockScope scope) {
+ }
+ public void endVisit(Clinit clinit, ClassScope scope) {
+ }
+ public void endVisit(
+ CompilationUnitDeclaration compilationUnitDeclaration,
+ CompilationUnitScope scope) {
+ }
+ public void endVisit(CompoundAssignment compoundAssignment, BlockScope scope) {
+ }
+ public void endVisit(
+ ConditionalExpression conditionalExpression,
+ BlockScope scope) {
+ }
+ public void endVisit(
+ ConstructorDeclaration constructorDeclaration,
+ ClassScope scope) {
+ }
+ public void endVisit(Continue continueStatement, BlockScope scope) {
+ }
+ public void endVisit(DefaultCase defaultCaseStatement, BlockScope scope) {
+ }
+ public void endVisit(DoStatement doStatement, BlockScope scope) {
+ }
+ public void endVisit(DoubleLiteral doubleLiteral, BlockScope scope) {
+ }
+ public void endVisit(EqualExpression equalExpression, BlockScope scope) {
+ }
+ public void endVisit(
+ ExplicitConstructorCall explicitConstructor,
+ BlockScope scope) {
+ }
+ public void endVisit(
+ ExtendedStringLiteral extendedStringLiteral,
+ BlockScope scope) {
+ }
+ public void endVisit(FalseLiteral falseLiteral, BlockScope scope) {
+ }
+ public void endVisit(FieldDeclaration fieldDeclaration, MethodScope scope) {
+ }
+ public void endVisit(FieldReference fieldReference, BlockScope scope) {
+ }
+ public void endVisit(FloatLiteral floatLiteral, BlockScope scope) {
+ }
+ public void endVisit(EmptyStatement emptyStatement, BlockScope scope) {
+ }
+ public void endVisit(ForStatement forStatement, BlockScope scope) {
+ }
+ public void endVisit(IfStatement ifStatement, BlockScope scope) {
+ }
+ public void endVisit(ImportReference importRef, CompilationUnitScope scope) {
+ }
+ public void endVisit(Initializer initializer, MethodScope scope) {
+ }
+ public void endVisit(
+ InstanceOfExpression instanceOfExpression,
+ BlockScope scope) {
+ }
+ public void endVisit(IntLiteral intLiteral, BlockScope scope) {
+ }
+ public void endVisit(LabeledStatement labeledStatement, BlockScope scope) {
+ }
+ public void endVisit(LocalDeclaration localDeclaration, BlockScope scope) {
+ }
+ public void endVisit(LongLiteral longLiteral, BlockScope scope) {
+ }
+ public void endVisit(
+ MemberTypeDeclaration memberTypeDeclaration,
+ ClassScope scope) {
+ }
+ public void endVisit(MessageSend messageSend, BlockScope scope) {
+ }
+ public void endVisit(MethodDeclaration methodDeclaration, ClassScope scope) {
+ }
+ public void endVisit(NullLiteral nullLiteral, BlockScope scope) {
+ }
+ public void endVisit(OR_OR_Expression or_or_Expression, BlockScope scope) {
+ }
+ public void endVisit(PostfixExpression postfixExpression, BlockScope scope) {
+ }
+ public void endVisit(PrefixExpression prefixExpression, BlockScope scope) {
+ }
+ public void endVisit(
+ QualifiedAllocationExpression qualifiedAllocationExpression,
+ BlockScope scope) {
+ }
+ public void endVisit(
+ QualifiedNameReference qualifiedNameReference,
+ BlockScope scope) {
+ }
+ public void endVisit(
+ QualifiedSuperReference qualifiedSuperReference,
+ BlockScope scope) {
+ }
+ public void endVisit(
+ QualifiedThisReference qualifiedThisReference,
+ BlockScope scope) {
+ }
+ public void endVisit(
+ QualifiedTypeReference qualifiedTypeReference,
+ BlockScope scope) {
+ }
+ public void endVisit(
+ QualifiedTypeReference qualifiedTypeReference,
+ ClassScope scope) {
+ }
+ public void endVisit(ReturnStatement returnStatement, BlockScope scope) {
+ }
+ public void endVisit(
+ SingleNameReference singleNameReference,
+ BlockScope scope) {
+ }
+ public void endVisit(
+ SingleTypeReference singleTypeReference,
+ BlockScope scope) {
+ }
+ public void endVisit(
+ SingleTypeReference singleTypeReference,
+ ClassScope scope) {
+ }
+ public void endVisit(StringLiteral stringLiteral, BlockScope scope) {
+ }
+ public void endVisit(SuperReference superReference, BlockScope scope) {
+ }
+ public void endVisit(SwitchStatement switchStatement, BlockScope scope) {
+ }
+ public void endVisit(
+ SynchronizedStatement synchronizedStatement,
+ BlockScope scope) {
+ }
+ public void endVisit(ThisReference thisReference, BlockScope scope) {
+ }
+ public void endVisit(ThrowStatement throwStatement, BlockScope scope) {
+ }
+ public void endVisit(TrueLiteral trueLiteral, BlockScope scope) {
+ }
+ public void endVisit(TryStatement tryStatement, BlockScope scope) {
+ }
+ public void endVisit(
+ TypeDeclaration typeDeclaration,
+ CompilationUnitScope scope) {
+ }
+ public void endVisit(UnaryExpression unaryExpression, BlockScope scope) {
+ }
+ public void endVisit(WhileStatement whileStatement, BlockScope scope) {
+ }
+ public boolean visit(
+ AllocationExpression allocationExpression,
+ BlockScope scope) {
+ return true;
+ }
+ public boolean visit(AND_AND_Expression and_and_Expression, BlockScope scope) {
+ return true;
+ }
+ public boolean visit(
+ AnonymousLocalTypeDeclaration anonymousTypeDeclaration,
+ BlockScope scope) {
+ return true;
+ }
+ public boolean visit(Argument argument, BlockScope scope) {
+ return true;
+ }
+ public boolean visit(
+ ArrayAllocationExpression arrayAllocationExpression,
+ BlockScope scope) {
+ return true;
+ }
+ public boolean visit(ArrayInitializer arrayInitializer, BlockScope scope) {
+ return true;
+ }
+ public boolean visit(
+ ArrayQualifiedTypeReference arrayQualifiedTypeReference,
+ BlockScope scope) {
+ return true;
+ }
+ public boolean visit(
+ ArrayQualifiedTypeReference arrayQualifiedTypeReference,
+ ClassScope scope) {
+ return true;
+ }
+ public boolean visit(ArrayReference arrayReference, BlockScope scope) {
+ return true;
+ }
+ public boolean visit(ArrayTypeReference arrayTypeReference, BlockScope scope) {
+ return true;
+ }
+ public boolean visit(ArrayTypeReference arrayTypeReference, ClassScope scope) {
+ return true;
+ }
+ public boolean visit(Assignment assignment, BlockScope scope) {
+ return true;
+ }
+ public boolean visit(AssertStatement assertStatement, BlockScope scope) {
+ return true;
+ }
+ public boolean visit(BinaryExpression binaryExpression, BlockScope scope) {
+ return true;
+ }
+ public boolean visit(Block block, BlockScope scope) {
+ return true;
+ }
+ public boolean visit(Break breakStatement, BlockScope scope) {
+ return true;
+ }
+ public boolean visit(Case caseStatement, BlockScope scope) {
+ return true;
+ }
+ public boolean visit(CastExpression castExpression, BlockScope scope) {
+ return true;
+ }
+ public boolean visit(CharLiteral charLiteral, BlockScope scope) {
+ return true;
+ }
+ public boolean visit(ClassLiteralAccess classLiteral, BlockScope scope) {
+ return true;
+ }
+ public boolean visit(Clinit clinit, ClassScope scope) {
+ return true;
+ }
+ public boolean visit(
+ CompilationUnitDeclaration compilationUnitDeclaration,
+ CompilationUnitScope scope) {
+ return true;
+ }
+ public boolean visit(CompoundAssignment compoundAssignment, BlockScope scope) {
+ return true;
+ }
+ public boolean visit(
+ ConditionalExpression conditionalExpression,
+ BlockScope scope) {
+ return true;
+ }
+ public boolean visit(
+ ConstructorDeclaration constructorDeclaration,
+ ClassScope scope) {
+ return true;
+ }
+ public boolean visit(Continue continueStatement, BlockScope scope) {
+ return true;
+ }
+ public boolean visit(DefaultCase defaultCaseStatement, BlockScope scope) {
+ return true;
+ }
+ public boolean visit(DoStatement doStatement, BlockScope scope) {
+ return true;
+ }
+ public boolean visit(DoubleLiteral doubleLiteral, BlockScope scope) {
+ return true;
+ }
+ public boolean visit(EqualExpression equalExpression, BlockScope scope) {
+ return true;
+ }
+ public boolean visit(EmptyStatement emptyStatement, BlockScope scope) {
+ return true;
+ }
+ public boolean visit(
+ ExplicitConstructorCall explicitConstructor,
+ BlockScope scope) {
+ return true;
+ }
+ public boolean visit(
+ ExtendedStringLiteral extendedStringLiteral,
+ BlockScope scope) {
+ return true;
+ }
+ public boolean visit(FalseLiteral falseLiteral, BlockScope scope) {
+ return true;
+ }
+ public boolean visit(FieldDeclaration fieldDeclaration, MethodScope scope) {
+ return true;
+ }
+ public boolean visit(FieldReference fieldReference, BlockScope scope) {
+ return true;
+ }
+ public boolean visit(FloatLiteral floatLiteral, BlockScope scope) {
+ return true;
+ }
+ public boolean visit(ForStatement forStatement, BlockScope scope) {
+ return true;
+ }
+ public boolean visit(IfStatement ifStatement, BlockScope scope) {
+ return true;
+ }
+ public boolean visit(ImportReference importRef, CompilationUnitScope scope) {
+ return true;
+ }
+ public boolean visit(Initializer initializer, MethodScope scope) {
+ return true;
+ }
+ public boolean visit(
+ InstanceOfExpression instanceOfExpression,
+ BlockScope scope) {
+ return true;
+ }
+ public boolean visit(IntLiteral intLiteral, BlockScope scope) {
+ return true;
+ }
+ public boolean visit(LabeledStatement labeledStatement, BlockScope scope) {
+ return true;
+ }
+ public boolean visit(LocalDeclaration localDeclaration, BlockScope scope) {
+ return true;
+ }
+ public boolean visit(LongLiteral longLiteral, BlockScope scope) {
+ return true;
+ }
+ public boolean visit(
+ MemberTypeDeclaration memberTypeDeclaration,
+ ClassScope scope) {
+ return true;
+ }
+ public boolean visit(MessageSend messageSend, BlockScope scope) {
+ return true;
+ }
+ public boolean visit(MethodDeclaration methodDeclaration, ClassScope scope) {
+ return true;
+ }
+ public boolean visit(NullLiteral nullLiteral, BlockScope scope) {
+ return true;
+ }
+ public boolean visit(OR_OR_Expression or_or_Expression, BlockScope scope) {
+ return true;
+ }
+ public boolean visit(PostfixExpression postfixExpression, BlockScope scope) {
+ return true;
+ }
+ public boolean visit(PrefixExpression prefixExpression, BlockScope scope) {
+ return true;
+ }
+ public boolean visit(
+ QualifiedAllocationExpression qualifiedAllocationExpression,
+ BlockScope scope) {
+ return true;
+ }
+ public boolean visit(
+ QualifiedNameReference qualifiedNameReference,
+ BlockScope scope) {
+ return true;
+ }
+ public boolean visit(
+ QualifiedSuperReference qualifiedSuperReference,
+ BlockScope scope) {
+ return true;
+ }
+ public boolean visit(
+ QualifiedThisReference qualifiedThisReference,
+ BlockScope scope) {
+ return true;
+ }
+ public boolean visit(
+ QualifiedTypeReference qualifiedTypeReference,
+ BlockScope scope) {
+ return true;
+ }
+ public boolean visit(
+ QualifiedTypeReference qualifiedTypeReference,
+ ClassScope scope) {
+ return true;
+ }
+ public boolean visit(ReturnStatement returnStatement, BlockScope scope) {
+ return true;
+ }
+ public boolean visit(
+ SingleNameReference singleNameReference,
+ BlockScope scope) {
+ return true;
+ }
+ public boolean visit(
+ SingleTypeReference singleTypeReference,
+ BlockScope scope) {
+ return true;
+ }
+ public boolean visit(
+ SingleTypeReference singleTypeReference,
+ ClassScope scope) {
+ return true;
+ }
+ public boolean visit(StringLiteral stringLiteral, BlockScope scope) {
+ return true;
+ }
+ public boolean visit(SuperReference superReference, BlockScope scope) {
+ return true;
+ }
+ public boolean visit(SwitchStatement switchStatement, BlockScope scope) {
+ return true;
+ }
+ public boolean visit(
+ SynchronizedStatement synchronizedStatement,
+ BlockScope scope) {
+ return true;
+ }
+ public boolean visit(ThisReference thisReference, BlockScope scope) {
+ return true;
+ }
+ public boolean visit(ThrowStatement throwStatement, BlockScope scope) {
+ return true;
+ }
+ public boolean visit(TrueLiteral trueLiteral, BlockScope scope) {
+ return true;
+ }
+ public boolean visit(TryStatement tryStatement, BlockScope scope) {
+ return true;
+ }
+ public boolean visit(
+ TypeDeclaration typeDeclaration,
+ CompilationUnitScope scope) {
+ return true;
+ }
+ public boolean visit(UnaryExpression unaryExpression, BlockScope scope) {
+ return true;
+ }
+ public boolean visit(WhileStatement whileStatement, BlockScope scope) {
+ return true;
+ }
+ public boolean visit(
+ LocalTypeDeclaration localTypeDeclaration,
+ BlockScope scope) {
+ return true;
+ }
+ public void endVisit(
+ LocalTypeDeclaration localTypeDeclaration,
+ BlockScope scope) {
+ }
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/CompilationResult.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/CompilationResult.java
new file mode 100644
index 0000000..90d5434
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/CompilationResult.java
@@ -0,0 +1,430 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.compiler;
+
+/**
+ * A compilation result consists of all information returned by the compiler for
+ * a single compiled compilation source unit. This includes:
+ * boolean
+ * This parameter is used to optimize the literals or leave them as they are in the source.
+ * If you put true, "Hello" + " world" will be converted to "Hello world".
+ */
+ public Compiler(
+ INameEnvironment environment,
+ IErrorHandlingPolicy policy,
+// Map settings,
+ final ICompilerRequestor requestor,
+ IProblemFactory problemFactory,
+ boolean parseLiteralExpressionsAsConstants) {
+
+ // create a problem handler given a handling policy
+// this.options = new CompilerOptions(settings);
+
+ // wrap requestor in DebugRequestor if one is specified
+// if(DebugRequestor == null) {
+ this.requestor = requestor;
+// } else {
+// this.requestor = new ICompilerRequestor(){
+// public void acceptResult(CompilationResult result){
+// if (DebugRequestor.isActive()){
+// DebugRequestor.acceptDebugResult(result);
+// }
+// requestor.acceptResult(result);
+// }
+// };
+// }
+ this.problemReporter =
+ new ProblemReporter(policy, problemFactory);//, this.options, problemFactory);
+ this.lookupEnvironment =
+ new LookupEnvironment(this, problemReporter, environment);//options, problemReporter, environment);
+ this.parser =
+ new UnitParser(
+ problemReporter);
+// parseLiteralExpressionsAsConstants,
+ // this.options.sourceLevel >= CompilerOptions.JDK1_4);
+ }
+
+ /**
+ * Add an additional binary type
+ */
+ public void accept(IBinaryType binaryType, PackageBinding packageBinding) {
+ lookupEnvironment.createBinaryTypeFrom(binaryType, packageBinding);
+ }
+
+ /**
+ * Add an additional compilation unit into the loop
+ * -> build compilation unit declarations, their bindings and record their results.
+ */
+ public void accept(ICompilationUnit sourceUnit) {
+ // Switch the current policy and compilation result for this unit to the requested one.
+ CompilationResult unitResult =
+ new CompilationResult(sourceUnit, totalUnits, totalUnits, 10); //this.options.maxProblemsPerUnit);
+ try {
+ // diet parsing for large collection of unit
+ CompilationUnitDeclaration parsedUnit;
+ if (totalUnits < parseThreshold) {
+ parsedUnit = parser.parse(sourceUnit, unitResult);
+ } else {
+ parsedUnit = parser.dietParse(sourceUnit, unitResult);
+ }
+
+// if (options.verbose) {
+// String count = String.valueOf(totalUnits + 1);
+// System.out.println(
+// Util.bind(
+// "compilation.request" , //$NON-NLS-1$
+// new String[] {
+// count,
+// count,
+// new String(sourceUnit.getFileName())}));
+// }
+
+ // initial type binding creation
+ lookupEnvironment.buildTypeBindings(parsedUnit);
+ this.addCompilationUnit(sourceUnit, parsedUnit);
+
+ // binding resolution
+ lookupEnvironment.completeTypeBindings(parsedUnit);
+ } catch (AbortCompilationUnit e) {
+ // at this point, currentCompilationUnitResult may not be sourceUnit, but some other
+ // one requested further along to resolve sourceUnit.
+ if (unitResult.compilationUnit == sourceUnit) { // only report once
+ requestor.acceptResult(unitResult.tagAsAccepted());
+ } else {
+ throw e; // want to abort enclosing request to compile
+ }
+ }
+ }
+
+ /**
+ * Add additional source types
+ */
+ public void accept(ISourceType[] sourceTypes, PackageBinding packageBinding) {
+ problemReporter.abortDueToInternalError(
+ Util.bind(
+ "abort.againstSourceModel " , //$NON-NLS-1$
+ String.valueOf(sourceTypes[0].getName()),
+ String.valueOf(sourceTypes[0].getFileName())));
+ }
+
+ protected void addCompilationUnit(
+ ICompilationUnit sourceUnit,
+ CompilationUnitDeclaration parsedUnit) {
+
+ // append the unit to the list of ones to process later on
+ int size = unitsToProcess.length;
+ if (totalUnits == size)
+ // when growing reposition units starting at position 0
+ System.arraycopy(
+ unitsToProcess,
+ 0,
+ (unitsToProcess = new CompilationUnitDeclaration[size * 2]),
+ 0,
+ totalUnits);
+ unitsToProcess[totalUnits++] = parsedUnit;
+ }
+
+ /**
+ * Add the initial set of compilation units into the loop
+ * -> build compilation unit declarations, their bindings and record their results.
+ */
+ protected void beginToCompile(ICompilationUnit[] sourceUnits) {
+ int maxUnits = sourceUnits.length;
+ totalUnits = 0;
+ unitsToProcess = new CompilationUnitDeclaration[maxUnits];
+
+ // Switch the current policy and compilation result for this unit to the requested one.
+ for (int i = 0; i < maxUnits; i++) {
+ CompilationUnitDeclaration parsedUnit;
+ CompilationResult unitResult =
+ new CompilationResult(sourceUnits[i], i, maxUnits, 10);//, this.options.maxProblemsPerUnit);
+ try {
+ // diet parsing for large collection of units
+ if (totalUnits < parseThreshold) {
+ parsedUnit = parser.parse(sourceUnits[i], unitResult);
+ } else {
+ parsedUnit = parser.dietParse(sourceUnits[i], unitResult);
+ }
+// if (options.verbose) {
+// System.out.println(
+// Util.bind(
+// "compilation.request" , //$NON-NLS-1$
+// new String[] {
+// String.valueOf(i + 1),
+// String.valueOf(maxUnits),
+// new String(sourceUnits[i].getFileName())}));
+// }
+ // initial type binding creation
+ lookupEnvironment.buildTypeBindings(parsedUnit);
+ this.addCompilationUnit(sourceUnits[i], parsedUnit);
+ //} catch (AbortCompilationUnit e) {
+ // requestor.acceptResult(unitResult.tagAsAccepted());
+ } finally {
+ sourceUnits[i] = null; // no longer hold onto the unit
+ }
+ }
+ // binding resolution
+ lookupEnvironment.completeTypeBindings();
+ }
+
+ /**
+ * General API
+ * -> compile each of supplied files
+ * -> recompile any required types for which we have an incomplete principle structure
+ */
+ public void compile(ICompilationUnit[] sourceUnits) {
+ CompilationUnitDeclaration unit = null;
+ int i = 0;
+ try {
+ // build and record parsed units
+
+ beginToCompile(sourceUnits);
+
+ // process all units (some more could be injected in the loop by the lookup environment)
+ for (; i < totalUnits; i++) {
+ unit = unitsToProcess[i];
+ try {
+// if (options.verbose)
+// System.out.println(
+// Util.bind(
+// "compilation.process" , //$NON-NLS-1$
+// new String[] {
+// String.valueOf(i + 1),
+// String.valueOf(totalUnits),
+// new String(unitsToProcess[i].getFileName())}));
+ process(unit, i);
+ } finally {
+ // cleanup compilation unit result
+ unit.cleanUp();
+// if (options.verbose)
+// System.out.println(Util.bind("compilation.done", //$NON-NLS-1$
+// new String[] {
+// String.valueOf(i + 1),
+// String.valueOf(totalUnits),
+// new String(unitsToProcess[i].getFileName())}));
+ }
+ unitsToProcess[i] = null; // release reference to processed unit declaration
+ requestor.acceptResult(unit.compilationResult.tagAsAccepted());
+ }
+ } catch (AbortCompilation e) {
+ this.handleInternalException(e, unit);
+ } catch (Error e) {
+ this.handleInternalException(e, unit, null);
+ throw e; // rethrow
+ } catch (RuntimeException e) {
+ this.handleInternalException(e, unit, null);
+ throw e; // rethrow
+ } finally {
+ this.reset();
+ }
+// if (options.verbose) {
+// if (totalUnits > 1) {
+// System.out.println(
+// Util.bind("compilation.units" , String.valueOf(totalUnits))); //$NON-NLS-1$
+// } else {
+// System.out.println(
+// Util.bind("compilation.unit" , String.valueOf(totalUnits))); //$NON-NLS-1$
+// }
+// }
+ }
+
+ protected void getMethodBodies(CompilationUnitDeclaration unit, int place) {
+ //fill the methods bodies in order for the code to be generated
+
+ if (unit.ignoreMethodBodies) {
+ unit.ignoreFurtherInvestigation = true;
+ return;
+ // if initial diet parse did not work, no need to dig into method bodies.
+ }
+
+ if (place < parseThreshold)
+ return; //work already done ...
+
+ //real parse of the method....
+ parser.scanner.setSource(
+ unit.compilationResult.compilationUnit.getContents());
+ if (unit.types != null) {
+ for (int i = unit.types.size(); --i >= 0;)
+ if (unit.types.get(i) instanceof TypeDeclaration) {
+ ((TypeDeclaration)unit.types.get(i)).parseMethod(parser, unit);
+ }
+ }
+ }
+
+ /*
+ * Compiler crash recovery in case of unexpected runtime exceptions
+ */
+ protected void handleInternalException(
+ Throwable internalException,
+ CompilationUnitDeclaration unit,
+ CompilationResult result) {
+
+ /* dump a stack trace to the console */
+ internalException.printStackTrace();
+
+ /* find a compilation result */
+ if ((unit != null)) // basing result upon the current unit if available
+ result = unit.compilationResult; // current unit being processed ?
+ if ((result == null) && (unitsToProcess != null) && (totalUnits > 0))
+ result = unitsToProcess[totalUnits - 1].compilationResult;
+ // last unit in beginToCompile ?
+
+ if (result != null) {
+ /* create and record a compilation problem */
+ StringWriter stringWriter = new StringWriter();
+ PrintWriter writer = new PrintWriter(stringWriter);
+ internalException.printStackTrace(writer);
+ StringBuffer buffer = stringWriter.getBuffer();
+
+ String[] pbArguments = new String[] {
+ Util.bind("compilation.internalError" ) //$NON-NLS-1$
+ + "\n" //$NON-NLS-1$
+ + buffer.toString()};
+
+ result
+ .record(
+ problemReporter
+ .createProblem(
+ result.getFileName(),
+ IProblem.Unclassified,
+ pbArguments,
+ pbArguments,
+ Error, // severity
+ 0, // source start
+ 0, // source end
+ 0, // line number
+ unit,
+ result),
+ unit);
+
+ /* hand back the compilation result */
+ if (!result.hasBeenAccepted) {
+ requestor.acceptResult(result.tagAsAccepted());
+ }
+ }
+ }
+
+ /*
+ * Compiler recovery in case of internal AbortCompilation event
+ */
+ protected void handleInternalException(
+ AbortCompilation abortException,
+ CompilationUnitDeclaration unit) {
+
+ /* special treatment for SilentAbort: silently cancelling the compilation process */
+ if (abortException.isSilent) {
+ if (abortException.silentException == null) {
+ return;
+ } else {
+ throw abortException.silentException;
+ }
+ }
+
+ /* uncomment following line to see where the abort came from */
+ // abortException.printStackTrace();
+
+ // Exception may tell which compilation result it is related, and which problem caused it
+ CompilationResult result = abortException.compilationResult;
+ if ((result == null) && (unit != null))
+ result = unit.compilationResult; // current unit being processed ?
+ if ((result == null) && (unitsToProcess != null) && (totalUnits > 0))
+ result = unitsToProcess[totalUnits - 1].compilationResult;
+ // last unit in beginToCompile ?
+ if (result != null && !result.hasBeenAccepted) {
+ /* distant problem which could not be reported back there */
+ if (abortException.problemId != 0) {
+ result
+ .record(
+ problemReporter
+ .createProblem(
+ result.getFileName(),
+ abortException.problemId,
+ abortException.problemArguments,
+ abortException.messageArguments,
+ Error, // severity
+ 0, // source start
+ 0, // source end
+ 0, // line number
+ unit,
+ result),
+ unit);
+ } else {
+ /* distant internal exception which could not be reported back there */
+ if (abortException.exception != null) {
+ this.handleInternalException(abortException.exception, null, result);
+ return;
+ }
+ }
+ /* hand back the compilation result */
+ if (!result.hasBeenAccepted) {
+ requestor.acceptResult(result.tagAsAccepted());
+ }
+ } else {
+ /*
+ if (abortException.problemId != 0){
+ IProblem problem =
+ problemReporter.createProblem(
+ "???".toCharArray(),
+ abortException.problemId,
+ abortException.problemArguments,
+ Error, // severity
+ 0, // source start
+ 0, // source end
+ 0); // line number
+ System.out.println(problem.getMessage());
+ }
+ */
+ abortException.printStackTrace();
+ }
+ }
+
+ /**
+ * Process a compilation unit already parsed and build.
+ */
+ public void process(CompilationUnitDeclaration unit, int i) {
+
+ getMethodBodies(unit, i);
+
+ // fault in fields & methods
+ if (unit.scope != null)
+ unit.scope.faultInTypes();
+
+ // verify inherited methods
+ if (unit.scope != null)
+ unit.scope.verifyMethods(lookupEnvironment.methodVerifier());
+
+ // type checking
+ unit.resolve();
+
+ // flow analysis
+ unit.analyseCode();
+
+ // code generation
+// unit.generateCode();
+
+ // reference info
+// if (options.produceReferenceInfo && unit.scope != null)
+// unit.scope.storeDependencyInfo();
+
+ // refresh the total number of units known at this stage
+ unit.compilationResult.totalUnitsKnown = totalUnits;
+ }
+ public void reset() {
+ lookupEnvironment.reset();
+ parser.scanner.source = null;
+ unitsToProcess = null;
+// if (DebugRequestor != null) DebugRequestor.reset();
+ }
+
+ /**
+ * Internal API used to resolve a given compilation unit. Can run a subset of the compilation process
+ */
+ public CompilationUnitDeclaration resolve(
+ ICompilationUnit sourceUnit,
+ boolean verifyMethods,
+ boolean analyzeCode) {
+// boolean generateCode) {
+
+ CompilationUnitDeclaration unit = null;
+ try {
+ // build and record parsed units
+ parseThreshold = 0; // will request a full parse
+ beginToCompile(new ICompilationUnit[] { sourceUnit });
+ // process all units (some more could be injected in the loop by the lookup environment)
+ unit = unitsToProcess[0];
+ getMethodBodies(unit, 0);
+ if (unit.scope != null) {
+// // fault in fields & methods
+// unit.scope.faultInTypes();
+
+// if (unit.scope != null && verifyMethods) {
+// // http://dev.eclipse.org/bugs/show_bug.cgi?id=23117
+// // verify inherited methods
+// unit.scope.verifyMethods(lookupEnvironment.methodVerifier());
+// }
+// // type checking
+// unit.resolve();
+
+ // flow analysis
+// if (analyzeCode) unit.analyseCode();
+
+ // code generation
+// if (generateCode) unit.generateCode();
+ }
+ unitsToProcess[0] = null; // release reference to processed unit declaration
+ requestor.acceptResult(unit.compilationResult.tagAsAccepted());
+ return unit;
+ } catch (AbortCompilation e) {
+ this.handleInternalException(e, unit);
+ return unit == null ? unitsToProcess[0] : unit;
+ } catch (Error e) {
+ this.handleInternalException(e, unit, null);
+ throw e; // rethrow
+ } catch (RuntimeException e) {
+ this.handleInternalException(e, unit, null);
+ throw e; // rethrow
+ } finally {
+ // No reset is performed there anymore since,
+ // within the CodeAssist (or related tools),
+ // the compiler may be called *after* a call
+ // to this resolve(...) method. And such a call
+ // needs to have a compiler with a non-empty
+ // environment.
+ // this.reset();
+ }
+ }
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/DefaultErrorHandlingPolicies.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/DefaultErrorHandlingPolicies.java
new file mode 100644
index 0000000..19152b4
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/DefaultErrorHandlingPolicies.java
@@ -0,0 +1,75 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.compiler;
+
+public class DefaultErrorHandlingPolicies {
+
+/*
+ * Accumulate all problems, then exit without proceeding.
+ *
+ * Typically, the #proceedWithProblems(Problem[]) should
+ * show the problems.
+ *
+ */
+public static IErrorHandlingPolicy exitAfterAllProblems() {
+ return new IErrorHandlingPolicy() {
+ public boolean stopOnFirstError() {
+ return false;
+ }
+ public boolean proceedOnErrors(){
+ return false;
+ }
+ };
+}
+/*
+ * Exit without proceeding on the first problem wich appears
+ * to be an error.
+ *
+ */
+public static IErrorHandlingPolicy exitOnFirstError() {
+ return new IErrorHandlingPolicy() {
+ public boolean stopOnFirstError() {
+ return true;
+ }
+ public boolean proceedOnErrors(){
+ return false;
+ }
+ };
+}
+/*
+ * Proceed on the first error met.
+ *
+ */
+public static IErrorHandlingPolicy proceedOnFirstError() {
+ return new IErrorHandlingPolicy() {
+ public boolean stopOnFirstError() {
+ return true;
+ }
+ public boolean proceedOnErrors(){
+ return true;
+ }
+ };
+}
+/*
+ * Accumulate all problems, then proceed with them.
+ *
+ */
+public static IErrorHandlingPolicy proceedWithAllProblems() {
+ return new IErrorHandlingPolicy() {
+ public boolean stopOnFirstError() {
+ return false;
+ }
+ public boolean proceedOnErrors(){
+ return true;
+ }
+ };
+}
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/DocumentElementParser.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/DocumentElementParser.java
new file mode 100644
index 0000000..f2cb849
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/DocumentElementParser.java
@@ -0,0 +1,1319 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.compiler;
+
+import net.sourceforge.phpdt.core.compiler.CharOperation;
+import net.sourceforge.phpdt.core.compiler.IProblem;
+import net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit;
+import net.sourceforge.phpdt.internal.compiler.parser.UnitParser;
+import net.sourceforge.phpdt.internal.compiler.problem.AbortCompilation;
+import net.sourceforge.phpdt.internal.compiler.problem.ProblemReporter;
+import net.sourceforge.phpeclipse.internal.compiler.ast.CompilationUnitDeclaration;
+
+import org.eclipse.core.runtime.CoreException;
+
+
+/*
+ * A document element parser extracts structural information
+ * from a piece of source, providing detailed source positions info.
+ *
+ * also see @IDocumentElementRequestor
+ *
+ * The structural investigation includes:
+ * - the package statement
+ * - import statements
+ * - top-level types: package member, member types (member types of member types...)
+ * - fields
+ * - methods
+ *
+ * Any (parsing) problem encountered is also provided.
+ */
+public class DocumentElementParser extends UnitParser {
+ IDocumentElementRequestor requestor;
+ private int localIntPtr;
+ private int lastFieldEndPosition;
+ private int lastFieldBodyEndPosition;
+ private int typeStartPosition;
+ private long selectorSourcePositions;
+ private int typeDims;
+ private int extendsDim;
+ private int declarationSourceStart;
+
+ /* int[] stack for storing javadoc positions */
+ int[][] intArrayStack;
+ int intArrayPtr;
+
+// CompilerOptions options;
+
+public DocumentElementParser(
+ final IDocumentElementRequestor requestor,
+ IProblemFactory problemFactory) {
+// CompilerOptions options) {
+ super(new ProblemReporter(
+ DefaultErrorHandlingPolicies.exitAfterAllProblems(),
+// options,
+ problemFactory) {
+ public void record(IProblem problem, CompilationResult unitResult) {
+ requestor.acceptProblem(problem);
+ }
+ });
+// false,
+// options.sourceLevel >= CompilerOptions.JDK1_4);
+ this.requestor = requestor;
+ intArrayStack = new int[30][];
+// this.options = options;
+}
+
+/**
+ *
+ * INTERNAL USE-ONLY
+ */
+//protected void adjustInterfaceModifiers() {
+// intStack[intPtr - 2] |= AccInterface;
+//}
+/*
+ * Will clear the comment stack when looking
+ * for a potential JavaDoc which might contain @deprecated.
+ *
+ * Additionally, before investigating for @deprecated, retrieve the positions
+ * of the JavaDoc comments so as to notify requestor with them.
+ */
+//public void checkAnnotation() {
+//
+// /* persisting javadoc positions */
+// pushOnIntArrayStack(this.getJavaDocPositions());
+// boolean deprecated = false;
+// int lastAnnotationIndex = -1;
+// int commentPtr = scanner.commentPtr;
+//
+// //since jdk1.2 look only in the last java doc comment...
+// nextComment : for (lastAnnotationIndex = scanner.commentPtr; lastAnnotationIndex >= 0; lastAnnotationIndex--){
+// //look for @deprecated into the first javadoc comment preceeding the declaration
+// int commentSourceStart = scanner.commentStarts[lastAnnotationIndex];
+// // javadoc only (non javadoc comment have negative end positions.)
+// if (modifiersSourceStart != -1 && modifiersSourceStart < commentSourceStart) {
+// continue nextComment;
+// }
+// if (scanner.commentStops[lastAnnotationIndex] < 0) {
+// continue nextComment;
+// }
+// int commentSourceEnd = scanner.commentStops[lastAnnotationIndex] - 1; //stop is one over
+// char[] comment = scanner.source;
+//
+// deprecated =
+// checkDeprecation(
+// commentSourceStart,
+// commentSourceEnd,
+// comment);
+// break nextComment;
+// }
+// if (deprecated) {
+// checkAndSetModifiers(AccDeprecated);
+// }
+// // modify the modifier source start to point at the first comment
+// if (commentPtr >= 0) {
+// declarationSourceStart = scanner.commentStarts[0];
+// }
+//}
+/**
+ *
+ * INTERNAL USE-ONLY
+ */
+//protected void consumeClassBodyDeclaration() {
+// // ClassBodyDeclaration ::= Diet Block
+// //push an Initializer
+// //optimize the push/pop
+//
+// super.consumeClassBodyDeclaration();
+// Initializer initializer = (Initializer) astStack[astPtr];
+// requestor.acceptInitializer(
+// initializer.declarationSourceStart,
+// initializer.declarationSourceEnd,
+// intArrayStack[intArrayPtr--],
+// 0,
+// modifiersSourceStart,
+// initializer.block.sourceStart,
+// initializer.block.sourceEnd);
+//}
+///**
+// *
+// * INTERNAL USE-ONLY
+// */
+//protected void consumeClassDeclaration() {
+// super.consumeClassDeclaration();
+// // we know that we have a TypeDeclaration on the top of the astStack
+// if (isLocalDeclaration()) {
+// // we ignore the local variable declarations
+// return;
+// }
+// requestor.exitClass(endStatementPosition, // '}' is the end of the body
+// ((TypeDeclaration) astStack[astPtr]).declarationSourceEnd);
+//}
+///**
+// *
+// * INTERNAL USE-ONLY
+// */
+//protected void consumeClassHeader() {
+// //ClassHeader ::= $empty
+// super.consumeClassHeader();
+// if (isLocalDeclaration()) {
+// // we ignore the local variable declarations
+// intArrayPtr--;
+// return;
+// }
+// TypeDeclaration typeDecl = (TypeDeclaration) astStack[astPtr];
+// TypeReference[] superInterfaces = typeDecl.superInterfaces;
+// char[][] interfaceNames = null;
+// int[] interfaceNameStarts = null;
+// int[] interfaceNameEnds = null;
+// if (superInterfaces != null) {
+// int superInterfacesLength = superInterfaces.length;
+// interfaceNames = new char[superInterfacesLength][];
+// interfaceNameStarts = new int[superInterfacesLength];
+// interfaceNameEnds = new int[superInterfacesLength];
+// for (int i = 0; i < superInterfacesLength; i++) {
+// TypeReference superInterface = superInterfaces[i];
+// interfaceNames[i] = CharOperation.concatWith(superInterface.getTypeName(), '.');
+// interfaceNameStarts[i] = superInterface.sourceStart;
+// interfaceNameEnds[i] = superInterface.sourceEnd;
+// }
+// }
+// // flush the comments related to the class header
+// scanner.commentPtr = -1;
+// TypeReference superclass = typeDecl.superclass;
+// if (superclass == null) {
+// requestor.enterClass(
+// typeDecl.declarationSourceStart,
+// intArrayStack[intArrayPtr--],
+// typeDecl.modifiers,
+// typeDecl.modifiersSourceStart,
+// typeStartPosition,
+// typeDecl.name,
+// typeDecl.sourceStart,
+// typeDecl.sourceEnd,
+// null,
+// -1,
+// -1,
+// interfaceNames,
+// interfaceNameStarts,
+// interfaceNameEnds,
+// scanner.currentPosition - 1);
+// } else {
+// requestor.enterClass(
+// typeDecl.declarationSourceStart,
+// intArrayStack[intArrayPtr--],
+// typeDecl.modifiers,
+// typeDecl.modifiersSourceStart,
+// typeStartPosition,
+// typeDecl.name,
+// typeDecl.sourceStart,
+// typeDecl.sourceEnd,
+// CharOperation.concatWith(superclass.getTypeName(), '.'),
+// superclass.sourceStart,
+// superclass.sourceEnd,
+// interfaceNames,
+// interfaceNameStarts,
+// interfaceNameEnds,
+// scanner.currentPosition - 1);
+//
+// }
+//}
+//protected void consumeClassHeaderName() {
+// // ClassHeaderName ::= Modifiersopt 'class' 'Identifier'
+// TypeDeclaration typeDecl;
+// if (nestedMethod[nestedType] == 0) {
+// if (nestedType != 0) {
+// typeDecl = new MemberTypeDeclaration(this.compilationUnit.compilationResult);
+// } else {
+// typeDecl = new TypeDeclaration(this.compilationUnit.compilationResult);
+// }
+// } else {
+// // Record that the block has a declaration for local types
+// typeDecl = new LocalTypeDeclaration(this.compilationUnit.compilationResult);
+// markEnclosingMemberWithLocalType();
+// blockReal();
+// }
+//
+// //highlight the name of the type
+// long pos = identifierPositionStack[identifierPtr];
+// typeDecl.sourceEnd = (int) pos;
+// typeDecl.sourceStart = (int) (pos >>> 32);
+// typeDecl.name = identifierStack[identifierPtr--];
+// identifierLengthPtr--;
+//
+// //compute the declaration source too
+// // 'class' and 'interface' push an int position
+// typeStartPosition = typeDecl.declarationSourceStart = intStack[intPtr--];
+// intPtr--;
+// int declarationSourceStart = intStack[intPtr--];
+// typeDecl.modifiersSourceStart = intStack[intPtr--];
+// typeDecl.modifiers = intStack[intPtr--];
+// if (typeDecl.declarationSourceStart > declarationSourceStart) {
+// typeDecl.declarationSourceStart = declarationSourceStart;
+// }
+// typeDecl.bodyStart = typeDecl.sourceEnd + 1;
+// pushOnAstStack(typeDecl);
+//}
+///**
+// *
+// * INTERNAL USE-ONLY
+// */
+//protected void consumeCompilationUnit() {
+// // CompilationUnit ::= EnterCompilationUnit PackageDeclarationopt ImportDeclarationsopt
+// requestor.exitCompilationUnit(scanner.source.length - 1);
+//}
+/**
+ *
+ * INTERNAL USE-ONLY
+ */
+//protected void consumeConstructorDeclaration() {
+// // ConstructorDeclaration ::= ConstructorHeader ConstructorBody
+// super.consumeConstructorDeclaration();
+// if (isLocalDeclaration()) {
+// // we ignore the local variable declarations
+// return;
+// }
+// ConstructorDeclaration cd = (ConstructorDeclaration) astStack[astPtr];
+// requestor.exitConstructor(endStatementPosition, cd.declarationSourceEnd);
+//}
+///**
+// *
+// * INTERNAL USE-ONLY
+// */
+//protected void consumeConstructorHeader() {
+// // ConstructorHeader ::= ConstructorHeaderName MethodHeaderParameters MethodHeaderThrowsClauseopt
+// super.consumeConstructorHeader();
+// if (isLocalDeclaration()) {
+// // we ignore the local variable declarations
+// intArrayPtr--;
+// return;
+// }
+// ConstructorDeclaration cd = (ConstructorDeclaration) astStack[astPtr];
+// Argument[] arguments = cd.arguments;
+// char[][] argumentTypes = null;
+// char[][] argumentNames = null;
+// int[] argumentTypeStarts = null;
+// int[] argumentTypeEnds = null;
+// int[] argumentNameStarts = null;
+// int[] argumentNameEnds = null;
+// if (arguments != null) {
+// int argumentLength = arguments.length;
+// argumentTypes = new char[argumentLength][];
+// argumentNames = new char[argumentLength][];
+// argumentNameStarts = new int[argumentLength];
+// argumentNameEnds = new int[argumentLength];
+// argumentTypeStarts = new int[argumentLength];
+// argumentTypeEnds = new int[argumentLength];
+// for (int i = 0; i < argumentLength; i++) {
+// Argument argument = arguments[i];
+// TypeReference argumentType = argument.type;
+// argumentTypes[i] = returnTypeName(argumentType);
+// argumentNames[i] = argument.name;
+// argumentNameStarts[i] = argument.sourceStart;
+// argumentNameEnds[i] = argument.sourceEnd;
+// argumentTypeStarts[i] = argumentType.sourceStart;
+// argumentTypeEnds[i] = argumentType.sourceEnd;
+// }
+// }
+// TypeReference[] thrownExceptions = cd.thrownExceptions;
+// char[][] exceptionTypes = null;
+// int[] exceptionTypeStarts = null;
+// int[] exceptionTypeEnds = null;
+// if (thrownExceptions != null) {
+// int thrownExceptionLength = thrownExceptions.length;
+// exceptionTypes = new char[thrownExceptionLength][];
+// exceptionTypeStarts = new int[thrownExceptionLength];
+// exceptionTypeEnds = new int[thrownExceptionLength];
+// for (int i = 0; i < thrownExceptionLength; i++) {
+// TypeReference exception = thrownExceptions[i];
+// exceptionTypes[i] = CharOperation.concatWith(exception.getTypeName(), '.');
+// exceptionTypeStarts[i] = exception.sourceStart;
+// exceptionTypeEnds[i] = exception.sourceEnd;
+// }
+// }
+// requestor
+// .enterConstructor(
+// cd.declarationSourceStart,
+// intArrayStack[intArrayPtr--],
+// cd.modifiers,
+// cd.modifiersSourceStart,
+// cd.selector,
+// cd.sourceStart,
+// (int) (selectorSourcePositions & 0xFFFFFFFFL),
+// // retrieve the source end of the name
+// argumentTypes,
+// argumentTypeStarts,
+// argumentTypeEnds,
+// argumentNames,
+// argumentNameStarts,
+// argumentNameEnds,
+// rParenPos,
+// // right parenthesis
+// exceptionTypes,
+// exceptionTypeStarts,
+// exceptionTypeEnds,
+// scanner.currentPosition - 1);
+//}
+//protected void consumeConstructorHeaderName() {
+// // ConstructorHeaderName ::= Modifiersopt 'Identifier' '('
+// ConstructorDeclaration cd = new ConstructorDeclaration(this.compilationUnit.compilationResult);
+//
+// //name -- this is not really revelant but we do .....
+// cd.selector = identifierStack[identifierPtr];
+// selectorSourcePositions = identifierPositionStack[identifierPtr--];
+// identifierLengthPtr--;
+//
+// //modifiers
+// cd.declarationSourceStart = intStack[intPtr--];
+// cd.modifiersSourceStart = intStack[intPtr--];
+// cd.modifiers = intStack[intPtr--];
+//
+// //highlight starts at the selector starts
+// cd.sourceStart = (int) (selectorSourcePositions >>> 32);
+// pushOnAstStack(cd);
+//
+// cd.sourceEnd = lParenPos;
+// cd.bodyStart = lParenPos + 1;
+//}
+//protected void consumeDefaultModifiers() {
+// checkAnnotation(); // might update modifiers with AccDeprecated
+// pushOnIntStack(modifiers); // modifiers
+// pushOnIntStack(-1);
+// pushOnIntStack(
+// declarationSourceStart >= 0 ? declarationSourceStart : scanner.startPosition);
+// resetModifiers();
+//}
+//protected void consumeDiet() {
+// // Diet ::= $empty
+// super.consumeDiet();
+// /* persisting javadoc positions
+// * Will be consume in consumeClassBodyDeclaration
+// */
+// pushOnIntArrayStack(this.getJavaDocPositions());
+//}
+///**
+// *
+// * INTERNAL USE-ONLY
+// */
+//protected void consumeEnterCompilationUnit() {
+// // EnterCompilationUnit ::= $empty
+// requestor.enterCompilationUnit();
+//}
+///**
+// *
+// * INTERNAL USE-ONLY
+// */
+//protected void consumeEnterVariable() {
+// // EnterVariable ::= $empty
+// boolean isLocalDeclaration = isLocalDeclaration();
+// if (!isLocalDeclaration && (variablesCounter[nestedType] != 0)) {
+// requestor.exitField(lastFieldBodyEndPosition, lastFieldEndPosition);
+// }
+// char[] name = identifierStack[identifierPtr];
+// long namePosition = identifierPositionStack[identifierPtr--];
+// int extendedTypeDimension = intStack[intPtr--];
+//
+// AbstractVariableDeclaration declaration;
+// if (nestedMethod[nestedType] != 0) {
+// // create the local variable declarations
+// declaration =
+// new LocalDeclaration(null, name, (int) (namePosition >>> 32), (int) namePosition);
+// } else {
+// // create the field declaration
+// declaration =
+// new FieldDeclaration(null, name, (int) (namePosition >>> 32), (int) namePosition);
+// }
+// identifierLengthPtr--;
+// TypeReference type;
+// int variableIndex = variablesCounter[nestedType];
+// int typeDim = 0;
+// if (variableIndex == 0) {
+// // first variable of the declaration (FieldDeclaration or LocalDeclaration)
+// if (nestedMethod[nestedType] != 0) {
+// // local declaration
+// declaration.declarationSourceStart = intStack[intPtr--];
+// declaration.modifiersSourceStart = intStack[intPtr--];
+// declaration.modifiers = intStack[intPtr--];
+// type = getTypeReference(typeDim = intStack[intPtr--]); // type dimension
+// pushOnAstStack(type);
+// } else {
+// // field declaration
+// type = getTypeReference(typeDim = intStack[intPtr--]); // type dimension
+// pushOnAstStack(type);
+// declaration.declarationSourceStart = intStack[intPtr--];
+// declaration.modifiersSourceStart = intStack[intPtr--];
+// declaration.modifiers = intStack[intPtr--];
+// }
+// } else {
+// type = (TypeReference) astStack[astPtr - variableIndex];
+// typeDim = type.dimensions();
+// AbstractVariableDeclaration previousVariable =
+// (AbstractVariableDeclaration) astStack[astPtr];
+// declaration.declarationSourceStart = previousVariable.declarationSourceStart;
+// declaration.modifiers = previousVariable.modifiers;
+// declaration.modifiersSourceStart = previousVariable.modifiersSourceStart;
+// }
+//
+// localIntPtr = intPtr;
+//
+// if (extendedTypeDimension == 0) {
+// declaration.type = type;
+// } else {
+// int dimension = typeDim + extendedTypeDimension;
+// //on the identifierLengthStack there is the information about the type....
+// int baseType;
+// if ((baseType = identifierLengthStack[identifierLengthPtr + 1]) < 0) {
+// //it was a baseType
+// declaration.type = TypeReference.baseTypeReference(-baseType, dimension);
+// declaration.type.sourceStart = type.sourceStart;
+// declaration.type.sourceEnd = type.sourceEnd;
+// } else {
+// declaration.type = this.copyDims(type, dimension);
+// }
+// }
+// variablesCounter[nestedType]++;
+// nestedMethod[nestedType]++;
+// pushOnAstStack(declaration);
+//
+// int[] javadocPositions = intArrayStack[intArrayPtr];
+// if (!isLocalDeclaration) {
+// requestor
+// .enterField(
+// declaration.declarationSourceStart,
+// javadocPositions,
+// declaration.modifiers,
+// declaration.modifiersSourceStart,
+// returnTypeName(declaration.type),
+// type.sourceStart,
+// type.sourceEnd,
+// typeDims,
+// name,
+// (int) (namePosition >>> 32),
+// (int) namePosition,
+// extendedTypeDimension,
+// extendedTypeDimension == 0 ? -1 : endPosition);
+// }
+//}
+///**
+// *
+// * INTERNAL USE-ONLY
+// */
+//protected void consumeExitVariableWithInitialization() {
+// // ExitVariableWithInitialization ::= $empty
+// // the scanner is located after the comma or the semi-colon.
+// // we want to include the comma or the semi-colon
+// super.consumeExitVariableWithInitialization();
+// nestedMethod[nestedType]--;
+// lastFieldEndPosition = scanner.currentPosition - 1;
+// lastFieldBodyEndPosition = ((AbstractVariableDeclaration) astStack[astPtr]).initialization.sourceEnd;
+//}
+//protected void consumeExitVariableWithoutInitialization() {
+// // ExitVariableWithoutInitialization ::= $empty
+// // do nothing by default
+// super.consumeExitVariableWithoutInitialization();
+// nestedMethod[nestedType]--;
+// lastFieldEndPosition = scanner.currentPosition - 1;
+// lastFieldBodyEndPosition = scanner.startPosition - 1;
+//}
+///**
+// *
+// * INTERNAL USE-ONLY
+// */
+//protected void consumeFieldDeclaration() {
+// // See consumeLocalVariableDeclarationDefaultModifier() in case of change: duplicated code
+// // FieldDeclaration ::= Modifiersopt Type VariableDeclarators ';'
+// // the super.consumeFieldDeclaration will reinitialize the variableCounter[nestedType]
+// int variableIndex = variablesCounter[nestedType];
+// super.consumeFieldDeclaration();
+// intArrayPtr--;
+// if (isLocalDeclaration())
+// return;
+// if (variableIndex != 0) {
+// requestor.exitField(lastFieldBodyEndPosition, lastFieldEndPosition);
+// }
+//}
+//protected void consumeFormalParameter() {
+// // FormalParameter ::= Type VariableDeclaratorId ==> false
+// // FormalParameter ::= Modifiers Type VariableDeclaratorId ==> true
+// /*
+// astStack :
+// identifierStack : type identifier
+// intStack : dim dim
+// ==>
+// astStack : Argument
+// identifierStack :
+// intStack :
+// */
+//
+// identifierLengthPtr--;
+// char[] name = identifierStack[identifierPtr];
+// long namePositions = identifierPositionStack[identifierPtr--];
+// TypeReference type = getTypeReference(intStack[intPtr--] + intStack[intPtr--]);
+// intPtr -= 3;
+// Argument arg =
+// new Argument(
+// name,
+// namePositions,
+// type,
+// intStack[intPtr + 1]); // modifiers
+// pushOnAstStack(arg);
+// intArrayPtr--;
+//}
+///**
+// *
+// * INTERNAL USE-ONLY
+// */
+//protected void consumeInterfaceDeclaration() {
+// super.consumeInterfaceDeclaration();
+// // we know that we have a TypeDeclaration on the top of the astStack
+// if (isLocalDeclaration()) {
+// // we ignore the local variable declarations
+// return;
+// }
+// requestor.exitInterface(endStatementPosition, // the '}' is the end of the body
+// ((TypeDeclaration) astStack[astPtr]).declarationSourceEnd);
+//}
+///**
+// *
+// * INTERNAL USE-ONLY
+// */
+//protected void consumeInterfaceHeader() {
+// //InterfaceHeader ::= $empty
+// super.consumeInterfaceHeader();
+// if (isLocalDeclaration()) {
+// // we ignore the local variable declarations
+// intArrayPtr--;
+// return;
+// }
+// TypeDeclaration typeDecl = (TypeDeclaration) astStack[astPtr];
+// TypeReference[] superInterfaces = typeDecl.superInterfaces;
+// char[][] interfaceNames = null;
+// int[] interfaceNameStarts = null;
+// int[] interfacenameEnds = null;
+// int superInterfacesLength = 0;
+// if (superInterfaces != null) {
+// superInterfacesLength = superInterfaces.length;
+// interfaceNames = new char[superInterfacesLength][];
+// interfaceNameStarts = new int[superInterfacesLength];
+// interfacenameEnds = new int[superInterfacesLength];
+// }
+// if (superInterfaces != null) {
+// for (int i = 0; i < superInterfacesLength; i++) {
+// TypeReference superInterface = superInterfaces[i];
+// interfaceNames[i] = CharOperation.concatWith(superInterface.getTypeName(), '.');
+// interfaceNameStarts[i] = superInterface.sourceStart;
+// interfacenameEnds[i] = superInterface.sourceEnd;
+// }
+// }
+// // flush the comments related to the interface header
+// scanner.commentPtr = -1;
+// requestor.enterInterface(
+// typeDecl.declarationSourceStart,
+// intArrayStack[intArrayPtr--],
+// typeDecl.modifiers,
+// typeDecl.modifiersSourceStart,
+// typeStartPosition,
+// typeDecl.name,
+// typeDecl.sourceStart,
+// typeDecl.sourceEnd,
+// interfaceNames,
+// interfaceNameStarts,
+// interfacenameEnds,
+// scanner.currentPosition - 1);
+//}
+//protected void consumeInterfaceHeaderName() {
+// // InterfaceHeaderName ::= Modifiersopt 'interface' 'Identifier'
+// TypeDeclaration typeDecl;
+// if (nestedMethod[nestedType] == 0) {
+// if (nestedType != 0) {
+// typeDecl = new MemberTypeDeclaration(this.compilationUnit.compilationResult);
+// } else {
+// typeDecl = new TypeDeclaration(this.compilationUnit.compilationResult);
+// }
+// } else {
+// // Record that the block has a declaration for local types
+// typeDecl = new LocalTypeDeclaration(this.compilationUnit.compilationResult);
+// markEnclosingMemberWithLocalType();
+// blockReal();
+// }
+//
+// //highlight the name of the type
+// long pos = identifierPositionStack[identifierPtr];
+// typeDecl.sourceEnd = (int) pos;
+// typeDecl.sourceStart = (int) (pos >>> 32);
+// typeDecl.name = identifierStack[identifierPtr--];
+// identifierLengthPtr--;
+//
+// //compute the declaration source too
+// // 'class' and 'interface' push an int position
+// typeStartPosition = typeDecl.declarationSourceStart = intStack[intPtr--];
+// intPtr--;
+// int declarationSourceStart = intStack[intPtr--];
+// typeDecl.modifiersSourceStart = intStack[intPtr--];
+// typeDecl.modifiers = intStack[intPtr--];
+// if (typeDecl.declarationSourceStart > declarationSourceStart) {
+// typeDecl.declarationSourceStart = declarationSourceStart;
+// }
+// typeDecl.bodyStart = typeDecl.sourceEnd + 1;
+// pushOnAstStack(typeDecl);
+//}
+///**
+// *
+// * INTERNAL USE-ONLY
+// */
+//protected void consumeLocalVariableDeclaration() {
+// // See consumeLocalVariableDeclarationDefaultModifier() in case of change: duplicated code
+// // FieldDeclaration ::= Modifiersopt Type VariableDeclarators ';'
+//
+// super.consumeLocalVariableDeclaration();
+// intArrayPtr--;
+//}
+///**
+// *
+// * INTERNAL USE-ONLY
+// */
+//protected void consumeMethodDeclaration(boolean isNotAbstract) {
+// // MethodDeclaration ::= MethodHeader MethodBody
+// // AbstractMethodDeclaration ::= MethodHeader ';'
+// super.consumeMethodDeclaration(isNotAbstract);
+// if (isLocalDeclaration()) {
+// // we ignore the local variable declarations
+// return;
+// }
+// MethodDeclaration md = (MethodDeclaration) astStack[astPtr];
+// requestor.exitMethod(endStatementPosition, md.declarationSourceEnd);
+//}
+///**
+// *
+// * INTERNAL USE-ONLY
+// */
+//protected void consumeMethodHeader() {
+// // MethodHeader ::= MethodHeaderName MethodHeaderParameters MethodHeaderExtendedDims ThrowsClauseopt
+// super.consumeMethodHeader();
+// if (isLocalDeclaration()) {
+// // we ignore the local variable declarations
+// intArrayPtr--;
+// return;
+// }
+// MethodDeclaration md = (MethodDeclaration) astStack[astPtr];
+//
+// TypeReference returnType = md.returnType;
+// char[] returnTypeName = returnTypeName(returnType);
+// Argument[] arguments = md.arguments;
+// char[][] argumentTypes = null;
+// char[][] argumentNames = null;
+// int[] argumentTypeStarts = null;
+// int[] argumentTypeEnds = null;
+// int[] argumentNameStarts = null;
+// int[] argumentNameEnds = null;
+// if (arguments != null) {
+// int argumentLength = arguments.length;
+// argumentTypes = new char[argumentLength][];
+// argumentNames = new char[argumentLength][];
+// argumentNameStarts = new int[argumentLength];
+// argumentNameEnds = new int[argumentLength];
+// argumentTypeStarts = new int[argumentLength];
+// argumentTypeEnds = new int[argumentLength];
+// for (int i = 0; i < argumentLength; i++) {
+// Argument argument = arguments[i];
+// TypeReference argumentType = argument.type;
+// argumentTypes[i] = returnTypeName(argumentType);
+// argumentNames[i] = argument.name;
+// argumentNameStarts[i] = argument.sourceStart;
+// argumentNameEnds[i] = argument.sourceEnd;
+// argumentTypeStarts[i] = argumentType.sourceStart;
+// argumentTypeEnds[i] = argumentType.sourceEnd;
+// }
+// }
+// TypeReference[] thrownExceptions = md.thrownExceptions;
+// char[][] exceptionTypes = null;
+// int[] exceptionTypeStarts = null;
+// int[] exceptionTypeEnds = null;
+// if (thrownExceptions != null) {
+// int thrownExceptionLength = thrownExceptions.length;
+// exceptionTypeStarts = new int[thrownExceptionLength];
+// exceptionTypeEnds = new int[thrownExceptionLength];
+// exceptionTypes = new char[thrownExceptionLength][];
+// for (int i = 0; i < thrownExceptionLength; i++) {
+// TypeReference exception = thrownExceptions[i];
+// exceptionTypes[i] = CharOperation.concatWith(exception.getTypeName(), '.');
+// exceptionTypeStarts[i] = exception.sourceStart;
+// exceptionTypeEnds[i] = exception.sourceEnd;
+// }
+// }
+// requestor
+// .enterMethod(
+// md.declarationSourceStart,
+// intArrayStack[intArrayPtr--],
+// md.modifiers,
+// md.modifiersSourceStart,
+// returnTypeName,
+// returnType.sourceStart,
+// returnType.sourceEnd,
+// typeDims,
+// md.selector,
+// md.sourceStart,
+// (int) (selectorSourcePositions & 0xFFFFFFFFL),
+// argumentTypes,
+// argumentTypeStarts,
+// argumentTypeEnds,
+// argumentNames,
+// argumentNameStarts,
+// argumentNameEnds,
+// rParenPos,
+// extendsDim,
+// extendsDim == 0 ? -1 : endPosition,
+// exceptionTypes,
+// exceptionTypeStarts,
+// exceptionTypeEnds,
+// scanner.currentPosition - 1);
+//}
+//protected void consumeMethodHeaderExtendedDims() {
+// // MethodHeaderExtendedDims ::= Dimsopt
+// // now we update the returnType of the method
+// MethodDeclaration md = (MethodDeclaration) astStack[astPtr];
+// int extendedDims = intStack[intPtr--];
+// extendsDim = extendedDims;
+// if (extendedDims != 0) {
+// TypeReference returnType = md.returnType;
+// md.sourceEnd = endPosition;
+// int dims = returnType.dimensions() + extendedDims;
+// int baseType;
+// if ((baseType = identifierLengthStack[identifierLengthPtr + 1]) < 0) {
+// //it was a baseType
+// int sourceStart = returnType.sourceStart;
+// int sourceEnd = returnType.sourceEnd;
+// returnType = TypeReference.baseTypeReference(-baseType, dims);
+// returnType.sourceStart = sourceStart;
+// returnType.sourceEnd = sourceEnd;
+// md.returnType = returnType;
+// } else {
+// md.returnType = this.copyDims(md.returnType, dims);
+// }
+// if (currentToken == TokenNameLBRACE) {
+// md.bodyStart = endPosition + 1;
+// }
+// }
+//}
+//protected void consumeMethodHeaderName() {
+// // MethodHeaderName ::= Modifiersopt Type 'Identifier' '('
+// MethodDeclaration md = new MethodDeclaration(this.compilationUnit.compilationResult);
+//
+// //name
+// md.selector = identifierStack[identifierPtr];
+// selectorSourcePositions = identifierPositionStack[identifierPtr--];
+// identifierLengthPtr--;
+// //type
+// md.returnType = getTypeReference(typeDims = intStack[intPtr--]);
+// //modifiers
+// md.declarationSourceStart = intStack[intPtr--];
+// md.modifiersSourceStart = intStack[intPtr--];
+// md.modifiers = intStack[intPtr--];
+//
+// //highlight starts at selector start
+// md.sourceStart = (int) (selectorSourcePositions >>> 32);
+// pushOnAstStack(md);
+// md.bodyStart = scanner.currentPosition-1;
+//}
+//protected void consumeModifiers() {
+// checkAnnotation(); // might update modifiers with AccDeprecated
+// pushOnIntStack(modifiers); // modifiers
+// pushOnIntStack(modifiersSourceStart);
+// pushOnIntStack(
+// declarationSourceStart >= 0 ? declarationSourceStart : modifiersSourceStart);
+// resetModifiers();
+//}
+/**
+ *
+ * INTERNAL USE-ONLY
+ */
+//protected void consumePackageDeclarationName() {
+// /* persisting javadoc positions */
+// pushOnIntArrayStack(this.getJavaDocPositions());
+//
+// super.consumePackageDeclarationName();
+// ImportReference importReference = compilationUnit.currentPackage;
+//
+// requestor.acceptPackage(
+// importReference.declarationSourceStart,
+// importReference.declarationSourceEnd,
+// intArrayStack[intArrayPtr--],
+// CharOperation.concatWith(importReference.getImportName(), '.'),
+// importReference.sourceStart);
+//}
+//protected void consumePushModifiers() {
+// checkAnnotation(); // might update modifiers with AccDeprecated
+// pushOnIntStack(modifiers); // modifiers
+// if (modifiersSourceStart < 0) {
+// pushOnIntStack(-1);
+// pushOnIntStack(
+// declarationSourceStart >= 0 ? declarationSourceStart : scanner.startPosition);
+// } else {
+// pushOnIntStack(modifiersSourceStart);
+// pushOnIntStack(
+// declarationSourceStart >= 0 ? declarationSourceStart : modifiersSourceStart);
+// }
+// resetModifiers();
+//}
+///**
+// *
+// * INTERNAL USE-ONLY
+// */
+//protected void consumeSingleTypeImportDeclarationName() {
+// // SingleTypeImportDeclarationName ::= 'import' Name
+//
+// /* persisting javadoc positions */
+// pushOnIntArrayStack(this.getJavaDocPositions());
+//
+// super.consumeSingleTypeImportDeclarationName();
+// ImportReference importReference = (ImportReference) astStack[astPtr];
+// requestor.acceptImport(
+// importReference.declarationSourceStart,
+// importReference.declarationSourceEnd,
+// intArrayStack[intArrayPtr--],
+// CharOperation.concatWith(importReference.getImportName(), '.'),
+// importReference.sourceStart,
+// false);
+//}
+///**
+// *
+// * INTERNAL USE-ONLY
+// */
+//protected void consumeStaticInitializer() {
+// // StaticInitializer ::= StaticOnly Block
+// //push an Initializer
+// //optimize the push/pop
+// super.consumeStaticInitializer();
+// Initializer initializer = (Initializer) astStack[astPtr];
+// requestor.acceptInitializer(
+// initializer.declarationSourceStart,
+// initializer.declarationSourceEnd,
+// intArrayStack[intArrayPtr--],
+// AccStatic,
+// intStack[intPtr--],
+// initializer.block.sourceStart,
+// initializer.declarationSourceEnd);
+//}
+//protected void consumeStaticOnly() {
+// // StaticOnly ::= 'static'
+// checkAnnotation(); // might update declaration source start
+// pushOnIntStack(modifiersSourceStart);
+// pushOnIntStack(
+// declarationSourceStart >= 0 ? declarationSourceStart : modifiersSourceStart);
+// jumpOverMethodBody();
+// nestedMethod[nestedType]++;
+// resetModifiers();
+//}
+///**
+// *
+// * INTERNAL USE-ONLY
+// */
+//protected void consumeTypeImportOnDemandDeclarationName() {
+// // TypeImportOnDemandDeclarationName ::= 'import' Name '.' '*'
+//
+// /* persisting javadoc positions */
+// pushOnIntArrayStack(this.getJavaDocPositions());
+//
+// super.consumeTypeImportOnDemandDeclarationName();
+// ImportReference importReference = (ImportReference) astStack[astPtr];
+// requestor.acceptImport(
+// importReference.declarationSourceStart,
+// importReference.declarationSourceEnd,
+// intArrayStack[intArrayPtr--],
+// CharOperation.concatWith(importReference.getImportName(), '.'),
+// importReference.sourceStart,
+// true);
+//}
+public CompilationUnitDeclaration endParse(int act) {
+ if (scanner.recordLineSeparator) {
+ requestor.acceptLineSeparatorPositions(scanner.getLineEnds());
+ }
+ return super.endParse(act);
+}
+/*
+ * Flush annotations defined prior to a given positions.
+ *
+ * Note: annotations are stacked in syntactical order
+ *
+ * Either answer given char[]
the specified key
+ * @return int the element for the key or -1 if the key is not
+ * defined in the hash table.
+ */
+public int get(Object key) {
+ int index = hashCode(key);
+ while (keyTable[index] != null) {
+ if (keyTable[index] == key)
+ return valueTable[index];
+ index = (index + 1) % keyTable.length;
+ }
+ return -1;
+}
+/**
+ * Return the hashcode for the key parameter
+ *
+ * @param key org.eclipse.jdt.internal.compiler.lookup.MethodBinding
+ * @return int
+ */
+public int hashCode(Object key) {
+ return (key.hashCode() & 0x7FFFFFFF) % keyTable.length;
+}
+/**
+ * Puts the specified element into the hashtable, using the specified
+ * key. The element may be retrieved by doing a get() with the same key.
+ * The key and the element cannot be null.
+ *
+ * @param key Object
the specified key in the hashtable
+ * @param value int
the specified element
+ * @return int the old value of the key, or -1 if it did not have one.
+ */
+public int put(Object key, int value) {
+ int index = hashCode(key);
+ while (keyTable[index] != null) {
+ if (keyTable[index] == key)
+ return valueTable[index] = value;
+ index = (index + 1) % keyTable.length;
+ }
+ keyTable[index] = key;
+ valueTable[index] = value;
+
+ // assumes the threshold is never equal to the size of the table
+ if (++elementSize > threshold)
+ rehash();
+ return value;
+}
+/**
+ * Rehashes the content of the table into a bigger table.
+ * This method is called automatically when the hashtable's
+ * size exceeds the threshold.
+ */
+private void rehash() {
+ ObjectCache newHashtable = new ObjectCache(keyTable.length * 2);
+ for (int i = keyTable.length; --i >= 0;)
+ if (keyTable[i] != null)
+ newHashtable.put(keyTable[i], valueTable[i]);
+
+ this.keyTable = newHashtable.keyTable;
+ this.valueTable = newHashtable.valueTable;
+ this.threshold = newHashtable.threshold;
+}
+/**
+ * Returns the number of elements contained in the hashtable.
+ *
+ * @return int
The size of the table
+ */
+public int size() {
+ return elementSize;
+}
+/**
+ * Converts to a rather lengthy String.
+ *
+ * @return String the ascii representation of the receiver
+ */
+public String toString() {
+ int max = size();
+ StringBuffer buf = new StringBuffer();
+ buf.append("{"); //$NON-NLS-1$
+ for (int i = 0; i < max; ++i) {
+ if (keyTable[i] != null) {
+ buf.append(keyTable[i]).append("->").append(valueTable[i]); //$NON-NLS-1$
+ }
+ if (i < max) {
+ buf.append(", "); //$NON-NLS-1$
+ }
+ }
+ buf.append("}"); //$NON-NLS-1$
+ return buf.toString();
+}
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IBinaryField.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IBinaryField.java
new file mode 100644
index 0000000..e59888a
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IBinaryField.java
@@ -0,0 +1,33 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.compiler.env;
+
+import net.sourceforge.phpdt.internal.compiler.impl.Constant;
+
+public interface IBinaryField extends IGenericField {
+/**
+ *
+ * @return org.eclipse.jdt.internal.compiler.Constant
+ */
+Constant getConstant();
+/**
+ * Answer the resolved name of the receiver's type in the
+ * class file format as specified in section 4.3.2 of the Java 2 VM spec.
+ *
+ * For example:
+ * - java.lang.String is Ljava/lang/String;
+ * - an int is I
+ * - a 2 dimensional array of strings is [[Ljava/lang/String;
+ * - an array of floats is [F
+ */
+
+char[] getTypeName();
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IBinaryMethod.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IBinaryMethod.java
new file mode 100644
index 0000000..316c368
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IBinaryMethod.java
@@ -0,0 +1,44 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.compiler.env;
+
+// clinit methods (synthetics too?) can be returned from IBinaryType>>getMethods()
+// BUT do not have to be... the compiler will ignore them when building the binding.
+// The synthetic argument of a member type's constructor (ie. the first arg of a non-static
+// member type) is also ignored by the compiler, BUT in this case it must be included
+// in the constructor's signature.
+
+public interface IBinaryMethod extends IGenericMethod {
+
+/**
+ * Answer the resolved names of the exception types in the
+ * class file format as specified in section 4.2 of the Java 2 VM spec
+ * or null if the array is empty.
+ *
+ * For example, java.lang.String is java/lang/String.
+ */
+char[][] getExceptionTypeNames();
+
+/**
+ * Answer the receiver's method descriptor which describes the parameter &
+ * return types as specified in section 4.3.3 of the Java 2 VM spec.
+ *
+ * For example:
+ * - int foo(String) is (Ljava/lang/String;)I
+ * - Object[] foo(int) is (I)[Ljava/lang/Object;
+ */
+char[] getMethodDescriptor();
+
+/**
+ * Answer whether the receiver represents a class initializer method.
+ */
+boolean isClinit();
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IBinaryNestedType.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IBinaryNestedType.java
new file mode 100644
index 0000000..a9aa1f0
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IBinaryNestedType.java
@@ -0,0 +1,38 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.compiler.env;
+
+public interface IBinaryNestedType {
+/**
+ * Answer the resolved name of the enclosing type in the
+ * class file format as specified in section 4.2 of the Java 2 VM spec.
+ *
+ * For example, java.lang.String is java/lang/String.
+ */
+
+char[] getEnclosingTypeName();
+/**
+ * Answer an int whose bits are set according the access constants
+ * defined by the VM spec.
+ */
+
+// We have added AccDeprecated & AccSynthetic.
+
+int getModifiers();
+/**
+ * Answer the resolved name of the member type in the
+ * class file format as specified in section 4.2 of the Java 2 VM spec.
+ *
+ * For example, p1.p2.A.M is p1/p2/A$M.
+ */
+
+char[] getName();
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IBinaryType.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IBinaryType.java
new file mode 100644
index 0000000..b9f3d19
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IBinaryType.java
@@ -0,0 +1,104 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.compiler.env;
+
+import net.sourceforge.phpdt.core.compiler.CharOperation;
+
+public interface IBinaryType extends IGenericType {
+
+ char[][] NoInterface = CharOperation.NO_CHAR_CHAR;
+ IBinaryNestedType[] NoNestedType = new IBinaryNestedType[0];
+ IBinaryField[] NoField = new IBinaryField[0];
+ IBinaryMethod[] NoMethod = new IBinaryMethod[0];
+/**
+ * Answer the resolved name of the enclosing type in the
+ * class file format as specified in section 4.2 of the Java 2 VM spec
+ * or null if the receiver is a top level type.
+ *
+ * For example, java.lang.String is java/lang/String.
+ */
+
+char[] getEnclosingTypeName();
+/**
+ * Answer the receiver's fields or null if the array is empty.
+ */
+
+IBinaryField[] getFields();
+/**
+ * Answer the resolved names of the receiver's interfaces in the
+ * class file format as specified in section 4.2 of the Java 2 VM spec
+ * or null if the array is empty.
+ *
+ * For example, java.lang.String is java/lang/String.
+ */
+
+char[][] getInterfaceNames();
+/**
+ * Answer the receiver's nested types or null if the array is empty.
+ *
+ * This nested type info is extracted from the inner class attributes.
+ * Ask the name environment to find a member type using its compound name.
+ */
+
+// NOTE: The compiler examines the nested type info & ignores the local types
+// so the local types do not have to be included.
+
+IBinaryNestedType[] getMemberTypes();
+/**
+ * Answer the receiver's methods or null if the array is empty.
+ */
+
+IBinaryMethod[] getMethods();
+/**
+ * Answer the resolved name of the type in the
+ * class file format as specified in section 4.2 of the Java 2 VM spec.
+ *
+ * For example, java.lang.String is java/lang/String.
+ */
+
+char[] getName();
+/**
+ * Answer the resolved name of the receiver's superclass in the
+ * class file format as specified in section 4.2 of the Java 2 VM spec
+ * or null if it does not have one.
+ *
+ * For example, java.lang.String is java/lang/String.
+ */
+
+char[] getSuperclassName();
+
+/**
+ * Answer true if the receiver is an anonymous class.
+ * false otherwise
+ */
+boolean isAnonymous();
+
+/**
+ * Answer true if the receiver is a local class.
+ * false otherwise
+ */
+boolean isLocal();
+
+/**
+ * Answer true if the receiver is a member class.
+ * false otherwise
+ */
+boolean isMember();
+
+/**
+ * Answer the source file attribute, or null if none.
+ *
+ * For example, "String.java"
+ */
+
+char[] sourceFileName();
+
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/ICompilationUnit.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/ICompilationUnit.java
new file mode 100644
index 0000000..811f518
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/ICompilationUnit.java
@@ -0,0 +1,36 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.compiler.env;
+
+/**
+ * This interface denotes a compilation unit, providing its name and content.
+ */
+public interface ICompilationUnit extends IDependent {
+/**
+ * Answer the contents of the compilation unit.
+ *
+ * In normal use, the contents are requested twice.
+ * Once during the initial lite parsing step, then again for the
+ * more detailed parsing step.
+ */
+char[] getContents();
+/**
+ * Answer the name of the top level public type.
+ * For example, {Hashtable}.
+ */
+char[] getMainTypeName();
+/**
+ * Answer the name of the package according to the directory structure
+ * or null if package consistency checks should be ignored.
+ * For example, {java, lang}.
+ */
+char[][] getPackageName();
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IConstants.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IConstants.java
index fd4092c..a0f7338 100644
--- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IConstants.java
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IConstants.java
@@ -27,8 +27,8 @@ public interface IConstants {
// int AccVolatile = 0x0040;
// int AccTransient = 0x0080;
// int AccNative = 0x0100;
-// int AccInterface = 0x0200;
-// int AccAbstract = 0x0400;
+ int AccInterface = 0x0200;
+ int AccAbstract = 0x0400;
// int AccStrictfp = 0x0800;
/*
@@ -40,5 +40,5 @@ public interface IConstants {
* Extra flags for types and members.
*/
// int AccSynthetic = 0x20000;
-// int AccDeprecated = 0x100000;
+ int AccDeprecated = 0x100000;
}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IDependent.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IDependent.java
new file mode 100644
index 0000000..8229ea5
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IDependent.java
@@ -0,0 +1,33 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.compiler.env;
+
+/**
+ * This represents the target file of a type dependency.
+ *
+ * All implementors of this interface are containers for types or types
+ * themselves which must be able to identify their source file name
+ * when file dependencies are collected.
+ */
+public interface IDependent {
+/**
+ * Answer the file name which defines the type.
+ *
+ * The path part (optional) must be separated from the actual
+ * file proper name by a java.io.File.separator.
+ *
+ * The proper file name includes the suffix extension (e.g. ".java")
+ *
+ * e.g. "c:/com/ibm/compiler/java/api/Compiler.java"
+ */
+
+char[] getFileName();
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IGenericField.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IGenericField.java
new file mode 100644
index 0000000..ac1f15e
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IGenericField.java
@@ -0,0 +1,27 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.compiler.env;
+
+public interface IGenericField {
+/**
+ * Answer an int whose bits are set according the access constants
+ * defined by the VM spec.
+ */
+
+// We have added AccDeprecated & AccSynthetic.
+
+int getModifiers();
+/**
+ * Answer the name of the field.
+ */
+
+char[] getName();
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IGenericMethod.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IGenericMethod.java
new file mode 100644
index 0000000..5c17762
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/compiler/env/IGenericMethod.java
@@ -0,0 +1,36 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.compiler.env;
+
+public interface IGenericMethod {
+/**
+ * Answer an int whose bits are set according the access constants
+ * defined by the VM spec.
+ */
+// We have added AccDeprecated & AccSynthetic.
+int getModifiers();
+
+/**
+ * Answer the name of the method.
+ *
+ * For a constructor, answer ICompilationUnit
+ * for use in the SourceMapper
.
+ * @see ICompilationUnit
+ */
+public class BasicCompilationUnit implements ICompilationUnit {
+ protected char[] contents;
+ protected char[] fileName;
+ protected char[][] packageName;
+ protected char[] mainTypeName;
+ protected String encoding;
+
+ public BasicCompilationUnit(char[] contents, char[][] packageName, String fileName, String encoding) {
+ this.contents = contents;
+ this.fileName = fileName.toCharArray();
+ this.packageName = packageName;
+
+ int start = fileName.lastIndexOf("/") + 1; //$NON-NLS-1$
+ if (start == 0 || start < fileName.lastIndexOf("\\")) //$NON-NLS-1$
+ start = fileName.lastIndexOf("\\") + 1; //$NON-NLS-1$
+
+ int end = fileName.lastIndexOf("."); //$NON-NLS-1$
+ if (end == -1)
+ end = fileName.length();
+
+ this.mainTypeName = fileName.substring(start, end).toCharArray();
+ this.encoding = encoding;
+ }
+ public char[] getContents() {
+ if (this.contents != null)
+ return this.contents; // answer the cached source
+
+ // otherwise retrieve it
+ try {
+ return Util.getFileCharContent(new File(new String(fileName)), this.encoding);
+ } catch (IOException e) {
+ }
+ return CharOperation.NO_CHAR;
+ }
+ public char[] getFileName() {
+ return this.fileName;
+ }
+ public char[] getMainTypeName() {
+ return this.mainTypeName;
+ }
+ public char[][] getPackageName() {
+ return this.packageName;
+ }
+ public String toString() {
+ return "CompilationUnit: " + new String(fileName); //$NON-NLS-1$
+ }
+
+
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/BufferCache.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/BufferCache.java
index 62ad8f0..7413c26 100644
--- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/BufferCache.java
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/BufferCache.java
@@ -11,7 +11,7 @@
package net.sourceforge.phpdt.internal.core;
import net.sourceforge.phpdt.core.IBuffer;
-import net.sourceforge.phpdt.core.util.LRUCache;
+import net.sourceforge.phpdt.internal.core.util.LRUCache;
/**
* An LRU cache of IBuffers
.
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/BufferManager.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/BufferManager.java
index 993c2a7..511d041 100644
--- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/BufferManager.java
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/BufferManager.java
@@ -14,8 +14,12 @@ import java.util.Enumeration;
import net.sourceforge.phpdt.core.IBuffer;
import net.sourceforge.phpdt.core.IBufferFactory;
+import net.sourceforge.phpdt.core.IJavaElement;
import net.sourceforge.phpdt.core.IOpenable;
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IResource;
+
/**
* The buffer manager manages the set of open buffers.
@@ -45,15 +49,15 @@ protected void addBuffer(IBuffer buffer) {
/**
* @see IBufferFactory#createBuffer(IOpenable)
*/
-//public IBuffer createBuffer(IOpenable owner) {
-// IJavaElement element = (IJavaElement)owner;
-// IResource resource = element.getResource();
-// return
-// new Buffer(
-// resource instanceof IFile ? (IFile)resource : null,
-// owner,
-// element.isReadOnly());
-//}
+public IBuffer createBuffer(IOpenable owner) {
+ IJavaElement element = (IJavaElement)owner;
+ IResource resource = element.getResource();
+ return
+ new Buffer(
+ resource instanceof IFile ? (IFile)resource : null,
+ owner,
+ element.isReadOnly());
+}
/**
* Returns the open buffer associated with the given owner,
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/ClasspathEntry.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/ClasspathEntry.java
new file mode 100644
index 0000000..bdb0401
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/ClasspathEntry.java
@@ -0,0 +1,587 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core;
+
+import net.sourceforge.phpdt.core.IClasspathEntry;
+import net.sourceforge.phpdt.core.IJavaProject;
+import net.sourceforge.phpdt.core.IPackageFragmentRoot;
+import net.sourceforge.phpdt.core.JavaModelException;
+import net.sourceforge.phpdt.core.compiler.CharOperation;
+import net.sourceforge.phpdt.internal.corext.Assert;
+import net.sourceforge.phpeclipse.PHPCore;
+
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.core.runtime.Path;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+/**
+ * @see IClasspathEntry
+ */
+public class ClasspathEntry implements IClasspathEntry {
+
+ /**
+ * Describes the kind of classpath entry - one of
+ * CPE_PROJECT, CPE_LIBRARY, CPE_SOURCE, CPE_VARIABLE or CPE_CONTAINER
+ */
+ public int entryKind;
+
+ /**
+ * Describes the kind of package fragment roots found on
+ * this classpath entry - either K_BINARY or K_SOURCE or
+ * K_OUTPUT.
+ */
+ public int contentKind;
+
+ /**
+ * The meaning of the path of a classpath entry depends on its entry kind:CPE_SOURCE
) -
+ * The path associated with this entry is the absolute path to the root folder. CPE_LIBRARY
) - the path
+ * associated with this entry is the absolute path to the JAR (or root folder), and
+ * in case it refers to an external JAR, then there is no associated resource in
+ * the workbench.
+ * CPE_PROJECT
) - the path of the entry denotes the
+ * path to the corresponding project resource.CPE_VARIABLE
) - the first segment of the path
+ * is the name of a classpath variable. If this classpath variable
+ * is bound to the path CPE_CONTAINER
) - the first segment of the path is denoting
+ * the unique container identifier (for which a ClasspathContainerInitializer
could be
+ * registered), and the remaining segments are used as additional hints for resolving the container entry to
+ * an actual IClasspathContainer
.null
if this classpath entry has no
+ * source attachment.
+ *
+ * Only library and variable classpath entries may have source attachments.
+ * For library classpath entries, the result path (if present) locates a source
+ * archive. For variable classpath entries, the result path (if present) has
+ * an analogous form and meaning as the variable path, namely the first segment
+ * is the name of a classpath variable.
+ */
+ public IPath sourceAttachmentPath;
+
+ /**
+ * Describes the path within the source archive where package fragments
+ * are located. An empty path indicates that packages are located at
+ * the root of the source archive. Returns a non-null
value
+ * if and only if getSourceAttachmentPath
returns
+ * a non-null
value.
+ */
+ public IPath sourceAttachmentRootPath;
+
+ /**
+ * Specific output location (for this source entry)
+ */
+ public IPath specificOutputLocation;
+
+ /**
+ * A constant indicating an output location.
+ */
+ public static final int K_OUTPUT = 10;
+
+ /**
+ * The export flag
+ */
+ public boolean isExported;
+
+ /**
+ * Creates a class path entry of the specified kind with the given path.
+ */
+ public ClasspathEntry(
+ int contentKind,
+ int entryKind,
+ IPath path,
+ IPath[] exclusionPatterns,
+ IPath sourceAttachmentPath,
+ IPath sourceAttachmentRootPath,
+ IPath specificOutputLocation,
+ boolean isExported) {
+
+ this.contentKind = contentKind;
+ this.entryKind = entryKind;
+ this.path = path;
+ this.exclusionPatterns = exclusionPatterns;
+ if (exclusionPatterns.length > 0) {
+ this.fullCharExclusionPatterns = UNINIT_PATTERNS;
+ }
+ this.sourceAttachmentPath = sourceAttachmentPath;
+ this.sourceAttachmentRootPath = sourceAttachmentRootPath;
+ this.specificOutputLocation = specificOutputLocation;
+ this.isExported = isExported;
+ }
+
+ /*
+ * Returns a char based representation of the exclusions patterns full path.
+ */
+ public char[][] fullExclusionPatternChars() {
+
+ if (this.fullCharExclusionPatterns == UNINIT_PATTERNS) {
+ int length = this.exclusionPatterns.length;
+ this.fullCharExclusionPatterns = new char[length][];
+ IPath prefixPath = path.removeTrailingSeparator();
+ for (int i = 0; i < length; i++) {
+ this.fullCharExclusionPatterns[i] =
+ prefixPath.append(this.exclusionPatterns[i]).toString().toCharArray();
+ }
+ }
+ return this.fullCharExclusionPatterns;
+ }
+
+ /**
+ * Returns the XML encoding of the class path.
+ */
+ public Element elementEncode(
+ Document document,
+ IPath projectPath)
+ throws JavaModelException {
+
+ Element element = document.createElement("classpathentry"); //$NON-NLS-1$
+ element.setAttribute("kind", kindToString(this.entryKind)); //$NON-NLS-1$
+ IPath xmlPath = this.path;
+ if (this.entryKind != IClasspathEntry.CPE_VARIABLE && this.entryKind != IClasspathEntry.CPE_CONTAINER) {
+ // translate to project relative from absolute (unless a device path)
+ if (xmlPath.isAbsolute()) {
+ if (projectPath != null && projectPath.isPrefixOf(xmlPath)) {
+ if (xmlPath.segment(0).equals(projectPath.segment(0))) {
+ xmlPath = xmlPath.removeFirstSegments(1);
+ xmlPath = xmlPath.makeRelative();
+ } else {
+ xmlPath = xmlPath.makeAbsolute();
+ }
+ }
+ }
+ }
+ element.setAttribute("path", xmlPath.toString()); //$NON-NLS-1$
+ if (this.sourceAttachmentPath != null) {
+ element.setAttribute("sourcepath", this.sourceAttachmentPath.toString()); //$NON-NLS-1$
+ }
+ if (this.sourceAttachmentRootPath != null) {
+ element.setAttribute("rootpath", this.sourceAttachmentRootPath.toString()); //$NON-NLS-1$
+ }
+ if (this.isExported) {
+ element.setAttribute("exported", "true"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ if (this.exclusionPatterns.length > 0) {
+ StringBuffer excludeRule = new StringBuffer(10);
+ for (int i = 0, max = this.exclusionPatterns.length; i < max; i++){
+ if (i > 0) excludeRule.append('|');
+ excludeRule.append(this.exclusionPatterns[i]);
+ }
+ element.setAttribute("excluding", excludeRule.toString()); //$NON-NLS-1$
+ }
+
+ if (this.specificOutputLocation != null) {
+ IPath outputLocation = this.specificOutputLocation.removeFirstSegments(1);
+ outputLocation = outputLocation.makeRelative();
+ element.setAttribute("output", outputLocation.toString()); //$NON-NLS-1$
+ }
+ return element;
+ }
+
+ public static IClasspathEntry elementDecode(Element element, IJavaProject project) {
+
+ IPath projectPath = project.getProject().getFullPath();
+ String kindAttr = element.getAttribute("kind"); //$NON-NLS-1$
+ String pathAttr = element.getAttribute("path"); //$NON-NLS-1$
+
+ // ensure path is absolute
+ IPath path = new Path(pathAttr);
+ int kind = kindFromString(kindAttr);
+ if (kind != IClasspathEntry.CPE_VARIABLE && kind != IClasspathEntry.CPE_CONTAINER && !path.isAbsolute()) {
+ path = projectPath.append(path);
+ }
+ // source attachment info (optional)
+ IPath sourceAttachmentPath =
+ element.hasAttribute("sourcepath") //$NON-NLS-1$
+ ? new Path(element.getAttribute("sourcepath")) //$NON-NLS-1$
+ : null;
+ IPath sourceAttachmentRootPath =
+ element.hasAttribute("rootpath") //$NON-NLS-1$
+ ? new Path(element.getAttribute("rootpath")) //$NON-NLS-1$
+ : null;
+
+ // exported flag (optional)
+ boolean isExported = element.getAttribute("exported").equals("true"); //$NON-NLS-1$ //$NON-NLS-2$
+
+ // exclusion patterns (optional)
+ String exclusion = element.getAttribute("excluding"); //$NON-NLS-1$
+ IPath[] exclusionPatterns = ClasspathEntry.NO_EXCLUSION_PATTERNS;
+ if (!exclusion.equals("")) { //$NON-NLS-1$
+ char[][] patterns = CharOperation.splitOn('|', exclusion.toCharArray());
+ int patternCount;
+ if ((patternCount = patterns.length) > 0) {
+ exclusionPatterns = new IPath[patternCount];
+ for (int j = 0; j < patterns.length; j++){
+ exclusionPatterns[j] = new Path(new String(patterns[j]));
+ }
+ }
+ }
+
+ // custom output location
+ IPath outputLocation = element.hasAttribute("output") ? projectPath.append(element.getAttribute("output")) : null; //$NON-NLS-1$ //$NON-NLS-2$
+
+ // recreate the CP entry
+ switch (kind) {
+
+ case IClasspathEntry.CPE_PROJECT :
+ return PHPCore.newProjectEntry(path, isExported);
+
+// case IClasspathEntry.CPE_LIBRARY :
+// return JavaCore.newLibraryEntry(
+// path,
+// sourceAttachmentPath,
+// sourceAttachmentRootPath,
+// isExported);
+
+ case IClasspathEntry.CPE_SOURCE :
+ // must be an entry in this project or specify another project
+ String projSegment = path.segment(0);
+ if (projSegment != null && projSegment.equals(project.getElementName())) { // this project
+ return PHPCore.newSourceEntry(path, exclusionPatterns, outputLocation);
+ } else { // another project
+ return PHPCore.newProjectEntry(path, isExported);
+ }
+
+// case IClasspathEntry.CPE_VARIABLE :
+// return PHPCore.newVariableEntry(
+// path,
+// sourceAttachmentPath,
+// sourceAttachmentRootPath,
+// isExported);
+
+ case IClasspathEntry.CPE_CONTAINER :
+ return PHPCore.newContainerEntry(
+ path,
+ isExported);
+
+ case ClasspathEntry.K_OUTPUT :
+ if (!path.isAbsolute()) return null;
+ return new ClasspathEntry(
+ ClasspathEntry.K_OUTPUT,
+ IClasspathEntry.CPE_LIBRARY,
+ path,
+ ClasspathEntry.NO_EXCLUSION_PATTERNS,
+ null, // source attachment
+ null, // source attachment root
+ null, // custom output location
+ false);
+ default :
+ throw new Assert.AssertionFailedException(Util.bind("classpath.unknownKind", kindAttr)); //$NON-NLS-1$
+ }
+ }
+
+ /**
+ * Returns true if the given object is a classpath entry
+ * with equivalent attributes.
+ */
+ public boolean equals(Object object) {
+ if (this == object)
+ return true;
+ if (object instanceof IClasspathEntry) {
+ IClasspathEntry otherEntry = (IClasspathEntry) object;
+
+ if (this.contentKind != otherEntry.getContentKind())
+ return false;
+
+ if (this.entryKind != otherEntry.getEntryKind())
+ return false;
+
+ if (this.isExported != otherEntry.isExported())
+ return false;
+
+ if (!this.path.equals(otherEntry.getPath()))
+ return false;
+
+ IPath otherPath = otherEntry.getSourceAttachmentPath();
+ if (this.sourceAttachmentPath == null) {
+ if (otherPath != null)
+ return false;
+ } else {
+ if (!this.sourceAttachmentPath.equals(otherPath))
+ return false;
+ }
+
+ otherPath = otherEntry.getSourceAttachmentRootPath();
+ if (this.sourceAttachmentRootPath == null) {
+ if (otherPath != null)
+ return false;
+ } else {
+ if (!this.sourceAttachmentRootPath.equals(otherPath))
+ return false;
+ }
+
+ IPath[] otherExcludes = otherEntry.getExclusionPatterns();
+ if (this.exclusionPatterns != otherExcludes){
+ int excludeLength = this.exclusionPatterns.length;
+ if (otherExcludes.length != excludeLength)
+ return false;
+ for (int i = 0; i < excludeLength; i++) {
+ // compare toStrings instead of IPaths
+ // since IPath.equals is specified to ignore trailing separators
+ if (!this.exclusionPatterns[i].toString().equals(otherExcludes[i].toString()))
+ return false;
+ }
+ }
+
+ otherPath = otherEntry.getOutputLocation();
+ if (this.specificOutputLocation == null) {
+ if (otherPath != null)
+ return false;
+ } else {
+ if (!this.specificOutputLocation.equals(otherPath))
+ return false;
+ }
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ /**
+ * @see IClasspathEntry
+ */
+ public int getContentKind() {
+ return this.contentKind;
+ }
+
+ /**
+ * @see IClasspathEntry
+ */
+ public int getEntryKind() {
+ return this.entryKind;
+ }
+
+ /**
+ * @see IClasspathEntry#getExclusionPatterns()
+ */
+ public IPath[] getExclusionPatterns() {
+ return this.exclusionPatterns;
+ }
+
+ /**
+ * @see IClasspathEntry#getOutputLocation()
+ */
+ public IPath getOutputLocation() {
+ return this.specificOutputLocation;
+ }
+
+ /**
+ * @see IClasspathEntry
+ */
+ public IPath getPath() {
+ return this.path;
+ }
+
+ /**
+ * @see IClasspathEntry
+ */
+ public IPath getSourceAttachmentPath() {
+ return this.sourceAttachmentPath;
+ }
+
+ /**
+ * @see IClasspathEntry
+ */
+ public IPath getSourceAttachmentRootPath() {
+ return this.sourceAttachmentRootPath;
+ }
+
+ /**
+ * Returns the hash code for this classpath entry
+ */
+ public int hashCode() {
+ return this.path.hashCode();
+ }
+
+ /**
+ * @see IClasspathEntry#isExported()
+ */
+ public boolean isExported() {
+ return this.isExported;
+ }
+
+ /**
+ * Returns the kind of a PackageFragmentRoot
from its String
form.
+ */
+ static int kindFromString(String kindStr) {
+
+ if (kindStr.equalsIgnoreCase("prj")) //$NON-NLS-1$
+ return IClasspathEntry.CPE_PROJECT;
+ if (kindStr.equalsIgnoreCase("var")) //$NON-NLS-1$
+ return IClasspathEntry.CPE_VARIABLE;
+ if (kindStr.equalsIgnoreCase("con")) //$NON-NLS-1$
+ return IClasspathEntry.CPE_CONTAINER;
+ if (kindStr.equalsIgnoreCase("src")) //$NON-NLS-1$
+ return IClasspathEntry.CPE_SOURCE;
+ if (kindStr.equalsIgnoreCase("lib")) //$NON-NLS-1$
+ return IClasspathEntry.CPE_LIBRARY;
+ if (kindStr.equalsIgnoreCase("output")) //$NON-NLS-1$
+ return ClasspathEntry.K_OUTPUT;
+ return -1;
+ }
+
+ /**
+ * Returns a String
for the kind of a class path entry.
+ */
+ static String kindToString(int kind) {
+
+ switch (kind) {
+ case IClasspathEntry.CPE_PROJECT :
+ return "src"; // backward compatibility //$NON-NLS-1$
+ case IClasspathEntry.CPE_SOURCE :
+ return "src"; //$NON-NLS-1$
+ case IClasspathEntry.CPE_LIBRARY :
+ return "lib"; //$NON-NLS-1$
+ case IClasspathEntry.CPE_VARIABLE :
+ return "var"; //$NON-NLS-1$
+ case IClasspathEntry.CPE_CONTAINER :
+ return "con"; //$NON-NLS-1$
+ case ClasspathEntry.K_OUTPUT :
+ return "output"; //$NON-NLS-1$
+ default :
+ return "unknown"; //$NON-NLS-1$
+ }
+ }
+
+ /**
+ * Returns a printable representation of this classpath entry.
+ */
+ public String toString() {
+ StringBuffer buffer = new StringBuffer();
+ buffer.append(getPath().toString());
+ buffer.append('[');
+ switch (getEntryKind()) {
+ case IClasspathEntry.CPE_LIBRARY :
+ buffer.append("CPE_LIBRARY"); //$NON-NLS-1$
+ break;
+ case IClasspathEntry.CPE_PROJECT :
+ buffer.append("CPE_PROJECT"); //$NON-NLS-1$
+ break;
+ case IClasspathEntry.CPE_SOURCE :
+ buffer.append("CPE_SOURCE"); //$NON-NLS-1$
+ break;
+ case IClasspathEntry.CPE_VARIABLE :
+ buffer.append("CPE_VARIABLE"); //$NON-NLS-1$
+ break;
+ case IClasspathEntry.CPE_CONTAINER :
+ buffer.append("CPE_CONTAINER"); //$NON-NLS-1$
+ break;
+ }
+ buffer.append("]["); //$NON-NLS-1$
+ switch (getContentKind()) {
+ case IPackageFragmentRoot.K_BINARY :
+ buffer.append("K_BINARY"); //$NON-NLS-1$
+ break;
+ case IPackageFragmentRoot.K_SOURCE :
+ buffer.append("K_SOURCE"); //$NON-NLS-1$
+ break;
+ case ClasspathEntry.K_OUTPUT :
+ buffer.append("K_OUTPUT"); //$NON-NLS-1$
+ break;
+ }
+ buffer.append(']');
+ if (getSourceAttachmentPath() != null) {
+ buffer.append("[sourcePath:"); //$NON-NLS-1$
+ buffer.append(getSourceAttachmentPath());
+ buffer.append(']');
+ }
+ if (getSourceAttachmentRootPath() != null) {
+ buffer.append("[rootPath:"); //$NON-NLS-1$
+ buffer.append(getSourceAttachmentRootPath());
+ buffer.append(']');
+ }
+ buffer.append("[isExported:"); //$NON-NLS-1$
+ buffer.append(this.isExported);
+ buffer.append(']');
+ IPath[] patterns = getExclusionPatterns();
+ int length;
+ if ((length = patterns.length) > 0) {
+ buffer.append("[excluding:"); //$NON-NLS-1$
+ for (int i = 0; i < length; i++) {
+ buffer.append(patterns[i]);
+ if (i != length-1) {
+ buffer.append('|');
+ }
+ }
+ buffer.append(']');
+ }
+ if (getOutputLocation() != null) {
+ buffer.append("[output:"); //$NON-NLS-1$
+ buffer.append(getOutputLocation());
+ buffer.append(']');
+ }
+ return buffer.toString();
+ }
+
+ /**
+ * Answers an ID which is used to distinguish entries during package
+ * fragment root computations
+ */
+ public String rootID(){
+
+ if (this.rootID == null) {
+ switch(this.entryKind){
+ case IClasspathEntry.CPE_LIBRARY :
+ this.rootID = "[LIB]"+this.path; //$NON-NLS-1$
+ break;
+ case IClasspathEntry.CPE_PROJECT :
+ this.rootID = "[PRJ]"+this.path; //$NON-NLS-1$
+ break;
+ case IClasspathEntry.CPE_SOURCE :
+ this.rootID = "[SRC]"+this.path; //$NON-NLS-1$
+ break;
+ case IClasspathEntry.CPE_VARIABLE :
+ this.rootID = "[VAR]"+this.path; //$NON-NLS-1$
+ break;
+ case IClasspathEntry.CPE_CONTAINER :
+ this.rootID = "[CON]"+this.path; //$NON-NLS-1$
+ break;
+ default :
+ this.rootID = ""; //$NON-NLS-1$
+ break;
+ }
+ }
+ return this.rootID;
+ }
+
+ /**
+ * @see IClasspathEntry
+ * @deprecated
+ */
+ public IClasspathEntry getResolvedEntry() {
+
+ return PHPCore.getResolvedClasspathEntry(this);
+ }
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CommitWorkingCopyOperation.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CommitWorkingCopyOperation.java
new file mode 100644
index 0000000..743484c
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CommitWorkingCopyOperation.java
@@ -0,0 +1,147 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core;
+
+import net.sourceforge.phpdt.core.IBuffer;
+import net.sourceforge.phpdt.core.ICompilationUnit;
+import net.sourceforge.phpdt.core.IJavaElement;
+import net.sourceforge.phpdt.core.IJavaModelStatus;
+import net.sourceforge.phpdt.core.IJavaModelStatusConstants;
+import net.sourceforge.phpdt.core.JavaModelException;
+
+import org.eclipse.core.resources.IResource;
+
+
+/**
+ * Commits the contents of a working copy compilation
+ * unit to its original element and resource, bringing
+ * the Java Model up-to-date with the current contents of the working
+ * copy.
+ *
+ *
It is possible that the contents of the
+ * original resource have changed since the working copy was created,
+ * in which case there is an update conflict. This operation allows
+ * for two settings to resolve conflict set by the fForce
flag:
false
- in this case an JavaModelException
+ * is throwntrue
- in this case the contents of
+ * the working copy are applied to the underlying resource even though
+ * the working copy was created before a subsequent change in the
+ * resourceThe default conflict resolution setting is the force flag is false
+ *
+ * A JavaModelOperation exception is thrown either if the commit could not
+ * be performed or if the new content of the compilation unit violates some Java Model
+ * constraint (e.g. if the new package declaration doesn't match the name of the folder
+ * containing the compilation unit).
+ */
+public class CommitWorkingCopyOperation extends JavaModelOperation {
+ /**
+ * Constructs an operation to commit the contents of a working copy
+ * to its original compilation unit.
+ */
+ public CommitWorkingCopyOperation(ICompilationUnit element, boolean force) {
+ super(new IJavaElement[] {element}, force);
+ }
+ /**
+ * @exception JavaModelException if setting the source
+ * of the original compilation unit fails
+ */
+ protected void executeOperation() throws JavaModelException {
+ try {
+ beginTask(Util.bind("workingCopy.commit"), 2); //$NON-NLS-1$
+ WorkingCopy copy = (WorkingCopy)getCompilationUnit();
+ ICompilationUnit original = (ICompilationUnit) copy.getOriginalElement();
+
+
+ // creates the delta builder (this remembers the content of the cu)
+ if (!original.isOpen()) {
+ // force opening so that the delta builder can get the old info
+ original.open(null);
+ }
+ JavaElementDeltaBuilder deltaBuilder;
+ if (Util.isExcluded(original)) {
+ deltaBuilder = null;
+ } else {
+ deltaBuilder = new JavaElementDeltaBuilder(original);
+ }
+
+ // save the cu
+ IBuffer originalBuffer = original.getBuffer();
+ if (originalBuffer == null) return;
+ char[] originalContents = originalBuffer.getCharacters();
+ boolean hasSaved = false;
+ try {
+ IBuffer copyBuffer = copy.getBuffer();
+ if (copyBuffer == null) return;
+ originalBuffer.setContents(copyBuffer.getCharacters());
+ original.save(fMonitor, fForce);
+ this.setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
+ hasSaved = true;
+ } finally {
+ if (!hasSaved){
+ // restore original buffer contents since something went wrong
+ originalBuffer.setContents(originalContents);
+ }
+ }
+ // make sure working copy is in sync
+ copy.updateTimeStamp((CompilationUnit)original);
+ copy.makeConsistent(this);
+ worked(1);
+
+ if (deltaBuilder != null) {
+ // build the deltas
+ deltaBuilder.buildDeltas();
+
+ // add the deltas to the list of deltas created during this operation
+ if (deltaBuilder.delta != null) {
+ addDelta(deltaBuilder.delta);
+ }
+ }
+ worked(1);
+ } finally {
+ done();
+ }
+ }
+ /**
+ * Returns the compilation unit this operation is working on.
+ */
+ protected ICompilationUnit getCompilationUnit() {
+ return (ICompilationUnit)getElementToProcess();
+ }
+ /**
+ * Possible failures:
String
+ */
+ protected int fSourceLength;
+
+ /**
+ * Timestamp of original resource at the time this element
+ * was opened or last updated.
+ */
+ protected long fTimestamp;
+/**
+ * Returns the length of the source string.
+ */
+public int getSourceLength() {
+ return fSourceLength;
+}
+protected ISourceRange getSourceRange() {
+ return new SourceRange(0, fSourceLength);
+}
+/**
+ * Sets the length of the source string.
+ */
+public void setSourceLength(int newSourceLength) {
+ fSourceLength = newSourceLength;
+}
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CompilationUnitProblemFinder.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CompilationUnitProblemFinder.java
new file mode 100644
index 0000000..6cfb4c4
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CompilationUnitProblemFinder.java
@@ -0,0 +1,233 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core;
+
+import java.util.Locale;
+
+import net.sourceforge.phpdt.core.ICompilationUnit;
+import net.sourceforge.phpdt.core.IJavaElement;
+import net.sourceforge.phpdt.core.IJavaProject;
+import net.sourceforge.phpdt.core.IPackageFragment;
+import net.sourceforge.phpdt.core.IProblemRequestor;
+import net.sourceforge.phpdt.core.JavaModelException;
+import net.sourceforge.phpdt.core.compiler.CharOperation;
+import net.sourceforge.phpdt.core.compiler.IProblem;
+import net.sourceforge.phpdt.internal.compiler.CompilationResult;
+import net.sourceforge.phpdt.internal.compiler.Compiler;
+import net.sourceforge.phpdt.internal.compiler.DefaultErrorHandlingPolicies;
+import net.sourceforge.phpdt.internal.compiler.ICompilerRequestor;
+import net.sourceforge.phpdt.internal.compiler.IErrorHandlingPolicy;
+import net.sourceforge.phpdt.internal.compiler.IProblemFactory;
+import net.sourceforge.phpdt.internal.compiler.env.INameEnvironment;
+import net.sourceforge.phpdt.internal.compiler.env.ISourceType;
+import net.sourceforge.phpdt.internal.compiler.lookup.PackageBinding;
+import net.sourceforge.phpdt.internal.compiler.parser.SourceTypeConverter;
+import net.sourceforge.phpdt.internal.compiler.problem.AbortCompilation;
+import net.sourceforge.phpdt.internal.compiler.problem.DefaultProblemFactory;
+import net.sourceforge.phpeclipse.PHPCore;
+import net.sourceforge.phpeclipse.internal.compiler.ast.CompilationUnitDeclaration;
+
+import org.eclipse.core.runtime.IProgressMonitor;
+
+/**
+ * Responsible for resolving types inside a compilation unit being reconciled,
+ * reporting the discovered problems to a given IProblemRequestor.
+ */
+public class CompilationUnitProblemFinder extends Compiler {
+
+ /**
+ * Answer a new CompilationUnitVisitor using the given name environment and compiler options.
+ * The environment and options will be in effect for the lifetime of the compiler.
+ * When the compiler is run, compilation results are sent to the given requestor.
+ *
+ * @param environment org.eclipse.jdt.internal.compiler.api.env.INameEnvironment
+ * Environment used by the compiler in order to resolve type and package
+ * names. The name environment implements the actual connection of the compiler
+ * to the outside world (e.g. in batch mode the name environment is performing
+ * pure file accesses, reuse previous build state or connection to repositories).
+ * Note: the name environment is responsible for implementing the actual classpath
+ * rules.
+ *
+ * @param policy org.eclipse.jdt.internal.compiler.api.problem.IErrorHandlingPolicy
+ * Configurable part for problem handling, allowing the compiler client to
+ * specify the rules for handling problems (stop on first error or accumulate
+ * them all) and at the same time perform some actions such as opening a dialog
+ * in UI when compiling interactively.
+ * @see org.eclipse.jdt.internal.compiler.api.problem.DefaultErrorHandlingPolicies
+ *
+ * @param settings The settings to use for the resolution.
+ *
+ * @param requestor org.eclipse.jdt.internal.compiler.api.ICompilerRequestor
+ * Component which will receive and persist all compilation results and is intended
+ * to consume them as they are produced. Typically, in a batch compiler, it is
+ * responsible for writing out the actual .class files to the file system.
+ * @see org.eclipse.jdt.internal.compiler.api.CompilationResult
+ *
+ * @param problemFactory org.eclipse.jdt.internal.compiler.api.problem.IProblemFactory
+ * Factory used inside the compiler to create problem descriptors. It allows the
+ * compiler client to supply its own representation of compilation problems in
+ * order to avoid object conversions. Note that the factory is not supposed
+ * to accumulate the created problems, the compiler will gather them all and hand
+ * them back as part of the compilation unit result.
+ */
+ protected CompilationUnitProblemFinder(
+ INameEnvironment environment,
+ IErrorHandlingPolicy policy,
+// Map settings,
+ ICompilerRequestor requestor,
+ IProblemFactory problemFactory) {
+
+ super(environment, policy, requestor, problemFactory, true);//settings, requestor, problemFactory, true);
+ }
+
+ /**
+ * Add additional source types
+ */
+ public void accept(ISourceType[] sourceTypes, PackageBinding packageBinding) {
+ // ensure to jump back to toplevel type for first one (could be a member)
+// while (sourceTypes[0].getEnclosingType() != null)
+// sourceTypes[0] = sourceTypes[0].getEnclosingType();
+
+ CompilationResult result =
+ new CompilationResult(sourceTypes[0].getFileName(), 1, 1, 10); //this.options.maxProblemsPerUnit);
+
+ // need to hold onto this
+ CompilationUnitDeclaration unit =
+ SourceTypeConverter.buildCompilationUnit(
+ sourceTypes,//sourceTypes[0] is always toplevel here
+ true, // need field and methods
+ true, // need member types
+ true, // need field initialization
+ lookupEnvironment.problemReporter,
+ result);
+
+ if (unit != null) {
+ this.lookupEnvironment.buildTypeBindings(unit);
+ this.lookupEnvironment.completeTypeBindings(unit, true);
+ }
+ }
+
+ /*
+ * Low-level API performing the actual compilation
+ */
+ protected static IErrorHandlingPolicy getHandlingPolicy() {
+ return DefaultErrorHandlingPolicies.proceedWithAllProblems();
+ }
+
+ protected static INameEnvironment getNameEnvironment(ICompilationUnit sourceUnit)
+ throws JavaModelException {
+ return (SearchableEnvironment) ((JavaProject) sourceUnit.getJavaProject())
+ .getSearchableNameEnvironment();
+ }
+
+ /*
+ * Answer the component to which will be handed back compilation results from the compiler
+ */
+ protected static ICompilerRequestor getRequestor() {
+ return new ICompilerRequestor() {
+ public void acceptResult(CompilationResult compilationResult) {
+ }
+ };
+ }
+
+ protected static IProblemFactory getProblemFactory(
+ final char[] fileName,
+ final IProblemRequestor problemRequestor,
+ final IProgressMonitor monitor) {
+
+ return new DefaultProblemFactory(Locale.getDefault()) {
+ public IProblem createProblem(
+ char[] originatingFileName,
+ int problemId,
+ String[] problemArguments,
+ String[] messageArguments,
+ int severity,
+ int startPosition,
+ int endPosition,
+ int lineNumber) {
+
+ if (monitor != null && monitor.isCanceled()){
+ throw new AbortCompilation(true, null); // silent abort
+ }
+
+ IProblem problem =
+ super.createProblem(
+ originatingFileName,
+ problemId,
+ problemArguments,
+ messageArguments,
+ severity,
+ startPosition,
+ endPosition,
+ lineNumber);
+ // only report local problems
+ if (CharOperation.equals(originatingFileName, fileName)){
+ if (JavaModelManager.VERBOSE){
+ System.out.println("PROBLEM FOUND while reconciling : "+problem.getMessage());//$NON-NLS-1$
+ }
+ problemRequestor.acceptProblem(problem);
+ }
+ if (monitor != null && monitor.isCanceled()){
+ throw new AbortCompilation(true, null); // silent abort
+ }
+
+ return problem;
+ }
+ };
+ }
+
+ public static CompilationUnitDeclaration process(
+ ICompilationUnit unitElement,
+ IProblemRequestor problemRequestor,
+ IProgressMonitor monitor)
+ throws JavaModelException {
+
+ char[] fileName = unitElement.getElementName().toCharArray();
+
+ IJavaProject project = unitElement.getJavaProject();
+ CompilationUnitProblemFinder problemFinder =
+ new CompilationUnitProblemFinder(
+ getNameEnvironment(unitElement),
+ getHandlingPolicy(),
+ getRequestor(),
+ getProblemFactory(fileName, problemRequestor, monitor));
+// project.getOptions(true),
+// getRequestor(),
+// getProblemFactory(fileName, problemRequestor, monitor));
+
+ CompilationUnitDeclaration unit = null;
+ try {
+ String encoding = project.getOption(PHPCore.CORE_ENCODING, true);
+
+ IPackageFragment packageFragment = (IPackageFragment)unitElement.getAncestor(IJavaElement.PACKAGE_FRAGMENT);
+ char[][] expectedPackageName = null;
+ if (packageFragment != null){
+ expectedPackageName = CharOperation.splitOn('.', packageFragment.getElementName().toCharArray());
+ }
+ unit = problemFinder.resolve(
+ new BasicCompilationUnit(
+ unitElement.getSource().toCharArray(),
+ expectedPackageName,
+ new String(fileName),
+ encoding),
+ true, // verify methods
+ true); // analyze code
+// true); // generate code
+ return unit;
+ } finally {
+ if (unit != null) {
+ unit.cleanUp();
+ }
+ problemFinder.lookupEnvironment.reset();
+ }
+ }
+}
+
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CompilationUnitStructureRequestor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CompilationUnitStructureRequestor.java
new file mode 100644
index 0000000..ce3680d
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CompilationUnitStructureRequestor.java
@@ -0,0 +1,587 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core;
+
+import java.util.Map;
+import java.util.Stack;
+
+import net.sourceforge.phpdt.core.ICompilationUnit;
+import net.sourceforge.phpdt.core.IField;
+import net.sourceforge.phpdt.core.IJavaElement;
+import net.sourceforge.phpdt.core.IMethod;
+import net.sourceforge.phpdt.core.IType;
+import net.sourceforge.phpdt.core.JavaModelException;
+import net.sourceforge.phpdt.core.Signature;
+import net.sourceforge.phpdt.core.compiler.IProblem;
+import net.sourceforge.phpdt.internal.compiler.ISourceElementRequestor;
+import net.sourceforge.phpdt.internal.compiler.parser.Parser;
+import net.sourceforge.phpdt.internal.compiler.util.HashtableOfObject;
+import net.sourceforge.phpdt.internal.core.util.ReferenceInfoAdapter;
+import net.sourceforge.phpdt.internal.corext.Assert;
+
+/**
+ * A requestor for the fuzzy parser, used to compute the children of an ICompilationUnit.
+ */
+public class CompilationUnitStructureRequestor extends ReferenceInfoAdapter implements ISourceElementRequestor {
+
+ /**
+ * The handle to the compilation unit being parsed
+ */
+ protected ICompilationUnit fUnit;
+
+ /**
+ * The info object for the compilation unit being parsed
+ */
+ protected CompilationUnitElementInfo fUnitInfo;
+
+ /**
+ * The import container info - null until created
+ */
+ protected JavaElementInfo fImportContainerInfo = null;
+
+ /**
+ * Hashtable of children elements of the compilation unit.
+ * Children are added to the table as they are found by
+ * the parser. Keys are handles, values are corresponding
+ * info objects.
+ */
+ protected Map fNewElements;
+
+ /**
+ * Stack of parent scope info objects. The info on the
+ * top of the stack is the parent of the next element found.
+ * For example, when we locate a method, the parent info object
+ * will be the type the method is contained in.
+ */
+ protected Stack fInfoStack;
+
+ /**
+ * Stack of parent handles, corresponding to the info stack. We
+ * keep both, since info objects do not have back pointers to
+ * handles.
+ */
+ protected Stack fHandleStack;
+
+ /**
+ * The name of the source file being parsed.
+ */
+ protected char[] fSourceFileName = null;
+
+ /**
+ * The dot-separated name of the package the compilation unit
+ * is contained in - based on the package statement in the
+ * compilation unit, and initialized by #acceptPackage.
+ * Initialized to null
for the default package.
+ */
+ protected char[] fPackageName = null;
+
+ /**
+ * The number of references reported thus far. Used to
+ * expand the arrays of reference kinds and names.
+ */
+ protected int fRefCount = 0;
+
+ /**
+ * The initial size of the reference kind and name
+ * arrays. If the arrays fill, they are doubled in
+ * size
+ */
+ protected static int fgReferenceAllocation = 50;
+
+ /**
+ * Problem requestor which will get notified of discovered problems
+ */
+ protected boolean hasSyntaxErrors = false;
+
+ /*
+ * The parser this requestor is using.
+ */
+ // protected Parser parser;
+ protected Parser parser;
+
+ /**
+ * Empty collections used for efficient initialization
+ */
+ protected static String[] fgEmptyStringArray = new String[0];
+ protected static byte[] fgEmptyByte = new byte[] {
+ };
+ protected static char[][] fgEmptyCharChar = new char[][] {
+ };
+ protected static char[] fgEmptyChar = new char[] {
+ };
+
+ protected HashtableOfObject fieldRefCache;
+ protected HashtableOfObject messageRefCache;
+ protected HashtableOfObject typeRefCache;
+ protected HashtableOfObject unknownRefCache;
+
+ protected CompilationUnitStructureRequestor(ICompilationUnit unit, CompilationUnitElementInfo unitInfo, Map newElements)
+ throws JavaModelException {
+ this.fUnit = unit;
+ this.fUnitInfo = unitInfo;
+ this.fNewElements = newElements;
+ this.fSourceFileName = unit.getElementName().toCharArray();
+ }
+ /**
+ * @see ISourceElementRequestor
+ */
+ //public void acceptImport(int declarationStart, int declarationEnd, char[] name, boolean onDemand) {
+ // JavaElementInfo parentInfo = (JavaElementInfo) fInfoStack.peek();
+ // JavaElement parentHandle= (JavaElement)fHandleStack.peek();
+ // if (!(parentHandle.getElementType() == IJavaElement.COMPILATION_UNIT)) {
+ // Assert.isTrue(false); // Should not happen
+ // }
+ //
+ // ICompilationUnit parentCU= (ICompilationUnit)parentHandle;
+ // //create the import container and its info
+ // IImportContainer importContainer= parentCU.getImportContainer();
+ // if (fImportContainerInfo == null) {
+ // fImportContainerInfo= new JavaElementInfo();
+ // fImportContainerInfo.setIsStructureKnown(true);
+ // parentInfo.addChild(importContainer);
+ // fNewElements.put(importContainer, fImportContainerInfo);
+ // }
+ //
+ // // tack on the '.*' if it is onDemand
+ // String importName;
+ // if (onDemand) {
+ // importName= new String(name) + ".*"; //$NON-NLS-1$
+ // } else {
+ // importName= new String(name);
+ // }
+ //
+ // ImportDeclaration handle = new ImportDeclaration(importContainer, importName);
+ // resolveDuplicates(handle);
+ //
+ // SourceRefElementInfo info = new SourceRefElementInfo();
+ // info.setSourceRangeStart(declarationStart);
+ // info.setSourceRangeEnd(declarationEnd);
+ //
+ // fImportContainerInfo.addChild(handle);
+ // fNewElements.put(handle, info);
+ //}
+ /*
+ * Table of line separator position. This table is passed once at the end
+ * of the parse action, so as to allow computation of normalized ranges.
+ *
+ * A line separator might corresponds to several characters in the source,
+ *
+ */
+ public void acceptLineSeparatorPositions(int[] positions) {
+ }
+ /**
+ * @see ISourceElementRequestor
+ */
+ //public void acceptPackage(int declarationStart, int declarationEnd, char[] name) {
+ //
+ // JavaElementInfo parentInfo = (JavaElementInfo) fInfoStack.peek();
+ // JavaElement parentHandle= (JavaElement)fHandleStack.peek();
+ // IPackageDeclaration handle = null;
+ // fPackageName= name;
+ //
+ // if (parentHandle.getElementType() == IJavaElement.COMPILATION_UNIT) {
+ // handle = new PackageDeclaration((ICompilationUnit) parentHandle, new String(name));
+ // }
+ // else {
+ // Assert.isTrue(false); // Should not happen
+ // }
+ // resolveDuplicates(handle);
+ //
+ // SourceRefElementInfo info = new SourceRefElementInfo();
+ // info.setSourceRangeStart(declarationStart);
+ // info.setSourceRangeEnd(declarationEnd);
+ //
+ // parentInfo.addChild(handle);
+ // fNewElements.put(handle, info);
+ //
+ //}
+ public void acceptProblem(IProblem problem) {
+ if ((problem.getID() & IProblem.Syntax) != 0) {
+ this.hasSyntaxErrors = true;
+ }
+ }
+ /**
+ * Convert these type names to signatures.
+ * @see Signature.
+ */
+ /* default */
+ static String[] convertTypeNamesToSigs(char[][] typeNames) {
+ if (typeNames == null)
+ return fgEmptyStringArray;
+ int n = typeNames.length;
+ if (n == 0)
+ return fgEmptyStringArray;
+ String[] typeSigs = new String[n];
+ for (int i = 0; i < n; ++i) {
+ typeSigs[i] = Signature.createTypeSignature(typeNames[i], false);
+ }
+ return typeSigs;
+ }
+ /**
+ * @see ISourceElementRequestor
+ */
+ public void enterClass(
+ int declarationStart,
+ int modifiers,
+ char[] name,
+ int nameSourceStart,
+ int nameSourceEnd,
+ char[] superclass,
+ char[][] superinterfaces) {
+
+ enterType(declarationStart, modifiers, name, nameSourceStart, nameSourceEnd, superclass, superinterfaces);
+
+ }
+ /**
+ * @see ISourceElementRequestor
+ */
+ public void enterCompilationUnit() {
+ fInfoStack = new Stack();
+ fHandleStack = new Stack();
+ fInfoStack.push(fUnitInfo);
+ fHandleStack.push(fUnit);
+ }
+ /**
+ * @see ISourceElementRequestor
+ */
+ public void enterConstructor(
+ int declarationStart,
+ int modifiers,
+ char[] name,
+ int nameSourceStart,
+ int nameSourceEnd,
+ char[][] parameterTypes,
+ char[][] parameterNames,
+ char[][] exceptionTypes) {
+
+ enterMethod(
+ declarationStart,
+ modifiers,
+ null,
+ name,
+ nameSourceStart,
+ nameSourceEnd,
+ parameterTypes,
+ parameterNames,
+ exceptionTypes,
+ true);
+ }
+ /**
+ * @see ISourceElementRequestor
+ */
+ public void enterField(int declarationStart, int modifiers, char[] type, char[] name, int nameSourceStart, int nameSourceEnd) {
+
+ SourceTypeElementInfo parentInfo = (SourceTypeElementInfo) fInfoStack.peek();
+ JavaElement parentHandle = (JavaElement) fHandleStack.peek();
+ IField handle = null;
+
+ if (parentHandle.getElementType() == IJavaElement.TYPE) {
+ handle = new SourceField((IType) parentHandle, new String(name));
+ } else {
+ Assert.isTrue(false); // Should not happen
+ }
+ resolveDuplicates(handle);
+
+ SourceFieldElementInfo info = new SourceFieldElementInfo();
+ info.setName(name);
+ info.setNameSourceStart(nameSourceStart);
+ info.setNameSourceEnd(nameSourceEnd);
+ info.setSourceRangeStart(declarationStart);
+ info.setFlags(modifiers);
+ info.setTypeName(type);
+
+ parentInfo.addChild(handle);
+ fNewElements.put(handle, info);
+
+ fInfoStack.push(info);
+ fHandleStack.push(handle);
+ }
+ /**
+ * @see ISourceElementRequestor
+ */
+ //public void enterInitializer(
+ // int declarationSourceStart,
+ // int modifiers) {
+ // JavaElementInfo parentInfo = (JavaElementInfo) fInfoStack.peek();
+ // JavaElement parentHandle= (JavaElement)fHandleStack.peek();
+ // IInitializer handle = null;
+ //
+ // if (parentHandle.getElementType() == IJavaElement.TYPE) {
+ // handle = ((IType) parentHandle).getInitializer(1);
+ // }
+ // else {
+ // Assert.isTrue(false); // Should not happen
+ // }
+ // resolveDuplicates(handle);
+ //
+ // InitializerElementInfo info = new InitializerElementInfo();
+ // info.setSourceRangeStart(declarationSourceStart);
+ // info.setFlags(modifiers);
+ //
+ // parentInfo.addChild(handle);
+ // fNewElements.put(handle, info);
+ //
+ // fInfoStack.push(info);
+ // fHandleStack.push(handle);
+ //}
+ /**
+ * @see ISourceElementRequestor
+ */
+ public void enterInterface(
+ int declarationStart,
+ int modifiers,
+ char[] name,
+ int nameSourceStart,
+ int nameSourceEnd,
+ char[][] superinterfaces) {
+
+ enterType(declarationStart, modifiers, name, nameSourceStart, nameSourceEnd, null, superinterfaces);
+
+ }
+ /**
+ * @see ISourceElementRequestor
+ */
+ public void enterMethod(
+ int declarationStart,
+ int modifiers,
+ char[] returnType,
+ char[] name,
+ int nameSourceStart,
+ int nameSourceEnd,
+ char[][] parameterTypes,
+ char[][] parameterNames,
+ char[][] exceptionTypes) {
+
+ enterMethod(
+ declarationStart,
+ modifiers,
+ returnType,
+ name,
+ nameSourceStart,
+ nameSourceEnd,
+ parameterTypes,
+ parameterNames,
+ exceptionTypes,
+ false);
+ }
+ /**
+ * @see ISourceElementRequestor
+ */
+ protected void enterMethod(
+ int declarationStart,
+ int modifiers,
+ char[] returnType,
+ char[] name,
+ int nameSourceStart,
+ int nameSourceEnd,
+ char[][] parameterTypes,
+ char[][] parameterNames,
+ char[][] exceptionTypes,
+ boolean isConstructor) {
+ SourceTypeElementInfo parentInfo = null;
+ try {
+ parentInfo = (SourceTypeElementInfo) fInfoStack.peek();
+ } catch (ClassCastException e) {
+ // parentInfo = null;
+ }
+ JavaElement parentHandle = (JavaElement) fHandleStack.peek();
+ IMethod handle = null;
+
+ // translate nulls to empty arrays
+ if (parameterTypes == null) {
+ parameterTypes = fgEmptyCharChar;
+ }
+ if (parameterNames == null) {
+ parameterNames = fgEmptyCharChar;
+ }
+ if (exceptionTypes == null) {
+ exceptionTypes = fgEmptyCharChar;
+ }
+
+ String[] parameterTypeSigs = convertTypeNamesToSigs(parameterTypes);
+ if (parentHandle.getElementType() == IJavaElement.TYPE) {
+ handle = new SourceMethod((IType) parentHandle, new String(name), parameterTypeSigs);
+ } else if (parentHandle.getElementType() == IJavaElement.COMPILATION_UNIT) {
+ handle = new SourceMethod((ICompilationUnit) parentHandle, name==null?"":new String(name), parameterTypeSigs);
+ } else {
+ Assert.isTrue(false); // Should not happen
+ }
+ resolveDuplicates(handle);
+
+ SourceMethodElementInfo info = new SourceMethodElementInfo();
+ info.setSourceRangeStart(declarationStart);
+ int flags = modifiers;
+ info.setName(name);
+ info.setNameSourceStart(nameSourceStart);
+ info.setNameSourceEnd(nameSourceEnd);
+ info.setConstructor(isConstructor);
+ info.setFlags(flags);
+ info.setArgumentNames(parameterNames);
+ info.setArgumentTypeNames(parameterTypes);
+ info.setReturnType(returnType == null ? new char[] { 'v', 'o', 'i', 'd' }
+ : returnType);
+ info.setExceptionTypeNames(exceptionTypes);
+
+ if (parentInfo == null) {
+ fUnitInfo.addChild(handle);
+ } else {
+ parentInfo.addChild(handle);
+ }
+ fNewElements.put(handle, info);
+ fInfoStack.push(info);
+ fHandleStack.push(handle);
+ }
+ /**
+ * Common processing for classes and interfaces.
+ */
+ protected void enterType(
+ int declarationStart,
+ int modifiers,
+ char[] name,
+ int nameSourceStart,
+ int nameSourceEnd,
+ char[] superclass,
+ char[][] superinterfaces) {
+
+ char[] enclosingTypeName = null;
+ char[] qualifiedName = null;
+
+ JavaElementInfo parentInfo = (JavaElementInfo) fInfoStack.peek();
+ JavaElement parentHandle = (JavaElement) fHandleStack.peek();
+ IType handle = null;
+ String nameString = new String(name);
+
+ if (parentHandle.getElementType() == IJavaElement.COMPILATION_UNIT) {
+ handle = ((ICompilationUnit) parentHandle).getType(nameString);
+ if (fPackageName == null) {
+ qualifiedName = nameString.toCharArray();
+ } else {
+ qualifiedName = (new String(fPackageName) + "." + nameString).toCharArray(); //$NON-NLS-1$
+ }
+ } else if (parentHandle.getElementType() == IJavaElement.TYPE) {
+ handle = ((IType) parentHandle).getType(nameString);
+ enclosingTypeName = ((SourceTypeElementInfo) parentInfo).getName();
+ qualifiedName = (new String(((SourceTypeElementInfo) parentInfo).getQualifiedName()) + "." + nameString).toCharArray(); //$NON-NLS-1$
+ } else {
+ Assert.isTrue(false); // Should not happen
+ }
+ resolveDuplicates(handle);
+
+ SourceTypeElementInfo info = new SourceTypeElementInfo();
+ info.setHandle(handle);
+ info.setSourceRangeStart(declarationStart);
+ info.setFlags(modifiers);
+ info.setName(name);
+ info.setNameSourceStart(nameSourceStart);
+ info.setNameSourceEnd(nameSourceEnd);
+ info.setSuperclassName(superclass);
+ info.setSuperInterfaceNames(superinterfaces);
+ info.setEnclosingTypeName(enclosingTypeName);
+ info.setSourceFileName(fSourceFileName);
+ info.setPackageName(fPackageName);
+ info.setQualifiedName(qualifiedName);
+ // for (Iterator iter = fNewElements.keySet().iterator(); iter.hasNext();){
+ // Object object = iter.next();
+ // if (object instanceof IImportDeclaration)
+ // info.addImport(((IImportDeclaration)object).getElementName().toCharArray());
+ // }
+
+ parentInfo.addChild(handle);
+ fNewElements.put(handle, info);
+
+ fInfoStack.push(info);
+ fHandleStack.push(handle);
+
+ }
+ /**
+ * @see ISourceElementRequestor
+ */
+ public void exitClass(int declarationEnd) {
+
+ exitMember(declarationEnd);
+ }
+ /**
+ * @see ISourceElementRequestor
+ */
+ public void exitCompilationUnit(int declarationEnd) {
+ fUnitInfo.setSourceLength(declarationEnd + 1);
+
+ // determine if there were any parsing errors
+ fUnitInfo.setIsStructureKnown(!this.hasSyntaxErrors);
+ }
+ /**
+ * @see ISourceElementRequestor
+ */
+ public void exitConstructor(int declarationEnd) {
+ exitMember(declarationEnd);
+ }
+ ///**
+ // * @see ISourceElementRequestor
+ // */
+ //public void exitField(int initializationStart, int declarationEnd, int declarationSourceEnd) {
+ // SourceFieldElementInfo info = (SourceFieldElementInfo) fInfoStack.pop();
+ // info.setSourceRangeEnd(declarationSourceEnd);
+ //
+ // // remember initializer source if field is a constant
+ // if (initializationStart != -1) {
+ // int flags = info.flags;
+ // Object typeInfo;
+ // if (Flags.isStatic(flags) && Flags.isFinal(flags)
+ // || ((typeInfo = fInfoStack.peek()) instanceof SourceTypeElementInfo
+ // && (Flags.isInterface(((SourceTypeElementInfo)typeInfo).flags)))) {
+ // int length = declarationEnd - initializationStart;
+ // if (length > 0) {
+ // char[] initializer = new char[length];
+ // System.arraycopy(this.parser.scanner.source, initializationStart, initializer, 0, length);
+ // info.initializationSource = initializer;
+ // }
+ // }
+ // }
+ // fHandleStack.pop();
+ //}
+ /**
+ * @see ISourceElementRequestor
+ */
+ public void exitInitializer(int declarationEnd) {
+ exitMember(declarationEnd);
+ }
+ /**
+ * @see ISourceElementRequestor
+ */
+ public void exitInterface(int declarationEnd) {
+ exitMember(declarationEnd);
+ }
+ /**
+ * common processing for classes and interfaces
+ */
+ protected void exitMember(int declarationEnd) {
+ SourceRefElementInfo info = (SourceRefElementInfo) fInfoStack.pop();
+ info.setSourceRangeEnd(declarationEnd);
+ fHandleStack.pop();
+ }
+ /**
+ * @see ISourceElementRequestor
+ */
+ public void exitMethod(int declarationEnd) {
+ exitMember(declarationEnd);
+ }
+
+ /**
+ * Resolves duplicate handles by incrementing the occurrence count
+ * of the handle being created until there is no conflict.
+ */
+ protected void resolveDuplicates(IJavaElement handle) {
+ while (fNewElements.containsKey(handle)) {
+ JavaElement h = (JavaElement) handle;
+ h.setOccurrenceCount(h.getOccurrenceCount() + 1);
+ }
+ }
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CopyElementsOperation.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CopyElementsOperation.java
new file mode 100644
index 0000000..ba92d34
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CopyElementsOperation.java
@@ -0,0 +1,262 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import net.sourceforge.phpdt.core.ICompilationUnit;
+import net.sourceforge.phpdt.core.IJavaElement;
+import net.sourceforge.phpdt.core.IJavaModelStatus;
+import net.sourceforge.phpdt.core.IJavaModelStatusConstants;
+import net.sourceforge.phpdt.core.IMember;
+import net.sourceforge.phpdt.core.IParent;
+import net.sourceforge.phpdt.core.JavaModelException;
+import net.sourceforge.phpdt.core.jdom.DOMFactory;
+import net.sourceforge.phpdt.core.jdom.IDOMCompilationUnit;
+import net.sourceforge.phpdt.core.jdom.IDOMNode;
+
+/**
+ * This operation copies/moves a collection of elements from their current
+ * container to a new container, optionally renaming the
+ * elements.
+ * Notes:
String
to use as the main task name
+ * for progress monitoring.
+ */
+protected String getMainTaskName() {
+ return Util.bind("operation.copyElementProgress"); //$NON-NLS-1$
+}
+/**
+ * Returns the nested operation to use for processing this element
+ */
+protected JavaModelOperation getNestedOperation(IJavaElement element) {
+ return null;
+// try {
+// IJavaElement dest = getDestinationParent(element);
+// switch (element.getElementType()) {
+// case IJavaElement.PACKAGE_DECLARATION :
+// return new CreatePackageDeclarationOperation(element.getElementName(), (ICompilationUnit) dest);
+// case IJavaElement.IMPORT_DECLARATION :
+// return new CreateImportOperation(element.getElementName(), (ICompilationUnit) dest);
+// case IJavaElement.TYPE :
+// if (isRenamingMainType(element, dest)) {
+// return new RenameResourceElementsOperation(new IJavaElement[] {dest}, new IJavaElement[] {dest.getParent()}, new String[]{getNewNameFor(element) + ".php"}, fForce); //$NON-NLS-1$
+// } else {
+// return new CreateTypeOperation(dest, getSourceFor(element) + Util.LINE_SEPARATOR, fForce);
+// }
+// case IJavaElement.METHOD :
+// return new CreateMethodOperation((IType) dest, getSourceFor(element) + Util.LINE_SEPARATOR, fForce);
+// case IJavaElement.FIELD :
+// return new CreateFieldOperation((IType) dest, getSourceFor(element) + Util.LINE_SEPARATOR, fForce);
+// case IJavaElement.INITIALIZER :
+// return new CreateInitializerOperation((IType) dest, getSourceFor(element) + Util.LINE_SEPARATOR);
+// default :
+// return null;
+// }
+// } catch (JavaModelException npe) {
+// return null;
+// }
+}
+/**
+ * Returns the cached source for this element or compute it if not already cached.
+ */
+private String getSourceFor(IJavaElement element) throws JavaModelException {
+ String source = (String) fSources.get(element);
+ if (source == null && element instanceof IMember) {
+ IMember member = (IMember)element;
+ ICompilationUnit cu = member.getCompilationUnit();
+ String cuSource = cu.getSource();
+ IDOMCompilationUnit domCU = new DOMFactory().createCompilationUnit(cuSource, cu.getElementName());
+ IDOMNode node = ((JavaElement)element).findNode(domCU);
+ source = new String(node.getCharacters());
+ fSources.put(element, source);
+ }
+ return source;
+}
+/**
+ * Returns true
if this element is the main type of its compilation unit.
+ */
+protected boolean isRenamingMainType(IJavaElement element, IJavaElement dest) {
+ if ((isRename() || getNewNameFor(element) != null)
+ && dest.getElementType() == IJavaElement.COMPILATION_UNIT) {
+ String typeName = dest.getElementName();
+ typeName = typeName.substring(0, typeName.length() - 5);
+ return element.getElementName().equals(typeName) && element.getParent().equals(dest);
+ }
+ return false;
+}
+/**
+ * Copy/move the element from the source to destination, renaming
+ * the elements as specified, honoring the collision policy.
+ *
+ * @exception JavaModelException if the operation is unable to
+ * be completed
+ */
+protected void processElement(IJavaElement element) throws JavaModelException {
+ JavaModelOperation op = getNestedOperation(element);
+ boolean createElementInCUOperation =op instanceof CreateElementInCUOperation;
+ if (op == null) {
+ return;
+ }
+ if (createElementInCUOperation) {
+ IJavaElement sibling = (IJavaElement) fInsertBeforeElements.get(element);
+ if (sibling != null) {
+ ((CreateElementInCUOperation) op).setRelativePosition(sibling, CreateElementInCUOperation.INSERT_BEFORE);
+ } else
+ if (isRename()) {
+ IJavaElement anchor = resolveRenameAnchor(element);
+ if (anchor != null) {
+ ((CreateElementInCUOperation) op).setRelativePosition(anchor, CreateElementInCUOperation.INSERT_AFTER); // insert after so that the anchor is found before when deleted below
+ }
+ }
+ String newName = getNewNameFor(element);
+ if (newName != null) {
+ ((CreateElementInCUOperation) op).setAlteredName(newName);
+ }
+ }
+ executeNestedOperation(op, 1);
+
+ JavaElement destination = (JavaElement) getDestinationParent(element);
+ ICompilationUnit unit= destination.getCompilationUnit();
+ if (!unit.isWorkingCopy()) {
+ unit.close();
+ }
+
+ if (createElementInCUOperation && isMove() && !isRenamingMainType(element, destination)) {
+ DeleteElementsOperation deleteOp = new DeleteElementsOperation(new IJavaElement[] { element }, fForce);
+ executeNestedOperation(deleteOp, 1);
+ }
+}
+/**
+ * Returns the anchor used for positioning in the destination for
+ * the element being renamed. For renaming, if no anchor has
+ * explicitly been provided, the element is anchored in the same position.
+ */
+private IJavaElement resolveRenameAnchor(IJavaElement element) throws JavaModelException {
+ IParent parent = (IParent) element.getParent();
+ IJavaElement[] children = parent.getChildren();
+ for (int i = 0; i < children.length; i++) {
+ IJavaElement child = children[i];
+ if (child.equals(element)) {
+ return child;
+ }
+ }
+ return null;
+}
+/**
+ * Possible failures:
+ * element
or its specified destination is
+ * is null
or does not exist. If a null
element is
+ * supplied, no element is provided in the status, otherwise, the non-existant element
+ * is supplied in the status.
+ * element
is not contained within a compilation unit.
+ * This operation only operates on elements contained within compilation units.
+ * element
is read only.
+ * element
+ * is of an incompatible type. The destination for a package declaration or import declaration must
+ * be a compilation unit; the destination for a type must be a type or compilation
+ * unit; the destinaion for any type member (other than a type) must be a type. When
+ * this error occurs, the element provided in the operation status is the element
.
+ * element
does not have valid syntax.
+ * In this case the element and name are provided in the status.
+
+ * Notes:
DOMFactory
used to manipulate the source code of
+ * ICompilationUnit
.
+ */
+ protected DOMFactory fFactory;
+ /**
+ * The list of new resources created during this operation.
+ */
+ protected ArrayList fCreatedElements;
+ /**
+ * When executed, this operation will copy the given resources to the
+ * given containers. The resources and destination containers must be in
+ * the correct order. If there is > 1 destination, the number of destinations
+ * must be the same as the number of resources being copied/moved.
+ */
+ public CopyResourceElementsOperation(IJavaElement[] resourcesToCopy, IJavaElement[] destContainers, boolean force) {
+ super(resourcesToCopy, destContainers, force);
+ fFactory = new DOMFactory();
+ }
+ /**
+ * When executed, this operation will copy the given resources to the
+ * given container.
+ */
+ public CopyResourceElementsOperation(IJavaElement[] resourcesToCopy, IJavaElement destContainer, boolean force) {
+ this(resourcesToCopy, new IJavaElement[]{destContainer}, force);
+ }
+ /**
+ * Returns the children of source
which are affected by this operation.
+ * If source
is a K_SOURCE
, these are the .java
+ * files, if it is a K_BINARY
, they are the .class
files.
+ */
+ private IResource[] collectResourcesOfInterest(IPackageFragment source) throws JavaModelException {
+ IJavaElement[] children = source.getChildren();
+ int childOfInterest = IJavaElement.COMPILATION_UNIT;
+// if (source.getKind() == IPackageFragmentRoot.K_BINARY) {
+// childOfInterest = IJavaElement.CLASS_FILE;
+// }
+ ArrayList correctKindChildren = new ArrayList(children.length);
+ for (int i = 0; i < children.length; i++) {
+ IJavaElement child = children[i];
+ if (child.getElementType() == childOfInterest) {
+ correctKindChildren.add(child.getResource());
+ }
+ }
+ // Gather non-java resources
+// Object[] nonJavaResources = source.getNonJavaResources();
+// int actualNonJavaResourceCount = 0;
+// for (int i = 0, max = nonJavaResources.length; i < max; i++){
+// if (nonJavaResources[i] instanceof IResource) actualNonJavaResourceCount++;
+// }
+// IResource[] actualNonJavaResources = new IResource[actualNonJavaResourceCount];
+// for (int i = 0, max = nonJavaResources.length, index = 0; i < max; i++){
+// if (nonJavaResources[i] instanceof IResource) actualNonJavaResources[index++] = (IResource)nonJavaResources[i];
+// }
+
+// if (actualNonJavaResourceCount != 0) {
+// int correctKindChildrenSize = correctKindChildren.size();
+// IResource[] result = new IResource[correctKindChildrenSize + actualNonJavaResourceCount];
+// correctKindChildren.toArray(result);
+// System.arraycopy(actualNonJavaResources, 0, result, correctKindChildrenSize, actualNonJavaResourceCount);
+// return result;
+// } else {
+ IResource[] result = new IResource[correctKindChildren.size()];
+ correctKindChildren.toArray(result);
+ return result;
+// }
+ }
+ /**
+ * Creates any destination package fragment(s) which do not exists yet.
+ */
+ private void createNeededPackageFragments(IContainer sourceFolder, IPackageFragmentRoot root, String newFragName, boolean moveFolder) throws JavaModelException {
+ IContainer parentFolder = (IContainer) root.getResource();
+ JavaElementDelta projectDelta = null;
+ String[] names = net.sourceforge.phpdt.internal.core.Util.getTrimmedSimpleNames(newFragName);
+ StringBuffer sideEffectPackageName = new StringBuffer();
+ char[][] exclusionsPatterns = ((PackageFragmentRoot)root).fullExclusionPatternChars();
+ for (int i = 0; i < names.length; i++) {
+ String subFolderName = names[i];
+ sideEffectPackageName.append(subFolderName);
+ IResource subFolder = parentFolder.findMember(subFolderName);
+ if (subFolder == null) {
+ // create deepest folder only if not a move (folder will be moved in processPackageFragmentResource)
+ if (!(moveFolder && i == names.length-1)) {
+ createFolder(parentFolder, subFolderName, fForce);
+ }
+ parentFolder = parentFolder.getFolder(new Path(subFolderName));
+ sourceFolder = sourceFolder.getFolder(new Path(subFolderName));
+ if (sourceFolder.isReadOnly()) {
+ parentFolder.setReadOnly(true);
+ }
+ IPackageFragment sideEffectPackage = root.getPackageFragment(sideEffectPackageName.toString());
+ if (i < names.length - 1 // all but the last one are side effect packages
+ && !net.sourceforge.phpdt.internal.core.Util.isExcluded(parentFolder, exclusionsPatterns)) {
+ if (projectDelta == null) {
+ projectDelta = getDeltaFor(root.getJavaProject());
+ }
+ projectDelta.added(sideEffectPackage);
+ }
+ fCreatedElements.add(sideEffectPackage);
+ } else {
+ parentFolder = (IContainer) subFolder;
+ }
+ sideEffectPackageName.append('.');
+ }
+ }
+ /**
+ * Returns the JavaElementDelta
for javaProject
,
+ * creating it and putting it in fDeltasPerProject
if
+ * it does not exist yet.
+ */
+ private JavaElementDelta getDeltaFor(IJavaProject javaProject) {
+ JavaElementDelta delta = (JavaElementDelta) fDeltasPerProject.get(javaProject);
+ if (delta == null) {
+ delta = new JavaElementDelta(javaProject);
+ fDeltasPerProject.put(javaProject, delta);
+ }
+ return delta;
+ }
+ /**
+ * @see MultiOperation
+ */
+ protected String getMainTaskName() {
+ return net.sourceforge.phpdt.internal.core.Util.bind("operation.copyResourceProgress"); //$NON-NLS-1$
+ }
+ /**
+ * Sets the deltas to register the changes resulting from this operation
+ * for this source element and its destination.
+ * If the operation is a cross project operationnewCUName
+ * to the destination package.processCompilationUnitResource
or
+ * processPackageFragmentResource
, depending on the type of
+ * element
.
+ */
+ protected void processElement(IJavaElement element) throws JavaModelException {
+ IJavaElement dest = getDestinationParent(element);
+ switch (element.getElementType()) {
+ case IJavaElement.COMPILATION_UNIT :
+ processCompilationUnitResource((ICompilationUnit) element, (IPackageFragment) dest);
+ fCreatedElements.add(((IPackageFragment) dest).getCompilationUnit(element.getElementName()));
+ break;
+ case IJavaElement.PACKAGE_FRAGMENT :
+ processPackageFragmentResource((IPackageFragment) element, (IPackageFragmentRoot) dest, getNewNameFor(element));
+ break;
+ default :
+ throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element));
+ }
+ }
+ /**
+ * @see MultiOperation
+ * Overridden to allow special processing of JavaElementDelta
s
+ * and fResultElements
.
+ */
+ protected void processElements() throws JavaModelException {
+ fCreatedElements = new ArrayList(fElementsToProcess.length);
+ try {
+ super.processElements();
+ } catch (JavaModelException jme) {
+ throw jme;
+ } finally {
+ fResultElements = new IJavaElement[fCreatedElements.size()];
+ fCreatedElements.toArray(fResultElements);
+ processDeltas();
+ }
+ }
+ /**
+ * Copies/moves a package fragment with the name newName
+ * to the destination package.cu
, modifying the type name and/or package
+ * declaration as necessary.
+ *
+ * @return the new source
+ */
+ private String updatedContent(ICompilationUnit cu, IPackageFragment dest, String newName) throws JavaModelException {
+ String currPackageName = cu.getParent().getElementName();
+ String destPackageName = dest.getElementName();
+ if (currPackageName.equals(destPackageName) && newName == null) {
+ return null; //nothing to change
+ } else {
+ String typeName = cu.getElementName();
+ typeName = typeName.substring(0, typeName.length() - 5);
+ IDOMCompilationUnit cuDOM = null;
+ IBuffer buffer = cu.getBuffer();
+ if (buffer == null) return null;
+ char[] contents = buffer.getCharacters();
+ if (contents == null) return null;
+ cuDOM = fFactory.createCompilationUnit(contents, typeName);
+ updateTypeName(cu, cuDOM, cu.getElementName(), newName);
+ updatePackageStatement(cuDOM, destPackageName);
+ return cuDOM.getContents();
+ }
+ }
+ /**
+ * Makes sure that cu
declares to be in the pkgName
package.
+ */
+ private void updatePackageStatement(IDOMCompilationUnit domCU, String pkgName) throws JavaModelException {
+ boolean defaultPackage = pkgName.equals(IPackageFragment.DEFAULT_PACKAGE_NAME);
+ boolean seenPackageNode = false;
+ Enumeration enum = domCU.getChildren();
+ while (enum.hasMoreElements()) {
+ IDOMNode node = (IDOMNode) enum.nextElement();
+ if (node.getNodeType() == IDOMNode.PACKAGE) {
+ if (! defaultPackage) {
+ node.setName(pkgName);
+ } else {
+ node.remove();
+ }
+ seenPackageNode = true;
+ break;
+ }
+ }
+ if (!seenPackageNode && !defaultPackage) {
+ //the cu was in a default package...no package declaration
+ //create the new package declaration as the first child of the cu
+// IDOMPackage pkg = fFactory.createPackage("package " + pkgName + ";" + net.sourceforge.phpdt.internal.compiler.util.Util.LINE_SEPARATOR); //$NON-NLS-1$ //$NON-NLS-2$
+// IDOMNode firstChild = domCU.getFirstChild();
+// if (firstChild != null) {
+// firstChild.insertSibling(pkg);
+// } // else the cu was empty: leave it empty
+ }
+ }
+ /**
+ * Renames the main type in cu
.
+ */
+ private void updateTypeName(ICompilationUnit cu, IDOMCompilationUnit domCU, String oldName, String newName) throws JavaModelException {
+ if (newName != null) {
+ if (fRenamedCompilationUnits == null) {
+ fRenamedCompilationUnits= new ArrayList(1);
+ }
+ fRenamedCompilationUnits.add(cu);
+ String oldTypeName= oldName.substring(0, oldName.length() - 5);
+ String newTypeName= newName.substring(0, newName.length() - 5);
+ // update main type name
+ IType[] types = cu.getTypes();
+ for (int i = 0, max = types.length; i < max; i++) {
+ IType currentType = types[i];
+ if (currentType.getElementName().equals(oldTypeName)) {
+ IDOMNode typeNode = ((JavaElement) currentType).findNode(domCU);
+ if (typeNode != null) {
+ typeNode.setName(newTypeName);
+ }
+ }
+ }
+ }
+ }
+ /**
+ * Possible failures:
+ * This abstract class implements behavior common to CreateElementInCUOperations
.
+ * To create a compilation unit, or an element contained in a compilation unit, the
+ * source code for the entire compilation unit is updated and saved.
+ *
+ *
The element being created can be positioned relative to an existing
+ * element in the compilation unit via the methods #createAfter
+ * and #createBefore
. By default, the new element is positioned
+ * as the last child of its parent element.
+ *
+ */
+public abstract class CreateElementInCUOperation extends JavaModelOperation {
+ /**
+ * The compilation unit DOM used for this operation
+ */
+ protected IDOMCompilationUnit fCUDOM;
+ /**
+ * A constant meaning to position the new element
+ * as the last child of its parent element.
+ */
+ protected static final int INSERT_LAST = 1;
+ /**
+ * A constant meaning to position the new element
+ * after the element defined by fAnchorElement
.
+ */
+ protected static final int INSERT_AFTER = 2;
+
+ /**
+ * A constant meaning to position the new element
+ * before the element defined by fAnchorElement
.
+ */
+ protected static final int INSERT_BEFORE = 3;
+ /**
+ * One of the position constants, describing where
+ * to position the newly created element.
+ */
+ protected int fInsertionPolicy = INSERT_LAST;
+ /**
+ * The element that the newly created element is
+ * positioned relative to, as described by
+ * fInsertPosition
, or null
+ * if the newly created element will be positioned
+ * last.
+ */
+ protected IJavaElement fAnchorElement = null;
+ /**
+ * A flag indicating whether creation of a new element occurred.
+ * A request for creating a duplicate element would request in this
+ * flag being set to false
. Ensures that no deltas are generated
+ * when creation does not occur.
+ */
+ protected boolean fCreationOccurred = true;
+ /**
+ * The element that is being created.
+ */
+ protected DOMNode fCreatedElement;
+ /**
+ * The position of the element that is being created.
+ */
+ protected int fInsertionPosition = -1;
+ /**
+ * The number of characters the new element replaces,
+ * or 0 if the new element is inserted,
+ * or -1 if the new element is append to the end of the CU.
+ */
+ protected int fReplacementLength = -1;
+ /**
+ * Constructs an operation that creates a Java Language Element with
+ * the specified parent, contained within a compilation unit.
+ */
+ public CreateElementInCUOperation(IJavaElement parentElement) {
+ super(null, new IJavaElement[]{parentElement});
+ initializeDefaultPosition();
+ }
+ /**
+ * Only allow cancelling if this operation is not nested.
+ */
+ protected void checkCanceled() {
+ if (!fNested) {
+ super.checkCanceled();
+ }
+ }
+ /**
+ * Instructs this operation to position the new element after
+ * the given sibling, or to add the new element as the last child
+ * of its parent if null
.
+ */
+ public void createAfter(IJavaElement sibling) {
+ setRelativePosition(sibling, INSERT_AFTER);
+ }
+ /**
+ * Instructs this operation to position the new element before
+ * the given sibling, or to add the new element as the last child
+ * of its parent if null
.
+ */
+ public void createBefore(IJavaElement sibling) {
+ setRelativePosition(sibling, INSERT_BEFORE);
+ }
+ /**
+ * Execute the operation - generate new source for the compilation unit
+ * and save the results.
+ *
+ * @exception JavaModelException if the operation is unable to complete
+ */
+ protected void executeOperation() throws JavaModelException {
+ try {
+ beginTask(getMainTaskName(), getMainAmountOfWork());
+ JavaElementDelta delta = newJavaElementDelta();
+ ICompilationUnit unit = getCompilationUnit();
+ generateNewCompilationUnitDOM(unit);
+ if (fCreationOccurred) {
+ //a change has really occurred
+ IBuffer buffer = unit.getBuffer();
+ if (buffer == null) return;
+ char[] bufferContents = buffer.getCharacters();
+ if (bufferContents == null) return;
+ char[] elementContents = net.sourceforge.phpdt.internal.core.Util.normalizeCRs(fCreatedElement.getCharacters(), bufferContents);
+ switch (fReplacementLength) {
+ case -1 :
+ // element is append at the end
+ buffer.append(elementContents);
+ break;
+ case 0 :
+ // element is inserted
+ buffer.replace(fInsertionPosition, 0, elementContents);
+ break;
+ default :
+ // element is replacing the previous one
+ buffer.replace(fInsertionPosition, fReplacementLength, elementContents);
+ }
+ unit.save(null, false);
+ boolean isWorkingCopy = unit.isWorkingCopy();
+ if (!isWorkingCopy)
+ this.setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
+ worked(1);
+ fResultElements = generateResultHandles();
+ if (!isWorkingCopy // if unit is working copy, then save will have already fired the delta
+ && !Util.isExcluded(unit)
+ && unit.getParent().exists()) {
+ for (int i = 0; i < fResultElements.length; i++) {
+ delta.added(fResultElements[i]);
+ }
+ addDelta(delta);
+ } // else unit is created outside classpath
+ // non-java resource delta will be notified by delta processor
+ }
+ } finally {
+ done();
+ }
+ }
+ /**
+ * Returns a JDOM document fragment for the element being created.
+ */
+ protected abstract IDOMNode generateElementDOM() throws JavaModelException;
+ /**
+ * Returns the DOM with the new source to use for the given compilation unit.
+ */
+ protected void generateNewCompilationUnitDOM(ICompilationUnit cu) throws JavaModelException {
+ IBuffer buffer = cu.getBuffer();
+ if (buffer == null) return;
+ char[] prevSource = buffer.getCharacters();
+ if (prevSource == null) return;
+
+ // create a JDOM for the compilation unit
+ fCUDOM = (new DOMFactory()).createCompilationUnit(prevSource, cu.getElementName());
+ IDOMNode child = generateElementDOM();
+ if (child != null) {
+ insertDOMNode(fCUDOM, child);
+ }
+ worked(1);
+ }
+ /**
+ * Creates and returns the handle for the element this operation created.
+ */
+ protected abstract IJavaElement generateResultHandle();
+ /**
+ * Creates and returns the handles for the elements this operation created.
+ */
+ protected IJavaElement[] generateResultHandles() throws JavaModelException {
+ return new IJavaElement[]{generateResultHandle()};
+ }
+ /**
+ * Returns the compilation unit in which the new element is being created.
+ */
+ protected ICompilationUnit getCompilationUnit() {
+ return getCompilationUnitFor(getParentElement());
+ }
+ /**
+ * Returns the amount of work for the main task of this operation for
+ * progress reporting.
+ */
+ protected int getMainAmountOfWork(){
+ return 2;
+ }
+ /**
+ * Returns the name of the main task of this operation for
+ * progress reporting.
+ */
+ public abstract String getMainTaskName();
+ /**
+ * Returns the elements created by this operation.
+ */
+ public IJavaElement[] getResultElements() {
+ return fResultElements;
+ }
+ /**
+ * Sets the default position in which to create the new type
+ * member. By default, the new element is positioned as the
+ * last child of the parent element in which it is created.
+ * Operations that require a different default position must
+ * override this method.
+ */
+ protected void initializeDefaultPosition() {
+
+ }
+ /**
+ * Inserts the given child into the given JDOM,
+ * based on the position settings of this operation.
+ *
+ * @see createAfter(IJavaElement)
+ * @see createBefore(IJavaElement);
+ */
+ protected void insertDOMNode(IDOMNode parent, IDOMNode child) {
+ if (fInsertionPolicy != INSERT_LAST) {
+ IDOMNode sibling = ((JavaElement)fAnchorElement).findNode(fCUDOM);
+ if (sibling != null && fInsertionPolicy == INSERT_AFTER) {
+ sibling = sibling.getNextNode();
+ }
+ if (sibling != null) {
+ sibling.insertSibling(child);
+ fCreatedElement = (DOMNode)child;
+ fInsertionPosition = ((DOMNode)sibling).getStartPosition();
+ fReplacementLength = 0;
+ return;
+ }
+ }
+ //add as the last element of the parent
+ parent.addChild(child);
+ fCreatedElement = (DOMNode)child;
+ fInsertionPosition = ((DOMNode)parent).getInsertionPosition();
+ // fInsertionPosition = lastChild == null ? ((DOMNode)parent).getInsertionPosition() : lastChild.getInsertionPosition();
+ fReplacementLength = parent.getParent() == null ? -1 : 0;
+ }
+ /**
+ * Sets the name of the DOMNode
that will be used to
+ * create this new element.
+ * Used by the CopyElementsOperation
for renaming.
+ * Only used for CreateTypeMemberOperation
+ */
+ protected void setAlteredName(String newName) {
+ }
+ /**
+ * Instructs this operation to position the new element relative
+ * to the given sibling, or to add the new element as the last child
+ * of its parent if null
. The position
+ * must be one of the position constants.
+ */
+ protected void setRelativePosition(IJavaElement sibling, int policy) throws IllegalArgumentException {
+ if (sibling == null) {
+ fAnchorElement = null;
+ fInsertionPolicy = INSERT_LAST;
+ } else {
+ fAnchorElement = sibling;
+ fInsertionPolicy = policy;
+ }
+ }
+ /**
+ * Possible failures:
null
.
+ * This operation adds/replaces a package declaration in an existing compilation unit. + * If the compilation unit already includes the specified package declaration, + * it is not generated (it does not generate duplicates). + * + *
Required Attributes:
NOTE: This operation only deletes elements contained within leaf resources -
+ * that is, elements within compilation units. To delete a compilation unit or
+ * a package, etc (which have an actual resource), a DeleteResourcesOperation
+ * should be used.
+ */
+public class DeleteElementsOperation extends MultiOperation {
+ /**
+ * The elements this operation processes grouped by compilation unit
+ * @see processElements(). Keys are compilation units,
+ * values are IRegion
s of elements to be processed in each
+ * compilation unit.
+ */
+ protected Map fChildrenToRemove;
+ /**
+ * The DOMFactory
used to manipulate the source code of
+ * ICompilationUnit
s.
+ */
+ protected DOMFactory fFactory;
+ /**
+ * When executed, this operation will delete the given elements. The elements
+ * to delete cannot be null
or empty, and must be contained within a
+ * compilation unit.
+ */
+ public DeleteElementsOperation(IJavaElement[] elementsToDelete, boolean force) {
+ super(elementsToDelete, force);
+ fFactory = new DOMFactory();
+ }
+
+ /**
+ * @see MultiOperation
+ */
+ protected String getMainTaskName() {
+ return Util.bind("operation.deleteElementProgress"); //$NON-NLS-1$
+ }
+ /**
+ * Groups the elements to be processed by their compilation unit.
+ * If parent/child combinations are present, children are
+ * discarded (only the parents are processed). Removes any
+ * duplicates specified in elements to be processed.
+ */
+ protected void groupElements() throws JavaModelException {
+ fChildrenToRemove = new HashMap(1);
+ int uniqueCUs = 0;
+ for (int i = 0, length = fElementsToProcess.length; i < length; i++) {
+ IJavaElement e = fElementsToProcess[i];
+ ICompilationUnit cu = getCompilationUnitFor(e);
+ if (cu == null) {
+ throw new JavaModelException(new JavaModelStatus(JavaModelStatus.READ_ONLY, e));
+ } else {
+ IRegion region = (IRegion) fChildrenToRemove.get(cu);
+ if (region == null) {
+ region = new Region();
+ fChildrenToRemove.put(cu, region);
+ uniqueCUs += 1;
+ }
+ region.add(e);
+ }
+ }
+ fElementsToProcess = new IJavaElement[uniqueCUs];
+ Iterator iter = fChildrenToRemove.keySet().iterator();
+ int i = 0;
+ while (iter.hasNext()) {
+ fElementsToProcess[i++] = (IJavaElement) iter.next();
+ }
+ }
+ /**
+ * Deletes this element from its compilation unit.
+ * @see MultiOperation
+ */
+ protected void processElement(IJavaElement element) throws JavaModelException {
+ ICompilationUnit cu = (ICompilationUnit) element;
+
+ // keep track of the import statements - if all are removed, delete
+ // the import container (and report it in the delta)
+// int numberOfImports = cu.getImports().length;
+
+ IBuffer buffer = cu.getBuffer();
+ if (buffer == null) return;
+ JavaElementDelta delta = new JavaElementDelta(cu);
+ IJavaElement[] cuElements = ((IRegion) fChildrenToRemove.get(cu)).getElements();
+ for (int i = 0, length = cuElements.length; i < length; i++) {
+ IJavaElement e = cuElements[i];
+ if (e.exists()) {
+ char[] contents = buffer.getCharacters();
+ if (contents == null) continue;
+ IDOMCompilationUnit cuDOM = fFactory.createCompilationUnit(contents, cu.getElementName());
+ DOMNode node = (DOMNode)((JavaElement) e).findNode(cuDOM);
+ if (node == null) Assert.isTrue(false, "Failed to locate " + e.getElementName() + " in " + cuDOM.getName()); //$NON-NLS-1$//$NON-NLS-2$
+
+ int startPosition = node.getStartPosition();
+ buffer.replace(startPosition, node.getEndPosition() - startPosition + 1, CharOperation.NO_CHAR);
+ delta.removed(e);
+// if (e.getElementType() == IJavaElement.IMPORT_DECLARATION) {
+// numberOfImports--;
+// if (numberOfImports == 0) {
+// delta.removed(cu.getImportContainer());
+// }
+// }
+ }
+ }
+ if (delta.getAffectedChildren().length > 0) {
+ cu.save(getSubProgressMonitor(1), fForce);
+ if (!cu.isWorkingCopy()) { // if unit is working copy, then save will have already fired the delta
+ addDelta(delta);
+ this.setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
+ }
+ }
+ }
+ /**
+ * @see MultiOperation
+ * This method first group the elements by ICompilationUnit
,
+ * and then processes the ICompilationUnit
.
+ */
+ protected void processElements() throws JavaModelException {
+ groupElements();
+ super.processElements();
+ }
+ /**
+ * @see MultiOperation
+ */
+ protected void verify(IJavaElement element) throws JavaModelException {
+ IJavaElement[] children = ((IRegion) fChildrenToRemove.get(element)).getElements();
+ for (int i = 0; i < children.length; i++) {
+ IJavaElement child = children[i];
+ if (child.getCorrespondingResource() != null)
+ error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, child);
+ if (child.isReadOnly())
+ error(IJavaModelStatusConstants.READ_ONLY, child);
+ }
+ }
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/DeleteResourceElementsOperation.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/DeleteResourceElementsOperation.java
new file mode 100644
index 0000000..e8c5128
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/DeleteResourceElementsOperation.java
@@ -0,0 +1,140 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core;
+
+import net.sourceforge.phpdt.core.IJavaElement;
+import net.sourceforge.phpdt.core.IOpenable;
+import net.sourceforge.phpdt.core.IPackageFragment;
+import net.sourceforge.phpdt.core.JavaModelException;
+
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IFolder;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+
+/**
+ * This operation deletes a collection of resources and all of their children.
+ * It does not delete resources which do not belong to the Java Model
+ * (eg GIF files).
+ */
+public class DeleteResourceElementsOperation extends MultiOperation {
+/**
+ * When executed, this operation will delete the given elements. The elements
+ * to delete cannot be null
or empty, and must have a corresponding
+ * resource.
+ */
+protected DeleteResourceElementsOperation(IJavaElement[] elementsToProcess, boolean force) {
+ super(elementsToProcess, force);
+}
+/**
+ * Deletes the direct children of frag
corresponding to its kind
+ * (K_SOURCE or K_BINARY), and deletes the corresponding folder if it is then
+ * empty.
+ */
+private void deletePackageFragment(IPackageFragment frag)
+ throws JavaModelException {
+ IResource res = frag.getResource();
+ if (res != null && res.getType() == IResource.FOLDER) {
+ // collect the children to remove
+ IJavaElement[] childrenOfInterest = frag.getChildren();
+ if (childrenOfInterest.length > 0) {
+ IResource[] resources = new IResource[childrenOfInterest.length];
+ // remove the children
+ for (int i = 0; i < childrenOfInterest.length; i++) {
+ resources[i] = childrenOfInterest[i].getCorrespondingResource();
+ }
+ deleteResources(resources, fForce);
+ }
+
+ // Discard non-java resources
+// Object[] nonJavaResources = frag.getNonJavaResources();
+// int actualResourceCount = 0;
+// for (int i = 0, max = nonJavaResources.length; i < max; i++){
+// if (nonJavaResources[i] instanceof IResource) actualResourceCount++;
+// }
+// IResource[] actualNonJavaResources = new IResource[actualResourceCount];
+// for (int i = 0, max = nonJavaResources.length, index = 0; i < max; i++){
+// if (nonJavaResources[i] instanceof IResource) actualNonJavaResources[index++] = (IResource)nonJavaResources[i];
+// }
+// deleteResources(actualNonJavaResources, fForce);
+
+ // delete remaining files in this package (.class file in the case where Proj=src=bin)
+ IResource[] remainingFiles;
+ try {
+ remainingFiles = ((IFolder) res).members();
+ } catch (CoreException ce) {
+ throw new JavaModelException(ce);
+ }
+ boolean isEmpty = true;
+ for (int i = 0, length = remainingFiles.length; i < length; i++) {
+ IResource file = remainingFiles[i];
+ if (file instanceof IFile) {
+ this.deleteResource(file, IResource.FORCE | IResource.KEEP_HISTORY);
+ } else {
+ isEmpty = false;
+ }
+ }
+ if (isEmpty) {
+ // delete recursively empty folders
+ IResource fragResource = frag.getResource();
+ if (fragResource != null) {
+ deleteEmptyPackageFragment(frag, false, fragResource.getParent());
+ }
+ }
+ }
+}
+/**
+ * @see MultiOperation
+ */
+protected String getMainTaskName() {
+ return Util.bind("operation.deleteResourceProgress"); //$NON-NLS-1$
+}
+/**
+ * @see MultiOperation. This method delegate to deleteResource
or
+ * deletePackageFragment
depending on the type of element
.
+ */
+protected void processElement(IJavaElement element) throws JavaModelException {
+ switch (element.getElementType()) {
+ case IJavaElement.CLASS_FILE :
+ case IJavaElement.COMPILATION_UNIT :
+ deleteResource(element.getResource(), fForce ? IResource.FORCE | IResource.KEEP_HISTORY : IResource.KEEP_HISTORY);
+ break;
+ case IJavaElement.PACKAGE_FRAGMENT :
+ deletePackageFragment((IPackageFragment) element);
+ break;
+ default :
+ throw new JavaModelException(new JavaModelStatus(JavaModelStatus.INVALID_ELEMENT_TYPES, element));
+ }
+ // ensure the element is closed
+ if (element instanceof IOpenable) {
+ ((IOpenable)element).close();
+ }
+}
+/**
+ * @see MultiOperation
+ */
+protected void verify(IJavaElement element) throws JavaModelException {
+ if (element == null || !element.exists())
+ error(JavaModelStatus.ELEMENT_DOES_NOT_EXIST, element);
+
+ int type = element.getElementType();
+ if (type <= IJavaElement.PACKAGE_FRAGMENT_ROOT || type > IJavaElement.COMPILATION_UNIT)
+ error(JavaModelStatus.INVALID_ELEMENT_TYPES, element);
+// else if (type == IJavaElement.PACKAGE_FRAGMENT && element instanceof JarPackageFragment)
+// error(JavaModelStatus.INVALID_ELEMENT_TYPES, element);
+ IResource resource = element.getResource();
+ if (resource instanceof IFolder) {
+ if (resource.isLinked()) {
+ error(JavaModelStatus.INVALID_RESOURCE, element);
+ }
+ }
+}
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/DeltaProcessor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/DeltaProcessor.java
index ac3dd0f..45ffede 100644
--- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/DeltaProcessor.java
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/DeltaProcessor.java
@@ -17,11 +17,14 @@ import java.util.HashSet;
import java.util.Map;
import net.sourceforge.phpdt.core.ElementChangedEvent;
+import net.sourceforge.phpdt.core.IClasspathEntry;
import net.sourceforge.phpdt.core.IJavaElement;
+import net.sourceforge.phpdt.core.IJavaModel;
import net.sourceforge.phpdt.core.IJavaProject;
-import net.sourceforge.phpdt.core.JavaCore;
import net.sourceforge.phpdt.core.JavaModelException;
import net.sourceforge.phpdt.internal.ui.util.PHPFileUtil;
+import net.sourceforge.phpeclipse.PHPCore;
+import net.sourceforge.phpeclipse.PHPeclipsePlugin;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
@@ -31,8 +34,10 @@ import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IResourceDeltaVisitor;
import org.eclipse.core.resources.IWorkspace;
+import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
+import org.eclipse.core.runtime.QualifiedName;
/**
@@ -224,7 +229,7 @@ public class DeltaProcessor implements IResourceChangeListener {
* to update.
*/
void addToProjectsToUpdateWithDependents(IProject project) {
- this.projectsToUpdate.add(JavaCore.create(project));
+ this.projectsToUpdate.add(PHPCore.create(project));
// this.addDependentProjects(project.getFullPath(), this.projectsToUpdate);
}
@@ -1061,75 +1066,75 @@ public class DeltaProcessor implements IResourceChangeListener {
return file.lastModified() + file.length();
}
-// public void initializeRoots() {
-// // remember roots infos as old roots infos
-// this.oldRoots = this.roots == null ? new HashMap() : this.roots;
-// this.oldOtherRoots = this.otherRoots == null ? new HashMap() : this.otherRoots;
-//
-// // recompute root infos only if necessary
-// if (!rootsAreStale) return;
-//
-// this.roots = new HashMap();
-// this.otherRoots = new HashMap();
-// this.sourceAttachments = new HashMap();
-//
-// IJavaModel model = this.manager.getJavaModel();
-// IJavaProject[] projects;
-// try {
-// projects = model.getJavaProjects();
-// } catch (JavaModelException e) {
-// // nothing can be done
-// return;
-// }
-// for (int i = 0, length = projects.length; i < length; i++) {
-// IJavaProject project = projects[i];
-// IClasspathEntry[] classpath;
-// try {
-// classpath = project.getResolvedClasspath(true);
-// } catch (JavaModelException e) {
-// // continue with next project
-// continue;
-// }
-// for (int j= 0, classpathLength = classpath.length; j < classpathLength; j++) {
-// IClasspathEntry entry = classpath[j];
-// if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) continue;
-//
- // root path
-// IPath path = entry.getPath();
-// if (this.roots.get(path) == null) {
-// this.roots.put(path, new RootInfo(project, path, ((ClasspathEntry)entry).fullExclusionPatternChars()));
-// } else {
-// ArrayList rootList = (ArrayList)this.otherRoots.get(path);
-// if (rootList == null) {
-// rootList = new ArrayList();
-// this.otherRoots.put(path, rootList);
-// }
-// rootList.add(new RootInfo(project, path, ((ClasspathEntry)entry).fullExclusionPatternChars()));
-// }
-//
-// // source attachment path
-// if (entry.getEntryKind() != IClasspathEntry.CPE_LIBRARY) continue;
-// QualifiedName qName = new QualifiedName(JavaCore.PLUGIN_ID, "sourceattachment: " + path.toOSString()); //$NON-NLS-1$;
-// String propertyString = null;
-// try {
-// propertyString = ResourcesPlugin.getWorkspace().getRoot().getPersistentProperty(qName);
-// } catch (CoreException e) {
-// continue;
-// }
-// IPath sourceAttachmentPath;
+ public void initializeRoots() {
+ // remember roots infos as old roots infos
+ this.oldRoots = this.roots == null ? new HashMap() : this.roots;
+ this.oldOtherRoots = this.otherRoots == null ? new HashMap() : this.otherRoots;
+
+ // recompute root infos only if necessary
+ if (!rootsAreStale) return;
+
+ this.roots = new HashMap();
+ this.otherRoots = new HashMap();
+ this.sourceAttachments = new HashMap();
+
+ IJavaModel model = this.manager.getJavaModel();
+ IJavaProject[] projects;
+ try {
+ projects = model.getJavaProjects();
+ } catch (JavaModelException e) {
+ // nothing can be done
+ return;
+ }
+ for (int i = 0, length = projects.length; i < length; i++) {
+ IJavaProject project = projects[i];
+ IClasspathEntry[] classpath;
+ try {
+ classpath = project.getResolvedClasspath(true);
+ } catch (JavaModelException e) {
+ // continue with next project
+ continue;
+ }
+ for (int j= 0, classpathLength = classpath.length; j < classpathLength; j++) {
+ IClasspathEntry entry = classpath[j];
+ if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) continue;
+
+// root path
+ IPath path = entry.getPath();
+ if (this.roots.get(path) == null) {
+ this.roots.put(path, new RootInfo(project, path, ((ClasspathEntry)entry).fullExclusionPatternChars()));
+ } else {
+ ArrayList rootList = (ArrayList)this.otherRoots.get(path);
+ if (rootList == null) {
+ rootList = new ArrayList();
+ this.otherRoots.put(path, rootList);
+ }
+ rootList.add(new RootInfo(project, path, ((ClasspathEntry)entry).fullExclusionPatternChars()));
+ }
+
+ // source attachment path
+ if (entry.getEntryKind() != IClasspathEntry.CPE_LIBRARY) continue;
+ QualifiedName qName = new QualifiedName(PHPCore.PLUGIN_ID, "sourceattachment: " + path.toOSString()); //$NON-NLS-1$;
+ String propertyString = null;
+ try {
+ propertyString = ResourcesPlugin.getWorkspace().getRoot().getPersistentProperty(qName);
+ } catch (CoreException e) {
+ continue;
+ }
+ IPath sourceAttachmentPath;
// if (propertyString != null) {
// int index= propertyString.lastIndexOf(JarPackageFragmentRoot.ATTACHMENT_PROPERTY_DELIMITER);
// sourceAttachmentPath = (index < 0) ? new Path(propertyString) : new Path(propertyString.substring(0, index));
// } else {
-// sourceAttachmentPath = entry.getSourceAttachmentPath();
-// }
-// if (sourceAttachmentPath != null) {
-// this.sourceAttachments.put(sourceAttachmentPath, path);
+ sourceAttachmentPath = entry.getSourceAttachmentPath();
// }
-// }
-// }
-// this.rootsAreStale = false;
-// }
+ if (sourceAttachmentPath != null) {
+ this.sourceAttachments.put(sourceAttachmentPath, path);
+ }
+ }
+ }
+ this.rootsAreStale = false;
+ }
/*
* Returns whether a given delta contains some information relevant to the JavaModel,
@@ -1664,7 +1669,7 @@ public class DeltaProcessor implements IResourceChangeListener {
case IResourceChangeEvent.PRE_DELETE :
try {
if(resource.getType() == IResource.PROJECT
- && ((IProject) resource).hasNature(JavaCore.NATURE_ID)) {
+ && ((IProject) resource).hasNature(PHPeclipsePlugin.PHP_NATURE_ID)) {
// TODO khartlage temp-del
// this.deleting((IProject)resource);
}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/DestroyWorkingCopyOperation.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/DestroyWorkingCopyOperation.java
new file mode 100644
index 0000000..bf5e827
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/DestroyWorkingCopyOperation.java
@@ -0,0 +1,76 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core;
+
+import java.util.Map;
+
+import net.sourceforge.phpdt.core.IJavaElement;
+import net.sourceforge.phpdt.core.JavaModelException;
+
+
+/**
+ * Destroys a working copy (remove it from its cache if it is shared)
+ * and signal its removal through a delta.
+ */
+public class DestroyWorkingCopyOperation extends JavaModelOperation {
+
+ public DestroyWorkingCopyOperation(IJavaElement workingCopy) {
+ super(new IJavaElement[] {workingCopy});
+ }
+ /**
+ * @exception JavaModelException if setting the source
+ * of the original compilation unit fails
+ */
+ protected void executeOperation() throws JavaModelException {
+ WorkingCopy workingCopy = getWorkingCopy();
+ workingCopy.close();
+
+ // if original element is not on classpath flush it from the cache
+ IJavaElement originalElement = workingCopy.getOriginalElement();
+ if (!workingCopy.getParent().exists()) {
+ ((CompilationUnit)originalElement).close();
+ }
+
+ // remove working copy from the cache if it is shared
+ JavaModelManager manager = JavaModelManager.getJavaModelManager();
+
+ // In order to be shared, working copies have to denote the same compilation unit
+ // AND use the same buffer factory.
+ // Assuming there is a little set of buffer factories, then use a 2 level Map cache.
+ Map sharedWorkingCopies = manager.sharedWorkingCopies;
+
+ Map perFactoryWorkingCopies = (Map) sharedWorkingCopies.get(workingCopy.bufferFactory);
+ if (perFactoryWorkingCopies != null){
+ if (perFactoryWorkingCopies.remove(originalElement) != null
+ && CompilationUnit.SHARED_WC_VERBOSE) {
+ System.out.println("Destroying shared working copy " + workingCopy.toStringWithAncestors());//$NON-NLS-1$
+ }
+ }
+
+ // report removed java delta
+ JavaElementDelta delta = new JavaElementDelta(this.getJavaModel());
+ delta.removed(workingCopy);
+ addDelta(delta);
+ removeReconcileDelta(workingCopy);
+ }
+ /**
+ * Returns the working copy this operation is working on.
+ */
+ protected WorkingCopy getWorkingCopy() {
+ return (WorkingCopy)getElementToProcess();
+ }
+ /**
+ * @see JavaModelOperation#isReadOnly
+ */
+ public boolean isReadOnly() {
+ return true;
+ }
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/ElementCache.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/ElementCache.java
new file mode 100644
index 0000000..2f990d7
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/ElementCache.java
@@ -0,0 +1,66 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core;
+
+import net.sourceforge.phpdt.core.IOpenable;
+import net.sourceforge.phpdt.core.JavaModelException;
+import net.sourceforge.phpdt.internal.core.util.LRUCache;
+
+/**
+ * An LRU cache of JavaElements
.
+ */
+public class ElementCache extends OverflowingLRUCache {
+/**
+ * Constructs a new element cache of the given size.
+ */
+public ElementCache(int size) {
+ super(size);
+}
+/**
+ * Constructs a new element cache of the given size.
+ */
+public ElementCache(int size, int overflow) {
+ super(size, overflow);
+}
+/**
+ * Returns true if the element is successfully closed and
+ * removed from the cache, otherwise false.
+ *
+ *
NOTE: this triggers an external removal of this element
+ * by closing the element.
+ */
+protected boolean close(LRUCacheEntry entry) {
+ IOpenable element = (IOpenable) entry._fKey;
+ try {
+ if (element.hasUnsavedChanges()) {
+ return false;
+ } else {
+ // We must close an entire JarPackageFragmentRoot at once.
+// if (element instanceof JarPackageFragment) {
+// JarPackageFragment packageFragment= (JarPackageFragment) element;
+// JarPackageFragmentRoot root = (JarPackageFragmentRoot) packageFragment.getParent();
+// root.close();
+// } else {
+ element.close();
+// }
+ return true;
+ }
+ } catch (JavaModelException npe) {
+ return false;
+ }
+}
+ /**
+ * Returns a new instance of the reciever.
+ */
+ protected LRUCache newInstance(int size, int overflow) {
+ return new ElementCache(size, overflow);
+ }
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/IJavaElementRequestor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/IJavaElementRequestor.java
new file mode 100644
index 0000000..79f5725
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/IJavaElementRequestor.java
@@ -0,0 +1,37 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core;
+
+import net.sourceforge.phpdt.core.IField;
+import net.sourceforge.phpdt.core.IMethod;
+import net.sourceforge.phpdt.core.IPackageFragment;
+import net.sourceforge.phpdt.core.IType;
+
+/**
+ * This interface is used by IRequestorNameLookup. As results
+ * are found by IRequestorNameLookup, they are reported to this
+ * interface. An IJavaElementRequestor is able to cancel
+ * at any time (that is, stop receiving results), by responding
+ *
+ * Note: This operation can be used for reorganizing elements within the same container.
+ *
+ * @see CopyElementsOperation
+ */
+public class MoveElementsOperation extends CopyElementsOperation {
+/**
+ * When executed, this operation will move the given elements to the given containers.
+ */
+public MoveElementsOperation(IJavaElement[] elementsToMove, IJavaElement[] destContainers, boolean force) {
+ super(elementsToMove, destContainers, force);
+}
+/**
+ * Returns the This operation can be used for reorganizing resources within the same container.
+ *
+ * @see CopyResourceElementsOperation
+ */
+public class MoveResourceElementsOperation extends CopyResourceElementsOperation {
+/**
+ * When executed, this operation will move the given elements to the given containers.
+ */
+public MoveResourceElementsOperation(IJavaElement[] elementsToMove, IJavaElement[] destContainers, boolean force) {
+ super(elementsToMove, destContainers, force);
+}
+/**
+ * @see MultiOperation
+ */
+protected String getMainTaskName() {
+ return Util.bind("operation.moveResourceProgress"); //$NON-NLS-1$
+}
+/**
+ * @see CopyResourceElementsOperation#isMove()
+ */
+protected boolean isMove() {
+ return true;
+}
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/MultiOperation.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/MultiOperation.java
new file mode 100644
index 0000000..5fe4c7c
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/MultiOperation.java
@@ -0,0 +1,310 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import net.sourceforge.phpdt.core.ICompilationUnit;
+import net.sourceforge.phpdt.core.IJavaElement;
+import net.sourceforge.phpdt.core.IJavaModelStatus;
+import net.sourceforge.phpdt.core.IJavaModelStatusConstants;
+import net.sourceforge.phpdt.core.IPackageFragment;
+import net.sourceforge.phpdt.core.JavaModelException;
+
+import org.eclipse.core.runtime.IStatus;
+
+
+/**
+ * This class is used to perform operations on multiple
+ * If several errors occured, they are collected in a multi-status
+ * Note that some renamings may not be used. If both a parent
+ * and a child have been selected for copy/move, only the parent
+ * is changed. Therefore, if a new name is specified for the child,
+ * the child's name will not be changed.
+ */
+ public void setRenamings(String[] renamings) {
+ fRenamingsList = renamings;
+ initializeRenamings();
+ }
+ /**
+ * This method is called for each Name lookup only returns a handle when the named element actually
+ * exists in the model; otherwise There are two logical sets of methods within this interface. Methods
+ * which start with The
+ * The name must be fully qualified (eg "java.lang.Object", "java.util.Hashtable$Entry")
+ */
+ public ICompilationUnit findCompilationUnit(String qualifiedTypeName) {
+ String pkgName= IPackageFragment.DEFAULT_PACKAGE_NAME;
+ String cuName= qualifiedTypeName;
+
+ int index= qualifiedTypeName.lastIndexOf('.');
+ if (index != -1) {
+ pkgName= qualifiedTypeName.substring(0, index);
+ cuName= qualifiedTypeName.substring(index + 1);
+ }
+ index= cuName.indexOf('$');
+ if (index != -1) {
+ cuName= cuName.substring(0, index);
+ }
+ cuName += ".java"; //$NON-NLS-1$
+ IPackageFragment[] frags= (IPackageFragment[]) fPackageFragments.get(pkgName);
+ if (frags != null) {
+ for (int i= 0; i < frags.length; i++) {
+ IPackageFragment frag= frags[i];
+// if (!(frag instanceof JarPackageFragment)) {
+// ICompilationUnit cu= frag.getCompilationUnit(cuName);
+// if (cu != null && cu.exists()) {
+// return cu;
+// }
+// }
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Returns the package fragment whose path matches the given
+ * (absolute) path, or The Package fragments which are in a jar only recognize .class files (
* @see JarPackageFragment).
*/
-//protected boolean computeChildren(OpenableElementInfo info, IResource resource) throws JavaModelException {
-// ArrayList vChildren = new ArrayList();
+protected boolean computeChildren(OpenableElementInfo info, IResource resource) throws JavaModelException {
+ ArrayList vChildren = new ArrayList();
// int kind = getKind();
-// String extType;
+ String extType;
// if (kind == IPackageFragmentRoot.K_SOURCE) {
-// extType = "java"; //$NON-NLS-1$
+ extType = "php"; //$NON-NLS-1$
// } else {
// extType = "class"; //$NON-NLS-1$
// }
-// try {
-// char[][] exclusionPatterns = ((PackageFragmentRoot)getPackageFragmentRoot()).fullExclusionPatternChars();
-// IResource[] members = ((IContainer) resource).members();
-// for (int i = 0, max = members.length; i < max; i++) {
-// IResource child = members[i];
-// if (child.getType() != IResource.FOLDER
-// && !Util.isExcluded(child, exclusionPatterns)) {
-// String extension = child.getProjectRelativePath().getFileExtension();
-// if (extension != null) {
-// if (extension.equalsIgnoreCase(extType)) {
-// IJavaElement childElement;
+ try {
+ char[][] exclusionPatterns = ((PackageFragmentRoot)getPackageFragmentRoot()).fullExclusionPatternChars();
+ IResource[] members = ((IContainer) resource).members();
+ for (int i = 0, max = members.length; i < max; i++) {
+ IResource child = members[i];
+ if (child.getType() != IResource.FOLDER
+ && !Util.isExcluded(child, exclusionPatterns)) {
+ String extension = child.getProjectRelativePath().getFileExtension();
+ if (extension != null) {
+ if (extension.equalsIgnoreCase(extType)) {
+ IJavaElement childElement;
// if (kind == IPackageFragmentRoot.K_SOURCE && Util.isValidCompilationUnitName(child.getName())) {
// childElement = getCompilationUnit(child.getName());
// vChildren.add(childElement);
@@ -74,18 +79,18 @@ protected PackageFragment(IPackageFragmentRoot root, String name) {
// childElement = getClassFile(child.getName());
// vChildren.add(childElement);
// }
-// }
-// }
-// }
-// }
-// } catch (CoreException e) {
-// throw new JavaModelException(e);
-// }
-// IJavaElement[] children = new IJavaElement[vChildren.size()];
-// vChildren.toArray(children);
-// info.setChildren(children);
-// return true;
-//}
+ }
+ }
+ }
+ }
+ } catch (CoreException e) {
+ throw new JavaModelException(e);
+ }
+ IJavaElement[] children = new IJavaElement[vChildren.size()];
+ vChildren.toArray(children);
+ info.setChildren(children);
+ return true;
+}
/**
* Returns true if this fragment contains at least one java resource.
* Returns false otherwise.
@@ -124,9 +129,9 @@ public ICompilationUnit createCompilationUnit(String name, String contents, bool
/**
* @see JavaElement
*/
-//protected OpenableElementInfo createElementInfo() {
-// return new PackageFragmentInfo();
-//}
+protected OpenableElementInfo createElementInfo() {
+ return new PackageFragmentInfo();
+}
/**
* @see ISourceManipulation
*/
@@ -137,10 +142,10 @@ public ICompilationUnit createCompilationUnit(String name, String contents, bool
/**
* @see Openable
*/
-//protected boolean generateInfos(OpenableElementInfo info, IProgressMonitor pm, Map newElements, IResource underlyingResource) throws JavaModelException {
-//
-// return computeChildren(info, underlyingResource);
-//}
+protected boolean generateInfos(OpenableElementInfo info, IProgressMonitor pm, Map newElements, IResource underlyingResource) throws JavaModelException {
+
+ return computeChildren(info, underlyingResource);
+}
///**
// * @see IPackageFragment#getClassFile(String)
// */
@@ -173,16 +178,16 @@ public ICompilationUnit getCompilationUnit(String name) {
/**
* @see IPackageFragment#getCompilationUnits()
*/
-//public ICompilationUnit[] getCompilationUnits() throws JavaModelException {
-// if (getKind() == IPackageFragmentRoot.K_BINARY) {
-// return fgEmptyCompilationUnitList;
-// }
-//
-// ArrayList list = getChildrenOfType(COMPILATION_UNIT);
-// ICompilationUnit[] array= new ICompilationUnit[list.size()];
-// list.toArray(array);
-// return array;
-//}
+public ICompilationUnit[] getCompilationUnits() throws JavaModelException {
+ if (getKind() == IPackageFragmentRoot.K_BINARY) {
+ return fgEmptyCompilationUnitList;
+ }
+
+ ArrayList list = getChildrenOfType(COMPILATION_UNIT);
+ ICompilationUnit[] array= new ICompilationUnit[list.size()];
+ list.toArray(array);
+ return array;
+}
/**
* @see JavaElement#getHandleMementoDelimiter()
*/
@@ -192,9 +197,9 @@ protected char getHandleMementoDelimiter() {
/**
* @see IPackageFragment#getKind()
*/
-//public int getKind() throws JavaModelException {
-// return ((IPackageFragmentRoot)getParent()).getKind();
-//}
+public int getKind() throws JavaModelException {
+ return ((IPackageFragmentRoot)getParent()).getKind();
+}
/**
* Returns an array of non-java resources contained in the receiver.
*/
@@ -209,14 +214,14 @@ protected char getHandleMementoDelimiter() {
/**
* @see IJavaElement#getPath()
*/
-//public IPath getPath() {
-// PackageFragmentRoot root = this.getPackageFragmentRoot();
-// if (root.isArchive()) {
-// return root.getPath();
-// } else {
-// return root.getPath().append(this.getElementName().replace('.', '/'));
-// }
-//}
+public IPath getPath() {
+ PackageFragmentRoot root = this.getPackageFragmentRoot();
+ if (root.isArchive()) {
+ return root.getPath();
+ } else {
+ return root.getPath().append(this.getElementName().replace('.', '/'));
+ }
+}
/**
* @see IJavaElement#getResource()
*/
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/PackageFragmentInfo.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/PackageFragmentInfo.java
new file mode 100644
index 0000000..01a8258
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/PackageFragmentInfo.java
@@ -0,0 +1,64 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core;
+
+import net.sourceforge.phpdt.core.JavaModelException;
+
+import org.eclipse.core.resources.IContainer;
+import org.eclipse.core.resources.IResource;
+
+
+/**
+ * Element info for PackageFragments.
+ */
+class PackageFragmentInfo extends OpenableElementInfo {
+
+ /**
+ * A array with all the non-java resources contained by this PackageFragment
+ */
+ protected Object[] fNonJavaResources;
+
+/**
+ * Create and initialize a new instance of the receiver
+ */
+public PackageFragmentInfo() {
+ fNonJavaResources = null;
+}
+/**
+ */
+boolean containsJavaResources() {
+ return fChildren.length != 0;
+}
+/**
+ * Returns an array of non-java resources contained in the receiver.
+ */
+Object[] getNonJavaResources(IResource underlyingResource, PackageFragmentRoot rootHandle) {
+ Object[] nonJavaResources = fNonJavaResources;
+ if (nonJavaResources == null) {
+ try {
+ nonJavaResources =
+ PackageFragmentRootInfo.computeFolderNonJavaResources(
+ (JavaProject)rootHandle.getJavaProject(),
+ (IContainer)underlyingResource,
+ rootHandle.fullExclusionPatternChars());
+ } catch (JavaModelException e) {
+ }
+ fNonJavaResources = nonJavaResources;
+ }
+ return nonJavaResources;
+}
+/**
+ * Set the fNonJavaResources to res value
+ */
+synchronized void setNonJavaResources(Object[] resources) {
+ fNonJavaResources = resources;
+}
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/PackageFragmentRoot.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/PackageFragmentRoot.java
index cf729bb..11aec11 100644
--- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/PackageFragmentRoot.java
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/PackageFragmentRoot.java
@@ -10,19 +10,22 @@
*******************************************************************************/
package net.sourceforge.phpdt.internal.core;
+import java.util.Map;
+
import net.sourceforge.phpdt.core.IJavaElement;
import net.sourceforge.phpdt.core.IJavaProject;
import net.sourceforge.phpdt.core.IPackageFragment;
import net.sourceforge.phpdt.core.IPackageFragmentRoot;
-import net.sourceforge.phpdt.core.JavaCore;
import net.sourceforge.phpdt.core.JavaModelException;
import net.sourceforge.phpdt.core.compiler.CharOperation;
+import net.sourceforge.phpeclipse.PHPCore;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
+import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.QualifiedName;
@@ -292,9 +295,9 @@ protected PackageFragmentRoot(IResource resource, IJavaProject project, String n
/**
* Returns a new element info for this element.
*/
-//protected OpenableElementInfo createElementInfo() {
-// return new PackageFragmentRootInfo();
-//}
+protected OpenableElementInfo createElementInfo() {
+ return new PackageFragmentRootInfo();
+}
/**
* @see IPackageFragmentRoot
@@ -425,8 +428,10 @@ public boolean equals(Object o) {
/*
* Returns the exclusion patterns from the classpath entry associated with this root.
*/
-//char[][] fullExclusionPatternChars() {
+char[][] fullExclusionPatternChars() {
+ return null;
// try {
+
// if (this.isOpen() && this.getKind() != IPackageFragmentRoot.K_SOURCE) return null;
// ClasspathEntry entry = (ClasspathEntry)getRawClasspathEntry();
// if (entry == null) {
@@ -437,16 +442,17 @@ public boolean equals(Object o) {
// } catch (JavaModelException e) {
// return null;
// }
-//}
+}
/**
* @see Openable
*/
-//protected boolean generateInfos(OpenableElementInfo info, IProgressMonitor pm, Map newElements, IResource underlyingResource) throws JavaModelException {
-//
+protected boolean generateInfos(OpenableElementInfo info, IProgressMonitor pm, Map newElements, IResource underlyingResource) throws JavaModelException {
+
// ((PackageFragmentRootInfo) info).setRootKind(determineKind(underlyingResource));
// return computeChildren(info);
-//}
+ return false;
+}
/**
* @see JavaElement#getHandleMemento()
@@ -479,9 +485,9 @@ public String getHandleMemento(){
/**
* @see IPackageFragmentRoot
*/
-//public int getKind() throws JavaModelException {
-// return ((PackageFragmentRootInfo)getElementInfo()).getRootKind();
-//}
+public int getKind() throws JavaModelException {
+ return ((PackageFragmentRootInfo)getElementInfo()).getRootKind();
+}
/**
* Returns an array of non-java resources contained in the receiver.
@@ -617,7 +623,7 @@ public IResource getResource() {
* of this root.
*/
protected QualifiedName getSourceAttachmentPropertyName() throws JavaModelException {
- return new QualifiedName(JavaCore.PLUGIN_ID, "sourceattachment: " + this.getPath().toOSString()); //$NON-NLS-1$
+ return new QualifiedName(PHPCore.PLUGIN_ID, "sourceattachment: " + this.getPath().toOSString()); //$NON-NLS-1$
}
public void setSourceAttachmentProperty(String property) {
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/PackageFragmentRootInfo.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/PackageFragmentRootInfo.java
new file mode 100644
index 0000000..061a5f3
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/PackageFragmentRootInfo.java
@@ -0,0 +1,176 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core;
+
+import net.sourceforge.phpdt.core.IClasspathEntry;
+import net.sourceforge.phpdt.core.IJavaProject;
+import net.sourceforge.phpdt.core.IPackageFragmentRoot;
+import net.sourceforge.phpdt.core.JavaModelException;
+
+import org.eclipse.core.resources.IContainer;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IPath;
+
+/**
+ * The element info for Notes: Notes: This can cause changes in package fragments, in case either the
+ * old or new output location folder are considered as a package fragment.
+ */
+ protected void updateOutputLocation() throws JavaModelException {
+
+ JavaProject project= ((JavaProject) getElementsToProcess()[0]);
+
+ beginTask(Util.bind("classpath.settingOutputLocationProgress", project.getElementName()), 2); //$NON-NLS-1$
+
+ IPath oldLocation= project.getOutputLocation();
+
+ // see if this will cause any package fragments to be added
+ boolean deltaToFire= false;
+ JavaElementDelta delta = newJavaElementDelta();
+// ArrayList added= determineAffectedPackageFragments(oldLocation);
+// Iterator iter = added.iterator();
+// while (iter.hasNext()){
+// IPackageFragment frag= (IPackageFragment)iter.next();
+// ((IPackageFragmentRoot)frag.getParent()).close();
+// if (!Util.isExcluded(frag)) {
+// delta.added(frag);
+// deltaToFire = true;
+// }
+// }
+
+ // see if this will cause any package fragments to be removed
+// ArrayList removed= determineAffectedPackageFragments(this.newOutputLocation);
+// iter = removed.iterator();
+// while (iter.hasNext()){
+// IPackageFragment frag= (IPackageFragment)iter.next();
+// ((IPackageFragmentRoot)frag.getParent()).close();
+// if (!Util.isExcluded(frag)) {
+// delta.removed(frag);
+// deltaToFire = true;
+// }
+// }
+
+ JavaModelManager.PerProjectInfo perProjectInfo = JavaModelManager.getJavaModelManager().getPerProjectInfoCheckExistence(project.getProject());
+ synchronized (perProjectInfo) {
+ perProjectInfo.outputLocation = this.newOutputLocation;
+ }
+
+ if (deltaToFire) {
+ addDelta(delta);
+ }
+ worked(1);
+ }
+
+ /**
+ * Update projects references so that the build order is consistent with the classpath
+ */
+ protected void updateProjectReferencesIfNecessary() throws JavaModelException {
+
+ if (!this.canChangeResource) return;
+ if (this.newRawPath == ReuseClasspath || this.newRawPath == UpdateClasspath) return;
+
+ JavaProject jproject = getProject();
+ String[] oldRequired = jproject.projectPrerequisites(this.oldResolvedPath);
+
+ if (this.newResolvedPath == null) {
+ this.newResolvedPath = jproject.getResolvedClasspath(this.newRawPath, null, true, this.needValidation, null /*no reverse map*/);
+ }
+ String[] newRequired = jproject.projectPrerequisites(this.newResolvedPath);
+
+ try {
+ IProject project = jproject.getProject();
+ IProjectDescription description = project.getDescription();
+
+ IProject[] projectReferences = description.getReferencedProjects();
+
+ HashSet oldReferences = new HashSet(projectReferences.length);
+ for (int i = 0; i < projectReferences.length; i++){
+ String projectName = projectReferences[i].getName();
+ oldReferences.add(projectName);
+ }
+ HashSet newReferences = (HashSet)oldReferences.clone();
+
+ for (int i = 0; i < oldRequired.length; i++){
+ String projectName = oldRequired[i];
+ newReferences.remove(projectName);
+ }
+ for (int i = 0; i < newRequired.length; i++){
+ String projectName = newRequired[i];
+ newReferences.add(projectName);
+ }
+
+ Iterator iter;
+ int newSize = newReferences.size();
+
+ checkIdentity: {
+ if (oldReferences.size() == newSize){
+ iter = newReferences.iterator();
+ while (iter.hasNext()){
+ if (!oldReferences.contains(iter.next())){
+ break checkIdentity;
+ }
+ }
+ return;
+ }
+ }
+ String[] requiredProjectNames = new String[newSize];
+ int index = 0;
+ iter = newReferences.iterator();
+ while (iter.hasNext()){
+ requiredProjectNames[index++] = (String)iter.next();
+ }
+ Util.sort(requiredProjectNames); // ensure that if changed, the order is consistent
+
+ IProject[] requiredProjectArray = new IProject[newSize];
+ IWorkspaceRoot wksRoot = project.getWorkspace().getRoot();
+ for (int i = 0; i < newSize; i++){
+ requiredProjectArray[i] = wksRoot.getProject(requiredProjectNames[i]);
+ }
+
+ description.setReferencedProjects(requiredProjectArray);
+ project.setDescription(description, this.fMonitor);
+
+ } catch(CoreException e){
+ throw new JavaModelException(e);
+ }
+ }
+
+ public IJavaModelStatus verify() {
+
+ IJavaModelStatus status = super.verify();
+ if (!status.isOK()) {
+ return status;
+ }
+
+ if (needValidation) {
+ IJavaProject project = (IJavaProject) getElementToProcess();
+ // retrieve classpath
+ IClasspathEntry[] entries = this.newRawPath;
+ if (entries == ReuseClasspath){
+ try {
+ entries = project.getRawClasspath();
+ } catch (JavaModelException e) {
+ return e.getJavaModelStatus();
+ }
+ }
+ // retrieve output location
+ IPath outputLocation = this.newOutputLocation;
+ if (outputLocation == ReuseOutputLocation){
+ try {
+ outputLocation = project.getOutputLocation();
+ } catch (JavaModelException e) {
+ return e.getJavaModelStatus();
+ }
+ }
+
+ // perform validation
+// return JavaConventions.validateClasspath(
+// project,
+// entries,
+// outputLocation);
+ }
+
+ return JavaModelStatus.VERIFIED_OK;
+ }
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/SourceField.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/SourceField.java
new file mode 100644
index 0000000..14094cd
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/SourceField.java
@@ -0,0 +1,77 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core;
+
+import net.sourceforge.phpdt.core.IField;
+import net.sourceforge.phpdt.core.IType;
+import net.sourceforge.phpdt.core.JavaModelException;
+import net.sourceforge.phpdt.core.Signature;
+import net.sourceforge.phpdt.core.jdom.IDOMNode;
+
+/**
+ * @see IField
+ */
+
+/* package */ class SourceField extends Member implements IField {
+
+/**
+ * Constructs a handle to the field with the given name in the specified type.
+ */
+protected SourceField(IType parent, String name) {
+ super(FIELD, parent, name);
+}
+/**
+ * @see JavaElement#equalsDOMNode
+ */
+protected boolean equalsDOMNode(IDOMNode node) throws JavaModelException {
+ return (node.getNodeType() == IDOMNode.FIELD) && super.equalsDOMNode(node);
+}
+/**
+ * @see IField
+ */
+public Object getConstant() throws JavaModelException {
+ SourceFieldElementInfo info = (SourceFieldElementInfo) getElementInfo();
+ return info.initializationSource;
+}
+/**
+ * @see JavaElement#getHandleMemento()
+ */
+protected char getHandleMementoDelimiter() {
+ return JavaElement.JEM_FIELD;
+}
+/**
+ * @see IField
+ */
+public String getTypeSignature() throws JavaModelException {
+ SourceFieldElementInfo info = (SourceFieldElementInfo) getElementInfo();
+ return info.getTypeSignature();
+}
+/**
+ * @private Debugging purposes
+ */
+protected void toStringInfo(int tab, StringBuffer buffer, Object info) {
+ buffer.append(this.tabString(tab));
+ if (info == null) {
+ buffer.append(getElementName());
+ buffer.append(" (not open)"); //$NON-NLS-1$
+ } else if (info == NO_INFO) {
+ buffer.append(getElementName());
+ } else {
+ try {
+ buffer.append(Signature.toString(this.getTypeSignature()));
+ buffer.append(" "); //$NON-NLS-1$
+ buffer.append(this.getElementName());
+ } catch (JavaModelException e) {
+ buffer.append(" A line separator might corresponds to several characters in the source.
+ *
+ * @see IDocumentElementRequestor#acceptLineSeparatorPositions(int[])
+ */
+public void acceptLineSeparatorPositions(int[] positions) {
+ if (positions != null) {
+ int length = positions.length;
+ if (length > 0) {
+ fLineStartPositions = new int[length + 1];
+ fLineStartPositions[0] = 0;
+ int documentLength = fDocument.length;
+ for (int i = 0; i < length; i++) {
+ int iPlusOne = i + 1;
+ int positionPlusOne = positions[i] + 1;
+ if (positionPlusOne < documentLength) {
+ if (iPlusOne < length) {
+ // more separators
+ fLineStartPositions[iPlusOne] = positionPlusOne;
+ } else {
+ // no more separators
+ if (fDocument[positionPlusOne] == '\n') {
+ fLineStartPositions[iPlusOne] = positionPlusOne + 1;
+ } else {
+ fLineStartPositions[iPlusOne] = positionPlusOne;
+ }
+ }
+ } else {
+ fLineStartPositions[iPlusOne] = positionPlusOne;
+ }
+ }
+ }
+ }
+}
+/**
+ * Does nothing.
+ */
+public void acceptProblem(IProblem problem) {} //TODO: (olivier) unused?
+/**
+ * Adds the given node to the current enclosing scope, building the JDOM
+ * tree. Nodes are only added to an enclosing scope when a compilation unit or type
+ * is being built (since those are the only nodes that have children).
+ *
+ * NOTE: nodes are added to the JDOM via the method #basicAddChild such that
+ * the nodes in the newly created JDOM are not fragmented.
+ */
+protected void addChild(IDOMNode child) {
+ if (fStack.size() > 0) {
+ DOMNode parent = (DOMNode) fStack.peek();
+ if (fBuildingCU || fBuildingType) {
+ parent.basicAddChild(child);
+ }
+ }
+}
+/**
+ * @see IDOMFactory#createCompilationUnit(String, String)
+ */
+public IDOMCompilationUnit createCompilationUnit(char[] contents, char[] name) {
+ return createCompilationUnit(new CompilationUnit(contents, name));
+}
+/**
+ * @see IDOMFactory#createCompilationUnit(String, String)
+ */
+public IDOMCompilationUnit createCompilationUnit(ICompilationUnit compilationUnit) {
+ if (fAbort) {
+ return null;
+ }
+ fNode.normalize(this);
+ return (IDOMCompilationUnit)fNode;
+}
+/**
+ * @see IDocumentElementRequestor#enterClass(int, int[], int, int, int, char[], int, int, char[], int, int, char[][], int[], int[], int)
+ */
+public void enterCompilationUnit() {
+ if (fBuildingCU) {
+ IDOMCompilationUnit cu= new DOMCompilationUnit(fDocument, new int[] {0, fDocument.length - 1});
+ fStack.push(cu);
+ }
+}
+/**
+ * Finishes the configuration of the compilation unit DOM object which
+ * was created by a previous enterCompilationUnit call.
+ *
+ * @see IDocumentElementRequestor#exitCompilationUnit(int)
+ */
+public void exitCompilationUnit(int declarationEnd) {
+ DOMCompilationUnit cu = (DOMCompilationUnit) fStack.pop();
+ cu.setSourceRangeEnd(declarationEnd);
+ fNode = cu;
+}
+/**
+ * Finishes the configuration of the class and interface DOM objects.
+ *
+ * @param bodyEnd - a source position corresponding to the closing bracket of the class
+ * @param declarationEnd - a source position corresponding to the end of the class
+ * declaration. This can include whitespace and comments following the closing bracket.
+ */
+protected void exitType(int bodyEnd, int declarationEnd) {
+ DOMType type = (DOMType)fStack.pop();
+ type.setSourceRangeEnd(declarationEnd);
+ type.setCloseBodyRangeStart(bodyEnd);
+ type.setCloseBodyRangeEnd(bodyEnd);
+ fNode = type;
+}
+/**
+ * @see ILineStartFinder#getLineStart(int)
+ */
+public int getLineStart(int position) {
+ int lineSeparatorCount = fLineStartPositions.length;
+ // reverse traversal intentional.
+ for(int i = lineSeparatorCount - 1; i >= 0; i--) {
+ if (fLineStartPositions[i] <= position)
+ return fLineStartPositions[i];
+ }
+ return 0;
+}
+/**
+ * Initializes the builder to create a document fragment.
+ *
+ * @param sourceCode - the document containing the source code to be analyzed
+ * @param buildingCompilationUnit - true if a the document is being analyzed to
+ * create a compilation unit, otherwise false
+ * @param buildingType - true if the document is being analyzed to create a
+ * type or compilation unit
+ */
+protected void initializeBuild(char[] sourceCode, boolean buildingCompilationUnit, boolean buildingType) {
+ fBuildingCU = buildingCompilationUnit;
+ fBuildingType = buildingType;
+ fStack = new Stack();
+ fDocument = sourceCode;
+ fFieldCount = 0;
+ fAbort = false;
+}
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/CompilationUnit.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/CompilationUnit.java
new file mode 100644
index 0000000..dcb38a5
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/CompilationUnit.java
@@ -0,0 +1,54 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core.jdom;
+
+import net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit;
+
+/**
+ * Implements a very simple version of the ICompilationUnit.
+ *
+ * Please do not use outside of jdom. NOTE: nodes are added to the JDOM via the method #basicAddChild such that
+ * the nodes in the newly created JDOM are not fragmented.
+ */
+protected void addChild(IDOMNode child) {
+ super.addChild(child);
+ if (fStack.isEmpty() && fFields != null) {
+ fFields.add(child);
+ }
+}
+/**
+ * @see IDOMFactory#createCompilationUnit()
+ */
+public IDOMCompilationUnit createCompilationUnit() {
+ return new DOMCompilationUnit();
+}
+/**
+ * @see IDOMFactory#createCompilationUnit(String, String)
+ */
+public IDOMCompilationUnit createCompilationUnit(ICompilationUnit compilationUnit) {
+ initializeBuild(compilationUnit.getContents(), true, true, false);
+ getParser(options).parseCompilationUnit(compilationUnit);
+ return super.createCompilationUnit(compilationUnit);
+}
+/**
+ * @see IDOMFactory#createField(String)
+ */
+//public IDOMField createField(char[] sourceCode) {
+// initializeBuild(sourceCode, false, false, true);
+// getParser(options).parseField(sourceCode);
+// if (fAbort || fNode == null) {
+// return null;
+// }
+//
+// // we only accept field declarations with one field
+// if (fFieldCount > 1) {
+// return null;
+// }
+//
+// fNode.normalize(this);
+// return (IDOMField)fNode;
+//}
+/**
+ *
+ */
+//public IDOMField[] createFields(char[] sourceCode) {
+// initializeBuild(sourceCode, false, false, false);
+// fFields= new ArrayList();
+// getParser(options).parseField(sourceCode);
+// if (fAbort) {
+// return null;
+// }
+// IDOMField[] fields= new IDOMField[fFields.size()];
+// fFields.toArray(fields);
+// for (int i= 0; i < fields.length; i++) {
+// DOMNode node= (DOMNode)fields[i];
+// if (i < (fields.length - 1)) {
+// DOMNode next= (DOMNode)fields[i + 1];
+// node.fNextNode= next;
+// next.fPreviousNode= node;
+// }
+// ((DOMNode)fields[i]).normalize(this);
+// }
+// return fields;
+//}
+/**
+ * @see IDOMFactory#createImport()
+ */
+//public IDOMImport createImport() {
+// return new DOMImport();
+//}
+/**
+ * @see IDOMFactory#createImport(String)
+ */
+//public IDOMImport createImport(char[] sourceCode) {
+// initializeBuild(sourceCode, false, false, true);
+// getParser(options).parseImport(sourceCode);
+// if (fAbort || fNode == null) {
+// return null;
+// }
+// fNode.normalize(this);
+// return (IDOMImport)fNode;
+//}
+/**
+ * Creates an INITIALIZER document fragment from the given source.
+ *
+ * @see IDOMFactory#createInitializer(String)
+ */
+//public IDOMInitializer createInitializer(char[] sourceCode) {
+// initializeBuild(sourceCode, false, false, true);
+// getParser(options).parseInitializer(sourceCode);
+// if (fAbort || fNode == null || !(fNode instanceof IDOMInitializer)) {
+// return null;
+// }
+// fNode.normalize(this);
+// return (IDOMInitializer)fNode;
+//}
+/**
+ * @see IDOMFactory#createMethod(String)
+ */
+//public IDOMMethod createMethod(char[] sourceCode) {
+// initializeBuild(sourceCode, false, false, true);
+// getParser(options).parseMethod(sourceCode);
+// if (fAbort || fNode == null) {
+// return null;
+// }
+// fNode.normalize(this);
+// return (IDOMMethod)fNode;
+//}
+/**
+ * @see IDOMFactory#createPackage()
+ */
+public IDOMPackage createPackage() {
+ return new DOMPackage();
+}
+/**
+ * @see IDOMFactory#createPackage(String)
+ */
+//public IDOMPackage createPackage(char[] sourceCode) {
+// initializeBuild(sourceCode, false, false, true);
+// getParser(options).parsePackage(sourceCode);
+// if (fAbort || fNode == null) {
+// return null;
+// }
+// fNode.normalize(this);
+// return (IDOMPackage)fNode;
+//}
+/**
+ * @see IDOMFactory#createType(String)
+ */
+//public IDOMType createType(char[] sourceCode) {
+// initializeBuild(sourceCode, false, true, false);
+// getParser(options).parseType(sourceCode);
+// if (fAbort) {
+// return null;
+// }
+// if (fNode != null) fNode.normalize(this);
+// return (IDOMType)fNode;
+//}
+/**
+ * Creates a new DOMMethod and inizializes.
+ *
+ * @param declarationStart - a source position corresponding to the first character
+ * of this constructor declaration
+ * @param modifiers - the modifiers for this constructor converted to a flag
+ * @param modifiersStart - a source position corresponding to the first character of the
+ * textual modifiers
+ * @param returnType - the name of the return type
+ * @param returnTypeStart - a source position corresponding to the first character
+ * of the return type
+ * @param returnTypeEnd - a source position corresponding to the last character
+ * of the return type
+ * @param returnTypeDimensionCount - the array dimension count as supplied on the
+ * return type (for instance, 'public int[] foo() {}')
+ * @param name - the name of this constructor
+ * @param nameStart - a source position corresponding to the first character of the name
+ * @param nameEnd - a source position corresponding to the last character of the name
+ * @param parameterTypes - a list of parameter type names
+ * @param parameterTypeStarts - a list of source positions corresponding to the
+ * first character of each parameter type name
+ * @param parameterTypeEnds - a list of source positions corresponding to the
+ * last character of each parameter type name
+ * @param parameterNames - a list of the names of the parameters
+ * @param parametersEnd - a source position corresponding to the last character of the
+ * parameter list
+ * @extendedReturnTypeDimensionCount - the array dimension count as supplied on the
+ * end of the parameter list (for instance, 'public int foo()[] {}')
+ * @extendedReturnTypeDimensionEnd - a source position corresponding to the last character
+ * of the extended return type dimension
+ * @param exceptionTypes - a list of the exception types
+ * @param exceptionTypeStarts - a list of source positions corresponding to the first
+ * character of the respective exception types
+ * @param exceptionTypeEnds - a list of source positions corresponding to the last
+ * character of the respective exception types
+ * @param bodyStart - a source position corresponding to the start of this
+ * constructor's body
+ */
+protected void enterAbstractMethod(int declarationStart, int[] javaDocPositions, int modifiers, int modifiersStart,
+ char[] returnType, int returnTypeStart, int returnTypeEnd, int returnTypeDimensionCount,
+ char[] name, int nameStart, int nameEnd, char[][] parameterTypes, int[] parameterTypeStarts,
+ int[] parameterTypeEnds, char[][] parameterNames, int[] parameterNameStarts,
+ int[] parameterNameEnds, int parametersEnd, int extendedReturnTypeDimensionCount,
+ int extendedReturnTypeDimensionEnd, char[][] exceptionTypes, int[] exceptionTypeStarts,
+ int[] exceptionTypeEnds, int bodyStart, boolean isConstructor) {
+ int[] sourceRange = {declarationStart, -1}; // will be fixed up on exit
+ int[] nameRange = {nameStart, nameEnd};
+ int[] commentRange = {-1, -1};
+ if (javaDocPositions != null) {
+ int length = javaDocPositions.length;
+ commentRange[0] = javaDocPositions[0];
+ commentRange[1] = javaDocPositions[length - 1];
+ }
+ int[] modifiersRange = {-1, -1};
+ if (modifiersStart > -1) {
+ modifiersRange[0] = modifiersStart;
+ if (isConstructor) {
+ modifiersRange[1] = nameStart - 1;
+ } else {
+ modifiersRange[1] = returnTypeStart - 1;
+ }
+ }
+ int[] returnTypeRange = null;
+
+ if (extendedReturnTypeDimensionCount > 0)
+ returnTypeRange = new int[] {returnTypeStart, returnTypeEnd,
+ parametersEnd + 1, extendedReturnTypeDimensionEnd};
+ else
+ returnTypeRange = new int[] {returnTypeStart, returnTypeEnd};
+ int[] parameterRange = {nameEnd + 1, parametersEnd};
+ int[] exceptionRange = {-1, -1};
+ if (exceptionTypes != null && exceptionTypes.length > 0) {
+ int exceptionCount = exceptionTypes.length;
+ exceptionRange[0] = exceptionTypeStarts[0];
+ exceptionRange[1] = exceptionTypeEnds[exceptionCount - 1];
+ }
+ int[] bodyRange = null;
+ if (exceptionRange[1] > -1) {
+ bodyRange = new int[] {exceptionRange[1] + 1, -1}; // will be fixed up on exit
+ } else {
+ bodyRange = new int[] {parametersEnd + 1, -1};
+ }
+ fNode = new DOMMethod(fDocument, sourceRange, CharArrayOps.charToString(name), nameRange, commentRange, modifiers,
+ modifiersRange, isConstructor, CharArrayOps.charToString(returnType), returnTypeRange,
+ CharArrayOps.charcharToString(parameterTypes),
+ CharArrayOps.charcharToString(parameterNames),
+ parameterRange, CharArrayOps.charcharToString(exceptionTypes), exceptionRange, bodyRange);
+ addChild(fNode);
+ fStack.push(fNode);
+}
+/**
+ * @see IDocumentElementRequestor#enterClass(
+ int declarationStart,
+ int[] javaDocPositions,
+ int modifiers,
+ int modifiersStart,
+ int classStart,
+ char[] name,
+ int nameStart,
+ int nameEnd,
+ char[] superclass,
+ int superclassStart,
+ int superclassEnd,
+ char[][] superinterfaces,
+ int[] superinterfaceStarts,
+ int[] superinterfaceEnds,
+ int bodyStart)
+ */
+public void enterClass(int declarationStart, int[] javaDocPositions, int modifiers, int modifiersStart, int keywordStart,
+ char[] name, int nameStart, int nameEnd, char[] superclass, int superclassStart,
+ int superclassEnd, char[][] superinterfaces, int[] superinterfaceStarts,
+ int[] superinterfaceEnds, int bodyStart) {
+
+ enterType(declarationStart, javaDocPositions, modifiers, modifiersStart, keywordStart,
+ name, nameStart, nameEnd, superclass, superclassStart,
+ superclassEnd, superinterfaces, superinterfaceStarts,
+ superinterfaceEnds, bodyStart, true);
+}
+/**
+ * @see IDocumentElementRequestor#enterConstructor(
+ int declarationStart,
+ int[] javaDocPositions,
+ int modifiers,
+ int modifiersStart,
+ char[] name,
+ int nameStart,
+ int nameEnd,
+ char[][] parameterTypes,
+ int [] parameterTypeStarts,
+ int [] parameterTypeEnds,
+ char[][] parameterNames,
+ int [] parameterNameStarts,
+ int [] parameterNameEnds,
+ int parametersEnd,
+ char[][] exceptionTypes,
+ int [] exceptionTypeStarts,
+ int [] exceptionTypeEnds,
+ int bodyStart)
+ */
+public void enterConstructor(int declarationStart, int[] javaDocPositions, int modifiers, int modifiersStart,
+ char[] name, int nameStart, int nameEnd, char[][] parameterTypes,
+ int[] parameterTypeStarts, int[] parameterTypeEnds, char[][] parameterNames,
+ int[] parameterNameStarts, int[] parameterNameEnds, int parametersEnd,
+ char[][] exceptionTypes, int[] exceptionTypeStarts, int[] exceptionTypeEnds,
+ int bodyStart) {
+
+ /* see 1FVIIQZ */
+ String nameString = new String(fDocument, nameStart, nameEnd - nameStart);
+ int openParenPosition = nameString.indexOf('(');
+ if (openParenPosition > -1)
+ nameEnd = nameStart + openParenPosition - 1;
+
+ enterAbstractMethod(declarationStart, javaDocPositions, modifiers, modifiersStart,
+ null, -1, -1, 0,
+ name, nameStart, nameEnd, parameterTypes, parameterTypeStarts,
+ parameterTypeEnds, parameterNames, parameterNameStarts,
+ parameterNameEnds, parametersEnd, 0,
+ -1, exceptionTypes, exceptionTypeStarts,
+ exceptionTypeEnds, bodyStart,true);
+}
+/**
+ * @see IDocumentElementRequestor#enterField(
+ int declarationStart,
+ int[] javaDocPositions,
+ int modifiers,
+ int modifiersStart,
+ char[] type,
+ int typeStart,
+ int typeEnd,
+ int typeDimensionCount,
+ char[] name,
+ int nameStart,
+ int nameEnd,
+ int extendedTypeDimensionCount,
+ int extendedTypeDimensionEnd)
+ */
+public void enterField(int declarationStart, int[] javaDocPositions, int modifiers, int modifiersStart,
+ char[] type, int typeStart, int typeEnd, int typeDimensionCount, char[] name,
+ int nameStart, int nameEnd, int extendedTypeDimensionCount,
+ int extendedTypeDimensionEnd) {
+ int[] sourceRange = {declarationStart,
+ (extendedTypeDimensionEnd > nameEnd) ? extendedTypeDimensionEnd : nameEnd};
+ int[] nameRange = {nameStart, nameEnd};
+ int[] commentRange = {-1, -1};
+ if (javaDocPositions != null) {
+ int length = javaDocPositions.length;
+ commentRange[0] = javaDocPositions[0];
+ commentRange[1] = javaDocPositions[length - 1];
+ }
+ int[] modifiersRange = {-1, -1};
+ if (modifiersStart > -1) {
+ modifiersRange[0] = modifiersStart;
+ modifiersRange[1] = typeStart - 1;
+ }
+ int[] typeRange = {typeStart, typeEnd};
+ boolean hasInitializer = false; // fixed on exitField
+ int[] initializerRange = {-1, -1}; // fixed on exitField
+ boolean isVariableDeclarator = false;
+ if (fNode instanceof DOMField) {
+ DOMField field = (DOMField)fNode;
+ if (field.fTypeRange[0] == typeStart)
+ isVariableDeclarator = true;
+ }
+ fNode = new DOMField(fDocument, sourceRange, CharArrayOps.charToString(name), nameRange, commentRange,
+ modifiers, modifiersRange, typeRange, CharArrayOps.charToString(type), hasInitializer,
+ initializerRange, isVariableDeclarator);
+ addChild(fNode);
+ fStack.push(fNode);
+}
+/**
+ * @see IDocumentElementRequestor#enterInterface(
+ int declarationStart,
+ int[] javaDocPositions,
+ int modifiers,
+ int modifiersStart,
+ int interfaceStart,
+ char[] name,
+ int nameStart,
+ int nameEnd,
+ char[][] superinterfaces,
+ int[] superinterfaceStarts,
+ int[] superinterfaceEnds,
+ int bodyStart)
+ */
+public void enterInterface(int declarationStart, int[] javaDocPositions, int modifiers, int modifiersStart, int keywordStart,
+ char[] name, int nameStart, int nameEnd, char[][] superinterfaces,
+ int[] superinterfaceStarts, int[] superinterfaceEnds, int bodyStart) {
+
+ enterType(declarationStart, javaDocPositions, modifiers, modifiersStart, keywordStart,
+ name, nameStart, nameEnd, null, -1, -1, superinterfaces,
+ superinterfaceStarts, superinterfaceEnds, bodyStart, false);
+}
+/**
+ * @see IDocumentElementRequestor#enterMethod(
+ int declarationStart,
+ int[] javaDocPositions,
+ int modifiers,
+ int modifiersStart,
+ char[] returnType,
+ int returnTypeStart,
+ int returnTypeEnd,
+ int returnTypeDimensionCount,
+ char[] name,
+ int nameStart,
+ int nameEnd,
+ char[][] parameterTypes,
+ int [] parameterTypeStarts,
+ int [] parameterTypeEnds,
+ char[][] parameterNames,
+ int [] parameterNameStarts,
+ int [] parameterNameEnds,
+ int parametersEnd,
+ int extendedReturnTypeDimensionCount,
+ int extendedReturnTypeDimensionEnd,
+ char[][] exceptionTypes,
+ int [] exceptionTypeStarts,
+ int [] exceptionTypeEnds,
+ int bodyStart)
+ */
+public void enterMethod(int declarationStart, int[] javaDocPositions, int modifiers, int modifiersStart,
+ char[] returnType, int returnTypeStart, int returnTypeEnd, int returnTypeDimensionCount,
+ char[] name, int nameStart, int nameEnd, char[][] parameterTypes, int[] parameterTypeStarts,
+ int[] parameterTypeEnds, char[][] parameterNames, int[] parameterNameStarts,
+ int[] parameterNameEnds, int parametersEnd, int extendedReturnTypeDimensionCount,
+ int extendedReturnTypeDimensionEnd, char[][] exceptionTypes, int[] exceptionTypeStarts,
+ int[] exceptionTypeEnds, int bodyStart) {
+ enterAbstractMethod(declarationStart, javaDocPositions, modifiers, modifiersStart,
+ returnType, returnTypeStart, returnTypeEnd, returnTypeDimensionCount,
+ name, nameStart, nameEnd, parameterTypes, parameterTypeStarts,
+ parameterTypeEnds, parameterNames, parameterNameStarts,
+ parameterNameEnds, parametersEnd, extendedReturnTypeDimensionCount,
+ extendedReturnTypeDimensionEnd, exceptionTypes, exceptionTypeStarts,
+ exceptionTypeEnds, bodyStart,false);
+}
+
+protected void enterType(int declarationStart, int[] javaDocPositions,
+ int modifiers, int modifiersStart, int keywordStart, char[] name,
+ int nameStart, int nameEnd, char[] superclass, int superclassStart,
+ int superclassEnd, char[][] superinterfaces, int[] superinterfaceStarts,
+ int[] superinterfaceEnds, int bodyStart, boolean isClass) {
+ if (fBuildingType) {
+ int[] sourceRange = {declarationStart, -1}; // will be fixed in the exit
+ int[] commentRange = {-1, -1};
+ if (javaDocPositions != null) {
+ int length = javaDocPositions.length;
+ commentRange[0] = javaDocPositions[0];
+ commentRange[1] = javaDocPositions[length - 1];
+ }
+ int[] modifiersRange = {-1, -1};
+ if (modifiersStart > -1) {
+ modifiersRange[0] = modifiersStart;
+ modifiersRange[1] = (modifiersStart > -1) ? keywordStart - 1 : -1;
+ }
+ int[] typeKeywordRange = {keywordStart, nameStart - 1};
+ int[] nameRange = new int[] {nameStart, nameEnd};
+ int[] extendsKeywordRange = {-1, -1};
+ int[] superclassRange = {-1, -1};
+ int[] implementsKeywordRange = {-1, -1};
+ int[] interfacesRange = {-1, -1};
+ if (isClass) {
+ if (superclass != null) {
+ extendsKeywordRange[0] = nameEnd + 1;
+ extendsKeywordRange[1] = superclassStart - 1;
+ superclassRange[0] = superclassStart;
+ superclassRange[1] = bodyStart - 1;
+ }
+ if (superinterfaces != null && superinterfaces.length > 0) {
+ superclassRange[1] = superclassEnd;
+ if (superclassEnd > -1) {
+ implementsKeywordRange[0] = superclassEnd + 1;
+ } else {
+ implementsKeywordRange[0] = nameEnd + 1;
+ }
+ implementsKeywordRange[1] = superinterfaceStarts[0] - 1;
+ interfacesRange[0] = superinterfaceStarts[0];
+ interfacesRange[1] = superinterfaceEnds[superinterfaces.length - 1];
+ }
+ } else {
+ if (superinterfaces != null && superinterfaces.length > 0) {
+ extendsKeywordRange[0] = nameEnd + 1;
+ extendsKeywordRange[1] = superinterfaceStarts[0] - 1;
+ interfacesRange[0] = superinterfaceStarts[0];
+ interfacesRange[1] = superinterfaceEnds[superinterfaces.length - 1];
+ }
+ }
+ int[] openBodyRange = {bodyStart, -1}; // fixed by setTypeRanges(DOMNode)
+ int[] closeBodyRange = {-1, -1}; // will be fixed in exit
+ fNode = new DOMType(fDocument, sourceRange, new String(name), nameRange, commentRange,
+ modifiers, modifiersRange, typeKeywordRange, superclassRange, extendsKeywordRange,
+ CharArrayOps.charcharToString(superinterfaces), interfacesRange,
+ implementsKeywordRange, openBodyRange,
+ closeBodyRange, isClass);
+ addChild(fNode);
+ fStack.push(fNode);
+ }
+}
+/**
+ * Finishes the configuration of the constructors and methods.
+ *
+ * @param bodyEnd - a source position corresponding to the closing bracket of the method
+ * @param declarationEnd - a source position corresponding to the end of the method
+ * declaration. This can include whitespace and comments following the closing bracket.
+ */
+protected void exitAbstractMethod(int bodyEnd, int declarationEnd) {
+ DOMMethod method = (DOMMethod) fStack.pop();
+ method.setSourceRangeEnd(declarationEnd);
+ method.setBodyRangeEnd(bodyEnd + 1);
+ fNode = method;
+ if (fBuildingSingleMember) {
+ fFinishedSingleMember= true;
+ }
+}
+/**
+ * Finishes the configuration of the class DOM object which
+ * was created by a previous enterClass call.
+ *
+ * @see IDocumentElementRequestor#exitClass(int, int)
+ */
+public void exitClass(int bodyEnd, int declarationEnd) {
+ exitType(bodyEnd, declarationEnd);
+}
+/**
+ * Finishes the configuration of the method DOM object which
+ * was created by a previous enterConstructor call.
+ *
+ * @see IDocumentElementRequestor#exitConstructor(int, int)
+ */
+public void exitConstructor(int bodyEnd, int declarationEnd) {
+ exitAbstractMethod(bodyEnd, declarationEnd);
+}
+/**
+ * Finishes the configuration of the field DOM object which
+ * was created by a previous enterField call.
+ *
+ * @see IDocumentElementRequestor#exitField(int, int)
+ */
+public void exitField(int bodyEnd, int declarationEnd) {
+ DOMField field = (DOMField)fStack.pop();
+ if (field.getEndPosition() < declarationEnd) {
+ field.setSourceRangeEnd(declarationEnd);
+ int nameEnd = field.fNameRange[1];
+ if (nameEnd < bodyEnd) {
+ /* see 1FVIIV8 - obtain initializer range */
+ String initializer = new String(fDocument, nameEnd + 1, bodyEnd - nameEnd);
+ int index = initializer.indexOf('=');
+ if (index > -1) {
+ field.setHasInitializer(true);
+ field.setInitializerRange(nameEnd + index + 2, bodyEnd);
+ }
+ }
+ }
+ fFieldCount++;
+ fNode = field;
+ if (fBuildingSingleMember) {
+ fFinishedSingleMember= true;
+ }
+}
+/**
+ * Finishes the configuration of the interface DOM object which
+ * was created by a previous enterInterface call.
+ *
+ * @see IDocumentElementRequestor#exitInterface(int, int)
+ */
+public void exitInterface(int bodyEnd, int declarationEnd) {
+ exitType(bodyEnd, declarationEnd);
+}
+/**
+ * Finishes the configuration of the method DOM object which
+ * was created by a previous enterMethod call.
+ *
+ * @see IDocumentElementRequestor#exitMethod(int, int)
+ */
+public void exitMethod(int bodyEnd, int declarationEnd) {
+ exitAbstractMethod(bodyEnd, declarationEnd);
+}
+/**
+ * Creates a new parser.
+ */
+protected DocumentElementParser getParser(Map settings) {
+ return new DocumentElementParser(this, new DefaultProblemFactory());//, new CompilerOptions(settings));
+}
+/**
+ * Initializes the builder to create a document fragment.
+ *
+ * @param sourceCode - the document containing the source code to be analyzed
+ * @param buildingCompilationUnit - true if a the document is being analyzed to
+ * create a compilation unit, otherwise false
+ * @param buildingType - true if the document is being analyzed to create a
+ * type or compilation unit
+ * @param singleMember - true if building a single member
+ */
+protected void initializeBuild(char[] sourceCode, boolean buildingCompilationUnit, boolean buildingType, boolean singleMember) {
+ super.initializeBuild(sourceCode, buildingCompilationUnit, buildingType);
+ fBuildingSingleMember= singleMember;
+ fFinishedSingleMember= false;
+
+}
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMCompilationUnit.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMCompilationUnit.java
new file mode 100644
index 0000000..10c07ef
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMCompilationUnit.java
@@ -0,0 +1,184 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core.jdom;
+
+import net.sourceforge.phpdt.core.Flags;
+import net.sourceforge.phpdt.core.IJavaElement;
+import net.sourceforge.phpdt.core.IPackageFragment;
+import net.sourceforge.phpdt.core.jdom.IDOMCompilationUnit;
+import net.sourceforge.phpdt.core.jdom.IDOMNode;
+import net.sourceforge.phpdt.core.jdom.IDOMType;
+import net.sourceforge.phpdt.internal.compiler.util.Util;
+import net.sourceforge.phpdt.internal.core.util.CharArrayBuffer;
+import net.sourceforge.phpdt.internal.core.util.CharArrayOps;
+
+/**
+ * DOMCompilation unit provides an implementation of IDOMCompilationUnit.
+ *
+ * @see IDOMCompilationUnit
+ * @see DOMNode
+ */
+class DOMCompilationUnit extends DOMNode implements IDOMCompilationUnit {
+
+ /**
+ * The comment and/or whitespace preceding the
+ * first document fragment in this compilation
+ * unit.
+ */
+ protected String fHeader;
+/**
+ * Creates a new empty COMPILATION_UNIT document fragment.
+ */
+DOMCompilationUnit() {
+ fHeader=""; //$NON-NLS-1$
+}
+/**
+ * Creates a new COMPILATION_UNIT on the given range of the document.
+ *
+ * @param document - the document containing this node's original contents
+ * @param sourceRange - a two element array of integers describing the
+ * entire inclusive source range of this node within its document.
+ * A compilation unit's source range is the entire document -
+ * the first integer is zero, and the second integer is the position
+ * of the last character in the document.
+ */
+DOMCompilationUnit(char[] document, int[] sourceRange) {
+ super(document, sourceRange, null, new int[]{-1, -1});
+ fHeader = ""; //$NON-NLS-1$
+}
+/**
+ * @see DOMNode#appendContents(CharArrayBuffer)
+ */
+protected void appendFragmentedContents(CharArrayBuffer buffer) {
+ buffer.append(getHeader());
+ appendContentsOfChildren(buffer);
+}
+/**
+ * @see IDOMNode#canHaveChildren()
+ */
+public boolean canHaveChildren() {
+ return true;
+}
+/**
+ * @see IDOMCompilationUnit#getHeader()
+ */
+public String getHeader() {
+ return fHeader;
+}
+/**
+ * @see IDOMNode#getJavaElement
+ */
+public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException {
+ if (parent.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
+ return ((IPackageFragment)parent).getCompilationUnit(getName());
+ } else {
+ throw new IllegalArgumentException(Util.bind("element.illegalParent")); //$NON-NLS-1$
+ }
+}
+/**
+ * @see IDOMCompilationUnit#getName()
+ */
+public String getName() {
+ IDOMType topLevelType= null;
+ IDOMType firstType= null;
+ IDOMNode child= fFirstChild;
+ while (child != null) {
+ if (child.getNodeType() == IDOMNode.TYPE) {
+ IDOMType type= (IDOMType)child;
+ if (firstType == null) {
+ firstType= type;
+ }
+ if (Flags.isPublic(type.getFlags())) {
+ topLevelType= type;
+ break;
+ }
+ }
+ child= child.getNextNode();
+ }
+ if (topLevelType == null) {
+ topLevelType= firstType;
+ }
+ if (topLevelType != null) {
+ return topLevelType.getName() + ".java"; //$NON-NLS-1$
+ } else {
+ return null;
+ }
+}
+/**
+ * @see IDOMNode#getNodeType()
+ */
+public int getNodeType() {
+ return IDOMNode.COMPILATION_UNIT;
+}
+/**
+ * Sets the header
+ */
+protected void initalizeHeader() {
+ DOMNode child = (DOMNode)getFirstChild();
+ if (child != null) {
+ int childStart = child.getStartPosition();
+ if (childStart > 1) {
+ setHeader(CharArrayOps.substring(fDocument, 0, childStart));
+ }
+ }
+}
+/**
+ * @see IDOMNode#isAllowableChild(IDOMNode)
+ */
+public boolean isAllowableChild(IDOMNode node) {
+ if (node != null) {
+ int type= node.getNodeType();
+ return type == IDOMNode.PACKAGE || type == IDOMNode.IMPORT || type == IDOMNode.TYPE;
+ } else {
+ return false;
+ }
+
+}
+/**
+ * @see DOMNode
+ */
+protected DOMNode newDOMNode() {
+ return new DOMCompilationUnit();
+}
+/**
+ * Normalizes this A field does not have a body.
+ *
+ * @see DOMMember#appendMemberBodyContents(CharArrayBuffer)
+ */
+protected void appendMemberBodyContents(CharArrayBuffer buffer) {}
+/**
+ * @see DOMMember#appendMemberDeclarationContents(CharArrayBuffer)
+ */
+protected void appendMemberDeclarationContents(CharArrayBuffer buffer) {
+
+ if (isVariableDeclarator()) {
+ buffer.append(fDocument, fSourceRange[0], fNameRange[0] - fSourceRange[0]);
+ } else {
+ buffer
+ .append(getTypeContents())
+ .append(fDocument, fTypeRange[1] + 1, fNameRange[0] - fTypeRange[1] - 1);
+ }
+
+ buffer.append(getNameContents());
+ if (hasInitializer()) {
+ if (fInitializerRange[0] < 0) {
+ buffer
+ .append('=')
+ .append(fInitializer)
+ .append(fDocument, fNameRange[1] + 1, fSourceRange[1] - fNameRange[1]);
+ } else {
+ buffer
+ .append(fDocument, fNameRange[1] + 1, fInitializerRange[0] - fNameRange[1] - 1)
+ .append(getInitializer())
+ .append(fDocument, fInitializerRange[1] + 1, fSourceRange[1] - fInitializerRange[1]);
+ }
+ } else {
+ if (fInitializerRange[0] < 0) {
+ buffer.append(fDocument, fNameRange[1] + 1, fSourceRange[1] - fNameRange[1]);
+ } else {
+ buffer.append(fDocument, fInitializerRange[1] + 1, fSourceRange[1] - fInitializerRange[1]);
+ }
+ }
+
+}
+/**
+ * Appends this member's header contents to the given CharArrayBuffer.
+ * Header contents include any preceding comments and modifiers.
+ *
+ * If this field is a secondary variable declarator, there is no header.
+ *
+ * @see DOMMember#appendMemberHeaderFragment(CharArrayBuffer)
+ */
+protected void appendMemberHeaderFragment(CharArrayBuffer buffer) {
+
+ if (isVariableDeclarator()) {
+ return;
+ } else {
+ super.appendMemberHeaderFragment(buffer);
+ }
+
+}
+/**
+ * @see DOMMember#appendSimpleContents(CharArrayBuffer)
+ */
+protected void appendSimpleContents(CharArrayBuffer buffer) {
+ // append eveything before my name
+ buffer.append(fDocument, fSourceRange[0], fNameRange[0] - fSourceRange[0]);
+ // append my name
+ buffer.append(fName);
+ // append everything after my name
+ buffer.append(fDocument, fNameRange[1] + 1, fSourceRange[1] - fNameRange[1]);
+}
+/**
+ * Generates detailed source indexes for this node if possible.
+ *
+ * @exception DOMException if unable to generate detailed source indexes
+ * for this node
+ */
+//protected void becomeDetailed() throws DOMException {
+// if (!isDetailed()) {
+// if (isVariableDeclarator() || hasMultipleVariableDeclarators()) {
+// DOMNode first = getFirstFieldDeclaration();
+// DOMNode last = getLastFieldDeclaration();
+// DOMNode node= first;
+// String source= first.getContents();
+// while (node != last) {
+// node= node.fNextNode;
+// source+=node.getContents();
+// }
+// DOMBuilder builder = new DOMBuilder();
+// IDOMField[] details= builder.createFields(source.toCharArray());
+// if (details.length == 0) {
+// throw new DOMException(Util.bind("dom.cannotDetail")); //$NON-NLS-1$
+// } else {
+// node= this;
+// for (int i= 0; i < details.length; i++) {
+// node.shareContents((DOMNode)details[i]);
+// node= node.fNextNode;
+// }
+// }
+// } else {
+// super.becomeDetailed();
+// }
+//
+// }
+//}
+/**
+ * @see IDOMNode#clone()
+ */
+public Object clone() {
+// if (isVariableDeclarator() || hasMultipleVariableDeclarators()) {
+// return getFactory().createField(new String(getSingleVariableDeclaratorContents()));
+// } else {
+ return super.clone();
+// }
+}
+/**
+ * Expands all variable declarators in this field declaration into
+ * stand-alone field declarations.
+ */
+protected void expand() {
+ if (isVariableDeclarator() || hasMultipleVariableDeclarators()) {
+ Enumeration siblings= new SiblingEnumeration(getFirstFieldDeclaration());
+ DOMField field= (DOMField)siblings.nextElement();
+ DOMNode next= field.fNextNode;
+ while (siblings.hasMoreElements() && (next instanceof DOMField) && (((DOMField)next).isVariableDeclarator())) {
+ field.localizeContents();
+ if (field.fParent != null) {
+ field.fParent.fragment();
+ }
+ field= (DOMField)siblings.nextElement();
+ next= field.fNextNode;
+ }
+ field.localizeContents();
+ }
+}
+/**
+ * @see DOMNode#getDetailedNode()
+ */
+//protected DOMNode getDetailedNode() {
+// if (isVariableDeclarator() || hasMultipleVariableDeclarators()) {
+// return (DOMNode)getFactory().createField(new String(getSingleVariableDeclaratorContents()));
+// } else {
+// return (DOMNode)getFactory().createField(getContents());
+// }
+//}
+/**
+ * Returns the first field document fragment that defines
+ * the type for this variable declarator.
+ */
+protected DOMField getFirstFieldDeclaration() {
+ if (isVariableDeclarator()) {
+ return ((DOMField)fPreviousNode).getFirstFieldDeclaration();
+ } else {
+ return this;
+ }
+}
+/**
+ * @see IDOMField#getInitializer()
+ */
+public String getInitializer() {
+ becomeDetailed();
+ if (hasInitializer()) {
+ if (fInitializer != null) {
+ return fInitializer;
+ } else {
+ return CharArrayOps.substring(fDocument, fInitializerRange[0], fInitializerRange[1] + 1 - fInitializerRange[0]);
+ }
+ } else {
+ return null;
+ }
+}
+/**
+ * @see IDOMNode#getJavaElement
+ */
+public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException {
+ if (parent.getElementType() == IJavaElement.TYPE) {
+ return ((IType)parent).getField(getName());
+ } else {
+ throw new IllegalArgumentException(Util.bind("element.illegalParent")); //$NON-NLS-1$
+ }
+}
+/**
+ * Returns the last field document fragment in this muli-declarator statement.
+ */
+protected DOMField getLastFieldDeclaration() {
+ DOMField field = this;
+ while (field.isVariableDeclarator() || field.hasMultipleVariableDeclarators()) {
+ if (field.fNextNode instanceof DOMField && ((DOMField)field.fNextNode).isVariableDeclarator()) {
+ field= (DOMField)field.fNextNode;
+ } else {
+ break;
+ }
+ }
+ return field;
+}
+/**
+ * @see DOMMember#getMemberDeclarationStartPosition()
+ */
+protected int getMemberDeclarationStartPosition() {
+ return fTypeRange[0];
+}
+/**
+ * @see IDOMNode#getNodeType()
+ */
+public int getNodeType() {
+ return IDOMNode.FIELD;
+}
+/**
+ * Returns a String representing this field declaration as a field
+ * declaration with one variable declarator.
+ */
+protected char[] getSingleVariableDeclaratorContents() {
+
+
+ CharArrayBuffer buffer= new CharArrayBuffer();
+ DOMField first= getFirstFieldDeclaration();
+ if (first.isDetailed()) {
+ first.appendMemberHeaderFragment(buffer);
+ buffer.append(getType());
+ if (isVariableDeclarator()) {
+ buffer.append(' ');
+ } else {
+ buffer.append(fDocument, fTypeRange[1] + 1, fNameRange[0] - fTypeRange[1] - 1);
+ }
+ } else {
+ buffer.append(first.fDocument, first.fSourceRange[0], first.fNameRange[0] - first.fSourceRange[0]);
+ }
+
+ buffer.append(getName());
+ if (hasInitializer()) {
+ if (fInitializerRange[0] < 0) {
+ buffer
+ .append('=')
+ .append(fInitializer)
+ .append(';')
+ .append(Util.LINE_SEPARATOR);
+ } else {
+ buffer
+ .append(fDocument, fNameRange[1] + 1, fInitializerRange[0] - fNameRange[1] - 1)
+ .append(getInitializer())
+ .append(';')
+ .append(Util.LINE_SEPARATOR);
+ }
+ } else {
+ buffer.append(';').append(Util.LINE_SEPARATOR);
+ }
+ return buffer.getContents();
+}
+/**
+ * @see IDOMField#getType()
+ */
+public String getType() {
+ return fType;
+}
+/**
+ * Returns the souce code to be used for this
+ * field's type.
+ */
+protected char[] getTypeContents() {
+ if (isTypeAltered()) {
+ return fType.toCharArray();
+ } else {
+ return CharArrayOps.subarray(fDocument, fTypeRange[0], fTypeRange[1] + 1 - fTypeRange[0]);
+ }
+}
+/**
+ * Returns true if this field has an initializer expression,
+ * otherwise false.
+ */
+protected boolean hasInitializer() {
+ return getMask(MASK_FIELD_HAS_INITIALIZER);
+}
+/**
+ * Returns true is this field declarations has more than one
+ * variable declarator, otherwise false;
+ */
+protected boolean hasMultipleVariableDeclarators() {
+ return fNextNode != null && (fNextNode instanceof DOMField) &&
+ ((DOMField)fNextNode).isVariableDeclarator();
+}
+/**
+ * Inserts the given un-parented node as a sibling of this node, immediately before
+ * this node. Once inserted, the sibling is only dependent on this document fragment.
+ *
+ * When a sibling is inserted before a variable declarator, it must first
+ * be expanded.
+ *
+ * @see IDOMNode#insertSibling(IDOMNode)
+ */
+public void insertSibling(IDOMNode sibling) throws IllegalArgumentException, DOMException {
+ if (isVariableDeclarator()) {
+ expand();
+ }
+ super.insertSibling(sibling);
+}
+/**
+ * Returns true if this field's type has been altered
+ * from the original document contents.
+ */
+protected boolean isTypeAltered() {
+ return getMask(MASK_FIELD_TYPE_ALTERED);
+}
+/**
+ * Returns true if this field is declared as a secondary variable
+ * declarator for a previous field declaration.
+ */
+protected boolean isVariableDeclarator() {
+ return getMask(MASK_FIELD_IS_VARIABLE_DECLARATOR);
+}
+/**
+ * @see DOMNode
+ */
+protected DOMNode newDOMNode() {
+ return new DOMField();
+}
+/**
+ * Normalizes this When a field with multiple declarators is removed, its declaration
+ * must first be expanded.
+ *
+ * @see IDOMNode#remove()
+ */
+public void remove() {
+ expand();
+ super.remove();
+}
+/**
+ * @see IDOMMember#setComment(String)
+ */
+public void setComment(String comment) {
+ expand();
+ super.setComment(comment);
+}
+/**
+ * @see IDOMMember#setFlags(int)
+ */
+public void setFlags(int flags) {
+ expand();
+ super.setFlags(flags);
+}
+/**
+ * Sets the state of this field declaration as having
+ * an initializer expression.
+ */
+protected void setHasInitializer(boolean hasInitializer) {
+ setMask(MASK_FIELD_HAS_INITIALIZER, hasInitializer);
+}
+/**
+ * @see IDOMField#setInitializer(char[])
+ */
+public void setInitializer(String initializer) {
+ becomeDetailed();
+ fragment();
+ setHasInitializer(initializer != null);
+ fInitializer= initializer;
+}
+/**
+ * Sets the initializer range.
+ */
+void setInitializerRange(int start, int end) {
+ fInitializerRange[0] = start;
+ fInitializerRange[1] = end;
+}
+/**
+ * Sets the state of this field declaration as being a
+ * secondary variable declarator for a previous field
+ * declaration.
+ */
+protected void setIsVariableDeclarator(boolean isVariableDeclarator) {
+ setMask(MASK_FIELD_IS_VARIABLE_DECLARATOR, isVariableDeclarator);
+}
+/**
+ * @see IDOMField#setName(char[])
+ */
+public void setName(String name) throws IllegalArgumentException {
+ if (name == null) {
+ throw new IllegalArgumentException(Util.bind("element.nullName")); //$NON-NLS-1$
+ } else {
+ super.setName(name);
+ setTypeAltered(true);
+ }
+}
+/**
+ * @see IDOMField#setType(char[])
+ */
+public void setType(String typeName) throws IllegalArgumentException {
+ if (typeName == null) {
+ throw new IllegalArgumentException(Util.bind("element.nullType")); //$NON-NLS-1$
+ }
+ becomeDetailed();
+ expand();
+ fragment();
+ setTypeAltered(true);
+ setNameAltered(true);
+ fType= typeName;
+}
+/**
+ * Sets the state of this field declaration as having
+ * the field type altered from the original document.
+ */
+protected void setTypeAltered(boolean typeAltered) {
+ setMask(MASK_FIELD_TYPE_ALTERED, typeAltered);
+}
+/**
+ * @see DOMNode#shareContents(DOMNode)
+ */
+protected void shareContents(DOMNode node) {
+ super.shareContents(node);
+ DOMField field= (DOMField)node;
+ fInitializer= field.fInitializer;
+ fInitializerRange= rangeCopy(field.fInitializerRange);
+ fType= field.fType;
+ fTypeRange= rangeCopy(field.fTypeRange);
+}
+/**
+ * @see IDOMNode#toString()
+ */
+public String toString() {
+ return "FIELD: " + getName(); //$NON-NLS-1$
+}
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMImport.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMImport.java
new file mode 100644
index 0000000..3ff5280
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMImport.java
@@ -0,0 +1,158 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core.jdom;
+
+import net.sourceforge.phpdt.core.IJavaElement;
+import net.sourceforge.phpdt.core.jdom.IDOMImport;
+import net.sourceforge.phpdt.core.jdom.IDOMNode;
+import net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit;
+import net.sourceforge.phpdt.internal.compiler.util.Util;
+import net.sourceforge.phpdt.internal.core.util.CharArrayBuffer;
+
+/**
+ * DOMImport provides an implementation of IDOMImport.
+ *
+ * @see IDOMImport
+ * @see DOMNode
+ */
+class DOMImport extends DOMNode implements IDOMImport {
+ /**
+ * Indicates if this import is an on demand type import
+ */
+ protected boolean fOnDemand;
+/**
+ * Creates a new empty IMPORT node.
+ */
+DOMImport() {
+ fName = "java.lang.*"; //$NON-NLS-1$
+ setMask(MASK_DETAILED_SOURCE_INDEXES, true);
+}
+/**
+ * Creates a new detailed IMPORT document fragment on the given range of the document.
+ *
+ * @param document - the document containing this node's original contents
+ * @param sourceRange - a two element array of integers describing the
+ * entire inclusive source range of this node within its document.
+ * Contents start on and include the character at the first position.
+ * Contents end on and include the character at the last position.
+ * An array of -1's indicates this node's contents do not exist
+ * in the document.
+ * @param name - the identifier portion of the name of this node, or
+ * This method always answers false since an initializer
+ * does not have a signature.
+ */
+public boolean isSignatureEqual(IDOMNode node) {
+ return false;
+}
+/**
+ * @see DOMNode
+ */
+protected DOMNode newDOMNode() {
+ return new DOMInitializer();
+}
+/**
+ * Offsets all the source indexes in this node by the given amount.
+ */
+protected void offset(int offset) {
+ super.offset(offset);
+ offsetRange(fBodyRange, offset);
+}
+/**
+ * @see IDOMInitializer#setBody(char[])
+ */
+public void setBody(String body) {
+ becomeDetailed();
+ fBody= body;
+ setHasBody(body != null);
+ fragment();
+}
+/**
+ * @see IDOMInitializer#setName(String)
+ */
+public void setName(String name) {}
+/**
+ * @see DOMNode#shareContents(DOMNode)
+ */
+protected void shareContents(DOMNode node) {
+ super.shareContents(node);
+ DOMInitializer init= (DOMInitializer)node;
+ fBody= init.fBody;
+ fBodyRange= rangeCopy(init.fBodyRange);
+}
+/**
+ * @see IDOMNode#toString()
+ */
+public String toString() {
+ return "INITIALIZER"; //$NON-NLS-1$
+}
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMMember.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMMember.java
new file mode 100644
index 0000000..19bde2e
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMMember.java
@@ -0,0 +1,351 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core.jdom;
+
+import net.sourceforge.phpdt.core.Flags;
+import net.sourceforge.phpdt.core.jdom.IDOMMember;
+import net.sourceforge.phpdt.internal.compiler.env.IConstants;
+import net.sourceforge.phpdt.internal.core.util.CharArrayBuffer;
+import net.sourceforge.phpdt.internal.core.util.CharArrayOps;
+
+/**
+ * DOMMember provides an implementation of IDOMMember.
+ *
+ * @see IDOMMember
+ * @see DOMNode
+ */
+
+abstract class DOMMember extends DOMNode implements IDOMMember {
+
+ /**
+ * The modifier flags for this member that can be
+ * analyzed with org.eclipse.jdt.core.Flags
+ */
+ protected int fFlags= 0;
+
+ /**
+ * The member's comments when it has been altered from
+ * the contents in the document, otherwise To facilitate the implementation of generating contents for members,
+ * the content of members is split into three sections - the header,
+ * declaration, and body sections. The header section includes any preceding
+ * comments and modifiers. The declaration section includes the portion of
+ * the member declaration that follows any modifiers and precedes the
+ * member body. The body section includes the member body and any trailing
+ * whitespace.
+ *
+ * @see DOMNode#appendFragmentedContents(CharArrayBuffer)
+ */
+protected void appendFragmentedContents(CharArrayBuffer buffer) {
+ if (isDetailed()) {
+ appendMemberHeaderFragment(buffer);
+ appendMemberDeclarationContents(buffer);
+ appendMemberBodyContents(buffer);
+ } else {
+ appendSimpleContents(buffer);
+ }
+}
+/**
+ * Appends this member's body contents to the given CharArrayBuffer.
+ * Body contents include the member body and any trailing whitespace.
+ */
+protected abstract void appendMemberBodyContents(CharArrayBuffer buffer);
+/**
+ * Appends this member's declaration contents to the given CharArrayBuffer.
+ * The declaration contents includes the portion of this member that
+ * appears after any modifiers and precedes the body.
+ */
+protected abstract void appendMemberDeclarationContents(CharArrayBuffer buffer);
+/**
+ * Appends this member's header contents to the given CharArrayBuffer.
+ * Header contents include any preceding comments and modifiers.
+ */
+protected void appendMemberHeaderFragment(CharArrayBuffer buffer) {
+
+ int spaceStart, spaceEnd;
+
+ // space before comment
+ if (hasComment()) {
+ spaceStart= fSourceRange[0];
+ spaceEnd= fCommentRange[0];
+ if (spaceEnd > 0) {
+ buffer.append(fDocument, spaceStart, spaceEnd - spaceStart);
+ }
+ }
+
+ String fragment= getComment();
+ if (fragment != null) {
+ buffer.append(fragment);
+ }
+
+ if (fCommentRange[1] >= 0) {
+ spaceStart= fCommentRange[1] + 1;
+ } else {
+ spaceStart= fSourceRange[0];
+ }
+ if (fModifierRange[0] >= 0) {
+ spaceEnd= fModifierRange[0] - 1;
+ } else {
+ spaceEnd= getMemberDeclarationStartPosition() - 1;
+ }
+
+ if (spaceEnd >= spaceStart) {
+ buffer.append(fDocument, spaceStart, spaceEnd + 1 - spaceStart);
+ }
+ buffer.append(getModifiersText());
+
+}
+/**
+ * Appends the contents of this node to the given CharArrayBuffer, using
+ * the original document and indicies as a form for the current attribute values
+ * of this node. This method is called when this node is know not to have
+ * detailed source indexes.
+ */
+protected abstract void appendSimpleContents(CharArrayBuffer buffer);
+/**
+ * Returns a copy of the given array with the new element appended
+ * to the end of the array.
+ */
+protected String[] appendString(String[] list, String element) {
+ String[] copy= new String[list.length + 1];
+ System.arraycopy(list, 0, copy, 0, list.length);
+ copy[list.length]= element;
+ return copy;
+}
+/**
+ * Returns a Two methods have equal signatures if there names are the same
+ * and their parameter types are the same.
+ */
+public boolean isSignatureEqual(IDOMNode node) {
+ boolean ok= node.getNodeType() == getNodeType();
+ if (ok) {
+ IDOMMethod method= (IDOMMethod)node;
+ ok = (isConstructor() && method.isConstructor()) ||
+ (!isConstructor() && !method.isConstructor());
+ if (ok && !isConstructor()) {
+ ok= getName().equals(method.getName());
+ }
+ if (!ok) {
+ return false;
+ }
+
+ String[] types= method.getParameterTypes();
+ if (fParameterTypes == null || fParameterTypes.length == 0) {
+ // this method has no parameters
+ if (types == null || types.length == 0) {
+ // the other method has no parameters either
+ return true;
+ }
+ } else {
+ // this method has parameters
+ if (types == null || types.length == 0) {
+ // the other method has no parameters
+ return false;
+ }
+ if (fParameterTypes.length != types.length) {
+ // the methods have a different number of parameters
+ return false;
+ }
+ int i;
+ for (i= 0; i < types.length; i++) {
+ if (!fParameterTypes[i].equals(types[i])) {
+ return false;
+ }
+ }
+ return true;
+ }
+ }
+ return false;
+
+}
+/**
+ * @see DOMNode
+ */
+protected DOMNode newDOMNode() {
+ return new DOMMethod();
+}
+/**
+ * Offsets all the source indexes in this node by the given amount.
+ */
+protected void offset(int offset) {
+ super.offset(offset);
+ offsetRange(fBodyRange, offset);
+ offsetRange(fExceptionRange, offset);
+ offsetRange(fParameterRange, offset);
+ offsetRange(fReturnTypeRange, offset);
+}
+/**
+ * @see IDOMMethod#setBody
+ */
+public void setBody(String body) {
+ becomeDetailed();
+ fragment();
+ fBody= body;
+ setHasBody(body != null);
+ if (!hasBody()) {
+ fBody= ";"+Util.LINE_SEPARATOR; //$NON-NLS-1$
+ }
+}
+/**
+ * Sets the end of the body range
+ */
+void setBodyRangeEnd(int end) {
+ fBodyRange[1] = end;
+}
+/**
+ * @see IDOMMethod#setConstructor(boolean)
+ */
+public void setConstructor(boolean b) {
+ becomeDetailed();
+ setMask(MASK_IS_CONSTRUCTOR, b);
+ fragment();
+}
+/**
+ * @see IDOMMethod#setExceptions(char[][])
+ */
+public void setExceptions(String[] names) {
+ becomeDetailed();
+ if (names == null || names.length == 0) {
+ fExceptions= null;
+ } else {
+ fExceptions= names;
+ CharArrayBuffer buffer = new CharArrayBuffer();
+ char[] comma = new char[] {',', ' '};
+ for (int i = 0, length = names.length; i < length; i++) {
+ if (i > 0)
+ buffer.append(comma);
+ buffer.append(names[i]);
+ }
+ fExceptionList= buffer.getContents();
+ }
+ fragment();
+}
+/**
+ * @see IDOMMethod#setName
+ */
+public void setName(String name) {
+ if (name == null) {
+ throw new IllegalArgumentException(Util.bind("element.nullName")); //$NON-NLS-1$
+ } else {
+ super.setName(name);
+ }
+}
+/**
+ * @see IDOMMethod#setParameters(char[][], char[][])
+ */
+public void setParameters(String[] types, String[] names) throws IllegalArgumentException {
+ becomeDetailed();
+ if (types== null || names == null) {
+ if (types == null && names == null) {
+ fParameterTypes= null;
+ fParameterNames= null;
+ fParameterList= new char[] {'(',')'};
+ } else {
+ throw new IllegalArgumentException(Util.bind("dom.mismatchArgNamesAndTypes")); //$NON-NLS-1$
+ }
+ } else if (names.length != types.length) {
+ throw new IllegalArgumentException(Util.bind("dom.mismatchArgNamesAndTypes")); //$NON-NLS-1$
+ } else if (names.length == 0) {
+ setParameters(null, null);
+ } else {
+ fParameterNames= names;
+ fParameterTypes= types;
+ CharArrayBuffer parametersBuffer = new CharArrayBuffer();
+ parametersBuffer.append("("); //$NON-NLS-1$
+ char[] comma = new char[] {',', ' '};
+ for (int i = 0; i < names.length; i++) {
+ if (i > 0) {
+ parametersBuffer.append(comma);
+ }
+ parametersBuffer
+ .append(types[i])
+ .append(' ')
+ .append(names[i]);
+ }
+ parametersBuffer.append(')');
+ fParameterList= parametersBuffer.getContents();
+ }
+ fragment();
+}
+/**
+ * @see IDOMMethod#setReturnType(char[])
+ */
+public void setReturnType(String name) throws IllegalArgumentException {
+ if (name == null) {
+ throw new IllegalArgumentException(Util.bind("dom.nullReturnType")); //$NON-NLS-1$
+ }
+ becomeDetailed();
+ fragment();
+ setReturnTypeAltered(true);
+ fReturnType= name;
+}
+/**
+ * Sets the state of this method declaration as having
+ * the return type altered from the original document.
+ */
+protected void setReturnTypeAltered(boolean typeAltered) {
+ setMask(MASK_RETURN_TYPE_ALTERED, typeAltered);
+}
+/**
+ */
+protected void setSourceRangeEnd(int end) {
+ super.setSourceRangeEnd(end);
+ fBodyRange[1]= end;
+}
+/**
+ * @see DOMNode#shareContents(DOMNode)
+ */
+protected void shareContents(DOMNode node) {
+ super.shareContents(node);
+ DOMMethod method= (DOMMethod)node;
+ fBody= method.fBody;
+ fBodyRange= rangeCopy(method.fBodyRange);
+ fExceptionList= method.fExceptionList;
+ fExceptionRange= rangeCopy(method.fExceptionRange);
+ fExceptions= method.fExceptions;
+ fParameterList= method.fParameterList;
+ fParameterNames= method.fParameterNames;
+ fParameterRange= rangeCopy(method.fParameterRange);
+ fParameterTypes= method.fParameterTypes;
+ fReturnType= method.fReturnType;
+ fReturnTypeRange= rangeCopy(method.fReturnTypeRange);
+}
+/**
+ * @see IDOMNode#toString()
+ */
+public String toString() {
+ if (isConstructor()) {
+ return "CONSTRUCTOR"; //$NON-NLS-1$
+ } else {
+ return "METHOD: " + getName(); //$NON-NLS-1$
+ }
+}
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMNode.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMNode.java
new file mode 100644
index 0000000..833adf9
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMNode.java
@@ -0,0 +1,971 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core.jdom;
+
+import java.util.Enumeration;
+
+import net.sourceforge.phpdt.core.jdom.DOMException;
+import net.sourceforge.phpdt.core.jdom.DOMFactory;
+import net.sourceforge.phpdt.core.jdom.IDOMCompilationUnit;
+import net.sourceforge.phpdt.core.jdom.IDOMFactory;
+import net.sourceforge.phpdt.core.jdom.IDOMMethod;
+import net.sourceforge.phpdt.core.jdom.IDOMNode;
+import net.sourceforge.phpdt.internal.compiler.util.Util;
+import net.sourceforge.phpdt.internal.core.util.CharArrayBuffer;
+
+/**
+ * DOMNode provides an implementation for A node represents a document fragment. When a node is created, its
+ * contents are located in a contiguous range of a shared document. A shared
+ * document is a char array, and is shared in the sense that the contents of other
+ * document fragments may also be contained in the array.
+ *
+ * A node maintains indicies of relevant portions of its contents
+ * in the shared document. Thus the original document and indicies create a
+ * form from which to generate the contents of the document fragment. As attributes
+ * of a node are changed, the node attempts to maintain the original formatting
+ * by only replacing relevant portions of the shared document with the value
+ * of new attributes (that is, filling in the form with replacement values).
+ *
+ * When a node is first created, it is considered unfragmented. When any
+ * attribute of the node is altered, the node is then considered fragmented
+ * from that point on. A node is also considered fragmented if any of its
+ * descendants are fragmented. When a node is unfragmented, the contents of the
+ * node can be efficiently generated from the original shared document. When
+ * a node is fragmented, the contents of the node must be created using the
+ * original document and indicies as a form, filling in replacement values
+ * as required.
+ *
+ * Generally, a node's contents consists of complete lines in a shared document.
+ * The contents of the node are normalized on creation to include any whitespace
+ * preceding the node on the line where the node begins, and to include and trailing
+ * whitespace up to the line where the next node begins. Any trailing // comments
+ * that begin on the line where the current node ends, are considered part of that
+ * node.
+ *
+ * @see IDOMNode
+ */
+public abstract class DOMNode implements IDOMNode {
+
+ /**
+ * The first child of this node - When a child is added, this node must be considered fragmented such that
+ * the contents of this node are properly generated.
+ *
+ * @see IDOMNode#addChild(IDOMNode)
+ */
+public void addChild(IDOMNode child) throws IllegalArgumentException, DOMException {
+ basicAddChild(child);
+
+ // if the node is a constructor, it must also be fragmented to update the constructor's name
+ if (child.getNodeType() == IDOMNode.METHOD && ((IDOMMethod)child).isConstructor()) {
+ ((DOMNode)child).fragment();
+ } else {
+ fragment();
+ }
+}
+/**
+ * Appends the current contents of this document fragment
+ * to the given If this node is fragmented, contents must be generated by
+ * using the original document and indicies as a form for the current
+ * attribute values of this node. If this node not fragmented, the
+ * contents can be obtained from the document.
+ *
+ */
+protected void appendContents(CharArrayBuffer buffer) {
+ if (isFragmented()) {
+ appendFragmentedContents(buffer);
+ } else {
+ buffer.append(fDocument, fSourceRange[0], fSourceRange[1] + 1 - fSourceRange[0]);
+ }
+}
+/**
+ * Appends the contents of all children of this node to the
+ * given This algorithm used minimizes String generation by merging
+ * adjacent unfragmented children into one substring operation.
+ *
+ */
+protected void appendContentsOfChildren(CharArrayBuffer buffer) {
+ DOMNode child= fFirstChild;
+ DOMNode sibling;
+
+ int start= 0, end= 0;
+ if (child != null) {
+ start= child.getStartPosition();
+ end= child.getEndPosition();
+ }
+ while (child != null) {
+ sibling= child.fNextNode;
+ if (sibling != null) {
+ if (sibling.isContentMergableWith(child)) {
+ end= sibling.getEndPosition();
+ } else {
+ if (child.isFragmented()) {
+ child.appendContents(buffer);
+ } else {
+ buffer.append(child.getDocument(), start, end + 1 - start);
+ }
+ start= sibling.getStartPosition();
+ end= sibling.getEndPosition();
+ }
+ } else {
+ if (child.isFragmented()) {
+ child.appendContents(buffer);
+ } else {
+ buffer.append(child.getDocument(), start, end + 1 - start);
+ }
+ }
+ child= sibling;
+ }
+}
+/**
+ * Appends the contents of this node to the given Default implementation of If this node is fragmented, contents must be generated by
+ * using the original document and indicies as a form for the current
+ * attribute values of this node. If this node not fragmented, the
+ * contents can be obtained from the document.
+ *
+ * @see IDOMNode#getContents()
+ */
+public String getContents() {
+ CharArrayBuffer buffer= new CharArrayBuffer();
+ appendContents(buffer);
+ return buffer.toString();
+}
+/**
+ * Returns a new document fragment representing this node with
+ * detailed source indexes. Subclasses that provide a detailed
+ * implementation must override this method.
+ */
+protected DOMNode getDetailedNode() {
+ return this;
+}
+/**
+ * Returns the document containing this node's original contents.
+ * The document may be shared by other nodes.
+ */
+protected char[] getDocument() {
+ return fDocument;
+}
+/**
+ * Returns the original position of the last character of this
+ * node's contents in its document.
+ */
+public int getEndPosition() {
+ return fSourceRange[1];
+}
+/**
+ * Returns a factory with which to create new document fragments.
+ */
+protected IDOMFactory getFactory() {
+ return new DOMFactory();
+}
+/**
+ * @see IDOMNode#getFirstChild()
+ */
+public IDOMNode getFirstChild() {
+ return fFirstChild;
+}
+/**
+ * Returns the position at which the first child of this node should be inserted.
+ */
+public int getInsertionPosition() {
+ return fInsertionPosition;
+}
+/**
+ * Returns By default, the signatures of two nodes are equal if their
+ * type and names are equal. Node types that have other requirements
+ * for equality must override this method.
+ */
+public boolean isSignatureEqual(IDOMNode node) {
+ return getNodeType() == node.getNodeType() && getName().equals(node.getName());
+}
+/**
+ * Localizes the contents of this node and all descendant nodes,
+ * such that this node is no longer dependent on its original
+ * document in order to generate its contents. This node and all
+ * descendant nodes become unfragmented and share a new
+ * document.
+ */
+protected void localizeContents() {
+
+ DOMNode clone= (DOMNode)clone();
+ shareContents(clone);
+
+}
+/**
+ * Returns a new empty When a child is removed, its parent is fragmented such that it properly
+ * generates its contents.
+ *
+ * @see IDOMNode#remove()
+ */
+public void remove() {
+
+ if (fParent != null) {
+ fParent.fragment();
+ }
+
+ // link siblings
+ if (fNextNode != null) {
+ fNextNode.fPreviousNode= fPreviousNode;
+ }
+ if (fPreviousNode != null) {
+ fPreviousNode.fNextNode= fNextNode;
+ }
+ // fix parent's pointers
+ if (fParent != null) {
+ if (fParent.fFirstChild == this) {
+ fParent.fFirstChild= fNextNode;
+ }
+ if (fParent.fLastChild == this) {
+ fParent.fLastChild= fPreviousNode;
+ }
+ }
+ // remove myself
+ fParent= null;
+ fNextNode= null;
+ fPreviousNode= null;
+}
+/**
+ * Sets the specified mask of this node's state mask on or off
+ * based on the boolean value - true -> on, false -> off.
+ */
+protected void setMask(int mask, boolean on) {
+ if (on) {
+ fStateMask |= mask;
+ } else {
+ fStateMask &= ~mask;
+ }
+}
+/**
+ * @see IDOMNode#setName
+ */
+public void setName(String name) {
+ fName= name;
+ setNameAltered(true);
+ fragment();
+}
+/**
+ * Sets the state of this node as having
+ * its name attribute altered from the original
+ * document contents.
+ */
+protected void setNameAltered(boolean altered) {
+ setMask(MASK_NAME_ALTERED, altered);
+}
+/**
+ * Sets the original position of the last character of this node's contents
+ * in its document. This method is only used during DOM creation while
+ * normalizing the source range of each node.
+ */
+protected void setSourceRangeEnd(int end) {
+ fSourceRange[1]= end;
+}
+/**
+ * Sets the original position of the first character of this node's contents
+ * in its document. This method is only used during DOM creation while
+ * normalizing the source range of each node.
+ */
+protected void setStartPosition(int start) {
+ fSourceRange[0]= start;
+}
+/**
+ * Sets the contents of this node and descendant nodes to be the
+ * (identical) contents of the given node and its descendants. This
+ * does not effect this node's parent and sibling configuration,
+ * only the contents of this node. This is used only to localize
+ * the contents of this node.
+ */
+protected void shareContents(DOMNode node) {
+ fDocument= node.fDocument;
+ fIsFragmented= node.fIsFragmented;
+ fName= node.fName;
+ fNameRange= rangeCopy(node.fNameRange);
+ fSourceRange= rangeCopy(node.fSourceRange);
+ fStateMask= node.fStateMask;
+
+
+ if (canHaveChildren()) {
+ Enumeration myChildren= getChildren();
+ Enumeration otherChildren= node.getChildren();
+ DOMNode myChild, otherChild;
+ while (myChildren.hasMoreElements()) {
+ myChild= (DOMNode)myChildren.nextElement();
+ otherChild= (DOMNode)otherChildren.nextElement();
+ myChild.shareContents(otherChild);
+ }
+ }
+}
+/**
+ * Returns a When the name of a type is set, all of its constructors must be marked
+ * as fragmented, since the names of the constructors must reflect the name
+ * of this type.
+ *
+ * @see IDOMNode#setName(char[])
+ */
+public void setName(String name) throws IllegalArgumentException {
+ if (name == null) {
+ throw new IllegalArgumentException(Util.bind("element.nullName")); //$NON-NLS-1$
+ }
+ super.setName(name);
+ Enumeration children= getChildren();
+ while (children.hasMoreElements()) {
+ IDOMNode child= (IDOMNode)children.nextElement();
+ if (child.getNodeType() == IDOMNode.METHOD && ((IDOMMethod)child).isConstructor()) {
+ ((DOMNode)child).fragment();
+ }
+ }
+}
+/**
+ * Sets the end of the open body range
+ */
+void setOpenBodyRangeEnd(int end) {
+ fOpenBodyRange[1] = end;
+}
+/**
+ * Sets the start of the open body range
+ */
+void setOpenBodyRangeStart(int start) {
+ fOpenBodyRange[0] = start;
+}
+/**
+ * @see IDOMType#setSuperclass(char[])
+ */
+public void setSuperclass(String superclassName) {
+ becomeDetailed();
+ fragment();
+ fSuperclass= superclassName;
+ setMask(MASK_TYPE_HAS_SUPERCLASS, superclassName != null);
+}
+/**
+ * @see IDOMType#setSuperInterfaces(String[])
+ */
+public void setSuperInterfaces(String[] names) {
+ becomeDetailed();
+ if (names == null) {
+ throw new IllegalArgumentException(Util.bind("dom.nullInterfaces")); //$NON-NLS-1$
+ }
+ fragment();
+ fSuperInterfaces= names;
+ if (names == null || names.length == 0) {
+ fInterfaces= null;
+ fSuperInterfaces= null;
+ setMask(MASK_TYPE_HAS_INTERFACES, false);
+ } else {
+ setMask(MASK_TYPE_HAS_INTERFACES, true);
+ CharArrayBuffer buffer = new CharArrayBuffer();
+ for (int i = 0; i < names.length; i++) {
+ if (i > 0) {
+ buffer.append(", "); //$NON-NLS-1$
+ }
+ buffer.append(names[i]);
+ }
+ fInterfaces = buffer.getContents();
+ }
+}
+/**
+ * Sets the type keyword
+ */
+void setTypeKeyword(String keyword) {
+ fTypeKeyword = keyword;
+}
+/**
+ * @see DOMNode#shareContents(DOMNode)
+ */
+protected void shareContents(DOMNode node) {
+ super.shareContents(node);
+ DOMType type= (DOMType)node;
+ fCloseBodyRange= rangeCopy(type.fCloseBodyRange);
+ fExtendsRange= type.fExtendsRange;
+ fImplementsRange= rangeCopy(type.fImplementsRange);
+ fInterfaces= type.fInterfaces;
+ fInterfacesRange= rangeCopy(type.fInterfacesRange);
+ fOpenBodyRange= rangeCopy(type.fOpenBodyRange);
+ fSuperclass= type.fSuperclass;
+ fSuperclassRange= rangeCopy(type.fSuperclassRange);
+ fSuperInterfaces= type.fSuperInterfaces;
+ fTypeKeyword= type.fTypeKeyword;
+ fTypeRange= rangeCopy(type.fTypeRange);
+}
+/**
+ * @see IDOMNode#toString()
+ */
+public String toString() {
+ return "TYPE: " + getName(); //$NON-NLS-1$
+}
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/ILineStartFinder.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/ILineStartFinder.java
new file mode 100644
index 0000000..8dda4de
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/ILineStartFinder.java
@@ -0,0 +1,25 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core.jdom;
+
+/**
+ * The This defaults to zero if the position corresponds to a position on the first line
+ * of the source.
+ */
+public int getLineStart(int position);
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/SiblingEnumeration.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/SiblingEnumeration.java
new file mode 100644
index 0000000..167ce0e
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/SiblingEnumeration.java
@@ -0,0 +1,54 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core.jdom;
+
+import java.util.Enumeration;
+
+import net.sourceforge.phpdt.core.jdom.IDOMNode;
+
+/**
+ * SiblingEnumeration provides an enumeration on a linked list
+ * of sibling DOM nodes.
+ *
+ * @see java.util.Enumeration
+ */
+
+/* package */ class SiblingEnumeration implements Enumeration {
+
+ /**
+ * The current location in the linked list
+ * of DOM nodes.
+ */
+ protected IDOMNode fCurrentElement;
+/**
+ * Creates an enumeration of silbings starting at the given node.
+ * If the given node is The iteration can be made efficient by making use of the fact that values in
+ * the cache (instances of Modifications to the cache must not be performed while using the
+ * enumeration. Doing so will lead to an illegal state.
+ *
+ * @see LRUCache
+ */
+public interface ICacheEnumeration extends Enumeration {
+ /**
+ * Returns the value of the previously accessed key in the enumeration.
+ * Must be called after a call to nextElement().
+ *
+ * @return Value of current cache entry
+ */
+ public Object getValue();
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/ILRUCacheable.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/ILRUCacheable.java
new file mode 100644
index 0000000..6c5662f
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/ILRUCacheable.java
@@ -0,0 +1,28 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core.util;
+
+/**
+ * Types implementing this interface can occupy a variable amount of space
+ * in an LRUCache. Cached items that do not implement this interface are
+ * considered to occupy one unit of space.
+ *
+ * @see LRUCache
+ */
+public interface ILRUCacheable {
+ /**
+ * Returns the space the receiver consumes in an LRU Cache. The default space
+ * value is 1.
+ *
+ * @return int Amount of cache space taken by the receiver
+ */
+ public int getCacheFootprint();
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/LRUCache.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/LRUCache.java
new file mode 100644
index 0000000..e1a933a
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/LRUCache.java
@@ -0,0 +1,498 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core.util;
+
+import java.util.Enumeration;
+import java.util.Hashtable;
+
+/**
+ * The The data structure is based on the LRU virtual memory paging scheme.
+ *
+ * Objects can take up a variable amount of cache space by implementing
+ * the This implementation is NOT thread-safe. Synchronization wrappers would
+ * have to be added to ensure atomic insertions and deletions from the cache.
+ *
+ * @see org.eclipse.jdt.internal.core.util.ILRUCacheable
+ */
+public class LRUCache implements Cloneable {
+
+ /**
+ * This type is used internally by the LRUCache to represent entries
+ * stored in the cache.
+ * It is static because it does not require a pointer to the cache
+ * which contains it.
+ *
+ * @see LRUCache
+ */
+ protected static class LRUCacheEntry {
+
+ /**
+ * Hash table key
+ */
+ public Object _fKey;
+
+ /**
+ * Hash table value (an LRUCacheEntry object)
+ */
+ public Object _fValue;
+
+ /**
+ * Time value for queue sorting
+ */
+ public int _fTimestamp;
+
+ /**
+ * Cache footprint of this entry
+ */
+ public int _fSpace;
+
+ /**
+ * Previous entry in queue
+ */
+ public LRUCacheEntry _fPrevious;
+
+ /**
+ * Next entry in queue
+ */
+ public LRUCacheEntry _fNext;
+
+ /**
+ * Creates a new instance of the receiver with the provided values
+ * for key, value, and space.
+ */
+ public LRUCacheEntry (Object key, Object value, int space) {
+ _fKey = key;
+ _fValue = value;
+ _fSpace = space;
+ }
+
+ /**
+ * Returns a String that represents the value of this object.
+ */
+ public String toString() {
+
+ return "LRUCacheEntry [" + _fKey + "-->" + _fValue + "]"; //$NON-NLS-3$ //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ }
+
+ /**
+ * Amount of cache space used so far
+ */
+ protected int fCurrentSpace;
+
+ /**
+ * Maximum space allowed in cache
+ */
+ protected int fSpaceLimit;
+
+ /**
+ * Counter for handing out sequential timestamps
+ */
+ protected int fTimestampCounter;
+
+ /**
+ * Hash table for fast random access to cache entries
+ */
+ protected Hashtable fEntryTable;
+
+ /**
+ * Start of queue (most recently used entry)
+ */
+ protected LRUCacheEntry fEntryQueue;
+
+ /**
+ * End of queue (least recently used entry)
+ */
+ protected LRUCacheEntry fEntryQueueTail;
+
+ /**
+ * Default amount of space in the cache
+ */
+ protected static final int DEFAULT_SPACELIMIT = 100;
+ /**
+ * Creates a new cache. Size of cache is defined by
+ *
+ * This interface contains constants only; it is not intended to be implemented
+ * or extended.
+ *
+ * Subclasses may override.
+ *
+ * @param selection containing the elements to be dragged
+ */
+ protected boolean isDragable(ISelection selection) {
+ return true;
+ }
+
+
+ /* non Java-doc
+ * @see org.eclipse.swt.dnd.DragSourceListener#dragSetData
+ */
+ public void dragSetData(DragSourceEvent event) {
+ // For consistency set the data to the selection even though
+ // the selection is provided by the LocalSelectionTransfer
+ // to the drop target adapter.
+ event.data= LocalSelectionTransfer.getInstance().getSelection();
+ }
+
+
+ /* non Java-doc
+ * @see org.eclipse.swt.dnd.DragSourceListener#dragFinished
+ */
+ public void dragFinished(DragSourceEvent event) {
+ // We assume that the drop target listener has done all
+ // the work.
+ Assert.isTrue(event.detail == DND.DROP_NONE);
+ LocalSelectionTransfer.getInstance().setSelection(null);
+ LocalSelectionTransfer.getInstance().setSelectionSetTime(0);
+ }
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/DelegatingDragAdapter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/DelegatingDragAdapter.java
new file mode 100644
index 0000000..74ace1c
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/DelegatingDragAdapter.java
@@ -0,0 +1,115 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.ui.dnd;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+import org.eclipse.swt.dnd.DragSource;
+import org.eclipse.swt.dnd.DragSourceEvent;
+import org.eclipse.swt.dnd.DragSourceListener;
+import org.eclipse.swt.dnd.Transfer;
+import org.eclipse.swt.dnd.TransferData;
+
+import org.eclipse.jface.util.Assert;
+
+/**
+ * A delegating drag adapter negotiates between a set of
+ * The following characters have special meaning:
+ * ? => any character
+ * * => any string
+ *
+ * The following characters have special meaning:
+ * ? => any character
+ * * => any string
+ *
+ * This interface is not intended to be implemented by clients.
+ *
+ * This working copy manager does not assume the ownership of this working copy, i.e.,
+ * the given working copy is not automatically be freed when this manager is shut down.
+ *
+ * @param input the editor input
+ * @param workingCopy the working copy
+ */
+ void setWorkingCopy(IEditorInput input, ICompilationUnit workingCopy);
+
+ /**
+ * Removes the working copy set for the given editor input. If there is no
+ * working copy set for this input or this input is not connected to this
+ * working copy manager, this call has no effect.
+ *
+ * @param input the editor input
+ */
+ void removeWorkingCopy(IEditorInput input);
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/IWorkingCopyProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/IWorkingCopyProvider.java
new file mode 100644
index 0000000..7d588ff
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/IWorkingCopyProvider.java
@@ -0,0 +1,36 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.ui;
+
+/**
+ * Interface used for Java element content providers to indicate that
+ * the content provider can return working copy elements for members
+ * below compilation units.
+ *
+ *
+ * This interface is not intended to be implemented by clients.
+ *
+ * This class may be instantiated; it is not intended to be subclassed.
+ *
+ * The implementation also handles non-Java elements by forwarding the requests to the
+ *
+ * This class may be instantiated; it is not intended to be subclassed.
+ *
+ * This class may be instantiated; it is not intended to be subclassed.
+ *
+ * This class provides static methods and fields only; it is not intended to be
+ * instantiated or subclassed by clients.
+ *
+ * When this id is used to access
+ * a view part with
+ * When this id is used to access
+ * a view part with
+ * This class may be instantiated; it is not intended to be subclassed.
+ *
- * Value is of type
- * Value is of type
+ * Value is of type
+ * Value is of type
+ * Note: Only images for elements in Java projects are currently updated on marker changes.
+ *
+ *
+ * The following Java element hierarchy is surfaced by this content provider:
+ *
+ * true
to #isCancelled
.
+ */
+public interface IJavaElementRequestor {
+public void acceptField(IField field);
+//public void acceptInitializer(IInitializer initializer);
+public void acceptMemberType(IType type);
+public void acceptMethod(IMethod method);
+public void acceptPackageFragment(IPackageFragment packageFragment);
+public void acceptType(IType type);
+/**
+ * Returns true
if this IJavaElementRequestor does
+ * not want to receive any more results.
+ */
+boolean isCanceled();
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaElement.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaElement.java
index c45befb..a55c97a 100644
--- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaElement.java
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaElement.java
@@ -18,8 +18,18 @@ import net.sourceforge.phpdt.core.IJavaModel;
import net.sourceforge.phpdt.core.IJavaModelStatusConstants;
import net.sourceforge.phpdt.core.IJavaProject;
import net.sourceforge.phpdt.core.IOpenable;
+import net.sourceforge.phpdt.core.IParent;
+import net.sourceforge.phpdt.core.ISourceRange;
+import net.sourceforge.phpdt.core.ISourceReference;
import net.sourceforge.phpdt.core.JavaModelException;
+import net.sourceforge.phpdt.core.jdom.IDOMCompilationUnit;
+import net.sourceforge.phpdt.core.jdom.IDOMNode;
+import net.sourceforge.phpdt.internal.corext.Assert;
+import org.eclipse.core.resources.IResourceStatus;
+import org.eclipse.core.resources.ResourcesPlugin;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.PlatformObject;
@@ -94,34 +104,34 @@ public abstract class JavaElement extends PlatformObject implements IJavaElement
/**
* @see IOpenable
*/
-// public void close() throws JavaModelException {
-// Object info = JavaModelManager.getJavaModelManager().peekAtInfo(this);
-// if (info != null) {
-// boolean wasVerbose = false;
-// try {
-// if (JavaModelManager.VERBOSE) {
-// System.out.println("CLOSING Element ("+ Thread.currentThread()+"): " + this.toStringWithAncestors()); //$NON-NLS-1$//$NON-NLS-2$
-// wasVerbose = true;
-// JavaModelManager.VERBOSE = false;
-// }
-// if (this instanceof IParent) {
-// IJavaElement[] children = ((JavaElementInfo) info).getChildren();
-// for (int i = 0, size = children.length; i < size; ++i) {
-// JavaElement child = (JavaElement) children[i];
-// child.close();
-// }
-// }
-// closing(info);
-// JavaModelManager.getJavaModelManager().removeInfo(this);
-// if (wasVerbose) {
-// System.out.println("-> Package cache size = " + JavaModelManager.getJavaModelManager().cache.pkgSize()); //$NON-NLS-1$
-// System.out.println("-> Openable cache filling ratio = " + JavaModelManager.getJavaModelManager().cache.openableFillingRatio() + "%"); //$NON-NLS-1$//$NON-NLS-2$
-// }
-// } finally {
-// JavaModelManager.VERBOSE = wasVerbose;
-// }
-// }
-// }
+ public void close() throws JavaModelException {
+ Object info = JavaModelManager.getJavaModelManager().peekAtInfo(this);
+ if (info != null) {
+ boolean wasVerbose = false;
+ try {
+ if (JavaModelManager.VERBOSE) {
+ System.out.println("CLOSING Element ("+ Thread.currentThread()+"): " + this.toStringWithAncestors()); //$NON-NLS-1$//$NON-NLS-2$
+ wasVerbose = true;
+ JavaModelManager.VERBOSE = false;
+ }
+ if (this instanceof IParent) {
+ IJavaElement[] children = ((JavaElementInfo) info).getChildren();
+ for (int i = 0, size = children.length; i < size; ++i) {
+ JavaElement child = (JavaElement) children[i];
+ child.close();
+ }
+ }
+ closing(info);
+ JavaModelManager.getJavaModelManager().removeInfo(this);
+ if (wasVerbose) {
+ System.out.println("-> Package cache size = " + JavaModelManager.getJavaModelManager().cache.pkgSize()); //$NON-NLS-1$
+ System.out.println("-> Openable cache filling ratio = " + JavaModelManager.getJavaModelManager().cache.openableFillingRatio() + "%"); //$NON-NLS-1$//$NON-NLS-2$
+ }
+ } finally {
+ JavaModelManager.VERBOSE = wasVerbose;
+ }
+ }
+ }
/**
* This element is being closed. Do any necessary cleanup.
*/
@@ -159,9 +169,9 @@ public abstract class JavaElement extends PlatformObject implements IJavaElement
* Returns true if this JavaElement
is equivalent to the given
* IDOMNode
.
*/
-// protected boolean equalsDOMNode(IDOMNode node) throws JavaModelException {
-// return false;
-// }
+ protected boolean equalsDOMNode(IDOMNode node) throws JavaModelException {
+ return false;
+ }
/**
* @see IJavaElement
*/
@@ -179,66 +189,66 @@ public abstract class JavaElement extends PlatformObject implements IJavaElement
* Returns the IDOMNode
that corresponds to this JavaElement
* or null
if there is no corresponding node.
*/
-// public IDOMNode findNode(IDOMCompilationUnit dom) {
-// int type = getElementType();
-// if (type == IJavaElement.COMPILATION_UNIT ||
-// type == IJavaElement.FIELD ||
-// type == IJavaElement.IMPORT_DECLARATION ||
-// type == IJavaElement.INITIALIZER ||
-// type == IJavaElement.METHOD ||
-// type == IJavaElement.PACKAGE_DECLARATION ||
-// type == IJavaElement.TYPE) {
-// ArrayList path = new ArrayList();
-// IJavaElement element = this;
-// while (element != null && element.getElementType() != IJavaElement.COMPILATION_UNIT) {
-// if (element.getElementType() != IJavaElement.IMPORT_CONTAINER) {
-// // the DOM does not have import containers, so skip them
-// path.add(0, element);
-// }
-// element = element.getParent();
-// }
-// if (path.size() == 0) {
-// try {
-// if (equalsDOMNode(dom)) {
-// return dom;
-// } else {
-// return null;
-// }
-// } catch(JavaModelException e) {
-// return null;
-// }
-// }
-// return ((JavaElement) path.get(0)).followPath(path, 0, dom.getFirstChild());
-// } else {
-// return null;
-// }
-// }
-// /**
-// */
-// protected IDOMNode followPath(ArrayList path, int position, IDOMNode node) {
-//
-// try {
-// if (equalsDOMNode(node)) {
-// if (position == (path.size() - 1)) {
-// return node;
-// } else {
-// if (node.getFirstChild() != null) {
-// position++;
-// return ((JavaElement)path.get(position)).followPath(path, position, node.getFirstChild());
-// } else {
-// return null;
-// }
-// }
-// } else if (node.getNextNode() != null) {
-// return followPath(path, position, node.getNextNode());
-// } else {
-// return null;
-// }
-// } catch (JavaModelException e) {
-// return null;
-// }
-//
-// }
+ public IDOMNode findNode(IDOMCompilationUnit dom) {
+ int type = getElementType();
+ if (type == IJavaElement.COMPILATION_UNIT ||
+ type == IJavaElement.FIELD ||
+ type == IJavaElement.IMPORT_DECLARATION ||
+ type == IJavaElement.INITIALIZER ||
+ type == IJavaElement.METHOD ||
+ type == IJavaElement.PACKAGE_DECLARATION ||
+ type == IJavaElement.TYPE) {
+ ArrayList path = new ArrayList();
+ IJavaElement element = this;
+ while (element != null && element.getElementType() != IJavaElement.COMPILATION_UNIT) {
+ if (element.getElementType() != IJavaElement.IMPORT_CONTAINER) {
+ // the DOM does not have import containers, so skip them
+ path.add(0, element);
+ }
+ element = element.getParent();
+ }
+ if (path.size() == 0) {
+ try {
+ if (equalsDOMNode(dom)) {
+ return dom;
+ } else {
+ return null;
+ }
+ } catch(JavaModelException e) {
+ return null;
+ }
+ }
+ return ((JavaElement) path.get(0)).followPath(path, 0, dom.getFirstChild());
+ } else {
+ return null;
+ }
+ }
+ /**
+ */
+ protected IDOMNode followPath(ArrayList path, int position, IDOMNode node) {
+
+ try {
+ if (equalsDOMNode(node)) {
+ if (position == (path.size() - 1)) {
+ return node;
+ } else {
+ if (node.getFirstChild() != null) {
+ position++;
+ return ((JavaElement)path.get(position)).followPath(path, position, node.getFirstChild());
+ } else {
+ return null;
+ }
+ }
+ } else if (node.getNextNode() != null) {
+ return followPath(path, position, node.getNextNode());
+ } else {
+ return null;
+ }
+ } catch (JavaModelException e) {
+ return null;
+ }
+
+ }
/**
* @see IJavaElement
*/
@@ -295,32 +305,31 @@ public abstract class JavaElement extends PlatformObject implements IJavaElement
* @exception JavaModelException if the element is not present or not accessible
*/
public Object getElementInfo() throws JavaModelException {
-return null;
// workaround to ensure parent project resolved classpath is available to avoid triggering initializers
// while the JavaModelManager lock is acquired (can cause deadlocks in clients)
-// IJavaProject project = getJavaProject();
-// if (project != null && !project.isOpen()) {
-// // TODO: need to revisit, since deadlock could still occur if perProjectInfo is removed concurrent before entering the lock
-// try {
-// project.getResolvedClasspath(true); // trigger all possible container/variable initialization outside the model lock
-// } catch (JavaModelException e) {
-// // project is not accessible or is not a java project
-// }
-// }
-//
-// // element info creation is done inside a lock on the JavaModelManager
-// JavaModelManager manager;
-// synchronized(manager = JavaModelManager.getJavaModelManager()){
-// Object info = manager.getInfo(this);
-// if (info == null) {
-// openHierarchy();
-// info= manager.getInfo(this);
-// if (info == null) {
-// throw newNotPresentException();
-// }
-// }
-// return info;
-// }
+ IJavaProject project = getJavaProject();
+ if (project != null && !project.isOpen()) {
+ // TODO: need to revisit, since deadlock could still occur if perProjectInfo is removed concurrent before entering the lock
+ try {
+ project.getResolvedClasspath(true); // trigger all possible container/variable initialization outside the model lock
+ } catch (JavaModelException e) {
+ // project is not accessible or is not a java project
+ }
+ }
+
+ // element info creation is done inside a lock on the JavaModelManager
+ JavaModelManager manager;
+ synchronized(manager = JavaModelManager.getJavaModelManager()){
+ Object info = manager.getInfo(this);
+ if (info == null) {
+ openHierarchy();
+ info= manager.getInfo(this);
+ if (info == null) {
+ throw newNotPresentException();
+ }
+ }
+ return info;
+ }
}
/**
* @see IAdaptable
@@ -411,30 +420,30 @@ return null;
* known to be within this element's source range already, and if no finer
* grained element is found at the position, this element is returned.
*/
-// protected IJavaElement getSourceElementAt(int position) throws JavaModelException {
-// if (this instanceof ISourceReference) {
-// IJavaElement[] children = getChildren();
-// int i;
-// for (i = 0; i < children.length; i++) {
-// IJavaElement aChild = children[i];
-// if (aChild instanceof SourceRefElement) {
-// SourceRefElement child = (SourceRefElement) children[i];
-// ISourceRange range = child.getSourceRange();
-// if (position < range.getOffset() + range.getLength() && position >= range.getOffset()) {
-// if (child instanceof IParent) {
-// return child.getSourceElementAt(position);
-// } else {
-// return child;
-// }
-// }
-// }
-// }
-// } else {
-// // should not happen
-// Assert.isTrue(false);
-// }
-// return this;
-// }
+ protected IJavaElement getSourceElementAt(int position) throws JavaModelException {
+ if (this instanceof ISourceReference) {
+ IJavaElement[] children = getChildren();
+ int i;
+ for (i = 0; i < children.length; i++) {
+ IJavaElement aChild = children[i];
+ if (aChild instanceof SourceRefElement) {
+ SourceRefElement child = (SourceRefElement) children[i];
+ ISourceRange range = child.getSourceRange();
+ if (position < range.getOffset() + range.getLength() && position >= range.getOffset()) {
+ if (child instanceof IParent) {
+ return child.getSourceElementAt(position);
+ } else {
+ return child;
+ }
+ }
+ }
+ }
+ } else {
+ // should not happen
+ Assert.isTrue(false);
+ }
+ return this;
+ }
/**
* Returns the SourceMapper facility for this element, or
* null
if this element does not have a
@@ -475,35 +484,35 @@ return null;
/**
* @see IJavaElement
*/
-// public boolean isStructureKnown() throws JavaModelException {
-// return ((JavaElementInfo)getElementInfo()).isStructureKnown();
-// }
+ public boolean isStructureKnown() throws JavaModelException {
+ return ((JavaElementInfo)getElementInfo()).isStructureKnown();
+ }
/**
* Creates and returns and not present exception for this element.
*/
protected JavaModelException newNotPresentException() {
return new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST, this));
}
-// /**
-// * Opens this element and all parents that are not already open.
-// *
-// * @exception JavaModelException this element is not present or accessible
-// */
-// protected void openHierarchy() throws JavaModelException {
-// if (this instanceof IOpenable) {
-// ((Openable) this).openWhenClosed(null);
-// } else {
-// Openable openableParent = (Openable)getOpenableParent();
-// if (openableParent != null) {
-// JavaElementInfo openableParentInfo = (JavaElementInfo) JavaModelManager.getJavaModelManager().getInfo((IJavaElement) openableParent);
-// if (openableParentInfo == null) {
-// openableParent.openWhenClosed(null);
-// } else {
-// throw newNotPresentException();
-// }
-// }
-// }
-// }
+ /**
+ * Opens this element and all parents that are not already open.
+ *
+ * @exception JavaModelException this element is not present or accessible
+ */
+ protected void openHierarchy() throws JavaModelException {
+ if (this instanceof IOpenable) {
+ ((Openable) this).openWhenClosed(null);
+ } else {
+ Openable openableParent = (Openable)getOpenableParent();
+ if (openableParent != null) {
+ JavaElementInfo openableParentInfo = (JavaElementInfo) JavaModelManager.getJavaModelManager().getInfo((IJavaElement) openableParent);
+ if (openableParentInfo == null) {
+ openableParent.openWhenClosed(null);
+ } else {
+ throw newNotPresentException();
+ }
+ }
+ }
+ }
/**
* This element has just been opened. Do any necessary setup.
*/
@@ -518,48 +527,48 @@ return null;
* Removes all cached info from the Java Model, including all children,
* but does not close this element.
*/
-// protected void removeInfo() {
-// Object info = JavaModelManager.getJavaModelManager().peekAtInfo(this);
-// if (info != null) {
-// if (this instanceof IParent) {
-// IJavaElement[] children = ((JavaElementInfo)info).getChildren();
-// for (int i = 0, size = children.length; i < size; ++i) {
-// JavaElement child = (JavaElement) children[i];
-// child.removeInfo();
-// }
-// }
-// JavaModelManager.getJavaModelManager().removeInfo(this);
-// }
-// }
-// /**
-// * Returns a copy of this element rooted at the given project.
-// */
+ protected void removeInfo() {
+ Object info = JavaModelManager.getJavaModelManager().peekAtInfo(this);
+ if (info != null) {
+ if (this instanceof IParent) {
+ IJavaElement[] children = ((JavaElementInfo)info).getChildren();
+ for (int i = 0, size = children.length; i < size; ++i) {
+ JavaElement child = (JavaElement) children[i];
+ child.removeInfo();
+ }
+ }
+ JavaModelManager.getJavaModelManager().removeInfo(this);
+ }
+ }
+ /**
+ * Returns a copy of this element rooted at the given project.
+ */
public abstract IJavaElement rootedAt(IJavaProject project);
-// /**
-// * Runs a Java Model Operation
-// */
-// public static void runOperation(JavaModelOperation operation, IProgressMonitor monitor) throws JavaModelException {
-// try {
-// if (operation.isReadOnly() || ResourcesPlugin.getWorkspace().isTreeLocked()) {
-// operation.run(monitor);
-// } else {
-// // use IWorkspace.run(...) to ensure that a build will be done in autobuild mode
-// ResourcesPlugin.getWorkspace().run(operation, monitor);
-// }
-// } catch (CoreException ce) {
-// if (ce instanceof JavaModelException) {
-// throw (JavaModelException)ce;
-// } else {
-// if (ce.getStatus().getCode() == IResourceStatus.OPERATION_FAILED) {
-// Throwable e= ce.getStatus().getException();
-// if (e instanceof JavaModelException) {
-// throw (JavaModelException) e;
-// }
-// }
-// throw new JavaModelException(ce);
-// }
-// }
-// }
+ /**
+ * Runs a Java Model Operation
+ */
+ public static void runOperation(JavaModelOperation operation, IProgressMonitor monitor) throws JavaModelException {
+ try {
+ if (operation.isReadOnly() || ResourcesPlugin.getWorkspace().isTreeLocked()) {
+ operation.run(monitor);
+ } else {
+ // use IWorkspace.run(...) to ensure that a build will be done in autobuild mode
+ ResourcesPlugin.getWorkspace().run(operation, monitor);
+ }
+ } catch (CoreException ce) {
+ if (ce instanceof JavaModelException) {
+ throw (JavaModelException)ce;
+ } else {
+ if (ce.getStatus().getCode() == IResourceStatus.OPERATION_FAILED) {
+ Throwable e= ce.getStatus().getException();
+ if (e instanceof JavaModelException) {
+ throw (JavaModelException) e;
+ }
+ }
+ throw new JavaModelException(ce);
+ }
+ }
+ }
/**
* Sets the occurrence count of the handle.
*/
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaElementDeltaBuilder.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaElementDeltaBuilder.java
new file mode 100644
index 0000000..0376079
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaElementDeltaBuilder.java
@@ -0,0 +1,409 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+import net.sourceforge.phpdt.core.IJavaElement;
+import net.sourceforge.phpdt.core.IJavaElementDelta;
+import net.sourceforge.phpdt.core.IParent;
+import net.sourceforge.phpdt.core.JavaModelException;
+import net.sourceforge.phpdt.core.compiler.CharOperation;
+
+
+/**
+ * A java element delta biulder creates a java element delta on
+ * a java element between the version of the java element
+ * at the time the comparator was created and the current version
+ * of the java element.
+ *
+ * It performs this operation by locally caching the contents of
+ * the java element when it is created. When the method
+ * createDeltas() is called, it creates a delta over the cached
+ * contents and the new contents.
+ */
+public class JavaElementDeltaBuilder {
+ /**
+ * The java element handle
+ */
+ IJavaElement javaElement;
+
+ /**
+ * The maximum depth in the java element children we should look into
+ */
+ int maxDepth = Integer.MAX_VALUE;
+
+ /**
+ * The old handle to info relationships
+ */
+ Map infos;
+
+ /**
+ * The old position info
+ */
+ Map oldPositions;
+
+ /**
+ * The new position info
+ */
+ Map newPositions;
+
+ /**
+ * Change delta
+ */
+ JavaElementDelta delta;
+
+ /**
+ * List of added elements
+ */
+ ArrayList added;
+
+ /**
+ * List of removed elements
+ */
+ ArrayList removed;
+
+ /**
+ * Doubly linked list item
+ */
+ class ListItem {
+ public IJavaElement previous;
+ public IJavaElement next;
+
+ public ListItem(IJavaElement previous, IJavaElement next) {
+ this.previous = previous;
+ this.next = next;
+ }
+ }
+/**
+ * Creates a java element comparator on a java element
+ * looking as deep as necessary.
+ */
+public JavaElementDeltaBuilder(IJavaElement javaElement) {
+ this.javaElement = javaElement;
+ this.initialize();
+ this.recordElementInfo(
+ javaElement,
+ (JavaModel)this.javaElement.getJavaModel(),
+ 0);
+}
+/**
+ * Creates a java element comparator on a java element
+ * looking only 'maxDepth' levels deep.
+ */
+public JavaElementDeltaBuilder(IJavaElement javaElement, int maxDepth) {
+ this.javaElement = javaElement;
+ this.maxDepth = maxDepth;
+ this.initialize();
+ this.recordElementInfo(
+ javaElement,
+ (JavaModel)this.javaElement.getJavaModel(),
+ 0);
+}
+/**
+ * Repairs the positioning information
+ * after an element has been added
+ */
+private void added(IJavaElement element) {
+ this.added.add(element);
+ ListItem current = this.getNewPosition(element);
+ ListItem previous = null, next = null;
+ if (current.previous != null)
+ previous = this.getNewPosition(current.previous);
+ if (current.next != null)
+ next = this.getNewPosition(current.next);
+ if (previous != null)
+ previous.next = current.next;
+ if (next != null)
+ next.previous = current.previous;
+}
+/**
+ * Builds the java element deltas between the old content of the compilation
+ * unit and its new content.
+ */
+public void buildDeltas() {
+ this.recordNewPositions(this.javaElement, 0);
+ this.findAdditions(this.javaElement, 0);
+ this.findDeletions();
+ this.findChangesInPositioning(this.javaElement, 0);
+ this.trimDelta(this.delta);
+ if (this.delta.getAffectedChildren().length == 0) {
+ // this is a fine grained but not children affected -> mark as content changed
+ this.delta.contentChanged();
+ }
+}
+/**
+ * Finds elements which have been added or changed.
+ */
+private void findAdditions(IJavaElement newElement, int depth) {
+ JavaElementInfo oldInfo = this.getElementInfo(newElement);
+ if (oldInfo == null && depth < this.maxDepth) {
+ this.delta.added(newElement);
+ added(newElement);
+ } else {
+ this.removeElementInfo(newElement);
+ }
+
+ if (depth >= this.maxDepth) {
+ // mark element as changed
+ this.delta.changed(newElement, IJavaElementDelta.F_CONTENT);
+ return;
+ }
+
+ JavaElementInfo newInfo = null;
+ try {
+ newInfo = (JavaElementInfo)((JavaElement)newElement).getElementInfo();
+ } catch (JavaModelException npe) {
+ return;
+ }
+
+ this.findContentChange(oldInfo, newInfo, newElement);
+
+ if (oldInfo != null && newElement instanceof IParent) {
+
+ IJavaElement[] children = newInfo.getChildren();
+ if (children != null) {
+ int length = children.length;
+ for(int i = 0; i < length; i++) {
+ this.findAdditions(children[i], depth + 1);
+ }
+ }
+ }
+}
+/**
+ * Looks for changed positioning of elements.
+ */
+private void findChangesInPositioning(IJavaElement element, int depth) {
+ if (depth >= this.maxDepth || this.added.contains(element) || this.removed.contains(element))
+ return;
+
+ if (!isPositionedCorrectly(element)) {
+ this.delta.changed(element, IJavaElementDelta.F_REORDER);
+ }
+
+ if (element instanceof IParent) {
+ JavaElementInfo info = null;
+ try {
+ info = (JavaElementInfo)((JavaElement)element).getElementInfo();
+ } catch (JavaModelException npe) {
+ return;
+ }
+
+ IJavaElement[] children = info.getChildren();
+ if (children != null) {
+ int length = children.length;
+ for(int i = 0; i < length; i++) {
+ this.findChangesInPositioning(children[i], depth + 1);
+ }
+ }
+ }
+}
+/**
+ * The elements are equivalent, but might have content changes.
+ */
+private void findContentChange(JavaElementInfo oldInfo, JavaElementInfo newInfo, IJavaElement newElement) {
+ if (oldInfo instanceof MemberElementInfo && newInfo instanceof MemberElementInfo) {
+ if (((MemberElementInfo)oldInfo).getModifiers() != ((MemberElementInfo)newInfo).getModifiers()) {
+ this.delta.changed(newElement, IJavaElementDelta.F_MODIFIERS);
+ } else if (oldInfo instanceof SourceMethodElementInfo && newInfo instanceof SourceMethodElementInfo) {
+ if (!CharOperation.equals(
+ ((SourceMethodElementInfo)oldInfo).getReturnTypeName(),
+ ((SourceMethodElementInfo)newInfo).getReturnTypeName())) {
+ this.delta.changed(newElement, IJavaElementDelta.F_CONTENT);
+ }
+ } else if (oldInfo instanceof SourceFieldElementInfo && newInfo instanceof SourceFieldElementInfo) {
+ if (!CharOperation.equals(
+ ((SourceFieldElementInfo)oldInfo).getTypeName(),
+ ((SourceFieldElementInfo)newInfo).getTypeName())) {
+ this.delta.changed(newElement, IJavaElementDelta.F_CONTENT);
+ }
+ }
+ }
+ if (oldInfo instanceof SourceTypeElementInfo && newInfo instanceof SourceTypeElementInfo) {
+ SourceTypeElementInfo oldSourceTypeInfo = (SourceTypeElementInfo)oldInfo;
+ SourceTypeElementInfo newSourceTypeInfo = (SourceTypeElementInfo)newInfo;
+ if (!CharOperation.equals(oldSourceTypeInfo.getSuperclassName(), newSourceTypeInfo.getSuperclassName())
+ || !CharOperation.equals(oldSourceTypeInfo.getInterfaceNames(), newSourceTypeInfo.getInterfaceNames())) {
+ this.delta.changed(newElement, IJavaElementDelta.F_SUPER_TYPES);
+ }
+ }
+}
+/**
+ * Adds removed deltas for any handles left in the table
+ */
+private void findDeletions() {
+ Iterator iter = this.infos.keySet().iterator();
+ while(iter.hasNext()) {
+ IJavaElement element = (IJavaElement)iter.next();
+ this.delta.removed(element);
+ this.removed(element);
+ }
+}
+private JavaElementInfo getElementInfo(IJavaElement element) {
+ return (JavaElementInfo)this.infos.get(element);
+}
+private ListItem getNewPosition(IJavaElement element) {
+ return (ListItem)this.newPositions.get(element);
+}
+private ListItem getOldPosition(IJavaElement element) {
+ return (ListItem)this.oldPositions.get(element);
+}
+private void initialize() {
+ this.infos = new HashMap(20);
+ this.oldPositions = new HashMap(20);
+ this.newPositions = new HashMap(20);
+ this.putOldPosition(this.javaElement, new ListItem(null, null));
+ this.putNewPosition(this.javaElement, new ListItem(null, null));
+ this.delta = new JavaElementDelta(javaElement);
+
+ // if building a delta on a compilation unit or below,
+ // it's a fine grained delta
+ if (javaElement.getElementType() >= IJavaElement.COMPILATION_UNIT) {
+ this.delta.fineGrained();
+ }
+
+ this.added = new ArrayList(5);
+ this.removed = new ArrayList(5);
+}
+/**
+ * Inserts position information for the elements into the new or old positions table
+ */
+private void insertPositions(IJavaElement[] elements, boolean isNew) {
+ int length = elements.length;
+ IJavaElement previous = null, current = null, next = (length > 0) ? elements[0] : null;
+ for(int i = 0; i < length; i++) {
+ previous = current;
+ current = next;
+ next = (i + 1 < length) ? elements[i + 1] : null;
+ if (isNew) {
+ this.putNewPosition(current, new ListItem(previous, next));
+ } else {
+ this.putOldPosition(current, new ListItem(previous, next));
+ }
+ }
+}
+/**
+ * Returns whether the elements position has not changed.
+ */
+private boolean isPositionedCorrectly(IJavaElement element) {
+ ListItem oldListItem = this.getOldPosition(element);
+ if (oldListItem == null) return false;
+
+ ListItem newListItem = this.getNewPosition(element);
+ if (newListItem == null) return false;
+
+ IJavaElement oldPrevious = oldListItem.previous;
+ IJavaElement newPrevious = newListItem.previous;
+ if (oldPrevious == null) {
+ return newPrevious == null;
+ } else {
+ return oldPrevious.equals(newPrevious);
+ }
+}
+private void putElementInfo(IJavaElement element, JavaElementInfo info) {
+ this.infos.put(element, info);
+}
+private void putNewPosition(IJavaElement element, ListItem position) {
+ this.newPositions.put(element, position);
+}
+private void putOldPosition(IJavaElement element, ListItem position) {
+ this.oldPositions.put(element, position);
+}
+/**
+ * Records this elements info, and attempts
+ * to record the info for the children.
+ */
+private void recordElementInfo(IJavaElement element, JavaModel model, int depth) {
+ if (depth >= this.maxDepth) {
+ return;
+ }
+ JavaElementInfo info = null;//(JavaElementInfo)JavaModelManager.getJavaModelManager().getInfo(element);
+ if (info == null) // no longer in the java model.
+ return;
+ this.putElementInfo(element, info);
+
+ if (element instanceof IParent) {
+ IJavaElement[] children = info.getChildren();
+ if (children != null) {
+ insertPositions(children, false);
+ for(int i = 0, length = children.length; i < length; i++)
+ recordElementInfo(children[i], model, depth + 1);
+ }
+ }
+}
+/**
+ * Fills the newPositions hashtable with the new position information
+ */
+private void recordNewPositions(IJavaElement newElement, int depth) {
+ if (depth < this.maxDepth && newElement instanceof IParent) {
+ JavaElementInfo info = null;
+ try {
+ info = (JavaElementInfo)((JavaElement)newElement).getElementInfo();
+ } catch (JavaModelException npe) {
+ return;
+ }
+
+ IJavaElement[] children = info.getChildren();
+ if (children != null) {
+ insertPositions(children, true);
+ for(int i = 0, length = children.length; i < length; i++) {
+ recordNewPositions(children[i], depth + 1);
+ }
+ }
+ }
+}
+/**
+ * Repairs the positioning information
+ * after an element has been removed
+ */
+private void removed(IJavaElement element) {
+ this.removed.add(element);
+ ListItem current = this.getOldPosition(element);
+ ListItem previous = null, next = null;
+ if (current.previous != null)
+ previous = this.getOldPosition(current.previous);
+ if (current.next != null)
+ next = this.getOldPosition(current.next);
+ if (previous != null)
+ previous.next = current.next;
+ if (next != null)
+ next.previous = current.previous;
+
+}
+private void removeElementInfo(IJavaElement element) {
+ this.infos.remove(element);
+}
+public String toString() {
+ StringBuffer buffer = new StringBuffer();
+ buffer.append("Built delta:\n"); //$NON-NLS-1$
+ buffer.append(this.delta.toString());
+ return buffer.toString();
+}
+/**
+ * Trims deletion deltas to only report the highest level of deletion
+ */
+private void trimDelta(JavaElementDelta delta) {
+ if (delta.getKind() == IJavaElementDelta.REMOVED) {
+ IJavaElementDelta[] children = delta.getAffectedChildren();
+ for(int i = 0, length = children.length; i < length; i++) {
+ delta.removeAffectedChild((JavaElementDelta)children[i]);
+ }
+ } else {
+ IJavaElementDelta[] children = delta.getAffectedChildren();
+ for(int i = 0, length = children.length; i < length; i++) {
+ trimDelta((JavaElementDelta)children[i]);
+ }
+ }
+}
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaElementRequestor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaElementRequestor.java
new file mode 100644
index 0000000..88201b0
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaElementRequestor.java
@@ -0,0 +1,225 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core;
+
+import java.util.ArrayList;
+
+import net.sourceforge.phpdt.core.IField;
+import net.sourceforge.phpdt.core.IMethod;
+import net.sourceforge.phpdt.core.IPackageFragment;
+import net.sourceforge.phpdt.core.IType;
+
+/**
+ * @see IJavaElementRequestor
+ */
+
+public class JavaElementRequestor implements IJavaElementRequestor {
+ /**
+ * True if this requestor no longer wants to receive
+ * results from its IRequestorNameLookup
.
+ */
+ protected boolean fCanceled= false;
+
+ /**
+ * A collection of the resulting fields, or null
+ * if no field results have been received.
+ */
+ protected ArrayList fFields= null;
+
+ /**
+ * A collection of the resulting initializers, or null
+ * if no initializer results have been received.
+ */
+ protected ArrayList fInitializers= null;
+
+ /**
+ * A collection of the resulting member types, or null
+ * if no member type results have been received.
+ */
+ protected ArrayList fMemberTypes= null;
+
+ /**
+ * A collection of the resulting methods, or null
+ * if no method results have been received.
+ */
+ protected ArrayList fMethods= null;
+
+ /**
+ * A collection of the resulting package fragments, or null
+ * if no package fragment results have been received.
+ */
+ protected ArrayList fPackageFragments= null;
+
+ /**
+ * A collection of the resulting types, or null
+ * if no type results have been received.
+ */
+ protected ArrayList fTypes= null;
+
+ /**
+ * Empty arrays used for efficiency
+ */
+ protected static IField[] fgEmptyFieldArray= new IField[0];
+// protected static IInitializer[] fgEmptyInitializerArray= new IInitializer[0];
+ protected static IType[] fgEmptyTypeArray= new IType[0];
+ protected static IPackageFragment[] fgEmptyPackageFragmentArray= new IPackageFragment[0];
+ protected static IMethod[] fgEmptyMethodArray= new IMethod[0];
+/**
+ * @see IJavaElementRequestor
+ */
+public void acceptField(IField field) {
+ if (fFields == null) {
+ fFields= new ArrayList();
+ }
+ fFields.add(field);
+}
+/**
+ * @see IJavaElementRequestor
+ */
+//public void acceptInitializer(IInitializer initializer) {
+// if (fInitializers == null) {
+// fInitializers= new ArrayList();
+// }
+// fInitializers.add(initializer);
+//}
+/**
+ * @see IJavaElementRequestor
+ */
+public void acceptMemberType(IType type) {
+ if (fMemberTypes == null) {
+ fMemberTypes= new ArrayList();
+ }
+ fMemberTypes.add(type);
+}
+/**
+ * @see IJavaElementRequestor
+ */
+public void acceptMethod(IMethod method) {
+ if (fMethods == null) {
+ fMethods = new ArrayList();
+ }
+ fMethods.add(method);
+}
+/**
+ * @see IJavaElementRequestor
+ */
+public void acceptPackageFragment(IPackageFragment packageFragment) {
+ if (fPackageFragments== null) {
+ fPackageFragments= new ArrayList();
+ }
+ fPackageFragments.add(packageFragment);
+}
+/**
+ * @see IJavaElementRequestor
+ */
+public void acceptType(IType type) {
+ if (fTypes == null) {
+ fTypes= new ArrayList();
+ }
+ fTypes.add(type);
+}
+/**
+ * @see IJavaElementRequestor
+ */
+public IField[] getFields() {
+ if (fFields == null) {
+ return fgEmptyFieldArray;
+ }
+ int size = fFields.size();
+ IField[] results = new IField[size];
+ fFields.toArray(results);
+ return results;
+}
+/**
+ * @see IJavaElementRequestor
+ */
+//public IInitializer[] getInitializers() {
+// if (fInitializers == null) {
+// return fgEmptyInitializerArray;
+// }
+// int size = fInitializers.size();
+// IInitializer[] results = new IInitializer[size];
+// fInitializers.toArray(results);
+// return results;
+//}
+/**
+ * @see IJavaElementRequestor
+ */
+public IType[] getMemberTypes() {
+ if (fMemberTypes == null) {
+ return fgEmptyTypeArray;
+ }
+ int size = fMemberTypes.size();
+ IType[] results = new IType[size];
+ fMemberTypes.toArray(results);
+ return results;
+}
+/**
+ * @see IJavaElementRequestor
+ */
+public IMethod[] getMethods() {
+ if (fMethods == null) {
+ return fgEmptyMethodArray;
+ }
+ int size = fMethods.size();
+ IMethod[] results = new IMethod[size];
+ fMethods.toArray(results);
+ return results;
+}
+/**
+ * @see IJavaElementRequestor
+ */
+public IPackageFragment[] getPackageFragments() {
+ if (fPackageFragments== null) {
+ return fgEmptyPackageFragmentArray;
+ }
+ int size = fPackageFragments.size();
+ IPackageFragment[] results = new IPackageFragment[size];
+ fPackageFragments.toArray(results);
+ return results;
+}
+/**
+ * @see IJavaElementRequestor
+ */
+public IType[] getTypes() {
+ if (fTypes== null) {
+ return fgEmptyTypeArray;
+ }
+ int size = fTypes.size();
+ IType[] results = new IType[size];
+ fTypes.toArray(results);
+ return results;
+}
+/**
+ * @see IJavaElementRequestor
+ */
+public boolean isCanceled() {
+ return fCanceled;
+}
+/**
+ * Reset the state of this requestor.
+ */
+public void reset() {
+ fCanceled = false;
+ fFields = null;
+ fInitializers = null;
+ fMemberTypes = null;
+ fMethods = null;
+ fPackageFragments = null;
+ fTypes = null;
+}
+/**
+ * Sets the #isCanceled state of this requestor to true or false.
+ */
+public void setCanceled(boolean b) {
+ fCanceled= b;
+}
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaModel.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaModel.java
index 41c449f..daa7f05 100644
--- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaModel.java
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaModel.java
@@ -10,14 +10,17 @@
*******************************************************************************/
package net.sourceforge.phpdt.internal.core;
+import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
+import java.util.Map;
import net.sourceforge.phpdt.core.IJavaElement;
import net.sourceforge.phpdt.core.IJavaModel;
import net.sourceforge.phpdt.core.IJavaProject;
import net.sourceforge.phpdt.core.JavaModelException;
+import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
@@ -25,6 +28,7 @@ import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
+import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.util.Assert;
@@ -60,55 +64,55 @@ protected JavaModel() throws Error {
/*
* @see IJavaModel
*/
-//public boolean contains(IResource resource) {
-// switch (resource.getType()) {
-// case IResource.ROOT:
-// case IResource.PROJECT:
-// return true;
-// }
-// // file or folder
-// IJavaProject[] projects;
-// try {
-// projects = this.getJavaProjects();
-// } catch (JavaModelException e) {
-// return false;
-// }
-// for (int i = 0, length = projects.length; i < length; i++) {
-// JavaProject project = (JavaProject)projects[i];
-//
-// if (!project.contains(resource)) {
-// return false;
-// }
-// }
-// return true;
-//}
+public boolean contains(IResource resource) {
+ switch (resource.getType()) {
+ case IResource.ROOT:
+ case IResource.PROJECT:
+ return true;
+ }
+ // file or folder
+ IJavaProject[] projects;
+ try {
+ projects = this.getJavaProjects();
+ } catch (JavaModelException e) {
+ return false;
+ }
+ for (int i = 0, length = projects.length; i < length; i++) {
+ JavaProject project = (JavaProject)projects[i];
+
+ if (!project.contains(resource)) {
+ return false;
+ }
+ }
+ return true;
+}
/**
* @see IJavaModel
*/
-//public void copy(IJavaElement[] elements, IJavaElement[] containers, IJavaElement[] siblings, String[] renamings, boolean force, IProgressMonitor monitor) throws JavaModelException {
-// if (elements != null && elements.length > 0 && elements[0] != null && elements[0].getElementType() < IJavaElement.TYPE) {
-// runOperation(new CopyResourceElementsOperation(elements, containers, force), elements, siblings, renamings, monitor);
-// } else {
-// runOperation(new CopyElementsOperation(elements, containers, force), elements, siblings, renamings, monitor);
-// }
-//}
+public void copy(IJavaElement[] elements, IJavaElement[] containers, IJavaElement[] siblings, String[] renamings, boolean force, IProgressMonitor monitor) throws JavaModelException {
+ if (elements != null && elements.length > 0 && elements[0] != null && elements[0].getElementType() < IJavaElement.TYPE) {
+ runOperation(new CopyResourceElementsOperation(elements, containers, force), elements, siblings, renamings, monitor);
+ } else {
+ runOperation(new CopyElementsOperation(elements, containers, force), elements, siblings, renamings, monitor);
+ }
+}
/**
* Returns a new element info for this element.
*/
-//protected OpenableElementInfo createElementInfo() {
-// return new JavaModelInfo();
-//}
+protected OpenableElementInfo createElementInfo() {
+ return new JavaModelInfo();
+}
/**
* @see IJavaModel
*/
-//public void delete(IJavaElement[] elements, boolean force, IProgressMonitor monitor) throws JavaModelException {
-// if (elements != null && elements.length > 0 && elements[0] != null && elements[0].getElementType() < IJavaElement.TYPE) {
-// runOperation(new DeleteResourceElementsOperation(elements, force), monitor);
-// } else {
-// runOperation(new DeleteElementsOperation(elements, force), monitor);
-// }
-//}
+public void delete(IJavaElement[] elements, boolean force, IProgressMonitor monitor) throws JavaModelException {
+ if (elements != null && elements.length > 0 && elements[0] != null && elements[0].getElementType() < IJavaElement.TYPE) {
+ runOperation(new DeleteResourceElementsOperation(elements, force), monitor);
+ } else {
+ runOperation(new DeleteElementsOperation(elements, force), monitor);
+ }
+}
/**
* Finds the given project in the list of the java model's children.
* Returns null if not found.
@@ -136,23 +140,23 @@ public static void flushExternalFileCache() {
/**
*/
-//protected boolean generateInfos(
-// OpenableElementInfo info,
-// IProgressMonitor pm,
-// Map newElements,
-// IResource underlyingResource) throws JavaModelException {
-//
-// JavaModelManager.getJavaModelManager().putInfo(this, info);
-// // determine my children
-// IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
-// for (int i = 0, max = projects.length; i < max; i++) {
-// IProject project = projects[i];
-// if (JavaProject.hasJavaNature(project)) {
-// info.addChild(getJavaProject(project));
-// }
-// }
-// return true;
-//}
+protected boolean generateInfos(
+ OpenableElementInfo info,
+ IProgressMonitor pm,
+ Map newElements,
+ IResource underlyingResource) throws JavaModelException {
+
+ JavaModelManager.getJavaModelManager().putInfo(this, info);
+ // determine my children
+ IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
+ for (int i = 0, max = projects.length; i < max; i++) {
+ IProject project = projects[i];
+ if (JavaProject.hasJavaNature(project)) {
+ info.addChild(getJavaProject(project));
+ }
+ }
+ return true;
+}
/**
* Returns the IJavaElement
represented by the String
* memento.
@@ -425,13 +429,13 @@ public IWorkspace getWorkspace() {
/**
* @see IJavaModel
*/
-//public void move(IJavaElement[] elements, IJavaElement[] containers, IJavaElement[] siblings, String[] renamings, boolean force, IProgressMonitor monitor) throws JavaModelException {
-// if (elements != null && elements.length > 0 && elements[0] != null && elements[0].getElementType() < IJavaElement.TYPE) {
-// runOperation(new MoveResourceElementsOperation(elements, containers, force), elements, siblings, renamings, monitor);
-// } else {
-// runOperation(new MoveElementsOperation(elements, containers, force), elements, siblings, renamings, monitor);
-// }
-//}
+public void move(IJavaElement[] elements, IJavaElement[] containers, IJavaElement[] siblings, String[] renamings, boolean force, IProgressMonitor monitor) throws JavaModelException {
+ if (elements != null && elements.length > 0 && elements[0] != null && elements[0].getElementType() < IJavaElement.TYPE) {
+ runOperation(new MoveResourceElementsOperation(elements, containers, force), elements, siblings, renamings, monitor);
+ } else {
+ runOperation(new MoveElementsOperation(elements, containers, force), elements, siblings, renamings, monitor);
+ }
+}
/**
* @see IJavaModel#refreshExternalArchives(IJavaElement[], IProgressMonitor)
@@ -446,16 +450,16 @@ public IWorkspace getWorkspace() {
/**
* @see IJavaModel
*/
-//public void rename(IJavaElement[] elements, IJavaElement[] destinations, String[] renamings, boolean force, IProgressMonitor monitor) throws JavaModelException {
-// MultiOperation op;
-// if (elements != null && elements.length > 0 && elements[0] != null && elements[0].getElementType() < IJavaElement.TYPE) {
-// op = new RenameResourceElementsOperation(elements, destinations, renamings, force);
-// } else {
-// op = new RenameElementsOperation(elements, destinations, renamings, force);
-// }
-//
-// runOperation(op, monitor);
-//}
+public void rename(IJavaElement[] elements, IJavaElement[] destinations, String[] renamings, boolean force, IProgressMonitor monitor) throws JavaModelException {
+ MultiOperation op;
+ if (elements != null && elements.length > 0 && elements[0] != null && elements[0].getElementType() < IJavaElement.TYPE) {
+ op = new RenameResourceElementsOperation(elements, destinations, renamings, force);
+ } else {
+ op = new RenameElementsOperation(elements, destinations, renamings, force);
+ }
+
+ runOperation(op, monitor);
+}
/*
* @see JavaElement#rootedAt(IJavaProject)
*/
@@ -466,15 +470,15 @@ public IJavaElement rootedAt(IJavaProject project) {
/**
* Configures and runs the MultiOperation
.
*/
-//protected void runOperation(MultiOperation op, IJavaElement[] elements, IJavaElement[] siblings, String[] renamings, IProgressMonitor monitor) throws JavaModelException {
-// op.setRenamings(renamings);
-// if (siblings != null) {
-// for (int i = 0; i < elements.length; i++) {
-// op.setInsertBefore(elements[i], siblings[i]);
-// }
-// }
-// runOperation(op, monitor);
-//}
+protected void runOperation(MultiOperation op, IJavaElement[] elements, IJavaElement[] siblings, String[] renamings, IProgressMonitor monitor) throws JavaModelException {
+ op.setRenamings(renamings);
+ if (siblings != null) {
+ for (int i = 0; i < elements.length; i++) {
+ op.setInsertBefore(elements[i], siblings[i]);
+ }
+ }
+ runOperation(op, monitor);
+}
/**
* @private Debugging purposes
*/
@@ -491,41 +495,41 @@ protected void toStringInfo(int tab, StringBuffer buffer, Object info) {
* or null if unbound
* Internal items must be referred to using container relative paths.
*/
-//public static Object getTarget(IContainer container, IPath path, boolean checkResourceExistence) {
-//
-// if (path == null) return null;
-//
-// // lookup - inside the container
-// if (path.getDevice() == null) { // container relative paths should not contain a device
-// // (see http://dev.eclipse.org/bugs/show_bug.cgi?id=18684)
-// // (case of a workspace rooted at d:\ )
-// IResource resource = container.findMember(path);
-// if (resource != null){
-// if (!checkResourceExistence ||resource.exists()) return resource;
-// return null;
-// }
-// }
-//
-// // if path is relative, it cannot be an external path
-// // (see http://dev.eclipse.org/bugs/show_bug.cgi?id=22517)
-// if (!path.isAbsolute()) return null;
-//
-// // lookup - outside the container
-// File externalFile = new File(path.toOSString());
-// if (!checkResourceExistence) {
-// return externalFile;
-// } else if (existingExternalFiles.contains(externalFile)) {
-// return externalFile;
-// } else {
-// if (JavaModelManager.ZIP_ACCESS_VERBOSE) {
-// System.out.println("(" + Thread.currentThread() + ") [JavaModel.getTarget(...)] Checking existence of " + path.toString()); //$NON-NLS-1$ //$NON-NLS-2$
-// }
-// if (externalFile.exists()) {
-// // cache external file
-// existingExternalFiles.add(externalFile);
-// return externalFile;
-// }
-// }
-// return null;
-//}
+public static Object getTarget(IContainer container, IPath path, boolean checkResourceExistence) {
+
+ if (path == null) return null;
+
+ // lookup - inside the container
+ if (path.getDevice() == null) { // container relative paths should not contain a device
+ // (see http://dev.eclipse.org/bugs/show_bug.cgi?id=18684)
+ // (case of a workspace rooted at d:\ )
+ IResource resource = container.findMember(path);
+ if (resource != null){
+ if (!checkResourceExistence ||resource.exists()) return resource;
+ return null;
+ }
+ }
+
+ // if path is relative, it cannot be an external path
+ // (see http://dev.eclipse.org/bugs/show_bug.cgi?id=22517)
+ if (!path.isAbsolute()) return null;
+
+ // lookup - outside the container
+ File externalFile = new File(path.toOSString());
+ if (!checkResourceExistence) {
+ return externalFile;
+ } else if (existingExternalFiles.contains(externalFile)) {
+ return externalFile;
+ } else {
+ if (JavaModelManager.ZIP_ACCESS_VERBOSE) {
+ System.out.println("(" + Thread.currentThread() + ") [JavaModel.getTarget(...)] Checking existence of " + path.toString()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ if (externalFile.exists()) {
+ // cache external file
+ existingExternalFiles.add(externalFile);
+ return externalFile;
+ }
+ }
+ return null;
+}
}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaModelCache.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaModelCache.java
new file mode 100644
index 0000000..4121aa3
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaModelCache.java
@@ -0,0 +1,150 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core;
+import java.util.HashMap;
+import java.util.Map;
+
+import net.sourceforge.phpdt.core.IJavaElement;
+
+/**
+ * The cache of java elements to their respective info.
+ */
+public class JavaModelCache {
+ public static final int PKG_CACHE_SIZE = 500;
+ public static final int OPENABLE_CACHE_SIZE = 2000;
+
+ /**
+ * Active Java Model Info
+ */
+ protected JavaModelInfo modelInfo;
+
+ /**
+ * Cache of open projects and package fragment roots.
+ */
+ protected Map projectAndRootCache;
+
+ /**
+ * Cache of open package fragments
+ */
+ protected Map pkgCache;
+
+ /**
+ * Cache of open compilation unit and class files
+ */
+ protected OverflowingLRUCache openableCache;
+
+ /**
+ * Cache of open children of openable Java Model Java elements
+ */
+ protected Map childrenCache;
+
+public JavaModelCache() {
+ this.projectAndRootCache = new HashMap(50);
+ this.pkgCache = new HashMap(PKG_CACHE_SIZE);
+ this.openableCache = new ElementCache(OPENABLE_CACHE_SIZE);
+ this.childrenCache = new HashMap(OPENABLE_CACHE_SIZE*20); // average 20 chilren per openable
+}
+
+public double openableFillingRatio() {
+ return this.openableCache.fillingRatio();
+}
+public int pkgSize() {
+ return this.pkgCache.size();
+}
+
+/**
+ * Returns the info for the element.
+ */
+public Object getInfo(IJavaElement element) {
+ switch (element.getElementType()) {
+ case IJavaElement.JAVA_MODEL:
+ return this.modelInfo;
+ case IJavaElement.JAVA_PROJECT:
+ case IJavaElement.PACKAGE_FRAGMENT_ROOT:
+ return this.projectAndRootCache.get(element);
+ case IJavaElement.PACKAGE_FRAGMENT:
+ return this.pkgCache.get(element);
+ case IJavaElement.COMPILATION_UNIT:
+ case IJavaElement.CLASS_FILE:
+ return this.openableCache.get(element);
+ default:
+ return this.childrenCache.get(element);
+ }
+}
+
+/**
+ * Returns the info for this element without
+ * disturbing the cache ordering.
+ */
+protected Object peekAtInfo(IJavaElement element) {
+ switch (element.getElementType()) {
+ case IJavaElement.JAVA_MODEL:
+ return this.modelInfo;
+ case IJavaElement.JAVA_PROJECT:
+ case IJavaElement.PACKAGE_FRAGMENT_ROOT:
+ return this.projectAndRootCache.get(element);
+ case IJavaElement.PACKAGE_FRAGMENT:
+ return this.pkgCache.get(element);
+ case IJavaElement.COMPILATION_UNIT:
+ case IJavaElement.CLASS_FILE:
+ return this.openableCache.peek(element);
+ default:
+ return this.childrenCache.get(element);
+ }
+}
+
+/**
+ * Remember the info for the element.
+ */
+protected void putInfo(IJavaElement element, Object info) {
+ switch (element.getElementType()) {
+ case IJavaElement.JAVA_MODEL:
+ this.modelInfo = (JavaModelInfo) info;
+ break;
+ case IJavaElement.JAVA_PROJECT:
+ case IJavaElement.PACKAGE_FRAGMENT_ROOT:
+ this.projectAndRootCache.put(element, info);
+ break;
+ case IJavaElement.PACKAGE_FRAGMENT:
+ this.pkgCache.put(element, info);
+ break;
+ case IJavaElement.COMPILATION_UNIT:
+ case IJavaElement.CLASS_FILE:
+ this.openableCache.put(element, info);
+ break;
+ default:
+ this.childrenCache.put(element, info);
+ }
+}
+/**
+ * Removes the info of the element from the cache.
+ */
+protected void removeInfo(IJavaElement element) {
+ switch (element.getElementType()) {
+ case IJavaElement.JAVA_MODEL:
+ this.modelInfo = null;
+ break;
+ case IJavaElement.JAVA_PROJECT:
+ case IJavaElement.PACKAGE_FRAGMENT_ROOT:
+ this.projectAndRootCache.remove(element);
+ break;
+ case IJavaElement.PACKAGE_FRAGMENT:
+ this.pkgCache.remove(element);
+ break;
+ case IJavaElement.COMPILATION_UNIT:
+ case IJavaElement.CLASS_FILE:
+ this.openableCache.remove(element);
+ break;
+ default:
+ this.childrenCache.remove(element);
+ }
+}
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaModelInfo.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaModelInfo.java
new file mode 100644
index 0000000..b572012
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaModelInfo.java
@@ -0,0 +1,70 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core;
+
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.ResourcesPlugin;
+
+/**
+ * Implementation of IJavaModel. A Java Model is specific to a
+ * workspace.
+ *
+ * @see IJavaModel
+ */
+public class JavaModelInfo extends OpenableElementInfo {
+
+ /**
+ * A array with all the non-java projects contained by this model
+ */
+ Object[] nonJavaResources;
+
+/**
+ * Constructs a new Java Model Info
+ */
+protected JavaModelInfo() {
+}
+/**
+ * Compute the non-java resources contained in this java project.
+ */
+private Object[] computeNonJavaResources() {
+ IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
+ int length = projects.length;
+ Object[] nonJavaResources = null;
+ int index = 0;
+ for (int i = 0; i < length; i++) {
+ IProject project = projects[i];
+ if (!JavaProject.hasJavaNature(project)) {
+ if (nonJavaResources == null) {
+ nonJavaResources = new Object[length];
+ }
+ nonJavaResources[index++] = project;
+ }
+ }
+ if (index == 0) return NO_NON_JAVA_RESOURCES;
+ if (index < length) {
+ System.arraycopy(nonJavaResources, 0, nonJavaResources = new Object[index], 0, index);
+ }
+ return nonJavaResources;
+}
+
+/**
+ * Returns an array of non-java resources contained in the receiver.
+ */
+Object[] getNonJavaResources() {
+
+ Object[] nonJavaResources = this.nonJavaResources;
+ if (nonJavaResources == null) {
+ nonJavaResources = computeNonJavaResources();
+ this.nonJavaResources = nonJavaResources;
+ }
+ return nonJavaResources;
+}
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaModelManager.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaModelManager.java
index 6652089..0ab7de9 100644
--- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaModelManager.java
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaModelManager.java
@@ -11,9 +11,12 @@
package net.sourceforge.phpdt.internal.core;
import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
import java.io.DataInputStream;
+import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
+import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
@@ -25,16 +28,21 @@ import java.util.WeakHashMap;
import java.util.zip.ZipFile;
import net.sourceforge.phpdt.core.ElementChangedEvent;
+import net.sourceforge.phpdt.core.IClasspathEntry;
import net.sourceforge.phpdt.core.ICompilationUnit;
import net.sourceforge.phpdt.core.IElementChangedListener;
import net.sourceforge.phpdt.core.IJavaElement;
import net.sourceforge.phpdt.core.IJavaElementDelta;
+import net.sourceforge.phpdt.core.IJavaModel;
import net.sourceforge.phpdt.core.IJavaProject;
+import net.sourceforge.phpdt.core.IPackageFragment;
+import net.sourceforge.phpdt.core.IPackageFragmentRoot;
import net.sourceforge.phpdt.core.IWorkingCopy;
-import net.sourceforge.phpdt.core.JavaCore;
import net.sourceforge.phpdt.core.JavaModelException;
import net.sourceforge.phpdt.internal.ui.util.PHPFileUtil;
+import net.sourceforge.phpeclipse.PHPCore;
import net.sourceforge.phpeclipse.PHPeclipsePlugin;
+import net.sourceforge.phpeclipse.builder.PHPBuilder;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
@@ -56,6 +64,7 @@ import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
+import org.eclipse.core.runtime.Plugin;
import org.eclipse.core.runtime.Preferences;
import org.eclipse.core.runtime.Status;
@@ -81,7 +90,7 @@ public class JavaModelManager implements ISaveParticipant {
public static HashMap PreviousSessionVariables = new HashMap(5);
public static HashSet OptionNames = new HashSet(20);
public final static String CP_VARIABLE_PREFERENCES_PREFIX = PHPeclipsePlugin.PLUGIN_ID+".classpathVariable."; //$NON-NLS-1$
-// public final static String CP_CONTAINER_PREFERENCES_PREFIX = JavaCore.PLUGIN_ID+".classpathContainer."; //$NON-NLS-1$
+// public final static String CP_CONTAINER_PREFERENCES_PREFIX = PHPCore.PLUGIN_ID+".classpathContainer."; //$NON-NLS-1$
public final static String CP_ENTRY_IGNORE = "##null
* if the given resource is not on the classpath of the given project.
*/
-// public static IJavaElement determineIfOnClasspath(
-// IResource resource,
-// IJavaProject project) {
-//
-// IPath resourcePath = resource.getFullPath();
-// try {
-// IClasspathEntry[] entries =
-// Util.isJavaFileName(resourcePath.lastSegment())
-// ? project.getRawClasspath() // JAVA file can only live inside SRC folder (on the raw path)
-// : ((JavaProject)project).getResolvedClasspath(true);
-//
-// for (int i = 0; i < entries.length; i++) {
-// IClasspathEntry entry = entries[i];
-// if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) continue;
-// IPath rootPath = entry.getPath();
-// if (rootPath.equals(resourcePath)) {
-// return project.getPackageFragmentRoot(resource);
-// } else if (rootPath.isPrefixOf(resourcePath) && !Util.isExcluded(resource, ((ClasspathEntry)entry).fullExclusionPatternChars())) {
-// // given we have a resource child of the root, it cannot be a JAR pkg root
-// IPackageFragmentRoot root = ((JavaProject) project).getFolderPackageFragmentRoot(rootPath);
-// if (root == null) return null;
-// IPath pkgPath = resourcePath.removeFirstSegments(rootPath.segmentCount());
-// if (resource.getType() == IResource.FILE) {
-// // if the resource is a file, then remove the last segment which
-// // is the file name in the package
-// pkgPath = pkgPath.removeLastSegments(1);
-//
-// // don't check validity of package name (see http://bugs.eclipse.org/bugs/show_bug.cgi?id=26706)
-// String pkgName = pkgPath.toString().replace('/', '.');
-// return root.getPackageFragment(pkgName);
-// } else {
-// String pkgName = Util.packageName(pkgPath);
-// if (pkgName == null || JavaConventions.validatePackageName(pkgName).getSeverity() == IStatus.ERROR) {
-// return null;
-// }
-// return root.getPackageFragment(pkgName);
-// }
-// }
-// }
-// } catch (JavaModelException npe) {
-// return null;
-// }
-// return null;
-// }
+ public static IJavaElement determineIfOnClasspath(
+ IResource resource,
+ IJavaProject project) {
+
+ IPath resourcePath = resource.getFullPath();
+ try {
+ IClasspathEntry[] entries =
+ Util.isJavaFileName(resourcePath.lastSegment())
+ ? project.getRawClasspath() // JAVA file can only live inside SRC folder (on the raw path)
+ : ((JavaProject)project).getResolvedClasspath(true);
+
+ for (int i = 0; i < entries.length; i++) {
+ IClasspathEntry entry = entries[i];
+ if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) continue;
+ IPath rootPath = entry.getPath();
+ if (rootPath.equals(resourcePath)) {
+ return project.getPackageFragmentRoot(resource);
+ } else if (rootPath.isPrefixOf(resourcePath) && !Util.isExcluded(resource, ((ClasspathEntry)entry).fullExclusionPatternChars())) {
+ // given we have a resource child of the root, it cannot be a JAR pkg root
+ IPackageFragmentRoot root = ((JavaProject) project).getFolderPackageFragmentRoot(rootPath);
+ if (root == null) return null;
+ IPath pkgPath = resourcePath.removeFirstSegments(rootPath.segmentCount());
+ if (resource.getType() == IResource.FILE) {
+ // if the resource is a file, then remove the last segment which
+ // is the file name in the package
+ pkgPath = pkgPath.removeLastSegments(1);
+
+ // don't check validity of package name (see http://bugs.eclipse.org/bugs/show_bug.cgi?id=26706)
+ String pkgName = pkgPath.toString().replace('/', '.');
+ return root.getPackageFragment(pkgName);
+ } else {
+ String pkgName = Util.packageName(pkgPath);
+ if (pkgName == null){// || JavaConventions.validatePackageName(pkgName).getSeverity() == IStatus.ERROR) {
+ return null;
+ }
+ return root.getPackageFragment(pkgName);
+ }
+ }
+ }
+ } catch (JavaModelException npe) {
+ return null;
+ }
+ return null;
+ }
/**
* The singleton manager
@@ -455,7 +458,7 @@ return null;
/**
* Infos cache.
*/
-// protected JavaModelCache cache = new JavaModelCache();
+ protected JavaModelCache cache = new JavaModelCache();
/**
* Set of elements which are out of sync with their buffers.
@@ -525,8 +528,8 @@ return null;
public IProject project;
public Object savedState;
public boolean triedRead;
-// public IClasspathEntry[] classpath;
-// public IClasspathEntry[] lastResolvedClasspath;
+ public IClasspathEntry[] classpath;
+ public IClasspathEntry[] lastResolvedClasspath;
public Map resolvedPathToRawEntries; // reverse map from resolved path to raw entries
public IPath outputLocation;
public Preferences preferences;
@@ -578,7 +581,7 @@ return null;
/**
* Line separator to use throughout the JavaModel for any source edit operation
*/
- // public static String LINE_SEPARATOR = System.getProperty("line.separator"); //$NON-NLS-1$
+ public static String LINE_SEPARATOR = System.getProperty("line.separator"); //$NON-NLS-1$
/**
* Constructs a new JavaModelManager
*/
@@ -652,7 +655,7 @@ return null;
* Configure the plugin with respect to option settings defined in ".options" file
*/
public void configurePluginDebugOptions(){
- if(JavaCore.getPlugin().isDebugging()){
+ if(PHPCore.getPlugin().isDebugging()){
// TODO khartlage temp-del
String option = Platform.getDebugOption(BUILDER_DEBUG);
// if(option != null) JavaBuilder.DEBUG = option.equalsIgnoreCase("true") ; //$NON-NLS-1$
@@ -934,9 +937,9 @@ return null;
/**
* Returns the info for the element.
*/
-// public Object getInfo(IJavaElement element) {
-// return this.cache.getInfo(element);
-// }
+ public Object getInfo(IJavaElement element) {
+ return this.cache.getInfo(element);
+ }
/**
* Returns the handle to the active Java Model.
@@ -997,7 +1000,7 @@ return null;
JavaModelManager.PerProjectInfo info = getPerProjectInfo(project, false /* don't create info */);
if (info == null) {
if (!JavaProject.hasJavaNature(project)) {
- throw ((JavaProject)JavaCore.create(project)).newNotPresentException();
+ throw ((JavaProject)PHPCore.create(project)).newNotPresentException();
}
info = getPerProjectInfo(project, true /* create info */);
}
@@ -1007,12 +1010,12 @@ return null;
/**
* Returns the name of the variables for which an CP variable initializer is registered through an extension point
*/
-// public static String[] getRegisteredVariableNames(){
-//
-// Plugin jdtCorePlugin = JavaCore.getPlugin();
-// if (jdtCorePlugin == null) return null;
-//
-// ArrayList variableList = new ArrayList(5);
+ public static String[] getRegisteredVariableNames(){
+
+ Plugin jdtCorePlugin = PHPCore.getPlugin();
+ if (jdtCorePlugin == null) return null;
+
+ ArrayList variableList = new ArrayList(5);
// IExtensionPoint extension = jdtCorePlugin.getDescriptor().getExtensionPoint(JavaModelManager.CPVARIABLE_INITIALIZER_EXTPOINT_ID);
// if (extension != null) {
// IExtension[] extensions = extension.getExtensions();
@@ -1024,17 +1027,17 @@ return null;
// }
// }
// }
-// String[] variableNames = new String[variableList.size()];
-// variableList.toArray(variableNames);
-// return variableNames;
-// }
+ String[] variableNames = new String[variableList.size()];
+ variableList.toArray(variableNames);
+ return variableNames;
+ }
/**
* Returns the name of the container IDs for which an CP container initializer is registered through an extension point
*/
// public static String[] getRegisteredContainerIDs(){
//
-// Plugin jdtCorePlugin = JavaCore.getPlugin();
+// Plugin jdtCorePlugin = PHPCore.getPlugin();
// if (jdtCorePlugin == null) return null;
//
// ArrayList containerIDList = new ArrayList(5);
@@ -1059,7 +1062,7 @@ return null;
*/
private File getSerializationFile(IProject project) {
if (!project.exists()) return null;
- IPluginDescriptor descr= JavaCore.getJavaCore().getDescriptor();
+ IPluginDescriptor descr= PHPCore.getJavaCore().getDescriptor();
IPath workingLocation= project.getPluginWorkingLocation(descr);
return workingLocation.append("state.dat").toFile(); //$NON-NLS-1$
}
@@ -1091,18 +1094,18 @@ return null;
} else { // internal resource (not an IFile or not existing)
IPath location;
if (file.getType() != IResource.FILE || (location = file.getLocation()) == null) {
- throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Util.bind("file.notFound", path.toString()), null)); //$NON-NLS-1$
+ throw new CoreException(new Status(IStatus.ERROR, PHPCore.PLUGIN_ID, -1, Util.bind("file.notFound", path.toString()), null)); //$NON-NLS-1$
}
fileSystemPath= location.toOSString();
}
} else if (!path.isAbsolute()) {
file= root.getFile(path);
if (file == null || file.getType() != IResource.FILE) {
- throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Util.bind("file.notFound", path.toString()), null)); //$NON-NLS-1$
+ throw new CoreException(new Status(IStatus.ERROR, PHPCore.PLUGIN_ID, -1, Util.bind("file.notFound", path.toString()), null)); //$NON-NLS-1$
}
IPath location = file.getLocation();
if (location == null) {
- throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Util.bind("file.notFound", path.toString()), null)); //$NON-NLS-1$
+ throw new CoreException(new Status(IStatus.ERROR, PHPCore.PLUGIN_ID, -1, Util.bind("file.notFound", path.toString()), null)); //$NON-NLS-1$
}
fileSystemPath= location.toOSString();
} else {
@@ -1119,7 +1122,7 @@ return null;
}
return zipFile;
} catch (IOException e) {
- throw new CoreException(new Status(Status.ERROR, JavaCore.PLUGIN_ID, -1, Util.bind("status.IOException"), e)); //$NON-NLS-1$
+ throw new CoreException(new Status(Status.ERROR, PHPCore.PLUGIN_ID, -1, Util.bind("status.IOException"), e)); //$NON-NLS-1$
}
}
}
@@ -1127,7 +1130,7 @@ return null;
// public void loadVariablesAndContainers() throws CoreException {
//
// // backward compatibility, consider persistent property
-// QualifiedName qName = new QualifiedName(JavaCore.PLUGIN_ID, "variables"); //$NON-NLS-1$
+// QualifiedName qName = new QualifiedName(PHPCore.PLUGIN_ID, "variables"); //$NON-NLS-1$
// String xmlString = ResourcesPlugin.getWorkspace().getRoot().getPersistentProperty(qName);
//
// try {
@@ -1173,7 +1176,7 @@ return null;
// }
//
// // load variables and containers from preferences into cache
-// Preferences preferences = JavaCore.getPlugin().getPluginPreferences();
+// Preferences preferences = PHPCore.getPlugin().getPluginPreferences();
//
// // only get variable from preferences not set to their default
// String[] propertyNames = preferences.propertyNames();
@@ -1270,18 +1273,19 @@ return null;
* Returns the info for this element without
* disturbing the cache ordering.
*/ // TODO: should be synchronized, could answer unitialized info or if cache is in middle of rehash, could even answer distinct element info
-// protected Object peekAtInfo(IJavaElement element) {
-// return this.cache.peekAtInfo(element);
-// }
+ protected Object peekAtInfo(IJavaElement element) {
+ return this.cache.peekAtInfo(element);
+ }
/**
* @see ISaveParticipant
*/
public void prepareToSave(ISaveContext context) throws CoreException {
}
-// protected void putInfo(IJavaElement element, Object info) {
-// this.cache.putInfo(element, info);
-// }
+
+ protected void putInfo(IJavaElement element, Object info) {
+ this.cache.putInfo(element, info);
+ }
/**
* Reads the build state for the relevant project.
@@ -1293,14 +1297,14 @@ return null;
DataInputStream in= new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
try {
String pluginID= in.readUTF();
- if (!pluginID.equals(JavaCore.PLUGIN_ID))
+ if (!pluginID.equals(PHPCore.PLUGIN_ID))
throw new IOException(Util.bind("build.wrongFileFormat")); //$NON-NLS-1$
String kind= in.readUTF();
if (!kind.equals("STATE")) //$NON-NLS-1$
throw new IOException(Util.bind("build.wrongFileFormat")); //$NON-NLS-1$
+ if (in.readBoolean())
+ return PHPBuilder.readState(project, in);
// TODO khartlage temp-del
-// if (in.readBoolean())
-// return JavaBuilder.readState(project, in);
// if (JavaBuilder.DEBUG)
// System.out.println("Saved state thinks last build failed for " + project.getName()); //$NON-NLS-1$
} finally {
@@ -1308,7 +1312,7 @@ return null;
}
} catch (Exception e) {
e.printStackTrace();
- throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, "Error reading last build state for project "+ project.getName(), e)); //$NON-NLS-1$
+ throw new CoreException(new Status(IStatus.ERROR, PHPCore.PLUGIN_ID, Platform.PLUGIN_ERROR, "Error reading last build state for project "+ project.getName(), e)); //$NON-NLS-1$
}
}
return null;
@@ -1409,9 +1413,9 @@ return null;
}
}
-// protected void removeInfo(IJavaElement element) {
-// this.cache.removeInfo(element);
-// }
+ protected void removeInfo(IJavaElement element) {
+ this.cache.removeInfo(element);
+ }
public void removePerProjectInfo(JavaProject javaProject) {
synchronized(perProjectInfo) { // use the perProjectInfo collection as its own lock
@@ -1435,49 +1439,48 @@ return null;
if (context.getKind() == ISaveContext.SNAPSHOT) return;
// save built state
- // TODO khartlage temp-del
-// if (info.triedRead) saveBuiltState(info);
+ if (info.triedRead) saveBuiltState(info);
}
/**
* Saves the built state for the project.
*/
-// private void saveBuiltState(PerProjectInfo info) throws CoreException {
+ private void saveBuiltState(PerProjectInfo info) throws CoreException {
// if (JavaBuilder.DEBUG)
// System.out.println(Util.bind("build.saveStateProgress", info.project.getName())); //$NON-NLS-1$
-// File file = getSerializationFile(info.project);
-// if (file == null) return;
-// long t = System.currentTimeMillis();
-// try {
-// DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
-// try {
-// out.writeUTF(JavaCore.PLUGIN_ID);
-// out.writeUTF("STATE"); //$NON-NLS-1$
-// if (info.savedState == null) {
-// out.writeBoolean(false);
-// } else {
-// out.writeBoolean(true);
-// JavaBuilder.writeState(info.savedState, out);
-// }
-// } finally {
-// out.close();
-// }
-// } catch (RuntimeException e) {
-// try {file.delete();} catch(SecurityException se) {}
-// throw new CoreException(
-// new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR,
-// Util.bind("build.cannotSaveState", info.project.getName()), e)); //$NON-NLS-1$
-// } catch (IOException e) {
-// try {file.delete();} catch(SecurityException se) {}
-// throw new CoreException(
-// new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR,
-// Util.bind("build.cannotSaveState", info.project.getName()), e)); //$NON-NLS-1$
-// }
+ File file = getSerializationFile(info.project);
+ if (file == null) return;
+ long t = System.currentTimeMillis();
+ try {
+ DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
+ try {
+ out.writeUTF(PHPCore.PLUGIN_ID);
+ out.writeUTF("STATE"); //$NON-NLS-1$
+ if (info.savedState == null) {
+ out.writeBoolean(false);
+ } else {
+ out.writeBoolean(true);
+ PHPBuilder.writeState(info.savedState, out);
+ }
+ } finally {
+ out.close();
+ }
+ } catch (RuntimeException e) {
+ try {file.delete();} catch(SecurityException se) {}
+ throw new CoreException(
+ new Status(IStatus.ERROR, PHPCore.PLUGIN_ID, Platform.PLUGIN_ERROR,
+ Util.bind("build.cannotSaveState", info.project.getName()), e)); //$NON-NLS-1$
+ } catch (IOException e) {
+ try {file.delete();} catch(SecurityException se) {}
+ throw new CoreException(
+ new Status(IStatus.ERROR, PHPCore.PLUGIN_ID, Platform.PLUGIN_ERROR,
+ Util.bind("build.cannotSaveState", info.project.getName()), e)); //$NON-NLS-1$
+ }
// if (JavaBuilder.DEBUG) {
// t = System.currentTimeMillis() - t;
// System.out.println(Util.bind("build.saveStateComplete", String.valueOf(t))); //$NON-NLS-1$
// }
-// }
+ }
/**
* @see ISaveParticipant
@@ -1506,7 +1509,7 @@ return null;
if (vStats != null) {
IStatus[] stats= new IStatus[vStats.size()];
vStats.toArray(stats);
- throw new CoreException(new MultiStatus(JavaCore.PLUGIN_ID, IStatus.ERROR, stats, Util.bind("build.cannotSaveStates"), null)); //$NON-NLS-1$
+ throw new CoreException(new MultiStatus(PHPCore.PLUGIN_ID, IStatus.ERROR, stats, Util.bind("build.cannotSaveStates"), null)); //$NON-NLS-1$
}
}
@@ -1518,7 +1521,7 @@ return null;
// optional behaviour
// possible value of index 0 is Compute
- if (!JavaCore.COMPUTE.equals(JavaCore.getOption(JavaCore.CORE_JAVA_BUILD_ORDER))) return; // cannot be customized at project level
+ if (!PHPCore.COMPUTE.equals(PHPCore.getOption(PHPCore.CORE_JAVA_BUILD_ORDER))) return; // cannot be customized at project level
if (javaBuildOrder == null || javaBuildOrder.length <= 1) return;
@@ -1587,14 +1590,14 @@ return null;
// if (this.deltaProcessor.indexManager != null){ // no more indexing
// this.deltaProcessor.indexManager.shutdown();
// }
-// try {
-// IJavaModel model = this.getJavaModel();
-// if (model != null) {
+ try {
+ IJavaModel model = this.getJavaModel();
+ if (model != null) {
-// model.close();
-// }
-// } catch (JavaModelException e) {
-// }
+ model.close();
+ }
+ } catch (JavaModelException e) {
+ }
}
/**
@@ -1659,11 +1662,11 @@ return null;
if (variablePath == JavaModelManager.VariableInitializationInProgress){
return;
}
- Preferences preferences = JavaCore.getPlugin().getPluginPreferences();
+ Preferences preferences = PHPCore.getPlugin().getPluginPreferences();
String variableKey = CP_VARIABLE_PREFERENCES_PREFIX+variableName;
String variableString = variablePath == null ? CP_ENTRY_IGNORE : variablePath.toString();
preferences.setDefault(variableKey, CP_ENTRY_IGNORE); // use this default to get rid of removed ones
preferences.setValue(variableKey, variableString);
- JavaCore.getPlugin().savePluginPreferences();
+ PHPCore.getPlugin().savePluginPreferences();
}
}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaModelOperation.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaModelOperation.java
index 0347ce1..4fc9675 100644
--- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaModelOperation.java
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaModelOperation.java
@@ -381,9 +381,8 @@ public abstract class JavaModelOperation implements IWorkspaceRunnable, IProgres
DeltaProcessor deltaProcessor = JavaModelManager.getJavaModelManager().deltaProcessor;
if (deltaProcessor.roots == null) {
// TODO khartlage temp-del
-// deltaProcessor.initializeRoots();
+ deltaProcessor.initializeRoots();
}
-
executeOperation();
} else {
throw new JavaModelException(status);
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaProject.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaProject.java
index c8541ba..2a0a680 100644
--- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaProject.java
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaProject.java
@@ -13,32 +13,76 @@ package net.sourceforge.phpdt.internal.core;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
-
+import java.io.OutputStreamWriter;
+import java.io.StringReader;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Hashtable;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.parsers.SAXParserFactory;
+
+import net.sourceforge.phpdt.core.IClasspathEntry;
import net.sourceforge.phpdt.core.IJavaElement;
+import net.sourceforge.phpdt.core.IJavaModelMarker;
+import net.sourceforge.phpdt.core.IJavaModelStatus;
+import net.sourceforge.phpdt.core.IJavaModelStatusConstants;
import net.sourceforge.phpdt.core.IJavaProject;
+import net.sourceforge.phpdt.core.IPackageFragment;
+import net.sourceforge.phpdt.core.IPackageFragmentRoot;
import net.sourceforge.phpdt.core.JavaModelException;
+import net.sourceforge.phpdt.internal.codeassist.ISearchableNameEnvironment;
+import net.sourceforge.phpdt.internal.compiler.util.ObjectVector;
+import net.sourceforge.phpdt.internal.corext.Assert;
+import net.sourceforge.phpeclipse.LoadPathEntry;
import net.sourceforge.phpeclipse.PHPCore;
import net.sourceforge.phpeclipse.PHPeclipsePlugin;
+import org.apache.xerces.dom.DocumentImpl;
+import org.apache.xml.serialize.Method;
+import org.apache.xml.serialize.OutputFormat;
+import org.apache.xml.serialize.Serializer;
+import org.apache.xml.serialize.SerializerFactory;
import org.eclipse.core.resources.ICommand;
import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IFolder;
+import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IProjectNature;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
+import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
+import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Preferences;
import org.eclipse.core.runtime.QualifiedName;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+import org.xml.sax.Attributes;
+import org.xml.sax.ContentHandler;
+import org.xml.sax.InputSource;
+import org.xml.sax.Locator;
+import org.xml.sax.SAXException;
+import org.xml.sax.XMLReader;
/**
* Handle for a Java Project.
@@ -58,7 +102,7 @@ import org.eclipse.core.runtime.QualifiedName;
*
* @see IJavaProject
*/
-public class JavaProject
+public class JavaProject
extends Openable
implements IJavaProject , IProjectNature {
@@ -76,6 +120,8 @@ public class JavaProject
* The platform project this IJavaProject
is based on
*/
protected IProject fProject;
+ protected List fLoadPathEntries;
+ protected boolean fScratched;
/**
* Name of file containing project classpath
@@ -90,7 +136,7 @@ public class JavaProject
/**
* Value of the project's raw classpath if the .classpath file contains invalid entries.
*/
-// public static final IClasspathEntry[] INVALID_CLASSPATH = new IClasspathEntry[0];
+ public static final IClasspathEntry[] INVALID_CLASSPATH = new IClasspathEntry[0];
private static final String CUSTOM_DEFAULT_OPTION_VALUE = "#\r\n\r#custom-non-empty-default-value#\r\n\r#"; //$NON-NLS-1$
@@ -185,7 +231,125 @@ public class JavaProject
super(JAVA_PROJECT, parent, project.getName());
fProject = project;
}
+ public void addLoadPathEntry(IProject anotherPHPProject) {
+ fScratched = true;
+
+ LoadPathEntry newEntry = new LoadPathEntry(anotherPHPProject);
+ getLoadPathEntries().add(newEntry);
+ }
+
+ public void configure() throws CoreException {
+ // get project description and then the associated build commands
+ IProjectDescription desc = fProject.getDescription();
+ ICommand[] commands = desc.getBuildSpec();
+
+ // determine if builder already associated
+ boolean found = false;
+ for (int i = 0; i < commands.length; ++i) {
+ if (commands[i].getBuilderName().equals(PHPeclipsePlugin.BUILDER_PARSER_ID)) {
+ found = true;
+ break;
+ }
+ }
+
+ // add builder if not already in project
+ if (!found) {
+ ICommand command = desc.newCommand();
+ command.setBuilderName(PHPeclipsePlugin.BUILDER_PARSER_ID);
+ ICommand[] newCommands = new ICommand[commands.length + 1];
+
+ // Add it before other builders.
+ System.arraycopy(commands, 0, newCommands, 1, commands.length);
+ newCommands[0] = command;
+ desc.setBuildSpec(newCommands);
+ fProject.setDescription(desc, null);
+ }
+ }
+
+ protected void loadLoadPathEntries() {
+ fLoadPathEntries = new ArrayList();
+
+ IFile loadPathsFile = getLoadPathEntriesFile();
+
+ XMLReader reader = null;
+ try {
+ reader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
+ reader.setContentHandler(getLoadPathEntriesContentHandler());
+ reader.parse(new InputSource(loadPathsFile.getContents()));
+ } catch (Exception e) {
+ //the file is nonextant or unreadable
+ }
+ }
+
+ public List getLoadPathEntries() {
+ if (fLoadPathEntries == null) {
+ loadLoadPathEntries();
+ }
+
+ return fLoadPathEntries;
+ }
+
+ protected ContentHandler getLoadPathEntriesContentHandler() {
+ return new ContentHandler() {
+ public void characters(char[] arg0, int arg1, int arg2) throws SAXException {
+ }
+
+ public void endDocument() throws SAXException {
+ }
+
+ public void endElement(String arg0, String arg1, String arg2) throws SAXException {
+ }
+
+ public void endPrefixMapping(String arg0) throws SAXException {
+ }
+
+ public void ignorableWhitespace(char[] arg0, int arg1, int arg2) throws SAXException {
+ }
+
+ public void processingInstruction(String arg0, String arg1) throws SAXException {
+ }
+
+ public void setDocumentLocator(Locator arg0) {
+ }
+
+ public void skippedEntity(String arg0) throws SAXException {
+ }
+
+ public void startDocument() throws SAXException {
+ }
+
+ public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
+ if ("pathentry".equals(qName))
+ if ("project".equals(atts.getValue("type"))) {
+ IPath referencedProjectPath = new Path(atts.getValue("path"));
+ IProject referencedProject = getProject(referencedProjectPath.lastSegment());
+ fLoadPathEntries.add(new LoadPathEntry(referencedProject));
+ }
+ }
+
+ public void startPrefixMapping(String arg0, String arg1) throws SAXException {
+ }
+ };
+ }
+
+ protected IFile getLoadPathEntriesFile() {
+ return fProject.getFile(".loadpath");
+ }
+
+ protected String getLoadPathXML() {
+ StringBuffer buffer = new StringBuffer();
+ buffer.append("null
if there is no reference to the path.
-// */
-// public IClasspathEntry getClasspathEntryFor(IPath path)
-// throws JavaModelException {
-//
-// IClasspathEntry[] entries = getExpandedClasspath(true);
-// for (int i = 0; i < entries.length; i++) {
-// if (entries[i].getPath().equals(path)) {
-// return entries[i];
-// }
-// }
-// return null;
-// }
+ public IPackageFragmentRoot[] getAllPackageFragmentRoots()
+ throws JavaModelException {
+
+ return computePackageFragmentRoots(getResolvedClasspath(true), true);
+ }
+
+ /**
+ * Returns the classpath entry that refers to the given path
+ * or null
if there is no reference to the path.
+ */
+ public IClasspathEntry getClasspathEntryFor(IPath path)
+ throws JavaModelException {
+
+ IClasspathEntry[] entries = getExpandedClasspath(true);
+ for (int i = 0; i < entries.length; i++) {
+ if (entries[i].getPath().equals(path)) {
+ return entries[i];
+ }
+ }
+ return null;
+ }
/*
* Returns the cycle marker associated with this project or null if none.
*/
-// public IMarker getCycleMarker(){
-// try {
-// IProject project = getProject();
-// if (project.exists()) {
-// IMarker[] markers = project.findMarkers(IJavaModelMarker.BUILDPATH_PROBLEM_MARKER, false, IResource.DEPTH_ZERO);
-// for (int i = 0, length = markers.length; i < length; i++) {
-// IMarker marker = markers[i];
-// String cycleAttr = (String)marker.getAttribute(IJavaModelMarker.CYCLE_DETECTED);
-// if (cycleAttr != null && cycleAttr.equals("true")){ //$NON-NLS-1$
-// return marker;
-// }
-// }
-// }
-// } catch (CoreException e) {
-// }
-// return null;
-// }
-//
-// /**
-// * This is a helper method returning the expanded classpath for the project, as a list of classpath entries,
-// * where all classpath variable entries have been resolved and substituted with their final target entries.
-// * All project exports have been appended to project entries.
-// */
-// public IClasspathEntry[] getExpandedClasspath(boolean ignoreUnresolvedVariable) throws JavaModelException {
-//
-// return getExpandedClasspath(ignoreUnresolvedVariable, false);
-// }
+ public IMarker getCycleMarker(){
+ try {
+ IProject project = getProject();
+ if (project.exists()) {
+ IMarker[] markers = project.findMarkers(IJavaModelMarker.BUILDPATH_PROBLEM_MARKER, false, IResource.DEPTH_ZERO);
+ for (int i = 0, length = markers.length; i < length; i++) {
+ IMarker marker = markers[i];
+ String cycleAttr = (String)marker.getAttribute(IJavaModelMarker.CYCLE_DETECTED);
+ if (cycleAttr != null && cycleAttr.equals("true")){ //$NON-NLS-1$
+ return marker;
+ }
+ }
+ }
+ } catch (CoreException e) {
+ }
+ return null;
+ }
+
+ /**
+ * This is a helper method returning the expanded classpath for the project, as a list of classpath entries,
+ * where all classpath variable entries have been resolved and substituted with their final target entries.
+ * All project exports have been appended to project entries.
+ */
+ public IClasspathEntry[] getExpandedClasspath(boolean ignoreUnresolvedVariable) throws JavaModelException {
+
+ return getExpandedClasspath(ignoreUnresolvedVariable, false);
+ }
/**
* Internal variant which can create marker on project for invalid entries,
* it will also perform classpath expansion in presence of project prerequisites
* exporting their entries.
*/
-// public IClasspathEntry[] getExpandedClasspath(
-// boolean ignoreUnresolvedVariable,
-// boolean generateMarkerOnError) throws JavaModelException {
-//
-// ObjectVector accumulatedEntries = new ObjectVector();
-// computeExpandedClasspath(this, ignoreUnresolvedVariable, generateMarkerOnError, new HashSet(5), accumulatedEntries);
-//
-// IClasspathEntry[] expandedPath = new IClasspathEntry[accumulatedEntries.size()];
-// accumulatedEntries.copyInto(expandedPath);
-//
-// return expandedPath;
-// }
+ public IClasspathEntry[] getExpandedClasspath(
+ boolean ignoreUnresolvedVariable,
+ boolean generateMarkerOnError) throws JavaModelException {
+
+ ObjectVector accumulatedEntries = new ObjectVector();
+ computeExpandedClasspath(this, ignoreUnresolvedVariable, generateMarkerOnError, new HashSet(5), accumulatedEntries);
+
+ IClasspathEntry[] expandedPath = new IClasspathEntry[accumulatedEntries.size()];
+ accumulatedEntries.copyInto(expandedPath);
+
+ return expandedPath;
+ }
/**
* Returns the char
that marks the start of this handles
@@ -1097,31 +1253,31 @@ public class JavaProject
}
return null;
}
-//
-// /**
-// * Convenience method that returns the specific type of info for a Java project.
-// */
-// protected JavaProjectElementInfo getJavaProjectElementInfo()
-// throws JavaModelException {
-//
-// return (JavaProjectElementInfo) getElementInfo();
-// }
+
+ /**
+ * Convenience method that returns the specific type of info for a Java project.
+ */
+ protected JavaProjectElementInfo getJavaProjectElementInfo()
+ throws JavaModelException {
+
+ return (JavaProjectElementInfo) getElementInfo();
+ }
/**
* @see IJavaProject
*/
-// public NameLookup getNameLookup() throws JavaModelException {
-//
-// JavaProjectElementInfo info = getJavaProjectElementInfo();
-// // lock on the project info to avoid race condition
-// synchronized(info){
-// NameLookup nameLookup;
-// if ((nameLookup = info.getNameLookup()) == null){
-// info.setNameLookup(nameLookup = new NameLookup(this));
-// }
-// return nameLookup;
-// }
-// }
+ public NameLookup getNameLookup() throws JavaModelException {
+
+ JavaProjectElementInfo info = getJavaProjectElementInfo();
+ // lock on the project info to avoid race condition
+ synchronized(info){
+ NameLookup nameLookup;
+ if ((nameLookup = info.getNameLookup()) == null){
+ info.setNameLookup(nameLookup = new NameLookup(this));
+ }
+ return nameLookup;
+ }
+ }
//
// /**
// * Returns an array of non-java resources contained in the receiver.
@@ -1134,91 +1290,91 @@ public class JavaProject
/**
* @see org.eclipse.jdt.core.IJavaProject#getOption(String, boolean)
*/
-// public String getOption(String optionName, boolean inheritJavaCoreOptions) {
-//
-// if (JavaModelManager.OptionNames.contains(optionName)){
-//
-// Preferences preferences = getPreferences();
-// if (preferences == null || preferences.isDefault(optionName)) {
-// return inheritJavaCoreOptions ? PHPCore.getOption(optionName) : null;
-// }
-// return preferences.getString(optionName).trim();
-// }
-// return null;
-// }
+ public String getOption(String optionName, boolean inheritJavaCoreOptions) {
+
+ if (JavaModelManager.OptionNames.contains(optionName)){
+
+ Preferences preferences = getPreferences();
+ if (preferences == null || preferences.isDefault(optionName)) {
+ return inheritJavaCoreOptions ? PHPCore.getOption(optionName) : null;
+ }
+ return preferences.getString(optionName).trim();
+ }
+ return null;
+ }
/**
* @see org.eclipse.jdt.core.IJavaProject#getOptions(boolean)
*/
-// public Map getOptions(boolean inheritJavaCoreOptions) {
-//
-// // initialize to the defaults from JavaCore options pool
-// Map options = inheritJavaCoreOptions ? PHPCore.getOptions() : new Hashtable(5);
-//
-// Preferences preferences = getPreferences();
-// if (preferences == null) return options; // cannot do better (non-Java project)
-// HashSet optionNames = JavaModelManager.OptionNames;
-//
-// // get preferences set to their default
-// if (inheritJavaCoreOptions){
-// String[] defaultPropertyNames = preferences.defaultPropertyNames();
-// for (int i = 0; i < defaultPropertyNames.length; i++){
-// String propertyName = defaultPropertyNames[i];
-// if (optionNames.contains(propertyName)){
-// options.put(propertyName, preferences.getDefaultString(propertyName).trim());
-// }
-// }
-// }
-// // get custom preferences not set to their default
-// String[] propertyNames = preferences.propertyNames();
-// for (int i = 0; i < propertyNames.length; i++){
-// String propertyName = propertyNames[i];
-// if (optionNames.contains(propertyName)){
-// options.put(propertyName, preferences.getString(propertyName).trim());
-// }
-// }
-// return options;
-// }
+ public Map getOptions(boolean inheritJavaCoreOptions) {
+
+ // initialize to the defaults from JavaCore options pool
+ Map options = inheritJavaCoreOptions ? PHPCore.getOptions() : new Hashtable(5);
+
+ Preferences preferences = getPreferences();
+ if (preferences == null) return options; // cannot do better (non-Java project)
+ HashSet optionNames = JavaModelManager.OptionNames;
+
+ // get preferences set to their default
+ if (inheritJavaCoreOptions){
+ String[] defaultPropertyNames = preferences.defaultPropertyNames();
+ for (int i = 0; i < defaultPropertyNames.length; i++){
+ String propertyName = defaultPropertyNames[i];
+ if (optionNames.contains(propertyName)){
+ options.put(propertyName, preferences.getDefaultString(propertyName).trim());
+ }
+ }
+ }
+ // get custom preferences not set to their default
+ String[] propertyNames = preferences.propertyNames();
+ for (int i = 0; i < propertyNames.length; i++){
+ String propertyName = propertyNames[i];
+ if (optionNames.contains(propertyName)){
+ options.put(propertyName, preferences.getString(propertyName).trim());
+ }
+ }
+ return options;
+ }
/**
* @see IJavaProject
*/
-// public IPath getOutputLocation() throws JavaModelException {
-//
-// JavaModelManager.PerProjectInfo perProjectInfo = JavaModelManager.getJavaModelManager().getPerProjectInfoCheckExistence(fProject);
-// IPath outputLocation = perProjectInfo.outputLocation;
-// if (outputLocation != null) return outputLocation;
-//
-// // force to read classpath - will position output location as well
-// this.getRawClasspath();
-// outputLocation = perProjectInfo.outputLocation;
-// if (outputLocation == null) {
-// return defaultOutputLocation();
-// }
-// return outputLocation;
-// }
-//
-// /**
-// * @return A handle to the package fragment root identified by the given path.
-// * This method is handle-only and the element may or may not exist. Returns
-// * null
if unable to generate a handle from the path (for example,
-// * an absolute path that has less than 1 segment. The path may be relative or
-// * absolute.
-// */
-// public IPackageFragmentRoot getPackageFragmentRoot(IPath path) {
-// if (!path.isAbsolute()) {
-// path = getPath().append(path);
-// }
-// int segmentCount = path.segmentCount();
-// switch (segmentCount) {
-// case 0:
-// return null;
-// case 1:
-// // default root
-// return getPackageFragmentRoot(getProject());
-// default:
-// // a path ending with .jar/.zip is still ambiguous and could still resolve to a source/lib folder
-// // thus will try to guess based on existing resource
+ public IPath getOutputLocation() throws JavaModelException {
+
+ JavaModelManager.PerProjectInfo perProjectInfo = JavaModelManager.getJavaModelManager().getPerProjectInfoCheckExistence(fProject);
+ IPath outputLocation = perProjectInfo.outputLocation;
+ if (outputLocation != null) return outputLocation;
+
+ // force to read classpath - will position output location as well
+ this.getRawClasspath();
+ outputLocation = perProjectInfo.outputLocation;
+ if (outputLocation == null) {
+ return defaultOutputLocation();
+ }
+ return outputLocation;
+ }
+
+ /**
+ * @return A handle to the package fragment root identified by the given path.
+ * This method is handle-only and the element may or may not exist. Returns
+ * null
if unable to generate a handle from the path (for example,
+ * an absolute path that has less than 1 segment. The path may be relative or
+ * absolute.
+ */
+ public IPackageFragmentRoot getPackageFragmentRoot(IPath path) {
+ if (!path.isAbsolute()) {
+ path = getPath().append(path);
+ }
+ int segmentCount = path.segmentCount();
+ switch (segmentCount) {
+ case 0:
+ return null;
+ case 1:
+ // default root
+ return getPackageFragmentRoot(getProject());
+ default:
+ // a path ending with .jar/.zip is still ambiguous and could still resolve to a source/lib folder
+ // thus will try to guess based on existing resource
// if (Util.isArchiveFileName(path.lastSegment())) {
// IResource resource = getProject().getWorkspace().getRoot().findMember(path);
// if (resource != null && resource.getType() == IResource.FOLDER){
@@ -1226,45 +1382,45 @@ public class JavaProject
// }
// return getPackageFragmentRoot0(path);
// } else {
-// return getPackageFragmentRoot(getProject().getWorkspace().getRoot().getFolder(path));
+ return getPackageFragmentRoot(getProject().getWorkspace().getRoot().getFolder(path));
// }
-// }
-// }
-//
-// /**
-// * The path is known to match a source/library folder entry.
-// */
-// public IPackageFragmentRoot getFolderPackageFragmentRoot(IPath path) {
-// if (path.segmentCount() == 1) { // default project root
-// return getPackageFragmentRoot(getProject());
-// }
-// return getPackageFragmentRoot(getProject().getWorkspace().getRoot().getFolder(path));
-// }
-//
-// /**
-// * @see IJavaProject
-// */
-// public IPackageFragmentRoot getPackageFragmentRoot(IResource resource) {
-//
-// switch (resource.getType()) {
-// case IResource.FILE:
+ }
+ }
+
+ /**
+ * The path is known to match a source/library folder entry.
+ */
+ public IPackageFragmentRoot getFolderPackageFragmentRoot(IPath path) {
+ if (path.segmentCount() == 1) { // default project root
+ return getPackageFragmentRoot(getProject());
+ }
+ return getPackageFragmentRoot(getProject().getWorkspace().getRoot().getFolder(path));
+ }
+
+ /**
+ * @see IJavaProject
+ */
+ public IPackageFragmentRoot getPackageFragmentRoot(IResource resource) {
+
+ switch (resource.getType()) {
+ case IResource.FILE:
// if (Util.isArchiveFileName(resource.getName())) {
// return new JarPackageFragmentRoot(resource, this);
// } else {
-// return null;
+ return null;
// }
-// case IResource.FOLDER:
-// return new PackageFragmentRoot(resource, this, resource.getName());
-// case IResource.PROJECT:
-// return new PackageFragmentRoot(resource, this, ""); //$NON-NLS-1$
-// default:
-// return null;
-// }
-// }
-//
-// /**
-// * @see IJavaProject
-// */
+ case IResource.FOLDER:
+ return new PackageFragmentRoot(resource, this, resource.getName());
+ case IResource.PROJECT:
+ return new PackageFragmentRoot(resource, this, ""); //$NON-NLS-1$
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * @see IJavaProject
+ */
// public IPackageFragmentRoot getPackageFragmentRoot(String jarPath) {
//
// return getPackageFragmentRoot0(JavaProject.canonicalizedPath(new Path(jarPath)));
@@ -1277,86 +1433,86 @@ public class JavaProject
//
// return new JarPackageFragmentRoot(jarPath, this);
// }
-//
-// /**
-// * @see IJavaProject
-// */
-// public IPackageFragmentRoot[] getPackageFragmentRoots()
-// throws JavaModelException {
-//
-// Object[] children;
-// int length;
-// IPackageFragmentRoot[] roots;
-//
-// System.arraycopy(
-// children = getChildren(),
-// 0,
-// roots = new IPackageFragmentRoot[length = children.length],
-// 0,
-// length);
-//
-// return roots;
-// }
+
+ /**
+ * @see IJavaProject
+ */
+ public IPackageFragmentRoot[] getPackageFragmentRoots()
+ throws JavaModelException {
+
+ Object[] children;
+ int length;
+ IPackageFragmentRoot[] roots;
+
+ System.arraycopy(
+ children = getChildren(),
+ 0,
+ roots = new IPackageFragmentRoot[length = children.length],
+ 0,
+ length);
+
+ return roots;
+ }
/**
* @see IJavaProject
* @deprecated
*/
-// public IPackageFragmentRoot[] getPackageFragmentRoots(IClasspathEntry entry) {
-// return findPackageFragmentRoots(entry);
-// }
+ public IPackageFragmentRoot[] getPackageFragmentRoots(IClasspathEntry entry) {
+ return findPackageFragmentRoots(entry);
+ }
/**
* Returns the package fragment root prefixed by the given path, or
* an empty collection if there are no such elements in the model.
*/
-// protected IPackageFragmentRoot[] getPackageFragmentRoots(IPath path)
-//
-// throws JavaModelException {
-// IPackageFragmentRoot[] roots = getAllPackageFragmentRoots();
-// ArrayList matches = new ArrayList();
-//
-// for (int i = 0; i < roots.length; ++i) {
-// if (path.isPrefixOf(roots[i].getPath())) {
-// matches.add(roots[i]);
-// }
-// }
-// IPackageFragmentRoot[] copy = new IPackageFragmentRoot[matches.size()];
-// matches.toArray(copy);
-// return copy;
-// }
+ protected IPackageFragmentRoot[] getPackageFragmentRoots(IPath path)
+
+ throws JavaModelException {
+ IPackageFragmentRoot[] roots = getAllPackageFragmentRoots();
+ ArrayList matches = new ArrayList();
+
+ for (int i = 0; i < roots.length; ++i) {
+ if (path.isPrefixOf(roots[i].getPath())) {
+ matches.add(roots[i]);
+ }
+ }
+ IPackageFragmentRoot[] copy = new IPackageFragmentRoot[matches.size()];
+ matches.toArray(copy);
+ return copy;
+ }
/**
* @see IJavaProject
*/
-// public IPackageFragment[] getPackageFragments() throws JavaModelException {
-//
-// IPackageFragmentRoot[] roots = getPackageFragmentRoots();
-// return getPackageFragmentsInRoots(roots);
-// }
+ public IPackageFragment[] getPackageFragments() throws JavaModelException {
+
+ IPackageFragmentRoot[] roots = getPackageFragmentRoots();
+ return getPackageFragmentsInRoots(roots);
+ }
/**
* Returns all the package fragments found in the specified
* package fragment roots.
*/
-// public IPackageFragment[] getPackageFragmentsInRoots(IPackageFragmentRoot[] roots) {
-//
-// ArrayList frags = new ArrayList();
-// for (int i = 0; i < roots.length; i++) {
-// IPackageFragmentRoot root = roots[i];
-// try {
-// IJavaElement[] rootFragments = root.getChildren();
-// for (int j = 0; j < rootFragments.length; j++) {
-// frags.add(rootFragments[j]);
-// }
-// } catch (JavaModelException e) {
-// // do nothing
-// }
-// }
-// IPackageFragment[] fragments = new IPackageFragment[frags.size()];
-// frags.toArray(fragments);
-// return fragments;
-// }
+ public IPackageFragment[] getPackageFragmentsInRoots(IPackageFragmentRoot[] roots) {
+
+ ArrayList frags = new ArrayList();
+ for (int i = 0; i < roots.length; i++) {
+ IPackageFragmentRoot root = roots[i];
+ try {
+ IJavaElement[] rootFragments = root.getChildren();
+ for (int j = 0; j < rootFragments.length; j++) {
+ frags.add(rootFragments[j]);
+ }
+ } catch (JavaModelException e) {
+ // do nothing
+ }
+ }
+ IPackageFragment[] fragments = new IPackageFragment[frags.size()];
+ frags.toArray(fragments);
+ return fragments;
+ }
/*
* @see IJavaElement
@@ -1372,166 +1528,183 @@ public class JavaProject
return fProject;
}
+
+ protected IProject getProject(String name) {
+ return PHPeclipsePlugin.getWorkspace().getRoot().getProject(name);
+ }
+
+ public List getReferencedProjects() {
+ List referencedProjects = new ArrayList();
+
+ Iterator iterator = getLoadPathEntries().iterator();
+ while (iterator.hasNext()) {
+ LoadPathEntry pathEntry = (LoadPathEntry) iterator.next();
+ if (pathEntry.getType() == LoadPathEntry.TYPE_PROJECT)
+ referencedProjects.add(pathEntry.getProject());
+ }
+ return referencedProjects;
+ }
+
/**
* Returns the project custom preference pool.
* Project preferences may include custom encoding.
*/
-// public Preferences getPreferences(){
-// IProject project = getProject();
-// if (!JavaProject.hasJavaNature(project)) return null;
-// JavaModelManager.PerProjectInfo perProjectInfo = JavaModelManager.getJavaModelManager().getPerProjectInfo(project, true);
-// Preferences preferences = perProjectInfo.preferences;
-// if (preferences != null) return preferences;
-// preferences = loadPreferences();
-// if (preferences == null) preferences = new Preferences();
-// perProjectInfo.preferences = preferences;
-// return preferences;
-// }
+ public Preferences getPreferences(){
+ IProject project = getProject();
+ if (!JavaProject.hasJavaNature(project)) return null;
+ JavaModelManager.PerProjectInfo perProjectInfo = JavaModelManager.getJavaModelManager().getPerProjectInfo(project, true);
+ Preferences preferences = perProjectInfo.preferences;
+ if (preferences != null) return preferences;
+ preferences = loadPreferences();
+ if (preferences == null) preferences = new Preferences();
+ perProjectInfo.preferences = preferences;
+ return preferences;
+ }
/**
* @see IJavaProject
*/
-// public IClasspathEntry[] getRawClasspath() throws JavaModelException {
-//
-// JavaModelManager.PerProjectInfo perProjectInfo = JavaModelManager.getJavaModelManager().getPerProjectInfoCheckExistence(fProject);
-// IClasspathEntry[] classpath = perProjectInfo.classpath;
-// if (classpath != null) return classpath;
-// classpath = this.readClasspathFile(false/*don't create markers*/, true/*log problems*/);
-//
-// // extract out the output location
-// IPath outputLocation = null;
-// if (classpath != null && classpath.length > 0) {
-// IClasspathEntry entry = classpath[classpath.length - 1];
-// if (entry.getContentKind() == ClasspathEntry.K_OUTPUT) {
-// outputLocation = entry.getPath();
-// IClasspathEntry[] copy = new IClasspathEntry[classpath.length - 1];
-// System.arraycopy(classpath, 0, copy, 0, copy.length);
-// classpath = copy;
-// }
-// }
-// if (classpath == null) {
-// return defaultClasspath();
-// }
-// /* Disable validate: classpath can contain CP variables and container that need to be resolved
-// if (classpath != INVALID_CLASSPATH
-// && !JavaConventions.validateClasspath(this, classpath, outputLocation).isOK()) {
-// classpath = INVALID_CLASSPATH;
-// }
-// */
-// perProjectInfo.classpath = classpath;
-// perProjectInfo.outputLocation = outputLocation;
-// return classpath;
-// }
+ public IClasspathEntry[] getRawClasspath() throws JavaModelException {
+
+ JavaModelManager.PerProjectInfo perProjectInfo = JavaModelManager.getJavaModelManager().getPerProjectInfoCheckExistence(fProject);
+ IClasspathEntry[] classpath = perProjectInfo.classpath;
+ if (classpath != null) return classpath;
+ classpath = this.readClasspathFile(false/*don't create markers*/, true/*log problems*/);
+
+ // extract out the output location
+ IPath outputLocation = null;
+ if (classpath != null && classpath.length > 0) {
+ IClasspathEntry entry = classpath[classpath.length - 1];
+ if (entry.getContentKind() == ClasspathEntry.K_OUTPUT) {
+ outputLocation = entry.getPath();
+ IClasspathEntry[] copy = new IClasspathEntry[classpath.length - 1];
+ System.arraycopy(classpath, 0, copy, 0, copy.length);
+ classpath = copy;
+ }
+ }
+ if (classpath == null) {
+ return defaultClasspath();
+ }
+ /* Disable validate: classpath can contain CP variables and container that need to be resolved
+ if (classpath != INVALID_CLASSPATH
+ && !JavaConventions.validateClasspath(this, classpath, outputLocation).isOK()) {
+ classpath = INVALID_CLASSPATH;
+ }
+ */
+ perProjectInfo.classpath = classpath;
+ perProjectInfo.outputLocation = outputLocation;
+ return classpath;
+ }
/**
* @see IJavaProject#getRequiredProjectNames
*/
-// public String[] getRequiredProjectNames() throws JavaModelException {
-//
-// return this.projectPrerequisites(getResolvedClasspath(true));
-// }
+ public String[] getRequiredProjectNames() throws JavaModelException {
+
+ return this.projectPrerequisites(getResolvedClasspath(true));
+ }
/**
* @see IJavaProject
*/
-// public IClasspathEntry[] getResolvedClasspath(boolean ignoreUnresolvedEntry)
-// throws JavaModelException {
-//
-// return
-// this.getResolvedClasspath(
-// ignoreUnresolvedEntry,
-// false); // generateMarkerOnError
-// }
+ public IClasspathEntry[] getResolvedClasspath(boolean ignoreUnresolvedEntry)
+ throws JavaModelException {
+
+ return
+ this.getResolvedClasspath(
+ ignoreUnresolvedEntry,
+ false); // generateMarkerOnError
+ }
/**
* Internal variant which can create marker on project for invalid entries
* and caches the resolved classpath on perProjectInfo
*/
-// public IClasspathEntry[] getResolvedClasspath(
-// boolean ignoreUnresolvedEntry,
-// boolean generateMarkerOnError)
-// throws JavaModelException {
-//
-// JavaModelManager manager = JavaModelManager.getJavaModelManager();
-// JavaModelManager.PerProjectInfo perProjectInfo = manager.getPerProjectInfoCheckExistence(fProject);
-//
-// // reuse cache if not needing to refresh markers or checking bound variables
-// if (ignoreUnresolvedEntry && !generateMarkerOnError && perProjectInfo != null){
-// // resolved path is cached on its info
-// IClasspathEntry[] infoPath = perProjectInfo.lastResolvedClasspath;
-// if (infoPath != null) return infoPath;
-// }
-// Map reverseMap = perProjectInfo == null ? null : new HashMap(5);
-// IClasspathEntry[] resolvedPath = getResolvedClasspath(
-// getRawClasspath(),
-// generateMarkerOnError ? getOutputLocation() : null,
-// ignoreUnresolvedEntry,
-// generateMarkerOnError,
-// reverseMap);
-//
-// if (perProjectInfo != null){
-// if (perProjectInfo.classpath == null // .classpath file could not be read
-// && generateMarkerOnError
-// && JavaProject.hasJavaNature(fProject)) {
-// this.createClasspathProblemMarker(new JavaModelStatus(
-// IJavaModelStatusConstants.INVALID_CLASSPATH_FILE_FORMAT,
-// Util.bind("classpath.cannotReadClasspathFile", this.getElementName()))); //$NON-NLS-1$
-// }
-//
-// perProjectInfo.lastResolvedClasspath = resolvedPath;
-// perProjectInfo.resolvedPathToRawEntries = reverseMap;
-// }
-// return resolvedPath;
-// }
+ public IClasspathEntry[] getResolvedClasspath(
+ boolean ignoreUnresolvedEntry,
+ boolean generateMarkerOnError)
+ throws JavaModelException {
+
+ JavaModelManager manager = JavaModelManager.getJavaModelManager();
+ JavaModelManager.PerProjectInfo perProjectInfo = manager.getPerProjectInfoCheckExistence(fProject);
+
+ // reuse cache if not needing to refresh markers or checking bound variables
+ if (ignoreUnresolvedEntry && !generateMarkerOnError && perProjectInfo != null){
+ // resolved path is cached on its info
+ IClasspathEntry[] infoPath = perProjectInfo.lastResolvedClasspath;
+ if (infoPath != null) return infoPath;
+ }
+ Map reverseMap = perProjectInfo == null ? null : new HashMap(5);
+ IClasspathEntry[] resolvedPath = getResolvedClasspath(
+ getRawClasspath(),
+ generateMarkerOnError ? getOutputLocation() : null,
+ ignoreUnresolvedEntry,
+ generateMarkerOnError,
+ reverseMap);
+
+ if (perProjectInfo != null){
+ if (perProjectInfo.classpath == null // .classpath file could not be read
+ && generateMarkerOnError
+ && JavaProject.hasJavaNature(fProject)) {
+ this.createClasspathProblemMarker(new JavaModelStatus(
+ IJavaModelStatusConstants.INVALID_CLASSPATH_FILE_FORMAT,
+ Util.bind("classpath.cannotReadClasspathFile", this.getElementName()))); //$NON-NLS-1$
+ }
+
+ perProjectInfo.lastResolvedClasspath = resolvedPath;
+ perProjectInfo.resolvedPathToRawEntries = reverseMap;
+ }
+ return resolvedPath;
+ }
/**
* Internal variant which can process any arbitrary classpath
*/
-// public IClasspathEntry[] getResolvedClasspath(
-// IClasspathEntry[] classpathEntries,
-// IPath projectOutputLocation, // only set if needing full classpath validation (and markers)
-// boolean ignoreUnresolvedEntry, // if unresolved entries are met, should it trigger initializations
-// boolean generateMarkerOnError,
-// Map reverseMap) // can be null if not interested in reverse mapping
-// throws JavaModelException {
-//
-// IJavaModelStatus status;
-// if (generateMarkerOnError){
-// flushClasspathProblemMarkers(false, false);
-// }
-//
-// int length = classpathEntries.length;
-// ArrayList resolvedEntries = new ArrayList();
-//
-// for (int i = 0; i < length; i++) {
-//
-// IClasspathEntry rawEntry = classpathEntries[i];
-// IPath resolvedPath;
-// status = null;
-//
-// /* validation if needed */
+ public IClasspathEntry[] getResolvedClasspath(
+ IClasspathEntry[] classpathEntries,
+ IPath projectOutputLocation, // only set if needing full classpath validation (and markers)
+ boolean ignoreUnresolvedEntry, // if unresolved entries are met, should it trigger initializations
+ boolean generateMarkerOnError,
+ Map reverseMap) // can be null if not interested in reverse mapping
+ throws JavaModelException {
+
+ IJavaModelStatus status;
+ if (generateMarkerOnError){
+ flushClasspathProblemMarkers(false, false);
+ }
+
+ int length = classpathEntries.length;
+ ArrayList resolvedEntries = new ArrayList();
+
+ for (int i = 0; i < length; i++) {
+
+ IClasspathEntry rawEntry = classpathEntries[i];
+ IPath resolvedPath;
+ status = null;
+
+ /* validation if needed */
// if (generateMarkerOnError || !ignoreUnresolvedEntry) {
// status = JavaConventions.validateClasspathEntry(this, rawEntry, false);
// if (generateMarkerOnError && !status.isOK()) createClasspathProblemMarker(status);
// }
-//
-// switch (rawEntry.getEntryKind()){
-//
-// case IClasspathEntry.CPE_VARIABLE :
-//
-// IClasspathEntry resolvedEntry = JavaCore.getResolvedClasspathEntry(rawEntry);
-// if (resolvedEntry == null) {
-// if (!ignoreUnresolvedEntry) throw new JavaModelException(status);
-// } else {
-// if (reverseMap != null && reverseMap.get(resolvedPath = resolvedEntry.getPath()) == null) reverseMap.put(resolvedPath , rawEntry);
-// resolvedEntries.add(resolvedEntry);
-// }
-// break;
-//
+
+ switch (rawEntry.getEntryKind()){
+
+ case IClasspathEntry.CPE_VARIABLE :
+
+ IClasspathEntry resolvedEntry = PHPCore.getResolvedClasspathEntry(rawEntry);
+ if (resolvedEntry == null) {
+ if (!ignoreUnresolvedEntry) throw new JavaModelException(status);
+ } else {
+ if (reverseMap != null && reverseMap.get(resolvedPath = resolvedEntry.getPath()) == null) reverseMap.put(resolvedPath , rawEntry);
+ resolvedEntries.add(resolvedEntry);
+ }
+ break;
+
// case IClasspathEntry.CPE_CONTAINER :
//
-// IClasspathContainer container = JavaCore.getClasspathContainer(rawEntry.getPath(), this);
+// IClasspathContainer container = PHPCore.getClasspathContainer(rawEntry.getPath(), this);
// if (container == null){
// if (!ignoreUnresolvedEntry) throw new JavaModelException(status);
// break;
@@ -1560,24 +1733,24 @@ public class JavaProject
// resolvedEntries.add(cEntry);
// }
// break;
-//
-// default :
-//
-// if (reverseMap != null && reverseMap.get(resolvedPath = rawEntry.getPath()) == null) reverseMap.put(resolvedPath, rawEntry);
-// resolvedEntries.add(rawEntry);
-//
-// }
-// }
-//
-// IClasspathEntry[] resolvedPath = new IClasspathEntry[resolvedEntries.size()];
-// resolvedEntries.toArray(resolvedPath);
-//
+
+ default :
+
+ if (reverseMap != null && reverseMap.get(resolvedPath = rawEntry.getPath()) == null) reverseMap.put(resolvedPath, rawEntry);
+ resolvedEntries.add(rawEntry);
+
+ }
+ }
+
+ IClasspathEntry[] resolvedPath = new IClasspathEntry[resolvedEntries.size()];
+ resolvedEntries.toArray(resolvedPath);
+
// if (generateMarkerOnError && projectOutputLocation != null) {
// status = JavaConventions.validateClasspath(this, resolvedPath, projectOutputLocation);
// if (!status.isOK()) createClasspathProblemMarker(status);
// }
-// return resolvedPath;
-// }
+ return resolvedPath;
+ }
/*
* @see IJavaElement
@@ -1589,15 +1762,15 @@ public class JavaProject
/**
* @see IJavaProject
*/
-// public ISearchableNameEnvironment getSearchableNameEnvironment()
-// throws JavaModelException {
-//
-// JavaProjectElementInfo info = getJavaProjectElementInfo();
-// if (info.getSearchableEnvironment() == null) {
-// info.setSearchableEnvironment(new SearchableEnvironment(this));
-// }
-// return info.getSearchableEnvironment();
-// }
+ public ISearchableNameEnvironment getSearchableNameEnvironment()
+ throws JavaModelException {
+
+ JavaProjectElementInfo info = getJavaProjectElementInfo();
+ if (info.getSearchableEnvironment() == null) {
+ info.setSearchableEnvironment(new SearchableEnvironment(this));
+ }
+ return info.getSearchableEnvironment();
+ }
/**
* Retrieve a shared property on a project. If the property is not defined, answers null.
@@ -1607,15 +1780,15 @@ public class JavaProject
*
* @see JavaProject#setSharedProperty(String, String)
*/
-// public String getSharedProperty(String key) throws CoreException {
-//
-// String property = null;
-// IFile rscFile = getProject().getFile(key);
-// if (rscFile.exists()) {
-// property = new String(Util.getResourceContentsAsByteArray(rscFile));
-// }
-// return property;
-// }
+ public String getSharedProperty(String key) throws CoreException {
+
+ String property = null;
+ IFile rscFile = getProject().getFile(key);
+ if (rscFile.exists()) {
+ property = new String(Util.getResourceContentsAsByteArray(rscFile));
+ }
+ return property;
+ }
/**
* @see JavaElement
@@ -1636,23 +1809,23 @@ public class JavaProject
/**
* @see IJavaProject
*/
-// public boolean hasBuildState() {
-//
-// return JavaModelManager.getJavaModelManager().getLastBuiltState(this.getProject(), null) != null;
-// }
+ public boolean hasBuildState() {
+
+ return JavaModelManager.getJavaModelManager().getLastBuiltState(this.getProject(), null) != null;
+ }
/**
* @see IJavaProject
*/
-// public boolean hasClasspathCycle(IClasspathEntry[] preferredClasspath) {
-// HashSet cycleParticipants = new HashSet();
-// updateCycleParticipants(preferredClasspath, new ArrayList(2), cycleParticipants, ResourcesPlugin.getWorkspace().getRoot(), new HashSet(2));
-// return !cycleParticipants.isEmpty();
-// }
+ public boolean hasClasspathCycle(IClasspathEntry[] preferredClasspath) {
+ HashSet cycleParticipants = new HashSet();
+ updateCycleParticipants(preferredClasspath, new ArrayList(2), cycleParticipants, ResourcesPlugin.getWorkspace().getRoot(), new HashSet(2));
+ return !cycleParticipants.isEmpty();
+ }
-// public boolean hasCycleMarker(){
-// return this.getCycleMarker() != null;
-// }
+ public boolean hasCycleMarker(){
+ return this.getCycleMarker() != null;
+ }
public int hashCode() {
return fProject.hashCode();
@@ -1674,104 +1847,104 @@ public class JavaProject
/**
* Answers true if the project potentially contains any source. A project which has no source is immutable.
*/
-// public boolean hasSource() {
-//
-// // look if any source folder on the classpath
-// // no need for resolved path given source folder cannot be abstracted
-// IClasspathEntry[] entries;
-// try {
-// entries = this.getRawClasspath();
-// } catch (JavaModelException e) {
-// return true; // unsure
-// }
-// for (int i = 0, max = entries.length; i < max; i++) {
-// if (entries[i].getEntryKind() == IClasspathEntry.CPE_SOURCE) {
-// return true;
-// }
-// }
-// return false;
-// }
+ public boolean hasSource() {
+
+ // look if any source folder on the classpath
+ // no need for resolved path given source folder cannot be abstracted
+ IClasspathEntry[] entries;
+ try {
+ entries = this.getRawClasspath();
+ } catch (JavaModelException e) {
+ return true; // unsure
+ }
+ for (int i = 0, max = entries.length; i < max; i++) {
+ if (entries[i].getEntryKind() == IClasspathEntry.CPE_SOURCE) {
+ return true;
+ }
+ }
+ return false;
+ }
/**
* Compare current classpath with given one to see if any different.
* Note that the argument classpath contains its binary output.
*/
-// public boolean isClasspathEqualsTo(IClasspathEntry[] newClasspath, IPath newOutputLocation, IClasspathEntry[] otherClasspathWithOutput)
-// throws JavaModelException {
-//
-// if (otherClasspathWithOutput != null && otherClasspathWithOutput.length > 0) {
-//
-// int length = otherClasspathWithOutput.length;
-// if (length == newClasspath.length + 1) {
-// // output is amongst file entries (last one)
-//
-// // compare classpath entries
-// for (int i = 0; i < length - 1; i++) {
-// if (!otherClasspathWithOutput[i].equals(newClasspath[i]))
-// return false;
-// }
-// // compare binary outputs
-// IClasspathEntry output = otherClasspathWithOutput[length - 1];
-// if (output.getContentKind() == ClasspathEntry.K_OUTPUT
-// && output.getPath().equals(newOutputLocation))
-// return true;
-// }
-// }
-// return false;
-// }
+ public boolean isClasspathEqualsTo(IClasspathEntry[] newClasspath, IPath newOutputLocation, IClasspathEntry[] otherClasspathWithOutput)
+ throws JavaModelException {
+
+ if (otherClasspathWithOutput != null && otherClasspathWithOutput.length > 0) {
+
+ int length = otherClasspathWithOutput.length;
+ if (length == newClasspath.length + 1) {
+ // output is amongst file entries (last one)
+
+ // compare classpath entries
+ for (int i = 0; i < length - 1; i++) {
+ if (!otherClasspathWithOutput[i].equals(newClasspath[i]))
+ return false;
+ }
+ // compare binary outputs
+ IClasspathEntry output = otherClasspathWithOutput[length - 1];
+ if (output.getContentKind() == ClasspathEntry.K_OUTPUT
+ && output.getPath().equals(newOutputLocation))
+ return true;
+ }
+ }
+ return false;
+ }
/*
* @see IJavaProject
*/
-// public boolean isOnClasspath(IJavaElement element) {
-// IPath path = element.getPath();
-// switch (element.getElementType()) {
-// case IJavaElement.PACKAGE_FRAGMENT_ROOT:
-// if (!((IPackageFragmentRoot)element).isArchive()) {
-// // ensure that folders are only excluded if all of their children are excluded
-// path = path.append("*"); //$NON-NLS-1$
-// }
-// break;
-// case IJavaElement.PACKAGE_FRAGMENT:
-// if (!((IPackageFragmentRoot)element.getParent()).isArchive()) {
-// // ensure that folders are only excluded if all of their children are excluded
-// path = path.append("*"); //$NON-NLS-1$
-// }
-// break;
-// }
-// return this.isOnClasspath(path);
-// }
-// private boolean isOnClasspath(IPath path) {
-// IClasspathEntry[] classpath;
-// try {
-// classpath = this.getResolvedClasspath(true/*ignore unresolved variable*/);
-// } catch(JavaModelException e){
-// return false; // not a Java project
-// }
-// for (int i = 0; i < classpath.length; i++) {
-// IClasspathEntry entry = classpath[i];
-// if (entry.getPath().isPrefixOf(path)
-// && !Util.isExcluded(path, ((ClasspathEntry)entry).fullExclusionPatternChars())) {
-// return true;
-// }
-// }
-// return false;
-// }
+ public boolean isOnClasspath(IJavaElement element) {
+ IPath path = element.getPath();
+ switch (element.getElementType()) {
+ case IJavaElement.PACKAGE_FRAGMENT_ROOT:
+ if (!((IPackageFragmentRoot)element).isArchive()) {
+ // ensure that folders are only excluded if all of their children are excluded
+ path = path.append("*"); //$NON-NLS-1$
+ }
+ break;
+ case IJavaElement.PACKAGE_FRAGMENT:
+ if (!((IPackageFragmentRoot)element.getParent()).isArchive()) {
+ // ensure that folders are only excluded if all of their children are excluded
+ path = path.append("*"); //$NON-NLS-1$
+ }
+ break;
+ }
+ return this.isOnClasspath(path);
+ }
+ private boolean isOnClasspath(IPath path) {
+ IClasspathEntry[] classpath;
+ try {
+ classpath = this.getResolvedClasspath(true/*ignore unresolved variable*/);
+ } catch(JavaModelException e){
+ return false; // not a Java project
+ }
+ for (int i = 0; i < classpath.length; i++) {
+ IClasspathEntry entry = classpath[i];
+ if (entry.getPath().isPrefixOf(path)
+ && !Util.isExcluded(path, ((ClasspathEntry)entry).fullExclusionPatternChars())) {
+ return true;
+ }
+ }
+ return false;
+ }
/*
* @see IJavaProject
*/
-// public boolean isOnClasspath(IResource resource) {
-// IPath path = resource.getFullPath();
-//
-// // ensure that folders are only excluded if all of their children are excluded
-// if (resource.getType() == IResource.FOLDER) {
-// path = path.append("*"); //$NON-NLS-1$
-// }
-//
-// return this.isOnClasspath(path);
-// }
+ public boolean isOnClasspath(IResource resource) {
+ IPath path = resource.getFullPath();
+
+ // ensure that folders are only excluded if all of their children are excluded
+ if (resource.getType() == IResource.FOLDER) {
+ path = path.append("*"); //$NON-NLS-1$
+ }
+
+ return this.isOnClasspath(path);
+ }
/*
@@ -1854,36 +2027,36 @@ public class JavaProject
/**
* Open project if resource isn't closed
*/
-// protected void openWhenClosed(IProgressMonitor pm) throws JavaModelException {
-//
-// if (!this.fProject.isOpen()) {
-// throw newNotPresentException();
-// } else {
-// super.openWhenClosed(pm);
-// }
-// }
+ protected void openWhenClosed(IProgressMonitor pm) throws JavaModelException {
-// public String[] projectPrerequisites(IClasspathEntry[] entries)
-// throws JavaModelException {
-//
-// ArrayList prerequisites = new ArrayList();
-// // need resolution
-// entries = getResolvedClasspath(entries, null, true, false, null/*no reverse map*/);
-// for (int i = 0, length = entries.length; i < length; i++) {
-// IClasspathEntry entry = entries[i];
-// if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
-// prerequisites.add(entry.getPath().lastSegment());
-// }
-// }
-// int size = prerequisites.size();
-// if (size == 0) {
-// return NO_PREREQUISITES;
-// } else {
-// String[] result = new String[size];
-// prerequisites.toArray(result);
-// return result;
-// }
-// }
+ if (!this.fProject.isOpen()) {
+ throw newNotPresentException();
+ } else {
+ super.openWhenClosed(pm);
+ }
+ }
+
+ public String[] projectPrerequisites(IClasspathEntry[] entries)
+ throws JavaModelException {
+
+ ArrayList prerequisites = new ArrayList();
+ // need resolution
+ entries = getResolvedClasspath(entries, null, true, false, null/*no reverse map*/);
+ for (int i = 0, length = entries.length; i < length; i++) {
+ IClasspathEntry entry = entries[i];
+ if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
+ prerequisites.add(entry.getPath().lastSegment());
+ }
+ }
+ int size = prerequisites.size();
+ if (size == 0) {
+ return NO_PREREQUISITES;
+ } else {
+ String[] result = new String[size];
+ prerequisites.toArray(result);
+ return result;
+ }
+ }
/**
@@ -1891,27 +2064,27 @@ public class JavaProject
* Returns null if .classfile is not present.
* Returns INVALID_CLASSPATH if it has a format problem.
*/
-// protected IClasspathEntry[] readClasspathFile(boolean createMarker, boolean logProblems) {
-//
-// try {
-// String xmlClasspath = getSharedProperty(CLASSPATH_FILENAME);
-// if (xmlClasspath == null) return null;
-// return decodeClasspath(xmlClasspath, createMarker, logProblems);
-// } catch(CoreException e) {
-// // file does not exist (or not accessible)
-// if (createMarker && this.getProject().isAccessible()) {
-// this.createClasspathProblemMarker(new JavaModelStatus(
-// IJavaModelStatusConstants.INVALID_CLASSPATH_FILE_FORMAT,
-// Util.bind("classpath.cannotReadClasspathFile", this.getElementName()))); //$NON-NLS-1$
-// }
-// if (logProblems) {
-// Util.log(e,
-// "Exception while retrieving "+ this.getPath() //$NON-NLS-1$
-// +"/.classpath, will revert to default classpath"); //$NON-NLS-1$
-// }
-// }
-// return null;
-// }
+ protected IClasspathEntry[] readClasspathFile(boolean createMarker, boolean logProblems) {
+
+ try {
+ String xmlClasspath = getSharedProperty(CLASSPATH_FILENAME);
+ if (xmlClasspath == null) return null;
+ return decodeClasspath(xmlClasspath, createMarker, logProblems);
+ } catch(CoreException e) {
+ // file does not exist (or not accessible)
+ if (createMarker && this.getProject().isAccessible()) {
+ this.createClasspathProblemMarker(new JavaModelStatus(
+ IJavaModelStatusConstants.INVALID_CLASSPATH_FILE_FORMAT,
+ Util.bind("classpath.cannotReadClasspathFile", this.getElementName()))); //$NON-NLS-1$
+ }
+ if (logProblems) {
+ Util.log(e,
+ "Exception while retrieving "+ this.getPath() //$NON-NLS-1$
+ +"/.classpath, will revert to default classpath"); //$NON-NLS-1$
+ }
+ }
+ return null;
+ }
/**
* Removes the given builder from the build spec for the given project.
@@ -1955,24 +2128,24 @@ public class JavaProject
*
* @return Return whether the .classpath file was modified.
*/
-// public boolean saveClasspath(IClasspathEntry[] newClasspath, IPath newOutputLocation) throws JavaModelException {
-//
-// if (!getProject().exists()) return false;
-//
-// IClasspathEntry[] fileEntries = readClasspathFile(false /*don't create markers*/, false/*don't log problems*/);
-// if (fileEntries != null && isClasspathEqualsTo(newClasspath, newOutputLocation, fileEntries)) {
-// // no need to save it, it is the same
-// return false;
-// }
-//
-// // actual file saving
-// try {
-// setSharedProperty(CLASSPATH_FILENAME, encodeClasspath(newClasspath, newOutputLocation, true));
-// return true;
-// } catch (CoreException e) {
-// throw new JavaModelException(e);
-// }
-// }
+ public boolean saveClasspath(IClasspathEntry[] newClasspath, IPath newOutputLocation) throws JavaModelException {
+
+ if (!getProject().exists()) return false;
+
+ IClasspathEntry[] fileEntries = readClasspathFile(false /*don't create markers*/, false/*don't log problems*/);
+ if (fileEntries != null && isClasspathEqualsTo(newClasspath, newOutputLocation, fileEntries)) {
+ // no need to save it, it is the same
+ return false;
+ }
+
+ // actual file saving
+ try {
+ setSharedProperty(CLASSPATH_FILENAME, encodeClasspath(newClasspath, newOutputLocation, true));
+ return true;
+ } catch (CoreException e) {
+ throw new JavaModelException(e);
+ }
+ }
/**
* Save project custom preferences to shareable file (.jprefs)
@@ -2055,50 +2228,50 @@ public class JavaProject
/**
* @see org.eclipse.jdt.core.IJavaProject#setOptions(Map)
*/
-// public void setOptions(Map newOptions) {
-//
-// Preferences preferences;
-// setPreferences(preferences = new Preferences()); // always reset (26255)
-// if (newOptions != null){
-// Iterator keys = newOptions.keySet().iterator();
-// while (keys.hasNext()){
-// String key = (String)keys.next();
-// if (!JavaModelManager.OptionNames.contains(key)) continue; // unrecognized option
-// // no filtering for encoding (custom encoding for project is allowed)
-// String value = (String)newOptions.get(key);
-// preferences.setDefault(key, CUSTOM_DEFAULT_OPTION_VALUE); // empty string isn't the default (26251)
-// preferences.setValue(key, value);
-// }
-// }
-//
-// // persist options
-// savePreferences(preferences);
-// }
+ public void setOptions(Map newOptions) {
+
+ Preferences preferences;
+ setPreferences(preferences = new Preferences()); // always reset (26255)
+ if (newOptions != null){
+ Iterator keys = newOptions.keySet().iterator();
+ while (keys.hasNext()){
+ String key = (String)keys.next();
+ if (!JavaModelManager.OptionNames.contains(key)) continue; // unrecognized option
+ // no filtering for encoding (custom encoding for project is allowed)
+ String value = (String)newOptions.get(key);
+ preferences.setDefault(key, CUSTOM_DEFAULT_OPTION_VALUE); // empty string isn't the default (26251)
+ preferences.setValue(key, value);
+ }
+ }
+
+ // persist options
+ savePreferences(preferences);
+ }
/**
* @see IJavaProject
*/
-// public void setOutputLocation(IPath path, IProgressMonitor monitor)
-// throws JavaModelException {
-//
-// if (path == null) {
-// throw new IllegalArgumentException(Util.bind("path.nullpath")); //$NON-NLS-1$
-// }
-// if (path.equals(getOutputLocation())) {
-// return;
-// }
-// this.setRawClasspath(SetClasspathOperation.ReuseClasspath, path, monitor);
-// }
+ public void setOutputLocation(IPath path, IProgressMonitor monitor)
+ throws JavaModelException {
+
+ if (path == null) {
+ throw new IllegalArgumentException(Util.bind("path.nullpath")); //$NON-NLS-1$
+ }
+ if (path.equals(getOutputLocation())) {
+ return;
+ }
+ this.setRawClasspath(SetClasspathOperation.ReuseClasspath, path, monitor);
+ }
/*
* Set cached preferences, no preference file is saved, only info is updated
*/
-// public void setPreferences(Preferences preferences) {
-// IProject project = getProject();
-// if (!JavaProject.hasJavaNature(project)) return; // ignore
-// JavaModelManager.PerProjectInfo perProjectInfo = JavaModelManager.getJavaModelManager().getPerProjectInfo(project, true);
-// perProjectInfo.preferences = preferences;
-// }
+ public void setPreferences(Preferences preferences) {
+ IProject project = getProject();
+ if (!JavaProject.hasJavaNature(project)) return; // ignore
+ JavaModelManager.PerProjectInfo perProjectInfo = JavaModelManager.getJavaModelManager().getPerProjectInfo(project, true);
+ perProjectInfo.preferences = preferences;
+ }
/**
* Sets the underlying kernel project of this Java project,
@@ -2117,73 +2290,73 @@ public class JavaProject
/**
* @see IJavaProject
*/
-// public void setRawClasspath(
-// IClasspathEntry[] entries,
-// IPath outputLocation,
-// IProgressMonitor monitor)
-// throws JavaModelException {
-//
-// setRawClasspath(
-// entries,
-// outputLocation,
-// monitor,
-// true, // canChangeResource (as per API contract)
-// getResolvedClasspath(true), // ignoreUnresolvedVariable
-// true, // needValidation
-// true); // need to save
-// }
+ public void setRawClasspath(
+ IClasspathEntry[] entries,
+ IPath outputLocation,
+ IProgressMonitor monitor)
+ throws JavaModelException {
+
+ setRawClasspath(
+ entries,
+ outputLocation,
+ monitor,
+ true, // canChangeResource (as per API contract)
+ getResolvedClasspath(true), // ignoreUnresolvedVariable
+ true, // needValidation
+ true); // need to save
+ }
-// public void setRawClasspath(
-// IClasspathEntry[] newEntries,
-// IPath newOutputLocation,
-// IProgressMonitor monitor,
-// boolean canChangeResource,
-// IClasspathEntry[] oldResolvedPath,
-// boolean needValidation,
-// boolean needSave)
-// throws JavaModelException {
-//
-// JavaModelManager manager =
-// (JavaModelManager) JavaModelManager.getJavaModelManager();
-// try {
-// IClasspathEntry[] newRawPath = newEntries;
-// if (newRawPath == null) { //are we already with the default classpath
-// newRawPath = defaultClasspath();
-// }
-// SetClasspathOperation op =
-// new SetClasspathOperation(
-// this,
-// oldResolvedPath,
-// newRawPath,
-// newOutputLocation,
-// canChangeResource,
-// needValidation,
-// needSave);
-// runOperation(op, monitor);
-//
-// } catch (JavaModelException e) {
-// manager.flush();
-// throw e;
-// }
-// }
+ public void setRawClasspath(
+ IClasspathEntry[] newEntries,
+ IPath newOutputLocation,
+ IProgressMonitor monitor,
+ boolean canChangeResource,
+ IClasspathEntry[] oldResolvedPath,
+ boolean needValidation,
+ boolean needSave)
+ throws JavaModelException {
+
+ JavaModelManager manager =
+ (JavaModelManager) JavaModelManager.getJavaModelManager();
+ try {
+ IClasspathEntry[] newRawPath = newEntries;
+ if (newRawPath == null) { //are we already with the default classpath
+ newRawPath = defaultClasspath();
+ }
+ SetClasspathOperation op =
+ new SetClasspathOperation(
+ this,
+ oldResolvedPath,
+ newRawPath,
+ newOutputLocation,
+ canChangeResource,
+ needValidation,
+ needSave);
+ runOperation(op, monitor);
+
+ } catch (JavaModelException e) {
+ manager.flush();
+ throw e;
+ }
+ }
/**
* @see IJavaProject
*/
-// public void setRawClasspath(
-// IClasspathEntry[] entries,
-// IProgressMonitor monitor)
-// throws JavaModelException {
-//
-// setRawClasspath(
-// entries,
-// SetClasspathOperation.ReuseOutputLocation,
-// monitor,
-// true, // canChangeResource (as per API contract)
-// getResolvedClasspath(true), // ignoreUnresolvedVariable
-// true, // needValidation
-// true); // need to save
-// }
+ public void setRawClasspath(
+ IClasspathEntry[] entries,
+ IProgressMonitor monitor)
+ throws JavaModelException {
+
+ setRawClasspath(
+ entries,
+ SetClasspathOperation.ReuseOutputLocation,
+ monitor,
+ true, // canChangeResource (as per API contract)
+ getResolvedClasspath(true), // ignoreUnresolvedVariable
+ true, // needValidation
+ true); // need to save
+ }
/**
* NOTE: null
specifies default classpath, and an empty
@@ -2191,21 +2364,21 @@ public class JavaProject
*
* @exception NotPresentException if this project does not exist.
*/
-// protected void setRawClasspath0(IClasspathEntry[] rawEntries)
-// throws JavaModelException {
-//
-// JavaModelManager.PerProjectInfo info = JavaModelManager.getJavaModelManager().getPerProjectInfoCheckExistence(fProject);
-//
-// synchronized (info) {
-// if (rawEntries != null) {
-// info.classpath = rawEntries;
-// }
-//
-// // clear cache of resolved classpath
-// info.lastResolvedClasspath = null;
-// info.resolvedPathToRawEntries = null;
-// }
-// }
+ protected void setRawClasspath0(IClasspathEntry[] rawEntries)
+ throws JavaModelException {
+
+ JavaModelManager.PerProjectInfo info = JavaModelManager.getJavaModelManager().getPerProjectInfoCheckExistence(fProject);
+
+ synchronized (info) {
+ if (rawEntries != null) {
+ info.classpath = rawEntries;
+ }
+
+ // clear cache of resolved classpath
+ info.lastResolvedClasspath = null;
+ info.resolvedPathToRawEntries = null;
+ }
+ }
/**
* Record a shared persistent property onto a project.
@@ -2237,109 +2410,109 @@ public class JavaProject
/**
* Update cycle markers for all java projects
*/
-// public static void updateAllCycleMarkers() throws JavaModelException {
-//
-// //long start = System.currentTimeMillis();
-//
-// JavaModelManager manager = JavaModelManager.getJavaModelManager();
-// IJavaProject[] projects = manager.getJavaModel().getJavaProjects();
-// IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
-//
-// HashSet cycleParticipants = new HashSet();
-// HashSet traversed = new HashSet();
-// int length = projects.length;
-//
-// // compute cycle participants
-// ArrayList prereqChain = new ArrayList();
-// for (int i = 0; i < length; i++){
-// JavaProject project = (JavaProject)projects[i];
-// if (!traversed.contains(project.getPath())){
-// prereqChain.clear();
-// project.updateCycleParticipants(null, prereqChain, cycleParticipants, workspaceRoot, traversed);
-// }
-// }
-// //System.out.println("updateAllCycleMarkers: " + (System.currentTimeMillis() - start) + " ms");
-//
-// for (int i = 0; i < length; i++){
-// JavaProject project = (JavaProject)projects[i];
-//
-// if (cycleParticipants.contains(project.getPath())){
-// IMarker cycleMarker = project.getCycleMarker();
-// String circularCPOption = project.getOption(JavaCore.CORE_CIRCULAR_CLASSPATH, true);
-// int circularCPSeverity = JavaCore.ERROR.equals(circularCPOption) ? IMarker.SEVERITY_ERROR : IMarker.SEVERITY_WARNING;
-// if (cycleMarker != null) {
-// // update existing cycle marker if needed
-// try {
-// int existingSeverity = ((Integer)cycleMarker.getAttribute(IMarker.SEVERITY)).intValue();
-// if (existingSeverity != circularCPSeverity) {
-// cycleMarker.setAttribute(IMarker.SEVERITY, circularCPSeverity);
-// }
-// } catch (CoreException e) {
-// throw new JavaModelException(e);
-// }
-// } else {
-// // create new marker
-// project.createClasspathProblemMarker(
-// new JavaModelStatus(IJavaModelStatusConstants.CLASSPATH_CYCLE, project));
-// }
-// } else {
-// project.flushClasspathProblemMarkers(true, false);
-// }
-// }
-// }
-//
-// /**
-// * If a cycle is detected, then cycleParticipants contains all the paths of projects involved in this cycle (directly and indirectly),
-// * no cycle if the set is empty (and started empty)
-// */
-// public void updateCycleParticipants(
-// IClasspathEntry[] preferredClasspath,
-// ArrayList prereqChain,
-// HashSet cycleParticipants,
-// IWorkspaceRoot workspaceRoot,
-// HashSet traversed){
-//
-// IPath path = this.getPath();
-// prereqChain.add(path);
-// traversed.add(path);
-// try {
-// IClasspathEntry[] classpath = preferredClasspath == null ? getResolvedClasspath(true) : preferredClasspath;
-// for (int i = 0, length = classpath.length; i < length; i++) {
-// IClasspathEntry entry = classpath[i];
-//
-// if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT){
-// IPath prereqProjectPath = entry.getPath();
-// int index = cycleParticipants.contains(prereqProjectPath) ? 0 : prereqChain.indexOf(prereqProjectPath);
-// if (index >= 0) { // refer to cycle, or in cycle itself
-// for (int size = prereqChain.size(); index < size; index++) {
-// cycleParticipants.add(prereqChain.get(index));
-// }
-// } else {
-// if (!traversed.contains(prereqProjectPath)) {
-// IResource member = workspaceRoot.findMember(prereqProjectPath);
-// if (member != null && member.getType() == IResource.PROJECT){
-// JavaProject project = (JavaProject)JavaCore.create((IProject)member);
-// project.updateCycleParticipants(null, prereqChain, cycleParticipants, workspaceRoot, traversed);
-// }
-// }
-// }
-// }
-// }
-// } catch(JavaModelException e){
-// }
-// prereqChain.remove(path);
-// }
+ public static void updateAllCycleMarkers() throws JavaModelException {
+
+ //long start = System.currentTimeMillis();
+
+ JavaModelManager manager = JavaModelManager.getJavaModelManager();
+ IJavaProject[] projects = manager.getJavaModel().getJavaProjects();
+ IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
+
+ HashSet cycleParticipants = new HashSet();
+ HashSet traversed = new HashSet();
+ int length = projects.length;
+
+ // compute cycle participants
+ ArrayList prereqChain = new ArrayList();
+ for (int i = 0; i < length; i++){
+ JavaProject project = (JavaProject)projects[i];
+ if (!traversed.contains(project.getPath())){
+ prereqChain.clear();
+ project.updateCycleParticipants(null, prereqChain, cycleParticipants, workspaceRoot, traversed);
+ }
+ }
+ //System.out.println("updateAllCycleMarkers: " + (System.currentTimeMillis() - start) + " ms");
+
+ for (int i = 0; i < length; i++){
+ JavaProject project = (JavaProject)projects[i];
+
+ if (cycleParticipants.contains(project.getPath())){
+ IMarker cycleMarker = project.getCycleMarker();
+ String circularCPOption = project.getOption(PHPCore.CORE_CIRCULAR_CLASSPATH, true);
+ int circularCPSeverity = PHPCore.ERROR.equals(circularCPOption) ? IMarker.SEVERITY_ERROR : IMarker.SEVERITY_WARNING;
+ if (cycleMarker != null) {
+ // update existing cycle marker if needed
+ try {
+ int existingSeverity = ((Integer)cycleMarker.getAttribute(IMarker.SEVERITY)).intValue();
+ if (existingSeverity != circularCPSeverity) {
+ cycleMarker.setAttribute(IMarker.SEVERITY, circularCPSeverity);
+ }
+ } catch (CoreException e) {
+ throw new JavaModelException(e);
+ }
+ } else {
+ // create new marker
+ project.createClasspathProblemMarker(
+ new JavaModelStatus(IJavaModelStatusConstants.CLASSPATH_CYCLE, project));
+ }
+ } else {
+ project.flushClasspathProblemMarkers(true, false);
+ }
+ }
+ }
+
+ /**
+ * If a cycle is detected, then cycleParticipants contains all the paths of projects involved in this cycle (directly and indirectly),
+ * no cycle if the set is empty (and started empty)
+ */
+ public void updateCycleParticipants(
+ IClasspathEntry[] preferredClasspath,
+ ArrayList prereqChain,
+ HashSet cycleParticipants,
+ IWorkspaceRoot workspaceRoot,
+ HashSet traversed){
+
+ IPath path = this.getPath();
+ prereqChain.add(path);
+ traversed.add(path);
+ try {
+ IClasspathEntry[] classpath = preferredClasspath == null ? getResolvedClasspath(true) : preferredClasspath;
+ for (int i = 0, length = classpath.length; i < length; i++) {
+ IClasspathEntry entry = classpath[i];
+
+ if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT){
+ IPath prereqProjectPath = entry.getPath();
+ int index = cycleParticipants.contains(prereqProjectPath) ? 0 : prereqChain.indexOf(prereqProjectPath);
+ if (index >= 0) { // refer to cycle, or in cycle itself
+ for (int size = prereqChain.size(); index < size; index++) {
+ cycleParticipants.add(prereqChain.get(index));
+ }
+ } else {
+ if (!traversed.contains(prereqProjectPath)) {
+ IResource member = workspaceRoot.findMember(prereqProjectPath);
+ if (member != null && member.getType() == IResource.PROJECT){
+ JavaProject project = (JavaProject)PHPCore.create((IProject)member);
+ project.updateCycleParticipants(null, prereqChain, cycleParticipants, workspaceRoot, traversed);
+ }
+ }
+ }
+ }
+ }
+ } catch(JavaModelException e){
+ }
+ prereqChain.remove(path);
+ }
/**
* Reset the collection of package fragment roots (local ones) - only if opened.
* Need to check *all* package fragment roots in order to reset NameLookup
*/
-// public void updatePackageFragmentRoots(){
-//
-// if (this.isOpen()) {
-// try {
-// JavaProjectElementInfo info = getJavaProjectElementInfo();
-//
-// IClasspathEntry[] classpath = getResolvedClasspath(true);
+ public void updatePackageFragmentRoots(){
+
+ if (this.isOpen()) {
+ try {
+ JavaProjectElementInfo info = getJavaProjectElementInfo();
+
+ IClasspathEntry[] classpath = getResolvedClasspath(true);
// NameLookup lookup = info.getNameLookup();
// if (lookup != null){
// IPackageFragmentRoot[] oldRoots = lookup.fPackageFragmentRoots;
@@ -2356,16 +2529,42 @@ public class JavaProject
// }
// info.setNameLookup(null); // discard name lookup (hold onto roots)
// }
-// info.setNonJavaResources(null);
-// info.setChildren(
-// computePackageFragmentRoots(classpath, false));
-//
-// } catch(JavaModelException e){
-// try {
-// close(); // could not do better
-// } catch(JavaModelException ex){
-// }
-// }
-// }
-// }
+ info.setNonJavaResources(null);
+ info.setChildren(
+ computePackageFragmentRoots(classpath, false));
+
+ } catch(JavaModelException e){
+ try {
+ close(); // could not do better
+ } catch(JavaModelException ex){
+ }
+ }
+ }
+ }
+
+ public void removeLoadPathEntry(IProject anotherPHPProject) {
+ Iterator entries = getLoadPathEntries().iterator();
+ while (entries.hasNext()) {
+ LoadPathEntry entry = (LoadPathEntry) entries.next();
+ if (entry.getType() == LoadPathEntry.TYPE_PROJECT && entry.getProject().getName().equals(anotherPHPProject.getName())) {
+ getLoadPathEntries().remove(entry);
+ fScratched = true;
+ break;
+ }
+ }
+ }
+
+ public void save() throws CoreException {
+ if (fScratched) {
+ InputStream xmlPath = new ByteArrayInputStream(getLoadPathXML().getBytes());
+ IFile loadPathsFile = getLoadPathEntriesFile();
+ if (!loadPathsFile.exists())
+ loadPathsFile.create(xmlPath, true, null);
+ else
+ loadPathsFile.setContents(xmlPath, true, false, null);
+
+ fScratched = false;
+ }
+ }
+
}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaProjectElementInfo.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaProjectElementInfo.java
new file mode 100644
index 0000000..c4ff0ad
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/JavaProjectElementInfo.java
@@ -0,0 +1,225 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core;
+
+import net.sourceforge.phpdt.core.IClasspathEntry;
+import net.sourceforge.phpdt.core.JavaModelException;
+
+import org.eclipse.core.resources.IContainer;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IPath;
+
+/**
+ * Info for IJavaProject.
+ * getChildren()
returns all of the IPackageFragmentRoots
+ * specified on the classpath for the project. This can include roots external to the
+ * project. See JavaProject#getAllPackageFragmentRoots()
and
+ * JavaProject#getPackageFragmentRoots()
. To get only the IPackageFragmentRoots
+ * that are internal to the project, use JavaProject#getChildren()
.
+ */
+
+/* package */
+class JavaProjectElementInfo extends OpenableElementInfo {
+
+ /**
+ * The name lookup facility to use with this project.
+ */
+ protected NameLookup fNameLookup = null;
+
+ /**
+ * The searchable builder environment facility used
+ * with this project (doubles as the builder environment).
+ */
+ protected SearchableEnvironment fSearchableEnvironment = null;
+
+ /**
+ * A array with all the non-java resources contained by this PackageFragment
+ */
+ private Object[] fNonJavaResources;
+
+ /**
+ * Create and initialize a new instance of the receiver
+ */
+ public JavaProjectElementInfo() {
+ fNonJavaResources = null;
+ }
+
+ /**
+ * Compute the non-java resources contained in this java project.
+ */
+ private Object[] computeNonJavaResources(JavaProject project) {
+
+ // determine if src == project and/or if bin == project
+ IPath projectPath = project.getProject().getFullPath();
+ boolean srcIsProject = false;
+ boolean binIsProject = false;
+ char[][] exclusionPatterns = null;
+ IClasspathEntry[] classpath = null;
+ IPath projectOutput = null;
+ try {
+ classpath = project.getResolvedClasspath(true/*ignore unresolved variable*/);
+ for (int i = 0; i < classpath.length; i++) {
+ IClasspathEntry entry = classpath[i];
+ if (projectPath.equals(entry.getPath())) {
+ srcIsProject = true;
+ exclusionPatterns = ((ClasspathEntry)entry).fullExclusionPatternChars();
+ break;
+ }
+ }
+ projectOutput = project.getOutputLocation();
+ binIsProject = projectPath.equals(projectOutput);
+ } catch (JavaModelException e) {
+ // ignore
+ }
+
+ Object[] nonJavaResources = new IResource[5];
+ int nonJavaResourcesCounter = 0;
+ try {
+ IResource[] members = ((IContainer) project.getResource()).members();
+ for (int i = 0, max = members.length; i < max; i++) {
+ IResource res = members[i];
+ switch (res.getType()) {
+ case IResource.FILE :
+ IPath resFullPath = res.getFullPath();
+ String resName = res.getName();
+
+ // ignore a jar file on the classpath
+// if (Util.isArchiveFileName(resName) && this.isClasspathEntryOrOutputLocation(resFullPath, classpath, projectOutput)) {
+// break;
+// }
+ // ignore .java file if src == project
+ if (srcIsProject
+// && Util.isValidCompilationUnitName(resName)
+ && !Util.isExcluded(res, exclusionPatterns)) {
+ break;
+ }
+ // ignore .class file if bin == project
+// if (binIsProject && Util.isValidClassFileName(resName)) {
+// break;
+// }
+ // else add non java resource
+ if (nonJavaResources.length == nonJavaResourcesCounter) {
+ // resize
+ System.arraycopy(
+ nonJavaResources,
+ 0,
+ (nonJavaResources = new IResource[nonJavaResourcesCounter * 2]),
+ 0,
+ nonJavaResourcesCounter);
+ }
+ nonJavaResources[nonJavaResourcesCounter++] = res;
+ break;
+ case IResource.FOLDER :
+ resFullPath = res.getFullPath();
+
+ // ignore non-excluded folders on the classpath or that correspond to an output location
+ if ((srcIsProject && !Util.isExcluded(res, exclusionPatterns) && Util.isValidFolderNameForPackage(res.getName()))
+ || this.isClasspathEntryOrOutputLocation(resFullPath, classpath, projectOutput)) {
+ break;
+ }
+ // else add non java resource
+ if (nonJavaResources.length == nonJavaResourcesCounter) {
+ // resize
+ System.arraycopy(
+ nonJavaResources,
+ 0,
+ (nonJavaResources = new IResource[nonJavaResourcesCounter * 2]),
+ 0,
+ nonJavaResourcesCounter);
+ }
+ nonJavaResources[nonJavaResourcesCounter++] = res;
+ }
+ }
+ if (nonJavaResources.length != nonJavaResourcesCounter) {
+ System.arraycopy(
+ nonJavaResources,
+ 0,
+ (nonJavaResources = new IResource[nonJavaResourcesCounter]),
+ 0,
+ nonJavaResourcesCounter);
+ }
+ } catch (CoreException e) {
+ nonJavaResources = NO_NON_JAVA_RESOURCES;
+ nonJavaResourcesCounter = 0;
+ }
+ return nonJavaResources;
+ }
+
+ /**
+ * @see IJavaProject
+ */
+ protected NameLookup getNameLookup() {
+
+ return fNameLookup;
+ }
+
+ /**
+ * Returns an array of non-java resources contained in the receiver.
+ */
+ Object[] getNonJavaResources(JavaProject project) {
+
+ Object[] nonJavaResources = fNonJavaResources;
+ if (nonJavaResources == null) {
+ nonJavaResources = computeNonJavaResources(project);
+ fNonJavaResources = nonJavaResources;
+ }
+ return nonJavaResources;
+ }
+
+ /**
+ * @see IJavaProject
+ */
+ protected SearchableEnvironment getSearchableEnvironment() {
+
+ return fSearchableEnvironment;
+ }
+ /*
+ * Returns whether the given path is a classpath entry or an output location.
+ */
+ private boolean isClasspathEntryOrOutputLocation(IPath path, IClasspathEntry[] resolvedClasspath, IPath projectOutput) {
+ if (projectOutput.equals(path)) return true;
+ for (int i = 0, length = resolvedClasspath.length; i < length; i++) {
+ IClasspathEntry entry = resolvedClasspath[i];
+ if (entry.getPath().equals(path)) {
+ return true;
+ }
+ IPath output;
+ if ((output = entry.getOutputLocation()) != null && output.equals(path)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ protected void setNameLookup(NameLookup newNameLookup) {
+
+ fNameLookup = newNameLookup;
+
+ // Reinitialize the searchable name environment since it caches
+ // the name lookup.
+ fSearchableEnvironment = null;
+ }
+
+ /**
+ * Set the fNonJavaResources to res value
+ */
+ synchronized void setNonJavaResources(Object[] resources) {
+
+ fNonJavaResources = resources;
+ }
+
+ protected void setSearchableEnvironment(SearchableEnvironment newSearchableEnvironment) {
+
+ fSearchableEnvironment = newSearchableEnvironment;
+ }
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/Member.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/Member.java
new file mode 100644
index 0000000..1d53b70
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/Member.java
@@ -0,0 +1,218 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core;
+
+import java.util.ArrayList;
+
+import net.sourceforge.phpdt.core.Flags;
+import net.sourceforge.phpdt.core.IJavaElement;
+import net.sourceforge.phpdt.core.IMember;
+import net.sourceforge.phpdt.core.IMethod;
+import net.sourceforge.phpdt.core.ISourceRange;
+import net.sourceforge.phpdt.core.IType;
+import net.sourceforge.phpdt.core.JavaModelException;
+import net.sourceforge.phpdt.core.Signature;
+import net.sourceforge.phpdt.core.jdom.IDOMNode;
+
+import com.sun.corba.se.internal.core.Constant;
+
+
+/**
+ * @see IMember
+ */
+
+/* package */ abstract class Member extends SourceRefElement implements IMember {
+protected Member(int type, IJavaElement parent, String name) {
+ super(type, parent, name);
+}
+protected boolean areSimilarMethods(
+ String name1, String[] params1,
+ String name2, String[] params2,
+ String[] simpleNames1) {
+
+ if (name1.equals(name2)) {
+ int params1Length = params1.length;
+ if (params1Length == params2.length) {
+ for (int i = 0; i < params1Length; i++) {
+ String simpleName1 =
+ simpleNames1 == null ?
+ Signature.getSimpleName(Signature.toString(params1[i])) :
+ simpleNames1[i];
+ String simpleName2 = Signature.getSimpleName(Signature.toString(params2[i]));
+ if (!simpleName1.equals(simpleName2)) {
+ return false;
+ }
+ }
+ return true;
+ }
+ }
+ return false;
+}
+/**
+ * Converts a field constant from the compiler's representation
+ * to the Java Model constant representation (Number or String).
+ */
+//protected static Object convertConstant(Constant constant) {
+// if (constant == null)
+// return null;
+// if (constant == Constant.NotAConstant) {
+// return null;
+// }
+// switch (constant.typeID()) {
+// case TypeIds.T_boolean :
+// return constant.booleanValue() ? Boolean.TRUE : Boolean.FALSE;
+// case TypeIds.T_byte :
+// return new Byte(constant.byteValue());
+// case TypeIds.T_char :
+// return new Character(constant.charValue());
+// case TypeIds.T_double :
+// return new Double(constant.doubleValue());
+// case TypeIds.T_float :
+// return new Float(constant.floatValue());
+// case TypeIds.T_int :
+// return new Integer(constant.intValue());
+// case TypeIds.T_long :
+// return new Long(constant.longValue());
+// case TypeIds.T_short :
+// return new Short(constant.shortValue());
+// case TypeIds.T_String :
+// return constant.stringValue();
+// default :
+// return null;
+// }
+//}
+/**
+ * @see JavaElement#equalsDOMNode
+ */
+protected boolean equalsDOMNode(IDOMNode node) throws JavaModelException {
+ return getElementName().equals(node.getName());
+}
+/*
+ * Helper method for SourceType.findMethods and BinaryType.findMethods
+ */
+protected IMethod[] findMethods(IMethod method, IMethod[] methods) {
+ String elementName = method.getElementName();
+ String[] parameters = method.getParameterTypes();
+ int paramLength = parameters.length;
+ String[] simpleNames = new String[paramLength];
+ for (int i = 0; i < paramLength; i++) {
+ simpleNames[i] = Signature.getSimpleName(Signature.toString(parameters[i]));
+ }
+ ArrayList list = new ArrayList();
+ next: for (int i = 0, length = methods.length; i < length; i++) {
+ IMethod existingMethod = methods[i];
+ if (this.areSimilarMethods(
+ elementName,
+ parameters,
+ existingMethod.getElementName(),
+ existingMethod.getParameterTypes(),
+ simpleNames)) {
+ list.add(existingMethod);
+ }
+ }
+ int size = list.size();
+ if (size == 0) {
+ return null;
+ } else {
+ IMethod[] result = new IMethod[size];
+ list.toArray(result);
+ return result;
+ }
+}
+/**
+ * @see IMember
+ */
+//public IClassFile getClassFile() {
+// return ((JavaElement)getParent()).getClassFile();
+//}
+/**
+ * @see IMember
+ */
+public IType getDeclaringType() {
+ JavaElement parent = (JavaElement)getParent();
+ if (parent.fLEType == TYPE) {
+ return (IType) parent;
+ }
+ return null;
+}
+/**
+ * @see IMember
+ */
+public int getFlags() throws JavaModelException {
+ MemberElementInfo info = (MemberElementInfo) getElementInfo();
+ return info.getModifiers();
+}
+/**
+ * @see JavaElement#getHandleMemento()
+ */
+protected char getHandleMementoDelimiter() {
+ return JavaElement.JEM_TYPE;
+}
+/**
+ * @see IMember
+ */
+public ISourceRange getNameRange() throws JavaModelException {
+ MemberElementInfo info= (MemberElementInfo)getElementInfo();
+ return new SourceRange(info.getNameSourceStart(), info.getNameSourceEnd() - info.getNameSourceStart() + 1);
+}
+/**
+ * @see IMember
+ */
+public boolean isBinary() {
+ return false;
+}
+protected boolean isMainMethod(IMethod method) throws JavaModelException {
+ if ("main".equals(method.getElementName()) && Signature.SIG_VOID.equals(method.getReturnType())) { //$NON-NLS-1$
+ int flags= method.getFlags();
+ if (Flags.isStatic(flags) && Flags.isPublic(flags)) {
+ String[] paramTypes= method.getParameterTypes();
+ if (paramTypes.length == 1) {
+ String name= Signature.toString(paramTypes[0]);
+ return "String[]".equals(Signature.getSimpleName(name)); //$NON-NLS-1$
+ }
+ }
+ }
+ return false;
+}
+/**
+ * @see IJavaElement
+ */
+public boolean isReadOnly() {
+ return false; //getClassFile() != null;
+}
+/**
+ */
+public String readableName() {
+
+ IJavaElement declaringType = getDeclaringType();
+ if (declaringType != null) {
+ String declaringName = ((JavaElement) getDeclaringType()).readableName();
+ StringBuffer buffer = new StringBuffer(declaringName);
+ buffer.append('.');
+ buffer.append(this.getElementName());
+ return buffer.toString();
+ } else {
+ return super.readableName();
+ }
+}
+/**
+ * Updates the name range for this element.
+ */
+protected void updateNameRange(int nameStart, int nameEnd) {
+ try {
+ MemberElementInfo info = (MemberElementInfo) getElementInfo();
+ info.setNameSourceStart(nameStart);
+ info.setNameSourceEnd(nameEnd);
+ } catch (JavaModelException npe) {
+ return;
+ }
+}
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/MemberElementInfo.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/MemberElementInfo.java
new file mode 100644
index 0000000..33d7f16
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/MemberElementInfo.java
@@ -0,0 +1,93 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core;
+
+/**
+ *Element info for IMember elements.
+ */
+/* package */ abstract class MemberElementInfo extends SourceRefElementInfo {
+ /**
+ * The modifiers associated with this member.
+ *
+ * @see IConstants
+ */
+ protected int flags;
+
+ /**
+ * The start position of this member's name in the its
+ * openable's buffer.
+ */
+ protected int nameStart= -1;
+
+ /**
+ * The last position of this member's name in the its
+ * openable's buffer.
+ */
+ protected int nameEnd= -1;
+
+ /**
+ * This member's name
+ */
+ protected char[] name;
+ /**
+ * @see org.eclipse.jdt.internal.compiler.env.IGenericType#getModifiers()
+ * @see org.eclipse.jdt.internal.compiler.env.IGenericMethod#getModifiers()
+ * @see org.eclipse.jdt.internal.compiler.env.IGenericField#getModifiers()
+ */
+ public int getModifiers() {
+ return this.flags;
+ }
+ /**
+ * @see org.eclipse.jdt.internal.compiler.env.ISourceType#getName()
+ */
+ public char[] getName() {
+ return this.name;
+ }
+ /**
+ * @see org.eclipse.jdt.internal.compiler.env.ISourceType#getNameSourceEnd()
+ * @see org.eclipse.jdt.internal.compiler.env.ISourceMethod#getNameSourceEnd()
+ * @see org.eclipse.jdt.internal.compiler.env.ISourceField#getNameSourceEnd()
+ */
+ public int getNameSourceEnd() {
+ return this.nameEnd;
+ }
+ /**
+ * @see org.eclipse.jdt.internal.compiler.env.ISourceType#getNameSourceStart()
+ * @see org.eclipse.jdt.internal.compiler.env.ISourceMethod#getNameSourceStart()
+ * @see org.eclipse.jdt.internal.compiler.env.ISourceField#getNameSourceStart()
+ */
+ public int getNameSourceStart() {
+ return this.nameStart;
+ }
+ protected void setFlags(int flags) {
+ this.flags = flags;
+ }
+ /**
+ * Sets this member's name
+ */
+ protected void setName(char[] name) {
+ this.name= name;
+ }
+ /**
+ * Sets the last position of this member's name, relative
+ * to its openable's source buffer.
+ */
+ protected void setNameSourceEnd(int end) {
+ this.nameEnd= end;
+ }
+ /**
+ * Sets the start position of this member's name, relative
+ * to its openable's source buffer.
+ */
+ protected void setNameSourceStart(int start) {
+ this.nameStart= start;
+ }
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/MoveElementsOperation.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/MoveElementsOperation.java
new file mode 100644
index 0000000..d1aad40
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/MoveElementsOperation.java
@@ -0,0 +1,45 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core;
+
+import net.sourceforge.phpdt.core.IJavaElement;
+
+/**
+ * This operation moves elements from their current
+ * container to a specified destination container, optionally renaming the
+ * elements.
+ * A move operation is equivalent to a copy operation, where
+ * the source elements are deleted after the copy.
+ * String
to use as the main task name
+ * for progress monitoring.
+ */
+protected String getMainTaskName() {
+ return Util.bind("operation.moveElementProgress"); //$NON-NLS-1$
+}
+/**
+ * @see CopyElementsOperation#isMove()
+ */
+protected boolean isMove() {
+ return true;
+}
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/MoveResourceElementsOperation.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/MoveResourceElementsOperation.java
new file mode 100644
index 0000000..943b1dc
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/MoveResourceElementsOperation.java
@@ -0,0 +1,44 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core;
+
+import net.sourceforge.phpdt.core.IJavaElement;
+
+/**
+ * This operation moves resources (package fragments and compilation units) from their current
+ * container to a specified destination container, optionally renaming the
+ * elements.
+ * A move resource operation is equivalent to a copy resource operation, where
+ * the source resources are deleted after the copy.
+ * IJavaElement
.
+ * It is responible for running each operation in turn, collecting
+ * the errors and merging the corresponding JavaElementDelta
s.
+ * JavaModelStatus
. Otherwise, a simple JavaModelStatus
+ * is thrown.
+ */
+public abstract class MultiOperation extends JavaModelOperation {
+ /**
+ * The list of renamings supplied to the operation
+ */
+ protected String[] fRenamingsList= null;
+ /**
+ * Table specifying the new parent for elements being
+ * copied/moved/renamed.
+ * Keyed by elements being processed, and
+ * values are the corresponding destination parent.
+ */
+ protected Map fParentElements;
+ /**
+ * Table specifying insertion positions for elements being
+ * copied/moved/renamed. Keyed by elements being processed, and
+ * values are the corresponding insertion point.
+ * @see processElements(IProgressMonitor)
+ */
+ protected Map fInsertBeforeElements= new HashMap(1);
+ /**
+ * This table presents the data in fRenamingList
in a more
+ * convenient way.
+ */
+ protected Map fRenamings;
+ /**
+ * Creates a new MultiOperation
.
+ */
+ protected MultiOperation(IJavaElement[] elementsToProcess, IJavaElement[] parentElements, boolean force) {
+ super(elementsToProcess, parentElements, force);
+ fParentElements = new HashMap(elementsToProcess.length);
+ if (elementsToProcess.length == parentElements.length) {
+ for (int i = 0; i < elementsToProcess.length; i++) {
+ fParentElements.put(elementsToProcess[i], parentElements[i]);
+ }
+ } else { //same destination for all elements to be moved/copied/renamed
+ for (int i = 0; i < elementsToProcess.length; i++) {
+ fParentElements.put(elementsToProcess[i], parentElements[0]);
+ }
+ }
+
+ }
+ /**
+ * Creates a new MultiOperation
on elementsToProcess
.
+ */
+ protected MultiOperation(IJavaElement[] elementsToProcess, boolean force) {
+ super(elementsToProcess, force);
+ }
+ /**
+ * Convenience method to create a JavaModelException
+ * embending a JavaModelStatus
.
+ */
+ protected void error(int code, IJavaElement element) throws JavaModelException {
+ throw new JavaModelException(new JavaModelStatus(code, element));
+ }
+ /**
+ * Executes the operation.
+ *
+ * @exception JavaModelException if one or several errors occured during the operation.
+ * If multiple errors occured, the corresponding JavaModelStatus
is a
+ * multi-status. Otherwise, it is a simple one.
+ */
+ protected void executeOperation() throws JavaModelException {
+ processElements();
+ }
+ /**
+ * Returns the parent of the element being copied/moved/renamed.
+ */
+ protected IJavaElement getDestinationParent(IJavaElement child) {
+ return (IJavaElement)fParentElements.get(child);
+ }
+ /**
+ * Returns the name to be used by the progress monitor.
+ */
+ protected abstract String getMainTaskName();
+ /**
+ * Returns the new name for element
, or null
+ * if there are no renamings specified.
+ */
+ protected String getNewNameFor(IJavaElement element) {
+ if (fRenamings != null)
+ return (String) fRenamings.get(element);
+ else
+ return null;
+ }
+ /**
+ * Sets up the renamings hashtable - keys are the elements and
+ * values are the new name.
+ */
+ private void initializeRenamings() {
+ if (fRenamingsList != null && fRenamingsList.length == fElementsToProcess.length) {
+ fRenamings = new HashMap(fRenamingsList.length);
+ for (int i = 0; i < fRenamingsList.length; i++) {
+ if (fRenamingsList[i] != null) {
+ fRenamings.put(fElementsToProcess[i], fRenamingsList[i]);
+ }
+ }
+ }
+ }
+ /**
+ * Returns true
if this operation represents a move or rename, false
+ * if this operation represents a copy.
+ * Note: a rename is just a move within the same parent with a name change.
+ */
+ protected boolean isMove() {
+ return false;
+ }
+ /**
+ * Returns true
if this operation represents a rename, false
+ * if this operation represents a copy or move.
+ */
+ protected boolean isRename() {
+ return false;
+ }
+
+ /**
+ * Subclasses must implement this method to process a given IJavaElement
.
+ */
+ protected abstract void processElement(IJavaElement element) throws JavaModelException;
+ /**
+ * Processes all the IJavaElement
s in turn, collecting errors
+ * and updating the progress monitor.
+ *
+ * @exception JavaModelException if one or several operation(s) was unable to
+ * be completed.
+ */
+ protected void processElements() throws JavaModelException {
+ beginTask(getMainTaskName(), fElementsToProcess.length);
+ IJavaModelStatus[] errors = new IJavaModelStatus[3];
+ int errorsCounter = 0;
+ for (int i = 0; i < fElementsToProcess.length; i++) {
+ try {
+ verify(fElementsToProcess[i]);
+ processElement(fElementsToProcess[i]);
+ } catch (JavaModelException jme) {
+ if (errorsCounter == errors.length) {
+ // resize
+ System.arraycopy(errors, 0, (errors = new IJavaModelStatus[errorsCounter*2]), 0, errorsCounter);
+ }
+ errors[errorsCounter++] = jme.getJavaModelStatus();
+ } finally {
+ worked(1);
+ }
+ }
+ done();
+ if (errorsCounter == 1) {
+ throw new JavaModelException(errors[0]);
+ } else if (errorsCounter > 1) {
+ if (errorsCounter != errors.length) {
+ // resize
+ System.arraycopy(errors, 0, (errors = new IJavaModelStatus[errorsCounter]), 0, errorsCounter);
+ }
+ throw new JavaModelException(JavaModelStatus.newMultiStatus(errors));
+ }
+ }
+ /**
+ * Sets the insertion position in the new container for the modified element. The element
+ * being modified will be inserted before the specified new sibling. The given sibling
+ * must be a child of the destination container specified for the modified element.
+ * The default is null
, which indicates that the element is to be
+ * inserted at the end of the container.
+ */
+ public void setInsertBefore(IJavaElement modifiedElement, IJavaElement newSibling) {
+ fInsertBeforeElements.put(modifiedElement, newSibling);
+ }
+ /**
+ * Sets the new names to use for each element being copied. The renamings
+ * correspond to the elements being processed, and the number of
+ * renamings must match the number of elements being processed.
+ * A null
entry in the list indicates that an element
+ * is not to be renamed.
+ *
+ * IJavaElement
before
+ * processElement
. It should check that this element
+ * can be processed.
+ */
+ protected abstract void verify(IJavaElement element) throws JavaModelException;
+ /**
+ * Verifies that the destination
specified for the element
is valid for the types of the
+ * element
and destination
.
+ */
+ protected void verifyDestination(IJavaElement element, IJavaElement destination) throws JavaModelException {
+ if (destination == null || !destination.exists())
+ error(IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST, destination);
+
+ int destType = destination.getElementType();
+ switch (element.getElementType()) {
+ case IJavaElement.PACKAGE_DECLARATION :
+ case IJavaElement.IMPORT_DECLARATION :
+ if (destType != IJavaElement.COMPILATION_UNIT)
+ error(IJavaModelStatusConstants.INVALID_DESTINATION, element);
+ break;
+ case IJavaElement.TYPE :
+ if (destType != IJavaElement.COMPILATION_UNIT && destType != IJavaElement.TYPE)
+ error(IJavaModelStatusConstants.INVALID_DESTINATION, element);
+ break;
+ case IJavaElement.METHOD :
+ case IJavaElement.FIELD :
+// case IJavaElement.INITIALIZER :
+// if (destType != IJavaElement.TYPE || destination instanceof BinaryType)
+// error(IJavaModelStatusConstants.INVALID_DESTINATION, element);
+// break;
+ case IJavaElement.COMPILATION_UNIT :
+ if (destType != IJavaElement.PACKAGE_FRAGMENT)
+ error(IJavaModelStatusConstants.INVALID_DESTINATION, element);
+ else if (isMove() && ((ICompilationUnit) element).isWorkingCopy())
+ error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element);
+ break;
+ case IJavaElement.PACKAGE_FRAGMENT :
+ IPackageFragment fragment = (IPackageFragment) element;
+ IJavaElement parent = fragment.getParent();
+ if (parent.isReadOnly())
+ error(IJavaModelStatusConstants.READ_ONLY, element);
+ else if (destType != IJavaElement.PACKAGE_FRAGMENT_ROOT)
+ error(IJavaModelStatusConstants.INVALID_DESTINATION, element);
+ break;
+ default :
+ error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element);
+ }
+ }
+ /**
+ * Verify that the new name specified for element
is
+ * valid for that type of Java element.
+ */
+ protected void verifyRenaming(IJavaElement element) throws JavaModelException {
+ String newName = getNewNameFor(element);
+ boolean isValid = true;
+
+ switch (element.getElementType()) {
+ case IJavaElement.PACKAGE_FRAGMENT :
+ if (element.getElementName().equals(IPackageFragment.DEFAULT_PACKAGE_NAME)) {
+ // don't allow renaming of default package (see PR #1G47GUM)
+ throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.NAME_COLLISION, element));
+ }
+// isValid = JavaConventions.validatePackageName(newName).getSeverity() != IStatus.ERROR;
+ isValid = true;
+ break;
+ case IJavaElement.COMPILATION_UNIT :
+// isValid = JavaConventions.validateCompilationUnitName(newName).getSeverity() != IStatus.ERROR;
+ isValid = true;
+ break;
+ case IJavaElement.INITIALIZER :
+ isValid = false; //cannot rename initializers
+ break;
+ default :
+// isValid = JavaConventions.validateIdentifier(newName).getSeverity() != IStatus.ERROR;
+ isValid = true;
+ break;
+ }
+
+ if (!isValid) {
+ throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_NAME, element, newName));
+ }
+ }
+ /**
+ * Verifies that the positioning sibling specified for the element
is exists and
+ * its parent is the destination container of this element
.
+ */
+ protected void verifySibling(IJavaElement element, IJavaElement destination) throws JavaModelException {
+ IJavaElement insertBeforeElement = (IJavaElement) fInsertBeforeElements.get(element);
+ if (insertBeforeElement != null) {
+ if (!insertBeforeElement.exists() || !insertBeforeElement.getParent().equals(destination)) {
+ error(IJavaModelStatusConstants.INVALID_SIBLING, insertBeforeElement);
+ }
+ }
+ }
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/NameLookup.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/NameLookup.java
new file mode 100644
index 0000000..d32a9d3
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/NameLookup.java
@@ -0,0 +1,765 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Map;
+
+import net.sourceforge.phpdt.core.IClasspathEntry;
+import net.sourceforge.phpdt.core.IJavaElement;
+import net.sourceforge.phpdt.core.IJavaProject;
+import net.sourceforge.phpdt.core.IPackageFragment;
+import net.sourceforge.phpdt.core.IPackageFragmentRoot;
+import net.sourceforge.phpdt.core.IType;
+import net.sourceforge.phpdt.core.IWorkingCopy;
+import net.sourceforge.phpdt.core.JavaModelException;
+import net.sourceforge.phpdt.core.ICompilationUnit;
+import net.sourceforge.phpdt.internal.core.util.PerThreadObject;
+import net.sourceforge.phpeclipse.PHPCore;
+
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.IWorkspace;
+import org.eclipse.core.resources.ResourcesPlugin;
+import org.eclipse.core.runtime.IPath;
+/**
+ * A NameLookup
provides name resolution within a Java project.
+ * The name lookup facility uses the project's classpath to prioritize the
+ * order in which package fragments are searched when resolving a name.
+ *
+ * null
is returned.
+ *
+ * find*
are intended to be convenience methods for quickly
+ * finding an element within another element; for instance, for finding a class within a
+ * package. The other set of methods all begin with seek*
. These methods
+ * do comprehensive searches of the IJavaProject
returning hits
+ * in real time through an IJavaElementRequestor
.
+ *
+ */
+public class NameLookup {
+ /**
+ * Accept flag for specifying classes.
+ */
+ public static final int ACCEPT_CLASSES = 0x00000002;
+
+ /**
+ * Accept flag for specifying interfaces.
+ */
+ public static final int ACCEPT_INTERFACES = 0x00000004;
+
+ /**
+ * The IPackageFragmentRoot
's associated
+ * with the classpath of this NameLookup facility's
+ * project.
+ */
+ protected IPackageFragmentRoot[] fPackageFragmentRoots= null;
+
+ /**
+ * Table that maps package names to lists of package fragments for
+ * all package fragments in the package fragment roots known
+ * by this name lookup facility. To allow > 1 package fragment
+ * with the same name, values are arrays of package fragments
+ * ordered as they appear on the classpath.
+ */
+ protected Map fPackageFragments;
+
+ /**
+ * The IWorkspace
that this NameLookup
+ * is configure within.
+ */
+ protected IWorkspace workspace;
+
+ /**
+ * A map from compilation unit handles to units to look inside (compilation
+ * units or working copies).
+ * Allows working copies to take precedence over compilation units.
+ * The cache is a 2-level cache, first keyed by thread.
+ */
+ protected PerThreadObject unitsToLookInside = new PerThreadObject();
+
+ public NameLookup(IJavaProject project) throws JavaModelException {
+ configureFromProject(project);
+ }
+
+ /**
+ * Returns true if:
+ *
+ * Otherwise, false is returned.
+ */
+ protected boolean acceptType(IType type, int acceptFlags) {
+ if (acceptFlags == 0)
+ return true; // no flags, always accepted
+ try {
+ if (type.isClass()) {
+ return (acceptFlags & ACCEPT_CLASSES) != 0;
+ } else {
+ return (acceptFlags & ACCEPT_INTERFACES) != 0;
+ }
+ } catch (JavaModelException npe) {
+ return false; // the class is not present, do not accept.
+ }
+ }
+
+ /**
+ * Configures this ACCEPT_CLASSES
+ * bit is on
+ * ACCEPT_INTERFACES
+ * bit is on
+ * ACCEPT_CLASSES
or ACCEPT_INTERFACES
+ * bit is on
+ * NameLookup
based on the
+ * info of the given IJavaProject
.
+ *
+ * @throws JavaModelException if the IJavaProject
has no classpath.
+ */
+ private void configureFromProject(IJavaProject project) throws JavaModelException {
+ workspace= ResourcesPlugin.getWorkspace();
+ fPackageFragmentRoots= ((JavaProject) project).getAllPackageFragmentRoots();
+ fPackageFragments= new HashMap();
+ IPackageFragment[] frags = this.getPackageFragmentsInRoots(fPackageFragmentRoots, project);
+ for (int i= 0; i < frags.length; i++) {
+ IPackageFragment fragment= frags[i];
+ IPackageFragment[] entry= (IPackageFragment[]) fPackageFragments.get(fragment.getElementName());
+ if (entry == null) {
+ entry= new IPackageFragment[1];
+ entry[0]= fragment;
+ fPackageFragments.put(fragment.getElementName(), entry);
+ } else {
+ IPackageFragment[] copy= new IPackageFragment[entry.length + 1];
+ System.arraycopy(entry, 0, copy, 0, entry.length);
+ copy[entry.length]= fragment;
+ fPackageFragments.put(fragment.getElementName(), copy);
+ }
+ }
+ }
+
+ /**
+ * Finds every type in the project whose simple name matches
+ * the prefix, informing the requestor of each hit. The requestor
+ * is polled for cancellation at regular intervals.
+ *
+ * partialMatch
argument indicates partial matches
+ * should be considered.
+ */
+ private void findAllTypes(String prefix, boolean partialMatch, int acceptFlags, IJavaElementRequestor requestor) {
+ int count= fPackageFragmentRoots.length;
+ for (int i= 0; i < count; i++) {
+ if (requestor.isCanceled())
+ return;
+ IPackageFragmentRoot root= fPackageFragmentRoots[i];
+ IJavaElement[] packages= null;
+ try {
+ packages= root.getChildren();
+ } catch (JavaModelException npe) {
+ continue; // the root is not present, continue;
+ }
+ if (packages != null) {
+ for (int j= 0, packageCount= packages.length; j < packageCount; j++) {
+ if (requestor.isCanceled())
+ return;
+ seekTypes(prefix, (IPackageFragment) packages[j], partialMatch, acceptFlags, requestor);
+ }
+ }
+ }
+ }
+
+ /**
+ * Returns the ICompilationUnit
which defines the type
+ * named qualifiedTypeName
, or null
if
+ * none exists. The domain of the search is bounded by the classpath
+ * of the IJavaProject
this NameLookup
was
+ * obtained from.
+ * null
if none exist. The domain of
+ * the search is bounded by the classpath of the IJavaProject
+ * this NameLookup
was obtained from.
+ * The path can be:
+ * - internal to the workbench: "/Project/src"
+ * - external to the workbench: "c:/jdk/classes.zip/java/lang"
+ */
+ public IPackageFragment findPackageFragment(IPath path) {
+ if (!path.isAbsolute()) {
+ throw new IllegalArgumentException(Util.bind("path.mustBeAbsolute")); //$NON-NLS-1$
+ }
+/*
+ * this code should rather use the package fragment map to find the candidate package, then
+ * check if the respective enclosing root maps to the one on this given IPath.
+ */
+ IResource possibleFragment = workspace.getRoot().findMember(path);
+ if (possibleFragment == null) {
+ //external jar
+ for (int i = 0; i < fPackageFragmentRoots.length; i++) {
+ IPackageFragmentRoot root = fPackageFragmentRoots[i];
+ if (!root.isExternal()) {
+ continue;
+ }
+ IPath rootPath = root.getPath();
+ int matchingCount = rootPath.matchingFirstSegments(path);
+ if (matchingCount != 0) {
+ String name = path.toOSString();
+ // + 1 is for the File.separatorChar
+ name = name.substring(rootPath.toOSString().length() + 1, name.length());
+ name = name.replace(File.separatorChar, '.');
+ IJavaElement[] list = null;
+ try {
+ list = root.getChildren();
+ } catch (JavaModelException npe) {
+ continue; // the package fragment root is not present;
+ }
+ int elementCount = list.length;
+ for (int j = 0; j < elementCount; j++) {
+ IPackageFragment packageFragment = (IPackageFragment) list[j];
+ if (nameMatches(name, packageFragment, false)) {
+ return packageFragment;
+ }
+ }
+ }
+ }
+ } else {
+ IJavaElement fromFactory = PHPCore.create(possibleFragment);
+ if (fromFactory == null) {
+ return null;
+ }
+ if (fromFactory instanceof IPackageFragment) {
+ return (IPackageFragment) fromFactory;
+ } else
+ if (fromFactory instanceof IJavaProject) {
+ // default package in a default root
+ JavaProject project = (JavaProject) fromFactory;
+ try {
+ IClasspathEntry entry = project.getClasspathEntryFor(path);
+ if (entry != null) {
+ IPackageFragmentRoot root =
+ project.getPackageFragmentRoot(project.getResource());
+ IPackageFragment[] pkgs = (IPackageFragment[]) fPackageFragments.get(IPackageFragment.DEFAULT_PACKAGE_NAME);
+ if (pkgs == null) {
+ return null;
+ }
+ for (int i = 0; i < pkgs.length; i++) {
+ if (pkgs[i].getParent().equals(root)) {
+ return pkgs[i];
+ }
+ }
+ }
+ } catch (JavaModelException e) {
+ return null;
+ }
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Returns the package fragments whose name matches the given
+ * (qualified) name, or null
if none exist.
+ *
+ * The name can be:
+ * - empty: ""
+ * - qualified: "pack.pack1.pack2"
+ * @param partialMatch partial name matches qualify when true
,
+ * only exact name matches qualify when false
+ */
+ public IPackageFragment[] findPackageFragments(String name, boolean partialMatch) {
+ int count= fPackageFragmentRoots.length;
+ if (partialMatch) {
+ name= name.toLowerCase();
+ for (int i= 0; i < count; i++) {
+ IPackageFragmentRoot root= fPackageFragmentRoots[i];
+ IJavaElement[] list= null;
+ try {
+ list= root.getChildren();
+ } catch (JavaModelException npe) {
+ continue; // the package fragment root is not present;
+ }
+ int elementCount= list.length;
+ IPackageFragment[] result = new IPackageFragment[elementCount];
+ int resultLength = 0;
+ for (int j= 0; j < elementCount; j++) {
+ IPackageFragment packageFragment= (IPackageFragment) list[j];
+ if (nameMatches(name, packageFragment, true)) {
+ result[resultLength++] = packageFragment;
+ }
+ }
+ if (resultLength > 0) {
+ System.arraycopy(result, 0, result = new IPackageFragment[resultLength], 0, resultLength);
+ return result;
+ } else {
+ return null;
+ }
+ }
+ } else {
+ IPackageFragment[] fragments= (IPackageFragment[]) fPackageFragments.get(name);
+ if (fragments != null) {
+ IPackageFragment[] result = new IPackageFragment[fragments.length];
+ int resultLength = 0;
+ for (int i= 0; i < fragments.length; i++) {
+ IPackageFragment packageFragment= fragments[i];
+ result[resultLength++] = packageFragment;
+ }
+ if (resultLength > 0) {
+ System.arraycopy(result, 0, result = new IPackageFragment[resultLength], 0, resultLength);
+ return result;
+ } else {
+ return null;
+ }
+ }
+ }
+ return null;
+ }
+
+ /**
+ *
+ */
+ public IType findType(String typeName, String packageName, boolean partialMatch, int acceptFlags) {
+ if (packageName == null) {
+ packageName= IPackageFragment.DEFAULT_PACKAGE_NAME;
+ }
+ JavaElementRequestor elementRequestor = new JavaElementRequestor();
+ seekPackageFragments(packageName, false, elementRequestor);
+ IPackageFragment[] packages= elementRequestor.getPackageFragments();
+
+ for (int i= 0, length= packages.length; i < length; i++) {
+ IType type= findType(typeName, packages[i], partialMatch, acceptFlags);
+ if (type != null)
+ return type;
+ }
+ return null;
+ }
+ /**
+ * Returns all the package fragments found in the specified
+ * package fragment roots. Make sure the returned fragments have the given
+ * project as great parent. This ensures the name lookup will not refer to another
+ * project (through jar package fragment roots)
+ */
+ private IPackageFragment[] getPackageFragmentsInRoots(IPackageFragmentRoot[] roots, IJavaProject project) {
+
+ // The following code assumes that all the roots have the given project as their parent
+ ArrayList frags = new ArrayList();
+ for (int i = 0; i < roots.length; i++) {
+ IPackageFragmentRoot root = roots[i];
+ try {
+ IJavaElement[] children = root.getChildren();
+
+ /* 2 jar package fragment roots can be equals but not belonging
+ to the same project. As a result, they share the same element info.
+ So this jar package fragment root could get the children of
+ another jar package fragment root.
+ The following code ensures that the children of this jar package
+ fragment root have the given project as a great parent.
+ */
+ int length = children.length;
+ if (length == 0) continue;
+ if (children[0].getParent().getParent().equals(project)) {
+ // the children have the right parent, simply add them to the list
+ for (int j = 0; j < length; j++) {
+ frags.add(children[j]);
+ }
+ } else {
+ // create a new handle with the root as the parent
+ for (int j = 0; j < length; j++) {
+ frags.add(root.getPackageFragment(children[j].getElementName()));
+ }
+ }
+ } catch (JavaModelException e) {
+ // do nothing
+ }
+ }
+ IPackageFragment[] fragments = new IPackageFragment[frags.size()];
+ frags.toArray(fragments);
+ return fragments;
+ }
+
+ /**
+ * Returns the first type in the given package whose name
+ * matches the given (unqualified) name, or null
if none
+ * exist. Specifying a null
package will result in no matches.
+ * The domain of the search is bounded by the Java project from which
+ * this name lookup was obtained.
+ *
+ * @param name the name of the type to find
+ * @param pkg the package to search
+ * @param partialMatch partial name matches qualify when true
,
+ * only exact name matches qualify when false
+ * @param acceptFlags a bit mask describing if classes, interfaces or both classes and interfaces
+ * are desired results. If no flags are specified, all types are returned.
+ *
+ * @see #ACCEPT_CLASSES
+ * @see #ACCEPT_INTERFACES
+ */
+ public IType findType(String name, IPackageFragment pkg, boolean partialMatch, int acceptFlags) {
+ if (pkg == null) {
+ return null;
+ }
+ // Return first found (ignore duplicates).
+//synchronized(JavaModelManager.getJavaModelManager()){
+// SingleTypeRequestor typeRequestor = new SingleTypeRequestor();
+// seekTypes(name, pkg, partialMatch, acceptFlags, typeRequestor);
+// IType type= typeRequestor.getType();
+// return type;
+//}
+ return null;
+ }
+
+ /**
+ * Returns the type specified by the qualified name, or null
+ * if none exist. The domain of
+ * the search is bounded by the Java project from which this name lookup was obtained.
+ *
+ * @param name the name of the type to find
+ * @param partialMatch partial name matches qualify when true
,
+ * only exact name matches qualify when false
+ * @param acceptFlags a bit mask describing if classes, interfaces or both classes and interfaces
+ * are desired results. If no flags are specified, all types are returned.
+ *
+ * @see #ACCEPT_CLASSES
+ * @see #ACCEPT_INTERFACES
+ */
+ public IType findType(String name, boolean partialMatch, int acceptFlags) {
+ int index= name.lastIndexOf('.');
+ String className= null, packageName= null;
+ if (index == -1) {
+ packageName= IPackageFragment.DEFAULT_PACKAGE_NAME;
+ className= name;
+ } else {
+ packageName= name.substring(0, index);
+ className= name.substring(index + 1);
+ }
+ return findType(className, packageName, partialMatch, acceptFlags);
+ }
+
+ /**
+ * Returns true if the given element's name matches the
+ * specified searchName
, otherwise false.
+ *
+ * partialMatch
argument indicates partial matches
+ * should be considered.
+ * NOTE: in partialMatch mode, the case will be ignored, and the searchName must already have
+ * been lowercased.
+ */
+ protected boolean nameMatches(String searchName, IJavaElement element, boolean partialMatch) {
+ if (partialMatch) {
+ // partial matches are used in completion mode, thus case insensitive mode
+ return element.getElementName().toLowerCase().startsWith(searchName);
+ } else {
+ return element.getElementName().equals(searchName);
+ }
+ }
+
+ /**
+ * Notifies the given requestor of all package fragments with the
+ * given name. Checks the requestor at regular intervals to see if the
+ * requestor has canceled. The domain of
+ * the search is bounded by the IJavaProject
+ * this NameLookup
was obtained from.
+ *
+ * @param partialMatch partial name matches qualify when true
;
+ * only exact name matches qualify when false
+ */
+ public void seekPackageFragments(String name, boolean partialMatch, IJavaElementRequestor requestor) {
+ int count= fPackageFragmentRoots.length;
+ String matchName= partialMatch ? name.toLowerCase() : name;
+ for (int i= 0; i < count; i++) {
+ if (requestor.isCanceled())
+ return;
+ IPackageFragmentRoot root= fPackageFragmentRoots[i];
+ IJavaElement[] list= null;
+ try {
+ list= root.getChildren();
+ } catch (JavaModelException npe) {
+ continue; // this root package fragment is not present
+ }
+ int elementCount= list.length;
+ for (int j= 0; j < elementCount; j++) {
+ if (requestor.isCanceled())
+ return;
+ IPackageFragment packageFragment= (IPackageFragment) list[j];
+ if (nameMatches(matchName, packageFragment, partialMatch))
+ requestor.acceptPackageFragment(packageFragment);
+ }
+ }
+ }
+
+ /**
+ * Notifies the given requestor of all types (classes and interfaces) in the
+ * given package fragment with the given (unqualified) name.
+ * Checks the requestor at regular intervals to see if the requestor
+ * has canceled. If the given package fragment is null
, all types in the
+ * project whose simple name matches the given name are found.
+ *
+ * @param name The name to search
+ * @param pkg The corresponding package fragment
+ * @param partialMatch partial name matches qualify when true
;
+ * only exact name matches qualify when false
+ * @param acceptFlags a bit mask describing if classes, interfaces or both classes and interfaces
+ * are desired results. If no flags are specified, all types are returned.
+ * @param requestor The requestor that collects the result
+ *
+ * @see #ACCEPT_CLASSES
+ * @see #ACCEPT_INTERFACES
+ */
+ public void seekTypes(String name, IPackageFragment pkg, boolean partialMatch, int acceptFlags, IJavaElementRequestor requestor) {
+
+ String matchName= partialMatch ? name.toLowerCase() : name;
+ if (matchName.indexOf('.') >= 0) { //looks for member type A.B
+ matchName= matchName.replace('.', '$');
+ }
+ if (pkg == null) {
+ findAllTypes(matchName, partialMatch, acceptFlags, requestor);
+ return;
+ }
+ IPackageFragmentRoot root= (IPackageFragmentRoot) pkg.getParent();
+ try {
+ int packageFlavor= root.getKind();
+ switch (packageFlavor) {
+// case IPackageFragmentRoot.K_BINARY :
+// seekTypesInBinaryPackage(matchName, pkg, partialMatch, acceptFlags, requestor);
+// break;
+ case IPackageFragmentRoot.K_SOURCE :
+ seekTypesInSourcePackage(matchName, pkg, partialMatch, acceptFlags, requestor);
+ break;
+ default :
+ return;
+ }
+ } catch (JavaModelException e) {
+ return;
+ }
+ }
+
+ /**
+ * Performs type search in a binary package.
+ */
+// protected void seekTypesInBinaryPackage(String name, IPackageFragment pkg, boolean partialMatch, int acceptFlags, IJavaElementRequestor requestor) {
+// IClassFile[] classFiles= null;
+// try {
+// classFiles= pkg.getClassFiles();
+// } catch (JavaModelException npe) {
+// return; // the package is not present
+// }
+// int length= classFiles.length;
+//
+// String unqualifiedName= name;
+// int index= name.lastIndexOf('$');
+// if (index != -1) {
+// //the type name of the inner type
+// unqualifiedName= name.substring(index + 1, name.length());
+// // unqualifiedName is empty if the name ends with a '$' sign.
+// // See http://dev.eclipse.org/bugs/show_bug.cgi?id=14642
+// if ((unqualifiedName.length() > 0 && Character.isDigit(unqualifiedName.charAt(0))) || unqualifiedName.length() == 0){
+// unqualifiedName = name;
+// }
+// }
+// String matchName= partialMatch ? name.toLowerCase() : name;
+// for (int i= 0; i < length; i++) {
+// if (requestor.isCanceled())
+// return;
+// IClassFile classFile= classFiles[i];
+// String elementName = classFile.getElementName();
+// if (partialMatch) elementName = elementName.toLowerCase();
+//
+// /**
+// * Must use startWith because matchName will never have the
+// * extension ".class" and the elementName always will.
+// */
+// if (elementName.startsWith(matchName)) {
+// IType type= null;
+// try {
+// type= classFile.getType();
+// } catch (JavaModelException npe) {
+// continue; // the classFile is not present
+// }
+// if (!partialMatch || (type.getElementName().length() > 0 && !Character.isDigit(type.getElementName().charAt(0)))) { //not an anonymous type
+// if (nameMatches(unqualifiedName, type, partialMatch) && acceptType(type, acceptFlags))
+// requestor.acceptType(type);
+// }
+// }
+// }
+// }
+
+ /**
+ * Performs type search in a source package.
+ */
+ protected void seekTypesInSourcePackage(String name, IPackageFragment pkg, boolean partialMatch, int acceptFlags, IJavaElementRequestor requestor) {
+ ICompilationUnit[] compilationUnits = null;
+ try {
+ compilationUnits = pkg.getCompilationUnits();
+ } catch (JavaModelException npe) {
+ return; // the package is not present
+ }
+ int length= compilationUnits.length;
+ String matchName = name;
+ int index= name.indexOf('$');
+ boolean potentialMemberType = false;
+ String potentialMatchName = null;
+ if (index != -1) {
+ //the compilation unit name of the inner type
+ potentialMatchName = name.substring(0, index);
+ potentialMemberType = true;
+ }
+
+ /**
+ * In the following, matchName will never have the extension ".java" and
+ * the compilationUnits always will. So add it if we're looking for
+ * an exact match.
+ */
+ String unitName = partialMatch ? matchName.toLowerCase() : matchName + ".java"; //$NON-NLS-1$
+ String potentialUnitName = null;
+ if (potentialMemberType) {
+ potentialUnitName = partialMatch ? potentialMatchName.toLowerCase() : potentialMatchName + ".java"; //$NON-NLS-1$
+ }
+
+ for (int i= 0; i < length; i++) {
+ if (requestor.isCanceled())
+ return;
+ ICompilationUnit compilationUnit= compilationUnits[i];
+
+ // unit to look inside
+ ICompilationUnit unitToLookInside = null;
+ Map workingCopies = (Map) this.unitsToLookInside.getCurrent();
+ if (workingCopies != null
+ && (unitToLookInside = (ICompilationUnit)workingCopies.get(compilationUnit)) != null){
+ compilationUnit = unitToLookInside;
+ }
+ if ((unitToLookInside != null && !potentialMemberType) || nameMatches(unitName, compilationUnit, partialMatch)) {
+ IType[] types= null;
+ try {
+ types= compilationUnit.getTypes();
+ } catch (JavaModelException npe) {
+ continue; // the compilation unit is not present
+ }
+ int typeLength= types.length;
+ for (int j= 0; j < typeLength; j++) {
+ if (requestor.isCanceled())
+ return;
+ IType type= types[j];
+ if (nameMatches(matchName, type, partialMatch)) {
+ if (acceptType(type, acceptFlags)) requestor.acceptType(type);
+ }
+ }
+ } else if (potentialMemberType && nameMatches(potentialUnitName, compilationUnit, partialMatch)) {
+ IType[] types= null;
+ try {
+ types= compilationUnit.getTypes();
+ } catch (JavaModelException npe) {
+ continue; // the compilation unit is not present
+ }
+ int typeLength= types.length;
+ for (int j= 0; j < typeLength; j++) {
+ if (requestor.isCanceled())
+ return;
+ IType type= types[j];
+ if (nameMatches(potentialMatchName, type, partialMatch)) {
+ seekQualifiedMemberTypes(name.substring(index + 1, name.length()), type, partialMatch, requestor, acceptFlags);
+ }
+ }
+ }
+
+ }
+ }
+/**
+ * Remembers a set of compilation units that will be looked inside
+ * when looking up a type. If they are working copies, they take
+ * precedence of their compilation units.
+ * null
means that no special compilation units should be used.
+ */
+public void setUnitsToLookInside(IWorkingCopy[] unitsToLookInside) {
+
+ if (unitsToLookInside == null) {
+ this.unitsToLookInside.setCurrent(null);
+ } else {
+ HashMap workingCopies = new HashMap();
+ this.unitsToLookInside.setCurrent(workingCopies);
+ for (int i = 0, length = unitsToLookInside.length; i < length; i++) {
+ IWorkingCopy unitToLookInside = unitsToLookInside[i];
+ ICompilationUnit original = (ICompilationUnit)unitToLookInside.getOriginalElement();
+ if (original != null) {
+ workingCopies.put(original, unitToLookInside);
+ } else {
+ workingCopies.put(unitToLookInside, unitToLookInside);
+ }
+ }
+ }
+}
+
+ /**
+ * Notifies the given requestor of all types (classes and interfaces) in the
+ * given type with the given (possibly qualified) name. Checks
+ * the requestor at regular intervals to see if the requestor
+ * has canceled.
+ *
+ * @param partialMatch partial name matches qualify when true
,
+ * only exact name matches qualify when false
+ */
+ protected void seekQualifiedMemberTypes(String qualifiedName, IType type, boolean partialMatch, IJavaElementRequestor requestor, int acceptFlags) {
+ if (type == null)
+ return;
+ IType[] types= null;
+ try {
+ types= type.getTypes();
+ } catch (JavaModelException npe) {
+ return; // the enclosing type is not present
+ }
+ String matchName= qualifiedName;
+ int index= qualifiedName.indexOf('$');
+ boolean nested= false;
+ if (index != -1) {
+ matchName= qualifiedName.substring(0, index);
+ nested= true;
+ }
+ int length= types.length;
+ for (int i= 0; i < length; i++) {
+ if (requestor.isCanceled())
+ return;
+ IType memberType= types[i];
+ if (nameMatches(matchName, memberType, partialMatch))
+ if (nested) {
+ seekQualifiedMemberTypes(qualifiedName.substring(index + 1, qualifiedName.length()), memberType, partialMatch, requestor, acceptFlags);
+ } else {
+ if (acceptType(memberType, acceptFlags)) requestor.acceptMemberType(memberType);
+ }
+ }
+ }
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/Openable.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/Openable.java
index a8ed665..79481b1 100644
--- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/Openable.java
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/Openable.java
@@ -10,15 +10,26 @@
*******************************************************************************/
package net.sourceforge.phpdt.internal.core;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
import net.sourceforge.phpdt.core.BufferChangedEvent;
import net.sourceforge.phpdt.core.IBuffer;
import net.sourceforge.phpdt.core.IBufferChangedListener;
+import net.sourceforge.phpdt.core.IBufferFactory;
import net.sourceforge.phpdt.core.IJavaElement;
+import net.sourceforge.phpdt.core.IJavaModelStatusConstants;
import net.sourceforge.phpdt.core.IOpenable;
+import net.sourceforge.phpdt.core.IPackageFragmentRoot;
import net.sourceforge.phpdt.core.JavaModelException;
+import net.sourceforge.phpdt.internal.codeassist.ISearchableNameEnvironment;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.IWorkspace;
+import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IProgressMonitor;
/**
@@ -42,57 +53,57 @@ protected Openable(int type, IJavaElement parent, String name) {
*/
public void bufferChanged(BufferChangedEvent event) {
if (event.getBuffer().isClosed()) {
-// JavaModelManager.getJavaModelManager().getElementsOutOfSynchWithBuffers().remove(this);
-// getBufferManager().removeBuffer(event.getBuffer());
+ JavaModelManager.getJavaModelManager().getElementsOutOfSynchWithBuffers().remove(this);
+ getBufferManager().removeBuffer(event.getBuffer());
} else {
-// JavaModelManager.getJavaModelManager().getElementsOutOfSynchWithBuffers().put(this, this);
+ JavaModelManager.getJavaModelManager().getElementsOutOfSynchWithBuffers().put(this, this);
}
}
-///**
-// * Updates the info objects for this element and all of its children by
-// * removing the current infos, generating new infos, and then placing
-// * the new infos into the Java Model cache tables.
-// */
-//protected void buildStructure(OpenableElementInfo info, IProgressMonitor monitor) throws JavaModelException {
-//
-// if (monitor != null && monitor.isCanceled()) return;
-//
-// // remove existing (old) infos
-// removeInfo();
-// HashMap newElements = new HashMap(11);
-// info.setIsStructureKnown(generateInfos(info, monitor, newElements, getResource()));
-// JavaModelManager.getJavaModelManager().getElementsOutOfSynchWithBuffers().remove(this);
-// for (Iterator iter = newElements.keySet().iterator(); iter.hasNext();) {
-// IJavaElement key = (IJavaElement) iter.next();
-// Object value = newElements.get(key);
-// JavaModelManager.getJavaModelManager().putInfo(key, value);
-// }
-//
-// // add the info for this at the end, to ensure that a getInfo cannot reply null in case the LRU cache needs
-// // to be flushed. Might lead to performance issues.
-// // see PR 1G2K5S7: ITPJCORE:ALL - NPE when accessing source for a binary type
-// JavaModelManager.getJavaModelManager().putInfo(this, info);
-//}
-///**
-// * Close the buffer associated with this element, if any.
-// */
-//protected void closeBuffer(OpenableElementInfo info) {
-// if (!hasBuffer()) return; // nothing to do
-// IBuffer buffer = null;
-// buffer = getBufferManager().getBuffer(this);
-// if (buffer != null) {
-// buffer.close();
-// buffer.removeBufferChangedListener(this);
-// }
-//}
-///**
-// * This element is being closed. Do any necessary cleanup.
-// */
-//protected void closing(Object info) throws JavaModelException {
-// OpenableElementInfo openableInfo = (OpenableElementInfo) info;
-// closeBuffer(openableInfo);
-// super.closing(info);
-//}
+/**
+ * Updates the info objects for this element and all of its children by
+ * removing the current infos, generating new infos, and then placing
+ * the new infos into the Java Model cache tables.
+ */
+protected void buildStructure(OpenableElementInfo info, IProgressMonitor monitor) throws JavaModelException {
+
+ if (monitor != null && monitor.isCanceled()) return;
+
+ // remove existing (old) infos
+ removeInfo();
+ HashMap newElements = new HashMap(11);
+ info.setIsStructureKnown(generateInfos(info, monitor, newElements, getResource()));
+ JavaModelManager.getJavaModelManager().getElementsOutOfSynchWithBuffers().remove(this);
+ for (Iterator iter = newElements.keySet().iterator(); iter.hasNext();) {
+ IJavaElement key = (IJavaElement) iter.next();
+ Object value = newElements.get(key);
+ JavaModelManager.getJavaModelManager().putInfo(key, value);
+ }
+
+ // add the info for this at the end, to ensure that a getInfo cannot reply null in case the LRU cache needs
+ // to be flushed. Might lead to performance issues.
+ // see PR 1G2K5S7: ITPJCORE:ALL - NPE when accessing source for a binary type
+ JavaModelManager.getJavaModelManager().putInfo(this, info);
+}
+/**
+ * Close the buffer associated with this element, if any.
+ */
+protected void closeBuffer(OpenableElementInfo info) {
+ if (!hasBuffer()) return; // nothing to do
+ IBuffer buffer = null;
+ buffer = getBufferManager().getBuffer(this);
+ if (buffer != null) {
+ buffer.close();
+ buffer.removeBufferChangedListener(this);
+ }
+}
+/**
+ * This element is being closed. Do any necessary cleanup.
+ */
+protected void closing(Object info) throws JavaModelException {
+ OpenableElementInfo openableInfo = (OpenableElementInfo) info;
+ closeBuffer(openableInfo);
+ super.closing(info);
+}
///**
// * @see ICodeAssist
// */
@@ -116,18 +127,18 @@ protected Openable(int type, IJavaElement parent, String name) {
// engine.complete(cu, position, 0);
// environment.unitToSkip = null;
//}
-///**
-// * @see ICodeAssist
-// */
-//protected IJavaElement[] codeSelect(org.eclipse.jdt.internal.compiler.env.ICompilationUnit cu, int offset, int length) throws JavaModelException {
+/**
+ * @see ICodeAssist
+ */
+//protected IJavaElement[] codeSelect(net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit cu, int offset, int length) throws JavaModelException {
// SelectionRequestor requestor= new SelectionRequestor(((JavaProject)getJavaProject()).getNameLookup(), this);
// this.codeSelect(cu, offset, length, requestor);
// return requestor.getElements();
//}
-///**
-// * @see ICodeAssist
-// */
-//protected void codeSelect(org.eclipse.jdt.internal.compiler.env.ICompilationUnit cu, int offset, int length, ISelectionRequestor requestor) throws JavaModelException {
+/**
+ * @see ICodeAssist
+ */
+//protected void codeSelect(net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit cu, int offset, int length, ISelectionRequestor requestor) throws JavaModelException {
// IBuffer buffer = getBuffer();
// if (buffer == null) {
// return;
@@ -145,24 +156,24 @@ protected Openable(int type, IJavaElement parent, String name) {
// SelectionEngine engine = new SelectionEngine(environment, requestor, project.getOptions(true));
// engine.select(cu, offset, offset + length - 1);
//}
-///**
-// * Returns a new element info for this element.
-// */
-//protected OpenableElementInfo createElementInfo() {
-// return new OpenableElementInfo();
-//}
-//
-///**
-// * Builds this element's structure and properties in the given
-// * info object, based on this element's current contents (reuse buffer
-// * contents if this element has an open buffer, or resource contents
-// * if this element does not have an open buffer). Children
-// * are placed in the given newElements table (note, this element
-// * has already been placed in the newElements table). Returns true
-// * if successful, or false if an error is encountered while determining
-// * the structure of this element.
-// */
-//protected abstract boolean generateInfos(OpenableElementInfo info, IProgressMonitor pm, Map newElements, IResource underlyingResource) throws JavaModelException;
+/**
+ * Returns a new element info for this element.
+ */
+protected OpenableElementInfo createElementInfo() {
+ return new OpenableElementInfo();
+}
+
+/**
+ * Builds this element's structure and properties in the given
+ * info object, based on this element's current contents (reuse buffer
+ * contents if this element has an open buffer, or resource contents
+ * if this element does not have an open buffer). Children
+ * are placed in the given newElements table (note, this element
+ * has already been placed in the newElements table). Returns true
+ * if successful, or false if an error is encountered while determining
+ * the structure of this element.
+ */
+protected abstract boolean generateInfos(OpenableElementInfo info, IProgressMonitor pm, Map newElements, IResource underlyingResource) throws JavaModelException;
/**
* Note: a buffer with no unsaved changes can be closed by the Java Model
* since it has a finite number of buffers allowed open at one time. If this
@@ -188,14 +199,14 @@ public IBuffer getBuffer() throws JavaModelException {
return null;
}
}
-//
-///**
-// * Answers the buffer factory to use for creating new buffers
-// */
-//public IBufferFactory getBufferFactory(){
-// return getBufferManager().getDefaultBufferFactory();
-//}
-//
+
+/**
+ * Answers the buffer factory to use for creating new buffers
+ */
+public IBufferFactory getBufferFactory(){
+ return getBufferManager().getDefaultBufferFactory();
+}
+
/**
* Returns the buffer manager for this element.
*/
@@ -211,15 +222,15 @@ protected BufferManager getBufferManager() {
public IResource getCorrespondingResource() throws JavaModelException {
return getUnderlyingResource();
}
-///*
-// * @see IJavaElement
-// */
-//public IOpenable getOpenable() {
-// return this;
-//}
-//
-//
-//
+/*
+ * @see IJavaElement
+ */
+public IOpenable getOpenable() {
+ return this;
+}
+
+
+
/**
* @see IJavaElement
*/
@@ -242,15 +253,15 @@ public IResource getUnderlyingResource() throws JavaModelException {
}
}
-//public boolean exists() {
-//
-// IPackageFragmentRoot root = this.getPackageFragmentRoot();
-// if (root == null || root == this || !root.isArchive()) {
-// return parentExists() && resourceExists();
-// } else {
-// return super.exists();
-// }
-//}
+public boolean exists() {
+
+ IPackageFragmentRoot root = this.getPackageFragmentRoot();
+ if (root == null || root == this || !root.isArchive()) {
+ return parentExists() && resourceExists();
+ } else {
+ return super.exists();
+ }
+}
/**
* Returns true if this element may have an associated source buffer,
@@ -259,44 +270,44 @@ public IResource getUnderlyingResource() throws JavaModelException {
protected boolean hasBuffer() {
return false;
}
-///**
-// * @see IParent
-// */
-//public boolean hasChildren() throws JavaModelException {
-// return getChildren().length > 0;
-//}
-///**
-// * @see IOpenable
-// */
-//public boolean hasUnsavedChanges() throws JavaModelException{
-//
-// if (isReadOnly() || !isOpen()) {
-// return false;
-// }
-// IBuffer buf = this.getBuffer();
-// if (buf != null && buf.hasUnsavedChanges()) {
-// return true;
-// }
-// // for package fragments, package fragment roots, and projects must check open buffers
-// // to see if they have an child with unsaved changes
-// if (fLEType == PACKAGE_FRAGMENT ||
-// fLEType == PACKAGE_FRAGMENT_ROOT ||
-// fLEType == JAVA_PROJECT ||
-// fLEType == JAVA_MODEL) { // fix for 1FWNMHH
-// Enumeration openBuffers= getBufferManager().getOpenBuffers();
-// while (openBuffers.hasMoreElements()) {
-// IBuffer buffer= (IBuffer)openBuffers.nextElement();
-// if (buffer.hasUnsavedChanges()) {
-// IJavaElement owner= (IJavaElement)buffer.getOwner();
-// if (isAncestorOf(owner)) {
-// return true;
-// }
-// }
-// }
-// }
-//
-// return false;
-//}
+/**
+ * @see IParent
+ */
+public boolean hasChildren() throws JavaModelException {
+ return getChildren().length > 0;
+}
+/**
+ * @see IOpenable
+ */
+public boolean hasUnsavedChanges() throws JavaModelException{
+
+ if (isReadOnly() || !isOpen()) {
+ return false;
+ }
+ IBuffer buf = this.getBuffer();
+ if (buf != null && buf.hasUnsavedChanges()) {
+ return true;
+ }
+ // for package fragments, package fragment roots, and projects must check open buffers
+ // to see if they have an child with unsaved changes
+ if (fLEType == PACKAGE_FRAGMENT ||
+ fLEType == PACKAGE_FRAGMENT_ROOT ||
+ fLEType == JAVA_PROJECT ||
+ fLEType == JAVA_MODEL) { // fix for 1FWNMHH
+ Enumeration openBuffers= getBufferManager().getOpenBuffers();
+ while (openBuffers.hasMoreElements()) {
+ IBuffer buffer= (IBuffer)openBuffers.nextElement();
+ if (buffer.hasUnsavedChanges()) {
+ IJavaElement owner= (IJavaElement)buffer.getOwner();
+ if (isAncestorOf(owner)) {
+ return true;
+ }
+ }
+ }
+ }
+
+ return false;
+}
/**
* Subclasses must override as required.
*
@@ -310,39 +321,37 @@ public boolean isConsistent() throws JavaModelException {
* @see IOpenable
*/
public boolean isOpen() {
- // TODO isOpen - Openable needs JavaModelManager
-// synchronized(JavaModelManager.getJavaModelManager()){
-// return JavaModelManager.getJavaModelManager().getInfo(this) != null;
-// }
- return false;
+ synchronized(JavaModelManager.getJavaModelManager()){
+ return JavaModelManager.getJavaModelManager().getInfo(this) != null;
+ }
+}
+/**
+ * Returns true if this represents a source element.
+ * Openable source elements have an associated buffer created
+ * when they are opened.
+ */
+protected boolean isSourceElement() {
+ return false;
}
-///**
-// * Returns true if this represents a source element.
-// * Openable source elements have an associated buffer created
-// * when they are opened.
-// */
-//protected boolean isSourceElement() {
-// return false;
-//}
-///**
-// * @see IOpenable
-// */
-//public void makeConsistent(IProgressMonitor pm) throws JavaModelException {
-// if (!isConsistent()) {
-// buildStructure((OpenableElementInfo)getElementInfo(), pm);
-// }
-//}
-///**
-// * @see IOpenable
-// */
-//public void open(IProgressMonitor pm) throws JavaModelException {
-// if (!isOpen()) {
-// // TODO: need to synchronize (IOpenable.open(IProgressMonitor) is API
-// // TODO: could use getElementInfo instead
-// this.openWhenClosed(pm);
-// }
-//}
-//
+/**
+ * @see IOpenable
+ */
+public void makeConsistent(IProgressMonitor pm) throws JavaModelException {
+ if (!isConsistent()) {
+ buildStructure((OpenableElementInfo)getElementInfo(), pm);
+ }
+}
+/**
+ * @see IOpenable
+ */
+public void open(IProgressMonitor pm) throws JavaModelException {
+ if (!isOpen()) {
+ // TODO: need to synchronize (IOpenable.open(IProgressMonitor) is API
+ // TODO: could use getElementInfo instead
+ this.openWhenClosed(pm);
+ }
+}
+
/**
* Opens a buffer on the contents of this element, and returns
* the buffer, or returns null
if opening fails.
@@ -352,98 +361,98 @@ public boolean isOpen() {
protected IBuffer openBuffer(IProgressMonitor pm) throws JavaModelException {
return null;
}
-//
-///**
-// * Open the parent element if necessary
-// *
-// */
-//protected void openParent(IProgressMonitor pm) throws JavaModelException {
-//
-// Openable openableParent = (Openable)getOpenableParent();
-// if (openableParent != null) {
-// if (!openableParent.isOpen()){
-// openableParent.openWhenClosed(pm);
-// }
-// }
-//}
-//
-///**
-// * Open an Openable
that is known to be closed (no check for isOpen()
).
-// */
-//protected void openWhenClosed(IProgressMonitor pm) throws JavaModelException {
-// try {
-//
-// if (JavaModelManager.VERBOSE){
-// System.out.println("OPENING Element ("+ Thread.currentThread()+"): " + this.toStringWithAncestors()); //$NON-NLS-1$//$NON-NLS-2$
-// }
-//
-// // 1) Parent must be open - open the parent if necessary
-// openParent(pm);
-//
-// // 2) create the new element info and open a buffer if needed
-// OpenableElementInfo info = createElementInfo();
-// if (isSourceElement()) {
-// this.openBuffer(pm);
-// }
-//
-// // 3) build the structure of the openable
-// buildStructure(info, pm);
-//
-// // 4) anything special
-// opening(info);
-//
+
+/**
+ * Open the parent element if necessary
+ *
+ */
+protected void openParent(IProgressMonitor pm) throws JavaModelException {
+
+ Openable openableParent = (Openable)getOpenableParent();
+ if (openableParent != null) {
+ if (!openableParent.isOpen()){
+ openableParent.openWhenClosed(pm);
+ }
+ }
+}
+
+/**
+ * Open an Openable
that is known to be closed (no check for isOpen()
).
+ */
+protected void openWhenClosed(IProgressMonitor pm) throws JavaModelException {
+ try {
+
+ if (JavaModelManager.VERBOSE){
+ System.out.println("OPENING Element ("+ Thread.currentThread()+"): " + this.toStringWithAncestors()); //$NON-NLS-1$//$NON-NLS-2$
+ }
+
+ // 1) Parent must be open - open the parent if necessary
+ openParent(pm);
+
+ // 2) create the new element info and open a buffer if needed
+ OpenableElementInfo info = createElementInfo();
+ if (isSourceElement()) {
+ this.openBuffer(pm);
+ }
+
+ // 3) build the structure of the openable
+ buildStructure(info, pm);
+
+ // 4) anything special
+ opening(info);
+
// if (JavaModelManager.VERBOSE) {
// System.out.println("-> Package cache size = " + JavaModelManager.getJavaModelManager().cache.pkgSize()); //$NON-NLS-1$
// System.out.println("-> Openable cache filling ratio = " + JavaModelManager.getJavaModelManager().cache.openableFillingRatio() + "%"); //$NON-NLS-1$//$NON-NLS-2$
// }
-//
-// // if any problems occuring openning the element, ensure that it's info
-// // does not remain in the cache (some elements, pre-cache their info
-// // as they are being opened).
-// } catch (JavaModelException e) {
-// JavaModelManager.getJavaModelManager().removeInfo(this);
-// throw e;
-// }
-//}
-//
-///**
-// * Answers true if the parent exists (null parent is answering true)
-// *
-// */
-//protected boolean parentExists(){
-//
-// IJavaElement parent = this.getParent();
-// if (parent == null) return true;
-// return parent.exists();
-//}
-//
-///**
-// * Returns whether the corresponding resource or associated file exists
-// */
-//protected boolean resourceExists() {
-// IWorkspace workspace = ResourcesPlugin.getWorkspace();
-// if (workspace == null) return false; // workaround for http://bugs.eclipse.org/bugs/show_bug.cgi?id=34069
-// return
-// JavaModel.getTarget(
-// workspace.getRoot(),
-// this.getPath().makeRelative(), // ensure path is relative (see http://dev.eclipse.org/bugs/show_bug.cgi?id=22517)
-// true) != null;
-//}
-//
-///**
-// * @see IOpenable
-// */
-//public void save(IProgressMonitor pm, boolean force) throws JavaModelException {
-// if (isReadOnly() || this.getResource().isReadOnly()) {
-// throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.READ_ONLY, this));
-// }
-// IBuffer buf = getBuffer();
-// if (buf != null) { // some Openables (like a JavaProject) don't have a buffer
-// buf.save(pm, force);
-// this.makeConsistent(pm); // update the element info of this element
-// }
-//}
-//
+
+ // if any problems occuring openning the element, ensure that it's info
+ // does not remain in the cache (some elements, pre-cache their info
+ // as they are being opened).
+ } catch (JavaModelException e) {
+ JavaModelManager.getJavaModelManager().removeInfo(this);
+ throw e;
+ }
+}
+
+/**
+ * Answers true if the parent exists (null parent is answering true)
+ *
+ */
+protected boolean parentExists(){
+
+ IJavaElement parent = this.getParent();
+ if (parent == null) return true;
+ return parent.exists();
+}
+
+/**
+ * Returns whether the corresponding resource or associated file exists
+ */
+protected boolean resourceExists() {
+ IWorkspace workspace = ResourcesPlugin.getWorkspace();
+ if (workspace == null) return false; // workaround for http://bugs.eclipse.org/bugs/show_bug.cgi?id=34069
+ return
+ JavaModel.getTarget(
+ workspace.getRoot(),
+ this.getPath().makeRelative(), // ensure path is relative (see http://dev.eclipse.org/bugs/show_bug.cgi?id=22517)
+ true) != null;
+}
+
+/**
+ * @see IOpenable
+ */
+public void save(IProgressMonitor pm, boolean force) throws JavaModelException {
+ if (isReadOnly() || this.getResource().isReadOnly()) {
+ throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.READ_ONLY, this));
+ }
+ IBuffer buf = getBuffer();
+ if (buf != null) { // some Openables (like a JavaProject) don't have a buffer
+ buf.save(pm, force);
+ this.makeConsistent(pm); // update the element info of this element
+ }
+}
+
/**
* Find enclosing package fragment root if any
*/
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/OpenableElementInfo.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/OpenableElementInfo.java
new file mode 100644
index 0000000..660c9f1
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/OpenableElementInfo.java
@@ -0,0 +1,17 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core;
+
+/** Element info for IOpenable elements. */
+/* package */ class OpenableElementInfo extends JavaElementInfo {
+
+
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/OverflowingLRUCache.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/OverflowingLRUCache.java
index 8b415c0..e7d92f2 100644
--- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/OverflowingLRUCache.java
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/OverflowingLRUCache.java
@@ -13,7 +13,7 @@ package net.sourceforge.phpdt.internal.core;
import java.util.Enumeration;
import java.util.Iterator;
-import net.sourceforge.phpdt.core.util.LRUCache;
+import net.sourceforge.phpdt.internal.core.util.LRUCache;
/**
* The OverflowingLRUCache
is an LRUCache which attempts
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/PackageDeclaration.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/PackageDeclaration.java
new file mode 100644
index 0000000..e79c736
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/PackageDeclaration.java
@@ -0,0 +1,49 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core;
+
+import net.sourceforge.phpdt.core.ICompilationUnit;
+import net.sourceforge.phpdt.core.IPackageDeclaration;
+import net.sourceforge.phpdt.core.JavaModelException;
+import net.sourceforge.phpdt.core.jdom.IDOMNode;
+
+/**
+ * @see IPackageDeclaration
+ */
+
+/* package */ class PackageDeclaration extends SourceRefElement implements IPackageDeclaration {
+protected PackageDeclaration(ICompilationUnit parent, String name) {
+ super(PACKAGE_DECLARATION, parent, name);
+}
+/**
+ * @see JavaElement#equalsDOMNode
+ */
+protected boolean equalsDOMNode(IDOMNode node) throws JavaModelException {
+ return (node.getNodeType() == IDOMNode.PACKAGE) && getElementName().equals(node.getName());
+}
+/**
+ * @see JavaElement#getHandleMemento()
+ */
+protected char getHandleMementoDelimiter() {
+ return JavaElement.JEM_PACKAGEDECLARATION;
+}
+/**
+ * @private Debugging purposes
+ */
+protected void toStringInfo(int tab, StringBuffer buffer, Object info) {
+ buffer.append(this.tabString(tab));
+ buffer.append("package "); //$NON-NLS-1$
+ buffer.append(getElementName());
+ if (info == null) {
+ buffer.append(" (not open)"); //$NON-NLS-1$
+ }
+}
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/PackageFragment.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/PackageFragment.java
index 2b559f5..6b75157 100644
--- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/PackageFragment.java
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/PackageFragment.java
@@ -10,6 +10,9 @@
*******************************************************************************/
package net.sourceforge.phpdt.internal.core;
+import java.util.ArrayList;
+import java.util.Map;
+
import net.sourceforge.phpdt.core.ICompilationUnit;
import net.sourceforge.phpdt.core.IJavaElement;
import net.sourceforge.phpdt.core.IJavaProject;
@@ -19,6 +22,8 @@ import net.sourceforge.phpdt.core.JavaModelException;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Path;
@@ -37,7 +42,7 @@ public class PackageFragment extends Openable implements IPackageFragment {
* @see IPackageFragment
*/
protected PackageFragment(IPackageFragmentRoot root, String name) {
- super(PACKAGE_FRAGMENT, null, name);
+ super(PACKAGE_FRAGMENT, root, name);
}
/**
* Compute the children of this package fragment.
@@ -47,26 +52,26 @@ protected PackageFragment(IPackageFragmentRoot root, String name) {
* PackageFragmentRoot
s.
+ */
+class PackageFragmentRootInfo extends OpenableElementInfo {
+
+ /**
+ * The SourceMapper for this JAR (or null
if
+ * this JAR does not have source attached).
+ */
+// protected SourceMapper sourceMapper = null;
+
+ /**
+ * The kind of the root associated with this info.
+ * Valid kinds are:
+ *
+ */
+ protected int fRootKind= IPackageFragmentRoot.K_SOURCE;
+
+ /**
+ * A array with all the non-java resources contained by this PackageFragment
+ */
+ protected Object[] fNonJavaResources;
+/**
+ * Create and initialize a new instance of the receiver
+ */
+public PackageFragmentRootInfo() {
+ fNonJavaResources = null;
+}
+/**
+ * Starting at this folder, create non-java resources for this package fragment root
+ * and add them to the non-java resources collection.
+ *
+ * @exception JavaModelException The resource associated with this package fragment does not exist
+ */
+static Object[] computeFolderNonJavaResources(JavaProject project, IContainer folder, char[][] exclusionPatterns) throws JavaModelException {
+ Object[] nonJavaResources = new IResource[5];
+ int nonJavaResourcesCounter = 0;
+ try {
+ IClasspathEntry[] classpath = project.getResolvedClasspath(true/*ignore unresolved variable*/);
+ IResource[] members = folder.members();
+ nextResource: for (int i = 0, max = members.length; i < max; i++) {
+ IResource member = members[i];
+ switch (member.getType()) {
+ case IResource.FILE :
+ String fileName = member.getName();
+
+ // ignore .java files that are not excluded
+ if (Util.isValidCompilationUnitName(fileName) && !Util.isExcluded(member, exclusionPatterns))
+ continue nextResource;
+ // ignore .class files
+// if (Util.isValidClassFileName(fileName))
+// continue nextResource;
+// // ignore .zip or .jar file on classpath
+// if (Util.isArchiveFileName(fileName) && isClasspathEntry(member.getFullPath(), classpath))
+// continue nextResource;
+ break;
+
+ case IResource.FOLDER :
+ // ignore valid packages or excluded folders that correspond to a nested pkg fragment root
+// if (Util.isValidFolderNameForPackage(member.getName())
+// && (!Util.isExcluded(member, exclusionPatterns)
+// || isClasspathEntry(member.getFullPath(), classpath)))
+// continue nextResource;
+ break;
+ }
+ if (nonJavaResources.length == nonJavaResourcesCounter) {
+ // resize
+ System.arraycopy(nonJavaResources, 0, (nonJavaResources = new IResource[nonJavaResourcesCounter * 2]), 0, nonJavaResourcesCounter);
+ }
+ nonJavaResources[nonJavaResourcesCounter++] = member;
+
+ }
+ if (nonJavaResources.length != nonJavaResourcesCounter) {
+ System.arraycopy(nonJavaResources, 0, (nonJavaResources = new IResource[nonJavaResourcesCounter]), 0, nonJavaResourcesCounter);
+ }
+ return nonJavaResources;
+ } catch (CoreException e) {
+ throw new JavaModelException(e);
+ }
+}
+/**
+ * Compute the non-package resources of this package fragment root.
+ *
+ * @exception JavaModelException The resource associated with this package fragment root does not exist
+ */
+private Object[] computeNonJavaResources(IJavaProject project, IResource underlyingResource, PackageFragmentRoot handle) {
+ Object[] nonJavaResources = NO_NON_JAVA_RESOURCES;
+ try {
+ // the underlying resource may be a folder or a project (in the case that the project folder
+ // is actually the package fragment root)
+ if (underlyingResource.getType() == IResource.FOLDER || underlyingResource.getType() == IResource.PROJECT) {
+ nonJavaResources =
+ computeFolderNonJavaResources(
+ (JavaProject)project,
+ (IContainer) underlyingResource,
+ handle.fullExclusionPatternChars());
+ }
+ } catch (JavaModelException e) {
+ }
+ return nonJavaResources;
+}
+/**
+ * Returns an array of non-java resources contained in the receiver.
+ */
+synchronized Object[] getNonJavaResources(IJavaProject project, IResource underlyingResource, PackageFragmentRoot handle) {
+ Object[] nonJavaResources = fNonJavaResources;
+ if (nonJavaResources == null) {
+ nonJavaResources = this.computeNonJavaResources(project, underlyingResource, handle);
+ fNonJavaResources = nonJavaResources;
+ }
+ return nonJavaResources;
+}
+/**
+ * Returns the kind of this root.
+ */
+public int getRootKind() {
+ return fRootKind;
+}
+/**
+ * Retuns the SourceMapper for this root, or IPackageFragmentRoot.K_SOURCE
+ * IPackageFragmentRoot.K_BINARY
null
+ * if this root does not have attached source.
+ */
+//protected synchronized SourceMapper getSourceMapper() {
+// return this.sourceMapper;
+//}
+private static boolean isClasspathEntry(IPath path, IClasspathEntry[] resolvedClasspath) {
+ for (int i = 0, length = resolvedClasspath.length; i < length; i++) {
+ IClasspathEntry entry = resolvedClasspath[i];
+ if (entry.getPath().equals(path)) {
+ return true;
+ }
+ }
+ return false;
+}
+/**
+ * Set the fNonJavaResources to res value
+ */
+synchronized void setNonJavaResources(Object[] resources) {
+ fNonJavaResources = resources;
+}
+/**
+ * Sets the kind of this root.
+ */
+protected void setRootKind(int newRootKind) {
+ fRootKind = newRootKind;
+}
+/**
+ * Sets the SourceMapper for this root.
+ */
+//protected synchronized void setSourceMapper(SourceMapper mapper) {
+// this.sourceMapper= mapper;
+//}
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/ReconcileWorkingCopyOperation.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/ReconcileWorkingCopyOperation.java
new file mode 100644
index 0000000..9df9bea
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/ReconcileWorkingCopyOperation.java
@@ -0,0 +1,104 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core;
+
+import net.sourceforge.phpdt.core.IJavaElement;
+import net.sourceforge.phpdt.core.IJavaModelStatus;
+import net.sourceforge.phpdt.core.IJavaModelStatusConstants;
+import net.sourceforge.phpdt.core.IProblemRequestor;
+import net.sourceforge.phpdt.core.JavaModelException;
+
+/**
+ * Reconcile a working copy and signal the changes through a delta.
+ */
+public class ReconcileWorkingCopyOperation extends JavaModelOperation {
+
+ boolean forceProblemDetection;
+
+ public ReconcileWorkingCopyOperation(IJavaElement workingCopy, boolean forceProblemDetection) {
+ super(new IJavaElement[] {workingCopy});
+ this.forceProblemDetection = forceProblemDetection;
+ }
+ /**
+ * @exception JavaModelException if setting the source
+ * of the original compilation unit fails
+ */
+ protected void executeOperation() throws JavaModelException {
+ if (fMonitor != null){
+ if (fMonitor.isCanceled()) return;
+ fMonitor.beginTask(Util.bind("element.reconciling"), 10); //$NON-NLS-1$
+ }
+
+ WorkingCopy workingCopy = getWorkingCopy();
+ boolean wasConsistent = workingCopy.isConsistent();
+ JavaElementDeltaBuilder deltaBuilder = null;
+
+ try {
+ // create the delta builder (this remembers the current content of the cu)
+ if (!wasConsistent){
+ deltaBuilder = new JavaElementDeltaBuilder(workingCopy);
+
+ // update the element infos with the content of the working copy
+ workingCopy.makeConsistent(fMonitor);
+ deltaBuilder.buildDeltas();
+
+ }
+
+ if (fMonitor != null) fMonitor.worked(2);
+
+ // force problem detection? - if structure was consistent
+ if (forceProblemDetection && wasConsistent){
+ if (fMonitor != null && fMonitor.isCanceled()) return;
+
+ IProblemRequestor problemRequestor = workingCopy.problemRequestor;
+ if (problemRequestor != null && problemRequestor.isActive()){
+ problemRequestor.beginReporting();
+ CompilationUnitProblemFinder.process(workingCopy, problemRequestor, fMonitor);
+ problemRequestor.endReporting();
+ }
+ }
+
+ // register the deltas
+ if (deltaBuilder != null){
+ if ((deltaBuilder.delta != null) && (deltaBuilder.delta.getAffectedChildren().length > 0)) {
+ addReconcileDelta(workingCopy, deltaBuilder.delta);
+ }
+ }
+ } finally {
+ if (fMonitor != null) fMonitor.done();
+ }
+ }
+ /**
+ * Returns the working copy this operation is working on.
+ */
+ protected WorkingCopy getWorkingCopy() {
+ return (WorkingCopy)getElementToProcess();
+ }
+ /**
+ * @see JavaModelOperation#isReadOnly
+ */
+ public boolean isReadOnly() {
+ return true;
+ }
+ protected IJavaModelStatus verify() {
+ IJavaModelStatus status = super.verify();
+ if (!status.isOK()) {
+ return status;
+ }
+ WorkingCopy workingCopy = getWorkingCopy();
+ if (workingCopy.useCount == 0) {
+ return new JavaModelStatus(IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST, workingCopy); //was destroyed
+ }
+ return status;
+ }
+
+
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/RenameElementsOperation.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/RenameElementsOperation.java
new file mode 100644
index 0000000..5d3fc42
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/RenameElementsOperation.java
@@ -0,0 +1,83 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core;
+
+import net.sourceforge.phpdt.core.IJavaElement;
+import net.sourceforge.phpdt.core.IJavaModelStatus;
+import net.sourceforge.phpdt.core.IJavaModelStatusConstants;
+import net.sourceforge.phpdt.core.ISourceReference;
+import net.sourceforge.phpdt.core.JavaModelException;
+
+/**
+ * This operation renames elements.
+ *
+ *
+ *
+ */
+public class RenameElementsOperation extends MoveElementsOperation {
+/**
+ * When executed, this operation will rename the specified elements with the given names in the
+ * corresponding destinations.
+ */
+public RenameElementsOperation(IJavaElement[] elements, IJavaElement[] destinations, String[] newNames, boolean force) {
+ //a rename is a move to the same parent with a new name specified
+ //these elements are from different parents
+ super(elements, destinations, force);
+ setRenamings(newNames);
+}
+/**
+ * @see MultiOperation
+ */
+protected String getMainTaskName() {
+ return Util.bind("operation.renameElementProgress"); //$NON-NLS-1$
+}
+/**
+ * @see CopyElementsOperation#isRename()
+ */
+protected boolean isRename() {
+ return true;
+}
+/**
+ * @see MultiOperation
+ */
+protected IJavaModelStatus verify() {
+ IJavaModelStatus status = super.verify();
+ if (! status.isOK())
+ return status;
+ if (fRenamingsList == null || fRenamingsList.length == 0)
+ return new JavaModelStatus(IJavaModelStatusConstants.NULL_NAME);
+ return JavaModelStatus.VERIFIED_OK;
+}
+/**
+ * @see MultiOperation
+ */
+protected void verify(IJavaElement element) throws JavaModelException {
+ int elementType = element.getElementType();
+
+ if (element == null || !element.exists())
+ error(IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST, element);
+
+ if (element.isReadOnly())
+ error(IJavaModelStatusConstants.READ_ONLY, element);
+
+ if (!(element instanceof ISourceReference))
+ error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element);
+
+ if (elementType < IJavaElement.TYPE || elementType == IJavaElement.INITIALIZER)
+ error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element);
+
+ verifyRenaming(element);
+}
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/RenameResourceElementsOperation.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/RenameResourceElementsOperation.java
new file mode 100644
index 0000000..a24f922
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/RenameResourceElementsOperation.java
@@ -0,0 +1,67 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core;
+
+import net.sourceforge.phpdt.core.ICompilationUnit;
+import net.sourceforge.phpdt.core.IJavaElement;
+import net.sourceforge.phpdt.core.IJavaModelStatusConstants;
+import net.sourceforge.phpdt.core.JavaModelException;
+
+/**
+ * This operation renames resources (Package fragments and compilation units).
+ *
+ *
+ *
+ */
+public class RenameResourceElementsOperation extends MoveResourceElementsOperation {
+/**
+ * When executed, this operation will rename the specified elements with the given names in the
+ * corresponding destinations.
+ */
+public RenameResourceElementsOperation(IJavaElement[] elements, IJavaElement[] destinations, String[] newNames, boolean force) {
+ //a rename is a move to the same parent with a new name specified
+ //these elements are from different parents
+ super(elements, destinations, force);
+ setRenamings(newNames);
+}
+/**
+ * @see MultiOperation
+ */
+protected String getMainTaskName() {
+ return Util.bind("operation.renameResourceProgress"); //$NON-NLS-1$
+}
+/**
+ * @see CopyResourceElementsOperation#isRename()
+ */
+protected boolean isRename() {
+ return true;
+}
+/**
+ * @see MultiOperation
+ */
+protected void verify(IJavaElement element) throws JavaModelException {
+ super.verify(element);
+
+ int elementType = element.getElementType();
+
+ if (!(elementType == IJavaElement.COMPILATION_UNIT || elementType == IJavaElement.PACKAGE_FRAGMENT)) {
+ error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element);
+ }
+ if (elementType == IJavaElement.COMPILATION_UNIT) {
+ if (((ICompilationUnit) element).isWorkingCopy()) {
+ error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element);
+ }
+ }
+ verifyRenaming(element);
+}
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/SearchableEnvironment.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/SearchableEnvironment.java
new file mode 100644
index 0000000..6bc4edc
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/SearchableEnvironment.java
@@ -0,0 +1,302 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core;
+
+import net.sourceforge.phpdt.core.ICompilationUnit;
+import net.sourceforge.phpdt.core.IJavaElement;
+import net.sourceforge.phpdt.core.IJavaProject;
+import net.sourceforge.phpdt.core.IPackageFragment;
+import net.sourceforge.phpdt.core.IType;
+import net.sourceforge.phpdt.core.JavaModelException;
+import net.sourceforge.phpdt.core.compiler.CharOperation;
+import net.sourceforge.phpdt.core.search.IJavaSearchConstants;
+import net.sourceforge.phpdt.core.search.ITypeNameRequestor;
+import net.sourceforge.phpdt.internal.codeassist.ISearchRequestor;
+import net.sourceforge.phpdt.internal.codeassist.ISearchableNameEnvironment;
+import net.sourceforge.phpdt.internal.compiler.env.IConstants;
+import net.sourceforge.phpdt.internal.compiler.env.ISourceType;
+import net.sourceforge.phpdt.internal.compiler.env.NameEnvironmentAnswer;
+
+import org.eclipse.core.runtime.IProgressMonitor;
+
+/**
+ * This class provides a SearchableBuilderEnvironment
for code assist which
+ * uses the Java model as a search tool.
+ */
+public class SearchableEnvironment implements ISearchableNameEnvironment, IJavaSearchConstants {
+ protected NameLookup nameLookup;
+ protected ICompilationUnit unitToSkip;
+
+ protected IJavaProject project;
+ // protected IJavaSearchScope searchScope;
+
+ /**
+ * Creates a SearchableEnvironment on the given project
+ */
+ public SearchableEnvironment(IJavaProject project) throws JavaModelException {
+ this.project = project;
+ this.nameLookup = (NameLookup) ((JavaProject) project).getNameLookup();
+
+ // Create search scope with visible entry on the project's classpath
+ // this.searchScope = SearchEngine.createJavaSearchScope(this.project.getAllPackageFragmentRoots());
+ }
+
+ /**
+ * Returns the given type in the the given package if it exists,
+ * otherwise null
.
+ */
+ protected NameEnvironmentAnswer find(String typeName, String packageName) {
+ if (packageName == null)
+ packageName = IPackageFragment.DEFAULT_PACKAGE_NAME;
+
+ IType type = this.nameLookup.findType(typeName, packageName, false, NameLookup.ACCEPT_CLASSES | NameLookup.ACCEPT_INTERFACES);
+ if (type != null) {
+ // if (type instanceof BinaryType) {
+ // try {
+ // return new NameEnvironmentAnswer(
+ // (IBinaryType) ((BinaryType) type).getElementInfo());
+ // } catch (JavaModelException npe) {
+ // return null;
+ // }
+ // } else { //SourceType
+ try {
+ // retrieve the requested type
+ SourceTypeElementInfo sourceType = (SourceTypeElementInfo) ((SourceType) type).getElementInfo();
+ ISourceType topLevelType = sourceType;
+ while (topLevelType.getEnclosingType() != null) {
+ topLevelType = topLevelType.getEnclosingType();
+ }
+ // find all siblings (other types declared in same unit, since may be used for name resolution)
+ IType[] types = sourceType.getHandle().getCompilationUnit().getTypes();
+ ISourceType[] sourceTypes = new ISourceType[types.length];
+
+ // in the resulting collection, ensure the requested type is the first one
+ sourceTypes[0] = sourceType;
+ for (int i = 0, index = 1; i < types.length; i++) {
+ ISourceType otherType = (ISourceType) ((JavaElement) types[i]).getElementInfo();
+ if (!otherType.equals(topLevelType))
+ sourceTypes[index++] = otherType;
+ }
+ return new NameEnvironmentAnswer(sourceTypes);
+ } catch (JavaModelException npe) {
+ return null;
+ }
+ // }
+ }
+ return null;
+ }
+
+ /**
+ * @see ISearchableNameEnvironment#findPackages(char[], ISearchRequestor)
+ */
+ public void findPackages(char[] prefix, ISearchRequestor requestor) {
+ // this.nameLookup.seekPackageFragments(
+ // new String(prefix),
+ // true,
+ // new SearchableEnvironmentRequestor(requestor));
+ }
+
+ /**
+ * @see INameEnvironment#findType(char[][])
+ */
+ public NameEnvironmentAnswer findType(char[][] compoundTypeName) {
+ if (compoundTypeName == null)
+ return null;
+
+ int length = compoundTypeName.length;
+ if (length <= 1) {
+ if (length == 0)
+ return null;
+ return find(new String(compoundTypeName[0]), null);
+ }
+
+ int lengthM1 = length - 1;
+ char[][] packageName = new char[lengthM1][];
+ System.arraycopy(compoundTypeName, 0, packageName, 0, lengthM1);
+
+ return find(new String(compoundTypeName[lengthM1]), CharOperation.toString(packageName));
+ }
+
+ /**
+ * @see INameEnvironment#findType(char[], char[][])
+ */
+ public NameEnvironmentAnswer findType(char[] name, char[][] packageName) {
+ if (name == null)
+ return null;
+
+ return find(new String(name), packageName == null || packageName.length == 0 ? null : CharOperation.toString(packageName));
+ }
+
+ /**
+ * @see ISearchableNameEnvironment#findTypes(char[], ISearchRequestor)
+ */
+ public void findTypes(char[] prefix, final ISearchRequestor storage) {
+
+ /*
+ if (true){
+ findTypes(new String(prefix), storage, NameLookup.ACCEPT_CLASSES | NameLookup.ACCEPT_INTERFACES);
+ return;
+ }
+ */
+ // try {
+ final String excludePath;
+ if (this.unitToSkip != null) {
+ if (!(this.unitToSkip instanceof IJavaElement)) {
+ // revert to model investigation
+ findTypes(new String(prefix), storage, NameLookup.ACCEPT_CLASSES | NameLookup.ACCEPT_INTERFACES);
+ return;
+ }
+ excludePath = ((IJavaElement) this.unitToSkip).getPath().toString();
+ } else {
+ excludePath = null;
+ }
+ int lastDotIndex = CharOperation.lastIndexOf('.', prefix);
+ char[] qualification, simpleName;
+ if (lastDotIndex < 0) {
+ qualification = null;
+ simpleName = CharOperation.toLowerCase(prefix);
+ } else {
+ qualification = CharOperation.subarray(prefix, 0, lastDotIndex);
+ simpleName = CharOperation.toLowerCase(CharOperation.subarray(prefix, lastDotIndex + 1, prefix.length));
+ }
+
+ IProgressMonitor progressMonitor = new IProgressMonitor() {
+ boolean isCanceled = false;
+ public void beginTask(String name, int totalWork) {
+ }
+ public void done() {
+ }
+ public void internalWorked(double work) {
+ }
+ public boolean isCanceled() {
+ return isCanceled;
+ }
+ public void setCanceled(boolean value) {
+ isCanceled = value;
+ }
+ public void setTaskName(String name) {
+ }
+ public void subTask(String name) {
+ }
+ public void worked(int work) {
+ }
+ };
+ ITypeNameRequestor nameRequestor = new ITypeNameRequestor() {
+ public void acceptClass(char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames, String path) {
+ if (excludePath != null && excludePath.equals(path))
+ return;
+ if (enclosingTypeNames != null && enclosingTypeNames.length > 0)
+ return; // accept only top level types
+ storage.acceptClass(packageName, simpleTypeName, IConstants.AccPublic);
+ }
+ public void acceptInterface(char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames, String path) {
+ if (excludePath != null && excludePath.equals(path))
+ return;
+ if (enclosingTypeNames != null && enclosingTypeNames.length > 0)
+ return; // accept only top level types
+ storage.acceptInterface(packageName, simpleTypeName, IConstants.AccPublic);
+ }
+ };
+ // try {
+ // new SearchEngine().searchAllTypeNames(
+ // this.project.getProject().getWorkspace(),
+ // qualification,
+ // simpleName,
+ // PREFIX_MATCH,
+ // CASE_INSENSITIVE,
+ // IJavaSearchConstants.TYPE,
+ // this.searchScope,
+ // nameRequestor,
+ // CANCEL_IF_NOT_READY_TO_SEARCH,
+ // progressMonitor);
+ // } catch (OperationCanceledException e) {
+ // findTypes(
+ // new String(prefix),
+ // storage,
+ // NameLookup.ACCEPT_CLASSES | NameLookup.ACCEPT_INTERFACES);
+ // }
+ // } catch (JavaModelException e) {
+ // findTypes(
+ // new String(prefix),
+ // storage,
+ // NameLookup.ACCEPT_CLASSES | NameLookup.ACCEPT_INTERFACES);
+ // }
+ }
+
+ /**
+ * Returns all types whose name starts with the given (qualified) prefix
.
+ *
+ * If the prefix
is unqualified, all types whose simple name matches
+ * the prefix
are returned.
+ */
+ private void findTypes(String prefix, ISearchRequestor storage, int type) {
+ SearchableEnvironmentRequestor requestor = new SearchableEnvironmentRequestor(storage, this.unitToSkip);
+ int index = prefix.lastIndexOf('.');
+ if (index == -1) {
+ this.nameLookup.seekTypes(prefix, null, true, type, requestor);
+ } else {
+ String packageName = prefix.substring(0, index);
+ JavaElementRequestor elementRequestor = new JavaElementRequestor();
+ this.nameLookup.seekPackageFragments(packageName, false, elementRequestor);
+ IPackageFragment[] fragments = elementRequestor.getPackageFragments();
+ if (fragments != null) {
+ String className = prefix.substring(index + 1);
+ for (int i = 0, length = fragments.length; i < length; i++)
+ if (fragments[i] != null)
+ this.nameLookup.seekTypes(className, fragments[i], true, type, requestor);
+ }
+ }
+ }
+
+ /**
+ * @see INameEnvironment#isPackage(char[][], char[])
+ */
+ public boolean isPackage(char[][] parentPackageName, char[] subPackageName) {
+ if (subPackageName == null || CharOperation.contains('.', subPackageName))
+ return false;
+ if (parentPackageName == null || parentPackageName.length == 0)
+ return isTopLevelPackage(subPackageName);
+ for (int i = 0, length = parentPackageName.length; i < length; i++)
+ if (parentPackageName[i] == null || CharOperation.contains('.', parentPackageName[i]))
+ return false;
+
+ String packageName = new String(CharOperation.concatWith(parentPackageName, subPackageName, '.'));
+ return this.nameLookup.findPackageFragments(packageName, false) != null;
+ }
+
+ public boolean isTopLevelPackage(char[] packageName) {
+ return packageName != null
+ && !CharOperation.contains('.', packageName)
+ && this.nameLookup.findPackageFragments(new String(packageName), false) != null;
+ }
+
+ /**
+ * Returns a printable string for the array.
+ */
+ protected String toStringChar(char[] name) {
+ return "[" //$NON-NLS-1$
+ + new String(name) + "]"; //$NON-NLS-1$
+ }
+
+ /**
+ * Returns a printable string for the array.
+ */
+ protected String toStringCharChar(char[][] names) {
+ StringBuffer result = new StringBuffer();
+ for (int i = 0; i < names.length; i++) {
+ result.append(toStringChar(names[i]));
+ }
+ return result.toString();
+ }
+
+ public void cleanup() {
+ }
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/SearchableEnvironmentRequestor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/SearchableEnvironmentRequestor.java
new file mode 100644
index 0000000..caf3e0f
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/SearchableEnvironmentRequestor.java
@@ -0,0 +1,82 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core;
+
+import net.sourceforge.phpdt.core.ICompilationUnit;
+import net.sourceforge.phpdt.core.IPackageFragment;
+import net.sourceforge.phpdt.core.IType;
+import net.sourceforge.phpdt.core.JavaModelException;
+import net.sourceforge.phpdt.internal.codeassist.ISearchRequestor;
+
+/**
+ * Implements IJavaElementRequestor
, wrappering and forwarding
+ * results onto a org.eclipse.jdt.internal.codeassist.api.ISearchRequestor
.
+ */
+class SearchableEnvironmentRequestor extends JavaElementRequestor implements IJavaElementRequestor {
+ /**
+ * The ISearchRequestor
this JavaElementRequestor wraps
+ * and forwards results to.
+ */
+ protected ISearchRequestor fRequestor;
+ /**
+ * The ICompilationUNit
this JavaElementRequestor will not
+ * accept types within.
+ */
+ protected ICompilationUnit fUnitToSkip;
+/**
+ * Constructs a SearchableEnvironmentRequestor that wraps the
+ * given SearchRequestor.
+ */
+public SearchableEnvironmentRequestor(ISearchRequestor requestor) {
+ fRequestor = requestor;
+ fUnitToSkip= null;
+}
+/**
+ * Constructs a SearchableEnvironmentRequestor that wraps the
+ * given SearchRequestor. The requestor will not accept types in
+ * the unitToSkip
.
+ */
+public SearchableEnvironmentRequestor(ISearchRequestor requestor, ICompilationUnit unitToSkip) {
+ fRequestor = requestor;
+ fUnitToSkip= unitToSkip;
+}
+/**
+ * Do nothing, a SearchRequestor does not accept initializers
+ * so there is no need to forward this results.
+ *
+ * @see IJavaElementRequestor
+ */
+//public void acceptInitializer(IInitializer initializer) {
+//
+//}
+/**
+ * @see IJavaElementRequestor
+ */
+public void acceptPackageFragment(IPackageFragment packageFragment) {
+ fRequestor.acceptPackage(packageFragment.getElementName().toCharArray());
+}
+/**
+ * @see IJavaElementRequestor
+ */
+public void acceptType(IType type) {
+ try {
+ if (fUnitToSkip != null && fUnitToSkip.equals(type.getCompilationUnit())){
+ return;
+ }
+ if (type.isClass()) {
+ fRequestor.acceptClass(type.getPackageFragment().getElementName().toCharArray(), type.getElementName().toCharArray(), type.getFlags());
+ } else {
+ fRequestor.acceptInterface(type.getPackageFragment().getElementName().toCharArray(), type.getElementName().toCharArray(), type.getFlags());
+ }
+ } catch (JavaModelException npe) {
+ }
+}
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/SetClasspathOperation.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/SetClasspathOperation.java
new file mode 100644
index 0000000..513ad3d
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/SetClasspathOperation.java
@@ -0,0 +1,837 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Map;
+
+import net.sourceforge.phpdt.core.IClasspathEntry;
+import net.sourceforge.phpdt.core.IJavaElement;
+import net.sourceforge.phpdt.core.IJavaElementDelta;
+import net.sourceforge.phpdt.core.IJavaModel;
+import net.sourceforge.phpdt.core.IJavaModelStatus;
+import net.sourceforge.phpdt.core.IJavaProject;
+import net.sourceforge.phpdt.core.IPackageFragment;
+import net.sourceforge.phpdt.core.IPackageFragmentRoot;
+import net.sourceforge.phpdt.core.JavaModelException;
+import net.sourceforge.phpdt.internal.compiler.util.ObjectVector;
+
+import org.eclipse.core.resources.IFolder;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IProjectDescription;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.IWorkspace;
+import org.eclipse.core.resources.IWorkspaceRoot;
+import org.eclipse.core.resources.ResourcesPlugin;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.core.runtime.Path;
+
+/**
+ * This operation sets an IJavaProject
's classpath.
+ *
+ * @see IJavaProject
+ */
+public class SetClasspathOperation extends JavaModelOperation {
+
+ IClasspathEntry[] oldResolvedPath, newResolvedPath;
+ IClasspathEntry[] newRawPath;
+ boolean canChangeResource;
+ boolean needCycleCheck;
+ boolean needValidation;
+ boolean needSave;
+ IPath newOutputLocation;
+
+ public static final IClasspathEntry[] ReuseClasspath = new IClasspathEntry[0];
+ public static final IClasspathEntry[] UpdateClasspath = new IClasspathEntry[0];
+ // if reusing output location, then also reuse clean flag
+ public static final IPath ReuseOutputLocation = new Path("Reuse Existing Output Location"); //$NON-NLS-1$
+
+ /**
+ * When executed, this operation sets the classpath of the given project.
+ */
+ public SetClasspathOperation(
+ IJavaProject project,
+ IClasspathEntry[] oldResolvedPath,
+ IClasspathEntry[] newRawPath,
+ IPath newOutputLocation,
+ boolean canChangeResource,
+ boolean needValidation,
+ boolean needSave) {
+
+ super(new IJavaElement[] { project });
+ this.oldResolvedPath = oldResolvedPath;
+ this.newRawPath = newRawPath;
+ this.newOutputLocation = newOutputLocation;
+ this.canChangeResource = canChangeResource;
+ this.needValidation = needValidation;
+ this.needSave = needSave;
+ }
+
+ /**
+ * Adds deltas for the given roots, with the specified change flag,
+ * and closes the root. Helper method for #setClasspath
+ */
+ protected void addClasspathDeltas(
+ IPackageFragmentRoot[] roots,
+ int flag,
+ JavaElementDelta delta) {
+
+ for (int i = 0; i < roots.length; i++) {
+ IPackageFragmentRoot root = roots[i];
+ delta.changed(root, flag);
+ if ((flag & IJavaElementDelta.F_REMOVED_FROM_CLASSPATH) != 0
+ || (flag & IJavaElementDelta.F_SOURCEATTACHED) != 0
+ || (flag & IJavaElementDelta.F_SOURCEDETACHED) != 0){
+ try {
+ root.close();
+ } catch (JavaModelException e) {
+ }
+ // force detach source on jar package fragment roots (source will be lazily computed when needed)
+ ((PackageFragmentRoot) root).setSourceAttachmentProperty(null);// loose info - will be recomputed
+ }
+ }
+ }
+
+
+
+ /**
+ * Returns the index of the item in the list if the given list contains the specified entry. If the list does
+ * not contain the entry, -1 is returned.
+ * A helper method for #setClasspath
+ */
+ protected int classpathContains(
+ IClasspathEntry[] list,
+ IClasspathEntry entry) {
+
+ IPath[] exclusionPatterns = entry.getExclusionPatterns();
+ nextEntry: for (int i = 0; i < list.length; i++) {
+ IClasspathEntry other = list[i];
+ if (other.getContentKind() == entry.getContentKind()
+ && other.getEntryKind() == entry.getEntryKind()
+ && other.isExported() == entry.isExported()
+ && other.getPath().equals(entry.getPath())) {
+ // check custom outputs
+ IPath entryOutput = entry.getOutputLocation();
+ IPath otherOutput = other.getOutputLocation();
+ if (entryOutput == null) {
+ if (otherOutput != null)
+ continue;
+ } else {
+ if (!entryOutput.equals(otherOutput))
+ continue;
+ }
+
+ // check exclusion patterns
+ IPath[] otherExcludes = other.getExclusionPatterns();
+ if (exclusionPatterns != otherExcludes) {
+ int excludeLength = exclusionPatterns.length;
+ if (otherExcludes.length != excludeLength)
+ continue;
+ for (int j = 0; j < excludeLength; j++) {
+ // compare toStrings instead of IPaths
+ // since IPath.equals is specified to ignore trailing separators
+ if (!exclusionPatterns[j].toString().equals(otherExcludes[j].toString()))
+ continue nextEntry;
+ }
+ }
+ return i;
+ }
+ }
+ return -1;
+ }
+
+ /**
+ * Recursively adds all subfolders of folder
to the given collection.
+ */
+ protected void collectAllSubfolders(IFolder folder, ArrayList collection) throws JavaModelException {
+ try {
+ IResource[] members= folder.members();
+ for (int i = 0, max = members.length; i < max; i++) {
+ IResource r= members[i];
+ if (r.getType() == IResource.FOLDER) {
+ collection.add(r);
+ collectAllSubfolders((IFolder)r, collection);
+ }
+ }
+ } catch (CoreException e) {
+ throw new JavaModelException(e);
+ }
+ }
+
+ /**
+ * Returns a collection of package fragments that have been added/removed
+ * as the result of changing the output location to/from the given
+ * location. The collection is empty if no package fragments are
+ * affected.
+ */
+// protected ArrayList determineAffectedPackageFragments(IPath location) throws JavaModelException {
+// ArrayList fragments = new ArrayList();
+// JavaProject project =getProject();
+//
+// // see if this will cause any package fragments to be affected
+// IWorkspace workspace = ResourcesPlugin.getWorkspace();
+// IResource resource = null;
+// if (location != null) {
+// resource = workspace.getRoot().findMember(location);
+// }
+// if (resource != null && resource.getType() == IResource.FOLDER) {
+// IFolder folder = (IFolder) resource;
+// // only changes if it actually existed
+// IClasspathEntry[] classpath = project.getExpandedClasspath(true);
+// for (int i = 0; i < classpath.length; i++) {
+// IClasspathEntry entry = classpath[i];
+// IPath path = classpath[i].getPath();
+// if (entry.getEntryKind() != IClasspathEntry.CPE_PROJECT && path.isPrefixOf(location) && !path.equals(location)) {
+// IPackageFragmentRoot[] roots = project.computePackageFragmentRoots(classpath[i]);
+// IPackageFragmentRoot root = roots[0];
+// // now the output location becomes a package fragment - along with any subfolders
+// ArrayList folders = new ArrayList();
+// folders.add(folder);
+// collectAllSubfolders(folder, folders);
+// Iterator elements = folders.iterator();
+// int segments = path.segmentCount();
+// while (elements.hasNext()) {
+// IFolder f = (IFolder) elements.next();
+// IPath relativePath = f.getFullPath().removeFirstSegments(segments);
+// String name = relativePath.toOSString();
+// name = name.replace(File.pathSeparatorChar, '.');
+// if (name.endsWith(".")) { //$NON-NLS-1$
+// name = name.substring(0, name.length() - 1);
+// }
+// IPackageFragment pkg = root.getPackageFragment(name);
+// fragments.add(pkg);
+// }
+// }
+// }
+// }
+// return fragments;
+// }
+
+ /**
+ * Sets the classpath of the pre-specified project.
+ */
+ protected void executeOperation() throws JavaModelException {
+ // project reference updated - may throw an exception if unable to write .project file
+ updateProjectReferencesIfNecessary();
+
+ // classpath file updated - may throw an exception if unable to write .classpath file
+ saveClasspathIfNecessary();
+
+ // perform classpath and output location updates, if exception occurs in classpath update,
+ // make sure the output location is updated before surfacing the exception (in case the output
+ // location update also throws an exception, give priority to the classpath update one).
+ JavaModelException originalException = null;
+
+ try {
+ JavaProject project = getProject();
+ if (this.newRawPath == UpdateClasspath) this.newRawPath = project.getRawClasspath();
+ if (this.newRawPath != ReuseClasspath){
+ updateClasspath();
+// project.updatePackageFragmentRoots();
+ JavaModelManager.getJavaModelManager().deltaProcessor.addForRefresh(project);
+ }
+
+ } catch(JavaModelException e){
+ originalException = e;
+ throw e;
+
+ } finally { // if traversed by an exception we still need to update the output location when necessary
+
+ try {
+ if (this.newOutputLocation != ReuseOutputLocation) updateOutputLocation();
+
+ } catch(JavaModelException e){
+ if (originalException != null) throw originalException;
+ throw e;
+ }
+ }
+ done();
+ }
+
+ /**
+ * Generates the delta of removed/added/reordered roots.
+ * Use three deltas in case the same root is removed/added/reordered (for
+ * instance, if it is changed from K_SOURCE to K_BINARY or vice versa)
+ */
+// protected void generateClasspathChangeDeltas(
+// IClasspathEntry[] oldResolvedPath,
+// IClasspathEntry[] newResolvedPath,
+// final JavaProject project) {
+//
+// JavaModelManager manager = JavaModelManager.getJavaModelManager();
+// boolean needToUpdateDependents = false;
+// JavaElementDelta delta = new JavaElementDelta(getJavaModel());
+// boolean hasDelta = false;
+// int oldLength = oldResolvedPath.length;
+// int newLength = newResolvedPath.length;
+//
+// final IndexManager indexManager = manager.getIndexManager();
+// Map oldRoots = null;
+// IPackageFragmentRoot[] roots = null;
+// if (project.isOpen()) {
+// try {
+// roots = project.getPackageFragmentRoots();
+// } catch (JavaModelException e) {
+// }
+// } else {
+// Map allRemovedRoots ;
+// if ((allRemovedRoots = manager.deltaProcessor.removedRoots) != null) {
+// roots = (IPackageFragmentRoot[]) allRemovedRoots.get(project);
+// }
+// }
+// if (roots != null) {
+// oldRoots = new HashMap();
+// for (int i = 0; i < roots.length; i++) {
+// IPackageFragmentRoot root = roots[i];
+// oldRoots.put(root.getPath(), root);
+// }
+// }
+// for (int i = 0; i < oldLength; i++) {
+//
+// int index = classpathContains(newResolvedPath, oldResolvedPath[i]);
+// if (index == -1) {
+// // do not notify remote project changes
+// if (oldResolvedPath[i].getEntryKind() == IClasspathEntry.CPE_PROJECT){
+// needToUpdateDependents = true;
+// this.needCycleCheck = true;
+// continue;
+// }
+//
+// IPackageFragmentRoot[] pkgFragmentRoots = null;
+// if (oldRoots != null) {
+// IPackageFragmentRoot oldRoot = (IPackageFragmentRoot) oldRoots.get(oldResolvedPath[i].getPath());
+// if (oldRoot != null) { // use old root if any (could be none if entry wasn't bound)
+// pkgFragmentRoots = new IPackageFragmentRoot[] { oldRoot };
+// }
+// }
+// if (pkgFragmentRoots == null) {
+// try {
+// ObjectVector accumulatedRoots = new ObjectVector();
+// HashSet rootIDs = new HashSet(5);
+// rootIDs.add(project.rootID());
+// project.computePackageFragmentRoots(
+// oldResolvedPath[i],
+// accumulatedRoots,
+// rootIDs,
+// true, // inside original project
+// false, // don't check existency
+// false); // don't retrieve exported roots
+// pkgFragmentRoots = new IPackageFragmentRoot[accumulatedRoots.size()];
+// accumulatedRoots.copyInto(pkgFragmentRoots);
+// } catch (JavaModelException e) {
+// pkgFragmentRoots = new IPackageFragmentRoot[] {};
+// }
+// }
+// addClasspathDeltas(pkgFragmentRoots, IJavaElementDelta.F_REMOVED_FROM_CLASSPATH, delta);
+//
+// int changeKind = oldResolvedPath[i].getEntryKind();
+// needToUpdateDependents |= (changeKind == IClasspathEntry.CPE_SOURCE) || oldResolvedPath[i].isExported();
+//
+// // Remove the .java files from the index for a source folder
+// // For a lib folder or a .jar file, remove the corresponding index if not shared.
+// if (indexManager != null) {
+// IClasspathEntry oldEntry = oldResolvedPath[i];
+// final IPath path = oldEntry.getPath();
+// switch (changeKind) {
+// case IClasspathEntry.CPE_SOURCE:
+// final char[][] exclusionPatterns = ((ClasspathEntry)oldEntry).fullExclusionPatternChars();
+// postAction(new IPostAction() {
+// public String getID() {
+// return path.toString();
+// }
+// public void run() throws JavaModelException {
+// indexManager.removeSourceFolderFromIndex(project, path, exclusionPatterns);
+// }
+// },
+// REMOVEALL_APPEND);
+// break;
+// case IClasspathEntry.CPE_LIBRARY:
+// final DeltaProcessor deltaProcessor = manager.deltaProcessor;
+// postAction(new IPostAction() {
+// public String getID() {
+// return path.toString();
+// }
+// public void run() throws JavaModelException {
+// if (deltaProcessor.otherRoots.get(path) == null) { // if root was not shared
+// indexManager.discardJobs(path.toString());
+// indexManager.removeIndex(path);
+// // TODO: we could just remove the in-memory index and have the indexing check for timestamps
+// }
+// }
+// },
+// REMOVEALL_APPEND);
+// break;
+// }
+// }
+// hasDelta = true;
+//
+// } else {
+// // do not notify remote project changes
+// if (oldResolvedPath[i].getEntryKind() == IClasspathEntry.CPE_PROJECT){
+// this.needCycleCheck |= (oldResolvedPath[i].isExported() != newResolvedPath[index].isExported());
+// continue;
+// }
+// needToUpdateDependents |= (oldResolvedPath[i].isExported() != newResolvedPath[index].isExported());
+// if (index != i) { //reordering of the classpath
+// addClasspathDeltas(
+// project.computePackageFragmentRoots(oldResolvedPath[i]),
+// IJavaElementDelta.F_REORDER,
+// delta);
+// int changeKind = oldResolvedPath[i].getEntryKind();
+// needToUpdateDependents |= (changeKind == IClasspathEntry.CPE_SOURCE);
+//
+// hasDelta = true;
+// }
+//
+// // check source attachment
+// IPath newSourcePath = newResolvedPath[index].getSourceAttachmentPath();
+// int sourceAttachmentFlags =
+// this.getSourceAttachmentDeltaFlag(
+// oldResolvedPath[i].getSourceAttachmentPath(),
+// newSourcePath,
+// null/*not a source root path*/);
+// int sourceAttachmentRootFlags =
+// this.getSourceAttachmentDeltaFlag(
+// oldResolvedPath[i].getSourceAttachmentRootPath(),
+// newResolvedPath[index].getSourceAttachmentRootPath(),
+// newSourcePath/*in case both root paths are null*/);
+// int flags = sourceAttachmentFlags | sourceAttachmentRootFlags;
+// if (flags != 0) {
+// addClasspathDeltas(
+// project.computePackageFragmentRoots(oldResolvedPath[i]),
+// flags,
+// delta);
+// hasDelta = true;
+// }
+// }
+// }
+//
+// for (int i = 0; i < newLength; i++) {
+//
+// int index = classpathContains(oldResolvedPath, newResolvedPath[i]);
+// if (index == -1) {
+// // do not notify remote project changes
+// if (newResolvedPath[i].getEntryKind() == IClasspathEntry.CPE_PROJECT){
+// needToUpdateDependents = true;
+// this.needCycleCheck = true;
+// continue;
+// }
+// addClasspathDeltas(
+// project.computePackageFragmentRoots(newResolvedPath[i]),
+// IJavaElementDelta.F_ADDED_TO_CLASSPATH,
+// delta);
+// int changeKind = newResolvedPath[i].getEntryKind();
+//
+// // Request indexing
+// if (indexManager != null) {
+// switch (changeKind) {
+// case IClasspathEntry.CPE_LIBRARY:
+// boolean pathHasChanged = true;
+// final IPath newPath = newResolvedPath[i].getPath();
+// for (int j = 0; j < oldLength; j++) {
+// IClasspathEntry oldEntry = oldResolvedPath[j];
+// if (oldEntry.getPath().equals(newPath)) {
+// pathHasChanged = false;
+// break;
+// }
+// }
+// if (pathHasChanged) {
+// postAction(new IPostAction() {
+// public String getID() {
+// return newPath.toString();
+// }
+// public void run() throws JavaModelException {
+// indexManager.indexLibrary(newPath, project.getProject());
+// }
+// },
+// REMOVEALL_APPEND);
+// }
+// break;
+// case IClasspathEntry.CPE_SOURCE:
+// IClasspathEntry entry = newResolvedPath[i];
+// final IPath path = entry.getPath();
+// final char[][] exclusionPatterns = ((ClasspathEntry)entry).fullExclusionPatternChars();
+// postAction(new IPostAction() {
+// public String getID() {
+// return path.toString();
+// }
+// public void run() throws JavaModelException {
+// indexManager.indexSourceFolder(project, path, exclusionPatterns);
+// }
+// },
+// APPEND); // append so that a removeSourceFolder action is not removed
+// break;
+// }
+// }
+//
+// needToUpdateDependents |= (changeKind == IClasspathEntry.CPE_SOURCE) || newResolvedPath[i].isExported();
+// hasDelta = true;
+//
+// } // classpath reordering has already been generated in previous loop
+// }
+//
+// if (hasDelta) {
+// this.addDelta(delta);
+// }
+// if (needToUpdateDependents){
+// updateAffectedProjects(project.getProject().getFullPath());
+// }
+// }
+
+ protected JavaProject getProject() {
+ return ((JavaProject) getElementsToProcess()[0]);
+ }
+
+ /*
+ * Returns the source attachment flag for the delta between the 2 give source paths.
+ * Returns either F_SOURCEATTACHED, F_SOURCEDETACHED, F_SOURCEATTACHED | F_SOURCEDETACHED
+ * or 0 if there is no difference.
+ */
+ private int getSourceAttachmentDeltaFlag(IPath oldPath, IPath newPath, IPath sourcePath) {
+ if (oldPath == null) {
+ if (newPath != null) {
+ return IJavaElementDelta.F_SOURCEATTACHED;
+ } else {
+ if (sourcePath != null) {
+ // if source path is specified and no root path, it needs to be recomputed dynamically
+ return IJavaElementDelta.F_SOURCEATTACHED | IJavaElementDelta.F_SOURCEDETACHED;
+ } else {
+ return 0;
+ }
+ }
+ } else if (newPath == null) {
+ return IJavaElementDelta.F_SOURCEDETACHED;
+ } else if (!oldPath.equals(newPath)) {
+ return IJavaElementDelta.F_SOURCEATTACHED | IJavaElementDelta.F_SOURCEDETACHED;
+ } else {
+ return 0;
+ }
+ }
+
+ /**
+ * Returns true
if this operation performs no resource modifications,
+ * otherwise false
. Subclasses must override.
+ */
+ public boolean isReadOnly() {
+ return !this.canChangeResource;
+ }
+
+ protected void saveClasspathIfNecessary() throws JavaModelException {
+
+ if (!this.canChangeResource || !this.needSave) return;
+
+ IClasspathEntry[] classpathForSave;
+ JavaProject project = getProject();
+ if (this.newRawPath == ReuseClasspath || this.newRawPath == UpdateClasspath){
+ classpathForSave = project.getRawClasspath();
+ } else {
+ classpathForSave = this.newRawPath;
+ }
+ IPath outputLocationForSave;
+ if (this.newOutputLocation == ReuseOutputLocation){
+ outputLocationForSave = project.getOutputLocation();
+ } else {
+ outputLocationForSave = this.newOutputLocation;
+ }
+ // if read-only .classpath, then the classpath setting will never been performed completely
+ if (project.saveClasspath(classpathForSave, outputLocationForSave)) {
+ this.setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
+ }
+ }
+
+ public String toString(){
+ StringBuffer buffer = new StringBuffer(20);
+ buffer.append("SetClasspathOperation\n"); //$NON-NLS-1$
+ buffer.append(" - classpath : "); //$NON-NLS-1$
+ if (this.newRawPath == ReuseClasspath){
+ buffer.append("true
if the signature of this SourceMethod
matches that of the given
+ * IDOMMethod
, otherwise false
.
+ */
+protected boolean signatureEquals(IDOMMethod method) throws JavaModelException {
+ String[] otherTypes= method.getParameterTypes();
+ String[] types= getParameterTypes();
+ boolean ok= true;
+
+ // ensure the number of parameters match
+ if (otherTypes == null || otherTypes.length == 0) {
+ ok= (types == null || types.length == 0);
+ } else if (types != null) {
+ ok= (otherTypes.length == types.length);
+ } else {
+ return false;
+ }
+
+ // ensure the parameter type signatures match
+ if (ok) {
+ if (types != null) {
+ int i;
+ for (i= 0; i < types.length; i++) {
+ String otherType= Signature.createTypeSignature(otherTypes[i].toCharArray(), false);
+ if (!types[i].equals(otherType)) {
+ ok= false;
+ break;
+ }
+ }
+ }
+ }
+
+ return ok;
+}
+/**
+ * @private Debugging purposes
+ */
+protected void toStringInfo(int tab, StringBuffer buffer, Object info) {
+ buffer.append(this.tabString(tab));
+ if (info == null) {
+ buffer.append(getElementName());
+ buffer.append(" (not open)"); //$NON-NLS-1$
+ } else if (info == NO_INFO) {
+ buffer.append(getElementName());
+ } else {
+ try {
+ if (Flags.isStatic(this.getFlags())) {
+ buffer.append("static "); //$NON-NLS-1$
+ }
+ if (!this.isConstructor()) {
+ buffer.append(Signature.toString(this.getReturnType()));
+ buffer.append(' ');
+ }
+ buffer.append(this.getElementName());
+ buffer.append('(');
+ String[] parameterTypes = this.getParameterTypes();
+ int length;
+ if (parameterTypes != null && (length = parameterTypes.length) > 0) {
+ for (int i = 0; i < length; i++) {
+ buffer.append(Signature.toString(parameterTypes[i]));
+ if (i < length - 1) {
+ buffer.append(", "); //$NON-NLS-1$
+ }
+ }
+ }
+ buffer.append(')');
+ } catch (JavaModelException e) {
+ buffer.append("null
)
+ * @return the editor, or null if wrong element type or opening failed
+ * @exception PartInitException if the editor could not be initialized
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its underlying resource
+ */
+ public static IEditorPart openInEditor(IJavaElement element) throws JavaModelException, PartInitException {
+ return EditorUtility.openInEditor(element);
+ }
+
+ /**
+ * Reveals the source range of the given source reference element in the
+ * given editor. No checking is done if the editor displays a compilation unit or
+ * class file that contains the given source reference. The editor simply reveals
+ * the source range denoted by the given source reference.
+ *
+ * @param part the editor displaying the compilation unit or class file
+ * @param element the source reference element defining the source range to be revealed
+ *
+ * @deprecated use - a working copy does not have an underlying resource.
+ *
+ * @see IJavaElement
+ */
+public IResource getUnderlyingResource() throws JavaModelException {
+ return null;
+}
+/**
+ * @see IWorkingCopy
+ */
+public IJavaElement getWorkingCopy() throws JavaModelException {
+ return this;
+}
+/**
+ * @see IWorkingCopy
+ */
+public IJavaElement getWorkingCopy(IProgressMonitor monitor, IBufferFactory factory, IProblemRequestor problemRequestor) throws JavaModelException {
+ return this;
+}
+/**
+ * @see IWorkingCopy
+ */
+public boolean isBasedOn(IResource resource) {
+ if (resource.getType() != IResource.FILE) {
+ return false;
+ }
+ if (this.useCount == 0) {
+ return false;
+ }
+ try {
+ // if resource got deleted, then #getModificationStamp() will answer IResource.NULL_STAMP, which is always different from the cached
+ // timestamp
+ return ((CompilationUnitElementInfo) getElementInfo()).fTimestamp == ((IFile) resource).getModificationStamp();
+ } catch (JavaModelException e) {
+ return false;
+ }
+}
+/**
+ * @see IWorkingCopy
+ */
+public boolean isWorkingCopy() {
+ return true;
+}
+
+/**
+ * @see IOpenable#makeConsistent(IProgressMonitor)
+ */
+//public void makeConsistent(IProgressMonitor monitor) throws JavaModelException {
+// if (!isConsistent()) { // TODO: this code isn't synchronized with regular opening of a working copy (should use getElementInfo)
+// super.makeConsistent(monitor);
+//
+// if (monitor != null && monitor.isCanceled()) return;
+// if (this.problemRequestor != null && this.problemRequestor.isActive()){
+// this.problemRequestor.beginReporting();
+// CompilationUnitProblemFinder.process(this, this.problemRequestor, monitor);
+// this.problemRequestor.endReporting();
+// }
+// }
+//}
+
+/**
+ * @see IOpenable
+ * @see IWorkingCopy
+ *
+ * @exception JavaModelException attempting to open a read only element for something other than navigation
+ * or if this is a working copy being opened after it has been destroyed.
+ */
+public void open(IProgressMonitor monitor) throws JavaModelException {
+ if (this.useCount == 0) { // was destroyed
+ throw newNotPresentException();
+ } else {
+ super.open(monitor);
+
+ if (monitor != null && monitor.isCanceled()) return;
+ if (this.problemRequestor != null && this.problemRequestor.isActive()){
+ this.problemRequestor.beginReporting();
+ CompilationUnitProblemFinder.process(this, this.problemRequestor, monitor);
+ this.problemRequestor.endReporting();
+ }
+ }
+}
+/**
+ * @see Openable
+ */
+//protected IBuffer openBuffer(IProgressMonitor pm) throws JavaModelException {
+//
+// if (this.useCount == 0) throw newNotPresentException(); // was destroyed
+//
+// // create buffer - working copies may use custom buffer factory
+// IBuffer buffer = getBufferFactory().createBuffer(this);
+// if (buffer == null) return null;
+//
+// // set the buffer source if needed
+// if (buffer.getCharacters() == null) {
+// ICompilationUnit original = (ICompilationUnit)this.getOriginalElement();
+// if (original.isOpen()) {
+// buffer.setContents(original.getSource());
+// } else {
+// IFile file = (IFile)original.getResource();
+// if (file == null || !file.exists()) {
+// // initialize buffer with empty contents
+// buffer.setContents(CharOperation.NO_CHAR);
+// } else {
+// buffer.setContents(Util.getResourceContentsAsCharArray(file));
+// }
+// }
+// }
+//
+// // add buffer to buffer cache
+// this.getBufferManager().addBuffer(buffer);
+//
+// // listen to buffer changes
+// buffer.addBufferChangedListener(this);
+//
+// return buffer;
+//}
+/*
+ * @see Openable#openParent(IProgressMonitor)
+ */
+protected void openParent(IProgressMonitor pm) throws JavaModelException {
+// if (FIX_BUG25184) {
+// try {
+// super.openParent(pm);
+// } catch(JavaModelException e){
+// // allow parent to not exist for working copies defined outside classpath
+// if (!e.isDoesNotExist()){
+// throw e;
+// }
+// }
+// } else {
+ super.openParent(pm);
+// }
+}
+
+/**
+ * @see IWorkingCopy
+ */
+public IMarker[] reconcile() throws JavaModelException {
+ reconcile(false, null);
+ return null;
+}
+
+/**
+ * @see IWorkingCopy
+ */
+public void reconcile(boolean forceProblemDetection, IProgressMonitor monitor) throws JavaModelException {
+ ReconcileWorkingCopyOperation op = new ReconcileWorkingCopyOperation(this, forceProblemDetection);
+ runOperation(op, monitor);
+}
+
+/**
+ * @see IWorkingCopy
+ */
+public void restore() throws JavaModelException {
+
+ if (this.useCount == 0) throw newNotPresentException(); //was destroyed
+
+ CompilationUnit original = (CompilationUnit) getOriginalElement();
+ IBuffer buffer = this.getBuffer();
+ if (buffer == null) return;
+ buffer.setContents(original.getContents());
+ updateTimeStamp(original);
+ makeConsistent(null);
+}
+/*
+ * @see JavaElement#rootedAt(IJavaProject)
+ */
+public IJavaElement rootedAt(IJavaProject project) {
+ return
+ new WorkingCopy(
+ (IPackageFragment)((JavaElement)fParent).rootedAt(project),
+ fName,
+ this.bufferFactory);
+
+}
+/**
+ * @see IOpenable
+ */
+public void save(IProgressMonitor pm, boolean force) throws JavaModelException {
+ if (isReadOnly()) {
+ throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.READ_ONLY, this));
+ }
+ // no need to save the buffer for a working copy (this is a noop)
+ //IBuffer buf = getBuffer();
+ //if (buf != null) { // some Openables (like a JavaProject) don't have a buffer
+ // buf.save(pm, force);
+ this.reconcile(); // not simply makeConsistent, also computes fine-grain deltas
+ // in case the working copy is being reconciled already (if not it would miss
+ // one iteration of deltas).
+ //}
+}
+
+/**
+ * @private Debugging purposes
+ */
+protected void toStringInfo(int tab, StringBuffer buffer, Object info) {
+ buffer.append(this.tabString(tab));
+ buffer.append("[Working copy] "); //$NON-NLS-1$
+ super.toStringInfo(0, buffer, info);
+}
+protected void updateTimeStamp(CompilationUnit original) throws JavaModelException {
+ long timeStamp =
+ ((IFile) original.getResource()).getModificationStamp();
+ if (timeStamp == IResource.NULL_STAMP) {
+ throw new JavaModelException(
+ new JavaModelStatus(IJavaModelStatusConstants.INVALID_RESOURCE));
+ }
+ ((CompilationUnitElementInfo) getElementInfo()).fTimestamp = timeStamp;
+}
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/WorkingCopyElementInfo.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/WorkingCopyElementInfo.java
new file mode 100644
index 0000000..9f91608
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/WorkingCopyElementInfo.java
@@ -0,0 +1,18 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core;
+
+import net.sourceforge.phpdt.core.compiler.IProblem;
+
+
+public class WorkingCopyElementInfo extends CompilationUnitElementInfo {
+ IProblem[] problems;
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/AbortIncrementalBuildException.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/AbortIncrementalBuildException.java
new file mode 100644
index 0000000..5b6a28e
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/AbortIncrementalBuildException.java
@@ -0,0 +1,25 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core.builder;
+
+/**
+ * Exception thrown when an incremental builder cannot find a .class file.
+ * Its possible the type can no longer be found because it was renamed inside its existing
+ * source file.
+ */
+public class AbortIncrementalBuildException extends RuntimeException {
+
+protected String qualifiedTypeName;
+
+public AbortIncrementalBuildException(String qualifiedTypeName) {
+ this.qualifiedTypeName = qualifiedTypeName;
+}
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/AbstractImageBuilder.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/AbstractImageBuilder.java
new file mode 100644
index 0000000..6b40b16
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/AbstractImageBuilder.java
@@ -0,0 +1,463 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core.builder;
+
+import java.util.ArrayList;
+import java.util.Locale;
+
+import net.sourceforge.phpdt.core.IJavaModelMarker;
+import net.sourceforge.phpdt.core.JavaModelException;
+import net.sourceforge.phpdt.core.compiler.IProblem;
+import net.sourceforge.phpdt.internal.compiler.Compiler;
+import net.sourceforge.phpdt.internal.compiler.CompilationResult;
+import net.sourceforge.phpdt.internal.compiler.DefaultErrorHandlingPolicies;
+import net.sourceforge.phpdt.internal.compiler.ICompilerRequestor;
+import net.sourceforge.phpdt.internal.compiler.problem.AbortCompilation;
+import net.sourceforge.phpdt.internal.core.Util;
+import net.sourceforge.phpeclipse.PHPCore;
+
+import org.eclipse.core.resources.IContainer;
+import org.eclipse.core.resources.IFolder;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IPath;
+
+/**
+ * The abstract superclass of Java builders.
+ * Provides the building and compilation mechanism
+ * in common with the batch and incremental builders.
+ */
+public abstract class AbstractImageBuilder implements ICompilerRequestor {
+
+protected PHPBuilder javaBuilder;
+protected State newState;
+
+// local copies
+protected NameEnvironment nameEnvironment;
+protected ClasspathMultiDirectory[] sourceLocations;
+protected BuildNotifier notifier;
+
+protected String encoding;
+protected Compiler compiler;
+protected WorkQueue workQueue;
+protected ArrayList problemSourceFiles;
+protected boolean compiledAllAtOnce;
+
+private boolean inCompiler;
+
+public static int MAX_AT_ONCE = 1000;
+
+protected AbstractImageBuilder(PHPBuilder javaBuilder) {
+ this.javaBuilder = javaBuilder;
+ this.newState = new State(javaBuilder);
+
+ // local copies
+ this.nameEnvironment = javaBuilder.nameEnvironment;
+ this.sourceLocations = this.nameEnvironment.sourceLocations;
+ this.notifier = javaBuilder.notifier;
+
+ this.encoding = javaBuilder.javaProject.getOption(PHPCore.CORE_ENCODING, true);
+ this.compiler = newCompiler();
+ this.workQueue = new WorkQueue();
+ this.problemSourceFiles = new ArrayList(3);
+}
+
+public void acceptResult(CompilationResult result) {
+ // In Batch mode, we write out the class files, hold onto the dependency info
+ // & additional types and report problems.
+
+ // In Incremental mode, when writing out a class file we need to compare it
+ // against the previous file, remembering if structural changes occured.
+ // Before reporting the new problems, we need to update the problem count &
+ // remove the old problems. Plus delete additional class files that no longer exist.
+
+ SourceFile compilationUnit = (SourceFile) result.getCompilationUnit(); // go directly back to the sourceFile
+ if (!workQueue.isCompiled(compilationUnit)) {
+ try {
+ workQueue.finished(compilationUnit);
+ updateProblemsFor(compilationUnit, result); // record compilation problems before potentially adding duplicate errors
+ updateTasksFor(compilationUnit, result); // record tasks
+
+ String typeLocator = compilationUnit.typeLocator();
+// ClassFile[] classFiles = result.getClassFiles();
+// int length = classFiles.length;
+// ArrayList duplicateTypeNames = null;
+// ArrayList definedTypeNames = new ArrayList(length);
+// for (int i = 0; i < length; i++) {
+// ClassFile classFile = classFiles[i];
+// char[][] compoundName = classFile.getCompoundName();
+// char[] typeName = compoundName[compoundName.length - 1];
+// boolean isNestedType = CharOperation.contains('$', typeName);
+//
+// // Look for a possible collision, if one exists, report an error but do not write the class file
+// if (isNestedType) {
+// String qualifiedTypeName = new String(classFile.outerMostEnclosingClassFile().fileName());
+// if (newState.isDuplicateLocator(qualifiedTypeName, typeLocator))
+// continue;
+// } else {
+// String qualifiedTypeName = new String(classFile.fileName()); // the qualified type name "p1/p2/A"
+// if (newState.isDuplicateLocator(qualifiedTypeName, typeLocator)) {
+// if (duplicateTypeNames == null)
+// duplicateTypeNames = new ArrayList();
+// duplicateTypeNames.add(compoundName);
+// createErrorFor(compilationUnit.resource, Util.bind("build.duplicateClassFile", new String(typeName))); //$NON-NLS-1$
+// continue;
+// }
+// newState.recordLocatorForType(qualifiedTypeName, typeLocator);
+// }
+// definedTypeNames.add(writeClassFile(classFile, compilationUnit.sourceLocation.binaryFolder, !isNestedType));
+// }
+
+// finishedWith(typeLocator, result, compilationUnit.getMainTypeName(), definedTypeNames, duplicateTypeNames);
+ notifier.compiled(compilationUnit);
+ } catch (CoreException e) {
+ Util.log(e, "JavaBuilder handling CoreException"); //$NON-NLS-1$
+ createErrorFor(compilationUnit.resource, Util.bind("build.inconsistentClassFile")); //$NON-NLS-1$
+ }
+ }
+}
+
+protected void cleanUp() {
+ this.nameEnvironment.cleanup();
+
+ this.javaBuilder = null;
+ this.nameEnvironment = null;
+ this.sourceLocations = null;
+ this.notifier = null;
+ this.compiler = null;
+ this.workQueue = null;
+ this.problemSourceFiles = null;
+}
+
+/* Compile the given elements, adding more elements to the work queue
+* if they are affected by the changes.
+*/
+protected void compile(SourceFile[] units) {
+ int toDo = units.length;
+ if (this.compiledAllAtOnce = toDo <= MAX_AT_ONCE) {
+ // do them all now
+ if (PHPBuilder.DEBUG)
+ for (int i = 0; i < toDo; i++)
+ System.out.println("About to compile " + units[i].typeLocator()); //$NON-NLS-1$
+ compile(units, null);
+ } else {
+ int i = 0;
+ boolean compilingFirstGroup = true;
+ while (i < toDo) {
+ int doNow = toDo < MAX_AT_ONCE ? toDo : MAX_AT_ONCE;
+ int index = 0;
+ SourceFile[] toCompile = new SourceFile[doNow];
+ while (i < toDo && index < doNow) {
+ // Although it needed compiling when this method was called, it may have
+ // already been compiled when it was referenced by another unit.
+ SourceFile unit = units[i++];
+ if (compilingFirstGroup || workQueue.isWaiting(unit)) {
+ if (PHPBuilder.DEBUG)
+ System.out.println("About to compile " + unit.typeLocator()); //$NON-NLS-1$
+ toCompile[index++] = unit;
+ }
+ }
+ if (index < doNow)
+ System.arraycopy(toCompile, 0, toCompile = new SourceFile[index], 0, index);
+ SourceFile[] additionalUnits = new SourceFile[toDo - i];
+ System.arraycopy(units, i, additionalUnits, 0, additionalUnits.length);
+ compilingFirstGroup = false;
+ compile(toCompile, additionalUnits);
+ }
+ }
+}
+
+void compile(SourceFile[] units, SourceFile[] additionalUnits) {
+ if (units.length == 0) return;
+ notifier.aboutToCompile(units[0]); // just to change the message
+
+ // extend additionalFilenames with all hierarchical problem types found during this entire build
+ if (!problemSourceFiles.isEmpty()) {
+ int toAdd = problemSourceFiles.size();
+ int length = additionalUnits == null ? 0 : additionalUnits.length;
+ if (length == 0)
+ additionalUnits = new SourceFile[toAdd];
+ else
+ System.arraycopy(additionalUnits, 0, additionalUnits = new SourceFile[length + toAdd], 0, length);
+ for (int i = 0; i < toAdd; i++)
+ additionalUnits[length + i] = (SourceFile) problemSourceFiles.get(i);
+ }
+ String[] initialTypeNames = new String[units.length];
+ for (int i = 0, l = units.length; i < l; i++)
+ initialTypeNames[i] = units[i].initialTypeName;
+ nameEnvironment.setNames(initialTypeNames, additionalUnits);
+ notifier.checkCancel();
+ try {
+ inCompiler = true;
+ compiler.compile(units);
+ } catch (AbortCompilation ignored) {
+ // ignore the AbortCompilcation coming from BuildNotifier.checkCancelWithinCompiler()
+ // the Compiler failed after the user has chose to cancel... likely due to an OutOfMemory error
+ } finally {
+ inCompiler = false;
+ }
+ // Check for cancel immediately after a compile, because the compiler may
+ // have been cancelled but without propagating the correct exception
+ notifier.checkCancel();
+}
+
+protected void createErrorFor(IResource resource, String message) {
+ try {
+ IMarker marker = resource.createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER);
+ int severity = IMarker.SEVERITY_ERROR;
+ if (message.equals(Util.bind("build.duplicateResource"))) //$NON-NLS-1$
+ if (PHPCore.WARNING.equals(javaBuilder.javaProject.getOption(PHPCore.CORE_JAVA_BUILD_DUPLICATE_RESOURCE, true)))
+ severity = IMarker.SEVERITY_WARNING;
+ marker.setAttributes(
+ new String[] {IMarker.MESSAGE, IMarker.SEVERITY, IMarker.CHAR_START, IMarker.CHAR_END},
+ new Object[] {message, new Integer(severity), new Integer(0), new Integer(1)});
+ } catch (CoreException e) {
+ throw internalException(e);
+ }
+}
+
+//protected void finishedWith(String sourceLocator, CompilationResult result, char[] mainTypeName) throws CoreException {//, ArrayList definedTypeNames, ArrayList duplicateTypeNames) throws CoreException {
+// if (duplicateTypeNames == null) {
+// newState.record(sourceLocator, result.qualifiedReferences, result.simpleNameReferences, mainTypeName, definedTypeNames);
+// return;
+// }
+//
+// char[][][] qualifiedRefs = result.qualifiedReferences;
+// char[][] simpleRefs = result.simpleNameReferences;
+// // for each duplicate type p1.p2.A, add the type name A (package was already added)
+// next : for (int i = 0, l = duplicateTypeNames.size(); i < l; i++) {
+// char[][] compoundName = (char[][]) duplicateTypeNames.get(i);
+// char[] typeName = compoundName[compoundName.length - 1];
+// int sLength = simpleRefs.length;
+// for (int j = 0; j < sLength; j++)
+// if (CharOperation.equals(simpleRefs[j], typeName))
+// continue next;
+// System.arraycopy(simpleRefs, 0, simpleRefs = new char[sLength + 1][], 0, sLength);
+// simpleRefs[sLength] = typeName;
+// }
+// newState.record(sourceLocator, qualifiedRefs, simpleRefs, mainTypeName, definedTypeNames);
+//}
+
+protected IContainer createFolder(IPath packagePath, IContainer outputFolder) throws CoreException {
+ if (packagePath.isEmpty()) return outputFolder;
+ IFolder folder = outputFolder.getFolder(packagePath);
+ if (!folder.exists()) {
+ createFolder(packagePath.removeLastSegments(1), outputFolder);
+ folder.create(true, true, null);
+ folder.setDerived(true);
+ }
+ return folder;
+}
+
+protected RuntimeException internalException(CoreException t) {
+ ImageBuilderInternalException imageBuilderException = new ImageBuilderInternalException(t);
+ if (inCompiler)
+ return new AbortCompilation(true, imageBuilderException);
+ return imageBuilderException;
+}
+
+protected Compiler newCompiler() {
+ // called once when the builder is initialized... can override if needed
+ return new Compiler(
+ nameEnvironment,
+ DefaultErrorHandlingPolicies.proceedWithAllProblems(),
+// javaBuilder.javaProject.getOptions(true),
+ this,
+ ProblemFactory.getProblemFactory(Locale.getDefault()));
+}
+
+protected boolean isExcludedFromProject(IPath childPath) throws JavaModelException {
+ // answer whether the folder should be ignored when walking the project as a source folder
+ if (childPath.segmentCount() > 2) return false; // is a subfolder of a package
+
+ for (int j = 0, k = sourceLocations.length; j < k; j++) {
+ if (childPath.equals(sourceLocations[j].binaryFolder.getFullPath())) return true;
+ if (childPath.equals(sourceLocations[j].sourceFolder.getFullPath())) return true;
+ }
+ // skip default output folder which may not be used by any source folder
+ return childPath.equals(javaBuilder.javaProject.getOutputLocation());
+}
+
+/**
+ * Creates a marker from each problem and adds it to the resource.
+ * The marker is as follows:
+ * - its type is T_PROBLEM
+ * - its plugin ID is the JavaBuilder's plugin ID
+ * - its message is the problem's message
+ * - its priority reflects the severity of the problem
+ * - its range is the problem's range
+ * - it has an extra attribute "ID" which holds the problem's id
+ */
+protected void storeProblemsFor(SourceFile sourceFile, IProblem[] problems) throws CoreException {
+ if (sourceFile == null || problems == null || problems.length == 0) return;
+
+// String missingClassFile = null;
+ IResource resource = sourceFile.resource;
+ for (int i = 0, l = problems.length; i < l; i++) {
+ IProblem problem = problems[i];
+ int id = problem.getID();
+ switch (id) {
+ case IProblem.IsClassPathCorrect :
+// PHPBuilder.removeProblemsAndTasksFor(javaBuilder.currentProject); // make this the only problem for this project
+// String[] args = problem.getArguments();
+// missingClassFile = args[0];
+ break;
+ case IProblem.SuperclassMustBeAClass :
+ case IProblem.SuperInterfaceMustBeAnInterface :
+ case IProblem.HierarchyCircularitySelfReference :
+ case IProblem.HierarchyCircularity :
+ case IProblem.HierarchyHasProblems :
+ case IProblem.SuperclassNotFound :
+ case IProblem.SuperclassNotVisible :
+ case IProblem.SuperclassAmbiguous :
+ case IProblem.SuperclassInternalNameProvided :
+ case IProblem.SuperclassInheritedNameHidesEnclosingName :
+ case IProblem.InterfaceNotFound :
+ case IProblem.InterfaceNotVisible :
+ case IProblem.InterfaceAmbiguous :
+ case IProblem.InterfaceInternalNameProvided :
+ case IProblem.InterfaceInheritedNameHidesEnclosingName :
+ // ensure that this file is always retrieved from source for the rest of the build
+ if (!problemSourceFiles.contains(sourceFile))
+ problemSourceFiles.add(sourceFile);
+ break;
+ }
+
+ if (id != IProblem.Task) {
+ IMarker marker = resource.createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER);
+ marker.setAttributes(
+ new String[] {
+ IMarker.MESSAGE,
+ IMarker.SEVERITY,
+ IJavaModelMarker.ID,
+ IMarker.CHAR_START,
+ IMarker.CHAR_END,
+ IMarker.LINE_NUMBER,
+ IJavaModelMarker.ARGUMENTS},
+ new Object[] {
+ problem.getMessage(),
+ new Integer(problem.isError() ? IMarker.SEVERITY_ERROR : IMarker.SEVERITY_WARNING),
+ new Integer(id),
+ new Integer(problem.getSourceStart()),
+ new Integer(problem.getSourceEnd() + 1),
+ new Integer(problem.getSourceLineNumber()),
+ Util.getProblemArgumentsForMarker(problem.getArguments())
+ });
+ }
+
+/* Do NOT want to populate the Java Model just to find the matching Java element.
+ * Also cannot query compilation units located in folders with invalid package
+ * names such as 'a/b.c.d/e'.
+
+ // compute a user-friendly location
+ IJavaElement element = JavaCore.create(resource);
+ if (element instanceof org.eclipse.jdt.core.ICompilationUnit) { // try to find a finer grain element
+ org.eclipse.jdt.core.ICompilationUnit unit = (org.eclipse.jdt.core.ICompilationUnit) element;
+ IJavaElement fragment = unit.getElementAt(problem.getSourceStart());
+ if (fragment != null) element = fragment;
+ }
+ String location = null;
+ if (element instanceof JavaElement)
+ location = ((JavaElement) element).readableName();
+ if (location != null)
+ marker.setAttribute(IMarker.LOCATION, location);
+*/
+
+// if (missingClassFile != null)
+// throw new MissingClassFileException(missingClassFile);
+ }
+}
+
+protected void storeTasksFor(SourceFile sourceFile, IProblem[] tasks) throws CoreException {
+ if (sourceFile == null || tasks == null || tasks.length == 0) return;
+
+ IResource resource = sourceFile.resource;
+ for (int i = 0, l = tasks.length; i < l; i++) {
+ IProblem task = tasks[i];
+ if (task.getID() == IProblem.Task) {
+ IMarker marker = resource.createMarker(IJavaModelMarker.TASK_MARKER);
+ int priority = IMarker.PRIORITY_NORMAL;
+ String compilerPriority = task.getArguments()[2];
+ if (PHPCore.COMPILER_TASK_PRIORITY_HIGH.equals(compilerPriority))
+ priority = IMarker.PRIORITY_HIGH;
+ else if (PHPCore.COMPILER_TASK_PRIORITY_LOW.equals(compilerPriority))
+ priority = IMarker.PRIORITY_LOW;
+ marker.setAttributes(
+ new String[] {
+ IMarker.MESSAGE,
+ IMarker.PRIORITY,
+ IMarker.DONE,
+ IMarker.CHAR_START,
+ IMarker.CHAR_END,
+ IMarker.LINE_NUMBER,
+ IMarker.USER_EDITABLE,
+ },
+ new Object[] {
+ task.getMessage(),
+ new Integer(priority),
+ new Boolean(false),
+ new Integer(task.getSourceStart()),
+ new Integer(task.getSourceEnd() + 1),
+ new Integer(task.getSourceLineNumber()),
+ new Boolean(false),
+ });
+ }
+ }
+}
+
+protected void updateProblemsFor(SourceFile sourceFile, CompilationResult result) throws CoreException {
+ IProblem[] problems = result.getProblems();
+ if (problems == null || problems.length == 0) return;
+
+ notifier.updateProblemCounts(problems);
+ storeProblemsFor(sourceFile, problems);
+}
+
+protected void updateTasksFor(SourceFile sourceFile, CompilationResult result) throws CoreException {
+ IProblem[] tasks = result.getTasks();
+ if (tasks == null || tasks.length == 0) return;
+
+ storeTasksFor(sourceFile, tasks);
+}
+
+//protected char[] writeClassFile(ClassFile classFile, IContainer outputFolder, boolean isSecondaryType) throws CoreException {
+// String fileName = new String(classFile.fileName()); // the qualified type name "p1/p2/A"
+// IPath filePath = new Path(fileName);
+// IContainer container = outputFolder;
+// if (filePath.segmentCount() > 1) {
+// container = createFolder(filePath.removeLastSegments(1), outputFolder);
+// filePath = new Path(filePath.lastSegment());
+// }
+//
+// IFile file = container.getFile(filePath.addFileExtension(JavaBuilder.CLASS_EXTENSION));
+// writeClassFileBytes(classFile.getBytes(), file, fileName, isSecondaryType);
+// // answer the name of the class file as in Y or Y$M
+// return filePath.lastSegment().toCharArray();
+//}
+//
+//protected void writeClassFileBytes(byte[] bytes, IFile file, String qualifiedFileName, boolean isSecondaryType) throws CoreException {
+// if (file.exists()) {
+// // Deal with shared output folders... last one wins... no collision cases detected
+// if (JavaBuilder.DEBUG)
+// System.out.println("Writing changed class file " + file.getName());//$NON-NLS-1$
+// file.setContents(new ByteArrayInputStream(bytes), true, false, null);
+// if (!file.isDerived())
+// file.setDerived(true);
+// } else {
+// // Default implementation just writes out the bytes for the new class file...
+// if (JavaBuilder.DEBUG)
+// System.out.println("Writing new class file " + file.getName());//$NON-NLS-1$
+// file.create(new ByteArrayInputStream(bytes), IResource.FORCE, null);
+// file.setDerived(true);
+// }
+//}
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/AdditionalTypeCollection.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/AdditionalTypeCollection.java
new file mode 100644
index 0000000..1979871
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/AdditionalTypeCollection.java
@@ -0,0 +1,22 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core.builder;
+
+public class AdditionalTypeCollection extends ReferenceCollection {
+
+char[][] definedTypeNames;
+
+protected AdditionalTypeCollection(char[][] definedTypeNames, char[][][] qualifiedReferences, char[][] simpleNameReferences) {
+ super(qualifiedReferences, simpleNameReferences);
+ this.definedTypeNames = definedTypeNames; // do not bother interning member type names (ie. 'A$M')
+}
+}
+
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/BatchImageBuilder.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/BatchImageBuilder.java
new file mode 100644
index 0000000..579de3c
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/BatchImageBuilder.java
@@ -0,0 +1,248 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core.builder;
+
+import java.util.ArrayList;
+
+import net.sourceforge.phpdt.internal.core.JavaModelManager;
+import net.sourceforge.phpdt.internal.core.Util;
+import net.sourceforge.phpeclipse.PHPCore;
+
+import org.eclipse.core.resources.IContainer;
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.IResourceProxy;
+import org.eclipse.core.resources.IResourceProxyVisitor;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IPath;
+
+public class BatchImageBuilder extends AbstractImageBuilder {
+
+protected BatchImageBuilder(PHPBuilder javaBuilder) {
+ super(javaBuilder);
+ this.nameEnvironment.isIncrementalBuild = false;
+}
+
+public void build() {
+ if (PHPBuilder.DEBUG)
+ System.out.println("FULL build"); //$NON-NLS-1$
+
+ try {
+// notifier.subTask(Util.bind("build.cleaningOutput")); //$NON-NLS-1$
+// JavaModelManager.getJavaModelManager().deltaProcessor.addForRefresh(javaBuilder.javaProject);
+// PHPBuilder.removeProblemsAndTasksFor(javaBuilder.currentProject);
+// cleanOutputFolders();
+ notifier.updateProgressDelta(0.1f);
+
+ notifier.subTask(Util.bind("build.analyzingSources")); //$NON-NLS-1$
+ ArrayList sourceFiles = new ArrayList(33);
+ addAllSourceFiles(sourceFiles);
+ notifier.updateProgressDelta(0.15f);
+
+ if (sourceFiles.size() > 0) {
+ SourceFile[] allSourceFiles = new SourceFile[sourceFiles.size()];
+ sourceFiles.toArray(allSourceFiles);
+
+ notifier.setProgressPerCompilationUnit(0.75f / allSourceFiles.length);
+ workQueue.addAll(allSourceFiles);
+ compile(allSourceFiles);
+ }
+
+ if (javaBuilder.javaProject.hasCycleMarker())
+ javaBuilder.mustPropagateStructuralChanges();
+ } catch (CoreException e) {
+ throw internalException(e);
+ } finally {
+ cleanUp();
+ }
+}
+
+protected void addAllSourceFiles(final ArrayList sourceFiles) throws CoreException {
+ for (int i = 0, l = sourceLocations.length; i < l; i++) {
+ final ClasspathMultiDirectory sourceLocation = sourceLocations[i];
+ final char[][] exclusionPatterns = sourceLocation.exclusionPatterns;
+ final boolean isAlsoProject = sourceLocation.sourceFolder.equals(javaBuilder.currentProject);
+ sourceLocation.sourceFolder.accept(
+ new IResourceProxyVisitor() {
+ public boolean visit(IResourceProxy proxy) throws CoreException {
+ IResource resource = null;
+ if (exclusionPatterns != null) {
+ resource = proxy.requestResource();
+ if (Util.isExcluded(resource, exclusionPatterns)) return false;
+ }
+ switch(proxy.getType()) {
+ case IResource.FILE :
+ if (Util.isJavaFileName(proxy.getName())) {
+ if (resource == null)
+ resource = proxy.requestResource();
+ sourceFiles.add(new SourceFile((IFile) resource, sourceLocation, encoding));
+ }
+ return false;
+ case IResource.FOLDER :
+ if (isAlsoProject && isExcludedFromProject(proxy.requestFullPath())) return false;
+ }
+ return true;
+ }
+ },
+ IResource.NONE
+ );
+ notifier.checkCancel();
+ }
+}
+
+protected void cleanOutputFolders() throws CoreException {
+ boolean deleteAll = PHPCore.CLEAN.equals(
+ javaBuilder.javaProject.getOption(PHPCore.CORE_JAVA_BUILD_CLEAN_OUTPUT_FOLDER, true));
+ if (deleteAll) {
+ ArrayList visited = new ArrayList(sourceLocations.length);
+ for (int i = 0, l = sourceLocations.length; i < l; i++) {
+ notifier.subTask(Util.bind("build.cleaningOutput")); //$NON-NLS-1$
+ ClasspathMultiDirectory sourceLocation = sourceLocations[i];
+ if (sourceLocation.hasIndependentOutputFolder) {
+ IContainer outputFolder = sourceLocation.binaryFolder;
+ if (!visited.contains(outputFolder)) {
+ visited.add(outputFolder);
+ IResource[] members = outputFolder.members();
+ for (int j = 0, m = members.length; j < m; j++)
+ members[j].delete(IResource.FORCE, null);
+ }
+ notifier.checkCancel();
+ copyExtraResourcesBack(sourceLocation, deleteAll);
+ } else {
+ boolean isOutputFolder = sourceLocation.sourceFolder.equals(sourceLocation.binaryFolder);
+ final char[][] exclusionPatterns =
+ isOutputFolder
+ ? sourceLocation.exclusionPatterns
+ : null; // ignore exclusionPatterns if output folder == another source folder... not this one
+ sourceLocation.binaryFolder.accept(
+ new IResourceProxyVisitor() {
+ public boolean visit(IResourceProxy proxy) throws CoreException {
+ IResource resource = null;
+ if (exclusionPatterns != null) {
+ resource = proxy.requestResource();
+ if (Util.isExcluded(resource, exclusionPatterns)) return false;
+ }
+ if (proxy.getType() == IResource.FILE) {
+// if (Util.isClassFileName(proxy.getName())) {
+// if (resource == null)
+// resource = proxy.requestResource();
+// resource.delete(IResource.FORCE, null);
+// }
+ return false;
+ }
+ notifier.checkCancel();
+ return true;
+ }
+ },
+ IResource.NONE
+ );
+ if (!isOutputFolder) {
+ notifier.checkCancel();
+ copyPackages(sourceLocation);
+ }
+ }
+ notifier.checkCancel();
+ }
+ } else {
+ for (int i = 0, l = sourceLocations.length; i < l; i++) {
+ ClasspathMultiDirectory sourceLocation = sourceLocations[i];
+ if (sourceLocation.hasIndependentOutputFolder)
+ copyExtraResourcesBack(sourceLocation, deleteAll);
+ else if (!sourceLocation.sourceFolder.equals(sourceLocation.binaryFolder))
+ copyPackages(sourceLocation); // output folder is different from source folder
+ notifier.checkCancel();
+ }
+ }
+}
+
+protected void copyExtraResourcesBack(ClasspathMultiDirectory sourceLocation, final boolean deletedAll) throws CoreException {
+ // When, if ever, does a builder need to copy resources files (not .java or .class) into the output folder?
+ // If we wipe the output folder at the beginning of the build then all 'extra' resources must be copied to the output folder.
+
+ notifier.subTask(Util.bind("build.copyingResources")); //$NON-NLS-1$
+ final int segmentCount = sourceLocation.sourceFolder.getFullPath().segmentCount();
+ final char[][] exclusionPatterns = sourceLocation.exclusionPatterns;
+ final IContainer outputFolder = sourceLocation.binaryFolder;
+ final boolean isAlsoProject = sourceLocation.sourceFolder.equals(javaBuilder.currentProject);
+ sourceLocation.sourceFolder.accept(
+ new IResourceProxyVisitor() {
+ public boolean visit(IResourceProxy proxy) throws CoreException {
+ IResource resource = null;
+ switch(proxy.getType()) {
+ case IResource.FILE :
+ if (Util.isJavaFileName(proxy.getName())) return false;// || Util.isClassFileName(proxy.getName())) return false;
+
+ resource = proxy.requestResource();
+ if (javaBuilder.filterExtraResource(resource)) return false;
+ if (exclusionPatterns != null && Util.isExcluded(resource, exclusionPatterns))
+ return false;
+
+ IPath partialPath = resource.getFullPath().removeFirstSegments(segmentCount);
+ IResource copiedResource = outputFolder.getFile(partialPath);
+ if (copiedResource.exists()) {
+ if (deletedAll) {
+ createErrorFor(resource, Util.bind("build.duplicateResource")); //$NON-NLS-1$
+ return false;
+ }
+ copiedResource.delete(IResource.FORCE, null); // last one wins
+ }
+ resource.copy(copiedResource.getFullPath(), IResource.FORCE, null);
+ copiedResource.setDerived(true);
+ return false;
+ case IResource.FOLDER :
+ resource = proxy.requestResource();
+ if (javaBuilder.filterExtraResource(resource)) return false;
+ if (exclusionPatterns != null && Util.isExcluded(resource, exclusionPatterns))
+ return false;
+
+ IPath folderPath = resource.getFullPath();
+ if (isAlsoProject && isExcludedFromProject(folderPath)) return false; // the sourceFolder == project
+ createFolder(folderPath.removeFirstSegments(segmentCount), outputFolder);
+ }
+ return true;
+ }
+ },
+ IResource.NONE
+ );
+}
+
+protected void copyPackages(ClasspathMultiDirectory sourceLocation) throws CoreException {
+ final int segmentCount = sourceLocation.sourceFolder.getFullPath().segmentCount();
+ final char[][] exclusionPatterns = sourceLocation.exclusionPatterns;
+ final IContainer outputFolder = sourceLocation.binaryFolder;
+ final boolean isAlsoProject = sourceLocation.sourceFolder.equals(javaBuilder.currentProject);
+ sourceLocation.sourceFolder.accept(
+ new IResourceProxyVisitor() {
+ public boolean visit(IResourceProxy proxy) throws CoreException {
+ switch(proxy.getType()) {
+ case IResource.FILE :
+ return false;
+ case IResource.FOLDER :
+ IResource resource = proxy.requestResource();
+ if (javaBuilder.filterExtraResource(resource)) return false;
+ if (exclusionPatterns != null && Util.isExcluded(resource, exclusionPatterns))
+ return false;
+
+ IPath folderPath = resource.getFullPath();
+ if (isAlsoProject && isExcludedFromProject(folderPath)) return false; // the sourceFolder == project
+ createFolder(folderPath.removeFirstSegments(segmentCount), outputFolder);
+ }
+ return true;
+ }
+ },
+ IResource.NONE
+ );
+}
+
+public String toString() {
+ return "batch image builder for:\n\tnew state: " + newState; //$NON-NLS-1$
+}
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/BuildNotifier.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/BuildNotifier.java
new file mode 100644
index 0000000..032cf26
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/BuildNotifier.java
@@ -0,0 +1,278 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core.builder;
+
+import net.sourceforge.phpdt.core.compiler.IProblem;
+import net.sourceforge.phpdt.internal.compiler.problem.AbortCompilation;
+import net.sourceforge.phpdt.internal.compiler.util.Util;
+
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.OperationCanceledException;
+
+public class BuildNotifier {
+
+protected IProgressMonitor monitor;
+protected boolean cancelling;
+protected float percentComplete;
+protected float progressPerCompilationUnit;
+protected int newErrorCount;
+protected int fixedErrorCount;
+protected int newWarningCount;
+protected int fixedWarningCount;
+protected int workDone;
+protected int totalWork;
+protected String previousSubtask;
+
+public static int NewErrorCount = 0;
+public static int FixedErrorCount = 0;
+public static int NewWarningCount = 0;
+public static int FixedWarningCount = 0;
+
+public static void resetProblemCounters() {
+ NewErrorCount = 0;
+ FixedErrorCount = 0;
+ NewWarningCount = 0;
+ FixedWarningCount = 0;
+}
+
+public BuildNotifier(IProgressMonitor monitor, IProject project) {
+ this.monitor = monitor;
+ this.cancelling = false;
+ this.newErrorCount = NewErrorCount;
+ this.fixedErrorCount = FixedErrorCount;
+ this.newWarningCount = NewWarningCount;
+ this.fixedWarningCount = FixedWarningCount;
+ this.workDone = 0;
+ this.totalWork = 1000000;
+}
+
+/**
+ * Notification before a compile that a unit is about to be compiled.
+ */
+public void aboutToCompile(SourceFile unit) {
+ String message = Util.bind("build.compiling", unit.resource.getFullPath().removeLastSegments(1).makeRelative().toString()); //$NON-NLS-1$
+ subTask(message);
+}
+
+public void begin() {
+ if (monitor != null)
+ monitor.beginTask("", totalWork); //$NON-NLS-1$
+ this.previousSubtask = null;
+}
+
+/**
+ * Check whether the build has been canceled.
+ */
+public void checkCancel() {
+ if (monitor != null && monitor.isCanceled())
+ throw new OperationCanceledException();
+}
+
+/**
+ * Check whether the build has been canceled.
+ * Must use this call instead of checkCancel() when within the compiler.
+ */
+public void checkCancelWithinCompiler() {
+ if (monitor != null && monitor.isCanceled() && !cancelling) {
+ // Once the compiler has been canceled, don't check again.
+ setCancelling(true);
+ // Only AbortCompilation can stop the compiler cleanly.
+ // We check cancelation again following the call to compile.
+ throw new AbortCompilation(true, null);
+ }
+}
+
+/**
+ * Notification while within a compile that a unit has finished being compiled.
+ */
+public void compiled(SourceFile unit) {
+ String message = Util.bind("build.compiling", unit.resource.getFullPath().removeLastSegments(1).makeRelative().toString()); //$NON-NLS-1$
+ subTask(message);
+ updateProgressDelta(progressPerCompilationUnit);
+ checkCancelWithinCompiler();
+}
+
+public void done() {
+ NewErrorCount = this.newErrorCount;
+ FixedErrorCount = this.fixedErrorCount;
+ NewWarningCount = this.newWarningCount;
+ FixedWarningCount = this.fixedWarningCount;
+
+ updateProgress(1.0f);
+ subTask(Util.bind("build.done")); //$NON-NLS-1$
+ if (monitor != null)
+ monitor.done();
+ this.previousSubtask = null;
+}
+
+/**
+ * Returns a string describing the problems.
+ */
+protected String problemsMessage() {
+ int numNew = newErrorCount + newWarningCount;
+ int numFixed = fixedErrorCount + fixedWarningCount;
+ if (numNew == 0 && numFixed == 0) return ""; //$NON-NLS-1$
+
+ boolean displayBoth = numNew > 0 && numFixed > 0;
+ StringBuffer buffer = new StringBuffer();
+ buffer.append('(');
+ if (numNew > 0) {
+ // (Found x errors + y warnings)
+ buffer.append(Util.bind("build.foundHeader")); //$NON-NLS-1$
+ buffer.append(' ');
+ if (displayBoth || newErrorCount > 0) {
+ if (newErrorCount == 1)
+ buffer.append(Util.bind("build.oneError")); //$NON-NLS-1$
+ else
+ buffer.append(Util.bind("build.multipleErrors", String.valueOf(newErrorCount))); //$NON-NLS-1$
+ if (displayBoth || newWarningCount > 0)
+ buffer.append(" + "); //$NON-NLS-1$
+ }
+ if (displayBoth || newWarningCount > 0) {
+ if (newWarningCount == 1)
+ buffer.append(Util.bind("build.oneWarning")); //$NON-NLS-1$
+ else
+ buffer.append(Util.bind("build.multipleWarnings", String.valueOf(newWarningCount))); //$NON-NLS-1$
+ }
+ if (numFixed > 0)
+ buffer.append(", "); //$NON-NLS-1$
+ }
+ if (numFixed > 0) {
+ // (Fixed x errors + y warnings) or (Found x errors + y warnings, Fixed x + y)
+ buffer.append(Util.bind("build.fixedHeader")); //$NON-NLS-1$
+ buffer.append(' ');
+ if (displayBoth) {
+ buffer.append(String.valueOf(fixedErrorCount));
+ buffer.append(" + "); //$NON-NLS-1$
+ buffer.append(String.valueOf(fixedWarningCount));
+ } else {
+ if (fixedErrorCount > 0) {
+ if (fixedErrorCount == 1)
+ buffer.append(Util.bind("build.oneError")); //$NON-NLS-1$
+ else
+ buffer.append(Util.bind("build.multipleErrors", String.valueOf(fixedErrorCount))); //$NON-NLS-1$
+ if (fixedWarningCount > 0)
+ buffer.append(" + "); //$NON-NLS-1$
+ }
+ if (fixedWarningCount > 0) {
+ if (fixedWarningCount == 1)
+ buffer.append(Util.bind("build.oneWarning")); //$NON-NLS-1$
+ else
+ buffer.append(Util.bind("build.multipleWarnings", String.valueOf(fixedWarningCount))); //$NON-NLS-1$
+ }
+ }
+ }
+ buffer.append(')');
+ return buffer.toString();
+}
+
+/**
+ * Sets the cancelling flag, which indicates we are in the middle
+ * of being cancelled. Certain places (those callable indirectly from the compiler)
+ * should not check cancel again while this is true, to avoid OperationCanceledException
+ * being thrown at an inopportune time.
+ */
+public void setCancelling(boolean cancelling) {
+ this.cancelling = cancelling;
+}
+
+/**
+ * Sets the amount of progress to report for compiling each compilation unit.
+ */
+public void setProgressPerCompilationUnit(float progress) {
+ this.progressPerCompilationUnit = progress;
+}
+
+public void subTask(String message) {
+ String pm = problemsMessage();
+ String msg = pm.length() == 0 ? message : pm + " " + message; //$NON-NLS-1$
+
+ if (msg.equals(this.previousSubtask)) return; // avoid refreshing with same one
+ //if (JavaBuilder.DEBUG) System.out.println(msg);
+ if (monitor != null)
+ monitor.subTask(msg);
+
+ this.previousSubtask = msg;
+}
+
+protected void updateProblemCounts(IProblem[] newProblems) {
+ for (int i = 0, l = newProblems.length; i < l; i++)
+ if (newProblems[i].isError()) newErrorCount++; else newWarningCount++;
+}
+
+/**
+ * Update the problem counts from one compilation result given the old and new problems,
+ * either of which may be null.
+ */
+protected void updateProblemCounts(IMarker[] oldProblems, IProblem[] newProblems) {
+ if (newProblems != null) {
+ next : for (int i = 0, l = newProblems.length; i < l; i++) {
+ IProblem newProblem = newProblems[i];
+ if (newProblem.getID() == IProblem.Task) continue; // skip task
+ boolean isError = newProblem.isError();
+ String message = newProblem.getMessage();
+
+ if (oldProblems != null) {
+ for (int j = 0, m = oldProblems.length; j < m; j++) {
+ IMarker pb = oldProblems[j];
+ if (pb == null) continue; // already matched up with a new problem
+ boolean wasError = IMarker.SEVERITY_ERROR
+ == pb.getAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR);
+ if (isError == wasError && message.equals(pb.getAttribute(IMarker.MESSAGE, ""))) { //$NON-NLS-1$
+ oldProblems[j] = null;
+ continue next;
+ }
+ }
+ }
+ if (isError) newErrorCount++; else newWarningCount++;
+ }
+ }
+ if (oldProblems != null) {
+ next : for (int i = 0, l = oldProblems.length; i < l; i++) {
+ IMarker oldProblem = oldProblems[i];
+ if (oldProblem == null) continue next; // already matched up with a new problem
+ boolean wasError = IMarker.SEVERITY_ERROR
+ == oldProblem.getAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR);
+ String message = oldProblem.getAttribute(IMarker.MESSAGE, ""); //$NON-NLS-1$
+
+ if (newProblems != null) {
+ for (int j = 0, m = newProblems.length; j < m; j++) {
+ IProblem pb = newProblems[j];
+ if (pb.getID() == IProblem.Task) continue; // skip task
+ if (wasError == pb.isError() && message.equals(pb.getMessage()))
+ continue next;
+ }
+ }
+ if (wasError) fixedErrorCount++; else fixedWarningCount++;
+ }
+ }
+}
+
+public void updateProgress(float percentComplete) {
+ if (percentComplete > this.percentComplete) {
+ this.percentComplete = Math.min(percentComplete, 1.0f);
+ int work = Math.round(this.percentComplete * this.totalWork);
+ if (work > this.workDone) {
+ if (monitor != null)
+ monitor.worked(work - this.workDone);
+ //if (JavaBuilder.DEBUG)
+ //System.out.println(java.text.NumberFormat.getPercentInstance().format(this.percentComplete));
+ this.workDone = work;
+ }
+ }
+}
+
+public void updateProgressDelta(float percentWorked) {
+ updateProgress(percentComplete + percentWorked);
+}
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/ClasspathDirectory.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/ClasspathDirectory.java
new file mode 100644
index 0000000..86f7d35
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/ClasspathDirectory.java
@@ -0,0 +1,117 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core.builder;
+
+import net.sourceforge.phpdt.internal.compiler.env.NameEnvironmentAnswer;
+import net.sourceforge.phpdt.internal.core.Util;
+import net.sourceforge.phpdt.internal.core.util.SimpleLookupTable;
+
+import org.eclipse.core.resources.IContainer;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IPath;
+
+class ClasspathDirectory extends ClasspathLocation {
+
+IContainer binaryFolder; // includes .class files for a single directory
+boolean isOutputFolder;
+String binaryLocation;
+SimpleLookupTable directoryCache;
+String[] missingPackageHolder = new String[1];
+
+ClasspathDirectory(IContainer binaryFolder, boolean isOutputFolder) {
+ this.binaryFolder = binaryFolder;
+ this.isOutputFolder = isOutputFolder;
+ IPath location = binaryFolder.getLocation();
+ this.binaryLocation = location != null ? location.addTrailingSeparator().toString() : ""; //$NON-NLS-1$
+
+ this.directoryCache = new SimpleLookupTable(5);
+}
+
+public void cleanup() {
+ this.directoryCache = null;
+}
+
+String[] directoryList(String qualifiedPackageName) {
+ String[] dirList = (String[]) directoryCache.get(qualifiedPackageName);
+ if (dirList == missingPackageHolder) return null; // package exists in another classpath directory or jar
+ if (dirList != null) return dirList;
+
+ try {
+ IResource container = binaryFolder.findMember(qualifiedPackageName); // this is a case-sensitive check
+ if (container instanceof IContainer) {
+ IResource[] members = ((IContainer) container).members();
+ dirList = new String[members.length];
+ int index = 0;
+ for (int i = 0, l = members.length; i < l; i++) {
+ IResource m = members[i];
+// if (m.getType() == IResource.FILE && Util.isClassFileName(m.getName()))
+// // add exclusion pattern check here if we want to hide .class files
+// dirList[index++] = m.getName();
+ }
+ if (index < dirList.length)
+ System.arraycopy(dirList, 0, dirList = new String[index], 0, index);
+ directoryCache.put(qualifiedPackageName, dirList);
+ return dirList;
+ }
+ } catch(CoreException ignored) {
+ }
+ directoryCache.put(qualifiedPackageName, missingPackageHolder);
+ return null;
+}
+
+boolean doesFileExist(String fileName, String qualifiedPackageName, String qualifiedFullName) {
+ String[] dirList = directoryList(qualifiedPackageName);
+ if (dirList == null) return false; // most common case
+
+ for (int i = dirList.length; --i >= 0;)
+ if (fileName.equals(dirList[i]))
+ return true;
+ return false;
+}
+
+public boolean equals(Object o) {
+ if (this == o) return true;
+ if (!(o instanceof ClasspathDirectory)) return false;
+
+ return binaryFolder.equals(((ClasspathDirectory) o).binaryFolder);
+}
+
+public NameEnvironmentAnswer findClass(String binaryFileName, String qualifiedPackageName, String qualifiedBinaryFileName) {
+ if (!doesFileExist(binaryFileName, qualifiedPackageName, qualifiedBinaryFileName)) return null; // most common case
+
+// try {
+// ClassFileReader reader = ClassFileReader.read(binaryLocation + qualifiedBinaryFileName);
+// if (reader != null) return new NameEnvironmentAnswer(reader);
+// } catch (Exception e) {} // treat as if class file is missing
+ return null;
+}
+
+public IPath getProjectRelativePath() {
+ return binaryFolder.getProjectRelativePath();
+}
+
+public boolean isOutputFolder() {
+ return isOutputFolder;
+}
+
+public boolean isPackage(String qualifiedPackageName) {
+ return directoryList(qualifiedPackageName) != null;
+}
+
+public void reset() {
+ this.directoryCache = new SimpleLookupTable(5);
+}
+
+public String toString() {
+ return "Binary classpath directory " + binaryFolder.getFullPath().toString(); //$NON-NLS-1$
+}
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/ClasspathLocation.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/ClasspathLocation.java
new file mode 100644
index 0000000..c9bbdad
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/ClasspathLocation.java
@@ -0,0 +1,53 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core.builder;
+
+import net.sourceforge.phpdt.internal.compiler.env.NameEnvironmentAnswer;
+
+import org.eclipse.core.resources.IContainer;
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.runtime.IPath;
+
+public abstract class ClasspathLocation {
+
+static ClasspathLocation forSourceFolder(IContainer sourceFolder, IContainer outputFolder, char[][] exclusionPatterns) {
+ return new ClasspathMultiDirectory(sourceFolder, outputFolder, exclusionPatterns);
+}
+
+public static ClasspathLocation forBinaryFolder(IContainer binaryFolder, boolean isOutputFolder) {
+ return new ClasspathDirectory(binaryFolder, isOutputFolder);
+}
+
+//static ClasspathLocation forLibrary(String libraryPathname) {
+// return new ClasspathJar(libraryPathname);
+//}
+
+//static ClasspathLocation forLibrary(IFile library) {
+// return new ClasspathJar(library);
+//}
+
+public abstract NameEnvironmentAnswer findClass(String binaryFileName, String qualifiedPackageName, String qualifiedBinaryFileName);
+
+public abstract IPath getProjectRelativePath();
+
+public boolean isOutputFolder() {
+ return false;
+}
+
+public abstract boolean isPackage(String qualifiedPackageName);
+
+// free anything which is not required when the state is saved
+public void cleanup() {
+}
+// reset any internal caches before another compile loop starts
+public void reset() {
+}
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/ClasspathMultiDirectory.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/ClasspathMultiDirectory.java
new file mode 100644
index 0000000..077fa45
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/ClasspathMultiDirectory.java
@@ -0,0 +1,48 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core.builder;
+
+import net.sourceforge.phpdt.core.compiler.CharOperation;
+
+import org.eclipse.core.resources.IContainer;
+
+class ClasspathMultiDirectory extends ClasspathDirectory {
+
+IContainer sourceFolder;
+char[][] exclusionPatterns; // used by builders when walking source folders
+boolean hasIndependentOutputFolder; // if output folder is not equal to any of the source folders
+
+ClasspathMultiDirectory(IContainer sourceFolder, IContainer binaryFolder, char[][] exclusionPatterns) {
+ super(binaryFolder, true);
+
+ this.sourceFolder = sourceFolder;
+ this.exclusionPatterns = exclusionPatterns;
+ this.hasIndependentOutputFolder = false;
+
+ // handle the case when a state rebuilds a source folder
+ if (this.exclusionPatterns != null && this.exclusionPatterns.length == 0)
+ this.exclusionPatterns = null;
+}
+
+public boolean equals(Object o) {
+ if (this == o) return true;
+ if (!(o instanceof ClasspathMultiDirectory)) return false;
+
+ ClasspathMultiDirectory md = (ClasspathMultiDirectory) o;
+ return sourceFolder.equals(md.sourceFolder) && binaryFolder.equals(md.binaryFolder)
+ && CharOperation.equals(exclusionPatterns, md.exclusionPatterns);
+}
+
+public String toString() {
+ return "Source classpath directory " + sourceFolder.getFullPath().toString() + //$NON-NLS-1$
+ " with binary directory " + binaryFolder.getFullPath().toString(); //$NON-NLS-1$
+}
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/ImageBuilderInternalException.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/ImageBuilderInternalException.java
new file mode 100644
index 0000000..8de3250
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/ImageBuilderInternalException.java
@@ -0,0 +1,40 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core.builder;
+
+import org.eclipse.core.runtime.CoreException;
+
+/**
+ * Exception thrown when there is an internal error in the image builder.
+ * May wrapper another exception.
+ */
+public class ImageBuilderInternalException extends RuntimeException {
+
+protected CoreException coreException;
+
+public ImageBuilderInternalException(CoreException e) {
+ this.coreException = e;
+}
+
+public CoreException getThrowable() {
+ return coreException;
+}
+
+public void printStackTrace() {
+ if (coreException != null) {
+ System.err.println(this);
+ System.err.println("Stack trace of embedded core exception:"); //$NON-NLS-1$
+ coreException.printStackTrace();
+ } else {
+ super.printStackTrace();
+ }
+}
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/IncrementalImageBuilder.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/IncrementalImageBuilder.java
new file mode 100644
index 0000000..694bcd9
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/IncrementalImageBuilder.java
@@ -0,0 +1,649 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core.builder;
+
+import java.util.ArrayList;
+
+import net.sourceforge.phpdt.core.compiler.CharOperation;
+import net.sourceforge.phpdt.core.compiler.IProblem;
+import net.sourceforge.phpdt.internal.compiler.CompilationResult;
+import net.sourceforge.phpdt.internal.core.Util;
+import net.sourceforge.phpdt.internal.core.util.SimpleLookupTable;
+
+import org.eclipse.core.resources.IContainer;
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IFolder;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.IResourceDelta;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IPath;
+
+/**
+ * The incremental image builder
+ */
+public class IncrementalImageBuilder extends AbstractImageBuilder {
+
+protected ArrayList sourceFiles;
+protected ArrayList previousSourceFiles;
+protected ArrayList qualifiedStrings;
+protected ArrayList simpleStrings;
+protected SimpleLookupTable secondaryTypesToRemove;
+protected boolean hasStructuralChanges;
+protected int compileLoop;
+
+public static int MaxCompileLoop = 5; // perform a full build if it takes more than ? incremental compile loops
+
+protected IncrementalImageBuilder(PHPBuilder javaBuilder) {
+ super(javaBuilder);
+ this.nameEnvironment.isIncrementalBuild = true;
+ this.newState.copyFrom(javaBuilder.lastState);
+
+ this.sourceFiles = new ArrayList(33);
+ this.previousSourceFiles = null;
+ this.qualifiedStrings = new ArrayList(33);
+ this.simpleStrings = new ArrayList(33);
+ this.hasStructuralChanges = false;
+ this.compileLoop = 0;
+}
+
+public boolean build(SimpleLookupTable deltas) {
+ // initialize builder
+ // walk this project's deltas, find changed source files
+ // walk prereq projects' deltas, find changed class files & add affected source files
+ // use the build state # to skip the deltas for certain prereq projects
+ // ignore changed zip/jar files since they caused a full build
+ // compile the source files & acceptResult()
+ // compare the produced class files against the existing ones on disk
+ // recompile all dependent source files of any type with structural changes or new/removed secondary type
+ // keep a loop counter to abort & perform a full build
+
+ if (PHPBuilder.DEBUG)
+ System.out.println("INCREMENTAL build"); //$NON-NLS-1$
+
+ try {
+ resetCollections();
+
+ notifier.subTask(Util.bind("build.analyzingDeltas")); //$NON-NLS-1$
+ IResourceDelta sourceDelta = (IResourceDelta) deltas.get(javaBuilder.currentProject);
+ if (sourceDelta != null)
+ if (!findSourceFiles(sourceDelta)) return false;
+ notifier.updateProgressDelta(0.10f);
+
+ Object[] keyTable = deltas.keyTable;
+ Object[] valueTable = deltas.valueTable;
+ for (int i = 0, l = valueTable.length; i < l; i++) {
+ IResourceDelta delta = (IResourceDelta) valueTable[i];
+ if (delta != null) {
+// ClasspathLocation[] classFoldersAndJars = (ClasspathLocation[]) javaBuilder.binaryLocationsPerProject.get(keyTable[i]);
+// if (classFoldersAndJars != null)
+// if (!findAffectedSourceFiles(delta, classFoldersAndJars)) return false;
+ }
+ }
+ notifier.updateProgressDelta(0.10f);
+
+ notifier.subTask(Util.bind("build.analyzingSources")); //$NON-NLS-1$
+ addAffectedSourceFiles();
+ notifier.updateProgressDelta(0.05f);
+
+ this.compileLoop = 0;
+ float increment = 0.40f;
+ while (sourceFiles.size() > 0) { // added to in acceptResult
+ if (++this.compileLoop > MaxCompileLoop) {
+ if (PHPBuilder.DEBUG)
+ System.out.println("ABORTING incremental build... exceeded loop count"); //$NON-NLS-1$
+ return false;
+ }
+ notifier.checkCancel();
+
+ SourceFile[] allSourceFiles = new SourceFile[sourceFiles.size()];
+ sourceFiles.toArray(allSourceFiles);
+ resetCollections();
+
+ workQueue.addAll(allSourceFiles);
+ notifier.setProgressPerCompilationUnit(increment / allSourceFiles.length);
+ increment = increment / 2;
+ compile(allSourceFiles);
+ removeSecondaryTypes();
+ addAffectedSourceFiles();
+ }
+ if (this.hasStructuralChanges && javaBuilder.javaProject.hasCycleMarker())
+ javaBuilder.mustPropagateStructuralChanges();
+ } catch (AbortIncrementalBuildException e) {
+ // abort the incremental build and let the batch builder handle the problem
+ if (PHPBuilder.DEBUG)
+ System.out.println("ABORTING incremental build... cannot find " + e.qualifiedTypeName + //$NON-NLS-1$
+ ". Could have been renamed inside its existing source file."); //$NON-NLS-1$
+ return false;
+ } catch (CoreException e) {
+ throw internalException(e);
+ } finally {
+ cleanUp();
+ }
+ return true;
+}
+
+protected void addAffectedSourceFiles() {
+ if (qualifiedStrings.isEmpty() && simpleStrings.isEmpty()) return;
+
+ // the qualifiedStrings are of the form 'p1/p2' & the simpleStrings are just 'X'
+ char[][][] qualifiedNames = ReferenceCollection.internQualifiedNames(qualifiedStrings);
+ // if a well known qualified name was found then we can skip over these
+ if (qualifiedNames.length < qualifiedStrings.size())
+ qualifiedNames = null;
+ char[][] simpleNames = ReferenceCollection.internSimpleNames(simpleStrings);
+ // if a well known name was found then we can skip over these
+ if (simpleNames.length < simpleStrings.size())
+ simpleNames = null;
+
+ Object[] keyTable = newState.references.keyTable;
+ Object[] valueTable = newState.references.valueTable;
+ next : for (int i = 0, l = valueTable.length; i < l; i++) {
+ ReferenceCollection refs = (ReferenceCollection) valueTable[i];
+ if (refs != null && refs.includes(qualifiedNames, simpleNames)) {
+ String typeLocator = (String) keyTable[i];
+ IFile file = javaBuilder.currentProject.getFile(typeLocator);
+ if (file.exists()) {
+ ClasspathMultiDirectory md = sourceLocations[0];
+ if (sourceLocations.length > 1) {
+ IPath sourceFileFullPath = file.getFullPath();
+ for (int j = 0, m = sourceLocations.length; j < m; j++) {
+ if (sourceLocations[j].sourceFolder.getFullPath().isPrefixOf(sourceFileFullPath)) {
+ md = sourceLocations[j];
+ if (md.exclusionPatterns == null || !Util.isExcluded(file, md.exclusionPatterns))
+ break;
+ }
+ }
+ }
+ SourceFile sourceFile = new SourceFile(file, md, encoding);
+ if (sourceFiles.contains(sourceFile)) continue next;
+ if (compiledAllAtOnce && previousSourceFiles != null && previousSourceFiles.contains(sourceFile))
+ continue next; // can skip previously compiled files since already saw hierarchy related problems
+
+ if (PHPBuilder.DEBUG)
+ System.out.println(" adding affected source file " + typeLocator); //$NON-NLS-1$
+ sourceFiles.add(sourceFile);
+ }
+ }
+ }
+}
+
+protected void addDependentsOf(IPath path, boolean hasStructuralChanges) {
+ if (hasStructuralChanges) {
+ newState.tagAsStructurallyChanged();
+ this.hasStructuralChanges = true;
+ }
+ // the qualifiedStrings are of the form 'p1/p2' & the simpleStrings are just 'X'
+ path = path.setDevice(null);
+ String packageName = path.removeLastSegments(1).toString();
+ if (!qualifiedStrings.contains(packageName))
+ qualifiedStrings.add(packageName);
+ String typeName = path.lastSegment();
+ int memberIndex = typeName.indexOf('$');
+ if (memberIndex > 0)
+ typeName = typeName.substring(0, memberIndex);
+ if (!simpleStrings.contains(typeName)) {
+ if (PHPBuilder.DEBUG)
+ System.out.println(" will look for dependents of " //$NON-NLS-1$
+ + typeName + " in " + packageName); //$NON-NLS-1$
+ simpleStrings.add(typeName);
+ }
+}
+
+protected void cleanUp() {
+ super.cleanUp();
+
+ this.sourceFiles = null;
+ this.previousSourceFiles = null;
+ this.qualifiedStrings = null;
+ this.simpleStrings = null;
+ this.secondaryTypesToRemove = null;
+ this.hasStructuralChanges = false;
+ this.compileLoop = 0;
+}
+
+//protected boolean findAffectedSourceFiles(IResourceDelta delta, ClasspathLocation[] classFoldersAndJars) {
+// for (int i = 0, l = classFoldersAndJars.length; i < l; i++) {
+// ClasspathLocation bLocation = classFoldersAndJars[i];
+// // either a .class file folder or a zip/jar file
+// if (bLocation != null) { // skip unchanged output folder
+// IPath p = bLocation.getProjectRelativePath();
+// if (p != null) {
+// IResourceDelta binaryDelta = delta.findMember(p);
+// if (binaryDelta != null) {
+// if (bLocation instanceof ClasspathJar) {
+// if (JavaBuilder.DEBUG)
+// System.out.println("ABORTING incremental build... found delta to jar/zip file"); //$NON-NLS-1$
+// return false; // do full build since jar file was changed (added/removed were caught as classpath change)
+// }
+// if (binaryDelta.getKind() == IResourceDelta.ADDED || binaryDelta.getKind() == IResourceDelta.REMOVED) {
+// if (JavaBuilder.DEBUG)
+// System.out.println("ABORTING incremental build... found added/removed binary folder"); //$NON-NLS-1$
+// return false; // added/removed binary folder should not make it here (classpath change), but handle anyways
+// }
+// int segmentCount = binaryDelta.getFullPath().segmentCount();
+// IResourceDelta[] children = binaryDelta.getAffectedChildren(); // .class files from class folder
+// for (int j = 0, m = children.length; j < m; j++)
+// findAffectedSourceFiles(children[j], segmentCount);
+// notifier.checkCancel();
+// }
+// }
+// }
+// }
+// return true;
+//}
+
+protected void findAffectedSourceFiles(IResourceDelta binaryDelta, int segmentCount) {
+ // When a package becomes a type or vice versa, expect 2 deltas,
+ // one on the folder & one on the class file
+ IResource resource = binaryDelta.getResource();
+ switch(resource.getType()) {
+ case IResource.FOLDER :
+ switch (binaryDelta.getKind()) {
+ case IResourceDelta.ADDED :
+ case IResourceDelta.REMOVED :
+ IPath packagePath = resource.getFullPath().removeFirstSegments(segmentCount);
+ String packageName = packagePath.toString();
+ if (binaryDelta.getKind() == IResourceDelta.ADDED) {
+ // see if any known source file is from the same package... classpath already includes new package
+ if (!newState.isKnownPackage(packageName)) {
+ if (PHPBuilder.DEBUG)
+ System.out.println("Found added package " + packageName); //$NON-NLS-1$
+ addDependentsOf(packagePath, false);
+ return;
+ }
+ if (PHPBuilder.DEBUG)
+ System.out.println("Skipped dependents of added package " + packageName); //$NON-NLS-1$
+ } else {
+ // see if the package still exists on the classpath
+// if (!nameEnvironment.isPackage(packageName)) {
+// if (JavaBuilder.DEBUG)
+// System.out.println("Found removed package " + packageName); //$NON-NLS-1$
+// addDependentsOf(packagePath, false);
+// return;
+// }
+ if (PHPBuilder.DEBUG)
+ System.out.println("Skipped dependents of removed package " + packageName); //$NON-NLS-1$
+ }
+ // fall thru & traverse the sub-packages and .class files
+ case IResourceDelta.CHANGED :
+ IResourceDelta[] children = binaryDelta.getAffectedChildren();
+ for (int i = 0, l = children.length; i < l; i++)
+ findAffectedSourceFiles(children[i], segmentCount);
+ }
+ return;
+ case IResource.FILE :
+// if (Util.isClassFileName(resource.getName())) {
+// IPath typePath = resource.getFullPath().removeFirstSegments(segmentCount).removeFileExtension();
+// switch (binaryDelta.getKind()) {
+// case IResourceDelta.ADDED :
+// case IResourceDelta.REMOVED :
+// if (JavaBuilder.DEBUG)
+// System.out.println("Found added/removed class file " + typePath); //$NON-NLS-1$
+// addDependentsOf(typePath, false);
+// return;
+// case IResourceDelta.CHANGED :
+// if ((binaryDelta.getFlags() & IResourceDelta.CONTENT) == 0)
+// return; // skip it since it really isn't changed
+// if (JavaBuilder.DEBUG)
+// System.out.println("Found changed class file " + typePath); //$NON-NLS-1$
+// addDependentsOf(typePath, false);
+// }
+// return;
+// }
+ }
+}
+
+protected boolean findSourceFiles(IResourceDelta delta) throws CoreException {
+ for (int i = 0, l = sourceLocations.length; i < l; i++) {
+ ClasspathMultiDirectory md = sourceLocations[i];
+ if (md.sourceFolder.equals(javaBuilder.currentProject)) {
+ // skip nested source & output folders when the project is a source folder
+ int segmentCount = delta.getFullPath().segmentCount();
+ IResourceDelta[] children = delta.getAffectedChildren();
+ for (int j = 0, m = children.length; j < m; j++)
+ if (!isExcludedFromProject(children[j].getFullPath()))
+ findSourceFiles(children[j], md, segmentCount);
+ } else {
+ IResourceDelta sourceDelta = delta.findMember(md.sourceFolder.getProjectRelativePath());
+
+ if (sourceDelta != null) {
+ if (sourceDelta.getKind() == IResourceDelta.REMOVED) {
+ if (PHPBuilder.DEBUG)
+ System.out.println("ABORTING incremental build... found removed source folder"); //$NON-NLS-1$
+ return false; // removed source folder should not make it here, but handle anyways (ADDED is supported)
+ }
+ int segmentCount = sourceDelta.getFullPath().segmentCount();
+ IResourceDelta[] children = sourceDelta.getAffectedChildren();
+ for (int j = 0, m = children.length; j < m; j++)
+ findSourceFiles(children[j], md, segmentCount);
+ }
+ }
+ notifier.checkCancel();
+ }
+ return true;
+}
+
+protected void findSourceFiles(IResourceDelta sourceDelta, ClasspathMultiDirectory md, int segmentCount) throws CoreException {
+ // When a package becomes a type or vice versa, expect 2 deltas,
+ // one on the folder & one on the source file
+ IResource resource = sourceDelta.getResource();
+ if (md.exclusionPatterns != null && Util.isExcluded(resource, md.exclusionPatterns)) return;
+ switch(resource.getType()) {
+ case IResource.FOLDER :
+ switch (sourceDelta.getKind()) {
+ case IResourceDelta.ADDED :
+ IPath addedPackagePath = resource.getFullPath().removeFirstSegments(segmentCount);
+ createFolder(addedPackagePath, md.binaryFolder); // ensure package exists in the output folder
+ // add dependents even when the package thinks it exists to be on the safe side
+ if (PHPBuilder.DEBUG)
+ System.out.println("Found added package " + addedPackagePath); //$NON-NLS-1$
+ addDependentsOf(addedPackagePath, true);
+ // fall thru & collect all the source files
+ case IResourceDelta.CHANGED :
+ IResourceDelta[] children = sourceDelta.getAffectedChildren();
+ for (int i = 0, l = children.length; i < l; i++)
+ findSourceFiles(children[i], md, segmentCount);
+ return;
+ case IResourceDelta.REMOVED :
+ IPath removedPackagePath = resource.getFullPath().removeFirstSegments(segmentCount);
+ if (sourceLocations.length > 1) {
+ for (int i = 0, l = sourceLocations.length; i < l; i++) {
+ if (sourceLocations[i].sourceFolder.getFolder(removedPackagePath).exists()) {
+ // only a package fragment was removed, same as removing multiple source files
+ createFolder(removedPackagePath, md.binaryFolder); // ensure package exists in the output folder
+ IResourceDelta[] removedChildren = sourceDelta.getAffectedChildren();
+ for (int j = 0, m = removedChildren.length; j < m; j++)
+ findSourceFiles(removedChildren[j], md, segmentCount);
+ return;
+ }
+ }
+ }
+ IFolder removedPackageFolder = md.binaryFolder.getFolder(removedPackagePath);
+ if (removedPackageFolder.exists())
+ removedPackageFolder.delete(IResource.FORCE, null);
+ // add dependents even when the package thinks it does not exist to be on the safe side
+ if (PHPBuilder.DEBUG)
+ System.out.println("Found removed package " + removedPackagePath); //$NON-NLS-1$
+ addDependentsOf(removedPackagePath, true);
+ newState.removePackage(sourceDelta);
+ }
+ return;
+ case IResource.FILE :
+ String resourceName = resource.getName();
+ if (Util.isJavaFileName(resourceName)) {
+ IPath typePath = resource.getFullPath().removeFirstSegments(segmentCount).removeFileExtension();
+ String typeLocator = resource.getProjectRelativePath().toString();
+ switch (sourceDelta.getKind()) {
+ case IResourceDelta.ADDED :
+ if (PHPBuilder.DEBUG)
+ System.out.println("Compile this added source file " + typeLocator); //$NON-NLS-1$
+ sourceFiles.add(new SourceFile((IFile) resource, md, encoding));
+ String typeName = typePath.toString();
+ if (!newState.isDuplicateLocator(typeName, typeLocator)) { // adding dependents results in 2 duplicate errors
+ if (PHPBuilder.DEBUG)
+ System.out.println("Found added source file " + typeName); //$NON-NLS-1$
+ addDependentsOf(typePath, true);
+ }
+ return;
+ case IResourceDelta.REMOVED :
+ char[][] definedTypeNames = newState.getDefinedTypeNamesFor(typeLocator);
+ if (definedTypeNames == null) { // defined a single type matching typePath
+ removeClassFile(typePath, md.binaryFolder);
+ if ((sourceDelta.getFlags() & IResourceDelta.MOVED_TO) != 0) {
+ // remove problems and tasks for a compilation unit that is being moved (to another package or renamed)
+ // if the target file is a compilation unit, the new cu will be recompiled
+ // if the target file is a non-java resource, then markers are removed
+ // see bug 2857
+ IResource movedFile = javaBuilder.workspaceRoot.getFile(sourceDelta.getMovedToPath());
+ PHPBuilder.removeProblemsAndTasksFor(movedFile);
+ }
+ } else {
+ if (PHPBuilder.DEBUG)
+ System.out.println("Found removed source file " + typePath.toString()); //$NON-NLS-1$
+ addDependentsOf(typePath, true); // add dependents of the source file since it may be involved in a name collision
+ if (definedTypeNames.length > 0) { // skip it if it failed to successfully define a type
+ IPath packagePath = typePath.removeLastSegments(1);
+ for (int i = 0, l = definedTypeNames.length; i < l; i++)
+ removeClassFile(packagePath.append(new String(definedTypeNames[i])), md.binaryFolder);
+ }
+ }
+ newState.removeLocator(typeLocator);
+ return;
+ case IResourceDelta.CHANGED :
+ if ((sourceDelta.getFlags() & IResourceDelta.CONTENT) == 0)
+ return; // skip it since it really isn't changed
+ if (PHPBuilder.DEBUG)
+ System.out.println("Compile this changed source file " + typeLocator); //$NON-NLS-1$
+ sourceFiles.add(new SourceFile((IFile) resource, md, encoding));
+ }
+ return;
+// } else if (Util.isClassFileName(resourceName)) {
+// return; // skip class files
+ } else if (md.hasIndependentOutputFolder) {
+ if (javaBuilder.filterExtraResource(resource)) return;
+
+ // copy all other resource deltas to the output folder
+ IPath resourcePath = resource.getFullPath().removeFirstSegments(segmentCount);
+ IResource outputFile = md.binaryFolder.getFile(resourcePath);
+ switch (sourceDelta.getKind()) {
+ case IResourceDelta.ADDED :
+ if (outputFile.exists()) {
+ if (PHPBuilder.DEBUG)
+ System.out.println("Deleting existing file " + resourcePath); //$NON-NLS-1$
+ outputFile.delete(IResource.FORCE, null);
+ }
+ if (PHPBuilder.DEBUG)
+ System.out.println("Copying added file " + resourcePath); //$NON-NLS-1$
+ createFolder(resourcePath.removeLastSegments(1), md.binaryFolder); // ensure package exists in the output folder
+ resource.copy(outputFile.getFullPath(), IResource.FORCE, null);
+ outputFile.setDerived(true);
+ return;
+ case IResourceDelta.REMOVED :
+ if (outputFile.exists()) {
+ if (PHPBuilder.DEBUG)
+ System.out.println("Deleting removed file " + resourcePath); //$NON-NLS-1$
+ outputFile.delete(IResource.FORCE, null);
+ }
+ return;
+ case IResourceDelta.CHANGED :
+ if ((sourceDelta.getFlags() & IResourceDelta.CONTENT) == 0)
+ return; // skip it since it really isn't changed
+ if (outputFile.exists()) {
+ if (PHPBuilder.DEBUG)
+ System.out.println("Deleting existing file " + resourcePath); //$NON-NLS-1$
+ outputFile.delete(IResource.FORCE, null);
+ }
+ if (PHPBuilder.DEBUG)
+ System.out.println("Copying changed file " + resourcePath); //$NON-NLS-1$
+ createFolder(resourcePath.removeLastSegments(1), md.binaryFolder); // ensure package exists in the output folder
+ resource.copy(outputFile.getFullPath(), IResource.FORCE, null);
+ outputFile.setDerived(true);
+ }
+ return;
+ }
+ }
+}
+
+protected void finishedWith(String sourceLocator, CompilationResult result, char[] mainTypeName, ArrayList definedTypeNames, ArrayList duplicateTypeNames) throws CoreException {
+ char[][] previousTypeNames = newState.getDefinedTypeNamesFor(sourceLocator);
+ if (previousTypeNames == null)
+ previousTypeNames = new char[][] {mainTypeName};
+ IPath packagePath = null;
+ next : for (int i = 0, l = previousTypeNames.length; i < l; i++) {
+ char[] previous = previousTypeNames[i];
+ for (int j = 0, m = definedTypeNames.size(); j < m; j++)
+ if (CharOperation.equals(previous, (char[]) definedTypeNames.get(j)))
+ continue next;
+
+ SourceFile sourceFile = (SourceFile) result.getCompilationUnit();
+ if (packagePath == null) {
+ int count = sourceFile.sourceLocation.sourceFolder.getFullPath().segmentCount();
+ packagePath = sourceFile.resource.getFullPath().removeFirstSegments(count).removeLastSegments(1);
+ }
+ if (secondaryTypesToRemove == null)
+ this.secondaryTypesToRemove = new SimpleLookupTable();
+ ArrayList types = (ArrayList) secondaryTypesToRemove.get(sourceFile.sourceLocation.binaryFolder);
+ if (types == null)
+ types = new ArrayList(definedTypeNames.size());
+ types.add(packagePath.append(new String(previous)));
+ secondaryTypesToRemove.put(sourceFile.sourceLocation.binaryFolder, types);
+ }
+// super.finishedWith(sourceLocator, result, mainTypeName, definedTypeNames, duplicateTypeNames);
+}
+
+protected void removeClassFile(IPath typePath, IContainer outputFolder) throws CoreException {
+ if (typePath.lastSegment().indexOf('$') == -1) { // is not a nested type
+ newState.removeQualifiedTypeName(typePath.toString());
+ // add dependents even when the type thinks it does not exist to be on the safe side
+ if (PHPBuilder.DEBUG)
+ System.out.println("Found removed type " + typePath); //$NON-NLS-1$
+ addDependentsOf(typePath, true); // when member types are removed, their enclosing type is structurally changed
+ }
+ IFile classFile = outputFolder.getFile(typePath.addFileExtension(PHPBuilder.CLASS_EXTENSION));
+ if (classFile.exists()) {
+ if (PHPBuilder.DEBUG)
+ System.out.println("Deleting class file of removed type " + typePath); //$NON-NLS-1$
+ classFile.delete(IResource.FORCE, null);
+ }
+}
+
+protected void removeSecondaryTypes() throws CoreException {
+ if (secondaryTypesToRemove != null) { // delayed deleting secondary types until the end of the compile loop
+ Object[] keyTable = secondaryTypesToRemove.keyTable;
+ Object[] valueTable = secondaryTypesToRemove.valueTable;
+ for (int i = 0, l = keyTable.length; i < l; i++) {
+ IContainer outputFolder = (IContainer) keyTable[i];
+ if (outputFolder != null) {
+ ArrayList paths = (ArrayList) valueTable[i];
+ for (int j = 0, m = paths.size(); j < m; j++)
+ removeClassFile((IPath) paths.get(j), outputFolder);
+ }
+ }
+ this.secondaryTypesToRemove = null;
+ if (previousSourceFiles != null && previousSourceFiles.size() > 1)
+ this.previousSourceFiles = null; // cannot optimize recompile case when a secondary type is deleted
+ }
+}
+
+protected void resetCollections() {
+ previousSourceFiles = sourceFiles.isEmpty() ? null : (ArrayList) sourceFiles.clone();
+
+ sourceFiles.clear();
+ qualifiedStrings.clear();
+ simpleStrings.clear();
+ workQueue.clear();
+}
+
+protected void updateProblemsFor(SourceFile sourceFile, CompilationResult result) throws CoreException {
+ IMarker[] markers = PHPBuilder.getProblemsFor(sourceFile.resource);
+ IProblem[] problems = result.getProblems();
+ if (problems == null && markers.length == 0) return;
+
+ notifier.updateProblemCounts(markers, problems);
+ PHPBuilder.removeProblemsFor(sourceFile.resource);
+ storeProblemsFor(sourceFile, problems);
+}
+
+protected void updateTasksFor(SourceFile sourceFile, CompilationResult result) throws CoreException {
+ IMarker[] markers = PHPBuilder.getTasksFor(sourceFile.resource);
+ IProblem[] tasks = result.getTasks();
+ if (tasks == null && markers.length == 0) return;
+
+ PHPBuilder.removeTasksFor(sourceFile.resource);
+ storeTasksFor(sourceFile, tasks);
+}
+
+//protected void writeClassFileBytes(byte[] bytes, IFile file, String qualifiedFileName, boolean isSecondaryType) throws CoreException {
+// // Before writing out the class file, compare it to the previous file
+// // If structural changes occured then add dependent source files
+// if (file.exists()) {
+// if (writeClassFileCheck(file, qualifiedFileName, bytes)) {
+// if (JavaBuilder.DEBUG)
+// System.out.println("Writing changed class file " + file.getName());//$NON-NLS-1$
+// file.setContents(new ByteArrayInputStream(bytes), true, false, null);
+// if (!file.isDerived())
+// file.setDerived(true);
+// } else if (JavaBuilder.DEBUG) {
+// System.out.println("Skipped over unchanged class file " + file.getName());//$NON-NLS-1$
+// }
+// } else {
+// if (isSecondaryType)
+// addDependentsOf(new Path(qualifiedFileName), true); // new secondary type
+// if (JavaBuilder.DEBUG)
+// System.out.println("Writing new class file " + file.getName());//$NON-NLS-1$
+// file.create(new ByteArrayInputStream(bytes), IResource.FORCE, null);
+// file.setDerived(true);
+// }
+//}
+
+//protected boolean writeClassFileCheck(IFile file, String fileName, byte[] newBytes) throws CoreException {
+// try {
+// byte[] oldBytes = Util.getResourceContentsAsByteArray(file);
+// if (this.compileLoop > 1) { // only optimize files which were recompiled during the dependent pass, see 33990
+// notEqual : if (newBytes.length == oldBytes.length) {
+// for (int i = newBytes.length; --i >= 0;)
+// if (newBytes[i] != oldBytes[i]) break notEqual;
+// return false; // bytes are identical so skip them
+// }
+// }
+// IPath location = file.getLocation();
+// if (location == null) return false; // unable to determine location of this class file
+// ClassFileReader reader = new ClassFileReader(oldBytes, location.toString().toCharArray());
+// // ignore local types since they're only visible inside a single method
+// if (!(reader.isLocal() || reader.isAnonymous()) && reader.hasStructuralChanges(newBytes)) {
+// if (JavaBuilder.DEBUG)
+// System.out.println("Type has structural changes " + fileName); //$NON-NLS-1$
+// addDependentsOf(new Path(fileName), true);
+// }
+// } catch (ClassFormatException e) {
+// addDependentsOf(new Path(fileName), true);
+// }
+// return true;
+//}
+
+public String toString() {
+ return "incremental image builder for:\n\tnew state: " + newState; //$NON-NLS-1$
+}
+
+
+/* Debug helper
+
+static void dump(IResourceDelta delta) {
+ StringBuffer buffer = new StringBuffer();
+ IPath path = delta.getFullPath();
+ for (int i = path.segmentCount(); --i > 0;)
+ buffer.append(" ");
+ switch (delta.getKind()) {
+ case IResourceDelta.ADDED:
+ buffer.append('+');
+ break;
+ case IResourceDelta.REMOVED:
+ buffer.append('-');
+ break;
+ case IResourceDelta.CHANGED:
+ buffer.append('*');
+ break;
+ case IResourceDelta.NO_CHANGE:
+ buffer.append('=');
+ break;
+ default:
+ buffer.append('?');
+ break;
+ }
+ buffer.append(path);
+ System.out.println(buffer.toString());
+ IResourceDelta[] children = delta.getAffectedChildren();
+ for (int i = 0, l = children.length; i < l; i++)
+ dump(children[i]);
+}
+*/
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/MissingClassFileException.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/MissingClassFileException.java
new file mode 100644
index 0000000..4099502
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/MissingClassFileException.java
@@ -0,0 +1,24 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core.builder;
+
+/**
+ * Exception thrown when the build should be aborted because a referenced
+ * class file cannot be found.
+ */
+public class MissingClassFileException extends RuntimeException {
+
+protected String missingClassFile;
+
+public MissingClassFileException(String missingClassFile) {
+ this.missingClassFile = missingClassFile;
+}
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/MissingSourceFileException.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/MissingSourceFileException.java
new file mode 100644
index 0000000..4c5bf91
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/MissingSourceFileException.java
@@ -0,0 +1,23 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core.builder;
+
+/**
+ * Exception thrown when the build should be aborted because a source file is missing/empty.
+ */
+public class MissingSourceFileException extends RuntimeException {
+
+protected String missingSourceFile;
+
+public MissingSourceFileException(String missingSourceFile) {
+ this.missingSourceFile = missingSourceFile;
+}
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/NameEnvironment.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/NameEnvironment.java
new file mode 100644
index 0000000..9265c4c
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/NameEnvironment.java
@@ -0,0 +1,332 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core.builder;
+
+import java.util.ArrayList;
+
+import net.sourceforge.phpdt.core.IClasspathEntry;
+import net.sourceforge.phpdt.core.IJavaProject;
+import net.sourceforge.phpdt.core.compiler.CharOperation;
+import net.sourceforge.phpdt.internal.compiler.env.INameEnvironment;
+import net.sourceforge.phpdt.internal.compiler.env.NameEnvironmentAnswer;
+import net.sourceforge.phpdt.internal.compiler.problem.AbortCompilation;
+import net.sourceforge.phpdt.internal.core.ClasspathEntry;
+import net.sourceforge.phpdt.internal.core.JavaModel;
+import net.sourceforge.phpdt.internal.core.JavaProject;
+import net.sourceforge.phpdt.internal.core.util.SimpleLookupTable;
+import net.sourceforge.phpeclipse.PHPCore;
+
+import org.eclipse.core.resources.IContainer;
+import org.eclipse.core.resources.IFolder;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IWorkspaceRoot;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.core.runtime.Path;
+
+public class NameEnvironment implements INameEnvironment {
+
+ boolean isIncrementalBuild;
+ ClasspathMultiDirectory[] sourceLocations;
+ //ClasspathLocation[] binaryLocations;
+
+ String[] initialTypeNames; // assumed that each name is of the form "a/b/ClassName"
+ SourceFile[] additionalUnits;
+
+ NameEnvironment(IWorkspaceRoot root, JavaProject javaProject, SimpleLookupTable binaryLocationsPerProject) throws CoreException {
+ this.isIncrementalBuild = false;
+// this.sourceLocations = new ClasspathMultiDirectory[0];
+ computeClasspathLocations(root, javaProject, binaryLocationsPerProject);
+ setNames(null, null);
+ }
+
+ public NameEnvironment(IJavaProject javaProject) {
+ this.isIncrementalBuild = false;
+ try {
+ computeClasspathLocations(javaProject.getProject().getWorkspace().getRoot(), (JavaProject) javaProject, null);
+ } catch(CoreException e) {
+// this.sourceLocations = new ClasspathMultiDirectory[0];
+ // this.binaryLocations = new ClasspathLocation[0];
+ }
+ setNames(null, null);
+ }
+
+ /* Some examples of resolved class path entries.
+ * Remember to search class path in the order that it was defined.
+ *
+ * 1a. typical project with no source folders:
+ * /Test[CPE_SOURCE][K_SOURCE] -> D:/eclipse.test/Test
+ * 1b. project with source folders:
+ * /Test/src1[CPE_SOURCE][K_SOURCE] -> D:/eclipse.test/Test/src1
+ * /Test/src2[CPE_SOURCE][K_SOURCE] -> D:/eclipse.test/Test/src2
+ * NOTE: These can be in any order & separated by prereq projects or libraries
+ * 1c. project external to workspace (only detectable using getLocation()):
+ * /Test/src[CPE_SOURCE][K_SOURCE] -> d:/eclipse.zzz/src
+ * Need to search source folder & output folder
+ *
+ * 2. zip files:
+ * D:/j9/lib/jclMax/classes.zip[CPE_LIBRARY][K_BINARY][sourcePath:d:/j9/lib/jclMax/source/source.zip]
+ * -> D:/j9/lib/jclMax/classes.zip
+ * ALWAYS want to take the library path as is
+ *
+ * 3a. prereq project (regardless of whether it has a source or output folder):
+ * /Test[CPE_PROJECT][K_SOURCE] -> D:/eclipse.test/Test
+ * ALWAYS want to append the output folder & ONLY search for .class files
+ */
+ private void computeClasspathLocations(
+ IWorkspaceRoot root,
+ JavaProject javaProject,
+ SimpleLookupTable binaryLocationsPerProject) throws CoreException {
+
+ /* Update incomplete classpath marker */
+ IClasspathEntry[] classpathEntries = javaProject.getExpandedClasspath(true, true);
+
+ /* Update cycle marker */
+ IMarker cycleMarker = javaProject.getCycleMarker();
+ if (cycleMarker != null) {
+ int severity = PHPCore.ERROR.equals(javaProject.getOption(PHPCore.CORE_CIRCULAR_CLASSPATH, true))
+ ? IMarker.SEVERITY_ERROR
+ : IMarker.SEVERITY_WARNING;
+ if (severity != ((Integer) cycleMarker.getAttribute(IMarker.SEVERITY)).intValue())
+ cycleMarker.setAttribute(IMarker.SEVERITY, severity);
+ }
+
+ ArrayList sLocations = new ArrayList(classpathEntries.length);
+ ArrayList bLocations = new ArrayList(classpathEntries.length);
+ nextEntry : for (int i = 0, l = classpathEntries.length; i < l; i++) {
+ ClasspathEntry entry = (ClasspathEntry) classpathEntries[i];
+ IPath path = entry.getPath();
+ Object target = JavaModel.getTarget(root, path, true);
+ if (target == null) continue nextEntry;
+
+ switch(entry.getEntryKind()) {
+ case IClasspathEntry.CPE_SOURCE :
+ if (!(target instanceof IContainer)) continue nextEntry;
+ IPath outputPath = entry.getOutputLocation() != null
+ ? entry.getOutputLocation()
+ : javaProject.getOutputLocation();
+ IContainer outputFolder;
+ if (outputPath.segmentCount() == 1) {
+ outputFolder = javaProject.getProject();
+ } else {
+ outputFolder = root.getFolder(outputPath);
+ if (!outputFolder.exists())
+ createFolder(outputFolder);
+ }
+ sLocations.add(
+ ClasspathLocation.forSourceFolder((IContainer) target, outputFolder, entry.fullExclusionPatternChars()));
+ continue nextEntry;
+
+ case IClasspathEntry.CPE_PROJECT :
+ if (!(target instanceof IProject)) continue nextEntry;
+ IProject prereqProject = (IProject) target;
+ if (!JavaProject.hasJavaNature(prereqProject)) continue nextEntry; // if project doesn't have java nature or is not accessible
+
+ JavaProject prereqJavaProject = (JavaProject) PHPCore.create(prereqProject);
+ IClasspathEntry[] prereqClasspathEntries = prereqJavaProject.getRawClasspath();
+ ArrayList seen = new ArrayList();
+ nextPrereqEntry: for (int j = 0, m = prereqClasspathEntries.length; j < m; j++) {
+ IClasspathEntry prereqEntry = (IClasspathEntry) prereqClasspathEntries[j];
+ if (prereqEntry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
+ Object prereqTarget = JavaModel.getTarget(root, prereqEntry.getPath(), true);
+ if (!(prereqTarget instanceof IContainer)) continue nextPrereqEntry;
+ IPath prereqOutputPath = prereqEntry.getOutputLocation() != null
+ ? prereqEntry.getOutputLocation()
+ : prereqJavaProject.getOutputLocation();
+ IContainer binaryFolder = prereqOutputPath.segmentCount() == 1
+ ? (IContainer) prereqProject
+ : (IContainer) root.getFolder(prereqOutputPath);
+ if (binaryFolder.exists() && !seen.contains(binaryFolder)) {
+ seen.add(binaryFolder);
+ ClasspathLocation bLocation = ClasspathLocation.forBinaryFolder(binaryFolder, true);
+ bLocations.add(bLocation);
+ if (binaryLocationsPerProject != null) { // normal builder mode
+ ClasspathLocation[] existingLocations = (ClasspathLocation[]) binaryLocationsPerProject.get(prereqProject);
+ if (existingLocations == null) {
+ existingLocations = new ClasspathLocation[] {bLocation};
+ } else {
+ int size = existingLocations.length;
+ System.arraycopy(existingLocations, 0, existingLocations = new ClasspathLocation[size + 1], 0, size);
+ existingLocations[size] = bLocation;
+ }
+ binaryLocationsPerProject.put(prereqProject, existingLocations);
+ }
+ }
+ }
+ }
+ continue nextEntry;
+
+// case IClasspathEntry.CPE_LIBRARY :
+// if (target instanceof IResource) {
+// IResource resource = (IResource) target;
+// ClasspathLocation bLocation = null;
+// if (resource instanceof IFile) {
+// if (!(Util.isArchiveFileName(path.lastSegment())))
+// continue nextEntry;
+// bLocation = ClasspathLocation.forLibrary((IFile) resource);
+// } else if (resource instanceof IContainer) {
+// bLocation = ClasspathLocation.forBinaryFolder((IContainer) target, false); // is library folder not output folder
+// }
+// bLocations.add(bLocation);
+// if (binaryLocationsPerProject != null) { // normal builder mode
+// IProject p = resource.getProject(); // can be the project being built
+// ClasspathLocation[] existingLocations = (ClasspathLocation[]) binaryLocationsPerProject.get(p);
+// if (existingLocations == null) {
+// existingLocations = new ClasspathLocation[] {bLocation};
+// } else {
+// int size = existingLocations.length;
+// System.arraycopy(existingLocations, 0, existingLocations = new ClasspathLocation[size + 1], 0, size);
+// existingLocations[size] = bLocation;
+// }
+// binaryLocationsPerProject.put(p, existingLocations);
+// }
+// } else if (target instanceof File) {
+// if (!(Util.isArchiveFileName(path.lastSegment())))
+// continue nextEntry;
+// bLocations.add(ClasspathLocation.forLibrary(path.toString()));
+// }
+// continue nextEntry;
+ }
+ }
+
+ // now split the classpath locations... place the output folders ahead of the other .class file folders & jars
+ ArrayList outputFolders = new ArrayList(1);
+ this.sourceLocations = new ClasspathMultiDirectory[sLocations.size()];
+ if (!sLocations.isEmpty()) {
+ sLocations.toArray(this.sourceLocations);
+
+ // collect the output folders, skipping duplicates
+ next : for (int i = 0, l = sourceLocations.length; i < l; i++) {
+ ClasspathMultiDirectory md = sourceLocations[i];
+ IPath outputPath = md.binaryFolder.getFullPath();
+ for (int j = 0; j < i; j++) { // compare against previously walked source folders
+ if (outputPath.equals(sourceLocations[j].binaryFolder.getFullPath())) {
+ md.hasIndependentOutputFolder = sourceLocations[j].hasIndependentOutputFolder;
+ continue next;
+ }
+ }
+ outputFolders.add(md);
+
+ // also tag each source folder whose output folder is an independent folder & is not also a source folder
+ for (int j = 0, m = sourceLocations.length; j < m; j++)
+ if (outputPath.equals(sourceLocations[j].sourceFolder.getFullPath()))
+ continue next;
+ md.hasIndependentOutputFolder = true;
+ }
+ }
+
+// combine the output folders with the binary folders & jars... place the output folders before other .class file folders & jars
+// this.binaryLocations = new ClasspathLocation[outputFolders.size() + bLocations.size()];
+// int index = 0;
+// for (int i = 0, l = outputFolders.size(); i < l; i++)
+// this.binaryLocations[index++] = (ClasspathLocation) outputFolders.get(i);
+// for (int i = 0, l = bLocations.size(); i < l; i++)
+// this.binaryLocations[index++] = (ClasspathLocation) bLocations.get(i);
+ }
+
+ public void cleanup() {
+ this.initialTypeNames = null;
+ this.additionalUnits = null;
+ for (int i = 0, l = sourceLocations.length; i < l; i++)
+ sourceLocations[i].cleanup();
+ // for (int i = 0, l = binaryLocations.length; i < l; i++)
+ // binaryLocations[i].cleanup();
+ }
+
+ private void createFolder(IContainer folder) throws CoreException {
+ if (!folder.exists()) {
+ createFolder(folder.getParent());
+ ((IFolder) folder).create(true, true, null);
+ }
+ }
+
+ private NameEnvironmentAnswer findClass(String qualifiedTypeName, char[] typeName) {
+ if (initialTypeNames != null) {
+ for (int i = 0, l = initialTypeNames.length; i < l; i++) {
+ if (qualifiedTypeName.equals(initialTypeNames[i])) {
+ if (isIncrementalBuild)
+ // catch the case that a type inside a source file has been renamed but other class files are looking for it
+ throw new AbortCompilation(true, new AbortIncrementalBuildException(qualifiedTypeName));
+ return null; // looking for a file which we know was provided at the beginning of the compilation
+ }
+ }
+ }
+
+ if (additionalUnits != null && sourceLocations.length > 0) {
+ // if an additional source file is waiting to be compiled, answer it BUT not if this is a secondary type search
+ // if we answer X.java & it no longer defines Y then the binary type looking for Y will think the class path is wrong
+ // let the recompile loop fix up dependents when the secondary type Y has been deleted from X.java
+ IPath qSourceFilePath = new Path(qualifiedTypeName + ".java"); //$NON-NLS-1$
+ int qSegmentCount = qSourceFilePath.segmentCount();
+ next : for (int i = 0, l = additionalUnits.length; i < l; i++) {
+ SourceFile additionalUnit = additionalUnits[i];
+ IPath fullPath = additionalUnit.resource.getFullPath();
+ int prefixCount = additionalUnit.sourceLocation.sourceFolder.getFullPath().segmentCount();
+ if (qSegmentCount == fullPath.segmentCount() - prefixCount) {
+ for (int j = 0; j < qSegmentCount; j++)
+ if (!qSourceFilePath.segment(j).equals(fullPath.segment(j + prefixCount)))
+ continue next;
+ return new NameEnvironmentAnswer(additionalUnit);
+ }
+ }
+ }
+
+ // String qBinaryFileName = qualifiedTypeName + ".class"; //$NON-NLS-1$
+ // String binaryFileName = qBinaryFileName;
+ // String qPackageName = ""; //$NON-NLS-1$
+ // if (qualifiedTypeName.length() > typeName.length) {
+ // int typeNameStart = qBinaryFileName.length() - typeName.length - 6; // size of ".class"
+ // qPackageName = qBinaryFileName.substring(0, typeNameStart - 1);
+ // binaryFileName = qBinaryFileName.substring(typeNameStart);
+ // }
+ //
+ // // NOTE: the output folders are added at the beginning of the binaryLocations
+ // for (int i = 0, l = binaryLocations.length; i < l; i++) {
+ // NameEnvironmentAnswer answer = binaryLocations[i].findClass(binaryFileName, qPackageName, qBinaryFileName);
+ // if (answer != null) return answer;
+ // }
+ return null;
+ }
+
+ public NameEnvironmentAnswer findType(char[][] compoundName) {
+ if (compoundName != null)
+ return findClass(new String(CharOperation.concatWith(compoundName, '/')), compoundName[compoundName.length - 1]);
+ return null;
+ }
+
+ public NameEnvironmentAnswer findType(char[] typeName, char[][] packageName) {
+ if (typeName != null)
+ return findClass(new String(CharOperation.concatWith(packageName, typeName, '/')), typeName);
+ return null;
+ }
+
+ public boolean isPackage(char[][] compoundName, char[] packageName) {
+ return isPackage(new String(CharOperation.concatWith(compoundName, packageName, '/')));
+ }
+
+ public boolean isPackage(String qualifiedPackageName) {
+ // NOTE: the output folders are added at the beginning of the binaryLocations
+ // for (int i = 0, l = binaryLocations.length; i < l; i++)
+ // if (binaryLocations[i].isPackage(qualifiedPackageName))
+ // return true;
+ return false;
+ }
+
+ void setNames(String[] initialTypeNames, SourceFile[] additionalUnits) {
+ this.initialTypeNames = initialTypeNames;
+ this.additionalUnits = additionalUnits;
+ for (int i = 0, l = sourceLocations.length; i < l; i++)
+ sourceLocations[i].reset();
+ // for (int i = 0, l = binaryLocations.length; i < l; i++)
+ // binaryLocations[i].reset();
+ }
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/PHPBuilder.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/PHPBuilder.java
new file mode 100644
index 0000000..ee59f34
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/PHPBuilder.java
@@ -0,0 +1,598 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core.builder;
+
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Map;
+
+import net.sourceforge.phpdt.core.IClasspathEntry;
+import net.sourceforge.phpdt.core.IJavaModelMarker;
+import net.sourceforge.phpdt.core.JavaModelException;
+import net.sourceforge.phpdt.core.compiler.CharOperation;
+import net.sourceforge.phpdt.internal.core.JavaModel;
+import net.sourceforge.phpdt.internal.core.JavaModelManager;
+import net.sourceforge.phpdt.internal.core.JavaProject;
+import net.sourceforge.phpdt.internal.core.Util;
+import net.sourceforge.phpdt.internal.core.util.SimpleLookupTable;
+import net.sourceforge.phpeclipse.PHPCore;
+
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.IResourceChangeEvent;
+import org.eclipse.core.resources.IResourceDelta;
+import org.eclipse.core.resources.IWorkspaceRoot;
+import org.eclipse.core.resources.IncrementalProjectBuilder;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.core.runtime.IProgressMonitor;
+
+public class PHPBuilder extends IncrementalProjectBuilder {
+
+ IProject currentProject;
+ JavaProject javaProject;
+ IWorkspaceRoot workspaceRoot;
+ NameEnvironment nameEnvironment;
+ SimpleLookupTable binaryLocationsPerProject; // maps a project to its binary resources (output folders, class folders, zip/jar files)
+ State lastState;
+ BuildNotifier notifier;
+ char[][] extraResourceFileFilters;
+ String[] extraResourceFolderFilters;
+
+ public static final String CLASS_EXTENSION = "class"; //$NON-NLS-1$
+
+ public static boolean DEBUG = true;
+
+ /**
+ * A list of project names that have been built.
+ * This list is used to reset the JavaModel.existingExternalFiles cache when a build cycle begins
+ * so that deleted external jars are discovered.
+ */
+ static ArrayList builtProjects = null;
+
+ public static IMarker[] getProblemsFor(IResource resource) {
+ try {
+ if (resource != null && resource.exists())
+ return resource.findMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, false, IResource.DEPTH_INFINITE);
+ } catch (CoreException e) {
+ } // assume there are no problems
+ return new IMarker[0];
+ }
+
+ public static IMarker[] getTasksFor(IResource resource) {
+ try {
+ if (resource != null && resource.exists())
+ return resource.findMarkers(IJavaModelMarker.TASK_MARKER, false, IResource.DEPTH_INFINITE);
+ } catch (CoreException e) {
+ } // assume there are no tasks
+ return new IMarker[0];
+ }
+
+ public static void finishedBuilding(IResourceChangeEvent event) {
+ BuildNotifier.resetProblemCounters();
+ }
+
+ public static void removeProblemsFor(IResource resource) {
+ try {
+ if (resource != null && resource.exists())
+ resource.deleteMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, false, IResource.DEPTH_INFINITE);
+ } catch (CoreException e) {
+ } // assume there were no problems
+ }
+
+ public static void removeTasksFor(IResource resource) {
+ try {
+ if (resource != null && resource.exists())
+ resource.deleteMarkers(IJavaModelMarker.TASK_MARKER, false, IResource.DEPTH_INFINITE);
+ } catch (CoreException e) {
+ } // assume there were no problems
+ }
+
+ public static void removeProblemsAndTasksFor(IResource resource) {
+ try {
+ if (resource != null && resource.exists()) {
+ resource.deleteMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, false, IResource.DEPTH_INFINITE);
+ resource.deleteMarkers(IJavaModelMarker.TASK_MARKER, false, IResource.DEPTH_INFINITE);
+ }
+ } catch (CoreException e) {
+ } // assume there were no problems
+ }
+
+ public static State readState(IProject project, DataInputStream in) throws IOException {
+ return State.read(project, in);
+ }
+
+ public static void writeState(Object state, DataOutputStream out) throws IOException {
+ ((State) state).write(out);
+ }
+
+ public PHPBuilder() {
+ }
+
+ protected IProject[] build(int kind, Map ignored, IProgressMonitor monitor) throws CoreException {
+ this.currentProject = getProject();
+ if (currentProject == null || !currentProject.isAccessible())
+ return new IProject[0];
+
+ if (DEBUG)
+ System.out.println("\nStarting build of " + currentProject.getName() //$NON-NLS-1$
+ +" @ " + new Date(System.currentTimeMillis())); //$NON-NLS-1$
+ this.notifier = new BuildNotifier(monitor, currentProject);
+ notifier.begin();
+ boolean ok = false;
+ try {
+ notifier.checkCancel();
+ initializeBuilder();
+
+ if (isWorthBuilding()) {
+ if (kind == FULL_BUILD) {
+ buildAll();
+ } else {
+ if ((this.lastState = getLastState(currentProject)) == null) {
+ if (DEBUG)
+ System.out.println("Performing full build since last saved state was not found"); //$NON-NLS-1$
+ buildAll();
+ } else if (hasClasspathChanged()) {
+ // if the output location changes, do not delete the binary files from old location
+ // the user may be trying something
+ buildAll();
+ } else if (nameEnvironment.sourceLocations.length > 0) {
+ // if there is no source to compile & no classpath changes then we are done
+ SimpleLookupTable deltas = findDeltas();
+ if (deltas == null)
+ buildAll();
+ else if (deltas.elementSize > 0)
+ buildDeltas(deltas);
+ else if (DEBUG)
+ System.out.println("Nothing to build since deltas were empty"); //$NON-NLS-1$
+ } else {
+ if (hasStructuralDelta()) { // double check that a jar file didn't get replaced in a binary project
+ buildAll();
+ } else {
+ if (DEBUG)
+ System.out.println("Nothing to build since there are no source folders and no deltas"); //$NON-NLS-1$
+ lastState.tagAsNoopBuild();
+ }
+ }
+ }
+ ok = true;
+ }
+ } catch (CoreException e) {
+ Util.log(e, "JavaBuilder handling CoreException"); //$NON-NLS-1$
+ IMarker marker = currentProject.createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER);
+ marker.setAttribute(IMarker.MESSAGE, Util.bind("build.inconsistentProject", e.getLocalizedMessage())); //$NON-NLS-1$
+ marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR);
+ } catch (ImageBuilderInternalException e) {
+ Util.log(e.getThrowable(), "JavaBuilder handling ImageBuilderInternalException"); //$NON-NLS-1$
+ IMarker marker = currentProject.createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER);
+ marker.setAttribute(IMarker.MESSAGE, Util.bind("build.inconsistentProject", e.coreException.getLocalizedMessage())); //$NON-NLS-1$
+ marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR);
+ } catch (MissingClassFileException e) {
+ // do not log this exception since its thrown to handle aborted compiles because of missing class files
+ if (DEBUG)
+ System.out.println(Util.bind("build.incompleteClassPath", e.missingClassFile)); //$NON-NLS-1$
+ IMarker marker = currentProject.createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER);
+ marker.setAttribute(IMarker.MESSAGE, Util.bind("build.incompleteClassPath", e.missingClassFile)); //$NON-NLS-1$
+ marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR);
+ } catch (MissingSourceFileException e) {
+ // do not log this exception since its thrown to handle aborted compiles because of missing source files
+ if (DEBUG)
+ System.out.println(Util.bind("build.missingSourceFile", e.missingSourceFile)); //$NON-NLS-1$
+ removeProblemsAndTasksFor(currentProject); // make this the only problem for this project
+ IMarker marker = currentProject.createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER);
+ marker.setAttribute(IMarker.MESSAGE, Util.bind("build.missingSourceFile", e.missingSourceFile)); //$NON-NLS-1$
+ marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR);
+ } finally {
+ if (!ok)
+ // If the build failed, clear the previously built state, forcing a full build next time.
+ clearLastState();
+ notifier.done();
+ cleanup();
+ }
+ IProject[] requiredProjects = getRequiredProjects(true);
+ if (DEBUG)
+ System.out.println("Finished build of " + currentProject.getName() //$NON-NLS-1$
+ +" @ " + new Date(System.currentTimeMillis())); //$NON-NLS-1$
+ return requiredProjects;
+ }
+
+ private void buildAll() {
+ notifier.checkCancel();
+ notifier.subTask(Util.bind("build.preparingBuild")); //$NON-NLS-1$
+ if (DEBUG && lastState != null)
+ System.out.println("Clearing last state : " + lastState); //$NON-NLS-1$
+ clearLastState();
+ BatchImageBuilder imageBuilder = new BatchImageBuilder(this);
+ imageBuilder.build();
+ recordNewState(imageBuilder.newState);
+ }
+
+ private void buildDeltas(SimpleLookupTable deltas) {
+ notifier.checkCancel();
+ notifier.subTask(Util.bind("build.preparingBuild")); //$NON-NLS-1$
+ if (DEBUG && lastState != null)
+ System.out.println("Clearing last state : " + lastState); //$NON-NLS-1$
+ clearLastState(); // clear the previously built state so if the build fails, a full build will occur next time
+ IncrementalImageBuilder imageBuilder = new IncrementalImageBuilder(this);
+ if (imageBuilder.build(deltas))
+ recordNewState(imageBuilder.newState);
+ else
+ buildAll();
+ }
+
+ private void cleanup() {
+ this.nameEnvironment = null;
+ this.binaryLocationsPerProject = null;
+ this.lastState = null;
+ this.notifier = null;
+ this.extraResourceFileFilters = null;
+ this.extraResourceFolderFilters = null;
+ }
+
+ private void clearLastState() {
+ JavaModelManager.getJavaModelManager().setLastBuiltState(currentProject, null);
+ }
+
+ boolean filterExtraResource(IResource resource) {
+ if (extraResourceFileFilters != null) {
+ char[] name = resource.getName().toCharArray();
+ for (int i = 0, l = extraResourceFileFilters.length; i < l; i++)
+ if (CharOperation.match(extraResourceFileFilters[i], name, true))
+ return true;
+ }
+ if (extraResourceFolderFilters != null) {
+ IPath path = resource.getProjectRelativePath();
+ String pathName = path.toString();
+ int count = path.segmentCount();
+ if (resource.getType() == IResource.FILE)
+ count--;
+ for (int i = 0, l = extraResourceFolderFilters.length; i < l; i++)
+ if (pathName.indexOf(extraResourceFolderFilters[i]) != -1)
+ for (int j = 0; j < count; j++)
+ if (extraResourceFolderFilters[i].equals(path.segment(j)))
+ return true;
+ }
+ return false;
+ }
+
+ private SimpleLookupTable findDeltas() {
+ notifier.subTask(Util.bind("build.readingDelta", currentProject.getName())); //$NON-NLS-1$
+ IResourceDelta delta = getDelta(currentProject);
+ SimpleLookupTable deltas = new SimpleLookupTable(3);
+ if (delta != null) {
+ if (delta.getKind() != IResourceDelta.NO_CHANGE) {
+ if (DEBUG)
+ System.out.println("Found source delta for: " + currentProject.getName()); //$NON-NLS-1$
+ deltas.put(currentProject, delta);
+ }
+ } else {
+ if (DEBUG)
+ System.out.println("Missing delta for: " + currentProject.getName()); //$NON-NLS-1$
+ notifier.subTask(""); //$NON-NLS-1$
+ return null;
+ }
+
+ Object[] keyTable = binaryLocationsPerProject.keyTable;
+ Object[] valueTable = binaryLocationsPerProject.valueTable;
+ nextProject : for (int i = 0, l = keyTable.length; i < l; i++) {
+ IProject p = (IProject) keyTable[i];
+ if (p != null && p != currentProject) {
+ State s = getLastState(p);
+ if (!lastState.wasStructurallyChanged(p, s)) { // see if we can skip its delta
+ if (s.wasNoopBuild())
+ continue nextProject; // project has no source folders and can be skipped
+ // ClasspathLocation[] classFoldersAndJars = (ClasspathLocation[]) valueTable[i];
+ boolean canSkip = true;
+ // for (int j = 0, m = classFoldersAndJars.length; j < m; j++) {
+ // if (classFoldersAndJars[j].isOutputFolder())
+ // classFoldersAndJars[j] = null; // can ignore output folder since project was not structurally changed
+ // else
+ // canSkip = false;
+ // }
+ if (canSkip)
+ continue nextProject; // project has no structural changes in its output folders
+ }
+
+ notifier.subTask(Util.bind("build.readingDelta", p.getName())); //$NON-NLS-1$
+ delta = getDelta(p);
+ if (delta != null) {
+ if (delta.getKind() != IResourceDelta.NO_CHANGE) {
+ if (DEBUG)
+ System.out.println("Found binary delta for: " + p.getName()); //$NON-NLS-1$
+ deltas.put(p, delta);
+ }
+ } else {
+ if (DEBUG)
+ System.out.println("Missing delta for: " + p.getName()); //$NON-NLS-1$
+ notifier.subTask(""); //$NON-NLS-1$
+ return null;
+ }
+ }
+ }
+ notifier.subTask(""); //$NON-NLS-1$
+ return deltas;
+ }
+
+ private State getLastState(IProject project) {
+ return (State) JavaModelManager.getJavaModelManager().getLastBuiltState(project, notifier.monitor);
+ }
+
+ /* Return the list of projects for which it requires a resource delta. This builder's project
+ * is implicitly included and need not be specified. Builders must re-specify the list
+ * of interesting projects every time they are run as this is not carried forward
+ * beyond the next build. Missing projects should be specified but will be ignored until
+ * they are added to the workspace.
+ */
+ private IProject[] getRequiredProjects(boolean includeBinaryPrerequisites) {
+ if (javaProject == null || workspaceRoot == null)
+ return new IProject[0];
+
+ ArrayList projects = new ArrayList();
+ try {
+ IClasspathEntry[] entries = javaProject.getExpandedClasspath(true);
+ for (int i = 0, l = entries.length; i < l; i++) {
+ IClasspathEntry entry = entries[i];
+ IPath path = entry.getPath();
+ IProject p = null;
+ switch (entry.getEntryKind()) {
+ case IClasspathEntry.CPE_PROJECT :
+ p = workspaceRoot.getProject(path.lastSegment()); // missing projects are considered too
+ break;
+ case IClasspathEntry.CPE_LIBRARY :
+ if (includeBinaryPrerequisites && path.segmentCount() > 1) {
+ // some binary resources on the class path can come from projects that are not included in the project references
+ IResource resource = workspaceRoot.findMember(path.segment(0));
+ if (resource instanceof IProject)
+ p = (IProject) resource;
+ }
+ }
+ if (p != null && !projects.contains(p))
+ projects.add(p);
+ }
+ } catch (JavaModelException e) {
+ return new IProject[0];
+ }
+ IProject[] result = new IProject[projects.size()];
+ projects.toArray(result);
+ return result;
+ }
+
+ private boolean hasClasspathChanged() {
+ ClasspathMultiDirectory[] newSourceLocations = nameEnvironment.sourceLocations;
+ ClasspathMultiDirectory[] oldSourceLocations = lastState.sourceLocations;
+ int newLength = newSourceLocations.length;
+ int oldLength = oldSourceLocations.length;
+ int n, o;
+ for (n = o = 0; n < newLength && o < oldLength; n++, o++) {
+ if (newSourceLocations[n].equals(oldSourceLocations[o]))
+ continue; // checks source & output folders
+ try {
+ if (newSourceLocations[n].sourceFolder.members().length == 0) { // added new empty source folder
+ o--;
+ continue;
+ }
+ } catch (CoreException ignore) {
+ }
+ if (DEBUG)
+ System.out.println(newSourceLocations[n] + " != " + oldSourceLocations[o]); //$NON-NLS-1$
+ return true;
+ }
+ while (n < newLength) {
+ try {
+ if (newSourceLocations[n].sourceFolder.members().length == 0) { // added new empty source folder
+ n++;
+ continue;
+ }
+ } catch (CoreException ignore) {
+ }
+ if (DEBUG)
+ System.out.println("Added non-empty source folder"); //$NON-NLS-1$
+ return true;
+ }
+ if (o < oldLength) {
+ if (DEBUG)
+ System.out.println("Removed source folder"); //$NON-NLS-1$
+ return true;
+ }
+
+ // ClasspathLocation[] newBinaryLocations = nameEnvironment.binaryLocations;
+ // ClasspathLocation[] oldBinaryLocations = lastState.binaryLocations;
+ // newLength = newBinaryLocations.length;
+ // oldLength = oldBinaryLocations.length;
+ // for (n = o = 0; n < newLength && o < oldLength; n++, o++) {
+ // if (newBinaryLocations[n].equals(oldBinaryLocations[o])) continue;
+ // if (DEBUG)
+ // System.out.println(newBinaryLocations[n] + " != " + oldBinaryLocations[o]); //$NON-NLS-1$
+ // return true;
+ // }
+ // if (n < newLength || o < oldLength) {
+ // if (DEBUG)
+ // System.out.println("Number of binary folders/jar files has changed"); //$NON-NLS-1$
+ // return true;
+ // }
+ return false;
+ }
+
+ private boolean hasStructuralDelta() {
+ // handle case when currentProject has only .class file folders and/or jar files... no source/output folders
+ IResourceDelta delta = getDelta(currentProject);
+ if (delta != null && delta.getKind() != IResourceDelta.NO_CHANGE) {
+ // ClasspathLocation[] classFoldersAndJars = (ClasspathLocation[]) binaryLocationsPerProject.get(currentProject);
+ // if (classFoldersAndJars != null) {
+ // for (int i = 0, l = classFoldersAndJars.length; i < l; i++) {
+ // ClasspathLocation classFolderOrJar = classFoldersAndJars[i]; // either a .class file folder or a zip/jar file
+ // if (classFolderOrJar != null) {
+ // IPath p = classFolderOrJar.getProjectRelativePath();
+ // if (p != null) {
+ // IResourceDelta binaryDelta = delta.findMember(p);
+ // if (binaryDelta != null && binaryDelta.getKind() != IResourceDelta.NO_CHANGE)
+ // return true;
+ // }
+ // }
+ // }
+ // }
+ }
+ return false;
+ }
+
+ private void initializeBuilder() throws CoreException {
+ this.javaProject = (JavaProject) PHPCore.create(currentProject);
+ this.workspaceRoot = currentProject.getWorkspace().getRoot();
+
+ // Flush the existing external files cache if this is the beginning of a build cycle
+ String projectName = currentProject.getName();
+ if (builtProjects == null || builtProjects.contains(projectName)) {
+ JavaModel.flushExternalFileCache();
+ builtProjects = new ArrayList();
+ }
+ builtProjects.add(projectName);
+
+ this.binaryLocationsPerProject = new SimpleLookupTable(3);
+ this.nameEnvironment = new NameEnvironment(workspaceRoot, javaProject, binaryLocationsPerProject);
+
+ String filterSequence = javaProject.getOption(PHPCore.CORE_JAVA_BUILD_RESOURCE_COPY_FILTER, true);
+ char[][] filters = filterSequence != null && filterSequence.length() > 0 ? CharOperation.splitAndTrimOn(',', filterSequence.toCharArray()) : null;
+ if (filters == null) {
+ this.extraResourceFileFilters = null;
+ this.extraResourceFolderFilters = null;
+ } else {
+ int fileCount = 0, folderCount = 0;
+ for (int i = 0, l = filters.length; i < l; i++) {
+ char[] f = filters[i];
+ if (f.length == 0)
+ continue;
+ if (f[f.length - 1] == '/')
+ folderCount++;
+ else
+ fileCount++;
+ }
+ this.extraResourceFileFilters = new char[fileCount][];
+ this.extraResourceFolderFilters = new String[folderCount];
+ for (int i = 0, l = filters.length; i < l; i++) {
+ char[] f = filters[i];
+ if (f.length == 0)
+ continue;
+ if (f[f.length - 1] == '/')
+ extraResourceFolderFilters[--folderCount] = new String(CharOperation.subarray(f, 0, f.length - 1));
+ else
+ extraResourceFileFilters[--fileCount] = f;
+ }
+ }
+ }
+
+ private boolean isClasspathBroken(IClasspathEntry[] classpath, IProject p) throws CoreException {
+ if (classpath == JavaProject.INVALID_CLASSPATH) // the .classpath file could not be read
+ return true;
+
+ IMarker[] markers = p.findMarkers(IJavaModelMarker.BUILDPATH_PROBLEM_MARKER, false, IResource.DEPTH_ZERO);
+ for (int i = 0, l = markers.length; i < l; i++)
+ if (((Integer) markers[i].getAttribute(IMarker.SEVERITY)).intValue() == IMarker.SEVERITY_ERROR)
+ return true;
+ return false;
+ }
+
+ private boolean isWorthBuilding() throws CoreException {
+ boolean abortBuilds = PHPCore.ABORT.equals(javaProject.getOption(PHPCore.CORE_JAVA_BUILD_INVALID_CLASSPATH, true));
+ if (!abortBuilds)
+ return true;
+
+ // Abort build only if there are classpath errors
+// if (isClasspathBroken(javaProject.getRawClasspath(), currentProject)) {
+// if (DEBUG)
+// System.out.println("Aborted build because project has classpath errors (incomplete or involved in cycle)"); //$NON-NLS-1$
+//
+// JavaModelManager.getJavaModelManager().deltaProcessor.addForRefresh(javaProject);
+//
+// removeProblemsAndTasksFor(currentProject); // remove all compilation problems
+//
+// IMarker marker = currentProject.createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER);
+// marker.setAttribute(IMarker.MESSAGE, Util.bind("build.abortDueToClasspathProblems")); //$NON-NLS-1$
+// marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR);
+// return false;
+// }
+
+ // make sure all prereq projects have valid build states... only when aborting builds since projects in cycles do not have build states
+ // except for projects involved in a 'warning' cycle (see below)
+ IProject[] requiredProjects = getRequiredProjects(false);
+ next : for (int i = 0, l = requiredProjects.length; i < l; i++) {
+ IProject p = requiredProjects[i];
+ if (getLastState(p) == null) {
+ // The prereq project has no build state: if this prereq project has a 'warning' cycle marker then allow build (see bug id 23357)
+ JavaProject prereq = (JavaProject) PHPCore.create(p);
+ if (prereq.hasCycleMarker() && PHPCore.WARNING.equals(javaProject.getOption(PHPCore.CORE_CIRCULAR_CLASSPATH, true)))
+ continue;
+ if (DEBUG)
+ System.out.println("Aborted build because prereq project " + p.getName() //$NON-NLS-1$
+ +" was not built"); //$NON-NLS-1$
+
+ removeProblemsAndTasksFor(currentProject); // make this the only problem for this project
+ IMarker marker = currentProject.createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER);
+ marker.setAttribute(IMarker.MESSAGE, isClasspathBroken(prereq.getRawClasspath(), p) ? Util.bind("build.prereqProjectHasClasspathProblems", p.getName()) //$NON-NLS-1$
+ : Util.bind("build.prereqProjectMustBeRebuilt", p.getName())); //$NON-NLS-1$
+ marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR);
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /*
+ * Instruct the build manager that this project is involved in a cycle and
+ * needs to propagate structural changes to the other projects in the cycle.
+ */
+ void mustPropagateStructuralChanges() {
+ HashSet cycleParticipants = new HashSet(3);
+ javaProject.updateCycleParticipants(null, new ArrayList(), cycleParticipants, workspaceRoot, new HashSet(3));
+ IPath currentPath = javaProject.getPath();
+ Iterator i = cycleParticipants.iterator();
+ while (i.hasNext()) {
+ IPath participantPath = (IPath) i.next();
+ if (participantPath != currentPath) {
+ IProject project = this.workspaceRoot.getProject(participantPath.segment(0));
+ if (hasBeenBuilt(project)) {
+ if (DEBUG)
+ System.out.println("Requesting another build iteration since cycle participant " + project.getName() //$NON-NLS-1$
+ +" has not yet seen some structural changes"); //$NON-NLS-1$
+ needRebuild();
+ return;
+ }
+ }
+ }
+ }
+
+ private void recordNewState(State state) {
+ Object[] keyTable = binaryLocationsPerProject.keyTable;
+ for (int i = 0, l = keyTable.length; i < l; i++) {
+ IProject prereqProject = (IProject) keyTable[i];
+ if (prereqProject != null && prereqProject != currentProject)
+ state.recordStructuralDependency(prereqProject, getLastState(prereqProject));
+ }
+
+ if (DEBUG)
+ System.out.println("Recording new state : " + state); //$NON-NLS-1$
+ // state.dump();
+ JavaModelManager.getJavaModelManager().setLastBuiltState(currentProject, state);
+ }
+
+ /**
+ * String representation for debugging purposes
+ */
+ public String toString() {
+ return currentProject == null ? "JavaBuilder for unknown project" //$NON-NLS-1$
+ : "JavaBuilder for " + currentProject.getName(); //$NON-NLS-1$
+ }
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/ProblemFactory.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/ProblemFactory.java
new file mode 100644
index 0000000..e3124ae
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/ProblemFactory.java
@@ -0,0 +1,32 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core.builder;
+
+import java.util.Locale;
+
+import net.sourceforge.phpdt.internal.compiler.problem.DefaultProblemFactory;
+import net.sourceforge.phpdt.internal.core.util.SimpleLookupTable;
+
+public class ProblemFactory extends DefaultProblemFactory {
+
+static SimpleLookupTable factories = new SimpleLookupTable(5);
+
+private ProblemFactory(Locale locale) {
+ super(locale);
+}
+
+public static ProblemFactory getProblemFactory(Locale locale) {
+ ProblemFactory factory = (ProblemFactory) factories.get(locale);
+ if (factory == null)
+ factories.put(locale, factory = new ProblemFactory(locale));
+ return factory;
+}
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/ReferenceCollection.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/ReferenceCollection.java
new file mode 100644
index 0000000..0691a69
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/ReferenceCollection.java
@@ -0,0 +1,226 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core.builder;
+
+import java.util.ArrayList;
+
+import net.sourceforge.phpdt.core.compiler.CharOperation;
+import net.sourceforge.phpdt.internal.compiler.lookup.TypeConstants;
+
+public class ReferenceCollection {
+
+char[][][] qualifiedNameReferences; // contains no simple names as in just 'a' which is kept in simpleNameReferences instead
+char[][] simpleNameReferences;
+
+protected ReferenceCollection(char[][][] qualifiedNameReferences, char[][] simpleNameReferences) {
+ this.qualifiedNameReferences = internQualifiedNames(qualifiedNameReferences);
+ this.simpleNameReferences = internSimpleNames(simpleNameReferences, true);
+}
+
+boolean includes(char[] simpleName) {
+ for (int i = 0, l = simpleNameReferences.length; i < l; i++)
+ if (simpleName == simpleNameReferences[i]) return true;
+ return false;
+}
+
+boolean includes(char[][] qualifiedName) {
+ for (int i = 0, l = qualifiedNameReferences.length; i < l; i++)
+ if (qualifiedName == qualifiedNameReferences[i]) return true;
+ return false;
+}
+
+boolean includes(char[][][] qualifiedNames, char[][] simpleNames) {
+ // if either collection of names is null, it means it contained a well known name so we know it already has a match
+ if (simpleNames == null || qualifiedNames == null) {
+ if (simpleNames == null && qualifiedNames == null) {
+ if (PHPBuilder.DEBUG)
+ System.out.println("Found well known match"); //$NON-NLS-1$
+ return true;
+ } else if (qualifiedNames == null) {
+ for (int i = 0, l = simpleNames.length; i < l; i++) {
+ if (includes(simpleNames[i])) {
+ if (PHPBuilder.DEBUG)
+ System.out.println("Found match in well known package to " + new String(simpleNames[i])); //$NON-NLS-1$
+ return true;
+ }
+ }
+ } else {
+ for (int i = 0, l = qualifiedNames.length; i < l; i++) {
+ char[][] qualifiedName = qualifiedNames[i];
+ if (qualifiedName.length == 1 ? includes(qualifiedName[0]) : includes(qualifiedName)) {
+ if (PHPBuilder.DEBUG)
+ System.out.println("Found well known match in " + CharOperation.toString(qualifiedName)); //$NON-NLS-1$
+ return true;
+ }
+ }
+ }
+ } else {
+ for (int i = 0, l = simpleNames.length; i < l; i++) {
+ if (includes(simpleNames[i])) {
+ for (int j = 0, m = qualifiedNames.length; j < m; j++) {
+ char[][] qualifiedName = qualifiedNames[j];
+ if (qualifiedName.length == 1 ? includes(qualifiedName[0]) : includes(qualifiedName)) {
+ if (PHPBuilder.DEBUG)
+ System.out.println("Found match in " + CharOperation.toString(qualifiedName) //$NON-NLS-1$
+ + " to " + new String(simpleNames[i])); //$NON-NLS-1$
+ return true;
+ }
+ }
+ return false;
+ }
+ }
+ }
+ return false;
+}
+
+
+// When any type is compiled, its methods are verified for certain problems
+// the MethodVerifier requests 3 well known types which end up in the reference collection
+// having WellKnownQualifiedNames & WellKnownSimpleNames, saves every type 40 bytes
+// NOTE: These collections are sorted by length
+static final char[][][] WellKnownQualifiedNames = new char[][][] {
+ TypeConstants.JAVA_LANG_RUNTIMEEXCEPTION,
+ TypeConstants.JAVA_LANG_THROWABLE,
+ TypeConstants.JAVA_LANG_OBJECT,
+ TypeConstants.JAVA_LANG,
+ new char[][] {TypeConstants.JAVA},
+ new char[][] {new char[] {'o', 'r', 'g'}},
+ new char[][] {new char[] {'c', 'o', 'm'}},
+ CharOperation.NO_CHAR_CHAR}; // default package
+static final char[][] WellKnownSimpleNames = new char[][] {
+ TypeConstants.JAVA_LANG_RUNTIMEEXCEPTION[2],
+ TypeConstants.JAVA_LANG_THROWABLE[2],
+ TypeConstants.JAVA_LANG_OBJECT[2],
+ TypeConstants.JAVA,
+ TypeConstants.LANG,
+ new char[] {'o', 'r', 'g'},
+ new char[] {'c', 'o', 'm'}};
+
+static final char[][][] EmptyQualifiedNames = new char[0][][];
+static final char[][] EmptySimpleNames = CharOperation.NO_CHAR_CHAR;
+
+// each array contains qualified char[][], one for size 2, 3, 4, 5, 6, 7 & the rest
+static final int MaxQualifiedNames = 7;
+static ArrayList[] InternedQualifiedNames = new ArrayList[MaxQualifiedNames];
+// each array contains simple char[], one for size 1 to 29 & the rest
+static final int MaxSimpleNames = 30;
+static ArrayList[] InternedSimpleNames = new ArrayList[MaxSimpleNames];
+static {
+ for (int i = 0; i < MaxQualifiedNames; i++)
+ InternedQualifiedNames[i] = new ArrayList(37);
+ for (int i = 0; i < MaxSimpleNames; i++)
+ InternedSimpleNames[i] = new ArrayList(11);
+}
+
+static char[][][] internQualifiedNames(ArrayList qualifiedStrings) {
+ if (qualifiedStrings == null) return EmptyQualifiedNames;
+ int length = qualifiedStrings.size();
+ if (length == 0) return EmptyQualifiedNames;
+
+ char[][][] result = new char[length][][];
+ for (int i = 0; i < length; i++)
+ result[i] = CharOperation.splitOn('/', ((String) qualifiedStrings.get(i)).toCharArray());
+ return internQualifiedNames(result);
+}
+
+static char[][][] internQualifiedNames(char[][][] qualifiedNames) {
+ if (qualifiedNames == null) return EmptyQualifiedNames;
+ int length = qualifiedNames.length;
+ if (length == 0) return EmptyQualifiedNames;
+
+ char[][][] keepers = new char[length][][];
+ int index = 0;
+ next : for (int i = 0; i < length; i++) {
+ char[][] qualifiedName = qualifiedNames[i];
+ int qLength = qualifiedName.length;
+ for (int j = 0, m = WellKnownQualifiedNames.length; j < m; j++) {
+ char[][] wellKnownName = WellKnownQualifiedNames[j];
+ if (qLength > wellKnownName.length)
+ break; // all remaining well known names are shorter
+ if (CharOperation.equals(qualifiedName, wellKnownName))
+ continue next;
+ }
+
+ // InternedQualifiedNames[0] is for the rest (> 7 & 1)
+ // InternedQualifiedNames[1] is for size 2...
+ // InternedQualifiedNames[6] is for size 7
+ ArrayList internedNames = InternedQualifiedNames[qLength <= MaxQualifiedNames ? qLength - 1 : 0];
+ for (int j = 0, m = internedNames.size(); j < m; j++) {
+ char[][] internedName = (char[][]) internedNames.get(j);
+ if (CharOperation.equals(qualifiedName, internedName)) {
+ keepers[index++] = internedName;
+ continue next;
+ }
+ }
+ qualifiedName = internSimpleNames(qualifiedName, false);
+ internedNames.add(qualifiedName);
+ keepers[index++] = qualifiedName;
+ }
+ if (length > index) {
+ if (length == 0) return EmptyQualifiedNames;
+ System.arraycopy(keepers, 0, keepers = new char[index][][], 0, index);
+ }
+ return keepers;
+}
+
+static char[][] internSimpleNames(ArrayList simpleStrings) {
+ if (simpleStrings == null) return EmptySimpleNames;
+ int length = simpleStrings.size();
+ if (length == 0) return EmptySimpleNames;
+
+ char[][] result = new char[length][];
+ for (int i = 0; i < length; i++)
+ result[i] = ((String) simpleStrings.get(i)).toCharArray();
+ return internSimpleNames(result, true);
+}
+
+static char[][] internSimpleNames(char[][] simpleNames, boolean removeWellKnown) {
+ if (simpleNames == null) return EmptySimpleNames;
+ int length = simpleNames.length;
+ if (length == 0) return EmptySimpleNames;
+
+ char[][] keepers = new char[length][];
+ int index = 0;
+ next : for (int i = 0; i < length; i++) {
+ char[] name = simpleNames[i];
+ int sLength = name.length;
+ for (int j = 0, m = WellKnownSimpleNames.length; j < m; j++) {
+ char[] wellKnownName = WellKnownSimpleNames[j];
+ if (sLength > wellKnownName.length)
+ break; // all remaining well known names are shorter
+ if (CharOperation.equals(name, wellKnownName)) {
+ if (!removeWellKnown)
+ keepers[index++] = WellKnownSimpleNames[j];
+ continue next;
+ }
+ }
+
+ // InternedSimpleNames[0] is for the rest (> 29)
+ // InternedSimpleNames[1] is for size 1...
+ // InternedSimpleNames[29] is for size 29
+ ArrayList internedNames = InternedSimpleNames[sLength < MaxSimpleNames ? sLength : 0];
+ for (int j = 0, m = internedNames.size(); j < m; j++) {
+ char[] internedName = (char[]) internedNames.get(j);
+ if (CharOperation.equals(name, internedName)) {
+ keepers[index++] = internedName;
+ continue next;
+ }
+ }
+ internedNames.add(name);
+ keepers[index++] = name;
+ }
+ if (length > index) {
+ if (index == 0) return EmptySimpleNames;
+ System.arraycopy(keepers, 0, keepers = new char[index][], 0, index);
+ }
+ return keepers;
+}
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/SourceFile.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/SourceFile.java
new file mode 100644
index 0000000..279708e
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/SourceFile.java
@@ -0,0 +1,102 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core.builder;
+
+import net.sourceforge.phpdt.core.compiler.CharOperation;
+import net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit;
+import net.sourceforge.phpdt.internal.compiler.problem.AbortCompilation;
+import net.sourceforge.phpdt.internal.core.Util;
+
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IPath;
+
+public class SourceFile implements ICompilationUnit {
+
+IFile resource;
+ClasspathMultiDirectory sourceLocation;
+String initialTypeName;
+String encoding;
+
+public SourceFile(IFile resource, ClasspathMultiDirectory sourceLocation, String encoding) {
+ this.resource = resource;
+ this.sourceLocation = sourceLocation;
+ this.initialTypeName = extractTypeName();
+ this.encoding = encoding;
+}
+
+public boolean equals(Object o) {
+ if (this == o) return true;
+ if (!(o instanceof SourceFile)) return false;
+
+ SourceFile f = (SourceFile) o;
+ return sourceLocation == f.sourceLocation && resource.getFullPath().equals(f.resource.getFullPath());
+}
+
+String extractTypeName() {
+ // answer a String with the qualified type name for the source file in the form: 'p1/p2/A'
+ IPath fullPath = resource.getFullPath();
+ int resourceSegmentCount = fullPath.segmentCount();
+ int sourceFolderSegmentCount = sourceLocation.sourceFolder.getFullPath().segmentCount();
+ int charCount = (resourceSegmentCount - sourceFolderSegmentCount - 1) - 5; // length of ".java"
+ for (int i = sourceFolderSegmentCount; i < resourceSegmentCount; i++)
+ charCount += fullPath.segment(i).length();
+
+ char[] result = new char[charCount];
+ int offset = 0;
+ resourceSegmentCount--; // deal with the last segment separately
+ for (int i = sourceFolderSegmentCount; i < resourceSegmentCount; i++) {
+ String segment = fullPath.segment(i);
+ int size = segment.length();
+ segment.getChars(0, size, result, offset);
+ offset += size;
+ result[offset++] = '/';
+ }
+ String segment = fullPath.segment(resourceSegmentCount);
+ int size = segment.length() - 5; // length of ".java"
+ segment.getChars(0, size, result, offset);
+ return new String(result);
+}
+
+public char[] getContents() {
+
+ try {
+ return Util.getResourceContentsAsCharArray(resource, this.encoding);
+ } catch (CoreException e) {
+ throw new AbortCompilation(true, new MissingSourceFileException(resource.getFullPath().toString()));
+ }
+}
+
+public char[] getFileName() {
+ return resource.getFullPath().toString().toCharArray(); // do not know what you want to return here
+}
+
+public char[] getMainTypeName() {
+ char[] typeName = initialTypeName.toCharArray();
+ int lastIndex = CharOperation.lastIndexOf('/', typeName);
+ return CharOperation.subarray(typeName, lastIndex + 1, -1);
+}
+
+public char[][] getPackageName() {
+ char[] typeName = initialTypeName.toCharArray();
+ int lastIndex = CharOperation.lastIndexOf('/', typeName);
+ return CharOperation.splitOn('/', typeName, 0, lastIndex);
+}
+
+String typeLocator() {
+ return resource.getProjectRelativePath().toString();
+}
+
+public String toString() {
+ return "SourceFile[" //$NON-NLS-1$
+ + resource.getFullPath() + "]"; //$NON-NLS-1$
+}
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/State.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/State.java
new file mode 100644
index 0000000..057d387
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/builder/State.java
@@ -0,0 +1,613 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core.builder;
+
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Date;
+
+import net.sourceforge.phpdt.core.compiler.CharOperation;
+import net.sourceforge.phpdt.internal.compiler.util.Util;
+import net.sourceforge.phpdt.internal.core.util.SimpleLookupTable;
+
+import org.eclipse.core.resources.IContainer;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.IResourceDelta;
+import org.eclipse.core.resources.IWorkspaceRoot;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.core.runtime.Path;
+
+public class State {
+// NOTE: this state cannot contain types that are not defined in this project
+
+String javaProjectName;
+ClasspathMultiDirectory[] sourceLocations;
+//ClasspathLocation[] binaryLocations;
+// keyed by the project relative path of the type (ie. "src1/p1/p2/A.java"), value is a ReferenceCollection or an AdditionalTypeCollection
+SimpleLookupTable references;
+// keyed by qualified type name "p1/p2/A", value is the project relative path which defines this type "src1/p1/p2/A.java"
+SimpleLookupTable typeLocators;
+
+int buildNumber;
+long lastStructuralBuildTime;
+SimpleLookupTable structuralBuildTimes;
+
+private String[] knownPackageNames; // of the form "p1/p2"
+
+static final byte VERSION = 0x0007;
+
+static final byte SOURCE_FOLDER = 1;
+static final byte BINARY_FOLDER = 2;
+static final byte EXTERNAL_JAR = 3;
+static final byte INTERNAL_JAR = 4;
+
+State() {
+}
+
+protected State(PHPBuilder javaBuilder) {
+ this.knownPackageNames = null;
+ this.javaProjectName = javaBuilder.currentProject.getName();
+ this.sourceLocations = javaBuilder.nameEnvironment.sourceLocations;
+// this.binaryLocations = javaBuilder.nameEnvironment.binaryLocations;
+ this.references = new SimpleLookupTable(7);
+ this.typeLocators = new SimpleLookupTable(7);
+
+ this.buildNumber = 0; // indicates a full build
+ this.lastStructuralBuildTime = System.currentTimeMillis();
+ this.structuralBuildTimes = new SimpleLookupTable(3);
+}
+
+void copyFrom(State lastState) {
+ try {
+ this.knownPackageNames = null;
+ this.buildNumber = lastState.buildNumber + 1;
+ this.lastStructuralBuildTime = lastState.lastStructuralBuildTime;
+ this.references = (SimpleLookupTable) lastState.references.clone();
+ this.typeLocators = (SimpleLookupTable) lastState.typeLocators.clone();
+ } catch (CloneNotSupportedException e) {
+ this.references = new SimpleLookupTable(lastState.references.elementSize);
+ Object[] keyTable = lastState.references.keyTable;
+ Object[] valueTable = lastState.references.valueTable;
+ for (int i = 0, l = keyTable.length; i < l; i++)
+ if (keyTable[i] != null)
+ this.references.put(keyTable[i], valueTable[i]);
+
+ this.typeLocators = new SimpleLookupTable(lastState.typeLocators.elementSize);
+ keyTable = lastState.typeLocators.keyTable;
+ valueTable = lastState.typeLocators.valueTable;
+ for (int i = 0, l = keyTable.length; i < l; i++)
+ if (keyTable[i] != null)
+ this.typeLocators.put(keyTable[i], valueTable[i]);
+ }
+}
+
+char[][] getDefinedTypeNamesFor(String typeLocator) {
+ Object c = references.get(typeLocator);
+ if (c instanceof AdditionalTypeCollection)
+ return ((AdditionalTypeCollection) c).definedTypeNames;
+ return null; // means only one type is defined with the same name as the file... saves space
+}
+
+boolean isDuplicateLocator(String qualifiedTypeName, String typeLocator) {
+ String existing = (String) typeLocators.get(qualifiedTypeName);
+ return existing != null && !existing.equals(typeLocator);
+}
+
+boolean isKnownPackage(String qualifiedPackageName) {
+ if (knownPackageNames == null) {
+ ArrayList names = new ArrayList(typeLocators.elementSize);
+ Object[] keyTable = typeLocators.keyTable;
+ for (int i = 0, l = keyTable.length; i < l; i++) {
+ if (keyTable[i] != null) {
+ String packageName = (String) keyTable[i]; // is a type name of the form p1/p2/A
+ int last = packageName.lastIndexOf('/');
+ packageName = last == -1 ? null : packageName.substring(0, last);
+ while (packageName != null && !names.contains(packageName)) {
+ names.add(packageName);
+ last = packageName.lastIndexOf('/');
+ packageName = last == -1 ? null : packageName.substring(0, last);
+ }
+ }
+ }
+ knownPackageNames = new String[names.size()];
+ names.toArray(knownPackageNames);
+ }
+ for (int i = 0, l = knownPackageNames.length; i < l; i++)
+ if (knownPackageNames[i].equals(qualifiedPackageName))
+ return true;
+ return false;
+}
+
+void record(String typeLocator, char[][][] qualifiedRefs, char[][] simpleRefs, char[] mainTypeName, ArrayList typeNames) {
+ if (typeNames.size() == 1 && CharOperation.equals(mainTypeName, (char[]) typeNames.get(0))) {
+ references.put(typeLocator, new ReferenceCollection(qualifiedRefs, simpleRefs));
+ } else {
+ char[][] definedTypeNames = new char[typeNames.size()][]; // can be empty when no types are defined
+ typeNames.toArray(definedTypeNames);
+ references.put(typeLocator, new AdditionalTypeCollection(definedTypeNames, qualifiedRefs, simpleRefs));
+ }
+}
+
+void recordLocatorForType(String qualifiedTypeName, String typeLocator) {
+ this.knownPackageNames = null;
+ typeLocators.put(qualifiedTypeName, typeLocator);
+}
+
+void recordStructuralDependency(IProject prereqProject, State prereqState) {
+ if (prereqState != null)
+ structuralBuildTimes.put(prereqProject.getName(), new Long(prereqState.lastStructuralBuildTime));
+}
+
+void removeLocator(String typeLocatorToRemove) {
+ this.knownPackageNames = null;
+ references.removeKey(typeLocatorToRemove);
+ typeLocators.removeValue(typeLocatorToRemove);
+}
+
+void removePackage(IResourceDelta sourceDelta) {
+ IResource resource = sourceDelta.getResource();
+ switch(resource.getType()) {
+ case IResource.FOLDER :
+ IResourceDelta[] children = sourceDelta.getAffectedChildren();
+ for (int i = 0, l = children.length; i < l; i++)
+ removePackage(children[i]);
+ return;
+ case IResource.FILE :
+ IPath typeLocatorPath = resource.getProjectRelativePath();
+ if (Util.isJavaFileName(typeLocatorPath.lastSegment()))
+ removeLocator(typeLocatorPath.toString());
+ }
+}
+
+void removeQualifiedTypeName(String qualifiedTypeNameToRemove) {
+ this.knownPackageNames = null;
+ typeLocators.removeKey(qualifiedTypeNameToRemove);
+}
+
+static State read(IProject project, DataInputStream in) throws IOException {
+ if (PHPBuilder.DEBUG)
+ System.out.println("About to read state..."); //$NON-NLS-1$
+ if (VERSION != in.readByte()) {
+ if (PHPBuilder.DEBUG)
+ System.out.println("Found non-compatible state version... answered null"); //$NON-NLS-1$
+ return null;
+ }
+
+ State newState = new State();
+ newState.javaProjectName = in.readUTF();
+ if (!project.getName().equals(newState.javaProjectName)) {
+ if (PHPBuilder.DEBUG)
+ System.out.println("Project's name does not match... answered null"); //$NON-NLS-1$
+ return null;
+ }
+ newState.buildNumber = in.readInt();
+ newState.lastStructuralBuildTime = in.readLong();
+
+ int length = in.readInt();
+ newState.sourceLocations = new ClasspathMultiDirectory[0];
+// newState.sourceLocations = new ClasspathMultiDirectory[length];
+// for (int i = 0; i < length; i++) {
+// IContainer sourceFolder = project, outputFolder = project;
+// String folderName;
+// if ((folderName = in.readUTF()).length() > 0) sourceFolder = project.getFolder(folderName);
+// if ((folderName = in.readUTF()).length() > 0) outputFolder = project.getFolder(folderName);
+// ClasspathMultiDirectory md =
+// (ClasspathMultiDirectory) ClasspathLocation.forSourceFolder(sourceFolder, outputFolder, readNames(in));
+// if (in.readBoolean())
+// md.hasIndependentOutputFolder = true;
+// newState.sourceLocations[i] = md;
+// }
+
+ length = in.readInt();
+// newState.binaryLocations = new ClasspathLocation[length];
+// IWorkspaceRoot root = project.getWorkspace().getRoot();
+// for (int i = 0; i < length; i++) {
+// switch (in.readByte()) {
+// case SOURCE_FOLDER :
+// newState.binaryLocations[i] = newState.sourceLocations[in.readInt()];
+// break;
+// case BINARY_FOLDER :
+// IPath path = new Path(in.readUTF());
+// IContainer outputFolder = path.segmentCount() == 1
+// ? (IContainer) root.getProject(path.toString())
+// : (IContainer) root.getFolder(path);
+// newState.binaryLocations[i] = ClasspathLocation.forBinaryFolder(outputFolder, in.readBoolean());
+// break;
+// case EXTERNAL_JAR :
+// newState.binaryLocations[i] = ClasspathLocation.forLibrary(in.readUTF());
+// break;
+// case INTERNAL_JAR :
+// newState.binaryLocations[i] = ClasspathLocation.forLibrary(root.getFile(new Path(in.readUTF())));
+// }
+// }
+
+ newState.structuralBuildTimes = new SimpleLookupTable(length = in.readInt());
+ for (int i = 0; i < length; i++)
+ newState.structuralBuildTimes.put(in.readUTF(), new Long(in.readLong()));
+
+ String[] internedTypeLocators = new String[length = in.readInt()];
+ for (int i = 0; i < length; i++)
+ internedTypeLocators[i] = in.readUTF();
+
+ newState.typeLocators = new SimpleLookupTable(length = in.readInt());
+ for (int i = 0; i < length; i++)
+ newState.typeLocators.put(in.readUTF(), internedTypeLocators[in.readInt()]);
+
+ char[][] internedSimpleNames = ReferenceCollection.internSimpleNames(readNames(in), false);
+ char[][][] internedQualifiedNames = new char[length = in.readInt()][][];
+ for (int i = 0; i < length; i++) {
+ int qLength = in.readInt();
+ char[][] qName = new char[qLength][];
+ for (int j = 0; j < qLength; j++)
+ qName[j] = internedSimpleNames[in.readInt()];
+ internedQualifiedNames[i] = qName;
+ }
+ internedQualifiedNames = ReferenceCollection.internQualifiedNames(internedQualifiedNames);
+
+ newState.references = new SimpleLookupTable(length = in.readInt());
+ for (int i = 0; i < length; i++) {
+ String typeLocator = internedTypeLocators[in.readInt()];
+ ReferenceCollection collection = null;
+ switch (in.readByte()) {
+ case 1 :
+ char[][] additionalTypeNames = readNames(in);
+ char[][][] qualifiedNames = new char[in.readInt()][][];
+ for (int j = 0, m = qualifiedNames.length; j < m; j++)
+ qualifiedNames[j] = internedQualifiedNames[in.readInt()];
+ char[][] simpleNames = new char[in.readInt()][];
+ for (int j = 0, m = simpleNames.length; j < m; j++)
+ simpleNames[j] = internedSimpleNames[in.readInt()];
+ collection = new AdditionalTypeCollection(additionalTypeNames, qualifiedNames, simpleNames);
+ break;
+ case 2 :
+ char[][][] qNames = new char[in.readInt()][][];
+ for (int j = 0, m = qNames.length; j < m; j++)
+ qNames[j] = internedQualifiedNames[in.readInt()];
+ char[][] sNames = new char[in.readInt()][];
+ for (int j = 0, m = sNames.length; j < m; j++)
+ sNames[j] = internedSimpleNames[in.readInt()];
+ collection = new ReferenceCollection(qNames, sNames);
+ }
+ newState.references.put(typeLocator, collection);
+ }
+ if (PHPBuilder.DEBUG)
+ System.out.println("Successfully read state for " + newState.javaProjectName); //$NON-NLS-1$
+ return newState;
+}
+
+private static char[][] readNames(DataInputStream in) throws IOException {
+ int length = in.readInt();
+ char[][] names = new char[length][];
+ for (int i = 0; i < length; i++) {
+ int nLength = in.readInt();
+ char[] name = new char[nLength];
+ for (int j = 0; j < nLength; j++)
+ name[j] = in.readChar();
+ names[i] = name;
+ }
+ return names;
+}
+
+void tagAsNoopBuild() {
+ this.buildNumber = -1; // tag the project since it has no source folders and can be skipped
+}
+
+boolean wasNoopBuild() {
+ return buildNumber == -1;
+}
+
+void tagAsStructurallyChanged() {
+ this.lastStructuralBuildTime = System.currentTimeMillis();
+}
+
+boolean wasStructurallyChanged(IProject prereqProject, State prereqState) {
+ if (prereqState != null) {
+ Object o = structuralBuildTimes.get(prereqProject.getName());
+ long previous = o == null ? 0 : ((Long) o).longValue();
+ if (previous == prereqState.lastStructuralBuildTime) return false;
+ }
+ return true;
+}
+
+void write(DataOutputStream out) throws IOException {
+ int length;
+ Object[] keyTable;
+ Object[] valueTable;
+
+/*
+ * byte VERSION
+ * String project name
+ * int build number
+ * int last structural build number
+*/
+ out.writeByte(VERSION);
+ out.writeUTF(javaProjectName);
+ out.writeInt(buildNumber);
+ out.writeLong(lastStructuralBuildTime);
+
+/*
+ * ClasspathMultiDirectory[]
+ * int id
+ * String path(s)
+*/
+ out.writeInt(length = sourceLocations.length);
+ for (int i = 0; i < length; i++) {
+ ClasspathMultiDirectory md = sourceLocations[i];
+ out.writeUTF(md.sourceFolder.getProjectRelativePath().toString());
+ out.writeUTF(md.binaryFolder.getProjectRelativePath().toString());
+ writeNames(md.exclusionPatterns, out);
+ out.writeBoolean(md.hasIndependentOutputFolder);
+ }
+
+/*
+ * ClasspathLocation[]
+ * int id
+ * String path(s)
+*/
+// out.writeInt(length = binaryLocations.length);
+// next : for (int i = 0; i < length; i++) {
+// ClasspathLocation c = binaryLocations[i];
+// if (c instanceof ClasspathMultiDirectory) {
+// out.writeByte(SOURCE_FOLDER);
+// for (int j = 0, m = sourceLocations.length; j < m; j++) {
+// if (sourceLocations[j] == c) {
+// out.writeInt(j);
+// continue next;
+// }
+// }
+// } else if (c instanceof ClasspathDirectory) {
+// out.writeByte(BINARY_FOLDER);
+// ClasspathDirectory cd = (ClasspathDirectory) c;
+// out.writeUTF(cd.binaryFolder.getFullPath().toString());
+// out.writeBoolean(cd.isOutputFolder);
+// } else {
+// ClasspathJar jar = (ClasspathJar) c;
+// if (jar.resource == null) {
+// out.writeByte(EXTERNAL_JAR);
+// out.writeUTF(jar.zipFilename);
+// } else {
+// out.writeByte(INTERNAL_JAR);
+// out.writeUTF(jar.resource.getFullPath().toString());
+// }
+// }
+// }
+
+/*
+ * Structural build numbers table
+ * String prereq project name
+ * int last structural build number
+*/
+ out.writeInt(length = structuralBuildTimes.elementSize);
+ if (length > 0) {
+ keyTable = structuralBuildTimes.keyTable;
+ valueTable = structuralBuildTimes.valueTable;
+ for (int i = 0, l = keyTable.length; i < l; i++) {
+ if (keyTable[i] != null) {
+ length--;
+ out.writeUTF((String) keyTable[i]);
+ out.writeLong(((Long) valueTable[i]).longValue());
+ }
+ }
+ if (PHPBuilder.DEBUG && length != 0)
+ System.out.println("structuralBuildNumbers table is inconsistent"); //$NON-NLS-1$
+ }
+
+/*
+ * String[] Interned type locators
+ */
+ out.writeInt(length = references.elementSize);
+ ArrayList internedTypeLocators = new ArrayList(length);
+ if (length > 0) {
+ keyTable = references.keyTable;
+ for (int i = 0, l = keyTable.length; i < l; i++) {
+ if (keyTable[i] != null) {
+ length--;
+ String key = (String) keyTable[i];
+ out.writeUTF(key);
+ internedTypeLocators.add(key);
+ }
+ }
+ if (PHPBuilder.DEBUG && length != 0)
+ System.out.println("references table is inconsistent"); //$NON-NLS-1$
+ }
+
+/*
+ * Type locators table
+ * String type name
+ * int interned locator id
+ */
+ out.writeInt(length = typeLocators.elementSize);
+ if (length > 0) {
+ keyTable = typeLocators.keyTable;
+ valueTable = typeLocators.valueTable;
+ for (int i = 0, l = keyTable.length; i < l; i++) {
+ if (keyTable[i] != null) {
+ length--;
+ out.writeUTF((String) keyTable[i]);
+ out.writeInt(internedTypeLocators.indexOf((String) valueTable[i]));
+ }
+ }
+ if (PHPBuilder.DEBUG && length != 0)
+ System.out.println("typeLocators table is inconsistent"); //$NON-NLS-1$
+ }
+
+/*
+ * char[][][] Interned qualified names
+ * char[][] Interned simple names
+ */
+ ArrayList internedQualifiedNames = new ArrayList(31);
+ ArrayList internedSimpleNames = new ArrayList(31);
+ valueTable = references.valueTable;
+ for (int i = 0, l = valueTable.length; i < l; i++) {
+ if (valueTable[i] != null) {
+ ReferenceCollection collection = (ReferenceCollection) valueTable[i];
+ char[][][] qNames = collection.qualifiedNameReferences;
+ for (int j = 0, m = qNames.length; j < m; j++) {
+ char[][] qName = qNames[j];
+ if (!internedQualifiedNames.contains(qName)) { // remember the names have been interned
+ internedQualifiedNames.add(qName);
+ for (int k = 0, n = qName.length; k < n; k++) {
+ char[] sName = qName[k];
+ if (!internedSimpleNames.contains(sName)) // remember the names have been interned
+ internedSimpleNames.add(sName);
+ }
+ }
+ }
+ char[][] sNames = collection.simpleNameReferences;
+ for (int j = 0, m = sNames.length; j < m; j++) {
+ char[] sName = sNames[j];
+ if (!internedSimpleNames.contains(sName)) // remember the names have been interned
+ internedSimpleNames.add(sName);
+ }
+ }
+ }
+ char[][] internedArray = new char[internedSimpleNames.size()][];
+ internedSimpleNames.toArray(internedArray);
+ writeNames(internedArray, out);
+ // now write the interned qualified names as arrays of interned simple names
+ out.writeInt(length = internedQualifiedNames.size());
+ for (int i = 0; i < length; i++) {
+ char[][] qName = (char[][]) internedQualifiedNames.get(i);
+ int qLength = qName.length;
+ out.writeInt(qLength);
+ for (int j = 0; j < qLength; j++)
+ out.writeInt(internedSimpleNames.indexOf(qName[j]));
+ }
+
+/*
+ * References table
+ * int interned locator id
+ * ReferenceCollection
+*/
+ out.writeInt(length = references.elementSize);
+ if (length > 0) {
+ keyTable = references.keyTable;
+ for (int i = 0, l = keyTable.length; i < l; i++) {
+ if (keyTable[i] != null) {
+ length--;
+ out.writeInt(internedTypeLocators.indexOf((String) keyTable[i]));
+ ReferenceCollection collection = (ReferenceCollection) valueTable[i];
+ if (collection instanceof AdditionalTypeCollection) {
+ out.writeByte(1);
+ AdditionalTypeCollection atc = (AdditionalTypeCollection) collection;
+ writeNames(atc.definedTypeNames, out);
+ } else {
+ out.writeByte(2);
+ }
+ char[][][] qNames = collection.qualifiedNameReferences;
+ int qLength = qNames.length;
+ out.writeInt(qLength);
+ for (int j = 0; j < qLength; j++)
+ out.writeInt(internedQualifiedNames.indexOf(qNames[j]));
+ char[][] sNames = collection.simpleNameReferences;
+ int sLength = sNames.length;
+ out.writeInt(sLength);
+ for (int j = 0; j < sLength; j++)
+ out.writeInt(internedSimpleNames.indexOf(sNames[j]));
+ }
+ }
+ if (PHPBuilder.DEBUG && length != 0)
+ System.out.println("references table is inconsistent"); //$NON-NLS-1$
+ }
+}
+
+private void writeNames(char[][] names, DataOutputStream out) throws IOException {
+ int length = names == null ? 0 : names.length;
+ out.writeInt(length);
+ for (int i = 0; i < length; i++) {
+ char[] name = names[i];
+ int nLength = name.length;
+ out.writeInt(nLength);
+ for (int j = 0; j < nLength; j++)
+ out.writeChar(name[j]);
+ }
+}
+
+/**
+ * Returns a string representation of the receiver.
+ */
+public String toString() {
+ return "State for " + javaProjectName //$NON-NLS-1$
+ + " (#" + buildNumber //$NON-NLS-1$
+ + " @ " + new Date(lastStructuralBuildTime) //$NON-NLS-1$
+ + ")"; //$NON-NLS-1$
+}
+
+/* Debug helper
+void dump() {
+ System.out.println("State for " + javaProjectName + " (" + buildNumber + " @ " + new Date(lastStructuralBuildTime) + ")");
+ System.out.println("\tClass path source locations:");
+ for (int i = 0, l = sourceLocations.length; i < l; i++)
+ System.out.println("\t\t" + sourceLocations[i]);
+ System.out.println("\tClass path binary locations:");
+ for (int i = 0, l = binaryLocations.length; i < l; i++)
+ System.out.println("\t\t" + binaryLocations[i]);
+
+ System.out.print("\tStructural build numbers table:");
+ if (structuralBuildTimes.elementSize == 0) {
+ System.out.print("
STATICDOMNode
's source positions to include whitespace preceeding
+ * the node on the line on which the node starts, and all whitespace after the node up to
+ * the next node's start
+ */
+void normalize(ILineStartFinder finder) {
+ super.normalize(finder);
+ initalizeHeader();
+}
+/**
+ * @see IDOMCompilationUnit@setHeader(String)
+ */
+public void setHeader(String comment) {
+ fHeader= comment;
+ fragment();
+}
+/**
+ * @see IDOMCompilationUnit#setName(String)
+ */
+public void setName(String name) {}
+/**
+ * @see DOMNode#shareContents(DOMNode)
+ */
+protected void shareContents(DOMNode node) {
+ super.shareContents(node);
+ fHeader= ((DOMCompilationUnit)node).fHeader;
+}
+/**
+ * @see IDOMNode#toString()
+ */
+public String toString() {
+ return "COMPILATION_UNIT: " + getName(); //$NON-NLS-1$
+}
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMField.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMField.java
new file mode 100644
index 0000000..32ebdb1
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMField.java
@@ -0,0 +1,618 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core.jdom;
+
+import java.util.Enumeration;
+
+import net.sourceforge.phpdt.core.IJavaElement;
+import net.sourceforge.phpdt.core.IType;
+import net.sourceforge.phpdt.core.jdom.DOMException;
+import net.sourceforge.phpdt.core.jdom.IDOMField;
+import net.sourceforge.phpdt.core.jdom.IDOMNode;
+import net.sourceforge.phpdt.internal.compiler.util.Util;
+import net.sourceforge.phpdt.internal.core.util.CharArrayBuffer;
+import net.sourceforge.phpdt.internal.core.util.CharArrayOps;
+
+/**
+ * DOMField provides an implementation of IDOMField.
+ *
+ * @see IDOMField
+ * @see DOMNode
+ */
+class DOMField extends DOMMember implements IDOMField {
+
+ /**
+ * Contains the type of the field when the type
+ * has been altered from the contents in the
+ * document, otherwise null
.
+ */
+ protected String fType;
+
+ /**
+ * The original inclusive source range of the
+ * field's type in the document.
+ */
+ protected int[] fTypeRange;
+
+ /**
+ * The contents of the initializer when the
+ * initializer has been altered from the
+ * original state in the document, otherwise
+ * null
.
+ */
+ protected String fInitializer;
+
+ /**
+ * The original inclusive source range of the
+ * initializer in the document.
+ */
+ protected int[] fInitializerRange;
+
+/**
+ * Constructs an empty field node.
+ */
+DOMField() {
+}
+/**
+ * Creates a new detailed FIELD document fragment on the given range of the document.
+ *
+ * @param document - the document containing this node's original contents
+ * @param sourceRange - a two element array of integers describing the
+ * entire inclusive source range of this node within its document.
+ * Contents start on and include the character at the first position.
+ * Contents end on and include the character at the last position.
+ * An array of -1's indicates this node's contents do not exist
+ * in the document.
+ * @param name - the identifier portion of the name of this field,
+ * corresponding to VariableDeclaratorId (JLS 8.3).
+ * @param nameRange - a two element array of integers describing the
+ * entire inclusive source range of this node's name within its document,
+ * including any array qualifiers that might follow the name.
+ * @param commentRange - a two element array describing the comments that precede
+ * the member declaration. The first matches the start of this node's
+ * sourceRange, and the second is the new-line or first non-whitespace
+ * character following the last comment. If no comments are present,
+ * this array contains two -1's.
+ * @param flags - an integer representing the modifiers for this member. The
+ * integer can be analyzed with org.eclipse.jdt.core.Flags
+ * @param modifierRange - a two element array describing the location of
+ * modifiers for this member within its source range. The first integer
+ * is the first character of the first modifier for this member, and
+ * the second integer is the last whitespace character preceeding the
+ * next part of this member declaration. If there are no modifiers present
+ * in this node's source code (that is, package default visibility), this array
+ * contains two -1's.
+ * @param typeRange- a two element array describing the location of the
+ * typeName in the document - the positions of the first and last characters
+ * of the typeName.
+ * @param type - the type of the field, in normalized form, as defined in
+ * Type in Field Declaration (JLS 8.3)
+ * @param hasInitializer - true if this field declaration includes an initializer,
+ * otherwise false
+ * @param initRange - a two element array describing the location of the initializer
+ * in the declaration. The first integer is the position of the character
+ * following the equals sign, and the position of the last character is the last
+ * in the initializer. If this field has no initializer, this array contains
+ * two -1's.
+ * @param isVariableDeclarator - true if the field is a seconday variable declarator
+ * for a previous field declaration.
+ */
+DOMField(char[] document, int[] sourceRange, String name, int[] nameRange, int[] commentRange, int flags, int[] modifierRange, int[] typeRange, String type, boolean hasInitializer, int[] initRange, boolean isVariableDeclarator) {
+ super(document, sourceRange, name, nameRange, commentRange, flags, modifierRange);
+
+ fType= type;
+ fTypeRange= typeRange;
+ setHasInitializer(hasInitializer);
+ fInitializerRange= initRange;
+ setIsVariableDeclarator(isVariableDeclarator);
+ setMask(MASK_DETAILED_SOURCE_INDEXES, true);
+
+}
+/**
+ * Creates a new simple FIELD document fragment on the given range of the document.
+ *
+ * @param document - the document containing this node's original contents
+ * @param sourceRange - a two element array of integers describing the
+ * entire inclusive source range of this node within its document.
+ * Contents start on and include the character at the first position.
+ * Contents end on and include the character at the last position.
+ * An array of -1's indicates this node's contents do not exist
+ * in the document.
+ * @param name - the identifier portion of the name of this field,
+ * corresponding to VariableDeclaratorId (JLS 8.3).
+ * @param nameRange - a two element array of integers describing the
+ * entire inclusive source range of this node's name within its document,
+ * including any array qualifiers that might follow the name.
+ * @param flags - an integer representing the modifiers for this member. The
+ * integer can be analyzed with org.eclipse.jdt.core.Flags
+ * @param type - the type of the field, in normalized form, as defined in
+ * Type in Field Declaration (JLS 8.3)
+ * @param isVariableDeclarator - true if the field is a seconday variable declarator
+ * for a previous field declaration.
+ */
+DOMField(char[] document, int[] sourceRange, String name, int[] nameRange, int flags, String type, boolean isVariableDeclarator) {
+ this(document, sourceRange, name, nameRange, new int[] {-1, -1}, flags, new int[] {-1, -1}, new int[] {-1, -1}, type, false, new int[] {-1, -1}, isVariableDeclarator);
+ setMask(MASK_DETAILED_SOURCE_INDEXES, false);
+}
+/**
+ * Appends this member's body contents to the given CharArrayBuffer.
+ * Body contents include the member body and any trailing whitespace.
+ *
+ * DOMNode
's end position.
+ */
+void normalizeEndPosition(ILineStartFinder finder, DOMNode next) {
+ if (next == null) {
+ // this node's end position includes all of the characters up
+ // to the end of the enclosing node
+ DOMNode parent = (DOMNode) getParent();
+ if (parent == null || parent instanceof DOMCompilationUnit) {
+ setSourceRangeEnd(fDocument.length - 1);
+ } else {
+ // parent is a type
+ int temp = ((DOMType)parent).getCloseBodyPosition() - 1;
+ setSourceRangeEnd(temp);
+ fInsertionPosition = Math.max(finder.getLineStart(temp + 1), getEndPosition());
+ }
+ } else {
+ // this node's end position is just before the start of the next node
+ // unless the next node is a field that is declared along with this one
+ int temp = next.getStartPosition() - 1;
+ fInsertionPosition = Math.max(finder.getLineStart(temp + 1), getEndPosition());
+
+ next.normalizeStartPosition(getEndPosition(), finder);
+ if (next instanceof DOMField) {
+ DOMField field = (DOMField) next;
+ if (field.isVariableDeclarator() && fTypeRange[0] == field.fTypeRange[0])
+ return;
+ }
+ setSourceRangeEnd(next.getStartPosition() - 1);
+ }
+}
+/**
+ * Normalizes this DOMNode
's start position.
+ */
+void normalizeStartPosition(int endPosition, ILineStartFinder finder) {
+ if (isVariableDeclarator()) {
+ // start position is end of last element
+ setStartPosition(fPreviousNode.getEndPosition() + 1);
+ } else {
+ super.normalizeStartPosition(endPosition, finder);
+ }
+}
+/**
+ * Offsets all the source indexes in this node by the given amount.
+ */
+protected void offset(int offset) {
+ super.offset(offset);
+ offsetRange(fInitializerRange, offset);
+ offsetRange(fTypeRange, offset);
+}
+/**
+ * Separates this node from its parent and siblings, maintaining any ties that
+ * this node has to the underlying document fragment.
+ *
+ * null
if this node does not have a name
+ * @param nameRange - a two element array of integers describing the
+ * entire inclusive source range of this node's name within its document,
+ * including any array qualifiers that might immediately follow the name
+ * or -1's if this node does not have a name.
+ * @param onDemand - indicates if this import is an on demand style import
+ */
+DOMImport(char[] document, int[] sourceRange, String name, int[] nameRange, boolean onDemand) {
+ super(document, sourceRange, name, nameRange);
+ fOnDemand = onDemand;
+ setMask(MASK_DETAILED_SOURCE_INDEXES, true);
+}
+/**
+ * Creates a new simple IMPORT document fragment on the given range of the document.
+ *
+ * @param document - the document containing this node's original contents
+ * @param sourceRange - a two element array of integers describing the
+ * entire inclusive source range of this node within its document.
+ * Contents start on and include the character at the first position.
+ * Contents end on and include the character at the last position.
+ * An array of -1's indicates this node's contents do not exist
+ * in the document.
+ * @param name - the identifier portion of the name of this node, or
+ * null
if this node does not have a name
+ * @param onDemand - indicates if this import is an on demand style import
+ */
+DOMImport(char[] document, int[] sourceRange, String name, boolean onDemand) {
+ this(document, sourceRange, name, new int[] {-1, -1}, onDemand);
+ fOnDemand = onDemand;
+ setMask(MASK_DETAILED_SOURCE_INDEXES, false);
+}
+/**
+ * @see DOMNode#appendFragmentedContents(CharArrayBuffer)
+ */
+protected void appendFragmentedContents(CharArrayBuffer buffer) {
+ if (fNameRange[0] < 0) {
+ buffer
+ .append("import ") //$NON-NLS-1$
+ .append(fName)
+ .append(';')
+ .append(Util.LINE_SEPARATOR);
+ } else {
+ buffer.append(fDocument, fSourceRange[0], fNameRange[0] - fSourceRange[0]);
+ //buffer.append(fDocument, fNameRange[0], fNameRange[1] - fNameRange[0] + 1);
+ buffer.append(fName);
+ buffer.append(fDocument, fNameRange[1] + 1, fSourceRange[1] - fNameRange[1]);
+ }
+}
+/**
+ * @see IDOMNode#getContents()
+ */
+public String getContents() {
+ if (fName == null) {
+ return null;
+ } else {
+ return super.getContents();
+ }
+}
+/**
+ * @see DOMNode#getDetailedNode()
+ */
+//protected DOMNode getDetailedNode() {
+// return (DOMNode)getFactory().createImport(getContents());
+//}
+/**
+ * @see IDOMNode#getJavaElement
+ */
+public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException {
+// if (parent.getElementType() == IJavaElement.COMPILATION_UNIT) {
+// return ((ICompilationUnit)parent).getImport(getName());
+// } else {
+ throw new IllegalArgumentException(Util.bind("element.illegalParent")); //$NON-NLS-1$
+// }
+}
+/**
+ * @see IDOMNode#getNodeType()
+ */
+public int getNodeType() {
+ return IDOMNode.IMPORT;
+}
+/**
+ * @see IDOMImport#isOnDemand()
+ */
+public boolean isOnDemand() {
+ return fOnDemand;
+}
+/**
+ * @see DOMNode
+ */
+protected DOMNode newDOMNode() {
+ return new DOMImport();
+}
+/**
+ * @see IDOMNode#setName(char[])
+ */
+public void setName(String name) {
+ if (name == null) {
+ throw new IllegalArgumentException(Util.bind("element.nullName")); //$NON-NLS-1$
+ }
+ becomeDetailed();
+ super.setName(name);
+ fOnDemand = name.endsWith(".*"); //$NON-NLS-1$
+}
+/**
+ * @see IDOMNode#toString()
+ */
+public String toString() {
+ return "IMPORT: " + getName(); //$NON-NLS-1$
+}
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMInitializer.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMInitializer.java
new file mode 100644
index 0000000..314ee35
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMInitializer.java
@@ -0,0 +1,229 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core.jdom;
+
+import net.sourceforge.phpdt.core.IJavaElement;
+import net.sourceforge.phpdt.core.IType;
+import net.sourceforge.phpdt.core.jdom.IDOMInitializer;
+import net.sourceforge.phpdt.core.jdom.IDOMNode;
+import net.sourceforge.phpdt.internal.compiler.util.Util;
+import net.sourceforge.phpdt.internal.core.util.CharArrayBuffer;
+import net.sourceforge.phpdt.internal.core.util.CharArrayOps;
+
+/**
+ * DOMInitializer provides an implementation of IDOMInitializer.
+ *
+ * @see IDOMInitializer
+ * @see DOMNode
+ */
+class DOMInitializer extends DOMMember implements IDOMInitializer {
+
+ /**
+ * The contents of the initializer's body when the
+ * body has been altered from the contents in the
+ * document, otherwise null
.
+ */
+ protected String fBody;
+
+ /**
+ * The original inclusive source range of the
+ * body in the document.
+ */
+ protected int[] fBodyRange;
+
+/**
+ * Constructs an empty initializer node.
+ */
+DOMInitializer() {
+
+}
+/**
+ * Creates a new detailed INITIALIZER document fragment on the given range of the document.
+ *
+ * @param document - the document containing this node's original contents
+ * @param sourceRange - a two element array of integers describing the
+ * entire inclusive source range of this node within its document.
+ * Contents start on and include the character at the first position.
+ * Contents end on and include the character at the last position.
+ * An array of -1's indicates this node's contents do not exist
+ * in the document.
+ * @param commentRange - a two element array describing the comments that precede
+ * the member declaration. The first matches the start of this node's
+ * sourceRange, and the second is the new-line or first non-whitespace
+ * character following the last comment. If no comments are present,
+ * this array contains two -1's.
+ * @param flags - an integer representing the modifiers for this member. The
+ * integer can be analyzed with org.eclipse.jdt.core.Flags
+ * @param modifierRange - a two element array describing the location of
+ * modifiers for this member within its source range. The first integer
+ * is the first character of the first modifier for this member, and
+ * the second integer is the last whitespace character preceeding the
+ * next part of this member declaration. If there are no modifiers present
+ * in this node's source code (that is, package default visibility), this array
+ * contains two -1's.
+ * @param bodyStartPosition - the position of the open brace of the body
+ * of this initialzer.
+ */
+DOMInitializer(char[] document, int[] sourceRange, int[] commentRange, int flags, int[] modifierRange, int bodyStartPosition) {
+ super(document, sourceRange, null, new int[]{-1, -1}, commentRange, flags, modifierRange);
+ fBodyRange= new int[2];
+ fBodyRange[0]= bodyStartPosition;
+ fBodyRange[1]= sourceRange[1];
+ setHasBody(true);
+ setMask(MASK_DETAILED_SOURCE_INDEXES, true);
+}
+/**
+ * Creates a new simple INITIALIZER document fragment on the given range of the document.
+ *
+ * @param document - the document containing this node's original contents
+ * @param sourceRange - a two element array of integers describing the
+ * entire inclusive source range of this node within its document.
+ * Contents start on and include the character at the first position.
+ * Contents end on and include the character at the last position.
+ * An array of -1's indicates this node's contents do not exist
+ * in the document.
+ * @param flags - an integer representing the modifiers for this member. The
+ * integer can be analyzed with org.eclipse.jdt.core.Flags
+ */
+DOMInitializer(char[] document, int[] sourceRange, int flags) {
+ this(document, sourceRange, new int[] {-1, -1}, flags, new int[] {-1, -1}, -1);
+ setMask(MASK_DETAILED_SOURCE_INDEXES, false);
+
+}
+/**
+ * @see DOMMember#appendMemberBodyContents(CharArrayBuffer)
+ */
+protected void appendMemberBodyContents(CharArrayBuffer buffer) {
+ if (hasBody()) {
+ buffer
+ .append(getBody())
+ .append(fDocument, fBodyRange[1] + 1, fSourceRange[1] - fBodyRange[1]);
+ } else {
+ buffer.append("{}").append(Util.LINE_SEPARATOR); //$NON-NLS-1$
+ }
+}
+/**
+ * @see DOMMember#appendMemberDeclarationContents(CharArrayBuffer)
+ */
+protected void appendMemberDeclarationContents(CharArrayBuffer buffer) {}
+/**
+ * @see DOMNode#appendSimpleContents(CharArrayBuffer)
+ */
+protected void appendSimpleContents(CharArrayBuffer buffer) {
+ // append eveything before my name
+ buffer.append(fDocument, fSourceRange[0], fNameRange[0] - fSourceRange[0]);
+ // append my name
+ buffer.append(fName);
+ // append everything after my name
+ buffer.append(fDocument, fNameRange[1] + 1, fSourceRange[1] - fNameRange[1]);
+}
+/**
+ * @see IDOMInitializer#getBody()
+ */
+public String getBody() {
+ becomeDetailed();
+ if (hasBody()) {
+ if (fBody != null) {
+ return fBody;
+ } else {
+ return CharArrayOps.substring(fDocument, fBodyRange[0], fBodyRange[1] + 1 - fBodyRange[0]);
+ }
+ } else {
+ return null;
+ }
+}
+/**
+ * @see DOMNode#getDetailedNode()
+ */
+//protected DOMNode getDetailedNode() {
+// return (DOMNode)getFactory().createInitializer(getContents());
+//}
+/**
+ * @see IDOMNode#getJavaElement
+ */
+public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException {
+// if (parent.getElementType() == IJavaElement.TYPE) {
+// int count = 1;
+// IDOMNode previousNode = getPreviousNode();
+// while (previousNode != null) {
+// if (previousNode instanceof DOMInitializer) {
+// count++;
+// }
+// previousNode = previousNode.getPreviousNode();
+// }
+// return ((IType) parent).getInitializer(count);
+// } else {
+ throw new IllegalArgumentException(Util.bind("element.illegalParent")); //$NON-NLS-1$
+// }
+}
+/**
+ * @see DOMMember#getMemberDeclarationStartPosition()
+ */
+protected int getMemberDeclarationStartPosition() {
+ return fBodyRange[0];
+}
+/**
+ * @see IDOMNode#getNodeType()
+ */
+public int getNodeType() {
+ return IDOMNode.INITIALIZER;
+}
+/**
+ * @see IDOMNode#isSigantureEqual(IDOMNode).
+ *
+ * null
.
+ */
+ protected String fComment= null;
+
+ /**
+ * The original inclusive source range of the
+ * member's preceding comments in the document,
+ * or -1's if the member did not originally have a
+ * comment.
+ */
+ protected int[] fCommentRange;
+
+
+ /**
+ * The member's modifiers textual representation when
+ * the modifiers (flags) have been altered from
+ * their original contents, otherwise null
.
+ */
+ protected char[] fModifiers= null;
+
+ /**
+ * The original inclusive source range of the
+ * member's modifiers in the document, or -1's if
+ * the member did not originally have modifiers in
+ * the source code (that is, package default visibility).
+ */
+ protected int[] fModifierRange;
+
+/**
+ * Constructs an empty member node.
+ */
+DOMMember() {
+
+}
+/**
+ * Creates a new member document fragment on the given range of the document.
+ *
+ * @param document - the document containing this node's original contents
+ * @param sourceRange - a two element array of integers describing the
+ * entire inclusive source range of this node within its document.
+ * Contents start on and include the character at the first position.
+ * Contents end on and include the character at the last position.
+ * An array of -1's indicates this node's contents do not exist
+ * in the document.
+ * @param name - the identifier portion of the name of this node, or
+ * null
if this node does not have a name
+ * @param nameRange - a two element array of integers describing the
+ * entire inclusive source range of this node's name within its document,
+ * including any array qualifiers that might immediately follow the name.
+ * @param commentRange - a two element array describing the comments that precede
+ * the member declaration. The first matches the start of this node's
+ * sourceRange, and the second is the new-line or first non-whitespace
+ * character following the last comment. If no comments are present,
+ * this array contains two -1's.
+ * @param flags - an integer representing the modifiers for this member. The
+ * integer can be analyzed with org.eclipse.jdt.core.Flags
+ * @param modifierRange - a two element array describing the location of
+ * modifiers for this member within its source range. The first integer
+ * is the first character of the first modifier for this member, and
+ * the second integer is the last whitespace character preceeding the
+ * next part of this member declaration. If there are no modifiers present
+ * in this node's source code (that is, package default visibility), this array
+ * contains two -1's.
+ */
+DOMMember(char[] document, int[] sourceRange, String name, int[] nameRange, int[] commentRange, int flags, int[] modifierRange) {
+ super(document, sourceRange, name, nameRange);
+ fFlags= flags;
+ fComment= null;
+ fCommentRange= commentRange;
+ fModifierRange= modifierRange;
+ setHasComment(commentRange[0] >= 0);
+}
+/**
+ * Appends the contents of this node to the given CharArrayBuffer, using
+ * the original document and indicies as a form for the current attribute values
+ * of this node.
+ *
+ * String
describing the modifiers for this member,
+ * ending with whitespace (if not empty). This value serves as a replacement
+ * value for the member's modifier range when the modifiers have been altered
+ * from their original contents.
+ */
+protected char[] generateFlags() {
+ char[] flags= Flags.toString(getFlags()).toCharArray();
+ if (flags.length == 0) {
+ return flags;
+ } else {
+ return CharArrayOps.concat(flags, new char[] {' '});
+ }
+}
+/**
+ * @see IDOMMember#getComment()
+ */
+public String getComment() {
+ becomeDetailed();
+ if (hasComment()) {
+ if (fComment != null) {
+ return fComment;
+ } else {
+ return CharArrayOps.substring(fDocument, fCommentRange[0], fCommentRange[1] + 1 - fCommentRange[0]);
+ }
+ } else {
+ return null;
+ }
+}
+/**
+ * @see IDOMMember#getFlags()
+ */
+public int getFlags() {
+ return fFlags;
+}
+/**
+ * Returns the location of the first character in the member's declaration
+ * section.
+ *
+ * @see DOMMember#getMemberDeclarationContents()
+ * @see DOMMember#getFragmentedContents()
+ */
+protected abstract int getMemberDeclarationStartPosition();
+/**
+ * Returns the String to be used for this member's flags when
+ * generating contents - either the original contents in the document
+ * or the replacement value.
+ */
+protected char[] getModifiersText() {
+ if (fModifiers == null) {
+ if (fModifierRange[0] < 0) {
+ return null;
+ } else {
+ return CharArrayOps.subarray(fDocument, fModifierRange[0], fModifierRange[1] + 1 - fModifierRange[0]);
+ }
+ } else {
+ return fModifiers;
+ }
+}
+/**
+ * Returns true if this member currently has a body.
+ */
+protected boolean hasBody() {
+ return getMask(MASK_HAS_BODY);
+}
+/**
+ * Returns true if this member currently has a comment.
+ */
+protected boolean hasComment() {
+ return getMask(MASK_HAS_COMMENT);
+}
+/**
+ * Offsets all the source indexes in this node by the given amount.
+ */
+protected void offset(int offset) {
+ super.offset(offset);
+ offsetRange(fCommentRange, offset);
+ offsetRange(fModifierRange, offset);
+}
+/**
+ * @see IDOMMember#setComment(String)
+ */
+public void setComment(String comment) {
+ becomeDetailed();
+ fComment= comment;
+ fragment();
+ setHasComment(comment != null);
+ /* see 1FVIJAH */
+ if (comment != null) {
+ String commentString = new String(comment);
+ if (commentString.indexOf("@deprecated") >= 0) { //$NON-NLS-1$
+ fFlags= fFlags | IConstants.AccDeprecated;
+ return;
+ }
+
+ }
+ fFlags= fFlags & (~IConstants.AccDeprecated);
+
+}
+/**
+ * @see IDOMMember#setFlags(int)
+ */
+public void setFlags(int flags) {
+ becomeDetailed();
+ if (Flags.isDeprecated(fFlags)) {
+ fFlags= flags | IConstants.AccDeprecated;
+ } else {
+ fFlags= flags & (~IConstants.AccDeprecated);
+ }
+ fragment();
+ fModifiers= generateFlags();
+}
+/**
+ * Sets the state of this member declaration as having
+ * a body.
+ */
+protected void setHasBody(boolean hasBody) {
+ setMask(MASK_HAS_BODY, hasBody);
+}
+/**
+ * Sets the state of this member declaration as having
+ * a preceding comment.
+ */
+protected void setHasComment(boolean hasComment) {
+ setMask(MASK_HAS_COMMENT, hasComment);
+}
+/**
+ * Sets the original position of the first character of this node's contents
+ * in its document. This method is only used during DOM creation while
+ * normalizing the source range of each node.
+ *
+ * Synchronize the start of the comment position with the start of the
+ * node.
+ */
+protected void setStartPosition(int start) {
+ if (fCommentRange[0] >= 0) {
+ fCommentRange[0]= start;
+ }
+ super.setStartPosition(start);
+}
+/**
+ * @see DOMNode#shareContents(DOMNode)
+ */
+protected void shareContents(DOMNode node) {
+ super.shareContents(node);
+ DOMMember member= (DOMMember)node;
+ fComment= member.fComment;
+ fCommentRange= rangeCopy(member.fCommentRange);
+ fFlags= member.fFlags;
+ fModifiers= member.fModifiers;
+ fModifierRange= rangeCopy(member.fModifierRange);
+}
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMMethod.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMMethod.java
new file mode 100644
index 0000000..3221fdf
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMMethod.java
@@ -0,0 +1,718 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core.jdom;
+
+import net.sourceforge.phpdt.core.IJavaElement;
+import net.sourceforge.phpdt.core.IType;
+import net.sourceforge.phpdt.core.Signature;
+import net.sourceforge.phpdt.core.jdom.IDOMMethod;
+import net.sourceforge.phpdt.core.jdom.IDOMNode;
+import net.sourceforge.phpdt.internal.compiler.util.Util;
+import net.sourceforge.phpdt.internal.core.util.CharArrayBuffer;
+import net.sourceforge.phpdt.internal.core.util.CharArrayOps;
+
+/**
+ * DOMMethod provides an implementation of IDOMMethod.
+ *
+ * @see IDOMMethod
+ * @see DOMNode
+ */
+
+class DOMMethod extends DOMMember implements IDOMMethod {
+
+ /**
+ * Contains the return type of the method when the
+ * return type has been altered from the contents
+ * in the document, otherwise null
.
+ */
+ protected String fReturnType;
+
+ /**
+ * The original inclusive source range of the
+ * method's return type in the document, or -1's
+ * if no return type is present in the document.
+ * If the return type of this method is qualified with
+ * '[]' following the parameter list, this array has
+ * four entries. In this case, the last two entries
+ * of the array are the inclusive source range of
+ * the array qualifiers.
+ */
+ protected int[] fReturnTypeRange;
+
+ /**
+ * Contains the textual representation of the method's
+ * parameter list, including open and closing parentheses
+ * when the parameters had been altered from the contents
+ * in the document, otherwise null
.
+ */
+ protected char[] fParameterList;
+
+ /**
+ * The original inclusive source range of the
+ * method's parameter list in the document.
+ */
+ protected int[] fParameterRange;
+
+ /**
+ * Contains the textual representation of the method's
+ * exception list when the exceptions had been altered
+ * from the contents in the document, otherwise
+ * null
. The exception list is a comment
+ * delimited list of exceptions, not including the "throws"
+ * keyword.
+ */
+ protected char[] fExceptionList;
+
+ /**
+ * The original inclusive source range of the
+ * method's exception list in the document.
+ */
+ protected int[] fExceptionRange;
+
+ /**
+ * Contains the method's body when the body has
+ * been altered from the contents in the document,
+ * otherwise null
. The body includes everything
+ * between and including the enclosing braces, and trailing
+ * whitespace.
+ */
+ protected String fBody;
+
+ /**
+ * The original inclusive source range of the
+ * method's body.
+ */
+ protected int[] fBodyRange;
+
+
+ /**
+ * Names of parameters in the method parameter list,
+ * or null
if the method has no parameters.
+ */
+ protected String[] fParameterNames;
+
+ /**
+ * Types of parameters in the method parameter list,
+ * or null
if the method has no parameters.
+ */
+ protected String[] fParameterTypes;
+
+ /**
+ * The exceptions the method throws, or null
+ * if the method throws no exceptions.
+ */
+ protected String[] fExceptions;
+
+
+/**
+ * Constructs an empty method node.
+ */
+DOMMethod() {
+
+}
+/**
+ * Creates a new detailed METHOD document fragment on the given range of the document.
+ *
+ * @param document - the document containing this node's original contents
+ * @param sourceRange - a two element array of integers describing the
+ * entire inclusive source range of this node within its document.
+ * Contents start on and include the character at the first position.
+ * Contents end on and include the character at the last position.
+ * An array of -1's indicates this node's contents do not exist
+ * in the document.
+ * @param name - the identifier portion of the name of this node, or
+ * null
if this node does not have a name
+ * @param nameRange - a two element array of integers describing the
+ * entire inclusive source range of this node's name within its document,
+ * including any array qualifiers that might immediately follow the name
+ * or -1's if this node does not have a name.
+ * @param commentRange - a two element array describing the comments that precede
+ * the member declaration. The first matches the start of this node's
+ * sourceRange, and the second is the new-line or first non-whitespace
+ * character following the last comment. If no comments are present,
+ * this array contains two -1's.
+ * @param flags - an integer representing the modifiers for this member. The
+ * integer can be analyzed with org.eclipse.jdt.core.Flags
+ * @param modifierRange - a two element array describing the location of
+ * modifiers for this member within its source range. The first integer
+ * is the first character of the first modifier for this member, and
+ * the second integer is the last whitespace character preceeding the
+ * next part of this member declaration. If there are no modifiers present
+ * in this node's source code (that is, package default visibility), this array
+ * contains two -1's.
+ * @param isConstructor - true if the method is a contructor, otherwise false
+ * @param returnType - the normalized return type of this method
+ * @param returnTypeRange - a two element array describing the location of the
+ * return type within the method's source range. The first integer is is
+ * the position of the first character in the return type, and the second
+ * integer is the position of the last character in the return type.
+ * For constructors, the contents of this array are -1's.
+ * If the return type of this method is qualified with '[]' following the
+ * parameter list, this array has four entries. In this case, the last
+ * two entries of the array are the inclusive source range of the array
+ * qualifiers.
+ * @param parameterTypes - an array of parameter types in the method declaration
+ * or null
if the method has no parameters
+ * @param parameterNames - an array of parameter names in the method declaration
+ * or null
if the method has no parameters
+ * @param parameterRange - a two element array describing the location of the
+ * parameter list in the method. The first integer is the location of the
+ * open parenthesis and the second integer is the location of the closing
+ * parenthesis.
+ * @param exceptions - an array of the names of exceptions thrown by this method
+ * or null
if the method throws no exceptions
+ * @param exceptionRange - a two element array describing the location of the
+ * exception list in the method declaration. The first integer is the position
+ * of the first character in the first exception the method throws, and the
+ * second integer is the position of the last character of the last exception
+ * this method throws.
+ * @param bodyRange - a two element array describing the location of the method's body.
+ * The first integer is the first character following the method's
+ * parameter list, or exception list (if present). The second integer is the location
+ * of the last character in the method's source range.
+ */
+DOMMethod(char[] document, int[] sourceRange, String name, int[] nameRange, int[] commentRange, int flags, int[] modifierRange, boolean isConstructor, String returnType, int[] returnTypeRange, String[] parameterTypes, String[] parameterNames, int[] parameterRange, String[] exceptions, int[] exceptionRange, int[] bodyRange) {
+ super(document, sourceRange, name, nameRange, commentRange, flags, modifierRange);
+
+ setMask(MASK_IS_CONSTRUCTOR, isConstructor);
+ fReturnType= returnType;
+ fReturnTypeRange= returnTypeRange;
+ fParameterTypes= parameterTypes;
+ fParameterNames= parameterNames;
+ fParameterRange= parameterRange;
+ fExceptionRange= exceptionRange;
+ fExceptions= exceptions;
+ setHasBody(true);
+ fBodyRange= bodyRange;
+ setMask(MASK_DETAILED_SOURCE_INDEXES, true);
+
+}
+/**
+ * Creates a new simple METHOD document fragment on the given range of the document.
+ *
+ * @param document - the document containing this node's original contents
+ * @param sourceRange - a two element array of integers describing the
+ * entire inclusive source range of this node within its document.
+ * Contents start on and include the character at the first position.
+ * Contents end on and include the character at the last position.
+ * An array of -1's indicates this node's contents do not exist
+ * in the document.
+ * @param name - the identifier portion of the name of this node, or
+ * null
if this node does not have a name
+ * @param nameRange - a two element array of integers describing the
+ * entire inclusive source range of this node's name within its document,
+ * including any array qualifiers that might immediately follow the name
+ * or -1's if this node does not have a name.
+ * @param flags - an integer representing the modifiers for this member. The
+ * integer can be analyzed with org.eclipse.jdt.core.Flags
+ * @param isConstructor - true if the method is a contructor, otherwise false
+ * @param returnType - the normalized return type of this method
+ * @param parameterTypes - an array of parameter types in the method declaration
+ * or null
if the method has no parameters
+ * @param parameterNames - an array of parameter names in the method declaration
+ * or null
if the method has no parameters
+ * @param exceptions - an array of the names of exceptions thrown by this method
+ * or null
if the method throws no exceptions
+ */
+DOMMethod(char[] document, int[] sourceRange, String name, int[] nameRange, int flags, boolean isConstructor, String returnType, String[] parameterTypes, String[] parameterNames, String[] exceptions) {
+ this(document, sourceRange, name, nameRange, new int[] {-1, -1}, flags, new int[] {-1, -1}, isConstructor, returnType, new int[] {-1, -1}, parameterTypes, parameterNames, new int[] {-1, -1}, exceptions, new int[] {-1, -1}, new int[] {-1, -1});
+ setMask(MASK_DETAILED_SOURCE_INDEXES, false);
+}
+/**
+ * @see IDOMMethod#addException(String)
+ */
+public void addException(String name) throws IllegalArgumentException {
+ if (name == null) {
+ throw new IllegalArgumentException(Util.bind("dom.nullExceptionType")); //$NON-NLS-1$
+ }
+ if (fExceptions == null) {
+ fExceptions= new String[1];
+ fExceptions[0]= name;
+ } else {
+ fExceptions= appendString(fExceptions, name);
+ }
+ setExceptions(fExceptions);
+}
+/**
+ * @see IDOMMethod#addParameter(String, String)
+ */
+public void addParameter(String type, String name) throws IllegalArgumentException {
+ if (type == null) {
+ throw new IllegalArgumentException(Util.bind("dom.nullTypeParameter")); //$NON-NLS-1$
+ }
+ if (name == null) {
+ throw new IllegalArgumentException(Util.bind("dom.nullNameParameter")); //$NON-NLS-1$
+ }
+ if (fParameterNames == null) {
+ fParameterNames= new String[1];
+ fParameterNames[0]= name;
+ } else {
+ fParameterNames= appendString(fParameterNames, name);
+ }
+ if (fParameterTypes == null) {
+ fParameterTypes= new String[1];
+ fParameterTypes[0]= type;
+ } else {
+ fParameterTypes= appendString(fParameterTypes, type);
+ }
+ setParameters(fParameterTypes, fParameterNames);
+}
+/**
+ * @see DOMMember#appendMemberBodyContents(CharArrayBuffer)
+ */
+protected void appendMemberBodyContents(CharArrayBuffer buffer) {
+ if (fBody != null) {
+ buffer.append(fBody);
+ } else {
+ buffer.append(fDocument, fBodyRange[0], fBodyRange[1] + 1 - fBodyRange[0]);
+ }
+}
+/**
+ * @see DOMMember#appendMemberDeclarationContents(CharArrayBuffer)
+ */
+protected void appendMemberDeclarationContents(CharArrayBuffer buffer) {
+
+ if (isConstructor()) {
+ buffer
+ .append(getConstructorName())
+ .append(fDocument, fNameRange[1] + 1, fParameterRange[0] - fNameRange[1] - 1);
+ } else {
+ buffer.append(getReturnTypeContents());
+ if (fReturnTypeRange[0] >= 0) {
+ buffer.append(fDocument, fReturnTypeRange[1] + 1, fNameRange[0] - fReturnTypeRange[1] - 1);
+ } else {
+ buffer.append(' ');
+ }
+ buffer
+ .append(getNameContents())
+ .append(fDocument, fNameRange[1] + 1, fParameterRange[0] - fNameRange[1] - 1);
+ }
+ if (fParameterList != null) {
+ buffer.append(fParameterList);
+ } else {
+ buffer.append(fDocument, fParameterRange[0], fParameterRange[1] + 1 - fParameterRange[0]);
+ }
+ int start;
+ if (hasTrailingArrayQualifier() && isReturnTypeAltered()) {
+ start= fReturnTypeRange[3] + 1;
+ } else {
+ start= fParameterRange[1] + 1;
+ }
+ if (fExceptions != null) {
+ // add 'throws' keyword
+ if (fExceptionRange[0] >= 0) {
+ buffer.append(fDocument, start, fExceptionRange[0] - start);
+ } else {
+ buffer.append(" throws "); //$NON-NLS-1$
+ }
+ // add exception list
+ if (fExceptionList != null) {
+ buffer.append(fExceptionList);
+ // add space before body
+ if (fExceptionRange[0] >= 0) {
+ buffer.append(fDocument, fExceptionRange[1] + 1, fBodyRange[0] - fExceptionRange[1] - 1);
+ } else {
+ buffer.append(fDocument, fParameterRange[1] + 1, fBodyRange[0] - fParameterRange[1] - 1);
+ }
+ } else {
+ // add list and space before body
+ buffer.append(fDocument, fExceptionRange[0], fBodyRange[0] - fExceptionRange[0]);
+ }
+ } else {
+ // add space before body
+ if (fExceptionRange[0] >= 0) {
+ buffer.append(fDocument, fExceptionRange[1] + 1, fBodyRange[0] - fExceptionRange[1] - 1);
+ } else {
+ buffer.append(fDocument, start, fBodyRange[0] - start);
+ }
+ }
+
+}
+/**
+ * @see DOMNode#appendSimpleContents(CharArrayBuffer)
+ */
+protected void appendSimpleContents(CharArrayBuffer buffer) {
+ // append eveything before my name
+ buffer.append(fDocument, fSourceRange[0], fNameRange[0] - fSourceRange[0]);
+ // append my name
+ if (isConstructor()) {
+ buffer.append(getConstructorName());
+ } else {
+ buffer.append(fName);
+ }
+ // append everything after my name
+ buffer.append(fDocument, fNameRange[1] + 1, fSourceRange[1] - fNameRange[1]);
+}
+/**
+ * @see IDOMMethod#getBody()
+ */
+public String getBody() {
+ becomeDetailed();
+ if (hasBody()) {
+ if (fBody != null) {
+ return fBody;
+ } else {
+ return CharArrayOps.substring(fDocument, fBodyRange[0], fBodyRange[1] + 1 - fBodyRange[0]);
+ }
+ } else {
+ return null;
+ }
+}
+/**
+ * Returns the simple name of the enclsoing type for this constructor.
+ * If the constuctor is not currently enclosed in a type, the original
+ * name of the constructor as found in the documnent is returned.
+ */
+protected String getConstructorName() {
+
+ if (isConstructor()) {
+ if (getParent() != null) {
+ return getParent().getName();
+ } else {
+ // If there is no parent use the original name
+ return new String(getNameContents());
+ }
+ } else {
+ return null;
+ }
+
+}
+/**
+ * @see DOMNode#getDetailedNode()
+ */
+//protected DOMNode getDetailedNode() {
+// return (DOMNode)getFactory().createMethod(getContents());
+//}
+/**
+ * @see IDOMMethod#getExceptions()
+ */
+public String[] getExceptions() {
+ return fExceptions;
+}
+/**
+ * @see IDOMNode#getJavaElement
+ */
+public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException {
+ if (parent.getElementType() == IJavaElement.TYPE) {
+ // translate parameter types to signatures
+ String[] sigs= null;
+ if (fParameterTypes != null) {
+ sigs= new String[fParameterTypes.length];
+ int i;
+ for (i= 0; i < fParameterTypes.length; i++) {
+ sigs[i]= Signature.createTypeSignature(fParameterTypes[i].toCharArray(), false);
+ }
+ }
+ String name= null;
+ if (isConstructor()) {
+ name= getConstructorName();
+ } else {
+ name= getName();
+ }
+ return ((IType)parent).getMethod(name, sigs);
+ } else {
+ throw new IllegalArgumentException(Util.bind("element.illegalParent")); //$NON-NLS-1$
+ }
+}
+/**
+ * @see DOMMember#getMemberDeclarationStartPosition()
+ */
+protected int getMemberDeclarationStartPosition() {
+ if (fReturnTypeRange[0] >= 0) {
+ return fReturnTypeRange[0];
+ } else {
+ return fNameRange[0];
+ }
+}
+/**
+ * @see IDOMNode#getName()
+ */
+public String getName() {
+ if (isConstructor()) {
+ return null;
+ } else {
+ return super.getName();
+ }
+}
+/**
+ * @see IDOMNode#getNodeType()
+ */
+public int getNodeType() {
+ return IDOMNode.METHOD;
+}
+/**
+ * @see IDOMMethod#getParameterNames()
+ */
+public String[] getParameterNames() {
+ return fParameterNames;
+}
+/**
+ * @see IDOMMethod#getParameterTypes()
+ */
+public String[] getParameterTypes() {
+ return fParameterTypes;
+}
+/**
+ * @see IDOMMethod#getReturnType()
+ */
+public String getReturnType() {
+ if (isConstructor()) {
+ return null;
+ } else {
+ return fReturnType;
+ }
+}
+/**
+ * Returns the source code to be used for this method's return type
+ */
+protected char[] getReturnTypeContents() {
+ if (isConstructor()) {
+ return null;
+ } else {
+ if (isReturnTypeAltered()) {
+ return fReturnType.toCharArray();
+ } else {
+ return CharArrayOps.subarray(fDocument, fReturnTypeRange[0], fReturnTypeRange[1] + 1 - fReturnTypeRange[0]);
+ }
+
+ }
+}
+/**
+ * Returns true if this method's return type has
+ * array qualifiers ('[]') following the parameter list.
+ */
+protected boolean hasTrailingArrayQualifier() {
+ return fReturnTypeRange.length > 2;
+}
+/**
+ * @see IDOMMethod#isConstructor()
+ */
+public boolean isConstructor() {
+ return getMask(MASK_IS_CONSTRUCTOR);
+}
+/**
+ * Returns true if this method's return type has been altered
+ * from the original document contents.
+ */
+protected boolean isReturnTypeAltered() {
+ return getMask(MASK_RETURN_TYPE_ALTERED);
+}
+/**
+ * @see IDOMNode#isSigantureEqual(IDOMNode).
+ *
+ * IDOMNode
.
+ *
+ * null
+ * when this node has no children. (Children of a node
+ * are implemented as a doubly linked list).
+ */
+ protected DOMNode fFirstChild= null;
+
+ /**
+ * The last child of this node - null
+ * when this node has no children. Used for efficient
+ * access to the last child when adding new children
+ * at the end of the linked list of children.
+ */
+ protected DOMNode fLastChild= null;
+
+ /**
+ * The sibling node following this node - null
+ * for the last node in the sibling list.
+ */
+ protected DOMNode fNextNode= null;
+
+ /**
+ * The parent of this node. A null
+ * parent indicates that this node is a root
+ * node of a document fragment.
+ */
+ protected DOMNode fParent= null;
+
+ /**
+ * The sibling node preceding this node - null
+ * for the first node in the sibling list.
+ */
+ protected DOMNode fPreviousNode= null;
+
+ /**
+ * True when this node has attributes that have
+ * been altered from their original state in the
+ * shared document, or when the attributes of a
+ * descendant have been altered. False when the
+ * contents of this node and all descendants are
+ * consistent with the content of the shared
+ * document.
+ */
+ protected boolean fIsFragmented= false;
+
+ /**
+ * The name of this node. For efficiency, the
+ * name of a node is duplicated in this variable
+ * on creation, rather than always having to fetch
+ * the name from the shared document.
+ */
+ protected String fName= null;
+
+ /**
+ * The original inclusive indicies of this node's name in
+ * the shared document. Values of -1 indiciate the name
+ * does not exist in the document.
+ */
+ protected int[] fNameRange;
+
+ /**
+ * The shared document that the contents for this node
+ * are contained in. Attribute indicies are positions
+ * in this character array.
+ */
+ protected char[] fDocument= null;
+
+ /**
+ * The original entire inclusive range of this node's contents
+ * within its document. Values of -1 indicate the contents
+ * of this node do not exist in the document.
+ */
+ protected int[] fSourceRange;
+
+ /**
+ * The current state of bit masks defined by this node.
+ * Initially all bit flags are turned off. All bit masks
+ * are defined by this class to avoid overlap, although
+ * bit masks are node type specific.
+ *
+ * @see #setMask
+ * @see #getMask
+ */
+ protected int fStateMask= 0;
+
+ /**
+ * This position is the position of the end of the last line separator before the closing brace starting
+ * position of the receiver.
+ */
+ protected int fInsertionPosition;
+
+ /**
+ * A bit mask indicating this field has an initializer
+ * expression
+ */
+ protected static final int MASK_FIELD_HAS_INITIALIZER= 0x00000001;
+
+ /**
+ * A bit mask indicating this field is a secondary variable
+ * declarator for a previous field declaration.
+ */
+ protected static final int MASK_FIELD_IS_VARIABLE_DECLARATOR= 0x00000002;
+
+ /**
+ * A bit mask indicating this field's type has been
+ * altered from its original contents in the document.
+ */
+ protected static final int MASK_FIELD_TYPE_ALTERED= 0x00000004;
+
+ /**
+ * A bit mask indicating this node's name has been
+ * altered from its original contents in the document.
+ */
+ protected static final int MASK_NAME_ALTERED= 0x00000008;
+
+ /**
+ * A bit mask indicating this node currently has a
+ * body.
+ */
+ protected static final int MASK_HAS_BODY= 0x00000010;
+
+ /**
+ * A bit mask indicating this node currently has a
+ * preceding comment.
+ */
+ protected static final int MASK_HAS_COMMENT= 0x00000020;
+
+ /**
+ * A bit mask indicating this method is a constructor.
+ */
+ protected static final int MASK_IS_CONSTRUCTOR= 0x00000040;
+
+ /**
+ * A bit mask indicating this type is a class.
+ */
+ protected static final int MASK_TYPE_IS_CLASS= 0x00000080;
+
+ /**
+ * A bit mask indicating this type has a superclass
+ * (requires or has an 'extends' clause).
+ */
+ protected static final int MASK_TYPE_HAS_SUPERCLASS= 0x00000100;
+
+ /**
+ * A bit mask indicating this type implements
+ * or extends some interfaces
+ */
+ protected static final int MASK_TYPE_HAS_INTERFACES= 0x00000200;
+
+ /**
+ * A bit mask indicating this return type of this method has
+ * been altered from the original contents.
+ */
+ protected static final int MASK_RETURN_TYPE_ALTERED= 0x00000400;
+
+ /**
+ * A bit mask indicating this node has detailed source indexes
+ */
+ protected static final int MASK_DETAILED_SOURCE_INDEXES = 0x00000800;
+
+/**
+ * Creates a new empty document fragment.
+ */
+DOMNode() {
+ fName= null;
+ fDocument= null;
+ fSourceRange= new int[]{-1, -1};
+ fNameRange= new int[]{-1, -1};
+ fragment();
+}
+/**
+ * Creates a new document fragment on the given range of the document.
+ *
+ * @param document - the document containing this node's original contents
+ * @param sourceRange - a two element array of integers describing the
+ * entire inclusive source range of this node within its document.
+ * Contents start on and include the character at the first position.
+ * Contents end on and include the character at the last position.
+ * An array of -1's indicates this node's contents do not exist
+ * in the document.
+ * @param name - the identifier portion of the name of this node, or
+ * null
if this node does not have a name
+ * @param nameRange - a two element array of integers describing the
+ * entire inclusive source range of this node's name within its document,
+ * including any array qualifiers that might immediately follow the name
+ * or -1's if this node does not have a name.
+ */
+DOMNode(char[] document, int[] sourceRange, String name, int[] nameRange) {
+ super();
+ fDocument= document;
+ fSourceRange= sourceRange;
+ fName= name;
+ fNameRange= nameRange;
+
+}
+/**
+ * Adds the given un-parented node (document fragment) as the last child of
+ * this node.
+ *
+ * CharArrayBuffer
.
+ *
+ * CharArrayBuffer
.
+ *
+ * CharArrayBufer
, using
+ * the original document and indicies as a form for the current attribute
+ * values of this node.
+ */
+protected abstract void appendFragmentedContents(CharArrayBuffer buffer);
+/**
+ * Adds the given un-parented node (document fragment) as the last child of
+ * this node without setting this node's 'fragmented' flag. This
+ * method is only used by the DOMBuilder
when creating a new DOM such
+ * that a new DOM is unfragmented.
+ */
+void basicAddChild(IDOMNode child) throws IllegalArgumentException, DOMException {
+ // verify child may be added
+ if (!canHaveChildren()) {
+ throw new DOMException(Util.bind("dom.unableAddChild")); //$NON-NLS-1$
+ }
+ if (child == null) {
+ throw new IllegalArgumentException(Util.bind("dom.addNullChild")); //$NON-NLS-1$
+ }
+ if (!isAllowableChild(child)) {
+ throw new DOMException(Util.bind("dom.addIncompatibleChild")); //$NON-NLS-1$
+ }
+ if (child.getParent() != null) {
+ throw new DOMException(Util.bind("dom.addChildWithParent")); //$NON-NLS-1$
+ }
+ /* NOTE: To test if the child is an ancestor of this node, we
+ * need only test if the root of this node is the child (the child
+ * is already a root since we have just guarenteed it has no parent).
+ */
+ if (child == getRoot()) {
+ throw new DOMException(Util.bind("dom.addAncestorAsChild")); //$NON-NLS-1$
+ }
+
+ DOMNode node= (DOMNode)child;
+
+ // if the child is not already part of this document, localize its contents
+ // before adding it to the tree
+ if (node.getDocument() != getDocument()) {
+ node.localizeContents();
+ }
+
+ // add the child last
+ if (fFirstChild == null) {
+ // this is the first and only child
+ fFirstChild= node;
+ } else {
+ fLastChild.fNextNode= node;
+ node.fPreviousNode= fLastChild;
+ }
+ fLastChild= node;
+ node.fParent= this;
+}
+/**
+ * Generates detailed source indexes for this node if possible.
+ *
+ * @exception DOMException if unable to generate detailed source indexes
+ * for this node
+ */
+protected void becomeDetailed() throws DOMException {
+ if (!isDetailed()) {
+ DOMNode detailed= getDetailedNode();
+ if (detailed == null) {
+ throw new DOMException(Util.bind("dom.cannotDetail")); //$NON-NLS-1$
+ }
+ if (detailed != this) {
+ shareContents(detailed);
+ }
+ }
+}
+/**
+ * Returns true if this node is allowed to have children, otherwise false.
+ *
+ * IDOMNode
interface method returns false; this
+ * method must be overridden by subclasses that implement nodes that allow
+ * children.
+ *
+ * @see IDOMNode#canHaveChildren()
+ */
+public boolean canHaveChildren() {
+ return false;
+}
+/**
+ * @see IDOMNode#clone()
+ */
+public Object clone() {
+
+ // create a new buffer with all my contents and children contents
+ int length= 0;
+ char[] buffer= null;
+ int offset= fSourceRange[0];
+
+ if (offset >= 0) {
+ length= fSourceRange[1] - offset + 1;
+ buffer= new char[length];
+ System.arraycopy(fDocument, offset, buffer, 0, length);
+ }
+ DOMNode clone= newDOMNode();
+ clone.shareContents(this);
+ clone.fDocument = buffer;
+
+ if (offset > 0) {
+ clone.offset(0 - offset);
+ }
+
+ // clone my children
+ if (canHaveChildren()) {
+ Enumeration children= getChildren();
+ while (children.hasMoreElements()) {
+ DOMNode child= (DOMNode)children.nextElement();
+ if (child.fDocument == fDocument) {
+ DOMNode childClone= child.cloneSharingDocument(buffer, offset);
+ clone.basicAddChild(childClone);
+ } else {
+ DOMNode childClone= (DOMNode)child.clone();
+ clone.addChild(childClone);
+ }
+
+ }
+ }
+
+ return clone;
+}
+private DOMNode cloneSharingDocument(char[] document, int rootOffset) {
+
+ DOMNode clone = newDOMNode();
+ clone.shareContents(this);
+ clone.fDocument = document;
+ if (rootOffset > 0) {
+ clone.offset(0 - rootOffset);
+ }
+
+ if (canHaveChildren()) {
+ Enumeration children = getChildren();
+ while (children.hasMoreElements()) {
+ DOMNode child = (DOMNode) children.nextElement();
+ if (child.fDocument == fDocument) {
+ DOMNode childClone= child.cloneSharingDocument(document, rootOffset);
+ clone.basicAddChild(childClone);
+ } else {
+ DOMNode childClone= (DOMNode)child.clone();
+ clone.addChild(childClone);
+ }
+ }
+ }
+ return clone;
+}
+/**
+ * Sets this node's fragmented flag and all ancestor fragmented flags
+ * to true
. Only those elements in the selection are part
+ * of the transfer which can be converted into an . This happens when an attribute of this node or a descendant
+ * node has been altered. When a node is fragmented, its contents must
+ * be generated from its attributes and original "form" rather than
+ * from the original contents in the document.
+ */
+protected void fragment() {
+ if (!isFragmented()) {
+ fIsFragmented= true;
+ if (fParent != null) {
+ fParent.fragment();
+ }
+ }
+}
+/**
+ * @see IDOMNode#getCharacters()
+ */
+public char[] getCharacters() {
+ CharArrayBuffer buffer= new CharArrayBuffer();
+ appendContents(buffer);
+ return buffer.getContents();
+}
+/**
+ * @see IDOMNode#getChild(String)
+ */
+public IDOMNode getChild(String name) {
+ DOMNode child = fFirstChild;
+ while (child != null) {
+ String n = child.getName();
+ if (name == null) {
+ if (n == null) {
+ return child;
+ }
+ } else {
+ if (name.equals(n)) {
+ return child;
+ }
+ }
+ child = child.fNextNode;
+ }
+ return null;
+}
+/**
+ * @see IDOMNode#getChildren()
+ */
+public Enumeration getChildren() {
+ return new SiblingEnumeration(fFirstChild);
+}
+/**
+ * Returns the current contents of this document fragment,
+ * or
finds previous and next line separators
+ * in source.
+ */
+public interface ILineStartFinder {
+/**
+ * Returns the position of the start of the line at or before the given source position.
+ *
+ * null
if this node has no contents.
+ *
+ * true
if the given mask of this node's state flag
+ * is turned on, otherwise false
.
+ */
+protected boolean getMask(int mask) {
+ return (fStateMask & mask) > 0;
+}
+/**
+ * @see IDOMNode#getName()
+ */
+public String getName() {
+ return fName;
+}
+/**
+ * Returns the source code to be used for this node's name.
+ */
+protected char[] getNameContents() {
+ if (isNameAltered()) {
+ return fName.toCharArray();
+ } else {
+ if (fName == null || fNameRange[0] < 0) {
+ return null;
+ } else {
+ int length = fNameRange[1] + 1 - fNameRange[0];
+ char[] result = new char[length];
+ System.arraycopy(fDocument, fNameRange[0], result, 0, length);
+ return result;
+ }
+ }
+}
+/**
+ * @see IDOMNode#getNextNode()
+ */
+public IDOMNode getNextNode() {
+ return fNextNode;
+}
+/**
+ * @see IDOMNode#getParent()
+ */
+public IDOMNode getParent() {
+ return fParent;
+}
+/**
+ * Answers a source position which corresponds to the end of the parent
+ * element's declaration.
+ */
+protected int getParentEndDeclaration() {
+ IDOMNode parent = getParent();
+ if (parent == null) {
+ return 0;
+ } else {
+ if (parent instanceof IDOMCompilationUnit) {
+ return 0;
+ } else {
+ return ((DOMType)parent).getOpenBodyEnd();
+ }
+ }
+}
+/**
+ * @see IDOMNode#getPreviousNode()
+ */
+public IDOMNode getPreviousNode() {
+ return fPreviousNode;
+}
+/**
+ * Returns the root node of this document fragment.
+ */
+protected IDOMNode getRoot() {
+ if (fParent == null) {
+ return this;
+ } else {
+ return fParent.getRoot();
+ }
+}
+/**
+ * Returns the original position of the first character of this
+ * node's contents in its document.
+ */
+public int getStartPosition() {
+ return fSourceRange[0];
+}
+/**
+ * @see IDOMNode#insertSibling(IDOMNode)
+ */
+public void insertSibling(IDOMNode sibling) throws IllegalArgumentException, DOMException {
+ // verify sibling may be added
+ if (sibling == null) {
+ throw new IllegalArgumentException(Util.bind("dom.addNullSibling")); //$NON-NLS-1$
+ }
+ if (fParent == null) {
+ throw new DOMException(Util.bind("dom.addSiblingBeforeRoot")); //$NON-NLS-1$
+ }
+ if (!fParent.isAllowableChild(sibling)) {
+ throw new DOMException(Util.bind("dom.addIncompatibleSibling")); //$NON-NLS-1$
+ }
+ if (sibling.getParent() != null) {
+ throw new DOMException(Util.bind("dom.addSiblingWithParent")); //$NON-NLS-1$
+ }
+ /* NOTE: To test if the sibling is an ancestor of this node, we
+ * need only test if the root of this node is the child (the sibling
+ * is already a root since we have just guaranteed it has no parent).
+ */
+ if (sibling == getRoot()) {
+ throw new DOMException(Util.bind("dom.addAncestorAsSibling")); //$NON-NLS-1$
+ }
+
+ DOMNode node= (DOMNode)sibling;
+
+ // if the sibling is not already part of this document, localize its contents
+ // before inserting it into the tree
+ if (node.getDocument() != getDocument()) {
+ node.localizeContents();
+ }
+
+ // insert the node
+ if (fPreviousNode == null) {
+ fParent.fFirstChild= node;
+ } else {
+ fPreviousNode.fNextNode= node;
+ }
+ node.fParent= fParent;
+ node.fPreviousNode= fPreviousNode;
+ node.fNextNode= this;
+ fPreviousNode= node;
+
+ // if the node is a constructor, it must also be fragmented to update the constructor's name
+ if (node.getNodeType() == IDOMNode.METHOD && ((IDOMMethod)node).isConstructor()) {
+ node.fragment();
+ } else {
+ fParent.fragment();
+ }
+}
+/**
+ * @see IDOMNode
+ */
+public boolean isAllowableChild(IDOMNode node) {
+ return false;
+}
+/**
+ * Returns true
if the contents of this node are from the same document as
+ * the given node, the contents of this node immediately follow the contents
+ * of the given node, and neither this node or the given node are fragmented -
+ * otherwise false
.
+ */
+protected boolean isContentMergableWith(DOMNode node) {
+ return !node.isFragmented() && !isFragmented() && node.getDocument() == getDocument() &&
+ node.getEndPosition() + 1 == getStartPosition();
+}
+/**
+ * Returns true
if this node has detailed source index information,
+ * or false
if this node has limited source index information. To
+ * perform some manipulations, detailed indexes are required.
+ */
+protected boolean isDetailed() {
+ return getMask(MASK_DETAILED_SOURCE_INDEXES);
+}
+/**
+ * Returns true
if this node's or a descendant node's contents
+ * have been altered since this node was created. This indicates
+ * that the contents of this node are no longer consistent with
+ * the contents of this node's document.
+ */
+protected boolean isFragmented() {
+ return fIsFragmented;
+}
+/**
+ * Returns true
if this noed's name has been altered
+ * from the original document contents.
+ */
+protected boolean isNameAltered() {
+ return getMask(MASK_NAME_ALTERED);
+}
+/**
+ * @see IDOMNode#isSignatureEqual(IDOMNode).
+ *
+ * DOMNode
for this instance.
+ */
+protected abstract DOMNode newDOMNode();
+/**
+ * Normalizes this DOMNode
's source positions to include whitespace preceeding
+ * the node on the line on which the node starts, and all whitespace after the node up to
+ * the next node's start
+ */
+void normalize(ILineStartFinder finder) {
+ if (getPreviousNode() == null)
+ normalizeStartPosition(getParentEndDeclaration(), finder);
+
+ // Set the children's position
+ if (canHaveChildren()) {
+ Enumeration children = getChildren();
+ while(children.hasMoreElements())
+ ((DOMNode)children.nextElement()).normalize(finder);
+ }
+
+ normalizeEndPosition(finder, (DOMNode)getNextNode());
+}
+/**
+ * Normalizes this DOMNode
's end position.
+ */
+void normalizeEndPosition(ILineStartFinder finder, DOMNode next) {
+ if (next == null) {
+ // this node's end position includes all of the characters up
+ // to the end of the enclosing node
+ DOMNode parent = (DOMNode) getParent();
+ if (parent == null || parent instanceof DOMCompilationUnit) {
+ setSourceRangeEnd(fDocument.length - 1);
+ } else {
+ // parent is a type
+ int temp = ((DOMType)parent).getCloseBodyPosition() - 1;
+ setSourceRangeEnd(temp);
+ fInsertionPosition = Math.max(finder.getLineStart(temp + 1), getEndPosition());
+ }
+ } else {
+ // this node's end position is just before the start of the next node
+ int temp = next.getStartPosition() - 1;
+ fInsertionPosition = Math.max(finder.getLineStart(temp + 1), getEndPosition());
+ next.normalizeStartPosition(getEndPosition(), finder);
+ setSourceRangeEnd(next.getStartPosition() - 1);
+ }
+}
+/**
+ * Normalizes this DOMNode
's start position.
+ */
+void normalizeStartPosition(int previousEnd, ILineStartFinder finder) {
+ int nodeStart = getStartPosition();
+ int lineStart = finder.getLineStart(nodeStart);
+ if (nodeStart > lineStart && (lineStart > previousEnd || (previousEnd == 0 && lineStart == 0)))
+ setStartPosition(lineStart);
+}
+/**
+ * Offsets all the source indexes in this node by the given amount.
+ */
+protected void offset(int offset) {
+ offsetRange(fNameRange, offset);
+ offsetRange(fSourceRange, offset);
+}
+/**
+ * Offsets the source range by the given amount
+ */
+protected void offsetRange(int[] range, int offset) {
+ for (int i= 0; i < range.length; i++) {
+ range[i]+=offset;
+ if (range[i] < 0) {
+ range[i]= -1;
+ }
+ }
+}
+/**
+ * Returns a copy of the given range.
+ */
+protected int[] rangeCopy(int[] range) {
+ int[] copy= new int[range.length];
+ for (int i= 0; i < range.length; i++) {
+ copy[i]= range[i];
+ }
+ return copy;
+}
+/**
+ * Separates this node from its parent and siblings, maintaining any ties that
+ * this node has to the underlying document fragment.
+ *
+ * String
representing this node - for Debug purposes only.
+ */
+public abstract String toString();
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMPackage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMPackage.java
new file mode 100644
index 0000000..0b80fc7
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMPackage.java
@@ -0,0 +1,141 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core.jdom;
+
+import net.sourceforge.phpdt.core.ICompilationUnit;
+import net.sourceforge.phpdt.core.IJavaElement;
+import net.sourceforge.phpdt.core.jdom.IDOMNode;
+import net.sourceforge.phpdt.core.jdom.IDOMPackage;
+import net.sourceforge.phpdt.internal.compiler.util.Util;
+import net.sourceforge.phpdt.internal.core.util.CharArrayBuffer;
+
+/**
+ * DOMPackage provides an implementation of IDOMPackage.
+ *
+ * @see IDOMPackage
+ * @see DOMNode
+ */
+class DOMPackage extends DOMNode implements IDOMPackage {
+
+/**
+ * Creates an empty PACKAGE node.
+ */
+DOMPackage() {
+ setMask(MASK_DETAILED_SOURCE_INDEXES, true);
+}
+/**
+ * Creates a new simple PACKAGE document fragment on the given range of the document.
+ *
+ * @param document - the document containing this node's original contents
+ * @param sourceRange - a two element array of integers describing the
+ * entire inclusive source range of this node within its document.
+ * Contents start on and include the character at the first position.
+ * Contents end on and include the character at the last position.
+ * An array of -1's indicates this node's contents do not exist
+ * in the document.
+ * @param name - the identifier portion of the name of this node, or
+ * null
if this node does not have a name
+ */
+DOMPackage(char[] document, int[] sourceRange, String name) {
+ super(document, sourceRange, name, new int[] {-1, -1});
+ setMask(MASK_DETAILED_SOURCE_INDEXES, false);
+}
+/**
+ * Creates a new detailed PACKAGE document fragment on the given range of the document.
+ *
+ * @param document - the document containing this node's original contents
+ * @param sourceRange - a two element array of integers describing the
+ * entire inclusive source range of this node within its document.
+ * Contents start on and include the character at the first position.
+ * Contents end on and include the character at the last position.
+ * An array of -1's indicates this node's contents do not exist
+ * in the document.
+ * @param name - the identifier portion of the name of this node, or
+ * null
if this node does not have a name
+ * @param nameRange - a two element array of integers describing the
+ * entire inclusive source range of this node's name within its document,
+ * including any array qualifiers that might immediately follow the name
+ * or -1's if this node does not have a name.
+ */
+DOMPackage(char[] document, int[] sourceRange, String name, int[] nameRange) {
+ super(document, sourceRange, name, nameRange);
+ setMask(MASK_DETAILED_SOURCE_INDEXES, true);
+}
+/**
+ * @see DOMNode#appendFragmentedContents(CharArrayBuffer)
+ */
+protected void appendFragmentedContents(CharArrayBuffer buffer) {
+ if (fNameRange[0] < 0) {
+ buffer
+ .append("package ") //$NON-NLS-1$
+ .append(fName)
+ .append(';')
+ .append(Util.LINE_SEPARATOR)
+ .append(Util.LINE_SEPARATOR);
+ } else {
+ buffer
+ .append(fDocument, fSourceRange[0], fNameRange[0] - fSourceRange[0])
+ .append(fName)
+ .append(fDocument, fNameRange[1] + 1, fSourceRange[1] - fNameRange[1]);
+ }
+}
+/**
+ * @see IDOMNode#getContents()
+ */
+public String getContents() {
+ if (fName == null) {
+ return null;
+ } else {
+ return super.getContents();
+ }
+}
+/**
+ * @see DOMNode#getDetailedNode()
+ */
+//protected DOMNode getDetailedNode() {
+// return (DOMNode)getFactory().createPackage(getContents());
+//}
+/**
+ * @see IDOMNode#getJavaElement
+ */
+public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException {
+ if (parent.getElementType() == IJavaElement.COMPILATION_UNIT) {
+ return ((ICompilationUnit)parent).getPackageDeclaration(getName());
+ } else {
+ throw new IllegalArgumentException(Util.bind("element.illegalParent")); //$NON-NLS-1$
+ }
+}
+/**
+ * @see IDOMNode#getNodeType()
+ */
+public int getNodeType() {
+ return IDOMNode.PACKAGE;
+}
+/**
+ * @see DOMNode
+ */
+protected DOMNode newDOMNode() {
+ return new DOMPackage();
+}
+/**
+ * @see IDOMNode#setName
+ */
+public void setName(String name) {
+ becomeDetailed();
+ super.setName(name);
+}
+/**
+ * @see IDOMNode#toString()
+ */
+public String toString() {
+ return "PACKAGE: " + getName(); //$NON-NLS-1$
+}
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMType.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMType.java
new file mode 100644
index 0000000..0ec3b3f
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/DOMType.java
@@ -0,0 +1,721 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core.jdom;
+
+import java.util.Enumeration;
+
+import net.sourceforge.phpdt.core.ICompilationUnit;
+import net.sourceforge.phpdt.core.IJavaElement;
+import net.sourceforge.phpdt.core.IType;
+import net.sourceforge.phpdt.core.compiler.ITerminalSymbols;
+import net.sourceforge.phpdt.core.compiler.InvalidInputException;
+import net.sourceforge.phpdt.core.jdom.IDOMMethod;
+import net.sourceforge.phpdt.core.jdom.IDOMNode;
+import net.sourceforge.phpdt.core.jdom.IDOMType;
+import net.sourceforge.phpdt.internal.compiler.parser.Scanner;
+import net.sourceforge.phpdt.internal.compiler.util.Util;
+import net.sourceforge.phpdt.internal.core.util.CharArrayBuffer;
+import net.sourceforge.phpdt.internal.core.util.CharArrayOps;
+
+/**
+ * DOMType provides an implementation of IDOMType.
+ *
+ * @see IDOMType
+ * @see DOMNode
+ */
+
+/* package */ class DOMType extends DOMMember implements IDOMType {
+
+ /**
+ * The 'class' or 'interface' keyword if altered
+ * from the documents contents, otherwise null
.
+ */
+ protected String fTypeKeyword;
+
+ /**
+ * The original inclusive source range of the 'class'
+ * or 'interface' keyword in the document.
+ */
+ protected int[] fTypeRange;
+
+ /**
+ * The superclass name for the class declaration
+ * if altered from the document's contents, otherwise
+ * null
. Also null
when this
+ * type represents an interface.
+ */
+ protected String fSuperclass;
+
+ /**
+ * The original inclusive source range of the superclass
+ * name in the document, or -1's of no superclass was
+ * specified in the document.
+ */
+ protected int[] fSuperclassRange;
+
+
+ /**
+ * The original inclusive souce range of the 'extends' keyword
+ * in the document, including surrounding whitespace, or -1's if
+ * the keyword was not present in the document.
+ */
+ protected int[] fExtendsRange;
+
+ /**
+ * The original inclusive souce range of the 'implements' keyword
+ * in the document, including surrounding whitespace, or -1's if
+ * the keyword was not present in the document.
+ */
+ protected int[] fImplementsRange;
+
+ /**
+ * The comma delimited list of interfaces this type implements
+ * or extends, if altered from the document's contents, otherwise
+ * null
. Also null
if this type does
+ * not implement or extend any interfaces.
+ */
+ protected char[] fInterfaces;
+
+ /**
+ * The original inclusive source range of the list of interfaces this
+ * type implements or extends, not including any surrouding whitespace.
+ * If the document did not specify interfaces, this array contains -1's.
+ */
+ protected int[] fInterfacesRange;
+
+
+
+ /**
+ * The original source range of the first character following the
+ * type name superclass name, or interface list, up to and including
+ * the first character before the first type member.
+ */
+ protected int[] fOpenBodyRange;
+
+ /**
+ * The original source range of the first new line or non whitespace
+ * character preceding the close brace of the type's body, up to the
+ * and including the first character before the next node (if there are
+ * no following nodes, the range ends at the position of the last
+ * character in the document).
+ */
+ protected int[] fCloseBodyRange;
+
+ /**
+ * A list of interfaces this type extends or implements.
+ * null
when this type does not extend
+ * or implement any interfaces.
+ */
+ protected String[] fSuperInterfaces= new String[0];
+
+ /**
+ * This position is the position of the end of the last line separator before the closing brace starting
+ * position of the receiver.
+ */
+// protected int fInsertionPosition;
+
+/**
+ * Constructs an empty type node.
+ */
+DOMType() {
+
+}
+/**
+ * Creates a new detailed TYPE document fragment on the given range of the document.
+ *
+ * @param document - the document containing this node's original contents
+ * @param sourceRange - a two element array of integers describing the
+ * entire inclusive source range of this node within its document.
+ * Contents start on and include the character at the first position.
+ * Contents end on and include the character at the last position.
+ * An array of -1's indicates this node's contents do not exist
+ * in the document.
+ * @param name - the identifier portion of the name of this node, or
+ * null
if this node does not have a name
+ * @param nameRange - a two element array of integers describing the
+ * entire inclusive source range of this node's name within its document,
+ * including any array qualifiers that might immediately follow the name
+ * or -1's if this node does not have a name.
+ * @param commentRange - a two element array describing the comments that precede
+ * the member declaration. The first matches the start of this node's
+ * sourceRange, and the second is the new-line or first non-whitespace
+ * character following the last comment. If no comments are present,
+ * this array contains two -1's.
+ * @param flags - an integer representing the modifiers for this member. The
+ * integer can be analyzed with org.eclipse.jdt.core.Flags
+ * @param modifierRange - a two element array describing the location of
+ * modifiers for this member within its source range. The first integer
+ * is the first character of the first modifier for this member, and
+ * the second integer is the last whitespace character preceeding the
+ * next part of this member declaration. If there are no modifiers present
+ * in this node's source code (that is, package default visibility), this array
+ * contains two -1's.
+ * @param typeRange - a two element array describing the location of the 'class'
+ * or 'interface' keyword in the type declaration - first and last character
+ * positions.
+ * @param superclassRange - a two element array describing the location of the
+ * superclass name in the type declaration - first and last character
+ * positions or two -1's if a superclass is not present in the document.
+ * @param extendsRange - a two element array describing the location of the
+ * 'extends' keyword in the type declaration, including any surrounding
+ * whitespace, or -1's if the 'extends' keyword is not present in the document.
+ * @param implementsList - an array of names of the interfaces this type implements
+ * or extends, or null
if this type does not implement or extend
+ * any interfaces.
+ * @param implementsRange - a two element array describing the location of the
+ * comment delimited list of interfaces this type implements or extends,
+ * not including any surrounding whitespace, or -1's if no interface list
+ * is present in the document.
+ * @param implementsKeywordRange - a two element array describing the location of the
+ * 'implements' keyword, including any surrounding whitespace, or -1's if no
+ * 'implements' keyword is present in the document.
+ * @param openBodyRange - a two element array describing the location of the
+ * open brace of the type's body and whitespace following the type declaration
+ * and preceeding the first member in the type.
+ * @param closeBodyRange - a two element array describing the source range of the
+ * first new line or non whitespace character preceeding the close brace of the
+ * type's body, up to the close brace
+ * @param isClass - true is the type is a class, false if it is an interface
+ */
+DOMType(char[] document, int[] sourceRange, String name, int[] nameRange, int[] commentRange, int flags, int[] modifierRange, int[] typeRange, int[] superclassRange, int[] extendsRange, String[] implementsList, int[] implementsRange, int[] implementsKeywordRange, int[] openBodyRange, int[] closeBodyRange, boolean isClass) {
+ super(document, sourceRange, name, nameRange, commentRange, flags, modifierRange);
+
+ fTypeRange= typeRange;
+ setMask(MASK_TYPE_IS_CLASS, isClass);
+
+ fExtendsRange= extendsRange;
+ fImplementsRange= implementsKeywordRange;
+ fSuperclassRange= superclassRange;
+ fInterfacesRange= implementsRange;
+ fCloseBodyRange= closeBodyRange;
+ setMask(MASK_TYPE_HAS_SUPERCLASS, superclassRange[0] > 0);
+ setMask(MASK_TYPE_HAS_INTERFACES, implementsList != null);
+ fSuperInterfaces= implementsList;
+ fOpenBodyRange= openBodyRange;
+ fCloseBodyRange= closeBodyRange;
+ setMask(MASK_DETAILED_SOURCE_INDEXES, true);
+
+}
+/**
+ * Creates a new simple TYPE document fragment on the given range of the document.
+ *
+ * @param document - the document containing this node's original contents
+ * @param sourceRange - a two element array of integers describing the
+ * entire inclusive source range of this node within its document.
+ * Contents start on and include the character at the first position.
+ * Contents end on and include the character at the last position.
+ * An array of -1's indicates this node's contents do not exist
+ * in the document.
+ * @param name - the identifier portion of the name of this node, or
+ * null
if this node does not have a name
+ * @param nameRange - a two element array of integers describing the
+ * entire inclusive source range of this node's name within its document,
+ * including any array qualifiers that might immediately follow the name
+ * or -1's if this node does not have a name.
+ * @param flags - an integer representing the modifiers for this member. The
+ * integer can be analyzed with org.eclipse.jdt.core.Flags
+ * @param implementsList - an array of names of the interfaces this type implements
+ * or extends, or null
if this type does not implement or extend
+ * any interfaces.
+ * @param isClass - true is the type is a class, false if it is an interface
+ */
+DOMType(char[] document, int[] sourceRange, String name, int[] nameRange, int flags, String[] implementsList, boolean isClass) {
+ this(document, sourceRange, name, nameRange, new int[] {-1, -1}, flags,
+ new int[] {-1, -1}, new int[] {-1, -1}, new int[] {-1, -1}, new int[] {-1, -1},
+ implementsList, new int[] {-1, -1}, new int[] {-1, -1}, new int[] {-1, -1}, new int[] {sourceRange[1], sourceRange[1]}, isClass);
+ setMask(MASK_DETAILED_SOURCE_INDEXES, false);
+}
+/**
+ * @see IDOMType#addSuperInterface(String)
+ */
+public void addSuperInterface(String name) throws IllegalArgumentException {
+ if (name == null) {
+ throw new IllegalArgumentException(Util.bind("dom.addNullInterface")); //$NON-NLS-1$
+ }
+ if (fSuperInterfaces == null) {
+ fSuperInterfaces= new String[1];
+ fSuperInterfaces[0]= name;
+ } else {
+ fSuperInterfaces= appendString(fSuperInterfaces, name);
+ }
+ setSuperInterfaces(fSuperInterfaces);
+}
+/**
+ * @see DOMMember#appendMemberBodyContents(CharArrayBuffer)
+ */
+protected void appendMemberBodyContents(CharArrayBuffer buffer) {
+ buffer.append(fDocument, fOpenBodyRange[0], fOpenBodyRange[1] + 1 - fOpenBodyRange[0]);
+ appendContentsOfChildren(buffer);
+ buffer.append(fDocument, fCloseBodyRange[0], fCloseBodyRange[1] + 1 - fCloseBodyRange[0]);
+ buffer.append(fDocument, fCloseBodyRange[1] + 1, fSourceRange[1] - fCloseBodyRange[1]);
+}
+/**
+ * @see DOMMember#appendMemberDeclarationContents(CharArrayBuffer )
+ */
+protected void appendMemberDeclarationContents(CharArrayBuffer buffer) {
+
+ if (fTypeKeyword != null) {
+ buffer.append(fTypeKeyword);
+ buffer.append(fDocument, fTypeRange[1], fNameRange[0] - fTypeRange[1] );
+ } else {
+ buffer.append(fDocument, fTypeRange[0], fTypeRange[1] + 1 - fTypeRange[0]);
+ }
+
+ buffer.append(getName());
+
+ if (isClass()) {
+ boolean hasSuperclass = false, hasInterfaces = false;
+ if (getMask(MASK_TYPE_HAS_SUPERCLASS)) {
+ hasSuperclass = true;
+ if (fExtendsRange[0] < 0) {
+ buffer.append(" extends "); //$NON-NLS-1$
+ } else {
+ buffer.append(fDocument, fExtendsRange[0], fExtendsRange[1] + 1 - fExtendsRange[0]);
+ }
+ if (fSuperclass != null) {
+ buffer.append(fSuperclass);
+ } else {
+ buffer.append(fDocument, fSuperclassRange[0], fSuperclassRange[1] + 1 - fSuperclassRange[0]);
+ }
+ }
+ if (getMask(MASK_TYPE_HAS_INTERFACES)) {
+ hasInterfaces = true;
+ if (fImplementsRange[0] < 0) {
+ buffer.append(" implements "); //$NON-NLS-1$
+ } else {
+ buffer.append(fDocument, fImplementsRange[0], fImplementsRange[1] + 1 - fImplementsRange[0]);
+ }
+ if (fInterfaces != null) {
+ buffer.append(fInterfaces);
+ } else {
+ buffer.append(fDocument, fInterfacesRange[0], fInterfacesRange[1] + 1 - fInterfacesRange[0]);
+ }
+ }
+ if (hasInterfaces) {
+ if (fImplementsRange[0] < 0) {
+ buffer.append(' ');
+ } else {
+ buffer.append(fDocument, fInterfacesRange[1] + 1, fOpenBodyRange[0] - fInterfacesRange[1] - 1);
+ }
+ } else {
+ if (hasSuperclass) {
+ if (fSuperclassRange[0] < 0) {
+ buffer.append(' ');
+ } else {
+ buffer.append(fDocument, fSuperclassRange[1] + 1, fOpenBodyRange[0] - fSuperclassRange[1] - 1);
+ }
+ } else {
+ buffer.append(fDocument, fNameRange[1] + 1, fOpenBodyRange[0] - fNameRange[1] - 1);
+ }
+ }
+ } else {
+ if (getMask(MASK_TYPE_HAS_INTERFACES)) {
+ if (fExtendsRange[0] < 0) {
+ buffer.append(" extends "); //$NON-NLS-1$
+ } else {
+ buffer.append(fDocument, fExtendsRange[0], fExtendsRange[1] + 1 - fExtendsRange[0]);
+ }
+ if (fInterfaces != null) {
+ buffer.append(fInterfaces);
+ buffer.append(' ');
+ } else {
+ buffer.append(fDocument, fInterfacesRange[0], fInterfacesRange[1] + 1 - fInterfacesRange[0]);
+ }
+ } else {
+ buffer.append(fDocument, fNameRange[1] + 1, fOpenBodyRange[0] - fNameRange[1] - 1);
+ }
+ }
+
+}
+/**
+ * @see DOMNode#appendSimpleContents(CharArrayBuffer)
+ */
+protected void appendSimpleContents(CharArrayBuffer buffer) {
+ // append eveything before my name
+ buffer.append(fDocument, fSourceRange[0], fNameRange[0] - fSourceRange[0]);
+ // append my name
+ buffer.append(fName);
+
+
+ // append everything after my name and before my first child
+ buffer.append(fDocument, fNameRange[1] + 1, fOpenBodyRange[1] - fNameRange[1]);
+ // append my children
+ appendContentsOfChildren(buffer);
+ // append from my last child to my end
+ buffer.append(fDocument, fCloseBodyRange[0], fSourceRange[1] - fCloseBodyRange[0] + 1);
+
+
+}
+/**
+ * @see IDOMNode#canHaveChildren()
+ */
+public boolean canHaveChildren() {
+ return true;
+}
+/**
+ * Returns the position of the closing brace for the body of this type.
+ * This value this method returns is only valid before the type has
+ * been normalized and is present only for normalization.
+ */
+int getCloseBodyPosition() {
+ return fCloseBodyRange[0];
+}
+/**
+ * @see DOMNode#getDetailedNode()
+ */
+//protected DOMNode getDetailedNode() {
+// return (DOMNode)getFactory().createType(getContents());
+//}
+/**
+ * @see DOMNode#getInsertionPosition()
+ */
+public int getInsertionPosition() {
+ // this should return the position of the end of the last line separator before the closing brace of the type
+ // See PR 1GELSDQ: ITPJUI:WINNT - JDOM: IType.createMethod does not insert nicely for inner types
+ return fInsertionPosition;
+}
+/**
+ * @see IDOMNode#getJavaElement
+ */
+public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException {
+ if (parent.getElementType() == IJavaElement.TYPE) {
+ return ((IType)parent).getType(getName());
+ } else if (parent.getElementType() == IJavaElement.COMPILATION_UNIT) {
+ return ((ICompilationUnit)parent).getType(getName());
+ } else {
+ throw new IllegalArgumentException(Util.bind("element.illegalParent")); //$NON-NLS-1$
+ }
+}
+/**
+ * @see DOMMember#getMemberDeclarationStartPosition()
+ */
+protected int getMemberDeclarationStartPosition() {
+ return fTypeRange[0];
+}
+/**
+ * @see IDOMNode#getNodeType()
+ */
+public int getNodeType() {
+ return IDOMNode.TYPE;
+}
+/**
+ * Answers the open body range end position.
+ */
+int getOpenBodyEnd() {
+ return fOpenBodyRange[1];
+}
+/**
+ * @see IDOMType#getSuperclass()
+ */
+public String getSuperclass() {
+ becomeDetailed();
+ if (getMask(MASK_TYPE_HAS_SUPERCLASS)) {
+ if (fSuperclass != null) {
+ return fSuperclass;
+ } else {
+ return CharArrayOps.substring(fDocument, fSuperclassRange[0], fSuperclassRange[1] + 1 - fSuperclassRange[0]);
+ }
+ } else {
+ return null;
+ }
+}
+/**
+ * @see IDOMType#getSuperInterfaces()
+ */
+public String[] getSuperInterfaces() {
+ return fSuperInterfaces;
+}
+/**
+ * @see IDOMNode
+ */
+public boolean isAllowableChild(IDOMNode node) {
+ if (node != null) {
+ int type= node.getNodeType();
+ return type == IDOMNode.TYPE || type == IDOMNode.FIELD|| type == IDOMNode.METHOD ||
+ type == IDOMNode.INITIALIZER;
+ } else {
+ return false;
+ }
+
+}
+/**
+ * @see IDOMType#isClass()
+ */
+public boolean isClass() {
+ return getMask(MASK_TYPE_IS_CLASS);
+}
+/**
+ * @see DOMNode
+ */
+protected DOMNode newDOMNode() {
+ return new DOMType();
+}
+/**
+ * Normalizes this DOMNode
's source positions to include whitespace preceeding
+ * the node on the line on which the node starts, and all whitespace after the node up to
+ * the next node's start
+ */
+void normalize(ILineStartFinder finder) {
+ // perform final changes to the open and close body ranges
+ int openBodyEnd, openBodyStart, closeBodyStart, closeBodyEnd;
+ DOMNode first = (DOMNode) getFirstChild();
+ DOMNode lastNode = null;
+ // look for the open body
+ Scanner scanner = new Scanner();
+ scanner.setSource(fDocument);
+ scanner.resetTo(fNameRange[1] + 1, fDocument.length);
+
+ try {
+ int currentToken = scanner.getNextToken();
+ while(currentToken != ITerminalSymbols.TokenNameLBRACE &&
+ currentToken != ITerminalSymbols.TokenNameEOF) {
+ currentToken = scanner.getNextToken();
+ }
+ if(currentToken == ITerminalSymbols.TokenNameLBRACE) {
+ openBodyEnd = scanner.currentPosition - 1;
+ openBodyStart = scanner.startPosition;
+ } else {
+ openBodyEnd = fDocument.length;
+ openBodyStart = fDocument.length;
+ }
+ } catch(InvalidInputException e) {
+ openBodyEnd = fDocument.length;
+ openBodyStart = fDocument.length;
+ }
+ if (first != null) {
+ int lineStart = finder.getLineStart(first.getStartPosition());
+ if (lineStart > openBodyEnd) {
+ openBodyEnd = lineStart - 1;
+ } else {
+ openBodyEnd = first.getStartPosition() - 1;
+ }
+ lastNode = (DOMNode) first.getNextNode();
+ if (lastNode == null) {
+ lastNode = first;
+ } else {
+ while (lastNode.getNextNode() != null) {
+ lastNode = (DOMNode) lastNode.getNextNode();
+ }
+ }
+ scanner.setSource(fDocument);
+ scanner.resetTo(lastNode.getEndPosition() + 1, fDocument.length);
+ try {
+ int currentToken = scanner.getNextToken();
+ while(currentToken != ITerminalSymbols.TokenNameRBRACE &&
+ currentToken != ITerminalSymbols.TokenNameEOF) {
+ currentToken = scanner.getNextToken();
+ }
+ if(currentToken == ITerminalSymbols.TokenNameRBRACE) {
+ closeBodyStart = scanner.startPosition;
+ closeBodyEnd = scanner.currentPosition - 1;
+ } else {
+ closeBodyStart = fDocument.length;
+ closeBodyEnd = fDocument.length;
+ }
+ } catch(InvalidInputException e) {
+ closeBodyStart = fDocument.length;
+ closeBodyEnd = fDocument.length;
+ }
+ } else {
+ scanner.resetTo(openBodyEnd, fDocument.length);
+ try {
+ int currentToken = scanner.getNextToken();
+ while(currentToken != ITerminalSymbols.TokenNameRBRACE &&
+ currentToken != ITerminalSymbols.TokenNameEOF) {
+ currentToken = scanner.getNextToken();
+ }
+ if(currentToken == ITerminalSymbols.TokenNameRBRACE) {
+ closeBodyStart = scanner.startPosition;
+ closeBodyEnd = scanner.currentPosition - 1;
+ } else {
+ closeBodyStart = fDocument.length;
+ closeBodyEnd = fDocument.length;
+ }
+ } catch(InvalidInputException e) {
+ closeBodyStart = fDocument.length;
+ closeBodyEnd = fDocument.length;
+ }
+ openBodyEnd = closeBodyEnd - 1;
+ }
+ setOpenBodyRangeEnd(openBodyEnd);
+ setOpenBodyRangeStart(openBodyStart);
+ setCloseBodyRangeStart(closeBodyStart);
+ setCloseBodyRangeEnd(closeBodyEnd);
+ fInsertionPosition = finder.getLineStart(closeBodyStart);
+ if (lastNode != null && fInsertionPosition < lastNode.getEndPosition()) {
+ fInsertionPosition = getCloseBodyPosition();
+ }
+ if (fInsertionPosition <= openBodyEnd) {
+ fInsertionPosition = getCloseBodyPosition();
+ }
+ super.normalize(finder);
+}
+
+/**
+ * Normalizes this DOMNode
's end position.
+ */
+void normalizeEndPosition(ILineStartFinder finder, DOMNode next) {
+ if (next == null) {
+ // this node's end position includes all of the characters up
+ // to the end of the enclosing node
+ DOMNode parent = (DOMNode) getParent();
+ if (parent == null || parent instanceof DOMCompilationUnit) {
+ setSourceRangeEnd(fDocument.length - 1);
+ } else {
+ // parent is a type
+ setSourceRangeEnd(((DOMType)parent).getCloseBodyPosition() - 1);
+ }
+ } else {
+ // this node's end position is just before the start of the next node
+ next.normalizeStartPosition(getEndPosition(), finder);
+ setSourceRangeEnd(next.getStartPosition() - 1);
+ }
+}
+
+/**
+ * Offsets all the source indexes in this node by the given amount.
+ */
+protected void offset(int offset) {
+ super.offset(offset);
+ offsetRange(fCloseBodyRange, offset);
+ offsetRange(fExtendsRange, offset);
+ offsetRange(fImplementsRange, offset);
+ offsetRange(fInterfacesRange, offset);
+ offsetRange(fOpenBodyRange, offset);
+ offsetRange(fSuperclassRange, offset);
+ offsetRange(fTypeRange, offset);
+}
+/**
+ * @see IDOMType#setClass(boolean)
+ */
+public void setClass(boolean b) {
+ becomeDetailed();
+ fragment();
+ setMask(MASK_TYPE_IS_CLASS, b);
+ if (b) {
+ fTypeKeyword= "class"; //$NON-NLS-1$
+ } else {
+ fTypeKeyword= "interface"; //$NON-NLS-1$
+ setSuperclass(null);
+ }
+}
+/**
+ * Sets the end of the close body range
+ */
+void setCloseBodyRangeEnd(int end) {
+ fCloseBodyRange[1] = end;
+}
+/**
+ * Sets the start of the close body range
+ */
+void setCloseBodyRangeStart(int start) {
+ fCloseBodyRange[0] = start;
+}
+/**
+ * Sets the name of this node.
+ *
+ * null
the enumeration is empty.
+ */
+SiblingEnumeration(IDOMNode child) {
+ fCurrentElement= child;
+}
+/**
+ * @see java.util.Enumeration#hasMoreElements()
+ */
+public boolean hasMoreElements() {
+ return fCurrentElement != null;
+}
+/**
+ * @see java.util.Enumeration#nextElement()
+ */
+public Object nextElement() {
+ IDOMNode curr= fCurrentElement;
+ if (curr != null) {
+ fCurrentElement= fCurrentElement.getNextNode();
+ }
+ return curr;
+}
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/SimpleDOMBuilder.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/SimpleDOMBuilder.java
new file mode 100644
index 0000000..c923015
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/jdom/SimpleDOMBuilder.java
@@ -0,0 +1,218 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core.jdom;
+
+import java.util.Map;
+
+import net.sourceforge.phpdt.core.jdom.IDOMCompilationUnit;
+import net.sourceforge.phpdt.internal.compiler.ISourceElementRequestor;
+import net.sourceforge.phpdt.internal.compiler.SourceElementParser;
+import net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit;
+import net.sourceforge.phpdt.internal.compiler.problem.DefaultProblemFactory;
+import net.sourceforge.phpdt.internal.core.util.CharArrayOps;
+import net.sourceforge.phpeclipse.PHPCore;
+
+/**
+ * A DOM builder that uses the SourceElementParser
+ */
+public class SimpleDOMBuilder extends AbstractDOMBuilder implements ISourceElementRequestor {
+
+public void acceptImport(int declarationStart, int declarationEnd, char[] name, boolean onDemand) {
+ int[] sourceRange = {declarationStart, declarationEnd};
+ String importName = new String(name);
+ /** name is set to contain the '*' */
+ if (onDemand) {
+ importName+=".*"; //$NON-NLS-1$
+ }
+ fNode= new DOMImport(fDocument, sourceRange, importName, onDemand);
+ addChild(fNode);
+}
+public void acceptPackage(int declarationStart, int declarationEnd, char[] name) {
+ int[] sourceRange= new int[] {declarationStart, declarationEnd};
+ fNode= new DOMPackage(fDocument, sourceRange, CharArrayOps.charToString(name));
+ addChild(fNode);
+}
+/**
+ * @see IDOMFactory#createCompilationUnit(String, String)
+ */
+public IDOMCompilationUnit createCompilationUnit(String sourceCode, String name) {
+ return createCompilationUnit(sourceCode.toCharArray(), name.toCharArray());
+}
+/**
+ * @see IDOMFactory#createCompilationUnit(String, String)
+ */
+public IDOMCompilationUnit createCompilationUnit(ICompilationUnit compilationUnit) {
+ initializeBuild(compilationUnit.getContents(), true, true);
+ getParser(PHPCore.getOptions()).parseCompilationUnit(compilationUnit, false);
+ return super.createCompilationUnit(compilationUnit);
+}
+/**
+ * Creates a new DOMMethod and inizializes.
+ *
+ * @param declarationStart - a source position corresponding to the first character
+ * of this constructor declaration
+ * @param modifiers - the modifiers for this constructor converted to a flag
+ * @param returnType - the name of the return type
+ * @param name - the name of this constructor
+ * @param nameStart - a source position corresponding to the first character of the name
+ * @param nameEnd - a source position corresponding to the last character of the name
+ * @param parameterTypes - a list of parameter type names
+ * @param parameterNames - a list of the names of the parameters
+ * @param exceptionTypes - a list of the exception types
+ */
+protected void enterAbstractMethod(int declarationStart, int modifiers,
+ char[] returnType, char[] name, int nameStart, int nameEnd, char[][] parameterTypes,
+ char[][] parameterNames, char[][] exceptionTypes, boolean isConstructor) {
+
+ int[] sourceRange = {declarationStart, -1}; // will be fixed up on exit
+ int[] nameRange = {nameStart, nameEnd};
+ fNode = new DOMMethod(fDocument, sourceRange, CharArrayOps.charToString(name), nameRange, modifiers,
+ isConstructor, CharArrayOps.charToString(returnType),
+ CharArrayOps.charcharToString(parameterTypes),
+ CharArrayOps.charcharToString(parameterNames),
+ CharArrayOps.charcharToString(exceptionTypes));
+ addChild(fNode);
+ fStack.push(fNode);
+}
+/**
+ */
+public void enterClass(int declarationStart, int modifiers, char[] name, int nameStart, int nameEnd, char[] superclass, char[][] superinterfaces) {
+ enterType(declarationStart, modifiers, name, nameStart, nameEnd, superclass,
+ superinterfaces, true);
+}
+/**
+ */
+public void enterConstructor(int declarationStart, int modifiers, char[] name, int nameStart, int nameEnd, char[][] parameterTypes, char[][] parameterNames, char[][] exceptionTypes) {
+ /* see 1FVIIQZ */
+ String nameString = new String(fDocument, nameStart, nameEnd - nameStart);
+ int openParenPosition = nameString.indexOf('(');
+ if (openParenPosition > -1)
+ nameEnd = nameStart + openParenPosition - 1;
+
+ enterAbstractMethod(declarationStart, modifiers,
+ null, name, nameStart, nameEnd, parameterTypes,
+ parameterNames, exceptionTypes,true);
+}
+/**
+ */
+public void enterField(int declarationStart, int modifiers, char[] type, char[] name, int nameStart, int nameEnd) {
+
+ int[] sourceRange = {declarationStart, -1};
+ int[] nameRange = {nameStart, nameEnd};
+ boolean isSecondary= false;
+ if (fNode instanceof DOMField) {
+ isSecondary = declarationStart == fNode.fSourceRange[0];
+ }
+ fNode = new DOMField(fDocument, sourceRange, CharArrayOps.charToString(name), nameRange,
+ modifiers, CharArrayOps.charToString(type), isSecondary);
+ addChild(fNode);
+ fStack.push(fNode);
+}
+/**
+
+ */
+public void enterInitializer(int declarationSourceStart, int modifiers) {
+ int[] sourceRange = {declarationSourceStart, -1};
+ fNode = new DOMInitializer(fDocument, sourceRange, modifiers);
+ addChild(fNode);
+ fStack.push(fNode);
+}
+/**
+ */
+public void enterInterface(int declarationStart, int modifiers, char[] name, int nameStart, int nameEnd, char[][] superinterfaces) {
+ enterType(declarationStart, modifiers, name, nameStart, nameEnd, null,
+ superinterfaces, false);
+}
+/**
+ */
+public void enterMethod(int declarationStart, int modifiers, char[] returnType, char[] name, int nameStart, int nameEnd, char[][] parameterTypes, char[][] parameterNames, char[][] exceptionTypes) {
+ enterAbstractMethod(declarationStart, modifiers,
+ returnType, name, nameStart, nameEnd, parameterTypes,
+ parameterNames, exceptionTypes,false);
+}
+/**
+ */
+protected void enterType(int declarationStart, int modifiers, char[] name,
+ int nameStart, int nameEnd, char[] superclass, char[][] superinterfaces, boolean isClass) {
+ if (fBuildingType) {
+ int[] sourceRange = {declarationStart, -1}; // will be fixed in the exit
+ int[] nameRange = new int[] {nameStart, nameEnd};
+ fNode = new DOMType(fDocument, sourceRange, new String(name), nameRange,
+ modifiers, CharArrayOps.charcharToString(superinterfaces), isClass);
+ addChild(fNode);
+ fStack.push(fNode);
+ }
+}
+/**
+ * Finishes the configuration of the class DOM object which
+ * was created by a previous enterClass call.
+ *
+ * @see ISourceElementRequestor#exitClass(int)
+ */
+public void exitClass(int declarationEnd) {
+ exitType(declarationEnd);
+}
+/**
+ * Finishes the configuration of the method DOM object which
+ * was created by a previous enterConstructor call.
+ *
+ * @see ISourceElementRequestor#exitConstructor(int)
+ */
+public void exitConstructor(int declarationEnd) {
+ exitMember(declarationEnd);
+}
+/**
+ */
+public void exitField(int initializationStart, int declarationEnd, int declarationSourceEnd) {
+ exitMember(declarationEnd);
+}
+/**
+ */
+public void exitInitializer(int declarationEnd) {
+ exitMember(declarationEnd);
+}
+/**
+ */
+public void exitInterface(int declarationEnd) {
+ exitType(declarationEnd);
+}
+/**
+ * Finishes the configuration of the member.
+ *
+ * @param declarationEnd - a source position corresponding to the end of the method
+ * declaration. This can include whitespace and comments following the closing bracket.
+ */
+protected void exitMember(int declarationEnd) {
+ DOMMember m= (DOMMember) fStack.pop();
+ m.setSourceRangeEnd(declarationEnd);
+ fNode = m;
+}
+/**
+ */
+public void exitMethod(int declarationEnd) {
+ exitMember(declarationEnd);
+}
+/**
+ * @see AbstractDOMBuilder#exitType
+ *
+ * @param declarationEnd - a source position corresponding to the end of the class
+ * declaration. This can include whitespace and comments following the closing bracket.
+ */
+protected void exitType(int declarationEnd) {
+ exitType(declarationEnd, declarationEnd);
+}
+/**
+ * Creates a new parser.
+ */
+protected SourceElementParser getParser(Map settings) {
+ return new SourceElementParser(this, new DefaultProblemFactory());//, new CompilerOptions(settings));
+}
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/messages.properties b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/messages.properties
new file mode 100644
index 0000000..347a008
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/messages.properties
@@ -0,0 +1,232 @@
+###############################################################################
+# Copyright (c) 2000, 2003 IBM Corporation and others.
+# All rights reserved. This program and the accompanying materials
+# are made available under the terms of the Common Public License v1.0
+# which accompanies this distribution, and is available at
+# http://www.eclipse.org/legal/cpl-v10.html
+#
+# Contributors:
+# IBM Corporation - initial API and implementation
+###############################################################################
+### JavaModel messages.
+
+### hierarchy
+hierarchy.nullProject = Project argument cannot be null.
+hierarchy.nullRegion = Region cannot be null.
+hierarchy.nullFocusType = Type focus cannot be null.
+hierarchy.creating = Creating type hierarchy...
+hierarchy.creatingOnType = Creating type hierarchy on {0}...
+
+### java element
+element.doesNotExist = {0} does not exist.
+element.invalidClassFileName = Class file name must end with .class.
+element.cannotReconcile = Must create reconciler on a working copy.
+element.reconciling = Reconciling...
+element.attachingSource = Attaching source...
+element.invalidType = Type is not one of the defined constants.
+element.classpathCycle = A cycle was detected in the project''s classpath.
+element.onlyOneJavaModel = Cannot instantiate more than one Java Model.
+element.projectDoesNotExist = Project {0} not present
+element.invalidResourceForProject = Illegal argument - must be one of IProject, IFolder, or IFile
+element.nullName = Name cannot be null.
+element.nullType = Type cannot be null.
+element.illegalParent = Illegal parent argument.
+element.notPresent = Not present
+
+### java model operations
+operation.needElements = Operation requires one or more elements.
+operation.needName = Operation requires a name.
+operation.needPath = Operation requires a path.
+operation.needAbsolutePath = Operation requires an absolute path. Relative path specified was: ''{0}''
+operation.needString = Operation requires a String.
+operation.notSupported = Operation not supported for specified element type(s):
+operation.cancelled = Operation cancelled.
+operation.nullContainer = Container cannot be null.
+operation.nullName = Name cannot be null.
+operation.copyElementProgress = Copying elements...
+operation.moveElementProgress = Moving elements...
+operation.renameElementProgress = Renaming elements...
+operation.copyResourceProgress = Copying resources...
+operation.moveResourceProgress = Moving resources...
+operation.renameResourceProgress = Renaming resources...
+operation.createUnitProgress = Creating a compilation unit...
+operation.createFieldProgress = Creating a field...
+operation.createImportsProgress = Creating imports...
+operation.createInitializerProgress = Creating an initializer...
+operation.createMethodProgress = Creating a method...
+operation.createPackageProgress = Creating a package declaration...
+operation.createPackageFragmentProgress = Creating package fragment(s)...
+operation.createTypeProgress = Creating a type...
+operation.deleteElementProgress = Deleting elements...
+operation.deleteResourceProgress = Deleting resources...
+operation.cannotRenameDefaultPackage = Default package cannot be renamed.
+operation.pathOutsideProject = Path ''{0}'' must denote location inside project {1}
+operation.sortelements = Sorting elements...
+
+### working copy
+workingCopy.commit = Committing working copy...
+
+### build status messages
+build.preparingBuild = Preparing for build
+build.readStateProgress = Reading saved built state for project {0}
+build.saveStateProgress = Saving built state for project {0}
+build.saveStateComplete = Saved in {0} ms
+build.readingDelta = Reading resource change information for {0}
+build.analyzingDeltas = Analyzing deltas
+build.analyzingSources = Analyzing sources
+build.cleaningOutput = Cleaning output folder
+build.copyingResources = Copying resources to the output folder
+build.compiling = Compiling {0}
+build.foundHeader = Found
+build.fixedHeader = Fixed
+build.oneError = 1 error
+build.oneWarning = 1 warning
+build.multipleErrors = {0} errors
+build.multipleWarnings = {0} warnings
+build.done = Build done
+
+### build errors
+build.wrongFileFormat = Wrong file format.
+build.cannotSaveState = Error saving last build state for project {0}.
+build.cannotSaveStates = Error saving build states.
+build.initializationError = Builder initialization error.
+build.serializationError = Builder serialization error.
+
+### build inconsistencies
+build.duplicateClassFile = The type {0} is already defined.
+build.duplicateResource = The resource is a duplicate and was not copied to the output folder.
+build.inconsistentClassFile = A class file was not written. The project may be inconsistent, if so try refreshing this project and rebuilding it.
+build.inconsistentProject = The project was not built due to "{0}". Fix the problem, then try refreshing this project and rebuilding it since it may be inconsistent.
+build.incompleteClassPath = The project was not built since its classpath is incomplete. Cannot find the class file for {0}. Fix the classpath then try rebuilding this project.
+build.missingSourceFile = The project was not built since the source file {0} could not be read.
+build.prereqProjectHasClasspathProblems = The project was not built since it depends on {0}, which has classpath problems.
+build.prereqProjectMustBeRebuilt = The project cannot be built until {0} is rebuilt. Rebuilding all projects is recommended.
+build.abortDueToClasspathProblems = The project was not built due to classpath errors (incomplete or involved in cycle).
+
+### status
+status.cannotUseDeviceOnPath = Operation requires a path with no device. Path specified was: {0}
+status.coreException = Core exception.
+status.defaultPackeReadOnly = Default package is read-only.
+status.evaluationError = Evaluation error: {0}.
+status.JDOMError = JDOM error.
+status.IOException = I/O exception.
+status.indexOutOfBounds = Index out of bounds.
+status.invalidContents = Invalid contents specified.
+status.invalidDestination = Invalid destination: ''{0}''.
+status.invalidName = Invalid name specified: {0}.
+status.invalidPackage = Invalid package: {0}.
+status.invalidPath = Invalid path: ''{0}''.
+status.invalidProject = Invalid project: {0}.
+status.invalidResource = Invalid resource: {0}.
+status.invalidResourceType = Invalid resource type for {0}.
+status.invalidSibling = Invalid sibling: {0}.
+status.nameCollision = {0} already exists in target.
+status.noLocalContents = Cannot find local contents for resource: {0}
+status.OK = OK
+status.readOnly = {0} is read-only.
+status.targetException = Target exception.
+status.updateConflict = Update conflict.
+
+### classpath
+classpath.buildPath = Build path
+classpath.cannotNestEntryInEntry = Cannot nest ''{0}'' inside ''{1}''. To enable the nesting exclude ''{2}'' from ''{1}''.
+classpath.cannotNestEntryInLibrary = Cannot nest ''{0}'' inside library ''{1}''.
+classpath.cannotNestEntryInOutput = Cannot nest ''{0}'' inside output folder ''{1}''.
+classpath.cannotNestOutputInEntry = Cannot nest output folder ''{0}'' inside ''{1}''.
+classpath.cannotNestOutputInOutput = Cannot nest output folder ''{0}'' inside output folder ''{1}''.
+classpath.cannotReadClasspathFile = Unable to read ''{0}/.classpath'' file.
+classpath.cannotReferToItself = Project cannot reference itself: {0}
+classpath.cannotUseDistinctSourceFolderAsOutput = Source folder ''{0}'' cannot output to distinct source folder ''{1}''.
+classpath.cannotUseLibraryAsOutput = Source folder ''{0}'' cannot output to library ''{1}''.
+classpath.closedProject = Required project: {0} needs to be open.
+classpath.couldNotWriteClasspathFile = Could not write ''{0}/.classpath'': {1}
+classpath.cycle = A cycle was detected in the classpath of project: {0}
+classpath.duplicateEntryPath = Classpath contains duplicate entry: {0}
+classpath.illegalContainerPath = Illegal classpath container path: ''{0}'', must have at least one segment (containerID+hints).
+classpath.illegalEntryInClasspathFile = Illegal entry in ''{0}/.classpath'' file: {1}
+classpath.illegalLibraryPath = Illegal path for required library: ''{0}''.
+classpath.illegalProjectPath = Illegal path for required project: ''{0}''.
+classpath.illegalSourceFolderPath = Illegal path for required source folder: ''{0}''.
+classpath.illegalVariablePath = Illegal classpath variable path: ''{0}'', must have at least one segment.
+classpath.invalidClasspathInClasspathFile = Invalid classpath in ''{0}/.classpath'' file: {1}
+classpath.invalidContainer = Invalid classpath container: {0}
+classpath.mustEndWithSlash = End exclusion filter ''{0}'' with / to fully exclude ''{1}''.
+classpath.unboundContainerPath = Unbound classpath container: ''{0}''.
+classpath.unboundLibrary = Missing required library: ''{0}''.
+classpath.unboundProject = Missing required Java project: {0}.
+classpath.settingOutputLocationProgress = Setting output location for: ''{0}''
+classpath.settingProgress = Setting classpath for: {0}
+classpath.unboundSourceAttachment = Invalid source attachment: ''{0}'' for required library ''{1}''.
+classpath.unboundSourceFolder = Missing required source folder: ''{0}''.
+classpath.unboundVariablePath = Unbound classpath variable: ''{0}''.
+classpath.unknownKind = Unknown kind: {0}
+classpath.xmlFormatError = XML format error in ''{0}/.classpath'' file: {1}
+classpath.disabledExclusionPatterns = Exclusion patterns are disabled, cannot exclude from entry: ''{0}''.
+classpath.disabledMultipleOutputLocations = Multiple output locations are disabled, cannot associate entry: ''{0}'' with a specific output.
+
+### miscellaneous
+file.notFound = File not found: ''{0}''.
+file.badFormat = Bad format.
+variable.badFormat = Bad format for variables.
+option.badFormat = Bad format for options.
+path.nullPath = Path cannot be null.
+path.mustBeAbsolute = Path must be absolute.
+cache.invalidLoadFactor = Incorrect load factor
+
+### code assist
+codeAssist.nullRequestor = Requestor cannot be null.
+
+### java conventions
+convention.unit.nullName = Compilation unit name must not be null.
+convention.unit.notJavaName = Compilation unit name must end with .java.
+convention.classFile.nullName = .class file name must not be null.
+convention.classFile.notJavaName = .class file name must end with .class.
+convention.illegalIdentifier = ''{0}'' is not a valid Java identifier.
+convention.import.nullImport = An import declaration must not be null.
+convention.import.unqualifiedImport = An import declaration must not end with an unqualified *.
+convention.type.nullName = A Java type name must not be null.
+convention.type.nameWithBlanks = A Java type name must not start or end with a blank.
+convention.type.dollarName = By convention, Java type names usually don''t contain the $ character.
+convention.type.lowercaseName = By convention, Java type names usually start with an uppercase letter.
+convention.type.invalidName = The type name ''{0}'' is not a valid identifier.
+convention.package.nullName = A package name must not be null.
+convention.package.emptyName = A package name must not be empty.
+convention.package.dotName = A package name cannot start or end with a dot.
+convention.package.nameWithBlanks = A package name must not start or end with a blank.
+convention.package.consecutiveDotsName = A package name must not contain two consecutive dots.
+convention.package.uppercaseName = By convention, package names usually start with a lowercase letter.
+
+### DOM
+dom.cannotDetail = Unable to generate detailed source indexes.
+dom.nullTypeParameter = Cannot add parameter with null type
+dom.nullNameParameter = Cannot add parameter with null name
+dom.nullReturnType = Return type cannot be null
+dom.nullExceptionType = Cannot add null exception
+dom.mismatchArgNamesAndTypes = Types and names must have identical length
+dom.addNullChild = Attempt to add null child
+dom.addIncompatibleChild = Attempt to add child of incompatible type
+dom.addChildWithParent = Attempt to add child that is already parented
+dom.unableAddChild = Attempt to add child to node that cannot have children
+dom.addAncestorAsChild = Attempt to add ancestor as child
+dom.addNullSibling = Attempt to insert null sibling
+dom.addSiblingBeforeRoot = Attempt to insert sibling before root node
+dom.addIncompatibleSibling = Attempt to insert sibling of incompatible type
+dom.addSiblingWithParent = Attempt to insert sibling that is already parented
+dom.addAncestorAsSibling = Attempt to insert ancestor as sibling
+dom.addNullInterface = Cannot add null interface
+dom.nullInterfaces = Illegal to set super interfaces to null
+
+### eval
+eval.needBuiltState = Cannot evaluate if the project has not been built once
+
+### correction
+correction.nullRequestor = Requestor cannot be null.
+correction.nullUnit = Compilation unit cannot be null.
+
+### JDT Adapter
+ant.jdtadapter.info.usingJdtCompiler = Using JDT compiler
+ant.jdtadapter.error.missingJDTCompiler = Cannot find the JDT compiler
+ant.jdtadapter.error.missingJRELIB = Cannot bind the JRE_LIB variable. To solve this problem, you can either set the JRE_LIB variable or use the bootclasspath parameter in your ant javac task
+ant.jdtadapter.error.ignoringMemoryInitialSize= Since fork is false, ignoring memoryInitialSize setting
+ant.jdtadapter.error.ignoringMemoryMaximumSize= Since fork is false, ignoring memoryMaximumSize setting
+ant.jdtadapter.error.compilationFailed = Compilation failed. Compiler errors are available in {0}
\ No newline at end of file
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/CharArrayOps.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/CharArrayOps.java
new file mode 100644
index 0000000..7041eb4
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/CharArrayOps.java
@@ -0,0 +1,145 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core.util;
+
+/**
+ * A class to do characters operations so that we can use
+ * char arrays more effectively.
+ */
+public class CharArrayOps { // TODO: should promote to CharOperation
+/**
+ * Returns the char arrays as an array of Strings
+ */
+public static String[] charcharToString(char[][] charchar) {
+ if (charchar == null) {
+ return null;
+ }
+ String[] strings= new String[charchar.length];
+ for (int i= 0; i < charchar.length; i++) {
+ strings[i]= new String(charchar[i]);
+ }
+ return strings;
+}
+/**
+ * Returns the char array as a String
+ */
+public static String charToString(char[] chars) {
+ if (chars == null) {
+ return null;
+ } else {
+ return new String(chars);
+ }
+}
+/**
+ * Concatinates the two arrays into one big array.
+ * If the first array is null, returns the second array.
+ * If the second array is null, returns the first array.
+ *
+ * @param first - the array which the other array is concatinated onto
+ * @param second - the array which is to be concatinated onto the first array
+ */
+public static char[] concat(char[] first, char[] second) {
+ if (first == null)
+ return second;
+ if (second == null)
+ return first;
+
+ int length1 = first.length;
+ int length2 = second.length;
+ char[] result = new char[length1 + length2];
+ System.arraycopy(first, 0, result, 0, length1);
+ System.arraycopy(second, 0, result, length1, length2);
+ return result;
+}
+/**
+ * Checks the two character arrays for equality.
+ *
+ * @param first - one of the arrays to be compared
+ * @param second - the other array which is to be compared
+ */
+public static boolean equals(char[] first, char[] second) {
+ if (first == second)
+ return true;
+ if (first == null || second == null)
+ return false;
+ if (first.length != second.length)
+ return false;
+
+ for (int i = 0, length = first.length; i < length; i++)
+ if (first[i] != second[i])
+ return false;
+ return true;
+}
+/**
+ * Returns the index of the first occurrence of character in buffer,
+ * starting from offset, or -1 if not found.
+ */
+public static int indexOf(char character, char[] buffer, int offset) {
+ for (int i= offset; i < buffer.length; i++) {
+ if (buffer[i] == character) {
+ return i;
+ }
+ }
+ return -1;
+}
+/**
+ * Extracts a sub-array from the given array, starting
+ * at the given startIndex and proceeding for length characters.
+ * Returns null if:
+ * 1. the src array is null
+ * 2. the start index is out of bounds
+ * 3. the length parameter specifies a end point which is out of bounds
+ * Does not return a copy of the array if possible, in other words, if start is zero
+ * and length equals the length of the src array.
+ *
+ * @param src - the array from which elements need to be copied
+ * @param start - the start index in the src array
+ * @param length - the number of characters to copy
+ */
+public static char[] subarray(char[] src, int start, int length) {
+ if (src == null)
+ return null;
+ int srcLength = src.length;
+ if (start < 0 || start >= srcLength)
+ return null;
+ if (length < 0 || start + length > srcLength)
+ return null;
+ if (srcLength == length && start == 0)
+ return src;
+
+ char[] result = new char[length];
+ if (length > 0)
+ System.arraycopy(src, start, result, 0, length);
+ return result;
+}
+/**
+ * Extracts a substring from the given array, starting
+ * at the given startIndex and proceeding for length characters.
+ * Returns null if:
+ * 1. the src array is null
+ * 2. the start index is out of bounds
+ * 3. the length parameter specifies a end point which is out of bounds
+ * Does not return a copy of the array if possible (if start is zero
+ * and length equals the length of the src array).
+ *
+ * @param src - the array from which elements need to be copied
+ * @param start - the start index in the src array
+ * @param length - the number of characters to copy
+ */
+public static String substring(char[] src, int start, int length) {
+ char[] chars= subarray(src, start, length);
+ if (chars != null) {
+ return new String(chars);
+ } else {
+ return null;
+ }
+}
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/ICacheEnumeration.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/ICacheEnumeration.java
new file mode 100644
index 0000000..1c77c5e
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/ICacheEnumeration.java
@@ -0,0 +1,39 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core.util;
+
+import java.util.Enumeration;
+
+/**
+ * The ICacheEnumeration
is used to iterate over both the keys
+ * and values in an LRUCache. The getValue()
method returns the
+ * value of the last key to be retrieved using nextElement()
.
+ * The nextElement()
method must be called before the
+ * getValue()
method.
+ *
+ * LRUCacheEntry
), know their key. For this reason,
+ * Hashtable lookups don't have to be made at each step of the iteration.
+ *
+ * LRUCache
is a hashtable that stores a finite number of elements.
+ * When an attempt is made to add values to a full cache, the least recently used values
+ * in the cache are discarded to make room for the new values as necessary.
+ *
+ * ILRUCacheable
interface.
+ *
+ * DEFAULT_SPACELIMIT
.
+ */
+ public LRUCache() {
+
+ this(DEFAULT_SPACELIMIT);
+ }
+ /**
+ * Creates a new cache.
+ * @param size Size of Cache
+ */
+ public LRUCache(int size) {
+
+ fTimestampCounter = fCurrentSpace = 0;
+ fEntryQueue = fEntryQueueTail = null;
+ fEntryTable = new Hashtable(size);
+ fSpaceLimit = size;
+ }
+ /**
+ * Returns a new cache containing the same contents.
+ *
+ * @return New copy of object.
+ */
+ public Object clone() {
+
+ LRUCache newCache = newInstance(fSpaceLimit);
+ LRUCacheEntry qEntry;
+
+ /* Preserve order of entries by copying from oldest to newest */
+ qEntry = this.fEntryQueueTail;
+ while (qEntry != null) {
+ newCache.privateAdd (qEntry._fKey, qEntry._fValue, qEntry._fSpace);
+ qEntry = qEntry._fPrevious;
+ }
+ return newCache;
+ }
+ /**
+ * Flushes all entries from the cache.
+ */
+ public void flush() {
+
+ fCurrentSpace = 0;
+ LRUCacheEntry entry = fEntryQueueTail; // Remember last entry
+ fEntryTable = new Hashtable(); // Clear it out
+ fEntryQueue = fEntryQueueTail = null;
+ while (entry != null) { // send deletion notifications in LRU order
+ privateNotifyDeletionFromCache(entry);
+ entry = entry._fPrevious;
+ }
+ }
+ /**
+ * Flushes the given entry from the cache. Does nothing if entry does not
+ * exist in cache.
+ *
+ * @param key Key of object to flush
+ */
+ public void flush (Object key) {
+
+ LRUCacheEntry entry;
+
+ entry = (LRUCacheEntry) fEntryTable.get(key);
+
+ /* If entry does not exist, return */
+ if (entry == null) return;
+
+ this.privateRemoveEntry (entry, false);
+ }
+ /**
+ * Answers the value in the cache at the given key.
+ * If the value is not in the cache, returns null
+ *
+ * @param key Hash table key of object to retrieve
+ * @return Retreived object, or null if object does not exist
+ */
+ public Object get(Object key) {
+
+ LRUCacheEntry entry = (LRUCacheEntry) fEntryTable.get(key);
+ if (entry == null) {
+ return null;
+ }
+
+ this.updateTimestamp (entry);
+ return entry._fValue;
+ }
+ /**
+ * Returns the amount of space that is current used in the cache.
+ */
+ public int getCurrentSpace() {
+ return fCurrentSpace;
+ }
+ /**
+ * Returns the maximum amount of space available in the cache.
+ */
+ public int getSpaceLimit() {
+ return fSpaceLimit;
+ }
+ /**
+ * Returns an Enumeration of the keys currently in the cache.
+ */
+ public Enumeration keys() {
+
+ return fEntryTable.keys();
+ }
+ /**
+ * Returns an enumeration that iterates over all the keys and values
+ * currently in the cache.
+ */
+ public ICacheEnumeration keysAndValues() {
+ return new ICacheEnumeration() {
+
+ Enumeration fValues = fEntryTable.elements();
+ LRUCacheEntry fEntry;
+
+ public boolean hasMoreElements() {
+ return fValues.hasMoreElements();
+ }
+
+ public Object nextElement() {
+ fEntry = (LRUCacheEntry) fValues.nextElement();
+ return fEntry._fKey;
+ }
+
+ public Object getValue() {
+ if (fEntry == null) {
+ throw new java.util.NoSuchElementException();
+ }
+ return fEntry._fValue;
+ }
+ };
+ }
+ /**
+ * Ensures there is the specified amount of free space in the receiver,
+ * by removing old entries if necessary. Returns true if the requested space was
+ * made available, false otherwise.
+ *
+ * @param space Amount of space to free up
+ */
+ protected boolean makeSpace (int space) {
+
+ int limit;
+
+ limit = this.getSpaceLimit();
+
+ /* if space is already available */
+ if (fCurrentSpace + space <= limit) {
+ return true;
+ }
+
+ /* if entry is too big for cache */
+ if (space > limit) {
+ return false;
+ }
+
+ /* Free up space by removing oldest entries */
+ while (fCurrentSpace + space > limit && fEntryQueueTail != null) {
+ this.privateRemoveEntry (fEntryQueueTail, false);
+ }
+ return true;
+ }
+ /**
+ * Returns a new LRUCache instance
+ */
+ protected LRUCache newInstance(int size) {
+ return new LRUCache(size);
+ }
+ /**
+ * Adds an entry for the given key/value/space.
+ */
+ protected void privateAdd (Object key, Object value, int space) {
+
+ LRUCacheEntry entry;
+
+ entry = new LRUCacheEntry(key, value, space);
+ this.privateAddEntry (entry, false);
+ }
+ /**
+ * Adds the given entry from the receiver.
+ * @param shuffle Indicates whether we are just shuffling the queue
+ * (in which case, the entry table is not modified).
+ */
+ protected void privateAddEntry (LRUCacheEntry entry, boolean shuffle) {
+
+ if (!shuffle) {
+ fEntryTable.put (entry._fKey, entry);
+ fCurrentSpace += entry._fSpace;
+ }
+
+ entry._fTimestamp = fTimestampCounter++;
+ entry._fNext = this.fEntryQueue;
+ entry._fPrevious = null;
+
+ if (fEntryQueue == null) {
+ /* this is the first and last entry */
+ fEntryQueueTail = entry;
+ } else {
+ fEntryQueue._fPrevious = entry;
+ }
+
+ fEntryQueue = entry;
+ }
+ /**
+ * An entry has been removed from the cache, for example because it has
+ * fallen off the bottom of the LRU queue.
+ * Subclasses could over-ride this to implement a persistent cache below the LRU cache.
+ */
+ protected void privateNotifyDeletionFromCache(LRUCacheEntry entry) {
+ // Default is NOP.
+ }
+ /**
+ * Removes the entry from the entry queue.
+ * @param shuffle indicates whether we are just shuffling the queue
+ * (in which case, the entry table is not modified).
+ */
+ protected void privateRemoveEntry (LRUCacheEntry entry, boolean shuffle) {
+
+ LRUCacheEntry previous, next;
+
+ previous = entry._fPrevious;
+ next = entry._fNext;
+
+ if (!shuffle) {
+ fEntryTable.remove(entry._fKey);
+ fCurrentSpace -= entry._fSpace;
+ privateNotifyDeletionFromCache(entry);
+ }
+
+ /* if this was the first entry */
+ if (previous == null) {
+ fEntryQueue = next;
+ } else {
+ previous._fNext = next;
+ }
+
+ /* if this was the last entry */
+ if (next == null) {
+ fEntryQueueTail = previous;
+ } else {
+ next._fPrevious = previous;
+ }
+ }
+ /**
+ * Sets the value in the cache at the given key. Returns the value.
+ *
+ * @param key Key of object to add.
+ * @param value Value of object to add.
+ * @return added value.
+ */
+ public Object put(Object key, Object value) {
+
+ int newSpace, oldSpace, newTotal;
+ LRUCacheEntry entry;
+
+ /* Check whether there's an entry in the cache */
+ newSpace = spaceFor (key, value);
+ entry = (LRUCacheEntry) fEntryTable.get (key);
+
+ if (entry != null) {
+
+ /**
+ * Replace the entry in the cache if it would not overflow
+ * the cache. Otherwise flush the entry and re-add it so as
+ * to keep cache within budget
+ */
+ oldSpace = entry._fSpace;
+ newTotal = getCurrentSpace() - oldSpace + newSpace;
+ if (newTotal <= getSpaceLimit()) {
+ updateTimestamp (entry);
+ entry._fValue = value;
+ entry._fSpace = newSpace;
+ this.fCurrentSpace = newTotal;
+ return value;
+ } else {
+ privateRemoveEntry (entry, false);
+ }
+ }
+ if (makeSpace(newSpace)) {
+ privateAdd (key, value, newSpace);
+ }
+ return value;
+ }
+ /**
+ * Removes and returns the value in the cache for the given key.
+ * If the key is not in the cache, returns null.
+ *
+ * @param key Key of object to remove from cache.
+ * @return Value removed from cache.
+ */
+ public Object removeKey (Object key) {
+
+ LRUCacheEntry entry = (LRUCacheEntry) fEntryTable.get(key);
+ if (entry == null) {
+ return null;
+ }
+ Object value = entry._fValue;
+ this.privateRemoveEntry (entry, false);
+ return value;
+ }
+ /**
+ * Sets the maximum amount of space that the cache can store
+ *
+ * @param limit Number of units of cache space
+ */
+ public void setSpaceLimit(int limit) {
+ if (limit < fSpaceLimit) {
+ makeSpace(fSpaceLimit - limit);
+ }
+ fSpaceLimit = limit;
+ }
+ /**
+ * Returns the space taken by the given key and value.
+ */
+ protected int spaceFor (Object key, Object value) {
+
+ if (value instanceof ILRUCacheable) {
+ return ((ILRUCacheable) value).getCacheFootprint();
+ } else {
+ return 1;
+ }
+ }
+/**
+ * Returns a String that represents the value of this object. This method
+ * is for debugging purposes only.
+ */
+public String toString() {
+ return
+ "LRUCache " + (fCurrentSpace * 100.0 / fSpaceLimit) + "% full\n" + //$NON-NLS-1$ //$NON-NLS-2$
+ this.toStringContents();
+}
+/**
+ * Returns a String that represents the contents of this object. This method
+ * is for debugging purposes only.
+ */
+protected String toStringContents() {
+ StringBuffer result = new StringBuffer();
+ int length = fEntryTable.size();
+ Object[] unsortedKeys = new Object[length];
+ String[] unsortedToStrings = new String[length];
+ Enumeration e = this.keys();
+ for (int i = 0; i < length; i++) {
+ Object key = e.nextElement();
+ unsortedKeys[i] = key;
+ unsortedToStrings[i] =
+ (key instanceof net.sourceforge.phpdt.internal.core.JavaElement) ?
+ ((net.sourceforge.phpdt.internal.core.JavaElement)key).getElementName() :
+ key.toString();
+ }
+ ToStringSorter sorter = new ToStringSorter();
+ sorter.sort(unsortedKeys, unsortedToStrings);
+ for (int i = 0; i < length; i++) {
+ String toString = sorter.sortedStrings[i];
+ Object value = this.get(sorter.sortedObjects[i]);
+ result.append(toString);
+ result.append(" -> "); //$NON-NLS-1$
+ result.append(value);
+ result.append("\n"); //$NON-NLS-1$
+ }
+ return result.toString();
+}
+ /**
+ * Updates the timestamp for the given entry, ensuring that the queue is
+ * kept in correct order. The entry must exist
+ */
+ protected void updateTimestamp (LRUCacheEntry entry) {
+
+ entry._fTimestamp = fTimestampCounter++;
+ if (fEntryQueue != entry) {
+ this.privateRemoveEntry (entry, true);
+ this.privateAddEntry (entry, true);
+ }
+ return;
+ }
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/ReferenceInfoAdapter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/ReferenceInfoAdapter.java
new file mode 100644
index 0000000..a53bebd
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/ReferenceInfoAdapter.java
@@ -0,0 +1,46 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core.util;
+
+/**
+ * An adapter which implements the methods for handling
+ * reference information from the parser.
+ */
+public abstract class ReferenceInfoAdapter {
+/**
+ * Does nothing.
+ */
+public void acceptConstructorReference(char[] typeName, int argCount, int sourcePosition) {}
+/**
+ * Does nothing.
+ */
+public void acceptFieldReference(char[] fieldName, int sourcePosition) {}
+/**
+ * Does nothing.
+ */
+public void acceptMethodReference(char[] methodName, int argCount, int sourcePosition) {}
+/**
+ * Does nothing.
+ */
+public void acceptTypeReference(char[][] typeName, int sourceStart, int sourceEnd) {}
+/**
+ * Does nothing.
+ */
+public void acceptTypeReference(char[] typeName, int sourcePosition) {}
+/**
+ * Does nothing.
+ */
+public void acceptUnknownReference(char[][] name, int sourceStart, int sourceEnd) {}
+/**
+ * Does nothing.
+ */
+public void acceptUnknownReference(char[] name, int sourcePosition) {}
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/SimpleLookupTable.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/SimpleLookupTable.java
new file mode 100644
index 0000000..01c61a6
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/SimpleLookupTable.java
@@ -0,0 +1,153 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core.util;
+
+/**
+ * A simple lookup table is a non-synchronized Hashtable, whose keys
+ * and values are Objects. It also uses linear probing to resolve collisions
+ * rather than a linked list of hash table entries.
+ */
+public final class SimpleLookupTable implements Cloneable {
+
+// to avoid using Enumerations, walk the individual tables skipping nulls
+public Object[] keyTable;
+public Object[] valueTable;
+public int elementSize; // number of elements in the table
+public int threshold;
+
+public SimpleLookupTable() {
+ this(13);
+}
+
+public SimpleLookupTable(int size) {
+ if (size < 3) size = 3;
+ this.elementSize = 0;
+ this.threshold = size + 1; // size is the expected number of elements
+ int tableLength = 2 * size + 1;
+ this.keyTable = new Object[tableLength];
+ this.valueTable = new Object[tableLength];
+}
+
+public Object clone() throws CloneNotSupportedException {
+ SimpleLookupTable result = (SimpleLookupTable) super.clone();
+ result.elementSize = this.elementSize;
+ result.threshold = this.threshold;
+
+ int length = this.keyTable.length;
+ result.keyTable = new Object[length];
+ System.arraycopy(this.keyTable, 0, result.keyTable, 0, length);
+
+ length = this.valueTable.length;
+ result.valueTable = new Object[length];
+ System.arraycopy(this.valueTable, 0, result.valueTable, 0, length);
+ return result;
+}
+
+public boolean containsKey(Object key) {
+ int length = keyTable.length;
+ int index = (key.hashCode() & 0x7FFFFFFF) % length;
+ Object currentKey;
+ while ((currentKey = keyTable[index]) != null) {
+ if (currentKey.equals(key)) return true;
+ if (++index == length) index = 0;
+ }
+ return false;
+}
+
+public Object get(Object key) {
+ int length = keyTable.length;
+ int index = (key.hashCode() & 0x7FFFFFFF) % length;
+ Object currentKey;
+ while ((currentKey = keyTable[index]) != null) {
+ if (currentKey.equals(key)) return valueTable[index];
+ if (++index == length) index = 0;
+ }
+ return null;
+}
+
+public Object keyForValue(Object valueToMatch) {
+ if (valueToMatch != null)
+ for (int i = 0, l = valueTable.length; i < l; i++)
+ if (valueToMatch.equals(valueTable[i]))
+ return keyTable[i];
+ return null;
+}
+
+public Object put(Object key, Object value) {
+ int length = keyTable.length;
+ int index = (key.hashCode() & 0x7FFFFFFF) % length;
+ Object currentKey;
+ while ((currentKey = keyTable[index]) != null) {
+ if (currentKey.equals(key)) return valueTable[index] = value;
+ if (++index == length) index = 0;
+ }
+ keyTable[index] = key;
+ valueTable[index] = value;
+
+ // assumes the threshold is never equal to the size of the table
+ if (++elementSize > threshold) rehash();
+ return value;
+}
+
+public void removeKey(Object key) {
+ int length = keyTable.length;
+ int index = (key.hashCode() & 0x7FFFFFFF) % length;
+ Object currentKey;
+ while ((currentKey = keyTable[index]) != null) {
+ if (currentKey.equals(key)) {
+ elementSize--;
+ keyTable[index] = null;
+ valueTable[index] = null;
+ if (keyTable[index + 1 == length ? 0 : index + 1] != null)
+ rehash(); // only needed if a possible collision existed
+ return;
+ }
+ if (++index == length) index = 0;
+ }
+}
+
+public void removeValue(Object valueToRemove) {
+ boolean rehash = false;
+ for (int i = 0, l = valueTable.length; i < l; i++) {
+ Object value = valueTable[i];
+ if (value != null && value.equals(valueToRemove)) {
+ elementSize--;
+ keyTable[i] = null;
+ valueTable[i] = null;
+ if (!rehash && keyTable[i + 1 == l ? 0 : i + 1] != null)
+ rehash = true; // only needed if a possible collision existed
+ }
+ }
+ if (rehash) rehash();
+}
+
+private void rehash() {
+ SimpleLookupTable newLookupTable = new SimpleLookupTable(elementSize * 2); // double the number of expected elements
+ Object currentKey;
+ for (int i = keyTable.length; --i >= 0;)
+ if ((currentKey = keyTable[i]) != null)
+ newLookupTable.put(currentKey, valueTable[i]);
+
+ this.keyTable = newLookupTable.keyTable;
+ this.valueTable = newLookupTable.valueTable;
+ this.elementSize = newLookupTable.elementSize;
+ this.threshold = newLookupTable.threshold;
+}
+
+public String toString() {
+ String s = ""; //$NON-NLS-1$
+ Object object;
+ for (int i = 0, l = valueTable.length; i < l; i++)
+ if ((object = valueTable[i]) != null)
+ s += keyTable[i].toString() + " -> " + object.toString() + "\n"; //$NON-NLS-2$ //$NON-NLS-1$
+ return s;
+}
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/ToStringSorter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/ToStringSorter.java
new file mode 100644
index 0000000..e2632f3
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/util/ToStringSorter.java
@@ -0,0 +1,75 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.core.util;
+
+/**
+ * The SortOperation takes a collection of objects and returns
+ * a sorted collection of these objects. The sorting of these
+ * objects is based on their toString(). They are sorted in
+ * alphabetical order.
+ */
+public class ToStringSorter {
+ Object[] sortedObjects;
+ String[] sortedStrings;
+/**
+ * Returns true if stringTwo is 'greater than' stringOne
+ * This is the 'ordering' method of the sort operation.
+ */
+public boolean compare(String stringOne, String stringTwo) {
+ return stringOne.compareTo(stringTwo) < 0;
+}
+/**
+ * Sort the objects in sorted collection and return that collection.
+ */
+private void quickSort(int left, int right) {
+ int originalLeft = left;
+ int originalRight = right;
+ int midIndex = (left + right) / 2;
+ String midToString = this.sortedStrings[midIndex];
+
+ do {
+ while (compare(this.sortedStrings[left], midToString))
+ left++;
+ while (compare(midToString, this.sortedStrings[right]))
+ right--;
+ if (left <= right) {
+ Object tmp = this.sortedObjects[left];
+ this.sortedObjects[left] = this.sortedObjects[right];
+ this.sortedObjects[right] = tmp;
+ String tmpToString = this.sortedStrings[left];
+ this.sortedStrings[left] = this.sortedStrings[right];
+ this.sortedStrings[right] = tmpToString;
+ left++;
+ right--;
+ }
+ } while (left <= right);
+
+ if (originalLeft < right)
+ quickSort(originalLeft, right);
+ if (left < originalRight)
+ quickSort(left, originalRight);
+}
+/**
+ * Return a new sorted collection from this unsorted collection.
+ * Sort using quick sort.
+ */
+public void sort(Object[] unSortedObjects, String[] unsortedStrings) {
+ int size = unSortedObjects.length;
+ this.sortedObjects = new Object[size];
+ this.sortedStrings = new String[size];
+
+ //copy the array so can return a new sorted collection
+ System.arraycopy(unSortedObjects, 0, this.sortedObjects, 0, size);
+ System.arraycopy(unsortedStrings, 0, this.sortedStrings, 0, size);
+ if (size > 1)
+ quickSort(0, size - 1);
+}
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/Assert.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/Assert.java
index c6f4e5c..8b3356a 100644
--- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/Assert.java
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/Assert.java
@@ -34,7 +34,7 @@ public final class Assert {
* breakage when assertions in the code are added or removed.
* true
if the given package fragment root is
+ * referenced. This means it is own by a different project but is referenced
+ * by the root's parent. Returns false
if the given root
+ * doesn't have an underlying resource.
+ */
+ public static boolean isReferenced(IPackageFragmentRoot root) {
+// IResource resource= root.getResource();
+// if (resource != null) {
+// IProject jarProject= resource.getProject();
+// IProject container= root.getJavaProject().getProject();
+// return !container.equals(jarProject);
+// }
+ return false;
+ }
+
+// private static IType findType(IPackageFragmentRoot root, String fullyQualifiedName) throws JavaModelException{
+// IJavaElement[] children= root.getChildren();
+// for (int i= 0; i < children.length; i++) {
+// IJavaElement element= children[i];
+// if (element.getElementType() == IJavaElement.PACKAGE_FRAGMENT){
+// IPackageFragment pack= (IPackageFragment)element;
+// if (! fullyQualifiedName.startsWith(pack.getElementName()))
+// continue;
+// IType type= findType(pack, fullyQualifiedName);
+// if (type != null && type.exists())
+// return type;
+// }
+// }
+// return null;
+// }
+
+// private static IType findType(IPackageFragment pack, String fullyQualifiedName) throws JavaModelException{
+// ICompilationUnit[] cus= pack.getCompilationUnits();
+// for (int i= 0; i < cus.length; i++) {
+// ICompilationUnit unit= cus[i];
+// ICompilationUnit wc= WorkingCopyUtil.getWorkingCopyIfExists(unit);
+// IType type= findType(wc, fullyQualifiedName);
+// if (type != null && type.exists())
+// return type;
+// }
+// return null;
+// }
+
+// private static IType findType(ICompilationUnit cu, String fullyQualifiedName) throws JavaModelException{
+// IType[] types= cu.getAllTypes();
+// for (int i= 0; i < types.length; i++) {
+// IType type= types[i];
+// if (getFullyQualifiedName(type).equals(fullyQualifiedName))
+// return type;
+// }
+// return null;
+// }
+
+ /**
+ * Finds a type by package and type name.
+ * @param jproject the java project to search in
+ * @param pack The package name
+ * @param typeQualifiedName the type qualified name (type name with enclosing type names (separated by dots))
+ * @return the type found, or null if not existing
+ * @deprecated Use IJavaProject.findType(String, String) instead
+ */
+// public static IType findType(IJavaProject jproject, String pack, String typeQualifiedName) throws JavaModelException {
+// return jproject.findType(pack, typeQualifiedName);
+// }
+
+ /**
+ * Finds a type container by container name.
+ * The returned element will be of type IType
or a IPackageFragment
.
+ * null
is returned if the type container could not be found.
+ * @param jproject The Java project defining the context to search
+ * @param typeContainerName A dot separarted name of the type container
+ * @see #getTypeContainerName(IType)
+ */
+// public static IJavaElement findTypeContainer(IJavaProject jproject, String typeContainerName) throws JavaModelException {
+// // try to find it as type
+// IJavaElement result= jproject.findType(typeContainerName);
+// if (result == null) {
+// // find it as package
+// IPath path= new Path(typeContainerName.replace('.', '/'));
+// result= jproject.findElement(path);
+// if (!(result instanceof IPackageFragment)) {
+// result= null;
+// }
+//
+// }
+// return result;
+// }
+
+ /**
+ * Finds a type in a compilation unit. Typical usage is to find the corresponding
+ * type in a working copy.
+ * @param cu the compilation unit to search in
+ * @param typeQualifiedName the type qualified name (type name with enclosing type names (separated by dots))
+ * @return the type found, or null if not existing
+ */
+ public static IType findTypeInCompilationUnit(ICompilationUnit cu, String typeQualifiedName) throws JavaModelException {
+ IType[] types= cu.getAllTypes();
+ for (int i= 0; i < types.length; i++) {
+ String currName= getTypeQualifiedName(types[i]);
+ if (typeQualifiedName.equals(currName)) {
+ return types[i];
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Finds a a member in a compilation unit. Typical usage is to find the corresponding
+ * member in a working copy.
+ * @param cu the compilation unit (eg. working copy) to search in
+ * @param member the member (eg. from the original)
+ * @return the member found, or null if not existing
+ */
+ public static IMember findMemberInCompilationUnit(ICompilationUnit cu, IMember member) throws JavaModelException {
+ IJavaElement[] elements= cu.findElements(member);
+ if (elements != null && elements.length > 0) {
+ return (IMember) elements[0];
+ }
+ return null;
+ }
+
+
+ /**
+ * Returns the element of the given compilation unit which is "equal" to the
+ * given element. Note that the given element usually has a parent different
+ * from the given compilation unit.
+ *
+ * @param cu the cu to search in
+ * @param element the element to look for
+ * @return an element of the given cu "equal" to the given element
+ */
+ public static IJavaElement findInCompilationUnit(ICompilationUnit cu, IJavaElement element) throws JavaModelException {
+ IJavaElement[] elements= cu.findElements(element);
+ if (elements != null && elements.length > 0) {
+ return elements[0];
+ }
+ return null;
+ }
+
+ /**
+ * Returns the qualified type name of the given type using '.' as separators.
+ * This is a replace for IType.getTypeQualifiedName()
+ * which uses '$' as separators. As '$' is also a valid character in an id
+ * this is ambiguous. JavaCore PR: 1GCFUNT
+ */
+ public static String getTypeQualifiedName(IType type) {
+ return type.getTypeQualifiedName('.');
+ }
+
+ private static void getTypeQualifiedName(IType type, StringBuffer buf) {
+ IType outerType= type.getDeclaringType();
+ if (outerType != null) {
+ getTypeQualifiedName(outerType, buf);
+ buf.append('.');
+ }
+ buf.append(type.getElementName());
+ }
+
+ /**
+ * Returns the fully qualified name of the given type using '.' as separators.
+ * This is a replace for IType.getFullyQualifiedTypeName
+ * which uses '$' as separators. As '$' is also a valid character in an id
+ * this is ambiguous. JavaCore PR: 1GCFUNT
+ */
+ public static String getFullyQualifiedName(IType type) {
+ return type.getFullyQualifiedName('.');
+ }
+
+ /**
+ * Returns the fully qualified name of a type's container. (package name or enclosing type name)
+ */
+ public static String getTypeContainerName(IType type) {
+ IType outerType= type.getDeclaringType();
+ if (outerType != null) {
+ return outerType.getFullyQualifiedName('.');
+ } else {
+ return type.getPackageFragment().getElementName();
+ }
+ }
+
+
+ /**
+ * Concatenates two names. Uses a dot for separation.
+ * Both strings can be empty or null
.
+ */
+ public static String concatenateName(String name1, String name2) {
+ StringBuffer buf= new StringBuffer();
+ if (name1 != null && name1.length() > 0) {
+ buf.append(name1);
+ }
+ if (name2 != null && name2.length() > 0) {
+ if (buf.length() > 0) {
+ buf.append('.');
+ }
+ buf.append(name2);
+ }
+ return buf.toString();
+ }
+
+ /**
+ * Concatenates two names. Uses a dot for separation.
+ * Both strings can be empty or null
.
+ */
+ public static String concatenateName(char[] name1, char[] name2) {
+ StringBuffer buf= new StringBuffer();
+ if (name1 != null && name1.length > 0) {
+ buf.append(name1);
+ }
+ if (name2 != null && name2.length > 0) {
+ if (buf.length() > 0) {
+ buf.append('.');
+ }
+ buf.append(name2);
+ }
+ return buf.toString();
+ }
+
+ /**
+ * Evaluates if a member (possible from another package) is visible from
+ * elements in a package.
+ * @param member The member to test the visibility for
+ * @param pack The package in focus
+ */
+ public static boolean isVisible(IMember member, IPackageFragment pack) throws JavaModelException {
+ int otherflags= member.getFlags();
+
+ if (Flags.isPublic(otherflags)) {
+ return true;
+ } else if (Flags.isPrivate(otherflags)) {
+ return false;
+ }
+
+ IPackageFragment otherpack= (IPackageFragment) findParentOfKind(member, IJavaElement.PACKAGE_FRAGMENT);
+ return (pack != null && pack.equals(otherpack));
+ }
+
+ /**
+ * Returns the package fragment root of IJavaElement
. If the given
+ * element is already a package fragment root, the element itself is returned.
+ */
+ public static IPackageFragmentRoot getPackageFragmentRoot(IJavaElement element) {
+ return (IPackageFragmentRoot) element.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
+ }
+
+ /**
+ * Returns the parent of the supplied java element that conforms to the given
+ * parent type or null
, if such a parent doesn't exit.
+ * @deprecated Use element.getParent().getAncestor(kind);
+ */
+ public static IJavaElement findParentOfKind(IJavaElement element, int kind) {
+ if (element != null && element.getParent() != null) {
+ return element.getParent().getAncestor(kind);
+ }
+ return null;
+ }
+
+ /**
+ * Finds a method in a type.
+ * This searches for a method with the same name and signature. Parameter types are only
+ * compared by the simple name, no resolving for the fully qualified type name is done.
+ * Constructors are only compared by parameters, not the name.
+ * @param name The name of the method to find
+ * @param paramTypes The type signatures of the parameters e.g. {"QString;","I"}
+ * @param isConstructor If the method is a constructor
+ * @return The first found method or null
, if nothing found
+ */
+ public static IMethod findMethod(String name, String[] paramTypes, boolean isConstructor, IType type) throws JavaModelException {
+ return findMethod(name, paramTypes, isConstructor, type.getMethods());
+ }
+
+ /**
+ * Finds a method by name.
+ * This searches for a method with a name and signature. Parameter types are only
+ * compared by the simple name, no resolving for the fully qualified type name is done.
+ * Constructors are only compared by parameters, not the name.
+ * @param name The name of the method to find
+ * @param paramTypes The type signatures of the parameters e.g. {"QString;","I"}
+ * @param isConstructor If the method is a constructor
+ * @param methods The methods to search in
+ * @return The found method or null
, if nothing found
+ */
+ public static IMethod findMethod(String name, String[] paramTypes, boolean isConstructor, IMethod[] methods) throws JavaModelException {
+ for (int i= methods.length - 1; i >= 0; i--) {
+ if (isSameMethodSignature(name, paramTypes, isConstructor, methods[i])) {
+ return methods[i];
+ }
+ }
+ return null;
+ }
+
+
+ /**
+ * Finds a method declararion in a type's hierarchy. The search is top down, so this
+ * returns the first declaration of the method in the hierarchy.
+ * This searches for a method with a name and signature. Parameter types are only
+ * compared by the simple name, no resolving for the fully qualified type name is done.
+ * Constructors are only compared by parameters, not the name.
+ * @param type Searches in this type's supertypes.
+ * @param name The name of the method to find
+ * @param paramTypes The type signatures of the parameters e.g. {"QString;","I"}
+ * @param isConstructor If the method is a constructor
+ * @return The first method found or null, if nothing found
+ */
+// public static IMethod findMethodDeclarationInHierarchy(ITypeHierarchy hierarchy, IType type, String name, String[] paramTypes, boolean isConstructor) throws JavaModelException {
+// IType[] superTypes= hierarchy.getAllSupertypes(type);
+// for (int i= superTypes.length - 1; i >= 0; i--) {
+// IMethod first= findMethod(name, paramTypes, isConstructor, superTypes[i]);
+// if (first != null && !Flags.isPrivate(first.getFlags())) {
+// // the order getAllSupertypes does make assumptions of the order of inner elements -> search recursivly
+// IMethod res= findMethodDeclarationInHierarchy(hierarchy, first.getDeclaringType(), name, paramTypes, isConstructor);
+// if (res != null) {
+// return res;
+// }
+// return first;
+// }
+// }
+// return null;
+// }
+
+ /**
+ * Finds a method implementation in a type's classhierarchy. The search is bottom-up, so this
+ * returns the nearest overridden method. Does not find methods in interfaces or abstract methods.
+ * This searches for a method with a name and signature. Parameter types are only
+ * compared by the simple name, no resolving for the fully qualified type name is done.
+ * Constructors are only compared by parameters, not the name.
+ * @param type Type to search the superclasses
+ * @param name The name of the method to find
+ * @param paramTypes The type signatures of the parameters e.g. {"QString;","I"}
+ * @param isConstructor If the method is a constructor
+ * @return The first method found or null, if nothing found
+ */
+// public static IMethod findMethodImplementationInHierarchy(ITypeHierarchy hierarchy, IType type, String name, String[] paramTypes, boolean isConstructor) throws JavaModelException {
+// IType[] superTypes= hierarchy.getAllSuperclasses(type);
+// for (int i= 0; i < superTypes.length; i++) {
+// IMethod found= findMethod(name, paramTypes, isConstructor, superTypes[i]);
+// if (found != null) {
+// if (Flags.isAbstract(found.getFlags())) {
+// return null;
+// }
+// return found;
+// }
+// }
+// return null;
+// }
+
+ /**
+ * Tests if a method equals to the given signature.
+ * Parameter types are only compared by the simple name, no resolving for
+ * the fully qualified type name is done. Constructors are only compared by
+ * parameters, not the name.
+ * @param Name of the method
+ * @param The type signatures of the parameters e.g. {"QString;","I"}
+ * @param Specifies if the method is a constructor
+ * @return Returns true
if the method has the given name and parameter types and constructor state.
+ */
+ public static boolean isSameMethodSignature(String name, String[] paramTypes, boolean isConstructor, IMethod curr) throws JavaModelException {
+ if (isConstructor || name.equals(curr.getElementName())) {
+ if (isConstructor == curr.isConstructor()) {
+ String[] currParamTypes= curr.getParameterTypes();
+ if (paramTypes.length == currParamTypes.length) {
+ for (int i= 0; i < paramTypes.length; i++) {
+ String t1= Signature.getSimpleName(Signature.toString(paramTypes[i]));
+ String t2= Signature.getSimpleName(Signature.toString(currParamTypes[i]));
+ if (!t1.equals(t2)) {
+ return false;
+ }
+ }
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Checks whether the given type has a valid main method or not.
+ */
+ public static boolean hasMainMethod(IType type) throws JavaModelException {
+ IMethod[] methods= type.getMethods();
+ for (int i= 0; i < methods.length; i++) {
+ if (methods[i].isMainMethod()) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Checks if the field is boolean.
+ */
+ public static boolean isBoolean(IField field) throws JavaModelException{
+ return field.getTypeSignature().equals(Signature.SIG_BOOLEAN);
+ }
+
+ /**
+ * Returns true if the element is on the build path of the given project
+ * @deprecated Use jproject.isOnClasspath(element);
+ */
+// public static boolean isOnBuildPath(IJavaProject jproject, IJavaElement element) throws JavaModelException {
+// return jproject.isOnClasspath(element);
+// }
+
+ /**
+ * Tests if the given element is on the class path of its containing project. Handles the case
+ * that the containing project isn't a Java project.
+ */
+// public static boolean isOnClasspath(IJavaElement element) {
+// IJavaProject project= element.getJavaProject();
+// if (!project.exists())
+// return false;
+// return project.isOnClasspath(element);
+// }
+
+ /**
+ * Resolves a type name in the context of the declaring type.
+ * @param refTypeSig the type name in signature notation (for example 'QVector')
+ * this can also be an array type, but dimensions will be ignored.
+ * @param declaringType the context for resolving (type where the reference was made in)
+ * @return returns the fully qualified type name or build-in-type name.
+ * if a unresoved type couldn't be resolved null is returned
+ */
+ public static String getResolvedTypeName(String refTypeSig, IType declaringType) throws JavaModelException {
+ int arrayCount= Signature.getArrayCount(refTypeSig);
+ char type= refTypeSig.charAt(arrayCount);
+ if (type == Signature.C_UNRESOLVED) {
+ int semi= refTypeSig.indexOf(Signature.C_SEMICOLON, arrayCount + 1);
+ if (semi == -1) {
+ throw new IllegalArgumentException();
+ }
+ String name= refTypeSig.substring(arrayCount + 1, semi);
+
+// String[][] resolvedNames= declaringType.resolveType(name);
+// if (resolvedNames != null && resolvedNames.length > 0) {
+// return JavaModelUtil.concatenateName(resolvedNames[0][0], resolvedNames[0][1]);
+// }
+ return null;
+ } else {
+ return Signature.toString(refTypeSig.substring(arrayCount));
+ }
+ }
+
+ /**
+ * Returns if a CU can be edited.
+ */
+ public static boolean isEditable(ICompilationUnit cu) {
+ if (cu.isWorkingCopy()) {
+ cu= (ICompilationUnit) cu.getOriginalElement();
+ }
+ IResource resource= cu.getResource();
+ return (resource.exists() && !resource.isReadOnly());
+ }
+
+ /**
+ * Finds a qualified import for a type name.
+ */
+// public static IImportDeclaration findImport(ICompilationUnit cu, String simpleName) throws JavaModelException {
+// IImportDeclaration[] existing= cu.getImports();
+// for (int i= 0; i < existing.length; i++) {
+// String curr= existing[i].getElementName();
+// if (curr.endsWith(simpleName)) {
+// int dotPos= curr.length() - simpleName.length() - 1;
+// if ((dotPos == -1) || (dotPos > 0 && curr.charAt(dotPos) == '.')) {
+// return existing[i];
+// }
+// }
+// }
+// return null;
+// }
+
+ /**
+ * Returns the original if the given member. If the member is already
+ * an original the input is returned. The returned member must not exist
+ */
+ public static IMember toOriginal(IMember member) {
+ if (member instanceof IMethod)
+ return toOriginalMethod((IMethod)member);
+ ICompilationUnit cu= member.getCompilationUnit();
+ if (cu != null && cu.isWorkingCopy())
+ return (IMember)cu.getOriginal(member);
+ return member;
+ }
+
+ /*
+ * XXX workaround for bug 18568
+ * http://bugs.eclipse.org/bugs/show_bug.cgi?id=18568
+ * to be removed once the bug is fixed
+ */
+ private static IMethod toOriginalMethod(IMethod method) {
+ try{
+ ICompilationUnit cu= method.getCompilationUnit();
+ if (cu == null || ! cu.isWorkingCopy())
+ return method;
+ //use the workaround only if needed
+ if (! method.getElementName().equals(method.getDeclaringType().getElementName()))
+ return (IMethod)cu.getOriginal(method);
+
+ IType originalType = (IType)toOriginal(method.getDeclaringType());
+ IMethod[] methods = originalType.findMethods(method);
+ boolean isConstructor = method.isConstructor();
+ for (int i=0; i < methods.length; i++) {
+ if (methods[i].isConstructor() == isConstructor)
+ return methods[i];
+ }
+ return null;
+ } catch(JavaModelException e){
+ return null;
+ }
+ }
+
+ /**
+ * Returns the original cu if the given cu. If the cu is already
+ * an original the input cu is returned. The returned cu must not exist
+ */
+ public static ICompilationUnit toOriginal(ICompilationUnit cu) {
+ if (cu != null && cu.isWorkingCopy())
+ return (ICompilationUnit) cu.getOriginal(cu);
+ return cu;
+ }
+
+ /**
+ * Returns the working copy of the given member. If the member is already in a
+ * working copy or the member does not exist in the working copy the input is returned.
+ */
+ public static IMember toWorkingCopy(IMember member) {
+ ICompilationUnit cu= member.getCompilationUnit();
+ if (cu != null && !cu.isWorkingCopy()) {
+ ICompilationUnit workingCopy= EditorUtility.getWorkingCopy(cu);
+ if (workingCopy != null) {
+ IJavaElement[] members= workingCopy.findElements(member);
+ if (members != null && members.length > 0) {
+ return (IMember) members[0];
+ }
+ }
+ }
+ return member;
+ }
+
+
+ /**
+ * Returns the working copy CU of the given CU. If the CU is already a
+ * working copy or the CU has no working copy the input CU is returned.
+ */
+ public static ICompilationUnit toWorkingCopy(ICompilationUnit cu) {
+ if (!cu.isWorkingCopy()) {
+ ICompilationUnit workingCopy= EditorUtility.getWorkingCopy(cu);
+ if (workingCopy != null) {
+ return workingCopy;
+ }
+ }
+ return cu;
+ }
+
+ /*
+ * http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253
+ *
+ * Reconciling happens in a separate thread. This can cause a situation where the
+ * Java element gets disposed after an exists test has been done. So we should not
+ * log not present exceptions when they happen in working copies.
+ */
+ public static boolean filterNotPresentException(CoreException exception) {
+ if (!(exception instanceof JavaModelException))
+ return true;
+ JavaModelException je= (JavaModelException)exception;
+ if (!je.isDoesNotExist())
+ return true;
+ IJavaElement[] elements= je.getJavaModelStatus().getElements();
+ for (int i= 0; i < elements.length; i++) {
+ IJavaElement element= elements[i];
+ ICompilationUnit unit= (ICompilationUnit)element.getAncestor(IJavaElement.COMPILATION_UNIT);
+ if (unit == null)
+ return true;
+ if (!unit.isWorkingCopy())
+ return true;
+ }
+ return false;
+ }
+
+// public static IType[] getAllSuperTypes(IType type, IProgressMonitor pm) throws JavaModelException {
+// //workaround for bugs 23644 and 23656
+// try{
+// pm.beginTask("", 3); //$NON-NLS-1$
+// ITypeHierarchy hierarchy= type.newSupertypeHierarchy(new SubProgressMonitor(pm, 1));
+//
+// IProgressMonitor subPm= new SubProgressMonitor(pm, 2);
+// List typeList= Arrays.asList(hierarchy.getAllSupertypes(type));
+// subPm.beginTask("", typeList.size()); //$NON-NLS-1$
+// Set types= new HashSet(typeList);
+// for (Iterator iter= typeList.iterator(); iter.hasNext();) {
+// IType superType= (IType)iter.next();
+// IType[] superTypes= getAllSuperTypes(superType, new SubProgressMonitor(subPm, 1));
+// types.addAll(Arrays.asList(superTypes));
+// }
+// types.add(type.getJavaProject().findType("java.lang.Object"));//$NON-NLS-1$
+// subPm.done();
+// return (IType[]) types.toArray(new IType[types.size()]);
+// } finally {
+// pm.done();
+// }
+// }
+
+
+ public static boolean isExcludedPath(IPath resourcePath, IPath[] exclusionPatterns) {
+ char[] path = resourcePath.toString().toCharArray();
+ for (int i = 0, length = exclusionPatterns.length; i < length; i++) {
+ char[] pattern= exclusionPatterns[i].toString().toCharArray();
+ if (CharOperation.pathMatch(pattern, path, true, '/')) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+
+ /*
+ * Returns whether the given resource path matches one of the exclusion
+ * patterns.
+ *
+ * @see IClasspathEntry#getExclusionPatterns
+ */
+ public final static boolean isExcluded(IPath resourcePath, char[][] exclusionPatterns) {
+ if (exclusionPatterns == null) return false;
+ char[] path = resourcePath.toString().toCharArray();
+ for (int i = 0, length = exclusionPatterns.length; i < length; i++)
+ if (CharOperation.pathMatch(exclusionPatterns[i], path, true, '/'))
+ return true;
+ return false;
+ }
+
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/IJavaHelpContextIds.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/IJavaHelpContextIds.java
new file mode 100644
index 0000000..cc130f4
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/IJavaHelpContextIds.java
@@ -0,0 +1,304 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.ui;
+
+import net.sourceforge.phpeclipse.PHPeclipsePlugin;
+
+
+
+/**
+ * Help context ids for the Java UI.
+ *
+ *
+ */
+ public static IStructuredSelection getStructuredSelection(IWorkbenchPart part) throws JavaModelException {
+ if (part instanceof PHPEditor)
+ return new StructuredSelection(codeResolve((PHPEditor)part));
+ ISelectionProvider provider= part.getSite().getSelectionProvider();
+ if (provider != null) {
+ ISelection selection= provider.getSelection();
+ if (selection instanceof IStructuredSelection)
+ return (IStructuredSelection)selection;
+ }
+ return StructuredSelection.EMPTY;
+ }
+
+
+ /**
+ * Converts the given structured selection into an array of Java elements.
+ * An empty array is returned if one of the elements stored in the structured
+ * selection is not of tupe part instanceof PHPEditor
: returns a structured selection
+ * using code resolve to convert the editor's text selection.part instanceof IWorkbenchPart
: returns the part's selection
+ * if it is a structured selection.default
: returns an empty structured selection.IJavaElement
+ */
+ public static IJavaElement[] getElements(IStructuredSelection selection) {
+ if (!selection.isEmpty()) {
+ IJavaElement[] result= new IJavaElement[selection.size()];
+ int i= 0;
+ for (Iterator iter= selection.iterator(); iter.hasNext(); i++) {
+ Object element= (Object) iter.next();
+ if (!(element instanceof IJavaElement))
+ return EMPTY_RESULT;
+ result[i]= (IJavaElement)element;
+ }
+ return result;
+ }
+ return EMPTY_RESULT;
+ }
+
+ public static boolean canOperateOn(PHPEditor editor) {
+ if (editor == null)
+ return false;
+ return getInput(editor) != null;
+
+ }
+
+ /**
+ * Converts the text selection provided by the given editor into an array of
+ * Java elements. If the selection doesn't cover a Java element and the selection's
+ * length is greater than 0 the methods returns the editor's input element.
+ */
+ public static IJavaElement[] codeResolveOrInput(PHPEditor editor) throws JavaModelException {
+ IJavaElement input= getInput(editor);
+ ITextSelection selection= (ITextSelection)editor.getSelectionProvider().getSelection();
+ IJavaElement[] result= codeResolve(input, selection);
+ if (result.length == 0) {
+ result= new IJavaElement[] {input};
+ }
+ return result;
+ }
+
+ public static IJavaElement[] codeResolveOrInputHandled(PHPEditor editor, Shell shell, String title) {
+ try {
+ return codeResolveOrInput(editor);
+ } catch(JavaModelException e) {
+ ExceptionHandler.handle(e, shell, title, ActionMessages.getString("SelectionConverter.codeResolve_failed")); //$NON-NLS-1$
+ }
+ return null;
+ }
+
+ /**
+ * Converts the text selection provided by the given editor a Java element by
+ * asking the user if code reolve returned more than one result. If the selection
+ * doesn't cover a Java element and the selection's length is greater than 0 the
+ * methods returns the editor's input element.
+ */
+ public static IJavaElement codeResolveOrInput(PHPEditor editor, Shell shell, String title, String message) throws JavaModelException {
+ IJavaElement[] elements= codeResolveOrInput(editor);
+ if (elements == null || elements.length == 0)
+ return null;
+ IJavaElement candidate= elements[0];
+ if (elements.length > 1) {
+ candidate= OpenActionUtil.selectJavaElement(elements, shell, title, message);
+ }
+ return candidate;
+ }
+
+ public static IJavaElement codeResolveOrInputHandled(PHPEditor editor, Shell shell, String title, String message) {
+ try {
+ return codeResolveOrInput(editor, shell, title, message);
+ } catch (JavaModelException e) {
+ ExceptionHandler.handle(e, shell, title, ActionMessages.getString("SelectionConverter.codeResolveOrInput_failed")); //$NON-NLS-1$
+ }
+ return null;
+ }
+
+ public static IJavaElement[] codeResolve(PHPEditor editor) throws JavaModelException {
+ return codeResolve(getInput(editor), (ITextSelection)editor.getSelectionProvider().getSelection());
+ }
+
+ /**
+ * Converts the text selection provided by the given editor a Java element by
+ * asking the user if code reolve returned more than one result. If the selection
+ * doesn't cover a Java element null
is returned.
+ */
+ public static IJavaElement codeResolve(PHPEditor editor, Shell shell, String title, String message) throws JavaModelException {
+ IJavaElement[] elements= codeResolve(editor);
+ if (elements == null || elements.length == 0)
+ return null;
+ IJavaElement candidate= elements[0];
+ if (elements.length > 1) {
+ candidate= OpenActionUtil.selectJavaElement(elements, shell, title, message);
+ }
+ return candidate;
+ }
+
+ public static IJavaElement[] codeResolveHandled(PHPEditor editor, Shell shell, String title) {
+ try {
+ return codeResolve(editor);
+ } catch (JavaModelException e) {
+ ExceptionHandler.handle(e, shell, title, ActionMessages.getString("SelectionConverter.codeResolve_failed")); //$NON-NLS-1$
+ }
+ return null;
+ }
+
+ public static IJavaElement getElementAtOffset(PHPEditor editor) throws JavaModelException {
+ return getElementAtOffset(getInput(editor), (ITextSelection)editor.getSelectionProvider().getSelection());
+ }
+
+ public static IType getTypeAtOffset(PHPEditor editor) throws JavaModelException {
+ IJavaElement element= SelectionConverter.getElementAtOffset(editor);
+ IType type= (IType)element.getAncestor(IJavaElement.TYPE);
+ if (type == null) {
+ ICompilationUnit unit= SelectionConverter.getInputAsCompilationUnit(editor);
+ if (unit != null)
+ type= unit.findPrimaryType();
+ }
+ return type;
+ }
+
+ public static IJavaElement getInput(PHPEditor editor) {
+ if (editor == null)
+ return null;
+ IEditorInput input= editor.getEditorInput();
+// if (input instanceof IClassFileEditorInput)
+// return ((IClassFileEditorInput)input).getClassFile();
+ IWorkingCopyManager manager= PHPeclipsePlugin.getDefault().getWorkingCopyManager();
+ return manager.getWorkingCopy(input);
+ }
+
+ public static ICompilationUnit getInputAsCompilationUnit(PHPEditor editor) {
+ Object editorInput= SelectionConverter.getInput(editor);
+ if (editorInput instanceof ICompilationUnit)
+ return (ICompilationUnit)editorInput;
+ else
+ return null;
+ }
+
+ private static IJavaElement[] codeResolve(IJavaElement input, ITextSelection selection) throws JavaModelException {
+// if (input instanceof ICodeAssist) {
+// IJavaElement[] elements= ((ICodeAssist)input).codeSelect(selection.getOffset(), selection.getLength());
+// if (elements != null && elements.length > 0)
+// return elements;
+// }
+ return EMPTY_RESULT;
+ }
+
+ private static IJavaElement getElementAtOffset(IJavaElement input, ITextSelection selection) throws JavaModelException {
+ if (input instanceof ICompilationUnit) {
+ ICompilationUnit cunit= (ICompilationUnit)input;
+ if (cunit.isWorkingCopy()) {
+ synchronized (cunit) {
+ cunit.reconcile();
+ }
+ }
+ IJavaElement ref= cunit.getElementAt(selection.getOffset());
+ if (ref == null)
+ return input;
+ else
+ return ref;
+ }
+// else if (input instanceof IClassFile) {
+// IJavaElement ref= ((IClassFile)input).getElementAt(selection.getOffset());
+// if (ref == null)
+// return input;
+// else
+// return ref;
+// }
+ return null;
+ }
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/BasicSelectionTransferDragAdapter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/BasicSelectionTransferDragAdapter.java
new file mode 100644
index 0000000..306796d
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/BasicSelectionTransferDragAdapter.java
@@ -0,0 +1,82 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.ui.dnd;
+
+import org.eclipse.swt.dnd.DND;
+import org.eclipse.swt.dnd.DragSourceAdapter;
+import org.eclipse.swt.dnd.DragSourceEvent;
+import org.eclipse.swt.dnd.Transfer;
+
+import org.eclipse.jface.util.Assert;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.ISelectionProvider;
+
+public class BasicSelectionTransferDragAdapter extends DragSourceAdapter implements TransferDragSourceListener {
+
+ private ISelectionProvider fProvider;
+
+ public BasicSelectionTransferDragAdapter(ISelectionProvider provider) {
+ Assert.isNotNull(provider);
+ fProvider= provider;
+ }
+
+ /**
+ * @see TransferDragSourceListener#getTransfer
+ */
+ public Transfer getTransfer() {
+ return LocalSelectionTransfer.getInstance();
+ }
+
+ /* non Java-doc
+ * @see org.eclipse.swt.dnd.DragSourceListener#dragStart
+ */
+ public void dragStart(DragSourceEvent event) {
+ ISelection selection= fProvider.getSelection();
+ LocalSelectionTransfer.getInstance().setSelection(selection);
+ LocalSelectionTransfer.getInstance().setSelectionSetTime(event.time);
+ event.doit= isDragable(selection);
+ }
+
+ /**
+ * Checks if the elements contained in the given selection can
+ * be dragged.
+ * TransferDragSourceListener
s
+ * On dragStart
the adapter determines the listener to be used for any further
+ * drag*
callback.
+ */
+public class DelegatingDragAdapter implements DragSourceListener {
+
+ private TransferDragSourceListener[] fPossibleListeners;
+ private List fActiveListeners;
+ private TransferDragSourceListener fFinishListener;
+
+ public DelegatingDragAdapter(TransferDragSourceListener[] listeners) {
+ setPossibleListeners(listeners);
+ }
+
+ protected void setPossibleListeners(TransferDragSourceListener[] listeners) {
+ Assert.isNotNull(listeners);
+ Assert.isTrue(fActiveListeners == null, "Can only set possible listeners before drag operation has started"); //$NON-NLS-1$
+ fPossibleListeners= listeners;
+ }
+
+ /* non Java-doc
+ * @see DragSourceListener
+ */
+ public void dragStart(DragSourceEvent event) {
+ fFinishListener= null;
+ boolean saveDoit= event.doit;
+ Object saveData= event.data;
+ boolean doIt= false;
+ List transfers= new ArrayList(fPossibleListeners.length);
+ fActiveListeners= new ArrayList(fPossibleListeners.length);
+
+ for (int i= 0; i < fPossibleListeners.length; i++) {
+ TransferDragSourceListener listener= fPossibleListeners[i];
+ event.doit= saveDoit;
+ listener.dragStart(event);
+ if (event.doit) {
+ transfers.add(listener.getTransfer());
+ fActiveListeners.add(listener);
+ }
+ doIt= doIt || event.doit;
+ }
+ if (doIt) {
+ ((DragSource)event.widget).setTransfer((Transfer[])transfers.toArray(new Transfer[transfers.size()]));
+ }
+ event.data= saveData;
+ event.doit= doIt;
+ }
+
+ /* non Java-doc
+ * @see DragSourceListener
+ */
+ public void dragSetData(DragSourceEvent event) {
+ fFinishListener= getListener(event.dataType);
+ if (fFinishListener != null)
+ fFinishListener.dragSetData(event);
+ }
+
+ /* non Java-doc
+ * @see DragSourceListener
+ */
+ public void dragFinished(DragSourceEvent event) {
+ try{
+ if (fFinishListener != null) {
+ fFinishListener.dragFinished(event);
+ } else {
+ // If the user presses Escape then we get a dragFinished without
+ // getting a dragSetData before.
+ fFinishListener= getListener(event.dataType);
+ if (fFinishListener != null)
+ fFinishListener.dragFinished(event);
+ }
+ } finally{
+ fFinishListener= null;
+ fActiveListeners= null;
+ }
+ }
+
+ private TransferDragSourceListener getListener(TransferData type) {
+ if (type == null)
+ return null;
+
+ for (Iterator iter= fActiveListeners.iterator(); iter.hasNext();) {
+ TransferDragSourceListener listener= (TransferDragSourceListener)iter.next();
+ if (listener.getTransfer().isSupportedType(type)) {
+ return listener;
+ }
+ }
+ return null;
+ }
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/DelegatingDropAdapter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/DelegatingDropAdapter.java
new file mode 100644
index 0000000..c3ad84a
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/DelegatingDropAdapter.java
@@ -0,0 +1,109 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.ui.dnd;
+
+import org.eclipse.swt.dnd.DropTargetEvent;
+import org.eclipse.swt.dnd.DropTargetListener;
+import org.eclipse.swt.dnd.TransferData;
+
+import org.eclipse.jface.util.Assert;
+
+/**
+ * A delegating drop adapter negotiates between a set of TransferDropTargetListener
s
+ * On dragEnter
the adapter determines the listener to be used for any further
+ * drag*
callback.
+ */
+public class DelegatingDropAdapter implements DropTargetListener {
+
+ private TransferDropTargetListener[] fListeners;
+
+ private TransferDropTargetListener fChosenListener;
+
+ /**
+ * Creates a new delegating drop adapter.
+ *
+ * @param listeners an array of potential listeners
+ */
+ public DelegatingDropAdapter(TransferDropTargetListener[] listeners) {
+ fListeners= listeners;
+ Assert.isNotNull(listeners);
+ }
+
+ /* non Java-doc
+ * @see DropTargetListener
+ */
+ public void dragEnter(DropTargetEvent event) {
+ fChosenListener= null;
+ event.currentDataType= selectPreferredListener(event.dataTypes);
+ if (fChosenListener != null)
+ fChosenListener.dragEnter(event);
+ }
+
+ /* non Java-doc
+ * @see DropTargetListener
+ */
+ public void dragLeave(DropTargetEvent event){
+ if (fChosenListener != null)
+ fChosenListener.dragLeave(event);
+ }
+
+ /* non Java-doc
+ * @see DropTargetListener
+ */
+ public void dragOperationChanged(DropTargetEvent event){
+ if (fChosenListener != null)
+ fChosenListener.dragOperationChanged(event);
+ }
+
+ /* non Java-doc
+ * @see DropTargetListener
+ */
+ public void dragOver(DropTargetEvent event){
+ if (fChosenListener != null)
+ fChosenListener.dragOver(event);
+ }
+
+ /* non Java-doc
+ * @see DropTargetListener
+ */
+ public void drop(DropTargetEvent event){
+ if (fChosenListener != null)
+ fChosenListener.drop(event);
+ fChosenListener= null;
+ }
+
+ /* non Java-doc
+ * @see DropTargetListener
+ */
+ public void dropAccept(DropTargetEvent event){
+ if (fChosenListener != null)
+ fChosenListener.dropAccept(event);
+ }
+
+ private TransferData selectPreferredListener(TransferData[] dataTypes) {
+ for (int i= 0; i < fListeners.length; i++) {
+ TransferData data= computeTransferData(dataTypes, fListeners[i]);
+ if (data != null)
+ return data;
+ }
+ return null;
+ }
+
+ private TransferData computeTransferData(TransferData[] dataTypes, TransferDropTargetListener listener) {
+ for (int i= 0; i < dataTypes.length; i++) {
+ if (listener.getTransfer().isSupportedType(dataTypes[i])) {
+ fChosenListener= listener;
+ return dataTypes[i];
+ }
+ }
+ return null;
+ }
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/JdtViewerDragAdapter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/JdtViewerDragAdapter.java
new file mode 100644
index 0000000..2906be9
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/JdtViewerDragAdapter.java
@@ -0,0 +1,37 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.ui.dnd;
+
+import org.eclipse.swt.dnd.DragSourceEvent;
+
+import org.eclipse.jface.util.Assert;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.viewers.StructuredViewer;
+
+public class JdtViewerDragAdapter extends DelegatingDragAdapter {
+
+ private StructuredViewer fViewer;
+
+ public JdtViewerDragAdapter(StructuredViewer viewer, TransferDragSourceListener[] listeners) {
+ super(listeners);
+ Assert.isNotNull(viewer);
+ fViewer= viewer;
+ }
+
+ public void dragStart(DragSourceEvent event) {
+ IStructuredSelection selection= (IStructuredSelection)fViewer.getSelection();
+ if (selection.isEmpty()) {
+ event.doit= false;
+ return;
+ }
+ super.dragStart(event);
+ }
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/JdtViewerDropAdapter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/JdtViewerDropAdapter.java
new file mode 100644
index 0000000..805efb3
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/JdtViewerDropAdapter.java
@@ -0,0 +1,261 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.ui.dnd;
+
+import org.eclipse.swt.dnd.DND;
+import org.eclipse.swt.dnd.DropTargetEvent;
+import org.eclipse.swt.dnd.DropTargetListener;
+import org.eclipse.swt.graphics.Point;
+import org.eclipse.swt.graphics.Rectangle;
+import org.eclipse.swt.widgets.Item;
+import org.eclipse.swt.widgets.TableItem;
+import org.eclipse.swt.widgets.TreeItem;
+
+import org.eclipse.jface.util.Assert;
+import org.eclipse.jface.viewers.StructuredViewer;
+
+/**
+ * A drag and drop adapter to be used together with structured viewers.
+ * The adapater delegates the dragEnter
, dragOperationChanged
+ *
, dragOver
and dropAccept
method to the
+ * validateDrop
method. Furthermore it adds location feedback.
+ */
+public class JdtViewerDropAdapter implements DropTargetListener {
+
+ /**
+ * Constant describing the position of the mouse cursor relative
+ * to the target object. This means the mouse is positioned
+ * slightly before the target.
+ */
+ protected static final int LOCATION_BEFORE= 1;
+
+ /**
+ * Constant describing the position of the mouse cursor relative
+ * to the target object. This means the mouse is positioned
+ * slightly after the target.
+ */
+ protected static final int LOCATION_AFTER= 2;
+
+ /**
+ * Constant describing the position of the mouse cursor relative
+ * to the target object. This means the mouse is positioned
+ * directly on the target.
+ */
+ protected static final int LOCATION_ON= 3;
+
+ /**
+ * Constant describing the position of the mouse cursor relative
+ * to the target object. This means the mouse is not positioned
+ * over or near any valid target.
+ */
+ protected static final int LOCATION_NONE= 4;
+
+ /**
+ * The threshold used to determine if the mouse is before or after
+ * an item.
+ */
+ private static final int LOCATION_EPSILON= 5;
+
+ /**
+ * Style to enable location feedback.
+ */
+ public static final int INSERTION_FEEDBACK= 1 << 1;
+
+ private StructuredViewer fViewer;
+ private int fFeedback;
+ private boolean fShowInsertionFeedback;
+ private int fRequestedOperation;
+ private int fLastOperation;
+ protected int fLocation;
+ protected Object fTarget;
+
+ public JdtViewerDropAdapter(StructuredViewer viewer, int feedback) {
+ fViewer= viewer;
+ Assert.isNotNull(fViewer);
+ fFeedback= feedback;
+ fLastOperation= -1;
+ }
+
+ /**
+ * Controls whether the drop adapter shows insertion feedback or not.
+ *
+ * @param showInsertionFeedback true
if the drop adapter is supposed
+ * to show insertion feedback. Otherwise false
+ */
+ public void showInsertionFeedback(boolean showInsertionFeedback) {
+ fShowInsertionFeedback= showInsertionFeedback;
+ }
+
+ /**
+ * Returns the viewer this adapter is working on.
+ */
+ protected StructuredViewer getViewer() {
+ return fViewer;
+ }
+
+ //---- Hooks to override -----------------------------------------------------
+
+ /**
+ * The actual drop has occurred. Calls drop(Object target, DropTargetEvent event)
+ *
.
+ * @see DropTargetListener#drop(org.eclipse.swt.dnd.DropTargetEvent)
+ */
+ public void drop(DropTargetEvent event) {
+ drop(fTarget, event);
+ }
+
+ /**
+ * The actual drop has occurred.
+ * @param target the drop target in form of a domain element.
+ * @param event the drop traget event
+ */
+ public void drop(Object target, DropTargetEvent event) {
+ }
+
+ /**
+ * Checks if the drop is valid. The method calls validateDrop
+ * (Object target, DropTargetEvent event). Implementors can alter the
+ *
DROP_NODEcurrentDataType
field and the detail
field
+ * to give feedback about drop acceptence.
+ */
+ public void validateDrop(DropTargetEvent event) {
+ validateDrop(fTarget, event, fRequestedOperation);
+ }
+
+ /**
+ * Checks if the drop on the current target is valid. The method
+ * can alter the currentDataType
field and the
+ * detail
field to give feedback about drop acceptence.
+ * @param target the drop target in form of a domain element.
+ * @param event the drop traget event
+ * @param operation the operation requested by the user.
+ */
+ public void validateDrop(Object target, DropTargetEvent event, int operation) {
+ }
+
+ public void dragEnter(DropTargetEvent event) {
+ dragOperationChanged(event);
+ }
+
+ public void dragLeave(DropTargetEvent event) {
+ fTarget= null;
+ fLocation= LOCATION_NONE;
+ }
+
+ public void dragOperationChanged(DropTargetEvent event) {
+ fRequestedOperation= event.detail;
+ fTarget= computeTarget(event);
+ fLocation= computeLocation(event);
+ validateDrop(event);
+ fLastOperation= event.detail;
+ computeFeedback(event);
+ }
+
+ public void dragOver(DropTargetEvent event) {
+ Object oldTarget= fTarget;
+ fTarget= computeTarget(event);
+
+ //set the location feedback
+ int oldLocation= fLocation;
+ fLocation= computeLocation(event);
+ if (oldLocation != fLocation || oldTarget != fTarget || fLastOperation != event.detail) {
+ validateDrop(event);
+ fLastOperation= event.detail;
+ } else {
+ event.detail= fLastOperation;
+ }
+ computeFeedback(event);
+ }
+
+ public void dropAccept(DropTargetEvent event) {
+ fTarget= computeTarget(event);
+ validateDrop(event);
+ fLastOperation= event.detail;
+ }
+
+ /**
+ * Returns the data held by event.item
. Inside a viewer
+ * this corresponds to the items data model element.
+ */
+ protected Object computeTarget(DropTargetEvent event) {
+ return event.item == null ? null : event.item.getData();
+ }
+
+ /**
+ * Returns the position of the given coordinates relative to the given target.
+ * The position is determined to be before, after, or on the item, based on
+ * some threshold value. The return value is one of the LOCATION_* constants
+ * defined in this class.
+ */
+ final protected int computeLocation(DropTargetEvent event) {
+ if (!(event.item instanceof Item))
+ return LOCATION_NONE;
+
+ Item item= (Item) event.item;
+ Point coordinates= fViewer.getControl().toControl(new Point(event.x, event.y));
+ Rectangle bounds= getBounds(item);
+ if (bounds == null) {
+ return LOCATION_NONE;
+ }
+ if ((coordinates.y - bounds.y) < LOCATION_EPSILON) {
+ return LOCATION_BEFORE;
+ }
+ if ((bounds.y + bounds.height - coordinates.y) < LOCATION_EPSILON) {
+ return LOCATION_AFTER;
+ }
+ return LOCATION_ON;
+ }
+
+ /**
+ * Returns the bounds of the given item, or null
if it is not a
+ * valid type of item.
+ */
+ private Rectangle getBounds(Item item) {
+ if (item instanceof TreeItem)
+ return ((TreeItem) item).getBounds();
+
+ if (item instanceof TableItem)
+ return ((TableItem) item).getBounds(0);
+
+ return null;
+ }
+
+ /**
+ * Sets the drag under feedback corresponding to the value of fLocation
+ * and the INSERTION_FEEDBACK
style bit.
+ */
+ protected void computeFeedback(DropTargetEvent event) {
+ if (!fShowInsertionFeedback && fLocation != LOCATION_NONE) {
+ event.feedback= DND.FEEDBACK_SELECT;
+ } else {
+ if (fLocation == LOCATION_BEFORE) {
+ event.feedback= DND.FEEDBACK_INSERT_BEFORE;
+ } else if (fLocation == LOCATION_AFTER) {
+ event.feedback= DND.FEEDBACK_INSERT_AFTER;
+ }
+ }
+ event.feedback|= fFeedback;
+ }
+
+ /**
+ * Sets the drop operation to .
+ */
+ protected void clearDropOperation(DropTargetEvent event) {
+ event.detail= DND.DROP_NONE;
+ }
+
+ /**
+ * Returns the requested drop operation.
+ */
+ protected int getRequestedOperation() {
+ return fRequestedOperation;
+ }
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/LocalSelectionTransfer.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/LocalSelectionTransfer.java
new file mode 100644
index 0000000..408c2f5
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/LocalSelectionTransfer.java
@@ -0,0 +1,99 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.ui.dnd;
+
+import net.sourceforge.phpdt.internal.ui.PHPUIMessages;
+import net.sourceforge.phpeclipse.PHPeclipsePlugin;
+
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.swt.dnd.ByteArrayTransfer;
+import org.eclipse.swt.dnd.TransferData;
+
+
+public class LocalSelectionTransfer extends ByteArrayTransfer {
+
+ // First attempt to create a UUID for the type name to make sure that
+ // different Eclipse applications use different "types" of
+ //
+ * IResourceLocalSelectionTransfer
+ private static final String TYPE_NAME= "local-selection-transfer-format" + (new Long(System.currentTimeMillis())).toString(); //$NON-NLS-1$;
+ private static final int TYPEID= registerType(TYPE_NAME);
+
+ private static final LocalSelectionTransfer INSTANCE= new LocalSelectionTransfer();
+
+ private ISelection fSelection;
+ private int fSelectionSetTime;
+
+ private LocalSelectionTransfer() {
+ }
+
+ /**
+ * Returns the singleton.
+ */
+ public static LocalSelectionTransfer getInstance() {
+ return INSTANCE;
+ }
+
+ /**
+ * Sets the transfer data for local use.
+ */
+ public void setSelection(ISelection s) {
+ fSelection= s;
+ }
+
+ /**
+ * Returns the local transfer data.
+ */
+ public ISelection getSelection() {
+ return fSelection;
+ }
+
+ public void javaToNative(Object object, TransferData transferData) {
+ // No encoding needed since this is a hardcoded string read and written in the same process.
+ // See nativeToJava below
+ byte[] check= TYPE_NAME.getBytes();
+ super.javaToNative(check, transferData);
+ }
+
+ public Object nativeToJava(TransferData transferData) {
+ Object result= super.nativeToJava(transferData);
+ if (isInvalidNativeType(result)) {
+ PHPeclipsePlugin.log(IStatus.ERROR, PHPUIMessages.getString("LocalSelectionTransfer.errorMessage")); //$NON-NLS-1$
+ }
+ return fSelection;
+ }
+
+ private boolean isInvalidNativeType(Object result) {
+ // No encoding needed since this is a hardcoded string read and written in the same process.
+ // See javaToNative above
+ return !(result instanceof byte[]) || !TYPE_NAME.equals(new String((byte[])result));
+ }
+
+ /**
+ * The type id used to identify this transfer.
+ */
+ protected int[] getTypeIds() {
+ return new int[] {TYPEID};
+ }
+
+ protected String[] getTypeNames(){
+ return new String[] {TYPE_NAME};
+ }
+
+ public int getSelectionSetTime() {
+ return fSelectionSetTime;
+ }
+
+ public void setSelectionSetTime(int time) {
+ fSelectionSetTime= time;
+ }
+
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/ResourceTransferDragAdapter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/ResourceTransferDragAdapter.java
new file mode 100644
index 0000000..876bb0c
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/ResourceTransferDragAdapter.java
@@ -0,0 +1,128 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.ui.dnd;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+import net.sourceforge.phpdt.internal.ui.IJavaStatusConstants;
+import net.sourceforge.phpdt.internal.ui.PHPUIMessages;
+import net.sourceforge.phpdt.internal.ui.util.SWTUtil;
+import net.sourceforge.phpeclipse.PHPeclipsePlugin;
+
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IAdaptable;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.MultiStatus;
+import org.eclipse.jface.dialogs.ErrorDialog;
+import org.eclipse.jface.util.Assert;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.ISelectionProvider;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.swt.dnd.DND;
+import org.eclipse.swt.dnd.DragSourceAdapter;
+import org.eclipse.swt.dnd.DragSourceEvent;
+import org.eclipse.swt.dnd.Transfer;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.ui.part.ResourceTransfer;
+
+
+/**
+ * A drag adapter that transfers the current selection as IResource
+ *
.
+ */
+public class ResourceTransferDragAdapter extends DragSourceAdapter implements TransferDragSourceListener {
+
+ private ISelectionProvider fProvider;
+
+ private static final List EMPTY_LIST= new ArrayList(0);
+
+ /**
+ * Creates a new ResourceTransferDragAdapter for the given selection
+ * provider.
+ *
+ * @param provider the selection provider to access the viewer's selection
+ */
+ public ResourceTransferDragAdapter(ISelectionProvider provider) {
+ fProvider= provider;
+ Assert.isNotNull(fProvider);
+ }
+
+ public Transfer getTransfer() {
+ return ResourceTransfer.getInstance();
+ }
+
+ public void dragStart(DragSourceEvent event) {
+ event.doit= convertSelection().size() > 0;
+ }
+
+ public void dragSetData(DragSourceEvent event) {
+ List resources= convertSelection();
+ event.data= (IResource[]) resources.toArray(new IResource[resources.size()]);
+ }
+
+ public void dragFinished(DragSourceEvent event) {
+ if (!event.doit)
+ return;
+
+ if (event.detail == DND.DROP_MOVE) {
+ handleFinishedDropMove(event);
+ }
+ }
+
+ private List convertSelection() {
+ ISelection s= fProvider.getSelection();
+ if (!(s instanceof IStructuredSelection))
+ return EMPTY_LIST;
+ IStructuredSelection selection= (IStructuredSelection)s;
+ List result= new ArrayList(selection.size());
+ for (Iterator iter= selection.iterator(); iter.hasNext();) {
+ Object element= iter.next();
+ if (element instanceof IAdaptable) {
+ IAdaptable adaptable= (IAdaptable)element;
+ IResource resource= (IResource)adaptable.getAdapter(IResource.class);
+ if (resource != null)
+ result.add(resource);
+ }
+ }
+ return result;
+ }
+
+ private void handleFinishedDropMove(DragSourceEvent event) {
+ MultiStatus status= new MultiStatus(
+ PHPeclipsePlugin.getPluginId(),
+ IJavaStatusConstants.INTERNAL_ERROR,
+ PHPUIMessages.getString("ResourceTransferDragAdapter.cannot_delete_resource"), //$NON-NLS-1$
+ null);
+ List resources= convertSelection();
+ for (Iterator iter= resources.iterator(); iter.hasNext();) {
+ IResource resource= (IResource) iter.next();
+ try {
+ resource.delete(true, null);
+ } catch (CoreException e) {
+ status.add(e.getStatus());
+ }
+ }
+ if (status.getChildren().length > 0) {
+ Shell parent= SWTUtil.getShell(event.widget);
+ ErrorDialog error= new ErrorDialog(parent,
+ PHPUIMessages.getString("ResourceTransferDragAdapter.moving_resource"), //$NON-NLS-1$
+ PHPUIMessages.getString("ResourceTransferDragAdapter.cannot_delete_files"), //$NON-NLS-1$
+ status, IStatus.ERROR);
+ error.open();
+ }
+ }
+}
+
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/TransferDragSourceListener.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/TransferDragSourceListener.java
new file mode 100644
index 0000000..b4f7ecb
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/TransferDragSourceListener.java
@@ -0,0 +1,25 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.ui.dnd;
+
+import org.eclipse.swt.dnd.DragSourceListener;
+import org.eclipse.swt.dnd.Transfer;
+
+/**
+ * A special drag source listener which is typed with a TransferData
.
+ */
+public interface TransferDragSourceListener extends DragSourceListener {
+
+ /**
+ * Returns the transfer used by this drag source.
+ */
+ public Transfer getTransfer();
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/TransferDropTargetListener.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/TransferDropTargetListener.java
new file mode 100644
index 0000000..f642ae8
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/dnd/TransferDropTargetListener.java
@@ -0,0 +1,25 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.ui.dnd;
+
+import org.eclipse.swt.dnd.DropTargetListener;
+import org.eclipse.swt.dnd.Transfer;
+
+/**
+ * A special drop target listener which is typed with a TransferData
.
+ */
+public interface TransferDropTargetListener extends DropTargetListener {
+
+ /**
+ * Returns the transfer used by this drop target.
+ */
+ public Transfer getTransfer();
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/packageview/PackagesMessages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/packageview/PackagesMessages.java
new file mode 100644
index 0000000..121b683
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/packageview/PackagesMessages.java
@@ -0,0 +1,58 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.ui.packageview;
+
+import java.text.MessageFormat;
+import java.util.MissingResourceException;
+import java.util.ResourceBundle;
+
+public class PackagesMessages {
+
+ private static final String RESOURCE_BUNDLE= "net.sourceforge.phpdt.internal.ui.packageview.PackagesMessages";//$NON-NLS-1$
+
+ private static ResourceBundle fgResourceBundle= ResourceBundle.getBundle(RESOURCE_BUNDLE);
+
+ private PackagesMessages() {
+ }
+
+ public static String getString(String key) {
+ try {
+ return fgResourceBundle.getString(key);
+ } catch (MissingResourceException e) {
+ return "!" + key + "!";//$NON-NLS-2$ //$NON-NLS-1$
+ }
+ }
+
+ /**
+ * Gets a string from the resource bundle and formats it with the argument
+ *
+ * @param key the string used to get the bundle value, must not be null
+ */
+ public static String getFormattedString(String key, Object arg) {
+ String format= null;
+ try {
+ format= fgResourceBundle.getString(key);
+ } catch (MissingResourceException e) {
+ return "!" + key + "!";//$NON-NLS-2$ //$NON-NLS-1$
+ }
+ if (arg == null)
+ arg= ""; //$NON-NLS-1$
+ return MessageFormat.format(format, new Object[] { arg });
+ }
+
+ /**
+ * Gets a string from the resource bundle and formats it with arguments
+ */
+ public static String getFormattedString(String key, String[] args) {
+ return MessageFormat.format(fgResourceBundle.getString(key), args);
+ }
+
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/packageview/PackagesMessages.properties b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/packageview/PackagesMessages.properties
new file mode 100644
index 0000000..01bac3f
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/packageview/PackagesMessages.properties
@@ -0,0 +1,97 @@
+###############################################################################
+# Copyright (c) 2000, 2003 IBM Corporation and others.
+# All rights reserved. This program and the accompanying materials
+# are made available under the terms of the Common Public License v1.0
+# which accompanies this distribution, and is available at
+# http://www.eclipse.org/legal/cpl-v10.html
+#
+# Contributors:
+# IBM Corporation - initial API and implementation
+###############################################################################
+
+BuildGroup.buildProject=&Build Project
+BuildGroup.rebuildProject=Rebuild Pro&ject
+
+DragAdapter.deleting=Deleting ...
+DragAdapter.problem=Problem while moving or copying files.
+DragAdapter.problemTitle=Drag & Drop
+DragAdapter.refreshing=Refreshing...
+
+DropAdapter.alreadyExists={0} already exists. Would you like to overwrite it?
+DropAdapter.errorMessage=Error while moving or copying files.
+DropAdapter.errorSame=Cannot copy {0}: the destination folder is the same as the source folder.
+DropAdapter.errorSubfolder=Cannot copy {0}: the destination folder is a subfolder of the source folder.
+DropAdapter.errorTitle=Drag & Drop
+DropAdapter.question=Question
+
+FilterSelectionAction.apply.label=Select &filters to apply (matching files will be hidden):
+FilterSelectionAction.apply.toolTip=Apply the defined filters
+FilterSelectionAction.dialog.title=Package Explorer Filters
+
+GotoPackage.action.label=&Package...
+GotoPackage.dialog.message=&Choose a package (? = any character, * = any string):
+GotoPackage.dialog.title=Go to Package
+GotoPackage.action.description=Searches for and selects the package entered.
+
+GotoType.action.label=&Type...
+GotoType.action.description=Searches for and selects the type entered.
+GotoType.dialog.message=&Choose a type (? = any character, * = any string):
+GotoType.dialog.title=Go to Type
+GotoType.error.message=An exception occurred while searching for types
+
+GotoResource.action.label=&Resource...
+GotoResource.dialog.title= Go to Resource
+
+OpenResource.action.description=Open the selected file in an editor.
+OpenResource.action.label=&Open
+OpenResource.error.message=Cannot open Java editor.
+OpenResource.error.messageArgs=Cannot open Java editor on {0}. {1}
+OpenResource.error.messageProblems=Problems Opening Editor.
+OpenResource.error.title=Open Resource
+
+Sorter.expectPackage=expects a PackageFragment or PackageFragmentRoot
+
+ShowLibraries.hideReferencedLibs=Hide referenced libraries
+ShowLibraries.showReferencedLibs=Show referenced libraries
+
+ShowBinaries.hideBinaryProjects=Hide library projects
+ShowBinaries.showBinaryProjects=Show library projects
+
+ShowInNavigator.description=Show the selected object(s) in the navigator
+ShowInNavigator.error=Cannot open navigator
+ShowInNavigator.label=Show in &Navigator
+
+PackageExplorer.filters=&Filters...
+PackageExplorer.gotoTitle=G&o To
+PackageExplorer.openPerspective=Open &Perspective
+PackageExplorer.refactoringTitle=&Refactor
+PackageExplorer.referencedLibs=Show Referenced &Libraries
+PackageExplorer.binaryProjects=Show Library Projects
+PackageExplorer.title=Package Explorer
+PackageExplorer.argTitle={0}: {1}
+PackageExplorer.toolTip= Working Set: {0}
+PackageExplorer.toolTip2= {0} - Working Set: {1}
+PackageExplorer.openWith=Open Wit&h
+
+PackageExplorer.element_not_present=Cannot reveal {0} in Package Explorer. The element may be hidden by a filter or an active working set.
+
+SelectionTransferDropAdapter.error.title=Drag and drop
+SelectionTransferDropAdapter.error.message=Unexpected exception. See log for details
+SelectionTransferDropAdapter.dialog.title=Move
+SelectionTransferDropAdapter.dialog.preview.label=Pre&view
+SelectionTransferDropAdapter.dialog.question=Do you want to update references to the moved element(s)? Click 'Preview' to see the preview of the reference updates.
+
+CollapseAllAction.label=Collapse All
+CollapseAllAction.tooltip=Collapse All
+CollapseAllAction.description=Collapse All
+
+ToggleLinkingAction.label=Lin&k With Editor
+ToggleLinkingAction.tooltip=Link with Editor
+ToggleLinkingAction.description=Link with active editor
+
+LayoutActionGroup.label= &Layout
+LayoutActionGroup.flatLayoutAction.label= &Flat
+LayoutActionGroup.hierarchicalLayoutAction.label= &Hierarchical
+
+ClassPathContainer.error_label=Could not resolve class path entry
+PackageExplorerPart.workspace=Workspace
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/packageview/SelectionTransferDragAdapter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/packageview/SelectionTransferDragAdapter.java
new file mode 100644
index 0000000..c0fca07
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/packageview/SelectionTransferDragAdapter.java
@@ -0,0 +1,43 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.ui.packageview;
+
+import java.util.Iterator;
+
+import net.sourceforge.phpdt.core.IJavaElement;
+import net.sourceforge.phpdt.core.IPackageFragmentRoot;
+
+import net.sourceforge.phpdt.internal.ui.dnd.BasicSelectionTransferDragAdapter;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.ISelectionProvider;
+import org.eclipse.jface.viewers.IStructuredSelection;
+
+public class SelectionTransferDragAdapter extends BasicSelectionTransferDragAdapter {
+
+ public SelectionTransferDragAdapter(ISelectionProvider provider) {
+ super(provider);
+ }
+
+ protected boolean isDragable(ISelection selection) {
+ if (selection instanceof IStructuredSelection) {
+ for (Iterator iter= ((IStructuredSelection)selection).iterator(); iter.hasNext();) {
+ Object element= iter.next();
+ if (element instanceof IJavaElement) {
+ IPackageFragmentRoot root= (IPackageFragmentRoot)((IJavaElement)element).getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
+ if (root != null && root.isArchive())
+ return false;
+ }
+ }
+ return true;
+ }
+ return false;
+ }
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/MembersOrderPreferenceCache.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/MembersOrderPreferenceCache.java
new file mode 100644
index 0000000..af66a6f
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/MembersOrderPreferenceCache.java
@@ -0,0 +1,90 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.ui.preferences;
+
+import java.util.StringTokenizer;
+
+import net.sourceforge.phpdt.ui.PreferenceConstants;
+
+import org.eclipse.jface.preference.IPreferenceStore;
+import org.eclipse.jface.util.IPropertyChangeListener;
+import org.eclipse.jface.util.PropertyChangeEvent;
+
+
+/**
+ */
+public class MembersOrderPreferenceCache implements IPropertyChangeListener {
+
+ public static final int TYPE_INDEX= 0;
+ public static final int CONSTRUCTORS_INDEX= 1;
+ public static final int METHOD_INDEX= 2;
+ public static final int FIELDS_INDEX= 3;
+ public static final int INIT_INDEX= 4;
+ public static final int STATIC_FIELDS_INDEX= 5;
+ public static final int STATIC_INIT_INDEX= 6;
+ public static final int STATIC_METHODS_INDEX= 7;
+ public static final int N_ENTRIES= STATIC_METHODS_INDEX + 1;
+
+ private int[] fOffsets= null;
+
+ public void propertyChange(PropertyChangeEvent event) {
+ if (PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER.equals(event.getProperty())) {
+ fOffsets= null;
+ }
+ }
+
+ public int getIndex(int kind) {
+ if (fOffsets == null) {
+ fOffsets= getOffsets();
+ }
+ return fOffsets[kind];
+ }
+
+ private int[] getOffsets() {
+ int[] offsets= new int[N_ENTRIES];
+ IPreferenceStore store= PreferenceConstants.getPreferenceStore();
+ String key= PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER;
+ boolean success= fillOffsetsFromPreferenceString(store.getString(key), offsets);
+ if (!success) {
+ store.setToDefault(key);
+ fillOffsetsFromPreferenceString(store.getDefaultString(key), offsets);
+ }
+ return offsets;
+ }
+
+ private boolean fillOffsetsFromPreferenceString(String str, int[] offsets) {
+ StringTokenizer tokenizer= new StringTokenizer(str, ","); //$NON-NLS-1$
+ int i= 0;
+ while (tokenizer.hasMoreTokens()) {
+ String token= tokenizer.nextToken().trim();
+ if ("T".equals(token)) { //$NON-NLS-1$
+ offsets[TYPE_INDEX]= i++;
+ } else if ("M".equals(token)) { //$NON-NLS-1$
+ offsets[METHOD_INDEX]= i++;
+ } else if ("F".equals(token)) { //$NON-NLS-1$
+ offsets[FIELDS_INDEX]= i++;
+ } else if ("I".equals(token)) { //$NON-NLS-1$
+ offsets[INIT_INDEX]= i++;
+ } else if ("SF".equals(token)) { //$NON-NLS-1$
+ offsets[STATIC_FIELDS_INDEX]= i++;
+ } else if ("SI".equals(token)) { //$NON-NLS-1$
+ offsets[STATIC_INIT_INDEX]= i++;
+ } else if ("SM".equals(token)) { //$NON-NLS-1$
+ offsets[STATIC_METHODS_INDEX]= i++;
+ } else if ("C".equals(token)) { //$NON-NLS-1$
+ offsets[CONSTRUCTORS_INDEX]= i++;
+ }
+ }
+ return i == N_ENTRIES;
+ }
+
+
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/MembersOrderPreferencePage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/MembersOrderPreferencePage.java
new file mode 100644
index 0000000..a7225ff
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/MembersOrderPreferencePage.java
@@ -0,0 +1,262 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+
+package net.sourceforge.phpdt.internal.ui.preferences;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.StringTokenizer;
+
+import net.sourceforge.phpdt.core.Flags;
+import net.sourceforge.phpdt.internal.ui.util.SWTUtil;
+import net.sourceforge.phpdt.internal.ui.viewsupport.ImageDescriptorRegistry;
+import net.sourceforge.phpdt.internal.ui.viewsupport.JavaElementImageProvider;
+import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.ListDialogField;
+import net.sourceforge.phpdt.ui.JavaElementImageDescriptor;
+import net.sourceforge.phpdt.ui.PreferenceConstants;
+import net.sourceforge.phpeclipse.PHPeclipsePlugin;
+
+import org.eclipse.jface.dialogs.Dialog;
+import org.eclipse.jface.preference.IPreferenceStore;
+import org.eclipse.jface.preference.PreferencePage;
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.jface.viewers.LabelProvider;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.ui.IWorkbench;
+import org.eclipse.ui.IWorkbenchPreferencePage;
+
+public class MembersOrderPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
+
+ private static final String ALL_ENTRIES= "T,SI,SF,SM,I,F,C,M"; //$NON-NLS-1$
+ private static final String PREF_OUTLINE_SORT_OPTION= PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER;
+
+ public static final String CONSTRUCTORS= "C"; //$NON-NLS-1$
+ public static final String FIELDS= "F"; //$NON-NLS-1$
+ public static final String METHODS= "M"; //$NON-NLS-1$
+ public static final String STATIC_METHODS= "SM"; //$NON-NLS-1$
+ public static final String STATIC_FIELDS= "SF"; //$NON-NLS-1$
+ public static final String INIT= "I"; //$NON-NLS-1$
+ public static final String STATIC_INIT= "SI"; //$NON-NLS-1$
+ public static final String TYPES= "T"; //$NON-NLS-1$
+
+ private ListDialogField fSortOrderList;
+
+ private static List getSortOrderList(String string) {
+ StringTokenizer tokenizer= new StringTokenizer(string, ","); //$NON-NLS-1$
+ List entries= new ArrayList();
+ for (int i= 0; tokenizer.hasMoreTokens(); i++) {
+ String token= tokenizer.nextToken();
+ entries.add(token);
+ }
+ return entries;
+ }
+
+ private static boolean isValidEntries(List entries) {
+ StringTokenizer tokenizer= new StringTokenizer(ALL_ENTRIES, ","); //$NON-NLS-1$
+ int i= 0;
+ for (; tokenizer.hasMoreTokens(); i++) {
+ String token= tokenizer.nextToken();
+ if (!entries.contains(token))
+ return false;
+ }
+ return i == entries.size();
+ }
+
+ public MembersOrderPreferencePage() {
+ //set the preference store
+ setPreferenceStore(PHPeclipsePlugin.getDefault().getPreferenceStore());
+
+ setDescription(PreferencesMessages.getString("MembersOrderPreferencePage.label.description")); //$NON-NLS-1$
+
+ String string= getPreferenceStore().getString(PREF_OUTLINE_SORT_OPTION);
+
+ String upLabel= PreferencesMessages.getString("MembersOrderPreferencePage.button.up"); //$NON-NLS-1$
+ String downLabel= PreferencesMessages.getString("MembersOrderPreferencePage.button.down"); //$NON-NLS-1$
+ String[] buttonlabels= new String[] { upLabel, downLabel };
+
+ fSortOrderList= new ListDialogField(null, buttonlabels, new MemberSortLabelProvider());
+ fSortOrderList.setDownButtonIndex(1);
+ fSortOrderList.setUpButtonIndex(0);
+
+ //validate entries stored in store, false get defaults
+ List entries= getSortOrderList(string);
+ if (!isValidEntries(entries)) {
+ string= PHPeclipsePlugin.getDefault().getPreferenceStore().getDefaultString(PREF_OUTLINE_SORT_OPTION);
+ entries= getSortOrderList(string);
+ }
+
+ fSortOrderList.setElements(entries);
+ }
+
+ /*
+ * @see PreferencePage#createControl(Composite)
+ */
+ public void createControl(Composite parent) {
+ super.createControl(parent);
+// WorkbenchHelp.setHelp(getControl(), IJavaHelpContextIds.SORT_ORDER_PREFERENCE_PAGE);
+ }
+
+ /*
+ * @see org.eclipse.jface.preference.PreferencePage#createContents(Composite)
+ */
+ protected Control createContents(Composite parent) {
+
+
+ Composite composite= new Composite(parent, SWT.NONE);
+
+ GridLayout layout= new GridLayout();
+ layout.numColumns= 3;
+ layout.marginWidth= 0;
+ layout.marginHeight= 0;
+ composite.setLayout(layout);
+
+ GridData data= new GridData();
+ data.verticalAlignment= GridData.FILL;
+ data.horizontalAlignment= GridData.FILL_HORIZONTAL;
+ composite.setLayoutData(data);
+
+ createSortOrderListDialogField(composite, 3);
+ Dialog.applyDialogFont(composite);
+ return composite;
+ }
+
+ private void createSortOrderListDialogField(Composite composite, int span) {
+ fSortOrderList.doFillIntoGrid(composite, span);
+
+ fSortOrderList.getLabelControl(null).dispose();
+
+ GridData data= (GridData) fSortOrderList.getListControl(null).getLayoutData();
+ data.grabExcessHorizontalSpace= true;
+ data.verticalAlignment= 0;
+ data.heightHint= SWTUtil.getTableHeightHint(fSortOrderList.getTableViewer().getTable(), 8);
+ }
+
+ /*
+ * @see org.eclipse.ui.IWorkbenchPreferencePage#init(IWorkbench)
+ */
+ public void init(IWorkbench workbench) {
+ }
+
+ /*
+ * @see org.eclipse.jface.preference.PreferencePage#performDefaults()
+ */
+ protected void performDefaults() {
+ String string= getPreferenceStore().getDefaultString(PREF_OUTLINE_SORT_OPTION);
+ fSortOrderList.setElements(getSortOrderList(string));
+ }
+
+ /*
+ * @see org.eclipse.jface.preference.IPreferencePage#performOk()
+ */
+ //reorders elements in the Outline based on selection
+ public boolean performOk() {
+ //update outline view
+
+ //save preferences
+ IPreferenceStore store= getPreferenceStore();
+
+ StringBuffer buf= new StringBuffer();
+ List curr= fSortOrderList.getElements();
+ for (Iterator iter= curr.iterator(); iter.hasNext();) {
+ String s= (String) iter.next();
+ buf.append(s);
+ buf.append(',');
+ }
+ store.setValue(PREF_OUTLINE_SORT_OPTION, buf.toString());
+ PHPeclipsePlugin.getDefault().savePluginPreferences();
+ return true;
+ }
+
+ private class MemberSortLabelProvider extends LabelProvider {
+
+ public MemberSortLabelProvider() {
+ }
+
+ /*
+ * @see org.eclipse.jface.viewers.ILabelProvider#getText(Object)
+ */
+ public String getText(Object element) {
+
+ if (element instanceof String) {
+ String s= (String) element;
+ if (s.equals(FIELDS)) {
+ return PreferencesMessages.getString("MembersOrderPreferencePage.fields.label"); //$NON-NLS-1$
+ } else if (s.equals(CONSTRUCTORS)) {
+ return PreferencesMessages.getString("MembersOrderPreferencePage.constructors.label"); //$NON-NLS-1$
+ } else if (s.equals(METHODS)) {
+ return PreferencesMessages.getString("MembersOrderPreferencePage.methods.label"); //$NON-NLS-1$
+ } else if (s.equals(STATIC_FIELDS)) {
+ return PreferencesMessages.getString("MembersOrderPreferencePage.staticfields.label"); //$NON-NLS-1$
+ } else if (s.equals(STATIC_METHODS)) {
+ return PreferencesMessages.getString("MembersOrderPreferencePage.staticmethods.label"); //$NON-NLS-1$
+ } else if (s.equals(INIT)) {
+ return PreferencesMessages.getString("MembersOrderPreferencePage.initialisers.label"); //$NON-NLS-1$
+ } else if (s.equals(STATIC_INIT)) {
+ return PreferencesMessages.getString("MembersOrderPreferencePage.staticinitialisers.label"); //$NON-NLS-1$
+ } else if (s.equals(TYPES)) {
+ return PreferencesMessages.getString("MembersOrderPreferencePage.types.label"); //$NON-NLS-1$
+ }
+ }
+ return ""; //$NON-NLS-1$
+ }
+
+ /*
+ * @see org.eclipse.jface.viewers.ILabelProvider#getImage(Object)
+ */
+ public Image getImage(Object element) {
+ //access to image registry
+ ImageDescriptorRegistry registry= PHPeclipsePlugin.getImageDescriptorRegistry();
+ ImageDescriptor descriptor= null;
+
+ if (element instanceof String) {
+ int visibility= Flags.AccPublic;
+ String s= (String) element;
+ if (s.equals(FIELDS)) {
+ //0 will give the default field image
+ descriptor= JavaElementImageProvider.getFieldImageDescriptor(false, visibility);
+ } else if (s.equals(CONSTRUCTORS)) {
+ descriptor= JavaElementImageProvider.getMethodImageDescriptor(false, visibility);
+ //add a constructor adornment to the image descriptor
+ descriptor= new JavaElementImageDescriptor(descriptor, JavaElementImageDescriptor.CONSTRUCTOR, JavaElementImageProvider.SMALL_SIZE);
+ } else if (s.equals(METHODS)) {
+ descriptor= JavaElementImageProvider.getMethodImageDescriptor(false, visibility);
+ } else if (s.equals(STATIC_FIELDS)) {
+ descriptor= JavaElementImageProvider.getFieldImageDescriptor(false, visibility);
+ //add a constructor adornment to the image descriptor
+ descriptor= new JavaElementImageDescriptor(descriptor, JavaElementImageDescriptor.STATIC, JavaElementImageProvider.SMALL_SIZE);
+ } else if (s.equals(STATIC_METHODS)) {
+ descriptor= JavaElementImageProvider.getMethodImageDescriptor(false, visibility);
+ //add a constructor adornment to the image descriptor
+ descriptor= new JavaElementImageDescriptor(descriptor, JavaElementImageDescriptor.STATIC, JavaElementImageProvider.SMALL_SIZE);
+ } else if (s.equals(INIT)) {
+ descriptor= JavaElementImageProvider.getMethodImageDescriptor(false, visibility);
+ } else if (s.equals(STATIC_INIT)) {
+ descriptor= JavaElementImageProvider.getMethodImageDescriptor(false, visibility);
+ descriptor= new JavaElementImageDescriptor(descriptor, JavaElementImageDescriptor.STATIC, JavaElementImageProvider.SMALL_SIZE);
+ } else if (s.equals(TYPES)) {
+ descriptor= JavaElementImageProvider.getTypeImageDescriptor(false, true, Flags.AccPublic);
+ } else {
+ descriptor= JavaElementImageProvider.getMethodImageDescriptor(false, Flags.AccPublic);
+ }
+ return registry.get(descriptor);
+ }
+ return null;
+ }
+
+ }
+
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/PHPEditorPreferencePage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/PHPEditorPreferencePage.java
index 836ca7c..641374d 100644
--- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/PHPEditorPreferencePage.java
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/PHPEditorPreferencePage.java
@@ -26,11 +26,13 @@ import net.sourceforge.phpdt.internal.ui.util.TabFolderLayout;
import net.sourceforge.phpdt.ui.PreferenceConstants;
import net.sourceforge.phpdt.ui.text.JavaTextTools;
import net.sourceforge.phpeclipse.IPreferenceConstants;
+import net.sourceforge.phpeclipse.PHPCore;
import net.sourceforge.phpeclipse.PHPeclipsePlugin;
import net.sourceforge.phpeclipse.phpeditor.PHPSourceViewerConfiguration;
import net.sourceforge.phpeclipse.preferences.ColorEditor;
import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Preferences;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.preference.PreferencePage;
@@ -74,6 +76,7 @@ import org.eclipse.ui.texteditor.WorkbenchChainedTextFontFieldEditor;
public class PHPEditorPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
private static final String BOLD = PreferenceConstants.EDITOR_BOLD_SUFFIX;
+ private static final String COMPILER_TASK_TAGS = PHPCore.COMPILER_TASK_TAGS;
public final OverlayPreferenceStore.OverlayKey[] fKeys =
new OverlayPreferenceStore.OverlayKey[] {
@@ -86,8 +89,8 @@ public class PHPEditorPreferencePage extends PreferencePage implements IWorkbenc
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_BOLD),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_COLOR),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_BOLD),
- new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_JAVA_TAG_COLOR),
- new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_JAVA_TAG_BOLD),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_JAVA_TAG_COLOR),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_JAVA_TAG_BOLD),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_JAVA_KEYWORD_COLOR),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_JAVA_KEYWORD_BOLD),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_PHP_FUNCTIONNAME_COLOR),
@@ -211,8 +214,8 @@ public class PHPEditorPreferencePage extends PreferencePage implements IWorkbenc
{
PHPUIMessages.getString("PHPEditorPreferencePage.singleLineComment"), PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_COLOR }, //$NON-NLS-1$
{
- PHPUIMessages.getString("PHPEditorPreferencePage.tags"), PreferenceConstants.EDITOR_JAVA_TAG_COLOR }, //$NON-NLS-1$
- {
+ PHPUIMessages.getString("PHPEditorPreferencePage.tags"), PreferenceConstants.EDITOR_JAVA_TAG_COLOR }, //$NON-NLS-1$
+ {
PHPUIMessages.getString("PHPEditorPreferencePage.keywords"), PreferenceConstants.EDITOR_JAVA_KEYWORD_COLOR }, //$NON-NLS-1$
{
PHPUIMessages.getString("PHPEditorPreferencePage.functionNames"), PreferenceConstants.EDITOR_PHP_FUNCTIONNAME_COLOR }, //$NON-NLS-1$
@@ -539,8 +542,9 @@ public class PHPEditorPreferencePage extends PreferencePage implements IWorkbenc
}
private Control createPreviewer(Composite parent) {
+ Preferences coreStore = createTemporaryCorePreferenceStore();
- fJavaTextTools = new JavaTextTools(fOverlayStore);
+ fJavaTextTools = new JavaTextTools(fOverlayStore, coreStore, false);
fPreviewViewer = new SourceViewer(parent, null, SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER);
fPreviewViewer.configure(new PHPSourceViewerConfiguration(fJavaTextTools, null));
@@ -551,7 +555,7 @@ public class PHPEditorPreferencePage extends PreferencePage implements IWorkbenc
String content = loadPreviewContentFromFile("ColorSettingPreviewCode.txt"); //$NON-NLS-1$
IDocument document = new Document(content);
- // PHPEditorEnvironment pe;
+ // PHPEditorEnvironment pe;
IDocumentPartitioner partitioner = fJavaTextTools.createDocumentPartitioner();
partitioner.connect(document);
document.setDocumentPartitioner(partitioner);
@@ -572,7 +576,13 @@ public class PHPEditorPreferencePage extends PreferencePage implements IWorkbenc
return fPreviewViewer.getControl();
}
+ private Preferences createTemporaryCorePreferenceStore() {
+ Preferences result = new Preferences();
+
+ result.setValue(COMPILER_TASK_TAGS, "TASK"); //$NON-NLS-1$
+ return result;
+ }
/**
* Initializes the given viewer's colors.
*
@@ -741,11 +751,11 @@ public class PHPEditorPreferencePage extends PreferencePage implements IWorkbenc
layout.numColumns = 2;
composite.setLayout(layout);
-// String text = "Analyse &problems while typing";
-// addCheckBox(composite, text, PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS, 0);
-//
-// text = PHPUIMessages.getString("PHPEditorPreferencePage.showQuickFixables"); //$NON-NLS-1$
-// addCheckBox(composite, text, PreferenceConstants.EDITOR_CORRECTION_INDICATION, 0);
+ // String text = "Analyse &problems while typing";
+ // addCheckBox(composite, text, PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS, 0);
+ //
+ // text = PHPUIMessages.getString("PHPEditorPreferencePage.showQuickFixables"); //$NON-NLS-1$
+ // addCheckBox(composite, text, PreferenceConstants.EDITOR_CORRECTION_INDICATION, 0);
Label label = new Label(composite, SWT.LEFT);
GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
@@ -857,49 +867,50 @@ public class PHPEditorPreferencePage extends PreferencePage implements IWorkbenc
return composite;
}
- private Control createBehaviourPage(Composite parent) {
- Composite composite= new Composite(parent, SWT.NULL);
- GridLayout layout= new GridLayout(); layout.numColumns= 2;
- composite.setLayout(layout);
- String label;
-// String label= PHPUIMessages.getString("PHPEditorPreferencePage.wrapStrings"); //$NON-NLS-1$
-// addCheckBox(composite, label, PreferenceConstants.EDITOR_WRAP_STRINGS, 1);
-
-// label= PHPUIMessages.getString("PHPEditorPreferencePage.smartHomeEnd"); //$NON-NLS-1$
-// addCheckBox(composite, label, PreferenceConstants.EDITOR_SMART_HOME_END, 1);
-//
-// label= PHPUIMessages.getString("PHPEditorPreferencePage.smartPaste"); //$NON-NLS-1$
-// addCheckBox(composite, label, PreferenceConstants.EDITOR_SMART_PASTE, 1);
-
- label= PHPUIMessages.getString("PHPEditorPreferencePage.insertSpaceForTabs"); //$NON-NLS-1$
- addCheckBox(composite, label, PreferenceConstants.EDITOR_SPACES_FOR_TABS, 1);
-
- label= PHPUIMessages.getString("PHPEditorPreferencePage.closeStringsPHP"); //$NON-NLS-1$
- addCheckBox(composite, label, PreferenceConstants.EDITOR_CLOSE_STRINGS_PHP, 1);
-
- label= PHPUIMessages.getString("PHPEditorPreferencePage.closeBracketsPHP"); //$NON-NLS-1$
- addCheckBox(composite, label, PreferenceConstants.EDITOR_CLOSE_BRACKETS_PHP, 1);
-
-// label= PHPUIMessages.getString("PHPEditorPreferencePage.closeBraces"); //$NON-NLS-1$
-// addCheckBox(composite, label, PreferenceConstants.EDITOR_CLOSE_BRACES, 1);
-//
-// label= PHPUIMessages.getString("PHPEditorPreferencePage.closePHPDocs"); //$NON-NLS-1$
-// Button button= addCheckBox(composite, label, PreferenceConstants.EDITOR_CLOSE_JAVADOCS, 1);
-//
-// label= PHPUIMessages.getString("PHPEditorPreferencePage.addPHPDocTags"); //$NON-NLS-1$
-// fAddJavaDocTagsButton= addCheckBox(composite, label, PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS, 1);
-// createDependency(button, fAddJavaDocTagsButton);
-
-// label= PHPUIMessages.getString("PHPEditorPreferencePage.formatPHPDocs"); //$NON-NLS-1$
-// addCheckBox(composite, label, PreferenceConstants.EDITOR_FORMAT_JAVADOCS, 1);
-//
- label= PHPUIMessages.getString("PHPEditorPreferencePage.closeStringsHTML"); //$NON-NLS-1$
- addCheckBox(composite, label, PreferenceConstants.EDITOR_CLOSE_STRINGS_HTML, 1);
-
- label= PHPUIMessages.getString("PHPEditorPreferencePage.closeBracketsHTML"); //$NON-NLS-1$
- addCheckBox(composite, label, PreferenceConstants.EDITOR_CLOSE_BRACKETS_HTML, 1);
- return composite;
- }
+ private Control createBehaviourPage(Composite parent) {
+ Composite composite = new Composite(parent, SWT.NULL);
+ GridLayout layout = new GridLayout();
+ layout.numColumns = 2;
+ composite.setLayout(layout);
+ String label;
+ // String label= PHPUIMessages.getString("PHPEditorPreferencePage.wrapStrings"); //$NON-NLS-1$
+ // addCheckBox(composite, label, PreferenceConstants.EDITOR_WRAP_STRINGS, 1);
+
+ // label= PHPUIMessages.getString("PHPEditorPreferencePage.smartHomeEnd"); //$NON-NLS-1$
+ // addCheckBox(composite, label, PreferenceConstants.EDITOR_SMART_HOME_END, 1);
+ //
+ // label= PHPUIMessages.getString("PHPEditorPreferencePage.smartPaste"); //$NON-NLS-1$
+ // addCheckBox(composite, label, PreferenceConstants.EDITOR_SMART_PASTE, 1);
+
+ label = PHPUIMessages.getString("PHPEditorPreferencePage.insertSpaceForTabs"); //$NON-NLS-1$
+ addCheckBox(composite, label, PreferenceConstants.EDITOR_SPACES_FOR_TABS, 1);
+
+ label = PHPUIMessages.getString("PHPEditorPreferencePage.closeStringsPHP"); //$NON-NLS-1$
+ addCheckBox(composite, label, PreferenceConstants.EDITOR_CLOSE_STRINGS_PHP, 1);
+
+ label = PHPUIMessages.getString("PHPEditorPreferencePage.closeBracketsPHP"); //$NON-NLS-1$
+ addCheckBox(composite, label, PreferenceConstants.EDITOR_CLOSE_BRACKETS_PHP, 1);
+
+ // label= PHPUIMessages.getString("PHPEditorPreferencePage.closeBraces"); //$NON-NLS-1$
+ // addCheckBox(composite, label, PreferenceConstants.EDITOR_CLOSE_BRACES, 1);
+ //
+ // label= PHPUIMessages.getString("PHPEditorPreferencePage.closePHPDocs"); //$NON-NLS-1$
+ // Button button= addCheckBox(composite, label, PreferenceConstants.EDITOR_CLOSE_JAVADOCS, 1);
+ //
+ // label= PHPUIMessages.getString("PHPEditorPreferencePage.addPHPDocTags"); //$NON-NLS-1$
+ // fAddJavaDocTagsButton= addCheckBox(composite, label, PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS, 1);
+ // createDependency(button, fAddJavaDocTagsButton);
+
+ // label= PHPUIMessages.getString("PHPEditorPreferencePage.formatPHPDocs"); //$NON-NLS-1$
+ // addCheckBox(composite, label, PreferenceConstants.EDITOR_FORMAT_JAVADOCS, 1);
+ //
+ label = PHPUIMessages.getString("PHPEditorPreferencePage.closeStringsHTML"); //$NON-NLS-1$
+ addCheckBox(composite, label, PreferenceConstants.EDITOR_CLOSE_STRINGS_HTML, 1);
+
+ label = PHPUIMessages.getString("PHPEditorPreferencePage.closeBracketsHTML"); //$NON-NLS-1$
+ addCheckBox(composite, label, PreferenceConstants.EDITOR_CLOSE_BRACKETS_HTML, 1);
+ return composite;
+ }
private static void indent(Control control) {
GridData gridData = new GridData();
@@ -926,28 +937,28 @@ public class PHPEditorPreferencePage extends PreferencePage implements IWorkbenc
layout.numColumns = 2;
contentAssistComposite.setLayout(layout);
String label;
-// String label = PHPUIMessages.getString("PHPEditorPreferencePage.insertSingleProposalsAutomatically"); //$NON-NLS-1$
-// addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_AUTOINSERT, 0);
-//
-// label = PHPUIMessages.getString("PHPEditorPreferencePage.showOnlyProposalsVisibleInTheInvocationContext"); //$NON-NLS-1$
-// addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_SHOW_VISIBLE_PROPOSALS, 0);
-//
-// label = PHPUIMessages.getString("PHPEditorPreferencePage.presentProposalsInAlphabeticalOrder"); //$NON-NLS-1$
-// addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_ORDER_PROPOSALS, 0);
-//
-// label = PHPUIMessages.getString("PHPEditorPreferencePage.automaticallyAddImportInsteadOfQualifiedName"); //$NON-NLS-1$
-// addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_ADDIMPORT, 0);
-//
-// label = PHPUIMessages.getString("PHPEditorPreferencePage.insertCompletion"); //$NON-NLS-1$
-// addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_INSERT_COMPLETION, 0);
-//
-// label = PHPUIMessages.getString("PHPEditorPreferencePage.fillArgumentNamesOnMethodCompletion"); //$NON-NLS-1$
-// Button button = addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES, 0);
-//
-// label = PHPUIMessages.getString("PHPEditorPreferencePage.guessArgumentNamesOnMethodCompletion"); //$NON-NLS-1$
-// fGuessMethodArgumentsButton =
-// addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_GUESS_METHOD_ARGUMENTS, 0);
-// createDependency(button, fGuessMethodArgumentsButton);
+ // String label = PHPUIMessages.getString("PHPEditorPreferencePage.insertSingleProposalsAutomatically"); //$NON-NLS-1$
+ // addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_AUTOINSERT, 0);
+ //
+ // label = PHPUIMessages.getString("PHPEditorPreferencePage.showOnlyProposalsVisibleInTheInvocationContext"); //$NON-NLS-1$
+ // addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_SHOW_VISIBLE_PROPOSALS, 0);
+ //
+ // label = PHPUIMessages.getString("PHPEditorPreferencePage.presentProposalsInAlphabeticalOrder"); //$NON-NLS-1$
+ // addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_ORDER_PROPOSALS, 0);
+ //
+ // label = PHPUIMessages.getString("PHPEditorPreferencePage.automaticallyAddImportInsteadOfQualifiedName"); //$NON-NLS-1$
+ // addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_ADDIMPORT, 0);
+ //
+ // label = PHPUIMessages.getString("PHPEditorPreferencePage.insertCompletion"); //$NON-NLS-1$
+ // addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_INSERT_COMPLETION, 0);
+ //
+ // label = PHPUIMessages.getString("PHPEditorPreferencePage.fillArgumentNamesOnMethodCompletion"); //$NON-NLS-1$
+ // Button button = addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES, 0);
+ //
+ // label = PHPUIMessages.getString("PHPEditorPreferencePage.guessArgumentNamesOnMethodCompletion"); //$NON-NLS-1$
+ // fGuessMethodArgumentsButton =
+ // addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_GUESS_METHOD_ARGUMENTS, 0);
+ // createDependency(button, fGuessMethodArgumentsButton);
label = PHPUIMessages.getString("PHPEditorPreferencePage.enableAutoActivation"); //$NON-NLS-1$
final Button autoactivation = addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_AUTOACTIVATION, 0);
@@ -1022,9 +1033,9 @@ public class PHPEditorPreferencePage extends PreferencePage implements IWorkbenc
item.setText(PHPUIMessages.getString("PHPEditorPreferencePage.problemIndicationTab.title")); //$NON-NLS-1$
item.setControl(createProblemIndicationPage(folder));
- item= new TabItem(folder, SWT.NONE);
- item.setText(PHPUIMessages.getString("PHPEditorPreferencePage.behaviourTab.title")); //$NON-NLS-1$
- item.setControl(createBehaviourPage(folder));
+ item = new TabItem(folder, SWT.NONE);
+ item.setText(PHPUIMessages.getString("PHPEditorPreferencePage.behaviourTab.title")); //$NON-NLS-1$
+ item.setControl(createBehaviourPage(folder));
// item= new TabItem(folder, SWT.NONE);
// item.setText(PHPUIMessages.getString("PHPEditorPreferencePage.hoverTab.title")); //$NON-NLS-1$
@@ -1113,11 +1124,11 @@ public class PHPEditorPreferencePage extends PreferencePage implements IWorkbenc
fBackgroundCustomRadioButton.setSelection(!default_);
fBackgroundColorButton.setEnabled(!default_);
-// boolean closeJavaDocs= fOverlayStore.getBoolean(PreferenceConstants.EDITOR_CLOSE_JAVADOCS);
-// fAddJavaDocTagsButton.setEnabled(closeJavaDocs);
+ // boolean closeJavaDocs= fOverlayStore.getBoolean(PreferenceConstants.EDITOR_CLOSE_JAVADOCS);
+ // fAddJavaDocTagsButton.setEnabled(closeJavaDocs);
-// boolean fillMethodArguments = fOverlayStore.getBoolean(PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES);
-// fGuessMethodArgumentsButton.setEnabled(fillMethodArguments);
+ // boolean fillMethodArguments = fOverlayStore.getBoolean(PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES);
+ // fGuessMethodArgumentsButton.setEnabled(fillMethodArguments);
updateAutoactivationControls();
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/PreferencesMessages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/PreferencesMessages.java
new file mode 100644
index 0000000..5d0fbf6
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/PreferencesMessages.java
@@ -0,0 +1,42 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.ui.preferences;
+
+import java.text.MessageFormat;
+import java.util.MissingResourceException;
+import java.util.ResourceBundle;
+
+public class PreferencesMessages {
+
+ private static final String RESOURCE_BUNDLE= "org.eclipse.jdt.internal.ui.preferences.PreferencesMessages";//$NON-NLS-1$
+
+ private static ResourceBundle fgResourceBundle= ResourceBundle.getBundle(RESOURCE_BUNDLE);
+
+ private PreferencesMessages() {
+ }
+
+ public static String getString(String key) {
+ try {
+ return fgResourceBundle.getString(key);
+ } catch (MissingResourceException e) {
+ return '!' + key + '!';
+ }
+ }
+
+ public static String getFormattedString(String key, String arg) {
+ return getFormattedString(key, new String[] { arg });
+ }
+
+ public static String getFormattedString(String key, String[] args) {
+ return MessageFormat.format(getString(key), args);
+ }
+
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/PreferencesMessages.properties b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/PreferencesMessages.properties
new file mode 100644
index 0000000..8f19d46
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/PreferencesMessages.properties
@@ -0,0 +1,500 @@
+###############################################################################
+# Copyright (c) 2000, 2003 IBM Corporation and others.
+# All rights reserved. This program and the accompanying materials
+# are made available under the terms of the Common Public License v1.0
+# which accompanies this distribution, and is available at
+# http://www.eclipse.org/legal/cpl-v10.html
+#
+# Contributors:
+# IBM Corporation - initial API and implementation
+###############################################################################
+
+BuildPathsPropertyPage.error.message=An error occurred while setting the build path
+BuildPathsPropertyPage.error.title=Error Setting Build Path
+BuildPathsPropertyPage.no_java_project.message=Not a Java project.
+BuildPathsPropertyPage.closed_project.message=Java information is not available for a closed project.
+
+ClasspathVariablesPreferencePage.title=Classpath Variables
+ClasspathVariablesPreferencePage.description=A classpath variable can be added to a project's class path. It can be used to define the location of a JAR file that isn't part of the workspace. The reserved class path variables JRE_LIB, JRE_SRC, JRE_SRCROOT are set internally depending on the JRE setting.
+
+ImportOrganizePreferencePage.description=Preferences used by the Organize Imports action:
+
+ImportOrganizePreferencePage.order.label=Define the &sorting order of import statements. A package name prefix (e.g. org.eclipse) is a valid entry.
+
+ImportOrganizePreferencePage.order.add.button=&New..
+ImportOrganizePreferencePage.order.edit.button=&Edit...
+ImportOrganizePreferencePage.order.up.button=&Up
+ImportOrganizePreferencePage.order.down.button=Do&wn
+ImportOrganizePreferencePage.order.remove.button=&Remove
+ImportOrganizePreferencePage.order.load.button=&Load...
+ImportOrganizePreferencePage.order.save.button=Sa&ve...
+ImportOrganizePreferencePage.ignoreLowerCase.label=Do not create imports for &types starting with a lowercase letter
+
+ImportOrganizePreferencePage.threshold.label=Number of &imports needed for .* (e.g. org.eclipse.*):
+ImportOrganizePreferencePage.error.invalidthreshold=Invalid import number.
+
+ImportOrganizePreferencePage.loadDialog.title=Load Import Order from File
+ImportOrganizePreferencePage.loadDialog.error.title=Load Import Order
+ImportOrganizePreferencePage.loadDialog.error.message=Loading failed. Not a valid import order file.
+
+ImportOrganizePreferencePage.saveDialog.title=Save Import Order to File
+ImportOrganizePreferencePage.saveDialog.error.title=Save Import Order
+ImportOrganizePreferencePage.saveDialog.error.message=Writing import order file failed.
+
+
+ImportOrganizeInputDialog.title=Import Order Entry
+ImportOrganizeInputDialog.message=&Package name or package name prefix:
+ImportOrganizeInputDialog.browse.button=&Browse...
+ImportOrganizeInputDialog.ChoosePackageDialog.title=Package Selection
+ImportOrganizeInputDialog.ChoosePackageDialog.description=Choose package name or package prefix:
+ImportOrganizeInputDialog.ChoosePackageDialog.empty=No packages available.
+ImportOrganizeInputDialog.error.enterName=Enter a package name.
+ImportOrganizeInputDialog.error.invalidName=Not a valid package name. {0}
+ImportOrganizeInputDialog.error.entryExists=Package name already exists in list.
+
+JavaBasePreferencePage.description=General settings for Java development:
+
+JavaBasePreferencePage.updateJavaViews=Update Java views
+JavaBasePreferencePage.onSave=On &save only
+JavaBasePreferencePage.whileEditing=While &editing
+JavaBasePreferencePage.notice.outliner=Note: This preference is not applied to already opened views (Outline view is always updated while editing)
+
+JavaBasePreferencePage.openTypeHierarchy=When opening a Type Hierarchy
+JavaBasePreferencePage.inPerspective=Open a new Type Hierarchy &Perspective
+JavaBasePreferencePage.inView=Show the &Type Hierarchy View in the current perspective
+JavaBasePreferencePage.doubleclick.action=Action on double click in the Package Explorer
+JavaBasePreferencePage.doubleclick.gointo=&Go into the selected element
+JavaBasePreferencePage.doubleclick.expand=E&xpand the selected element
+
+NewJavaProjectPreferencePage.description=Specify the classpath entries used as default by the New Java Project creation wizard:
+
+NewJavaProjectPreferencePage.sourcefolder.label=Source and output folder
+NewJavaProjectPreferencePage.sourcefolder.project=&Project
+NewJavaProjectPreferencePage.sourcefolder.folder=&Folders
+NewJavaProjectPreferencePage.folders.src=&Source folder name:
+NewJavaProjectPreferencePage.folders.bin=&Output folder name:
+
+NewJavaProjectPreferencePage.jrelibrary.label=As &JRE library use:
+NewJavaProjectPreferencePage.jre_variable.description=JRE_LIB variable
+NewJavaProjectPreferencePage.jre_container.description=JRE container
+
+NewJavaProjectPreferencePage.folders.error.namesempty=Enter folder names.
+NewJavaProjectPreferencePage.folders.error.invalidsrcname=Invalid source folder name: {0}
+NewJavaProjectPreferencePage.folders.error.invalidbinname=Invalid output folder name: {0}
+NewJavaProjectPreferencePage.folders.error.invalidcp=Settings will result in an invalid build path. Check for nested folders.
+
+NewJavaProjectPreferencePage.error.decode=Error while decoding JRE entry
+
+JavaEditorPreferencePage.annotationsTab.title= Annotation&s
+JavaEditorPreferencePage.showQuickFixables= Indicate annotations solvable with &Quick Fix in vertical ruler
+JavaEditorPreferencePage.analyseAnnotationsWhileTyping= Analyze annotations &while typing
+JavaEditorPreferencePage.annotationPresentationOptions= Annotation &presentation:
+JavaEditorPreferencePage.description=Java Editor settings:
+JavaEditorPreferencePage.annotations.bookmarks= Bookmarks
+JavaEditorPreferencePage.annotations.searchResults= Search Results
+JavaEditorPreferencePage.annotations.errors= Errors
+JavaEditorPreferencePage.annotations.warnings= Warnings
+JavaEditorPreferencePage.annotations.tasks= Tasks
+JavaEditorPreferencePage.annotations.others= Others
+JavaEditorPreferencePage.annotations.showInText= Show in &text
+JavaEditorPreferencePage.annotations.showInOverviewRuler= Show in overview &ruler
+JavaEditorPreferencePage.annotations.color= C&olor:
+JavaEditorPreferencePage.multiLineComment=Multi-line comment
+JavaEditorPreferencePage.singleLineComment=Single-line comment
+JavaEditorPreferencePage.keywords=Keywords
+JavaEditorPreferencePage.strings=Strings
+JavaEditorPreferencePage.others=Others
+JavaEditorPreferencePage.javaCommentTaskTags=Task Tags
+JavaEditorPreferencePage.javaDocKeywords=Javadoc keywords
+JavaEditorPreferencePage.javaDocHtmlTags=Javadoc HTML tags
+JavaEditorPreferencePage.javaDocLinks=Javadoc links
+JavaEditorPreferencePage.javaDocOthers=Javadoc others
+JavaEditorPreferencePage.backgroundColor=Background color
+JavaEditorPreferencePage.systemDefault=S&ystem Default
+JavaEditorPreferencePage.custom=C&ustom:
+JavaEditorPreferencePage.foreground=Fo®round:
+JavaEditorPreferencePage.color=C&olor:
+JavaEditorPreferencePage.bold=&Bold
+JavaEditorPreferencePage.preview=Preview:
+JavaEditorPreferencePage.displayedTabWidth=Displayed &tab width:
+JavaEditorPreferencePage.insertSpaceForTabs=Ins&ert space for tabs (see Code Formatter preference page)
+JavaEditorPreferencePage.showOverviewRuler=Show overview &ruler
+JavaEditorPreferencePage.highlightMatchingBrackets=Highlight &matching brackets
+JavaEditorPreferencePage.highlightCurrentLine=Hi&ghlight current line
+JavaEditorPreferencePage.showPrintMargin=Sho&w print margin
+JavaEditorPreferencePage.printMarginColumn=Print margin col&umn:
+JavaEditorPreferencePage.insertSingleProposalsAutomatically=Insert single &proposals automatically
+JavaEditorPreferencePage.showOnlyProposalsVisibleInTheInvocationContext=Show only proposals &visible in the invocation context
+JavaEditorPreferencePage.presentProposalsInAlphabeticalOrder=Present proposals in a&lphabetical order
+JavaEditorPreferencePage.enableAutoActivation=&Enable auto activation
+JavaEditorPreferencePage.automaticallyAddImportInsteadOfQualifiedName=Automatically add import instead of &qualified name
+JavaEditorPreferencePage.completionInserts=Completion inser&ts
+JavaEditorPreferencePage.completionOverwrites=Completion over&writes
+JavaEditorPreferencePage.fillArgumentNamesOnMethodCompletion=&Fill argument names on method completion
+JavaEditorPreferencePage.guessArgumentNamesOnMethodCompletion=&Guess filled argument names
+JavaEditorPreferencePage.autoActivationDelay=Auto activation dela&y:
+JavaEditorPreferencePage.autoActivationTriggersForJava=Auto activation &triggers for Java:
+JavaEditorPreferencePage.autoActivationTriggersForJavaDoc=Auto activation triggers for &Javadoc:
+
+JavaEditorPreferencePage.codeAssist.colorOptions= Code assist colo&r options:
+JavaEditorPreferencePage.codeAssist.color= C&olor:
+JavaEditorPreferencePage.backgroundForCompletionProposals= Completion proposal background
+JavaEditorPreferencePage.foregroundForCompletionProposals= Completion proposal foreground
+JavaEditorPreferencePage.backgroundForMethodParameters= Method parameter background
+JavaEditorPreferencePage.foregroundForMethodParameters= Method parameter foreground
+JavaEditorPreferencePage.backgroundForCompletionReplacement= Completion overwrite background
+JavaEditorPreferencePage.foregroundForCompletionReplacement= Completion overwrite foreground
+
+JavaEditorPreferencePage.general=Appeara&nce
+JavaEditorPreferencePage.colors=Synta&x
+JavaEditorPreferencePage.codeAssist= &Code Assist
+JavaEditorPreferencePage.empty_input=Empty input
+JavaEditorPreferencePage.invalid_input=''{0}'' is not a valid input.
+JavaEditorPreferencePage.showLineNumbers=Show lin&e numbers
+JavaEditorPreferencePage.lineNumberForegroundColor=Line number foreground
+JavaEditorPreferencePage.matchingBracketsHighlightColor2=Matching brackets highlight
+JavaEditorPreferencePage.currentLineHighlighColor=Current line highlight
+JavaEditorPreferencePage.printMarginColor2=Print margin
+JavaEditorPreferencePage.findScopeColor2=Find scope
+JavaEditorPreferencePage.linkedPositionColor2=Linked position
+JavaEditorPreferencePage.linkColor2=Link
+JavaEditorPreferencePage.synchronizeOnCursor=Synchroni&ze outline selection on cursor move (editor must be reopened)
+JavaEditorPreferencePage.appearanceOptions=Appearance co&lor options:
+
+JavaEditorPreferencePage.typing.tabTitle= T&yping
+JavaEditorPreferencePage.typing.description= Select options for automatic text modifications
+JavaEditorPreferencePage.closeStrings= Close strin&gs
+JavaEditorPreferencePage.closeBrackets= Close &brackets and parenthesis
+JavaEditorPreferencePage.closeBraces= Cl&ose braces
+JavaEditorPreferencePage.closeJavaDocs= Close Java&docs and comments
+JavaEditorPreferencePage.wrapStrings= &Wrap Java strings
+JavaEditorPreferencePage.addJavaDocTags= Add Javadoc &tags
+JavaEditorPreferencePage.smartPaste= Pasting fo&r correct indentation
+
+JavaEditorPreferencePage.smartHomeEnd= S&mart cursor positioning at line start and end
+
+JavaEditorPreferencePage.hoverTab.title= Ho&vers
+
+JavaEditorPreferencePage.navigationTab.title= Nav&igation
+JavaEditorPreferencePage.navigation.browserLikeLinks= S&upport hyperlink style navigation for "Open Declaration"
+JavaEditorPreferencePage.navigation.browserLikeLinksKeyModifier= Hyperlink style navigation key &modifier:
+JavaEditorPreferencePage.navigation.modifierIsNotValid= Modifier ''{0}'' is not valid.
+JavaEditorPreferencePage.navigation.shiftIsDisabled= The modifier 'Shift' is not allowed because 'Shift' + click sets a new selection.
+
+JavaEditorPreferencePage.navigation.delimiter= +
+JavaEditorPreferencePage.navigation.insertDelimiterAndModifierAndDelimiter= \ + {0} +
+JavaEditorPreferencePage.navigation.insertModifierAndDelimiter= \ {0} +
+JavaEditorPreferencePage.navigation.insertDelimiterAndModifier= \ + {0}
+
+JavaEditorHoverConfigurationBlock.hoverPreferences= &Hover key modifier preferences:
+JavaEditorHoverConfigurationBlock.enabled= &Enabled
+JavaEditorHoverConfigurationBlock.keyModifier= Key &Modifier:
+JavaEditorHoverConfigurationBlock.description= Description:
+JavaEditorHoverConfigurationBlock.modifierIsNotValid= Modifier ''{0}'' is not valid.
+JavaEditorHoverConfigurationBlock.modifierIsNotValidForHover= Modifier ''{0}'' for ''{1}'' hover is not valid.
+JavaEditorHoverConfigurationBlock.duplicateModifier= ''{0}'' hover uses the same modifier as ''{1}'' hover.
+
+JavaEditorHoverConfigurationBlock.delimiter= +
+JavaEditorHoverConfigurationBlock.insertDelimiterAndModifierAndDelimiter= \ + {0} +
+JavaEditorHoverConfigurationBlock.insertModifierAndDelimiter= \ {0} +
+JavaEditorHoverConfigurationBlock.insertDelimiterAndModifier= \ + {0}
+
+JavaElementInfoPage.binary=binary
+JavaElementInfoPage.classpath_entry_kind=Classpath entry kind:
+JavaElementInfoPage.library=library
+JavaElementInfoPage.nameLabel=Name:
+JavaElementInfoPage.not_present=not present
+JavaElementInfoPage.package=Package:
+JavaElementInfoPage.package_contents=Package contents:
+JavaElementInfoPage.project=project
+JavaElementInfoPage.resource_path=Resource path:
+JavaElementInfoPage.source=source
+JavaElementInfoPage.variable=variable
+JavaElementInfoPage.variable_path=Variable path:
+JavaElementInfoPage.location=Location:
+
+JavadocConfigurationPropertyPage.IsPackageFragmentRoot.description=Specify the location (URL) of the documentation generated by Javadoc. The Javadoc location will contain a file called 'package-list'. For example: \'http://www.sample-url.org/doc/\'
+JavadocConfigurationPropertyPage.IsIncorrectElement.description=Javadoc location can only be attached to Java projects or JAR files in Java projects
+JavadocConfigurationPropertyPage.IsJavaProject.description=Specify the location (URL) of the project\'s Javadoc documentation. This location is used by the Javadoc export wizard as default value and by the \'Open External Javadoc\' action. For example: \'file://c:/myworkspace/myproject/doc/\'.
+
+JavadocConfigurationBlock.location.label=Javadoc &location:
+JavadocConfigurationBlock.location.button=Bro&wse...
+
+JavadocConfigurationBlock.error.notafolder=Location does not exist.
+JavadocConfigurationBlock.warning.packagelistnotfound=Location does not contain file 'package-list'.
+
+JavadocConfigurationBlock.javadocLocationDialog.label=Javadoc Location Selection
+JavadocConfigurationBlock.javadocLocationDialog.message=&Select Javadoc location:
+
+JavadocConfigurationBlock.MalformedURL.error=Invalid URL
+
+JavadocConfigurationBlock.ValidateButton.label=&Validate...
+JavadocConfigurationBlock.InvalidLocation.message= Location is invalid. Location contains neither the file \'package-list\' nor \'index.html'.
+JavadocConfigurationBlock.ValidLocation.message= Location is valid. Files \'package-list\' and \'index.html\' found. Click OK to open in browser.
+JavadocConfigurationBlock.UnableToValidateLocation.message=Unable to validate location
+JavadocConfigurationBlock.MessageDialog.title=Validating Javadoc Location
+
+JavadocPreferencePage.description=Specify the location of the Javadoc command to be used by the Javadoc export wizard. Location must be an absolute path.
+JavadocPreferencePage.command.label=&Javadoc command:
+JavadocPreferencePage.command.button=Bro&wse...
+
+JavadocPreferencePage.error.notexists=Javadoc command does not exist
+
+JavadocPreferencePage.browsedialog.title=Javadoc Command Selection
+
+MembersOrderPreferencePage.button.up=U&p
+MembersOrderPreferencePage.button.down=Do&wn
+MembersOrderPreferencePage.label.description=&Choose the order in which members will be displayed. The order is also used by the 'Sort Members' action.
+
+SourceAttachmentPropertyPage.error.title=Error Attaching Source
+SourceAttachmentPropertyPage.error.message=An error occurred while associating the source
+
+SourceAttachmentPropertyPage.noarchive.message=Source can only be attached to JAR files in Java projects.
+SourceAttachmentPropertyPage.containerentry.message=JAR belongs to the container ''{0}''.\nTo configure the source attachment, go directly to the corresponding configuration page (For example for JREs go to ''Installed JREs'' page in the preferences).
+
+AppearancePreferencePage.description= Appearance of Java elements in viewers:
+AppearancePreferencePage.methodreturntype.label= Show &method return types
+AppearancePreferencePage.overrideindicator.label= Show &override indicators in outline and hierarchy
+AppearancePreferencePage.pkgNamePatternEnable.label= &Compress all package name segments, except the final segment
+AppearancePreferencePage.pkgNamePattern.label= Com&pression pattern (e.g. given package name 'org.eclipse.jdt' pattern '.' will compress it to '..jdt', '0' to 'jdt', '1~.' to 'o~.e~.jdt'):
+AppearancePreferencePage.showMembersInPackagesView=S&how members in Package Explorer
+AppearancePreferencePage.stackViewsVerticallyInTheJavaBrowsingPerspective=&Stack views vertically in the Java Browsing perspective
+AppearancePreferencePage.preferenceOnlyEffectiveForNewPerspectives=Note: This preference will only take effect on new perspectives
+AppearancePreferencePage.packageNameCompressionPattern.error.isEmpty=Enter a package name compression pattern
+AppearancePreferencePage.foldEmptyPackages= &Fold empty packages in hierarchical Package Explorer layout
+
+CodeFormatterPreferencePage.title=Code Formatter
+CodeFormatterPreferencePage.description=Options for the Java Code Formatter:
+
+CodeFormatterPreferencePage.empty_input=Empty input
+CodeFormatterPreferencePage.invalid_input=''{0}'' is not a valid input.
+
+CodeFormatterPreferencePage.newline_opening_braces.label=I&nsert a new line before an opening brace
+CodeFormatterPreferencePage.newline_control_statement.label=Insert new &lines in control statements
+CodeFormatterPreferencePage.newline_clear_lines=Clear all &blank lines
+CodeFormatterPreferencePage.newline_else_if.label=&Insert new line between 'else if'
+CodeFormatterPreferencePage.newline_empty_block.label=In&sert a new line inside an empty block
+CodeFormatterPreferencePage.split_line.label=Ma&ximum line length:
+CodeFormatterPreferencePage.style_compact_assignement.label=&Compact assignment
+CodeFormatterPreferencePage.style_space_castexpression.label=Insert sp&ace after a cast
+CodeFormatterPreferencePage.tab_char.label=Insert &tabs for indentation, not spaces
+CodeFormatterPreferencePage.tab_size.label=&Number of spaces representing an indentation level:
+
+CodeFormatterPreferencePage.tab.newline.tabtitle=Ne&w Lines
+CodeFormatterPreferencePage.tab.linesplit.tabtitle=Line S&plitting
+CodeFormatterPreferencePage.tab.style.tabtitle=St&yle
+
+TodoTaskPreferencePage.title=Task Tags
+
+TodoTaskPropertyPage.useworkspacesettings.label=Use &workspace settings
+TodoTaskPropertyPage.useworkspacesettings.change=&Configure Workspace Settings...
+TodoTaskPropertyPage.useprojectsettings.label=Use pr&oject settings
+
+TodoTaskConfigurationBlock.markers.tasks.high.priority=High
+TodoTaskConfigurationBlock.markers.tasks.normal.priority=Normal
+TodoTaskConfigurationBlock.markers.tasks.low.priority=Low
+TodoTaskConfigurationBlock.markers.tasks.label=&Strings indicating tasks in Java comments:
+TodoTaskConfigurationBlock.markers.tasks.add.button=Ne&w...
+TodoTaskConfigurationBlock.markers.tasks.remove.button=Remo&ve
+TodoTaskConfigurationBlock.markers.tasks.edit.button=Edi&t...
+TodoTaskConfigurationBlock.markers.tasks.name.column=Tag
+TodoTaskConfigurationBlock.markers.tasks.priority.column=Priority
+
+TodoTaskConfigurationBlock.needsbuild.title=Task Tags Settings Changed
+TodoTaskConfigurationBlock.needsfullbuild.message=The task tags settings have changed. A full rebuild is required to make changes effective. Do the full build now?
+TodoTaskConfigurationBlock.needsprojectbuild.message=The task tags settings have changed. A rebuild of the project is required to make changes effective. Do the project build now?
+
+TodoTaskInputDialog.new.title=New Task Tag
+TodoTaskInputDialog.edit.title=Edit Task Tag
+TodoTaskInputDialog.name.label=T&ag:
+TodoTaskInputDialog.priority.label=&Priority:
+TodoTaskInputDialog.priority.high=High
+TodoTaskInputDialog.priority.normal=Normal
+TodoTaskInputDialog.priority.low=Low
+TodoTaskInputDialog.error.enterName=Enter task tag name.
+TodoTaskInputDialog.error.comma=Name cannot contain a comma.
+TodoTaskInputDialog.error.entryExists=Entry with the same name already exists.
+TodoTaskInputDialog.error.noSpace=Name can not start or end with a whitespace.
+
+CompilerPreferencePage.title=Compiler
+CompilerPreferencePage.description=Options for the Java compiler:\nNote that a full rebuild is required to make changes effective.
+
+CompilerPropertyPage.useworkspacesettings.label=Use &workspace settings
+CompilerPropertyPage.useworkspacesettings.change=&Configure Workspace Settings...
+CompilerPropertyPage.useprojectsettings.label=Use pr&oject settings
+
+CompilerConfigurationBlock.style.tabtitle=&Style
+CompilerConfigurationBlock.problems.tabtitle=&Problems
+CompilerConfigurationBlock.compliance.tabtitle=&Compliance and Classfiles
+CompilerConfigurationBlock.others.tabtitle=&Build Path
+
+CompilerConfigurationBlock.style.description=Select the severity level for the following problems:
+CompilerConfigurationBlock.problems.description=Select the severity level for the following problems:
+CompilerConfigurationBlock.build_warnings.description=Select the severity level for the following build path problems:
+
+CompilerConfigurationBlock.variable_attr.label=Add &variable attributes to generated class files (used by the debugger)
+CompilerConfigurationBlock.line_number_attr.label=Add &line number attributes to generated class files (used by the debugger)
+CompilerConfigurationBlock.source_file_attr.label=Add source &file name to generated class file (used by the debugger)
+CompilerConfigurationBlock.codegen_unused_local.label=Pr&eserve unused local variables (i.e. never read)
+
+CompilerConfigurationBlock.compiler_compliance.label=C&ompiler compliance level:
+CompilerConfigurationBlock.default_settings.label=&Use default compliance settings
+CompilerConfigurationBlock.source_compatibility.label=Source co&mpatibility:
+CompilerConfigurationBlock.codegen_targetplatform.label=Ge&nerated .class files compatibility:
+CompilerConfigurationBlock.pb_assert_as_identifier.label=&Report 'assert' as identifier:
+
+CompilerConfigurationBlock.compliance.group.label=JDK Compliance
+CompilerConfigurationBlock.classfiles.group.label=Classfile Generation
+
+CompilerConfigurationBlock.pb_unreachable_code.label=&Unreachable code:
+CompilerConfigurationBlock.pb_invalid_import.label=Unresol&vable import statements:
+CompilerConfigurationBlock.pb_overriding_pkg_dflt.label=&Methods overridden but not package visible:
+CompilerConfigurationBlock.pb_method_naming.label=Me&thods with a constructor name:
+CompilerConfigurationBlock.pb_no_effect_assignment.label=Assignment has no &effect (e.g. 'x = x'):
+CompilerConfigurationBlock.pb_incompatible_interface_method.label=Conflict of interface method &with protected 'Object' method:
+
+
+CompilerConfigurationBlock.pb_hidden_catchblock.label=&Hidden catch blocks:
+CompilerConfigurationBlock.pb_static_access_receiver.label=Non-stat&ic access to static member
+CompilerConfigurationBlock.pb_unused_imports.label=Unus&ed imports:
+CompilerConfigurationBlock.pb_unused_local.label=Unused &local variables (i.e. never read):
+CompilerConfigurationBlock.pb_unused_parameter.label=U&nused parameters (i.e. never read):
+CompilerConfigurationBlock.pb_unused_private.label=Unused private &types, methods or fields:
+CompilerConfigurationBlock.pb_non_externalized_strings.label=Usage of non-e&xternalized strings:
+CompilerConfigurationBlock.pb_deprecation.label=Usa&ge of deprecated API:
+CompilerConfigurationBlock.pb_deprecation_in_deprecation.label=Signal use &of deprecated API inside deprecated code.
+
+CompilerConfigurationBlock.pb_synth_access_emul.label=Access to a &non-accessible member of an enclosing type:
+CompilerConfigurationBlock.pb_char_array_in_concat.label=&Using a char array in string concatenation:
+CompilerConfigurationBlock.pb_incomplete_build_path.label=&Incomplete build path:
+CompilerConfigurationBlock.pb_build_path_cycles.label=Circular d&ependencies:
+CompilerConfigurationBlock.pb_duplicate_resources.label=D&uplicated resources:
+CompilerConfigurationBlock.pb_max_per_unit.label=Ma&ximum number of problems reported per compilation unit:
+
+
+CompilerConfigurationBlock.resource_filter.description=Enter resources and resource types that should not be copied to the output folder during a build. List is comma separated (e.g. '*.doc, plugin.xml, scripts/')
+CompilerConfigurationBlock.resource_filter.label=Filtered &Resources:
+CompilerConfigurationBlock.build_invalid_classpath.label=Ab&ort building on build path errors
+CompilerConfigurationBlock.build_clean_outputfolder.label=Scrub output folders o&n full build
+CompilerConfigurationBlock.enable_exclusion_patterns.label=Enable using e&xclusion patterns in source folders
+CompilerConfigurationBlock.enable_multiple_outputlocations.label=Enable using &multiple output locations for source folders
+
+CompilerConfigurationBlock.error=Error
+CompilerConfigurationBlock.warning=Warning
+CompilerConfigurationBlock.ignore=Ignore
+
+CompilerConfigurationBlock.version11=1.1
+CompilerConfigurationBlock.version12=1.2
+CompilerConfigurationBlock.version13=1.3
+CompilerConfigurationBlock.version14=1.4
+
+CompilerConfigurationBlock.needsbuild.title=Compiler Settings Changed
+CompilerConfigurationBlock.needsfullbuild.message=The compiler settings have changed. A full rebuild is required to make changes effective. Do the full build now?
+CompilerConfigurationBlock.needsprojectbuild.message=The compiler settings have changed. A rebuild of the project is required to make changes effective. Do the project build now?
+
+CompilerConfigurationBlock.cpl13src14.error=In 1.3 compliance level, source compatibility can not be 1.4
+CompilerConfigurationBlock.cpl13trg14.error=In 1.3 compliance level, the classfile compatibility can not be 1.4
+CompilerConfigurationBlock.src14asrterr.error=When source compatibility is 1.4, 'assert' cannot be an identifier.
+CompilerConfigurationBlock.src14tgt14.error=When source compatibility is 1.4, the classfile compatibility has to be 1.4.
+
+CompilerConfigurationBlock.empty_input=Number of problems can not be empty.
+CompilerConfigurationBlock.invalid_input={0} is not a valid number of problems.
+
+CompilerConfigurationBlock.filter.invalidsegment.error=Filter is invalid: {0}
+
+OptionsConfigurationBlock.builderror.title=Preference Changes
+OptionsConfigurationBlock.builderror.message=Problem while building. Check log for details.
+
+OptionsConfigurationBlock.buildall.taskname=Build all...
+OptionsConfigurationBlock.buildproject.taskname=Build project ''{0}''...
+
+CodeGenerationPreferencePage.title=&Code Generation
+CodeGenerationPreferencePage.description=Options for Code Generation:
+
+CodeGenerationPreferencePage.tab.names.tabtitle=&Names
+CodeGenerationPreferencePage.tab.templates.tabtitle=&Code and Comments
+
+NameConventionConfigurationBlock.field.label=Fields
+NameConventionConfigurationBlock.static.label=Static Fields
+NameConventionConfigurationBlock.arg.label=Parameters
+NameConventionConfigurationBlock.local.label=Local Variables
+
+NameConventionConfigurationBlock.dialog.prefix=P&refix list:
+NameConventionConfigurationBlock.dialog.suffix=S&uffix list:
+
+NameConventionConfigurationBlock.error.emptyprefix=Prefix strings can not contain an empty entry.
+NameConventionConfigurationBlock.error.emptysuffix=Suffix strings can not contain an empty entry.
+NameConventionConfigurationBlock.error.invalidprefix={0} is not a valid prefix.
+NameConventionConfigurationBlock.error.invalidsuffix={0} is not a valid suffix.
+
+NameConventionConfigurationBlock.list.label=C&onventions for variable names:
+NameConventionConfigurationBlock.list.edit.button=&Edit...
+NameConventionConfigurationBlock.list.name.column=Variable type
+NameConventionConfigurationBlock.list.prefix.column=Prefix list
+NameConventionConfigurationBlock.list.suffix.column=Suffix list
+
+NameConventionConfigurationBlock.field.dialog.title=Field Name Conventions
+NameConventionConfigurationBlock.field.dialog.message=Specify prefix and suffix to be used for fields (comma separated):
+
+NameConventionConfigurationBlock.static.dialog.title=Static Field Name Conventions
+NameConventionConfigurationBlock.static.dialog.message=Specify prefix and suffix to be used for static fields (comma separated):
+
+NameConventionConfigurationBlock.arg.dialog.title=Parameter Name Conventions
+NameConventionConfigurationBlock.arg.dialog.message=Specify prefix and suffix to be used for parameters (comma separated):
+
+NameConventionConfigurationBlock.local.dialog.title=Local Variable Name Conventions
+NameConventionConfigurationBlock.local.dialog.message=Specify prefix and suffix to be used for local variables (comma separated):
+
+MembersOrderPreferencePage.fields.label=Fields
+MembersOrderPreferencePage.constructors.label=Constructors
+MembersOrderPreferencePage.methods.label=Methods
+MembersOrderPreferencePage.staticfields.label=Static Fields
+MembersOrderPreferencePage.staticmethods.label=Static Methods
+MembersOrderPreferencePage.initialisers.label=Initializers
+MembersOrderPreferencePage.staticinitialisers.label=Static Initializers
+MembersOrderPreferencePage.types.label=Types
+
+CodeTemplateBlock.templates.comment.node=Comments
+CodeTemplateBlock.templates.code.node=Code
+
+CodeTemplateBlock.catchblock.label=Catch block body
+CodeTemplateBlock.methodstub.label=Method body
+CodeTemplateBlock.constructorstub.label=Constructor body
+CodeTemplateBlock.newtype.label=New Java files
+CodeTemplateBlock.typecomment.label=Types
+CodeTemplateBlock.methodcomment.label=Methods
+CodeTemplateBlock.overridecomment.label=Overriding methods
+CodeTemplateBlock.constructorcomment.label=Constructors
+
+CodeTemplateBlock.templates.edit.button=&Edit...
+CodeTemplateBlock.templates.import.button=&Import...
+CodeTemplateBlock.templates.export.button=E&xport...
+CodeTemplateBlock.templates.exportall.button=Ex&port All...
+
+CodeTemplateBlock.createcomment.label=A&utomatically add comments for new methods and types
+CodeTemplateBlock.createcomment.description=(does not apply to comments contained in the code patterns)
+CodeTemplateBlock.templates.label=C&onfigure generated code and comments:
+CodeTemplateBlock.preview=Pa&ttern:
+
+CodeTemplateBlock.import.title=Importing Templates
+CodeTemplateBlock.import.extension=*.xml
+
+CodeTemplateBlock.export.title=Exporting {0} Code Template(s)
+CodeTemplateBlock.export.filename=codetemplates.xml
+CodeTemplateBlock.export.extension=*.xml
+
+CodeTemplateBlock.export.exists.title=Exporting Code Templates
+CodeTemplateBlock.export.exists.message={0} already exists.\nDo you want to replace it?
+
+CodeTemplateBlock.error.read.title= Code Templates
+CodeTemplateBlock.error.read.message= Failed to read templates.
+
+CodeTemplateBlock.error.parse.message= Failed to parse templates:\n{0}
+
+CodeTemplateBlock.error.write.title=Code Templates
+CodeTemplateBlock.error.write.message=Failed to write templates.
+
+CodeTemplateBlock.export.error.title= Exporting Templates
+CodeTemplateBlock.export.error.hidden= Export failed.\n{0} is a hidden file.
+CodeTemplateBlock.export.error.canNotWrite= Export failed.\n{0} can not be modified.
+CodeTemplateBlock.export.error.fileNotFound= Export failed:\n{0}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaColorManager.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaColorManager.java
index a7a462b..3c57e1d 100644
--- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaColorManager.java
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaColorManager.java
@@ -20,20 +20,47 @@ import org.eclipse.swt.widgets.Display;
* Java color manager.
*/
public class JavaColorManager implements IColorManager, IColorManagerExtension {
-
protected Map fKeyTable= new HashMap(10);
protected Map fDisplayTable= new HashMap(2);
-
-
+
+ /**
+ * Flag which tells if the colors are automatically disposed when
+ * the current display gets disposed.
+ */
+ private boolean fAutoDisposeOnDisplayDispose;
+
+
+ /**
+ * Creates a new Java color manager which automatically
+ * disposes the allocated colors when the current display
+ * gets disposed.
+ */
public JavaColorManager() {
+ this(true);
+ }
+
+ /**
+ * Creates a new Java color manager.
+ *
+ * @param autoDisposeOnDisplayDispose if true
the color manager
+ * automatically disposes all managed colors when the current display gets disposed
+ * and all calls to {@link org.eclipse.jface.text.source.ISharedTextColors#dispose()} are ignored.
+ *
+ * @since 2.1
+ */
+ public JavaColorManager(boolean autoDisposeOnDisplayDispose) {
+ fAutoDisposeOnDisplayDispose= autoDisposeOnDisplayDispose;
}
- private void dispose(Display display) {
+ public void dispose(Display display) {
Map colorTable= (Map) fDisplayTable.get(display);
if (colorTable != null) {
Iterator e= colorTable.values().iterator();
- while (e.hasNext())
- ((Color) e.next()).dispose();
+ while (e.hasNext()) {
+ Color color= (Color)e.next();
+ if (color != null && !color.isDisposed())
+ color.dispose();
+ }
}
}
@@ -50,11 +77,13 @@ public class JavaColorManager implements IColorManager, IColorManagerExtension {
if (colorTable == null) {
colorTable= new HashMap(10);
fDisplayTable.put(display, colorTable);
- display.disposeExec(new Runnable() {
- public void run() {
- dispose(display);
- }
- });
+ if (fAutoDisposeOnDisplayDispose) {
+ display.disposeExec(new Runnable() {
+ public void run() {
+ dispose(display);
+ }
+ });
+ }
}
Color color= (Color) colorTable.get(rgb);
@@ -70,7 +99,8 @@ public class JavaColorManager implements IColorManager, IColorManagerExtension {
* @see IColorManager#dispose
*/
public void dispose() {
- // nothing to dispose
+ if (!fAutoDisposeOnDisplayDispose)
+ dispose(Display.getCurrent());
}
/*
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaElementProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaElementProvider.java
new file mode 100644
index 0000000..ed4d33a
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaElementProvider.java
@@ -0,0 +1,90 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.ui.text;
+
+
+import net.sourceforge.phpdt.core.IJavaElement;
+import net.sourceforge.phpdt.core.JavaModelException;
+import net.sourceforge.phpdt.internal.ui.actions.SelectionConverter;
+import net.sourceforge.phpeclipse.phpeditor.PHPEditor;
+
+import org.eclipse.jface.text.IRegion;
+import org.eclipse.jface.text.ITextViewer;
+import org.eclipse.jface.text.Region;
+import org.eclipse.jface.text.information.IInformationProvider;
+import org.eclipse.jface.text.information.IInformationProviderExtension;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.ui.IEditorPart;
+
+
+
+/**
+ * Provides a Java element to be displayed in by an information presenter.
+ */
+public class JavaElementProvider implements IInformationProvider, IInformationProviderExtension {
+
+ private PHPEditor fEditor;
+ private boolean fUseCodeResolve;
+
+ public JavaElementProvider(IEditorPart editor) {
+ fUseCodeResolve= false;
+ if (editor instanceof PHPEditor)
+ fEditor= (PHPEditor)editor;
+ }
+
+ public JavaElementProvider(IEditorPart editor, boolean useCodeResolve) {
+ this(editor);
+ fUseCodeResolve= useCodeResolve;
+ }
+
+ /*
+ * @see IInformationProvider#getSubject(ITextViewer, int)
+ */
+ public IRegion getSubject(ITextViewer textViewer, int offset) {
+ if (textViewer != null && fEditor != null) {
+ IRegion region= JavaWordFinder.findWord(textViewer.getDocument(), offset);
+ if (region != null)
+ return region;
+ else
+ return new Region(offset, 0);
+ }
+ return null;
+ }
+
+ /*
+ * @see IInformationProvider#getInformation(ITextViewer, IRegion)
+ */
+ public String getInformation(ITextViewer textViewer, IRegion subject) {
+ return getInformation2(textViewer, subject).toString();
+ }
+
+ /*
+ * @see IInformationProviderExtension#getElement(ITextViewer, IRegion)
+ */
+ public Object getInformation2(ITextViewer textViewer, IRegion subject) {
+ if (fEditor == null)
+ return null;
+
+ try {
+ if (fUseCodeResolve) {
+ IStructuredSelection sel= SelectionConverter.getStructuredSelection(fEditor);
+ if (!sel.isEmpty())
+ return sel.getFirstElement();
+ }
+ IJavaElement element= SelectionConverter.getElementAtOffset(fEditor);
+ if (element != null)
+ return element;
+ return SelectionConverter.getInput(fEditor);
+ } catch (JavaModelException e) {
+ return null;
+ }
+ }
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaOutlineInformationControl.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaOutlineInformationControl.java
new file mode 100644
index 0000000..68db9b5
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaOutlineInformationControl.java
@@ -0,0 +1,608 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.ui.text;
+
+import net.sourceforge.phpdt.core.ICompilationUnit;
+import net.sourceforge.phpdt.core.IJavaElement;
+import net.sourceforge.phpdt.core.IParent;
+import net.sourceforge.phpdt.core.JavaModelException;
+import net.sourceforge.phpdt.internal.ui.actions.OpenActionUtil;
+import net.sourceforge.phpdt.internal.ui.util.StringMatcher;
+import net.sourceforge.phpdt.internal.ui.viewsupport.AppearanceAwareLabelProvider;
+import net.sourceforge.phpdt.internal.ui.viewsupport.DecoratingJavaLabelProvider;
+import net.sourceforge.phpdt.internal.ui.viewsupport.JavaElementLabels;
+import net.sourceforge.phpdt.ui.JavaElementSorter;
+import net.sourceforge.phpdt.ui.StandardJavaElementContentProvider;
+import net.sourceforge.phpeclipse.PHPeclipsePlugin;
+
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.jface.text.IInformationControl;
+import org.eclipse.jface.text.IInformationControlExtension;
+import org.eclipse.jface.text.IInformationControlExtension2;
+import org.eclipse.jface.viewers.AbstractTreeViewer;
+import org.eclipse.jface.viewers.IBaseLabelProvider;
+import org.eclipse.jface.viewers.ILabelProvider;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.viewers.StructuredSelection;
+import org.eclipse.jface.viewers.StructuredViewer;
+import org.eclipse.jface.viewers.TreeViewer;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.jface.viewers.ViewerFilter;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.DisposeListener;
+import org.eclipse.swt.events.FocusListener;
+import org.eclipse.swt.events.KeyEvent;
+import org.eclipse.swt.events.KeyListener;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.events.SelectionListener;
+import org.eclipse.swt.graphics.Color;
+import org.eclipse.swt.graphics.FontMetrics;
+import org.eclipse.swt.graphics.GC;
+import org.eclipse.swt.graphics.Point;
+import org.eclipse.swt.graphics.Rectangle;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Layout;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.swt.widgets.Text;
+import org.eclipse.swt.widgets.Tree;
+import org.eclipse.swt.widgets.TreeItem;
+
+/**
+ * @author dmegert
+ *
+ * To change this generated comment edit the template variable "typecomment":
+ * Window>Preferences>Java>Templates.
+ * To enable and disable the creation of type comments go to
+ * Window>Preferences>Java>Code Generation.
+ */
+public class JavaOutlineInformationControl implements IInformationControl, IInformationControlExtension, IInformationControlExtension2 {
+
+
+ /**
+ * The NamePatternFilter selects the elements which
+ * match the given string patterns.
+ * true
if participant should be notified
+ */
+ public void notifyParticipants(boolean notify) {
+ fNotify = notify;
+ }
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/AbstractJavaEditorTextHover.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/AbstractJavaEditorTextHover.java
new file mode 100644
index 0000000..565a8ab
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/AbstractJavaEditorTextHover.java
@@ -0,0 +1,105 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+
+package net.sourceforge.phpdt.internal.ui.text.java.hover;
+
+import net.sourceforge.phpdt.core.IJavaElement;
+import net.sourceforge.phpdt.internal.ui.text.JavaWordFinder;
+import net.sourceforge.phpdt.ui.text.java.hover.IJavaEditorTextHover;
+
+import org.eclipse.jface.text.IRegion;
+import org.eclipse.jface.text.ITextViewer;
+import org.eclipse.ui.IEditorPart;
+
+/**
+ * Abstract class for providing hover information for Java elements.
+ *
+ * @since 2.1
+ */
+public abstract class AbstractJavaEditorTextHover implements IJavaEditorTextHover {
+
+
+ private IEditorPart fEditor;
+
+
+ /*
+ * @see IJavaEditorTextHover#setEditor(IEditorPart)
+ */
+ public void setEditor(IEditorPart editor) {
+ fEditor= editor;
+ }
+
+ protected IEditorPart getEditor() {
+ return fEditor;
+ }
+
+// protected ICodeAssist getCodeAssist() {
+// if (fEditor != null) {
+// IEditorInput input= fEditor.getEditorInput();
+// if (input instanceof IClassFileEditorInput) {
+// IClassFileEditorInput cfeInput= (IClassFileEditorInput) input;
+// return cfeInput.getClassFile();
+// }
+//
+// IWorkingCopyManager manager= PHPeclipsePlugin.getDefault().getWorkingCopyManager();
+// return manager.getWorkingCopy(input);
+// }
+//
+// return null;
+// }
+
+ /*
+ * @see ITextHover#getHoverRegion(ITextViewer, int)
+ */
+ public IRegion getHoverRegion(ITextViewer textViewer, int offset) {
+ return JavaWordFinder.findWord(textViewer.getDocument(), offset);
+ }
+
+ /*
+ * @see ITextHover#getHoverInfo(ITextViewer, IRegion)
+ */
+ public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
+
+// ICodeAssist resolve= getCodeAssist();
+// if (resolve != null) {
+// try {
+// IJavaElement[] result= null;
+//
+// synchronized (resolve) {
+// result= resolve.codeSelect(hoverRegion.getOffset(), hoverRegion.getLength());
+// }
+//
+// if (result == null)
+// return null;
+//
+// int nResults= result.length;
+// if (nResults == 0)
+// return null;
+//
+// return getHoverInfo(result);
+//
+// } catch (JavaModelException x) {
+// PHPeclipsePlugin.log(x.getStatus());
+// }
+// }
+ return null;
+ }
+
+ /**
+ * Provides hover information for the given Java elements.
+ *
+ * @return the hover information string
+ * @since 2.1
+ */
+ protected String getHoverInfo(IJavaElement[] javaElements) {
+ return null;
+ }
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/BestMatchHover.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/BestMatchHover.java
new file mode 100644
index 0000000..88cd055
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/BestMatchHover.java
@@ -0,0 +1,142 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.ui.text.java.hover;
+
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+
+import net.sourceforge.phpdt.ui.PreferenceConstants;
+import net.sourceforge.phpdt.ui.text.java.hover.IJavaEditorTextHover;
+import net.sourceforge.phpeclipse.PHPeclipsePlugin;
+
+import org.eclipse.jface.text.IRegion;
+import org.eclipse.jface.text.ITextHover;
+import org.eclipse.jface.text.ITextViewer;
+import org.eclipse.ui.IEditorPart;
+
+/**
+ * Caution: this implementation is a layer breaker and contains some "shortcuts"
+ */
+public class BestMatchHover extends AbstractJavaEditorTextHover {
+
+ private static class JavaEditorTextHoverDescriptorComparator implements Comparator {
+
+ /*
+ * @see Comparator#compare(Object, Object)
+ */
+ public int compare(Object object0, Object object1) {
+
+ JavaEditorTextHoverDescriptor element0= (JavaEditorTextHoverDescriptor)object0;
+ JavaEditorTextHoverDescriptor element1= (JavaEditorTextHoverDescriptor)object1;
+
+ String id0= element0.getId();
+ String id1= element1.getId();
+
+ if (id0 != null && id0.equals(id1))
+ return 0;
+
+ if (id0 != null && JavaProblemHover.isJavaProblemHover(id0))
+ return -1;
+
+ if (id1 != null && JavaProblemHover.isJavaProblemHover(id1))
+ return +1;
+
+
+ // now compare non-problem hovers
+ if (element0.dependsOn(element1))
+ return -1;
+
+ if (element1.dependsOn(element0))
+ return +1;
+
+ return 0;
+ }
+ }
+
+ protected String fCurrentPerspectiveId;
+ protected List fTextHoverSpecifications;
+ protected List fInstantiatedTextHovers;
+
+
+ public BestMatchHover() {
+ installTextHovers();
+ }
+
+ public BestMatchHover(IEditorPart editor) {
+ this();
+ setEditor(editor);
+ }
+
+ /**
+ * Installs all text hovers.
+ */
+ private void installTextHovers() {
+
+ // initialize lists - indicates that the initialization happened
+ fTextHoverSpecifications= new ArrayList(2);
+ fInstantiatedTextHovers= new ArrayList(2);
+
+ // populate list
+ JavaEditorTextHoverDescriptor[] hoverDescs= PHPeclipsePlugin.getDefault().getJavaEditorTextHoverDescriptors();
+ for (int i= 0; i < hoverDescs.length; i++) {
+ // ensure that we don't add ourselves to the list
+ if (!PreferenceConstants.ID_BESTMATCH_HOVER.equals(hoverDescs[i].getId()))
+ fTextHoverSpecifications.add(hoverDescs[i]);
+ }
+ Collections.sort(fTextHoverSpecifications, new JavaEditorTextHoverDescriptorComparator());
+ }
+
+ private void checkTextHovers() {
+ if (fTextHoverSpecifications.size() == 0)
+ return;
+
+ for (Iterator iterator= new ArrayList(fTextHoverSpecifications).iterator(); iterator.hasNext(); ) {
+ JavaEditorTextHoverDescriptor spec= (JavaEditorTextHoverDescriptor) iterator.next();
+
+ IJavaEditorTextHover hover= spec.createTextHover();
+ if (hover != null) {
+ hover.setEditor(getEditor());
+ addTextHover(hover);
+ fTextHoverSpecifications.remove(spec);
+ }
+ }
+ }
+
+ protected void addTextHover(ITextHover hover) {
+ if (!fInstantiatedTextHovers.contains(hover))
+ fInstantiatedTextHovers.add(hover);
+ }
+
+ /*
+ * @see ITextHover#getHoverInfo(ITextViewer, IRegion)
+ */
+ public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
+
+ checkTextHovers();
+
+ if (fInstantiatedTextHovers == null)
+ return null;
+
+ for (Iterator iterator= fInstantiatedTextHovers.iterator(); iterator.hasNext(); ) {
+ ITextHover hover= (ITextHover) iterator.next();
+
+ String s= hover.getHoverInfo(textViewer, hoverRegion);
+ if (s != null && s.trim().length() > 0)
+ return s;
+ }
+
+ return null;
+ }
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaEditorTextHoverDescriptor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaEditorTextHoverDescriptor.java
new file mode 100644
index 0000000..7f8148f
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaEditorTextHoverDescriptor.java
@@ -0,0 +1,312 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+
+package net.sourceforge.phpdt.internal.ui.text.java.hover;
+
+import java.text.Collator;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.StringTokenizer;
+
+import net.sourceforge.phpdt.ui.PreferenceConstants;
+import net.sourceforge.phpdt.ui.text.java.hover.IJavaEditorTextHover;
+import net.sourceforge.phpeclipse.PHPeclipsePlugin;
+import net.sourceforge.phpeclipse.phpeditor.EditorUtility;
+
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IConfigurationElement;
+import org.eclipse.core.runtime.IPluginDescriptor;
+import org.eclipse.core.runtime.IPluginPrerequisite;
+import org.eclipse.core.runtime.IPluginRegistry;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Platform;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.jface.text.Assert;
+import org.eclipse.swt.SWT;
+
+/**
+ * Describes a Java editor text hover.
+ *
+ * @since 2.1
+ */
+public class JavaEditorTextHoverDescriptor implements Comparable {
+
+ private static final String JAVA_EDITOR_TEXT_HOVER_EXTENSION_POINT= "net.sourceforge.phpeclipse.phpEditorTextHovers"; //$NON-NLS-1$
+ private static final String HOVER_TAG= "hover"; //$NON-NLS-1$
+ private static final String ID_ATTRIBUTE= "id"; //$NON-NLS-1$
+ private static final String CLASS_ATTRIBUTE= "class"; //$NON-NLS-1$
+ private static final String LABEL_ATTRIBUTE= "label"; //$NON-NLS-1$
+ private static final String ACTIVATE_PLUG_IN_ATTRIBUTE= "activate"; //$NON-NLS-1$
+ private static final String DESCRIPTION_ATTRIBUTE= "description"; //$NON-NLS-1$
+
+ public static final String NO_MODIFIER= "0"; //$NON-NLS-1$
+ public static final String DISABLED_TAG= "!"; //$NON-NLS-1$
+ public static final String VALUE_SEPARATOR= ";"; //$NON-NLS-1$
+
+ private int fStateMask;
+ private String fModifierString;
+ private boolean fIsEnabled;
+
+ private IConfigurationElement fElement;
+
+
+ /**
+ * Returns all Java editor text hovers contributed to the workbench.
+ */
+ public static JavaEditorTextHoverDescriptor[] getContributedHovers() {
+ IPluginRegistry registry= Platform.getPluginRegistry();
+ IConfigurationElement[] elements= registry.getConfigurationElementsFor(JAVA_EDITOR_TEXT_HOVER_EXTENSION_POINT);
+ JavaEditorTextHoverDescriptor[] hoverDescs= createDescriptors(elements);
+ initializeFromPreferences(hoverDescs);
+ return hoverDescs;
+ }
+
+ /**
+ * Computes the state mask for the given modifier string.
+ *
+ * @param modifiers the string with the modifiers, separated by '+', '-', ';', ',' or '.'
+ * @return the state mask or -1 if the input is invalid
+ */
+ public static int computeStateMask(String modifiers) {
+ if (modifiers == null)
+ return -1;
+
+ if (modifiers.length() == 0)
+ return SWT.NONE;
+
+ int stateMask= 0;
+ StringTokenizer modifierTokenizer= new StringTokenizer(modifiers, ",;.:+-* "); //$NON-NLS-1$
+ while (modifierTokenizer.hasMoreTokens()) {
+ int modifier= EditorUtility.findLocalizedModifier(modifierTokenizer.nextToken());
+ if (modifier == 0 || (stateMask & modifier) == modifier)
+ return -1;
+ stateMask= stateMask | modifier;
+ }
+ return stateMask;
+ }
+
+ /**
+ * Creates a new Java Editor text hover descriptor from the given configuration element.
+ */
+ private JavaEditorTextHoverDescriptor(IConfigurationElement element) {
+ Assert.isNotNull(element);
+ fElement= element;
+ }
+
+ /**
+ * Creates the Java editor text hover.
+ */
+ public IJavaEditorTextHover createTextHover() {
+ boolean isHoversPlugInActivated= fElement.getDeclaringExtension().getDeclaringPluginDescriptor().isPluginActivated();
+ if (isHoversPlugInActivated || canActivatePlugIn()) {
+ try {
+ return (IJavaEditorTextHover)fElement.createExecutableExtension(CLASS_ATTRIBUTE);
+ } catch (CoreException x) {
+ PHPeclipsePlugin.log(new Status(IStatus.ERROR, PHPeclipsePlugin.getPluginId(), 0, JavaHoverMessages.getString("JavaTextHover.createTextHover"), null)); //$NON-NLS-1$
+ }
+ }
+
+ return null;
+ }
+
+ //---- XML Attribute accessors ---------------------------------------------
+
+ /**
+ * Returns the hover's id.
+ */
+ public String getId() {
+ return fElement.getAttribute(ID_ATTRIBUTE);
+ }
+
+ /**
+ * Returns the hover's class name.
+ */
+ public String getHoverClassName() {
+ return fElement.getAttribute(CLASS_ATTRIBUTE);
+ }
+
+ /**
+ * Returns the hover's label.
+ */
+ public String getLabel() {
+ String label= fElement.getAttribute(LABEL_ATTRIBUTE);
+ if (label != null)
+ return label;
+
+ // Return simple class name
+ label= getHoverClassName();
+ int lastDot= label.lastIndexOf('.');
+ if (lastDot >= 0 && lastDot < label.length() - 1)
+ return label.substring(lastDot + 1);
+ else
+ return label;
+ }
+
+ /**
+ * Returns the hover's description.
+ *
+ * @return the hover's description or null
if not provided
+ */
+ public String getDescription() {
+ return fElement.getAttribute(DESCRIPTION_ATTRIBUTE);
+ }
+
+
+ public boolean canActivatePlugIn() {
+ return Boolean.valueOf(fElement.getAttribute(ACTIVATE_PLUG_IN_ATTRIBUTE)).booleanValue();
+ }
+
+ public boolean equals(Object obj) {
+ if (obj == null || !obj.getClass().equals(this.getClass()) || getId() == null)
+ return false;
+ return getId().equals(((JavaEditorTextHoverDescriptor)obj).getId());
+ }
+
+ public int hashCode() {
+ return getId().hashCode();
+ }
+
+ /*
+ * Implements a method from IComparable
+ */
+ public int compareTo(Object o) {
+ return Collator.getInstance().compare(getLabel(), ((JavaEditorTextHoverDescriptor)o).getLabel());
+ }
+
+ /**
+ * @param descriptor a JavaEditorTextHoverDescriptor
+ * @return true
if this contributed hover depends on the other one
+ */
+ public boolean dependsOn(JavaEditorTextHoverDescriptor descriptor) {
+ if (descriptor == null)
+ return false;
+
+ IPluginDescriptor thisPluginDescriptor= fElement.getDeclaringExtension().getDeclaringPluginDescriptor();
+ IPluginDescriptor otherPluginDescriptor= descriptor.fElement.getDeclaringExtension().getDeclaringPluginDescriptor();
+ return dependsOn(thisPluginDescriptor, otherPluginDescriptor);
+ }
+
+ private boolean dependsOn(IPluginDescriptor descriptor0, IPluginDescriptor descriptor1) {
+
+ IPluginRegistry registry= Platform.getPluginRegistry();
+ IPluginPrerequisite[] prerequisites= descriptor0.getPluginPrerequisites();
+
+ for (int i= 0; i < prerequisites.length; i++) {
+ IPluginPrerequisite prerequisite= prerequisites[i];
+ String id= prerequisite.getUniqueIdentifier();
+ IPluginDescriptor descriptor= registry.getPluginDescriptor(id);
+
+ if (descriptor != null && (descriptor.equals(descriptor1) || dependsOn(descriptor, descriptor1)))
+ return true;
+ }
+
+ return false;
+ }
+
+ private static JavaEditorTextHoverDescriptor[] createDescriptors(IConfigurationElement[] elements) {
+ List result= new ArrayList(elements.length);
+ for (int i= 0; i < elements.length; i++) {
+ IConfigurationElement element= elements[i];
+ if (HOVER_TAG.equals(element.getName())) {
+ JavaEditorTextHoverDescriptor desc= new JavaEditorTextHoverDescriptor(element);
+ result.add(desc);
+ }
+ }
+ Collections.sort(result);
+ return (JavaEditorTextHoverDescriptor[])result.toArray(new JavaEditorTextHoverDescriptor[result.size()]);
+ }
+
+ private static void initializeFromPreferences(JavaEditorTextHoverDescriptor[] hovers) {
+ String compiledTextHoverModifiers= PHPeclipsePlugin.getDefault().getPreferenceStore().getString(PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS);
+
+ StringTokenizer tokenizer= new StringTokenizer(compiledTextHoverModifiers, VALUE_SEPARATOR);
+ HashMap idToModifier= new HashMap(tokenizer.countTokens() / 2);
+
+ while (tokenizer.hasMoreTokens()) {
+ String id= tokenizer.nextToken();
+ if (tokenizer.hasMoreTokens())
+ idToModifier.put(id, tokenizer.nextToken());
+ }
+
+ String compiledTextHoverModifierMasks= PHPeclipsePlugin.getDefault().getPreferenceStore().getString(PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIER_MASKS);
+
+ tokenizer= new StringTokenizer(compiledTextHoverModifierMasks, VALUE_SEPARATOR);
+ HashMap idToModifierMask= new HashMap(tokenizer.countTokens() / 2);
+
+ while (tokenizer.hasMoreTokens()) {
+ String id= tokenizer.nextToken();
+ if (tokenizer.hasMoreTokens())
+ idToModifierMask.put(id, tokenizer.nextToken());
+ }
+
+ for (int i= 0; i < hovers.length; i++) {
+ String modifierString= (String)idToModifier.get(hovers[i].getId());
+ boolean enabled= true;
+ if (modifierString == null)
+ modifierString= DISABLED_TAG;
+
+ if (modifierString.startsWith(DISABLED_TAG)) {
+ enabled= false;
+ modifierString= modifierString.substring(1);
+ }
+
+ if (modifierString.equals(NO_MODIFIER))
+ modifierString= ""; //$NON-NLS-1$
+
+ hovers[i].fModifierString= modifierString;
+ hovers[i].fIsEnabled= enabled;
+ hovers[i].fStateMask= computeStateMask(modifierString);
+ if (hovers[i].fStateMask == -1) {
+ // Fallback: use stored modifier masks
+ try {
+ hovers[i].fStateMask= Integer.parseInt((String)idToModifierMask.get(hovers[i].getId()));
+ } catch (NumberFormatException ex) {
+ hovers[i].fStateMask= -1;
+ }
+ // Fix modifier string
+ int stateMask= hovers[i].fStateMask;
+ if (stateMask == -1)
+ hovers[i].fModifierString=""; //$NON-NLS-1$
+ else
+ hovers[i].fModifierString= EditorUtility.getModifierString(stateMask);
+ }
+ }
+ }
+
+ /**
+ * Returns the configured modifier getStateMask for this hover.
+ *
+ * @return the hover modifier stateMask or -1 if no hover is configured
+ */
+ public int getStateMask() {
+ return fStateMask;
+ }
+
+ /**
+ * Returns the modifier String as set in the preference store.
+ *
+ * @return the modifier string
+ */
+ public String getModifierString() {
+ return fModifierString;
+ }
+
+ /**
+ * Returns whether this hover is enabled or not.
+ *
+ * @return true
if enabled
+ */
+ public boolean isEnabled() {
+ return fIsEnabled;
+ }
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaEditorTextHoverProxy.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaEditorTextHoverProxy.java
new file mode 100644
index 0000000..9b08fae
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaEditorTextHoverProxy.java
@@ -0,0 +1,86 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+
+package net.sourceforge.phpdt.internal.ui.text.java.hover;
+
+import net.sourceforge.phpdt.ui.text.java.hover.IJavaEditorTextHover;
+
+import org.eclipse.jface.text.IRegion;
+import org.eclipse.jface.text.ITextViewer;
+import org.eclipse.ui.IEditorPart;
+
+
+/**
+ * Proxy for JavaEditorTextHovers.
+ *
+ * @since 2.1
+ */
+public class JavaEditorTextHoverProxy extends AbstractJavaEditorTextHover {
+
+ private JavaEditorTextHoverDescriptor fHoverDescriptor;
+ private IJavaEditorTextHover fHover;
+
+ public JavaEditorTextHoverProxy(JavaEditorTextHoverDescriptor descriptor, IEditorPart editor) {
+ fHoverDescriptor= descriptor;
+ setEditor(editor);
+ }
+
+ /*
+ * @see IJavaEditorTextHover#setEditor(IEditorPart)
+ */
+ public void setEditor(IEditorPart editor) {
+ super.setEditor(editor);
+
+ if (fHover != null)
+ fHover.setEditor(getEditor());
+ }
+
+ public boolean isEnabled() {
+ return true;
+ }
+
+ /*
+ * @see ITextHover#getHoverRegion(ITextViewer, int)
+ */
+ public IRegion getHoverRegion(ITextViewer textViewer, int offset) {
+ if (!isEnabled() || fHoverDescriptor == null)
+ return null;
+
+ if (isCreated() || createHover())
+ return fHover.getHoverRegion(textViewer, offset);
+ else
+ return null;
+ }
+
+ /*
+ * @see ITextHover#getHoverInfo(ITextViewer, IRegion)
+ */
+ public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
+ if (!isEnabled() || fHoverDescriptor == null)
+ return null;
+
+ if (isCreated() || createHover())
+ return fHover.getHoverInfo(textViewer, hoverRegion);
+ else
+ return null;
+ }
+
+ private boolean isCreated() {
+ return fHover != null;
+ }
+
+ private boolean createHover() {
+ fHover= fHoverDescriptor.createTextHover();
+ if (fHover != null)
+ fHover.setEditor(getEditor());
+ return isCreated();
+ }
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaHoverMessages.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaHoverMessages.java
new file mode 100644
index 0000000..711f49d
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaHoverMessages.java
@@ -0,0 +1,32 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.ui.text.java.hover;
+
+import java.util.MissingResourceException;
+import java.util.ResourceBundle;
+
+class JavaHoverMessages {
+
+ private static final String RESOURCE_BUNDLE= "net.sourceforge.phpdt.internal.ui.text.java.hover.JavaHoverMessages";//$NON-NLS-1$
+
+ private static ResourceBundle fgResourceBundle= ResourceBundle.getBundle(RESOURCE_BUNDLE);
+
+ private JavaHoverMessages() {
+ }
+
+ public static String getString(String key) {
+ try {
+ return fgResourceBundle.getString(key);
+ } catch (MissingResourceException e) {
+ return "!" + key + "!";//$NON-NLS-2$ //$NON-NLS-1$
+ }
+ }
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaHoverMessages.properties b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaHoverMessages.properties
new file mode 100644
index 0000000..2a9d7f5
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaHoverMessages.properties
@@ -0,0 +1,14 @@
+###############################################################################
+# Copyright (c) 2000, 2003 IBM Corporation and others.
+# All rights reserved. This program and the accompanying materials
+# are made available under the terms of the Common Public License v1.0
+# which accompanies this distribution, and is available at
+# http://www.eclipse.org/legal/cpl-v10.html
+#
+# Contributors:
+# IBM Corporation - initial API and implementation
+###############################################################################
+
+TypeHover.more_to_come=\ ...
+
+JavaTextHover.createTextHover=Could not create java text hover
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaProblemHover.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaProblemHover.java
new file mode 100644
index 0000000..1ca1d0b
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaProblemHover.java
@@ -0,0 +1,85 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+
+package net.sourceforge.phpdt.internal.ui.text.java.hover;
+
+import java.util.Iterator;
+
+import net.sourceforge.phpdt.ui.PreferenceConstants;
+import net.sourceforge.phpeclipse.PHPeclipsePlugin;
+import net.sourceforge.phpeclipse.phpeditor.IJavaAnnotation;
+import net.sourceforge.phpeclipse.phpeditor.JavaAnnotationIterator;
+import net.sourceforge.phpeclipse.phpeditor.PHPUnitEditor;
+
+import org.eclipse.jface.text.IRegion;
+import org.eclipse.jface.text.ITextViewer;
+import org.eclipse.jface.text.Position;
+import org.eclipse.jface.text.source.Annotation;
+import org.eclipse.jface.text.source.IAnnotationModel;
+import org.eclipse.ui.IEditorPart;
+import org.eclipse.ui.externaltools.internal.ant.editor.derived.HTMLPrinter;
+import org.eclipse.ui.texteditor.IDocumentProvider;
+
+
+public class JavaProblemHover extends AbstractJavaEditorTextHover {
+
+ /*
+ * Formats a message as HTML text.
+ */
+ private String formatMessage(String message) {
+ StringBuffer buffer= new StringBuffer();
+ HTMLPrinter.addPageProlog(buffer);
+ HTMLPrinter.addParagraph(buffer, HTMLPrinter.convertToHTMLContent(message));
+ HTMLPrinter.addPageEpilog(buffer);
+ return buffer.toString();
+ }
+
+ /*
+ * @see ITextHover#getHoverInfo(ITextViewer, IRegion)
+ */
+ public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
+
+ if (getEditor() == null)
+ return null;
+
+ IDocumentProvider provider= PHPeclipsePlugin.getDefault().getCompilationUnitDocumentProvider();
+ IAnnotationModel model= provider.getAnnotationModel(getEditor().getEditorInput());
+
+ if (model != null) {
+ Iterator e= new JavaAnnotationIterator(model, true);
+ while (e.hasNext()) {
+ Annotation a= (Annotation) e.next();
+ Position p= model.getPosition(a);
+ if (p.overlapsWith(hoverRegion.getOffset(), hoverRegion.getLength())) {
+ String msg= ((IJavaAnnotation) a).getMessage();
+ if (msg != null && msg.trim().length() > 0)
+ return formatMessage(msg);
+ }
+ }
+ }
+
+ return null;
+ }
+
+ /*
+ * @see IJavaEditorTextHover#setEditor(IEditorPart)
+ */
+ public void setEditor(IEditorPart editor) {
+ if (editor instanceof PHPUnitEditor)
+ super.setEditor(editor);
+ else
+ super.setEditor(null);
+ }
+
+ static boolean isJavaProblemHover(String id) {
+ return PreferenceConstants.ID_PROBLEM_HOVER.equals(id);
+ }
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaSourceHover.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaSourceHover.java
new file mode 100644
index 0000000..786076f
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/hover/JavaSourceHover.java
@@ -0,0 +1,112 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+
+package net.sourceforge.phpdt.internal.ui.text.java.hover;
+
+import java.io.IOException;
+
+import net.sourceforge.phpdt.core.IJavaElement;
+import net.sourceforge.phpdt.core.IMember;
+import net.sourceforge.phpdt.core.ISourceReference;
+import net.sourceforge.phpdt.core.JavaModelException;
+import net.sourceforge.phpdt.internal.ui.text.PHPCodeReader;
+import net.sourceforge.phpdt.internal.ui.viewsupport.JavaElementLabels;
+import net.sourceforge.phpeclipse.PHPeclipsePlugin;
+
+import org.eclipse.jface.text.Document;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.ui.externaltools.internal.ant.editor.derived.HTMLPrinter;
+
+/**
+ * Provides source as hover info for Java elements.
+ */
+public class JavaSourceHover extends AbstractJavaEditorTextHover {
+
+ private final int LABEL_FLAGS= JavaElementLabels.ALL_FULLY_QUALIFIED
+ | JavaElementLabels.M_PRE_RETURNTYPE | JavaElementLabels.M_PARAMETER_TYPES | JavaElementLabels.M_PARAMETER_NAMES | JavaElementLabels.M_EXCEPTIONS
+ | JavaElementLabels.F_PRE_TYPE_SIGNATURE;
+
+
+ /*
+ * @see JavaElementHover
+ */
+ protected String getHoverInfo(IJavaElement[] result) {
+ int nResults= result.length;
+ StringBuffer buffer= new StringBuffer();
+
+ if (nResults > 1) {
+
+ for (int i= 0; i < result.length; i++) {
+ HTMLPrinter.startBulletList(buffer);
+ IJavaElement curr= result[i];
+ if (curr instanceof IMember)
+ HTMLPrinter.addBullet(buffer, getInfoText((IMember) curr));
+ HTMLPrinter.endBulletList(buffer);
+ }
+
+ } else {
+
+ IJavaElement curr= result[0];
+ if (curr instanceof IMember && curr instanceof ISourceReference) {
+ HTMLPrinter.addSmallHeader(buffer, getInfoText(((IMember)curr)));
+ try {
+ String source= ((ISourceReference)curr).getSource();
+ source= removeLeadingComments(source);
+ HTMLPrinter.addParagraph(buffer, ""); //$NON-NLS-1$
+ HTMLPrinter.addParagraph(buffer, source);
+ HTMLPrinter.addParagraph(buffer, "
"); //$NON-NLS-1$
+ } catch (JavaModelException ex) {
+ // only write small header
+ }
+ }
+ }
+
+ if (buffer.length() > 0) {
+ HTMLPrinter.insertPageProlog(buffer, 0);
+ HTMLPrinter.addPageEpilog(buffer);
+ return buffer.toString();
+ }
+
+ return null;
+ }
+
+ private String getInfoText(IMember member) {
+ return JavaElementLabels.getElementLabel(member, LABEL_FLAGS);
+ }
+
+ private String removeLeadingComments(String source) {
+ PHPCodeReader reader= new PHPCodeReader();
+ IDocument document= new Document(source);
+ int i;
+ try {
+ reader.configureForwardReader(document, 0, document.getLength(), true, false);
+ int c= reader.read();
+ while (c != -1 && (c == '\r' || c == '\n')) {
+ c= reader.read();
+ }
+ i= reader.getOffset();
+ reader.close();
+ } catch (IOException ex) {
+ i= 0;
+ } finally {
+ try {
+ if (reader != null)
+ reader.close();
+ } catch (IOException ex) {
+ PHPeclipsePlugin.log(ex);
+ }
+ }
+
+ if (i < 0)
+ return source;
+ return source.substring(i);
+ }
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/PHPFileUtil.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/PHPFileUtil.java
index 4917de5..1f8c8fe 100644
--- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/PHPFileUtil.java
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/PHPFileUtil.java
@@ -11,13 +11,106 @@ import org.eclipse.core.resources.IFile;
*
*/
public class PHPFileUtil {
- static public boolean isPHPFile(IFile file) {
- if ("php".equalsIgnoreCase(file.getFileExtension())
- || "php3".equalsIgnoreCase(file.getFileExtension())
- || "php4".equalsIgnoreCase(file.getFileExtension())
- || "inc".equalsIgnoreCase(file.getFileExtension())) {
- return true;
+ public final static char[] SUFFIX_php = ".php".toCharArray(); //$NON-NLS-1$
+ public final static char[] SUFFIX_PHP = ".PHP".toCharArray(); //$NON-NLS-1$
+ public final static char[] SUFFIX_php3 = ".php3".toCharArray(); //$NON-NLS-1$
+ public final static char[] SUFFIX_PHP3 = ".PHP3".toCharArray(); //$NON-NLS-1$
+ public final static char[] SUFFIX_php4 = ".php4".toCharArray(); //$NON-NLS-1$
+ public final static char[] SUFFIX_PHP4 = ".PHP4".toCharArray(); //$NON-NLS-1$
+ public final static char[] SUFFIX_inc = ".inc".toCharArray(); //$NON-NLS-1$
+ public final static char[] SUFFIX_INC = ".INC".toCharArray(); //$NON-NLS-1$
+
+ public static boolean isPHPFile(IFile file) {
+ String extension = file.getFileExtension();
+ return isPHPFileName(file.getLocation().toString());
+ }
+
+ /**
+ * Returns true iff str.toLowerCase().endsWith(".php")
+ * implementation is not creating extra strings.
+ */
+ public final static boolean isPHPFileName(String name) {
+ return isPHP_FileName(name) || isPHP3_FileName(name) || isPHP4_FileName(name) || isINC_FileName(name);
+ }
+ // static public boolean isPHPFile(String extension) {
+ // if ("php".equalsIgnoreCase(extension)
+ // || "php3".equalsIgnoreCase(extension)
+ // || "php4".equalsIgnoreCase(extension)
+ // || "inc".equalsIgnoreCase(extension)) {
+ // return true;
+ // }
+ // return false;
+ // }
+
+ /**
+ * Returns true iff str.toLowerCase().endsWith(".php")
+ * implementation is not creating extra strings.
+ */
+ private final static boolean isPHP_FileName(String name) {
+ int nameLength = name == null ? 0 : name.length();
+ int suffixLength = SUFFIX_PHP.length;
+ if (nameLength < suffixLength)
+ return false;
+
+ for (int i = 0, offset = nameLength - suffixLength; i < suffixLength; i++) {
+ char c = name.charAt(offset + i);
+ if (c != SUFFIX_php[i] && c != SUFFIX_PHP[i])
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Returns true iff str.toLowerCase().endsWith(".php3")
+ * implementation is not creating extra strings.
+ */
+ private final static boolean isPHP3_FileName(String name) {
+ int nameLength = name == null ? 0 : name.length();
+ int suffixLength = SUFFIX_PHP3.length;
+ if (nameLength < suffixLength)
+ return false;
+
+ for (int i = 0, offset = nameLength - suffixLength; i < suffixLength; i++) {
+ char c = name.charAt(offset + i);
+ if (c != SUFFIX_php3[i] && c != SUFFIX_PHP3[i])
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Returns true iff str.toLowerCase().endsWith(".php4")
+ * implementation is not creating extra strings.
+ */
+ private final static boolean isPHP4_FileName(String name) {
+ int nameLength = name == null ? 0 : name.length();
+ int suffixLength = SUFFIX_PHP4.length;
+ if (nameLength < suffixLength)
+ return false;
+
+ for (int i = 0, offset = nameLength - suffixLength; i < suffixLength; i++) {
+ char c = name.charAt(offset + i);
+ if (c != SUFFIX_php4[i] && c != SUFFIX_PHP4[i])
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Returns true iff str.toLowerCase().endsWith(".inc")
+ * implementation is not creating extra strings.
+ */
+ private final static boolean isINC_FileName(String name) {
+ int nameLength = name == null ? 0 : name.length();
+ int suffixLength = SUFFIX_INC.length;
+ if (nameLength < suffixLength)
+ return false;
+
+ for (int i = 0, offset = nameLength - suffixLength; i < suffixLength; i++) {
+ char c = name.charAt(offset + i);
+ if (c != SUFFIX_inc[i] && c != SUFFIX_INC[i])
+ return false;
}
- return false;
+ return true;
}
}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/SWTUtil.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/SWTUtil.java
index 5344dc0..ffdd686 100644
--- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/SWTUtil.java
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/util/SWTUtil.java
@@ -1,12 +1,16 @@
-/*
- * (c) Copyright IBM Corp. 2000, 2001.
- * All Rights Reserved.
- */
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
package net.sourceforge.phpdt.internal.ui.util;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.util.Assert;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DragSource;
import org.eclipse.swt.dnd.DropTarget;
@@ -18,8 +22,13 @@ import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.ScrollBar;
import org.eclipse.swt.widgets.Shell;
+import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.Widget;
+import org.eclipse.jface.dialogs.IDialogConstants;
+import org.eclipse.jface.resource.JFaceResources;
+import org.eclipse.jface.util.Assert;
+
/**
* Utility class to simplify access to some SWT resources.
*/
@@ -66,6 +75,8 @@ public class SWTUtil {
* Returns a width hint for a button control.
*/
public static int getButtonWidthHint(Button button) {
+ if (button.getFont().equals(JFaceResources.getDefaultFont()))
+ button.setFont(JFaceResources.getDialogFont());
PixelConverter converter= new PixelConverter(button);
int widthHint= converter.convertHorizontalDLUsToPixels(IDialogConstants.BUTTON_WIDTH);
return Math.max(widthHint, button.computeSize(SWT.DEFAULT, SWT.DEFAULT, true).x);
@@ -75,6 +86,8 @@ public class SWTUtil {
* Returns a height hint for a button control.
*/
public static int getButtonHeigthHint(Button button) {
+ if (button.getFont().equals(JFaceResources.getDefaultFont()))
+ button.setFont(JFaceResources.getDialogFont());
PixelConverter converter= new PixelConverter(button);
return converter.convertVerticalDLUsToPixels(IDialogConstants.BUTTON_HEIGHT);
}
@@ -94,7 +107,16 @@ public class SWTUtil {
((GridData)gd).heightHint= getButtonHeigthHint(button);
((GridData)gd).widthHint= getButtonWidthHint(button);
}
- }
+ }
+
+ public static int getTableHeightHint(Table table, int rows) {
+ if (table.getFont().equals(JFaceResources.getDefaultFont()))
+ table.setFont(JFaceResources.getDialogFont());
+ int result= table.getItemHeight() * rows + table.getHeaderHeight();
+ if (table.getLinesVisible())
+ result+= table.getGridLineWidth() * (rows - 1);
+ return result;
+ }
-}
\ No newline at end of file
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/AppearanceAwareLabelProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/AppearanceAwareLabelProvider.java
new file mode 100644
index 0000000..265ccbf
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/AppearanceAwareLabelProvider.java
@@ -0,0 +1,99 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.ui.viewsupport;
+
+import net.sourceforge.phpdt.ui.PreferenceConstants;
+
+import org.eclipse.jface.preference.IPreferenceStore;
+import org.eclipse.jface.util.IPropertyChangeListener;
+import org.eclipse.jface.util.PropertyChangeEvent;
+import org.eclipse.jface.viewers.LabelProviderChangedEvent;
+
+
+/**
+ * JavaUILabelProvider that respects settings from the Appearance preference page.
+ * Triggers a viewer update when a preference changes.
+ */
+public class AppearanceAwareLabelProvider extends JavaUILabelProvider implements IPropertyChangeListener {
+
+ public final static int DEFAULT_TEXTFLAGS= JavaElementLabels.ROOT_VARIABLE | JavaElementLabels.M_PARAMETER_TYPES |
+ JavaElementLabels.M_APP_RETURNTYPE | JavaElementLabels.REFERENCED_ROOT_POST_QUALIFIED;
+ public final static int DEFAULT_IMAGEFLAGS= JavaElementImageProvider.OVERLAY_ICONS;
+
+ private int fTextFlagMask;
+ private int fImageFlagMask;
+
+ /**
+ * Constructor for AppearanceAwareLabelProvider.
+ */
+ public AppearanceAwareLabelProvider(int textFlags, int imageFlags) {
+ super(textFlags, imageFlags);
+ initMasks();
+ PreferenceConstants.getPreferenceStore().addPropertyChangeListener(this);
+ }
+
+ /**
+ * Creates a labelProvider with DEFAULT_TEXTFLAGS and DEFAULT_IMAGEFLAGS
+ */
+ public AppearanceAwareLabelProvider() {
+ this(DEFAULT_TEXTFLAGS, DEFAULT_IMAGEFLAGS);
+ }
+
+ private void initMasks() {
+ IPreferenceStore store= PreferenceConstants.getPreferenceStore();
+ fTextFlagMask= -1;
+ if (!store.getBoolean(PreferenceConstants.APPEARANCE_METHOD_RETURNTYPE)) {
+ fTextFlagMask ^= JavaElementLabels.M_APP_RETURNTYPE;
+ }
+ if (!store.getBoolean(PreferenceConstants.APPEARANCE_COMPRESS_PACKAGE_NAMES)) {
+ fTextFlagMask ^= JavaElementLabels.P_COMPRESSED;
+ }
+
+ fImageFlagMask= -1;
+ }
+
+ /*
+ * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
+ */
+ public void propertyChange(PropertyChangeEvent event) {
+ String property= event.getProperty();
+ if (property.equals(PreferenceConstants.APPEARANCE_METHOD_RETURNTYPE)
+ || property.equals(PreferenceConstants.APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW)
+ || property.equals(PreferenceConstants.APPEARANCE_COMPRESS_PACKAGE_NAMES)) {
+ initMasks();
+ LabelProviderChangedEvent lpEvent= new LabelProviderChangedEvent(this, null); // refresh all
+ fireLabelProviderChanged(lpEvent);
+ }
+ }
+
+ /*
+ * @see IBaseLabelProvider#dispose()
+ */
+ public void dispose() {
+ PreferenceConstants.getPreferenceStore().removePropertyChangeListener(this);
+ super.dispose();
+ }
+
+ /*
+ * @see JavaUILabelProvider#evaluateImageFlags()
+ */
+ protected int evaluateImageFlags(Object element) {
+ return getImageFlags() & fImageFlagMask;
+ }
+
+ /*
+ * @see JavaUILabelProvider#evaluateTextFlags()
+ */
+ protected int evaluateTextFlags(Object element) {
+ return getTextFlags() & fTextFlagMask;
+ }
+
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/DecoratingJavaLabelProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/DecoratingJavaLabelProvider.java
new file mode 100644
index 0000000..921fe54
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/DecoratingJavaLabelProvider.java
@@ -0,0 +1,132 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.ui.viewsupport;
+
+import net.sourceforge.phpdt.ui.OverrideIndicatorLabelDecorator;
+import net.sourceforge.phpdt.ui.ProblemsLabelDecorator;
+import net.sourceforge.phpeclipse.PHPeclipsePlugin;
+
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.jface.viewers.DecoratingLabelProvider;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.ui.IDecoratorManager;
+import org.eclipse.ui.PlatformUI;
+
+
+/**
+ * Decorator prepared for the switch to use lightweight label decorators:
+ * uncomment the lbale decorator entries in plugin.xml and change
+ * USE_LIGHTWEIGHT to true.
+ * Certain views don't want problems or override indicators, so they signal this
+ * in the constructor. So on each getImage the corrsponding decorators are
+ * turned off and on again.
+ */
+public class DecoratingJavaLabelProvider extends DecoratingLabelProvider {
+
+ private static final boolean USE_LIGHTWEIGHT= false;
+
+ private static final String PROBLEM_DECORATOR_ID= "net.sourceforge.phpdt.ui.problem.decorator"; //$NON-NLS-1$
+ private static final String OVERRIDE_DECORATOR_ID= "net.sourceforge.phpdt.ui.override.decorator"; //$NON-NLS-1$
+
+ private boolean fUseErrorTick;
+ private boolean fUseOverride;
+
+ /**
+ * Decorating label provider for Java. Combines a JavaUILabelProvider
+ * with problem and override indicuator with the workbench decorator (label
+ * decorator extension point).
+ */
+ public DecoratingJavaLabelProvider(JavaUILabelProvider labelProvider) {
+ this(labelProvider, true, true);
+ }
+
+ /**
+ * Decorating label provider for Java. Combines a JavaUILabelProvider
+ * (if enabled with problem and override indicator) with the workbench
+ * decorator (label decorator extension point).
+ */
+ public DecoratingJavaLabelProvider(JavaUILabelProvider labelProvider, boolean errorTick, boolean override) {
+ super(labelProvider, PlatformUI.getWorkbench().getDecoratorManager().getLabelDecorator());
+ fUseErrorTick= errorTick;
+ fUseOverride= override;
+ if (!USE_LIGHTWEIGHT) {
+ if (errorTick) {
+ labelProvider.addLabelDecorator(new ProblemsLabelDecorator(null));
+ }
+ if (override) {
+ labelProvider.addLabelDecorator(new OverrideIndicatorLabelDecorator(null));
+ }
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.jface.viewers.ILabelProvider#getImage(java.lang.Object)
+ */
+ public Image getImage(Object element) {
+ if (USE_LIGHTWEIGHT) {
+ IDecoratorManager manager= PlatformUI.getWorkbench().getDecoratorManager();
+
+ boolean disableErrorTick= manager.getEnabled(PROBLEM_DECORATOR_ID) && !fUseErrorTick;
+ boolean disableOverride= manager.getEnabled(OVERRIDE_DECORATOR_ID) && !fUseOverride;
+ try {
+ if (disableErrorTick) {
+ manager.setEnabled(PROBLEM_DECORATOR_ID, false);
+ }
+ if (disableOverride) {
+ manager.setEnabled(OVERRIDE_DECORATOR_ID, false);
+ }
+ Image image= super.getImage(element);
+ if (disableErrorTick) {
+ manager.setEnabled(PROBLEM_DECORATOR_ID, true);
+ }
+ if (disableOverride) {
+ manager.setEnabled(OVERRIDE_DECORATOR_ID, true);
+ }
+ return image;
+ } catch (CoreException e) {
+ PHPeclipsePlugin.log(e);
+ }
+ }
+ return super.getImage(element);
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.jface.viewers.ILabelProvider#getText(java.lang.Object)
+ */
+ public String getText(Object element) {
+ if (USE_LIGHTWEIGHT) {
+ IDecoratorManager manager= PlatformUI.getWorkbench().getDecoratorManager();
+
+ boolean disableErrorTick= manager.getEnabled(PROBLEM_DECORATOR_ID) && !fUseErrorTick;
+ boolean disableOverride= manager.getEnabled(OVERRIDE_DECORATOR_ID) && !fUseOverride;
+ try {
+ if (disableErrorTick) {
+ manager.setEnabled(PROBLEM_DECORATOR_ID, false);
+ }
+ if (disableOverride) {
+ manager.setEnabled(OVERRIDE_DECORATOR_ID, false);
+ }
+ String text= super.getText(element);
+ if (disableErrorTick) {
+ manager.setEnabled(PROBLEM_DECORATOR_ID, true);
+ }
+ if (disableOverride) {
+ manager.setEnabled(OVERRIDE_DECORATOR_ID, true);
+ }
+ return text;
+ } catch (CoreException e) {
+ PHPeclipsePlugin.log(e);
+ }
+ }
+ return super.getText(element);
+ }
+
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/IProblemChangedListener.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/IProblemChangedListener.java
new file mode 100644
index 0000000..ed030b0
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/IProblemChangedListener.java
@@ -0,0 +1,31 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.ui.viewsupport;
+
+import org.eclipse.core.resources.IResource;
+
+/**
+ * Can be added to a ProblemMarkerManager to get notified about problem
+ * marker changes. Used to update error ticks.
+ */
+public interface IProblemChangedListener {
+
+ /**
+ * Called when problems changed. This call is posted in an aynch exec, therefore passed
+ * resources must not exist.
+ * @param changedElements A set with elements of type IResource
that
+ * describe the resources that had an problem change.
+ * @param isMarkerChange If set to true
, the change was a marker change, if
+ * false
, the change came from an annotation model modification.
+ */
+ void problemsChanged(IResource[] changedResources, boolean isMarkerChange);
+
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ImageImageDescriptor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ImageImageDescriptor.java
new file mode 100644
index 0000000..2dd5a89
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/ImageImageDescriptor.java
@@ -0,0 +1,53 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.ui.viewsupport;
+
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.graphics.ImageData;
+
+import org.eclipse.jface.resource.ImageDescriptor;
+
+/**
+ */
+public class ImageImageDescriptor extends ImageDescriptor {
+
+ private Image fImage;
+
+ /**
+ * Constructor for ImagImageDescriptor.
+ */
+ public ImageImageDescriptor(Image image) {
+ super();
+ fImage= image;
+ }
+
+ /* (non-Javadoc)
+ * @see ImageDescriptor#getImageData()
+ */
+ public ImageData getImageData() {
+ return fImage.getImageData();
+ }
+
+ /* (non-Javadoc)
+ * @see Object#equals(Object)
+ */
+ public boolean equals(Object obj) {
+ return (obj != null) && getClass().equals(obj.getClass()) && fImage.equals(((ImageImageDescriptor)obj).fImage);
+ }
+
+ /* (non-Javadoc)
+ * @see Object#hashCode()
+ */
+ public int hashCode() {
+ return fImage.hashCode();
+ }
+
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/JavaElementImageProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/JavaElementImageProvider.java
new file mode 100644
index 0000000..1b842ab
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/JavaElementImageProvider.java
@@ -0,0 +1,421 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.ui.viewsupport;
+
+import net.sourceforge.phpdt.core.Flags;
+import net.sourceforge.phpdt.core.IField;
+import net.sourceforge.phpdt.core.IJavaElement;
+import net.sourceforge.phpdt.core.IJavaProject;
+import net.sourceforge.phpdt.core.IMember;
+import net.sourceforge.phpdt.core.IMethod;
+import net.sourceforge.phpdt.core.IPackageFragment;
+import net.sourceforge.phpdt.core.IPackageFragmentRoot;
+import net.sourceforge.phpdt.core.IType;
+import net.sourceforge.phpdt.core.JavaModelException;
+import net.sourceforge.phpdt.internal.ui.PHPUiImages;
+import net.sourceforge.phpdt.internal.ui.PHPUIMessages;
+import net.sourceforge.phpdt.ui.JavaElementImageDescriptor;
+import net.sourceforge.phpeclipse.PHPeclipsePlugin;
+
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.runtime.IAdaptable;
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.jface.util.Assert;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.graphics.Point;
+import org.eclipse.ui.ISharedImages;
+import org.eclipse.ui.model.IWorkbenchAdapter;
+
+/**
+ * Default strategy of the Java plugin for the construction of Java element icons.
+ */
+public class JavaElementImageProvider {
+
+ /**
+ * Flags for the JavaImageLabelProvider:
+ * Generate images with overlays.
+ */
+ public final static int OVERLAY_ICONS = 0x1;
+
+ /**
+ * Generate small sized images.
+ */
+ public final static int SMALL_ICONS = 0x2;
+
+ /**
+ * Use the 'light' style for rendering types.
+ */
+ public final static int LIGHT_TYPE_ICONS = 0x4;
+
+ public static final Point SMALL_SIZE = new Point(16, 16);
+ public static final Point BIG_SIZE = new Point(22, 16);
+
+ private static ImageDescriptor DESC_OBJ_PROJECT_CLOSED;
+ private static ImageDescriptor DESC_OBJ_PROJECT;
+ private static ImageDescriptor DESC_OBJ_FOLDER;
+ {
+ ISharedImages images = PHPeclipsePlugin.getDefault().getWorkbench().getSharedImages();
+ DESC_OBJ_PROJECT_CLOSED = images.getImageDescriptor(ISharedImages.IMG_OBJ_PROJECT_CLOSED);
+ DESC_OBJ_PROJECT = images.getImageDescriptor(ISharedImages.IMG_OBJ_PROJECT);
+ DESC_OBJ_FOLDER = images.getImageDescriptor(ISharedImages.IMG_OBJ_FOLDER);
+ }
+
+ private ImageDescriptorRegistry fRegistry;
+
+ public JavaElementImageProvider() {
+ fRegistry = null; // lazy initialization
+ }
+
+ /**
+ * Returns the icon for a given element. The icon depends on the element type
+ * and element properties. If configured, overlay icons are constructed for
+ * ISourceReference
s.
+ * @param flags Flags as defined by the JavaImageLabelProvider
+ */
+ public Image getImageLabel(Object element, int flags) {
+ return getImageLabel(computeDescriptor(element, flags));
+ }
+
+ private Image getImageLabel(ImageDescriptor descriptor) {
+ if (descriptor == null)
+ return null;
+ return getRegistry().get(descriptor);
+ }
+
+ private ImageDescriptorRegistry getRegistry() {
+ if (fRegistry == null) {
+ fRegistry = PHPeclipsePlugin.getImageDescriptorRegistry();
+ }
+ return fRegistry;
+ }
+
+ private ImageDescriptor computeDescriptor(Object element, int flags) {
+ if (element instanceof IJavaElement) {
+ return getJavaImageDescriptor((IJavaElement) element, flags);
+ } else if (element instanceof IFile) {
+ IFile file = (IFile) element;
+ if ("java".equals(file.getFileExtension())) { //$NON-NLS-1$
+ return getCUResourceImageDescriptor(file, flags); // image for a CU not on the build path
+ }
+ return getWorkbenchImageDescriptor(file, flags);
+ } else if (element instanceof IAdaptable) {
+ return getWorkbenchImageDescriptor((IAdaptable) element, flags);
+ }
+ return null;
+ }
+
+ private static boolean showOverlayIcons(int flags) {
+ return (flags & OVERLAY_ICONS) != 0;
+ }
+
+ private static boolean useSmallSize(int flags) {
+ return (flags & SMALL_ICONS) != 0;
+ }
+
+ private static boolean useLightIcons(int flags) {
+ return (flags & LIGHT_TYPE_ICONS) != 0;
+ }
+
+ /**
+ * Returns an image descriptor for a compilatio unit not on the class path.
+ * The descriptor includes overlays, if specified.
+ */
+ public ImageDescriptor getCUResourceImageDescriptor(IFile file, int flags) {
+ Point size = useSmallSize(flags) ? SMALL_SIZE : BIG_SIZE;
+ return new JavaElementImageDescriptor(PHPUiImages.DESC_OBJS_CUNIT_RESOURCE, 0, size);
+ }
+
+ /**
+ * Returns an image descriptor for a java element. The descriptor includes overlays, if specified.
+ */
+ public ImageDescriptor getJavaImageDescriptor(IJavaElement element, int flags) {
+ int adornmentFlags = computeJavaAdornmentFlags(element, flags);
+ Point size = useSmallSize(flags) ? SMALL_SIZE : BIG_SIZE;
+ return new JavaElementImageDescriptor(getBaseImageDescriptor(element, flags), adornmentFlags, size);
+ }
+
+ /**
+ * Returns an image descriptor for a IAdaptable. The descriptor includes overlays, if specified (only error ticks apply).
+ * Returns null
if no image could be found.
+ */
+ public ImageDescriptor getWorkbenchImageDescriptor(IAdaptable adaptable, int flags) {
+ IWorkbenchAdapter wbAdapter = (IWorkbenchAdapter) adaptable.getAdapter(IWorkbenchAdapter.class);
+ if (wbAdapter == null) {
+ return null;
+ }
+ ImageDescriptor descriptor = wbAdapter.getImageDescriptor(adaptable);
+ if (descriptor == null) {
+ return null;
+ }
+
+ Point size = useSmallSize(flags) ? SMALL_SIZE : BIG_SIZE;
+ return new JavaElementImageDescriptor(descriptor, 0, size);
+ }
+
+ // ---- Computation of base image key -------------------------------------------------
+
+ /**
+ * Returns an image descriptor for a java element. This is the base image, no overlays.
+ */
+ public ImageDescriptor getBaseImageDescriptor(IJavaElement element, int renderFlags) {
+ IType type = null;
+ boolean isInterface = false;
+ try {
+ switch (element.getElementType()) {
+ case IJavaElement.INITIALIZER :
+ return PHPUiImages.DESC_MISC_PRIVATE; // 23479
+ case IJavaElement.METHOD :
+ IMember member = (IMember) element;
+ type = member.getDeclaringType();
+ isInterface = (type != null) && member.getDeclaringType().isInterface();
+ return getMethodImageDescriptor(isInterface, member.getFlags());
+ case IJavaElement.FIELD :
+ IField field = (IField) element;
+ return getFieldImageDescriptor(field.getDeclaringType().isInterface(), field.getFlags());
+
+ case IJavaElement.PACKAGE_DECLARATION :
+ return PHPUiImages.DESC_OBJS_PACKDECL;
+
+ case IJavaElement.IMPORT_DECLARATION :
+ return PHPUiImages.DESC_OBJS_IMPDECL;
+
+ case IJavaElement.IMPORT_CONTAINER :
+ return PHPUiImages.DESC_OBJS_IMPCONT;
+
+ case IJavaElement.TYPE :
+ {
+ type = (IType) element;
+ isInterface = type.isInterface();
+
+ if (useLightIcons(renderFlags)) {
+ return isInterface ? PHPUiImages.DESC_OBJS_INTERFACEALT : PHPUiImages.DESC_OBJS_CLASSALT;
+ }
+ boolean isInner = type.getDeclaringType() != null;
+ return getTypeImageDescriptor(isInterface, isInner, type.getFlags());
+ }
+
+ case IJavaElement.PACKAGE_FRAGMENT_ROOT :
+ {
+ IPackageFragmentRoot root = (IPackageFragmentRoot) element;
+ // if (root.isArchive()) {
+ // IPath attach= root.getSourceAttachmentPath();
+ // if (root.isExternal()) {
+ // if (attach == null) {
+ // return PHPUiImages.DESC_OBJS_EXTJAR;
+ // } else {
+ // return PHPUiImages.DESC_OBJS_EXTJAR_WSRC;
+ // }
+ // } else {
+ // if (attach == null) {
+ // return PHPUiImages.DESC_OBJS_JAR;
+ // } else {
+ // return PHPUiImages.DESC_OBJS_JAR_WSRC;
+ // }
+ // }
+ // } else {
+ return PHPUiImages.DESC_OBJS_PACKFRAG_ROOT;
+ // }
+ }
+
+ case IJavaElement.PACKAGE_FRAGMENT :
+ return getPackageFragmentIcon(element, renderFlags);
+
+ case IJavaElement.COMPILATION_UNIT :
+ return PHPUiImages.DESC_OBJS_CUNIT;
+
+ case IJavaElement.CLASS_FILE :
+ /* this is too expensive for large packages
+ try {
+ IClassFile cfile= (IClassFile)element;
+ if (cfile.isClass())
+ return PHPUiImages.IMG_OBJS_CFILECLASS;
+ return PHPUiImages.IMG_OBJS_CFILEINT;
+ } catch(JavaModelException e) {
+ // fall through;
+ }*/
+ return PHPUiImages.DESC_OBJS_CFILE;
+
+ case IJavaElement.JAVA_PROJECT :
+ IJavaProject jp = (IJavaProject) element;
+ if (jp.getProject().isOpen()) {
+ IProject project = jp.getProject();
+ IWorkbenchAdapter adapter = (IWorkbenchAdapter) project.getAdapter(IWorkbenchAdapter.class);
+ if (adapter != null) {
+ ImageDescriptor result = adapter.getImageDescriptor(project);
+ if (result != null)
+ return result;
+ }
+ return DESC_OBJ_PROJECT;
+ }
+ return DESC_OBJ_PROJECT_CLOSED;
+
+ case IJavaElement.JAVA_MODEL :
+ return PHPUiImages.DESC_OBJS_JAVA_MODEL;
+ }
+
+ Assert.isTrue(false, PHPUIMessages.getString("JavaImageLabelprovider.assert.wrongImage")); //$NON-NLS-1$
+ return null; //$NON-NLS-1$
+
+ } catch (JavaModelException e) {
+ if (e.isDoesNotExist())
+ return PHPUiImages.DESC_OBJS_UNKNOWN;
+ PHPeclipsePlugin.log(e);
+ return PHPUiImages.DESC_OBJS_GHOST;
+ }
+ }
+
+ protected ImageDescriptor getPackageFragmentIcon(IJavaElement element, int renderFlags) throws JavaModelException {
+ // IPackageFragment fragment= (IPackageFragment)element;
+ // boolean containsJavaElements= false;
+ // try {
+ // containsJavaElements= fragment.hasChildren();
+ // } catch(JavaModelException e) {
+ // // assuming no children;
+ // }
+ // if(!containsJavaElements && (fragment.getNonJavaResources().length > 0))
+ // return PHPUiImages.DESC_OBJS_EMPTY_PACKAGE_RESOURCES;
+ // else if (!containsJavaElements)
+ // return PHPUiImages.DESC_OBJS_EMPTY_PACKAGE;
+ return PHPUiImages.DESC_OBJS_PACKAGE;
+ }
+
+ public void dispose() {
+ }
+
+ // ---- Methods to compute the adornments flags ---------------------------------
+
+ private int computeJavaAdornmentFlags(IJavaElement element, int renderFlags) {
+ int flags = 0;
+ if (showOverlayIcons(renderFlags) && element instanceof IMember) {
+ try {
+ IMember member = (IMember) element;
+
+ if (element.getElementType() == IJavaElement.METHOD && ((IMethod) element).isConstructor())
+ flags |= JavaElementImageDescriptor.CONSTRUCTOR;
+
+ int modifiers = member.getFlags();
+ if (Flags.isAbstract(modifiers) && confirmAbstract(member))
+ flags |= JavaElementImageDescriptor.ABSTRACT;
+ if (Flags.isFinal(modifiers) || isInterfaceField(member))
+ flags |= JavaElementImageDescriptor.FINAL;
+ // if (Flags.isSynchronized(modifiers) && confirmSynchronized(member))
+ // flags |= JavaElementImageDescriptor.SYNCHRONIZED;
+ if (Flags.isStatic(modifiers) || isInterfaceField(member))
+ flags |= JavaElementImageDescriptor.STATIC;
+
+ // if (member.getElementType() == IJavaElement.TYPE) {
+ // if (JavaModelUtil.hasMainMethod((IType) member)) {
+ // flags |= JavaElementImageDescriptor.RUNNABLE;
+ // }
+ // }
+ } catch (JavaModelException e) {
+ // do nothing. Can't compute runnable adornment or get flags
+ }
+ }
+ return flags;
+ }
+
+ private static boolean confirmAbstract(IMember element) throws JavaModelException {
+ // never show the abstract symbol on interfaces or members in interfaces
+ if (element.getElementType() == IJavaElement.TYPE) {
+ return ((IType) element).isClass();
+ }
+ return element.getDeclaringType().isClass();
+ }
+
+ private static boolean isInterfaceField(IMember element) throws JavaModelException {
+ // always show the final && static symbol on interface fields
+ if (element.getElementType() == IJavaElement.FIELD) {
+ return element.getDeclaringType().isInterface();
+ }
+ return false;
+ }
+
+ private static boolean confirmSynchronized(IJavaElement member) {
+ // Synchronized types are allowed but meaningless.
+ return member.getElementType() != IJavaElement.TYPE;
+ }
+
+ public static ImageDescriptor getMethodImageDescriptor(boolean isInInterface, int flags) {
+ if (Flags.isPublic(flags) || isInInterface)
+ return PHPUiImages.DESC_MISC_PUBLIC;
+ if (Flags.isProtected(flags))
+ return PHPUiImages.DESC_MISC_PROTECTED;
+ if (Flags.isPrivate(flags))
+ return PHPUiImages.DESC_MISC_PRIVATE;
+
+ return PHPUiImages.DESC_MISC_DEFAULT;
+ }
+
+ public static ImageDescriptor getFieldImageDescriptor(boolean isInInterface, int flags) {
+ if (Flags.isPublic(flags) || isInInterface)
+ return PHPUiImages.DESC_FIELD_PUBLIC;
+ if (Flags.isProtected(flags))
+ return PHPUiImages.DESC_FIELD_PROTECTED;
+ if (Flags.isPrivate(flags))
+ return PHPUiImages.DESC_FIELD_PRIVATE;
+
+ return PHPUiImages.DESC_FIELD_DEFAULT;
+ }
+
+ public static ImageDescriptor getTypeImageDescriptor(boolean isInterface, boolean isInner, int flags) {
+ if (isInner) {
+ if (isInterface) {
+ return getInnerInterfaceImageDescriptor(flags);
+ } else {
+ return getInnerClassImageDescriptor(flags);
+ }
+ } else {
+ if (isInterface) {
+ return getInterfaceImageDescriptor(flags);
+ } else {
+ return getClassImageDescriptor(flags);
+ }
+ }
+ }
+
+ private static ImageDescriptor getClassImageDescriptor(int flags) {
+ if (Flags.isPublic(flags) || Flags.isProtected(flags) || Flags.isPrivate(flags))
+ return PHPUiImages.DESC_OBJS_CLASS;
+ else
+ return PHPUiImages.DESC_OBJS_CLASS_DEFAULT;
+ }
+
+ private static ImageDescriptor getInnerClassImageDescriptor(int flags) {
+ if (Flags.isPublic(flags))
+ return PHPUiImages.DESC_OBJS_INNER_CLASS_PUBLIC;
+ else if (Flags.isPrivate(flags))
+ return PHPUiImages.DESC_OBJS_INNER_CLASS_PRIVATE;
+ else if (Flags.isProtected(flags))
+ return PHPUiImages.DESC_OBJS_INNER_CLASS_PROTECTED;
+ else
+ return PHPUiImages.DESC_OBJS_INNER_CLASS_DEFAULT;
+ }
+
+ private static ImageDescriptor getInterfaceImageDescriptor(int flags) {
+ if (Flags.isPublic(flags) || Flags.isProtected(flags) || Flags.isPrivate(flags))
+ return PHPUiImages.DESC_OBJS_INTERFACE;
+ else
+ return PHPUiImages.DESC_OBJS_INTERFACE_DEFAULT;
+ }
+
+ private static ImageDescriptor getInnerInterfaceImageDescriptor(int flags) {
+ if (Flags.isPublic(flags))
+ return PHPUiImages.DESC_OBJS_INNER_INTERFACE_PUBLIC;
+ else if (Flags.isPrivate(flags))
+ return PHPUiImages.DESC_OBJS_INNER_INTERFACE_PRIVATE;
+ else if (Flags.isProtected(flags))
+ return PHPUiImages.DESC_OBJS_INNER_INTERFACE_PROTECTED;
+ else
+ return PHPUiImages.DESC_OBJS_INTERFACE_DEFAULT;
+ }
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/JavaElementLabels.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/JavaElementLabels.java
new file mode 100644
index 0000000..4e71612
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/JavaElementLabels.java
@@ -0,0 +1,765 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.ui.viewsupport;
+
+import net.sourceforge.phpdt.core.ICompilationUnit;
+import net.sourceforge.phpdt.core.IField;
+import net.sourceforge.phpdt.core.IJavaElement;
+import net.sourceforge.phpdt.core.IMethod;
+import net.sourceforge.phpdt.core.IPackageFragment;
+import net.sourceforge.phpdt.core.IPackageFragmentRoot;
+import net.sourceforge.phpdt.core.IType;
+import net.sourceforge.phpdt.core.JavaModelException;
+import net.sourceforge.phpdt.core.Signature;
+import net.sourceforge.phpdt.internal.corext.util.JavaModelUtil;
+import net.sourceforge.phpdt.internal.ui.PHPUIMessages;
+import net.sourceforge.phpdt.ui.PreferenceConstants;
+import net.sourceforge.phpeclipse.PHPeclipsePlugin;
+
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.IAdaptable;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.jface.preference.IPreferenceStore;
+import org.eclipse.ui.model.IWorkbenchAdapter;
+
+public class JavaElementLabels {
+
+ /**
+ * Method names contain parameter types.
+ * e.g. foo(int)
+ */
+ public final static int M_PARAMETER_TYPES = 1 << 0;
+
+ /**
+ * Method names contain parameter names.
+ * e.g. foo(index)
+ */
+ public final static int M_PARAMETER_NAMES = 1 << 1;
+
+ /**
+ * Method names contain thrown exceptions.
+ * e.g. foo throws IOException
+ */
+ public final static int M_EXCEPTIONS = 1 << 2;
+
+ /**
+ * Method names contain return type (appended)
+ * e.g. foo : int
+ */
+ public final static int M_APP_RETURNTYPE = 1 << 3;
+
+ /**
+ * Method names contain return type (appended)
+ * e.g. int foo
+ */
+ public final static int M_PRE_RETURNTYPE = 1 << 4;
+
+ /**
+ * Method names are fully qualified.
+ * e.g. java.util.Vector.size
+ */
+ public final static int M_FULLY_QUALIFIED = 1 << 5;
+
+ /**
+ * Method names are post qualified.
+ * e.g. size - java.util.Vector
+ */
+ public final static int M_POST_QUALIFIED = 1 << 6;
+
+ /**
+ * Initializer names are fully qualified.
+ * e.g. java.util.Vector.{ ... }
+ */
+ public final static int I_FULLY_QUALIFIED = 1 << 7;
+
+ /**
+ * Type names are post qualified.
+ * e.g. { ... } - java.util.Map
+ */
+ public final static int I_POST_QUALIFIED = 1 << 8;
+
+ /**
+ * Field names contain the declared type (appended)
+ * e.g. int fHello
+ */
+ public final static int F_APP_TYPE_SIGNATURE = 1 << 9;
+
+ /**
+ * Field names contain the declared type (prepended)
+ * e.g. fHello : int
+ */
+ public final static int F_PRE_TYPE_SIGNATURE = 1 << 10;
+
+ /**
+ * Fields names are fully qualified.
+ * e.g. java.lang.System.out
+ */
+ public final static int F_FULLY_QUALIFIED = 1 << 11;
+
+ /**
+ * Fields names are post qualified.
+ * e.g. out - java.lang.System
+ */
+ public final static int F_POST_QUALIFIED = 1 << 12;
+
+ /**
+ * Type names are fully qualified.
+ * e.g. java.util.Map.MapEntry
+ */
+ public final static int T_FULLY_QUALIFIED = 1 << 13;
+
+ /**
+ * Type names are type container qualified.
+ * e.g. Map.MapEntry
+ */
+ public final static int T_CONTAINER_QUALIFIED = 1 << 14;
+
+ /**
+ * Type names are post qualified.
+ * e.g. MapEntry - java.util.Map
+ */
+ public final static int T_POST_QUALIFIED = 1 << 15;
+
+ /**
+ * Declarations (import container / declarartion, package declarartion) are qualified.
+ * e.g. java.util.Vector.class/import container
+ */
+ public final static int D_QUALIFIED = 1 << 16;
+
+ /**
+ * Declarations (import container / declarartion, package declarartion) are post qualified.
+ * e.g. import container - java.util.Vector.class
+ */
+ public final static int D_POST_QUALIFIED = 1 << 17;
+
+ /**
+ * Class file names are fully qualified.
+ * e.g. java.util.Vector.class
+ */
+ public final static int CF_QUALIFIED = 1 << 18;
+
+ /**
+ * Class file names are post qualified.
+ * e.g. Vector.class - java.util
+ */
+ public final static int CF_POST_QUALIFIED = 1 << 19;
+
+ /**
+ * Compilation unit names are fully qualified.
+ * e.g. java.util.Vector.java
+ */
+ public final static int CU_QUALIFIED = 1 << 20;
+
+ /**
+ * Compilation unit names are post qualified.
+ * e.g. Vector.java - java.util
+ */
+ public final static int CU_POST_QUALIFIED = 1 << 21;
+
+ /**
+ * Package names are qualified.
+ * e.g. MyProject/src/java.util
+ */
+ public final static int P_QUALIFIED = 1 << 22;
+
+ /**
+ * Package names are post qualified.
+ * e.g. java.util - MyProject/src
+ */
+ public final static int P_POST_QUALIFIED = 1 << 23;
+
+ /**
+ * Package Fragment Roots contain variable name if from a variable.
+ * e.g. JRE_LIB - c:\java\lib\rt.jar
+ */
+ public final static int ROOT_VARIABLE = 1 << 24;
+
+ /**
+ * Package Fragment Roots contain the project name if not an archive (prepended).
+ * e.g. MyProject/src
+ */
+ public final static int ROOT_QUALIFIED = 1 << 25;
+
+ /**
+ * Package Fragment Roots contain the project name if not an archive (appended).
+ * e.g. src - MyProject
+ */
+ public final static int ROOT_POST_QUALIFIED = 1 << 26;
+
+ /**
+ * Add root path to all elements except Package Fragment Roots and Java projects.
+ * e.g. java.lang.Vector - c:\java\lib\rt.jar
+ * Option only applies to getElementLabel
+ */
+ public final static int APPEND_ROOT_PATH = 1 << 27;
+
+ /**
+ * Add root path to all elements except Package Fragment Roots and Java projects.
+ * e.g. java.lang.Vector - c:\java\lib\rt.jar
+ * Option only applies to getElementLabel
+ */
+ public final static int PREPEND_ROOT_PATH = 1 << 28;
+
+ /**
+ * Package names are compressed.
+ * e.g. o*.e*.search
+ */
+ public final static int P_COMPRESSED = 1 << 29;
+
+ /**
+ * Post qualify referenced package fragement roots. For example
+ * jdt.jar - org.eclipse.jdt.ui
if the jar is referenced
+ * from another project.
+ */
+ public final static int REFERENCED_ROOT_POST_QUALIFIED = 1 << 30;
+
+ /**
+ * Qualify all elements
+ */
+ public final static int ALL_FULLY_QUALIFIED =
+ F_FULLY_QUALIFIED
+ | M_FULLY_QUALIFIED
+ | I_FULLY_QUALIFIED
+ | T_FULLY_QUALIFIED
+ | D_QUALIFIED
+ | CF_QUALIFIED
+ | CU_QUALIFIED
+ | P_QUALIFIED
+ | ROOT_QUALIFIED;
+
+ /**
+ * Post qualify all elements
+ */
+ public final static int ALL_POST_QUALIFIED =
+ F_POST_QUALIFIED
+ | M_POST_QUALIFIED
+ | I_POST_QUALIFIED
+ | T_POST_QUALIFIED
+ | D_POST_QUALIFIED
+ | CF_POST_QUALIFIED
+ | CU_POST_QUALIFIED
+ | P_POST_QUALIFIED
+ | ROOT_POST_QUALIFIED;
+
+ /**
+ * Default options (M_PARAMETER_TYPES enabled)
+ */
+ public final static int ALL_DEFAULT = M_PARAMETER_TYPES;
+
+ /**
+ * Default qualify options (All except Root and Package)
+ */
+ public final static int DEFAULT_QUALIFIED =
+ F_FULLY_QUALIFIED | M_FULLY_QUALIFIED | I_FULLY_QUALIFIED | T_FULLY_QUALIFIED | D_QUALIFIED | CF_QUALIFIED | CU_QUALIFIED;
+
+ /**
+ * Default post qualify options (All except Root and Package)
+ */
+ public final static int DEFAULT_POST_QUALIFIED =
+ F_POST_QUALIFIED
+ | M_POST_QUALIFIED
+ | I_POST_QUALIFIED
+ | T_POST_QUALIFIED
+ | D_POST_QUALIFIED
+ | CF_POST_QUALIFIED
+ | CU_POST_QUALIFIED;
+
+ public final static String CONCAT_STRING = PHPUIMessages.getString("JavaElementLabels.concat_string"); // " - "; //$NON-NLS-1$
+ public final static String COMMA_STRING = PHPUIMessages.getString("JavaElementLabels.comma_string"); // ", "; //$NON-NLS-1$
+ public final static String DECL_STRING = PHPUIMessages.getString("JavaElementLabels.declseparator_string"); // " "; // use for return type //$NON-NLS-1$
+
+ /*
+ * Package name compression
+ */
+ private static String fgPkgNamePattern = ""; //$NON-NLS-1$
+ private static String fgPkgNamePrefix;
+ private static String fgPkgNamePostfix;
+ private static int fgPkgNameChars;
+ private static int fgPkgNameLength = -1;
+
+ private JavaElementLabels() {
+ }
+
+ private static boolean getFlag(int flags, int flag) {
+ return (flags & flag) != 0;
+ }
+
+ public static String getTextLabel(Object obj, int flags) {
+ if (obj instanceof IJavaElement) {
+ return getElementLabel((IJavaElement) obj, flags);
+ } else if (obj instanceof IAdaptable) {
+ IWorkbenchAdapter wbadapter = (IWorkbenchAdapter) ((IAdaptable) obj).getAdapter(IWorkbenchAdapter.class);
+ if (wbadapter != null) {
+ return wbadapter.getLabel(obj);
+ }
+ }
+ return ""; //$NON-NLS-1$
+ }
+
+ /**
+ * Returns the label for a Java element. Flags as defined above.
+ */
+ public static String getElementLabel(IJavaElement element, int flags) {
+ StringBuffer buf = new StringBuffer(60);
+ getElementLabel(element, flags, buf);
+ return buf.toString();
+ }
+
+ /**
+ * Returns the label for a Java element. Flags as defined above.
+ */
+ public static void getElementLabel(IJavaElement element, int flags, StringBuffer buf) {
+ int type = element.getElementType();
+ IPackageFragmentRoot root = null;
+
+ if (type != IJavaElement.JAVA_MODEL && type != IJavaElement.JAVA_PROJECT && type != IJavaElement.PACKAGE_FRAGMENT_ROOT)
+ root = JavaModelUtil.getPackageFragmentRoot(element);
+ if (root != null && getFlag(flags, PREPEND_ROOT_PATH)) {
+ getPackageFragmentRootLabel(root, ROOT_QUALIFIED, buf);
+ buf.append(CONCAT_STRING);
+ }
+
+ switch (type) {
+ case IJavaElement.METHOD :
+ getMethodLabel((IMethod) element, flags, buf);
+ break;
+ case IJavaElement.FIELD :
+ getFieldLabel((IField) element, flags, buf);
+ break;
+ // case IJavaElement.INITIALIZER:
+ // getInitializerLabel((IInitializer) element, flags, buf);
+ // break;
+ case IJavaElement.TYPE :
+ getTypeLabel((IType) element, flags, buf);
+ break;
+ // case IJavaElement.CLASS_FILE:
+ // getClassFileLabel((IClassFile) element, flags, buf);
+ // break;
+ case IJavaElement.COMPILATION_UNIT :
+ getCompilationUnitLabel((ICompilationUnit) element, flags, buf);
+ break;
+ case IJavaElement.PACKAGE_FRAGMENT :
+ getPackageFragmentLabel((IPackageFragment) element, flags, buf);
+ break;
+ case IJavaElement.PACKAGE_FRAGMENT_ROOT :
+ getPackageFragmentRootLabel((IPackageFragmentRoot) element, flags, buf);
+ break;
+ case IJavaElement.IMPORT_CONTAINER :
+ case IJavaElement.IMPORT_DECLARATION :
+ case IJavaElement.PACKAGE_DECLARATION :
+ getDeclararionLabel(element, flags, buf);
+ break;
+ case IJavaElement.JAVA_PROJECT :
+ case IJavaElement.JAVA_MODEL :
+ buf.append(element.getElementName());
+ break;
+ default :
+ buf.append(element.getElementName());
+ }
+
+ if (root != null && getFlag(flags, APPEND_ROOT_PATH)) {
+ buf.append(CONCAT_STRING);
+ getPackageFragmentRootLabel(root, ROOT_QUALIFIED, buf);
+ }
+ }
+
+ /**
+ * Appends the label for a method to a StringBuffer. Considers the M_* flags.
+ */
+ public static void getMethodLabel(IMethod method, int flags, StringBuffer buf) {
+ try {
+ // return type
+ if (getFlag(flags, M_PRE_RETURNTYPE) && method.exists() && !method.isConstructor()) {
+ buf.append(Signature.getSimpleName(Signature.toString(method.getReturnType())));
+ buf.append(' ');
+ }
+
+ // qualification
+ if (getFlag(flags, M_FULLY_QUALIFIED)) {
+ getTypeLabel(method.getDeclaringType(), T_FULLY_QUALIFIED | (flags & P_COMPRESSED), buf);
+ buf.append('.');
+ }
+
+ buf.append(method.getElementName());
+
+ // parameters
+ if (getFlag(flags, M_PARAMETER_TYPES | M_PARAMETER_NAMES)) {
+ buf.append('(');
+
+ String[] types = getFlag(flags, M_PARAMETER_TYPES) ? method.getParameterTypes() : null;
+ String[] names = (getFlag(flags, M_PARAMETER_NAMES) && method.exists()) ? method.getParameterNames() : null;
+ int nParams = types != null ? types.length : names.length;
+
+ for (int i = 0; i < nParams; i++) {
+ if (i > 0) {
+ buf.append(COMMA_STRING); //$NON-NLS-1$
+ }
+ if (types != null) {
+ buf.append(Signature.getSimpleName(Signature.toString(types[i])));
+ }
+ if (names != null) {
+ if (types != null) {
+ buf.append(' ');
+ }
+ buf.append(names[i]);
+ }
+ }
+ buf.append(')');
+ }
+
+ if (getFlag(flags, M_EXCEPTIONS) && method.exists()) {
+ String[] types = method.getExceptionTypes();
+ if (types.length > 0) {
+ buf.append(" throws "); //$NON-NLS-1$
+ for (int i = 0; i < types.length; i++) {
+ if (i > 0) {
+ buf.append(COMMA_STRING);
+ }
+ buf.append(Signature.getSimpleName(Signature.toString(types[i])));
+ }
+ }
+ }
+
+ if (getFlag(flags, M_APP_RETURNTYPE) && method.exists() && !method.isConstructor()) {
+ buf.append(DECL_STRING);
+ buf.append(Signature.getSimpleName(Signature.toString(method.getReturnType())));
+ }
+
+ // post qualification
+ if (getFlag(flags, M_POST_QUALIFIED)) {
+ buf.append(CONCAT_STRING);
+ getTypeLabel(method.getDeclaringType(), T_FULLY_QUALIFIED | (flags & P_COMPRESSED), buf);
+ }
+
+ } catch (JavaModelException e) {
+ PHPeclipsePlugin.log(e); // NotExistsException will not reach this point
+ }
+ }
+
+ /**
+ * Appends the label for a field to a StringBuffer. Considers the F_* flags.
+ */
+ public static void getFieldLabel(IField field, int flags, StringBuffer buf) {
+ try {
+ if (getFlag(flags, F_PRE_TYPE_SIGNATURE) && field.exists()) {
+ buf.append(Signature.toString(field.getTypeSignature()));
+ buf.append(' ');
+ }
+
+ // qualification
+ if (getFlag(flags, F_FULLY_QUALIFIED)) {
+ getTypeLabel(field.getDeclaringType(), T_FULLY_QUALIFIED | (flags & P_COMPRESSED), buf);
+ buf.append('.');
+ }
+ buf.append(field.getElementName());
+
+ if (getFlag(flags, F_APP_TYPE_SIGNATURE) && field.exists()) {
+ buf.append(DECL_STRING);
+ buf.append(Signature.toString(field.getTypeSignature()));
+ }
+
+ // post qualification
+ if (getFlag(flags, F_POST_QUALIFIED)) {
+ buf.append(CONCAT_STRING);
+ getTypeLabel(field.getDeclaringType(), T_FULLY_QUALIFIED | (flags & P_COMPRESSED), buf);
+ }
+
+ } catch (JavaModelException e) {
+ PHPeclipsePlugin.log(e); // NotExistsException will not reach this point
+ }
+ }
+
+ /**
+ * Appends the label for a initializer to a StringBuffer. Considers the I_* flags.
+ */
+ // public static void getInitializerLabel(IInitializer initializer, int flags, StringBuffer buf) {
+ // // qualification
+ // if (getFlag(flags, I_FULLY_QUALIFIED)) {
+ // getTypeLabel(initializer.getDeclaringType(), T_FULLY_QUALIFIED | (flags & P_COMPRESSED), buf);
+ // buf.append('.');
+ // }
+ // buf.append(JavaUIMessages.getString("JavaElementLabels.initializer")); //$NON-NLS-1$
+ //
+ // // post qualification
+ // if (getFlag(flags, I_POST_QUALIFIED)) {
+ // buf.append(CONCAT_STRING);
+ // getTypeLabel(initializer.getDeclaringType(), T_FULLY_QUALIFIED | (flags & P_COMPRESSED), buf);
+ // }
+ // }
+
+ /**
+ * Appends the label for a type to a StringBuffer. Considers the T_* flags.
+ */
+ public static void getTypeLabel(IType type, int flags, StringBuffer buf) {
+ if (getFlag(flags, T_FULLY_QUALIFIED)) {
+ if (type != null) { // jsurfer INSERT
+ IPackageFragment pack = type.getPackageFragment();
+ if (!pack.isDefaultPackage()) {
+ getPackageFragmentLabel(pack, (flags & P_COMPRESSED), buf);
+ buf.append('.');
+ }
+ buf.append(JavaModelUtil.getTypeQualifiedName(type));
+ } // jsurfer INSERT
+ } else if (getFlag(flags, T_CONTAINER_QUALIFIED)) {
+ buf.append(JavaModelUtil.getTypeQualifiedName(type));
+ } else {
+ buf.append(type.getElementName());
+ }
+ // post qualification
+ if (getFlag(flags, T_POST_QUALIFIED)) {
+ buf.append(CONCAT_STRING);
+ IType declaringType = type.getDeclaringType();
+ if (declaringType != null) {
+ getTypeLabel(declaringType, T_FULLY_QUALIFIED | (flags & P_COMPRESSED), buf);
+ } else {
+ getPackageFragmentLabel(type.getPackageFragment(), (flags & P_COMPRESSED), buf);
+ }
+ }
+ }
+
+ /**
+ * Appends the label for a declaration to a StringBuffer. Considers the D_* flags.
+ */
+ public static void getDeclararionLabel(IJavaElement declaration, int flags, StringBuffer buf) {
+ if (getFlag(flags, D_QUALIFIED)) {
+ IJavaElement openable = (IJavaElement) declaration.getOpenable();
+ if (openable != null) {
+ buf.append(getElementLabel(openable, CF_QUALIFIED | CU_QUALIFIED));
+ buf.append('/');
+ }
+ }
+ if (declaration.getElementType() == IJavaElement.IMPORT_CONTAINER) {
+ buf.append(PHPUIMessages.getString("JavaElementLabels.import_container")); //$NON-NLS-1$
+ } else {
+ buf.append(declaration.getElementName());
+ }
+ // post qualification
+ if (getFlag(flags, D_POST_QUALIFIED)) {
+ IJavaElement openable = (IJavaElement) declaration.getOpenable();
+ if (openable != null) {
+ buf.append(CONCAT_STRING);
+ buf.append(getElementLabel(openable, CF_QUALIFIED | CU_QUALIFIED));
+ }
+ }
+ }
+
+ /**
+ * Appends the label for a class file to a StringBuffer. Considers the CF_* flags.
+ */
+ // public static void getClassFileLabel(IClassFile classFile, int flags, StringBuffer buf) {
+ // if (getFlag(flags, CF_QUALIFIED)) {
+ // IPackageFragment pack= (IPackageFragment) classFile.getParent();
+ // if (!pack.isDefaultPackage()) {
+ // buf.append(pack.getElementName());
+ // buf.append('.');
+ // }
+ // }
+ // buf.append(classFile.getElementName());
+ //
+ // if (getFlag(flags, CF_POST_QUALIFIED)) {
+ // buf.append(CONCAT_STRING);
+ // getPackageFragmentLabel((IPackageFragment) classFile.getParent(), 0, buf);
+ // }
+ // }
+
+ /**
+ * Appends the label for a compilation unit to a StringBuffer. Considers the CU_* flags.
+ */
+ public static void getCompilationUnitLabel(ICompilationUnit cu, int flags, StringBuffer buf) {
+ if (getFlag(flags, CU_QUALIFIED)) {
+ IPackageFragment pack = (IPackageFragment) cu.getParent();
+ if (!pack.isDefaultPackage()) {
+ buf.append(pack.getElementName());
+ buf.append('.');
+ }
+ }
+ buf.append(cu.getElementName());
+
+ if (getFlag(flags, CU_POST_QUALIFIED)) {
+ buf.append(CONCAT_STRING);
+ getPackageFragmentLabel((IPackageFragment) cu.getParent(), 0, buf);
+ }
+ }
+
+ /**
+ * Appends the label for a package fragment to a StringBuffer. Considers the P_* flags.
+ */
+ public static void getPackageFragmentLabel(IPackageFragment pack, int flags, StringBuffer buf) {
+ if (getFlag(flags, P_QUALIFIED)) {
+ getPackageFragmentRootLabel((IPackageFragmentRoot) pack.getParent(), ROOT_QUALIFIED, buf);
+ buf.append('/');
+ }
+ refreshPackageNamePattern();
+ if (pack.isDefaultPackage()) {
+ buf.append(PHPUIMessages.getString("JavaElementLabels.default_package")); //$NON-NLS-1$
+ } else if (getFlag(flags, P_COMPRESSED) && fgPkgNameLength >= 0) {
+ String name = pack.getElementName();
+ int start = 0;
+ int dot = name.indexOf('.', start);
+ while (dot > 0) {
+ if (dot - start > fgPkgNameLength - 1) {
+ buf.append(fgPkgNamePrefix);
+ if (fgPkgNameChars > 0)
+ buf.append(name.substring(start, Math.min(start + fgPkgNameChars, dot)));
+ buf.append(fgPkgNamePostfix);
+ } else
+ buf.append(name.substring(start, dot + 1));
+ start = dot + 1;
+ dot = name.indexOf('.', start);
+ }
+ buf.append(name.substring(start));
+ } else {
+ buf.append(pack.getElementName());
+ }
+ if (getFlag(flags, P_POST_QUALIFIED)) {
+ buf.append(CONCAT_STRING);
+ getPackageFragmentRootLabel((IPackageFragmentRoot) pack.getParent(), ROOT_QUALIFIED, buf);
+ }
+ }
+
+ /**
+ * Appends the label for a package fragment root to a StringBuffer. Considers the ROOT_* flags.
+ */
+ public static void getPackageFragmentRootLabel(IPackageFragmentRoot root, int flags, StringBuffer buf) {
+ if (root.isArchive())
+ getArchiveLabel(root, flags, buf);
+ else
+ getFolderLabel(root, flags, buf);
+ }
+
+ private static void getArchiveLabel(IPackageFragmentRoot root, int flags, StringBuffer buf) {
+ // Handle variables different
+ if (getFlag(flags, ROOT_VARIABLE) && getVariableLabel(root, flags, buf))
+ return;
+ boolean external = root.isExternal();
+ if (external)
+ getExternalArchiveLabel(root, flags, buf);
+ else
+ getInternalArchiveLabel(root, flags, buf);
+ }
+
+ private static boolean getVariableLabel(IPackageFragmentRoot root, int flags, StringBuffer buf) {
+ // try {
+ // IClasspathEntry rawEntry= root.getRawClasspathEntry();
+ // if (rawEntry != null) {
+ // if (rawEntry.getEntryKind() == IClasspathEntry.CPE_VARIABLE) {
+ // buf.append(rawEntry.getPath().makeRelative());
+ // buf.append(CONCAT_STRING);
+ // if (root.isExternal())
+ // buf.append(root.getPath().toOSString());
+ // else
+ // buf.append(root.getPath().makeRelative().toString());
+ // return true;
+ // }
+ // }
+ // } catch (JavaModelException e) {
+ // PHPeclipsePlugin.log(e); // problems with class path
+ // }
+ return false;
+ }
+
+ private static void getExternalArchiveLabel(IPackageFragmentRoot root, int flags, StringBuffer buf) {
+ IPath path = root.getPath();
+ if (getFlag(flags, REFERENCED_ROOT_POST_QUALIFIED)) {
+ int segements = path.segmentCount();
+ if (segements > 0) {
+ buf.append(path.segment(segements - 1));
+ if (segements > 1 || path.getDevice() != null) {
+ buf.append(CONCAT_STRING);
+ buf.append(path.removeLastSegments(1).toOSString());
+ }
+ } else {
+ buf.append(path.toOSString());
+ }
+ } else {
+ buf.append(path.toOSString());
+ }
+ }
+
+ private static void getInternalArchiveLabel(IPackageFragmentRoot root, int flags, StringBuffer buf) {
+ IResource resource = root.getResource();
+ boolean rootQualified = getFlag(flags, ROOT_QUALIFIED);
+ boolean referencedQualified =
+ getFlag(flags, REFERENCED_ROOT_POST_QUALIFIED) && JavaModelUtil.isReferenced(root) && resource != null;
+ if (rootQualified) {
+ buf.append(root.getPath().makeRelative().toString());
+ } else {
+ buf.append(root.getElementName());
+ if (referencedQualified) {
+ buf.append(CONCAT_STRING);
+ buf.append(resource.getParent().getFullPath().makeRelative().toString());
+ } else if (getFlag(flags, ROOT_POST_QUALIFIED)) {
+ buf.append(CONCAT_STRING);
+ buf.append(root.getParent().getPath().makeRelative().toString());
+ }
+ }
+ }
+
+ private static void getFolderLabel(IPackageFragmentRoot root, int flags, StringBuffer buf) {
+ IResource resource = root.getResource();
+ boolean rootQualified = getFlag(flags, ROOT_QUALIFIED);
+ boolean referencedQualified =
+ getFlag(flags, REFERENCED_ROOT_POST_QUALIFIED) && JavaModelUtil.isReferenced(root) && resource != null;
+ if (rootQualified) {
+ buf.append(root.getPath().makeRelative().toString());
+ } else {
+ if (resource != null)
+ buf.append(resource.getProjectRelativePath().toString());
+ else
+ buf.append(root.getElementName());
+ if (referencedQualified) {
+ buf.append(CONCAT_STRING);
+ buf.append(resource.getProject().getName());
+ } else if (getFlag(flags, ROOT_POST_QUALIFIED)) {
+ buf.append(CONCAT_STRING);
+ buf.append(root.getParent().getElementName());
+ }
+ }
+ }
+
+ private static void refreshPackageNamePattern() {
+ String pattern = getPkgNamePatternForPackagesView();
+ if (pattern.equals(fgPkgNamePattern))
+ return;
+ else if (pattern.equals("")) { //$NON-NLS-1$
+ fgPkgNamePattern = ""; //$NON-NLS-1$
+ fgPkgNameLength = -1;
+ return;
+ }
+ fgPkgNamePattern = pattern;
+ int i = 0;
+ fgPkgNameChars = 0;
+ fgPkgNamePrefix = ""; //$NON-NLS-1$
+ fgPkgNamePostfix = ""; //$NON-NLS-1$
+ while (i < pattern.length()) {
+ char ch = pattern.charAt(i);
+ if (Character.isDigit(ch)) {
+ fgPkgNameChars = ch - 48;
+ if (i > 0)
+ fgPkgNamePrefix = pattern.substring(0, i);
+ if (i >= 0)
+ fgPkgNamePostfix = pattern.substring(i + 1);
+ fgPkgNameLength = fgPkgNamePrefix.length() + fgPkgNameChars + fgPkgNamePostfix.length();
+ return;
+ }
+ i++;
+ }
+ fgPkgNamePrefix = pattern;
+ fgPkgNameLength = pattern.length();
+ }
+
+ private static String getPkgNamePatternForPackagesView() {
+ IPreferenceStore store = PreferenceConstants.getPreferenceStore();
+ if (!store.getBoolean(PreferenceConstants.APPEARANCE_COMPRESS_PACKAGE_NAMES))
+ return ""; //$NON-NLS-1$
+ return store.getString(PreferenceConstants.APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW);
+ }
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/JavaUILabelProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/JavaUILabelProvider.java
new file mode 100644
index 0000000..eac133f
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/JavaUILabelProvider.java
@@ -0,0 +1,210 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.ui.viewsupport;
+
+import java.util.ArrayList;
+
+import org.eclipse.core.resources.IStorage;
+
+import org.eclipse.swt.graphics.Image;
+
+import org.eclipse.jface.viewers.ILabelDecorator;
+import org.eclipse.jface.viewers.ILabelProviderListener;
+import org.eclipse.jface.viewers.LabelProvider;
+
+public class JavaUILabelProvider extends LabelProvider {
+
+ protected JavaElementImageProvider fImageLabelProvider;
+ protected StorageLabelProvider fStorageLabelProvider;
+
+ protected ArrayList fLabelDecorators;
+
+ private int fImageFlags;
+ private int fTextFlags;
+
+ /**
+ * Creates a new label provider with default flags.
+ */
+ public JavaUILabelProvider() {
+ this(JavaElementLabels.M_PARAMETER_TYPES, JavaElementImageProvider.OVERLAY_ICONS);
+ }
+
+ /**
+ * @param textFlags Flags defined in JavaElementLabels
.
+ * @param imageFlags Flags defined in JavaElementImageProvider
.
+ */
+ public JavaUILabelProvider(int textFlags, int imageFlags) {
+ fImageLabelProvider= new JavaElementImageProvider();
+ fLabelDecorators= null;
+
+ fStorageLabelProvider= new StorageLabelProvider();
+ fImageFlags= imageFlags;
+ fTextFlags= textFlags;
+ }
+
+ /**
+ * Adds a decorator to the label provider
+ */
+ public void addLabelDecorator(ILabelDecorator decorator) {
+ if (fLabelDecorators == null) {
+ fLabelDecorators= new ArrayList(2);
+ }
+ fLabelDecorators.add(decorator);
+ }
+
+ /**
+ * Sets the textFlags.
+ * @param textFlags The textFlags to set
+ */
+ public final void setTextFlags(int textFlags) {
+ fTextFlags= textFlags;
+ }
+
+ /**
+ * Sets the imageFlags
+ * @param imageFlags The imageFlags to set
+ */
+ public final void setImageFlags(int imageFlags) {
+ fImageFlags= imageFlags;
+ }
+
+ /**
+ * Gets the image flags.
+ * Can be overwriten by super classes.
+ * @return Returns a int
+ */
+ public final int getImageFlags() {
+ return fImageFlags;
+ }
+
+ /**
+ * Gets the text flags.
+ * @return Returns a int
+ */
+ public final int getTextFlags() {
+ return fTextFlags;
+ }
+
+ /**
+ * Evaluates the image flags for a element.
+ * Can be overwriten by super classes.
+ * @return Returns a int
+ */
+ protected int evaluateImageFlags(Object element) {
+ return getImageFlags();
+ }
+
+ /**
+ * Evaluates the text flags for a element. Can be overwriten by super classes.
+ * @return Returns a int
+ */
+ protected int evaluateTextFlags(Object element) {
+ return getTextFlags();
+ }
+
+
+ /* (non-Javadoc)
+ * @see ILabelProvider#getImage
+ */
+ public Image getImage(Object element) {
+ Image result= fImageLabelProvider.getImageLabel(element, evaluateImageFlags(element));
+ if (result == null && (element instanceof IStorage)) {
+ result= fStorageLabelProvider.getImage(element);
+ }
+ if (fLabelDecorators != null && result != null) {
+ for (int i= 0; i < fLabelDecorators.size(); i++) {
+ ILabelDecorator decorator= (ILabelDecorator) fLabelDecorators.get(i);
+ result= decorator.decorateImage(result, element);
+ }
+ }
+ return result;
+ }
+
+ /* (non-Javadoc)
+ * @see ILabelProvider#getText
+ */
+ public String getText(Object element) {
+ String result= JavaElementLabels.getTextLabel(element, evaluateTextFlags(element));
+ if (result.length() == 0 && (element instanceof IStorage)) {
+ result= fStorageLabelProvider.getText(element);
+ }
+ if (fLabelDecorators != null && result.length() > 0) {
+ for (int i= 0; i < fLabelDecorators.size(); i++) {
+ ILabelDecorator decorator= (ILabelDecorator) fLabelDecorators.get(i);
+ result= decorator.decorateText(result, element);
+ }
+ }
+ return result;
+ }
+
+ /* (non-Javadoc)
+ * @see IBaseLabelProvider#dispose
+ */
+ public void dispose() {
+ if (fLabelDecorators != null) {
+ for (int i= 0; i < fLabelDecorators.size(); i++) {
+ ILabelDecorator decorator= (ILabelDecorator) fLabelDecorators.get(i);
+ decorator.dispose();
+ }
+ fLabelDecorators= null;
+ }
+ fStorageLabelProvider.dispose();
+ fImageLabelProvider.dispose();
+ }
+
+ /* (non-Javadoc)
+ * @see IBaseLabelProvider#addListener(ILabelProviderListener)
+ */
+ public void addListener(ILabelProviderListener listener) {
+ if (fLabelDecorators != null) {
+ for (int i= 0; i < fLabelDecorators.size(); i++) {
+ ILabelDecorator decorator= (ILabelDecorator) fLabelDecorators.get(i);
+ decorator.addListener(listener);
+ }
+ }
+ super.addListener(listener);
+ }
+
+ /* (non-Javadoc)
+ * @see IBaseLabelProvider#isLabelProperty(Object, String)
+ */
+ public boolean isLabelProperty(Object element, String property) {
+ return true;
+ }
+
+ /* (non-Javadoc)
+ * @see IBaseLabelProvider#removeListener(ILabelProviderListener)
+ */
+ public void removeListener(ILabelProviderListener listener) {
+ if (fLabelDecorators != null) {
+ for (int i= 0; i < fLabelDecorators.size(); i++) {
+ ILabelDecorator decorator= (ILabelDecorator) fLabelDecorators.get(i);
+ decorator.removeListener(listener);
+ }
+ }
+ super.removeListener(listener);
+ }
+
+ public static ILabelDecorator[] getDecorators(boolean errortick, ILabelDecorator extra) {
+ if (errortick) {
+ if (extra == null) {
+ return new ILabelDecorator[] {};
+ } else {
+ return new ILabelDecorator[] { extra };
+ }
+ }
+ if (extra != null) {
+ return new ILabelDecorator[] { extra };
+ }
+ return null;
+ }
+
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/MemberFilter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/MemberFilter.java
new file mode 100644
index 0000000..8e8bad2
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/MemberFilter.java
@@ -0,0 +1,100 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.ui.viewsupport;
+
+import net.sourceforge.phpdt.core.Flags;
+import net.sourceforge.phpdt.core.IField;
+import net.sourceforge.phpdt.core.IJavaElement;
+import net.sourceforge.phpdt.core.IMember;
+import net.sourceforge.phpdt.core.IType;
+import net.sourceforge.phpdt.core.JavaModelException;
+
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.jface.viewers.ViewerFilter;
+
+/**
+ * Filter for the methods viewer.
+ * Changing a filter property does not trigger a refiltering of the viewer
+ */
+public class MemberFilter extends ViewerFilter {
+
+ public static final int FILTER_NONPUBLIC= 1;
+ public static final int FILTER_STATIC= 2;
+ public static final int FILTER_FIELDS= 4;
+
+ private int fFilterProperties;
+
+ /**
+ * Modifies filter and add a property to filter for
+ */
+ public final void addFilter(int filter) {
+ fFilterProperties |= filter;
+ }
+ /**
+ * Modifies filter and remove a property to filter for
+ */
+ public final void removeFilter(int filter) {
+ fFilterProperties &= (-1 ^ filter);
+ }
+ /**
+ * Tests if a property is filtered
+ */
+ public final boolean hasFilter(int filter) {
+ return (fFilterProperties & filter) != 0;
+ }
+
+ /*
+ * @see ViewerFilter@isFilterProperty
+ */
+ public boolean isFilterProperty(Object element, Object property) {
+ return false;
+ }
+ /*
+ * @see ViewerFilter@select
+ */
+ public boolean select(Viewer viewer, Object parentElement, Object element) {
+ try {
+ if (hasFilter(FILTER_FIELDS) && element instanceof IField) {
+ return false;
+ }
+ if (element instanceof IMember) {
+ IMember member= (IMember)element;
+ if (member.getElementName().startsWith("<")) { // filter out IProblemChangedListener
.
+ */
+ public void removeListener(IProblemChangedListener listener) {
+ fListeners.remove(listener);
+ if (fListeners.isEmpty()) {
+ PHPeclipsePlugin.getWorkspace().removeResourceChangeListener(this);
+ PHPeclipsePlugin.getDefault().getCompilationUnitDocumentProvider().removeGlobalAnnotationModelListener(this);
+ }
+ }
+
+ private void fireChanges(final IResource[] changes, final boolean isMarkerChange) {
+ Display display= SWTUtil.getStandardDisplay();
+ if (display != null && !display.isDisposed()) {
+ display.asyncExec(new Runnable() {
+ public void run() {
+ Object[] listeners= fListeners.getListeners();
+ for (int i= 0; i < listeners.length; i++) {
+ IProblemChangedListener curr= (IProblemChangedListener) listeners[i];
+ curr.problemsChanged(changes, isMarkerChange);
+ }
+ }
+ });
+ }
+ }
+
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/StatusBarUpdater.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/StatusBarUpdater.java
new file mode 100644
index 0000000..ec9f214
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/StatusBarUpdater.java
@@ -0,0 +1,81 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.ui.viewsupport;
+
+
+import net.sourceforge.phpdt.core.IJavaElement;
+import net.sourceforge.phpdt.internal.ui.PHPUIMessages;
+
+import org.eclipse.core.resources.IContainer;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.jface.action.IStatusLineManager;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.ISelectionChangedListener;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.viewers.SelectionChangedEvent;
+
+/**
+ * Add the StatusBarUpdater
to your ViewPart to have the statusbar
+ * describing the selected elements.
+ */
+public class StatusBarUpdater implements ISelectionChangedListener {
+
+ private final int LABEL_FLAGS= JavaElementLabels.DEFAULT_QUALIFIED | JavaElementLabels.ROOT_POST_QUALIFIED | JavaElementLabels.APPEND_ROOT_PATH |
+ JavaElementLabels.M_PARAMETER_TYPES | JavaElementLabels.M_PARAMETER_NAMES | JavaElementLabels.M_APP_RETURNTYPE | JavaElementLabels.M_EXCEPTIONS |
+ JavaElementLabels.F_APP_TYPE_SIGNATURE;
+
+ private IStatusLineManager fStatusLineManager;
+
+ public StatusBarUpdater(IStatusLineManager statusLineManager) {
+ fStatusLineManager= statusLineManager;
+ }
+
+ /*
+ * @see ISelectionChangedListener#selectionChanged
+ */
+ public void selectionChanged(SelectionChangedEvent event) {
+ String statusBarMessage= formatMessage(event.getSelection());
+ fStatusLineManager.setMessage(statusBarMessage);
+ }
+
+
+ protected String formatMessage(ISelection sel) {
+ if (sel instanceof IStructuredSelection && !sel.isEmpty()) {
+ IStructuredSelection selection= (IStructuredSelection) sel;
+
+ int nElements= selection.size();
+ if (nElements > 1) {
+ return PHPUIMessages.getFormattedString("StatusBarUpdater.num_elements_selected", String.valueOf(nElements)); //$NON-NLS-1$
+ } else {
+ Object elem= selection.getFirstElement();
+ if (elem instanceof IJavaElement) {
+ return formatJavaElementMessage((IJavaElement) elem);
+ } else if (elem instanceof IResource) {
+ return formatResourceMessage((IResource) elem);
+ }
+ }
+ }
+ return ""; //$NON-NLS-1$
+ }
+
+ private String formatJavaElementMessage(IJavaElement element) {
+ return JavaElementLabels.getElementLabel(element, LABEL_FLAGS);
+ }
+
+ private String formatResourceMessage(IResource element) {
+ IContainer parent= element.getParent();
+ if (parent != null && parent.getType() != IResource.ROOT)
+ return element.getName() + JavaElementLabels.CONCAT_STRING + parent.getFullPath().makeRelative().toString();
+ else
+ return element.getName();
+ }
+
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/StorageLabelProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/StorageLabelProvider.java
new file mode 100644
index 0000000..7ba4287
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/viewsupport/StorageLabelProvider.java
@@ -0,0 +1,129 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.internal.ui.viewsupport;
+
+
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+import org.eclipse.core.resources.IStorage;
+import org.eclipse.core.runtime.IPath;
+
+import org.eclipse.swt.graphics.Image;
+
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.jface.viewers.LabelProvider;
+
+import org.eclipse.ui.IEditorRegistry;
+import org.eclipse.ui.IFileEditorMapping;
+import org.eclipse.ui.PlatformUI;
+
+/**
+ * Standard label provider for IStorage objects.
+ * Use this class when you want to present IStorage objects in a viewer.
+ */
+public class StorageLabelProvider extends LabelProvider {
+
+ private IEditorRegistry fEditorRegistry= PlatformUI.getWorkbench().getEditorRegistry();
+ private Map fJarImageMap= new HashMap(10);
+ private Image fDefaultImage;
+
+ /* (non-Javadoc)
+ * @see ILabelProvider#getImage
+ */
+ public Image getImage(Object element) {
+ if (element instanceof IStorage)
+ return getImageForJarEntry((IStorage)element);
+
+ return super.getImage(element);
+ }
+
+ /* (non-Javadoc)
+ * @see ILabelProvider#getText
+ */
+ public String getText(Object element) {
+ if (element instanceof IStorage)
+ return ((IStorage)element).getName();
+
+ return super.getText(element);
+ }
+
+ /* (non-Javadoc)
+ *
+ * @see IBaseLabelProvider#dispose
+ */
+ public void dispose() {
+ if (fJarImageMap != null) {
+ Iterator each= fJarImageMap.values().iterator();
+ while (each.hasNext()) {
+ Image image= (Image)each.next();
+ image.dispose();
+ }
+ fJarImageMap= null;
+ }
+ if (fDefaultImage != null)
+ fDefaultImage.dispose();
+ fDefaultImage= null;
+ }
+
+ /*
+ * Gets and caches an image for a JarEntryFile.
+ * The image for a JarEntryFile is retrieved from the EditorRegistry.
+ */
+ private Image getImageForJarEntry(IStorage element) {
+ if (fJarImageMap == null)
+ return getDefaultImage();
+
+ if (element == null || element.getName() == null)
+ return getDefaultImage();
+
+ // Try to find icon for full name
+ String name= element.getName();
+ Image image= (Image)fJarImageMap.get(name);
+ if (image != null)
+ return image;
+ IFileEditorMapping[] mappings= fEditorRegistry.getFileEditorMappings();
+ int i= 0;
+ while (i < mappings.length) {
+ if (mappings[i].getLabel().equals(name))
+ break;
+ i++;
+ }
+ String key= name;
+ if (i == mappings.length) {
+ // Try to find icon for extension
+ IPath path= element.getFullPath();
+ if (path == null)
+ return getDefaultImage();
+ key= path.getFileExtension();
+ if (key == null)
+ return getDefaultImage();
+ image= (Image)fJarImageMap.get(key);
+ if (image != null)
+ return image;
+ }
+
+ // Get the image from the editor registry
+ ImageDescriptor desc= fEditorRegistry.getImageDescriptor(name);
+ image= desc.createImage();
+
+ fJarImageMap.put(key, image);
+
+ return image;
+ }
+
+ private Image getDefaultImage() {
+ if (fDefaultImage == null)
+ fDefaultImage= fEditorRegistry.getImageDescriptor((String)null).createImage();
+ return fDefaultImage;
+ }
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/IWorkingCopyManager.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/IWorkingCopyManager.java
new file mode 100644
index 0000000..bab2691
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/IWorkingCopyManager.java
@@ -0,0 +1,77 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.ui;
+
+import org.eclipse.core.runtime.CoreException;
+
+import org.eclipse.ui.IEditorInput;
+
+import net.sourceforge.phpdt.core.ICompilationUnit;
+
+/**
+ * Interface for accessing working copies of ICompilationUnit
+ * objects. The original compilation unit is only given indirectly by means
+ * of an IEditorInput
. The life cycle is as follows:
+ *
+ *
+ * connect
creates and remembers a working copy of the
+ * compilation unit which is encoded in the given editor inputgetWorkingCopy
returns the working copy remembered on
+ * connect
disconnect
destroys the working copy remembered on
+ * connect
null
if the
+ * input does not encode an editor input, or if there is no remembered working
+ * copy for this compilation unit
+ */
+ ICompilationUnit getWorkingCopy(IEditorInput input);
+
+ /**
+ * Shuts down this working copy manager. All working copies still remembered
+ * by this manager are destroyed.
+ */
+ void shutdown();
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/IWorkingCopyManagerExtension.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/IWorkingCopyManagerExtension.java
new file mode 100644
index 0000000..541f630
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/IWorkingCopyManagerExtension.java
@@ -0,0 +1,43 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+
+package net.sourceforge.phpdt.ui;
+
+import org.eclipse.ui.IEditorInput;
+
+import net.sourceforge.phpdt.core.ICompilationUnit;
+
+/**
+ * Extension interface for IWorkingCopyManager
.
+ * @since 2.1
+ */
+public interface IWorkingCopyManagerExtension {
+
+ /**
+ * Sets the given working copy for the given editor input. If the given editor input
+ * is not connected to this working copy manager, this call has no effect. true
if the content provider returns working
+ * copy elements; otherwise false
is returned.
+ *
+ * @return whether working copy elements are provided.
+ */
+ public boolean providesWorkingCopies();
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/JavaElementImageDescriptor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/JavaElementImageDescriptor.java
new file mode 100644
index 0000000..4cf8183
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/JavaElementImageDescriptor.java
@@ -0,0 +1,237 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.ui;
+
+
+import org.eclipse.swt.graphics.ImageData;
+import org.eclipse.swt.graphics.Point;
+
+import org.eclipse.jface.resource.CompositeImageDescriptor;
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.jface.util.Assert;
+
+import net.sourceforge.phpdt.internal.ui.PHPUiImages;
+
+/**
+ * A JavaImageDescriptor consists of a base image and several adornments. The adornments
+ * are computed according to the flags either passed during creation or set via the method
+ * setAdornments
.
+ *
+ * setAdornments
+ * for valid values.
+ * @param size the size of the resulting image
+ * @see #setAdornments(int)
+ */
+ public JavaElementImageDescriptor(ImageDescriptor baseImage, int flags, Point size) {
+ fBaseImage= baseImage;
+ Assert.isNotNull(fBaseImage);
+ fFlags= flags;
+ Assert.isTrue(fFlags >= 0);
+ fSize= size;
+ Assert.isNotNull(fSize);
+ }
+
+ /**
+ * Sets the descriptors adornments. Valid values are: ABSTRACT
, FINAL
,
+ * SYNCHRONIZED
, ,
RUNNABLE,
WARNING,
+ *
ERROR,
OVERRIDDES,
IClassFileIMPLEMENTS
, CONSTRUCTOR
,
+ * or any combination of those.
+ *
+ * @param adornments the image descritpors adornments
+ */
+ public void setAdornments(int adornments) {
+ Assert.isTrue(adornments >= 0);
+ fFlags= adornments;
+ }
+
+ /**
+ * Returns the current adornments.
+ *
+ * @return the current adornments
+ */
+ public int getAdronments() {
+ return fFlags;
+ }
+
+ /**
+ * Sets the size of the image created by calling createImage()
.
+ *
+ * @param size the size of the image returned from calling createImage()
+ * @see ImageDescriptor#createImage()
+ */
+ public void setImageSize(Point size) {
+ Assert.isNotNull(size);
+ Assert.isTrue(size.x >= 0 && size.y >= 0);
+ fSize= size;
+ }
+
+ /**
+ * Returns the size of the image created by calling createImage()
.
+ *
+ * @return the size of the image created by calling createImage()
+ * @see ImageDescriptor#createImage()
+ */
+ public Point getImageSize() {
+ return new Point(fSize.x, fSize.y);
+ }
+
+ /* (non-Javadoc)
+ * Method declared in CompositeImageDescriptor
+ */
+ protected Point getSize() {
+ return fSize;
+ }
+
+ /* (non-Javadoc)
+ * Method declared on Object.
+ */
+ public boolean equals(Object object) {
+ if (object == null || !JavaElementImageDescriptor.class.equals(object.getClass()))
+ return false;
+
+ JavaElementImageDescriptor other= (JavaElementImageDescriptor)object;
+ return (fBaseImage.equals(other.fBaseImage) && fFlags == other.fFlags && fSize.equals(other.fSize));
+ }
+
+ /* (non-Javadoc)
+ * Method declared on Object.
+ */
+ public int hashCode() {
+ return fBaseImage.hashCode() | fFlags | fSize.hashCode();
+ }
+
+ /* (non-Javadoc)
+ * Method declared in CompositeImageDescriptor
+ */
+ protected void drawCompositeImage(int width, int height) {
+ ImageData bg;
+ if ((bg= fBaseImage.getImageData()) == null)
+ bg= DEFAULT_IMAGE_DATA;
+
+ drawImage(bg, 0, 0);
+ drawTopRight();
+ drawBottomRight();
+ drawBottomLeft();
+ }
+
+ private void drawTopRight() {
+ int x= getSize().x;
+ ImageData data= null;
+ if ((fFlags & ABSTRACT) != 0) {
+ data= PHPUiImages.DESC_OVR_ABSTRACT.getImageData();
+ x-= data.width;
+ drawImage(data, x, 0);
+ }
+ if ((fFlags & CONSTRUCTOR) != 0) {
+ data= PHPUiImages.DESC_OVR_CONSTRUCTOR.getImageData();
+ x-= data.width;
+ drawImage(data, x, 0);
+ }
+ if ((fFlags & FINAL) != 0) {
+ data= PHPUiImages.DESC_OVR_FINAL.getImageData();
+ x-= data.width;
+ drawImage(data, x, 0);
+ }
+ if ((fFlags & STATIC) != 0) {
+ data= PHPUiImages.DESC_OVR_STATIC.getImageData();
+ x-= data.width;
+ drawImage(data, x, 0);
+ }
+ }
+
+ private void drawBottomRight() {
+ Point size= getSize();
+ int x= size.x;
+ ImageData data= null;
+ if ((fFlags & OVERRIDES) != 0) {
+ data= PHPUiImages.DESC_OVR_OVERRIDES.getImageData();
+ x-= data.width;
+ drawImage(data, x, size.y - data.height);
+ }
+ if ((fFlags & IMPLEMENTS) != 0) {
+ data= PHPUiImages.DESC_OVR_IMPLEMENTS.getImageData();
+ x-= data.width;
+ drawImage(data, x, size.y - data.height);
+ }
+ if ((fFlags & SYNCHRONIZED) != 0) {
+ data= PHPUiImages.DESC_OVR_SYNCH.getImageData();
+ x-= data.width;
+ drawImage(data, x, size.y - data.height);
+ }
+ if ((fFlags & RUNNABLE) != 0) {
+ data= PHPUiImages.DESC_OVR_RUN.getImageData();
+ x-= data.width;
+ drawImage(data, x, size.y - data.height);
+ }
+ }
+
+ private void drawBottomLeft() {
+ Point size= getSize();
+ int x= 0;
+ ImageData data= null;
+ if ((fFlags & ERROR) != 0) {
+ data= PHPUiImages.DESC_OVR_ERROR.getImageData();
+ drawImage(data, x, size.y - data.height);
+ x+= data.width;
+ }
+ if ((fFlags & WARNING) != 0) {
+ data= PHPUiImages.DESC_OVR_WARNING.getImageData();
+ drawImage(data, x, size.y - data.height);
+ x+= data.width;
+ }
+ }
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/JavaElementLabelProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/JavaElementLabelProvider.java
new file mode 100644
index 0000000..4067228
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/JavaElementLabelProvider.java
@@ -0,0 +1,268 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.ui;
+
+import net.sourceforge.phpdt.internal.ui.viewsupport.JavaElementImageProvider;
+import net.sourceforge.phpdt.internal.ui.viewsupport.JavaElementLabels;
+import net.sourceforge.phpdt.internal.ui.viewsupport.StorageLabelProvider;
+
+import org.eclipse.core.resources.IStorage;
+import org.eclipse.jface.viewers.LabelProvider;
+import org.eclipse.swt.graphics.Image;
+
+
+
+/**
+ * Standard label provider for Java elements.
+ * Use this class when you want to present the Java elements in a viewer.
+ * IWorkbenchAdapter
of the element.
+ * 0
) indicating that the label should show
+ * the basic images only.
+ */
+ public final static int SHOW_BASICS= 0x000;
+
+
+ /**
+ * Constant indicating the default label rendering.
+ * Currently the default is equivalent to
+ * SHOW_PARAMETERS | SHOW_OVERLAY_ICONS
.
+ */
+ public final static int SHOW_DEFAULT= new Integer(SHOW_PARAMETERS | SHOW_OVERLAY_ICONS).intValue();
+
+ private JavaElementImageProvider fImageLabelProvider;
+
+ private StorageLabelProvider fStorageLabelProvider;
+ private int fFlags;
+ private int fImageFlags;
+ private int fTextFlags;
+
+ /**
+ * Creates a new label provider with SHOW_DEFAULT
flag.
+ *
+ * @see #SHOW_DEFAULT
+ * @since 2.0
+ */
+ public JavaElementLabelProvider() {
+ this(SHOW_DEFAULT);
+ }
+
+ /**
+ * Creates a new label provider.
+ *
+ * @param flags the initial options; a bitwise OR of SHOW_*
constants
+ */
+ public JavaElementLabelProvider(int flags) {
+ fImageLabelProvider= new JavaElementImageProvider();
+ fStorageLabelProvider= new StorageLabelProvider();
+ fFlags= flags;
+ updateImageProviderFlags();
+ updateTextProviderFlags();
+ }
+
+ private boolean getFlag( int flag) {
+ return (fFlags & flag) != 0;
+ }
+
+ /**
+ * Turns on the rendering options specified in the given flags.
+ *
+ * @param flags the options; a bitwise OR of SHOW_*
constants
+ */
+ public void turnOn(int flags) {
+ fFlags |= flags;
+ updateImageProviderFlags();
+ updateTextProviderFlags();
+ }
+
+ /**
+ * Turns off the rendering options specified in the given flags.
+ *
+ * @param flags the initial options; a bitwise OR of SHOW_*
constants
+ */
+ public void turnOff(int flags) {
+ fFlags &= (~flags);
+ updateImageProviderFlags();
+ updateTextProviderFlags();
+ }
+
+ private void updateImageProviderFlags() {
+ fImageFlags= 0;
+ if (getFlag(SHOW_OVERLAY_ICONS)) {
+ fImageFlags |= JavaElementImageProvider.OVERLAY_ICONS;
+ }
+ if (getFlag(SHOW_SMALL_ICONS)) {
+ fImageFlags |= JavaElementImageProvider.SMALL_ICONS;
+ }
+ }
+
+ private void updateTextProviderFlags() {
+ fTextFlags= 0;
+ if (getFlag(SHOW_RETURN_TYPE)) {
+ fTextFlags |= JavaElementLabels.M_APP_RETURNTYPE;
+ }
+ if (getFlag(SHOW_PARAMETERS)) {
+ fTextFlags |= JavaElementLabels.M_PARAMETER_TYPES;
+ }
+ if (getFlag(SHOW_CONTAINER)) {
+ fTextFlags |= JavaElementLabels.P_POST_QUALIFIED | JavaElementLabels.T_POST_QUALIFIED | JavaElementLabels.CF_POST_QUALIFIED | JavaElementLabels.CU_POST_QUALIFIED | JavaElementLabels.M_POST_QUALIFIED | JavaElementLabels.F_POST_QUALIFIED;
+ }
+ if (getFlag(SHOW_POSTIFIX_QUALIFICATION)) {
+ fTextFlags |= (JavaElementLabels.T_POST_QUALIFIED | JavaElementLabels.CF_POST_QUALIFIED | JavaElementLabels.CU_POST_QUALIFIED);
+ } else if (getFlag(SHOW_CONTAINER_QUALIFICATION)) {
+ fTextFlags |=(JavaElementLabels.T_FULLY_QUALIFIED | JavaElementLabels.CF_QUALIFIED | JavaElementLabels.CU_QUALIFIED);
+ }
+ if (getFlag(SHOW_TYPE)) {
+ fTextFlags |= JavaElementLabels.F_APP_TYPE_SIGNATURE;
+ }
+ if (getFlag(SHOW_ROOT)) {
+ fTextFlags |= JavaElementLabels.APPEND_ROOT_PATH;
+ }
+ if (getFlag(SHOW_VARIABLE)) {
+ fTextFlags |= JavaElementLabels.ROOT_VARIABLE;
+ }
+ if (getFlag(SHOW_QUALIFIED)) {
+ fTextFlags |= (JavaElementLabels.F_FULLY_QUALIFIED | JavaElementLabels.M_FULLY_QUALIFIED | JavaElementLabels.I_FULLY_QUALIFIED
+ | JavaElementLabels.T_FULLY_QUALIFIED | JavaElementLabels.D_QUALIFIED | JavaElementLabels.CF_QUALIFIED | JavaElementLabels.CU_QUALIFIED);
+ }
+ if (getFlag(SHOW_POST_QUALIFIED)) {
+ fTextFlags |= (JavaElementLabels.F_POST_QUALIFIED | JavaElementLabels.M_POST_QUALIFIED | JavaElementLabels.I_POST_QUALIFIED
+ | JavaElementLabels.T_POST_QUALIFIED | JavaElementLabels.D_POST_QUALIFIED | JavaElementLabels.CF_POST_QUALIFIED | JavaElementLabels.CU_POST_QUALIFIED);
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see ILabelProvider#getImage
+ */
+ public Image getImage(Object element) {
+ Image result= fImageLabelProvider.getImageLabel(element, fImageFlags);
+ if (result != null) {
+ return result;
+ }
+
+ if (element instanceof IStorage)
+ return fStorageLabelProvider.getImage(element);
+
+ return result;
+ }
+
+ /* (non-Javadoc)
+ * @see ILabelProvider#getText
+ */
+ public String getText(Object element) {
+ String text= JavaElementLabels.getTextLabel(element, fTextFlags);
+ if (text.length() > 0) {
+ return text;
+ }
+
+ if (element instanceof IStorage)
+ return fStorageLabelProvider.getText(element);
+
+ return text;
+ }
+
+ /* (non-Javadoc)
+ *
+ * @see IBaseLabelProvider#dispose
+ */
+ public void dispose() {
+ fStorageLabelProvider.dispose();
+ fImageLabelProvider.dispose();
+ }
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/JavaElementSorter.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/JavaElementSorter.java
new file mode 100644
index 0000000..95bcc5e
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/JavaElementSorter.java
@@ -0,0 +1,278 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.ui;
+
+import java.text.Collator;
+
+import net.sourceforge.phpdt.core.Flags;
+import net.sourceforge.phpdt.core.IField;
+import net.sourceforge.phpdt.core.IJavaElement;
+import net.sourceforge.phpdt.core.IMethod;
+import net.sourceforge.phpdt.core.IPackageFragment;
+import net.sourceforge.phpdt.core.IPackageFragmentRoot;
+import net.sourceforge.phpdt.core.JavaModelException;
+import net.sourceforge.phpdt.core.Signature;
+import net.sourceforge.phpdt.internal.ui.preferences.MembersOrderPreferenceCache;
+import net.sourceforge.phpeclipse.PHPeclipsePlugin;
+
+import org.eclipse.core.resources.IContainer;
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IStorage;
+import org.eclipse.core.runtime.IAdaptable;
+import org.eclipse.jface.viewers.ContentViewer;
+import org.eclipse.jface.viewers.IBaseLabelProvider;
+import org.eclipse.jface.viewers.ILabelProvider;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.jface.viewers.ViewerSorter;
+import org.eclipse.ui.model.IWorkbenchAdapter;
+
+
+/**
+ * Sorter for Java elements. Ordered by element category, then by element name.
+ * Package fragment roots are sorted as ordered on the classpath.
+ *
+ * "org.eclipse.jdt.ui"
).
+ * This class provides static methods for:
+ *
+ *
+ * "org.eclipse.jdt.ui"
).
+ */
+// public static final String ID_PLUGIN= "org.eclipse.jdt.ui"; //$NON-NLS-1$
+
+ /**
+ * The id of the Java perspective
+ * (value "org.eclipse.jdt.ui.JavaPerspective"
).
+ */
+// public static final String ID_PERSPECTIVE= "org.eclipse.jdt.ui.JavaPerspective"; //$NON-NLS-1$
+
+ /**
+ * The id of the Java hierarchy perspective
+ * (value "org.eclipse.jdt.ui.JavaHierarchyPerspective"
).
+ */
+// public static final String ID_HIERARCHYPERSPECTIVE= "org.eclipse.jdt.ui.JavaHierarchyPerspective"; //$NON-NLS-1$
+
+ /**
+ * The id of the Java action set
+ * (value "org.eclipse.jdt.ui.JavaActionSet"
).
+ */
+// public static final String ID_ACTION_SET= "org.eclipse.jdt.ui.JavaActionSet"; //$NON-NLS-1$
+
+ /**
+ * The id of the Java Element Creation action set
+ * (value "org.eclipse.jdt.ui.JavaElementCreationActionSet"
).
+ *
+ * @since 2.0
+ */
+// public static final String ID_ELEMENT_CREATION_ACTION_SET= "org.eclipse.jdt.ui.JavaElementCreationActionSet"; //$NON-NLS-1$
+
+ /**
+ * The id of the Java Coding action set
+ * (value "org.eclipse.jdt.ui.CodingActionSet"
).
+ *
+ * @since 2.0
+ */
+// public static final String ID_CODING_ACTION_SET= "org.eclipse.jdt.ui.CodingActionSet"; //$NON-NLS-1$
+
+ /**
+ * The id of the Java action set for open actions
+ * (value "org.eclipse.jdt.ui.A_OpenActionSet"
).
+ *
+ * @since 2.0
+ */
+// public static final String ID_OPEN_ACTION_SET= "org.eclipse.jdt.ui.A_OpenActionSet"; //$NON-NLS-1$
+
+ /**
+ * The id of the Java Search action set
+ * (value org.eclipse.jdt.ui.SearchActionSet"
).
+ *
+ * @since 2.0
+ */
+// public static final String ID_SEARCH_ACTION_SET= "org.eclipse.jdt.ui.SearchActionSet"; //$NON-NLS-1$
+
+ /**
+ * The editor part id of the editor that presents Java compilation units
+ * (value "org.eclipse.jdt.ui.CompilationUnitEditor"
).
+ */
+// public static final String ID_CU_EDITOR= "net.sourceforge.phpdt.ui.PHPUnitEditor"; //$NON-NLS-1$
+
+ /**
+ * The editor part id of the editor that presents Java binary class files
+ * (value "org.eclipse.jdt.ui.ClassFileEditor"
).
+ */
+// public static final String ID_CF_EDITOR= "org.eclipse.jdt.ui.ClassFileEditor"; //$NON-NLS-1$
+
+ /**
+ * The editor part id of the code snippet editor
+ * (value "org.eclipse.jdt.ui.SnippetEditor"
).
+ */
+// public static final String ID_SNIPPET_EDITOR= "org.eclipse.jdt.ui.SnippetEditor"; //$NON-NLS-1$
+
+ /**
+ * The view part id of the Packages view
+ * (value "org.eclipse.jdt.ui.PackageExplorer"
).
+ * IWorkbenchPage.findView
or
+ * showView
, the returned IViewPart
+ * can be safely cast to an IPackagesViewPart
.
+ * "org.eclipse.jdt.ui.TypeHierarchy"
).
+ * IWorkbenchPage.findView
or
+ * showView
, the returned IViewPart
+ * can be safely cast to an ITypeHierarchyViewPart
.
+ * "org.eclipse.jdt.ui.JavaBrowsingPerspective"
).
+ *
+ * @since 2.0
+ */
+// public static String ID_BROWSING_PERSPECTIVE= "org.eclipse.jdt.ui.JavaBrowsingPerspective"; //$NON-NLS-1$
+
+ /**
+ * The view part id of the Java Browsing Projects view
+ * (value "org.eclipse.jdt.ui.ProjectsView"
).
+ *
+ * @since 2.0
+ */
+// public static String ID_PROJECTS_VIEW= "org.eclipse.jdt.ui.ProjectsView"; //$NON-NLS-1$
+
+ /**
+ * The view part id of the Java Browsing Packages view
+ * (value "org.eclipse.jdt.ui.PackagesView"
).
+ *
+ * @since 2.0
+ */
+// public static String ID_PACKAGES_VIEW= "org.eclipse.jdt.ui.PackagesView"; //$NON-NLS-1$
+
+ /**
+ * The view part id of the Java Browsing Types view
+ * (value "org.eclipse.jdt.ui.TypesView"
).
+ *
+ * @since 2.0
+ */
+// public static String ID_TYPES_VIEW= "org.eclipse.jdt.ui.TypesView"; //$NON-NLS-1$
+
+ /**
+ * The view part id of the Java Browsing Members view
+ * (value "org.eclipse.jdt.ui.MembersView"
).
+ *
+ * @since 2.0
+ */
+// public static String ID_MEMBERS_VIEW= "org.eclipse.jdt.ui.MembersView"; //$NON-NLS-1$
+
+ /**
+ * The class org.eclipse.debug.core.model.IProcess allows attaching
+ * String properties to processes. The Java UI contributes a property
+ * page for IProcess that will show the contents of the property
+ * with this key.
+ * The intent of this property is to show the command line a process
+ * was launched with.
+ * @deprecated
+ */
+// public final static String ATTR_CMDLINE= "org.eclipse.jdt.ui.launcher.cmdLine"; //$NON-NLS-1$
+
+ /**
+ * Returns the shared images for the Java UI.
+ *
+ * @return the shared images manager
+ */
+ public static ISharedImages getSharedImages() {
+ if (fgSharedImages == null)
+ fgSharedImages= new SharedImages();
+
+ return fgSharedImages;
+ }
+
+ /**
+ * Creates a selection dialog that lists all packages of the given Java project.
+ * The caller is responsible for opening the dialog with Window.open
,
+ * and subsequently extracting the selected package (of type
+ * IPackageFragment
) via SelectionDialog.getResult
.
+ *
+ * @param parent the parent shell of the dialog to be created
+ * @param project the Java project
+ * @param style flags defining the style of the dialog; the valid flags are:
+ * IJavaElementSearchConstants.CONSIDER_BINARIES
, indicating that
+ * packages from binary package fragment roots should be included in addition
+ * to those from source package fragment roots;
+ * IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS
, indicating that
+ * packages from required projects should be included as well.
+ * @param filter the initial pattern to filter the set of packages. For example "com" shows
+ * all packages starting with "com". The meta character '?' representing any character and
+ * '*' representing any string are supported. Clients can pass an empty string if no filtering
+ * is required.
+ * @return a new selection dialog
+ * @exception JavaModelException if the selection dialog could not be opened
+ *
+ * @since 2.0
+ */
+// public static SelectionDialog createPackageDialog(Shell parent, IJavaProject project, int style, String filter) throws JavaModelException {
+// Assert.isTrue((style | IJavaElementSearchConstants.CONSIDER_BINARIES | IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS) ==
+// (IJavaElementSearchConstants.CONSIDER_BINARIES | IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS));
+//
+// IPackageFragmentRoot[] roots= null;
+// if ((style & IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS) != 0) {
+// roots= project.getAllPackageFragmentRoots();
+// } else {
+// roots= project.getPackageFragmentRoots();
+// }
+//
+// List consideredRoots= null;
+// if ((style & IJavaElementSearchConstants.CONSIDER_BINARIES) != 0) {
+// consideredRoots= Arrays.asList(roots);
+// } else {
+// consideredRoots= new ArrayList(roots.length);
+// for (int i= 0; i < roots.length; i++) {
+// IPackageFragmentRoot root= roots[i];
+// if (root.getKind() != IPackageFragmentRoot.K_BINARY)
+// consideredRoots.add(root);
+//
+// }
+// }
+//
+// int flags= JavaElementLabelProvider.SHOW_DEFAULT;
+// if (consideredRoots.size() > 1)
+// flags= flags | JavaElementLabelProvider.SHOW_ROOT;
+//
+// List packages= new ArrayList();
+// Iterator iter= consideredRoots.iterator();
+// while(iter.hasNext()) {
+// IPackageFragmentRoot root= (IPackageFragmentRoot)iter.next();
+// packages.addAll(Arrays.asList(root.getChildren()));
+// }
+// ElementListSelectionDialog dialog= new ElementListSelectionDialog(parent, new JavaElementLabelProvider(flags));
+// dialog.setIgnoreCase(false);
+// dialog.setElements(packages.toArray()); // XXX inefficient
+// dialog.setFilter(filter);
+// return dialog;
+// }
+
+ /**
+ * Creates a selection dialog that lists all packages of the given Java project.
+ * The caller is responsible for opening the dialog with Window.open
,
+ * and subsequently extracting the selected package (of type
+ * IPackageFragment
) via SelectionDialog.getResult
.
+ *
+ * @param parent the parent shell of the dialog to be created
+ * @param project the Java project
+ * @param style flags defining the style of the dialog; the valid flags are:
+ * IJavaElementSearchConstants.CONSIDER_BINARIES
, indicating that
+ * packages from binary package fragment roots should be included in addition
+ * to those from source package fragment roots;
+ * IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS
, indicating that
+ * packages from required projects should be included as well.
+ * @return a new selection dialog
+ * @exception JavaModelException if the selection dialog could not be opened
+ */
+// public static SelectionDialog createPackageDialog(Shell parent, IJavaProject project, int style) throws JavaModelException {
+// return createPackageDialog(parent, project, style, ""); //$NON-NLS-1$
+// }
+
+ /**
+ * Creates a selection dialog that lists all packages under the given package
+ * fragment root.
+ * The caller is responsible for opening the dialog with Window.open
,
+ * and subsequently extracting the selected package (of type
+ * IPackageFragment
) via SelectionDialog.getResult
.
+ *
+ * @param parent the parent shell of the dialog to be created
+ * @param root the package fragment root
+ * @param filter the initial pattern to filter the set of packages. For example "com" shows
+ * all packages starting with "com". The meta character '?' representing any character and
+ * '*' representing any string are supported. Clients can pass an empty string if no filtering
+ * is required.
+ * @return a new selection dialog
+ * @exception JavaModelException if the selection dialog could not be opened
+ *
+ * @since 2.0
+ */
+// public static SelectionDialog createPackageDialog(Shell parent, IPackageFragmentRoot root, String filter) throws JavaModelException {
+// ElementListSelectionDialog dialog= new ElementListSelectionDialog(parent, new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT));
+// dialog.setIgnoreCase(false);
+// dialog.setElements(root.getChildren());
+// dialog.setFilter(filter);
+// return dialog;
+// }
+
+ /**
+ * Creates a selection dialog that lists all packages under the given package
+ * fragment root.
+ * The caller is responsible for opening the dialog with Window.open
,
+ * and subsequently extracting the selected package (of type
+ * IPackageFragment
) via SelectionDialog.getResult
.
+ *
+ * @param parent the parent shell of the dialog to be created
+ * @param root the package fragment root
+ * @return a new selection dialog
+ * @exception JavaModelException if the selection dialog could not be opened
+ */
+// public static SelectionDialog createPackageDialog(Shell parent, IPackageFragmentRoot root) throws JavaModelException {
+// return createPackageDialog(parent, root, ""); //$NON-NLS-1$
+// }
+
+ /**
+ * Creates a selection dialog that lists all types in the given scope.
+ * The caller is responsible for opening the dialog with Window.open
,
+ * and subsequently extracting the selected type(s) (of type
+ * IType
) via SelectionDialog.getResult
.
+ *
+ * @param parent the parent shell of the dialog to be created
+ * @param context the runnable context used to show progress when the dialog
+ * is being populated
+ * @param scope the scope that limits which types are included
+ * @param style flags defining the style of the dialog; the only valid values are
+ * IJavaElementSearchConstants.CONSIDER_CLASSES
,
+ * CONSIDER_INTERFACES
, or their bitwise OR
+ * (equivalent to CONSIDER_TYPES
)
+ * @param multipleSelection true
if multiple selection is allowed
+ * @param filter the initial pattern to filter the set of types. For example "Abstract" shows
+ * all types starting with "abstract". The meta character '?' representing any character and
+ * '*' representing any string are supported. Clients can pass an empty string if no filtering
+ * is required.
+ * @exception JavaModelException if the selection dialog could not be opened
+ *
+ * @since 2.0
+ */
+// public static SelectionDialog createTypeDialog(Shell parent, IRunnableContext context, IJavaSearchScope scope, int style, boolean multipleSelection, String filter) throws JavaModelException {
+// int elementKinds= 0;
+// if (style == IJavaElementSearchConstants.CONSIDER_TYPES) {
+// elementKinds= IJavaSearchConstants.TYPE;
+// } else if (style == IJavaElementSearchConstants.CONSIDER_INTERFACES) {
+// elementKinds= IJavaSearchConstants.INTERFACE;
+// } else if (style == IJavaElementSearchConstants.CONSIDER_CLASSES) {
+// elementKinds= IJavaSearchConstants.CLASS;
+// } else {
+// Assert.isTrue(false, "illegal style"); //$NON-NLS-1$
+// }
+// if (multipleSelection) {
+// MultiTypeSelectionDialog dialog= new MultiTypeSelectionDialog(parent, context, elementKinds, scope);
+// dialog.setMessage(JavaUIMessages.getString("JavaUI.defaultDialogMessage")); //$NON-NLS-1$
+// dialog.setFilter(filter);
+// return dialog;
+// } else {
+// TypeSelectionDialog dialog= new TypeSelectionDialog(parent, context, elementKinds, scope);
+// dialog.setMessage(JavaUIMessages.getString("JavaUI.defaultDialogMessage")); //$NON-NLS-1$
+// dialog.setFilter(filter);
+// return dialog;
+// }
+// }
+
+ /**
+ * Creates a selection dialog that lists all types in the given scope.
+ * The caller is responsible for opening the dialog with Window.open
,
+ * and subsequently extracting the selected type(s) (of type
+ * IType
) via SelectionDialog.getResult
.
+ *
+ * @param parent the parent shell of the dialog to be created
+ * @param context the runnable context used to show progress when the dialog
+ * is being populated
+ * @param scope the scope that limits which types are included
+ * @param style flags defining the style of the dialog; the only valid values are
+ * IJavaElementSearchConstants.CONSIDER_CLASSES
,
+ * CONSIDER_INTERFACES
, or their bitwise OR
+ * (equivalent to CONSIDER_TYPES
)
+ * @param multipleSelection true
if multiple selection is allowed
+ * @return a new selection dialog
+ * @exception JavaModelException if the selection dialog could not be opened
+ */
+// public static SelectionDialog createTypeDialog(Shell parent, IRunnableContext context, IJavaSearchScope scope, int style, boolean multipleSelection) throws JavaModelException {
+// return createTypeDialog(parent, context, scope, style, multipleSelection, "");//$NON-NLS-1$
+// }
+
+ /**
+ * Creates a selection dialog that lists all types in the given scope containing
+ * a standard main
method.
+ * The caller is responsible for opening the dialog with Window.open
,
+ * and subsequently extracting the selected type(s) (of type
+ * IType
) via SelectionDialog.getResult
.
+ *
+ * @param parent the parent shell of the dialog to be created
+ * @param context the runnable context used to show progress when the dialog
+ * is being populated
+ * @param scope the scope that limits which types are included
+ * @param style flags defining the style of the dialog; the only valid values are
+ * IJavaElementSearchConstants.CONSIDER_BINARIES
,
+ * CONSIDER_EXTERNAL_JARS
, or their bitwise OR, or 0
+ * @param multipleSelection true
if multiple selection is allowed
+ * @param filter the initial pattern to filter the set of types containg a main method. For
+ * example "App" shows all types starting with "app". The meta character '?' representing
+ * any character and '*' representing any string are supported. Clients can pass an empty
+ * string if no filtering is required.
+ * @return a new selection dialog
+ *
+ * @since 2.0
+ */
+// public static SelectionDialog createMainTypeDialog(Shell parent, IRunnableContext context, IJavaSearchScope scope, int style, boolean multipleSelection, String filter) {
+// if (multipleSelection) {
+// MultiMainTypeSelectionDialog dialog= new MultiMainTypeSelectionDialog(parent, context, scope, style);
+// dialog.setFilter(filter);
+// return dialog;
+// } else {
+// MainTypeSelectionDialog dialog= new MainTypeSelectionDialog(parent, context, scope, style);
+// dialog.setFilter(filter);
+// return dialog;
+// }
+// }
+
+ /**
+ * Creates a selection dialog that lists all types in the given scope containing
+ * a standard main
method.
+ * The caller is responsible for opening the dialog with Window.open
,
+ * and subsequently extracting the selected type(s) (of type
+ * IType
) via SelectionDialog.getResult
.
+ *
+ * @param parent the parent shell of the dialog to be created
+ * @param context the runnable context used to show progress when the dialog
+ * is being populated
+ * @param scope the scope that limits which types are included
+ * @param style flags defining the style of the dialog; the only valid values are
+ * IJavaElementSearchConstants.CONSIDER_BINARIES
,
+ * CONSIDER_EXTERNAL_JARS
, or their bitwise OR, or 0
+ * @param multipleSelection true
if multiple selection is allowed
+ * @return a new selection dialog
+ */
+// public static SelectionDialog createMainTypeDialog(Shell parent, IRunnableContext context, IJavaSearchScope scope, int style, boolean multipleSelection) {
+// return createMainTypeDialog(parent, context, scope, style, multipleSelection, "");//$NON-NLS-1$
+// }
+
+ /**
+ * Creates a selection dialog that lists all types in the given project.
+ * The caller is responsible for opening the dialog with Window.open
,
+ * and subsequently extracting the selected type(s) (of type
+ * IType
) via SelectionDialog.getResult
.
+ *
+ * @param parent the parent shell of the dialog to be created
+ * @param context the runnable context used to show progress when the dialog
+ * is being populated
+ * @param project the Java project
+ * @param style flags defining the style of the dialog; the only valid values are
+ * IJavaElementSearchConstants.CONSIDER_CLASSES
,
+ * CONSIDER_INTERFACES
, or their bitwise OR
+ * (equivalent to CONSIDER_TYPES
)
+ * @param multipleSelection true
if multiple selection is allowed
+ * @return a new selection dialog
+ * @exception JavaModelException if the selection dialog could not be opened
+ */
+// public static SelectionDialog createTypeDialog(Shell parent, IRunnableContext context, IProject project, int style, boolean multipleSelection) throws JavaModelException {
+// IJavaSearchScope scope= SearchEngine.createJavaSearchScope(new IJavaProject[] { JavaCore.create(project) });
+// return createTypeDialog(parent, context, scope, style, multipleSelection);
+// }
+
+ /**
+ * Opens a Java editor on the given Java element. The element can be a compilation unit
+ * or class file. If there already is an open Java editor for the given element, it is returned.
+ *
+ * @param element the input element; either a compilation unit
+ * (ICompilationUnit
) or a class file (revealInEditor(IEditorPart, IJavaElement)
instead
+ */
+// public static void revealInEditor(IEditorPart part, ISourceReference element) {
+// if (element instanceof IJavaElement)
+// revealInEditor(part, (IJavaElement) element);
+// }
+
+ /**
+ * Reveals the given java element in the given editor. If the element is not an instance
+ * of ISourceReference
this method result in a NOP. If it is a source
+ * reference no checking is done if the editor displays a compilation unit or class file that
+ * contains the source reference element. The editor simply reveals the source range
+ * denoted by the given element.
+ *
+ * @param part the editor displaying a compilation unit or class file
+ * @param element the element to be revealed
+ *
+ * @since 2.0
+ */
+// public static void revealInEditor(IEditorPart part, IJavaElement element) {
+// EditorUtility.revealInEditor(part, element);
+// }
+
+ /**
+ * Returns the working copy manager for the Java UI plug-in.
+ *
+ * @return the working copy manager for the Java UI plug-in
+ */
+ public static IWorkingCopyManager getWorkingCopyManager() {
+ return PHPeclipsePlugin.getDefault().getWorkingCopyManager();
+ }
+
+ /**
+ * Answers the shared working copies currently registered for the Java plug-in.
+ * Note that the returned array can include working copies that are
+ * not on the class path of a Java project.
+ *
+ * @return the list of shared working copies
+ *
+ * @see org.eclipse.jdt.core.JavaCore#getSharedWorkingCopies(org.eclipse.jdt.core.IBufferFactory)
+ * @since 2.0
+ */
+ public static IWorkingCopy[] getSharedWorkingCopies() {
+ return PHPCore.getSharedWorkingCopies(getBufferFactory());
+ }
+
+ /**
+ * Answers the shared working copies that are on the class path of a Java
+ * project currently registered for the Java plug-in.
+ *
+ *
+ * @return the list of shared working copies
+ *
+ * @see #getSharedWorkingCopies()
+ * @since 2.1
+ */
+// public static IWorkingCopy[] getSharedWorkingCopiesOnClasspath() {
+// IWorkingCopy[] wcs= getSharedWorkingCopies();
+// List result= new ArrayList(wcs.length);
+// for (int i = 0; i < wcs.length; i++) {
+// IWorkingCopy wc= wcs[i];
+// if (wc instanceof IJavaElement) {
+// IJavaElement je= (IJavaElement)wc;
+// if (je.getJavaProject().isOnClasspath(je)) {
+// result.add(wc);
+// }
+// }
+// }
+// return (IWorkingCopy[])result.toArray(new IWorkingCopy[result.size()]);
+// }
+
+ /**
+ * Returns the BufferFactory for the Java UI plug-in.
+ *
+ * @return the BufferFactory for the Java UI plug-in
+ *
+ * @see org.eclipse.jdt.core.IBufferFactory
+ * @since 2.0
+ */
+ public static IBufferFactory getBufferFactory() {
+ PHPDocumentProvider provider= PHPeclipsePlugin.getDefault().getCompilationUnitDocumentProvider();
+ if (provider != null)
+ return provider.getBufferFactory();
+ return null;
+ }
+
+ /**
+ * Returns the DocumentProvider used for Java compilation units.
+ *
+ * @return the DocumentProvider for Java compilation units.
+ *
+ * @see IDocumentProvider
+ * @since 2.0
+ */
+ public static IDocumentProvider getDocumentProvider() {
+ return PHPeclipsePlugin.getDefault().getCompilationUnitDocumentProvider();
+ }
+
+ /**
+ * Sets the Javadoc location for an archive with the given path.
+ *
+ * @param archivePath the path of the library; this can be an workspace path
+ * or an external path in case of an external library.
+ * @param url The Javadoc location to set. This location should contain index.html and
+ * a file 'package-list'. null
clears the current documentation
+ * location.
+ *
+ * @since 2.0
+ */
+// public static void setLibraryJavadocLocation(IPath archivePath, URL url) {
+// JavaDocLocations.setLibraryJavadocLocation(archivePath, url);
+// }
+
+ /**
+ * Returns the Javadoc location for an archive or null
if no
+ * location is available.
+ *
+ * @param archivePath the path of the library. This can be an workspace path
+ * or an external path in case of an external library.
+ *
+ * @since 2.0
+ */
+// public static URL getLibraryJavadocLocation(IPath archivePath) {
+// return JavaDocLocations.getLibraryJavadocLocation(archivePath);
+// }
+
+ /**
+ * Sets the Javadoc location for a Java project. This location is used for
+ * all types located in the project's source folders.
+ *
+ * @param project the project
+ * @param url The Javadoc location to set. This location should contain index.html and
+ * a file 'package-list'. null
clears the current documentation
+ * location.
+ *
+ * @since 2.1
+ */
+// public static void setProjectJavadocLocation(IJavaProject project, URL url) {
+// JavaDocLocations.setProjectJavadocLocation(project, url);
+// }
+
+ /**
+ * Returns the Javadoc location for a Java project or null
if no
+ * location is available. This location is used for all types located in the project's
+ * source folders.
+ *
+ * @param project the project
+ *
+ * @since 2.1
+ */
+// public static URL getProjectJavadocLocation(IJavaProject project) {
+// return JavaDocLocations.getProjectJavadocLocation(project);
+// }
+
+ /**
+ * Returns the Javadoc base URL for an element. The base location contains the
+ * index file. This location doesn't have to exist. Returns
+ * null
if no javadoc location has been attached to the
+ * element's library or project. Example of a returned URL is http://www.
+ * junit. org/junit/javadoc.
+ *
+ * @param The element for which the doc URL is requested.
+ *
+ * @since 2.0
+ */
+// public static URL getJavadocBaseLocation(IJavaElement element) throws JavaModelException {
+// return JavaDocLocations.getJavadocBaseLocation(element);
+// }
+
+ /**
+ * Returns the Javadoc URL for an element. Example of a returned URL is
+ * http://www.junit.org/junit/javadoc/junit/extensions/TestSetup.html.
+ * This returned location doesn't have to exist. Returns null
+ * if no javadoc location has been attached to the element's library or
+ * project.
+ *
+ * @param The element for which the doc URL is requested.
+ * @param includeAnchor If set, the URL contains an anchor for member references:
+ * http://www.junit.org/junit/javadoc/junit/extensions/TestSetup.html#run(junit.framework.TestResult). Note
+ * that this involves type resolving and is a more expensive call than without anchor.
+ *
+ * @since 2.0
+ */
+// public static URL getJavadocLocation(IJavaElement element, boolean includeAnchor) throws JavaModelException {
+// return JavaDocLocations.getJavadocLocation(element, includeAnchor);
+// }
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/OverrideIndicatorLabelDecorator.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/OverrideIndicatorLabelDecorator.java
new file mode 100644
index 0000000..895ee73
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/OverrideIndicatorLabelDecorator.java
@@ -0,0 +1,193 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.ui;
+
+import net.sourceforge.phpdt.core.Flags;
+import net.sourceforge.phpdt.core.IMethod;
+import net.sourceforge.phpdt.core.IType;
+import net.sourceforge.phpdt.core.JavaModelException;
+import net.sourceforge.phpdt.internal.corext.util.JavaModelUtil;
+import net.sourceforge.phpdt.internal.ui.PHPUiImages;
+import net.sourceforge.phpdt.internal.ui.viewsupport.ImageDescriptorRegistry;
+import net.sourceforge.phpdt.internal.ui.viewsupport.ImageImageDescriptor;
+import net.sourceforge.phpeclipse.PHPeclipsePlugin;
+
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.jface.viewers.IDecoration;
+import org.eclipse.jface.viewers.ILabelDecorator;
+import org.eclipse.jface.viewers.ILabelProviderListener;
+import org.eclipse.jface.viewers.ILightweightLabelDecorator;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.graphics.Point;
+import org.eclipse.swt.graphics.Rectangle;
+
+
+/**
+ * LabelDecorator that decorates an method's image with override or implements overlays.
+ * The viewer using this decorator is responsible for updating the images on element changes.
+ *
+ * null
to use the Java plugin's
+ * image registry.
+ */
+ /**
+ * Note: This constructor is for internal use only. Clients should not call this constructor.
+ */
+ public OverrideIndicatorLabelDecorator(ImageDescriptorRegistry registry) {
+ fRegistry= registry;
+ }
+
+ private ImageDescriptorRegistry getRegistry() {
+ if (fRegistry == null) {
+ fRegistry= fUseNewRegistry ? new ImageDescriptorRegistry() : PHPeclipsePlugin.getImageDescriptorRegistry();
+ }
+ return fRegistry;
+ }
+
+
+ /* (non-Javadoc)
+ * @see ILabelDecorator#decorateText(String, Object)
+ */
+ public String decorateText(String text, Object element) {
+ return text;
+ }
+
+ /* (non-Javadoc)
+ * @see ILabelDecorator#decorateImage(Image, Object)
+ */
+ public Image decorateImage(Image image, Object element) {
+ int adornmentFlags= computeAdornmentFlags(element);
+ if (adornmentFlags != 0) {
+ ImageDescriptor baseImage= new ImageImageDescriptor(image);
+ Rectangle bounds= image.getBounds();
+ return getRegistry().get(new JavaElementImageDescriptor(baseImage, adornmentFlags, new Point(bounds.width, bounds.height)));
+ }
+ return image;
+ }
+
+ /**
+ * Note: This method is for internal use only. Clients should not call this method.
+ */
+ public int computeAdornmentFlags(Object element) {
+ if (element instanceof IMethod) {
+ if (!PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.APPEARANCE_OVERRIDE_INDICATOR)) {
+ return 0;
+ }
+
+ try {
+ IMethod method= (IMethod) element;
+// if (!method.getJavaProject().isOnClasspath(method)) {
+// return 0;
+// }
+
+ int flags= method.getFlags();
+ IType type = method.getDeclaringType();//jsurfer INSERT
+ if (type!=null && type.isClass() && !method.isConstructor() && !Flags.isPrivate(flags) && !Flags.isStatic(flags)) {
+ return getOverrideIndicators(method);
+ }
+ } catch (JavaModelException e) {
+ if (!e.isDoesNotExist()) {
+ PHPeclipsePlugin.log(e);
+ }
+ }
+ }
+ return 0;
+ }
+
+ /**
+ * Note: This method is for internal use only. Clients should not call this method.
+ */
+ protected int getOverrideIndicators(IMethod method) throws JavaModelException {
+ IType type= method.getDeclaringType();
+// ITypeHierarchy hierarchy= SuperTypeHierarchyCache.getTypeHierarchy(type);
+// if (hierarchy != null) {
+// return findInHierarchy(type, hierarchy, method.getElementName(), method.getParameterTypes());
+// }
+ return 0;
+ }
+
+ /**
+ * Note: This method is for internal use only. Clients should not call this method.
+ */
+// protected int findInHierarchy(IType type, ITypeHierarchy hierarchy, String name, String[] paramTypes) throws JavaModelException {
+// IMethod impl= JavaModelUtil.findMethodDeclarationInHierarchy(hierarchy, type, name, paramTypes, false);
+// if (impl != null) {
+// IMethod overridden= JavaModelUtil.findMethodImplementationInHierarchy(hierarchy, type, name, paramTypes, false);
+// if (overridden != null) {
+// return JavaElementImageDescriptor.OVERRIDES;
+// } else {
+// return JavaElementImageDescriptor.IMPLEMENTS;
+// }
+// }
+// return 0;
+// }
+
+ /* (non-Javadoc)
+ * @see IBaseLabelProvider#addListener(ILabelProviderListener)
+ */
+ public void addListener(ILabelProviderListener listener) {
+ }
+
+ /* (non-Javadoc)
+ * @see IBaseLabelProvider#dispose()
+ */
+ public void dispose() {
+ if (fRegistry != null && fUseNewRegistry) {
+ fRegistry.dispose();
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see IBaseLabelProvider#isLabelProperty(Object, String)
+ */
+ public boolean isLabelProperty(Object element, String property) {
+ return true;
+ }
+
+ /* (non-Javadoc)
+ * @see IBaseLabelProvider#removeListener(ILabelProviderListener)
+ */
+ public void removeListener(ILabelProviderListener listener) {
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.jface.viewers.ILightweightLabelDecorator#decorate(java.lang.Object, org.eclipse.jface.viewers.IDecoration)
+ */
+ public void decorate(Object element, IDecoration decoration) {
+ int adornmentFlags= computeAdornmentFlags(element);
+ if (adornmentFlags != 0) {
+ decoration.addOverlay(PHPUiImages.DESC_OVR_OVERRIDES);
+ }
+ }
+
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/PreferenceConstants.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/PreferenceConstants.java
index 58b13a2..1b6474c 100644
--- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/PreferenceConstants.java
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/PreferenceConstants.java
@@ -13,6 +13,7 @@ package net.sourceforge.phpdt.ui;
import net.sourceforge.phpeclipse.IPreferenceConstants;
import net.sourceforge.phpeclipse.PHPeclipsePlugin;
+import org.eclipse.jface.action.Action;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.resource.JFaceResources;
@@ -383,6 +384,36 @@ public class PreferenceConstants {
* javaEditorTextHovers
.
+ *
+ * @since 2.1
+ */
+ public static String ID_BESTMATCH_HOVER= "net.sourceforge.phpdt.ui.BestMatchHover"; //$NON-NLS-1$
+
+ /**
+ * The id of the source code hover contributed for extension point
+ * javaEditorTextHovers
.
+ *
+ * @since 2.1
+ */
+ public static String ID_SOURCE_HOVER= "net.sourceforge.phpdt.ui.JavaSourceHover"; //$NON-NLS-1$
+
+ /**
+ * The id of the problem hover contributed for extension point
+ * javaEditorTextHovers
.
+ *
+ * @since 2.1
+ */
+ public static String ID_PROBLEM_HOVER = "net.sourceforge.phpdt.ui.ProblemHover"; //$NON-NLS-1$
/**
* A named preference that controls whether bracket matching highlighting is turned on or off.
@@ -942,26 +973,25 @@ public class PreferenceConstants {
*/
public final static String EDITOR_SINGLE_LINE_COMMENT_BOLD = IPreferenceConstants.PHP_SINGLELINE_COMMENT + EDITOR_BOLD_SUFFIX;
- /**
- * A named preference that holds the color used to render php start and stop tags.
- * String
. A RGB color value encoded as a string
- * using class PreferenceConverter
- * Boolean
.
- * String
. A RGB color value encoded as a string
+ * using class PreferenceConverter
+ * Boolean
.
+ * EDITOR_TEXT_HOVER_MODIFIERS
+ * cannot be resolved to valid SWT modifier bits.
+ *
+ * @see JavaUI
+ * @see #EDITOR_TEXT_HOVER_MODIFIERS
+ * @since 2.1.1
+ */
+ public static final String EDITOR_TEXT_HOVER_MODIFIER_MASKS = "hoverModifierMasks"; //$NON-NLS-1$
+
public static void initializeDefaultValues(IPreferenceStore store) {
store.setDefault(PreferenceConstants.EDITOR_SHOW_SEGMENTS, false);
@@ -1803,9 +1844,9 @@ public class PreferenceConstants {
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_COLOR, new RGB(63, 127, 95));
store.setDefault(PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_BOLD, false);
- PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVA_TAG_COLOR, new RGB(255, 0, 128));
- store.setDefault(PreferenceConstants.EDITOR_JAVA_TAG_BOLD, true);
-
+ PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVA_TAG_COLOR, new RGB(255, 0, 128));
+ store.setDefault(PreferenceConstants.EDITOR_JAVA_TAG_BOLD, true);
+
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVA_KEYWORD_COLOR, new RGB(127, 0, 85));
store.setDefault(PreferenceConstants.EDITOR_JAVA_KEYWORD_BOLD, true);
@@ -1882,6 +1923,14 @@ public class PreferenceConstants {
store.setDefault(PreferenceConstants.EDITOR_ALT_SHIFT_HOVER, PreferenceConstants.EDITOR_DEFAULT_HOVER_CONFIGURED_ID);
store.setDefault(PreferenceConstants.EDITOR_CTRL_ALT_SHIFT_HOVER, PreferenceConstants.EDITOR_DEFAULT_HOVER_CONFIGURED_ID);
+ String ctrl = Action.findModifierString(SWT.CTRL);
+ store.setDefault(PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS, "net.sourceforge.phpdt.ui.BestMatchHover;0;net.sourceforge.phpdt.ui.JavaSourceHover;" + ctrl); //$NON-NLS-1$
+ store.setDefault(PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIER_MASKS, "net.sourceforge.phpdt.ui.BestMatchHover;0;net.sourceforge.phpdt.ui.JavaSourceHover;" + SWT.CTRL); //$NON-NLS-1$
+
+ store.setDefault(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS, true);
+ store.setDefault(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER, ctrl);
+ store.setDefault(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK, SWT.CTRL);
+
// do more complicated stuff
// NewJavaProjectPreferencePage.initDefaults(store);
}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/ProblemsLabelDecorator.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/ProblemsLabelDecorator.java
new file mode 100644
index 0000000..53e172d
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/ProblemsLabelDecorator.java
@@ -0,0 +1,359 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.ui;
+
+import java.util.Iterator;
+
+import net.sourceforge.phpdt.core.ICompilationUnit;
+import net.sourceforge.phpdt.core.IJavaElement;
+import net.sourceforge.phpdt.core.ISourceRange;
+import net.sourceforge.phpdt.core.ISourceReference;
+import net.sourceforge.phpdt.core.JavaModelException;
+import net.sourceforge.phpdt.internal.ui.PHPUiImages;
+import net.sourceforge.phpdt.internal.ui.viewsupport.IProblemChangedListener;
+import net.sourceforge.phpdt.internal.ui.viewsupport.ImageDescriptorRegistry;
+import net.sourceforge.phpdt.internal.ui.viewsupport.ImageImageDescriptor;
+import net.sourceforge.phpeclipse.PHPeclipsePlugin;
+
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.jface.text.Position;
+import org.eclipse.jface.text.source.Annotation;
+import org.eclipse.jface.text.source.IAnnotationModel;
+import org.eclipse.jface.util.ListenerList;
+import org.eclipse.jface.viewers.IBaseLabelProvider;
+import org.eclipse.jface.viewers.IDecoration;
+import org.eclipse.jface.viewers.ILabelDecorator;
+import org.eclipse.jface.viewers.ILabelProviderListener;
+import org.eclipse.jface.viewers.ILightweightLabelDecorator;
+import org.eclipse.jface.viewers.LabelProviderChangedEvent;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.graphics.Point;
+import org.eclipse.swt.graphics.Rectangle;
+import org.eclipse.ui.part.FileEditorInput;
+import org.eclipse.ui.texteditor.MarkerAnnotation;
+
+/**
+ * LabelDecorator that decorates an element's image with error and warning overlays that
+ * represent the severity of markers attached to the element's underlying resource. To see
+ * a problem decoration for a marker, the marker needs to be a subtype of IMarker.PROBLEM
.
+ * LabelProviderChangedEvent
carring additional
+ * information whether the event orgins from a maker change.
+ * ProblemsLabelChangedEvent
s are only generated by
+ * ProblemsLabelDecorator
s.
+ * false
an annotation
+ * model change is the origin. In this case viewers not displaying working copies can ignore these
+ * events.
+ *
+ * @return if this event origins from a marker change.
+ */
+ public boolean isMarkerChange() {
+ return fMarkerChange;
+ }
+
+ }
+
+ private static final int ERRORTICK_WARNING= JavaElementImageDescriptor.WARNING;
+ private static final int ERRORTICK_ERROR= JavaElementImageDescriptor.ERROR;
+
+ private ImageDescriptorRegistry fRegistry;
+ private boolean fUseNewRegistry= false;
+ private IProblemChangedListener fProblemChangedListener;
+
+ private ListenerList fListeners;
+
+ /**
+ * Creates a new ProblemsLabelDecorator
.
+ */
+ public ProblemsLabelDecorator() {
+ this(null);
+ fUseNewRegistry= true;
+ }
+
+ /*
+ * Creates decorator with a shared image registry.
+ *
+ * @param registry The registry to use or null
to use the Java plugin's
+ * image registry.
+ */
+ /**
+ * Note: This constructor is for internal use only. Clients should not call this constructor.
+ */
+ public ProblemsLabelDecorator(ImageDescriptorRegistry registry) {
+ fRegistry= registry;
+ fProblemChangedListener= null;
+ }
+
+ private ImageDescriptorRegistry getRegistry() {
+ if (fRegistry == null) {
+ fRegistry= fUseNewRegistry ? new ImageDescriptorRegistry() : PHPeclipsePlugin.getImageDescriptorRegistry();
+ }
+ return fRegistry;
+ }
+
+
+ /* (non-Javadoc)
+ * @see ILabelDecorator#decorateText(String, Object)
+ */
+ public String decorateText(String text, Object element) {
+ return text;
+ }
+
+ /* (non-Javadoc)
+ * @see ILabelDecorator#decorateImage(Image, Object)
+ */
+ public Image decorateImage(Image image, Object obj) {
+ int adornmentFlags= computeAdornmentFlags(obj);
+ if (adornmentFlags != 0) {
+ ImageDescriptor baseImage= new ImageImageDescriptor(image);
+ Rectangle bounds= image.getBounds();
+ return getRegistry().get(new JavaElementImageDescriptor(baseImage, adornmentFlags, new Point(bounds.width, bounds.height)));
+ }
+ return image;
+ }
+
+ /**
+ * Note: This method is for internal use only. Clients should not call this method.
+ */
+ protected int computeAdornmentFlags(Object obj) {
+ try {
+ if (obj instanceof IJavaElement) {
+ IJavaElement element= (IJavaElement) obj;
+ int type= element.getElementType();
+ switch (type) {
+ case IJavaElement.JAVA_PROJECT:
+ case IJavaElement.PACKAGE_FRAGMENT_ROOT:
+ return getErrorTicksFromMarkers(element.getResource(), IResource.DEPTH_INFINITE, null);
+ case IJavaElement.PACKAGE_FRAGMENT:
+ case IJavaElement.CLASS_FILE:
+ return getErrorTicksFromMarkers(element.getResource(), IResource.DEPTH_ONE, null);
+ case IJavaElement.COMPILATION_UNIT:
+ case IJavaElement.PACKAGE_DECLARATION:
+ case IJavaElement.IMPORT_DECLARATION:
+ case IJavaElement.IMPORT_CONTAINER:
+ case IJavaElement.TYPE:
+ case IJavaElement.INITIALIZER:
+ case IJavaElement.METHOD:
+ case IJavaElement.FIELD:
+ ICompilationUnit cu= (ICompilationUnit) element.getAncestor(IJavaElement.COMPILATION_UNIT);
+ if (cu != null) {
+ ISourceReference ref= (type == IJavaElement.COMPILATION_UNIT) ? null : (ISourceReference) element;
+ // The assumption is that only source elements in compilation unit can have markers
+ if (cu.isWorkingCopy()) {
+ // working copy: look at annotation model
+ return getErrorTicksFromWorkingCopy((ICompilationUnit) cu.getOriginalElement(), ref);
+ }
+ return getErrorTicksFromMarkers(cu.getResource(), IResource.DEPTH_ONE, ref);
+ }
+ break;
+ default:
+ }
+ } else if (obj instanceof IResource) {
+ return getErrorTicksFromMarkers((IResource) obj, IResource.DEPTH_INFINITE, null);
+ }
+ } catch (CoreException e) {
+ if (e instanceof JavaModelException) {
+ if (((JavaModelException) e).isDoesNotExist()) {
+ return 0;
+ }
+ }
+ PHPeclipsePlugin.log(e);
+ }
+ return 0;
+ }
+
+ private int getErrorTicksFromMarkers(IResource res, int depth, ISourceReference sourceElement) throws CoreException {
+ if (res == null || !res.isAccessible()) {
+ return 0;
+ }
+ int info= 0;
+
+ IMarker[] markers= res.findMarkers(IMarker.PROBLEM, true, depth);
+ if (markers != null) {
+ for (int i= 0; i < markers.length && (info != ERRORTICK_ERROR); i++) {
+ IMarker curr= markers[i];
+ if (sourceElement == null || isMarkerInRange(curr, sourceElement)) {
+ int priority= curr.getAttribute(IMarker.SEVERITY, -1);
+ if (priority == IMarker.SEVERITY_WARNING) {
+ info= ERRORTICK_WARNING;
+ } else if (priority == IMarker.SEVERITY_ERROR) {
+ info= ERRORTICK_ERROR;
+ }
+ }
+ }
+ }
+ return info;
+ }
+
+ private boolean isMarkerInRange(IMarker marker, ISourceReference sourceElement) throws CoreException {
+ if (marker.isSubtypeOf(IMarker.TEXT)) {
+ int pos= marker.getAttribute(IMarker.CHAR_START, -1);
+ return isInside(pos, sourceElement);
+ }
+ return false;
+ }
+
+
+ private int getErrorTicksFromWorkingCopy(ICompilationUnit original, ISourceReference sourceElement) throws CoreException {
+ int info= 0;
+ FileEditorInput editorInput= new FileEditorInput((IFile) original.getResource());
+ IAnnotationModel model= PHPeclipsePlugin.getDefault().getCompilationUnitDocumentProvider().getAnnotationModel(editorInput);
+ if (model != null) {
+ Iterator iter= model.getAnnotationIterator();
+ while ((info != ERRORTICK_ERROR) && iter.hasNext()) {
+ Annotation curr= (Annotation) iter.next();
+ IMarker marker= isAnnotationInRange(model, curr, sourceElement);
+ if (marker != null) {
+ int priority= marker.getAttribute(IMarker.SEVERITY, -1);
+ if (priority == IMarker.SEVERITY_WARNING) {
+ info= ERRORTICK_WARNING;
+ } else if (priority == IMarker.SEVERITY_ERROR) {
+ info= ERRORTICK_ERROR;
+ }
+ }
+ }
+ }
+ return info;
+ }
+
+ private IMarker isAnnotationInRange(IAnnotationModel model, Annotation annot, ISourceReference sourceElement) throws CoreException {
+ if (annot instanceof MarkerAnnotation) {
+ IMarker marker= ((MarkerAnnotation) annot).getMarker();
+ if (marker.exists() && marker.isSubtypeOf(IMarker.PROBLEM)) {
+ Position pos= model.getPosition(annot);
+ if (sourceElement == null || isInside(pos.getOffset(), sourceElement)) {
+ return marker;
+ }
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Tests if a position is inside the source range of an element.
+ * @param pos Position to be tested.
+ * @param sourceElement Source element (must be a IJavaElement)
+ * @return boolean Return true
if position is located inside the source element.
+ * @throws CoreException Exception thrown if element range could not be accessed.
+ *
+ * @since 2.1
+ */
+ protected boolean isInside(int pos, ISourceReference sourceElement) throws CoreException {
+ ISourceRange range= sourceElement.getSourceRange();
+ if (range != null) {
+ int rangeOffset= range.getOffset();
+ return (rangeOffset <= pos && rangeOffset + range.getLength() > pos);
+ }
+ return false;
+ }
+
+ /* (non-Javadoc)
+ * @see IBaseLabelProvider#dispose()
+ */
+ public void dispose() {
+ if (fProblemChangedListener != null) {
+ PHPeclipsePlugin.getDefault().getProblemMarkerManager().removeListener(fProblemChangedListener);
+ fProblemChangedListener= null;
+ }
+ if (fRegistry != null && fUseNewRegistry) {
+ fRegistry.dispose();
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see IBaseLabelProvider#isLabelProperty(Object, String)
+ */
+ public boolean isLabelProperty(Object element, String property) {
+ return true;
+ }
+
+ /* (non-Javadoc)
+ * @see IBaseLabelProvider#addListener(ILabelProviderListener)
+ */
+ public void addListener(ILabelProviderListener listener) {
+ if (fListeners == null) {
+ fListeners= new ListenerList();
+ }
+ fListeners.add(listener);
+ if (fProblemChangedListener == null) {
+ fProblemChangedListener= new IProblemChangedListener() {
+ public void problemsChanged(IResource[] changedResources, boolean isMarkerChange) {
+ fireProblemsChanged(changedResources, isMarkerChange);
+ }
+ };
+ PHPeclipsePlugin.getDefault().getProblemMarkerManager().addListener(fProblemChangedListener);
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see IBaseLabelProvider#removeListener(ILabelProviderListener)
+ */
+ public void removeListener(ILabelProviderListener listener) {
+ if (fListeners != null) {
+ fListeners.remove(listener);
+ if (fListeners.isEmpty() && fProblemChangedListener != null) {
+ PHPeclipsePlugin.getDefault().getProblemMarkerManager().removeListener(fProblemChangedListener);
+ fProblemChangedListener= null;
+ }
+ }
+ }
+
+ private void fireProblemsChanged(IResource[] changedResources, boolean isMarkerChange) {
+ if (fListeners != null && !fListeners.isEmpty()) {
+ LabelProviderChangedEvent event= new ProblemsLabelChangedEvent(this, changedResources, isMarkerChange);
+ Object[] listeners= fListeners.getListeners();
+ for (int i= 0; i < listeners.length; i++) {
+ ((ILabelProviderListener) listeners[i]).labelProviderChanged(event);
+ }
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.jface.viewers.ILightweightLabelDecorator#decorate(java.lang.Object, org.eclipse.jface.viewers.IDecoration)
+ */
+ public void decorate(Object element, IDecoration decoration) {
+ int adornmentFlags= computeAdornmentFlags(element);
+ if (adornmentFlags == ERRORTICK_ERROR) {
+ decoration.addOverlay(PHPUiImages.DESC_OVR_ERROR);
+ } else if (adornmentFlags == ERRORTICK_WARNING) {
+ decoration.addOverlay(PHPUiImages.DESC_OVR_WARNING);
+ }
+ }
+
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/StandardJavaElementContentProvider.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/StandardJavaElementContentProvider.java
new file mode 100644
index 0000000..21b7dc1
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/StandardJavaElementContentProvider.java
@@ -0,0 +1,449 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.ui;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import net.sourceforge.phpdt.core.ICompilationUnit;
+import net.sourceforge.phpdt.core.IJavaElement;
+import net.sourceforge.phpdt.core.IJavaElementDelta;
+import net.sourceforge.phpdt.core.IJavaModel;
+import net.sourceforge.phpdt.core.IJavaProject;
+import net.sourceforge.phpdt.core.IPackageFragment;
+import net.sourceforge.phpdt.core.IPackageFragmentRoot;
+import net.sourceforge.phpdt.core.IParent;
+import net.sourceforge.phpdt.core.ISourceReference;
+import net.sourceforge.phpdt.core.JavaModelException;
+import net.sourceforge.phpdt.internal.corext.util.JavaModelUtil;
+import net.sourceforge.phpeclipse.PHPCore;
+
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IFolder;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.jface.viewers.ITreeContentProvider;
+import org.eclipse.jface.viewers.Viewer;
+
+
+/**
+ * A base content provider for Java elements. It provides access to the
+ * Java element hierarchy without listening to changes in the Java model.
+ * If updating the presentation on Java model change is required than
+ * clients have to subclass, listen to Java model changes and have to update
+ * the UI using corresponding methods provided by the JFace viewers or their
+ * own UI presentation.
+ *
+Java model (
+ * IJavaModel
)
+ Java project (IJavaProject
)
+ package fragment root (IPackageFragmentRoot
)
+ package fragment (IPackageFragment
)
+ compilation unit (ICompilationUnit
)
+ binary class file (IClassFile
)
+ *
+ * Note that when the entire Java project is declared to be package fragment root, + * the corresponding package fragment root element that normally appears between the + * Java project and the package fragments is automatically filtered out. + *
+ * This content provider can optionally return working copy elements for members + * below compilation units. If enabled, working copy members are returned for those + * compilation units in the Java element hierarchy for which a shared working copy exists + * in JDT core. + * + * @see org.eclipse.jdt.ui.IWorkingCopyProvider + * @see JavaCore#getSharedWorkingCopies(org.eclipse.jdt.core.IBufferFactory) + * + * @since 2.0 + */ +public class StandardJavaElementContentProvider implements ITreeContentProvider, IWorkingCopyProvider { + + protected static final Object[] NO_CHILDREN= new Object[0]; + + protected boolean fProvideMembers= false; + protected boolean fProvideWorkingCopy= false; + + /** + * Creates a new content provider. The content provider does not + * provide members of compilation units or class files and it does + * not provide working copy elements. + */ + public StandardJavaElementContentProvider() { + } + + /** + * Creates a newStandardJavaElementContentProvider
.
+ *
+ * @param provideMembers if true
members below compilation units
+ * and class files are provided.
+ * @param provideWorkingCopy if true
the element provider provides
+ * working copies members of compilation units which have an associated working
+ * copy in JDT core. Otherwise only original elements are provided.
+ */
+ public StandardJavaElementContentProvider(boolean provideMembers, boolean provideWorkingCopy) {
+ fProvideMembers= provideMembers;
+ fProvideWorkingCopy= provideWorkingCopy;
+ }
+
+ /**
+ * Returns whether members are provided when asking
+ * for a compilation units or class file for its children.
+ *
+ * @return true
if the content provider provides members;
+ * otherwise false
is returned
+ */
+ public boolean getProvideMembers() {
+ return fProvideMembers;
+ }
+
+ /**
+ * Sets whether the content provider is supposed to return members
+ * when asking a compilation unit or class file for its children.
+ *
+ * @param b if true
then members are provided.
+ * If false
compilation units and class files are the
+ * leaves provided by this content provider.
+ */
+ public void setProvideMembers(boolean b) {
+ fProvideMembers= b;
+ }
+
+ /**
+ * Returns whether the provided members are from a working
+ * copy or the original compilation unit.
+ *
+ * @return true
if the content provider provides
+ * working copy members; otherwise false
is
+ * returned
+ *
+ * @see #setProvideWorkingCopy(boolean)
+ */
+ public boolean getProvideWorkingCopy() {
+ return fProvideWorkingCopy;
+ }
+
+ /**
+ * Sets whether the members are provided from a shared working copy
+ * that exists for a original compilation unit in the Java element hierarchy.
+ *
+ * @param b if true
members are provided from a
+ * working copy if one exists in JDT core. If false
the
+ * provider always returns original elements.
+ */
+ public void setProvideWorkingCopy(boolean b) {
+ fProvideWorkingCopy= b;
+ }
+
+ /* (non-Javadoc)
+ * @see IWorkingCopyProvider#providesWorkingCopies()
+ */
+ public boolean providesWorkingCopies() {
+ return fProvideWorkingCopy;
+ }
+
+ /* (non-Javadoc)
+ * Method declared on IStructuredContentProvider.
+ */
+ public Object[] getElements(Object parent) {
+ return getChildren(parent);
+ }
+
+ /* (non-Javadoc)
+ * Method declared on IContentProvider.
+ */
+ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+ }
+
+ /* (non-Javadoc)
+ * Method declared on IContentProvider.
+ */
+ public void dispose() {
+ }
+
+ /* (non-Javadoc)
+ * Method declared on ITreeContentProvider.
+ */
+ public Object[] getChildren(Object element) {
+ if (!exists(element))
+ return NO_CHILDREN;
+
+ try {
+ if (element instanceof IJavaModel)
+ return getJavaProjects((IJavaModel)element);
+
+// if (element instanceof IJavaProject)
+// return getPackageFragmentRoots((IJavaProject)element);
+//
+ if (element instanceof IPackageFragmentRoot)
+ return getPackageFragments((IPackageFragmentRoot)element);
+
+// if (element instanceof IPackageFragment)
+// return getPackageContents((IPackageFragment)element);
+
+ if (element instanceof IFolder)
+ return getResources((IFolder)element);
+
+ if (fProvideMembers && element instanceof ISourceReference && element instanceof IParent) {
+ if (fProvideWorkingCopy && element instanceof ICompilationUnit) {
+ element= JavaModelUtil.toWorkingCopy((ICompilationUnit) element);
+ }
+ return ((IParent)element).getChildren();
+ }
+ } catch (JavaModelException e) {
+ return NO_CHILDREN;
+ }
+ return NO_CHILDREN;
+ }
+
+ /* (non-Javadoc)
+ * @see ITreeContentProvider
+ */
+ public boolean hasChildren(Object element) {
+ if (fProvideMembers) {
+ // assume CUs and class files are never empty
+ if (element instanceof ICompilationUnit ){
+// ||
+// element instanceof IClassFile) {
+ return true;
+ }
+ } else {
+ // don't allow to drill down into a compilation unit or class file
+ if (element instanceof ICompilationUnit ||
+// element instanceof IClassFile ||
+ element instanceof IFile)
+ return false;
+ }
+
+ if (element instanceof IJavaProject) {
+ IJavaProject jp= (IJavaProject)element;
+ if (!jp.getProject().isOpen()) {
+ return false;
+ }
+ }
+
+ if (element instanceof IParent) {
+ try {
+ // when we have Java children return true, else we fetch all the children
+ if (((IParent)element).hasChildren())
+ return true;
+ } catch(JavaModelException e) {
+ return true;
+ }
+ }
+ Object[] children= getChildren(element);
+ return (children != null) && children.length > 0;
+ }
+
+ /* (non-Javadoc)
+ * Method declared on ITreeContentProvider.
+ */
+ public Object getParent(Object element) {
+ if (!exists(element))
+ return null;
+ return internalGetParent(element);
+ }
+
+ private Object[] getPackageFragments(IPackageFragmentRoot root) throws JavaModelException {
+ IJavaElement[] fragments= root.getChildren();
+// Object[] nonJavaResources= root.getNonJavaResources();
+// if (nonJavaResources == null)
+ return fragments;
+// return concatenate(fragments, nonJavaResources);
+ }
+
+ /**
+ * Note: This method is for internal use only. Clients should not call this method.
+ */
+// protected Object[] getPackageFragmentRoots(IJavaProject project) throws JavaModelException {
+// if (!project.getProject().isOpen())
+// return NO_CHILDREN;
+//
+// IPackageFragmentRoot[] roots= project.getPackageFragmentRoots();
+// List list= new ArrayList(roots.length);
+// // filter out package fragments that correspond to projects and
+// // replace them with the package fragments directly
+// for (int i= 0; i < roots.length; i++) {
+// IPackageFragmentRoot root= (IPackageFragmentRoot)roots[i];
+// if (isProjectPackageFragmentRoot(root)) {
+// Object[] children= root.getChildren();
+// for (int k= 0; k < children.length; k++)
+// list.add(children[k]);
+// }
+// else if (hasChildren(root)) {
+// list.add(root);
+// }
+// }
+// return concatenate(list.toArray(), project.getNonJavaResources());
+// }
+
+ /**
+ * Note: This method is for internal use only. Clients should not call this method.
+ */
+ protected Object[] getJavaProjects(IJavaModel jm) throws JavaModelException {
+ return jm.getJavaProjects();
+ }
+
+// private Object[] getPackageContents(IPackageFragment fragment) throws JavaModelException {
+// if (fragment.getKind() == IPackageFragmentRoot.K_SOURCE) {
+// return concatenate(fragment.getCompilationUnits(), fragment.getNonJavaResources());
+// }
+// return concatenate(fragment.getClassFiles(), fragment.getNonJavaResources());
+// }
+
+ private Object[] getResources(IFolder folder) {
+ try {
+ // filter out folders that are package fragment roots
+ Object[] members= folder.members();
+ List nonJavaResources= new ArrayList();
+ for (int i= 0; i < members.length; i++) {
+ Object o= members[i];
+ // A folder can also be a package fragement root in the following case
+ // Project
+ // + src <- source folder
+ // + excluded <- excluded from class path
+ // + included <- a new source folder.
+ // Included is a member of excluded, but since it is rendered as a source
+ // folder we have to exclude it as a normal child.
+ if (o instanceof IFolder) {
+ IJavaElement element= PHPCore.create((IFolder)o);
+ if (element instanceof IPackageFragmentRoot && element.exists()) {
+ continue;
+ }
+ }
+ nonJavaResources.add(o);
+ }
+ return nonJavaResources.toArray();
+ } catch(CoreException e) {
+ return NO_CHILDREN;
+ }
+ }
+
+ /**
+ * Note: This method is for internal use only. Clients should not call this method.
+ */
+ protected boolean isClassPathChange(IJavaElementDelta delta) {
+
+ // need to test the flags only for package fragment roots
+ if (delta.getElement().getElementType() != IJavaElement.PACKAGE_FRAGMENT_ROOT)
+ return false;
+
+ int flags= delta.getFlags();
+ return (delta.getKind() == IJavaElementDelta.CHANGED &&
+ ((flags & IJavaElementDelta.F_ADDED_TO_CLASSPATH) != 0) ||
+ ((flags & IJavaElementDelta.F_REMOVED_FROM_CLASSPATH) != 0) ||
+ ((flags & IJavaElementDelta.F_REORDER) != 0));
+ }
+
+ /**
+ * Note: This method is for internal use only. Clients should not call this method.
+ */
+ protected Object skipProjectPackageFragmentRoot(IPackageFragmentRoot root) {
+ try {
+ if (isProjectPackageFragmentRoot(root))
+ return root.getParent();
+ return root;
+ } catch(JavaModelException e) {
+ return root;
+ }
+ }
+
+ /**
+ * Note: This method is for internal use only. Clients should not call this method.
+ */
+ protected boolean isPackageFragmentEmpty(IJavaElement element) throws JavaModelException {
+ if (element instanceof IPackageFragment) {
+ IPackageFragment fragment= (IPackageFragment)element;
+ if (!(fragment.hasChildren() ) )
+// ||
+// fragment.getNonJavaResources().length > 0) && fragment.hasSubpackages())
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Note: This method is for internal use only. Clients should not call this method.
+ */
+ protected boolean isProjectPackageFragmentRoot(IPackageFragmentRoot root) throws JavaModelException {
+ IResource resource= root.getResource();
+ return (resource instanceof IProject);
+ }
+
+ /**
+ * Note: This method is for internal use only. Clients should not call this method.
+ */
+ protected boolean exists(Object element) {
+ if (element == null) {
+ return false;
+ }
+ if (element instanceof IResource) {
+ return ((IResource)element).exists();
+ }
+ if (element instanceof IJavaElement) {
+ return ((IJavaElement)element).exists();
+ }
+ return true;
+ }
+
+ /**
+ * Note: This method is for internal use only. Clients should not call this method.
+ */
+ protected Object internalGetParent(Object element) {
+ if (element instanceof IJavaProject) {
+ return ((IJavaProject)element).getJavaModel();
+ }
+ // try to map resources to the containing package fragment
+ if (element instanceof IResource) {
+ IResource parent= ((IResource)element).getParent();
+ IJavaElement jParent= PHPCore.create(parent);
+ // http://bugs.eclipse.org/bugs/show_bug.cgi?id=31374
+ if (jParent != null && jParent.exists())
+ return jParent;
+ return parent;
+ }
+
+ // for package fragments that are contained in a project package fragment
+ // we have to skip the package fragment root as the parent.
+ if (element instanceof IPackageFragment) {
+ IPackageFragmentRoot parent= (IPackageFragmentRoot)((IPackageFragment)element).getParent();
+ return skipProjectPackageFragmentRoot(parent);
+ }
+ if (element instanceof IJavaElement) {
+ IJavaElement candidate= ((IJavaElement)element).getParent();
+ // If the parent is a CU we might have shown working copy elements below CU level. If so
+ // return the original element instead of the working copy.
+ if (candidate != null && candidate.getElementType() == IJavaElement.COMPILATION_UNIT) {
+ candidate= JavaModelUtil.toOriginal((ICompilationUnit) candidate);
+ }
+ return candidate;
+ }
+ return null;
+ }
+
+ /**
+ * Note: This method is for internal use only. Clients should not call this method.
+ */
+ protected static Object[] concatenate(Object[] a1, Object[] a2) {
+ int a1Len= a1.length;
+ int a2Len= a2.length;
+ Object[] res= new Object[a1Len + a2Len];
+ System.arraycopy(a1, 0, res, 0, a1Len);
+ System.arraycopy(a2, 0, res, a1Len, a2Len);
+ return res;
+ }
+
+
+}
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/MemberFilterActionGroup.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/MemberFilterActionGroup.java
new file mode 100644
index 0000000..48815ed
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/actions/MemberFilterActionGroup.java
@@ -0,0 +1,273 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.ui.actions;
+
+import net.sourceforge.phpdt.internal.ui.IJavaHelpContextIds;
+import net.sourceforge.phpdt.internal.ui.PHPUiImages;
+import net.sourceforge.phpdt.internal.ui.actions.ActionMessages;
+import net.sourceforge.phpdt.internal.ui.viewsupport.MemberFilter;
+import net.sourceforge.phpdt.internal.ui.viewsupport.MemberFilterAction;
+import net.sourceforge.phpeclipse.PHPeclipsePlugin;
+
+import org.eclipse.jface.action.IMenuManager;
+import org.eclipse.jface.action.IToolBarManager;
+import org.eclipse.jface.preference.IPreferenceStore;
+import org.eclipse.jface.util.Assert;
+import org.eclipse.jface.viewers.StructuredViewer;
+import org.eclipse.swt.custom.BusyIndicator;
+import org.eclipse.ui.IActionBars;
+import org.eclipse.ui.IMemento;
+import org.eclipse.ui.actions.ActionGroup;
+
+/**
+ * Action Group that contributes filter buttons for a view parts showing
+ * methods and fields. Contributed filters are: hide fields, hide static
+ * members and hide non-public members.
+ * + * The action group installs a filter on a structured viewer. The filter is connected + * to the actions installed in the view part's toolbar menu and is updated when the + * state of the buttons changes. + * + *
+ * This class may be instantiated; it is not intended to be subclassed. + *
+ * + * @since 2.0 + */ +public class MemberFilterActionGroup extends ActionGroup { + + public static final int FILTER_NONPUBLIC= MemberFilter.FILTER_NONPUBLIC; + public static final int FILTER_STATIC= MemberFilter.FILTER_STATIC; + public static final int FILTER_FIELDS= MemberFilter.FILTER_FIELDS; + + private static final String TAG_HIDEFIELDS= "hidefields"; //$NON-NLS-1$ + private static final String TAG_HIDESTATIC= "hidestatic"; //$NON-NLS-1$ + private static final String TAG_HIDENONPUBLIC= "hidenonpublic"; //$NON-NLS-1$ + + private MemberFilterAction[] fFilterActions; + private MemberFilter fFilter; + + private StructuredViewer fViewer; + private String fViewerId; + private boolean fInViewMenu; + + + /** + * Creates a newMemberFilterActionGroup
.
+ *
+ * @param viewer the viewer to be filtered
+ * @param viewerId a unique id of the viewer. Used as a key to to store
+ * the last used filter settings in the preference store
+ */
+ public MemberFilterActionGroup(StructuredViewer viewer, String viewerId) {
+ this(viewer, viewerId, false);
+ }
+
+ /**
+ * Creates a new MemberFilterActionGroup
.
+ *
+ * @param viewer the viewer to be filtered
+ * @param viewerId a unique id of the viewer. Used as a key to to store
+ * the last used filter settings in the preference store
+ * @param inViewMenu if true
the actions are added to the view
+ * menu. If false
they are added to the toobar.
+ *
+ * @since 2.1
+ */
+ public MemberFilterActionGroup(StructuredViewer viewer, String viewerId, boolean inViewMenu) {
+ fViewer= viewer;
+ fViewerId= viewerId;
+ fInViewMenu= inViewMenu;
+
+ // get initial values
+ IPreferenceStore store= PHPeclipsePlugin.getDefault().getPreferenceStore();
+ boolean doHideFields= store.getBoolean(getPreferenceKey(FILTER_FIELDS));
+ boolean doHideStatic= store.getBoolean(getPreferenceKey(FILTER_STATIC));
+ boolean doHidePublic= store.getBoolean(getPreferenceKey(FILTER_NONPUBLIC));
+
+ fFilter= new MemberFilter();
+ if (doHideFields)
+ fFilter.addFilter(FILTER_FIELDS);
+ if (doHideStatic)
+ fFilter.addFilter(FILTER_STATIC);
+ if (doHidePublic)
+ fFilter.addFilter(FILTER_NONPUBLIC);
+
+ // fields
+ String title= ActionMessages.getString("MemberFilterActionGroup.hide_fields.label"); //$NON-NLS-1$
+ String helpContext= IJavaHelpContextIds.FILTER_FIELDS_ACTION;
+ MemberFilterAction hideFields= new MemberFilterAction(this, title, FILTER_FIELDS, helpContext, doHideFields);
+ hideFields.setDescription(ActionMessages.getString("MemberFilterActionGroup.hide_fields.description")); //$NON-NLS-1$
+ hideFields.setToolTipText(ActionMessages.getString("MemberFilterActionGroup.hide_fields.tooltip")); //$NON-NLS-1$
+ PHPUiImages.setLocalImageDescriptors(hideFields, "fields_co.gif"); //$NON-NLS-1$
+
+ // static
+ title= ActionMessages.getString("MemberFilterActionGroup.hide_static.label"); //$NON-NLS-1$
+ helpContext= IJavaHelpContextIds.FILTER_STATIC_ACTION;
+ MemberFilterAction hideStatic= new MemberFilterAction(this, title, FILTER_STATIC, helpContext, doHideStatic);
+ hideStatic.setDescription(ActionMessages.getString("MemberFilterActionGroup.hide_static.description")); //$NON-NLS-1$
+ hideStatic.setToolTipText(ActionMessages.getString("MemberFilterActionGroup.hide_static.tooltip")); //$NON-NLS-1$
+ PHPUiImages.setLocalImageDescriptors(hideStatic, "static_co.gif"); //$NON-NLS-1$
+
+ // non-public
+ title= ActionMessages.getString("MemberFilterActionGroup.hide_nonpublic.label"); //$NON-NLS-1$
+ helpContext= IJavaHelpContextIds.FILTER_PUBLIC_ACTION;
+ MemberFilterAction hideNonPublic= new MemberFilterAction(this, title, FILTER_NONPUBLIC, helpContext, doHidePublic);
+ hideNonPublic.setDescription(ActionMessages.getString("MemberFilterActionGroup.hide_nonpublic.description")); //$NON-NLS-1$
+ hideNonPublic.setToolTipText(ActionMessages.getString("MemberFilterActionGroup.hide_nonpublic.tooltip")); //$NON-NLS-1$
+ PHPUiImages.setLocalImageDescriptors(hideNonPublic, "public_co.gif"); //$NON-NLS-1$
+
+ // order corresponds to order in toolbar
+ fFilterActions= new MemberFilterAction[] { hideFields, hideStatic, hideNonPublic };
+
+ fViewer.addFilter(fFilter);
+ }
+
+ private String getPreferenceKey(int filterProperty) {
+ return "MemberFilterActionGroup." + fViewerId + '.' + String.valueOf(filterProperty); //$NON-NLS-1$
+ }
+
+ /**
+ * Sets the member filters.
+ *
+ * @param filterProperty the filter to be manipulated. Valid values are FILTER_FIELDS
,
+ * FILTER_PUBLIC
, and FILTER_PRIVATE
as defined by this action
+ * group
+ * @param set if true
the given filter is installed. If false
the
+ * given filter is removed
+ * .
+ */
+ public void setMemberFilter(int filterProperty, boolean set) {
+ setMemberFilters(new int[] {filterProperty}, new boolean[] {set}, true);
+ }
+
+ private void setMemberFilters(int[] propertyKeys, boolean[] propertyValues, boolean refresh) {
+ if (propertyKeys.length == 0)
+ return;
+ Assert.isTrue(propertyKeys.length == propertyValues.length);
+
+ for (int i= 0; i < propertyKeys.length; i++) {
+ int filterProperty= propertyKeys[i];
+ boolean set= propertyValues[i];
+ if (set) {
+ fFilter.addFilter(filterProperty);
+ } else {
+ fFilter.removeFilter(filterProperty);
+ }
+ IPreferenceStore store= PHPeclipsePlugin.getDefault().getPreferenceStore();
+
+ for (int j= 0; j < fFilterActions.length; j++) {
+ int currProperty= fFilterActions[j].getFilterProperty();
+ if (currProperty == filterProperty) {
+ fFilterActions[j].setChecked(set);
+ }
+ store.setValue(getPreferenceKey(currProperty), hasMemberFilter(currProperty));
+ }
+ }
+ if (refresh) {
+ fViewer.getControl().setRedraw(false);
+ BusyIndicator.showWhile(fViewer.getControl().getDisplay(), new Runnable() {
+ public void run() {
+ fViewer.refresh();
+ }
+ });
+ fViewer.getControl().setRedraw(true);
+ }
+ }
+
+ /**
+ * Returns true
if the given filter is installed.
+ *
+ * @param filterProperty the filter to be tested. Valid values are FILTER_FIELDS
,
+ * FILTER_PUBLIC
, and FILTER_PRIVATE
as defined by this action
+ * group
+ */
+ public boolean hasMemberFilter(int filterProperty) {
+ return fFilter.hasFilter(filterProperty);
+ }
+
+ /**
+ * Saves the state of the filter actions in a memento.
+ *
+ * @param memento the memento to which the state is saved
+ */
+ public void saveState(IMemento memento) {
+ memento.putString(TAG_HIDEFIELDS, String.valueOf(hasMemberFilter(FILTER_FIELDS)));
+ memento.putString(TAG_HIDESTATIC, String.valueOf(hasMemberFilter(FILTER_STATIC)));
+ memento.putString(TAG_HIDENONPUBLIC, String.valueOf(hasMemberFilter(FILTER_NONPUBLIC)));
+ }
+
+ /**
+ * Restores the state of the filter actions from a memento.
+ * + * Note: This method does not refresh the viewer. + *
+ * @param memento the memento from which the state is restored + */ + public void restoreState(IMemento memento) { + setMemberFilters( + new int[] {FILTER_FIELDS, FILTER_STATIC, FILTER_NONPUBLIC}, + new boolean[] { + Boolean.valueOf(memento.getString(TAG_HIDEFIELDS)).booleanValue(), + Boolean.valueOf(memento.getString(TAG_HIDESTATIC)).booleanValue(), + Boolean.valueOf(memento.getString(TAG_HIDENONPUBLIC)).booleanValue() + }, false); + } + + /* (non-Javadoc) + * @see ActionGroup#fillActionBars(IActionBars) + */ + public void fillActionBars(IActionBars actionBars) { + contributeToToolBar(actionBars.getToolBarManager()); + }; + + /** + * Adds the filter actions to the given tool bar + * + * @param tbm the tool bar to which the actions are added + */ + public void contributeToToolBar(IToolBarManager tbm) { + if (fInViewMenu) + return; + tbm.add(fFilterActions[0]); // fields + tbm.add(fFilterActions[1]); // static + tbm.add(fFilterActions[2]); // public + } + + /** + * Adds the filter actions to the given menu manager. + * + * @param menu the menu manager to which the actions are added + * @since 2.1 + */ + public void contributeToViewMenu(IMenuManager menu) { + if (!fInViewMenu) + return; + final String filters= "filters"; //$NON-NLS-1$ + if (menu.find(filters) != null) { + menu.prependToGroup(filters, fFilterActions[0]); // fields + menu.prependToGroup(filters, fFilterActions[1]); // static + menu.prependToGroup(filters, fFilterActions[2]); // public + } else { + menu.add(fFilterActions[0]); // fields + menu.add(fFilterActions[1]); // static + menu.add(fFilterActions[2]); // public + } + } + + /* (non-Javadoc) + * @see ActionGroup#dispose() + */ + public void dispose() { + super.dispose(); + } + +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/JavaTextTools.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/JavaTextTools.java index 6d4f394..4bad7d2 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/JavaTextTools.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/JavaTextTools.java @@ -10,10 +10,13 @@ import net.sourceforge.phpdt.internal.ui.text.JavaColorManager; import net.sourceforge.phpdt.internal.ui.text.phpdoc.PHPDocCodeScanner; import net.sourceforge.phpeclipse.IPreferenceConstants; import net.sourceforge.phpeclipse.phpeditor.php.HTMLCodeScanner; +import net.sourceforge.phpeclipse.phpeditor.php.IPHPPartitionScannerConstants; import net.sourceforge.phpeclipse.phpeditor.php.PHPCodeScanner; +import net.sourceforge.phpeclipse.phpeditor.php.PHPPartitionScanner; import net.sourceforge.phpeclipse.phpeditor.php.SmartyCodeScanner; import net.sourceforge.phpeclipse.phpeditor.php.SmartyDocCodeScanner; +import org.eclipse.core.runtime.Preferences; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.text.IDocumentPartitioner; import org.eclipse.jface.text.rules.DefaultPartitioner; @@ -40,10 +43,35 @@ import org.eclipse.jface.util.PropertyChangeEvent; */ public class JavaTextTools { - private class PreferenceListener implements IPropertyChangeListener { + private static PHPPartitionScanner HTML_PARTITION_SCANNER = null; + + private static PHPPartitionScanner PHP_PARTITION_SCANNER = null; + private static PHPPartitionScanner SMARTY_PARTITION_SCANNER = null; + + // private final static String[] TYPES= new String[] { PHPPartitionScanner.PHP, PHPPartitionScanner.JAVA_DOC, PHPPartitionScanner.JAVA_MULTILINE_COMMENT }; + private final static String[] TYPES = + new String[] { + IPHPPartitionScannerConstants.PHP, + IPHPPartitionScannerConstants.PHP_MULTILINE_COMMENT, + IPHPPartitionScannerConstants.HTML, + IPHPPartitionScannerConstants.HTML_MULTILINE_COMMENT, + IPHPPartitionScannerConstants.JAVASCRIPT, + IPHPPartitionScannerConstants.CSS, + IPHPPartitionScannerConstants.SMARTY, + IPHPPartitionScannerConstants.SMARTY_MULTILINE_COMMENT }; + private static PHPPartitionScanner XML_PARTITION_SCANNER = null; + + /** + * This tools' preference listener. + */ + private class PreferenceListener implements IPropertyChangeListener, Preferences.IPropertyChangeListener { public void propertyChange(PropertyChangeEvent event) { adaptToPreferenceChange(event); } + public void propertyChange(Preferences.PropertyChangeEvent event) { + adaptToPreferenceChange( + new PropertyChangeEvent(event.getSource(), event.getProperty(), event.getOldValue(), event.getNewValue())); + } }; /** The color manager */ @@ -69,6 +97,11 @@ public class JavaTextTools { /** The preference store */ private IPreferenceStore fPreferenceStore; + /** + * The core preference store. + * @since 2.1 + */ + private Preferences fCorePreferenceStore; /** The preference change listener */ private PreferenceListener fPreferenceListener = new PreferenceListener(); @@ -100,6 +133,42 @@ public class JavaTextTools { } /** + * Creates a new Java text tools collection. + * + * @param store the preference store to initialize the text tools. The text tool + * instance installs a listener on the passed preference store to adapt itself to + * changes in the preference store. In generalPreferenceConstants.
+ * getPreferenceStore()
shoould be used to initialize the text tools.
+ * @param coreStore optional preference store to initialize the text tools. The text tool
+ * instance installs a listener on the passed preference store to adapt itself to
+ * changes in the preference store.
+ * @param autoDisposeOnDisplayDispose if true
the color manager
+ * automatically disposes all managed colors when the current display gets disposed
+ * and all calls to {@link org.eclipse.jface.text.source.ISharedTextColors#dispose()} are ignored.
+ * @see org.eclipse.jdt.ui.PreferenceConstants#getPreferenceStore()
+ * @since 2.1
+ */
+ public JavaTextTools(IPreferenceStore store, Preferences coreStore, boolean autoDisposeOnDisplayDispose) {
+ fPreferenceStore = store;
+ fPreferenceStore.addPropertyChangeListener(fPreferenceListener);
+
+ fCorePreferenceStore = coreStore;
+ if (fCorePreferenceStore != null)
+ fCorePreferenceStore.addPropertyChangeListener(fPreferenceListener);
+
+ fColorManager = new JavaColorManager(autoDisposeOnDisplayDispose);
+ fCodeScanner = new PHPCodeScanner(fColorManager, store);
+ fMultilineCommentScanner = new SingleTokenPHPScanner(fColorManager, store, IPreferenceConstants.PHP_MULTILINE_COMMENT);
+ fSinglelineCommentScanner = new SingleTokenPHPScanner(fColorManager, store, IPreferenceConstants.PHP_SINGLELINE_COMMENT);
+ fStringScanner = new SingleTokenPHPScanner(fColorManager, store, IPreferenceConstants.PHP_STRING);
+ fPHPDocScanner = new PHPDocCodeScanner(fColorManager, store);
+ fHTMLScanner = new HTMLCodeScanner(fColorManager, store);
+ fSmartyScanner = new SmartyCodeScanner(fColorManager, store);
+ fSmartyDocScanner = new SmartyDocCodeScanner(fColorManager, store);
+ fPartitionScanner = new FastJavaPartitionScanner();
+ }
+
+ /**
* Disposes all the individual tools of this tools collection.
*/
public void dispose() {
@@ -119,6 +188,12 @@ public class JavaTextTools {
if (fPreferenceStore != null) {
fPreferenceStore.removePropertyChangeListener(fPreferenceListener);
fPreferenceStore = null;
+
+ if (fCorePreferenceStore != null) {
+ fCorePreferenceStore.removePropertyChangeListener(fPreferenceListener);
+ fCorePreferenceStore = null;
+ }
+
fPreferenceListener = null;
}
}
@@ -230,22 +305,60 @@ public class JavaTextTools {
}
/**
- * Factory method for creating a Java-specific document partitioner
+ * Factory method for creating a PHP-specific document partitioner
* using this object's partitions scanner. This method is a
* convenience method.
*
* @return a newly created Java document partitioner
*/
public IDocumentPartitioner createDocumentPartitioner() {
+ return createDocumentPartitioner(".php");
+ }
- String[] types =
- new String[] {
- FastJavaPartitionScanner.JAVA_DOC,
- FastJavaPartitionScanner.JAVA_MULTI_LINE_COMMENT,
- FastJavaPartitionScanner.JAVA_SINGLE_LINE_COMMENT,
- FastJavaPartitionScanner.JAVA_STRING };
+ /**
+ * Factory method for creating a PHP-specific document partitioner
+ * using this object's partitions scanner. This method is a
+ * convenience method.
+ *
+ * @return a newly created Java document partitioner
+ */
+ public IDocumentPartitioner createDocumentPartitioner(String extension) {
- return new DefaultPartitioner(getPartitionScanner(), types);
+ // String[] types =
+ // new String[] {
+ // FastJavaPartitionScanner.JAVA_DOC,
+ // FastJavaPartitionScanner.JAVA_MULTI_LINE_COMMENT,
+ // FastJavaPartitionScanner.JAVA_SINGLE_LINE_COMMENT,
+ // FastJavaPartitionScanner.JAVA_STRING };
+ //
+ // return new DefaultPartitioner(getPartitionScanner(), types);
+ IDocumentPartitioner partitioner = null;
+ // System.out.println(extension);
+ if (extension.equalsIgnoreCase(".html") || extension.equalsIgnoreCase(".htm")) {
+ // html
+ partitioner = createHTMLPartitioner();
+ } else if (extension.equalsIgnoreCase(".xml")) {
+ // xml
+ partitioner = createXMLPartitioner();
+ } else if (extension.equalsIgnoreCase(".js")) {
+ // javascript
+ partitioner = createJavaScriptPartitioner();
+ } else if (extension.equalsIgnoreCase(".css")) {
+ // cascading style sheets
+ partitioner = createCSSPartitioner();
+ } else if (extension.equalsIgnoreCase(".tpl")) {
+ // smarty ?
+ partitioner = createSmartyPartitioner();
+ } else if (extension.equalsIgnoreCase(".inc")) {
+ // php include files ?
+ partitioner = createIncludePartitioner();
+ }
+
+ if (partitioner == null) {
+ partitioner = createPHPPartitioner();
+ }
+
+ return partitioner;
}
/**
@@ -297,4 +410,73 @@ public class JavaTextTools {
if (fPHPDocScanner.affectsBehavior(event))
fPHPDocScanner.adaptToPreferenceChange(event);
}
+
+ /**
+ * Return a partitioner for .html files.
+ */
+ private static IDocumentPartitioner createHTMLPartitioner() {
+ return new DefaultPartitioner(getHTMLPartitionScanner(), TYPES);
+ }
+
+ private static IDocumentPartitioner createIncludePartitioner() {
+ return new DefaultPartitioner(getPHPPartitionScanner(), TYPES);
+ }
+
+ private static IDocumentPartitioner createJavaScriptPartitioner() {
+ return new DefaultPartitioner(getHTMLPartitionScanner(), TYPES);
+ }
+
+ /**
+ * Return a partitioner for .php files.
+ */
+ private static IDocumentPartitioner createPHPPartitioner() {
+ return new DefaultPartitioner(getPHPPartitionScanner(), TYPES);
+ }
+
+ private static IDocumentPartitioner createSmartyPartitioner() {
+ return new DefaultPartitioner(getSmartyPartitionScanner(), TYPES);
+ }
+
+ private static IDocumentPartitioner createXMLPartitioner() {
+ return new DefaultPartitioner(getXMLPartitionScanner(), TYPES);
+ }
+
+ private static IDocumentPartitioner createCSSPartitioner() {
+ return new DefaultPartitioner(getHTMLPartitionScanner(), TYPES);
+ }
+ /**
+ * Return a scanner for creating html partitions.
+ */
+ private static PHPPartitionScanner getHTMLPartitionScanner() {
+ if (HTML_PARTITION_SCANNER == null)
+ HTML_PARTITION_SCANNER = new PHPPartitionScanner(IPHPPartitionScannerConstants.HTML_FILE);
+ return HTML_PARTITION_SCANNER;
+ }
+ /**
+ * Return a scanner for creating php partitions.
+ */
+ private static PHPPartitionScanner getPHPPartitionScanner() {
+ if (PHP_PARTITION_SCANNER == null)
+ PHP_PARTITION_SCANNER = new PHPPartitionScanner(IPHPPartitionScannerConstants.PHP_FILE);
+ return PHP_PARTITION_SCANNER;
+ }
+
+ /**
+ * Return a scanner for creating smarty partitions.
+ */
+ private static PHPPartitionScanner getSmartyPartitionScanner() {
+ if (SMARTY_PARTITION_SCANNER == null)
+ SMARTY_PARTITION_SCANNER = new PHPPartitionScanner(IPHPPartitionScannerConstants.SMARTY_FILE);
+ return SMARTY_PARTITION_SCANNER;
+ }
+
+ /**
+ * Return a scanner for creating xml partitions.
+ */
+ private static PHPPartitionScanner getXMLPartitionScanner() {
+ if (XML_PARTITION_SCANNER == null)
+ XML_PARTITION_SCANNER = new PHPPartitionScanner(IPHPPartitionScannerConstants.XML_FILE);
+ return XML_PARTITION_SCANNER;
+ }
+
}
\ No newline at end of file
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/java/hover/IJavaEditorTextHover.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/java/hover/IJavaEditorTextHover.java
new file mode 100644
index 0000000..337a481
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/java/hover/IJavaEditorTextHover.java
@@ -0,0 +1,39 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpdt.ui.text.java.hover;
+
+import org.eclipse.jface.text.ITextHover;
+
+import org.eclipse.ui.IEditorPart;
+
+/**
+ * Provides a hover popup which appears on top of an editor with relevant
+ * display information. If the text hover does not provide information no
+ * hover popup is shown.
+ * + * Clients may implement this interface.
+ * + * @see org.eclipse.ui.IEditorPart + * @see org.eclipse.jface.text.ITextHover + * + * @since 2.0 + */ +public interface IJavaEditorTextHover extends ITextHover { + + /** + * Sets the editor on which the hover is shown. + * + * @param editor the editor on which the hover popup should be shown + */ + void setEditor(IEditorPart editor); + +} + diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/java/hover/package.html b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/java/hover/package.html new file mode 100644 index 0000000..7cfda13 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/text/java/hover/package.html @@ -0,0 +1,16 @@ + + + + + + +"org.phpeclipse.phpdt.core"
).
*/
- public static final String PLUGIN_ID = "net.sourceforge.phpeclipse.core"; //$NON-NLS-1$
-
+// public static final String PLUGIN_ID = "net.sourceforge.phpeclipse.core"; //$NON-NLS-1$
+ public static final String PLUGIN_ID = PHPeclipsePlugin.PLUGIN_ID;
/**
* Possible configurable option ID.
* @see #getDefaultOptions
@@ -160,6 +189,406 @@ public class PHPCore {
public static final String CLEAN = "clean"; //$NON-NLS-1$
/**
+ * Possible configurable option ID.
+ * @see #getDefaultOptions
+ * @since 2.1
+ */
+ public static final String COMPILER_TASK_TAGS = PLUGIN_ID + ".compiler.taskTags"; //$NON-NLS-1$
+
+ /**
+ * Name of the handle id attribute in a Java marker.
+ */
+ protected static final String ATT_HANDLE_ID =
+ "net.sourceforge.phpdt.internal.core.JavaModelManager.handleId" ; //$NON-NLS-1$
+
+ // *************** Possible IDs for configurable options. ********************
+
+ /**
+ * Possible configurable option ID.
+ * @see #getDefaultOptions()
+ */
+ public static final String COMPILER_LOCAL_VARIABLE_ATTR = PLUGIN_ID + ".compiler.debug.localVariable"; //$NON-NLS-1$
+ /**
+ * Possible configurable option ID.
+ * @see #getDefaultOptions()
+ */
+ public static final String COMPILER_LINE_NUMBER_ATTR = PLUGIN_ID + ".compiler.debug.lineNumber"; //$NON-NLS-1$
+ /**
+ * Possible configurable option ID.
+ * @see #getDefaultOptions
+ */
+ public static final String COMPILER_SOURCE_FILE_ATTR = PLUGIN_ID + ".compiler.debug.sourceFile"; //$NON-NLS-1$
+ /**
+ * Possible configurable option ID.
+ * @see #getDefaultOptions
+ */
+ public static final String COMPILER_CODEGEN_UNUSED_LOCAL = PLUGIN_ID + ".compiler.codegen.unusedLocal"; //$NON-NLS-1$
+ /**
+ * Possible configurable option ID.
+ * @see #getDefaultOptions
+ */
+ public static final String COMPILER_CODEGEN_TARGET_PLATFORM = PLUGIN_ID + ".compiler.codegen.targetPlatform"; //$NON-NLS-1$
+ /**
+ * Possible configurable option ID.
+ * @see #getDefaultOptions
+ */
+ public static final String COMPILER_PB_UNREACHABLE_CODE = PLUGIN_ID + ".compiler.problem.unreachableCode"; //$NON-NLS-1$
+ /**
+ * Possible configurable option ID.
+ * @see #getDefaultOptions
+ */
+ public static final String COMPILER_PB_INVALID_IMPORT = PLUGIN_ID + ".compiler.problem.invalidImport"; //$NON-NLS-1$
+ /**
+ * Possible configurable option ID.
+ * @see #getDefaultOptions
+ */
+ public static final String COMPILER_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD = PLUGIN_ID + ".compiler.problem.overridingPackageDefaultMethod"; //$NON-NLS-1$
+ /**
+ * Possible configurable option ID.
+ * @see #getDefaultOptions
+ */
+ public static final String COMPILER_PB_METHOD_WITH_CONSTRUCTOR_NAME = PLUGIN_ID + ".compiler.problem.methodWithConstructorName"; //$NON-NLS-1$
+ /**
+ * Possible configurable option ID.
+ * @see #getDefaultOptions
+ */
+ public static final String COMPILER_PB_DEPRECATION = PLUGIN_ID + ".compiler.problem.deprecation"; //$NON-NLS-1$
+ /**
+ * Possible configurable option ID.
+ * @see #getDefaultOptions
+ * @since 2.1
+ */
+ public static final String COMPILER_PB_DEPRECATION_IN_DEPRECATED_CODE = PLUGIN_ID + ".compiler.problem.deprecationInDeprecatedCode"; //$NON-NLS-1$
+ /**
+ * Possible configurable option ID.
+ * @see #getDefaultOptions
+ */
+ public static final String COMPILER_PB_HIDDEN_CATCH_BLOCK = PLUGIN_ID + ".compiler.problem.hiddenCatchBlock"; //$NON-NLS-1$
+ /**
+ * Possible configurable option ID.
+ * @see #getDefaultOptions
+ */
+ public static final String COMPILER_PB_UNUSED_LOCAL = PLUGIN_ID + ".compiler.problem.unusedLocal"; //$NON-NLS-1$
+ /**
+ * Possible configurable option ID.
+ * @see #getDefaultOptions
+ */
+ public static final String COMPILER_PB_UNUSED_PARAMETER = PLUGIN_ID + ".compiler.problem.unusedParameter"; //$NON-NLS-1$
+ /**
+ * Possible configurable option ID.
+ * @see #getDefaultOptions
+ * @since 2.1
+ */
+ public static final String COMPILER_PB_UNUSED_PARAMETER_WHEN_IMPLEMENTING_ABSTRACT = PLUGIN_ID + ".compiler.problem.unusedParameterWhenImplementingAbstract"; //$NON-NLS-1$
+ /**
+ * Possible configurable option ID.
+ * @see #getDefaultOptions
+ * @since 2.1
+ */
+ public static final String COMPILER_PB_UNUSED_PARAMETER_WHEN_OVERRIDING_CONCRETE = PLUGIN_ID + ".compiler.problem.unusedParameterWhenOverridingConcrete"; //$NON-NLS-1$
+ /**
+ * Possible configurable option ID.
+ * @see #getDefaultOptions
+ * @since 2.0
+ */
+ public static final String COMPILER_PB_UNUSED_IMPORT = PLUGIN_ID + ".compiler.problem.unusedImport"; //$NON-NLS-1$
+ /**
+ * Possible configurable option ID.
+ * @see #getDefaultOptions
+ */
+ public static final String COMPILER_PB_SYNTHETIC_ACCESS_EMULATION = PLUGIN_ID + ".compiler.problem.syntheticAccessEmulation"; //$NON-NLS-1$
+ /**
+ * Possible configurable option ID.
+ * @see #getDefaultOptions
+ * @since 2.0
+ */
+ public static final String COMPILER_PB_NON_NLS_STRING_LITERAL = PLUGIN_ID + ".compiler.problem.nonExternalizedStringLiteral"; //$NON-NLS-1$
+ /**
+ * Possible configurable option ID.
+ * @see #getDefaultOptions
+ * @since 2.0
+ */
+ public static final String COMPILER_PB_ASSERT_IDENTIFIER = PLUGIN_ID + ".compiler.problem.assertIdentifier"; //$NON-NLS-1$
+ /**
+ * Possible configurable option ID.
+ * @see #getDefaultOptions
+ * @since 2.1
+ */
+ public static final String COMPILER_PB_STATIC_ACCESS_RECEIVER = PLUGIN_ID + ".compiler.problem.staticAccessReceiver"; //$NON-NLS-1$
+ /**
+ * Possible configurable option ID.
+ * @see #getDefaultOptions
+ * @since 2.1
+ */
+ public static final String COMPILER_PB_NO_EFFECT_ASSIGNMENT = PLUGIN_ID + ".compiler.problem.noEffectAssignment"; //$NON-NLS-1$
+ /**
+ * Possible configurable option ID.
+ * @see #getDefaultOptions
+ * @since 2.1
+ */
+ public static final String COMPILER_PB_INCOMPATIBLE_NON_INHERITED_INTERFACE_METHOD = PLUGIN_ID + ".compiler.problem.incompatibleNonInheritedInterfaceMethod"; //$NON-NLS-1$
+ /**
+ * Possible configurable option ID.
+ * @see #getDefaultOptions
+ * @since 2.1
+ */
+ public static final String COMPILER_PB_UNUSED_PRIVATE_MEMBER = PLUGIN_ID + ".compiler.problem.unusedPrivateMember"; //$NON-NLS-1$
+ /**
+ * Possible configurable option ID.
+ * @see #getDefaultOptions
+ * @since 2.1
+ */
+ public static final String COMPILER_PB_CHAR_ARRAY_IN_STRING_CONCATENATION = PLUGIN_ID + ".compiler.problem.noImplicitStringConversion"; //$NON-NLS-1$
+ /**
+ * Possible configurable option ID.
+ * @see #getDefaultOptions
+ * @since 2.0
+ */
+ public static final String COMPILER_PB_MAX_PER_UNIT = PLUGIN_ID + ".compiler.maxProblemPerUnit"; //$NON-NLS-1$
+ /**
+ * Possible configurable option ID.
+ * @see #getDefaultOptions
+ * @since 2.0
+ */
+ public static final String COMPILER_SOURCE = PLUGIN_ID + ".compiler.source"; //$NON-NLS-1$
+ /**
+ * Possible configurable option ID.
+ * @see #getDefaultOptions
+ * @since 2.0
+ */
+ public static final String COMPILER_COMPLIANCE = PLUGIN_ID + ".compiler.compliance"; //$NON-NLS-1$
+ /**
+ * Possible configurable option ID.
+ * @see #getDefaultOptions
+ * @since 2.1
+ */
+ public static final String COMPILER_TASK_PRIORITIES = PLUGIN_ID + ".compiler.taskPriorities"; //$NON-NLS-1$
+ /**
+ * Possible configurable option value for COMPILER_TASK_PRIORITIES.
+ * @see #getDefaultOptions
+ * @since 2.1
+ */
+ public static final String COMPILER_TASK_PRIORITY_HIGH = "HIGH"; //$NON-NLS-1$
+ /**
+ * Possible configurable option value for COMPILER_TASK_PRIORITIES.
+ * @see #getDefaultOptions
+ * @since 2.1
+ */
+ public static final String COMPILER_TASK_PRIORITY_LOW = "LOW"; //$NON-NLS-1$
+ /**
+ * Possible configurable option value for COMPILER_TASK_PRIORITIES.
+ * @see #getDefaultOptions
+ * @since 2.1
+ */
+ public static final String COMPILER_TASK_PRIORITY_NORMAL = "NORMAL"; //$NON-NLS-1$
+ /**
+ * Possible configurable option ID.
+ * @see #getDefaultOptions
+ */
+ public static final String CORE_JAVA_BUILD_ORDER = PLUGIN_ID + ".computeJavaBuildOrder"; //$NON-NLS-1$
+ /**
+ * Possible configurable option ID.
+ * @see #getDefaultOptions
+ * @since 2.0
+ */
+ public static final String CORE_JAVA_BUILD_RESOURCE_COPY_FILTER = PLUGIN_ID + ".builder.resourceCopyExclusionFilter"; //$NON-NLS-1$
+ /**
+ * Possible configurable option ID.
+ * @see #getDefaultOptions
+ * @since 2.1
+ */
+ public static final String CORE_JAVA_BUILD_DUPLICATE_RESOURCE = PLUGIN_ID + ".builder.duplicateResourceTask"; //$NON-NLS-1$
+ /**
+ * Possible configurable option ID.
+ * @see #getDefaultOptions
+ * @since 2.1
+ */
+ public static final String CORE_JAVA_BUILD_CLEAN_OUTPUT_FOLDER = PLUGIN_ID + ".builder.cleanOutputFolder"; //$NON-NLS-1$
+ /**
+ * Possible configurable option ID.
+ * @see #getDefaultOptions
+ * @since 2.1
+ */
+ public static final String CORE_INCOMPLETE_CLASSPATH = PLUGIN_ID + ".incompleteClasspath"; //$NON-NLS-1$
+ /**
+ * Possible configurable option ID.
+ * @see #getDefaultOptions
+ * @since 2.1
+ */
+ public static final String CORE_CIRCULAR_CLASSPATH = PLUGIN_ID + ".circularClasspath"; //$NON-NLS-1$
+ /**
+ * Possible configurable option ID.
+ * @see #getDefaultOptions
+ * @since 2.0
+ */
+ public static final String CORE_JAVA_BUILD_INVALID_CLASSPATH = PLUGIN_ID + ".builder.invalidClasspath"; //$NON-NLS-1$
+ /**
+ * Possible configurable option ID.
+ * @see #getDefaultOptions
+ * @since 2.1
+ */
+ public static final String CORE_ENABLE_CLASSPATH_EXCLUSION_PATTERNS = PLUGIN_ID + ".classpath.exclusionPatterns"; //$NON-NLS-1$
+ /**
+ * Possible configurable option ID.
+ * @see #getDefaultOptions
+ * @since 2.1
+ */
+ public static final String CORE_ENABLE_CLASSPATH_MULTIPLE_OUTPUT_LOCATIONS = PLUGIN_ID + ".classpath.multipleOutputLocations"; //$NON-NLS-1$
+ /**
+ * Default task tag
+ * @since 2.1
+ */
+ public static final String DEFAULT_TASK_TAG = "TODO"; //$NON-NLS-1$
+ /**
+ * Default task priority
+ * @since 2.1
+ */
+ public static final String DEFAULT_TASK_PRIORITY = "NORMAL"; //$NON-NLS-1$
+ /**
+ * Possible configurable option ID
+ * @see #getDefaultOptions
+ * @since 2.1
+ */
+ public static final String FORMATTER_SPACE_CASTEXPRESSION = PLUGIN_ID + ".formatter.space.castexpression"; //$NON-NLS-1$
+ /**
+ * Possible configurable option ID.
+ * @see #getDefaultOptions
+ * @since 2.0
+ */
+ public static final String CODEASSIST_VISIBILITY_CHECK = PLUGIN_ID + ".codeComplete.visibilityCheck"; //$NON-NLS-1$
+ /**
+ * Possible configurable option ID.
+ * @see #getDefaultOptions
+ * @since 2.0
+ */
+ public static final String CODEASSIST_IMPLICIT_QUALIFICATION = PLUGIN_ID + ".codeComplete.forceImplicitQualification"; //$NON-NLS-1$
+ /**
+ * Possible configurable option ID.
+ * @see #getDefaultOptions
+ * @since 2.1
+ */
+ public static final String CODEASSIST_FIELD_PREFIXES = PLUGIN_ID + ".codeComplete.fieldPrefixes"; //$NON-NLS-1$
+ /**
+ * Possible configurable option ID.
+ * @see #getDefaultOptions
+ * @since 2.1
+ */
+ public static final String CODEASSIST_STATIC_FIELD_PREFIXES = PLUGIN_ID + ".codeComplete.staticFieldPrefixes"; //$NON-NLS-1$
+ /**
+ * Possible configurable option ID.
+ * @see #getDefaultOptions
+ * @since 2.1
+ */
+ public static final String CODEASSIST_LOCAL_PREFIXES = PLUGIN_ID + ".codeComplete.localPrefixes"; //$NON-NLS-1$
+ /**
+ * Possible configurable option ID.
+ * @see #getDefaultOptions
+ * @since 2.1
+ */
+ public static final String CODEASSIST_ARGUMENT_PREFIXES = PLUGIN_ID + ".codeComplete.argumentPrefixes"; //$NON-NLS-1$
+ /**
+ * Possible configurable option ID.
+ * @see #getDefaultOptions
+ * @since 2.1
+ */
+ public static final String CODEASSIST_FIELD_SUFFIXES = PLUGIN_ID + ".codeComplete.fieldSuffixes"; //$NON-NLS-1$
+ /**
+ * Possible configurable option ID.
+ * @see #getDefaultOptions
+ * @since 2.1
+ */
+ public static final String CODEASSIST_STATIC_FIELD_SUFFIXES = PLUGIN_ID + ".codeComplete.staticFieldSuffixes"; //$NON-NLS-1$
+ /**
+ * Possible configurable option ID.
+ * @see #getDefaultOptions
+ * @since 2.1
+ */
+ public static final String CODEASSIST_LOCAL_SUFFIXES = PLUGIN_ID + ".codeComplete.localSuffixes"; //$NON-NLS-1$
+ /**
+ * Possible configurable option ID.
+ * @see #getDefaultOptions
+ * @since 2.1
+ */
+ public static final String CODEASSIST_ARGUMENT_SUFFIXES = PLUGIN_ID + ".codeComplete.argumentSuffixes"; //$NON-NLS-1$
+
+ // *************** Possible values for configurable options. ********************
+
+ /**
+ * Possible configurable option value.
+ * @see #getDefaultOptions
+ */
+ public static final String GENERATE = "generate"; //$NON-NLS-1$
+ /**
+ * Possible configurable option value.
+ * @see #getDefaultOptions
+ */
+ public static final String DO_NOT_GENERATE = "do not generate"; //$NON-NLS-1$
+ /**
+ * Possible configurable option value.
+ * @see #getDefaultOptions
+ */
+ public static final String PRESERVE = "preserve"; //$NON-NLS-1$
+ /**
+ * Possible configurable option value.
+ * @see #getDefaultOptions
+ */
+ public static final String OPTIMIZE_OUT = "optimize out"; //$NON-NLS-1$
+ /**
+ * Possible configurable option value.
+ * @see #getDefaultOptions
+ */
+ public static final String VERSION_1_1 = "1.1"; //$NON-NLS-1$
+ /**
+ * Possible configurable option value.
+ * @see #getDefaultOptions
+ */
+ public static final String VERSION_1_2 = "1.2"; //$NON-NLS-1$
+ /**
+ * Possible configurable option value.
+ * @see #getDefaultOptions
+ * @since 2.0
+ */
+ public static final String VERSION_1_3 = "1.3"; //$NON-NLS-1$
+ /**
+ * Possible configurable option value.
+ * @see #getDefaultOptions
+ * @since 2.0
+ */
+ public static final String VERSION_1_4 = "1.4"; //$NON-NLS-1$
+ /**
+ * Possible configurable option value.
+ * @see #getDefaultOptions
+ * @since 2.0
+ */
+ public static final String ABORT = "abort"; //$NON-NLS-1$
+ /**
+ * Possible configurable option value.
+ * @see #getDefaultOptions
+ */
+ public static final String ERROR = "error"; //$NON-NLS-1$
+ /**
+ * Possible configurable option value.
+ * @see #getDefaultOptions
+ */
+ public static final String WARNING = "warning"; //$NON-NLS-1$
+ /**
+ * Possible configurable option value.
+ * @see #getDefaultOptions
+ */
+ public static final String IGNORE = "ignore"; //$NON-NLS-1$
+ /**
+ * Possible configurable option value.
+ * @see #getDefaultOptions
+ */
+ public static final String COMPUTE = "compute"; //$NON-NLS-1$
+ /**
+ * Possible configurable option value.
+ * @see #getDefaultOptions
+ * @since 2.0
+ */
+
+
+ /**
* Returns a table of all known configurable options with their default values.
* These options allow to configure the behaviour of the underlying components.
* The client may safely use the result as a template that they can modify and
@@ -347,7 +776,6 @@ public class PHPCore {
* - option id: "org.phpeclipse.phpdt.core.compiler.taskTags"
* - possible values: { "String
; value type: String
)
* @see #setOptions
*/
- public static Hashtable getDefaultOptions() {
-
- Hashtable defaultOptions = new Hashtable(10);
-
- // see #initializeDefaultPluginPreferences() for changing default settings
- Preferences preferences = getPlugin().getPluginPreferences();
- HashSet optionNames = OptionNames;
-
- // get preferences set to their default
- String[] defaultPropertyNames = preferences.defaultPropertyNames();
- for (int i = 0; i < defaultPropertyNames.length; i++) {
- String propertyName = defaultPropertyNames[i];
- if (optionNames.contains(propertyName)) {
- defaultOptions.put(propertyName, preferences.getDefaultString(propertyName));
- }
- }
- // get preferences not set to their default
- String[] propertyNames = preferences.propertyNames();
- for (int i = 0; i < propertyNames.length; i++) {
- String propertyName = propertyNames[i];
- if (optionNames.contains(propertyName)) {
- defaultOptions.put(propertyName, preferences.getDefaultString(propertyName));
- }
- }
- // get encoding through resource plugin
- defaultOptions.put(CORE_ENCODING, ResourcesPlugin.getEncoding());
-
- return defaultOptions;
- }
+// public static Hashtable getDefaultOptions() {
+//
+// Hashtable defaultOptions = new Hashtable(10);
+//
+// // see #initializeDefaultPluginPreferences() for changing default settings
+// Preferences preferences = getPlugin().getPluginPreferences();
+// HashSet optionNames = OptionNames;
+//
+// // get preferences set to their default
+// String[] defaultPropertyNames = preferences.defaultPropertyNames();
+// for (int i = 0; i < defaultPropertyNames.length; i++) {
+// String propertyName = defaultPropertyNames[i];
+// if (optionNames.contains(propertyName)) {
+// defaultOptions.put(propertyName, preferences.getDefaultString(propertyName));
+// }
+// }
+// // get preferences not set to their default
+// String[] propertyNames = preferences.propertyNames();
+// for (int i = 0; i < propertyNames.length; i++) {
+// String propertyName = propertyNames[i];
+// if (optionNames.contains(propertyName)) {
+// defaultOptions.put(propertyName, preferences.getDefaultString(propertyName));
+// }
+// }
+// // get encoding through resource plugin
+// defaultOptions.put(CORE_ENCODING, ResourcesPlugin.getEncoding());
+//
+// return defaultOptions;
+// }
/**
* Helper method for returning one option value only. Equivalent to (String)JavaCore.getOptions().get(optionName)
* Note that it may answer null
if this option does not exist.
@@ -581,17 +1009,17 @@ public class PHPCore {
* @see JavaCore#getDefaultOptions
* @since 2.0
*/
- public static String getOption(String optionName) {
-
- if (CORE_ENCODING.equals(optionName)) {
- return ResourcesPlugin.getEncoding();
- }
- if (OptionNames.contains(optionName)) {
- Preferences preferences = getPlugin().getPluginPreferences();
- return preferences.getString(optionName).trim();
- }
- return null;
- }
+// public static String getOption(String optionName) {
+//
+// if (CORE_ENCODING.equals(optionName)) {
+// return ResourcesPlugin.getEncoding();
+// }
+// if (OptionNames.contains(optionName)) {
+// Preferences preferences = getPlugin().getPluginPreferences();
+// return preferences.getString(optionName).trim();
+// }
+// return null;
+// }
/**
* Returns the table of the current options. Initially, all options have their default values,
@@ -604,37 +1032,37 @@ public class PHPCore {
* (key type: String
; value type: String
)
* @see JavaCore#getDefaultOptions
*/
- public static Hashtable getOptions() {
-
- Hashtable options = new Hashtable(10);
-
- // see #initializeDefaultPluginPreferences() for changing default settings
- Plugin plugin = getPlugin();
- if (plugin != null) {
- Preferences preferences = getPlugin().getPluginPreferences();
- HashSet optionNames = OptionNames;
-
- // get preferences set to their default
- String[] defaultPropertyNames = preferences.defaultPropertyNames();
- for (int i = 0; i < defaultPropertyNames.length; i++) {
- String propertyName = defaultPropertyNames[i];
- if (optionNames.contains(propertyName)) {
- options.put(propertyName, preferences.getDefaultString(propertyName));
- }
- }
- // get preferences not set to their default
- String[] propertyNames = preferences.propertyNames();
- for (int i = 0; i < propertyNames.length; i++) {
- String propertyName = propertyNames[i];
- if (optionNames.contains(propertyName)) {
- options.put(propertyName, preferences.getString(propertyName).trim());
- }
- }
- // get encoding through resource plugin
- options.put(CORE_ENCODING, ResourcesPlugin.getEncoding());
- }
- return options;
- }
+// public static Hashtable getOptions() {
+//
+// Hashtable options = new Hashtable(10);
+//
+// // see #initializeDefaultPluginPreferences() for changing default settings
+// Plugin plugin = getPlugin();
+// if (plugin != null) {
+// Preferences preferences = getPlugin().getPluginPreferences();
+// HashSet optionNames = OptionNames;
+//
+// // get preferences set to their default
+// String[] defaultPropertyNames = preferences.defaultPropertyNames();
+// for (int i = 0; i < defaultPropertyNames.length; i++) {
+// String propertyName = defaultPropertyNames[i];
+// if (optionNames.contains(propertyName)) {
+// options.put(propertyName, preferences.getDefaultString(propertyName));
+// }
+// }
+// // get preferences not set to their default
+// String[] propertyNames = preferences.propertyNames();
+// for (int i = 0; i < propertyNames.length; i++) {
+// String propertyName = propertyNames[i];
+// if (optionNames.contains(propertyName)) {
+// options.put(propertyName, preferences.getString(propertyName).trim());
+// }
+// }
+// // get encoding through resource plugin
+// options.put(CORE_ENCODING, ResourcesPlugin.getEncoding());
+// }
+// return options;
+// }
/**
* Sets the current table of options. All and only the options explicitly included in the given table
* are remembered; all previous option settings are forgotten, including ones not explicitly
@@ -647,28 +1075,28 @@ public class PHPCore {
* or null
to reset all options to their default values
* @see JavaCore#getDefaultOptions
*/
- public static void setOptions(Hashtable newOptions) {
-
- // see #initializeDefaultPluginPreferences() for changing default settings
- Preferences preferences = getPlugin().getPluginPreferences();
-
- if (newOptions == null) {
- newOptions = getDefaultOptions();
- }
- Enumeration keys = newOptions.keys();
- while (keys.hasMoreElements()) {
- String key = (String) keys.nextElement();
- if (!OptionNames.contains(key))
- continue; // unrecognized option
- if (key.equals(CORE_ENCODING))
- continue; // skipped, contributed by resource prefs
- String value = (String) newOptions.get(key);
- preferences.setValue(key, value);
- }
-
- // persist options
- getPlugin().savePluginPreferences();
- }
+// public static void setOptions(Hashtable newOptions) {
+//
+// // see #initializeDefaultPluginPreferences() for changing default settings
+// Preferences preferences = getPlugin().getPluginPreferences();
+//
+// if (newOptions == null) {
+// newOptions = getDefaultOptions();
+// }
+// Enumeration keys = newOptions.keys();
+// while (keys.hasMoreElements()) {
+// String key = (String) keys.nextElement();
+// if (!OptionNames.contains(key))
+// continue; // unrecognized option
+// if (key.equals(CORE_ENCODING))
+// continue; // skipped, contributed by resource prefs
+// String value = (String) newOptions.get(key);
+// preferences.setValue(key, value);
+// }
+//
+// // persist options
+// getPlugin().savePluginPreferences();
+// }
public static IProject[] getPHPProjects() {
List phpProjectsList = new ArrayList();
IProject[] workspaceProjects = PHPeclipsePlugin.getWorkspace().getRoot().getProjects();
@@ -683,15 +1111,15 @@ public class PHPCore {
return (IProject[]) phpProjectsList.toArray(phpProjects);
}
- public static PHPProject getPHPProject(String name) {
- IProject aProject = PHPeclipsePlugin.getWorkspace().getRoot().getProject(name);
- if (isPHPProject(aProject)) {
- PHPProject thePHPProject = new PHPProject();
- thePHPProject.setProject(aProject);
- return thePHPProject;
- }
- return null;
- }
+// public static PHPProject getPHPProject(String name) {
+// IProject aProject = PHPeclipsePlugin.getWorkspace().getRoot().getProject(name);
+// if (isPHPProject(aProject)) {
+// PHPProject thePHPProject = new PHPProject();
+// thePHPProject.setProject(aProject);
+// return thePHPProject;
+// }
+// return null;
+// }
public static boolean isPHPProject(IProject aProject) {
try {
@@ -702,36 +1130,37 @@ public class PHPCore {
return false;
}
- public static PHPFile create(IFile aFile) {
- if (PHPFile.EXTENSION.equalsIgnoreCase(aFile.getFileExtension()))
- return new PHPFile(aFile);
- if (PHPFile.EXTENSION1.equalsIgnoreCase(aFile.getFileExtension()))
- return new PHPFile(aFile);
- if (PHPFile.EXTENSION2.equalsIgnoreCase(aFile.getFileExtension()))
- return new PHPFile(aFile);
- if (PHPFile.EXTENSION3.equalsIgnoreCase(aFile.getFileExtension()))
- return new PHPFile(aFile);
- if (PHPFile.EXTENSION4.equalsIgnoreCase(aFile.getFileExtension()))
- return new PHPFile(aFile);
- if (PHPFile.EXTENSION5.equalsIgnoreCase(aFile.getFileExtension()))
- return new PHPFile(aFile);
-
- return null;
- }
+// public static PHPFile create(IFile aFile) {
+// if (PHPFile.EXTENSION.equalsIgnoreCase(aFile.getFileExtension()))
+// return new PHPFile(aFile);
+// if (PHPFile.EXTENSION1.equalsIgnoreCase(aFile.getFileExtension()))
+// return new PHPFile(aFile);
+// if (PHPFile.EXTENSION2.equalsIgnoreCase(aFile.getFileExtension()))
+// return new PHPFile(aFile);
+// if (PHPFile.EXTENSION3.equalsIgnoreCase(aFile.getFileExtension()))
+// return new PHPFile(aFile);
+// if (PHPFile.EXTENSION4.equalsIgnoreCase(aFile.getFileExtension()))
+// return new PHPFile(aFile);
+// if (PHPFile.EXTENSION5.equalsIgnoreCase(aFile.getFileExtension()))
+// return new PHPFile(aFile);
+//
+// return null;
+// }
- public static PHPProject create(IProject aProject) {
- try {
- if (aProject.hasNature(PHPeclipsePlugin.PHP_NATURE_ID)) {
- PHPProject project = new PHPProject();
- project.setProject(aProject);
- return project;
- }
- } catch (CoreException e) {
- System.err.println("Exception occurred in PHPCore#create(IProject): " + e.toString());
- }
-
- return null;
- }
+// public static PHPProject create(IProject aProject) {
+//
+// try {
+// if (aProject.hasNature(PHPeclipsePlugin.PHP_NATURE_ID)) {
+// PHPProject project = new PHPProject();
+// project.setProject(aProject);
+// return project;
+// }
+// } catch (CoreException e) {
+// System.err.println("Exception occurred in PHPCore#create(IProject): " + e.toString());
+// }
+//
+// return null;
+// }
public static void addPHPNature(IProject project, IProgressMonitor monitor) throws CoreException {
if (!project.hasNature(PHPeclipsePlugin.PHP_NATURE_ID)) {
@@ -757,173 +1186,7 @@ public class PHPCore {
/**
* Initializes the default preferences settings for this plug-in.
*/
- protected static void initializeDefaultPluginPreferences() {
-
- Preferences preferences = PHPeclipsePlugin.getDefault().getPluginPreferences();
- HashSet optionNames = OptionNames;
-
- // // Compiler settings
- // preferences.setDefault(COMPILER_LOCAL_VARIABLE_ATTR, GENERATE);
- // optionNames.add(COMPILER_LOCAL_VARIABLE_ATTR);
- //
- // preferences.setDefault(COMPILER_LINE_NUMBER_ATTR, GENERATE);
- // optionNames.add(COMPILER_LINE_NUMBER_ATTR);
- //
- // preferences.setDefault(COMPILER_SOURCE_FILE_ATTR, GENERATE);
- // optionNames.add(COMPILER_SOURCE_FILE_ATTR);
- //
- // preferences.setDefault(COMPILER_CODEGEN_UNUSED_LOCAL, PRESERVE);
- // optionNames.add(COMPILER_CODEGEN_UNUSED_LOCAL);
- //
- // preferences.setDefault(COMPILER_CODEGEN_TARGET_PLATFORM, VERSION_1_1);
- // optionNames.add(COMPILER_CODEGEN_TARGET_PLATFORM);
- //
- // preferences.setDefault(COMPILER_PB_UNREACHABLE_CODE, ERROR);
- // optionNames.add(COMPILER_PB_UNREACHABLE_CODE);
- //
- // preferences.setDefault(COMPILER_PB_INVALID_IMPORT, ERROR);
- // optionNames.add(COMPILER_PB_INVALID_IMPORT);
- //
- // preferences.setDefault(COMPILER_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD, WARNING);
- // optionNames.add(COMPILER_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD);
- //
- // preferences.setDefault(COMPILER_PB_METHOD_WITH_CONSTRUCTOR_NAME, WARNING);
- // optionNames.add(COMPILER_PB_METHOD_WITH_CONSTRUCTOR_NAME);
- //
- // preferences.setDefault(COMPILER_PB_DEPRECATION, WARNING);
- // optionNames.add(COMPILER_PB_DEPRECATION);
- //
- // preferences.setDefault(COMPILER_PB_DEPRECATION_IN_DEPRECATED_CODE, DISABLED);
- // optionNames.add(COMPILER_PB_DEPRECATION_IN_DEPRECATED_CODE);
- //
- // preferences.setDefault(COMPILER_PB_HIDDEN_CATCH_BLOCK, WARNING);
- // optionNames.add(COMPILER_PB_HIDDEN_CATCH_BLOCK);
- //
- // preferences.setDefault(COMPILER_PB_UNUSED_LOCAL, IGNORE);
- // optionNames.add(COMPILER_PB_UNUSED_LOCAL);
- //
- // preferences.setDefault(COMPILER_PB_UNUSED_PARAMETER, IGNORE);
- // optionNames.add(COMPILER_PB_UNUSED_PARAMETER);
- //
- // preferences.setDefault(COMPILER_PB_UNUSED_IMPORT, WARNING);
- // optionNames.add(COMPILER_PB_UNUSED_IMPORT);
- //
- // preferences.setDefault(COMPILER_PB_SYNTHETIC_ACCESS_EMULATION, IGNORE);
- // optionNames.add(COMPILER_PB_SYNTHETIC_ACCESS_EMULATION);
- //
- // preferences.setDefault(COMPILER_PB_NON_NLS_STRING_LITERAL, IGNORE);
- // optionNames.add(COMPILER_PB_NON_NLS_STRING_LITERAL);
- //
- // preferences.setDefault(COMPILER_PB_ASSERT_IDENTIFIER, IGNORE);
- // optionNames.add(COMPILER_PB_ASSERT_IDENTIFIER);
- //
- // preferences.setDefault(COMPILER_PB_STATIC_ACCESS_RECEIVER, WARNING);
- // optionNames.add(COMPILER_PB_STATIC_ACCESS_RECEIVER);
- //
- // preferences.setDefault(COMPILER_PB_NO_EFFECT_ASSIGNMENT, WARNING);
- // optionNames.add(COMPILER_PB_NO_EFFECT_ASSIGNMENT);
- //
- // preferences.setDefault(COMPILER_TASK_TAGS, ""); //$NON-NLS-1$
- // optionNames.add(COMPILER_TASK_TAGS);
- //
- // preferences.setDefault(COMPILER_TASK_PRIORITIES, ""); //$NON-NLS-1$
- // optionNames.add(COMPILER_TASK_PRIORITIES);
- //
- // preferences.setDefault(COMPILER_SOURCE, VERSION_1_3);
- // optionNames.add(COMPILER_SOURCE);
- //
- // preferences.setDefault(COMPILER_COMPLIANCE, VERSION_1_3);
- // optionNames.add(COMPILER_COMPLIANCE);
- //
- // preferences.setDefault(COMPILER_PB_MAX_PER_UNIT, "100"); //$NON-NLS-1$
- // optionNames.add(COMPILER_PB_MAX_PER_UNIT);
- //
- // // Builder settings
- // preferences.setDefault(CORE_JAVA_BUILD_RESOURCE_COPY_FILTER, ""); //$NON-NLS-1$
- // optionNames.add(CORE_JAVA_BUILD_RESOURCE_COPY_FILTER);
- //
- // preferences.setDefault(CORE_JAVA_BUILD_INVALID_CLASSPATH, ABORT);
- // optionNames.add(CORE_JAVA_BUILD_INVALID_CLASSPATH);
- //
- // preferences.setDefault(CORE_JAVA_BUILD_DUPLICATE_RESOURCE, WARNING);
- // optionNames.add(CORE_JAVA_BUILD_DUPLICATE_RESOURCE);
- //
- // preferences.setDefault(CORE_JAVA_BUILD_CLEAN_OUTPUT_FOLDER, CLEAN);
- // optionNames.add(CORE_JAVA_BUILD_CLEAN_OUTPUT_FOLDER);
- //
- // // JavaCore settings
- // preferences.setDefault(CORE_JAVA_BUILD_ORDER, IGNORE);
- // optionNames.add(CORE_JAVA_BUILD_ORDER);
- //
- // preferences.setDefault(CORE_CIRCULAR_CLASSPATH, ERROR);
- // optionNames.add(CORE_CIRCULAR_CLASSPATH);
- //
- // preferences.setDefault(CORE_INCOMPLETE_CLASSPATH, ERROR);
- // optionNames.add(CORE_INCOMPLETE_CLASSPATH);
-
- // encoding setting comes from resource plug-in
- optionNames.add(CORE_ENCODING);
-
- // Formatter settings
- preferences.setDefault(FORMATTER_NEWLINE_OPENING_BRACE, DO_NOT_INSERT);
- optionNames.add(FORMATTER_NEWLINE_OPENING_BRACE);
-
- preferences.setDefault(FORMATTER_NEWLINE_CONTROL, DO_NOT_INSERT);
- optionNames.add(FORMATTER_NEWLINE_CONTROL);
-
- preferences.setDefault(FORMATTER_CLEAR_BLANK_LINES, PRESERVE_ONE);
- optionNames.add(FORMATTER_CLEAR_BLANK_LINES);
-
- preferences.setDefault(FORMATTER_NEWLINE_ELSE_IF, DO_NOT_INSERT);
- optionNames.add(FORMATTER_NEWLINE_ELSE_IF);
-
- preferences.setDefault(FORMATTER_NEWLINE_EMPTY_BLOCK, INSERT);
- optionNames.add(FORMATTER_NEWLINE_EMPTY_BLOCK);
-
- preferences.setDefault(FORMATTER_LINE_SPLIT, "80"); //$NON-NLS-1$
- optionNames.add(FORMATTER_LINE_SPLIT);
-
- preferences.setDefault(FORMATTER_COMPACT_ASSIGNMENT, NORMAL);
- optionNames.add(FORMATTER_COMPACT_ASSIGNMENT);
-
- preferences.setDefault(FORMATTER_TAB_CHAR, TAB);
- optionNames.add(FORMATTER_TAB_CHAR);
-
- preferences.setDefault(FORMATTER_TAB_SIZE, "4"); //$NON-NLS-1$
- optionNames.add(FORMATTER_TAB_SIZE);
-
- // CodeAssist settings
- // preferences.setDefault(CODEASSIST_VISIBILITY_CHECK, DISABLED); //$NON-NLS-1$
- // optionNames.add(CODEASSIST_VISIBILITY_CHECK);
- //
- // preferences.setDefault(CODEASSIST_IMPLICIT_QUALIFICATION, DISABLED); //$NON-NLS-1$
- // optionNames.add(CODEASSIST_IMPLICIT_QUALIFICATION);
- //
- // preferences.setDefault(CODEASSIST_FIELD_PREFIXES, ""); //$NON-NLS-1$
- // optionNames.add(CODEASSIST_FIELD_PREFIXES);
- //
- // preferences.setDefault(CODEASSIST_STATIC_FIELD_PREFIXES, ""); //$NON-NLS-1$
- // optionNames.add(CODEASSIST_STATIC_FIELD_PREFIXES);
- //
- // preferences.setDefault(CODEASSIST_LOCAL_PREFIXES, ""); //$NON-NLS-1$
- // optionNames.add(CODEASSIST_LOCAL_PREFIXES);
- //
- // preferences.setDefault(CODEASSIST_ARGUMENT_PREFIXES, ""); //$NON-NLS-1$
- // optionNames.add(CODEASSIST_ARGUMENT_PREFIXES);
- //
- // preferences.setDefault(CODEASSIST_FIELD_SUFFIXES, ""); //$NON-NLS-1$
- // optionNames.add(CODEASSIST_FIELD_SUFFIXES);
- //
- // preferences.setDefault(CODEASSIST_STATIC_FIELD_SUFFIXES, ""); //$NON-NLS-1$
- // optionNames.add(CODEASSIST_STATIC_FIELD_SUFFIXES);
- //
- // preferences.setDefault(CODEASSIST_LOCAL_SUFFIXES, ""); //$NON-NLS-1$
- // optionNames.add(CODEASSIST_LOCAL_SUFFIXES);
- //
- // preferences.setDefault(CODEASSIST_ARGUMENT_SUFFIXES, ""); //$NON-NLS-1$
- // optionNames.add(CODEASSIST_ARGUMENT_SUFFIXES);
-
- }
+
/**
* Runs the given action as an atomic Java model operation.
*
@@ -961,4 +1224,2557 @@ public class PHPCore {
workspace.run(new BatchOperation(action), monitor);
}
}
+
+/**
+ * Adds the given listener for changes to Java elements.
+ * Has no effect if an identical listener is already registered.
+ *
+ * This listener will only be notified during the POST_CHANGE resource change notification
+ * and any reconcile operation (POST_RECONCILE).
+ * For finer control of the notification, use addElementChangedListener(IElementChangedListener,int)
,
+ * which allows to specify a different eventMask.
+ *
+ * @see ElementChangedEvent
+ * @param listener the listener
+ */
+public static void addElementChangedListener(IElementChangedListener listener) {
+ addElementChangedListener(listener, ElementChangedEvent.POST_CHANGE | ElementChangedEvent.POST_RECONCILE);
+}
+
+/**
+ * Adds the given listener for changes to Java elements.
+ * Has no effect if an identical listener is already registered.
+ * After completion of this method, the given listener will be registered for exactly
+ * the specified events. If they were previously registered for other events, they
+ * will be deregistered.
+ *
+ * Once registered, a listener starts receiving notification of changes to + * java elements in the model. The listener continues to receive + * notifications until it is replaced or removed. + *
+ *
+ * Listeners can listen for several types of event as defined in ElementChangeEvent
.
+ * Clients are free to register for any number of event types however if they register
+ * for more than one, it is their responsibility to ensure they correctly handle the
+ * case where the same java element change shows up in multiple notifications.
+ * Clients are guaranteed to receive only the events for which they are registered.
+ *
String
,
+ * value type: String
)
+ * @param element the Java element for which the marker needs to be configured
+ */
+public static void addJavaElementMarkerAttributes(
+ Map attributes,
+ IJavaElement element) {
+// if (element instanceof IMember)
+// element = ((IMember) element).getClassFile();
+ if (attributes != null && element != null)
+ attributes.put(ATT_HANDLE_ID, element.getHandleIdentifier());
+}
+
+/**
+ * Configures the given marker for the given Java element.
+ * Used for markers, which denote a Java element rather than a resource.
+ *
+ * @param marker the marker to be configured
+ * @param element the Java element for which the marker needs to be configured
+ * @exception CoreException if the IMarker.setAttribute
on the marker fails
+ */
+public void configureJavaElementMarker(IMarker marker, IJavaElement element)
+ throws CoreException {
+// if (element instanceof IMember)
+// element = ((IMember) element).getClassFile();
+ if (marker != null && element != null)
+ marker.setAttribute(ATT_HANDLE_ID, element.getHandleIdentifier());
+}
+
+/**
+ * Returns the Java model element corresponding to the given handle identifier
+ * generated by IJavaElement.getHandleIdentifier()
, or
+ * null
if unable to create the associated element.
+ */
+public static IJavaElement create(String handleIdentifier) {
+ if (handleIdentifier == null) {
+ return null;
+ }
+ try {
+ return JavaModelManager.getJavaModelManager().getHandleFromMemento(handleIdentifier);
+ } catch (JavaModelException e) {
+ return null;
+ }
+}
+/**
+ * Returns the Java element corresponding to the given file, or
+ * null
if unable to associate the given file
+ * with a Java element.
+ *
+ * The file must be one of:
.java
file - the element returned is the corresponding ICompilationUnit
.class
file - the element returned is the corresponding IClassFile
.jar
file - the element returned is the corresponding IPackageFragmentRoot
+ * Creating a Java element has the side effect of creating and opening all of the
+ * element's parents if they are not yet open.
+ *
+ * @param the given file
+ * @return the Java element corresponding to the given file, or
+ * null
if unable to associate the given file
+ * with a Java element
+ */
+public static IJavaElement create(IFile file) {
+ return JavaModelManager.create(file, null);
+}
+/**
+ * Returns the package fragment or package fragment root corresponding to the given folder, or
+ * null
if unable to associate the given folder with a Java element.
+ *
+ * Note that a package fragment root is returned rather than a default package. + *
+ * Creating a Java element has the side effect of creating and opening all of the
+ * element's parents if they are not yet open.
+ *
+ * @param the given folder
+ * @return the package fragment or package fragment root corresponding to the given folder, or
+ * null
if unable to associate the given folder with a Java element
+ */
+public static IJavaElement create(IFolder folder) {
+ return JavaModelManager.create(folder, null);
+}
+/**
+ * Returns the Java project corresponding to the given project.
+ *
+ * Creating a Java Project has the side effect of creating and opening all of the + * project's parents if they are not yet open. + *
+ * Note that no check is done at this time on the existence or the java nature of this project.
+ *
+ * @param project the given project
+ * @return the Java project corresponding to the given project, null if the given project is null
+ */
+public static IJavaProject create(IProject project) {
+ if (project == null) {
+ return null;
+ }
+ JavaModel javaModel = JavaModelManager.getJavaModelManager().getJavaModel();
+ return javaModel.getJavaProject(project);
+}
+/**
+ * Returns the Java element corresponding to the given resource, or
+ * null
if unable to associate the given resource
+ * with a Java element.
+ *
+ * The resource must be one of:
IJavaProject
.java
file - the element returned is the corresponding ICompilationUnit
.class
file - the element returned is the corresponding IClassFile
.jar
file - the element returned is the corresponding IPackageFragmentRoot
IPackageFragmentRoot
+ * or IPackageFragment
IJavaModel
+ * Creating a Java element has the side effect of creating and opening all of the
+ * element's parents if they are not yet open.
+ *
+ * @param resource the given resource
+ * @return the Java element corresponding to the given resource, or
+ * null
if unable to associate the given resource
+ * with a Java element
+ */
+public static IJavaElement create(IResource resource) {
+ return JavaModelManager.create(resource, null);
+}
+/**
+ * Returns the Java model.
+ *
+ * @param root the given root
+ * @return the Java model, or null
if the root is null
+ */
+public static IJavaModel create(IWorkspaceRoot root) {
+ if (root == null) {
+ return null;
+ }
+ return JavaModelManager.getJavaModelManager().getJavaModel();
+}
+/**
+ * Creates and returns a class file element for
+ * the given .class
file. Returns null
if unable
+ * to recognize the class file.
+ *
+ * @param file the given .class
file
+ * @return a class file element for the given .class
file, or null
if unable
+ * to recognize the class file
+ */
+//public static IClassFile createClassFileFrom(IFile file) {
+// return JavaModelManager.createClassFileFrom(file, null);
+//}
+/**
+ * Creates and returns a compilation unit element for
+ * the given .java
file. Returns null
if unable
+ * to recognize the compilation unit.
+ *
+ * @param file the given .java
file
+ * @return a compilation unit element for the given .java
file, or null
if unable
+ * to recognize the compilation unit
+ */
+public static ICompilationUnit createCompilationUnitFrom(IFile file) {
+ return JavaModelManager.createCompilationUnitFrom(file, null);
+}
+/**
+ * Creates and returns a handle for the given JAR file.
+ * The Java model associated with the JAR's project may be
+ * created as a side effect.
+ *
+ * @param file the given JAR file
+ * @return a handle for the given JAR file, or null
if unable to create a JAR package fragment root.
+ * (for example, if the JAR file represents a non-Java resource)
+ */
+//public static IPackageFragmentRoot createJarPackageFragmentRootFrom(IFile file) {
+// return JavaModelManager.createJarPackageFragmentRootFrom(file, null);
+//}
+
+/**
+ * Answers the project specific value for a given classpath container.
+ * In case this container path could not be resolved, then will answer null
.
+ * Both the container path and the project context are supposed to be non-null.
+ *
+ * The containerPath is a formed by a first ID segment followed with extra segments, which can be
+ * used as additional hints for resolution. If no container was ever recorded for this container path
+ * onto this project (using setClasspathContainer
, then a
+ * ClasspathContainerInitializer
will be activated if any was registered for this container
+ * ID onto the extension point "org.eclipse.jdt.core.classpathContainerInitializer".
+ *
+ * There is no assumption that the returned container must answer the exact same containerPath
+ * when requested IClasspathContainer#getPath
.
+ * Indeed, the containerPath is just an indication for resolving it to an actual container object.
+ *
+ * Classpath container values are persisted locally to the workspace, but
+ * are not preserved from a session to another. It is thus highly recommended to register a
+ * ClasspathContainerInitializer
for each referenced container
+ * (through the extension point "org.eclipse.jdt.core.ClasspathContainerInitializer").
+ *
+ * @param containerPath the name of the container, which needs to be resolved
+ * @param project a specific project in which the container is being resolved
+ * @return the corresponding classpath container or null
if unable to find one.
+ *
+ * @exception JavaModelException if an exception occurred while resolving the container, or if the resolved container
+ * contains illegal entries (contains CPE_CONTAINER entries or null entries).
+ *
+ * @see ClasspathContainerInitializer
+ * @see IClasspathContainer
+ * @see #setClasspathContainer(IPath, IJavaProject[], IClasspathContainer[], IProgressMonitor)
+ * @since 2.0
+ */
+//public static IClasspathContainer getClasspathContainer(final IPath containerPath, final IJavaProject project) throws JavaModelException {
+//
+// IClasspathContainer container = JavaModelManager.containerGet(project, containerPath);
+// if (container == JavaModelManager.ContainerInitializationInProgress) return null; // break cycle
+//
+// if (container == null){
+// final ClasspathContainerInitializer initializer = JavaCore.getClasspathContainerInitializer(containerPath.segment(0));
+// if (initializer != null){
+// if (JavaModelManager.CP_RESOLVE_VERBOSE){
+// System.out.println("CPContainer INIT - triggering initialization of: ["+project.getElementName()+"] " + containerPath + " using initializer: "+ initializer); //$NON-NLS-1$ //$NON-NLS-2$//$NON-NLS-3$
+// new Exception("FAKE exception for dumping current CPContainer (["+project.getElementName()+"] "+ containerPath+ ")INIT invocation stack trace").printStackTrace(); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
+// }
+// JavaModelManager.containerPut(project, containerPath, JavaModelManager.ContainerInitializationInProgress); // avoid initialization cycles
+// boolean ok = false;
+// try {
+// // wrap initializer call with Safe runnable in case initializer would be causing some grief
+// Platform.run(new ISafeRunnable() {
+// public void handleException(Throwable exception) {
+// Util.log(exception, "Exception occurred in classpath container initializer: "+initializer); //$NON-NLS-1$
+// }
+// public void run() throws Exception {
+// initializer.initialize(containerPath, project);
+// }
+// });
+//
+// // retrieve value (if initialization was successful)
+// container = JavaModelManager.containerGet(project, containerPath);
+// if (container == JavaModelManager.ContainerInitializationInProgress) return null; // break cycle
+// ok = true;
+// } finally {
+// if (!ok) JavaModelManager.containerPut(project, containerPath, null); // flush cache
+// }
+// if (JavaModelManager.CP_RESOLVE_VERBOSE){
+// System.out.print("CPContainer INIT - after resolution: ["+project.getElementName()+"] " + containerPath + " --> "); //$NON-NLS-2$//$NON-NLS-1$//$NON-NLS-3$
+// if (container != null){
+// System.out.print("container: "+container.getDescription()+" {"); //$NON-NLS-2$//$NON-NLS-1$
+// IClasspathEntry[] entries = container.getClasspathEntries();
+// if (entries != null){
+// for (int i = 0; i < entries.length; i++){
+// if (i > 0) System.out.println(", ");//$NON-NLS-1$
+// System.out.println(entries[i]);
+// }
+// }
+// System.out.println("}");//$NON-NLS-1$
+// } else {
+// System.out.println("{unbound}");//$NON-NLS-1$
+// }
+// }
+// } else {
+// if (JavaModelManager.CP_RESOLVE_VERBOSE){
+// System.out.println("CPContainer INIT - no initializer found for: "+project.getElementName()+"] " + containerPath); //$NON-NLS-1$ //$NON-NLS-2$
+// }
+// }
+// }
+// return container;
+//}
+
+/**
+ * Helper method finding the classpath container initializer registered for a given classpath container ID
+ * or null
if none was found while iterating over the contributions to extension point to
+ * the extension point "org.eclipse.jdt.core.classpathContainerInitializer".
+ *
+ * A containerID is the first segment of any container path, used to identify the registered container initializer. + *
+ * @param String - a containerID identifying a registered initializer
+ * @return ClasspathContainerInitializer - the registered classpath container initializer or
+ * Classpath variable values are persisted locally to the workspace, and
+ * are preserved from session to session.
+ *
+ * Note that classpath variables can be contributed registered initializers for,
+ * using the extension point "org.eclipse.jdt.core.classpathVariableInitializer".
+ * If an initializer is registered for a variable, its persisted value will be ignored:
+ * its initializer will thus get the opportunity to rebind the variable differently on
+ * each session.
+ *
+ * @param variableName the name of the classpath variable
+ * @return the path, or
+ * @param the given variable
+ * @return ClasspathVariableInitializer - the registered classpath variable initializer or
+ * Classpath variable values are persisted locally to the workspace, and
+ * are preserved from session to session.
+ *
+ *
+ * @return the list of classpath variable names
+ * @see #setClasspathVariable
+ */
+//public static String[] getClasspathVariableNames() {
+// return JavaModelManager.variableNames();
+//}
+
+/**
+ * Returns a table of all known configurable options with their default values.
+ * These options allow to configure the behaviour of the underlying components.
+ * The client may safely use the result as a template that they can modify and
+ * then pass to
+ * For a complete description of the configurable options, see
+ * For a complete description of the configurable options, see
+ * Variable source attachment path and root path are also resolved and recorded in the resulting classpath entry.
+ *
+ * NOTE: This helper method does not handle classpath containers, for which should rather be used
+ *
+ *
+ * @param entry the given variable entry
+ * @return the resolved library or project classpath entry, or
+ * A container entry allows to express indirect references to a set of libraries, projects and variable entries,
+ * which can be interpreted differently for each Java project where it is used.
+ * A classpath container entry can be resolved using
+ * A container is exclusively resolved by a
+ * A container path must be formed of at least one segment, where:
+ * Example of an ClasspathContainerInitializer for a classpath container denoting a default JDK container:
+ *
+ * containerEntry = JavaCore.newContainerEntry(new Path("MyProvidedJDK/default"));
+ *
+ *
+ * Note that this operation does not attempt to validate classpath containers
+ * or access the resources at the given paths.
+ *
+ * The resulting entry is not exported to dependent projects. This method is equivalent to
+ *
+ * @param containerPath the path identifying the container, it must be formed of two
+ * segments
+ * @return a new container classpath entry
+ *
+ * @see JavaCore#getClasspathContainer(IPath, IJavaProject)
+ * @see JavaCore#newContainerEntry(IPath, boolean)
+ * @since 2.0
+ */
+public static IClasspathEntry newContainerEntry(IPath containerPath) {
+
+ return newContainerEntry(containerPath, false);
+}
+
+/**
+ * Creates and returns a new classpath entry of kind
+ * A container entry allows to express indirect references to a set of libraries, projects and variable entries,
+ * which can be interpreted differently for each Java project where it is used.
+ * A classpath container entry can be resolved using
+ * A container is exclusively resolved by a
+ * A container path must be formed of at least one segment, where:
+ * Example of an ClasspathContainerInitializer for a classpath container denoting a default JDK container:
+ *
+ * containerEntry = JavaCore.newContainerEntry(new Path("MyProvidedJDK/default"));
+ *
+ *
+ * Note that this operation does not attempt to validate classpath containers
+ * or access the resources at the given paths.
+ *
+ * @param containerPath the path identifying the container, it must be formed of at least
+ * one segment (ID+hints)
+ * @param isExported a boolean indicating whether this entry is contributed to dependent
+ * projects in addition to the output location
+ * @return a new container classpath entry
+ *
+ * @see JavaCore#getClasspathContainer(IPath, IJavaProject)
+ * @see JavaCore#setClasspathContainer(IPath, IJavaProject[], IClasspathContainer[], IProgressMonitor)
+ * @see JavaCore#newContainerEntry(IPath, boolean)
+ * @since 2.0
+ */
+public static IClasspathEntry newContainerEntry(IPath containerPath, boolean isExported) {
+
+ if (containerPath == null || containerPath.segmentCount() < 1) {
+ Assert.isTrue(
+ false,
+ "Illegal classpath container path: \'" + containerPath.makeRelative().toString() + "\', must have at least one segment (containerID+hints)"); //$NON-NLS-1$//$NON-NLS-2$
+ }
+ return new ClasspathEntry(
+ IPackageFragmentRoot.K_SOURCE,
+ IClasspathEntry.CPE_CONTAINER,
+ containerPath,
+ ClasspathEntry.NO_EXCLUSION_PATTERNS,
+ null, // source attachment
+ null, // source attachment root
+ null, // specific output folder
+ isExported);
+}
+
+/**
+ * Creates and returns a new non-exported classpath entry of kind
+ * A library entry is used to denote a prerequisite JAR or root folder containing binaries.
+ * The target JAR or folder can either be defined internally to the workspace (absolute path relative
+ * to the workspace root) or externally to the workspace (absolute path in the file system).
+ *
+ * e.g. Here are some examples of binary path usage
+ * The resulting entry is not exported to dependent projects. This method is equivalent to
+ *
+ *
+ * @param path the absolute path of the binary archive
+ * @param sourceAttachmentPath the absolute path of the corresponding source archive or folder,
+ * or
+ * A library entry is used to denote a prerequisite JAR or root folder containing binaries.
+ * The target JAR or folder can either be defined internally to the workspace (absolute path relative
+ * to the workspace root) or externally to the workspace (absolute path in the file system).
+ *
+ * e.g. Here are some examples of binary path usage
+ *
+ * @param path the absolute path of the binary archive
+ * @param sourceAttachmentPath the absolute path of the corresponding source archive or folder,
+ * or
+ * A project entry is used to denote a prerequisite project on a classpath.
+ * The referenced project will be contributed as a whole, either as sources (in the Java Model, it
+ * contributes all its package fragment roots) or as binaries (when building, it contributes its
+ * whole output location).
+ *
+ * A project reference allows to indirect through another project, independently from its internal layout.
+ *
+ * The prerequisite project is referred to using an absolute path relative to the workspace root.
+ *
+ * The resulting entry is not exported to dependent projects. This method is equivalent to
+ *
+ *
+ * @param path the absolute path of the binary archive
+ * @return a new project classpath entry
+ *
+ * @see JavaCore#newProjectEntry(IPath, boolean)
+ */
+public static IClasspathEntry newProjectEntry(IPath path) {
+ return newProjectEntry(path, false);
+}
+
+/**
+ * Creates and returns a new classpath entry of kind
+ * A project entry is used to denote a prerequisite project on a classpath.
+ * The referenced project will be contributed as a whole, either as sources (in the Java Model, it
+ * contributes all its package fragment roots) or as binaries (when building, it contributes its
+ * whole output location).
+ *
+ * A project reference allows to indirect through another project, independently from its internal layout.
+ *
+ * The prerequisite project is referred to using an absolute path relative to the workspace root.
+ *
+ *
+ * @param path the absolute path of the prerequisite project
+ * @param isExported indicates whether this entry is contributed to dependent
+ * projects in addition to the output location
+ * @return a new project classpath entry
+ * @since 2.0
+ */
+public static IClasspathEntry newProjectEntry(IPath path, boolean isExported) {
+
+ if (!path.isAbsolute()) Assert.isTrue(false, "Path for IClasspathEntry must be absolute"); //$NON-NLS-1$
+
+ return new ClasspathEntry(
+ IPackageFragmentRoot.K_SOURCE,
+ IClasspathEntry.CPE_PROJECT,
+ path,
+ ClasspathEntry.NO_EXCLUSION_PATTERNS,
+ null, // source attachment
+ null, // source attachment root
+ null, // specific output folder
+ isExported);
+}
+
+/**
+ * Returns a new empty region.
+ *
+ * @return a new empty region
+ */
+public static IRegion newRegion() {
+ return new Region();
+}
+
+/**
+ * Creates and returns a new classpath entry of kind
+ * The source folder is referred to using an absolute path relative to the
+ * workspace root, e.g.
+ * The source classpath entry created by this method includes all source
+ * files below the given workspace-relative path. To selectively exclude
+ * some of these source files, use the factory method
+ *
+ * Note that all sources/binaries inside a project are contributed as a whole through
+ * a project entry (see
+ * The source folder is referred to using an absolute path relative to the
+ * workspace root, e.g.
+ * The source classpath entry created by this method includes all source
+ * files below the given workspace-relative path except for those matched
+ * by one (or more) of the given exclusion patterns. Each exclusion pattern
+ * is represented by a relative path, which is interpreted as relative to
+ * the source folder. For example, if the source folder path is
+ *
+ * Note that all sources/binaries inside a project are contributed as a whole through
+ * a project entry (see
+ * The source folder is referred to using an absolute path relative to the
+ * workspace root, e.g.
+ * The source classpath entry created by this method includes all source
+ * files below the given workspace-relative path except for those matched
+ * by one (or more) of the given exclusion patterns. Each exclusion pattern
+ * is represented by a relative path, which is interpreted as relative to
+ * the source folder. For example, if the source folder path is
+ *
+ * Additionally, a source entry can be associated with a specific output location.
+ * By doing so, the Java builder will ensure that the generated ".class" files will
+ * be issued inside this output location, as opposed to be generated into the
+ * project default output location (when output location is
+ * Also note that all sources/binaries inside a project are contributed as a whole through
+ * a project entry (see
+ * A variable entry allows to express indirect references on a classpath to other projects or libraries,
+ * depending on what the classpath variable is referring.
+ *
+ * It is possible to register an automatic initializer (null
if
+ * none was found.
+ * @since 2.1
+ */
+//public static ClasspathContainerInitializer getClasspathContainerInitializer(String containerID){
+//
+// Plugin jdtCorePlugin = JavaCore.getPlugin();
+// if (jdtCorePlugin == null) return null;
+//
+// IExtensionPoint extension = jdtCorePlugin.getDescriptor().getExtensionPoint(JavaModelManager.CPCONTAINER_INITIALIZER_EXTPOINT_ID);
+// if (extension != null) {
+// IExtension[] extensions = extension.getExtensions();
+// for(int i = 0; i < extensions.length; i++){
+// IConfigurationElement [] configElements = extensions[i].getConfigurationElements();
+// for(int j = 0; j < configElements.length; j++){
+// String initializerID = configElements[j].getAttribute("id"); //$NON-NLS-1$
+// if (initializerID != null && initializerID.equals(containerID)){
+// if (JavaModelManager.CP_RESOLVE_VERBOSE) {
+// System.out.println("CPContainer INIT - found initializer: "+containerID +" --> " + configElements[j].getAttribute("class"));//$NON-NLS-3$//$NON-NLS-2$//$NON-NLS-1$
+// }
+// try {
+// Object execExt = configElements[j].createExecutableExtension("class"); //$NON-NLS-1$
+// if (execExt instanceof ClasspathContainerInitializer){
+// return (ClasspathContainerInitializer)execExt;
+// }
+// } catch(CoreException e) {
+// }
+// }
+// }
+// }
+// }
+// return null;
+//}
+
+/**
+ * Returns the path held in the given classpath variable.
+ * Returns null
if none
+ * @see #setClasspathVariable
+ */
+public static IPath getClasspathVariable(final String variableName) {
+
+ IPath variablePath = JavaModelManager.variableGet(variableName);
+ if (variablePath == JavaModelManager.VariableInitializationInProgress) return null; // break cycle
+
+ if (variablePath != null) {
+ return variablePath;
+ }
+
+ // even if persisted value exists, initializer is given priority, only if no initializer is found the persisted value is reused
+// final ClasspathVariableInitializer initializer = PHPCore.getClasspathVariableInitializer(variableName);
+// if (initializer != null){
+// if (JavaModelManager.CP_RESOLVE_VERBOSE){
+// System.out.println("CPVariable INIT - triggering initialization of: " + variableName+ " using initializer: "+ initializer); //$NON-NLS-1$ //$NON-NLS-2$
+// new Exception("FAKE exception for dumping current CPVariable ("+variableName+ ")INIT invocation stack trace").printStackTrace(); //$NON-NLS-1$//$NON-NLS-2$
+// }
+// JavaModelManager.variablePut(variableName, JavaModelManager.VariableInitializationInProgress); // avoid initialization cycles
+// boolean ok = false;
+// try {
+// // wrap initializer call with Safe runnable in case initializer would be causing some grief
+// Platform.run(new ISafeRunnable() {
+// public void handleException(Throwable exception) {
+// Util.log(exception, "Exception occurred in classpath variable initializer: "+initializer+" while initializing variable: "+variableName); //$NON-NLS-1$ //$NON-NLS-2$
+// }
+// public void run() throws Exception {
+// initializer.initialize(variableName);
+// }
+// });
+// variablePath = (IPath) JavaModelManager.variableGet(variableName); // initializer should have performed side-effect
+// if (variablePath == JavaModelManager.VariableInitializationInProgress) return null; // break cycle (initializer did not init or reentering call)
+// if (JavaModelManager.CP_RESOLVE_VERBOSE){
+// System.out.println("CPVariable INIT - after initialization: " + variableName + " --> " + variablePath); //$NON-NLS-2$//$NON-NLS-1$
+// }
+// ok = true;
+// } finally {
+// if (!ok) JavaModelManager.variablePut(variableName, null); // flush cache
+// }
+// } else {
+// if (JavaModelManager.CP_RESOLVE_VERBOSE){
+// System.out.println("CPVariable INIT - no initializer found for: " + variableName); //$NON-NLS-1$
+// }
+// }
+ return variablePath;
+}
+
+/**
+ * Helper method finding the classpath variable initializer registered for a given classpath variable name
+ * or null
if none was found while iterating over the contributions to extension point to
+ * the extension point "org.eclipse.jdt.core.classpathVariableInitializer".
+ * null
if
+ * none was found.
+ * @since 2.1
+ */
+public static ClasspathVariableInitializer getClasspathVariableInitializer(String variable){
+
+ Plugin jdtCorePlugin = PHPCore.getPlugin();
+ if (jdtCorePlugin == null) return null;
+
+// IExtensionPoint extension = jdtCorePlugin.getDescriptor().getExtensionPoint(JavaModelManager.CPVARIABLE_INITIALIZER_EXTPOINT_ID);
+// if (extension != null) {
+// IExtension[] extensions = extension.getExtensions();
+// for(int i = 0; i < extensions.length; i++){
+// IConfigurationElement [] configElements = extensions[i].getConfigurationElements();
+// for(int j = 0; j < configElements.length; j++){
+// try {
+// String varAttribute = configElements[j].getAttribute("variable"); //$NON-NLS-1$
+// if (variable.equals(varAttribute)) {
+// if (JavaModelManager.CP_RESOLVE_VERBOSE) {
+// System.out.println("CPVariable INIT - found initializer: "+variable+" --> " + configElements[j].getAttribute("class"));//$NON-NLS-3$//$NON-NLS-2$//$NON-NLS-1$
+// }
+// Object execExt = configElements[j].createExecutableExtension("class"); //$NON-NLS-1$
+// if (execExt instanceof ClasspathVariableInitializer){
+// return (ClasspathVariableInitializer)execExt;
+// }
+// }
+// } catch(CoreException e){
+// }
+// }
+// }
+// }
+ return null;
+}
+
+/**
+ * Returns the names of all known classpath variables.
+ * setOptions
.
+ *
+ * Helper constants have been defined on JavaCore for each of the option ID and
+ * their possible constant values.
+ *
+ * Note: more options might be added in further releases.
+ *
+ * RECOGNIZED OPTIONS:
+ * COMPILER / Generating Local Variable Debug Attribute
+ * When generated, this attribute will enable local variable names
+ * to be displayed in debugger, only in place where variables are
+ * definitely assigned (.class file is then bigger)
+ * - option id: "org.eclipse.jdt.core.compiler.debug.localVariable"
+ * - possible values: { "generate", "do not generate" }
+ * - default: "generate"
+ *
+ * COMPILER / Generating Line Number Debug Attribute
+ * When generated, this attribute will enable source code highlighting in debugger
+ * (.class file is then bigger).
+ * - option id: "org.eclipse.jdt.core.compiler.debug.lineNumber"
+ * - possible values: { "generate", "do not generate" }
+ * - default: "generate"
+ *
+ * COMPILER / Generating Source Debug Attribute
+ * When generated, this attribute will enable the debugger to present the
+ * corresponding source code.
+ * - option id: "org.eclipse.jdt.core.compiler.debug.sourceFile"
+ * - possible values: { "generate", "do not generate" }
+ * - default: "generate"
+ *
+ * COMPILER / Preserving Unused Local Variables
+ * Unless requested to preserve unused local variables (that is, never read), the
+ * compiler will optimize them out, potentially altering debugging
+ * - option id: "org.eclipse.jdt.core.compiler.codegen.unusedLocal"
+ * - possible values: { "preserve", "optimize out" }
+ * - default: "preserve"
+ *
+ * COMPILER / Defining Target Java Platform
+ * For binary compatibility reason, .class files can be tagged to with certain VM versions and later.
+ * Note that "1.4" target require to toggle compliance mode to "1.4" too.
+ * - option id: "org.eclipse.jdt.core.compiler.codegen.targetPlatform"
+ * - possible values: { "1.1", "1.2", "1.3", "1.4" }
+ * - default: "1.1"
+ *
+ * COMPILER / Reporting Unreachable Code
+ * Unreachable code can optionally be reported as an error, warning or simply
+ * ignored. The bytecode generation will always optimized it out.
+ * - option id: "org.eclipse.jdt.core.compiler.problem.unreachableCode"
+ * - possible values: { "error", "warning", "ignore" }
+ * - default: "error"
+ *
+ * COMPILER / Reporting Invalid Import
+ * An import statement that cannot be resolved might optionally be reported
+ * as an error, as a warning or ignored.
+ * - option id: "org.eclipse.jdt.core.compiler.problem.invalidImport"
+ * - possible values: { "error", "warning", "ignore" }
+ * - default: "error"
+ *
+ * COMPILER / Reporting Attempt to Override Package-Default Method
+ * A package default method is not visible in a different package, and thus
+ * cannot be overridden. When enabling this option, the compiler will signal
+ * such scenarii either as an error or a warning.
+ * - option id: "org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod"
+ * - possible values: { "error", "warning", "ignore" }
+ * - default: "warning"
+ *
+ * COMPILER / Reporting Method With Constructor Name
+ * Naming a method with a constructor name is generally considered poor
+ * style programming. When enabling this option, the compiler will signal such
+ * scenarii either as an error or a warning.
+ * - option id: "org.eclipse.jdt.core.compiler.problem.methodWithConstructorName"
+ * - possible values: { "error", "warning", "ignore" }
+ * - default: "warning"
+ *
+ * COMPILER / Reporting Deprecation
+ * When enabled, the compiler will signal use of deprecated API either as an
+ * error or a warning.
+ * - option id: "org.eclipse.jdt.core.compiler.problem.deprecation"
+ * - possible values: { "error", "warning", "ignore" }
+ * - default: "warning"
+ *
+ * COMPILER / Reporting Deprecation Inside Deprecated Code
+ * When enabled, the compiler will signal use of deprecated API inside deprecated code.
+ * The severity of the problem is controlled with option "org.eclipse.jdt.core.compiler.problem.deprecation".
+ * - option id: "org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode"
+ * - possible values: { "enabled", "disabled" }
+ * - default: "disabled"
+ *
+ * COMPILER / Reporting Hidden Catch Block
+ * Locally to a try statement, some catch blocks may hide others . For example,
+ * try { throw new java.io.CharConversionException();
+ * } catch (java.io.CharConversionException e) {
+ * } catch (java.io.IOException e) {}.
+ * When enabling this option, the compiler will issue an error or a warning for hidden
+ * catch blocks corresponding to checked exceptions
+ * - option id: "org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock"
+ * - possible values: { "error", "warning", "ignore" }
+ * - default: "warning"
+ *
+ * COMPILER / Reporting Unused Local
+ * When enabled, the compiler will issue an error or a warning for unused local
+ * variables (that is, variables never read from)
+ * - option id: "org.eclipse.jdt.core.compiler.problem.unusedLocal"
+ * - possible values: { "error", "warning", "ignore" }
+ * - default: "ignore"
+ *
+ * COMPILER / Reporting Unused Parameter
+ * When enabled, the compiler will issue an error or a warning for unused method
+ * parameters (that is, parameters never read from)
+ * - option id: "org.eclipse.jdt.core.compiler.problem.unusedParameter"
+ * - possible values: { "error", "warning", "ignore" }
+ * - default: "ignore"
+ *
+ * COMPILER / Reporting Unused Parameter if Implementing Abstract Method
+ * When enabled, the compiler will signal unused parameters in abstract method implementations.
+ * The severity of the problem is controlled with option "org.eclipse.jdt.core.compiler.problem.unusedParameter".
+ * - option id: "org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract"
+ * - possible values: { "enabled", "disabled" }
+ * - default: "disabled"
+ *
+ * COMPILER / Reporting Unused Parameter if Overriding Concrete Method
+ * When enabled, the compiler will signal unused parameters in methods overriding concrete ones.
+ * The severity of the problem is controlled with option "org.eclipse.jdt.core.compiler.problem.unusedParameter".
+ * - option id: "org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete"
+ * - possible values: { "enabled", "disabled" }
+ * - default: "disabled"
+ *
+ * COMPILER / Reporting Unused Import
+ * When enabled, the compiler will issue an error or a warning for unused import
+ * reference
+ * - option id: "org.eclipse.jdt.core.compiler.problem.unusedImport"
+ * - possible values: { "error", "warning", "ignore" }
+ * - default: "warning"
+ *
+ * COMPILER / Reporting Unused Private Members
+ * When enabled, the compiler will issue an error or a warning whenever a private
+ * method or field is declared but never used within the same unit.
+ * - option id: "org.eclipse.jdt.core.compiler.problem.unusedPrivateMember"
+ * - possible values: { "error", "warning", "ignore" }
+ * - default: "ignore"
+ *
+ * COMPILER / Reporting Synthetic Access Emulation
+ * When enabled, the compiler will issue an error or a warning whenever it emulates
+ * access to a non-accessible member of an enclosing type. Such access can have
+ * performance implications.
+ * - option id: "org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation"
+ * - possible values: { "error", "warning", "ignore" }
+ * - default: "ignore"
+ *
+ * COMPILER / Reporting Non-Externalized String Literal
+ * When enabled, the compiler will issue an error or a warning for non externalized
+ * String literal (that is, not tagged with //$NON-NLS-
+ *
+ * @return a mutable table containing the default settings of all known options
+ * (key type: String
; value type: String
)
+ * @see #setOptions
+ */
+public static Hashtable getDefaultOptions(){
+
+ Hashtable defaultOptions = new Hashtable(10);
+
+ // see #initializeDefaultPluginPreferences() for changing default settings
+ Preferences preferences = getPlugin().getPluginPreferences();
+ HashSet optionNames = JavaModelManager.OptionNames;
+
+ // get preferences set to their default
+ String[] defaultPropertyNames = preferences.defaultPropertyNames();
+ for (int i = 0; i < defaultPropertyNames.length; i++){
+ String propertyName = defaultPropertyNames[i];
+ if (optionNames.contains(propertyName)) {
+ defaultOptions.put(propertyName, preferences.getDefaultString(propertyName));
+ }
+ }
+ // get preferences not set to their default
+ String[] propertyNames = preferences.propertyNames();
+ for (int i = 0; i < propertyNames.length; i++){
+ String propertyName = propertyNames[i];
+ if (optionNames.contains(propertyName)) {
+ defaultOptions.put(propertyName, preferences.getDefaultString(propertyName));
+ }
+ }
+ // get encoding through resource plugin
+ defaultOptions.put(CORE_ENCODING, ResourcesPlugin.getEncoding());
+
+ return defaultOptions;
+}
+
+/**
+ * Returns the single instance of the Java core plug-in runtime class.
+ * Equivalent to (JavaCore) getPlugin()
.
+ *
+ * @return the single instance of the Java core plug-in runtime class
+ */
+public static PHPeclipsePlugin getJavaCore() {
+ return (PHPeclipsePlugin) getPlugin();
+}
+
+/**
+ * Helper method for returning one option value only. Equivalent to (String)JavaCore.getOptions().get(optionName)
+ * Note that it may answer null
if this option does not exist.
+ * getDefaultOptions
.
+ * getDefaultOptions
.
+ * String
; value type: String
)
+ * @see JavaCore#getDefaultOptions
+ */
+public static Hashtable getOptions() {
+
+ Hashtable options = new Hashtable(10);
+
+ // see #initializeDefaultPluginPreferences() for changing default settings
+ Plugin plugin = getPlugin();
+ if (plugin != null) {
+ Preferences preferences = getPlugin().getPluginPreferences();
+ HashSet optionNames = JavaModelManager.OptionNames;
+
+ // get preferences set to their default
+ String[] defaultPropertyNames = preferences.defaultPropertyNames();
+ for (int i = 0; i < defaultPropertyNames.length; i++){
+ String propertyName = defaultPropertyNames[i];
+ if (optionNames.contains(propertyName)){
+ options.put(propertyName, preferences.getDefaultString(propertyName));
+ }
+ }
+ // get preferences not set to their default
+ String[] propertyNames = preferences.propertyNames();
+ for (int i = 0; i < propertyNames.length; i++){
+ String propertyName = propertyNames[i];
+ if (optionNames.contains(propertyName)){
+ options.put(propertyName, preferences.getString(propertyName).trim());
+ }
+ }
+ // get encoding through resource plugin
+ options.put(CORE_ENCODING, ResourcesPlugin.getEncoding());
+ }
+ return options;
+}
+
+/**
+ * This is a helper method, which returns the resolved classpath entry denoted
+ * by a given entry (if it is a variable entry). It is obtained by resolving the variable
+ * reference in the first segment. Returns
+ *
+ * null
null
JavaCore#getClasspathContainer(IPath, IJavaProject)
.
+ * null
+ * if the given variable entry could not be resolved to a valid classpath entry
+ */
+public static IClasspathEntry getResolvedClasspathEntry(IClasspathEntry entry) {
+
+ if (entry.getEntryKind() != IClasspathEntry.CPE_VARIABLE)
+ return entry;
+
+ IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
+ IPath resolvedPath = PHPCore.getResolvedVariablePath(entry.getPath());
+ if (resolvedPath == null)
+ return null;
+
+ Object target = JavaModel.getTarget(workspaceRoot, resolvedPath, false);
+ if (target == null)
+ return null;
+
+ // inside the workspace
+ if (target instanceof IResource) {
+ IResource resolvedResource = (IResource) target;
+ if (resolvedResource != null) {
+ switch (resolvedResource.getType()) {
+
+ case IResource.PROJECT :
+ // internal project
+ return PHPCore.newProjectEntry(resolvedPath, entry.isExported());
+
+ case IResource.FILE :
+// if (Util.isArchiveFileName(resolvedResource.getName())) {
+// // internal binary archive
+// return JavaCore.newLibraryEntry(
+// resolvedPath,
+// getResolvedVariablePath(entry.getSourceAttachmentPath()),
+// getResolvedVariablePath(entry.getSourceAttachmentRootPath()),
+// entry.isExported());
+// }
+ break;
+
+ case IResource.FOLDER :
+ // internal binary folder
+// return JavaCore.newLibraryEntry(
+// resolvedPath,
+// getResolvedVariablePath(entry.getSourceAttachmentPath()),
+// getResolvedVariablePath(entry.getSourceAttachmentRootPath()),
+// entry.isExported());
+ break;
+ }
+ }
+ }
+ // outside the workspace
+ if (target instanceof File) {
+ File externalFile = (File) target;
+ if (externalFile.isFile()) {
+ String fileName = externalFile.getName().toLowerCase();
+// if (fileName.endsWith(".jar" //$NON-NLS-1$
+// ) || fileName.endsWith(".zip" //$NON-NLS-1$
+// )) { // external binary archive
+// return JavaCore.newLibraryEntry(
+// resolvedPath,
+// getResolvedVariablePath(entry.getSourceAttachmentPath()),
+// getResolvedVariablePath(entry.getSourceAttachmentRootPath()),
+// entry.isExported());
+// }
+ } else { // external binary folder
+ if (resolvedPath.isAbsolute()){
+// return JavaCore.newLibraryEntry(
+// resolvedPath,
+// getResolvedVariablePath(entry.getSourceAttachmentPath()),
+// getResolvedVariablePath(entry.getSourceAttachmentRootPath()),
+// entry.isExported());
+ }
+ }
+ }
+ return null;
+}
+
+
+/**
+ * Resolve a variable path (helper method).
+ *
+ * @param variablePath the given variable path
+ * @return the resolved variable path or null
if none
+ */
+public static IPath getResolvedVariablePath(IPath variablePath) {
+
+ if (variablePath == null)
+ return null;
+ int count = variablePath.segmentCount();
+ if (count == 0)
+ return null;
+
+ // lookup variable
+ String variableName = variablePath.segment(0);
+ IPath resolvedPath = PHPCore.getClasspathVariable(variableName);
+ if (resolvedPath == null)
+ return null;
+
+ // append path suffix
+ if (count > 1) {
+ resolvedPath = resolvedPath.append(variablePath.removeFirstSegments(1));
+ }
+ return resolvedPath;
+}
+
+/**
+ * Answers the shared working copies currently registered for this buffer factory.
+ * Working copies can be shared by several clients using the same buffer factory,see
+ * IWorkingCopy.getSharedWorkingCopy
.
+ *
+ * @param factory the given buffer factory
+ * @return the list of shared working copies for a given buffer factory
+ * @see IWorkingCopy
+ * @since 2.0
+ */
+public static IWorkingCopy[] getSharedWorkingCopies(IBufferFactory factory){
+
+ // if factory is null, default factory must be used
+ if (factory == null) factory = BufferManager.getDefaultBufferManager().getDefaultBufferFactory();
+ Map sharedWorkingCopies = JavaModelManager.getJavaModelManager().sharedWorkingCopies;
+
+ Map perFactoryWorkingCopies = (Map) sharedWorkingCopies.get(factory);
+ if (perFactoryWorkingCopies == null) return JavaModelManager.NoWorkingCopy;
+ Collection copies = perFactoryWorkingCopies.values();
+ IWorkingCopy[] result = new IWorkingCopy[copies.size()];
+ copies.toArray(result);
+ return result;
+}
+
+/**
+ * Initializes the default preferences settings for this plug-in.
+ */
+protected static void initializeDefaultPluginPreferences() {
+
+ Preferences preferences = PHPeclipsePlugin.getDefault().getPluginPreferences();
+ HashSet optionNames = JavaModelManager.OptionNames;
+
+ // Compiler settings
+ preferences.setDefault(COMPILER_LOCAL_VARIABLE_ATTR, GENERATE);
+ optionNames.add(COMPILER_LOCAL_VARIABLE_ATTR);
+
+ preferences.setDefault(COMPILER_LINE_NUMBER_ATTR, GENERATE);
+ optionNames.add(COMPILER_LINE_NUMBER_ATTR);
+
+ preferences.setDefault(COMPILER_SOURCE_FILE_ATTR, GENERATE);
+ optionNames.add(COMPILER_SOURCE_FILE_ATTR);
+
+ preferences.setDefault(COMPILER_CODEGEN_UNUSED_LOCAL, PRESERVE);
+ optionNames.add(COMPILER_CODEGEN_UNUSED_LOCAL);
+
+ preferences.setDefault(COMPILER_CODEGEN_TARGET_PLATFORM, VERSION_1_1);
+ optionNames.add(COMPILER_CODEGEN_TARGET_PLATFORM);
+
+ preferences.setDefault(COMPILER_PB_UNREACHABLE_CODE, ERROR);
+ optionNames.add(COMPILER_PB_UNREACHABLE_CODE);
+
+ preferences.setDefault(COMPILER_PB_INVALID_IMPORT, ERROR);
+ optionNames.add(COMPILER_PB_INVALID_IMPORT);
+
+ preferences.setDefault(COMPILER_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD, WARNING);
+ optionNames.add(COMPILER_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD);
+
+ preferences.setDefault(COMPILER_PB_METHOD_WITH_CONSTRUCTOR_NAME, WARNING);
+ optionNames.add(COMPILER_PB_METHOD_WITH_CONSTRUCTOR_NAME);
+
+ preferences.setDefault(COMPILER_PB_DEPRECATION, WARNING);
+ optionNames.add(COMPILER_PB_DEPRECATION);
+
+ preferences.setDefault(COMPILER_PB_DEPRECATION_IN_DEPRECATED_CODE, DISABLED);
+ optionNames.add(COMPILER_PB_DEPRECATION_IN_DEPRECATED_CODE);
+
+ preferences.setDefault(COMPILER_PB_HIDDEN_CATCH_BLOCK, WARNING);
+ optionNames.add(COMPILER_PB_HIDDEN_CATCH_BLOCK);
+
+ preferences.setDefault(COMPILER_PB_UNUSED_LOCAL, IGNORE);
+ optionNames.add(COMPILER_PB_UNUSED_LOCAL);
+
+ preferences.setDefault(COMPILER_PB_UNUSED_PARAMETER, IGNORE);
+ optionNames.add(COMPILER_PB_UNUSED_PARAMETER);
+
+ preferences.setDefault(COMPILER_PB_UNUSED_PARAMETER_WHEN_IMPLEMENTING_ABSTRACT, DISABLED);
+ optionNames.add(COMPILER_PB_UNUSED_PARAMETER_WHEN_IMPLEMENTING_ABSTRACT);
+
+ preferences.setDefault(COMPILER_PB_UNUSED_PARAMETER_WHEN_OVERRIDING_CONCRETE, DISABLED);
+ optionNames.add(COMPILER_PB_UNUSED_PARAMETER_WHEN_OVERRIDING_CONCRETE);
+
+ preferences.setDefault(COMPILER_PB_UNUSED_IMPORT, WARNING);
+ optionNames.add(COMPILER_PB_UNUSED_IMPORT);
+
+ preferences.setDefault(COMPILER_PB_UNUSED_PRIVATE_MEMBER, IGNORE);
+ optionNames.add(COMPILER_PB_UNUSED_PRIVATE_MEMBER);
+
+ preferences.setDefault(COMPILER_PB_SYNTHETIC_ACCESS_EMULATION, IGNORE);
+ optionNames.add(COMPILER_PB_SYNTHETIC_ACCESS_EMULATION);
+
+ preferences.setDefault(COMPILER_PB_NON_NLS_STRING_LITERAL, IGNORE);
+ optionNames.add(COMPILER_PB_NON_NLS_STRING_LITERAL);
+
+ preferences.setDefault(COMPILER_PB_ASSERT_IDENTIFIER, IGNORE);
+ optionNames.add(COMPILER_PB_ASSERT_IDENTIFIER);
+
+ preferences.setDefault(COMPILER_PB_STATIC_ACCESS_RECEIVER, WARNING);
+ optionNames.add(COMPILER_PB_STATIC_ACCESS_RECEIVER);
+
+ preferences.setDefault(COMPILER_PB_NO_EFFECT_ASSIGNMENT, WARNING);
+ optionNames.add(COMPILER_PB_NO_EFFECT_ASSIGNMENT);
+
+ preferences.setDefault(COMPILER_PB_INCOMPATIBLE_NON_INHERITED_INTERFACE_METHOD, WARNING);
+ optionNames.add(COMPILER_PB_INCOMPATIBLE_NON_INHERITED_INTERFACE_METHOD);
+
+ preferences.setDefault(COMPILER_PB_CHAR_ARRAY_IN_STRING_CONCATENATION, WARNING);
+ optionNames.add(COMPILER_PB_CHAR_ARRAY_IN_STRING_CONCATENATION);
+
+ preferences.setDefault(COMPILER_TASK_TAGS, DEFAULT_TASK_TAG); //$NON-NLS-1$
+ optionNames.add(COMPILER_TASK_TAGS);
+
+ preferences.setDefault(COMPILER_TASK_PRIORITIES, DEFAULT_TASK_PRIORITY); //$NON-NLS-1$
+ optionNames.add(COMPILER_TASK_PRIORITIES);
+
+ preferences.setDefault(COMPILER_SOURCE, VERSION_1_3);
+ optionNames.add(COMPILER_SOURCE);
+
+ preferences.setDefault(COMPILER_COMPLIANCE, VERSION_1_3);
+ optionNames.add(COMPILER_COMPLIANCE);
+
+ preferences.setDefault(COMPILER_PB_MAX_PER_UNIT, "100"); //$NON-NLS-1$
+ optionNames.add(COMPILER_PB_MAX_PER_UNIT);
+
+ // Builder settings
+ preferences.setDefault(CORE_JAVA_BUILD_RESOURCE_COPY_FILTER, ""); //$NON-NLS-1$
+ optionNames.add(CORE_JAVA_BUILD_RESOURCE_COPY_FILTER);
+
+ preferences.setDefault(CORE_JAVA_BUILD_INVALID_CLASSPATH, ABORT);
+ optionNames.add(CORE_JAVA_BUILD_INVALID_CLASSPATH);
+
+ preferences.setDefault(CORE_JAVA_BUILD_DUPLICATE_RESOURCE, WARNING);
+ optionNames.add(CORE_JAVA_BUILD_DUPLICATE_RESOURCE);
+
+ preferences.setDefault(CORE_JAVA_BUILD_CLEAN_OUTPUT_FOLDER, CLEAN);
+ optionNames.add(CORE_JAVA_BUILD_CLEAN_OUTPUT_FOLDER);
+
+ // JavaCore settings
+ preferences.setDefault(CORE_JAVA_BUILD_ORDER, IGNORE);
+ optionNames.add(CORE_JAVA_BUILD_ORDER);
+
+ preferences.setDefault(CORE_CIRCULAR_CLASSPATH, ERROR);
+ optionNames.add(CORE_CIRCULAR_CLASSPATH);
+
+ preferences.setDefault(CORE_INCOMPLETE_CLASSPATH, ERROR);
+ optionNames.add(CORE_INCOMPLETE_CLASSPATH);
+
+ preferences.setDefault(CORE_ENABLE_CLASSPATH_EXCLUSION_PATTERNS, ENABLED);
+ optionNames.add(CORE_ENABLE_CLASSPATH_EXCLUSION_PATTERNS);
+
+ preferences.setDefault(CORE_ENABLE_CLASSPATH_MULTIPLE_OUTPUT_LOCATIONS, ENABLED);
+ optionNames.add(CORE_ENABLE_CLASSPATH_MULTIPLE_OUTPUT_LOCATIONS);
+
+ // encoding setting comes from resource plug-in
+ optionNames.add(CORE_ENCODING);
+
+ // Formatter settings
+ preferences.setDefault(FORMATTER_NEWLINE_OPENING_BRACE, DO_NOT_INSERT);
+ optionNames.add(FORMATTER_NEWLINE_OPENING_BRACE);
+
+ preferences.setDefault(FORMATTER_NEWLINE_CONTROL, DO_NOT_INSERT);
+ optionNames.add(FORMATTER_NEWLINE_CONTROL);
+
+ preferences.setDefault(FORMATTER_CLEAR_BLANK_LINES, PRESERVE_ONE);
+ optionNames.add(FORMATTER_CLEAR_BLANK_LINES);
+
+ preferences.setDefault(FORMATTER_NEWLINE_ELSE_IF, DO_NOT_INSERT);
+ optionNames.add(FORMATTER_NEWLINE_ELSE_IF);
+
+ preferences.setDefault(FORMATTER_NEWLINE_EMPTY_BLOCK, INSERT);
+ optionNames.add(FORMATTER_NEWLINE_EMPTY_BLOCK);
+
+ preferences.setDefault(FORMATTER_LINE_SPLIT, "80"); //$NON-NLS-1$
+ optionNames.add(FORMATTER_LINE_SPLIT);
+
+ preferences.setDefault(FORMATTER_COMPACT_ASSIGNMENT, NORMAL);
+ optionNames.add(FORMATTER_COMPACT_ASSIGNMENT);
+
+ preferences.setDefault(FORMATTER_TAB_CHAR, TAB);
+ optionNames.add(FORMATTER_TAB_CHAR);
+
+ preferences.setDefault(FORMATTER_TAB_SIZE, "4"); //$NON-NLS-1$
+ optionNames.add(FORMATTER_TAB_SIZE);
+
+ preferences.setDefault(FORMATTER_SPACE_CASTEXPRESSION, INSERT); //$NON-NLS-1$
+ optionNames.add(FORMATTER_SPACE_CASTEXPRESSION);
+
+ // CodeAssist settings
+ preferences.setDefault(CODEASSIST_VISIBILITY_CHECK, DISABLED); //$NON-NLS-1$
+ optionNames.add(CODEASSIST_VISIBILITY_CHECK);
+
+ preferences.setDefault(CODEASSIST_IMPLICIT_QUALIFICATION, DISABLED); //$NON-NLS-1$
+ optionNames.add(CODEASSIST_IMPLICIT_QUALIFICATION);
+
+ preferences.setDefault(CODEASSIST_FIELD_PREFIXES, ""); //$NON-NLS-1$
+ optionNames.add(CODEASSIST_FIELD_PREFIXES);
+
+ preferences.setDefault(CODEASSIST_STATIC_FIELD_PREFIXES, ""); //$NON-NLS-1$
+ optionNames.add(CODEASSIST_STATIC_FIELD_PREFIXES);
+
+ preferences.setDefault(CODEASSIST_LOCAL_PREFIXES, ""); //$NON-NLS-1$
+ optionNames.add(CODEASSIST_LOCAL_PREFIXES);
+
+ preferences.setDefault(CODEASSIST_ARGUMENT_PREFIXES, ""); //$NON-NLS-1$
+ optionNames.add(CODEASSIST_ARGUMENT_PREFIXES);
+
+ preferences.setDefault(CODEASSIST_FIELD_SUFFIXES, ""); //$NON-NLS-1$
+ optionNames.add(CODEASSIST_FIELD_SUFFIXES);
+
+ preferences.setDefault(CODEASSIST_STATIC_FIELD_SUFFIXES, ""); //$NON-NLS-1$
+ optionNames.add(CODEASSIST_STATIC_FIELD_SUFFIXES);
+
+ preferences.setDefault(CODEASSIST_LOCAL_SUFFIXES, ""); //$NON-NLS-1$
+ optionNames.add(CODEASSIST_LOCAL_SUFFIXES);
+
+ preferences.setDefault(CODEASSIST_ARGUMENT_SUFFIXES, ""); //$NON-NLS-1$
+ optionNames.add(CODEASSIST_ARGUMENT_SUFFIXES);
+}
+
+/**
+ * Returns whether the given marker references the given Java element.
+ * Used for markers, which denote a Java element rather than a resource.
+ *
+ * @param element the element
+ * @param marker the marker
+ * @return true
if the marker references the element, false otherwise
+ * @exception CoreException if the IMarker.getAttribute
on the marker fails
+ */
+public static boolean isReferencedBy(IJavaElement element, IMarker marker) throws CoreException {
+
+ // only match units or classfiles
+ if (element instanceof IMember){
+ IMember member = (IMember) element;
+ if (member.isBinary()){
+ element = null; //member.getClassFile();
+ } else {
+ element = member.getCompilationUnit();
+ }
+ }
+ if (element == null) return false;
+ if (marker == null) return false;
+
+ String markerHandleId = (String)marker.getAttribute(ATT_HANDLE_ID);
+ if (markerHandleId == null) return false;
+
+ IJavaElement markerElement = PHPCore.create(markerHandleId);
+// while (true){
+ if (element.equals(markerElement)) return true; // external elements may still be equal with different handleIDs.
+
+ // cycle through enclosing types in case marker is associated with a classfile (15568)
+// if (markerElement instanceof IClassFile){
+// IType enclosingType = ((IClassFile)markerElement).getType().getDeclaringType();
+// if (enclosingType != null){
+// markerElement = enclosingType.getClassFile(); // retry with immediate enclosing classfile
+// continue;
+// }
+// }
+// break;
+// }
+ return false;
+}
+
+/**
+ * Returns whether the given marker delta references the given Java element.
+ * Used for markers deltas, which denote a Java element rather than a resource.
+ *
+ * @param element the element
+ * @param markerDelta the marker delta
+ * @return true
if the marker delta references the element
+ * @exception CoreException if the IMarkerDelta.getAttribute
on the marker delta fails
+ */
+public static boolean isReferencedBy(IJavaElement element, IMarkerDelta markerDelta) throws CoreException {
+
+ // only match units or classfiles
+ if (element instanceof IMember){
+ IMember member = (IMember) element;
+ if (member.isBinary()){
+ element = null; //member.getClassFile();
+ } else {
+ element = member.getCompilationUnit();
+ }
+ }
+ if (element == null) return false;
+ if (markerDelta == null) return false;
+
+ String markerDeltarHandleId = (String)markerDelta.getAttribute(ATT_HANDLE_ID);
+ if (markerDeltarHandleId == null) return false;
+
+ IJavaElement markerElement = PHPCore.create(markerDeltarHandleId);
+// while (true){
+ if (element.equals(markerElement)) return true; // external elements may still be equal with different handleIDs.
+
+ // cycle through enclosing types in case marker is associated with a classfile (15568)
+// if (markerElement instanceof IClassFile){
+// IType enclosingType = ((IClassFile)markerElement).getType().getDeclaringType();
+// if (enclosingType != null){
+// markerElement = enclosingType.getClassFile(); // retry with immediate enclosing classfile
+// continue;
+// }
+// }
+// break;
+// }
+ return false;
+}
+
+/**
+ * Creates and returns a new classpath entry of kind CPE_CONTAINER
+ * for the given path. The path of the container will be used during resolution so as to map this
+ * container entry to a set of other classpath entries the container is acting for.
+ * JavaCore.getResolvedClasspathContainer
,
+ * and updated with JavaCore.classpathContainerChanged
+ * ClasspathContainerInitializer
registered onto the
+ * extension point "org.eclipse.jdt.core.classpathContainerInitializer".
+ *
+ *
+ * newContainerEntry(-,false)
.
+ * CPE_CONTAINER
+ * for the given path. The path of the container will be used during resolution so as to map this
+ * container entry to a set of other classpath entries the container is acting for.
+ * JavaCore.getResolvedClasspathContainer
,
+ * and updated with JavaCore.classpathContainerChanged
+ * ClasspathContainerInitializer
registered onto the
+ * extension point "org.eclipse.jdt.core.classpathContainerInitializer".
+ *
+ *
+ * CPE_LIBRARY
for the
+ * JAR or folder identified by the given absolute path. This specifies that all package fragments
+ * within the root will have children of type IClassFile
.
+ *
+ *
+ * Note that this operation does not attempt to validate or access the
+ * resources at the given paths.
+ * "c:/jdk1.2.2/jre/lib/rt.jar"
- reference to an external JAR "/Project/someLib.jar"
- reference to an internal JAR "c:/classes/"
- reference to an external binary foldernewLibraryEntry(-,-,-,false)
.
+ * null
if none
+ * @param sourceAttachmentRootPath the location of the root within the source archive or folder
+ * or null
if this location should be automatically detected.
+ * @return a new library classpath entry
+ *
+ * @see #newLibraryEntry(IPath, IPath, IPath, boolean)
+ */
+//public static IClasspathEntry newLibraryEntry(
+// IPath path,
+// IPath sourceAttachmentPath,
+// IPath sourceAttachmentRootPath) {
+//
+// return newLibraryEntry(path, sourceAttachmentPath, sourceAttachmentRootPath, false);
+//}
+
+/**
+ * Creates and returns a new classpath entry of kind CPE_LIBRARY
for the JAR or folder
+ * identified by the given absolute path. This specifies that all package fragments within the root
+ * will have children of type IClassFile
.
+ *
+ *
+ * Note that this operation does not attempt to validate or access the
+ * resources at the given paths.
+ * "c:/jdk1.2.2/jre/lib/rt.jar"
- reference to an external JAR "/Project/someLib.jar"
- reference to an internal JAR "c:/classes/"
- reference to an external binary foldernull
if none
+ * @param sourceAttachmentRootPath the location of the root within the source archive or folder
+ * or null
if this location should be automatically detected.
+ * @param isExported indicates whether this entry is contributed to dependent
+ * projects in addition to the output location
+ * @return a new library classpath entry
+ * @since 2.0
+ */
+//public static IClasspathEntry newLibraryEntry(
+// IPath path,
+// IPath sourceAttachmentPath,
+// IPath sourceAttachmentRootPath,
+// boolean isExported) {
+//
+// if (!path.isAbsolute()) Assert.isTrue(false, "Path for IClasspathEntry must be absolute"); //$NON-NLS-1$
+//
+// return new ClasspathEntry(
+// IPackageFragmentRoot.K_BINARY,
+// IClasspathEntry.CPE_LIBRARY,
+// JavaProject.canonicalizedPath(path),
+// ClasspathEntry.NO_EXCLUSION_PATTERNS,
+// sourceAttachmentPath,
+// sourceAttachmentRootPath,
+// null, // specific output folder
+// isExported);
+//}
+
+/**
+ * Creates and returns a new non-exported classpath entry of kind CPE_PROJECT
+ * for the project identified by the given absolute path.
+ * newProjectEntry(_,false)
.
+ * CPE_PROJECT
+ * for the project identified by the given absolute path.
+ * CPE_SOURCE
+ * for the project's source folder identified by the given absolute
+ * workspace-relative path. This specifies that all package fragments
+ * within the root will have children of type ICompilationUnit
.
+ * /Project/src
. A project's source
+ * folders are located with that project. That is, a source classpath
+ * entry specifying the path /P1/src
is only usable for
+ * project P1
.
+ * JavaCore.newSourceEntry(IPath,IPath[])
instead.
+ * JavaCore.newProjectEntry
). Particular
+ * source entries cannot be selectively exported.
+ * CPE_SOURCE
+ * for the project's source folder identified by the given absolute
+ * workspace-relative path but excluding all source files with paths
+ * matching any of the given patterns. This specifies that all package
+ * fragments within the root will have children of type
+ * ICompilationUnit
.
+ * /Project/src
. A project's source
+ * folders are located with that project. That is, a source classpath
+ * entry specifying the path /P1/src
is only usable for
+ * project P1
.
+ * /Project/src
and the exclusion pattern is
+ * com/xyz/tests/**
, then source files
+ * like /Project/src/com/xyz/Foo.java
+ * and /Project/src/com/xyz/utils/Bar.java
would be included,
+ * whereas /Project/src/com/xyz/tests/T1.java
+ * and /Project/src/com/xyz/tests/quick/T2.java
would be
+ * excluded. Exclusion patterns can contain can contain '**', '*' or '?'
+ * wildcards; see IClasspathEntry.getExclusionPatterns
+ * for the full description of the syntax and semantics of exclusion
+ * patterns.
+ * JavaCore.newSourceEntry(IPath)
.
+ * JavaCore.newProjectEntry
). Particular
+ * source entries cannot be selectively exported.
+ * CPE_SOURCE
+ * for the project's source folder identified by the given absolute
+ * workspace-relative path but excluding all source files with paths
+ * matching any of the given patterns, and associated with a specific output location
+ * (that is, ".class" files are not going to the project default output location).
+ * All package fragments within the root will have children of type
+ * ICompilationUnit
.
+ * /Project/src
. A project's source
+ * folders are located with that project. That is, a source classpath
+ * entry specifying the path /P1/src
is only usable for
+ * project P1
.
+ * /Project/src
and the exclusion pattern is
+ * com/xyz/tests/**
, then source files
+ * like /Project/src/com/xyz/Foo.java
+ * and /Project/src/com/xyz/utils/Bar.java
would be included,
+ * whereas /Project/src/com/xyz/tests/T1.java
+ * and /Project/src/com/xyz/tests/quick/T2.java
would be
+ * excluded. Exclusion patterns can contain can contain '**', '*' or '?'
+ * wildcards; see IClasspathEntry.getExclusionPatterns
+ * for the full description of the syntax and semantics of exclusion
+ * patterns.
+ * JavaCore.newSourceEntry(IPath)
.
+ * null
).
+ * Note that multiple source entries may target the same output location.
+ * The output location is referred to using an absolute path relative to the
+ * workspace root, e.g. "/Project/bin"
, it must be located inside
+ * the same project as the source folder.
+ * JavaCore.newProjectEntry
). Particular
+ * source entries cannot be selectively exported.
+ * null
if using project default ouput location)
+ * @return a new source classpath entry with the given exclusion patterns
+ * @see #newSourceEntry(org.eclipse.core.runtime.IPath)
+ * @see IClasspathEntry#getExclusionPatterns
+ * @see IClasspathEntry#getOutputLocation()
+ *
+ * @since 2.1
+ */
+public static IClasspathEntry newSourceEntry(IPath path, IPath[] exclusionPatterns, IPath specificOutputLocation) {
+
+ if (!path.isAbsolute()) Assert.isTrue(false, "Path for IClasspathEntry must be absolute"); //$NON-NLS-1$
+ if (exclusionPatterns == null) Assert.isTrue(false, "Exclusion pattern set cannot be null"); //$NON-NLS-1$
+
+ return new ClasspathEntry(
+ IPackageFragmentRoot.K_SOURCE,
+ IClasspathEntry.CPE_SOURCE,
+ path,
+ exclusionPatterns,
+ null, // source attachment
+ null, // source attachment root
+ specificOutputLocation, // custom output location
+ false);
+}
+
+/**
+ * Creates and returns a new non-exported classpath entry of kind CPE_VARIABLE
+ * for the given path. The first segment of the path is the name of a classpath variable.
+ * The trailing segments of the path will be appended to resolved variable path.
+ * ClasspathVariableInitializer
),
+ * which will be invoked through the extension point "org.eclipse.jdt.core.classpathVariableInitializer".
+ * After resolution, a classpath variable entry may either correspond to a project or a library entry.
+ * e.g. Here are some examples of variable path usage
JDTCORE
is
+ * bound to "c:/jars/jdtcore.jar". The resolved classpath entry is denoting the library "c:\jars\jdtcore.jar"JDTCORE
is
+ * bound to "/Project_JDTCORE". The resolved classpath entry is denoting the project "/Project_JDTCORE"PLUGINS
+ * is bound to "c:/eclipse/plugins". The resolved classpath entry is denoting the library "c:/eclipse/plugins/com.example/example.jar"
+ * The resulting entry is not exported to dependent projects. This method is equivalent to
+ * newVariableEntry(-,-,-,false)
.
+ *
+ *
+ * @param variablePath the path of the binary archive; first segment is the
+ * name of a classpath variable
+ * @param variableSourceAttachmentPath the path of the corresponding source archive,
+ * or null
if none; if present, the first segment is the
+ * name of a classpath variable (not necessarily the same variable
+ * as the one that begins variablePath
)
+ * @param sourceAttachmentRootPath the location of the root within the source archive
+ * or null
if archivePath
is also null
+ * @return a new library classpath entry
+ *
+ * @see JavaCore#newVariableEntry(IPath, IPath, IPath, boolean)
+ */
+//public static IClasspathEntry newVariableEntry(
+// IPath variablePath,
+// IPath variableSourceAttachmentPath,
+// IPath sourceAttachmentRootPath) {
+//
+// return newVariableEntry(variablePath, variableSourceAttachmentPath, sourceAttachmentRootPath, false);
+//}
+
+/**
+ * Creates and returns a new non-exported classpath entry of kind CPE_VARIABLE
+ * for the given path. The first segment of the path is the name of a classpath variable.
+ * The trailing segments of the path will be appended to resolved variable path.
+ *
+ * A variable entry allows to express indirect references on a classpath to other projects or libraries, + * depending on what the classpath variable is referring. + *
+ * It is possible to register an automatic initializer (ClasspathVariableInitializer
),
+ * which will be invoked through the extension point "org.eclipse.jdt.core.classpathVariableInitializer".
+ * After resolution, a classpath variable entry may either correspond to a project or a library entry.
+ *
+ * e.g. Here are some examples of variable path usage
JDTCORE
is
+ * bound to "c:/jars/jdtcore.jar". The resolved classpath entry is denoting the library "c:\jars\jdtcore.jar"JDTCORE
is
+ * bound to "/Project_JDTCORE". The resolved classpath entry is denoting the project "/Project_JDTCORE"PLUGINS
+ * is bound to "c:/eclipse/plugins". The resolved classpath entry is denoting the library "c:/eclipse/plugins/com.example/example.jar"
+ *
+ * @param variablePath the path of the binary archive; first segment is the
+ * name of a classpath variable
+ * @param variableSourceAttachmentPath the path of the corresponding source archive,
+ * or null
if none; if present, the first segment is the
+ * name of a classpath variable (not necessarily the same variable
+ * as the one that begins variablePath
)
+ * @param sourceAttachmentRootPath the location of the root within the source archive
+ * or null
if archivePath
is also null
+ * @param isExported indicates whether this entry is contributed to dependent
+ * projects in addition to the output location
+ * @return a new variable classpath entry
+ * @since 2.0
+ */
+//public static IClasspathEntry newVariableEntry(
+// IPath variablePath,
+// IPath variableSourceAttachmentPath,
+// IPath variableSourceAttachmentRootPath,
+// boolean isExported) {
+//
+// if (variablePath == null || variablePath.segmentCount() < 1) {
+// Assert.isTrue(
+// false,
+// "Illegal classpath variable path: \'" + variablePath.makeRelative().toString() + "\', must have at least one segment"); //$NON-NLS-1$//$NON-NLS-2$
+// }
+//
+// return new ClasspathEntry(
+// IPackageFragmentRoot.K_SOURCE,
+// IClasspathEntry.CPE_VARIABLE,
+// variablePath,
+// ClasspathEntry.NO_EXCLUSION_PATTERNS,
+// variableSourceAttachmentPath, // source attachment
+// variableSourceAttachmentRootPath, // source attachment root
+// null, // specific output folder
+// isExported);
+//}
+
+/**
+ * Removed the given classpath variable. Does nothing if no value was
+ * set for this classpath variable.
+ *
+ * This functionality cannot be used while the resource tree is locked. + *
+ * Classpath variable values are persisted locally to the workspace, and + * are preserved from session to session. + *
+ * + * @param variableName the name of the classpath variable + * @see #setClasspathVariable + * + * @deprecated - use version with extra IProgressMonitor + */ +//public static void removeClasspathVariable(String variableName) { +// removeClasspathVariable(variableName, null); +//} + +/** + * Removed the given classpath variable. Does nothing if no value was + * set for this classpath variable. + *
+ * This functionality cannot be used while the resource tree is locked. + *
+ * Classpath variable values are persisted locally to the workspace, and + * are preserved from session to session. + *
+ *
+ * @param variableName the name of the classpath variable
+ * @param monitor the progress monitor to report progress
+ * @see #setClasspathVariable
+ */
+//public static void removeClasspathVariable(
+// String variableName,
+// IProgressMonitor monitor) {
+//
+// try {
+// updateVariableValues(new String[]{ variableName}, new IPath[]{ null }, monitor);
+// } catch (JavaModelException e) {
+// }
+//}
+
+/**
+ * Removes the given element changed listener.
+ * Has no affect if an identical listener is not registered.
+ *
+ * @param listener the listener
+ */
+public static void removeElementChangedListener(IElementChangedListener listener) {
+ JavaModelManager.getJavaModelManager().removeElementChangedListener(listener);
+}
+
+/**
+ * Bind a container reference path to some actual containers (IClasspathContainer
).
+ * This API must be invoked whenever changes in container need to be reflected onto the JavaModel.
+ * Containers can have distinct values in different projects, therefore this API considers a
+ * set of projects with their respective containers.
+ *
+ * containerPath
is the path under which these values can be referenced through
+ * container classpath entries (IClasspathEntry#CPE_CONTAINER
). A container path
+ * is formed by a first ID segment followed with extra segments, which can be used as additional hints
+ * for the resolution. The container ID is used to identify a ClasspathContainerInitializer
+ * registered on the extension point "org.eclipse.jdt.core.classpathContainerInitializer".
+ *
+ * There is no assumption that each individual container value passed in argument
+ * (respectiveContainers
) must answer the exact same path when requested
+ * IClasspathContainer#getPath
.
+ * Indeed, the containerPath is just an indication for resolving it to an actual container object. It can be
+ * delegated to a ClasspathContainerInitializer
, which can be activated through the extension
+ * point "org.eclipse.jdt.core.ClasspathContainerInitializer").
+ *
+ * In reaction to changing container values, the JavaModel will be updated to reflect the new + * state of the updated container. + *
+ * This functionality cannot be used while the resource tree is locked. + *
+ * Classpath container values are persisted locally to the workspace, but
+ * are not preserved from a session to another. It is thus highly recommended to register a
+ * ClasspathContainerInitializer
for each referenced container
+ * (through the extension point "org.eclipse.jdt.core.ClasspathContainerInitializer").
+ *
+ * Note: setting a container to null
will cause it to be lazily resolved again whenever
+ * its value is required. In particular, this will cause a registered initializer to be invoked
+ * again.
+ *
+ * @param containerPath - the name of the container reference, which is being updated
+ * @param affectedProjects - the set of projects for which this container is being bound
+ * @param respectiveContainers - the set of respective containers for the affected projects
+ * @param monitor a monitor to report progress
+ *
+ * @see ClasspathContainerInitializer
+ * @see #getClasspathContainer(IPath, IJavaProject)
+ * @see IClasspathContainer
+ * @since 2.0
+ */
+//public static void setClasspathContainer(final IPath containerPath, IJavaProject[] affectedProjects, IClasspathContainer[] respectiveContainers, IProgressMonitor monitor) throws JavaModelException {
+//
+// if (affectedProjects.length != respectiveContainers.length) Assert.isTrue(false, "Projects and containers collections should have the same size"); //$NON-NLS-1$
+//
+// if (monitor != null && monitor.isCanceled()) return;
+//
+// if (JavaModelManager.CP_RESOLVE_VERBOSE){
+// System.out.println("CPContainer SET - setting container: ["+containerPath+"] for projects: {" //$NON-NLS-1$ //$NON-NLS-2$
+// + (Util.toString(affectedProjects,
+// new Util.Displayable(){
+// public String displayString(Object o) { return ((IJavaProject) o).getElementName(); }
+// }))
+// + "} with values: " //$NON-NLS-1$
+// + (Util.toString(respectiveContainers,
+// new Util.Displayable(){
+// public String displayString(Object o) { return ((IClasspathContainer) o).getDescription(); }
+// }))
+// );
+// }
+//
+// final int projectLength = affectedProjects.length;
+// final IJavaProject[] modifiedProjects;
+// System.arraycopy(affectedProjects, 0, modifiedProjects = new IJavaProject[projectLength], 0, projectLength);
+// final IClasspathEntry[][] oldResolvedPaths = new IClasspathEntry[projectLength][];
+//
+// // filter out unmodified project containers
+// int remaining = 0;
+// for (int i = 0; i < projectLength; i++){
+//
+// if (monitor != null && monitor.isCanceled()) return;
+//
+// IJavaProject affectedProject = affectedProjects[i];
+// IClasspathContainer newContainer = respectiveContainers[i];
+// if (newContainer == null) newContainer = JavaModelManager.ContainerInitializationInProgress; // 30920 - prevent infinite loop
+// boolean found = false;
+// if (JavaProject.hasJavaNature(affectedProject.getProject())){
+// IClasspathEntry[] rawClasspath = affectedProject.getRawClasspath();
+// for (int j = 0, cpLength = rawClasspath.length; j
+ * Classpath variable values are persisted locally to the workspace, and
+ * are preserved from session to session.
+ *
+ *
+ * @param variableName the name of the classpath variable
+ * @param path the path
+ * @see #getClasspathVariable
+ *
+ * @deprecated - use API with IProgressMonitor
+ */
+//public static void setClasspathVariable(String variableName, IPath path)
+// throws JavaModelException {
+//
+// setClasspathVariable(variableName, path, null);
+//}
+
+/**
+ * Sets the value of the given classpath variable.
+ * The path must not be null.
+ *
+ * This functionality cannot be used while the resource tree is locked.
+ *
+ * Classpath variable values are persisted locally to the workspace, and
+ * are preserved from session to session.
+ *
+ * Updating a variable with the same value has no effect.
+ *
+ * @param variableName the name of the classpath variable
+ * @param path the path
+ * @param monitor a monitor to report progress
+ * @see #getClasspathVariable
+ */
+//public static void setClasspathVariable(
+// String variableName,
+// IPath path,
+// IProgressMonitor monitor)
+// throws JavaModelException {
+//
+// if (path == null) Assert.isTrue(false, "Variable path cannot be null"); //$NON-NLS-1$
+// setClasspathVariables(new String[]{variableName}, new IPath[]{ path }, monitor);
+//}
+
+/**
+ * Sets the values of all the given classpath variables at once.
+ * Null paths can be used to request corresponding variable removal.
+ *
+ * This functionality cannot be used while the resource tree is locked.
+ *
+ * Classpath variable values are persisted locally to the workspace, and
+ * are preserved from session to session.
+ *
+ * Updating a variable with the same value has no effect.
+ *
+ * @param variableNames an array of names for the updated classpath variables
+ * @param paths an array of path updates for the modified classpath variables (null
+ * meaning that the corresponding value will be removed
+ * @param monitor a monitor to report progress
+ * @see #getClasspathVariable
+ * @since 2.0
+ */
+//public static void setClasspathVariables(
+// String[] variableNames,
+// IPath[] paths,
+// IProgressMonitor monitor)
+// throws JavaModelException {
+//
+// if (variableNames.length != paths.length) Assert.isTrue(false, "Variable names and paths collections should have the same size"); //$NON-NLS-1$
+// //TODO: should check that null cannot be used as variable paths
+// updateVariableValues(variableNames, paths, monitor);
+//}
+
+/* (non-Javadoc)
+ * Method declared on IExecutableExtension.
+ * Record any necessary initialization data from the plugin.
+ */
+public void setInitializationData(
+ IConfigurationElement cfig,
+ String propertyName,
+ Object data)
+ throws CoreException {
+}
+
+/**
+ * Sets the current table of options. All and only the options explicitly included in the given table
+ * are remembered; all previous option settings are forgotten, including ones not explicitly
+ * mentioned.
+ *
+ * For a complete description of the configurable options, see
+ * De-registers the JavaModelManager as a resource changed listener and save participant.
+ *
+ * @see org.eclipse.core.runtime.Plugin#shutdown()
+ */
+public void shutdown() {
+
+ //savePluginPreferences();
+ getPlugin().savePluginPreferences();
+ IWorkspace workspace = ResourcesPlugin.getWorkspace();
+ workspace.removeResourceChangeListener(JavaModelManager.getJavaModelManager().deltaProcessor);
+ workspace.removeSaveParticipant(PHPeclipsePlugin.getDefault());
+
+ ((JavaModelManager) JavaModelManager.getJavaModelManager()).shutdown();
+}
+
+/**
+ * Initiate the background indexing process.
+ * This should be deferred after the plugin activation.
+ */
+//private void startIndexing() {
+//
+// JavaModelManager.getJavaModelManager().getIndexManager().reset();
+//}
+
+/**
+ * Startup of the JavaCore plug-in.
+ *
+ * Registers the JavaModelManager as a resource changed listener and save participant.
+ * Starts the background indexing, and restore saved classpath variable values.
+ *
+ * @see org.eclipse.core.runtime.Plugin#startup()
+ */
+public void startup() {
+
+ JavaModelManager manager = JavaModelManager.getJavaModelManager();
+ try {
+ manager.configurePluginDebugOptions();
+
+ // request state folder creation (workaround 19885)
+ PHPCore.getPlugin().getStateLocation();
+
+ // retrieve variable values
+ PHPCore.getPlugin().getPluginPreferences().addPropertyChangeListener(new JavaModelManager.PluginPreferencesListener());
+// TODO khartlage temp-del
+// manager.loadVariablesAndContainers();
+
+ IWorkspace workspace = ResourcesPlugin.getWorkspace();
+ workspace.addResourceChangeListener(
+ manager.deltaProcessor,
+ IResourceChangeEvent.PRE_AUTO_BUILD
+ | IResourceChangeEvent.POST_AUTO_BUILD
+ | IResourceChangeEvent.POST_CHANGE
+ | IResourceChangeEvent.PRE_DELETE
+ | IResourceChangeEvent.PRE_CLOSE);
+
+// startIndexing();
+ workspace.addSaveParticipant(PHPeclipsePlugin.getDefault(), manager);
+
+ } catch (CoreException e) {
+ } catch (RuntimeException e) {
+ manager.shutdown();
+ throw e;
+ }
+}
+
+
+/**
+ * Internal updating of a variable values (null path meaning removal), allowing to change multiple variable values at once.
+ */
+//private static void updateVariableValues(
+// String[] variableNames,
+// IPath[] variablePaths,
+// IProgressMonitor monitor) throws JavaModelException {
+//
+// if (monitor != null && monitor.isCanceled()) return;
+//
+// if (JavaModelManager.CP_RESOLVE_VERBOSE){
+// System.out.println("CPVariable SET - setting variables: {" + Util.toString(variableNames) //$NON-NLS-1$
+// + "} with values: " + Util.toString(variablePaths)); //$NON-NLS-1$
+// }
+//
+// int varLength = variableNames.length;
+//
+// // gather classpath information for updating
+// final HashMap affectedProjects = new HashMap(5);
+// JavaModelManager manager = JavaModelManager.getJavaModelManager();
+// IJavaModel model = manager.getJavaModel();
+//
+// // filter out unmodified variables
+// int discardCount = 0;
+// for (int i = 0; i < varLength; i++){
+// String variableName = variableNames[i];
+// IPath oldPath = (IPath)JavaModelManager.variableGet(variableName); // if reentering will provide previous session value
+// if (oldPath == JavaModelManager.VariableInitializationInProgress){
+// IPath previousPath = (IPath)JavaModelManager.PreviousSessionVariables.get(variableName);
+// if (previousPath != null){
+// if (JavaModelManager.CP_RESOLVE_VERBOSE){
+// System.out.println("CPVariable INIT - reentering access to variable: " + variableName+ " during its initialization, will see previous value: "+ previousPath); //$NON-NLS-1$ //$NON-NLS-2$
+// }
+// JavaModelManager.variablePut(variableName, previousPath); // replace value so reentering calls are seeing old value
+// }
+// oldPath = null; //33695 - cannot filter out restored variable, must update affected project to reset cached CP
+// }
+// if (oldPath != null && oldPath.equals(variablePaths[i])){
+// variableNames[i] = null;
+// discardCount++;
+// }
+// }
+// if (discardCount > 0){
+// if (discardCount == varLength) return;
+// int changedLength = varLength - discardCount;
+// String[] changedVariableNames = new String[changedLength];
+// IPath[] changedVariablePaths = new IPath[changedLength];
+// for (int i = 0, index = 0; i < varLength; i++){
+// if (variableNames[i] != null){
+// changedVariableNames[index] = variableNames[i];
+// changedVariablePaths[index] = variablePaths[i];
+// index++;
+// }
+// }
+// variableNames = changedVariableNames;
+// variablePaths = changedVariablePaths;
+// varLength = changedLength;
+// }
+//
+// if (monitor != null && monitor.isCanceled()) return;
+//
+// if (model != null) {
+// IJavaProject[] projects = model.getJavaProjects();
+// nextProject : for (int i = 0, projectLength = projects.length; i < projectLength; i++){
+// IJavaProject project = projects[i];
+//
+// // check to see if any of the modified variables is present on the classpath
+// IClasspathEntry[] classpath = project.getRawClasspath();
+// for (int j = 0, cpLength = classpath.length; j < cpLength; j++){
+//
+// IClasspathEntry entry = classpath[j];
+// for (int k = 0; k < varLength; k++){
+//
+// String variableName = variableNames[k];
+// if (entry.getEntryKind() == IClasspathEntry.CPE_VARIABLE){
+//
+// if (variableName.equals(entry.getPath().segment(0))){
+// affectedProjects.put(project, project.getResolvedClasspath(true));
+// continue nextProject;
+// }
+// IPath sourcePath, sourceRootPath;
+// if (((sourcePath = entry.getSourceAttachmentPath()) != null && variableName.equals(sourcePath.segment(0)))
+// || ((sourceRootPath = entry.getSourceAttachmentRootPath()) != null && variableName.equals(sourceRootPath.segment(0)))) {
+//
+// affectedProjects.put(project, project.getResolvedClasspath(true));
+// continue nextProject;
+// }
+// }
+// }
+// }
+// }
+// }
+// // update variables
+// for (int i = 0; i < varLength; i++){
+// JavaModelManager.variablePut(variableNames[i], variablePaths[i]);
+// }
+// final String[] dbgVariableNames = variableNames;
+//
+// // update affected project classpaths
+// if (!affectedProjects.isEmpty()) {
+// try {
+// JavaCore_DeleteIt_DeleteIt_DeleteIt_DeleteIt_DeleteIt_DeleteIt_DeleteIt_DeleteIt_DeleteIt_DeleteIt_DeleteIt_DeleteIt_DeleteIt.run(
+// new IWorkspaceRunnable() {
+// public void run(IProgressMonitor monitor) throws CoreException {
+// // propagate classpath change
+// Iterator projectsToUpdate = affectedProjects.keySet().iterator();
+// while (projectsToUpdate.hasNext()) {
+//
+// if (monitor != null && monitor.isCanceled()) return;
+//
+// JavaProject project = (JavaProject) projectsToUpdate.next();
+//
+// if (JavaModelManager.CP_RESOLVE_VERBOSE){
+// System.out.println("CPVariable SET - updating affected project: ["+project.getElementName()+"] due to setting variables: "+ Util.toString(dbgVariableNames)); //$NON-NLS-1$ //$NON-NLS-2$
+// }
+//
+// project
+// .setRawClasspath(
+// project.getRawClasspath(),
+// SetClasspathOperation.ReuseOutputLocation,
+// null, // don't call beginTask on the monitor (see http://bugs.eclipse.org/bugs/show_bug.cgi?id=3717)
+// !ResourcesPlugin.getWorkspace().isTreeLocked(), // can change resources
+// (IClasspathEntry[]) affectedProjects.get(project),
+// false, // updating - no validation
+// false); // updating - no need to save
+// }
+// }
+// },
+// monitor);
+// } catch (CoreException e) {
+// if (JavaModelManager.CP_RESOLVE_VERBOSE){
+// System.out.println("CPVariable SET - FAILED DUE TO EXCEPTION: "+Util.toString(dbgVariableNames)); //$NON-NLS-1$
+// e.printStackTrace();
+// }
+// if (e instanceof JavaModelException) {
+// throw (JavaModelException)e;
+// } else {
+// throw new JavaModelException(e);
+// }
+// }
+// }
+//}
}
\ No newline at end of file
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPPerspectiveFactory.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPPerspectiveFactory.java
index 2fe7605..8c9a4f0 100644
--- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPPerspectiveFactory.java
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPPerspectiveFactory.java
@@ -59,7 +59,7 @@ public class PHPPerspectiveFactory implements IPerspectiveFactory {
layout.addShowViewShortcut(IPageLayout.ID_BOOKMARKS);
// new actions - PHP project creation wizards
- layout.addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewInterfaceCreationWizard"); //$NON-NLS-1$
+// layout.addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewInterfaceCreationWizard"); //$NON-NLS-1$
layout.addNewWizardShortcut("net.sourceforge.phpeclipse.wizards.PHPFileWizard"); //$NON-NLS-1$
layout.addNewWizardShortcut("org.eclipse.ui.wizards.new.folder");//$NON-NLS-1$
layout.addNewWizardShortcut("org.eclipse.ui.wizards.new.file");//$NON-NLS-1$
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPSyntaxEditorPreferencePage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPSyntaxEditorPreferencePage.java
new file mode 100644
index 0000000..7b9ba11
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPSyntaxEditorPreferencePage.java
@@ -0,0 +1,560 @@
+package net.sourceforge.phpeclipse;
+
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+import net.sourceforge.phpeclipse.preferences.ColorEditor;
+import net.sourceforge.phpeclipse.preferences.OverlayPreferenceStore;
+import net.sourceforge.phpeclipse.preferences.PHPPreferencesMessages;
+
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.jface.preference.FileFieldEditor;
+import org.eclipse.jface.preference.IPreferenceStore;
+import org.eclipse.jface.preference.PreferenceConverter;
+import org.eclipse.jface.preference.PreferencePage;
+import org.eclipse.jface.text.source.ISourceViewer;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.StyledText;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.events.SelectionListener;
+import org.eclipse.swt.graphics.Color;
+import org.eclipse.swt.graphics.RGB;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Group;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.List;
+import org.eclipse.ui.IWorkbench;
+import org.eclipse.ui.IWorkbenchPreferencePage;
+
+/*
+ * The preference page for setting the PHP Editor options.
+ */
+public class PHPSyntaxEditorPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
+
+ public final OverlayPreferenceStore.OverlayKey[] Keys =
+ new OverlayPreferenceStore.OverlayKey[] {
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IPreferenceConstants.PHP_MULTILINE_COMMENT),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_MULTILINE_COMMENT_BOLD),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_MULTILINE_COMMENT_ITALIC),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_MULTILINE_COMMENT_UNDERLINE),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IPreferenceConstants.PHP_SINGLELINE_COMMENT),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_SINGLELINE_COMMENT_BOLD),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_SINGLELINE_COMMENT_ITALIC),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_SINGLELINE_COMMENT_UNDERLINE),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IPreferenceConstants.PHP_KEYWORD),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_KEYWORD_BOLD),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_KEYWORD_ITALIC),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_KEYWORD_UNDERLINE),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IPreferenceConstants.PHP_VARIABLE),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_VARIABLE_BOLD),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_VARIABLE_ITALIC),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_VARIABLE_UNDERLINE),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IPreferenceConstants.PHP_TYPE),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_TYPE_BOLD),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_TYPE_ITALIC),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_TYPE_UNDERLINE),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IPreferenceConstants.PHP_CONSTANT),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_CONSTANT_BOLD),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_CONSTANT_ITALIC),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_CONSTANT_UNDERLINE),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IPreferenceConstants.PHP_FUNCTIONNAME),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_FUNCTIONNAME_BOLD),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_FUNCTIONNAME_ITALIC),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_FUNCTIONNAME_UNDERLINE),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IPreferenceConstants.PHP_STRING),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_STRING_BOLD),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_STRING_ITALIC),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_STRING_UNDERLINE),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IPreferenceConstants.PHP_DEFAULT),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_DEFAULT_BOLD),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_DEFAULT_ITALIC),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHP_DEFAULT_UNDERLINE),
+
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IPreferenceConstants.PHPDOC_KEYWORD),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHPDOC_KEYWORD_BOLD),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHPDOC_KEYWORD_ITALIC),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHPDOC_KEYWORD_UNDERLINE),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IPreferenceConstants.PHPDOC_TAG),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHPDOC_TAG_BOLD),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHPDOC_TAG_ITALIC),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHPDOC_TAG_UNDERLINE),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IPreferenceConstants.PHPDOC_LINK),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHPDOC_LINK_BOLD),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHPDOC_LINK_ITALIC),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHPDOC_LINK_UNDERLINE),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IPreferenceConstants.PHPDOC_DEFAULT),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHPDOC_DEFAULT_BOLD),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHPDOC_DEFAULT_ITALIC),
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IPreferenceConstants.PHPDOC_DEFAULT_UNDERLINE),
+
+ new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IPreferenceConstants.PHP_USERDEF_XMLFILE),
+ // new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IPreferenceConstants.PHP_EDITOR_BACKGROUND)
+ };
+
+ private final String[][] SyntaxColorListModel =
+ new String[][] {
+ {
+ PHPPreferencesMessages.getString("PHPEditorSyntaxPreferencePage.multiLineComment"),
+ IPreferenceConstants.PHP_MULTILINE_COMMENT },
+ {
+ PHPPreferencesMessages.getString("PHPEditorSyntaxPreferencePage.singleLineComment"),
+ IPreferenceConstants.PHP_SINGLELINE_COMMENT },
+ {
+ PHPPreferencesMessages.getString("PHPEditorSyntaxPreferencePage.keywords"), IPreferenceConstants.PHP_KEYWORD }, {
+ PHPPreferencesMessages.getString("PHPEditorSyntaxPreferencePage.variables"), IPreferenceConstants.PHP_VARIABLE }, {
+ PHPPreferencesMessages.getString("PHPEditorSyntaxPreferencePage.types"), IPreferenceConstants.PHP_TYPE }, {
+ PHPPreferencesMessages.getString("PHPEditorSyntaxPreferencePage.functions"), IPreferenceConstants.PHP_FUNCTIONNAME }, {
+ PHPPreferencesMessages.getString("PHPEditorSyntaxPreferencePage.constants"), IPreferenceConstants.PHP_CONSTANT }, {
+ PHPPreferencesMessages.getString("PHPEditorSyntaxPreferencePage.strings"), IPreferenceConstants.PHP_STRING }, {
+ PHPPreferencesMessages.getString("PHPEditorSyntaxPreferencePage.others"), IPreferenceConstants.PHP_DEFAULT }, {
+ PHPPreferencesMessages.getString("PHPEditorSyntaxPreferencePage.phpdoc_keywords"), IPreferenceConstants.PHPDOC_KEYWORD }, {
+ PHPPreferencesMessages.getString("PHPEditorSyntaxPreferencePage.phpdoc_tags"), IPreferenceConstants.PHPDOC_TAG }, {
+ PHPPreferencesMessages.getString("PHPEditorSyntaxPreferencePage.phpdoc_links"), IPreferenceConstants.PHPDOC_LINK }, {
+ PHPPreferencesMessages.getString("PHPEditorSyntaxPreferencePage.phpdoc_others"), IPreferenceConstants.PHPDOC_DEFAULT }
+ };
+
+ private OverlayPreferenceStore OverlayStore;
+
+ private Map ColorButtons = new HashMap();
+ private SelectionListener ColorButtonListener = new SelectionListener() {
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ public void widgetSelected(SelectionEvent e) {
+ ColorEditor editor = (ColorEditor) e.widget.getData();
+ PreferenceConverter.setValue(OverlayStore, (String) ColorButtons.get(editor), editor.getColorValue());
+ }
+ };
+
+ private Map CheckBoxes = new HashMap();
+ private SelectionListener CheckBoxListener = new SelectionListener() {
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ public void widgetSelected(SelectionEvent e) {
+ Button button = (Button) e.widget;
+ OverlayStore.setValue((String) CheckBoxes.get(button), button.getSelection());
+ }
+ };
+
+ private List SyntaxColorList;
+ /** The ColorEditor that choose the foreground color. */
+ private ColorEditor SyntaxForegroundColorEditor;
+ private Button BoldCheckBox;
+ private Button ItalicCheckBox;
+ private Button UnderlineCheckBox;
+ private FileFieldEditor userdefPHPSyntaxFileFFE;
+ // private BooleanFieldEditor showLineNumber;
+ // private IntegerFieldEditor formatterTabSize;
+ // private BooleanFieldEditor spacesForTabs;
+
+ public PHPSyntaxEditorPreferencePage() {
+ setDescription(PHPPreferencesMessages.getString("PHPEditorSyntaxPreferencePage.description")); //$NON-NLS-1$
+ setPreferenceStore(PHPeclipsePlugin.getDefault().getPreferenceStore());
+ OverlayStore = new OverlayPreferenceStore(getPreferenceStore(), Keys);
+ }
+
+ public void init(IWorkbench workbench) {
+ }
+
+ public void createControl(Composite parent) {
+ super.createControl(parent);
+ }
+
+ private void handleSyntaxColorListSelection() {
+ int i = SyntaxColorList.getSelectionIndex();
+ String key = SyntaxColorListModel[i][1];
+ RGB rgb = PreferenceConverter.getColor(OverlayStore, key);
+ SyntaxForegroundColorEditor.setColorValue(rgb);
+ BoldCheckBox.setSelection(OverlayStore.getBoolean(key + "_bold"));
+ ItalicCheckBox.setSelection(OverlayStore.getBoolean(key + "_italic"));
+ UnderlineCheckBox.setSelection(OverlayStore.getBoolean(key + "_underline"));
+ }
+
+ /**
+ * Create the group of options for other parameters (background color for example).
+ * @param parent the parent component
+ */
+ private void backgroundOptionPage(Composite parent) {
+ Label label = new Label(parent, SWT.LEFT);
+ label.setText(PHPPreferencesMessages.getString("PHPEditorSyntaxPreferencePage.color")); //$NON-NLS-1$
+ GridData gd = new GridData();
+ gd.horizontalAlignment = GridData.BEGINNING;
+ label.setLayoutData(gd);
+// final ColorEditor syntaxBackgroundColorEditor = new ColorEditor(parent);
+// RGB rgb = PreferenceConverter.getColor(OverlayStore, IPreferenceConstants.PHP_EDITOR_BACKGROUND);
+// syntaxBackgroundColorEditor.setColorValue(rgb);
+// Button backgroundColorButton = syntaxBackgroundColorEditor.getButton();
+// gd = new GridData(GridData.FILL_HORIZONTAL);
+// gd.horizontalAlignment = GridData.BEGINNING;
+// backgroundColorButton.setLayoutData(gd);
+// backgroundColorButton.addSelectionListener(new SelectionListener() {
+// public void widgetDefaultSelected(SelectionEvent e) {
+// // do nothing
+// }
+// public void widgetSelected(SelectionEvent e) {
+// PreferenceConverter.setValue(OverlayStore, IPreferenceConstants.PHP_EDITOR_BACKGROUND, syntaxBackgroundColorEditor.getColorValue());
+// }
+// });
+ }
+
+ /**
+ * Create the group of options for the syntax parameters.
+ * @param parent the parent component
+ * @return
+ */
+ private Control createSyntaxPage(Composite parent) {
+
+ Composite colorComposite = new Composite(parent, SWT.NULL);
+ colorComposite.setLayout(new GridLayout());
+
+ Label label = new Label(colorComposite, SWT.LEFT);
+ label.setText(PHPPreferencesMessages.getString("PHPEditorSyntaxPreferencePage.syntax")); //$NON-NLS-1$
+ label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+
+ Composite editorComposite = new Composite(colorComposite, SWT.NONE);
+ GridLayout layout = new GridLayout();
+ layout.numColumns = 2;
+ layout.marginHeight = 0;
+ layout.marginWidth = 0;
+ editorComposite.setLayout(layout);
+ GridData gd = new GridData(GridData.FILL_BOTH);
+ editorComposite.setLayoutData(gd);
+
+ SyntaxColorList = new List(editorComposite, SWT.SINGLE | SWT.V_SCROLL | SWT.BORDER);
+ gd = new GridData(GridData.FILL_BOTH);
+ gd.heightHint = convertHeightInCharsToPixels(5);
+ SyntaxColorList.setLayoutData(gd);
+
+ Composite stylesComposite = new Composite(editorComposite, SWT.NONE);
+ layout = new GridLayout();
+ layout.marginHeight = 0;
+ layout.marginWidth = 0;
+ layout.numColumns = 2;
+ stylesComposite.setLayout(layout);
+ stylesComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
+
+ label = new Label(stylesComposite, SWT.LEFT);
+ label.setText(PHPPreferencesMessages.getString("PHPEditorSyntaxPreferencePage.color")); //$NON-NLS-1$
+ gd = new GridData();
+ gd.horizontalAlignment = GridData.BEGINNING;
+ label.setLayoutData(gd);
+
+ SyntaxForegroundColorEditor = new ColorEditor(stylesComposite);
+ Button foregroundColorButton = SyntaxForegroundColorEditor.getButton();
+ gd = new GridData(GridData.FILL_HORIZONTAL);
+ gd.horizontalAlignment = GridData.BEGINNING;
+ foregroundColorButton.setLayoutData(gd);
+
+ BoldCheckBox = new Button(stylesComposite, SWT.CHECK);
+ BoldCheckBox.setText(PHPPreferencesMessages.getString("PHPEditorSyntaxPreferencePage.bold")); //$NON-NLS-1$
+ gd = new GridData(GridData.FILL_HORIZONTAL);
+ gd.horizontalAlignment = GridData.BEGINNING;
+ gd.horizontalSpan = 2;
+ BoldCheckBox.setLayoutData(gd);
+
+ ItalicCheckBox = new Button(stylesComposite, SWT.CHECK);
+ ItalicCheckBox.setText(PHPPreferencesMessages.getString("PHPEditorSyntaxPreferencePage.italic")); //$NON-NLS-1$
+ ItalicCheckBox.setEnabled(false);
+ gd = new GridData(GridData.FILL_HORIZONTAL);
+ gd.horizontalAlignment = GridData.BEGINNING;
+ gd.horizontalSpan = 2;
+ ItalicCheckBox.setLayoutData(gd);
+
+ UnderlineCheckBox = new Button(stylesComposite, SWT.CHECK);
+ UnderlineCheckBox.setText(PHPPreferencesMessages.getString("PHPEditorSyntaxPreferencePage.underline")); //$NON-NLS-1$
+ UnderlineCheckBox.setEnabled(false);
+ gd = new GridData(GridData.FILL_HORIZONTAL);
+ gd.horizontalAlignment = GridData.BEGINNING;
+ gd.horizontalSpan = 2;
+ UnderlineCheckBox.setLayoutData(gd);
+
+ Composite customSyntaxComposite = new Composite(colorComposite, SWT.NONE);
+ layout = new GridLayout();
+ layout.marginHeight = 0;
+ layout.marginWidth = 0;
+ layout.numColumns = 3;
+ stylesComposite.setLayout(layout);
+ stylesComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
+
+ userdefPHPSyntaxFileFFE =
+ new FileFieldEditor(
+ IPreferenceConstants.PHP_USERDEF_XMLFILE,
+ PHPPreferencesMessages.getString("PHPEditorSyntaxPreferencePage.syntaxdialog"),
+ colorComposite);
+ userdefPHPSyntaxFileFFE.setPreferencePage(this);
+ userdefPHPSyntaxFileFFE.setPreferenceStore(getPreferenceStore());
+ userdefPHPSyntaxFileFFE.load();
+
+ SyntaxColorList.addSelectionListener(new SelectionListener() {
+ public void widgetDefaultSelected(SelectionEvent e) {
+ // do nothing
+ }
+ public void widgetSelected(SelectionEvent e) {
+ handleSyntaxColorListSelection();
+ }
+ });
+
+ foregroundColorButton.addSelectionListener(new SelectionListener() {
+ public void widgetDefaultSelected(SelectionEvent e) {
+ // do nothing
+ }
+ public void widgetSelected(SelectionEvent e) {
+ int i = SyntaxColorList.getSelectionIndex();
+ String key = SyntaxColorListModel[i][1];
+
+ PreferenceConverter.setValue(OverlayStore, key, SyntaxForegroundColorEditor.getColorValue());
+ }
+ });
+ BoldCheckBox.addSelectionListener(new SelectionListener() {
+ public void widgetDefaultSelected(SelectionEvent e) {
+ // do nothing
+ }
+ public void widgetSelected(SelectionEvent e) {
+ int i = SyntaxColorList.getSelectionIndex();
+ String key = SyntaxColorListModel[i][1];
+ OverlayStore.setValue(key + "_bold", BoldCheckBox.getSelection());
+ }
+ });
+
+ ItalicCheckBox.addSelectionListener(new SelectionListener() {
+ public void widgetDefaultSelected(SelectionEvent e) {
+ // do nothing
+ }
+ public void widgetSelected(SelectionEvent e) {
+ int i = SyntaxColorList.getSelectionIndex();
+ String key = SyntaxColorListModel[i][1];
+ OverlayStore.setValue(key + "_italic", ItalicCheckBox.getSelection());
+ }
+ });
+
+ UnderlineCheckBox.addSelectionListener(new SelectionListener() {
+ public void widgetDefaultSelected(SelectionEvent e) {
+ // do nothing
+ }
+ public void widgetSelected(SelectionEvent e) {
+ int i = SyntaxColorList.getSelectionIndex();
+ String key = SyntaxColorListModel[i][1];
+ OverlayStore.setValue(key + "_underline", UnderlineCheckBox.getSelection());
+ }
+ });
+ return colorComposite;
+ }
+
+ private void initializeViewerColors(ISourceViewer viewer) {
+
+ IPreferenceStore store = OverlayStore;
+ if (store != null) {
+
+ StyledText styledText = viewer.getTextWidget();
+ }
+ }
+
+ private Color createColor(IPreferenceStore store, String key, Display display) {
+ RGB rgb = null;
+ if (store.contains(key)) {
+ if (store.isDefault(key))
+ rgb = PreferenceConverter.getDefaultColor(store, key);
+ else
+ rgb = PreferenceConverter.getColor(store, key);
+ if (rgb != null)
+ return new Color(display, rgb);
+ }
+ return null;
+ }
+
+ private static void setEnabled(Control control, boolean enable) {
+ control.setEnabled(enable);
+ if (control instanceof Composite) {
+ Composite composite = (Composite) control;
+ Control[] children = composite.getChildren();
+ for (int i = 0; i < children.length; i++)
+ setEnabled(children[i], enable);
+ }
+ }
+
+ private static void indent(Control control) {
+ GridData gridData = new GridData();
+ gridData.horizontalIndent = 20;
+ control.setLayoutData(gridData);
+ }
+
+ private static void createDependency(final Button master, final Control slave) {
+ indent(slave);
+ master.addSelectionListener(new SelectionListener() {
+ public void widgetSelected(SelectionEvent e) {
+ slave.setEnabled(master.getSelection());
+ }
+
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ });
+ }
+
+ protected Control createContents(Composite parent) {
+ OverlayStore.load();
+ OverlayStore.start();
+ //Create overall composite
+ Composite composite = new Composite(parent, SWT.NONE);
+ GridLayout layout = new GridLayout();
+ layout.marginHeight = 0;
+ layout.marginWidth = 0;
+ composite.setLayout(layout);
+ Composite syntaxComposite = new Composite(composite, SWT.NULL);
+ syntaxComposite.setLayout(new GridLayout());
+ layout = new GridLayout();
+ layout.numColumns = 3;
+ Group syntaxGroup = new Group(syntaxComposite, SWT.NONE);
+ syntaxGroup.setText(PHPPreferencesMessages.getString("PHPEditorSyntaxPreferencePage.foreground"));
+ syntaxGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ syntaxGroup.setLayout(layout);
+ createSyntaxPage(syntaxGroup);
+
+ Composite backgroundOptions = new Composite(composite,SWT.NULL);
+ backgroundOptions.setLayout(new GridLayout());
+ layout = new GridLayout();
+ layout.numColumns = 3;
+ Group backgroundOptionsGroup = new Group(backgroundOptions,SWT.NONE);
+ backgroundOptionsGroup.setText(PHPPreferencesMessages.getString("PHPEditorSyntaxPreferencePage.background"));
+ backgroundOptionsGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+ backgroundOptionsGroup.setLayout(layout);
+ backgroundOptionPage(backgroundOptionsGroup);
+
+ initialize();
+
+
+// showLineNumber = new BooleanFieldEditor(PHPeclipsePlugin.LINE_NUMBER_RULER,
+// "Show line numbers", composite);
+// showLineNumber.setPreferencePage(this);
+// showLineNumber.setPreferenceStore(getPreferenceStore());
+// showLineNumber.load();
+
+// formatterTabSize = new IntegerFieldEditor(PHPeclipsePlugin.FORMATTER_TAB_SIZE,
+// "Displayed tab width", composite, 3);
+// formatterTabSize.setPreferencePage(this);
+// formatterTabSize.setPreferenceStore(getPreferenceStore());
+// formatterTabSize.load();
+//
+// spacesForTabs = new BooleanFieldEditor(PHPeclipsePlugin.SPACES_FOR_TABS,
+// "Spaces for Tabs", composite);
+// spacesForTabs.setPreferencePage(this);
+// spacesForTabs.setPreferenceStore(getPreferenceStore());
+// spacesForTabs.load();
+ return composite;
+ }
+
+ private void initialize() {
+ initializeFields();
+ for (int i = 0; i < SyntaxColorListModel.length; i++)
+ SyntaxColorList.add(SyntaxColorListModel[i][0]);
+ SyntaxColorList.getDisplay().asyncExec(new Runnable() {
+ public void run() {
+ if (SyntaxColorList != null && !SyntaxColorList.isDisposed()) {
+ SyntaxColorList.select(0);
+ handleSyntaxColorListSelection();
+ }
+ }
+ });
+ }
+
+ private void initializeFields() {
+
+ Iterator e = ColorButtons.keySet().iterator();
+ while (e.hasNext()) {
+ ColorEditor c = (ColorEditor) e.next();
+ String key = (String) ColorButtons.get(c);
+ RGB rgb = PreferenceConverter.getColor(OverlayStore, key);
+ c.setColorValue(rgb);
+ }
+
+ e = CheckBoxes.keySet().iterator();
+ while (e.hasNext()) {
+ Button b = (Button) e.next();
+ String key = (String) CheckBoxes.get(b);
+ b.setSelection(OverlayStore.getBoolean(key));
+ }
+ }
+
+ public boolean performOk() {
+ OverlayStore.propagate();
+ IPreferenceStore store = getPreferenceStore();
+ PHPeclipsePlugin.getDefault().savePluginPreferences();
+ userdefPHPSyntaxFileFFE.store();
+ // showLineNumber.store();
+ // spacesForTabs.store();
+ // formatterTabSize.store();
+ return true;
+ }
+
+ protected void performDefaults() {
+ OverlayStore.loadDefaults();
+ initializeFields();
+ handleSyntaxColorListSelection();
+ userdefPHPSyntaxFileFFE.loadDefault();
+ // showLineNumber.loadDefault();
+ // spacesForTabs.loadDefault();
+ // showLineNumber.loadDefault();
+ // formatterTabSize.loadDefault();
+ super.performDefaults();
+ }
+
+ public void dispose() {
+ if (OverlayStore != null) {
+ OverlayStore.stop();
+ OverlayStore = null;
+ }
+ super.dispose();
+ }
+
+ private Control addColorButton(Composite composite, String label, String key, int indentation) {
+ Label labelControl = new Label(composite, SWT.NONE);
+ labelControl.setText(label);
+ GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
+ gd.horizontalIndent = indentation;
+ labelControl.setLayoutData(gd);
+ ColorEditor editor = new ColorEditor(composite);
+ Button button = editor.getButton();
+ button.setData(editor);
+ gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
+ button.setLayoutData(gd);
+ button.addSelectionListener(ColorButtonListener);
+ ColorButtons.put(editor, key);
+ return composite;
+ }
+
+ private Button addCheckBox(Composite parent, String label, String key, int indentation) {
+ Button checkBox = new Button(parent, SWT.CHECK);
+ checkBox.setText(label);
+ GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
+ gd.horizontalIndent = indentation;
+ gd.horizontalSpan = 2;
+ checkBox.setLayoutData(gd);
+ checkBox.addSelectionListener(CheckBoxListener);
+ CheckBoxes.put(checkBox, key);
+ return checkBox;
+ }
+
+ private void updateStatus(IStatus status) {
+ }
+
+ /**
+ * @deprecated Inline to avoid reference to preference page
+ */
+ public static boolean indicateQuixFixableProblems() {
+ // return PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_CORRECTION_INDICATION);
+ return false;
+ }
+
+ /**
+ * @deprecated Inline to avoid reference to preference page
+ */
+ static public boolean synchronizeOutlineOnCursorMove() {
+ // return PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE);
+ return false;
+ }
+
+}
\ No newline at end of file
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPeclipsePlugin.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPeclipsePlugin.java
index 8cdd585..fe4136e 100644
--- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPeclipsePlugin.java
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPeclipsePlugin.java
@@ -23,8 +23,13 @@ import java.util.Set;
import net.sourceforge.phpdt.externaltools.internal.model.ColorManager;
import net.sourceforge.phpdt.externaltools.internal.model.ExternalToolsPlugin;
import net.sourceforge.phpdt.externaltools.internal.model.VariableContextManager;
+import net.sourceforge.phpdt.internal.ui.preferences.MembersOrderPreferenceCache;
import net.sourceforge.phpdt.internal.ui.preferences.TemplatePreferencePage;
+import net.sourceforge.phpdt.internal.ui.text.java.hover.JavaEditorTextHoverDescriptor;
import net.sourceforge.phpdt.internal.ui.viewsupport.ImageDescriptorRegistry;
+import net.sourceforge.phpdt.internal.ui.viewsupport.ProblemMarkerManager;
+import net.sourceforge.phpdt.ui.IContextMenuConstants;
+import net.sourceforge.phpdt.ui.IWorkingCopyManager;
import net.sourceforge.phpdt.ui.PreferenceConstants;
import net.sourceforge.phpdt.ui.text.JavaTextTools;
import net.sourceforge.phpeclipse.builder.ExternalEditorInput;
@@ -33,6 +38,7 @@ import net.sourceforge.phpeclipse.builder.FileStorage;
import net.sourceforge.phpeclipse.builder.IdentifierIndexManager;
import net.sourceforge.phpeclipse.phpeditor.PHPDocumentProvider;
import net.sourceforge.phpeclipse.phpeditor.PHPSyntaxRdr;
+import net.sourceforge.phpeclipse.phpeditor.WorkingCopyManager;
import net.sourceforge.phpeclipse.phpeditor.util.PHPColorProvider;
import net.sourceforge.phpeclipse.resourcesview.PHPElement;
import net.sourceforge.phpeclipse.resourcesview.PHPElementAdapterFactory;
@@ -52,6 +58,9 @@ import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
+import org.eclipse.jface.action.GroupMarker;
+import org.eclipse.jface.action.IMenuManager;
+import org.eclipse.jface.action.Separator;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.text.BadLocationException;
@@ -83,7 +92,7 @@ public class PHPeclipsePlugin extends AbstractUIPlugin implements IPreferenceCon
* id of builder - matches plugin.xml (concatenate pluginid.builderid)
*/
public static final String BUILDER_PARSER_ID = PLUGIN_ID + ".parserbuilder";
-//public static final String BUILDER_INDEX_ID = PLUGIN_ID + ".indexbuilder";
+ //public static final String BUILDER_INDEX_ID = PLUGIN_ID + ".indexbuilder";
/** General debug flag*/
public static final boolean DEBUG = false;
@@ -134,14 +143,20 @@ public class PHPeclipsePlugin extends AbstractUIPlugin implements IPreferenceCon
/** Windows NT */
private static final int WINDOWS_NT = 5;
- private PHPDocumentProvider fCompilationUnitDocumentProvider;
private ImageDescriptorRegistry fImageDescriptorRegistry;
private HashMap fIndexManagerMap = new HashMap();
+ private IWorkingCopyManager fWorkingCopyManager;
+ private PHPDocumentProvider fCompilationUnitDocumentProvider;
private JavaTextTools fJavaTextTools;
+ private ProblemMarkerManager fProblemMarkerManager;
+ private MembersOrderPreferenceCache fMembersOrderPreferenceCache;
+
private IFile fLastEditorFile = null;
+ private JavaEditorTextHoverDescriptor[] fJavaEditorTextHoverDescriptors;
+
/**
* The constructor.
*/
@@ -156,7 +171,50 @@ public class PHPeclipsePlugin extends AbstractUIPlugin implements IPreferenceCon
// resourceBundle = null;
// }
}
-
+ /**
+ * Returns all Java editor text hovers contributed to the workbench.
+ *
+ * @return an array of JavaEditorTextHoverDescriptor
+ * @since 2.1
+ */
+ public JavaEditorTextHoverDescriptor[] getJavaEditorTextHoverDescriptors() {
+ if (fJavaEditorTextHoverDescriptors == null)
+ fJavaEditorTextHoverDescriptors= JavaEditorTextHoverDescriptor.getContributedHovers();
+ return fJavaEditorTextHoverDescriptors;
+ }
+
+ /**
+ * Resets the Java editor text hovers contributed to the workbench.
+ *
+ * This will force a rebuild of the descriptors the next time
+ * a client asks for them.
+ *
+ * This method is part of the
+ * Subclasses are free to extend this method to pick up
+ * initialization parameters from the plug-in plug-in manifest
+ * (
+ * For example, the following method looks for a boolean-valued
+ * parameter named "trace":
+ * getDefaultOptions
.
+ * String
; value type: String
),
+ * or null
to reset all options to their default values
+ * @see JavaCore#getDefaultOptions
+ */
+public static void setOptions(Hashtable newOptions) {
+
+ // see #initializeDefaultPluginPreferences() for changing default settings
+ Preferences preferences = getPlugin().getPluginPreferences();
+
+ if (newOptions == null){
+ newOptions = PHPCore.getDefaultOptions();
+ }
+ Enumeration keys = newOptions.keys();
+ while (keys.hasMoreElements()){
+ String key = (String)keys.nextElement();
+ if (!JavaModelManager.OptionNames.contains(key)) continue; // unrecognized option
+ if (key.equals(CORE_ENCODING)) continue; // skipped, contributed by resource prefs
+ String value = (String)newOptions.get(key);
+ preferences.setValue(key, value);
+ }
+
+ // persist options
+ getPlugin().savePluginPreferences();
+}
+
+/**
+ * Shutdown the JavaCore plug-in.
+ * FULL_BUILD
by visiting all nodes in the resource
+ * tree under the specified project.
+ *
+ * @param iProject
+ */
+ public void processFull(final IProject iProject, final IProgressMonitor monitor) {
+ final IdentifierIndexManager indexManager = PHPeclipsePlugin.getDefault().getIndexManager(iProject);
+ // Create resource visitor logic
+ IResourceVisitor myVisitor = new IResourceVisitor() {
+ public boolean visit(IResource resource) throws CoreException {
+ if (resource.getType() == IResource.FILE) {
+ if (monitor.isCanceled()) {
+ throw new OperationCanceledException();
+ }
+ if ((resource.getFileExtension() != null) && PHPFileUtil.isPHPFile((IFile) resource)) {
+ monitor.worked(1);
+ monitor.subTask("Parsing: " + resource.getFullPath());
+ // check for parsing errors
+ PHPParserAction.parseFile((IFile) resource);
+ // update indexfile for the project:
+ JavaProject nature = (JavaProject) iProject.getNature(PHPeclipsePlugin.PHP_NATURE_ID);
+ indexManager.addFile((IFile) resource);
+ }
+ }
+
+ return true;
+ }
+ };
+
+ // Process the project using the visitor just created
+ try {
+
+ // if (iProject.hasNature(PHPeclipsePlugin.PHP_NATURE_ID)) {
+ // thePHPProject = new PHPProject();
+ // thePHPProject.setProject(iProject);
+ // }
+ indexManager.initialize();
+ iProject.accept(myVisitor);
+ indexManager.writeFile();
+ } catch (CoreException e) {
+ e.printStackTrace();
+ }
+
+ }
+
+ /**
+ * Sets initialization data for this builder.
+ * IExecutableExtension
+ * interface.
+ * plugin.xml
) file,
+ * but should be sure to invoke this method on their superclass.
+ *
+ * public void setInitializationData(IConfigurationElement cfig,
+ * String propertyName, Object data)
+ * throws CoreException {
+ * super.setInitializationData(cfig, propertyName, data);
+ * if (data instanceof Hashtable) {
+ * Hashtable args = (Hashtable) data;
+ * String traceValue = (String) args.get("trace");
+ * TRACING = (traceValue!=null && traceValue.equals("true"));
+ * }
+ * }
+ *
+ *
setInitializationData
has been called.
+ * The default implementation should be called by all overriding methods.
+ *
+ * @see #setInitializationData
+ */
+ protected void startupOnInitialize() {
+ // traceMsg("Parse Builder Initialize - startupOnInitialize()");
+ }
+
+ /**
+ * Write trace statements.
+ * System.out.println with prefix tagging used for simplicity.
+ */
+ // private void traceMsg(String msg) {
+ // if (PHPeclipsePlugin.DEBUG | traceEnabled)
+ // System.out.println(
+ // buildMode
+ // + "<"
+ // + getProject()
+ // + "> "
+ // + "\t\t\t"
+ // + buildMark
+ // + msg);
+ // }
+
+}
\ No newline at end of file
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/builder/ParserBuilder.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/builder/ParserBuilder.java
deleted file mode 100644
index d351132..0000000
--- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/builder/ParserBuilder.java
+++ /dev/null
@@ -1,166 +0,0 @@
-package net.sourceforge.phpeclipse.builder;
-
-import java.util.Map;
-
-import net.sourceforge.phpdt.internal.ui.util.PHPFileUtil;
-import net.sourceforge.phpeclipse.PHPeclipsePlugin;
-import net.sourceforge.phpeclipse.phpeditor.PHPParserAction;
-import net.sourceforge.phpeclipse.resourcesview.PHPProject;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceDelta;
-import org.eclipse.core.resources.IResourceVisitor;
-import org.eclipse.core.resources.IncrementalProjectBuilder;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IConfigurationElement;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-
-/**
- * Builder for .php files.
- *
- *
- * @see org.eclipse.core.resources.IncrementalProjectBuilder
- * @see org.eclipse.core.resources.IResourceDelta
- */
-public class ParserBuilder extends IncrementalProjectBuilder {
- private final static int TOTAL_WORK = 100;
-
- /**
- * Constructor
- */
- public ParserBuilder() {
- }
-
- /**
- *
- */
- protected IProject[] build(int kind, Map args, IProgressMonitor monitor) throws CoreException {
- monitor.beginTask("Parsing files", TOTAL_WORK);
-
- if (kind == IncrementalProjectBuilder.FULL_BUILD) {
- IResourceDelta delta = getDelta(getProject());
-
- processFull(getProject(), monitor);
-
- } else { // INCREMENTAL_BUILD or AUTO_BUILD
-
- IResourceDelta delta = getDelta(getProject());
- if (delta != null) {
- delta.accept(new ParserVisitor(getProject(), monitor));
- }
-
- }
- monitor.done();
- return null;
- }
-
- /**
- * Performs a FULL_BUILD
by visiting all nodes in the resource
- * tree under the specified project.
- *
- * @param iProject
- */
- public void processFull(final IProject iProject, final IProgressMonitor monitor) {
- final IdentifierIndexManager indexManager = PHPeclipsePlugin.getDefault().getIndexManager(iProject);
- // Create resource visitor logic
- IResourceVisitor myVisitor = new IResourceVisitor() {
- public boolean visit(IResource resource) throws CoreException {
- if (resource.getType() == IResource.FILE) {
- if (monitor.isCanceled()) {
- throw new OperationCanceledException();
- }
- if ((resource.getFileExtension() != null) && PHPFileUtil.isPHPFile((IFile) resource)) {
- monitor.worked(1);
- monitor.subTask("Parsing: " + resource.getFullPath());
- // check for parsing errors
- PHPParserAction.parseFile((IFile) resource);
- // update indexfile for the project:
- PHPProject nature = (PHPProject) iProject.getNature(PHPeclipsePlugin.PHP_NATURE_ID);
- indexManager.addFile((IFile) resource);
- }
- }
-
- return true;
- }
- };
-
- // Process the project using the visitor just created
- try {
-
-// if (iProject.hasNature(PHPeclipsePlugin.PHP_NATURE_ID)) {
-// thePHPProject = new PHPProject();
-// thePHPProject.setProject(iProject);
-// }
- indexManager.initialize();
- iProject.accept(myVisitor);
- indexManager.writeFile();
- } catch (CoreException e) {
- e.printStackTrace();
- }
-
- }
-
- /**
- * Sets initialization data for this builder.
- *
- * This method is part of the IExecutableExtension
- * interface.
- *
- * Subclasses are free to extend this method to pick up
- * initialization parameters from the plug-in plug-in manifest
- * (plugin.xml
) file,
- * but should be sure to invoke this method on their superclass.
- *
- * For example, the following method looks for a boolean-valued - * parameter named "trace": - *
- * public void setInitializationData(IConfigurationElement cfig, - * String propertyName, Object data) - * throws CoreException { - * super.setInitializationData(cfig, propertyName, data); - * if (data instanceof Hashtable) { - * Hashtable args = (Hashtable) data; - * String traceValue = (String) args.get("trace"); - * TRACING = (traceValue!=null && traceValue.equals("true")); - * } - * } - *- * - */ - public void setInitializationData(IConfigurationElement config, String propertyName, Object data) throws CoreException { - super.setInitializationData(config, propertyName, data); - - } - - /** - * Informs this builder that it is being started by the build management - * infrastructure. By the time this method is run, the builder's project - * is available and
setInitializationData
has been called.
- * The default implementation should be called by all overriding methods.
- *
- * @see #setInitializationData
- */
- protected void startupOnInitialize() {
- // traceMsg("Parse Builder Initialize - startupOnInitialize()");
- }
-
- /**
- * Write trace statements.
- * System.out.println with prefix tagging used for simplicity.
- */
- // private void traceMsg(String msg) {
- // if (PHPeclipsePlugin.DEBUG | traceEnabled)
- // System.out.println(
- // buildMode
- // + "<"
- // + getProject()
- // + "> "
- // + "\t\t\t"
- // + buildMark
- // + msg);
- // }
-}
\ No newline at end of file
diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/builder/State.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/builder/State.java
new file mode 100644
index 0000000..754ecbe
--- /dev/null
+++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/builder/State.java
@@ -0,0 +1,612 @@
+/*******************************************************************************
+ * Copyright (c) 2000, 2003 IBM Corporation and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Common Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/cpl-v10.html
+ *
+ * Contributors:
+ * IBM Corporation - initial API and implementation
+ *******************************************************************************/
+package net.sourceforge.phpeclipse.builder;
+
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Date;
+
+import net.sourceforge.phpdt.internal.core.Util;
+import net.sourceforge.phpdt.internal.core.util.SimpleLookupTable;
+
+import org.eclipse.core.resources.IContainer;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.IResourceDelta;
+import org.eclipse.core.resources.IWorkspaceRoot;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.core.runtime.Path;
+
+public class State {
+// NOTE: this state cannot contain types that are not defined in this project
+
+String javaProjectName;
+ClasspathMultiDirectory[] sourceLocations;
+ClasspathLocation[] binaryLocations;
+// keyed by the project relative path of the type (ie. "src1/p1/p2/A.java"), value is a ReferenceCollection or an AdditionalTypeCollection
+SimpleLookupTable references;
+// keyed by qualified type name "p1/p2/A", value is the project relative path which defines this type "src1/p1/p2/A.java"
+SimpleLookupTable typeLocators;
+
+int buildNumber;
+long lastStructuralBuildTime;
+SimpleLookupTable structuralBuildTimes;
+
+private String[] knownPackageNames; // of the form "p1/p2"
+
+static final byte VERSION = 0x0007;
+
+static final byte SOURCE_FOLDER = 1;
+static final byte BINARY_FOLDER = 2;
+static final byte EXTERNAL_JAR = 3;
+static final byte INTERNAL_JAR = 4;
+
+State() {
+}
+
+protected State(PHPBuilder javaBuilder) {
+ this.knownPackageNames = null;
+ this.javaProjectName = javaBuilder.currentProject.getName();
+
+// this.sourceLocations = javaBuilder.nameEnvironment.sourceLocations;
+// this.binaryLocations = javaBuilder.nameEnvironment.binaryLocations;
+ this.references = new SimpleLookupTable(7);
+ this.typeLocators = new SimpleLookupTable(7);
+
+ this.buildNumber = 0; // indicates a full build
+ this.lastStructuralBuildTime = System.currentTimeMillis();
+ this.structuralBuildTimes = new SimpleLookupTable(3);
+}
+
+void copyFrom(State lastState) {
+ try {
+ this.knownPackageNames = null;
+ this.buildNumber = lastState.buildNumber + 1;
+ this.lastStructuralBuildTime = lastState.lastStructuralBuildTime;
+ this.references = (SimpleLookupTable) lastState.references.clone();
+ this.typeLocators = (SimpleLookupTable) lastState.typeLocators.clone();
+ } catch (CloneNotSupportedException e) {
+ this.references = new SimpleLookupTable(lastState.references.elementSize);
+ Object[] keyTable = lastState.references.keyTable;
+ Object[] valueTable = lastState.references.valueTable;
+ for (int i = 0, l = keyTable.length; i < l; i++)
+ if (keyTable[i] != null)
+ this.references.put(keyTable[i], valueTable[i]);
+
+ this.typeLocators = new SimpleLookupTable(lastState.typeLocators.elementSize);
+ keyTable = lastState.typeLocators.keyTable;
+ valueTable = lastState.typeLocators.valueTable;
+ for (int i = 0, l = keyTable.length; i < l; i++)
+ if (keyTable[i] != null)
+ this.typeLocators.put(keyTable[i], valueTable[i]);
+ }
+}
+
+char[][] getDefinedTypeNamesFor(String typeLocator) {
+ Object c = references.get(typeLocator);
+// if (c instanceof AdditionalTypeCollection)
+// return ((AdditionalTypeCollection) c).definedTypeNames;
+ return null; // means only one type is defined with the same name as the file... saves space
+}
+
+boolean isDuplicateLocator(String qualifiedTypeName, String typeLocator) {
+ String existing = (String) typeLocators.get(qualifiedTypeName);
+ return existing != null && !existing.equals(typeLocator);
+}
+
+boolean isKnownPackage(String qualifiedPackageName) {
+ if (knownPackageNames == null) {
+ ArrayList names = new ArrayList(typeLocators.elementSize);
+ Object[] keyTable = typeLocators.keyTable;
+ for (int i = 0, l = keyTable.length; i < l; i++) {
+ if (keyTable[i] != null) {
+ String packageName = (String) keyTable[i]; // is a type name of the form p1/p2/A
+ int last = packageName.lastIndexOf('/');
+ packageName = last == -1 ? null : packageName.substring(0, last);
+ while (packageName != null && !names.contains(packageName)) {
+ names.add(packageName);
+ last = packageName.lastIndexOf('/');
+ packageName = last == -1 ? null : packageName.substring(0, last);
+ }
+ }
+ }
+ knownPackageNames = new String[names.size()];
+ names.toArray(knownPackageNames);
+ }
+ for (int i = 0, l = knownPackageNames.length; i < l; i++)
+ if (knownPackageNames[i].equals(qualifiedPackageName))
+ return true;
+ return false;
+}
+
+void record(String typeLocator, char[][][] qualifiedRefs, char[][] simpleRefs, char[] mainTypeName, ArrayList typeNames) {
+// if (typeNames.size() == 1 && CharOperation.equals(mainTypeName, (char[]) typeNames.get(0))) {
+// references.put(typeLocator, new ReferenceCollection(qualifiedRefs, simpleRefs));
+// } else {
+// char[][] definedTypeNames = new char[typeNames.size()][]; // can be empty when no types are defined
+// typeNames.toArray(definedTypeNames);
+// references.put(typeLocator, new AdditionalTypeCollection(definedTypeNames, qualifiedRefs, simpleRefs));
+// }
+}
+
+void recordLocatorForType(String qualifiedTypeName, String typeLocator) {
+ this.knownPackageNames = null;
+ typeLocators.put(qualifiedTypeName, typeLocator);
+}
+
+void recordStructuralDependency(IProject prereqProject, State prereqState) {
+ if (prereqState != null)
+ structuralBuildTimes.put(prereqProject.getName(), new Long(prereqState.lastStructuralBuildTime));
+}
+
+void removeLocator(String typeLocatorToRemove) {
+ this.knownPackageNames = null;
+ references.removeKey(typeLocatorToRemove);
+ typeLocators.removeValue(typeLocatorToRemove);
+}
+
+void removePackage(IResourceDelta sourceDelta) {
+ IResource resource = sourceDelta.getResource();
+ switch(resource.getType()) {
+ case IResource.FOLDER :
+ IResourceDelta[] children = sourceDelta.getAffectedChildren();
+ for (int i = 0, l = children.length; i < l; i++)
+ removePackage(children[i]);
+ return;
+ case IResource.FILE :
+ IPath typeLocatorPath = resource.getProjectRelativePath();
+ if (Util.isJavaFileName(typeLocatorPath.lastSegment()))
+ removeLocator(typeLocatorPath.toString());
+ }
+}
+
+void removeQualifiedTypeName(String qualifiedTypeNameToRemove) {
+ this.knownPackageNames = null;
+ typeLocators.removeKey(qualifiedTypeNameToRemove);
+}
+
+static State read(IProject project, DataInputStream in) throws IOException {
+// if (JavaBuilder.DEBUG)
+// System.out.println("About to read state..."); //$NON-NLS-1$
+ if (VERSION != in.readByte()) {
+// if (JavaBuilder.DEBUG)
+// System.out.println("Found non-compatible state version... answered null"); //$NON-NLS-1$
+ return null;
+ }
+
+ State newState = new State();
+ newState.javaProjectName = in.readUTF();
+ if (!project.getName().equals(newState.javaProjectName)) {
+// if (JavaBuilder.DEBUG)
+// System.out.println("Project's name does not match... answered null"); //$NON-NLS-1$
+ return null;
+ }
+ newState.buildNumber = in.readInt();
+ newState.lastStructuralBuildTime = in.readLong();
+
+ int length = in.readInt();
+ newState.sourceLocations = new ClasspathMultiDirectory[length];
+ for (int i = 0; i < length; i++) {
+ IContainer sourceFolder = project, outputFolder = project;
+ String folderName;
+ if ((folderName = in.readUTF()).length() > 0) sourceFolder = project.getFolder(folderName);
+ if ((folderName = in.readUTF()).length() > 0) outputFolder = project.getFolder(folderName);
+ ClasspathMultiDirectory md =
+ (ClasspathMultiDirectory) ClasspathLocation.forSourceFolder(sourceFolder, outputFolder, readNames(in));
+ if (in.readBoolean())
+ md.hasIndependentOutputFolder = true;
+ newState.sourceLocations[i] = md;
+ }
+
+ length = in.readInt();
+ newState.binaryLocations = new ClasspathLocation[length];
+ IWorkspaceRoot root = project.getWorkspace().getRoot();
+ for (int i = 0; i < length; i++) {
+ switch (in.readByte()) {
+ case SOURCE_FOLDER :
+ newState.binaryLocations[i] = newState.sourceLocations[in.readInt()];
+ break;
+ case BINARY_FOLDER :
+ IPath path = new Path(in.readUTF());
+ IContainer outputFolder = path.segmentCount() == 1
+ ? (IContainer) root.getProject(path.toString())
+ : (IContainer) root.getFolder(path);
+ newState.binaryLocations[i] = ClasspathLocation.forBinaryFolder(outputFolder, in.readBoolean());
+ break;
+// case EXTERNAL_JAR :
+// newState.binaryLocations[i] = ClasspathLocation.forLibrary(in.readUTF());
+// break;
+// case INTERNAL_JAR :
+// newState.binaryLocations[i] = ClasspathLocation.forLibrary(root.getFile(new Path(in.readUTF())));
+ }
+ }
+
+ newState.structuralBuildTimes = new SimpleLookupTable(length = in.readInt());
+ for (int i = 0; i < length; i++)
+ newState.structuralBuildTimes.put(in.readUTF(), new Long(in.readLong()));
+
+ String[] internedTypeLocators = new String[length = in.readInt()];
+ for (int i = 0; i < length; i++)
+ internedTypeLocators[i] = in.readUTF();
+
+ newState.typeLocators = new SimpleLookupTable(length = in.readInt());
+ for (int i = 0; i < length; i++)
+ newState.typeLocators.put(in.readUTF(), internedTypeLocators[in.readInt()]);
+
+// char[][] internedSimpleNames = ReferenceCollection.internSimpleNames(readNames(in), false);
+// char[][][] internedQualifiedNames = new char[length = in.readInt()][][];
+// for (int i = 0; i < length; i++) {
+// int qLength = in.readInt();
+// char[][] qName = new char[qLength][];
+// for (int j = 0; j < qLength; j++)
+// qName[j] = internedSimpleNames[in.readInt()];
+// internedQualifiedNames[i] = qName;
+// }
+// internedQualifiedNames = ReferenceCollection.internQualifiedNames(internedQualifiedNames);
+
+// newState.references = new SimpleLookupTable(length = in.readInt());
+// for (int i = 0; i < length; i++) {
+// String typeLocator = internedTypeLocators[in.readInt()];
+// ReferenceCollection collection = null;
+// switch (in.readByte()) {
+// case 1 :
+// char[][] additionalTypeNames = readNames(in);
+// char[][][] qualifiedNames = new char[in.readInt()][][];
+// for (int j = 0, m = qualifiedNames.length; j < m; j++)
+// qualifiedNames[j] = internedQualifiedNames[in.readInt()];
+// char[][] simpleNames = new char[in.readInt()][];
+// for (int j = 0, m = simpleNames.length; j < m; j++)
+// simpleNames[j] = internedSimpleNames[in.readInt()];
+// collection = new AdditionalTypeCollection(additionalTypeNames, qualifiedNames, simpleNames);
+// break;
+// case 2 :
+// char[][][] qNames = new char[in.readInt()][][];
+// for (int j = 0, m = qNames.length; j < m; j++)
+// qNames[j] = internedQualifiedNames[in.readInt()];
+// char[][] sNames = new char[in.readInt()][];
+// for (int j = 0, m = sNames.length; j < m; j++)
+// sNames[j] = internedSimpleNames[in.readInt()];
+// collection = new ReferenceCollection(qNames, sNames);
+// }
+// newState.references.put(typeLocator, collection);
+// }
+// if (JavaBuilder.DEBUG)
+// System.out.println("Successfully read state for " + newState.javaProjectName); //$NON-NLS-1$
+ return newState;
+}
+
+private static char[][] readNames(DataInputStream in) throws IOException {
+ int length = in.readInt();
+ char[][] names = new char[length][];
+ for (int i = 0; i < length; i++) {
+ int nLength = in.readInt();
+ char[] name = new char[nLength];
+ for (int j = 0; j < nLength; j++)
+ name[j] = in.readChar();
+ names[i] = name;
+ }
+ return names;
+}
+
+void tagAsNoopBuild() {
+ this.buildNumber = -1; // tag the project since it has no source folders and can be skipped
+}
+
+boolean wasNoopBuild() {
+ return buildNumber == -1;
+}
+
+void tagAsStructurallyChanged() {
+ this.lastStructuralBuildTime = System.currentTimeMillis();
+}
+
+boolean wasStructurallyChanged(IProject prereqProject, State prereqState) {
+ if (prereqState != null) {
+ Object o = structuralBuildTimes.get(prereqProject.getName());
+ long previous = o == null ? 0 : ((Long) o).longValue();
+ if (previous == prereqState.lastStructuralBuildTime) return false;
+ }
+ return true;
+}
+
+void write(DataOutputStream out) throws IOException {
+ int length;
+ Object[] keyTable;
+ Object[] valueTable;
+
+/*
+ * byte VERSION
+ * String project name
+ * int build number
+ * int last structural build number
+*/
+ out.writeByte(VERSION);
+ out.writeUTF(javaProjectName);
+ out.writeInt(buildNumber);
+ out.writeLong(lastStructuralBuildTime);
+
+/*
+ * ClasspathMultiDirectory[]
+ * int id
+ * String path(s)
+*/
+ out.writeInt(length = sourceLocations.length);
+ for (int i = 0; i < length; i++) {
+ ClasspathMultiDirectory md = sourceLocations[i];
+ out.writeUTF(md.sourceFolder.getProjectRelativePath().toString());
+ out.writeUTF(md.binaryFolder.getProjectRelativePath().toString());
+ writeNames(md.exclusionPatterns, out);
+ out.writeBoolean(md.hasIndependentOutputFolder);
+ }
+
+/*
+ * ClasspathLocation[]
+ * int id
+ * String path(s)
+*/
+ out.writeInt(length = binaryLocations.length);
+ next : for (int i = 0; i < length; i++) {
+ ClasspathLocation c = binaryLocations[i];
+ if (c instanceof ClasspathMultiDirectory) {
+ out.writeByte(SOURCE_FOLDER);
+ for (int j = 0, m = sourceLocations.length; j < m; j++) {
+ if (sourceLocations[j] == c) {
+ out.writeInt(j);
+ continue next;
+ }
+ }
+ } else if (c instanceof ClasspathDirectory) {
+ out.writeByte(BINARY_FOLDER);
+ ClasspathDirectory cd = (ClasspathDirectory) c;
+ out.writeUTF(cd.binaryFolder.getFullPath().toString());
+ out.writeBoolean(cd.isOutputFolder);
+ } else {
+// ClasspathJar jar = (ClasspathJar) c;
+// if (jar.resource == null) {
+// out.writeByte(EXTERNAL_JAR);
+// out.writeUTF(jar.zipFilename);
+// } else {
+// out.writeByte(INTERNAL_JAR);
+// out.writeUTF(jar.resource.getFullPath().toString());
+// }
+ }
+ }
+
+/*
+ * Structural build numbers table
+ * String prereq project name
+ * int last structural build number
+*/
+ out.writeInt(length = structuralBuildTimes.elementSize);
+ if (length > 0) {
+ keyTable = structuralBuildTimes.keyTable;
+ valueTable = structuralBuildTimes.valueTable;
+ for (int i = 0, l = keyTable.length; i < l; i++) {
+ if (keyTable[i] != null) {
+ length--;
+ out.writeUTF((String) keyTable[i]);
+ out.writeLong(((Long) valueTable[i]).longValue());
+ }
+ }
+// if (JavaBuilder.DEBUG && length != 0)
+// System.out.println("structuralBuildNumbers table is inconsistent"); //$NON-NLS-1$
+ }
+
+/*
+ * String[] Interned type locators
+ */
+ out.writeInt(length = references.elementSize);
+ ArrayList internedTypeLocators = new ArrayList(length);
+ if (length > 0) {
+ keyTable = references.keyTable;
+ for (int i = 0, l = keyTable.length; i < l; i++) {
+ if (keyTable[i] != null) {
+ length--;
+ String key = (String) keyTable[i];
+ out.writeUTF(key);
+ internedTypeLocators.add(key);
+ }
+ }
+// if (JavaBuilder.DEBUG && length != 0)
+// System.out.println("references table is inconsistent"); //$NON-NLS-1$
+ }
+
+/*
+ * Type locators table
+ * String type name
+ * int interned locator id
+ */
+ out.writeInt(length = typeLocators.elementSize);
+ if (length > 0) {
+ keyTable = typeLocators.keyTable;
+ valueTable = typeLocators.valueTable;
+ for (int i = 0, l = keyTable.length; i < l; i++) {
+ if (keyTable[i] != null) {
+ length--;
+ out.writeUTF((String) keyTable[i]);
+ out.writeInt(internedTypeLocators.indexOf((String) valueTable[i]));
+ }
+ }
+// if (JavaBuilder.DEBUG && length != 0)
+// System.out.println("typeLocators table is inconsistent"); //$NON-NLS-1$
+ }
+
+/*
+ * char[][][] Interned qualified names
+ * char[][] Interned simple names
+ */
+ ArrayList internedQualifiedNames = new ArrayList(31);
+ ArrayList internedSimpleNames = new ArrayList(31);
+ valueTable = references.valueTable;
+ for (int i = 0, l = valueTable.length; i < l; i++) {
+// if (valueTable[i] != null) {
+// ReferenceCollection collection = (ReferenceCollection) valueTable[i];
+// char[][][] qNames = collection.qualifiedNameReferences;
+// for (int j = 0, m = qNames.length; j < m; j++) {
+// char[][] qName = qNames[j];
+// if (!internedQualifiedNames.contains(qName)) { // remember the names have been interned
+// internedQualifiedNames.add(qName);
+// for (int k = 0, n = qName.length; k < n; k++) {
+// char[] sName = qName[k];
+// if (!internedSimpleNames.contains(sName)) // remember the names have been interned
+// internedSimpleNames.add(sName);
+// }
+// }
+// }
+// char[][] sNames = collection.simpleNameReferences;
+// for (int j = 0, m = sNames.length; j < m; j++) {
+// char[] sName = sNames[j];
+// if (!internedSimpleNames.contains(sName)) // remember the names have been interned
+// internedSimpleNames.add(sName);
+// }
+// }
+ }
+ char[][] internedArray = new char[internedSimpleNames.size()][];
+ internedSimpleNames.toArray(internedArray);
+ writeNames(internedArray, out);
+ // now write the interned qualified names as arrays of interned simple names
+ out.writeInt(length = internedQualifiedNames.size());
+ for (int i = 0; i < length; i++) {
+ char[][] qName = (char[][]) internedQualifiedNames.get(i);
+ int qLength = qName.length;
+ out.writeInt(qLength);
+ for (int j = 0; j < qLength; j++)
+ out.writeInt(internedSimpleNames.indexOf(qName[j]));
+ }
+
+/*
+ * References table
+ * int interned locator id
+ * ReferenceCollection
+*/
+ out.writeInt(length = references.elementSize);
+ if (length > 0) {
+ keyTable = references.keyTable;
+ for (int i = 0, l = keyTable.length; i < l; i++) {
+// if (keyTable[i] != null) {
+// length--;
+// out.writeInt(internedTypeLocators.indexOf((String) keyTable[i]));
+// ReferenceCollection collection = (ReferenceCollection) valueTable[i];
+// if (collection instanceof AdditionalTypeCollection) {
+// out.writeByte(1);
+// AdditionalTypeCollection atc = (AdditionalTypeCollection) collection;
+// writeNames(atc.definedTypeNames, out);
+// } else {
+// out.writeByte(2);
+// }
+// char[][][] qNames = collection.qualifiedNameReferences;
+// int qLength = qNames.length;
+// out.writeInt(qLength);
+// for (int j = 0; j < qLength; j++)
+// out.writeInt(internedQualifiedNames.indexOf(qNames[j]));
+// char[][] sNames = collection.simpleNameReferences;
+// int sLength = sNames.length;
+// out.writeInt(sLength);
+// for (int j = 0; j < sLength; j++)
+// out.writeInt(internedSimpleNames.indexOf(sNames[j]));
+// }
+ }
+// if (JavaBuilder.DEBUG && length != 0)
+// System.out.println("references table is inconsistent"); //$NON-NLS-1$
+ }
+}
+
+private void writeNames(char[][] names, DataOutputStream out) throws IOException {
+ int length = names == null ? 0 : names.length;
+ out.writeInt(length);
+ for (int i = 0; i < length; i++) {
+ char[] name = names[i];
+ int nLength = name.length;
+ out.writeInt(nLength);
+ for (int j = 0; j < nLength; j++)
+ out.writeChar(name[j]);
+ }
+}
+
+/**
+ * Returns a string representation of the receiver.
+ */
+public String toString() {
+ return "State for " + javaProjectName //$NON-NLS-1$
+ + " (#" + buildNumber //$NON-NLS-1$
+ + " @ " + new Date(lastStructuralBuildTime) //$NON-NLS-1$
+ + ")"; //$NON-NLS-1$
+}
+
+/* Debug helper
+void dump() {
+ System.out.println("State for " + javaProjectName + " (" + buildNumber + " @ " + new Date(lastStructuralBuildTime) + ")");
+ System.out.println("\tClass path source locations:");
+ for (int i = 0, l = sourceLocations.length; i < l; i++)
+ System.out.println("\t\t" + sourceLocations[i]);
+ System.out.println("\tClass path binary locations:");
+ for (int i = 0, l = binaryLocations.length; i < l; i++)
+ System.out.println("\t\t" + binaryLocations[i]);
+
+ System.out.print("\tStructural build numbers table:");
+ if (structuralBuildTimes.elementSize == 0) {
+ System.out.print("