*******************************************************************************/
package net.sourceforge.phpdt.core;
+import org.eclipse.core.runtime.IProgressMonitor;
+import net.sourceforge.phpdt.core.IProblemRequestor;
+import net.sourceforge.phpdt.core.JavaModelException;
+
/**
*/
public interface ICompilationUnit extends IJavaElement, ISourceReference, IParent, IOpenable, IWorkingCopy, ISourceManipulation {
//extends IJavaElement, ISourceReference, IParent, IOpenable, IWorkingCopy, ISourceManipulation, ICodeAssist {
+
+ /**
+ * Constant indicating that a reconcile operation should not return an AST.
+ * @since 3.0
+ */
+ public static final int NO_AST = 0;
+
+ /**
+ * Changes this compilation unit handle into a working copy. A new <code>IBuffer</code> is
+ * created using this compilation unit handle's owner. Uses the primary owner is none was
+ * specified when this compilation unit handle was created.
+ * <p>
+ * When switching to working copy mode, problems are reported to given
+ * <code>IProblemRequestor</code>.
+ * </p>
+ * <p>
+ * Once in working copy mode, changes to this compilation unit or its children are done in memory.
+ * Only the new buffer is affected. Using <code>commitWorkingCopy(boolean, IProgressMonitor)</code>
+ * will bring the underlying resource in sync with this compilation unit.
+ * </p>
+ * <p>
+ * If this compilation unit was already in working copy mode, an internal counter is incremented and no
+ * other action is taken on this compilation unit. To bring this compilation unit back into the original mode
+ * (where it reflects the underlying resource), <code>discardWorkingCopy</code> must be call as many
+ * times as <code>becomeWorkingCopy</code>.
+ * </p>
+ *
+ * @param problemRequestor a requestor which will get notified of problems detected during
+ * reconciling as they are discovered. The requestor can be set to <code>null</code> indicating
+ * that the client is not interested in problems.
+ * @param monitor a progress monitor used to report progress while opening this compilation unit
+ * or <code>null</code> if no progress should be reported
+ * @throws JavaModelException if this compilation unit could not become a working copy.
+ * @see #discardWorkingCopy()
+ * @since 3.0
+ */
+ void becomeWorkingCopy(IProblemRequestor problemRequestor, IProgressMonitor monitor) throws JavaModelException;
+ /**
+ * Commits the contents of this working copy to its underlying resource.
+ *
+ * <p>It is possible that the contents of the original resource have changed
+ * since this working copy was created, in which case there is an update conflict.
+ * The value of the <code>force</code> parameter effects the resolution of
+ * such a conflict:<ul>
+ * <li> <code>true</code> - in this case the contents of this working copy are applied to
+ * the underlying resource even though this working copy was created before
+ * a subsequent change in the resource</li>
+ * <li> <code>false</code> - in this case a <code>JavaModelException</code> is thrown</li>
+ * </ul>
+ * <p>
+ * Since 2.1, a working copy can be created on a not-yet existing compilation
+ * unit. In particular, such a working copy can then be committed in order to create
+ * the corresponding compilation unit.
+ * </p>
+ * @param force a flag to handle the cases when the contents of the original resource have changed
+ * since this working copy was created
+ * @param monitor the given progress monitor
+ * @throws JavaModelException if this working copy could not commit. Reasons include:
+ * <ul>
+ * <li> A <code>CoreException</code> occurred while updating an underlying resource
+ * <li> This element is not a working copy (INVALID_ELEMENT_TYPES)
+ * <li> A update conflict (described above) (UPDATE_CONFLICT)
+ * </ul>
+ * @since 3.0
+ */
+ void commitWorkingCopy(boolean force, IProgressMonitor monitor) throws JavaModelException;
+ /**
+ * Changes this compilation unit in working copy mode back to its original mode.
+ * <p>
+ * This has no effect if this compilation unit was not in working copy mode.
+ * </p>
+ * <p>
+ * If <code>becomeWorkingCopy</code> was called several times on this
+ * compilation unit, <code>discardWorkingCopy</code> must be called as
+ * many times before it switches back to the original mode.
+ * </p>
+ *
+ * @throws JavaModelException if this working copy could not return in its original mode.
+ * @see #becomeWorkingCopy(IProblemRequestor, IProgressMonitor)
+ * @since 3.0
+ */
+ void discardWorkingCopy() throws JavaModelException;
/**
* Creates and returns an import declaration in this compilation unit
* with the given name.
*/
//IPackageDeclaration[] getPackageDeclarations() throws JavaModelException;
/**
+ * Returns the primary compilation unit (whose owner is the primary owner)
+ * this working copy was created from, or this compilation unit if this a primary
+ * compilation unit.
+ * <p>
+ * Note that the returned primary compilation unit can be in working copy mode.
+ * </p>
+ *
+ * @return the primary compilation unit this working copy was created from,
+ * or this compilation unit if it is primary
+ * @since 3.0
+ */
+ICompilationUnit getPrimary();
+/**
* Returns the top-level type declared in this compilation unit with the given simple type name.
* The type name has to be a valid compilation unit name.
* This is a handle-only method. The type may or may not exist.
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IPath;
+import org.eclipse.core.runtime.jobs.ISchedulingRule;
/**
* Common protocol for all elements provided by the Java model.
* @since 2.0
*/
IPath getPath();
-
+ /**
+ * Returns the primary element (whose compilation unit is the primary compilation unit)
+ * this working copy element was created from, or this element if it is a descendant of a
+ * primary compilation unit or if it is not a descendant of a working copy (e.g. it is a
+ * binary member).
+ * The returned element may or may not exist.
+ *
+ * @return the primary element this working copy element was created from, or this
+ * element.
+ * @since 3.0
+ */
+ IJavaElement getPrimaryElement();
/**
* Returns the innermost resource enclosing this element.
* If this element is included in an archive and this archive is not external,
* @since 2.0
*/
IResource getResource();
-
+ /**
+ * Returns the scheduling rule associated with this Java element.
+ * This is a handle-only method.
+ *
+ * @return the scheduling rule associated with this Java element
+ * @since 3.0
+ */
+ ISchedulingRule getSchedulingRule();
/**
* Returns the smallest underlying resource that contains
* this element, or <code>null</code> if this element is not contained
* @since 2.0
*/
public int F_ARCHIVE_CONTENT_CHANGED = 0x8000;
-
+ /**
+ * Change flag indicating that a compilation unit has become a primary working copy, or that a
+ * primary working copy has reverted to a compilation unit.
+ * This flag is only valid if the element is an <code>ICompilationUnit</code>.
+ *
+ * @since 3.0
+ */
+ public int F_PRIMARY_WORKING_COPY = 0x10000;
/**
* Returns deltas for the children that have been added.
* @return deltas for the children that have been added
* @since 2.1
*/
public static final int DISABLED_CP_MULTIPLE_OUTPUT_LOCATIONS = 1003;
+
+ /**
+ * Status constant indicating that a compiler failure occurred.
+ * @since 3.0
+ */
+ public static final int COMPILER_FAILURE = 1005;
}
package net.sourceforge.phpdt.core;
import org.eclipse.core.runtime.IProgressMonitor;
+import net.sourceforge.phpdt.core.JavaModelException;
/**
*/
boolean isOpen();
/**
+ * 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.
+ *
+ * <p>Note: although <code>open</code> is exposed in the API, clients are
+ * not expected to open and close elements - the Java model does this automatically
+ * as elements are accessed.
+ *
+ * @param progress the given progress monitor
+ * @exception JavaModelException if an error occurs accessing the contents
+ * of its underlying resource. Reasons include:
+ * <ul>
+ * <li>This Java element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
+ * </ul>
+ */
+public void open(IProgressMonitor progress) throws JavaModelException;
+/**
* Makes this element consistent with its underlying resource or buffer
* by updating the element's structure and properties as necessary.
*
* <li>This Java element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
* </ul>
*/
-public void open(IProgressMonitor progress) throws JavaModelException;
+//public void open(IProgressMonitor progress) throws JavaModelException;
/**
* Saves any changes in this element's buffer to its underlying resource
* via a workspace resource operation. This has no effect if the element has no underlying
* </ul>
*/
public void save(IProgressMonitor progress, boolean force) throws JavaModelException;
+
}
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceChangeEvent;
+import org.eclipse.core.resources.ISavedState;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.IWorkspaceRunnable;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Plugin;
import org.eclipse.core.runtime.Preferences;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.core.runtime.jobs.Job;
+import net.sourceforge.phpdt.internal.core.util.Util;
+import org.osgi.framework.BundleContext;
public class JavaCore {
//
// // retrieve variable values
// JavaCore.getPlugin().getPluginPreferences().addPropertyChangeListener(new JavaModelManager.PluginPreferencesListener());
-//// TODO khartlage temp-del
+//// TODO : jsurfer temp-del
//// manager.loadVariablesAndContainers();
//
// IWorkspace workspace = ResourcesPlugin.getWorkspace();
// }
// }
//}
+/* (non-Javadoc)
+ * Startup the JavaCore plug-in.
+ * <p>
+ * Registers the JavaModelManager as a resource changed listener and save participant.
+ * Starts the background indexing, and restore saved classpath variable values.
+ * <p>
+ * @throws Exception
+ * @see org.eclipse.core.runtime.Plugin#start(BundleContext)
+ */
+public static void start(final Plugin plugin, BundleContext context) throws Exception {
+// super.start(context);
+
+ final 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());
+// manager.loadVariablesAndContainers();
+
+ final IWorkspace workspace = ResourcesPlugin.getWorkspace();
+ workspace.addResourceChangeListener(
+ manager.deltaState,
+ IResourceChangeEvent.PRE_BUILD
+ | IResourceChangeEvent.POST_BUILD
+ | IResourceChangeEvent.POST_CHANGE
+ | IResourceChangeEvent.PRE_DELETE
+ | IResourceChangeEvent.PRE_CLOSE);
+
+// startIndexing();
+
+ // process deltas since last activated in indexer thread so that indexes are up-to-date.
+ // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=38658
+ Job processSavedState = new Job(Util.bind("savedState.jobName")) { //$NON-NLS-1$
+ protected IStatus run(IProgressMonitor monitor) {
+ try {
+ // add save participant and process delta atomically
+ // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=59937
+ workspace.run(
+ new IWorkspaceRunnable() {
+ public void run(IProgressMonitor progress) throws CoreException {
+// ISavedState savedState = workspace.addSaveParticipant(JavaCore.this, manager);
+ ISavedState savedState = workspace.addSaveParticipant(plugin, manager);
+ if (savedState != null) {
+ // the event type coming from the saved state is always POST_AUTO_BUILD
+ // force it to be POST_CHANGE so that the delta processor can handle it
+ manager.deltaState.getDeltaProcessor().overridenEventType = IResourceChangeEvent.POST_CHANGE;
+ savedState.processResourceChangeEvents(manager.deltaState);
+ }
+ }
+ },
+ monitor);
+ } catch (CoreException e) {
+ return e.getStatus();
+ }
+ return Status.OK_STATUS;
+ }
+ };
+ processSavedState.setSystem(true);
+ processSavedState.setPriority(Job.SHORT); // process asap
+ processSavedState.schedule();
+ } catch (RuntimeException e) {
+ manager.shutdown();
+ throw e;
+ }
+}
+/* (non-Javadoc)
+ * Shutdown the JavaCore plug-in.
+ * <p>
+ * De-registers the JavaModelManager as a resource changed listener and save participant.
+ * <p>
+ * @see org.eclipse.core.runtime.Plugin#stop(BundleContext)
+ */
+public static void stop(Plugin plugin, BundleContext context) throws Exception {
+ try {
+ plugin.savePluginPreferences();
+ IWorkspace workspace = ResourcesPlugin.getWorkspace();
+ workspace.removeResourceChangeListener(JavaModelManager.getJavaModelManager().deltaState);
+ workspace.removeSaveParticipant(plugin);
+
+ JavaModelManager.getJavaModelManager().shutdown();
+ } finally {
+ // ensure we call super.stop as the last thing
+// super.stop(context);
+ }
+}
}
\ No newline at end of file
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2000, 2004 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.internal.core.BufferManager;
+import net.sourceforge.phpdt.internal.core.DefaultWorkingCopyOwner;
+
+/**
+ * The owner of an <code>ICompilationUnit</code> handle in working copy mode.
+ * An owner is used to identify a working copy and to create its buffer.
+ * <p>
+ * Clients should subclass this class to instantiate a working copy owner that is specific to their need and that
+ * they can pass in to various APIs (e.g. <code>IType.resolveType(String, WorkingCopyOwner)</code>.
+ * Clients can also override the default implementation of <code>createBuffer(ICompilationUnit)</code>.
+ * </p><p>
+ * Note: even though this class has no abstract method, which means that it provides functional default behvior,
+ * it is still an abstract class, as clients are intended to own their owner implementation.
+ * </p>
+ * @see ICompilationUnit#becomeWorkingCopy(IProblemRequestor, org.eclipse.core.runtime.IProgressMonitor)
+ * @see ICompilationUnit#discardWorkingCopy()
+ * @see ICompilationUnit#getWorkingCopy(org.eclipse.core.runtime.IProgressMonitor)
+ * @since 3.0
+ */
+public abstract class WorkingCopyOwner {
+
+ /**
+ * Sets the buffer provider of the primary working copy owner. Note that even if the
+ * buffer provider is a working copy owner, only its <code>createBuffer(ICompilationUnit)</code>
+ * method is used by the primary working copy owner. It doesn't replace the internal primary
+ * working owner.
+ * <p>
+ * This method is for internal use by the jdt-related plug-ins.
+ * Clients outside of the jdt should not reference this method.
+ * </p>
+ *
+ * @param primaryBufferProvider the primary buffer provider
+ */
+ public static void setPrimaryBufferProvider(WorkingCopyOwner primaryBufferProvider) {
+ DefaultWorkingCopyOwner.PRIMARY.primaryBufferProvider = primaryBufferProvider;
+ }
+
+ /**
+ * Creates a buffer for the given working copy.
+ * The new buffer will be initialized with the contents of the underlying file
+ * if and only if it was not already initialized by the compilation owner (a buffer is
+ * uninitialized if its content is <code>null</code>).
+ * <p>
+ * Note: This buffer will be associated to the working copy for its entire life-cycle. Another
+ * working copy on same unit but owned by a different owner would not share the same buffer
+ * unless its owner decided to implement such a sharing behaviour.
+ * </p>
+ *
+ * @param workingCopy the working copy of the buffer
+ * @return IBuffer the created buffer for the given working copy
+ * @see IBuffer
+ */
+ public IBuffer createBuffer(ICompilationUnit workingCopy) {
+
+ return BufferManager.getDefaultBufferManager().createBuffer(workingCopy);
+ }
+
+}
// 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(
+ CompilationUnitDeclaration unit,
+ ICompilationUnit sourceUnit,
+ boolean verifyMethods,
+ boolean analyzeCode) {
+
+ try {
+ if (unit == null) {
+ // 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];
+ } else {
+ // initial type binding creation
+ lookupEnvironment.buildTypeBindings(unit);
+
+ // binding resolution
+ lookupEnvironment.completeTypeBindings();
+ }
+ // TODO : jsurfer check this
+// this.parser.getMethodBodies(unit);
+ 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();
+ }
+ if (unitsToProcess != null) 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();
+ }
+ }
+ /**
* Internal API used to resolve a given compilation unit. Can run a subset of
* the compilation process
*/
// this.reset();
}
}
+
}
import java.util.ArrayList;
+import net.sourceforge.phpdt.internal.compiler.CompilationResult;
+
import net.sourceforge.phpdt.core.compiler.CharOperation;
import net.sourceforge.phpdt.core.compiler.IProblem;
import net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit;
// diet = old;
}
}
-public void parseCompilationUnit(
- ICompilationUnit unit,
- boolean needReferenceInfo) {
-// boolean old = diet;
-// if (needReferenceInfo) {
-// unknownRefs = new NameReference[10];
-// unknownRefsCounter = 0;
-// }
+public CompilationUnitDeclaration parseCompilationUnit(
+ ICompilationUnit unit,
+ boolean fullParse) {
+
+// boolean old = diet;
+// if (fullParse) {
+// unknownRefs = new NameReference[10];
+// unknownRefsCounter = 0;
+// }
- try {
-// diet = true;
- reportReferenceInfo = needReferenceInfo;
- CompilationResult compilationUnitResult = new CompilationResult(unit, 0, 0, 10); //this.options.maxProblemsPerUnit);
- CompilationUnitDeclaration parsedUnit = parse(unit, compilationUnitResult, false);
- if (scanner.recordLineSeparator) {
- requestor.acceptLineSeparatorPositions(scanner.getLineEnds());
+ try {
+// diet = true;
+ this.reportReferenceInfo = fullParse;
+ CompilationResult compilationUnitResult = new CompilationResult(unit, 0, 0, this.options.maxProblemsPerUnit);
+ CompilationUnitDeclaration parsedUnit = parse(unit, compilationUnitResult, false);
+ if (scanner.recordLineSeparator) {
+ requestor.acceptLineSeparatorPositions(scanner.getLineEnds());
+ }
+ int initialStart = this.scanner.initialPosition;
+ int initialEnd = this.scanner.eofPosition;
+// if (this.localDeclarationVisitor != null || fullParse){
+// diet = false;
+// this.getMethodBodies(parsedUnit);
+// }
+ this.scanner.resetTo(initialStart, initialEnd);
+ notifySourceElementRequestor(parsedUnit);
+ return parsedUnit;
+ } catch (AbortCompilation e) {
+ // ignore this exception
+ } finally {
+// diet = old;
}
- int initialStart = this.scanner.initialPosition;
- int initialEnd = this.scanner.eofPosition;
-// if (this.localDeclarationVisitor != null || needReferenceInfo){
-// diet = false;
-// this.getMethodBodies(parsedUnit);
-// }
- this.scanner.resetTo(initialStart, initialEnd);
- notifySourceElementRequestor(parsedUnit);
- } catch (AbortCompilation e) {
- } finally {
-// diet = old;
+ return null;
}
-}
+
//public void parseTypeMemberDeclarations(
// ISourceType sourceType,
// ICompilationUnit sourceUnit,
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2000, 2004 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;
+
+/* This class is not intended to be instantiated. */
+public final class Assert {
+
+private Assert() {
+ // cannot be instantiated
+}
+/** Asserts that an argument is legal. If the given boolean is
+ * not <code>true</code>, an <code>IllegalArgumentException</code>
+ * is thrown.
+ *
+ * @param expression the outcode of the check
+ * @return <code>true</code> if the check passes (does not return
+ * if the check fails)
+ * @exception IllegalArgumentException if the legality test failed
+ */
+public static boolean isLegal(boolean expression) {
+ return isLegal(expression, ""); //$NON-NLS-1$
+}
+/** Asserts that an argument is legal. If the given boolean is
+ * not <code>true</code>, an <code>IllegalArgumentException</code>
+ * is thrown.
+ * The given message is included in that exception, to aid debugging.
+ *
+ * @param expression the outcode of the check
+ * @param message the message to include in the exception
+ * @return <code>true</code> if the check passes (does not return
+ * if the check fails)
+ * @exception IllegalArgumentException if the legality test failed
+ */
+public static boolean isLegal(boolean expression, String message) {
+ if (!expression)
+ throw new IllegalArgumentException(message);
+ return expression;
+}
+/** Asserts that the given object is not <code>null</code>. If this
+ * is not the case, some kind of unchecked exception is thrown.
+ *
+ * @param object the value to test
+ * @exception IllegalArgumentException if the object is <code>null</code>
+ */
+public static void isNotNull(Object object) {
+ isNotNull(object, ""); //$NON-NLS-1$
+}
+/** Asserts that the given object is not <code>null</code>. If this
+ * is not the case, some kind of unchecked exception is thrown.
+ * The given message is included in that exception, to aid debugging.
+ *
+ * @param object the value to test
+ * @param message the message to include in the exception
+ * @exception IllegalArgumentException if the object is <code>null</code>
+ */
+public static void isNotNull(Object object, String message) {
+ if (object == null)
+ throw new AssertionFailedException("null argument; " + message); //$NON-NLS-1$
+}
+/** Asserts that the given boolean is <code>true</code>. If this
+ * is not the case, some kind of unchecked exception is thrown.
+ *
+ * @param expression the outcode of the check
+ * @return <code>true</code> if the check passes (does not return
+ * if the check fails)
+ */
+public static boolean isTrue(boolean expression) {
+ return isTrue(expression, ""); //$NON-NLS-1$
+}
+/** Asserts that the given boolean is <code>true</code>. If this
+ * is not the case, some kind of unchecked exception is thrown.
+ * The given message is included in that exception, to aid debugging.
+ *
+ * @param expression the outcode of the check
+ * @param message the message to include in the exception
+ * @return <code>true</code> if the check passes (does not return
+ * if the check fails)
+ */
+public static boolean isTrue(boolean expression, String message) {
+ if (!expression)
+ throw new AssertionFailedException("Assertion failed; " + message); //$NON-NLS-1$
+ return expression;
+}
+
+ public static class AssertionFailedException extends RuntimeException {
+ public AssertionFailedException(String detail) {
+ super(detail);
+ }
+ }
+}
import java.io.File;
import java.io.IOException;
+import net.sourceforge.phpdt.core.IJavaElement;
+import net.sourceforge.phpdt.core.IJavaProject;
import net.sourceforge.phpdt.core.compiler.CharOperation;
import net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit;
import net.sourceforge.phpdt.internal.compiler.util.Util;
-import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.runtime.CoreException;
/**
* A basic implementation of <code>ICompilationUnit</code>
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;
+// 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 BasicCompilationUnit(char[] contents, char[][] packageName, String fileName) {
+ 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 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();
+ int end = fileName.lastIndexOf("."); //$NON-NLS-1$
+ if (end == -1)
+ end = fileName.length();
- this.mainTypeName = fileName.substring(start, end).toCharArray();
- this.encoding = encoding;
+ this.mainTypeName = fileName.substring(start, end).toCharArray();
+ this.encoding = null;
+}
+ public BasicCompilationUnit(char[] contents, char[][] packageName, String fileName, String encoding) {
+ this(contents, packageName, fileName);
+ this.encoding = encoding;
+ }
+ public BasicCompilationUnit(char[] contents, char[][] packageName, String fileName, IJavaElement javaElement) {
+ this(contents, packageName, fileName);
+ initEncoding(javaElement);
+ }
+ /*
+ * Initialize compilation unit encoding.
+ * If we have a project, then get file name corresponding IFile and retrieve its encoding using
+ * new API for encoding.
+ * In case of a class file, then go through project in order to let the possibility to retrieve
+ * a corresponding source file resource.
+ * If we have a compilation unit, then get encoding from its resource directly...
+ */
+ private void initEncoding(IJavaElement javaElement) {
+ if (javaElement != null) {
+ try {
+ IJavaProject javaProject = javaElement.getJavaProject();
+ switch (javaElement.getElementType()) {
+ case IJavaElement.COMPILATION_UNIT:
+ IFile file = (IFile) javaElement.getResource();
+ if (file != null) {
+ this.encoding = file.getCharset();
+ break;
+ }
+ // if no file, then get project encoding
+ default:
+ IProject project = (IProject) javaProject.getResource();
+ if (project != null) {
+ this.encoding = project.getDefaultCharset();
+ }
+ break;
+ }
+ } catch (CoreException e1) {
+ this.encoding = null;
+ }
+ } else {
+ this.encoding = null;
+ }
}
public char[] getContents() {
if (this.contents != null)
*/
protected void executeOperation() throws JavaModelException {
try {
- this.runnable.run(fMonitor);
+ this.runnable.run(progressMonitor);
} catch (CoreException ce) {
if (ce instanceof JavaModelException) {
throw (JavaModelException)ce;
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2000, 2004 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.*;
+import net.sourceforge.phpdt.core.IJavaElement;
+import net.sourceforge.phpdt.core.JavaModelException;
+
+/**
+ * Switch and ICompilationUnit to working copy mode
+ * and signal the working copy addition through a delta.
+ */
+public class BecomeWorkingCopyOperation extends JavaModelOperation {
+
+ IProblemRequestor problemRequestor;
+
+ /*
+ * Creates a BecomeWorkingCopyOperation for the given working copy.
+ * perOwnerWorkingCopies map is not null if the working copy is a shared working copy.
+ */
+ public BecomeWorkingCopyOperation(CompilationUnit workingCopy, IProblemRequestor problemRequestor) {
+ super(new IJavaElement[] {workingCopy});
+ this.problemRequestor = problemRequestor;
+ }
+ protected void executeOperation() throws JavaModelException {
+
+ // open the working copy now to ensure contents are that of the current state of this element
+ CompilationUnit workingCopy = getWorkingCopy();
+ JavaModelManager.getJavaModelManager().getPerWorkingCopyInfo(workingCopy, true/*create if needed*/, true/*record usage*/, this.problemRequestor);
+ workingCopy.openWhenClosed(workingCopy.createElementInfo(), this.progressMonitor);
+
+ if (!workingCopy.isPrimary()) {
+ // report added java delta for a non-primary working copy
+ JavaElementDelta delta = new JavaElementDelta(this.getJavaModel());
+ delta.added(workingCopy);
+ addDelta(delta);
+ } else {
+ if (workingCopy.getResource().isAccessible()) {
+ // report a F_PRIMARY_WORKING_COPY change delta for a primary working copy
+ JavaElementDelta delta = new JavaElementDelta(this.getJavaModel());
+ delta.changed(workingCopy, IJavaElementDelta.F_PRIMARY_WORKING_COPY);
+ addDelta(delta);
+ } else {
+ // report an ADDED delta
+ JavaElementDelta delta = new JavaElementDelta(this.getJavaModel());
+ delta.added(workingCopy, IJavaElementDelta.F_PRIMARY_WORKING_COPY);
+ addDelta(delta);
+ }
+ }
+
+ this.resultElements = new IJavaElement[] {workingCopy};
+ }
+ /*
+ * Returns the working copy this operation is working on.
+ */
+ protected CompilationUnit getWorkingCopy() {
+ return (CompilationUnit)getElementToProcess();
+ }
+ /*
+ * @see JavaModelOperation#isReadOnly
+ */
+ public boolean isReadOnly() {
+ return true;
+ }
+
+}
import net.sourceforge.phpdt.core.IJavaModelStatusConstants;
import net.sourceforge.phpdt.core.IOpenable;
import net.sourceforge.phpdt.core.JavaModelException;
+import net.sourceforge.phpdt.internal.core.util.Util;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2000, 2004 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.WorkingCopyOwner;
+
+/**
+ * Wraps an IBufferFactory.
+ * TODO remove when removing IBufferFactory
+ * @deprecated
+ */
+public class BufferFactoryWrapper extends WorkingCopyOwner {
+
+ public net.sourceforge.phpdt.core.IBufferFactory factory;
+
+ private BufferFactoryWrapper(net.sourceforge.phpdt.core.IBufferFactory factory) {
+ this.factory = factory;
+ }
+
+ public static WorkingCopyOwner create(net.sourceforge.phpdt.core.IBufferFactory factory) {
+ return new BufferFactoryWrapper(factory);
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.jdt.core.WorkingCopyOwner#createBuffer(org.eclipse.jdt.core.ICompilationUnit)
+ */
+ public IBuffer createBuffer(ICompilationUnit workingCopy) {
+ if (this.factory == null) return super.createBuffer(workingCopy);
+ return this.factory.createBuffer(workingCopy);
+ }
+
+ public boolean equals(Object obj) {
+ if (!(obj instanceof BufferFactoryWrapper)) return false;
+ BufferFactoryWrapper other = (BufferFactoryWrapper)obj;
+ if (this.factory == null) return other.factory == null;
+ return this.factory.equals(other.factory);
+ }
+ public int hashCode() {
+ if (this.factory == null) return 0;
+ return this.factory.hashCode();
+ }
+ public String toString() {
+ return "FactoryWrapper for " + this.factory; //$NON-NLS-1$
+ }
+}
*******************************************************************************/
package net.sourceforge.phpdt.internal.core;
+import java.util.HashMap;
+
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.JavaCore;
+import net.sourceforge.phpdt.core.JavaModelException;
import net.sourceforge.phpdt.core.compiler.CharOperation;
+import net.sourceforge.phpdt.internal.core.util.Util;
import net.sourceforge.phpdt.internal.corext.Assert;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
+import net.sourceforge.phpdt.internal.core.XMLWriter;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
return JavaCore.getResolvedClasspathEntry(this);
}
+ /**
+ * Returns the XML encoding of the class path.
+ */
+ public void elementEncode(XMLWriter writer, IPath projectPath, boolean indent, boolean newLine) {
+ HashMap parameters = new HashMap();
+
+ parameters.put("kind", ClasspathEntry.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();
+ }
+ }
+ }
+ }
+ parameters.put("path", String.valueOf(xmlPath));//$NON-NLS-1$
+
+ if (this.sourceAttachmentPath != null) {
+ xmlPath = this.sourceAttachmentPath;
+ // translate to project relative from absolute
+ if (this.entryKind != IClasspathEntry.CPE_VARIABLE && projectPath != null && projectPath.isPrefixOf(xmlPath)) {
+ if (xmlPath.segment(0).equals(projectPath.segment(0))) {
+ xmlPath = xmlPath.removeFirstSegments(1);
+ xmlPath = xmlPath.makeRelative();
+ }
+ }
+ parameters.put("sourcepath", String.valueOf(xmlPath));//$NON-NLS-1$
+ }
+ if (this.sourceAttachmentRootPath != null) {
+ parameters.put("rootpath", String.valueOf(this.sourceAttachmentRootPath));//$NON-NLS-1$
+ }
+ if (this.isExported) {
+ parameters.put("exported", "true");//$NON-NLS-1$//$NON-NLS-2$
+ }
+// if (this.inclusionPatterns != null && this.inclusionPatterns.length > 0) {
+// StringBuffer includeRule = new StringBuffer(10);
+// for (int i = 0, max = this.inclusionPatterns.length; i < max; i++){
+// if (i > 0) includeRule.append('|');
+// includeRule.append(this.inclusionPatterns[i]);
+// }
+// parameters.put("including", String.valueOf(includeRule));//$NON-NLS-1$
+// }
+ if (this.exclusionPatterns != null && 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]);
+ }
+ parameters.put("excluding", String.valueOf(excludeRule));//$NON-NLS-1$
+ }
+
+ if (this.specificOutputLocation != null) {
+ IPath outputLocation = this.specificOutputLocation.removeFirstSegments(1);
+ outputLocation = outputLocation.makeRelative();
+ parameters.put("output", String.valueOf(outputLocation));//$NON-NLS-1$
+ }
+
+ writer.printTag("classpathentry", parameters, indent, newLine, true);//$NON-NLS-1$
+ }
}
*******************************************************************************/
package net.sourceforge.phpdt.internal.core;
+import java.io.ByteArrayInputStream;
+import java.io.UnsupportedEncodingException;
+
import net.sourceforge.phpdt.core.IBuffer;
import net.sourceforge.phpdt.core.ICompilationUnit;
import net.sourceforge.phpdt.core.IJavaElement;
import net.sourceforge.phpdt.core.IJavaModelStatusConstants;
import net.sourceforge.phpdt.core.JavaModelException;
+import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.IWorkspace;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.jobs.ISchedulingRule;
+
+import net.sourceforge.phpdt.internal.core.CompilationUnit;
+import net.sourceforge.phpdt.internal.core.JavaElementDeltaBuilder;
+import net.sourceforge.phpdt.internal.core.PackageFragmentRoot;
+import net.sourceforge.phpdt.internal.core.util.Util;
/**
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()) {
+ CompilationUnit workingCopy = getCompilationUnit();
+ IFile resource = (IFile)workingCopy.getResource();
+ ICompilationUnit primary = workingCopy.getPrimary();
+ boolean isPrimary = workingCopy.isPrimary();
+
+ JavaElementDeltaBuilder deltaBuilder = null;
+// PackageFragmentRoot root = (PackageFragmentRoot)workingCopy.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
+ boolean isIncluded = !Util.isExcluded(workingCopy);
+// if (isPrimary || (root.isOnClasspath() && isIncluded && resource.isAccessible() && Util.isValidCompilationUnitName(workingCopy.getElementName()))) {
+ if (isPrimary || (isIncluded && resource.isAccessible() && Util.isValidCompilationUnitName(workingCopy.getElementName()))) {
+
// force opening so that the delta builder can get the old info
- original.open(null);
- }
- JavaElementDeltaBuilder deltaBuilder;
- if (Util.isExcluded(original)) {
- deltaBuilder = null;
+ if (!isPrimary && !primary.isOpen()) {
+ primary.open(null);
+ }
+
+ // creates the delta builder (this remembers the content of the cu) if:
+ // - it is not excluded
+ // - and it is not a primary or it is a non-consistent primary
+ if (isIncluded && (!isPrimary || !workingCopy.isConsistent())) {
+ deltaBuilder = new JavaElementDeltaBuilder(primary);
+ }
+
+ // save the cu
+ IBuffer primaryBuffer = primary.getBuffer();
+ if (!isPrimary) {
+ if (primaryBuffer == null) return;
+ char[] primaryContents = primaryBuffer.getCharacters();
+ boolean hasSaved = false;
+ try {
+ IBuffer workingCopyBuffer = workingCopy.getBuffer();
+ if (workingCopyBuffer == null) return;
+ primaryBuffer.setContents(workingCopyBuffer.getCharacters());
+ primaryBuffer.save(this.progressMonitor, this.force);
+ primary.makeConsistent(this);
+ hasSaved = true;
+ } finally {
+ if (!hasSaved){
+ // restore original buffer contents since something went wrong
+ primaryBuffer.setContents(primaryContents);
+ }
+ }
+ } else {
+ // for a primary working copy no need to set the content of the buffer again
+ primaryBuffer.save(this.progressMonitor, this.force);
+ primary.makeConsistent(this);
+ }
} 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);
+ // working copy on cu outside classpath OR resource doesn't exist yet
+ String encoding = null;
+ try {
+ encoding = resource.getCharset();
+ }
+ catch (CoreException ce) {
+ // use no encoding
+ }
+ String contents = workingCopy.getSource();
+ if (contents == null) return;
+ try {
+ byte[] bytes = encoding == null
+ ? contents.getBytes()
+ : contents.getBytes(encoding);
+ ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
+ if (resource.exists()) {
+ resource.setContents(
+ stream,
+ this.force ? IResource.FORCE | IResource.KEEP_HISTORY : IResource.KEEP_HISTORY,
+ null);
+ } else {
+ resource.create(
+ stream,
+ this.force,
+ this.progressMonitor);
+ }
+ } catch (CoreException e) {
+ throw new JavaModelException(e);
+ } catch (UnsupportedEncodingException e) {
+ throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION);
}
+
}
+
+ setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
+
// make sure working copy is in sync
- copy.updateTimeStamp((CompilationUnit)original);
- copy.makeConsistent(this);
+ workingCopy.updateTimeStamp((CompilationUnit)primary);
+ workingCopy.makeConsistent(this);
worked(1);
+ // build the deltas
if (deltaBuilder != null) {
- // build the deltas
deltaBuilder.buildDeltas();
// add the deltas to the list of deltas created during this operation
done();
}
}
+
/**
* Returns the compilation unit this operation is working on.
*/
- protected ICompilationUnit getCompilationUnit() {
- return (ICompilationUnit)getElementToProcess();
+ protected CompilationUnit getCompilationUnit() {
+ return (CompilationUnit)getElementToProcess();
+ }
+ protected ISchedulingRule getSchedulingRule() {
+ IResource resource = getElementToProcess().getResource();
+ IWorkspace workspace = resource.getWorkspace();
+ if (resource.exists()) {
+ return workspace.getRuleFactory().modifyRule(resource);
+ } else {
+ return workspace.getRuleFactory().createRule(resource);
+ }
}
/**
* Possible failures: <ul>
}
ICompilationUnit original= (ICompilationUnit)cu.getOriginalElement();
IResource resource = original.getResource();
- if (!cu.isBasedOn(resource) && !fForce) {
+ if (!cu.isBasedOn(resource) && !force) {
return new JavaModelStatus(IJavaModelStatusConstants.UPDATE_CONFLICT);
}
// no read-only check, since some repository adapters can change the flag on save
import java.util.ArrayList;
import java.util.HashMap;
-import java.util.Iterator;
import java.util.Map;
import net.sourceforge.phpdt.core.IBuffer;
import net.sourceforge.phpdt.core.IWorkingCopy;
import net.sourceforge.phpdt.core.JavaModelException;
import net.sourceforge.phpdt.core.Signature;
+import net.sourceforge.phpdt.core.WorkingCopyOwner;
import net.sourceforge.phpdt.core.compiler.CharOperation;
import net.sourceforge.phpdt.core.jdom.IDOMNode;
import net.sourceforge.phpdt.internal.compiler.IProblemFactory;
import net.sourceforge.phpdt.internal.compiler.SourceElementParser;
import net.sourceforge.phpdt.internal.compiler.impl.CompilerOptions;
import net.sourceforge.phpdt.internal.compiler.problem.DefaultProblemFactory;
+import net.sourceforge.phpdt.internal.core.util.Util;
+import net.sourceforge.phpeclipse.internal.compiler.ast.CompilationUnitDeclaration;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Path;
+import net.sourceforge.phpdt.internal.core.JavaModelManager;
+//import net.sourceforge.phpdt.core.dom.AST;
+import net.sourceforge.phpdt.internal.core.ReconcileWorkingCopyOperation;
-/**
+import net.sourceforge.phpdt.internal.core.DiscardWorkingCopyOperation;
+
+import net.sourceforge.phpdt.internal.core.CompilationUnitElementInfo;
+import net.sourceforge.phpdt.internal.core.JavaModelStatus;
+
+import net.sourceforge.phpdt.internal.core.BufferManager;
+import net.sourceforge.phpdt.internal.core.DefaultWorkingCopyOwner;
+import net.sourceforge.phpdt.internal.core.Openable;
+
+import net.sourceforge.phpdt.internal.core.PackageFragment;
+
+/**
* @see ICompilationUnit
*/
public class CompilationUnit extends Openable implements ICompilationUnit, net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit {
-
- public static boolean SHARED_WC_VERBOSE = false;
-
- // TODO: Remove when we are certain that every client is ready for this fix
- public static final boolean FIX_BUG25184 = true;
+ public WorkingCopyOwner owner;
/**
* Constructs a handle to a compilation unit with the given name in the
- * specified package.
+ * specified package for the specified owner
*
* @exception IllegalArgumentException if the name of the compilation unit
* does not end with ".java"
*/
-protected CompilationUnit(IPackageFragment parent, String name) {
- super(COMPILATION_UNIT, parent, name);
- if (!Util.isJavaFileName(name)) {
- throw new IllegalArgumentException(net.sourceforge.phpdt.internal.core.Util.bind("convention.unit.notJavaName")); //$NON-NLS-1$
- }
+protected CompilationUnit(PackageFragment parent, String name, WorkingCopyOwner owner) {
+ super(parent, name);
+ this.owner = owner;
}
/**
* Accepts the given visitor onto the parsed tree of this compilation unit, after
//public void accept(IAbstractSyntaxTreeVisitor visitor) throws JavaModelException {
// CompilationUnitVisitor.visit(this, visitor);
//}
+/*
+ * @see ICompilationUnit#becomeWorkingCopy(IProblemRequestor, IProgressMonitor)
+ */
+public void becomeWorkingCopy(IProblemRequestor problemRequestor, IProgressMonitor monitor) throws JavaModelException {
+ JavaModelManager manager = JavaModelManager.getJavaModelManager();
+ JavaModelManager.PerWorkingCopyInfo perWorkingCopyInfo = manager.getPerWorkingCopyInfo(this, false/*don't create*/, true /*record usage*/, null/*no problem requestor needed*/);
+ if (perWorkingCopyInfo == null) {
+ // close cu and its children
+ close();
-protected void buildStructure(OpenableElementInfo info, IProgressMonitor monitor) throws JavaModelException {
+ BecomeWorkingCopyOperation operation = new BecomeWorkingCopyOperation(this, problemRequestor);
+ operation.runOperation(monitor);
+ }
+}
+//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);
+//}
+protected boolean buildStructure(OpenableElementInfo info, final IProgressMonitor pm, Map newElements, IResource underlyingResource) throws JavaModelException {
- if (monitor != null && monitor.isCanceled()) return;
+ // check if this compilation unit can be opened
+ if (!isWorkingCopy()) { // no check is done on root kind or exclusion pattern for working copies
+ if ( // ((IPackageFragment)getParent()).getKind() == IPackageFragmentRoot.K_BINARY||
+ !isValidCompilationUnit()
+ || !underlyingResource.isAccessible()) {
+ throw newNotPresentException();
+ }
+ }
+
+ // prevents reopening of non-primary working copies (they are closed when they are discarded and should not be reopened)
+ if (!isPrimary() && getPerWorkingCopyInfo() == null) {
+ throw newNotPresentException();
+ }
- // remove existing (old) infos
- removeInfo();
+ CompilationUnitElementInfo unitInfo = (CompilationUnitElementInfo) info;
- 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);
+ // get buffer contents
+ IBuffer buffer = getBufferManager().getBuffer(CompilationUnit.this);
+ if (buffer == null) {
+ buffer = openBuffer(pm, unitInfo); // open buffer independently from the info, since we are building the info
}
- // 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);
-}
+ final char[] contents = buffer == null ? null : buffer.getCharacters();
+ // generate structure and compute syntax problems if needed
+ CompilationUnitStructureRequestor requestor = new CompilationUnitStructureRequestor(this, unitInfo, newElements);
+ JavaModelManager.PerWorkingCopyInfo perWorkingCopyInfo = getPerWorkingCopyInfo();
+ IJavaProject project = getJavaProject();
+ boolean computeProblems = JavaProject.hasJavaNature(project.getProject()) && perWorkingCopyInfo != null && perWorkingCopyInfo.isActive();
+ IProblemFactory problemFactory = new DefaultProblemFactory();
+ Map options = project.getOptions(true);
+ SourceElementParser parser = new SourceElementParser(
+ requestor,
+ problemFactory,
+ new CompilerOptions(options));
+ //, true/*report local declarations*/);
+ requestor.parser = parser;
+ CompilationUnitDeclaration unit = parser.parseCompilationUnit(new net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit() {
+ public char[] getContents() {
+ return contents;
+ }
+ public char[] getMainTypeName() {
+ return CompilationUnit.this.getMainTypeName();
+ }
+ public char[][] getPackageName() {
+ return CompilationUnit.this.getPackageName();
+ }
+ public char[] getFileName() {
+ return CompilationUnit.this.getFileName();
+ }
+ }, true /*full parse to find local elements*/);
+
+ // update timestamp (might be IResource.NULL_STAMP if original does not exist)
+ if (underlyingResource == null) {
+ underlyingResource = getResource();
+ }
+ unitInfo.timestamp = ((IFile)underlyingResource).getModificationStamp();
+
+ // compute other problems if needed
+ CompilationUnitDeclaration compilationUnitDeclaration = null;
+ try {
+ if (computeProblems){
+ perWorkingCopyInfo.beginReporting();
+ compilationUnitDeclaration = CompilationUnitProblemFinder.process(unit, this, contents, parser, this.owner, perWorkingCopyInfo, problemFactory, false/*don't cleanup cu*/, pm);
+ perWorkingCopyInfo.endReporting();
+ }
+
+// if (info instanceof ASTHolderCUInfo) {
+// int astLevel = ((ASTHolderCUInfo) info).astLevel;
+// org.eclipse.jdt.core.dom.CompilationUnit cu = AST.convertCompilationUnit(astLevel, unit, contents, options, pm);
+// ((ASTHolderCUInfo) info).ast = cu;
+// }
+ } finally {
+ if (compilationUnitDeclaration != null) {
+ compilationUnitDeclaration.cleanUp();
+ }
+ }
+
+ return unitInfo.isStructureKnown();
+}
///**
// * @see ICodeAssist#codeComplete(int, ICompletionRequestor)
// */
throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, this));
}
/**
+ * @see ICompilationUnit#commitWorkingCopy(boolean, IProgressMonitor)
+ */
+public void commitWorkingCopy(boolean force, IProgressMonitor monitor) throws JavaModelException {
+ CommitWorkingCopyOperation op= new CommitWorkingCopyOperation(this, force);
+ op.runOperation(monitor);
+}
+/**
* @see ISourceManipulation#copy(IJavaElement, IJavaElement, String, boolean, IProgressMonitor)
*/
public void copy(IJavaElement container, IJavaElement sibling, String rename, boolean force, IProgressMonitor monitor) throws JavaModelException {
}
getJavaModel().copy(elements, containers, null, renamings, force, monitor);
}
+
/**
* Returns a new element info for this element.
*/
-protected OpenableElementInfo createElementInfo() {
+protected Object createElementInfo() {
return new CompilationUnitElementInfo();
}
///**
getJavaModel().delete(elements, force, monitor);
}
/**
- * This is not a working copy, do nothing.
- *
* @see IWorkingCopy#destroy()
+ * @deprecated
*/
public void destroy() {
+ try {
+ discardWorkingCopy();
+ } catch (JavaModelException e) {
+ e.printStackTrace();
+ }
+}
+/*
+ * @see ICompilationUnit#discardWorkingCopy
+ */
+public void discardWorkingCopy() throws JavaModelException {
+ // discard working copy and its children
+ DiscardWorkingCopyOperation op = new DiscardWorkingCopyOperation(this);
+ op.runOperation(null);
}
-
/**
* Returns true if this handle represents the same Java element
* as the given handle.
*
- * <p>Compilation units must also check working copy state;
- *
* @see Object#equals(java.lang.Object)
*/
-public boolean equals(Object o) {
- return super.equals(o) && !((ICompilationUnit)o).isWorkingCopy();
+public boolean equals(Object obj) {
+ if (!(obj instanceof CompilationUnit)) return false;
+ CompilationUnit other = (CompilationUnit)obj;
+ return this.owner.equals(other.owner) && super.equals(obj);
}
/**
* @see JavaElement#equalsDOMNode(IDOMNode)
}
return null;
}
-
/**
* @see IWorkingCopy#findSharedWorkingCopy(IBufferFactory)
+ * @deprecated
*/
public IJavaElement findSharedWorkingCopy(IBufferFactory factory) {
// if factory is null, default factory must be used
if (factory == null) factory = this.getBufferManager().getDefaultBufferFactory();
-
- // 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 = JavaModelManager.getJavaModelManager().sharedWorkingCopies;
- Map perFactoryWorkingCopies = (Map) sharedWorkingCopies.get(factory);
- if (perFactoryWorkingCopies == null) return null;
- return (WorkingCopy)perFactoryWorkingCopies.get(this);
+ return findWorkingCopy(BufferFactoryWrapper.create(factory));
}
+/**
+ * @see ICompilationUnit#findWorkingCopy(WorkingCopyOwner)
+ */
+public ICompilationUnit findWorkingCopy(WorkingCopyOwner workingCopyOwner) {
+ CompilationUnit cu = new CompilationUnit((PackageFragment)this.parent, getElementName(), workingCopyOwner);
+ if (workingCopyOwner == DefaultWorkingCopyOwner.PRIMARY) {
+ return cu;
+ } else {
+ // must be a working copy
+ JavaModelManager.PerWorkingCopyInfo perWorkingCopyInfo = cu.getPerWorkingCopyInfo();
+ if (perWorkingCopyInfo != null) {
+ return perWorkingCopyInfo.getWorkingCopy();
+ } else {
+ return null;
+ }
+ }
+}
protected boolean generateInfos(OpenableElementInfo info, IProgressMonitor pm, Map newElements, IResource underlyingResource) throws JavaModelException {
// if (getParent() instanceof JarPackageFragment) {
if (isWorkingCopy()) {
CompilationUnit original = (CompilationUnit) getOriginalElement();
// might be IResource.NULL_STAMP if original does not exist
- unitInfo.fTimestamp = ((IFile) original.getResource()).getModificationStamp();
+ unitInfo.timestamp = ((IFile) original.getResource()).getModificationStamp();
}
return unitInfo.isStructureKnown();
// }
return e;
}
}
+/**
+ * @see IJavaElement
+ */
+public int getElementType() {
+ return COMPILATION_UNIT;
+}
public char[] getFileName(){
return getElementName().toCharArray();
}
name= name.substring(0, name.length() - 5);
return name.toCharArray();
}
+
/**
- * Returns <code>null</code>, this is not a working copy.
- *
* @see IWorkingCopy#getOriginal(IJavaElement)
+ * @deprecated
*/
public IJavaElement getOriginal(IJavaElement workingCopyElement) {
- return null;
+ // backward compatibility
+ if (!isWorkingCopy()) return null;
+ CompilationUnit cu = (CompilationUnit)workingCopyElement.getAncestor(COMPILATION_UNIT);
+ if (cu == null || !this.owner.equals(cu.owner)) {
+ return null;
+ }
+
+ return workingCopyElement.getPrimaryElement();
}
/**
- * Returns <code>null</code>, this is not a working copy.
- *
* @see IWorkingCopy#getOriginalElement()
+ * @deprecated
*/
public IJavaElement getOriginalElement() {
- return null;
+ // backward compatibility
+ if (!isWorkingCopy()) return null;
+
+ return getPrimaryElement();
+}
+/*
+ * @see ICompilationUnit#getOwner()
+ */
+public WorkingCopyOwner getOwner() {
+ return isPrimary() || !isWorkingCopy() ? null : this.owner;
}
/**
* @see ICompilationUnit#getPackageDeclaration(String)
return this.getParent().getPath().append(this.getElementName());
}
}
+/*
+ * Returns the per working copy info for the receiver, or null if none exist.
+ * Note: the use count of the per working copy info is NOT incremented.
+ */
+public JavaModelManager.PerWorkingCopyInfo getPerWorkingCopyInfo() {
+ return JavaModelManager.getJavaModelManager().getPerWorkingCopyInfo(this, false/*don't create*/, false/*don't record usage*/, null/*no problem requestor needed*/);
+}
+/*
+ * @see ICompilationUnit#getPrimary()
+ */
+public ICompilationUnit getPrimary() {
+ return (ICompilationUnit)getPrimaryElement(true);
+}
+/*
+ * @see JavaElement#getPrimaryElement(boolean)
+ */
+public IJavaElement getPrimaryElement(boolean checkOwner) {
+ if (checkOwner && isPrimary()) return this;
+ return new CompilationUnit((PackageFragment)getParent(), getElementName(), DefaultWorkingCopyOwner.PRIMARY);
+}
+
/**
* @see IJavaElement#getResource()
*/
list.toArray(array);
return array;
}
+/**
+ * @see IJavaElement
+ */
public IResource getUnderlyingResource() throws JavaModelException {
- if (FIX_BUG25184) {
- return super.getUnderlyingResource();
- } else {
- return getResource();
- }
+ if (isWorkingCopy() && !isPrimary()) return null;
+ return super.getUnderlyingResource();
}
+///**
+// * @see IWorkingCopy#getSharedWorkingCopy(IProgressMonitor, IBufferFactory, IProblemRequestor)
+// */
+//public IJavaElement getSharedWorkingCopy(IProgressMonitor pm, IBufferFactory factory, IProblemRequestor problemRequestor) throws JavaModelException {
+//
+// // if factory is null, default factory must be used
+// if (factory == null) factory = this.getBufferManager().getDefaultBufferFactory();
+//
+// 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(factory);
+// if (perFactoryWorkingCopies == null){
+// perFactoryWorkingCopies = new HashMap();
+// sharedWorkingCopies.put(factory, perFactoryWorkingCopies);
+// }
+// WorkingCopy workingCopy = (WorkingCopy)perFactoryWorkingCopies.get(this);
+// if (workingCopy != null) {
+// workingCopy.useCount++;
+//
+// if (SHARED_WC_VERBOSE) {
+// System.out.println("Incrementing use count of shared working copy " + workingCopy.toStringWithAncestors()); //$NON-NLS-1$
+// }
+//
+// return workingCopy;
+// } else {
+// CreateWorkingCopyOperation op = new CreateWorkingCopyOperation(this, perFactoryWorkingCopies, factory, problemRequestor);
+// runOperation(op, pm);
+// return op.getResultElements()[0];
+// }
+//}
+///**
+// * @see IWorkingCopy#getWorkingCopy()
+// */
+//public IJavaElement getWorkingCopy() throws JavaModelException {
+// return this.getWorkingCopy(null, null, null);
+//}
+//
+///**
+// * @see IWorkingCopy#getWorkingCopy(IProgressMonitor, IBufferFactory, IProblemRequestor)
+// */
+//public IJavaElement getWorkingCopy(IProgressMonitor pm, IBufferFactory factory, IProblemRequestor problemRequestor) throws JavaModelException {
+// CreateWorkingCopyOperation op = new CreateWorkingCopyOperation(this, null, factory, problemRequestor);
+// runOperation(op, pm);
+// return op.getResultElements()[0];
+//}
/**
* @see IWorkingCopy#getSharedWorkingCopy(IProgressMonitor, IBufferFactory, IProblemRequestor)
+ * @deprecated
*/
public IJavaElement getSharedWorkingCopy(IProgressMonitor pm, IBufferFactory factory, IProblemRequestor problemRequestor) throws JavaModelException {
// if factory is null, default factory must be used
if (factory == null) factory = this.getBufferManager().getDefaultBufferFactory();
-
- 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(factory);
- if (perFactoryWorkingCopies == null){
- perFactoryWorkingCopies = new HashMap();
- sharedWorkingCopies.put(factory, perFactoryWorkingCopies);
- }
- WorkingCopy workingCopy = (WorkingCopy)perFactoryWorkingCopies.get(this);
- if (workingCopy != null) {
- workingCopy.useCount++;
-
- if (SHARED_WC_VERBOSE) {
- System.out.println("Incrementing use count of shared working copy " + workingCopy.toStringWithAncestors()); //$NON-NLS-1$
- }
-
- return workingCopy;
- } else {
- CreateWorkingCopyOperation op = new CreateWorkingCopyOperation(this, perFactoryWorkingCopies, factory, problemRequestor);
- runOperation(op, pm);
- return op.getResultElements()[0];
- }
+ return getWorkingCopy(BufferFactoryWrapper.create(factory), problemRequestor, pm);
}
/**
* @see IWorkingCopy#getWorkingCopy()
+ * @deprecated
*/
public IJavaElement getWorkingCopy() throws JavaModelException {
- return this.getWorkingCopy(null, null, null);
+ return getWorkingCopy(null);
+}
+/**
+ * @see ICompilationUnit#getWorkingCopy(IProgressMonitor)
+ */
+public ICompilationUnit getWorkingCopy(IProgressMonitor monitor) throws JavaModelException {
+ return getWorkingCopy(new WorkingCopyOwner() {/*non shared working copy*/}, null/*no problem requestor*/, monitor);
}
-
/**
* @see IWorkingCopy#getWorkingCopy(IProgressMonitor, IBufferFactory, IProblemRequestor)
+ * @deprecated
*/
-public IJavaElement getWorkingCopy(IProgressMonitor pm, IBufferFactory factory, IProblemRequestor problemRequestor) throws JavaModelException {
- CreateWorkingCopyOperation op = new CreateWorkingCopyOperation(this, null, factory, problemRequestor);
- runOperation(op, pm);
- return op.getResultElements()[0];
+public IJavaElement getWorkingCopy(IProgressMonitor monitor, IBufferFactory factory, IProblemRequestor problemRequestor) throws JavaModelException {
+ return getWorkingCopy(BufferFactoryWrapper.create(factory), problemRequestor, monitor);
}
-
/**
- * @see Openable#hasBuffer()
+ * @see ICompilationUnit#getWorkingCopy(WorkingCopyOwner, IProblemRequestor, IProgressMonitor)
*/
-protected boolean hasBuffer() {
- return true;
+public ICompilationUnit getWorkingCopy(WorkingCopyOwner workingCopyOwner, IProblemRequestor problemRequestor, IProgressMonitor monitor) throws JavaModelException {
+ if (!isPrimary()) return this;
+
+ JavaModelManager manager = JavaModelManager.getJavaModelManager();
+
+ CompilationUnit workingCopy = new CompilationUnit((PackageFragment)getParent(), getElementName(), workingCopyOwner);
+ JavaModelManager.PerWorkingCopyInfo perWorkingCopyInfo =
+ manager.getPerWorkingCopyInfo(workingCopy, false/*don't create*/, true/*record usage*/, null/*not used since don't create*/);
+ if (perWorkingCopyInfo != null) {
+ return perWorkingCopyInfo.getWorkingCopy(); // return existing handle instead of the one created above
+ }
+ BecomeWorkingCopyOperation op = new BecomeWorkingCopyOperation(workingCopy, problemRequestor);
+ op.runOperation(monitor);
+ return workingCopy;
}
+
/**
* If I am not open, return true to avoid parsing.
*
return false;
}
/**
- * Returns false, this is not a working copy.
- *
+ * @see Openable#hasBuffer()
+ */
+protected boolean hasBuffer() {
+ return true;
+}
+/*
+ * @see ICompilationUnit#hasResourceChanged()
+ */
+public boolean hasResourceChanged() {
+ if (!isWorkingCopy()) return false;
+
+ // if resource got deleted, then #getModificationStamp() will answer IResource.NULL_STAMP, which is always different from the cached
+ // timestamp
+ Object info = JavaModelManager.getJavaModelManager().getInfo(this);
+ if (info == null) return false;
+ return ((CompilationUnitElementInfo)info).timestamp != getResource().getModificationStamp();
+}
+/**
* @see IWorkingCopy#isBasedOn(IResource)
+ * @deprecated
*/
public boolean isBasedOn(IResource resource) {
- return false;
+ if (!isWorkingCopy()) return false;
+ if (!getResource().equals(resource)) return false;
+ return !hasResourceChanged();
}
/**
* @see IOpenable#isConsistent()
*/
-public boolean isConsistent() throws JavaModelException {
+public boolean isConsistent() {
return JavaModelManager.getJavaModelManager().getElementsOutOfSynchWithBuffers().get(this) == null;
}
+
+/**
+ *
+ * @see IOpenable
+ */
+public boolean isOpen() {
+ Object info = JavaModelManager.getJavaModelManager().getInfo(this);
+ return info != null && ((CompilationUnitElementInfo)info).isOpen();
+}
+public boolean isPrimary() {
+ return this.owner == DefaultWorkingCopyOwner.PRIMARY;
+}
/**
* @see Openable#isSourceElement()
*/
protected boolean isSourceElement() {
return true;
}
-/**
- * @see IWorkingCopy#isWorkingCopy()
+protected boolean isValidCompilationUnit() {
+ IPackageFragmentRoot root = getPackageFragmentRoot();
+ try {
+ if (root.getKind() != IPackageFragmentRoot.K_SOURCE) return false;
+ } catch (JavaModelException e) {
+ return false;
+ }
+// IResource resource = getResource();
+// if (resource != null) {
+// char[][] inclusionPatterns = ((PackageFragmentRoot)root).fullInclusionPatternChars();
+// char[][] exclusionPatterns = ((PackageFragmentRoot)root).fullExclusionPatternChars();
+// if (Util.isExcluded(resource, inclusionPatterns, exclusionPatterns)) return false;
+// }
+ if (!Util.isValidCompilationUnitName(getElementName())) return false;
+ return true;
+}
+/*
+ * @see ICompilationUnit#isWorkingCopy()
*/
public boolean isWorkingCopy() {
- return false;
+ // For backward compatibility, non primary working copies are always returning true; in removal
+ // delta, clients can still check that element was a working copy before being discarded.
+ return !isPrimary() || getPerWorkingCopyInfo() != null;
}
/**
* @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
- // create a new info and make it the current info
- OpenableElementInfo info = createElementInfo();
- buildStructure(info, monitor);
- }
+ makeConsistent(false/*don't create AST*/, 0, monitor);
+}
+public Object makeConsistent(boolean createAST, int astLevel, IProgressMonitor monitor) throws JavaModelException {
+ if (isConsistent()) return null;
+
+ // create a new info and make it the current info
+ // (this will remove the info and its children just before storing the new infos)
+// if (createAST) {
+// ASTHolderCUInfo info = new ASTHolderCUInfo();
+// info.astLevel = astLevel;
+// openWhenClosed(info, monitor);
+// org.eclipse.jdt.core.dom.CompilationUnit result = info.ast;
+// info.ast = null;
+// return result;
+// } else {
+ openWhenClosed(createElementInfo(), monitor);
+ return null;
+// }
}
+//public net.sourceforge.phpdt.core.dom.CompilationUnit makeConsistent(boolean createAST, int astLevel, IProgressMonitor monitor) throws JavaModelException {
+// if (isConsistent()) return null;
+//
+// // create a new info and make it the current info
+// // (this will remove the info and its children just before storing the new infos)
+// if (createAST) {
+// ASTHolderCUInfo info = new ASTHolderCUInfo();
+// info.astLevel = astLevel;
+// openWhenClosed(info, monitor);
+// net.sourceforge.phpdt.core.dom.CompilationUnit result = info.ast;
+// info.ast = null;
+// return result;
+// } else {
+// openWhenClosed(createElementInfo(), monitor);
+// return null;
+// }
+//}
/**
* @see ISourceManipulation#move(IJavaElement, IJavaElement, String, boolean, IProgressMonitor)
getJavaModel().move(elements, containers, null, renamings, force, monitor);
}
+///**
+// * @see Openable#openBuffer(IProgressMonitor)
+// */
+//protected IBuffer openBuffer(IProgressMonitor pm) throws JavaModelException {
+//
+// // create buffer - compilation units only use default buffer factory
+// BufferManager bufManager = getBufferManager();
+// IBuffer buffer = getBufferFactory().createBuffer(this);
+// if (buffer == null) return null;
+//
+// // set the buffer source
+// if (buffer.getCharacters() == null){
+// IFile file = (IFile)this.getResource();
+// if (file == null || !file.exists()) throw newNotPresentException();
+// buffer.setContents(Util.getResourceContentsAsCharArray(file));
+// }
+//
+// // add buffer to buffer cache
+// bufManager.addBuffer(buffer);
+//
+// // listen to buffer changes
+// buffer.addBufferChangedListener(this);
+//
+// return buffer;
+//}
/**
- * @see Openable#openBuffer(IProgressMonitor)
+ * @see Openable#openBuffer(IProgressMonitor, Object)
*/
-protected IBuffer openBuffer(IProgressMonitor pm) throws JavaModelException {
+protected IBuffer openBuffer(IProgressMonitor pm, Object info) throws JavaModelException {
- // create buffer - compilation units only use default buffer factory
- BufferManager bufManager = getBufferManager();
- IBuffer buffer = getBufferFactory().createBuffer(this);
+ // create buffer
+ boolean isWorkingCopy = isWorkingCopy();
+ IBuffer buffer =
+ isWorkingCopy
+ ? this.owner.createBuffer(this)
+ : BufferManager.getDefaultBufferManager().createBuffer(this);
if (buffer == null) return null;
// set the buffer source
- if (buffer.getCharacters() == null){
- IFile file = (IFile)this.getResource();
- if (file == null || !file.exists()) throw newNotPresentException();
- buffer.setContents(Util.getResourceContentsAsCharArray(file));
+ if (buffer.getCharacters() == null) {
+ if (isWorkingCopy) {
+ ICompilationUnit original;
+ if (!isPrimary()
+ && (original = new CompilationUnit((PackageFragment)getParent(), getElementName(), DefaultWorkingCopyOwner.PRIMARY)).isOpen()) {
+ buffer.setContents(original.getSource());
+ } else {
+ IFile file = (IFile)getResource();
+ if (file == null || !file.exists()) {
+ // initialize buffer with empty contents
+ buffer.setContents(CharOperation.NO_CHAR);
+ } else {
+ buffer.setContents(Util.getResourceContentsAsCharArray(file));
+ }
+ }
+ } else {
+ IFile file = (IFile)this.getResource();
+ if (file == null || !file.exists()) throw newNotPresentException();
+ buffer.setContents(Util.getResourceContentsAsCharArray(file));
+ }
}
// add buffer to buffer cache
+ BufferManager bufManager = getBufferManager();
bufManager.addBuffer(buffer);
// listen to buffer changes
return buffer;
}
-protected void openParent(IProgressMonitor pm) throws JavaModelException {
- if (FIX_BUG25184) {
- super.openParent(pm);
- } else {
- try {
- super.openParent(pm);
- } catch(JavaModelException e){
- // allow parent to not exist for compilation units defined outside classpath
- if (!e.isDoesNotExist()){
- throw e;
- }
+/*
+ * @see Openable#openParent
+ */
+protected void openParent(Object childInfo, HashMap newElements, IProgressMonitor pm) throws JavaModelException {
+ try {
+ super.openParent(childInfo, newElements, pm);
+ } catch(JavaModelException e){
+ // allow parent to not exist for working copies defined outside classpath
+ if (!isWorkingCopy() && !e.isDoesNotExist()){
+ throw e;
}
}
}
-protected boolean parentExists() {
- if (FIX_BUG25184) {
- return super.parentExists();
- } else {
- return true; // tolerate units outside classpath
- }
-}
/**
- * @see IWorkingCopy#reconcile()
+ * @see ICompilationUnit#reconcile()
+ * @deprecated
*/
public IMarker[] reconcile() throws JavaModelException {
- // Reconciling is not supported on non working copies
+ reconcile(NO_AST, false/*don't force problem detection*/, null/*use primary owner*/, null/*no progress monitor*/);
return null;
}
+/**
+ * @see ICompilationUnit#reconcile(int, boolean, WorkingCopyOwner, IProgressMonitor)
+ */
+public void reconcile(boolean forceProblemDetection, IProgressMonitor monitor) throws JavaModelException {
+ reconcile(NO_AST, forceProblemDetection, null/*use primary owner*/, monitor);
+}
/**
- * @see IWorkingCopy#reconcile(boolean, IProgressMonitor)
+ * @see ICompilationUnit#reconcile(int, boolean, WorkingCopyOwner, IProgressMonitor)
+ * @since 3.0
*/
-public void reconcile(
+//public org.eclipse.jdt.core.dom.CompilationUnit reconcile(
+ public Object reconcile(
+ int astLevel,
boolean forceProblemDetection,
+ WorkingCopyOwner workingCopyOwner,
IProgressMonitor monitor)
throws JavaModelException {
- // Reconciling is not supported on non working copies
+
+ if (!isWorkingCopy()) return null; // Reconciling is not supported on non working copies
+ if (workingCopyOwner == null) workingCopyOwner = DefaultWorkingCopyOwner.PRIMARY;
+
+ boolean createAST = false;
+// if (astLevel == AST.JLS2) {
+// // client asking for level 2 AST; these are supported
+// createAST = true;
+// } else if (astLevel == AST.JLS3) {
+// // client asking for level 3 ASTs; these are not supported
+// // TODO (jerome) - these should also be supported in 1.5 stream
+// createAST = false;
+// } else {
+// // client asking for no AST (0) or unknown ast level
+// // either way, request denied
+// createAST = false;
+// }
+ ReconcileWorkingCopyOperation op = new ReconcileWorkingCopyOperation(this, createAST, astLevel, forceProblemDetection, workingCopyOwner);
+ op.runOperation(monitor);
+// return op.ast;
+ return null;
}
/**
// }
// });
//}
-/**
- * @see JavaElement#rootedAt(IJavaProject)
+///**
+// * @see JavaElement#rootedAt(IJavaProject)
+// */
+//public IJavaElement rootedAt(IJavaProject project) {
+// return
+// new CompilationUnit(
+// (IPackageFragment)((JavaElement)parent).rootedAt(project),
+// name);
+//}
+/*
+ * Assume that this is a working copy
*/
-public IJavaElement rootedAt(IJavaProject project) {
- return
- new CompilationUnit(
- (IPackageFragment)((JavaElement)fParent).rootedAt(project),
- fName);
+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()).timestamp = timeStamp;
}
-
}
/**
* The length of this compilation unit's source code <code>String</code>
*/
- protected int fSourceLength;
-
+ protected int sourceLength;
+
/**
* Timestamp of original resource at the time this element
* was opened or last updated.
*/
- protected long fTimestamp;
+ protected long timestamp;
/**
* Returns the length of the source string.
*/
public int getSourceLength() {
- return fSourceLength;
+ return sourceLength;
}
protected ISourceRange getSourceRange() {
- return new SourceRange(0, fSourceLength);
+ return new SourceRange(0, sourceLength);
+}
+protected boolean isOpen() {
+ return true;
}
/**
* Sets the length of the source string.
*/
public void setSourceLength(int newSourceLength) {
- fSourceLength = newSourceLength;
+ sourceLength = newSourceLength;
}
}
import net.sourceforge.phpdt.core.ICompilationUnit;
import net.sourceforge.phpdt.core.IJavaElement;
+import net.sourceforge.phpdt.core.IJavaModelStatusConstants;
import net.sourceforge.phpdt.core.IJavaProject;
import net.sourceforge.phpdt.core.IPackageFragment;
import net.sourceforge.phpdt.core.IProblemRequestor;
import net.sourceforge.phpdt.core.JavaCore;
import net.sourceforge.phpdt.core.JavaModelException;
+import net.sourceforge.phpdt.core.WorkingCopyOwner;
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.env.ISourceType;
import net.sourceforge.phpdt.internal.compiler.lookup.PackageBinding;
import net.sourceforge.phpdt.internal.compiler.parser.SourceTypeConverter;
+import net.sourceforge.phpdt.internal.compiler.parser.UnitParser;
import net.sourceforge.phpdt.internal.compiler.problem.AbortCompilation;
import net.sourceforge.phpdt.internal.compiler.problem.DefaultProblemFactory;
+import net.sourceforge.phpdt.internal.core.util.Util;
import net.sourceforge.phpeclipse.internal.compiler.ast.CompilationUnitDeclaration;
import org.eclipse.core.runtime.IProgressMonitor;
+import net.sourceforge.phpdt.internal.core.JavaModelManager;
/**
* Responsible for resolving types inside a compilation unit being reconciled,
}
public static CompilationUnitDeclaration process(
+ CompilationUnitDeclaration unit,
+ ICompilationUnit unitElement,
+ char[] contents,
+ UnitParser parser,
+ WorkingCopyOwner workingCopyOwner,
+ IProblemRequestor problemRequestor,
+ IProblemFactory problemFactory,
+ boolean cleanupCU,
+ IProgressMonitor monitor)
+ throws JavaModelException {
+
+ char[] fileName = unitElement.getElementName().toCharArray();
+
+ JavaProject project = (JavaProject) unitElement.getJavaProject();
+ CompilationUnitProblemFinder problemFinder =
+ new CompilationUnitProblemFinder(
+ project.newSearchableNameEnvironment(workingCopyOwner),
+ getHandlingPolicy(),
+ project.getOptions(true),
+ getRequestor(),
+ problemFactory);
+ if (parser != null) {
+ problemFinder.parser = parser;
+ }
+
+ try {
+
+ IPackageFragment packageFragment = (IPackageFragment)unitElement.getAncestor(IJavaElement.PACKAGE_FRAGMENT);
+ char[][] expectedPackageName = null;
+ if (packageFragment != null){
+ expectedPackageName = CharOperation.splitOn('.', packageFragment.getElementName().toCharArray());
+ }
+ if (unit == null) {
+ unit = problemFinder.resolve(
+ new BasicCompilationUnit(
+ contents,
+ expectedPackageName,
+ new String(fileName),
+ unitElement),
+ true, // verify methods
+ true); //, // analyze code
+ //true); // generate code
+ } else {
+ problemFinder.resolve(
+ unit,
+ null, // no need for source
+ true, // verify methods
+ true); //, // analyze code
+ // true); // generate code
+ }
+ reportProblems(unit, problemRequestor, monitor);
+ return unit;
+ } catch(RuntimeException e) {
+ // avoid breaking other tools due to internal compiler failure (40334)
+ Util.log(e, "Exception occurred during problem detection: "); //$NON-NLS-1$
+ throw new JavaModelException(e, IJavaModelStatusConstants.COMPILER_FAILURE);
+ } finally {
+ if (cleanupCU && unit != null) {
+ unit.cleanUp();
+ }
+ problemFinder.lookupEnvironment.reset();
+ }
+ }
+ public static CompilationUnitDeclaration process(
+ ICompilationUnit unitElement,
+ char[] contents,
+ WorkingCopyOwner workingCopyOwner,
+ IProblemRequestor problemRequestor,
+ boolean cleanupCU,
+ IProgressMonitor monitor)
+ throws JavaModelException {
+
+ return process(null/*no CompilationUnitDeclaration*/, unitElement, contents, null/*use default Parser*/, workingCopyOwner, problemRequestor, new DefaultProblemFactory(), cleanupCU, monitor);
+ }
+ public static CompilationUnitDeclaration process(
ICompilationUnit unitElement,
IProblemRequestor problemRequestor,
IProgressMonitor monitor)
problemFinder.lookupEnvironment.reset();
}
}
+ private static void reportProblems(CompilationUnitDeclaration unit, IProblemRequestor problemRequestor, IProgressMonitor monitor) {
+ CompilationResult unitResult = unit.compilationResult;
+ IProblem[] problems = unitResult.getAllProblems();
+ for (int i = 0, problemLength = problems == null ? 0 : problems.length; i < problemLength; i++) {
+ if (JavaModelManager.VERBOSE){
+ System.out.println("PROBLEM FOUND while reconciling : "+problems[i].getMessage());//$NON-NLS-1$
+ }
+ if (monitor != null && monitor.isCanceled()) break;
+ problemRequestor.acceptProblem(problems[i]);
+ }
+ }
}
import java.util.Map;
import java.util.Stack;
+import net.sourceforge.phpdt.internal.core.JavaElement;
+import net.sourceforge.phpdt.internal.core.SourceField;
+import net.sourceforge.phpdt.internal.core.SourceFieldElementInfo;
+import net.sourceforge.phpdt.internal.core.SourceMethod;
+import net.sourceforge.phpdt.internal.core.SourceTypeElementInfo;
+
import net.sourceforge.phpdt.core.ICompilationUnit;
import net.sourceforge.phpdt.core.IField;
import net.sourceforge.phpdt.core.IJavaElement;
exceptionTypes,
true);
}
+
/**
* @see ISourceElementRequestor
*/
IField handle = null;
if (parentHandle.getElementType() == IJavaElement.TYPE) {
- handle = new SourceField((IType) parentHandle, new String(name));
+ handle = new SourceField(parentHandle, new String(name));
} else {
Assert.isTrue(false); // Should not happen
}
}
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);
-
+ // TODO : jsurfer changed
+// if (parentHandle.getElementType() == IJavaElement.TYPE) {
+ handle = new SourceMethod(parentHandle, new String(name), parameterTypeSigs);
+// }
+// else {
+// Assert.isTrue(false); // Should not happen
+// }
+ resolveDuplicates(handle);
+
SourceMethodElementInfo info = new SourceMethodElementInfo();
info.setSourceRangeStart(declarationStart);
int flags = modifiers;
import net.sourceforge.phpdt.core.jdom.DOMFactory;
import net.sourceforge.phpdt.core.jdom.IDOMCompilationUnit;
import net.sourceforge.phpdt.core.jdom.IDOMNode;
+import net.sourceforge.phpdt.internal.core.util.Util;
/**
* This operation copies/moves a collection of elements from their current
}
if (createElementInCUOperation && isMove() && !isRenamingMainType(element, destination)) {
- DeleteElementsOperation deleteOp = new DeleteElementsOperation(new IJavaElement[] { element }, fForce);
+ DeleteElementsOperation deleteOp = new DeleteElementsOperation(new IJavaElement[] { element }, force);
executeNestedOperation(deleteOp, 1);
}
}
import net.sourceforge.phpdt.core.jdom.IDOMCompilationUnit;
import net.sourceforge.phpdt.core.jdom.IDOMNode;
import net.sourceforge.phpdt.core.jdom.IDOMPackage;
+import net.sourceforge.phpdt.internal.core.util.Util;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
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);
+ String[] names = net.sourceforge.phpdt.internal.core.util.Util.getTrimmedSimpleNames(newFragName);
StringBuffer sideEffectPackageName = new StringBuffer();
char[][] exclusionsPatterns = ((PackageFragmentRoot)root).fullExclusionPatternChars();
for (int i = 0; i < names.length; i++) {
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);
+ createFolder(parentFolder, subFolderName, force);
}
parentFolder = parentFolder.getFolder(new Path(subFolderName));
sourceFolder = sourceFolder.getFolder(new Path(subFolderName));
}
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)) {
+ && !net.sourceforge.phpdt.internal.core.util.Util.isExcluded(parentFolder, exclusionsPatterns)) {
if (projectDelta == null) {
projectDelta = getDeltaFor(root.getJavaProject());
}
* @see MultiOperation
*/
protected String getMainTaskName() {
- return net.sourceforge.phpdt.internal.core.Util.bind("operation.copyResourceProgress"); //$NON-NLS-1$
+ return net.sourceforge.phpdt.internal.core.util.Util.bind("operation.copyResourceProgress"); //$NON-NLS-1$
}
/**
* Sets the deltas to register the changes resulting from this operation
*
*/
protected void prepareDeltas(IJavaElement sourceElement, IJavaElement destinationElement, boolean isMove) {
- if (net.sourceforge.phpdt.internal.core.Util.isExcluded(sourceElement) || net.sourceforge.phpdt.internal.core.Util.isExcluded(destinationElement)) return;
+ if (net.sourceforge.phpdt.internal.core.util.Util.isExcluded(sourceElement) || net.sourceforge.phpdt.internal.core.util.Util.isExcluded(destinationElement)) return;
IJavaProject destProject = destinationElement.getJavaProject();
if (isMove) {
IJavaProject sourceProject = sourceElement.getJavaProject();
if (!destFile.equals(sourceResource)) {
try {
if (destFile.exists()) {
- if (fForce) {
+ if (force) {
// we can remove it
deleteResource(destFile, IResource.KEEP_HISTORY);
} else {
Util.bind("status.nameCollision", destFile.getFullPath().toString()))); //$NON-NLS-1$
}
}
- int flags = fForce ? IResource.FORCE : IResource.NONE;
+ int flags = force ? IResource.FORCE : IResource.NONE;
if (this.isMove()) {
flags |= IResource.KEEP_HISTORY;
sourceResource.move(destFile.getFullPath(), flags, getSubProgressMonitor(1));
String encoding = source.getJavaProject().getOption(JavaCore.CORE_ENCODING, true);
destFile.setContents(
new ByteArrayInputStream(encoding == null ? newContent.getBytes() : newContent.getBytes(encoding)),
- fForce ? IResource.FORCE | IResource.KEEP_HISTORY : IResource.KEEP_HISTORY,
+ force ? IResource.FORCE | IResource.KEEP_HISTORY : IResource.KEEP_HISTORY,
getSubProgressMonitor(1));
}
} catch(IOException e) {
prepareDeltas(source.getType(oldName), destCU.getType(newName), isMove());
}
} else {
- if (!fForce) {
+ if (!force) {
throw new JavaModelException(new JavaModelStatus(
IJavaModelStatusConstants.NAME_COLLISION,
Util.bind("status.nameCollision", destFile.getFullPath().toString()))); //$NON-NLS-1$
String encoding = source.getJavaProject().getOption(JavaCore.CORE_ENCODING, true);
destFile.setContents(
new ByteArrayInputStream(encoding == null ? newContent.getBytes() : newContent.getBytes(encoding)),
- fForce ? IResource.FORCE | IResource.KEEP_HISTORY : IResource.KEEP_HISTORY,
+ force ? IResource.FORCE | IResource.KEEP_HISTORY : IResource.KEEP_HISTORY,
getSubProgressMonitor(1));
}
} catch(IOException e) {
} catch (JavaModelException jme) {
throw jme;
} finally {
- fResultElements = new IJavaElement[fCreatedElements.size()];
- fCreatedElements.toArray(fResultElements);
+ resultElements = new IJavaElement[fCreatedElements.size()];
+ fCreatedElements.toArray(resultElements);
processDeltas();
}
}
+
/**
* Copies/moves a package fragment with the name <code>newName</code>
* to the destination package.<br>
// Process resources
if (shouldMoveFolder) {
// move underlying resource
- srcFolder.move(destPath, fForce, true /* keep history */, getSubProgressMonitor(1));
+ srcFolder.move(destPath, force, true /* keep history */, getSubProgressMonitor(1));
this.setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
} else {
// process the leaf resources
for (int i = 0, max = resources.length; i < max; i++) {
IResource destinationResource = ResourcesPlugin.getWorkspace().getRoot().findMember(destPath.append(resources[i].getName()));
if (destinationResource != null) {
- if (fForce) {
+ if (force) {
deleteResource(destinationResource, IResource.KEEP_HISTORY);
} else {
throw new JavaModelException(new JavaModelStatus(
for (int i = 0, max = resources.length; i < max; i++) {
IResource destinationResource = ResourcesPlugin.getWorkspace().getRoot().findMember(destPath.append(resources[i].getName()));
if (destinationResource != null) {
- if (fForce) {
+ if (force) {
// we need to delete this resource if this operation wants to override existing resources
deleteResource(destinationResource, IResource.KEEP_HISTORY);
} else {
String domCUContents = domCU.getContents();
String cuContents = null;
if (domCUContents != null) {
- cuContents = net.sourceforge.phpdt.internal.core.Util.normalizeCRs(domCU.getContents(), bufferContents);
+ cuContents = net.sourceforge.phpdt.internal.core.util.Util.normalizeCRs(domCU.getContents(), bufferContents);
} else {
// See PR http://dev.eclipse.org/bugs/show_bug.cgi?id=11285
cuContents = bufferContents;//$NON-NLS-1$
*******************************************************************************/
package net.sourceforge.phpdt.internal.core;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.IWorkspace;
+import org.eclipse.core.runtime.jobs.ISchedulingRule;
+
import net.sourceforge.phpdt.core.IBuffer;
import net.sourceforge.phpdt.core.ICompilationUnit;
import net.sourceforge.phpdt.core.IJavaElement;
import net.sourceforge.phpdt.core.jdom.IDOMCompilationUnit;
import net.sourceforge.phpdt.core.jdom.IDOMNode;
import net.sourceforge.phpdt.internal.core.jdom.DOMNode;
+import net.sourceforge.phpdt.internal.core.util.Util;
/**
* <p>This abstract class implements behavior common to <code>CreateElementInCUOperations</code>.
* Only allow cancelling if this operation is not nested.
*/
protected void checkCanceled() {
- if (!fNested) {
+ if (!isNested) {
super.checkCanceled();
}
}
if (buffer == null) return;
char[] bufferContents = buffer.getCharacters();
if (bufferContents == null) return;
- char[] elementContents = net.sourceforge.phpdt.internal.core.Util.normalizeCRs(fCreatedElement.getCharacters(), bufferContents);
+ char[] elementContents = net.sourceforge.phpdt.internal.core.util.Util.normalizeCRs(fCreatedElement.getCharacters(), bufferContents);
switch (fReplacementLength) {
case -1 :
// element is append at the end
if (!isWorkingCopy)
this.setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
worked(1);
- fResultElements = generateResultHandles();
+ resultElements = 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]);
+ for (int i = 0; i < resultElements.length; i++) {
+ delta.added(resultElements[i]);
}
addDelta(delta);
} // else unit is created outside classpath
* progress reporting.
*/
public abstract String getMainTaskName();
+
+ protected ISchedulingRule getSchedulingRule() {
+ IResource resource = getCompilationUnit().getResource();
+ IWorkspace workspace = resource.getWorkspace();
+ return workspace.getRuleFactory().modifyRule(resource);
+ }
/**
* Returns the elements created by this operation.
*/
public IJavaElement[] getResultElements() {
- return fResultElements;
+ return resultElements;
}
/**
* Sets the default position in which to create the new type
import net.sourceforge.phpdt.core.jdom.IDOMNode;
import net.sourceforge.phpdt.core.jdom.IDOMPackage;
import net.sourceforge.phpdt.internal.core.jdom.DOMNode;
+import net.sourceforge.phpdt.internal.core.util.Util;
import org.eclipse.core.runtime.IStatus;
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2000, 2004 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.WorkingCopyOwner;
+
+/**
+ * A working copy owner that creates internal buffers.
+ * It also defines the PRIMARY working copy owner that is used by JDT/Core.
+ */
+public class DefaultWorkingCopyOwner extends WorkingCopyOwner {
+
+ public WorkingCopyOwner primaryBufferProvider;
+
+ public static final DefaultWorkingCopyOwner PRIMARY = new DefaultWorkingCopyOwner();
+
+ private DefaultWorkingCopyOwner() {
+ // only one instance can be created
+ }
+
+ /**
+ * @deprecated Marked deprecated as it is using deprecated code
+ */
+ public IBuffer createBuffer(ICompilationUnit workingCopy) {
+ if (this.primaryBufferProvider != null) return this.primaryBufferProvider.createBuffer(workingCopy);
+ return super.createBuffer(workingCopy);
+ }
+ public String toString() {
+ return "Primary owner"; //$NON-NLS-1$
+ }
+}
import net.sourceforge.phpdt.core.jdom.DOMFactory;
import net.sourceforge.phpdt.core.jdom.IDOMCompilationUnit;
import net.sourceforge.phpdt.internal.core.jdom.DOMNode;
+import net.sourceforge.phpdt.internal.core.util.Util;
import net.sourceforge.phpdt.internal.corext.Assert;
/**
}
}
if (delta.getAffectedChildren().length > 0) {
- cu.save(getSubProgressMonitor(1), fForce);
+ cu.save(getSubProgressMonitor(1), force);
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);
import net.sourceforge.phpdt.core.IOpenable;
import net.sourceforge.phpdt.core.IPackageFragment;
import net.sourceforge.phpdt.core.JavaModelException;
+import net.sourceforge.phpdt.internal.core.util.Util;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
for (int i = 0; i < childrenOfInterest.length; i++) {
resources[i] = childrenOfInterest[i].getCorrespondingResource();
}
- deleteResources(resources, fForce);
+ deleteResources(resources, force);
}
// Discard non-java resources
switch (element.getElementType()) {
case IJavaElement.CLASS_FILE :
case IJavaElement.COMPILATION_UNIT :
- deleteResource(element.getResource(), fForce ? IResource.FORCE | IResource.KEEP_HISTORY : IResource.KEEP_HISTORY);
+ deleteResource(element.getResource(), force ? IResource.FORCE | IResource.KEEP_HISTORY : IResource.KEEP_HISTORY);
break;
case IJavaElement.PACKAGE_FRAGMENT :
deletePackageFragment((IPackageFragment) element);
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2000, 2004 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.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Hashtable;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+
+import net.sourceforge.phpdt.core.IClasspathEntry;
+import net.sourceforge.phpdt.core.IElementChangedListener;
+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.core.util.Util;
+
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IProjectDescription;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.IResourceChangeEvent;
+import org.eclipse.core.resources.IResourceChangeListener;
+import org.eclipse.core.resources.IResourceDelta;
+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.ISafeRunnable;
+import org.eclipse.core.runtime.Path;
+import org.eclipse.core.runtime.Platform;
+import org.eclipse.core.runtime.QualifiedName;
+import net.sourceforge.phpdt.internal.core.DeltaProcessor;
+import net.sourceforge.phpdt.internal.core.JavaModelManager;
+
+import net.sourceforge.phpdt.core.ElementChangedEvent;
+import net.sourceforge.phpdt.core.IJavaElementDelta;
+import net.sourceforge.phpdt.internal.core.builder.PHPBuilder;
+
+/**
+ * Keep the global states used during Java element delta processing.
+ */
+public class DeltaProcessingState implements IResourceChangeListener {
+
+ /*
+ * Collection of listeners for Java element deltas
+ */
+ public IElementChangedListener[] elementChangedListeners = new IElementChangedListener[5];
+ public int[] elementChangedListenerMasks = new int[5];
+ public int elementChangedListenerCount = 0;
+
+ /*
+ * Collection of pre Java resource change listeners
+ */
+ public IResourceChangeListener[] preResourceChangeListeners = new IResourceChangeListener[1];
+ public int preResourceChangeListenerCount = 0;
+
+ /*
+ * The delta processor for the current thread.
+ */
+ private ThreadLocal deltaProcessors = new ThreadLocal();
+
+ /* A table from IPath (from a classpath entry) to RootInfo */
+ public HashMap roots = new HashMap();
+
+ /* A table from IPath (from a classpath entry) to ArrayList of RootInfo
+ * Used when an IPath corresponds to more than one root */
+ public HashMap otherRoots = new HashMap();
+
+ /* A table from IPath (from a classpath entry) to RootInfo
+ * from the last time the delta processor was invoked. */
+ public HashMap oldRoots = new HashMap();
+
+ /* A table from IPath (from a classpath entry) to ArrayList of RootInfo
+ * from the last time the delta processor was invoked.
+ * Used when an IPath corresponds to more than one root */
+ public HashMap oldOtherRoots = new HashMap();
+
+ /* A table from IPath (a source attachment path from a classpath entry) to IPath (a root path) */
+ public HashMap sourceAttachments = new HashMap();
+
+ /* Whether the roots tables should be recomputed */
+ public boolean rootsAreStale = true;
+
+ /* Threads that are currently running initializeRoots() */
+ private Set initializingThreads = Collections.synchronizedSet(new HashSet());
+
+ public Hashtable externalTimeStamps = new Hashtable();
+
+ public HashMap projectUpdates = new HashMap();
+
+ public static class ProjectUpdateInfo {
+ JavaProject project;
+ IClasspathEntry[] oldResolvedPath;
+ IClasspathEntry[] newResolvedPath;
+ IClasspathEntry[] newRawPath;
+
+ /**
+ * Update projects references so that the build order is consistent with the classpath
+ */
+ public void updateProjectReferencesIfNecessary() throws JavaModelException {
+
+ String[] oldRequired = this.project.projectPrerequisites(this.oldResolvedPath);
+
+ if (this.newResolvedPath == null) {
+ this.newResolvedPath = this.project.getResolvedClasspath(this.newRawPath, null, true, true, null/*no reverse map*/);
+ }
+ String[] newRequired = this.project.projectPrerequisites(this.newResolvedPath);
+ try {
+ IProject projectResource = this.project.getProject();
+ IProjectDescription description = projectResource.getDescription();
+
+ IProject[] projectReferences = description.getDynamicReferences();
+
+ 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 = projectResource.getWorkspace().getRoot();
+ for (int i = 0; i < newSize; i++){
+ requiredProjectArray[i] = wksRoot.getProject(requiredProjectNames[i]);
+ }
+ description.setDynamicReferences(requiredProjectArray);
+ projectResource.setDescription(description, null);
+
+ } catch(CoreException e){
+ throw new JavaModelException(e);
+ }
+ }
+ }
+
+
+ /**
+ * Workaround for bug 15168 circular errors not reported
+ * This is a cache of the projects before any project addition/deletion has started.
+ */
+ public IJavaProject[] modelProjectsCache;
+
+ /*
+ * Need to clone defensively the listener information, in case some listener is reacting to some notification iteration by adding/changing/removing
+ * any of the other (for example, if it deregisters itself).
+ */
+ public void addElementChangedListener(IElementChangedListener listener, int eventMask) {
+ for (int i = 0; i < this.elementChangedListenerCount; i++){
+ if (this.elementChangedListeners[i].equals(listener)){
+
+ // only clone the masks, since we could be in the middle of notifications and one listener decide to change
+ // any event mask of another listeners (yet not notified).
+ int cloneLength = this.elementChangedListenerMasks.length;
+ System.arraycopy(this.elementChangedListenerMasks, 0, this.elementChangedListenerMasks = new int[cloneLength], 0, cloneLength);
+ this.elementChangedListenerMasks[i] = eventMask; // could be different
+ return;
+ }
+ }
+ // may need to grow, no need to clone, since iterators will have cached original arrays and max boundary and we only add to the end.
+ int length;
+ if ((length = this.elementChangedListeners.length) == this.elementChangedListenerCount){
+ System.arraycopy(this.elementChangedListeners, 0, this.elementChangedListeners = new IElementChangedListener[length*2], 0, length);
+ System.arraycopy(this.elementChangedListenerMasks, 0, this.elementChangedListenerMasks = new int[length*2], 0, length);
+ }
+ this.elementChangedListeners[this.elementChangedListenerCount] = listener;
+ this.elementChangedListenerMasks[this.elementChangedListenerCount] = eventMask;
+ this.elementChangedListenerCount++;
+ }
+
+ public void addPreResourceChangedListener(IResourceChangeListener listener) {
+ for (int i = 0; i < this.preResourceChangeListenerCount; i++){
+ if (this.preResourceChangeListeners[i].equals(listener)) {
+ return;
+ }
+ }
+ // may need to grow, no need to clone, since iterators will have cached original arrays and max boundary and we only add to the end.
+ int length;
+ if ((length = this.preResourceChangeListeners.length) == this.preResourceChangeListenerCount){
+ System.arraycopy(this.preResourceChangeListeners, 0, this.preResourceChangeListeners = new IResourceChangeListener[length*2], 0, length);
+ }
+ this.preResourceChangeListeners[this.preResourceChangeListenerCount] = listener;
+ this.preResourceChangeListenerCount++;
+ }
+
+ public DeltaProcessor getDeltaProcessor() {
+ DeltaProcessor deltaProcessor = (DeltaProcessor)this.deltaProcessors.get();
+ if (deltaProcessor != null) return deltaProcessor;
+ deltaProcessor = new DeltaProcessor(this, JavaModelManager.getJavaModelManager());
+ this.deltaProcessors.set(deltaProcessor);
+ return deltaProcessor;
+ }
+
+ public void performClasspathResourceChange(JavaProject project, IClasspathEntry[] oldResolvedPath, IClasspathEntry[] newResolvedPath, IClasspathEntry[] newRawPath, boolean canChangeResources) throws JavaModelException {
+ ProjectUpdateInfo info = new ProjectUpdateInfo();
+ info.project = project;
+ info.oldResolvedPath = oldResolvedPath;
+ info.newResolvedPath = newResolvedPath;
+ info.newRawPath = newRawPath;
+ if (canChangeResources) {
+ this.projectUpdates.remove(project); // remove possibly awaiting one
+ info.updateProjectReferencesIfNecessary();
+ return;
+ }
+ this.recordProjectUpdate(info);
+ }
+
+ public void initializeRoots() {
+
+ // recompute root infos only if necessary
+ HashMap newRoots = null;
+ HashMap newOtherRoots = null;
+ HashMap newSourceAttachments = null;
+ if (this.rootsAreStale) {
+ Thread currentThread = Thread.currentThread();
+ boolean addedCurrentThread = false;
+ try {
+ // if reentering initialization (through a container initializer for example) no need to compute roots again
+ // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=47213
+ if (!this.initializingThreads.add(currentThread)) return;
+ addedCurrentThread = true;
+
+ newRoots = new HashMap();
+ newOtherRoots = new HashMap();
+ newSourceAttachments = new HashMap();
+
+ IJavaModel model = JavaModelManager.getJavaModelManager().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++) {
+ JavaProject project = (JavaProject) projects[i];
+// IClasspathEntry[] classpath;
+// try {
+// classpath = project.getResolvedClasspath(true/*ignoreUnresolvedEntry*/, false/*don't generateMarkerOnError*/, false/*don't returnResolutionInProgress*/);
+// } 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 (newRoots.get(path) == null) {
+// newRoots.put(path, new DeltaProcessor.RootInfo(project, path, ((ClasspathEntry)entry).fullInclusionPatternChars(), ((ClasspathEntry)entry).fullExclusionPatternChars(), entry.getEntryKind()));
+// } else {
+// ArrayList rootList = (ArrayList)newOtherRoots.get(path);
+// if (rootList == null) {
+// rootList = new ArrayList();
+// newOtherRoots.put(path, rootList);
+// }
+// rootList.add(new DeltaProcessor.RootInfo(project, path, ((ClasspathEntry)entry).fullInclusionPatternChars(), ((ClasspathEntry)entry).fullExclusionPatternChars(), entry.getEntryKind()));
+// }
+//
+// // 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;
+// if (propertyString != null) {
+// int index= propertyString.lastIndexOf(PackageFragmentRoot.ATTACHMENT_PROPERTY_DELIMITER);
+// sourceAttachmentPath = (index < 0) ? new Path(propertyString) : new Path(propertyString.substring(0, index));
+// } else {
+// sourceAttachmentPath = entry.getSourceAttachmentPath();
+// }
+// if (sourceAttachmentPath != null) {
+// newSourceAttachments.put(sourceAttachmentPath, path);
+// }
+// }
+ }
+ } finally {
+ if (addedCurrentThread) {
+ this.initializingThreads.remove(currentThread);
+ }
+ }
+ }
+ synchronized(this) {
+ this.oldRoots = this.roots;
+ this.oldOtherRoots = this.otherRoots;
+ if (this.rootsAreStale && newRoots != null) { // double check again
+ this.roots = newRoots;
+ this.otherRoots = newOtherRoots;
+ this.sourceAttachments = newSourceAttachments;
+ this.rootsAreStale = false;
+ }
+ }
+ }
+
+ public synchronized void recordProjectUpdate(ProjectUpdateInfo newInfo) {
+
+ JavaProject project = newInfo.project;
+ ProjectUpdateInfo oldInfo = (ProjectUpdateInfo) this.projectUpdates.get(project);
+ if (oldInfo != null) { // refresh new classpath information
+ oldInfo.newRawPath = newInfo.newRawPath;
+ oldInfo.newResolvedPath = newInfo.newResolvedPath;
+ } else {
+ this.projectUpdates.put(project, newInfo);
+ }
+ }
+ public synchronized ProjectUpdateInfo[] removeAllProjectUpdates() {
+ int length = this.projectUpdates.size();
+ if (length == 0) return null;
+ ProjectUpdateInfo[] updates = new ProjectUpdateInfo[length];
+ this.projectUpdates.values().toArray(updates);
+ this.projectUpdates.clear();
+ return updates;
+ }
+
+ public void removeElementChangedListener(IElementChangedListener listener) {
+
+ for (int i = 0; i < this.elementChangedListenerCount; i++){
+
+ if (this.elementChangedListeners[i].equals(listener)){
+
+ // need to clone defensively since we might be in the middle of listener notifications (#fire)
+ int length = this.elementChangedListeners.length;
+ IElementChangedListener[] newListeners = new IElementChangedListener[length];
+ System.arraycopy(this.elementChangedListeners, 0, newListeners, 0, i);
+ int[] newMasks = new int[length];
+ System.arraycopy(this.elementChangedListenerMasks, 0, newMasks, 0, i);
+
+ // copy trailing listeners
+ int trailingLength = this.elementChangedListenerCount - i - 1;
+ if (trailingLength > 0){
+ System.arraycopy(this.elementChangedListeners, i+1, newListeners, i, trailingLength);
+ System.arraycopy(this.elementChangedListenerMasks, i+1, newMasks, i, trailingLength);
+ }
+
+ // update manager listener state (#fire need to iterate over original listeners through a local variable to hold onto
+ // the original ones)
+ this.elementChangedListeners = newListeners;
+ this.elementChangedListenerMasks = newMasks;
+ this.elementChangedListenerCount--;
+ return;
+ }
+ }
+ }
+
+ public void removePreResourceChangedListener(IResourceChangeListener listener) {
+
+ for (int i = 0; i < this.preResourceChangeListenerCount; i++){
+
+ if (this.preResourceChangeListeners[i].equals(listener)){
+
+ // need to clone defensively since we might be in the middle of listener notifications (#fire)
+ int length = this.preResourceChangeListeners.length;
+ IResourceChangeListener[] newListeners = new IResourceChangeListener[length];
+ System.arraycopy(this.preResourceChangeListeners, 0, newListeners, 0, i);
+
+ // copy trailing listeners
+ int trailingLength = this.preResourceChangeListenerCount - i - 1;
+ if (trailingLength > 0){
+ System.arraycopy(this.preResourceChangeListeners, i+1, newListeners, i, trailingLength);
+ }
+
+ // update manager listener state (#fire need to iterate over original listeners through a local variable to hold onto
+ // the original ones)
+ this.preResourceChangeListeners = newListeners;
+ this.preResourceChangeListenerCount--;
+ return;
+ }
+ }
+ }
+
+ public void resourceChanged(final IResourceChangeEvent event) {
+ boolean isPostChange = event.getType() == IResourceChangeEvent.POST_CHANGE;
+ if (isPostChange) {
+ for (int i = 0; i < this.preResourceChangeListenerCount; i++) {
+ // wrap callbacks with Safe runnable for subsequent listeners to be called when some are causing grief
+ final IResourceChangeListener listener = this.preResourceChangeListeners[i];
+ Platform.run(new ISafeRunnable() {
+ public void handleException(Throwable exception) {
+ Util.log(exception, "Exception occurred in listener of pre Java resource change notification"); //$NON-NLS-1$
+ }
+ public void run() throws Exception {
+ listener.resourceChanged(event);
+ }
+ });
+ }
+ }
+ try {
+ getDeltaProcessor().resourceChanged(event);
+ } finally {
+ // TODO (jerome) see 47631, may want to get rid of following so as to reuse delta processor ?
+ if (isPostChange) {
+ this.deltaProcessors.set(null);
+ }
+ }
+
+ }
+
+ /*
+ * Update the roots that are affected by the addition or the removal of the given container resource.
+ */
+// public synchronized void updateRoots(IPath containerPath, IResourceDelta containerDelta, DeltaProcessor deltaProcessor) {
+// Map updatedRoots;
+// Map otherUpdatedRoots;
+// if (containerDelta.getKind() == IResourceDelta.REMOVED) {
+// updatedRoots = this.oldRoots;
+// otherUpdatedRoots = this.oldOtherRoots;
+// } else {
+// updatedRoots = this.roots;
+// otherUpdatedRoots = this.otherRoots;
+// }
+// Iterator iterator = updatedRoots.keySet().iterator();
+// while (iterator.hasNext()) {
+// IPath path = (IPath)iterator.next();
+// if (containerPath.isPrefixOf(path) && !containerPath.equals(path)) {
+// IResourceDelta rootDelta = containerDelta.findMember(path.removeFirstSegments(1));
+// if (rootDelta == null) continue;
+// DeltaProcessor.RootInfo rootInfo = (DeltaProcessor.RootInfo)updatedRoots.get(path);
+//
+// if (!rootInfo.project.getPath().isPrefixOf(path)) { // only consider roots that are not included in the container
+// deltaProcessor.updateCurrentDeltaAndIndex(rootDelta, IJavaElement.PACKAGE_FRAGMENT_ROOT, rootInfo);
+// }
+//
+// ArrayList rootList = (ArrayList)otherUpdatedRoots.get(path);
+// if (rootList != null) {
+// Iterator otherProjects = rootList.iterator();
+// while (otherProjects.hasNext()) {
+// rootInfo = (DeltaProcessor.RootInfo)otherProjects.next();
+// if (!rootInfo.project.getPath().isPrefixOf(path)) { // only consider roots that are not included in the container
+// deltaProcessor.updateCurrentDeltaAndIndex(rootDelta, IJavaElement.PACKAGE_FRAGMENT_ROOT, rootInfo);
+// }
+// }
+// }
+// }
+// }
+// }
+
+}
import java.io.File;
import java.util.ArrayList;
+import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
+import java.util.Iterator;
import java.util.Map;
import net.sourceforge.phpdt.core.ElementChangedEvent;
import net.sourceforge.phpdt.core.IClasspathEntry;
+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.JavaModelException;
import net.sourceforge.phpdt.core.JavaCore;
+import net.sourceforge.phpdt.core.JavaModelException;
import net.sourceforge.phpdt.internal.ui.util.PHPFileUtil;
import net.sourceforge.phpeclipse.PHPeclipsePlugin;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
+import org.eclipse.core.runtime.ISafeRunnable;
+import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.QualifiedName;
+import net.sourceforge.phpdt.internal.core.builder.PHPBuilder;
+
+import net.sourceforge.phpdt.internal.core.DeltaProcessingState;
+import net.sourceforge.phpdt.internal.core.JavaElementDelta;
+import net.sourceforge.phpdt.internal.core.JavaModelManager;
+import net.sourceforge.phpdt.internal.core.util.Util;
/**
final static String EXTERNAL_JAR_UNCHANGED = "external jar unchanged"; //$NON-NLS-1$
final static String INTERNAL_JAR_IGNORE = "internal jar ignore"; //$NON-NLS-1$
- final static int NON_JAVA_RESOURCE = -1;
+ private final static int NON_JAVA_RESOURCE = -1;
+ public static boolean DEBUG = false;
+ public static boolean VERBOSE = false;
+ public static final int DEFAULT_CHANGE_EVENT = 0; // must not collide with ElementChangedEvent event masks
/**
* The <code>JavaElementDelta</code> corresponding to the <code>IResourceDelta</code> being translated.
*/
* This is used as a stack of java elements (using getParent() to pop it, and
* using the various get*(...) to push it. */
Openable currentElement;
-
+ /*
+ * Queue of deltas created explicily by the Java Model that
+ * have yet to be fired.
+ */
+ public ArrayList javaModelDeltas= new ArrayList();
+ /*
+ * Queue of reconcile deltas on working copies that have yet to be fired.
+ * This is a table form IWorkingCopy to IJavaElementDelta
+ */
+ public HashMap reconcileDeltas = new HashMap();
+
+ /*
+ * Turns delta firing on/off. By default it is on.
+ */
+ private boolean isFiring= true;
+
+
public HashMap externalTimeStamps = new HashMap();
public HashSet projectsToUpdate = new HashSet();
// list of root projects which namelookup caches need to be updated for dependents
// TODO: (jerome) is it needed? projectsToUpdate might be sufficient
public HashSet projectsForDependentNamelookupRefresh = new HashSet();
- JavaModelManager manager;
+ /*
+ * The global state of delta processing.
+ */
+ private DeltaProcessingState state;
+
+ /*
+ * The Java model manager
+ */
+ private JavaModelManager manager;
/* A table from IJavaProject to an array of IPackageFragmentRoot.
* This table contains the pkg fragment roots of the project that are being deleted.
* This is null if no refresh is needed.
*/
HashSet refreshedElements;
- public static boolean VERBOSE = false;
class OutputsInfo {
IPath[] paths;
}
}
- DeltaProcessor(JavaModelManager manager) {
+// DeltaProcessor(JavaModelManager manager) {
+// this.manager = manager;
+// }
+
+ /*
+ * Type of event that should be processed no matter what the real event type is.
+ */
+ public int overridenEventType = -1;
+
+ public DeltaProcessor(DeltaProcessingState state, JavaModelManager manager) {
+ this.state = state;
this.manager = manager;
}
-
/*
* Adds the dependents of the given project to the list of the projects
* to update.
}
return false;
}
-
+ /*
+ * Merges all awaiting deltas.
+ */
+ private IJavaElementDelta mergeDeltas(Collection deltas) {
+ if (deltas.size() == 0) return null;
+ if (deltas.size() == 1) return (IJavaElementDelta)deltas.iterator().next();
+
+ if (VERBOSE) {
+ System.out.println("MERGING " + deltas.size() + " DELTAS ["+Thread.currentThread()+"]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ Iterator iterator = deltas.iterator();
+ JavaElementDelta rootDelta = new JavaElementDelta(this.manager.javaModel);
+ boolean insertedTree = false;
+ while (iterator.hasNext()) {
+ JavaElementDelta delta = (JavaElementDelta)iterator.next();
+ if (VERBOSE) {
+ System.out.println(delta.toString());
+ }
+ IJavaElement element = delta.getElement();
+ if (this.manager.javaModel.equals(element)) {
+ IJavaElementDelta[] children = delta.getAffectedChildren();
+ for (int j = 0; j < children.length; j++) {
+ JavaElementDelta projectDelta = (JavaElementDelta) children[j];
+ rootDelta.insertDeltaTree(projectDelta.getElement(), projectDelta);
+ insertedTree = true;
+ }
+ IResourceDelta[] resourceDeltas = delta.getResourceDeltas();
+ if (resourceDeltas != null) {
+ for (int i = 0, length = resourceDeltas.length; i < length; i++) {
+ rootDelta.addResourceDelta(resourceDeltas[i]);
+ insertedTree = true;
+ }
+ }
+ } else {
+ rootDelta.insertDeltaTree(element, delta);
+ insertedTree = true;
+ }
+ }
+ if (insertedTree) return rootDelta;
+ return null;
+ }
+ private void notifyListeners(IJavaElementDelta deltaToNotify, int eventType, IElementChangedListener[] listeners, int[] listenerMask, int listenerCount) {
+ final ElementChangedEvent extraEvent = new ElementChangedEvent(deltaToNotify, eventType);
+ for (int i= 0; i < listenerCount; i++) {
+ if ((listenerMask[i] & eventType) != 0){
+ final IElementChangedListener listener = listeners[i];
+ long start = -1;
+ if (VERBOSE) {
+ System.out.print("Listener #" + (i+1) + "=" + listener.toString());//$NON-NLS-1$//$NON-NLS-2$
+ start = System.currentTimeMillis();
+ }
+ // wrap callbacks with Safe runnable for subsequent listeners to be called when some are causing grief
+ Platform.run(new ISafeRunnable() {
+ public void handleException(Throwable exception) {
+ Util.log(exception, "Exception occurred in listener of Java element change notification"); //$NON-NLS-1$
+ }
+ public void run() throws Exception {
+ listener.elementChanged(extraEvent);
+ }
+ });
+ if (VERBOSE) {
+ System.out.println(" -> " + (System.currentTimeMillis()-start) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ }
+ }
+ }
/**
* Generic processing for elements with changed contents:<ul>
* <li>The element is closed such that any subsequent accesses will re-open
// //fCurrentDelta.changed(project, IJavaElementDelta.F_OPTIONS_CHANGED);
// }
// }
-
+ /*
+ * Registers the given delta with this delta processor.
+ */
+ public void registerJavaModelDelta(IJavaElementDelta delta) {
+ this.javaModelDeltas.add(delta);
+ }
/**
* Removes the given element from its parents cache of children. If the
* element does not have a parent, or the parent is not currently open,
}
}
}
+
/**
* Notification that some resource changes have happened
* on the platform, and that the Java Model should update any required
* @see IResource
*/
public void resourceChanged(IResourceChangeEvent event) {
-
+ // jsurfer TODO compare 3.0 sources
if (event.getSource() instanceof IWorkspace) {
+ int eventType = this.overridenEventType == -1 ? event.getType() : this.overridenEventType;
IResource resource = event.getResource();
IResourceDelta delta = event.getDelta();
- switch(event.getType()){
+ switch(eventType){
case IResourceChangeEvent.PRE_DELETE :
try {
if(resource.getType() == IResource.PROJECT
&& ((IProject) resource).hasNature(PHPeclipsePlugin.PHP_NATURE_ID)) {
- // TODO khartlage temp-del
+ // TODO jsurfer temp-del
// this.deleting((IProject)resource);
}
} catch(CoreException e){
return;
case IResourceChangeEvent.PRE_AUTO_BUILD :
-// TODO khartlage temp-del
+// TODO jsurfer temp-del
// if(isAffectedBy(delta)) { // avoid populating for SYNC or MARKER deltas
// this.checkProjectsBeingAddedOrRemoved(delta);
//
break;
case IResourceChangeEvent.POST_AUTO_BUILD :
-// TODO khartlage temp-del
+// TODO jsurfer temp-del
// JavaBuilder.finishedBuilding(event);
break;
case IResourceChangeEvent.POST_CHANGE :
-// TODO khartlage temp-del
+// TODO jsurfer temp-del
// if (isAffectedBy(delta)) {
// try {
// if (this.refreshedElements != null) {
}
}
/*
+ * Flushes all deltas without firing them.
+ */
+ public void flush() {
+ this.javaModelDeltas = new ArrayList();
+ }
+ /*
* Finds the root info this path is included in.
* Returns null if not found.
*/
return null;
}
/*
+ * Fire Java Model delta, flushing them after the fact after post_change notification.
+ * If the firing mode has been turned off, this has no effect.
+ */
+ public void fire(IJavaElementDelta customDelta, int eventType) {
+ if (!this.isFiring) return;
+
+ if (DEBUG) {
+ System.out.println("-----------------------------------------------------------------------------------------------------------------------");//$NON-NLS-1$
+ }
+
+ IJavaElementDelta deltaToNotify;
+ if (customDelta == null){
+ deltaToNotify = this.mergeDeltas(this.javaModelDeltas);
+ } else {
+ deltaToNotify = customDelta;
+ }
+
+ // Refresh internal scopes
+// if (deltaToNotify != null) {
+// Iterator scopes = this.manager.searchScopes.keySet().iterator();
+// while (scopes.hasNext()) {
+// AbstractSearchScope scope = (AbstractSearchScope)scopes.next();
+// scope.processDelta(deltaToNotify);
+// }
+// }
+
+ // Notification
+
+ // Important: if any listener reacts to notification by updating the listeners list or mask, these lists will
+ // be duplicated, so it is necessary to remember original lists in a variable (since field values may change under us)
+ IElementChangedListener[] listeners = this.state.elementChangedListeners;
+ int[] listenerMask = this.state.elementChangedListenerMasks;
+ int listenerCount = this.state.elementChangedListenerCount;
+
+ switch (eventType) {
+ case DEFAULT_CHANGE_EVENT:
+ firePostChangeDelta(deltaToNotify, listeners, listenerMask, listenerCount);
+ fireReconcileDelta(listeners, listenerMask, listenerCount);
+ break;
+ case ElementChangedEvent.POST_CHANGE:
+ firePostChangeDelta(deltaToNotify, listeners, listenerMask, listenerCount);
+ fireReconcileDelta(listeners, listenerMask, listenerCount);
+ break;
+ }
+ }
+
+ private void firePostChangeDelta(
+ IJavaElementDelta deltaToNotify,
+ IElementChangedListener[] listeners,
+ int[] listenerMask,
+ int listenerCount) {
+
+ // post change deltas
+ if (DEBUG){
+ System.out.println("FIRING POST_CHANGE Delta ["+Thread.currentThread()+"]:"); //$NON-NLS-1$//$NON-NLS-2$
+ System.out.println(deltaToNotify == null ? "<NONE>" : deltaToNotify.toString()); //$NON-NLS-1$
+ }
+ if (deltaToNotify != null) {
+ // flush now so as to keep listener reactions to post their own deltas for subsequent iteration
+ this.flush();
+
+ notifyListeners(deltaToNotify, ElementChangedEvent.POST_CHANGE, listeners, listenerMask, listenerCount);
+ }
+ }
+ private void fireReconcileDelta(
+ IElementChangedListener[] listeners,
+ int[] listenerMask,
+ int listenerCount) {
+
+
+ IJavaElementDelta deltaToNotify = mergeDeltas(this.reconcileDeltas.values());
+ if (DEBUG){
+ System.out.println("FIRING POST_RECONCILE Delta ["+Thread.currentThread()+"]:"); //$NON-NLS-1$//$NON-NLS-2$
+ System.out.println(deltaToNotify == null ? "<NONE>" : deltaToNotify.toString()); //$NON-NLS-1$
+ }
+ if (deltaToNotify != null) {
+ // flush now so as to keep listener reactions to post their own deltas for subsequent iteration
+ this.reconcileDeltas = new HashMap();
+
+ notifyListeners(deltaToNotify, ElementChangedEvent.POST_RECONCILE, listeners, listenerMask, listenerCount);
+ }
+ }
+ /*
* Returns the root info for the given path. Look in the old roots table if kind is REMOVED.
*/
RootInfo rootInfo(IPath path, int kind) {
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2000, 2004 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.IJavaElementDelta;
+import net.sourceforge.phpdt.core.JavaModelException;
+
+/**
+ * Discards a working copy (decrement its use count and remove its working copy info if the use count is 0)
+ * and signal its removal through a delta.
+ */
+public class DiscardWorkingCopyOperation extends JavaModelOperation {
+
+ public DiscardWorkingCopyOperation(IJavaElement workingCopy) {
+ super(new IJavaElement[] {workingCopy});
+ }
+ protected void executeOperation() throws JavaModelException {
+ CompilationUnit workingCopy = getWorkingCopy();
+
+ int useCount = JavaModelManager.getJavaModelManager().discardPerWorkingCopyInfo(workingCopy);
+ if (useCount == 0) {
+ if (!workingCopy.isPrimary()) {
+ // report removed java delta for a non-primary working copy
+ JavaElementDelta delta = new JavaElementDelta(this.getJavaModel());
+ delta.removed(workingCopy);
+ addDelta(delta);
+ removeReconcileDelta(workingCopy);
+ } else {
+ if (workingCopy.getResource().isAccessible()) {
+ // report a F_PRIMARY_WORKING_COPY change delta for a primary working copy
+ JavaElementDelta delta = new JavaElementDelta(this.getJavaModel());
+ delta.changed(workingCopy, IJavaElementDelta.F_PRIMARY_WORKING_COPY);
+ addDelta(delta);
+ } else {
+ // report a REMOVED delta
+ JavaElementDelta delta = new JavaElementDelta(this.getJavaModel());
+ delta.removed(workingCopy, IJavaElementDelta.F_PRIMARY_WORKING_COPY);
+ addDelta(delta);
+ }
+ }
+ }
+ }
+ /**
+ * Returns the working copy this operation is working on.
+ */
+ protected CompilationUnit getWorkingCopy() {
+ return (CompilationUnit)getElementToProcess();
+ }
+ /**
+ * @see JavaModelOperation#isReadOnly
+ */
+ public boolean isReadOnly() {
+ return true;
+ }
+}
package net.sourceforge.phpdt.internal.core;
import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
import net.sourceforge.phpdt.core.ICompilationUnit;
import net.sourceforge.phpdt.core.IJavaElement;
import net.sourceforge.phpdt.core.IJavaModel;
import net.sourceforge.phpdt.core.IJavaModelStatusConstants;
import net.sourceforge.phpdt.core.IJavaProject;
+import net.sourceforge.phpdt.core.IMember;
import net.sourceforge.phpdt.core.IOpenable;
import net.sourceforge.phpdt.core.IParent;
import net.sourceforge.phpdt.core.ISourceRange;
import net.sourceforge.phpdt.core.jdom.IDOMNode;
import net.sourceforge.phpdt.internal.corext.Assert;
+import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceStatus;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IAdaptable;
+import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.PlatformObject;
+import org.eclipse.core.runtime.jobs.ISchedulingRule;
+import net.sourceforge.phpdt.internal.core.JavaElementInfo;
+
+import net.sourceforge.phpdt.internal.core.JavaModelManager;
+import net.sourceforge.phpdt.internal.core.util.Util;
/**
* Root of Java element handle hierarchy.
* them. The occurrence count starts at 1 (thus the first
* occurrence is occurrence 1, not occurrence 0).
*/
- protected int fOccurrenceCount = 1;
+ protected int occurrenceCount = 1;
/**
* This element's type - one of the constants defined
* in IJavaLanguageElementTypes.
*/
- protected int fLEType = 0;
+ //protected int fLEType = 0;
/**
* This element's parent, or <code>null</code> if this
* element does not have a parent.
*/
- protected IJavaElement fParent;
+ protected IJavaElement parent;
/**
* This element's name, or an empty <code>String</code> if this
* element does not have a name.
*/
- protected String fName;
+ protected String name;
protected static final Object NO_INFO = new Object();
/**
- * Constructs a handle for a java element of the specified type, with
+ * Constructs a handle for a java element with
* the given parent element and name.
*
- * @param type - one of the constants defined in IJavaLanguageElement
+ * @param parent The parent of java element
+ * @param name The name of java element
*
* @exception IllegalArgumentException if the type is not one of the valid
* Java element type constants
*
*/
- protected JavaElement(int type, IJavaElement parent, String name) throws IllegalArgumentException {
- if (type < JAVA_MODEL || type > IMPORT_DECLARATION) {
- throw new IllegalArgumentException(Util.bind("element.invalidType")); //$NON-NLS-1$
- }
- fLEType= type;
- fParent= parent;
- fName= name;
+ protected JavaElement(JavaElement parent, String name) throws IllegalArgumentException {
+ this.parent = parent;
+ this.name = name;
}
/**
* @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;
- }
- }
+ JavaModelManager.getJavaModelManager().removeInfoAndChildren(this);
}
/**
* This element is being closed. Do any necessary cleanup.
*/
- protected void closing(Object info) throws JavaModelException {
- }
+ protected abstract void closing(Object info) throws JavaModelException;
+ /*
+ * Returns a new element info for this element.
+ */
+ protected abstract Object createElementInfo();
/**
* Returns true if this handle represents the same Java element
* as the given handle. By default, two handles represent the same
if (this == o) return true;
// Java model parent is null
- if (fParent == null) return super.equals(o);
+ if (this.parent == null) return super.equals(o);
- if (o instanceof JavaElement) {
- JavaElement other = (JavaElement) o;
- if (fLEType != other.fLEType) return false;
-
- return fName.equals(other.fName) &&
- fParent.equals(other.fParent) &&
- fOccurrenceCount == other.fOccurrenceCount;
- }
- return false;
+ // assume instanceof check is done in subclass
+ JavaElement other = (JavaElement) o;
+ return this.occurrenceCount == other.occurrenceCount &&
+ this.name.equals(other.name) &&
+ this.parent.equals(other.parent);
}
/**
* Returns true if this <code>JavaElement</code> is equivalent to the given
return null;
}
/**
+ * Generates the element infos for this element, its ancestors (if they are not opened) and its children (if it is an Openable).
+ * Puts the newly created element info in the given map.
+ */
+ protected abstract void generateInfos(Object info, HashMap newElements, IProgressMonitor pm) throws JavaModelException;
+
+ /**
* @see IParent
*/
public IJavaElement[] getChildren() throws JavaModelException {
* Returns the info for this handle.
* If this element is not already open, it and all of its parents are opened.
* Does not return null.
- * NOTE: BinaryType infos are NJOT rooted under JavaElementInfo.
+ * NOTE: BinaryType infos are NOT rooted under JavaElementInfo.
* @exception JavaModelException if the element is not present or not accessible
*/
public Object getElementInfo() throws JavaModelException {
- // 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;
- }
+ return getElementInfo(null);
}
/**
- * @see IAdaptable
+ * Returns the info for this handle.
+ * If this element is not already open, it and all of its parents are opened.
+ * Does not return null.
+ * NOTE: BinaryType infos are NOT rooted under JavaElementInfo.
+ * @exception JavaModelException if the element is not present or not accessible
*/
- public String getElementName() {
- return fName;
+ public Object getElementInfo(IProgressMonitor monitor) throws JavaModelException {
+
+ JavaModelManager manager = JavaModelManager.getJavaModelManager();
+ Object info = manager.getInfo(this);
+ if (info != null) return info;
+ return openWhenClosed(createElementInfo(), monitor);
}
/**
- * @see IJavaElement
+ * @see IAdaptable
*/
- public int getElementType() {
- return fLEType;
+ public String getElementName() {
+ return name;
}
+
/**
* @see IJavaElement
*/
* Returns the occurrence count of the handle.
*/
protected int getOccurrenceCount() {
- return fOccurrenceCount;
+ return occurrenceCount;
}
/*
* @see IJavaElement
*/
public IOpenable getOpenableParent() {
- return (IOpenable)fParent;
+ return (IOpenable)parent;
}
/**
* @see IJavaElement
*/
public IJavaElement getParent() {
- return fParent;
+ return parent;
}
+ /*
+ * @see IJavaElement#getPrimaryElement()
+ */
+ public IJavaElement getPrimaryElement() {
+ return getPrimaryElement(true);
+ }
+ /*
+ * Returns the primary element. If checkOwner, and the cu owner is primary,
+ * return this element.
+ */
+ public IJavaElement getPrimaryElement(boolean checkOwner) {
+ return this;
+ }
/**
* Returns the element that is located at the given source position
* in this element. This is a helper method for <code>ICompilationUnit#getElementAt</code>,
// public SourceMapper getSourceMapper() {
// return ((JavaElement)getParent()).getSourceMapper();
// }
+ /* (non-Javadoc)
+ * @see org.eclipse.jdt.core.IJavaElement#getSchedulingRule()
+ */
+ public ISchedulingRule getSchedulingRule() {
+ IResource resource = getResource();
+ if (resource == null) {
+ class NoResourceSchedulingRule implements ISchedulingRule {
+ public IPath path;
+ public NoResourceSchedulingRule(IPath path) {
+ this.path = path;
+ }
+ public boolean contains(ISchedulingRule rule) {
+ if (rule instanceof NoResourceSchedulingRule) {
+ return this.path.isPrefixOf(((NoResourceSchedulingRule)rule).path);
+ } else {
+ return false;
+ }
+ }
+ public boolean isConflicting(ISchedulingRule rule) {
+ if (rule instanceof NoResourceSchedulingRule) {
+ IPath otherPath = ((NoResourceSchedulingRule)rule).path;
+ return this.path.isPrefixOf(otherPath) || otherPath.isPrefixOf(this.path);
+ } else {
+ return false;
+ }
+ }
+ }
+ return new NoResourceSchedulingRule(getPath());
+ } else {
+ return resource;
+ }
+ }
+ /**
+ * @see IParent
+ */
+ public boolean hasChildren() throws JavaModelException {
+ // if I am not open, return true to avoid opening (case of a Java project, a compilation unit or a class file).
+ // also see https://bugs.eclipse.org/bugs/show_bug.cgi?id=52474
+ Object elementInfo = JavaModelManager.getJavaModelManager().getInfo(this);
+ if (elementInfo instanceof JavaElementInfo) {
+ return ((JavaElementInfo)elementInfo).getChildren().length > 0;
+ } else {
+ return true;
+ }
+ }
/**
* Returns the hash code for this Java element. By default,
* override this method.
*/
public int hashCode() {
- if (fParent == null) return super.hashCode();
- return Util.combineHashCodes(fName.hashCode(), fParent.hashCode());
+ if (this.parent == null) return super.hashCode();
+ return Util.combineHashCodes(this.name.hashCode(), this.parent.hashCode());
}
+
/**
* Returns true if this element is an ancestor of the given element,
* otherwise false.
*
* @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();
- }
- }
- }
- }
+// 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.
*/
protected void opening(Object info) {
}
+ /*
+ * Opens an <code>Openable</code> that is known to be closed (no check for <code>isOpen()</code>).
+ * Returns the created element info.
+ */
+ protected Object openWhenClosed(Object info, IProgressMonitor monitor) throws JavaModelException {
+ JavaModelManager manager = JavaModelManager.getJavaModelManager();
+ boolean hadTemporaryCache = manager.hasTemporaryCache();
+ try {
+ HashMap newElements = manager.getTemporaryCache();
+ generateInfos(info, newElements, monitor);
+ if (info == null) {
+ info = newElements.get(this);
+ }
+ if (info == null) { // a source ref element could not be opened
+ // close any buffer that was opened for the openable parent
+ Iterator iterator = newElements.keySet().iterator();
+ while (iterator.hasNext()) {
+ IJavaElement element = (IJavaElement)iterator.next();
+ if (element instanceof Openable) {
+ ((Openable)element).closeBuffer();
+ }
+ }
+ throw newNotPresentException();
+ }
+ if (!hadTemporaryCache) {
+ manager.putInfos(this, newElements);
+ }
+ } finally {
+ if (!hadTemporaryCache) {
+ manager.resetTemporaryCache();
+ }
+ }
+ return info;
+ }
/**
*/
public String readableName() {
* 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.
- */
- public abstract IJavaElement rootedAt(IJavaProject 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
*/
* Sets the occurrence count of the handle.
*/
protected void setOccurrenceCount(int count) {
- fOccurrenceCount = count;
+ occurrenceCount = count;
}
protected String tabString(int tab) {
StringBuffer buffer = new StringBuffer();
import net.sourceforge.phpdt.core.IJavaProject;
import org.eclipse.core.resources.IResourceDelta;
+import net.sourceforge.phpdt.internal.core.SimpleDelta;
/**
* @see IJavaElementDelta
*/
-public class JavaElementDelta implements IJavaElementDelta {
+public class JavaElementDelta extends SimpleDelta implements IJavaElementDelta {
/**
* The element that this delta describes the change to.
* @see #getElement()
}
}
}
+///**
+// * Creates the nested deltas resulting from an add operation.
+// * Convenience method for creating add deltas.
+// * The constructor should be used to create the root delta
+// * and then an add operation should call this method.
+// */
+//public void added(IJavaElement element) {
+// JavaElementDelta addedDelta = new JavaElementDelta(element);
+// addedDelta.fKind = ADDED;
+// insertDeltaTree(element, addedDelta);
+//}
/**
* Creates the nested deltas resulting from an add operation.
* Convenience method for creating add deltas.
* and then an add operation should call this method.
*/
public void added(IJavaElement element) {
+ added(element, 0);
+}
+public void added(IJavaElement element, int flags) {
JavaElementDelta addedDelta = new JavaElementDelta(element);
- addedDelta.fKind = ADDED;
+ addedDelta.added();
+ addedDelta.changeFlags |= flags;
insertDeltaTree(element, addedDelta);
}
/**
public void contentChanged() {
fChangeFlags |= F_CONTENT;
}
-/**
- * Clone this delta so that its elements are rooted at the given project.
- */
-public IJavaElementDelta clone(IJavaProject project) {
- JavaElementDelta clone =
- new JavaElementDelta(((JavaElement)fChangedElement).rootedAt(project));
- if (fAffectedChildren != fgEmptyDelta) {
- int length = fAffectedChildren.length;
- IJavaElementDelta[] cloneChildren = new IJavaElementDelta[length];
- for (int i= 0; i < length; i++) {
- cloneChildren[i] = ((JavaElementDelta)fAffectedChildren[i]).clone(project);
- }
- clone.fAffectedChildren = cloneChildren;
- }
- clone.fChangeFlags = fChangeFlags;
- clone.fKind = fKind;
- if (fMovedFromHandle != null) {
- clone.fMovedFromHandle = ((JavaElement)fMovedFromHandle).rootedAt(project);
- }
- if (fMovedToHandle != null) {
- clone.fMovedToHandle = ((JavaElement)fMovedToHandle).rootedAt(project);
- }
- clone.resourceDeltas = this.resourceDeltas;
- clone.resourceDeltasCounter = this.resourceDeltasCounter;
- return clone;
-}
+///**
+// * Clone this delta so that its elements are rooted at the given project.
+// */
+//public IJavaElementDelta clone(IJavaProject project) {
+// JavaElementDelta clone =
+// new JavaElementDelta(((JavaElement)fChangedElement).rootedAt(project));
+// if (fAffectedChildren != fgEmptyDelta) {
+// int length = fAffectedChildren.length;
+// IJavaElementDelta[] cloneChildren = new IJavaElementDelta[length];
+// for (int i= 0; i < length; i++) {
+// cloneChildren[i] = ((JavaElementDelta)fAffectedChildren[i]).clone(project);
+// }
+// clone.fAffectedChildren = cloneChildren;
+// }
+// clone.fChangeFlags = fChangeFlags;
+// clone.fKind = fKind;
+// if (fMovedFromHandle != null) {
+// clone.fMovedFromHandle = ((JavaElement)fMovedFromHandle).rootedAt(project);
+// }
+// if (fMovedToHandle != null) {
+// clone.fMovedToHandle = ((JavaElement)fMovedToHandle).rootedAt(project);
+// }
+// clone.resourceDeltas = this.resourceDeltas;
+// clone.resourceDeltasCounter = this.resourceDeltasCounter;
+// return clone;
+//}
/**
* Creates the nested deltas for a closed element.
* and then the delete operation should call this method.
*/
public void removed(IJavaElement element) {
+ removed(element, 0);
+}
+public void removed(IJavaElement element, int flags) {
JavaElementDelta removedDelta= new JavaElementDelta(element);
insertDeltaTree(element, removedDelta);
JavaElementDelta actualDelta = getDeltaFor(element);
if (actualDelta != null) {
- actualDelta.fKind = REMOVED;
- actualDelta.fChangeFlags = 0;
+ actualDelta.removed();
+ actualDelta.changeFlags |= flags;
actualDelta.fAffectedChildren = fgEmptyDelta;
}
}
+
/**
* Creates the nested deltas resulting from a change operation.
* Convenience method for creating change deltas.
import net.sourceforge.phpdt.core.IJavaModel;
import net.sourceforge.phpdt.core.IJavaProject;
import net.sourceforge.phpdt.core.JavaModelException;
+import net.sourceforge.phpdt.internal.core.util.Util;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Path;
+import net.sourceforge.phpdt.internal.core.JavaModelInfo;
+import net.sourceforge.phpdt.internal.core.JavaProject;
+import net.sourceforge.phpdt.internal.core.OpenableElementInfo;
import org.eclipse.jface.util.Assert;
* @exception Error if called more than once
*/
protected JavaModel() throws Error {
- super(JAVA_MODEL, null, "" /*workspace has empty name*/); //$NON-NLS-1$
+ super(null, "" /*workspace has empty name*/); //$NON-NLS-1$
+}
+protected boolean buildStructure(OpenableElementInfo info, IProgressMonitor pm, Map newElements, IResource underlyingResource) /*throws JavaModelException*/ {
+
+ // 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));
+ }
+ }
+
+ newElements.put(this, info);
+
+ return true;
}
/*
* @see IJavaModel
/**
* Returns a new element info for this element.
*/
-protected OpenableElementInfo createElementInfo() {
+protected Object createElementInfo() {
return new JavaModelInfo();
}
}
return null;
}
-
+/**
+ * @see IJavaElement
+ */
+public int getElementType() {
+ return JAVA_MODEL;
+}
/**
* Flushes the cache of external files known to be existing.
*/
// }
// return type;
//}
+
+
/**
* @see JavaElement#getHandleMemento()
*/
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
+import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import net.sourceforge.phpdt.internal.ui.util.PHPFileUtil;
import net.sourceforge.phpeclipse.PHPeclipsePlugin;
import net.sourceforge.phpdt.internal.core.builder.PHPBuilder;
+import net.sourceforge.phpdt.internal.core.util.Util;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.runtime.Plugin;
import org.eclipse.core.runtime.Preferences;
import org.eclipse.core.runtime.Status;
+import net.sourceforge.phpdt.internal.core.BufferManager;
+
+import net.sourceforge.phpdt.internal.core.DefaultWorkingCopyOwner;
+
+import net.sourceforge.phpdt.internal.core.DeltaProcessingState;
+
+import net.sourceforge.phpdt.internal.core.DeltaProcessor;
+
+import net.sourceforge.phpdt.core.IParent;
+import net.sourceforge.phpdt.internal.core.JavaElementInfo;
+
+import net.sourceforge.phpdt.core.IProblemRequestor;
+import net.sourceforge.phpdt.core.WorkingCopyOwner;
+import net.sourceforge.phpdt.core.compiler.IProblem;
+import net.sourceforge.phpdt.internal.core.CompilationUnit;
+import net.sourceforge.phpdt.internal.core.JavaElement;
+import net.sourceforge.phpdt.internal.core.JavaElementDeltaBuilder;
+import net.sourceforge.phpdt.internal.core.JavaModelManager.PerWorkingCopyInfo;
/**
* The <code>JavaModelManager</code> manages instances of <code>IJavaModel</code>.
public final static IWorkingCopy[] NoWorkingCopy = new IWorkingCopy[0];
/**
+ * Table from WorkingCopyOwner to a table of ICompilationUnit (working copy handle) to PerWorkingCopyInfo.
+ * NOTE: this object itself is used as a lock to synchronize creation/removal of per working copy infos
+ */
+ protected Map perWorkingCopyInfos = new HashMap(5);
+ /**
* Returns whether the given full path (for a package) conflicts with the output location
* of the given project.
*/
IPath resourcePath = resource.getFullPath();
try {
IClasspathEntry[] entries =
- Util.isJavaFileName(resourcePath.lastSegment())
+ net.sourceforge.phpdt.internal.compiler.util.Util.isJavaFileName(resourcePath.lastSegment())
? project.getRawClasspath() // JAVA file can only live inside SRC folder (on the raw path)
: ((JavaProject)project).getResolvedClasspath(true);
*/
protected JavaModelCache cache = new JavaModelCache();
+ /*
+ * Temporary cache of newly opened elements
+ */
+ private ThreadLocal temporaryCache = new ThreadLocal();
/**
* Set of elements which are out of sync with their buffers.
*/
protected Map elementsOutOfSynchWithBuffers = new HashMap(11);
-
+ /**
+ * Holds the state used for delta processing.
+ */
+ public DeltaProcessingState deltaState = new DeltaProcessingState();
/**
* Turns delta firing on/off. By default it is on.
*/
/**
* Used to convert <code>IResourceDelta</code>s into <code>IJavaElementDelta</code>s.
*/
- public final DeltaProcessor deltaProcessor = new DeltaProcessor(this);
+// public final DeltaProcessor deltaProcessor = new DeltaProcessor(this);
/**
* Used to update the JavaModel for <code>IJavaElementDelta</code>s.
*/
this.project = project;
}
}
+ public static class PerWorkingCopyInfo implements IProblemRequestor {
+ int useCount = 0;
+ IProblemRequestor problemRequestor;
+ ICompilationUnit workingCopy;
+ public PerWorkingCopyInfo(ICompilationUnit workingCopy, IProblemRequestor problemRequestor) {
+ this.workingCopy = workingCopy;
+ this.problemRequestor = problemRequestor;
+ }
+ public void acceptProblem(IProblem problem) {
+ if (this.problemRequestor == null) return;
+ this.problemRequestor.acceptProblem(problem);
+ }
+ public void beginReporting() {
+ if (this.problemRequestor == null) return;
+ this.problemRequestor.beginReporting();
+ }
+ public void endReporting() {
+ if (this.problemRequestor == null) return;
+ this.problemRequestor.endReporting();
+ }
+ public ICompilationUnit getWorkingCopy() {
+ return this.workingCopy;
+ }
+ public boolean isActive() {
+ return this.problemRequestor != null && this.problemRequestor.isActive();
+ }
+ public String toString() {
+ StringBuffer buffer = new StringBuffer();
+ buffer.append("Info for "); //$NON-NLS-1$
+ buffer.append(((JavaElement)workingCopy).toStringWithAncestors());
+ buffer.append("\nUse count = "); //$NON-NLS-1$
+ buffer.append(this.useCount);
+ buffer.append("\nProblem requestor:\n "); //$NON-NLS-1$
+ buffer.append(this.problemRequestor);
+ return buffer.toString();
+ }
+ }
public static boolean VERBOSE = true;
public static boolean CP_RESOLVE_VERBOSE = false;
public static boolean ZIP_ACCESS_VERBOSE = false;
Variables.remove(varName);
}
}
-// TODO khartlage temp-del
+// TODO jsurfer temp-del
// if (propertyName.startsWith(CP_CONTAINER_PREFERENCES_PREFIX)) {
// recreatePersistedContainer(propertyName, (String)event.getNewValue(), false);
// }
*/
public void configurePluginDebugOptions(){
if(JavaCore.getPlugin().isDebugging()){
-// TODO khartlage temp-del
+// TODO jsurfer temp-del
+
String option = Platform.getDebugOption(BUILDER_DEBUG);
// if(option != null) JavaBuilder.DEBUG = option.equalsIgnoreCase("true") ; //$NON-NLS-1$
//
// option = Platform.getDebugOption(SELECTION_DEBUG);
// if(option != null) SelectionEngine.DEBUG = option.equalsIgnoreCase("true") ; //$NON-NLS-1$
- option = Platform.getDebugOption(SHARED_WC_DEBUG);
- if(option != null) CompilationUnit.SHARED_WC_VERBOSE = option.equalsIgnoreCase("true") ; //$NON-NLS-1$
-
option = Platform.getDebugOption(ZIP_ACCESS_DEBUG);
if(option != null) JavaModelManager.ZIP_ACCESS_VERBOSE = option.equalsIgnoreCase("true") ; //$NON-NLS-1$
}
}
+ /*
+ * Discards the per working copy info for the given working copy (making it a compilation unit)
+ * if its use count was 1. Otherwise, just decrement the use count.
+ * If the working copy is primary, computes the delta between its state and the original compilation unit
+ * and register it.
+ * Close the working copy, its buffer and remove it from the shared working copy table.
+ * Ignore if no per-working copy info existed.
+ * NOTE: it must be synchronized as it may interact with the element info cache (if useCount is decremented to 0), see bug 50667.
+ * Returns the new use count (or -1 if it didn't exist).
+ */
+ public synchronized int discardPerWorkingCopyInfo(CompilationUnit workingCopy) throws JavaModelException {
+ synchronized(perWorkingCopyInfos) {
+ WorkingCopyOwner owner = workingCopy.owner;
+ Map workingCopyToInfos = (Map)this.perWorkingCopyInfos.get(owner);
+ if (workingCopyToInfos == null) return -1;
+
+ PerWorkingCopyInfo info = (PerWorkingCopyInfo)workingCopyToInfos.get(workingCopy);
+ if (info == null) return -1;
+
+ if (--info.useCount == 0) {
+ // create the delta builder (this remembers the current content of the working copy)
+ JavaElementDeltaBuilder deltaBuilder = null;
+ if (workingCopy.isPrimary()) {
+ deltaBuilder = new JavaElementDeltaBuilder(workingCopy);
+ }
+
+ // remove per working copy info
+ workingCopyToInfos.remove(workingCopy);
+ if (workingCopyToInfos.isEmpty()) {
+ this.perWorkingCopyInfos.remove(owner);
+ }
+
+ // remove infos + close buffer (since no longer working copy)
+ removeInfoAndChildren(workingCopy);
+ workingCopy.closeBuffer();
+
+ // compute the delta if needed and register it if there are changes
+ if (deltaBuilder != null) {
+ deltaBuilder.buildDeltas();
+ if ((deltaBuilder.delta != null) && (deltaBuilder.delta.getAffectedChildren().length > 0)) {
+ getDeltaProcessor().registerJavaModelDelta(deltaBuilder.delta);
+ }
+ }
+
+ }
+ return info.useCount;
+ }
+ }
/**
* @see ISaveParticipant
}
-
+ public DeltaProcessor getDeltaProcessor() {
+ return this.deltaState.getDeltaProcessor();
+ }
/**
* Returns the set of elements which are out of synch with their buffers.
*/
}
return info;
}
+ /*
+ * Returns the per-working copy info for the given working copy at the given path.
+ * If it doesn't exist and if create, add a new per-working copy info with the given problem requestor.
+ * If recordUsage, increment the per-working copy info's use count.
+ * Returns null if it doesn't exist and not create.
+ */
+ public PerWorkingCopyInfo getPerWorkingCopyInfo(CompilationUnit workingCopy,boolean create, boolean recordUsage, IProblemRequestor problemRequestor) {
+ synchronized(perWorkingCopyInfos) { // use the perWorkingCopyInfo collection as its own lock
+ WorkingCopyOwner owner = workingCopy.owner;
+ Map workingCopyToInfos = (Map)this.perWorkingCopyInfos.get(owner);
+ if (workingCopyToInfos == null && create) {
+ workingCopyToInfos = new HashMap();
+ this.perWorkingCopyInfos.put(owner, workingCopyToInfos);
+ }
+ PerWorkingCopyInfo info = workingCopyToInfos == null ? null : (PerWorkingCopyInfo) workingCopyToInfos.get(workingCopy);
+ if (info == null && create) {
+ info= new PerWorkingCopyInfo(workingCopy, problemRequestor);
+ workingCopyToInfos.put(workingCopy, info);
+ }
+ if (info != null && recordUsage) info.useCount++;
+ return info;
+ }
+ }
/**
* Returns the name of the variables for which an CP variable initializer is registered through an extension point
*/
IPath workingLocation= project.getPluginWorkingLocation(descr);
return workingLocation.append("state.dat").toFile(); //$NON-NLS-1$
}
-
+ /*
+ * Returns the temporary cache for newly opened elements for the current thread.
+ * Creates it if not already created.
+ */
+ public HashMap getTemporaryCache() {
+ HashMap result = (HashMap)this.temporaryCache.get();
+ if (result == null) {
+ result = new HashMap();
+ this.temporaryCache.set(result);
+ }
+ return result;
+ }
/**
* Returns the open ZipFile at the given location. If the ZipFile
* does not yet exist, it is created, opened, and added to the cache
}
}
}
-
+ /*
+ * Returns whether there is a temporary cache for the current thread.
+ */
+ public boolean hasTemporaryCache() {
+ return this.temporaryCache.get() != null;
+ }
// public void loadVariablesAndContainers() throws CoreException {
//
// // backward compatibility, consider persistent property
protected void putInfo(IJavaElement element, Object info) {
this.cache.putInfo(element, info);
}
-
+ /*
+ * Puts the infos in the given map (keys are IJavaElements and values are JavaElementInfos)
+ * in the Java model cache in an atomic way.
+ * First checks that the info for the opened element (or one of its ancestors) has not been
+ * added to the cache. If it is the case, another thread has opened the element (or one of
+ * its ancestors). So returns without updating the cache.
+ */
+ protected synchronized void putInfos(IJavaElement openedElement, Map newElements) {
+ // remove children
+ Object existingInfo = this.cache.peekAtInfo(openedElement);
+ if (openedElement instanceof IParent && existingInfo instanceof JavaElementInfo) {
+ IJavaElement[] children = ((JavaElementInfo)existingInfo).getChildren();
+ for (int i = 0, size = children.length; i < size; ++i) {
+ JavaElement child = (JavaElement) children[i];
+ try {
+ child.close();
+ } catch (JavaModelException e) {
+ // ignore
+ }
+ }
+ }
+
+ Iterator iterator = newElements.keySet().iterator();
+ while (iterator.hasNext()) {
+ IJavaElement element = (IJavaElement)iterator.next();
+ Object info = newElements.get(element);
+ this.cache.putInfo(element, info);
+ }
+ }
/**
* Reads the build state for the relevant project.
*/
}
}
- protected void removeInfo(IJavaElement element) {
- this.cache.removeInfo(element);
- }
-
+// PROTECTED VOID REMOVEINFO(IJAVAELEMENT ELEMENT) {
+// THIS.CACHE.REMOVEINFO(ELEMENT);
+// }
+ /*
+ * Removes all cached info for the given element (including all children)
+ * from the cache.
+ * Returns the info for the given element, or null if it was closed.
+ */
+ public synchronized Object removeInfoAndChildren(JavaElement element) throws JavaModelException {
+ Object info = this.cache.peekAtInfo(element);
+ if (info != null) {
+ boolean wasVerbose = false;
+ try {
+ if (VERBOSE) {
+ System.out.println("CLOSING Element ("+ Thread.currentThread()+"): " + element.toStringWithAncestors()); //$NON-NLS-1$//$NON-NLS-2$
+ wasVerbose = true;
+ VERBOSE = false;
+ }
+ element.closing(info);
+ if (element instanceof IParent && info instanceof JavaElementInfo) {
+ IJavaElement[] children = ((JavaElementInfo)info).getChildren();
+ for (int i = 0, size = children.length; i < size; ++i) {
+ JavaElement child = (JavaElement) children[i];
+ child.close();
+ }
+ }
+ this.cache.removeInfo(element);
+ if (wasVerbose) {
+ System.out.println("-> Package cache size = " + this.cache.pkgSize()); //$NON-NLS-1$
+ System.out.println("-> Openable cache filling ratio = " + NumberFormat.getInstance().format(this.cache.openableFillingRatio()) + "%"); //$NON-NLS-1$//$NON-NLS-2$
+ }
+ } finally {
+ JavaModelManager.VERBOSE = wasVerbose;
+ }
+ return info;
+ }
+ return null;
+ }
public void removePerProjectInfo(JavaProject javaProject) {
synchronized(perProjectInfo) { // use the perProjectInfo collection as its own lock
IProject project = javaProject.getProject();
}
}
}
-
+ /*
+ * Resets the temporary cache for newly created elements to null.
+ */
+ public void resetTemporaryCache() {
+ this.temporaryCache.set(null);
+ }
/**
* @see ISaveParticipant
*/
preferences.setValue(variableKey, variableString);
JavaCore.getPlugin().savePluginPreferences();
}
+ /*
+ * Returns all the working copies which have the given owner.
+ * Adds the working copies of the primary owner if specified.
+ * Returns null if it has none.
+ */
+ public ICompilationUnit[] getWorkingCopies(WorkingCopyOwner owner, boolean addPrimary) {
+ synchronized(perWorkingCopyInfos) {
+ ICompilationUnit[] primaryWCs = addPrimary && owner != DefaultWorkingCopyOwner.PRIMARY
+ ? getWorkingCopies(DefaultWorkingCopyOwner.PRIMARY, false)
+ : null;
+ Map workingCopyToInfos = (Map)perWorkingCopyInfos.get(owner);
+ if (workingCopyToInfos == null) return primaryWCs;
+ int primaryLength = primaryWCs == null ? 0 : primaryWCs.length;
+ int size = workingCopyToInfos.size(); // note size is > 0 otherwise pathToPerWorkingCopyInfos would be null
+ ICompilationUnit[] result = new ICompilationUnit[primaryLength + size];
+ if (primaryWCs != null) {
+ System.arraycopy(primaryWCs, 0, result, 0, primaryLength);
+ }
+ Iterator iterator = workingCopyToInfos.values().iterator();
+ int index = primaryLength;
+ while(iterator.hasNext()) {
+ result[index++] = ((JavaModelManager.PerWorkingCopyInfo)iterator.next()).getWorkingCopy();
+ }
+ return result;
+ }
+ }
}
import net.sourceforge.phpdt.core.IWorkingCopy;
import net.sourceforge.phpdt.core.JavaModelException;
import net.sourceforge.phpdt.internal.core.util.PerThreadObject;
+import net.sourceforge.phpdt.internal.core.util.Util;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResourceStatus;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRunnable;
+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.OperationCanceledException;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.SubProgressMonitor;
+import org.eclipse.core.runtime.jobs.ISchedulingRule;
+import net.sourceforge.phpdt.internal.core.DeltaProcessor;
+import net.sourceforge.phpdt.internal.core.JavaModelManager;
/**
* empty result if no elements are created, or if this
* operation is not actually executed.
*/
- protected static IJavaElement[] fgEmptyResult= new IJavaElement[] {};
+ protected static IJavaElement[] NO_ELEMENTS= new IJavaElement[] {};
/**
* The elements created by this operation - empty
* until the operation actually creates elements.
*/
- protected IJavaElement[] fResultElements= fgEmptyResult;
+ protected IJavaElement[] resultElements= NO_ELEMENTS;
/**
* The progress monitor passed into this operation
*/
- protected IProgressMonitor fMonitor= null;
+ protected IProgressMonitor progressMonitor= null;
/**
* A flag indicating whether this operation is nested.
*/
- protected boolean fNested = false;
+ protected boolean isNested = false;
/**
* Conflict resolution policy - by default do not force (fail on a conflict).
*/
- protected boolean fForce= false;
+ protected boolean force= false;
/*
* A per thread stack of java model operations (PerThreadObject of ArrayList).
protected JavaModelOperation(IJavaElement[] elementsToProcess, IJavaElement[] parentElements, boolean force) {
fElementsToProcess = elementsToProcess;
fParentElements= parentElements;
- fForce= force;
+ force= force;
}
/**
* A common constructor for all Java Model operations.
*/
protected JavaModelOperation(IJavaElement[] elements, boolean force) {
fElementsToProcess = elements;
- fForce= force;
+ force= force;
}
/**
*/
protected JavaModelOperation(IJavaElement element, boolean force) {
fElementsToProcess = new IJavaElement[]{element};
- fForce= force;
+ force= force;
}
/*
* @see IProgressMonitor
*/
public void beginTask(String name, int totalWork) {
- if (fMonitor != null) {
- fMonitor.beginTask(name, totalWork);
+ if (progressMonitor != null) {
+ progressMonitor.beginTask(name, totalWork);
}
}
/**
* @see IProgressMonitor
*/
public void done() {
- if (fMonitor != null) {
- fMonitor.done();
+ if (progressMonitor != null) {
+ progressMonitor.done();
}
}
/*
*
* @exception JavaModelException The operation has failed.
*/
- protected void execute() throws JavaModelException {
- IJavaModelStatus status= verify();
- if (status.isOK()) {
- // if first time here, computes the root infos before executing the operation
- DeltaProcessor deltaProcessor = JavaModelManager.getJavaModelManager().deltaProcessor;
- if (deltaProcessor.roots == null) {
-// TODO khartlage temp-del
- deltaProcessor.initializeRoots();
- }
- executeOperation();
- } else {
- throw new JavaModelException(status);
- }
- }
+// protected void execute() throws JavaModelException {
+// IJavaModelStatus status= verify();
+// if (status.isOK()) {
+// // if first time here, computes the root infos before executing the operation
+// DeltaProcessor deltaProcessor = JavaModelManager.getJavaModelManager().deltaProcessor;
+// if (deltaProcessor.roots == null) {
+//// TODO khartlage temp-del
+// deltaProcessor.initializeRoots();
+// }
+// executeOperation();
+// } else {
+// throw new JavaModelException(status);
+// }
+// }
+
/**
* Convenience method to run an operation within this operation
*/
* Returns the elements created by this operation.
*/
public IJavaElement[] getResultElements() {
- return fResultElements;
+ return resultElements;
+ }
+ /*
+ * Returns the scheduling rule for this operation (i.e. the resource that needs to be locked
+ * while this operation is running.
+ * Subclasses can override.
+ */
+ protected ISchedulingRule getSchedulingRule() {
+ return ResourcesPlugin.getWorkspace().getRoot();
}
/**
* Creates and returns a subprogress monitor if appropriate.
*/
protected IProgressMonitor getSubProgressMonitor(int workAmount) {
IProgressMonitor sub = null;
- if (fMonitor != null) {
- sub = new SubProgressMonitor(fMonitor, workAmount, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK);
+ if (progressMonitor != null) {
+ sub = new SubProgressMonitor(progressMonitor, workAmount, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK);
}
return sub;
}
return !this.isReadOnly() && this.getAttribute(HAS_MODIFIED_RESOURCE_ATTR) == TRUE;
}
public void internalWorked(double work) {
- if (fMonitor != null) {
- fMonitor.internalWorked(work);
+ if (progressMonitor != null) {
+ progressMonitor.internalWorked(work);
}
}
/**
* @see IProgressMonitor
*/
public boolean isCanceled() {
- if (fMonitor != null) {
- return fMonitor.isCanceled();
+ if (progressMonitor != null) {
+ return progressMonitor.isCanceled();
}
return false;
}
*/
protected void moveResources(IResource[] resources, IPath destinationPath) throws JavaModelException {
IProgressMonitor subProgressMonitor = null;
- if (fMonitor != null) {
- subProgressMonitor = new SubProgressMonitor(fMonitor, resources.length, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK);
+ if (progressMonitor != null) {
+ subProgressMonitor = new SubProgressMonitor(progressMonitor, resources.length, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK);
}
IWorkspace workspace = resources[0].getWorkspace();
try {
*/
public void run(IProgressMonitor monitor) throws CoreException {
JavaModelManager manager = JavaModelManager.getJavaModelManager();
- int previousDeltaCount = manager.javaModelDeltas.size();
+ DeltaProcessor deltaProcessor = manager.getDeltaProcessor();
+ int previousDeltaCount = deltaProcessor.javaModelDeltas.size();
try {
- fMonitor = monitor;
+ progressMonitor = monitor;
pushOperation(this);
try {
- this.execute();
+ // computes the root infos before executing the operation
+ // noop if aready initialized
+ JavaModelManager.getJavaModelManager().deltaState.initializeRoots();
+
+ executeOperation();
} finally {
if (this.isTopLevelOperation()) {
this.runPostActions();
} finally {
try {
-// TODO khartlage temp-del
+// TODO jsurfer temp-del
// update JavaModel using deltas that were recorded during this operation
// for (int i = previousDeltaCount, size = manager.javaModelDeltas.size(); i < size; i++) {
// manager.updateJavaModel((IJavaElementDelta)manager.javaModelDeltas.get(i));
}
}
}
+ /**
+ * Main entry point for Java Model operations. Runs a Java Model Operation as an IWorkspaceRunnable
+ * if not read-only.
+ */
+ public void runOperation(IProgressMonitor monitor) throws JavaModelException {
+ IJavaModelStatus status= verify();
+ if (!status.isOK()) {
+ throw new JavaModelException(status);
+ }
+ try {
+ if (isReadOnly()) {
+ run(monitor);
+ } else {
+ // Use IWorkspace.run(...) to ensure that a build will be done in autobuild mode.
+ // Note that if the tree is locked, this will throw a CoreException, but this is ok
+ // as this operation is modifying the tree (not read-only) and a CoreException will be thrown anyway.
+ ResourcesPlugin.getWorkspace().run(this, getSchedulingRule(), IWorkspace.AVOID_UPDATE, 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);
+ }
+ }
+ }
protected void runPostActions() throws JavaModelException {
while (this.actionsStart <= this.actionsEnd) {
IPostAction postAction = this.actions[this.actionsStart++];
* @see IProgressMonitor
*/
public void setCanceled(boolean b) {
- if (fMonitor != null) {
- fMonitor.setCanceled(b);
+ if (progressMonitor != null) {
+ progressMonitor.setCanceled(b);
}
}
/**
* @see CreateElementInCUOperation#checkCanceled
*/
protected void setNested(boolean nested) {
- fNested = nested;
+ isNested = nested;
}
/**
* @see IProgressMonitor
*/
public void setTaskName(String name) {
- if (fMonitor != null) {
- fMonitor.setTaskName(name);
+ if (progressMonitor != null) {
+ progressMonitor.setTaskName(name);
}
}
/**
* @see IProgressMonitor
*/
public void subTask(String name) {
- if (fMonitor != null) {
- fMonitor.subTask(name);
+ if (progressMonitor != null) {
+ progressMonitor.subTask(name);
}
}
/**
* @see IProgressMonitor
*/
public void worked(int work) {
- if (fMonitor != null) {
- fMonitor.worked(work);
+ if (progressMonitor != null) {
+ progressMonitor.worked(work);
checkCanceled();
}
}
import net.sourceforge.phpdt.core.IJavaModelStatus;
import net.sourceforge.phpdt.core.IJavaModelStatusConstants;
import net.sourceforge.phpdt.core.JavaCore;
+import net.sourceforge.phpdt.internal.core.util.Util;
import org.eclipse.core.resources.IResourceStatus;
import org.eclipse.core.runtime.CoreException;
import javax.xml.parsers.SAXParserFactory;
import net.sourceforge.phpdt.core.IClasspathEntry;
+import net.sourceforge.phpdt.core.ICompilationUnit;
import net.sourceforge.phpdt.core.IJavaElement;
import net.sourceforge.phpdt.core.IJavaModelMarker;
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.core.JavaCore;
+import net.sourceforge.phpdt.core.JavaModelException;
+import net.sourceforge.phpdt.core.WorkingCopyOwner;
import net.sourceforge.phpdt.internal.codeassist.ISearchableNameEnvironment;
import net.sourceforge.phpdt.internal.compiler.util.ObjectVector;
+import net.sourceforge.phpdt.internal.core.util.Util;
import net.sourceforge.phpdt.internal.corext.Assert;
import net.sourceforge.phpeclipse.LoadPathEntry;
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 javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+
import org.eclipse.core.resources.ICommand;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Preferences;
import org.eclipse.core.runtime.QualifiedName;
+import net.sourceforge.phpdt.internal.core.ClasspathEntry;
+import net.sourceforge.phpdt.internal.core.XMLWriter;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
/**
* The platform project this <code>IJavaProject</code> is based on
*/
- protected IProject fProject;
+ protected IProject project;
protected List fLoadPathEntries;
protected boolean fScratched;
/**
* Constructor needed for <code>IProject.getNature()</code> and <code>IProject.addNature()</code>.
*
- * @see #setProject
+ * @see #setProject(IProject)
*/
public JavaProject() {
- super(JAVA_PROJECT, null, null);
+ super(null, null);
}
- public JavaProject(IProject project, IJavaElement parent) {
- super(JAVA_PROJECT, parent, project.getName());
- fProject = project;
+ public JavaProject(IProject project, JavaElement parent) {
+ super(parent, project.getName());
+ this.project = project;
}
public void addLoadPathEntry(IProject anotherPHPProject) {
fScratched = true;
public void configure() throws CoreException {
// get project description and then the associated build commands
- IProjectDescription desc = fProject.getDescription();
+ IProjectDescription desc = project.getDescription();
ICommand[] commands = desc.getBuildSpec();
// determine if builder already associated
System.arraycopy(commands, 0, newCommands, 1, commands.length);
newCommands[0] = command;
desc.setBuildSpec(newCommands);
- fProject.setDescription(desc, null);
+ project.setDescription(desc, null);
}
}
}
protected IFile getLoadPathEntriesFile() {
- return fProject.getFile(".loadpath");
+ return project.getFile(".loadpath");
}
protected String getLoadPathXML() {
setJavaCommand(description, command);
}
}
+ /**
+ * @see Openable
+ */
+ protected boolean buildStructure(OpenableElementInfo info, IProgressMonitor pm, Map newElements, IResource underlyingResource) throws JavaModelException {
+
+ // check whether the java project can be opened
+ if (!underlyingResource.isAccessible()) {
+ throw newNotPresentException();
+ }
+
+ IWorkspace workspace = ResourcesPlugin.getWorkspace();
+ IWorkspaceRoot wRoot = workspace.getRoot();
+ // cannot refresh cp markers on opening (emulate cp check on startup) since can create deadlocks (see bug 37274)
+// IClasspathEntry[] resolvedClasspath = getResolvedClasspath(true/*ignoreUnresolvedEntry*/, false/*don't generateMarkerOnError*/, false/*don't returnResolutionInProgress*/);
+
+// // compute the pkg fragment roots
+// info.setChildren(computePackageFragmentRoots(resolvedClasspath, false));
+//
+// // remember the timestamps of external libraries the first time they are looked up
+// for (int i = 0, length = resolvedClasspath.length; i < length; i++) {
+// IClasspathEntry entry = resolvedClasspath[i];
+// if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
+// IPath path = entry.getPath();
+// Object target = JavaModel.getTarget(wRoot, path, true);
+// if (target instanceof java.io.File) {
+// Map externalTimeStamps = JavaModelManager.getJavaModelManager().deltaState.externalTimeStamps;
+// if (externalTimeStamps.get(path) == null) {
+// long timestamp = DeltaProcessor.getTimeStamp((java.io.File)target);
+// externalTimeStamps.put(path, new Long(timestamp));
+// }
+// }
+// }
+// }
- protected void closing(Object info) throws JavaModelException {
+ return true;
+ }
+ protected void closing(Object info) {
- // forget source attachment recommendations
- IPackageFragmentRoot[] roots = this.getPackageFragmentRoots();
-// for (int i = 0; i < roots.length; i++) {
-// if (roots[i] instanceof JarPackageFragmentRoot){
-// ((JarPackageFragmentRoot) roots[i]).setSourceAttachmentProperty(null);
+// // forget source attachment recommendations
+// Object[] children = ((JavaElementInfo)info).children;
+// for (int i = 0, length = children.length; i < length; i++) {
+// Object child = children[i];
+// if (child instanceof JarPackageFragmentRoot){
+// ((JarPackageFragmentRoot)child).setSourceAttachmentProperty(null);
// }
// }
super.closing(info);
}
+// protected void closing(Object info) throws JavaModelException {
+//
+// // forget source attachment recommendations
+// IPackageFragmentRoot[] roots = this.getPackageFragmentRoots();
+//// for (int i = 0; i < roots.length; i++) {
+//// if (roots[i] instanceof JarPackageFragmentRoot){
+//// ((JarPackageFragmentRoot) roots[i]).setSourceAttachmentProperty(null);
+//// }
+//// }
+//
+// super.closing(info);
+// }
switch (innerMostEntry.getEntryKind()) {
case IClasspathEntry.CPE_SOURCE:
// .class files are not visible in source folders
- return true; //!Util.isClassFileName(fullPath.lastSegment());
+ return true; //!net.sourceforge.phpdt.internal.compiler.util.Util.isClassFileName(fullPath.lastSegment());
case IClasspathEntry.CPE_LIBRARY:
// .java files are not visible in library folders
- return !Util.isJavaFileName(fullPath.lastSegment());
+ return !net.sourceforge.phpdt.internal.compiler.util.Util.isJavaFileName(fullPath.lastSegment());
}
}
if (innerMostOutput != null) {
/**
* Returns a new element info for this element.
*/
- protected OpenableElementInfo createElementInfo() {
-
+ protected Object createElementInfo() {
return new JavaProjectElementInfo();
}
+
+ /*
+ * Returns a new search name environment for this project. This name environment first looks in the given working copies.
+ */
+// public ISearchableNameEnvironment newSearchableNameEnvironment(ICompilationUnit[] workingCopies) throws JavaModelException {
+// return new SearchableEnvironment(this, workingCopies);
+// }
+
+ /*
+ * Returns a new search name environment for this project. This name environment first looks in the working copies
+ * of the given owner.
+ */
+ public ISearchableNameEnvironment newSearchableNameEnvironment(WorkingCopyOwner owner) throws JavaModelException {
+ return new SearchableEnvironment(this, owner);
+ }
/**
* Reads and decode an XML classpath string
*/
/**
* Returns the XML String encoding of the class path.
*/
- protected String encodeClasspath(IClasspathEntry[] classpath, IPath outputLocation, boolean useLineSeparator) throws JavaModelException {
-
- Document document = new DocumentImpl();
- Element cpElement = document.createElement("classpath"); //$NON-NLS-1$
- document.appendChild(cpElement);
-
- for (int i = 0; i < classpath.length; ++i) {
- cpElement.appendChild(((ClasspathEntry)classpath[i]).elementEncode(document, getProject().getFullPath()));
- }
-
- if (outputLocation != null) {
- outputLocation = outputLocation.removeFirstSegments(1);
- outputLocation = outputLocation.makeRelative();
- Element oElement = document.createElement("classpathentry"); //$NON-NLS-1$
- oElement.setAttribute("kind", ClasspathEntry.kindToString(ClasspathEntry.K_OUTPUT)); //$NON-NLS-1$
- oElement.setAttribute("path", outputLocation.toString()); //$NON-NLS-1$
- cpElement.appendChild(oElement);
- }
-
- // produce a String output
+ protected String encodeClasspath(IClasspathEntry[] classpath, IPath outputLocation, boolean indent) throws JavaModelException {
try {
ByteArrayOutputStream s = new ByteArrayOutputStream();
- OutputFormat format = new OutputFormat();
- if (useLineSeparator) {
- format.setIndenting(true);
- format.setLineSeparator(System.getProperty("line.separator")); //$NON-NLS-1$
- } else {
- format.setPreserveSpace(true);
- }
- Serializer serializer =
- SerializerFactory.getSerializerFactory(Method.XML).makeSerializer(
- new OutputStreamWriter(s, "UTF8"), //$NON-NLS-1$
- format);
- serializer.asDOMSerializer().serialize(document);
- return s.toString("UTF8"); //$NON-NLS-1$
+ OutputStreamWriter writer = new OutputStreamWriter(s, "UTF8"); //$NON-NLS-1$
+ XMLWriter xmlWriter = new XMLWriter(writer);
+
+ xmlWriter.startTag("classpath", indent); //$NON-NLS-1$
+ for (int i = 0; i < classpath.length; ++i) {
+ ((ClasspathEntry)classpath[i]).elementEncode(xmlWriter, this.project.getFullPath(), indent, true);
+ }
+
+ if (outputLocation != null) {
+ outputLocation = outputLocation.removeFirstSegments(1);
+ outputLocation = outputLocation.makeRelative();
+ HashMap parameters = new HashMap();
+ parameters.put("kind", ClasspathEntry.kindToString(ClasspathEntry.K_OUTPUT));//$NON-NLS-1$
+ parameters.put("path", String.valueOf(outputLocation));//$NON-NLS-1$
+ xmlWriter.printTag("classpathentry", parameters, indent, true, true);//$NON-NLS-1$
+ }
+
+ xmlWriter.endTag("classpath", indent);//$NON-NLS-1$
+ writer.flush();
+ writer.close();
+ return s.toString("UTF8");//$NON-NLS-1$
} catch (IOException e) {
throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION);
}
}
+ /**
+ * Returns the XML String encoding of the class path.
+ */
+// protected String encodeClasspath(IClasspathEntry[] classpath, IPath outputLocation, boolean useLineSeparator) throws JavaModelException {
+//
+// Document document = new DocumentImpl();
+// Element cpElement = document.createElement("classpath"); //$NON-NLS-1$
+// document.appendChild(cpElement);
+//
+// for (int i = 0; i < classpath.length; ++i) {
+// cpElement.appendChild(((ClasspathEntry)classpath[i]).elementEncode(document, getProject().getFullPath()));
+// }
+//
+// if (outputLocation != null) {
+// outputLocation = outputLocation.removeFirstSegments(1);
+// outputLocation = outputLocation.makeRelative();
+// Element oElement = document.createElement("classpathentry"); //$NON-NLS-1$
+// oElement.setAttribute("kind", ClasspathEntry.kindToString(ClasspathEntry.K_OUTPUT)); //$NON-NLS-1$
+// oElement.setAttribute("path", outputLocation.toString()); //$NON-NLS-1$
+// cpElement.appendChild(oElement);
+// }
+//
+// // produce a String output
+// try {
+// ByteArrayOutputStream s = new ByteArrayOutputStream();
+// OutputFormat format = new OutputFormat();
+// if (useLineSeparator) {
+// format.setIndenting(true);
+// format.setLineSeparator(System.getProperty("line.separator")); //$NON-NLS-1$
+// } else {
+// format.setPreserveSpace(true);
+// }
+// Serializer serializer =
+// SerializerFactory.getSerializerFactory(Method.XML).makeSerializer(
+// new OutputStreamWriter(s, "UTF8"), //$NON-NLS-1$
+// format);
+// serializer.asDOMSerializer().serialize(document);
+// return s.toString("UTF8"); //$NON-NLS-1$
+// } catch (IOException e) {
+// throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION);
+// }
+// }
/**
* Returns true if this handle represents the same Java project
JavaProject other = (JavaProject) o;
return getProject().equals(other.getProject())
- && fOccurrenceCount == other.fOccurrenceCount;
+ && occurrenceCount == other.occurrenceCount;
}
public boolean exists() {
- if (!hasJavaNature(fProject)) return false;
+ if (!hasJavaNature(project)) return false;
return super.exists();
}
}
}
- /**
- * @see Openable
- */
- protected boolean generateInfos(
- OpenableElementInfo info,
- IProgressMonitor pm,
- Map newElements,
- IResource underlyingResource) throws JavaModelException {
-
- boolean validInfo = false;
- try {
- if (getProject().isOpen()) {
- // put the info now, because computing the roots requires it
- JavaModelManager.getJavaModelManager().putInfo(this, info);
-
- // compute the pkg fragment roots
- updatePackageFragmentRoots();
-
- // remember the timestamps of external libraries the first time they are looked up
- IClasspathEntry[] resolvedClasspath = getResolvedClasspath(true/*ignore unresolved variable*/);
- for (int i = 0, length = resolvedClasspath.length; i < length; i++) {
- IClasspathEntry entry = resolvedClasspath[i];
- if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
- IPath path = entry.getPath();
- Object target = JavaModel.getTarget(ResourcesPlugin.getWorkspace().getRoot(), path, true);
- if (target instanceof java.io.File) {
- Map externalTimeStamps = JavaModelManager.getJavaModelManager().deltaProcessor.externalTimeStamps;
- if (externalTimeStamps.get(path) == null) {
- long timestamp = DeltaProcessor.getTimeStamp((java.io.File)target);
- externalTimeStamps.put(path, new Long(timestamp));
- }
- }
- }
- }
-
- // only valid if reaches here
- validInfo = true;
- }
- } finally {
- if (!validInfo)
- JavaModelManager.getJavaModelManager().removeInfo(this);
- }
- return validInfo;
- }
+// /**
+// * @see Openable
+// */
+// protected boolean generateInfos(
+// OpenableElementInfo info,
+// IProgressMonitor pm,
+// Map newElements,
+// IResource underlyingResource) throws JavaModelException {
+//
+// boolean validInfo = false;
+// try {
+// if (getProject().isOpen()) {
+// // put the info now, because computing the roots requires it
+// JavaModelManager.getJavaModelManager().putInfo(this, info);
+//
+// // compute the pkg fragment roots
+// updatePackageFragmentRoots();
+//
+// // remember the timestamps of external libraries the first time they are looked up
+// IClasspathEntry[] resolvedClasspath = getResolvedClasspath(true/*ignore unresolved variable*/);
+// for (int i = 0, length = resolvedClasspath.length; i < length; i++) {
+// IClasspathEntry entry = resolvedClasspath[i];
+// if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
+// IPath path = entry.getPath();
+// Object target = JavaModel.getTarget(ResourcesPlugin.getWorkspace().getRoot(), path, true);
+// if (target instanceof java.io.File) {
+// Map externalTimeStamps = JavaModelManager.getJavaModelManager().deltaProcessor.externalTimeStamps;
+// if (externalTimeStamps.get(path) == null) {
+// long timestamp = DeltaProcessor.getTimeStamp((java.io.File)target);
+// externalTimeStamps.put(path, new Long(timestamp));
+// }
+// }
+// }
+// }
+//
+// // only valid if reaches here
+// validInfo = true;
+// }
+// } finally {
+// if (!validInfo)
+// JavaModelManager.getJavaModelManager().removeInfo(this);
+// }
+// return validInfo;
+// }
/**
* @see IJavaProject
}
return null;
}
-
+ /**
+ * @see IJavaElement
+ */
+ public int getElementType() {
+ return JAVA_PROJECT;
+ }
/**
* 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.
return nameLookup;
}
}
+ /*
+ * Returns a new name lookup. This name lookup first looks in the given working copies.
+ */
+ public NameLookup newNameLookup(ICompilationUnit[] workingCopies) throws JavaModelException {
+
+ JavaProjectElementInfo info = getJavaProjectElementInfo();
+ // lock on the project info to avoid race condition while computing the pkg fragment roots and package fragment caches
+// synchronized(info){
+// return new NameLookup(info.getAllPackageFragmentRoots(this), info.getAllPackageFragments(this), workingCopies);
+// }
+ return null;
+ }
+
+ /*
+ * Returns a new name lookup. This name lookup first looks in the working copies of the given owner.
+ */
+ public NameLookup newNameLookup(WorkingCopyOwner owner) throws JavaModelException {
+
+ JavaModelManager manager = JavaModelManager.getJavaModelManager();
+ ICompilationUnit[] workingCopies = owner == null ? null : manager.getWorkingCopies(owner, true/*add primary WCs*/);
+ return newNameLookup(workingCopies);
+ }
//
// /**
// * Returns an array of non-java resources contained in the receiver.
*/
public IPath getOutputLocation() throws JavaModelException {
- JavaModelManager.PerProjectInfo perProjectInfo = JavaModelManager.getJavaModelManager().getPerProjectInfoCheckExistence(fProject);
+ JavaModelManager.PerProjectInfo perProjectInfo = JavaModelManager.getJavaModelManager().getPerProjectInfoCheckExistence(project);
IPath outputLocation = perProjectInfo.outputLocation;
if (outputLocation != null) return outputLocation;
*/
public IProject getProject() {
- return fProject;
+ return project;
}
protected IProject getProject(String name) {
*/
public IClasspathEntry[] getRawClasspath() throws JavaModelException {
- JavaModelManager.PerProjectInfo perProjectInfo = JavaModelManager.getJavaModelManager().getPerProjectInfoCheckExistence(fProject);
+ JavaModelManager.PerProjectInfo perProjectInfo = JavaModelManager.getJavaModelManager().getPerProjectInfoCheckExistence(project);
IClasspathEntry[] classpath = perProjectInfo.classpath;
if (classpath != null) return classpath;
classpath = this.readClasspathFile(false/*don't create markers*/, true/*log problems*/);
throws JavaModelException {
JavaModelManager manager = JavaModelManager.getJavaModelManager();
- JavaModelManager.PerProjectInfo perProjectInfo = manager.getPerProjectInfoCheckExistence(fProject);
+ JavaModelManager.PerProjectInfo perProjectInfo = manager.getPerProjectInfoCheckExistence(project);
// reuse cache if not needing to refresh markers or checking bound variables
if (ignoreUnresolvedEntry && !generateMarkerOnError && perProjectInfo != null){
if (perProjectInfo != null){
if (perProjectInfo.classpath == null // .classpath file could not be read
&& generateMarkerOnError
- && JavaProject.hasJavaNature(fProject)) {
+ && JavaProject.hasJavaNature(project)) {
this.createClasspathProblemMarker(new JavaModelStatus(
IJavaModelStatusConstants.INVALID_CLASSPATH_FILE_FORMAT,
Util.bind("classpath.cannotReadClasspathFile", this.getElementName()))); //$NON-NLS-1$
}
public int hashCode() {
- return fProject.hashCode();
+ return project.hashCode();
}
/**
// return op.getResult();
// }
- /**
- * Open project if resource isn't closed
- */
- protected void openWhenClosed(IProgressMonitor pm) throws JavaModelException {
-
- if (!this.fProject.isOpen()) {
- throw newNotPresentException();
- } else {
- super.openWhenClosed(pm);
- }
- }
+// /**
+// * Open project if resource isn't closed
+// */
+// protected void openWhenClosed(IProgressMonitor pm) throws JavaModelException {
+//
+// if (!this.fProject.isOpen()) {
+// throw newNotPresentException();
+// } else {
+// super.openWhenClosed(pm);
+// }
+// }
public String[] projectPrerequisites(IClasspathEntry[] entries)
throws JavaModelException {
*/
public void setProject(IProject project) {
- fProject = project;
- fParent = JavaModelManager.getJavaModelManager().getJavaModel();
- fName = project.getName();
+ project = project;
+ parent = JavaModelManager.getJavaModelManager().getJavaModel();
+ name = project.getName();
}
/**
protected void setRawClasspath0(IClasspathEntry[] rawEntries)
throws JavaModelException {
- JavaModelManager.PerProjectInfo info = JavaModelManager.getJavaModelManager().getPerProjectInfoCheckExistence(fProject);
+ JavaModelManager.PerProjectInfo info = JavaModelManager.getJavaModelManager().getPerProjectInfoCheckExistence(project);
synchronized (info) {
if (rawEntries != null) {
import net.sourceforge.phpdt.core.IClasspathEntry;
import net.sourceforge.phpdt.core.JavaModelException;
+import net.sourceforge.phpdt.internal.core.util.Util;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IResource;
import java.util.ArrayList;
+import net.sourceforge.phpdt.internal.core.JavaElement;
+
import net.sourceforge.phpdt.core.Flags;
import net.sourceforge.phpdt.core.IJavaElement;
import net.sourceforge.phpdt.core.IMember;
*/
/* package */ abstract class Member extends SourceRefElement implements IMember {
-protected Member(int type, IJavaElement parent, String name) {
- super(type, parent, name);
-}
+ protected Member(JavaElement parent, String name) {
+ super(parent, name);
+ }
protected boolean areSimilarMethods(
String name1, String[] params1,
String name2, String[] params2,
* @see IMember
*/
public IType getDeclaringType() {
- JavaElement parent = (JavaElement)getParent();
- if (parent.fLEType == TYPE) {
- return (IType) parent;
+ JavaElement parentElement = (JavaElement)getParent();
+ if (parentElement.getElementType() == TYPE) {
+ return (IType) parentElement;
}
return null;
}
package net.sourceforge.phpdt.internal.core;
import net.sourceforge.phpdt.core.IJavaElement;
+import net.sourceforge.phpdt.internal.core.util.Util;
/**
* This operation moves elements from their current
package net.sourceforge.phpdt.internal.core;
import net.sourceforge.phpdt.core.IJavaElement;
+import net.sourceforge.phpdt.internal.core.util.Util;
/**
* This operation moves resources (package fragments and compilation units) from their current
import net.sourceforge.phpdt.core.ICompilationUnit;
import net.sourceforge.phpdt.core.JavaCore;
import net.sourceforge.phpdt.internal.core.util.PerThreadObject;
+import net.sourceforge.phpdt.internal.core.util.Util;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
*******************************************************************************/
package net.sourceforge.phpdt.internal.core;
+import java.text.NumberFormat;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IProgressMonitor;
+import net.sourceforge.phpdt.internal.core.JavaElement;
+
+import net.sourceforge.phpdt.internal.core.JavaModelManager;
+import net.sourceforge.phpdt.internal.core.OpenableElementInfo;
/**
* Abstract class for implementations of java elements which are IOpenable.
*/
public abstract class Openable extends JavaElement implements IOpenable, IBufferChangedListener {
-protected Openable(int type, IJavaElement parent, String name) {
- super(type, parent, name);
+protected Openable(JavaElement parent, String name) {
+ super(parent, name);
}
/**
* The buffer associated with this element has changed. Registers
JavaModelManager.getJavaModelManager().getElementsOutOfSynchWithBuffers().put(this, this);
}
}
+
+ /**
+ * 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 buildStructure(OpenableElementInfo info, IProgressMonitor pm, Map newElements, IResource underlyingResource) throws JavaModelException;
+
+///**
+// * 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);
+//}
+/*
+ * Returns whether this element can be removed from the Java model cache to make space.
+ */
+public boolean canBeRemovedFromCache() {
+ try {
+ return !hasUnsavedChanges();
+ } catch (JavaModelException e) {
+ return false;
+ }
+}
+/*
+ * Returns whether the buffer of this element can be removed from the Java model cache to make space.
+ */
+public boolean canBufferBeRemovedFromCache(IBuffer buffer) {
+ return !buffer.hasUnsavedChanges();
+}
/**
- * 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.
+ * Close the buffer associated with this element, if any.
*/
-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);
+protected void closeBuffer() {
+ if (!hasBuffer()) return; // nothing to do
+ IBuffer buffer = getBufferManager().getBuffer(this);
+ if (buffer != null) {
+ buffer.close();
+ buffer.removeBufferChangedListener(this);
}
-
- // 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.
/**
* 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);
+protected void closing(Object info) {
+ closeBuffer();
}
+
///**
// * @see ICodeAssist
// */
// 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() {
+protected Object 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;
-/**
- * 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;
+protected void generateInfos(Object info, HashMap newElements, IProgressMonitor monitor) throws JavaModelException {
+
+ if (JavaModelManager.VERBOSE){
+ System.out.println("OPENING Element ("+ Thread.currentThread()+"): " + this.toStringWithAncestors()); //$NON-NLS-1$//$NON-NLS-2$
+ }
+
+ // open the parent if necessary
+ openParent(info, newElements, monitor);
+ if (monitor != null && monitor.isCanceled()) return;
+
+ // puts the info before building the structure so that questions to the handle behave as if the element existed
+ // (case of compilation units becoming working copies)
+ newElements.put(this, info);
+
+ // build the structure of the openable (this will open the buffer if needed)
+ try {
+ OpenableElementInfo openableElementInfo = (OpenableElementInfo)info;
+ boolean isStructureKnown = buildStructure(openableElementInfo, monitor, newElements, getResource());
+ openableElementInfo.setIsStructureKnown(isStructureKnown);
+ } catch (JavaModelException e) {
+ newElements.remove(this);
+ throw e;
+ }
+
+ // remove out of sync buffer for this element
+ JavaModelManager.getJavaModelManager().getElementsOutOfSynchWithBuffers().remove(this);
+
+ if (JavaModelManager.VERBOSE) {
+ System.out.println("-> Package cache size = " + JavaModelManager.getJavaModelManager().cache.pkgSize()); //$NON-NLS-1$
+ System.out.println("-> Openable cache filling ratio = " + NumberFormat.getInstance().format(JavaModelManager.getJavaModelManager().cache.openableFillingRatio()) + "%"); //$NON-NLS-1$//$NON-NLS-2$
+ }
+}
/**
* 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
* @see IJavaElement
*/
public IResource getUnderlyingResource() throws JavaModelException {
- IResource parentResource = fParent.getUnderlyingResource();
+ IResource parentResource = parent.getUnderlyingResource();
if (parentResource == null) {
return null;
}
int type = parentResource.getType();
if (type == IResource.FOLDER || type == IResource.PROJECT) {
IContainer folder = (IContainer) parentResource;
- IResource resource = folder.findMember(fName);
+ IResource resource = folder.findMember(name);
if (resource == null) {
throw newNotPresentException();
} else {
if (buf != null && buf.hasUnsavedChanges()) {
return true;
}
- // for package fragments, package fragment roots, and projects must check open buffers
+// 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
+ int elementType = getElementType();
+ if (elementType == PACKAGE_FRAGMENT ||
+ elementType == PACKAGE_FRAGMENT_ROOT ||
+ elementType == JAVA_PROJECT ||
+ elementType == JAVA_MODEL) { // fix for 1FWNMHH
Enumeration openBuffers= getBufferManager().getOpenBuffers();
while (openBuffers.hasMoreElements()) {
IBuffer buffer= (IBuffer)openBuffers.nextElement();
protected boolean isSourceElement() {
return false;
}
+///**
+// * @see IOpenable
+// */
+//public void makeConsistent(IProgressMonitor pm) throws JavaModelException {
+// if (!isConsistent()) {
+// buildStructure((OpenableElementInfo)getElementInfo(), pm);
+// }
+//}
/**
* @see IOpenable
- */
-public void makeConsistent(IProgressMonitor pm) throws JavaModelException {
- if (!isConsistent()) {
- buildStructure((OpenableElementInfo)getElementInfo(), pm);
+ */
+public void makeConsistent(IProgressMonitor monitor) throws JavaModelException {
+ if (isConsistent()) return;
+
+ // create a new info and make it the current info
+ // (this will remove the info and its children just before storing the new infos)
+ JavaModelManager manager = JavaModelManager.getJavaModelManager();
+ boolean hadTemporaryCache = manager.hasTemporaryCache();
+ try {
+ HashMap newElements = manager.getTemporaryCache();
+ openWhenClosed(newElements, monitor);
+ if (newElements.get(this) == null) {
+ // close any buffer that was opened for the new elements
+ Iterator iterator = newElements.keySet().iterator();
+ while (iterator.hasNext()) {
+ IJavaElement element = (IJavaElement)iterator.next();
+ if (element instanceof Openable) {
+ ((Openable)element).closeBuffer();
+ }
+ }
+ throw newNotPresentException();
+ }
+ if (!hadTemporaryCache) {
+ manager.putInfos(this, newElements);
+ }
+ } finally {
+ if (!hadTemporaryCache) {
+ manager.resetTemporaryCache();
+ }
}
}
+
/**
* @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);
- }
+ getElementInfo(pm);
}
-
/**
* Opens a buffer on the contents of this element, and returns
* the buffer, or returns <code>null</code> if opening fails.
}
/**
- * Open the parent element if necessary
- *
+ * Open the parent element if necessary.
*/
-protected void openParent(IProgressMonitor pm) throws JavaModelException {
+protected void openParent(Object childInfo, HashMap newElements, IProgressMonitor pm) throws JavaModelException {
Openable openableParent = (Openable)getOpenableParent();
- if (openableParent != null) {
- if (!openableParent.isOpen()){
- openableParent.openWhenClosed(pm);
- }
+ if (openableParent != null && !openableParent.isOpen()){
+ openableParent.generateInfos(openableParent.createElementInfo(), newElements, pm);
}
}
-/**
- * Open an <code>Openable</code> that is known to be closed (no check for <code>isOpen()</code>).
- */
-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$
+///**
+// * Open an <code>Openable</code> that is known to be closed (no check for <code>isOpen()</code>).
+// */
+//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$
// }
-
- // 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;
- }
-}
+//
+// // 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)
import java.util.Iterator;
import net.sourceforge.phpdt.internal.core.util.LRUCache;
+import net.sourceforge.phpdt.internal.core.util.Util;
/**
* The <code>OverflowingLRUCache</code> is an LRUCache which attempts
*******************************************************************************/
package net.sourceforge.phpdt.internal.core;
+import net.sourceforge.phpdt.core.IJavaElement;
+import net.sourceforge.phpdt.internal.core.CompilationUnit;
+
import net.sourceforge.phpdt.core.ICompilationUnit;
import net.sourceforge.phpdt.core.IPackageDeclaration;
import net.sourceforge.phpdt.core.JavaModelException;
*/
/* package */ class PackageDeclaration extends SourceRefElement implements IPackageDeclaration {
-protected PackageDeclaration(ICompilationUnit parent, String name) {
- super(PACKAGE_DECLARATION, parent, name);
-}
+ protected PackageDeclaration(CompilationUnit parent, String name) {
+ super(parent, name);
+ }
+ public boolean equals(Object o) {
+ if (!(o instanceof PackageDeclaration)) return false;
+ return super.equals(o);
+ }
/**
* @see JavaElement#equalsDOMNode
*/
return (node.getNodeType() == IDOMNode.PACKAGE) && getElementName().equals(node.getName());
}
/**
+ * @see IJavaElement
+ */
+public int getElementType() {
+ return PACKAGE_DECLARATION;
+}
+/**
* @see JavaElement#getHandleMemento()
*/
protected char getHandleMementoDelimiter() {
package net.sourceforge.phpdt.internal.core;
import java.util.ArrayList;
+import java.util.HashSet;
import java.util.Map;
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.IPackageFragmentRoot;
import net.sourceforge.phpdt.core.JavaModelException;
+import net.sourceforge.phpdt.internal.core.util.Util;
+import net.sourceforge.phpdt.internal.ui.util.PHPFileUtil;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IResource;
* Constant empty list of compilation units
*/
protected static ICompilationUnit[] fgEmptyCompilationUnitList= new ICompilationUnit[] {};
-/**
- * Constructs a handle for a package fragment
- *
- * @see IPackageFragment
- */
-protected PackageFragment(IPackageFragmentRoot root, String name) {
- super(PACKAGE_FRAGMENT, root, name);
-}
-/**
- * Compute the children of this package fragment.
- *
- * <p>Package fragments which are folders recognize files based on the
- * type of the fragment
- * <p>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();
-// int kind = getKind();
- String extType;
-// if (kind == IPackageFragmentRoot.K_SOURCE) {
- 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;
-// if (kind == IPackageFragmentRoot.K_SOURCE && Util.isValidCompilationUnitName(child.getName())) {
-// childElement = getCompilationUnit(child.getName());
-// vChildren.add(childElement);
-// } else if (Util.isValidClassFileName(child.getName())) {
-// childElement = getClassFile(child.getName());
-// vChildren.add(childElement);
-// }
+ /**
+ * Constructs a handle for a package fragment
+ *
+ * @see IPackageFragment
+ */
+ protected PackageFragment(PackageFragmentRoot root, String name) {
+ super(root, name);
+ }
+ /**
+ * @see Openable
+ */
+ protected boolean buildStructure(OpenableElementInfo info, IProgressMonitor pm, Map newElements, IResource underlyingResource) throws JavaModelException {
+
+ // check whether this pkg can be opened
+ if (!underlyingResource.isAccessible()) throw newNotPresentException();
+
+ int kind = getKind();
+ String extType;
+// if (kind == IPackageFragmentRoot.K_SOURCE) {
+ extType = "php"; //EXTENSION_java;
+// } else {
+// extType = EXTENSION_class;
+// }
+
+ // add compilation units/class files from resources
+ HashSet vChildren = new HashSet();
+ try {
+ PackageFragmentRoot root = getPackageFragmentRoot();
+// char[][] inclusionPatterns = root.fullInclusionPatternChars();
+ char[][] exclusionPatterns = root.fullExclusionPatternChars();
+ IResource[] members = ((IContainer) underlyingResource).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 = new CompilationUnit(this, child.getName(), DefaultWorkingCopyOwner.PRIMARY);
+// vChildren.add(childElement);
+// } else if (Util.isValidClassFileName(child.getName())) {
+// childElement = getClassFile(child.getName());
+// vChildren.add(childElement);
+// }
+ }
}
}
}
+ } catch (CoreException e) {
+ throw new JavaModelException(e);
}
- } catch (CoreException e) {
- throw new JavaModelException(e);
+
+// if (kind == IPackageFragmentRoot.K_SOURCE) {
+// // add primary compilation units
+// ICompilationUnit[] primaryCompilationUnits = getCompilationUnits(DefaultWorkingCopyOwner.PRIMARY);
+// for (int i = 0, length = primaryCompilationUnits.length; i < length; i++) {
+// ICompilationUnit primary = primaryCompilationUnits[i];
+// vChildren.add(primary);
+// }
+// }
+
+ IJavaElement[] children = new IJavaElement[vChildren.size()];
+ vChildren.toArray(children);
+ info.setChildren(children);
+ return true;
}
- IJavaElement[] children = new IJavaElement[vChildren.size()];
- vChildren.toArray(children);
- info.setChildren(children);
- return true;
-}
+///**
+// * Compute the children of this package fragment.
+// *
+// * <p>Package fragments which are folders recognize files based on the
+// * type of the fragment
+// * <p>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();
+//// int kind = getKind();
+// String extType;
+//// if (kind == IPackageFragmentRoot.K_SOURCE) {
+// 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;
+//// if (kind == IPackageFragmentRoot.K_SOURCE && Util.isValidCompilationUnitName(child.getName())) {
+//// childElement = getCompilationUnit(child.getName());
+//// vChildren.add(childElement);
+//// } else if (Util.isValidClassFileName(child.getName())) {
+//// 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;
+//}
/**
* Returns true if this fragment contains at least one java resource.
* Returns false otherwise.
/**
* @see JavaElement
*/
-protected OpenableElementInfo createElementInfo() {
+protected Object createElementInfo() {
return new PackageFragmentInfo();
}
/**
// IJavaElement[] elements = new IJavaElement[] {this};
// getJavaModel().delete(elements, force, monitor);
//}
-/**
- * @see Openable
- */
-protected boolean generateInfos(OpenableElementInfo info, IProgressMonitor pm, Map newElements, IResource underlyingResource) throws JavaModelException {
-
- return computeChildren(info, underlyingResource);
-}
+///**
+// * @see Openable
+// */
+//protected boolean generateInfos(OpenableElementInfo info, IProgressMonitor pm, Map newElements, IResource underlyingResource) throws JavaModelException {
+//
+// return computeChildren(info, underlyingResource);
+//}
///**
// * @see IPackageFragment#getClassFile(String)
// */
//}
/**
* @see IPackageFragment#getCompilationUnit(String)
+ * @exception IllegalArgumentExcpetion if the name does not end with ".java"
*/
-public ICompilationUnit getCompilationUnit(String name) {
- return new CompilationUnit(this, name);
+public ICompilationUnit getCompilationUnit(String cuName) {
+ if (! PHPFileUtil.isPHPFileName(cuName)) {
+ throw new IllegalArgumentException(Util.bind("convention.unit.notJavaName")); //$NON-NLS-1$
+ }
+ return new CompilationUnit(this, cuName, DefaultWorkingCopyOwner.PRIMARY);
}
/**
* @see IPackageFragment#getCompilationUnits()
return array;
}
/**
+ * @see IJavaElement
+ */
+public int getElementType() {
+ return PACKAGE_FRAGMENT;
+}
+/**
* @see JavaElement#getHandleMementoDelimiter()
*/
protected char getHandleMementoDelimiter() {
* @see IJavaElement#getUnderlyingResource()
*/
public IResource getUnderlyingResource() throws JavaModelException {
- IResource rootResource = fParent.getUnderlyingResource();
+ IResource rootResource = parent.getUnderlyingResource();
if (rootResource == null) {
//jar package fragment root that has no associated resource
return null;
// String[] renamings= new String[] {name};
// getJavaModel().rename(elements, dests, renamings, force, monitor);
//}
-/*
- * @see JavaElement#rootedAt(IJavaProject)
- */
-public IJavaElement rootedAt(IJavaProject project) {
- return
- new PackageFragment(
- (IPackageFragmentRoot)((JavaElement)fParent).rootedAt(project),
- fName);
-}
+///*
+// * @see JavaElement#rootedAt(IJavaProject)
+// */
+//public IJavaElement rootedAt(IJavaProject project) {
+// return
+// new PackageFragment(
+// (IPackageFragmentRoot)((JavaElement)parent).rootedAt(project),
+// name);
+//}
/**
* Debugging purposes
*/
*******************************************************************************/
package net.sourceforge.phpdt.internal.core;
+import java.util.ArrayList;
import java.util.Map;
import net.sourceforge.phpdt.core.IJavaElement;
import net.sourceforge.phpdt.core.JavaModelException;
import net.sourceforge.phpdt.core.JavaCore;
import net.sourceforge.phpdt.core.compiler.CharOperation;
+import net.sourceforge.phpdt.internal.core.util.Util;
+import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.QualifiedName;
+import net.sourceforge.phpdt.core.IClasspathEntry;
+import net.sourceforge.phpdt.core.IJavaModelStatusConstants;
+import net.sourceforge.phpdt.internal.core.Openable;
+import net.sourceforge.phpdt.internal.core.OpenableElementInfo;
+
+import net.sourceforge.phpdt.internal.core.JavaProject;
+import net.sourceforge.phpdt.internal.core.PackageFragmentRootInfo;
/**
*/
protected Object resource;
-/**
- * Constructs a package fragment root which is the root of the java package
- * directory hierarchy.
- */
-protected PackageFragmentRoot(IResource resource, IJavaProject project, String name) {
- super(PACKAGE_FRAGMENT_ROOT, project, name);
- this.resource = resource;
-}
+ /**
+ * Constructs a package fragment root which is the root of the java package
+ * directory hierarchy.
+ */
+ protected PackageFragmentRoot(IResource resource, JavaProject project, String name) {
+ super(project, name);
+ this.resource = resource;
+ }
+
+ /**
+ * @see Openable
+ */
+ protected boolean buildStructure(OpenableElementInfo info, IProgressMonitor pm, Map newElements, IResource underlyingResource) throws JavaModelException {
+
+ // check whether this pkg fragment root can be opened
+ if (!resourceExists() ) { //|| !isOnClasspath()) {
+ throw newNotPresentException();
+ }
+ ((PackageFragmentRootInfo) info).setRootKind(determineKind(underlyingResource));
+ return computeChildren(info, newElements);
+ }
+ /**
+ * Returns the root's kind - K_SOURCE or K_BINARY, defaults
+ * to K_SOURCE if it is not on the classpath.
+ *
+ * @exception NotPresentException if the project and root do
+ * not exist.
+ */
+ protected int determineKind(IResource underlyingResource) throws JavaModelException {
+// IClasspathEntry[] entries= ((JavaProject)getJavaProject()).getExpandedClasspath(true);
+// for (int i= 0; i < entries.length; i++) {
+// IClasspathEntry entry= entries[i];
+// if (entry.getPath().equals(underlyingResource.getFullPath())) {
+// return entry.getContentKind();
+// }
+// }
+ return IPackageFragmentRoot.K_SOURCE;
+ }
+ /**
+ * Compute the package fragment children of this package fragment root.
+ *
+ * @exception JavaModelException The resource associated with this package fragment root does not exist
+ */
+ protected boolean computeChildren(OpenableElementInfo info, Map newElements) throws JavaModelException {
+ // Note the children are not opened (so not added to newElements) for a regular package fragment root
+ // Howver they are opened for a Jar package fragment root (see JarPackageFragmentRoot#computeChildren)
+ try {
+ // the underlying resource may be a folder or a project (in the case that the project folder
+ // is actually the package fragment root)
+ IResource underlyingResource = getResource();
+ if (underlyingResource.getType() == IResource.FOLDER || underlyingResource.getType() == IResource.PROJECT) {
+ ArrayList vChildren = new ArrayList(5);
+ IContainer rootFolder = (IContainer) underlyingResource;
+ // char[][] inclusionPatterns = fullInclusionPatternChars();
+ char[][] exclusionPatterns = fullExclusionPatternChars();
+ computeFolderChildren(rootFolder, !Util.isExcluded(rootFolder, exclusionPatterns), "", vChildren, exclusionPatterns); //$NON-NLS-1$
+
+ IJavaElement[] children = new IJavaElement[vChildren.size()];
+ vChildren.toArray(children);
+ info.setChildren(children);
+ }
+ } catch (JavaModelException e) {
+ //problem resolving children; structure remains unknown
+ info.setChildren(new IJavaElement[]{});
+ throw e;
+ }
+ return true;
+ }
+ /**
+ * Starting at this folder, create package fragments and add the fragments that are not exclused
+ * to the collection of children.
+ *
+ * @exception JavaModelException The resource associated with this package fragment does not exist
+ */
+ protected void computeFolderChildren(IContainer folder, boolean isIncluded, String prefix, ArrayList vChildren, char[][] exclusionPatterns) throws JavaModelException {
+ //, char[][] inclusionPatterns, char[][] exclusionPatterns) throws JavaModelException {
+
+ if (isIncluded) {
+ IPackageFragment pkg = getPackageFragment(prefix);
+ vChildren.add(pkg);
+ }
+ try {
+ JavaProject javaProject = (JavaProject)getJavaProject();
+ IResource[] members = folder.members();
+ boolean hasIncluded = isIncluded;
+ for (int i = 0, max = members.length; i < max; i++) {
+ IResource member = members[i];
+ String memberName = member.getName();
+
+ switch(member.getType()) {
+
+ case IResource.FOLDER:
+ if (Util.isValidFolderNameForPackage(memberName)) {
+ boolean isMemberIncluded = !Util.isExcluded(member, exclusionPatterns);
+ // keep looking inside as long as included already, or may have child included due to inclusion patterns
+// if (isMemberIncluded || inclusionPatterns != null) {
+// // eliminate binary output only if nested inside direct subfolders
+// if (javaProject.contains(member)) {
+// String newPrefix;
+// if (prefix.length() == 0) {
+// newPrefix = memberName;
+// } else {
+// newPrefix = prefix + "." + memberName; //$NON-NLS-1$
+// }
+// computeFolderChildren((IFolder) member, isMemberIncluded, newPrefix, vChildren, inclusionPatterns, exclusionPatterns);
+// }
+// }
+ }
+ break;
+ case IResource.FILE:
+ // inclusion filter may only include files, in which case we still want to include the immediate parent package (lazily)
+ if (!hasIncluded
+ && Util.isValidCompilationUnitName(memberName)
+ && !Util.isExcluded(member, exclusionPatterns)) {
+ hasIncluded = true;
+ IPackageFragment pkg = getPackageFragment(prefix);
+ vChildren.add(pkg);
+ }
+ break;
+ }
+ }
+ } catch(IllegalArgumentException e){
+ throw new JavaModelException(e, IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST); // could be thrown by ElementTree when path is not found
+ } catch (CoreException e) {
+ throw new JavaModelException(e);
+ }
+ }
/**
* @see IPackageFragmentRoot
*/
-/**
- * Returns a new element info for this element.
- */
-protected OpenableElementInfo createElementInfo() {
- return new PackageFragmentRootInfo();
-}
+ /**
+ * Returns a new element info for this element.
+ */
+ protected Object createElementInfo() {
+ return new PackageFragmentRootInfo();
+ }
/**
* @see IPackageFragmentRoot
PackageFragmentRoot other = (PackageFragmentRoot) o;
return getJavaModel().equals(other.getJavaModel()) &&
this.resource.equals(other.resource) &&
- fOccurrenceCount == other.fOccurrenceCount;
+ occurrenceCount == other.occurrenceCount;
}
/**
return JavaElement.JEM_PACKAGEFRAGMENTROOT;
}
/**
+ * @see IJavaElement
+ */
+public int getElementType() {
+ return PACKAGE_FRAGMENT_ROOT;
+}
+/**
* @see JavaElement#getHandleMemento()
*/
public String getHandleMemento(){
// }
//}
-/*
- * @see JavaElement#rootedAt(IJavaProject)
- */
-public IJavaElement rootedAt(IJavaProject project) {
- return
- new PackageFragmentRoot(
- getResource(),
- project,
- fName);
-}
+///*
+// * @see JavaElement#rootedAt(IJavaProject)
+// */
+//public IJavaElement rootedAt(IJavaProject project) {
+// return
+// new PackageFragmentRoot(
+// getResource(),
+// project,
+// name);
+//}
/**
* @private Debugging purposes
import net.sourceforge.phpdt.core.IJavaProject;
import net.sourceforge.phpdt.core.IPackageFragmentRoot;
import net.sourceforge.phpdt.core.JavaModelException;
+import net.sourceforge.phpdt.internal.core.util.Util;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IResource;
*******************************************************************************/
package net.sourceforge.phpdt.internal.core;
+import java.util.Map;
+
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;
+import net.sourceforge.phpdt.core.WorkingCopyOwner;
+import net.sourceforge.phpdt.internal.core.util.Util;
+import net.sourceforge.phpeclipse.internal.compiler.ast.CompilationUnitDeclaration;
/**
* Reconcile a working copy and signal the changes through a delta.
*/
public class ReconcileWorkingCopyOperation extends JavaModelOperation {
+ boolean createAST;
+ int astLevel;
boolean forceProblemDetection;
+ WorkingCopyOwner workingCopyOwner;
+// org.eclipse.jdt.core.dom.CompilationUnit ast;
public ReconcileWorkingCopyOperation(IJavaElement workingCopy, boolean forceProblemDetection) {
super(new IJavaElement[] {workingCopy});
this.forceProblemDetection = forceProblemDetection;
}
+ public ReconcileWorkingCopyOperation(IJavaElement workingCopy, boolean creatAST, int astLevel, boolean forceProblemDetection, WorkingCopyOwner workingCopyOwner) {
+ super(new IJavaElement[] {workingCopy});
+ this.createAST = creatAST;
+ this.astLevel = astLevel;
+ this.forceProblemDetection = forceProblemDetection;
+ this.workingCopyOwner = workingCopyOwner;
+ }
/**
* @exception JavaModelException if setting the source
* of the original compilation unit fails
// }
protected void executeOperation() throws JavaModelException {
// TODO jsurfer optimize for PHP
- if (fMonitor != null){
- if (fMonitor.isCanceled()) return;
- fMonitor.beginTask(Util.bind("element.reconciling"), 10); //$NON-NLS-1$
+ if (progressMonitor != null){
+ if (progressMonitor.isCanceled()) return;
+ progressMonitor.beginTask(Util.bind("element.reconciling"), 10); //$NON-NLS-1$
}
- WorkingCopy workingCopy = getWorkingCopy();
+ CompilationUnit workingCopy = getWorkingCopy();
// boolean wasConsistent = workingCopy.isConsistent();
// JavaElementDeltaBuilder deltaBuilder = null;
//
// }
- if (fMonitor != null) fMonitor.worked(2);
+ if (progressMonitor != null) progressMonitor.worked(2);
// force problem detection? - if structure was consistent
if (forceProblemDetection){
- if (fMonitor != null && fMonitor.isCanceled()) return;
-
- IProblemRequestor problemRequestor = workingCopy.problemRequestor;
+ if (progressMonitor != null && progressMonitor.isCanceled()) return;
+ CompilationUnitDeclaration unit = null;
+ try {
+ IProblemRequestor problemRequestor = workingCopy.getPerWorkingCopyInfo();
if (problemRequestor != null && problemRequestor.isActive()){
problemRequestor.beginReporting();
- CompilationUnitProblemFinder.process(workingCopy, problemRequestor, fMonitor);
+ char[] contents = workingCopy.getContents();
+ unit = CompilationUnitProblemFinder.process(workingCopy, contents, this.workingCopyOwner, problemRequestor, false/*don't cleanup cu*/, this.progressMonitor);
+
+ CompilationUnitProblemFinder.process(workingCopy, problemRequestor, progressMonitor);
problemRequestor.endReporting();
}
+ if (progressMonitor != null) progressMonitor.worked(1);
+ if (this.createAST && unit != null) {
+// Map options = workingCopy.getJavaProject().getOptions(true);
+// this.ast = AST.convertCompilationUnit(this.astLevel, unit, contents, options, this.progressMonitor);
+ if (progressMonitor != null) progressMonitor.worked(1);
+ }
+ } finally {
+ if (unit != null) {
+ unit.cleanUp();
+ }
+ }
}
// register the deltas
// }
// }
} finally {
- if (fMonitor != null) fMonitor.done();
+ if (progressMonitor != null) progressMonitor.done();
}
}
/**
* Returns the working copy this operation is working on.
*/
- protected WorkingCopy getWorkingCopy() {
- return (WorkingCopy)getElementToProcess();
+ protected CompilationUnit getWorkingCopy() {
+ return (CompilationUnit)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) {
+ CompilationUnit workingCopy = getWorkingCopy();
+ if (!workingCopy.isWorkingCopy()) {
return new JavaModelStatus(IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST, workingCopy); //was destroyed
}
return status;
}
-
}
import net.sourceforge.phpdt.core.IJavaModelStatusConstants;
import net.sourceforge.phpdt.core.ISourceReference;
import net.sourceforge.phpdt.core.JavaModelException;
+import net.sourceforge.phpdt.internal.core.util.Util;
/**
* This operation renames elements.
import net.sourceforge.phpdt.core.IJavaElement;
import net.sourceforge.phpdt.core.IJavaModelStatusConstants;
import net.sourceforge.phpdt.core.JavaModelException;
+import net.sourceforge.phpdt.internal.core.util.Util;
/**
* This operation renames resources (Package fragments and compilation units).
import net.sourceforge.phpdt.core.IPackageFragment;
import net.sourceforge.phpdt.core.IType;
import net.sourceforge.phpdt.core.JavaModelException;
+import net.sourceforge.phpdt.core.WorkingCopyOwner;
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.INameEnvironment;
import net.sourceforge.phpdt.internal.compiler.env.ISourceType;
import net.sourceforge.phpdt.internal.compiler.env.NameEnvironmentAnswer;
protected ICompilationUnit unitToSkip;
protected IJavaProject project;
- // protected IJavaSearchScope searchScope;
+ //protected IJavaSearchScope searchScope;
+ /**
+ * Creates a Sea
/**
* Creates a SearchableEnvironment on the given project
*/
// Create search scope with visible entry on the project's classpath
// this.searchScope = SearchEngine.createJavaSearchScope(this.project.getAllPackageFragmentRoots());
}
+
+
+ /**
+ * Creates a SearchableEnvironment on the given project
+ */
+ public SearchableEnvironment(JavaProject project, WorkingCopyOwner owner) throws JavaModelException {
+ this.project = project;
+ this.nameLookup = project.newNameLookup(owner);
+
+ // 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 <code>null</code>.
import net.sourceforge.phpdt.core.IPackageFragmentRoot;
import net.sourceforge.phpdt.core.JavaModelException;
import net.sourceforge.phpdt.internal.compiler.util.ObjectVector;
+import net.sourceforge.phpdt.internal.core.util.Util;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
+import net.sourceforge.phpdt.internal.core.JavaModelManager;
+import net.sourceforge.phpdt.internal.core.JavaProject;
/**
* This operation sets an <code>IJavaProject</code>'s classpath.
IClasspathEntry[] oldResolvedPath, newResolvedPath;
IClasspathEntry[] newRawPath;
- boolean canChangeResource;
+ boolean canChangeResources;
boolean needCycleCheck;
boolean needValidation;
boolean needSave;
IPath newOutputLocation;
+ JavaProject project;
+ boolean identicalRoots;
public static final IClasspathEntry[] ReuseClasspath = new IClasspathEntry[0];
public static final IClasspathEntry[] UpdateClasspath = new IClasspathEntry[0];
* When executed, this operation sets the classpath of the given project.
*/
public SetClasspathOperation(
- IJavaProject project,
+ JavaProject project,
IClasspathEntry[] oldResolvedPath,
IClasspathEntry[] newRawPath,
IPath newOutputLocation,
this.oldResolvedPath = oldResolvedPath;
this.newRawPath = newRawPath;
this.newOutputLocation = newOutputLocation;
- this.canChangeResource = canChangeResource;
+ this.canChangeResources = canChangeResource;
this.needValidation = needValidation;
this.needSave = needSave;
+ this.project = project;
}
/**
// }
// return fragments;
// }
-
/**
* Sets the classpath of the pre-specified project.
*/
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);
+ project.updatePackageFragmentRoots();
+ JavaModelManager.getJavaModelManager().getDeltaProcessor().addForRefresh(project);
}
} catch(JavaModelException e){
} catch(JavaModelException e){
if (originalException != null) throw originalException;
throw e;
+ } finally {
+ // ensures the project is getting rebuilt if only variable is modified
+ if (!this.identicalRoots && this.canChangeResources) {
+ try {
+ this.project.getProject().touch(this.progressMonitor);
+ } catch (CoreException e) {
+ if (JavaModelManager.CP_RESOLVE_VERBOSE){
+ Util.verbose("CPContainer INIT - FAILED to touch project: "+ this.project.getElementName(), System.err); //$NON-NLS-1$
+ e.printStackTrace();
+ }
+ }
+ }
}
}
done();
}
-
+
/**
* Generates the delta of removed/added/reordered roots.
* Use three deltas in case the same root is removed/added/reordered (for
* otherwise <code>false</code>. Subclasses must override.
*/
public boolean isReadOnly() {
- return !this.canChangeResource;
+ return !this.canChangeResources;
}
protected void saveClasspathIfNecessary() throws JavaModelException {
- if (!this.canChangeResource || !this.needSave) return;
+ if (!this.canChangeResources || !this.needSave) return;
IClasspathEntry[] classpathForSave;
JavaProject project = getProject();
// resolve new path (asking for marker creation if problems)
if (this.newResolvedPath == null) {
- this.newResolvedPath = project.getResolvedClasspath(true, this.canChangeResource);
+ this.newResolvedPath = project.getResolvedClasspath(true, this.canChangeResources);
}
// if (this.oldResolvedPath != null) {
project.setRawClasspath(
UpdateClasspath,
SetClasspathOperation.ReuseOutputLocation,
- this.fMonitor,
- this.canChangeResource,
+ this.progressMonitor,
+ this.canChangeResources,
project.getResolvedClasspath(true),
false, // updating only - no validation
false); // updating only - no need to save
protected void updateCycleMarkersIfNecessary(IClasspathEntry[] newResolvedPath) {
if (!this.needCycleCheck) return;
- if (!this.canChangeResource) return;
+ if (!this.canChangeResources) return;
try {
JavaProject project = getProject();
*/
protected void updateProjectReferencesIfNecessary() throws JavaModelException {
- if (!this.canChangeResource) return;
+ if (!this.canChangeResources) return;
if (this.newRawPath == ReuseClasspath || this.newRawPath == UpdateClasspath) return;
JavaProject jproject = getProject();
}
description.setReferencedProjects(requiredProjectArray);
- project.setDescription(description, this.fMonitor);
+ project.setDescription(description, this.progressMonitor);
} catch(CoreException e){
throw new JavaModelException(e);
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2000, 2004 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.IJavaElementDelta;
+
+/**
+ * A simple Java element delta that remembers the kind of changes only.
+ */
+public class SimpleDelta {
+
+ /*
+ * @see IJavaElementDelta#getKind()
+ */
+ protected int kind = 0;
+
+ /*
+ * @see IJavaElementDelta#getFlags()
+ */
+ protected int changeFlags = 0;
+
+ /*
+ * Marks this delta as added
+ */
+ public void added() {
+ this.kind = IJavaElementDelta.ADDED;
+ }
+
+ /*
+ * Marks this delta as changed with the given change flag
+ */
+ public void changed(int flags) {
+ this.kind = IJavaElementDelta.CHANGED;
+ this.changeFlags |= flags;
+ }
+
+ /*
+ * @see IJavaElementDelta#getFlags()
+ */
+ public int getFlags() {
+ return this.changeFlags;
+ }
+
+ /*
+ * @see IJavaElementDelta#getKind()
+ */
+ public int getKind() {
+ return this.kind;
+ }
+
+ /*
+ * Mark this delta has a having a modifiers change
+ */
+ public void modifiers() {
+ changed(IJavaElementDelta.F_MODIFIERS);
+ }
+
+ /*
+ * Marks this delta as removed
+ */
+ public void removed() {
+ this.kind = IJavaElementDelta.REMOVED;
+ this.changeFlags = 0;
+ }
+
+ /*
+ * Mark this delta has a having a super type change
+ */
+ public void superTypes() {
+ changed(IJavaElementDelta.F_SUPER_TYPES);
+ }
+
+ protected void toDebugString(StringBuffer buffer) {
+ buffer.append("["); //$NON-NLS-1$
+ switch (getKind()) {
+ case IJavaElementDelta.ADDED :
+ buffer.append('+');
+ break;
+ case IJavaElementDelta.REMOVED :
+ buffer.append('-');
+ break;
+ case IJavaElementDelta.CHANGED :
+ buffer.append('*');
+ break;
+ default :
+ buffer.append('?');
+ break;
+ }
+ buffer.append("]: {"); //$NON-NLS-1$
+ toDebugString(buffer, getFlags());
+ buffer.append("}"); //$NON-NLS-1$
+ }
+
+ protected boolean toDebugString(StringBuffer buffer, int flags) {
+ boolean prev = false;
+ if ((flags & IJavaElementDelta.F_MODIFIERS) != 0) {
+ if (prev)
+ buffer.append(" | "); //$NON-NLS-1$
+ buffer.append("MODIFIERS CHANGED"); //$NON-NLS-1$
+ prev = true;
+ }
+ if ((flags & IJavaElementDelta.F_SUPER_TYPES) != 0) {
+ if (prev)
+ buffer.append(" | "); //$NON-NLS-1$
+ buffer.append("SUPER TYPES CHANGED"); //$NON-NLS-1$
+ prev = true;
+ }
+ return prev;
+ }
+
+ public String toString() {
+ StringBuffer buffer = new StringBuffer();
+ toDebugString(buffer);
+ return buffer.toString();
+ }
+}
*******************************************************************************/
package net.sourceforge.phpdt.internal.core;
+import net.sourceforge.phpdt.core.IJavaElement;
+import net.sourceforge.phpdt.internal.core.JavaElement;
+
import net.sourceforge.phpdt.core.IField;
import net.sourceforge.phpdt.core.IType;
import net.sourceforge.phpdt.core.JavaModelException;
/* 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);
-}
+ /**
+ * Constructs a handle to the field with the given name in the specified type.
+ */
+ protected SourceField(JavaElement parent, String name) {
+ super(parent, name);
+ }
+ public boolean equals(Object o) {
+ if (!(o instanceof SourceField)) return false;
+ return super.equals(o);
+ }
/**
* @see JavaElement#equalsDOMNode
*/
return info.initializationSource;
}
/**
+ * @see IJavaElement
+ */
+public int getElementType() {
+ return FIELD;
+}
+/**
* @see JavaElement#getHandleMemento()
*/
protected char getHandleMementoDelimiter() {
*******************************************************************************/
package net.sourceforge.phpdt.internal.core;
+import net.sourceforge.phpdt.internal.core.JavaElement;
+
+import net.sourceforge.phpdt.core.IJavaElement;
+
import net.sourceforge.phpdt.core.Flags;
import net.sourceforge.phpdt.core.ICompilationUnit;
import net.sourceforge.phpdt.core.IMethod;
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.core.util.Util;
import net.sourceforge.phpdt.internal.corext.Assert;
* An empty list of Strings
*/
protected static final String[] fgEmptyList= new String[] {};
-protected SourceMethod(IType parent, String name, String[] parameterTypes) {
- super(METHOD, parent, name);
- Assert.isTrue(name.indexOf('.') == -1);
- if (parameterTypes == null) {
- fParameterTypes= fgEmptyList;
- } else {
- fParameterTypes= parameterTypes;
+ protected SourceMethod(JavaElement parent, String name, String[] parameterTypes) {
+ super(parent, name);
+ Assert.isTrue(name.indexOf('.') == -1);
+ if (parameterTypes == null) {
+ fParameterTypes= fgEmptyList;
+ } else {
+ fParameterTypes= parameterTypes;
+ }
}
-}
-protected SourceMethod(ICompilationUnit parent, String name, String[] parameterTypes) {
- super(METHOD, parent, name);
- Assert.isTrue(name.indexOf('.') == -1);
- if (parameterTypes == null) {
- fParameterTypes= fgEmptyList;
- } else {
- fParameterTypes= parameterTypes;
+ public boolean equals(Object o) {
+ if (!(o instanceof SourceMethod)) return false;
+ return super.equals(o) && Util.equalArraysOrNull(fParameterTypes, ((SourceMethod)o).fParameterTypes);
}
-}
-public boolean equals(Object o) {
- return super.equals(o) && Util.equalArraysOrNull(fParameterTypes, ((SourceMethod)o).fParameterTypes);
-}
/**
* @see JavaElement#equalsDOMNode
*/
}
/**
+ * @see IJavaElement
+ */
+public int getElementType() {
+ return METHOD;
+}
+/**
* @see IMethod
*/
public String[] getExceptionTypes() throws JavaModelException {
*******************************************************************************/
package net.sourceforge.phpdt.internal.core;
+import java.util.HashMap;
+
import net.sourceforge.phpdt.core.IBuffer;
import net.sourceforge.phpdt.core.ICompilationUnit;
import net.sourceforge.phpdt.core.IJavaElement;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
+import net.sourceforge.phpdt.internal.core.JavaElementInfo;
+import net.sourceforge.phpdt.internal.core.JavaModelManager;
+import net.sourceforge.phpdt.internal.core.Openable;
+
+import net.sourceforge.phpdt.internal.core.JavaElement;
/**
* Abstract class for Java elements which implement ISourceReference.
*/
/* package */ abstract class SourceRefElement extends JavaElement implements ISourceReference {
-protected SourceRefElement(int type, IJavaElement parent, String name) {
- super(type, parent, name);
+ protected SourceRefElement(JavaElement parent, String name) {
+ super(parent, name);
+ }
+/**
+ * This element is being closed. Do any necessary cleanup.
+ */
+protected void closing(Object info) throws JavaModelException {
+ // Do any necessary cleanup
+}
+/**
+ * Returns a new element info for this element.
+ */
+protected Object createElementInfo() {
+ return null; // not used for source ref elements
}
/**
* @see ISourceManipulation
// IJavaElement[] elements = new IJavaElement[] {this};
// getJavaModel().delete(elements, force, monitor);
//}
+/*
+ * @see JavaElement#generateInfos
+ */
+protected void generateInfos(Object info, HashMap newElements, IProgressMonitor pm) throws JavaModelException {
+ Openable openableParent = (Openable)getOpenableParent();
+ if (openableParent == null) return;
+
+ JavaElementInfo openableParentInfo = (JavaElementInfo) JavaModelManager.getJavaModelManager().getInfo(openableParent);
+ if (openableParentInfo == null) {
+ openableParent.generateInfos(openableParent.createElementInfo(), newElements, pm);
+ }
+}
/**
* @see IMember
*/
import java.util.ArrayList;
+import net.sourceforge.phpdt.internal.core.SourceTypeElementInfo;
+
+import net.sourceforge.phpdt.internal.core.JavaElement;
+import net.sourceforge.phpdt.internal.core.util.Util;
+
import net.sourceforge.phpdt.core.IField;
import net.sourceforge.phpdt.core.IJavaElement;
import net.sourceforge.phpdt.core.IMember;
* An empty list of Strings
*/
protected static final String[] fgEmptyList= new String[] {};
-protected SourceType(IJavaElement parent, String name) {
- super(TYPE, parent, name);
- Assert.isTrue(name.indexOf('.') == -1);
-}
+ protected SourceType(JavaElement parent, String name) {
+ super(parent, name);
+ Assert.isTrue(name.indexOf('.') == -1, Util.bind("sourcetype.invalidName", name)); //$NON-NLS-1$
+ }
/**
* @see IType
*/
return null;
}
/**
+ * @see IJavaElement
+ */
+public int getElementType() {
+ return TYPE;
+}
+/**
* @see IType#getField
*/
public IField getField(String name) {
* @see IType
*/
public IPackageFragment getPackageFragment() {
- IJavaElement parent = fParent;
- while (parent != null) {
- if (parent.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
- return (IPackageFragment) parent;
+ IJavaElement parentElement = this.parent;
+ while (parentElement != null) {
+ if (parentElement.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
+ return (IPackageFragment)parentElement;
}
else {
- parent = parent.getParent();
+ parentElement = parentElement.getParent();
}
}
Assert.isTrue(false); // should not happen
return null;
}
+
/**
* @see IType
*/
}
return strings;
}
+
/**
* @see IType
*/
* @see IType#getTypeQualifiedName(char)
*/
public String getTypeQualifiedName(char enclosingTypeSeparator) {
- if (fParent.getElementType() == IJavaElement.COMPILATION_UNIT) {
- return fName;
+ if (parent.getElementType() == IJavaElement.COMPILATION_UNIT) {
+ return name;
} else {
- return ((IType) fParent).getTypeQualifiedName(enclosingTypeSeparator) + enclosingTypeSeparator + fName;
+ return ((IType) parent).getTypeQualifiedName(enclosingTypeSeparator) + enclosingTypeSeparator + name;
}
}
--- /dev/null
+/*******************************************************************************
+ * Copyright (c) 2000, 2004 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.PrintWriter;
+import java.io.Writer;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.HashMap;
+/**
+ * @since 3.0
+ */
+class XMLWriter extends PrintWriter {
+ /* constants */
+ private static final String XML_VERSION= "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; //$NON-NLS-1$
+ private static void appendEscapedChar(StringBuffer buffer, char c) {
+ String replacement= getReplacement(c);
+ if (replacement != null) {
+ buffer.append('&');
+ buffer.append(replacement);
+ buffer.append(';');
+ } else {
+ buffer.append(c);
+ }
+ }
+ private static String getEscaped(String s) {
+ StringBuffer result= new StringBuffer(s.length() + 10);
+ for (int i= 0; i < s.length(); ++i)
+ appendEscapedChar(result, s.charAt(i));
+ return result.toString();
+ }
+ private static String getReplacement(char c) {
+ // Encode special XML characters into the equivalent character references.
+ // These five are defined by default for all XML documents.
+ switch (c) {
+ case '<' :
+ return "lt"; //$NON-NLS-1$
+ case '>' :
+ return "gt"; //$NON-NLS-1$
+ case '"' :
+ return "quot"; //$NON-NLS-1$
+ case '\'' :
+ return "apos"; //$NON-NLS-1$
+ case '&' :
+ return "amp"; //$NON-NLS-1$
+ }
+ return null;
+ }
+ private int tab;
+ public XMLWriter(Writer writer) {
+ super(writer);
+ tab= 0;
+ println(XML_VERSION);
+ }
+ public void endTag(String name, boolean insertTab) {
+ tab--;
+ printTag('/' + name, null, insertTab, true, false);
+ }
+ private void printTabulation() {
+ for (int i= 0; i < tab; i++)
+ super.print('\t');
+ }
+ public void printTag(String name, HashMap parameters, boolean insertTab, boolean insertNewLine, boolean closeTag) {
+ StringBuffer sb= new StringBuffer();
+ sb.append("<"); //$NON-NLS-1$
+ sb.append(name);
+ if (parameters != null) {
+ for (Enumeration en = Collections.enumeration(parameters.keySet()); en.hasMoreElements();) {
+ sb.append(" "); //$NON-NLS-1$
+ String key= (String) en.nextElement();
+ sb.append(key);
+ sb.append("=\""); //$NON-NLS-1$
+ sb.append(getEscaped(String.valueOf(parameters.get(key))));
+ sb.append("\""); //$NON-NLS-1$
+ }
+ }
+ if (closeTag) {
+ sb.append("/>"); //$NON-NLS-1$
+ } else {
+ sb.append(">"); //$NON-NLS-1$
+ }
+ if (insertTab) {
+ printTabulation();
+ }
+ if (insertNewLine) {
+ println(sb.toString());
+ } else {
+ print(sb.toString());
+ }
+ }
+ public void startTag(String name, boolean insertTab) {
+ printTag(name, null, insertTab, true, false);
+ tab++;
+ }
+}
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.phpdt.internal.core.util.Util;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFolder;
import net.sourceforge.phpdt.core.JavaCore;
import net.sourceforge.phpdt.internal.core.JavaModelManager;
-import net.sourceforge.phpdt.internal.core.Util;
+import net.sourceforge.phpdt.internal.core.util.Util;
import net.sourceforge.phpeclipse.PHPeclipsePlugin;
import net.sourceforge.phpeclipse.builder.IdentifierIndexManager;
import org.eclipse.core.resources.IResourceProxyVisitor;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
+import net.sourceforge.phpdt.internal.core.builder.PHPBuilder;
+import net.sourceforge.phpdt.internal.core.builder.SourceFile;
public class BatchImageBuilder extends AbstractImageBuilder {
try {
notifier.subTask(Util.bind("build.cleaningOutput")); //$NON-NLS-1$
- JavaModelManager.getJavaModelManager().deltaProcessor.addForRefresh(javaBuilder.javaProject);
PHPBuilder.removeProblemsAndTasksFor(javaBuilder.currentProject);
-// cleanOutputFolders();
+// cleanOutputFolders(true);
notifier.updateProgressDelta(0.1f);
notifier.subTask(Util.bind("build.analyzingSources")); //$NON-NLS-1$
if (javaBuilder.javaProject.hasCycleMarker())
javaBuilder.mustPropagateStructuralChanges();
+
} catch (CoreException e) {
throw internalException(e);
} finally {
}
switch(proxy.getType()) {
case IResource.FILE :
- if (Util.isJavaFileName(proxy.getName())) {
+ if (net.sourceforge.phpdt.internal.compiler.util.Util.isJavaFileName(proxy.getName())) {
if (resource == null)
resource = proxy.requestResource();
sourceFiles.add(new SourceFile((IFile) resource, sourceLocation, encoding));
IResource resource = null;
switch(proxy.getType()) {
case IResource.FILE :
- if (Util.isJavaFileName(proxy.getName())) return false;// || Util.isClassFileName(proxy.getName())) return false;
+ if (net.sourceforge.phpdt.internal.compiler.util.Util.isJavaFileName(proxy.getName())) return false;// || Util.isClassFileName(proxy.getName())) return false;
resource = proxy.requestResource();
if (javaBuilder.filterExtraResource(resource)) return false;
import net.sourceforge.phpdt.core.compiler.IProblem;
import net.sourceforge.phpdt.internal.compiler.problem.AbortCompilation;
-import net.sourceforge.phpdt.internal.core.Util;
+import net.sourceforge.phpdt.internal.core.util.Util;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
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 net.sourceforge.phpdt.internal.core.util.Util;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IResource;
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 net.sourceforge.phpdt.internal.core.util.Util;
import net.sourceforge.phpdt.internal.ui.util.PHPFileUtil;
import net.sourceforge.phpeclipse.PHPeclipsePlugin;
import net.sourceforge.phpeclipse.builder.IdentifierIndexManager;
return;
case IResource.FILE :
String resourceName = resource.getName();
- if (Util.isJavaFileName(resourceName)) {
+ if (net.sourceforge.phpdt.internal.compiler.util.Util.isJavaFileName(resourceName)) {
IPath typePath = resource.getFullPath().removeFirstSegments(
segmentCount).removeFileExtension();
String typeLocator = resource.getProjectRelativePath().toString();
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.phpdt.internal.core.util.Util;
import net.sourceforge.phpdt.internal.ui.util.PHPFileUtil;
import net.sourceforge.phpeclipse.PHPeclipsePlugin;
import net.sourceforge.phpeclipse.builder.IdentifierIndexManager;
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 net.sourceforge.phpdt.internal.core.util.Util;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
--- /dev/null
+/*******************************************************************************
+ * 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 org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.IAdaptable;
+import org.eclipse.core.runtime.IAdapterFactory;
+
+import org.eclipse.ui.IContainmentAdapter;
+import org.eclipse.ui.IContributorResourceAdapter;
+import org.eclipse.ui.IPersistableElement;
+import org.eclipse.ui.model.IWorkbenchAdapter;
+import org.eclipse.ui.views.properties.FilePropertySource;
+import org.eclipse.ui.views.properties.IPropertySource;
+import org.eclipse.ui.views.properties.ResourcePropertySource;
+import org.eclipse.ui.views.tasklist.ITaskListResourceAdapter;
+
+import org.eclipse.search.ui.ISearchPageScoreComputer;
+
+import net.sourceforge.phpdt.core.ICompilationUnit;
+import net.sourceforge.phpdt.core.IJavaElement;
+import net.sourceforge.phpdt.core.IPackageFragmentRoot;
+
+import net.sourceforge.phpdt.internal.corext.util.JavaModelUtil;
+//import net.sourceforge.phpdt.internal.ui.search.JavaSearchPageScoreComputer;
+//import net.sourceforge.phpdt.internal.ui.search.SearchUtil;
+
+/**
+ * Implements basic UI support for Java elements.
+ * Implements handle to persistent support for Java elements.
+ */
+public class JavaElementAdapterFactory implements IAdapterFactory, IContributorResourceAdapter{
+
+ private static Class[] PROPERTIES= new Class[] {
+ IPropertySource.class,
+ IResource.class,
+// IWorkbenchAdapter.class,
+// IResourceLocator.class,
+ IPersistableElement.class,
+ IProject.class,
+ IContributorResourceAdapter.class,
+// ITaskListResourceAdapter.class,
+// IContainmentAdapter.class
+ };
+
+// private Object fSearchPageScoreComputer;
+// private static IResourceLocator fgResourceLocator= new ResourceLocator();
+// private static JavaWorkbenchAdapter fgJavaWorkbenchAdapter= new JavaWorkbenchAdapter();
+// private static ITaskListResourceAdapter fgTaskListAdapter= new JavaTaskListAdapter();
+// private static JavaElementContainmentAdapter fgJavaElementContainmentAdapter= new JavaElementContainmentAdapter();
+
+ public Class[] getAdapterList() {
+// updateLazyLoadedAdapters();
+ return PROPERTIES;
+ }
+
+ public Object getAdapter(Object element, Class key) {
+// updateLazyLoadedAdapters();
+ IJavaElement java= (IJavaElement) element;
+
+ if (IPropertySource.class.equals(key)) {
+ return getProperties(java);
+ } if (IResource.class.equals(key)) {
+ return getResource(java);
+ } if (IProject.class.equals(key)) {
+ return getProject(java);
+// } if (fSearchPageScoreComputer != null && ISearchPageScoreComputer.class.equals(key)) {
+// return fSearchPageScoreComputer;
+// } if (IWorkbenchAdapter.class.equals(key)) {
+// return fgJavaWorkbenchAdapter;
+// } if (IResourceLocator.class.equals(key)) {
+// return fgResourceLocator;
+// } if (IPersistableElement.class.equals(key)) {
+// return new PersistableJavaElementFactory(java);
+ } if (IContributorResourceAdapter.class.equals(key)) {
+ return this;
+// } if (ITaskListResourceAdapter.class.equals(key)) {
+// return fgTaskListAdapter;
+// } if (IContainmentAdapter.class.equals(key)) {
+// return fgJavaElementContainmentAdapter;
+ }
+ return null;
+ }
+
+ private IResource getResource(IJavaElement element) {
+ // can't use IJavaElement.getResource directly as we are interrested in the
+ // corresponding resource
+ switch (element.getElementType()) {
+ case IJavaElement.TYPE:
+ // top level types behave like the CU
+ IJavaElement parent= element.getParent();
+ if (parent instanceof ICompilationUnit) {
+ return JavaModelUtil.toOriginal((ICompilationUnit) parent).getResource();
+ }
+ return null;
+ case IJavaElement.COMPILATION_UNIT:
+ return JavaModelUtil.toOriginal((ICompilationUnit) element).getResource();
+ case IJavaElement.CLASS_FILE:
+ case IJavaElement.PACKAGE_FRAGMENT:
+ // test if in a archive
+ IPackageFragmentRoot root= (IPackageFragmentRoot) element.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
+ if (!root.isArchive()) {
+ return element.getResource();
+ }
+ return null;
+ case IJavaElement.PACKAGE_FRAGMENT_ROOT:
+ case IJavaElement.JAVA_PROJECT:
+ case IJavaElement.JAVA_MODEL:
+ return element.getResource();
+ default:
+ return null;
+ }
+ }
+
+ /*
+ * @see org.eclipse.ui.IContributorResourceAdapter#getAdaptedResource(org.eclipse.core.runtime.IAdaptable)
+ */
+ public IResource getAdaptedResource(IAdaptable adaptable) {
+ return getResource((IJavaElement)adaptable);
+ }
+
+ private IResource getProject(IJavaElement element) {
+ return element.getJavaProject().getProject();
+ }
+
+ private IPropertySource getProperties(IJavaElement element) {
+ IResource resource= getResource(element);
+ if (resource == null)
+// return new JavaElementProperties(element);
+ if (resource.getType() == IResource.FILE)
+ return new FilePropertySource((IFile) resource);
+ return new ResourcePropertySource(resource);
+ }
+
+// private void updateLazyLoadedAdapters() {
+// if (fSearchPageScoreComputer == null && SearchUtil.isSearchPlugInActivated())
+// createSearchPageScoreComputer();
+// }
+
+// private void createSearchPageScoreComputer() {
+// fSearchPageScoreComputer= new JavaSearchPageScoreComputer();
+// PROPERTIES= new Class[] {
+// IPropertySource.class,
+// IResource.class,
+// ISearchPageScoreComputer.class,
+// IWorkbenchAdapter.class,
+// IResourceLocator.class,
+// IPersistableElement.class,
+// IProject.class,
+// IContributorResourceAdapter.class,
+// ITaskListResourceAdapter.class,
+// IContainmentAdapter.class
+// };
+// }
+}
--- /dev/null
+/*******************************************************************************
+ * 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 org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.IAdapterFactory;
+
+import net.sourceforge.phpdt.core.IJavaElement;
+import net.sourceforge.phpdt.core.JavaCore;
+
+public class ResourceAdapterFactory implements IAdapterFactory {
+
+ private static Class[] PROPERTIES= new Class[] {
+ IJavaElement.class
+ };
+
+ public Class[] getAdapterList() {
+ return PROPERTIES;
+ }
+
+ public Object getAdapter(Object element, Class key) {
+ if (IJavaElement.class.equals(key)) {
+ return JavaCore.create((IResource)element);
+ }
+ return null;
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * 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.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+import net.sourceforge.phpdt.internal.ui.text.folding.JavaFoldingStructureProviderDescriptor;
+import net.sourceforge.phpdt.internal.ui.text.folding.JavaFoldingStructureProviderRegistry;
+import net.sourceforge.phpdt.internal.ui.util.PixelConverter;
+import net.sourceforge.phpdt.ui.PreferenceConstants;
+import net.sourceforge.phpdt.ui.text.folding.IJavaFoldingPreferenceBlock;
+import net.sourceforge.phpeclipse.PHPeclipsePlugin;
+
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.jface.text.Assert;
+import org.eclipse.jface.viewers.ComboViewer;
+import org.eclipse.jface.viewers.ISelectionChangedListener;
+import org.eclipse.jface.viewers.IStructuredContentProvider;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.viewers.LabelProvider;
+import org.eclipse.jface.viewers.SelectionChangedEvent;
+import org.eclipse.jface.viewers.StructuredSelection;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.StackLayout;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.events.SelectionListener;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.layout.FillLayout;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Combo;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Label;
+
+/**
+ * Configures Java Editor folding preferences.
+ *
+ * @since 3.0
+ */
+class FoldingConfigurationBlock {
+
+ private static class ErrorPreferences implements IJavaFoldingPreferenceBlock {
+ private String fMessage;
+
+ protected ErrorPreferences(String message) {
+ fMessage= message;
+ }
+
+ /*
+ * @see org.eclipse.jdt.internal.ui.text.folding.IJavaFoldingPreferences#createControl(org.eclipse.swt.widgets.Group)
+ */
+ public Control createControl(Composite composite) {
+ Composite inner= new Composite(composite, SWT.NONE);
+ inner.setLayout(new FillLayout(SWT.VERTICAL));
+
+ Label label= new Label(inner, SWT.CENTER);
+ label.setText(fMessage);
+
+ return inner;
+ }
+
+ public void initialize() {
+ }
+
+ public void performOk() {
+ }
+
+ public void performDefaults() {
+ }
+
+ public void dispose() {
+ }
+
+ }
+
+ /** The overlay preference store. */
+ private final OverlayPreferenceStore fStore;
+
+ /* The controls */
+ private Combo fProviderCombo;
+ private Button fFoldingCheckbox;
+ private ComboViewer fProviderViewer;
+ private Map fProviderDescriptors;
+ private Composite fGroup;
+ private Map fProviderPreferences;
+ private Map fProviderControls;
+ private StackLayout fStackLayout;
+
+
+ public FoldingConfigurationBlock(OverlayPreferenceStore store) {
+ Assert.isNotNull(store);
+ fStore= store;
+ fStore.addKeys(createOverlayStoreKeys());
+ fProviderDescriptors= createListModel();
+ fProviderPreferences= new HashMap();
+ fProviderControls= new HashMap();
+ }
+
+ private Map createListModel() {
+ JavaFoldingStructureProviderRegistry reg= PHPeclipsePlugin.getDefault().getFoldingStructureProviderRegistry();
+ reg.reloadExtensions();
+ JavaFoldingStructureProviderDescriptor[] descs= reg.getFoldingProviderDescriptors();
+ Map map= new HashMap();
+ for (int i= 0; i < descs.length; i++) {
+ map.put(descs[i].getId(), descs[i]);
+ }
+ return map;
+ }
+
+ private OverlayPreferenceStore.OverlayKey[] createOverlayStoreKeys() {
+
+ ArrayList overlayKeys= new ArrayList();
+
+ overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_FOLDING_ENABLED));
+ overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_FOLDING_PROVIDER));
+
+ OverlayPreferenceStore.OverlayKey[] keys= new OverlayPreferenceStore.OverlayKey[overlayKeys.size()];
+ overlayKeys.toArray(keys);
+ return keys;
+ }
+
+ /**
+ * Creates page for folding preferences.
+ *
+ * @param parent the parent composite
+ * @return the control for the preference page
+ */
+ Control createControl(Composite parent) {
+
+ Composite composite= new Composite(parent, SWT.NULL);
+ // assume parent page uses griddata
+ GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_CENTER | GridData.VERTICAL_ALIGN_FILL);
+ composite.setLayoutData(gd);
+ GridLayout layout= new GridLayout();
+ layout.numColumns= 2;
+ PixelConverter pc= new PixelConverter(composite);
+ layout.verticalSpacing= pc.convertHeightInCharsToPixels(1) / 2;
+ composite.setLayout(layout);
+
+
+ /* check box for new editors */
+ fFoldingCheckbox= new Button(composite, SWT.CHECK);
+ fFoldingCheckbox.setText(PreferencesMessages.getString("FoldingConfigurationBlock.enable")); //$NON-NLS-1$
+ gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING | GridData.VERTICAL_ALIGN_BEGINNING);
+ fFoldingCheckbox.setLayoutData(gd);
+ fFoldingCheckbox.addSelectionListener(new SelectionListener() {
+ public void widgetSelected(SelectionEvent e) {
+ boolean enabled= fFoldingCheckbox.getSelection();
+ fStore.setValue(PreferenceConstants.EDITOR_FOLDING_ENABLED, enabled);
+ updateCheckboxDependencies();
+ }
+
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ });
+
+ Label label= new Label(composite, SWT.CENTER);
+ gd= new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING);
+ label.setLayoutData(gd);
+
+ /* list */
+ Composite comboComp= new Composite(composite, SWT.NONE);
+ gd= new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING);
+ GridLayout gridLayout= new GridLayout(2, false);
+ gridLayout.marginWidth= 0;
+ comboComp.setLayout(gridLayout);
+
+ Label comboLabel= new Label(comboComp, SWT.CENTER);
+ gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING | GridData.VERTICAL_ALIGN_CENTER);
+ comboLabel.setLayoutData(gd);
+ comboLabel.setText(PreferencesMessages.getString("FoldingConfigurationBlock.combo_caption")); //$NON-NLS-1$
+
+ label= new Label(composite, SWT.CENTER);
+ gd= new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING);
+ label.setLayoutData(gd);
+
+ fProviderCombo= new Combo(comboComp, SWT.READ_ONLY | SWT.DROP_DOWN);
+ gd= new GridData(GridData.HORIZONTAL_ALIGN_END | GridData.VERTICAL_ALIGN_CENTER);
+ fProviderCombo.setLayoutData(gd);
+
+ /* list viewer */
+ fProviderViewer= new ComboViewer(fProviderCombo);
+ fProviderViewer.setContentProvider(new IStructuredContentProvider() {
+
+ /*
+ * @see org.eclipse.jface.viewers.IContentProvider#dispose()
+ */
+ public void dispose() {
+ }
+
+ /*
+ * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object)
+ */
+ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
+ }
+
+ /*
+ * @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object)
+ */
+ public Object[] getElements(Object inputElement) {
+ return fProviderDescriptors.values().toArray();
+ }
+ });
+ fProviderViewer.setLabelProvider(new LabelProvider() {
+ /*
+ * @see org.eclipse.jface.viewers.LabelProvider#getImage(java.lang.Object)
+ */
+ public Image getImage(Object element) {
+ return null;
+ }
+
+ /*
+ * @see org.eclipse.jface.viewers.LabelProvider#getText(java.lang.Object)
+ */
+ public String getText(Object element) {
+ return ((JavaFoldingStructureProviderDescriptor) element).getName();
+ }
+ });
+ fProviderViewer.addSelectionChangedListener(new ISelectionChangedListener() {
+
+ public void selectionChanged(SelectionChangedEvent event) {
+ IStructuredSelection sel= (IStructuredSelection) event.getSelection();
+ if (!sel.isEmpty()) {
+ fStore.setValue(PreferenceConstants.EDITOR_FOLDING_PROVIDER, ((JavaFoldingStructureProviderDescriptor) sel.getFirstElement()).getId());
+ updateListDependencies();
+ }
+ }
+ });
+ fProviderViewer.setInput(fProviderDescriptors);
+ fProviderViewer.refresh();
+
+ Composite groupComp= new Composite(composite, SWT.NONE);
+ gd= new GridData(GridData.FILL_BOTH);
+ gd.horizontalSpan= 2;
+ groupComp.setLayoutData(gd);
+ gridLayout= new GridLayout(1, false);
+ gridLayout.marginWidth= 0;
+ groupComp.setLayout(gridLayout);
+
+ /* contributed provider preferences. */
+ fGroup= new Composite(groupComp, SWT.NONE);
+ gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING | GridData.VERTICAL_ALIGN_BEGINNING);
+ fGroup.setLayoutData(gd);
+ fStackLayout= new StackLayout();
+ fGroup.setLayout(fStackLayout);
+
+ return composite;
+ }
+
+ private void updateCheckboxDependencies() {
+ }
+
+ void updateListDependencies() {
+ String id= fStore.getString(PreferenceConstants.EDITOR_FOLDING_PROVIDER);
+ JavaFoldingStructureProviderDescriptor desc= (JavaFoldingStructureProviderDescriptor) fProviderDescriptors.get(id);
+ IJavaFoldingPreferenceBlock prefs;
+
+ if (desc == null) {
+ // safety in case there is no such descriptor
+ String message= PreferencesMessages.getString("FoldingConfigurationBlock.error.not_exist"); //$NON-NLS-1$
+ PHPeclipsePlugin.log(new Status(IStatus.WARNING, PHPeclipsePlugin.getPluginId(), IStatus.OK, message, null));
+ prefs= new ErrorPreferences(message);
+ } else {
+ prefs= (IJavaFoldingPreferenceBlock) fProviderPreferences.get(id);
+ if (prefs == null) {
+ try {
+ prefs= desc.createPreferences();
+ fProviderPreferences.put(id, prefs);
+ } catch (CoreException e) {
+ PHPeclipsePlugin.log(e);
+ prefs= new ErrorPreferences(e.getLocalizedMessage());
+ }
+ }
+ }
+
+ Control control= (Control) fProviderControls.get(id);
+ if (control == null) {
+ control= prefs.createControl(fGroup);
+ if (control == null) {
+ String message= PreferencesMessages.getString("FoldingConfigurationBlock.info.no_preferences"); //$NON-NLS-1$
+ control= new ErrorPreferences(message).createControl(fGroup);
+ } else {
+ fProviderControls.put(id, control);
+ }
+ }
+ fStackLayout.topControl= control;
+ control.pack();
+ fGroup.layout();
+ fGroup.getParent().layout();
+
+ prefs.initialize();
+ }
+
+ void initialize() {
+ restoreFromPreferences();
+ }
+
+ void performOk() {
+ for (Iterator it= fProviderPreferences.values().iterator(); it.hasNext();) {
+ IJavaFoldingPreferenceBlock prefs= (IJavaFoldingPreferenceBlock) it.next();
+ prefs.performOk();
+ }
+ }
+
+ void performDefaults() {
+ restoreFromPreferences();
+ for (Iterator it= fProviderPreferences.values().iterator(); it.hasNext();) {
+ IJavaFoldingPreferenceBlock prefs= (IJavaFoldingPreferenceBlock) it.next();
+ prefs.performDefaults();
+ }
+ }
+
+ void dispose() {
+ for (Iterator it= fProviderPreferences.values().iterator(); it.hasNext();) {
+ IJavaFoldingPreferenceBlock prefs= (IJavaFoldingPreferenceBlock) it.next();
+ prefs.dispose();
+ }
+ }
+
+ private void restoreFromPreferences() {
+ boolean enabled= fStore.getBoolean(PreferenceConstants.EDITOR_FOLDING_ENABLED);
+ fFoldingCheckbox.setSelection(enabled);
+ updateCheckboxDependencies();
+
+ String id= fStore.getString(PreferenceConstants.EDITOR_FOLDING_PROVIDER);
+ Object provider= fProviderDescriptors.get(id);
+ if (provider != null) {
+ fProviderViewer.setSelection(new StructuredSelection(provider), true);
+ updateListDependencies();
+ }
+ }
+}
import java.util.SortedSet;
import java.util.StringTokenizer;
import java.util.TreeSet;
+
import net.sourceforge.phpdt.core.JavaCore;
import net.sourceforge.phpdt.internal.ui.IJavaHelpContextIds;
import net.sourceforge.phpdt.internal.ui.dialogs.StatusInfo;
import net.sourceforge.phpdt.internal.ui.dialogs.StatusUtil;
+import net.sourceforge.phpdt.internal.ui.text.PreferencesAdapter;
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.phpeditor.JavaSourceViewer;
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.action.Action;
+import net.sourceforge.phpdt.internal.ui.preferences.FoldingConfigurationBlock;
+import net.sourceforge.phpdt.internal.ui.preferences.PreferencesMessages;
import org.eclipse.jface.dialogs.Dialog;
+import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.swt.SWT;
-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.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
+import org.eclipse.ui.editors.text.EditorsUI;
import org.eclipse.ui.help.WorkbenchHelp;
+import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants;
import org.eclipse.ui.texteditor.AnnotationPreference;
-import org.eclipse.ui.texteditor.ExtendedTextEditorPreferenceConstants;
+import org.eclipse.ui.texteditor.ChainedPreferenceStore;
import org.eclipse.ui.texteditor.MarkerAnnotationPreferences;
/**
* The page for setting the editor options.
{
PreferencesMessages
.getString("JavaEditorPreferencePage.lineNumberForegroundColor"),
- ExtendedTextEditorPreferenceConstants.EDITOR_LINE_NUMBER_RULER_COLOR},
+ AbstractDecoratedTextEditorPreferenceConstants.EDITOR_LINE_NUMBER_RULER_COLOR},
//$NON-NLS-1$
{
PreferencesMessages
{
PreferencesMessages
.getString("JavaEditorPreferencePage.currentLineHighlighColor"),
- ExtendedTextEditorPreferenceConstants.EDITOR_CURRENT_LINE_COLOR},
+ AbstractDecoratedTextEditorPreferenceConstants.EDITOR_CURRENT_LINE_COLOR},
//$NON-NLS-1$
{
PreferencesMessages
.getString("JavaEditorPreferencePage.printMarginColor2"),
- ExtendedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLOR},
+ AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLOR},
//$NON-NLS-1$
{
PreferencesMessages
{PreferencesMessages.getString("JavaEditorPreferencePage.linkColor2"),
PreferenceConstants.EDITOR_LINK_COLOR}, //$NON-NLS-1$
};
- private final String[][] fAnnotationColorListModel;
+// private final String[][] fAnnotationColorListModel;
private final String[][] fContentAssistColorListModel = new String[][]{
{
PreferencesMessages
.getString("JavaEditorPreferencePage.foregroundForCompletionReplacement"),
PreferenceConstants.CODEASSIST_REPLACEMENT_FOREGROUND} //$NON-NLS-1$
};
- private final String[][] fAnnotationDecorationListModel = new String[][]{
- {
- PreferencesMessages
- .getString("JavaEditorPreferencePage.AnnotationDecoration.NONE"),
- AnnotationPreference.STYLE_NONE},
- //$NON-NLS-1$
- {
- PreferencesMessages
- .getString("JavaEditorPreferencePage.AnnotationDecoration.SQUIGGLIES"),
- AnnotationPreference.STYLE_SQUIGGLIES},
- //$NON-NLS-1$
- {
- PreferencesMessages
- .getString("JavaEditorPreferencePage.AnnotationDecoration.UNDERLINE"),
- AnnotationPreference.STYLE_UNDERLINE},
- //$NON-NLS-1$
- {
- PreferencesMessages
- .getString("JavaEditorPreferencePage.AnnotationDecoration.BOX"),
- AnnotationPreference.STYLE_BOX},
- //$NON-NLS-1$
- {
- PreferencesMessages
- .getString("JavaEditorPreferencePage.AnnotationDecoration.IBEAM"),
- AnnotationPreference.STYLE_IBEAM} //$NON-NLS-1$
- };
+// private final String[][] fAnnotationDecorationListModel = new String[][]{
+// {
+// PreferencesMessages
+// .getString("JavaEditorPreferencePage.AnnotationDecoration.NONE"),
+// AnnotationPreference.STYLE_NONE},
+// //$NON-NLS-1$
+// {
+// PreferencesMessages
+// .getString("JavaEditorPreferencePage.AnnotationDecoration.SQUIGGLIES"),
+// AnnotationPreference.STYLE_SQUIGGLIES},
+// //$NON-NLS-1$
+// {
+// PreferencesMessages
+// .getString("JavaEditorPreferencePage.AnnotationDecoration.UNDERLINE"),
+// AnnotationPreference.STYLE_UNDERLINE},
+// //$NON-NLS-1$
+// {
+// PreferencesMessages
+// .getString("JavaEditorPreferencePage.AnnotationDecoration.BOX"),
+// AnnotationPreference.STYLE_BOX},
+// //$NON-NLS-1$
+// {
+// PreferencesMessages
+// .getString("JavaEditorPreferencePage.AnnotationDecoration.IBEAM"),
+// AnnotationPreference.STYLE_IBEAM} //$NON-NLS-1$
+// };
private OverlayPreferenceStore fOverlayStore;
private JavaTextTools fJavaTextTools;
private JavaEditorHoverConfigurationBlock fJavaEditorHoverConfigurationBlock;
+ private FoldingConfigurationBlock fFoldingConfigurationBlock;
+
private Map fColorButtons = new HashMap();
private Map fCheckBoxes = new HashMap();
private SelectionListener fCheckBoxListener = new SelectionListener() {
MarkerAnnotationPreferences markerAnnotationPreferences = new MarkerAnnotationPreferences();
fKeys = createOverlayStoreKeys(markerAnnotationPreferences);
fOverlayStore = new OverlayPreferenceStore(getPreferenceStore(), fKeys);
- fAnnotationColorListModel = createAnnotationTypeListModel(markerAnnotationPreferences);
+// fAnnotationColorListModel = createAnnotationTypeListModel(markerAnnotationPreferences);
}
private OverlayPreferenceStore.OverlayKey[] createOverlayStoreKeys(
MarkerAnnotationPreferences preferences) {
PreferenceConstants.EDITOR_MATCHING_BRACKETS));
overlayKeys.add(new OverlayPreferenceStore.OverlayKey(
OverlayPreferenceStore.STRING,
- ExtendedTextEditorPreferenceConstants.EDITOR_CURRENT_LINE_COLOR));
+ AbstractDecoratedTextEditorPreferenceConstants.EDITOR_CURRENT_LINE_COLOR));
overlayKeys.add(new OverlayPreferenceStore.OverlayKey(
OverlayPreferenceStore.BOOLEAN,
- ExtendedTextEditorPreferenceConstants.EDITOR_CURRENT_LINE));
+ AbstractDecoratedTextEditorPreferenceConstants.EDITOR_CURRENT_LINE));
overlayKeys.add(new OverlayPreferenceStore.OverlayKey(
OverlayPreferenceStore.STRING,
- ExtendedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLOR));
+ AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLOR));
overlayKeys.add(new OverlayPreferenceStore.OverlayKey(
OverlayPreferenceStore.INT,
- ExtendedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN));
+ AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN));
overlayKeys.add(new OverlayPreferenceStore.OverlayKey(
OverlayPreferenceStore.BOOLEAN,
- ExtendedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN));
+ AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN));
// overlayKeys.add(new
// OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN,
// PreferenceConstants.EDITOR_MARK_OCCURRENCES));
PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS));
overlayKeys.add(new OverlayPreferenceStore.OverlayKey(
OverlayPreferenceStore.BOOLEAN,
- ExtendedTextEditorPreferenceConstants.EDITOR_OVERVIEW_RULER));
+ AbstractDecoratedTextEditorPreferenceConstants.EDITOR_OVERVIEW_RULER));
overlayKeys.add(new OverlayPreferenceStore.OverlayKey(
OverlayPreferenceStore.STRING,
- ExtendedTextEditorPreferenceConstants.EDITOR_LINE_NUMBER_RULER_COLOR));
+ AbstractDecoratedTextEditorPreferenceConstants.EDITOR_LINE_NUMBER_RULER_COLOR));
overlayKeys.add(new OverlayPreferenceStore.OverlayKey(
OverlayPreferenceStore.BOOLEAN,
- ExtendedTextEditorPreferenceConstants.EDITOR_LINE_NUMBER_RULER));
+ AbstractDecoratedTextEditorPreferenceConstants.EDITOR_LINE_NUMBER_RULER));
overlayKeys.add(new OverlayPreferenceStore.OverlayKey(
OverlayPreferenceStore.BOOLEAN,
PreferenceConstants.EDITOR_SPACES_FOR_TABS));
RGB rgb = PreferenceConverter.getColor(fOverlayStore, key);
fContentAssistColorEditor.setColorValue(rgb);
}
- private void handleAnnotationListSelection() {
- int i = fAnnotationList.getSelectionIndex();
- String key = fAnnotationColorListModel[i][1];
- RGB rgb = PreferenceConverter.getColor(fOverlayStore, key);
- fAnnotationForegroundColorEditor.setColorValue(rgb);
- key = fAnnotationColorListModel[i][2];
- boolean showInText = fOverlayStore.getBoolean(key);
- fShowInTextCheckBox.setSelection(showInText);
- key = fAnnotationColorListModel[i][6];
- if (key != null) {
- fDecorationStyleCombo.setEnabled(showInText);
- for (int j = 0; j < fAnnotationDecorationListModel.length; j++) {
- String value = fOverlayStore.getString(key);
- if (fAnnotationDecorationListModel[j][1].equals(value)) {
- fDecorationStyleCombo.setText(fAnnotationDecorationListModel[j][0]);
- break;
- }
- }
- } else {
- fDecorationStyleCombo.setEnabled(false);
- fDecorationStyleCombo.setText(fAnnotationDecorationListModel[1][0]); // set
- // selection
- // to
- // squigglies
- // if
- // the
- // key
- // is
- // not
- // there
- // (legacy
- // support)
- }
- key = fAnnotationColorListModel[i][3];
- fShowInOverviewRulerCheckBox.setSelection(fOverlayStore.getBoolean(key));
- key = fAnnotationColorListModel[i][4];
- if (key != null) {
- fHighlightInTextCheckBox.setSelection(fOverlayStore.getBoolean(key));
- fHighlightInTextCheckBox.setEnabled(true);
- } else
- fHighlightInTextCheckBox.setEnabled(false);
- key = fAnnotationColorListModel[i][5];
- if (key != null) {
- fShowInVerticalRulerCheckBox.setSelection(fOverlayStore.getBoolean(key));
- fShowInVerticalRulerCheckBox.setEnabled(true);
- } else {
- fShowInVerticalRulerCheckBox.setSelection(true);
- fShowInVerticalRulerCheckBox.setEnabled(false);
- }
- }
+// private void handleAnnotationListSelection() {
+// int i = fAnnotationList.getSelectionIndex();
+// String key = fAnnotationColorListModel[i][1];
+// RGB rgb = PreferenceConverter.getColor(fOverlayStore, key);
+// fAnnotationForegroundColorEditor.setColorValue(rgb);
+// key = fAnnotationColorListModel[i][2];
+// boolean showInText = fOverlayStore.getBoolean(key);
+// fShowInTextCheckBox.setSelection(showInText);
+// key = fAnnotationColorListModel[i][6];
+// if (key != null) {
+// fDecorationStyleCombo.setEnabled(showInText);
+// for (int j = 0; j < fAnnotationDecorationListModel.length; j++) {
+// String value = fOverlayStore.getString(key);
+// if (fAnnotationDecorationListModel[j][1].equals(value)) {
+// fDecorationStyleCombo.setText(fAnnotationDecorationListModel[j][0]);
+// break;
+// }
+// }
+// } else {
+// fDecorationStyleCombo.setEnabled(false);
+// fDecorationStyleCombo.setText(fAnnotationDecorationListModel[1][0]); // set
+// // selection
+// // to
+// // squigglies
+// // if
+// // the
+// // key
+// // is
+// // not
+// // there
+// // (legacy
+// // support)
+// }
+// key = fAnnotationColorListModel[i][3];
+// fShowInOverviewRulerCheckBox.setSelection(fOverlayStore.getBoolean(key));
+// key = fAnnotationColorListModel[i][4];
+// if (key != null) {
+// fHighlightInTextCheckBox.setSelection(fOverlayStore.getBoolean(key));
+// fHighlightInTextCheckBox.setEnabled(true);
+// } else
+// fHighlightInTextCheckBox.setEnabled(false);
+// key = fAnnotationColorListModel[i][5];
+// if (key != null) {
+// fShowInVerticalRulerCheckBox.setSelection(fOverlayStore.getBoolean(key));
+// fShowInVerticalRulerCheckBox.setEnabled(true);
+// } else {
+// fShowInVerticalRulerCheckBox.setSelection(true);
+// fShowInVerticalRulerCheckBox.setEnabled(false);
+// }
+// }
private Control createSyntaxPage(Composite parent) {
Composite colorComposite = new Composite(parent, SWT.NULL);
colorComposite.setLayout(new GridLayout());
private Control createPreviewer(Composite parent) {
Preferences coreStore = createTemporaryCorePreferenceStore();
fJavaTextTools = new JavaTextTools(fOverlayStore, coreStore, false);
- fPreviewViewer = new JavaSourceViewer(parent, null, null, false,
- SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER);
+ IPreferenceStore generalTextStore= EditorsUI.getPreferenceStore();
+ IPreferenceStore store= new ChainedPreferenceStore(new IPreferenceStore[] { fOverlayStore, new PreferencesAdapter(createTemporaryCorePreferenceStore()), generalTextStore });
+
+ fPreviewViewer= new JavaSourceViewer(parent, null, null, false, SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER, store);
+
fPreviewViewer.configure(new PHPSourceViewerConfiguration(fJavaTextTools,
null));
// Font font= JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT);
fPreviewViewer.setEditable(false);
String content = loadPreviewContentFromFile("ColorSettingPreviewCode.txt"); //$NON-NLS-1$
IDocument document = new Document(content);
- fJavaTextTools.setupJavaDocumentPartitioner(document, ".php"); //IJavaPartitions.JAVA_PARTITIONING);
+ fJavaTextTools.setupJavaDocumentPartitioner(document, ".php", null); //IJavaPartitions.JAVA_PARTITIONING);
fPreviewViewer.setDocument(document);
return fPreviewViewer.getControl();
}
label = PreferencesMessages
.getString("JavaEditorPreferencePage.printMarginColumn"); //$NON-NLS-1$
addTextField(appearanceComposite, label,
- ExtendedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN, 3, 0,
+ AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN, 3, 0,
true);
label = PreferencesMessages
.getString("JavaEditorPreferencePage.showOverviewRuler"); //$NON-NLS-1$
addCheckBox(appearanceComposite, label,
- ExtendedTextEditorPreferenceConstants.EDITOR_OVERVIEW_RULER, 0);
+ AbstractDecoratedTextEditorPreferenceConstants.EDITOR_OVERVIEW_RULER, 0);
label = PreferencesMessages
.getString("JavaEditorPreferencePage.showLineNumbers"); //$NON-NLS-1$
addCheckBox(appearanceComposite, label,
- ExtendedTextEditorPreferenceConstants.EDITOR_LINE_NUMBER_RULER, 0);
+ AbstractDecoratedTextEditorPreferenceConstants.EDITOR_LINE_NUMBER_RULER, 0);
label = PreferencesMessages
.getString("JavaEditorPreferencePage.highlightMatchingBrackets"); //$NON-NLS-1$
addCheckBox(appearanceComposite, label,
label = PreferencesMessages
.getString("JavaEditorPreferencePage.highlightCurrentLine"); //$NON-NLS-1$
addCheckBox(appearanceComposite, label,
- ExtendedTextEditorPreferenceConstants.EDITOR_CURRENT_LINE, 0);
+ AbstractDecoratedTextEditorPreferenceConstants.EDITOR_CURRENT_LINE, 0);
label = PreferencesMessages
.getString("JavaEditorPreferencePage.showPrintMargin"); //$NON-NLS-1$
addCheckBox(appearanceComposite, label,
- ExtendedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN, 0);
+ AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN, 0);
label = PreferencesMessages
.getString("JavaEditorPreferencePage.markOccurrences"); //$NON-NLS-1$
// Button master= addCheckBox(appearanceComposite, label,
});
return appearanceComposite;
}
- private Control createAnnotationsPage(Composite parent) {
- Composite composite = new Composite(parent, SWT.NULL);
- GridLayout layout = new GridLayout();
- layout.numColumns = 2;
- composite.setLayout(layout);
- String text = PreferencesMessages
- .getString("JavaEditorPreferencePage.analyseAnnotationsWhileTyping"); //$NON-NLS-1$
- addCheckBox(composite, text,
- PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS, 0);
- text = PreferencesMessages
- .getString("JavaEditorPreferencePage.showQuickFixables"); //$NON-NLS-1$
- addCheckBox(composite, text,
- PreferenceConstants.EDITOR_CORRECTION_INDICATION, 0);
- addFiller(composite);
- Label label = new Label(composite, SWT.LEFT);
- label.setText(PreferencesMessages
- .getString("JavaEditorPreferencePage.annotationPresentationOptions")); //$NON-NLS-1$
- GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
- gd.horizontalSpan = 2;
- label.setLayoutData(gd);
- Composite editorComposite = new Composite(composite, SWT.NONE);
- layout = new GridLayout();
- layout.numColumns = 2;
- layout.marginHeight = 0;
- layout.marginWidth = 0;
- editorComposite.setLayout(layout);
- gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.FILL_VERTICAL);
- gd.horizontalSpan = 2;
- editorComposite.setLayoutData(gd);
- fAnnotationList = new List(editorComposite, SWT.SINGLE | SWT.V_SCROLL
- | SWT.BORDER);
- gd = new GridData(GridData.VERTICAL_ALIGN_BEGINNING
- | GridData.FILL_HORIZONTAL);
- gd.heightHint = convertHeightInCharsToPixels(10);
- fAnnotationList.setLayoutData(gd);
- Composite optionsComposite = new Composite(editorComposite, SWT.NONE);
- layout = new GridLayout();
- layout.marginHeight = 0;
- layout.marginWidth = 0;
- layout.numColumns = 2;
- optionsComposite.setLayout(layout);
- optionsComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
- fShowInTextCheckBox = new Button(optionsComposite, SWT.CHECK);
- fShowInTextCheckBox.setText(PreferencesMessages
- .getString("JavaEditorPreferencePage.annotations.showInText")); //$NON-NLS-1$
- gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalAlignment = GridData.BEGINNING;
- gd.horizontalSpan = 2;
- fShowInTextCheckBox.setLayoutData(gd);
- fDecorationStyleCombo = new Combo(optionsComposite, SWT.READ_ONLY);
- for (int i = 0; i < fAnnotationDecorationListModel.length; i++)
- fDecorationStyleCombo.add(fAnnotationDecorationListModel[i][0]);
- gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalAlignment = GridData.BEGINNING;
- gd.horizontalSpan = 2;
- gd.horizontalIndent = 20;
- fDecorationStyleCombo.setLayoutData(gd);
- fHighlightInTextCheckBox = new Button(optionsComposite, SWT.CHECK);
- fHighlightInTextCheckBox.setText(PreferencesMessages
- .getString("TextEditorPreferencePage.annotations.highlightInText")); //$NON-NLS-1$
- gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalAlignment = GridData.BEGINNING;
- gd.horizontalSpan = 2;
- fHighlightInTextCheckBox.setLayoutData(gd);
- fShowInOverviewRulerCheckBox = new Button(optionsComposite, SWT.CHECK);
- fShowInOverviewRulerCheckBox.setText(PreferencesMessages
- .getString("JavaEditorPreferencePage.annotations.showInOverviewRuler")); //$NON-NLS-1$
- gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalAlignment = GridData.BEGINNING;
- gd.horizontalSpan = 2;
- fShowInOverviewRulerCheckBox.setLayoutData(gd);
- fShowInVerticalRulerCheckBox = new Button(optionsComposite, SWT.CHECK);
- fShowInVerticalRulerCheckBox.setText(PreferencesMessages
- .getString("JavaEditorPreferencePage.annotations.showInVerticalRuler")); //$NON-NLS-1$
- gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalAlignment = GridData.BEGINNING;
- gd.horizontalSpan = 2;
- fShowInVerticalRulerCheckBox.setLayoutData(gd);
- label = new Label(optionsComposite, SWT.LEFT);
- label.setText(PreferencesMessages
- .getString("JavaEditorPreferencePage.annotations.color")); //$NON-NLS-1$
- gd = new GridData();
- gd.horizontalAlignment = GridData.BEGINNING;
- label.setLayoutData(gd);
- fAnnotationForegroundColorEditor = new ColorEditor(optionsComposite);
- Button foregroundColorButton = fAnnotationForegroundColorEditor.getButton();
- gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalAlignment = GridData.BEGINNING;
- foregroundColorButton.setLayoutData(gd);
- fAnnotationList.addSelectionListener(new SelectionListener() {
- public void widgetDefaultSelected(SelectionEvent e) {
- // do nothing
- }
- public void widgetSelected(SelectionEvent e) {
- handleAnnotationListSelection();
- }
- });
- fShowInTextCheckBox.addSelectionListener(new SelectionListener() {
- public void widgetDefaultSelected(SelectionEvent e) {
- // do nothing
- }
- public void widgetSelected(SelectionEvent e) {
- int i = fAnnotationList.getSelectionIndex();
- String key = fAnnotationColorListModel[i][2];
- fOverlayStore.setValue(key, fShowInTextCheckBox.getSelection());
- String decorationKey = fAnnotationColorListModel[i][6];
- fDecorationStyleCombo.setEnabled(decorationKey != null
- && fShowInTextCheckBox.getSelection());
- }
- });
- fHighlightInTextCheckBox.addSelectionListener(new SelectionListener() {
- public void widgetDefaultSelected(SelectionEvent e) {
- // do nothing
- }
- public void widgetSelected(SelectionEvent e) {
- int i = fAnnotationList.getSelectionIndex();
- String key = fAnnotationColorListModel[i][4];
- fOverlayStore.setValue(key, fHighlightInTextCheckBox.getSelection());
- }
- });
- fShowInOverviewRulerCheckBox.addSelectionListener(new SelectionListener() {
- public void widgetDefaultSelected(SelectionEvent e) {
- // do nothing
- }
- public void widgetSelected(SelectionEvent e) {
- int i = fAnnotationList.getSelectionIndex();
- String key = fAnnotationColorListModel[i][3];
- fOverlayStore
- .setValue(key, fShowInOverviewRulerCheckBox.getSelection());
- }
- });
- fShowInVerticalRulerCheckBox.addSelectionListener(new SelectionListener() {
- public void widgetDefaultSelected(SelectionEvent e) {
- // do nothing
- }
- public void widgetSelected(SelectionEvent e) {
- int i = fAnnotationList.getSelectionIndex();
- String key = fAnnotationColorListModel[i][5];
- fOverlayStore
- .setValue(key, fShowInVerticalRulerCheckBox.getSelection());
- }
- });
- foregroundColorButton.addSelectionListener(new SelectionListener() {
- public void widgetDefaultSelected(SelectionEvent e) {
- // do nothing
- }
- public void widgetSelected(SelectionEvent e) {
- int i = fAnnotationList.getSelectionIndex();
- String key = fAnnotationColorListModel[i][1];
- PreferenceConverter.setValue(fOverlayStore, key,
- fAnnotationForegroundColorEditor.getColorValue());
- }
- });
- fDecorationStyleCombo.addSelectionListener(new SelectionListener() {
- /**
- * {@inheritdoc}
- */
- public void widgetDefaultSelected(SelectionEvent e) {
- // do nothing
- }
- /**
- * {@inheritdoc}
- */
- public void widgetSelected(SelectionEvent e) {
- int i = fAnnotationList.getSelectionIndex();
- String key = fAnnotationColorListModel[i][6];
- if (key != null) {
- for (int j = 0; j < fAnnotationDecorationListModel.length; j++) {
- if (fAnnotationDecorationListModel[j][0]
- .equals(fDecorationStyleCombo.getText())) {
- fOverlayStore.setValue(key, fAnnotationDecorationListModel[j][1]);
- break;
- }
- }
- }
- }
- });
- return composite;
- }
+// private Control createAnnotationsPage(Composite parent) {
+// Composite composite = new Composite(parent, SWT.NULL);
+// GridLayout layout = new GridLayout();
+// layout.numColumns = 2;
+// composite.setLayout(layout);
+// String text = PreferencesMessages
+// .getString("JavaEditorPreferencePage.analyseAnnotationsWhileTyping"); //$NON-NLS-1$
+// addCheckBox(composite, text,
+// PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS, 0);
+// text = PreferencesMessages
+// .getString("JavaEditorPreferencePage.showQuickFixables"); //$NON-NLS-1$
+// addCheckBox(composite, text,
+// PreferenceConstants.EDITOR_CORRECTION_INDICATION, 0);
+// addFiller(composite);
+// Label label = new Label(composite, SWT.LEFT);
+// label.setText(PreferencesMessages
+// .getString("JavaEditorPreferencePage.annotationPresentationOptions")); //$NON-NLS-1$
+// GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
+// gd.horizontalSpan = 2;
+// label.setLayoutData(gd);
+// Composite editorComposite = new Composite(composite, SWT.NONE);
+// layout = new GridLayout();
+// layout.numColumns = 2;
+// layout.marginHeight = 0;
+// layout.marginWidth = 0;
+// editorComposite.setLayout(layout);
+// gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.FILL_VERTICAL);
+// gd.horizontalSpan = 2;
+// editorComposite.setLayoutData(gd);
+// fAnnotationList = new List(editorComposite, SWT.SINGLE | SWT.V_SCROLL
+// | SWT.BORDER);
+// gd = new GridData(GridData.VERTICAL_ALIGN_BEGINNING
+// | GridData.FILL_HORIZONTAL);
+// gd.heightHint = convertHeightInCharsToPixels(10);
+// fAnnotationList.setLayoutData(gd);
+// Composite optionsComposite = new Composite(editorComposite, SWT.NONE);
+// layout = new GridLayout();
+// layout.marginHeight = 0;
+// layout.marginWidth = 0;
+// layout.numColumns = 2;
+// optionsComposite.setLayout(layout);
+// optionsComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
+// fShowInTextCheckBox = new Button(optionsComposite, SWT.CHECK);
+// fShowInTextCheckBox.setText(PreferencesMessages
+// .getString("JavaEditorPreferencePage.annotations.showInText")); //$NON-NLS-1$
+// gd = new GridData(GridData.FILL_HORIZONTAL);
+// gd.horizontalAlignment = GridData.BEGINNING;
+// gd.horizontalSpan = 2;
+// fShowInTextCheckBox.setLayoutData(gd);
+// fDecorationStyleCombo = new Combo(optionsComposite, SWT.READ_ONLY);
+// for (int i = 0; i < fAnnotationDecorationListModel.length; i++)
+// fDecorationStyleCombo.add(fAnnotationDecorationListModel[i][0]);
+// gd = new GridData(GridData.FILL_HORIZONTAL);
+// gd.horizontalAlignment = GridData.BEGINNING;
+// gd.horizontalSpan = 2;
+// gd.horizontalIndent = 20;
+// fDecorationStyleCombo.setLayoutData(gd);
+// fHighlightInTextCheckBox = new Button(optionsComposite, SWT.CHECK);
+// fHighlightInTextCheckBox.setText(PreferencesMessages
+// .getString("TextEditorPreferencePage.annotations.highlightInText")); //$NON-NLS-1$
+// gd = new GridData(GridData.FILL_HORIZONTAL);
+// gd.horizontalAlignment = GridData.BEGINNING;
+// gd.horizontalSpan = 2;
+// fHighlightInTextCheckBox.setLayoutData(gd);
+// fShowInOverviewRulerCheckBox = new Button(optionsComposite, SWT.CHECK);
+// fShowInOverviewRulerCheckBox.setText(PreferencesMessages
+// .getString("JavaEditorPreferencePage.annotations.showInOverviewRuler")); //$NON-NLS-1$
+// gd = new GridData(GridData.FILL_HORIZONTAL);
+// gd.horizontalAlignment = GridData.BEGINNING;
+// gd.horizontalSpan = 2;
+// fShowInOverviewRulerCheckBox.setLayoutData(gd);
+// fShowInVerticalRulerCheckBox = new Button(optionsComposite, SWT.CHECK);
+// fShowInVerticalRulerCheckBox.setText(PreferencesMessages
+// .getString("JavaEditorPreferencePage.annotations.showInVerticalRuler")); //$NON-NLS-1$
+// gd = new GridData(GridData.FILL_HORIZONTAL);
+// gd.horizontalAlignment = GridData.BEGINNING;
+// gd.horizontalSpan = 2;
+// fShowInVerticalRulerCheckBox.setLayoutData(gd);
+// label = new Label(optionsComposite, SWT.LEFT);
+// label.setText(PreferencesMessages
+// .getString("JavaEditorPreferencePage.annotations.color")); //$NON-NLS-1$
+// gd = new GridData();
+// gd.horizontalAlignment = GridData.BEGINNING;
+// label.setLayoutData(gd);
+// fAnnotationForegroundColorEditor = new ColorEditor(optionsComposite);
+// Button foregroundColorButton = fAnnotationForegroundColorEditor.getButton();
+// gd = new GridData(GridData.FILL_HORIZONTAL);
+// gd.horizontalAlignment = GridData.BEGINNING;
+// foregroundColorButton.setLayoutData(gd);
+// fAnnotationList.addSelectionListener(new SelectionListener() {
+// public void widgetDefaultSelected(SelectionEvent e) {
+// // do nothing
+// }
+// public void widgetSelected(SelectionEvent e) {
+// handleAnnotationListSelection();
+// }
+// });
+// fShowInTextCheckBox.addSelectionListener(new SelectionListener() {
+// public void widgetDefaultSelected(SelectionEvent e) {
+// // do nothing
+// }
+// public void widgetSelected(SelectionEvent e) {
+// int i = fAnnotationList.getSelectionIndex();
+// String key = fAnnotationColorListModel[i][2];
+// fOverlayStore.setValue(key, fShowInTextCheckBox.getSelection());
+// String decorationKey = fAnnotationColorListModel[i][6];
+// fDecorationStyleCombo.setEnabled(decorationKey != null
+// && fShowInTextCheckBox.getSelection());
+// }
+// });
+// fHighlightInTextCheckBox.addSelectionListener(new SelectionListener() {
+// public void widgetDefaultSelected(SelectionEvent e) {
+// // do nothing
+// }
+// public void widgetSelected(SelectionEvent e) {
+// int i = fAnnotationList.getSelectionIndex();
+// String key = fAnnotationColorListModel[i][4];
+// fOverlayStore.setValue(key, fHighlightInTextCheckBox.getSelection());
+// }
+// });
+// fShowInOverviewRulerCheckBox.addSelectionListener(new SelectionListener() {
+// public void widgetDefaultSelected(SelectionEvent e) {
+// // do nothing
+// }
+// public void widgetSelected(SelectionEvent e) {
+// int i = fAnnotationList.getSelectionIndex();
+// String key = fAnnotationColorListModel[i][3];
+// fOverlayStore
+// .setValue(key, fShowInOverviewRulerCheckBox.getSelection());
+// }
+// });
+// fShowInVerticalRulerCheckBox.addSelectionListener(new SelectionListener() {
+// public void widgetDefaultSelected(SelectionEvent e) {
+// // do nothing
+// }
+// public void widgetSelected(SelectionEvent e) {
+// int i = fAnnotationList.getSelectionIndex();
+// String key = fAnnotationColorListModel[i][5];
+// fOverlayStore
+// .setValue(key, fShowInVerticalRulerCheckBox.getSelection());
+// }
+// });
+// foregroundColorButton.addSelectionListener(new SelectionListener() {
+// public void widgetDefaultSelected(SelectionEvent e) {
+// // do nothing
+// }
+// public void widgetSelected(SelectionEvent e) {
+// int i = fAnnotationList.getSelectionIndex();
+// String key = fAnnotationColorListModel[i][1];
+// PreferenceConverter.setValue(fOverlayStore, key,
+// fAnnotationForegroundColorEditor.getColorValue());
+// }
+// });
+// fDecorationStyleCombo.addSelectionListener(new SelectionListener() {
+// /**
+// * {@inheritdoc}
+// */
+// public void widgetDefaultSelected(SelectionEvent e) {
+// // do nothing
+// }
+// /**
+// * {@inheritdoc}
+// */
+// public void widgetSelected(SelectionEvent e) {
+// int i = fAnnotationList.getSelectionIndex();
+// String key = fAnnotationColorListModel[i][6];
+// if (key != null) {
+// for (int j = 0; j < fAnnotationDecorationListModel.length; j++) {
+// if (fAnnotationDecorationListModel[j][0]
+// .equals(fDecorationStyleCombo.getText())) {
+// fOverlayStore.setValue(key, fAnnotationDecorationListModel[j][1]);
+// break;
+// }
+// }
+// }
+// }
+// });
+// return composite;
+// }
private String[][] createAnnotationTypeListModel(
MarkerAnnotationPreferences preferences) {
ArrayList listModelItems = new ArrayList();
*/
protected Control createContents(Composite parent) {
initializeDefaultColors();
+ fFoldingConfigurationBlock= new FoldingConfigurationBlock(fOverlayStore);
fOverlayStore.load();
fOverlayStore.start();
TabFolder folder = new TabFolder(parent, SWT.NONE);
item.setText(PreferencesMessages.getString("JavaEditorPreferencePage.codeAssist"));
//$NON-NLS-1$
item.setControl(createContentAssistPage(folder));
- item = new TabItem(folder, SWT.NONE);
- item.setText(PreferencesMessages
- .getString("JavaEditorPreferencePage.annotationsTab.title")); //$NON-NLS-1$
- item.setControl(createAnnotationsPage(folder));
+// item = new TabItem(folder, SWT.NONE);
+// item.setText(PreferencesMessages
+// .getString("JavaEditorPreferencePage.annotationsTab.title")); //$NON-NLS-1$
+// item.setControl(createAnnotationsPage(folder));
item= new TabItem(folder, SWT.NONE);
item.setText(PreferencesMessages.getString("JavaEditorPreferencePage.typing.tabTitle"));
//$NON-NLS-1$
item.setText(PreferencesMessages.getString("JavaEditorPreferencePage.navigationTab.title"));
//$NON-NLS-1$
item.setControl(createNavigationPage(folder));
-
+ item= new TabItem(folder, SWT.NONE);
+ item.setText(PreferencesMessages.getString("JavaEditorPreferencePage.folding.title")); //$NON-NLS-1$
+ item.setControl(fFoldingConfigurationBlock.createControl(folder));
+
initialize();
Dialog.applyDialogFont(folder);
return folder;
}
}
});
- for (int i = 0; i < fAnnotationColorListModel.length; i++)
- fAnnotationList.add(fAnnotationColorListModel[i][0]);
- fAnnotationList.getDisplay().asyncExec(new Runnable() {
- public void run() {
- if (fAnnotationList != null && !fAnnotationList.isDisposed()) {
- fAnnotationList.select(0);
- handleAnnotationListSelection();
- }
- }
- });
+// for (int i = 0; i < fAnnotationColorListModel.length; i++)
+// fAnnotationList.add(fAnnotationColorListModel[i][0]);
+// fAnnotationList.getDisplay().asyncExec(new Runnable() {
+// public void run() {
+// if (fAnnotationList != null && !fAnnotationList.isDisposed()) {
+// fAnnotationList.select(0);
+// handleAnnotationListSelection();
+// }
+// }
+// });
// for (int i= 0; i < fContentAssistColorListModel.length; i++)
// fContentAssistColorList.add(fContentAssistColorListModel[i][0]);
// fContentAssistColorList.getDisplay().asyncExec(new Runnable() {
// }
// }
// });
+ fFoldingConfigurationBlock.initialize();
}
private void initializeFields() {
Iterator e = fColorButtons.keySet().iterator();
*/
public boolean performOk() {
// fJavaEditorHoverConfigurationBlock.performOk();
+ fFoldingConfigurationBlock.performOk();
// fOverlayStore.setValue(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK,
// computeStateMask(fBrowserLikeLinksKeyModifierText.getText()));
fOverlayStore.propagate();
initializeFields();
handleSyntaxColorListSelection();
handleAppearanceColorListSelection();
- handleAnnotationListSelection();
+// handleAnnotationListSelection();
// handleContentAssistColorListSelection();
// fJavaEditorHoverConfigurationBlock.performDefaults();
+ fFoldingConfigurationBlock.performDefaults();
super.performDefaults();
fPreviewViewer.invalidateTextPresentation();
}
* @see DialogPage#dispose()
*/
public void dispose() {
+ fFoldingConfigurationBlock.dispose();
+
if (fJavaTextTools != null) {
fJavaTextTools.dispose();
fJavaTextTools = null;
-/*
- * (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.preferences;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
+import org.eclipse.jface.text.Assert;
+
/**
* An overlaying preference store.
*/
public static final class TypeDescriptor {
private TypeDescriptor() {
}
- };
+ }
public static final TypeDescriptor BOOLEAN= new TypeDescriptor();
public static final TypeDescriptor DOUBLE= new TypeDescriptor();
fDescriptor= descriptor;
fKey= key;
}
- };
+ }
private class PropertyListener implements IPropertyChangeListener {
if (key != null)
propagateProperty(fParent, key, fStore);
}
- };
+ }
private IPreferenceStore fParent;
private OverlayKey[] fOverlayKeys;
private PropertyListener fPropertyListener;
+ private boolean fLoaded;
public OverlayPreferenceStore(IPreferenceStore parent, OverlayKey[] overlayKeys) {
public void load() {
for (int i= 0; i < fOverlayKeys.length; i++)
loadProperty(fParent, fOverlayKeys[i], fStore, true);
+
+ fLoaded= true;
+
}
public void loadDefaults() {
if (covers(name))
fStore.setValue(name, value);
}
-}
\ No newline at end of file
+
+ /**
+ * The keys to add to the list of overlay keys.
+ * <p>
+ * Note: This method must be called before {@link #load()} is called.
+ * </p>
+ *
+ * @param keys
+ * @since 3.0
+ */
+ public void addKeys(OverlayKey[] keys) {
+ Assert.isTrue(!fLoaded);
+ Assert.isNotNull(keys);
+
+ int overlayKeysLength= fOverlayKeys.length;
+ OverlayKey[] result= new OverlayKey[keys.length + overlayKeysLength];
+
+ for (int i= 0, length= overlayKeysLength; i < length; i++)
+ result[i]= fOverlayKeys[i];
+
+ for (int i= 0, length= keys.length; i < length; i++)
+ result[overlayKeysLength + i]= keys[i];
+
+ fOverlayKeys= result;
+
+ if (fLoaded)
+ load();
+ }
+}
.getString("JavaEditorPreferencePage.AnnotationDecoration.NONE"),
AnnotationPreference.STYLE_NONE},
//$NON-NLS-1$
- {
- PreferencesMessages
- .getString("JavaEditorPreferencePage.AnnotationDecoration.SQUIGGLIES"),
- AnnotationPreference.STYLE_SQUIGGLIES},
+// {
+// PreferencesMessages
+// .getString("JavaEditorPreferencePage.AnnotationDecoration.SQUIGGLIES"),
+// AnnotationPreference.STYLE_SQUIGGLIES},
//$NON-NLS-1$
{
PreferencesMessages
PHPEditorPreferencePage.phpDocKeywords=PHPDoc keywords
PHPEditorPreferencePage.phpDocHtmlTags=PHPDoc HTML tags
PHPEditorPreferencePage.phpDocLinks=PHPDoc links
-PHPEditorPreferencePage.phpDocOthers=PHPDoc others
\ No newline at end of file
+PHPEditorPreferencePage.phpDocOthers=PHPDoc others
+
+JavaEditorPreferencePage.folding.title= &Folding
+
+FoldingConfigurationBlock.enable= Enable folding when &opening a new editor
+FoldingConfigurationBlock.combo_caption= Select folding to &use:
+FoldingConfigurationBlock.info.no_preferences= The selected folding provider did not provide a preference control
+FoldingConfigurationBlock.error.not_exist= The selected folding provider does not exist
--- /dev/null
+/*******************************************************************************
+ * 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.internal.ui.text.java.hover.SourceViewerInformationControl;
+
+import org.eclipse.jface.resource.JFaceResources;
+import org.eclipse.jface.text.Assert;
+import org.eclipse.jface.text.BadLocationException;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.jface.text.IRegion;
+import org.eclipse.jface.text.ITextViewerExtension;
+import org.eclipse.swt.custom.StyledText;
+import org.eclipse.swt.graphics.Font;
+import org.eclipse.swt.graphics.GC;
+import org.eclipse.swt.graphics.Point;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Shell;
+
+/**
+ * Source viewer used to display quick diff hovers.
+ *
+ * @since 3.0
+ */
+public class CustomSourceInformationControl extends SourceViewerInformationControl {
+
+ /** The font name for the viewer font - the same as the java editor's. */
+ private static final String SYMBOLIC_FONT_NAME= "org.eclipse.jdt.ui.editors.textfont"; //$NON-NLS-1$
+
+ /** The maximum width of the control, set in <code>setSizeConstraints(int, int)</code>. */
+ int fMaxWidth= Integer.MAX_VALUE;
+ /** The maximum height of the control, set in <code>setSizeConstraints(int, int)</code>. */
+ int fMaxHeight= Integer.MAX_VALUE;
+
+ /** The partition type to be used as the starting partition type by the paritition scanner. */
+ private String fPartition;
+ /** The horizontal scroll index. */
+ private int fHorizontalScrollPixel;
+
+ /*
+ * @see org.eclipse.jface.text.IInformationControl#setSizeConstraints(int, int)
+ */
+ public void setSizeConstraints(int maxWidth, int maxHeight) {
+ fMaxWidth= maxWidth;
+ fMaxHeight= maxHeight;
+ }
+
+ /**
+ * Creates a new information control.
+ *
+ * @param parent the shell that is the parent of this hover / control
+ * @param partition the initial partition type to be used for the underlying viewer
+ */
+ public CustomSourceInformationControl(Shell parent, String partition) {
+ super(parent);
+ setViewerFont();
+ setStartingPartitionType(partition);
+ }
+
+ /*
+ * @see org.eclipse.jface.text.IInformationControl#computeSizeHint()
+ */
+ public Point computeSizeHint() {
+ Point size= super.computeSizeHint();
+ size.x= Math.min(size.x, fMaxWidth);
+ size.y= Math.min(size.y, fMaxHeight);
+ return size;
+ }
+
+ /**
+ * Sets the font for this viewer sustaining selection and scroll position.
+ */
+ private void setViewerFont() {
+ Font font= JFaceResources.getFont(SYMBOLIC_FONT_NAME);
+
+ if (getViewer().getDocument() != null) {
+
+ Point selection= getViewer().getSelectedRange();
+ int topIndex= getViewer().getTopIndex();
+
+ StyledText styledText= getViewer().getTextWidget();
+ Control parent= styledText;
+ if (getViewer() instanceof ITextViewerExtension) {
+ ITextViewerExtension extension= (ITextViewerExtension) getViewer();
+ parent= extension.getControl();
+ }
+
+ parent.setRedraw(false);
+
+ styledText.setFont(font);
+
+ getViewer().setSelectedRange(selection.x , selection.y);
+ getViewer().setTopIndex(topIndex);
+
+ if (parent instanceof Composite) {
+ Composite composite= (Composite) parent;
+ composite.layout(true);
+ }
+
+ parent.setRedraw(true);
+
+ } else {
+ StyledText styledText= getViewer().getTextWidget();
+ styledText.setFont(font);
+ }
+ }
+
+ /**
+ * Sets the initial partition for the underlying source viewer.
+ *
+ * @param partition the partition type
+ */
+ public void setStartingPartitionType(String partition) {
+ if (partition == null)
+ fPartition= IDocument.DEFAULT_CONTENT_TYPE;
+ else
+ fPartition= partition;
+ }
+
+ /*
+ * @see org.eclipse.jface.text.IInformationControl#setInformation(java.lang.String)
+ */
+ public void setInformation(String content) {
+ super.setInformation(content);
+ IDocument doc= getViewer().getDocument();
+ if (doc == null)
+ return;
+
+ // ensure that we can scroll enough
+ ensureScrollable();
+
+ String start= null;
+ if (IPHPPartitions.PHP_PHPDOC_COMMENT.equals(fPartition)) {
+ start= "/**" + doc.getLegalLineDelimiters()[0]; //$NON-NLS-1$
+ } else if (IPHPPartitions.PHP_MULTILINE_COMMENT.equals(fPartition)) {
+ start= "/*" + doc.getLegalLineDelimiters()[0]; //$NON-NLS-1$
+ }
+ if (start != null) {
+ try {
+ doc.replace(0, 0, start);
+ int startLen= start.length();
+ getViewer().setDocument(doc, startLen, doc.getLength() - startLen);
+ } catch (BadLocationException e) {
+ // impossible
+ Assert.isTrue(false);
+ }
+ }
+
+ getViewer().getTextWidget().setHorizontalPixel(fHorizontalScrollPixel);
+ }
+
+ /**
+ * Ensures that the control can be scrolled at least to
+ * <code>fHorizontalScrollPixel</code> and adjusts <code>fMaxWidth</code>
+ * accordingly.
+ */
+ private void ensureScrollable() {
+ IDocument doc= getViewer().getDocument();
+ if (doc == null)
+ return;
+
+ StyledText widget= getViewer().getTextWidget();
+ if (widget == null || widget.isDisposed())
+ return;
+
+ int last= doc.getNumberOfLines() - 1;
+ GC gc= new GC(widget);
+ gc.setFont(widget.getFont());
+ int maxWidth= 0;
+ String content= new String();
+
+ try {
+ for (int i= 0; i <= last; i++) {
+ IRegion line;
+ line= doc.getLineInformation(i);
+ content= doc.get(line.getOffset(), line.getLength());
+ int width= gc.textExtent(content).x;
+ if (width > maxWidth) {
+ maxWidth= width;
+ }
+ }
+ } catch (BadLocationException e) {
+ return;
+ } finally {
+ gc.dispose();
+ }
+
+ // limit the size of the window to the maximum width minus scrolling,
+ // but never more than the configured max size (viewport size).
+ fMaxWidth= Math.max(0, Math.min(fMaxWidth, maxWidth - fHorizontalScrollPixel + 8));
+ }
+
+ /*
+ * @see org.eclipse.jdt.internal.ui.text.java.hover.SourceViewerInformationControl#hasContents()
+ */
+ public boolean hasContents() {
+ return super.hasContents() && fMaxWidth > 0;
+ }
+
+ /**
+ * Sets the horizontal scroll index in pixels.
+ *
+ * @param scrollIndex the new horizontal scroll index
+ */
+ public void setHorizontalScrollPixel(int scrollIndex) {
+ scrollIndex= Math.max(0, scrollIndex);
+ fHorizontalScrollPixel= scrollIndex;
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * 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.folding;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+import net.sourceforge.phpdt.internal.ui.preferences.OverlayPreferenceStore;
+import net.sourceforge.phpdt.internal.ui.preferences.OverlayPreferenceStore.OverlayKey;
+import net.sourceforge.phpdt.ui.PreferenceConstants;
+import net.sourceforge.phpdt.ui.text.folding.IJavaFoldingPreferenceBlock;
+import net.sourceforge.phpeclipse.PHPeclipsePlugin;
+
+import org.eclipse.jface.preference.IPreferenceStore;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.events.SelectionListener;
+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.Label;
+
+
+/**
+ * Java default folding preferences.
+ *
+ * @since 3.0
+ */
+public class DefaultJavaFoldingPreferenceBlock implements IJavaFoldingPreferenceBlock {
+
+ private IPreferenceStore fStore;
+ private OverlayPreferenceStore fOverlayStore;
+ private OverlayKey[] fKeys;
+ private Map fCheckBoxes= new HashMap();
+ private SelectionListener fCheckBoxListener= new SelectionListener() {
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ public void widgetSelected(SelectionEvent e) {
+ Button button= (Button) e.widget;
+ fOverlayStore.setValue((String) fCheckBoxes.get(button), button.getSelection());
+ }
+ };
+
+
+ public DefaultJavaFoldingPreferenceBlock() {
+ fStore= PHPeclipsePlugin.getDefault().getPreferenceStore();
+ fKeys= createKeys();
+ fOverlayStore= new OverlayPreferenceStore(fStore, fKeys);
+ }
+
+ private OverlayKey[] createKeys() {
+ ArrayList overlayKeys= new ArrayList();
+
+ overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_FOLDING_JAVADOC));
+ overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_FOLDING_INNERTYPES));
+ overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_FOLDING_METHODS));
+ overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_FOLDING_IMPORTS));
+
+ return (OverlayKey[]) overlayKeys.toArray(new OverlayKey[overlayKeys.size()]);
+ }
+
+ /*
+ * @see net.sourceforge.phpdt.internal.ui.text.folding.IJavaFoldingPreferences#createControl(org.eclipse.swt.widgets.Group)
+ */
+ public Control createControl(Composite composite) {
+ fOverlayStore.load();
+ fOverlayStore.start();
+
+ Composite inner= new Composite(composite, SWT.NONE);
+ GridLayout layout= new GridLayout(1, true);
+ layout.verticalSpacing= 3;
+ layout.marginWidth= 0;
+ inner.setLayout(layout);
+
+ Label label= new Label(inner, SWT.LEFT);
+ label.setText(FoldingMessages.getString("DefaultJavaFoldingPreferenceBlock.title")); //$NON-NLS-1$
+
+ addCheckBox(inner, FoldingMessages.getString("DefaultJavaFoldingPreferenceBlock.comments"), PreferenceConstants.EDITOR_FOLDING_JAVADOC, 0); //$NON-NLS-1$
+ addCheckBox(inner, FoldingMessages.getString("DefaultJavaFoldingPreferenceBlock.innerTypes"), PreferenceConstants.EDITOR_FOLDING_INNERTYPES, 0); //$NON-NLS-1$
+ addCheckBox(inner, FoldingMessages.getString("DefaultJavaFoldingPreferenceBlock.methods"), PreferenceConstants.EDITOR_FOLDING_METHODS, 0); //$NON-NLS-1$
+ addCheckBox(inner, FoldingMessages.getString("DefaultJavaFoldingPreferenceBlock.imports"), PreferenceConstants.EDITOR_FOLDING_IMPORTS, 0); //$NON-NLS-1$
+
+ return inner;
+ }
+
+ 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= 1;
+ gd.grabExcessVerticalSpace= false;
+ checkBox.setLayoutData(gd);
+ checkBox.addSelectionListener(fCheckBoxListener);
+
+ fCheckBoxes.put(checkBox, key);
+
+ return checkBox;
+ }
+
+ private void initializeFields() {
+ Iterator it= fCheckBoxes.keySet().iterator();
+ while (it.hasNext()) {
+ Button b= (Button) it.next();
+ String key= (String) fCheckBoxes.get(b);
+ b.setSelection(fOverlayStore.getBoolean(key));
+ }
+ }
+
+ /*
+ * @see net.sourceforge.phpdt.internal.ui.text.folding.AbstractJavaFoldingPreferences#performOk()
+ */
+ public void performOk() {
+ fOverlayStore.propagate();
+ }
+
+
+ /*
+ * @see net.sourceforge.phpdt.internal.ui.text.folding.AbstractJavaFoldingPreferences#initialize()
+ */
+ public void initialize() {
+ initializeFields();
+ }
+
+ /*
+ * @see net.sourceforge.phpdt.internal.ui.text.folding.AbstractJavaFoldingPreferences#performDefaults()
+ */
+ public void performDefaults() {
+ fOverlayStore.loadDefaults();
+ initializeFields();
+ }
+
+ /*
+ * @see net.sourceforge.phpdt.internal.ui.text.folding.AbstractJavaFoldingPreferences#dispose()
+ */
+ public void dispose() {
+ fOverlayStore.stop();
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * 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.folding;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import net.sourceforge.phpdt.core.ElementChangedEvent;
+import net.sourceforge.phpdt.core.IElementChangedListener;
+import net.sourceforge.phpdt.core.IJavaElement;
+import net.sourceforge.phpdt.core.IJavaElementDelta;
+import net.sourceforge.phpdt.core.IParent;
+import net.sourceforge.phpdt.core.ISourceRange;
+import net.sourceforge.phpdt.core.ISourceReference;
+import net.sourceforge.phpdt.core.IType;
+import net.sourceforge.phpdt.core.JavaCore;
+import net.sourceforge.phpdt.core.JavaModelException;
+import net.sourceforge.phpdt.core.ToolFactory;
+import net.sourceforge.phpdt.core.compiler.IScanner;
+import net.sourceforge.phpdt.core.compiler.ITerminalSymbols;
+import net.sourceforge.phpdt.core.compiler.InvalidInputException;
+import net.sourceforge.phpdt.ui.IWorkingCopyManager;
+import net.sourceforge.phpdt.ui.PreferenceConstants;
+import net.sourceforge.phpdt.ui.text.folding.IJavaFoldingStructureProvider;
+import net.sourceforge.phpeclipse.PHPeclipsePlugin;
+import net.sourceforge.phpeclipse.phpeditor.PHPEditor;
+import net.sourceforge.phpeclipse.phpeditor.PHPUnitEditor;
+
+import org.eclipse.jface.preference.IPreferenceStore;
+import org.eclipse.jface.text.BadLocationException;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.jface.text.IRegion;
+import org.eclipse.jface.text.Position;
+import org.eclipse.jface.text.Region;
+import org.eclipse.jface.text.source.Annotation;
+import org.eclipse.jface.text.source.IAnnotationModel;
+import org.eclipse.jface.text.source.projection.IProjectionListener;
+import org.eclipse.jface.text.source.projection.ProjectionAnnotation;
+import org.eclipse.jface.text.source.projection.ProjectionAnnotationModel;
+import org.eclipse.jface.text.source.projection.ProjectionViewer;
+import org.eclipse.ui.texteditor.IDocumentProvider;
+import org.eclipse.ui.texteditor.ITextEditor;
+
+
+/**
+ * Updates the projection model of a class file or compilation unit.
+ *
+ * @since 3.0
+ */
+public class DefaultJavaFoldingStructureProvider implements IProjectionListener, IJavaFoldingStructureProvider {
+
+ private static class JavaProjectionAnnotation extends ProjectionAnnotation {
+
+ private IJavaElement fJavaElement;
+ private boolean fIsComment;
+
+ public JavaProjectionAnnotation(IJavaElement element, boolean isCollapsed, boolean isComment) {
+ super(isCollapsed);
+ fJavaElement= element;
+ fIsComment= isComment;
+ }
+
+ public IJavaElement getElement() {
+ return fJavaElement;
+ }
+
+ public void setElement(IJavaElement element) {
+ fJavaElement= element;
+ }
+
+ public boolean isComment() {
+ return fIsComment;
+ }
+
+ public void setIsComment(boolean isComment) {
+ fIsComment= isComment;
+ }
+ }
+
+ private class ElementChangedListener implements IElementChangedListener {
+
+ /*
+ * @see net.sourceforge.phpdt.core.IElementChangedListener#elementChanged(net.sourceforge.phpdt.core.ElementChangedEvent)
+ */
+ public void elementChanged(ElementChangedEvent e) {
+ IJavaElementDelta delta= findElement(fInput, e.getDelta());
+ if (delta != null)
+ processDelta(delta);
+ }
+
+ private IJavaElementDelta findElement(IJavaElement target, IJavaElementDelta delta) {
+
+ if (delta == null || target == null)
+ return null;
+
+ IJavaElement element= delta.getElement();
+
+ if (element.getElementType() > IJavaElement.CLASS_FILE)
+ return null;
+
+ if (target.equals(element))
+ return delta;
+
+ IJavaElementDelta[] children= delta.getAffectedChildren();
+ if (children == null || children.length == 0)
+ return null;
+
+ for (int i= 0; i < children.length; i++) {
+ IJavaElementDelta d= findElement(target, children[i]);
+ if (d != null)
+ return d;
+ }
+
+ return null;
+ }
+ }
+
+
+ private IDocument fCachedDocument;
+
+ private ITextEditor fEditor;
+ private ProjectionViewer fViewer;
+ private IJavaElement fInput;
+ private IElementChangedListener fElementListener;
+
+ private boolean fAllowCollapsing= false;
+ private boolean fCollapseJavadoc= false;
+ private boolean fCollapseImportContainer= true;
+ private boolean fCollapseInnerTypes= true;
+ private boolean fCollapseMethods= false;
+
+ public DefaultJavaFoldingStructureProvider() {
+ }
+
+ public void install(ITextEditor editor, ProjectionViewer viewer) {
+ if (editor instanceof PHPEditor) {
+ fEditor= editor;
+ fViewer= viewer;
+ fViewer.addProjectionListener(this);
+ }
+ }
+
+ public void uninstall() {
+ if (isInstalled()) {
+ projectionDisabled();
+ fViewer.removeProjectionListener(this);
+ fViewer= null;
+ fEditor= null;
+ }
+ }
+
+ protected boolean isInstalled() {
+ return fEditor != null;
+ }
+
+ /*
+ * @see org.eclipse.jface.text.source.projection.IProjectionListener#projectionEnabled()
+ */
+ public void projectionEnabled() {
+ if (fEditor instanceof PHPEditor) {
+ initialize();
+ fElementListener= new ElementChangedListener();
+ JavaCore.addElementChangedListener(fElementListener);
+ }
+ }
+
+ /*
+ * @see org.eclipse.jface.text.source.projection.IProjectionListener#projectionDisabled()
+ */
+ public void projectionDisabled() {
+ fCachedDocument= null;
+ if (fElementListener != null) {
+ JavaCore.removeElementChangedListener(fElementListener);
+ fElementListener= null;
+ }
+ }
+
+ public void initialize() {
+
+ if (!isInstalled())
+ return;
+
+ initializePreferences();
+
+ try {
+
+ IDocumentProvider provider= fEditor.getDocumentProvider();
+ fCachedDocument= provider.getDocument(fEditor.getEditorInput());
+ fAllowCollapsing= true;
+
+ if (fEditor instanceof PHPUnitEditor) {
+ IWorkingCopyManager manager= PHPeclipsePlugin.getDefault().getWorkingCopyManager();
+ fInput= manager.getWorkingCopy(fEditor.getEditorInput());
+ }
+// else if (fEditor instanceof ClassFileEditor) {
+// IClassFileEditorInput editorInput= (IClassFileEditorInput) fEditor.getEditorInput();
+// fInput= editorInput.getClassFile();
+// }
+
+ if (fInput != null) {
+ ProjectionAnnotationModel model= (ProjectionAnnotationModel) fEditor.getAdapter(ProjectionAnnotationModel.class);
+ if (model != null) {
+ Map additions= computeAdditions((IParent) fInput);
+ model.removeAllAnnotations();
+ model.replaceAnnotations(null, additions);
+ }
+ }
+
+ } finally {
+ fCachedDocument= null;
+ fAllowCollapsing= false;
+ }
+ }
+
+ private void initializePreferences() {
+ IPreferenceStore store= PHPeclipsePlugin.getDefault().getPreferenceStore();
+ fCollapseInnerTypes= store.getBoolean(PreferenceConstants.EDITOR_FOLDING_INNERTYPES);
+ fCollapseImportContainer= store.getBoolean(PreferenceConstants.EDITOR_FOLDING_IMPORTS);
+ fCollapseJavadoc= store.getBoolean(PreferenceConstants.EDITOR_FOLDING_JAVADOC);
+ fCollapseMethods= store.getBoolean(PreferenceConstants.EDITOR_FOLDING_METHODS);
+ }
+
+ private Map computeAdditions(IParent parent) {
+ Map map= new HashMap();
+ try {
+ computeAdditions(parent.getChildren(), map);
+ } catch (JavaModelException x) {
+ }
+ return map;
+ }
+
+ private void computeAdditions(IJavaElement[] elements, Map map) throws JavaModelException {
+ for (int i= 0; i < elements.length; i++) {
+ IJavaElement element= elements[i];
+
+ computeAdditions(element, map);
+
+ if (element instanceof IParent) {
+ IParent parent= (IParent) element;
+ computeAdditions(parent.getChildren(), map);
+ }
+ }
+ }
+
+ private void computeAdditions(IJavaElement element, Map map) {
+
+ boolean createProjection= false;
+
+ boolean collapse= false;
+ switch (element.getElementType()) {
+
+ case IJavaElement.IMPORT_CONTAINER:
+ collapse= fAllowCollapsing && fCollapseImportContainer;
+ createProjection= true;
+ break;
+ case IJavaElement.TYPE:
+ collapse= fAllowCollapsing && fCollapseInnerTypes && isInnerType((IType) element);
+ createProjection= true;
+ break;
+ case IJavaElement.METHOD:
+ collapse= fAllowCollapsing && fCollapseMethods;
+ createProjection= true;
+ break;
+ }
+
+ if (createProjection) {
+ IRegion[] regions= computeProjectionRanges(element);
+ if (regions != null) {
+ // comments
+ for (int i= 0; i < regions.length - 1; i++) {
+ Position position= createProjectionPosition(regions[i]);
+ if (position != null)
+ map.put(new JavaProjectionAnnotation(element, fAllowCollapsing && fCollapseJavadoc, true), position);
+ }
+ // code
+ Position position= createProjectionPosition(regions[regions.length - 1]);
+ if (position != null)
+ map.put(new JavaProjectionAnnotation(element, collapse, false), position);
+ }
+ }
+ }
+
+ private boolean isInnerType(IType type) {
+
+ try {
+ return type.isMember();
+ } catch (JavaModelException x) {
+ IJavaElement parent= type.getParent();
+ if (parent != null) {
+ int parentType= parent.getElementType();
+ return (parentType != IJavaElement.COMPILATION_UNIT && parentType != IJavaElement.CLASS_FILE);
+ }
+ }
+
+ return false;
+ }
+
+ private IRegion[] computeProjectionRanges(IJavaElement element) {
+
+ try {
+ if (element instanceof ISourceReference) {
+ ISourceReference reference= (ISourceReference) element;
+ ISourceRange range= reference.getSourceRange();
+ String contents= reference.getSource();
+ if (contents == null)
+ return null;
+
+ IScanner scanner= ToolFactory.createScanner(true, false, false);//, false);
+ scanner.setSource(contents.toCharArray());
+ List regions= new ArrayList();
+ int shift= range.getOffset();
+ int start= shift;
+ while (true) {
+
+ int token= scanner.getNextToken();
+ start= shift + scanner.getCurrentTokenStartPosition();
+
+ switch (token) {
+ case ITerminalSymbols.TokenNameCOMMENT_PHPDOC: // COMMENT_JAVADOC:
+ case ITerminalSymbols.TokenNameCOMMENT_BLOCK: {
+ int end= shift + scanner.getCurrentTokenEndPosition() + 1;
+ regions.add(new Region(start, end - start));
+ }
+ case ITerminalSymbols.TokenNameCOMMENT_LINE:
+ continue;
+ }
+
+ break;
+ }
+
+ regions.add(new Region(start, range.getOffset() + range.getLength() - start));
+
+ if (regions.size() > 0) {
+ IRegion[] result= new IRegion[regions.size()];
+ regions.toArray(result);
+ return result;
+ }
+ }
+ } catch (JavaModelException e) {
+ } catch (InvalidInputException e) {
+ }
+
+ return null;
+ }
+
+ private Position createProjectionPosition(IRegion region) {
+
+ if (fCachedDocument == null)
+ return null;
+
+ try {
+
+ int start= fCachedDocument.getLineOfOffset(region.getOffset());
+ int end= fCachedDocument.getLineOfOffset(region.getOffset() + region.getLength());
+ if (start != end) {
+ int offset= fCachedDocument.getLineOffset(start);
+ int endOffset= fCachedDocument.getLineOffset(end + 1);
+ return new Position(offset, endOffset - offset);
+ }
+
+ } catch (BadLocationException x) {
+ }
+
+ return null;
+ }
+
+ protected void processDelta(IJavaElementDelta delta) {
+
+ if (!isInstalled())
+ return;
+
+ ProjectionAnnotationModel model= (ProjectionAnnotationModel) fEditor.getAdapter(ProjectionAnnotationModel.class);
+ if (model == null)
+ return;
+
+ try {
+
+ IDocumentProvider provider= fEditor.getDocumentProvider();
+ fCachedDocument= provider.getDocument(fEditor.getEditorInput());
+ fAllowCollapsing= false;
+
+ Map additions= new HashMap();
+ List deletions= new ArrayList();
+ List updates= new ArrayList();
+
+ Map updated= computeAdditions((IParent) fInput);
+ Map previous= createAnnotationMap(model);
+
+
+ Iterator e= updated.keySet().iterator();
+ while (e.hasNext()) {
+ JavaProjectionAnnotation annotation= (JavaProjectionAnnotation) e.next();
+ IJavaElement element= annotation.getElement();
+ Position position= (Position) updated.get(annotation);
+
+ List annotations= (List) previous.get(element);
+ if (annotations == null) {
+
+ additions.put(annotation, position);
+
+ } else {
+
+ Iterator x= annotations.iterator();
+ while (x.hasNext()) {
+ JavaProjectionAnnotation a= (JavaProjectionAnnotation) x.next();
+ if (annotation.isComment() == a.isComment()) {
+ Position p= model.getPosition(a);
+ if (p != null && !position.equals(p)) {
+ p.setOffset(position.getOffset());
+ p.setLength(position.getLength());
+ updates.add(a);
+ }
+ x.remove();
+ break;
+ }
+ }
+
+ if (annotations.isEmpty())
+ previous.remove(element);
+ }
+ }
+
+ e= previous.values().iterator();
+ while (e.hasNext()) {
+ List list= (List) e.next();
+ int size= list.size();
+ for (int i= 0; i < size; i++)
+ deletions.add(list.get(i));
+ }
+
+ match(model, deletions, additions, updates);
+
+ Annotation[] removals= new Annotation[deletions.size()];
+ deletions.toArray(removals);
+ Annotation[] changes= new Annotation[updates.size()];
+ updates.toArray(changes);
+ model.modifyAnnotations(removals, additions, changes);
+
+ } finally {
+ fCachedDocument= null;
+ fAllowCollapsing= true;
+ }
+ }
+
+ private void match(ProjectionAnnotationModel model, List deletions, Map additions, List changes) {
+ if (deletions.isEmpty() || (additions.isEmpty() && changes.isEmpty()))
+ return;
+
+ List newDeletions= new ArrayList();
+ List newChanges= new ArrayList();
+
+ Iterator deletionIterator= deletions.iterator();
+ outer: while (deletionIterator.hasNext()) {
+ JavaProjectionAnnotation deleted= (JavaProjectionAnnotation) deletionIterator.next();
+ Position deletedPosition= model.getPosition(deleted);
+ if (deletedPosition == null)
+ continue;
+
+ Iterator changesIterator= changes.iterator();
+ while (changesIterator.hasNext()) {
+ JavaProjectionAnnotation changed= (JavaProjectionAnnotation) changesIterator.next();
+ if (deleted.isComment() == changed.isComment()) {
+ Position changedPosition= model.getPosition(changed);
+ if (changedPosition == null)
+ continue;
+
+ if (deletedPosition.getOffset() == changedPosition.getOffset()) {
+
+ deletedPosition.setLength(changedPosition.getLength());
+ deleted.setElement(changed.getElement());
+
+ deletionIterator.remove();
+ newChanges.add(deleted);
+
+ changesIterator.remove();
+ newDeletions.add(changed);
+
+ continue outer;
+ }
+ }
+ }
+
+ Iterator additionsIterator= additions.keySet().iterator();
+ while (additionsIterator.hasNext()) {
+ JavaProjectionAnnotation added= (JavaProjectionAnnotation) additionsIterator.next();
+ if (deleted.isComment() == added.isComment()) {
+ Position addedPosition= (Position) additions.get(added);
+
+ if (deletedPosition.getOffset() == addedPosition.getOffset()) {
+
+ deletedPosition.setLength(addedPosition.getLength());
+ deleted.setElement(added.getElement());
+
+ deletionIterator.remove();
+ newChanges.add(deleted);
+
+ additionsIterator.remove();
+
+ break;
+ }
+ }
+ }
+ }
+
+ deletions.addAll(newDeletions);
+ changes.addAll(newChanges);
+ }
+
+ private Map createAnnotationMap(IAnnotationModel model) {
+ Map map= new HashMap();
+ Iterator e= model.getAnnotationIterator();
+ while (e.hasNext()) {
+ Object annotation= e.next();
+ if (annotation instanceof JavaProjectionAnnotation) {
+ JavaProjectionAnnotation java= (JavaProjectionAnnotation) annotation;
+ List list= (List) map.get(java.getElement());
+ if (list == null) {
+ list= new ArrayList(2);
+ map.put(java.getElement(), list);
+ }
+ list.add(java);
+ }
+ }
+ return map;
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * 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.folding;
+
+import org.eclipse.swt.SWT;
+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.Label;
+
+import net.sourceforge.phpdt.ui.text.folding.IJavaFoldingPreferenceBlock;
+
+
+/**
+ * Empty preference block for extensions to the
+ * <code>net.sourceforge.phpdt.ui.javaFoldingStructureProvider</code> extension
+ * point that do not specify their own.
+ *
+ * @since 3.0
+ */
+class EmptyJavaFoldingPreferenceBlock implements IJavaFoldingPreferenceBlock {
+ /*
+ * @see net.sourceforge.phpdt.internal.ui.text.folding.IJavaFoldingPreferences#createControl(org.eclipse.swt.widgets.Group)
+ */
+ public Control createControl(Composite composite) {
+ Composite inner= new Composite(composite, SWT.NONE);
+ inner.setLayout(new GridLayout(3, false));
+
+ Label label= new Label(inner, SWT.CENTER);
+ GridData gd= new GridData(GridData.FILL_BOTH);
+ gd.widthHint= 30;
+ label.setLayoutData(gd);
+
+ label= new Label(inner, SWT.CENTER);
+ label.setText(FoldingMessages.getString("EmptyJavaFoldingPreferenceBlock.emptyCaption")); //$NON-NLS-1$
+ gd= new GridData(GridData.CENTER);
+ label.setLayoutData(gd);
+
+ label= new Label(inner, SWT.CENTER);
+ gd= new GridData(GridData.FILL_BOTH);
+ gd.widthHint= 30;
+ label.setLayoutData(gd);
+
+ return inner;
+ }
+
+ /*
+ * @see net.sourceforge.phpdt.internal.ui.text.folding.IJavaFoldingPreferenceBlock#initialize()
+ */
+ public void initialize() {
+ }
+
+ /*
+ * @see net.sourceforge.phpdt.internal.ui.text.folding.IJavaFoldingPreferenceBlock#performOk()
+ */
+ public void performOk() {
+ }
+
+ /*
+ * @see net.sourceforge.phpdt.internal.ui.text.folding.IJavaFoldingPreferenceBlock#performDefaults()
+ */
+ public void performDefaults() {
+ }
+
+ /*
+ * @see net.sourceforge.phpdt.internal.ui.text.folding.IJavaFoldingPreferenceBlock#dispose()
+ */
+ public void dispose() {
+ }
+
+}
--- /dev/null
+/*******************************************************************************
+ * 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.folding;
+
+import java.util.MissingResourceException;
+import java.util.ResourceBundle;
+
+/**
+ * @since 3.0
+ */
+class FoldingMessages {
+
+ private static final String BUNDLE_NAME= FoldingMessages.class.getName();
+
+ private static final ResourceBundle RESOURCE_BUNDLE= ResourceBundle.getBundle(BUNDLE_NAME);
+
+ private FoldingMessages() {
+ }
+
+ public static String getString(String key) {
+ try {
+ return RESOURCE_BUNDLE.getString(key);
+ } catch (MissingResourceException e) {
+ return '!' + key + '!';
+ }
+ }
+}
--- /dev/null
+###############################################################################
+# Copyright (c) 2000, 2004 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
+###############################################################################
+
+
+DefaultJavaFoldingPreferenceBlock.title= Initially fold these region types:
+DefaultJavaFoldingPreferenceBlock.comments= &Comments
+DefaultJavaFoldingPreferenceBlock.innerTypes= Inner &types
+DefaultJavaFoldingPreferenceBlock.methods= &Methods
+DefaultJavaFoldingPreferenceBlock.imports= &Imports
+
+EmptyJavaFoldingPreferenceBlock.emptyCaption=
--- /dev/null
+/*******************************************************************************
+ * 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.folding;
+
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IConfigurationElement;
+
+import org.eclipse.jface.text.Assert;
+
+import net.sourceforge.phpdt.ui.text.folding.IJavaFoldingPreferenceBlock;
+import net.sourceforge.phpdt.ui.text.folding.IJavaFoldingStructureProvider;
+
+/**
+ * Describes a contribution to the folding provider extension point.
+ *
+ * @since 3.0
+ */
+public final class JavaFoldingStructureProviderDescriptor {
+
+ /* extension point attribute names */
+
+ private static final String PREFERENCES_CLASS= "preferencesClass"; //$NON-NLS-1$
+ private static final String CLASS= "class"; //$NON-NLS-1$
+ private static final String NAME= "name"; //$NON-NLS-1$
+ private static final String ID= "id"; //$NON-NLS-1$
+
+ /** The identifier of the extension. */
+ private String fId;
+ /** The name of the extension. */
+ private String fName;
+ /** The class name of the provided <code>IJavaFoldingStructureProvider</code>. */
+ private String fClass;
+ /**
+ * <code>true</code> if the extension specifies a custom
+ * <code>IJavaFoldingPreferenceBlock</code>.
+ */
+ private boolean fHasPreferences;
+ /** The configuration element of this extension. */
+ private IConfigurationElement fElement;
+
+ /**
+ * Creates a new descriptor.
+ *
+ * @param element the configuration element to read
+ */
+ JavaFoldingStructureProviderDescriptor(IConfigurationElement element) {
+ fElement= element;
+ fId= element.getAttributeAsIs(ID);
+ Assert.isLegal(fId != null);
+
+ fName= element.getAttribute(NAME);
+ if (fName == null)
+ fName= fId;
+
+ fClass= element.getAttributeAsIs(CLASS);
+ Assert.isLegal(fClass != null);
+
+ if (element.getAttributeAsIs(PREFERENCES_CLASS) == null)
+ fHasPreferences= false;
+ else
+ fHasPreferences= true;
+ }
+
+ /**
+ * Creates a folding provider as described in the extension's xml.
+ *
+ * @return a new instance of the folding provider described by this
+ * descriptor
+ * @throws CoreException if creation fails
+ */
+ public IJavaFoldingStructureProvider createProvider() throws CoreException {
+ IJavaFoldingStructureProvider prov= (IJavaFoldingStructureProvider) fElement.createExecutableExtension(CLASS);
+ return prov;
+ }
+
+ /**
+ * Creates a preferences object as described in the extension's xml.
+ *
+ * @return a new instance of the reference provider described by this
+ * descriptor
+ * @throws CoreException if creation fails
+ */
+ public IJavaFoldingPreferenceBlock createPreferences() throws CoreException {
+ if (fHasPreferences) {
+ IJavaFoldingPreferenceBlock prefs= (IJavaFoldingPreferenceBlock) fElement.createExecutableExtension(PREFERENCES_CLASS);
+ return prefs;
+ } else {
+ return new EmptyJavaFoldingPreferenceBlock();
+ }
+ }
+
+ /**
+ * Returns the identifier of the described extension.
+ *
+ * @return Returns the id
+ */
+ public String getId() {
+ return fId;
+ }
+
+ /**
+ * Returns the name of the described extension.
+ *
+ * @return Returns the name
+ */
+ public String getName() {
+ return fName;
+ }
+}
--- /dev/null
+/*******************************************************************************
+ * 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.folding;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
+import net.sourceforge.phpdt.ui.PreferenceConstants;
+import net.sourceforge.phpdt.ui.text.folding.IJavaFoldingStructureProvider;
+import net.sourceforge.phpeclipse.PHPeclipsePlugin;
+
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IConfigurationElement;
+import org.eclipse.core.runtime.IExtensionRegistry;
+import org.eclipse.core.runtime.Platform;
+
+/**
+ * @since 3.0
+ */
+public class JavaFoldingStructureProviderRegistry {
+
+ private static final String EXTENSION_POINT= "foldingStructureProviders"; //$NON-NLS-1$
+
+ /** The map of descriptors, indexed by their identifiers. */
+ private Map fDescriptors;
+
+ /**
+ * Creates a new instance.
+ */
+ public JavaFoldingStructureProviderRegistry() {
+ }
+
+ /**
+ * Returns an array of <code>IJavaFoldingProviderDescriptor</code> describing
+ * all extension to the <code>foldingProviders</code> extension point.
+ *
+ * @return the list of extensions to the
+ * <code>quickDiffReferenceProvider</code> extension point.
+ */
+ public JavaFoldingStructureProviderDescriptor[] getFoldingProviderDescriptors() {
+ synchronized (this) {
+ ensureRegistered();
+ return (JavaFoldingStructureProviderDescriptor[]) fDescriptors.values().toArray(new JavaFoldingStructureProviderDescriptor[fDescriptors.size()]);
+ }
+ }
+
+ /**
+ * Returns the folding provider with identifier <code>id</code> or
+ * <code>null</code> if no such provider is registered.
+ *
+ * @param id the identifier for which a provider is wanted
+ * @return the corresponding provider, or <code>null</code> if none can be
+ * found
+ */
+ public JavaFoldingStructureProviderDescriptor getFoldingProviderDescriptor(String id) {
+ synchronized (this) {
+ ensureRegistered();
+ return (JavaFoldingStructureProviderDescriptor) fDescriptors.get(id);
+ }
+ }
+
+ /**
+ * Instantiates and returns the provider that is currently configured in the
+ * preferences.
+ *
+ * @return the current provider according to the preferences
+ */
+ public IJavaFoldingStructureProvider getCurrentFoldingProvider() {
+ String id= PHPeclipsePlugin.getDefault().getPreferenceStore().getString(PreferenceConstants.EDITOR_FOLDING_PROVIDER);
+ JavaFoldingStructureProviderDescriptor desc= getFoldingProviderDescriptor(id);
+ if (desc != null) {
+ try {
+ return desc.createProvider();
+ } catch (CoreException e) {
+ PHPeclipsePlugin.log(e);
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Ensures that the extensions are read and stored in
+ * <code>fDescriptors</code>.
+ */
+ private void ensureRegistered() {
+ if (fDescriptors == null)
+ reloadExtensions();
+ }
+
+ /**
+ * Reads all extensions.
+ * <p>
+ * This method can be called more than once in
+ * order to reload from a changed extension registry.
+ * </p>
+ */
+ public void reloadExtensions() {
+ IExtensionRegistry registry= Platform.getExtensionRegistry();
+ Map map= new HashMap();
+
+ IConfigurationElement[] elements= registry.getConfigurationElementsFor(PHPeclipsePlugin.getPluginId(), EXTENSION_POINT);
+ for (int i= 0; i < elements.length; i++) {
+ JavaFoldingStructureProviderDescriptor desc= new JavaFoldingStructureProviderDescriptor(elements[i]);
+ map.put(desc.getId(), desc);
+ }
+
+ synchronized(this) {
+ fDescriptors= Collections.unmodifiableMap(map);
+ }
+ }
+
+}
import net.sourceforge.phpdt.core.JavaCore;
import net.sourceforge.phpeclipse.PHPeclipsePlugin;
import net.sourceforge.phpeclipse.phpeditor.EditorUtility;
-import net.sourceforge.phpeclipse.phpeditor.PHPDocumentProvider;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.ISharedImages;
// }
// return (IWorkingCopy[])result.toArray(new IWorkingCopy[result.size()]);
// }
-
+
/**
* Returns the BufferFactory for the Java UI plug-in.
*
*
* @see org.eclipse.jdt.core.IBufferFactory
* @since 2.0
+ * @deprecated {@link IBufferFactory} has been replaced by {@link org.eclipse.jdt.core.WorkingCopyOwner}.
+ * The Java UI plug-in uses the <i>primary working copy owner</i> that can be accessed with <code>null</code> in
+ * API's that require an owner
*/
public static IBufferFactory getBufferFactory() {
- PHPDocumentProvider provider= PHPeclipsePlugin.getDefault().getCompilationUnitDocumentProvider();
- if (provider != null)
- return provider.getBufferFactory();
- return null;
+ return PHPeclipsePlugin.getDefault().getBufferFactory();
}
-
/**
* Returns the DocumentProvider used for Java compilation units.
*
*/
public static final String EDITOR_TEXT_HOVER_MODIFIER_MASKS = "hoverModifierMasks"; //$NON-NLS-1$
+ /**
+ * A named preference that controls whether folding is enabled in the Java editor.
+ * <p>
+ * Value is of type <code>Boolean</code>.
+ * </p>
+ *
+ * @since 3.0
+ */
+ public static final String EDITOR_FOLDING_ENABLED= "editor_folding_enabled"; //$NON-NLS-1$
+
+ /**
+ * A named preference that stores the configured folding provider.
+ * <p>
+ * Value is of type <code>String</code>.
+ * </p>
+ *
+ * @since 3.0
+ */
+ public static final String EDITOR_FOLDING_PROVIDER= "editor_folding_provider"; //$NON-NLS-1$
+
+ /**
+ * A named preference that stores the value for Javadoc folding for the default folding provider.
+ * <p>
+ * Value is of type <code>Boolean</code>.
+ * </p>
+ *
+ * @since 3.0
+ */
+ public static final String EDITOR_FOLDING_JAVADOC= "editor_folding_default_javadoc"; //$NON-NLS-1$
+
+ /**
+ * A named preference that stores the value for inner type folding for the default folding provider.
+ * <p>
+ * Value is of type <code>Boolean</code>.
+ * </p>
+ *
+ * @since 3.0
+ */
+ public static final String EDITOR_FOLDING_INNERTYPES= "editor_folding_default_innertypes"; //$NON-NLS-1$
+
+ /**
+ * A named preference that stores the value for method folding for the default folding provider.
+ * <p>
+ * Value is of type <code>Boolean</code>.
+ * </p>
+ *
+ * @since 3.0
+ */
+ public static final String EDITOR_FOLDING_METHODS= "editor_folding_default_methods"; //$NON-NLS-1$
+
+ /**
+ * A named preference that stores the value for imports folding for the default folding provider.
+ * <p>
+ * Value is of type <code>Boolean</code>.
+ * </p>
+ *
+ * @since 3.0
+ */
+ public static final String EDITOR_FOLDING_IMPORTS= "editor_folding_default_imports"; //$NON-NLS-1$
+
+
public static void initializeDefaultValues(IPreferenceStore store) {
store.setDefault(PreferenceConstants.EDITOR_SHOW_SEGMENTS, false);
store.setDefault(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER, ctrl);
store.setDefault(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK, SWT.CTRL);
+ // folding
+ store.setDefault(PreferenceConstants.EDITOR_FOLDING_ENABLED, true);
+ store.setDefault(PreferenceConstants.EDITOR_FOLDING_PROVIDER, "org.eclipse.jdt.ui.text.defaultFoldingProvider"); //$NON-NLS-1$
+ store.setDefault(PreferenceConstants.EDITOR_FOLDING_JAVADOC, false);
+ store.setDefault(PreferenceConstants.EDITOR_FOLDING_INNERTYPES, true);
+ store.setDefault(PreferenceConstants.EDITOR_FOLDING_METHODS, false);
+ store.setDefault(PreferenceConstants.EDITOR_FOLDING_IMPORTS, true);
+
// do more complicated stuff
// NewJavaProjectPreferencePage.initDefaults(store);
}
--- /dev/null
+/*******************************************************************************
+ * 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.folding;
+
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+
+
+/**
+ * Contributors to the <code>net.sourceforge.phpdt.ui.foldingStructureProvider</code> extension point
+ * can specify an implementation of this interface to be displayed on the Java > Editor > Folding
+ * preference page.
+ * <p>
+ * Clients may implement this interface.
+ * </p>
+ *
+ * @since 3.0
+ */
+public interface IJavaFoldingPreferenceBlock {
+
+ /**
+ * Creates the control that will be displayed on the Java Editor folding
+ * preference page.
+ *
+ * @param parent the parent composite to which to add the preferences control
+ * @return the control that was added to <code>parent</code>
+ */
+ Control createControl(Composite parent);
+
+ /**
+ * Called after creating the control. Implementations should load the
+ * preferences values and update the controls accordingly.
+ */
+ void initialize();
+
+ /**
+ * Called when the <code>OK</code> button is pressed on the preference
+ * page. Implementations should commit the configured preference settings
+ * into their form of preference storage.
+ */
+ void performOk();
+
+ /**
+ * Called when the <code>Defaults</code> button is pressed on the
+ * preference page. Implementation should reset any preference settings to
+ * their default values and adjust the controls accordingly.
+ */
+ void performDefaults();
+
+ /**
+ * Called when the preference page is being disposed. Implementations should
+ * free any resources they are holding on to.
+ */
+ void dispose();
+
+}
--- /dev/null
+/*******************************************************************************
+ * 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.folding;
+
+import org.eclipse.jface.text.source.projection.ProjectionViewer;
+
+import org.eclipse.ui.texteditor.ITextEditor;
+
+/**
+ * Contributors to the
+ * <code>net.sourceforge.phpdt.ui.foldingStructureProvider</code> extension
+ * point must specify an implementation of this interface which will create and
+ * maintain
+ * {@link org.eclipse.jface.text.source.projection.ProjectionAnnotation} objects
+ * as understood by
+ * {@link org.eclipse.jface.text.source.projection.ProjectionViewer}.
+ * <p>
+ * Clients may implement this interface.
+ * </p>
+ *
+ * @since 3.0
+ */
+public interface IJavaFoldingStructureProvider {
+
+ /**
+ * Installs this structure provider on the given editor and viewer.
+ * Implementations should observe the projection events generated by
+ * <code>viewer</code> and enable / disable generation of projection
+ * structure accordingly.
+ *
+ * @param editor the editor that this provider works on
+ * @param viewer the projection viewer that displays the annotations created
+ * by this structure provider
+ */
+ public abstract void install(ITextEditor editor, ProjectionViewer viewer);
+
+ /**
+ * Uninstalls this structure provider. Any references to editors or viewers
+ * should be cleared.
+ */
+ public abstract void uninstall();
+
+ /**
+ * (Re-)initializes the structure provided by the receiver.
+ */
+ public abstract void initialize();
+}
--- /dev/null
+<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+ <meta name="Author" content="IBM">
+ <meta name="GENERATOR" content="Eclipse Text Editor">
+ <title>Java Folding</title>
+</head>
+<body>
+Application programming interfaces for interaction
+with the Eclipse Java Editor folding.
+<h2>
+Package Specification</h2>
+Interfaces for contributions to the <code>org.eclipse.jdt.ui.foldingStructureProviders</code> extension point.
+</body>
+</html>
import java.util.List;
import java.util.Set;
+import net.sourceforge.phpdt.core.IBuffer;
+import net.sourceforge.phpdt.core.IBufferFactory;
+import net.sourceforge.phpdt.core.ICompilationUnit;
+import net.sourceforge.phpdt.core.IJavaElement;
import net.sourceforge.phpdt.core.JavaCore;
+import net.sourceforge.phpdt.core.WorkingCopyOwner;
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.core.JavaModelManager;
+import net.sourceforge.phpdt.internal.ui.JavaElementAdapterFactory;
+import net.sourceforge.phpdt.internal.ui.ResourceAdapterFactory;
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.phpeclipse.builder.ExternalStorageDocumentProvider;
import net.sourceforge.phpeclipse.builder.FileStorage;
import net.sourceforge.phpeclipse.builder.IdentifierIndexManager;
+import net.sourceforge.phpeclipse.phpeditor.CustomBufferFactory;
+import net.sourceforge.phpeclipse.phpeditor.DocumentAdapter;
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;
-import net.sourceforge.phpeclipse.resourcesview.ResourceAdapterFactory;
import org.eclipse.core.boot.BootLoader;
import org.eclipse.core.resources.IFile;
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.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
+import net.sourceforge.phpdt.internal.ui.text.folding.JavaFoldingStructureProviderRegistry;
+
+import net.sourceforge.phpdt.internal.ui.text.PreferencesAdapter;
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.resource.JFaceResources;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
+import org.eclipse.jface.util.IPropertyChangeListener;
+import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IEditorDescriptor;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.editors.text.EditorsUI;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.plugin.AbstractUIPlugin;
+import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants;
+import org.eclipse.ui.texteditor.ChainedPreferenceStore;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.ui.texteditor.MarkerAnnotationPreferences;
+import org.osgi.framework.BundleContext;
/**
* The main plugin class to be used in the desktop.
*/
private ImageDescriptorRegistry fImageDescriptorRegistry;
private HashMap fIndexManagerMap = new HashMap();
private IWorkingCopyManager fWorkingCopyManager;
+ private IBufferFactory fBufferFactory;
private PHPDocumentProvider fCompilationUnitDocumentProvider;
private JavaTextTools fJavaTextTools;
private ProblemMarkerManager fProblemMarkerManager;
private MembersOrderPreferenceCache fMembersOrderPreferenceCache;
private IFile fLastEditorFile = null;
private JavaEditorTextHoverDescriptor[] fJavaEditorTextHoverDescriptors;
+
+ private JavaElementAdapterFactory fJavaElementAdapterFactory;
+// private MarkerAdapterFactory fMarkerAdapterFactory;
+// private EditorInputAdapterFactory fEditorInputAdapterFactory;
+ private ResourceAdapterFactory fResourceAdapterFactory;
+// private LogicalPackageAdapterFactory fLogicalPackageAdapterFactory;
+ private IPropertyChangeListener fFontPropertyChangeListener;
+ /**
+ * Property change listener on this plugin's preference store.
+ *
+ * @since 3.0
+ */
+ private IPropertyChangeListener fPropertyChangeListener;
+
+ /**
+ * The combined preference store.
+ * @since 3.0
+ */
+ private IPreferenceStore fCombinedPreferenceStore;
+ /**
+ * The extension point registry for the <code>org.eclipse.jdt.ui.javaFoldingStructureProvider</code>
+ * extension point.
+ *
+ * @since 3.0
+ */
+ private JavaFoldingStructureProviderRegistry fFoldingStructureProviderRegistry;
/**
* The constructor.
*/
fCompilationUnitDocumentProvider = new PHPDocumentProvider();
return fCompilationUnitDocumentProvider;
}
+
/**
* Get the identifier index manager for the given project
*
fProblemMarkerManager = new ProblemMarkerManager();
return fProblemMarkerManager;
}
+
public synchronized JavaTextTools getJavaTextTools() {
if (fJavaTextTools == null)
fJavaTextTools = new JavaTextTools(getPreferenceStore());
public void setLastEditorFile(IFile textEditor) {
this.fLastEditorFile = textEditor;
}
+ /*
+ * @see org.eclipse.core.runtime.Plugin#stop
+ */
+ public void stop(BundleContext context) throws Exception {
+ try {
+ JavaCore.stop(this, context);
+
+ ColorManager.getDefault().dispose();
+ // save the information from the php index files if necessary
+ Collection collection = fIndexManagerMap.values();
+ Iterator iterator = collection.iterator();
+ IdentifierIndexManager indexManager = null;
+ while (iterator.hasNext()) {
+ indexManager = (IdentifierIndexManager) iterator.next();
+ indexManager.writeFile();
+ }
+ if (fImageDescriptorRegistry != null)
+ fImageDescriptorRegistry.dispose();
+
+// AllTypesCache.terminate();
+
+ if (fImageDescriptorRegistry != null)
+ fImageDescriptorRegistry.dispose();
+
+ unregisterAdapters();
+
+// if (fASTProvider != null) {
+// fASTProvider.dispose();
+// fASTProvider= null;
+// }
+
+ if (fWorkingCopyManager != null) {
+ fWorkingCopyManager.shutdown();
+ fWorkingCopyManager= null;
+ }
+
+ if (fCompilationUnitDocumentProvider != null) {
+ fCompilationUnitDocumentProvider.shutdown();
+ fCompilationUnitDocumentProvider= null;
+ }
+
+ if (fJavaTextTools != null) {
+ fJavaTextTools.dispose();
+ fJavaTextTools= null;
+ }
+// JavaDocLocations.shutdownJavadocLocations();
+
+ uninstallPreferenceStoreBackwardsCompatibility();
+
+// RefactoringCore.getUndoManager().shutdown();
+ } finally {
+ super.stop(context);
+ }
+ }
/**
* @see org.eclipse.ui.plugin.AbstractUIPlugin#shutdown()
*/
- public void shutdown() throws CoreException {
- // moved down (see below):
- // super.shutdown();
- // externalTools.shutDown();
- ColorManager.getDefault().dispose();
- // save the information from the php index files if necessary
- Collection collection = fIndexManagerMap.values();
- Iterator iterator = collection.iterator();
- IdentifierIndexManager indexManager = null;
- while (iterator.hasNext()) {
- indexManager = (IdentifierIndexManager) iterator.next();
- indexManager.writeFile();
- }
- if (fImageDescriptorRegistry != null)
- fImageDescriptorRegistry.dispose();
- // unregisterAdapters();
- super.shutdown();
- if (fWorkingCopyManager != null) {
- fWorkingCopyManager.shutdown();
- fWorkingCopyManager = null;
- }
- if (fCompilationUnitDocumentProvider != null) {
- fCompilationUnitDocumentProvider.shutdown();
- fCompilationUnitDocumentProvider = null;
- }
- if (fJavaTextTools != null) {
- fJavaTextTools.dispose();
- fJavaTextTools = null;
- }
- // JavaDocLocations.shutdownJavadocLocations();
- //
- // JFaceResources.getFontRegistry().removeListener(fFontPropertyChangeListener);
- // begin JavaCore#shutdown()
- //savePluginPreferences();
- savePluginPreferences();
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
- workspace.removeResourceChangeListener(JavaModelManager
- .getJavaModelManager().deltaProcessor);
- workspace.removeSaveParticipant(PHPeclipsePlugin.getDefault());
- ((JavaModelManager) JavaModelManager.getJavaModelManager()).shutdown();
- // end JavaCore#shutdown()
- }
- public void startup() throws CoreException {
- super.startup();
- // begin JavaCore.startup();
- JavaModelManager manager = JavaModelManager.getJavaModelManager();
- try {
- manager.configurePluginDebugOptions();
- // request state folder creation (workaround 19885)
- // JavaCore.getPlugin().getStateLocation();
- getStateLocation();
- // retrieve variable values
- // JavaCore.getPlugin().getPluginPreferences().addPropertyChangeListener(new
- // JavaModelManager.PluginPreferencesListener());
- 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;
- }
- // end JavaCore.startup();
- IAdapterManager platformManager = Platform.getAdapterManager();
- platformManager.registerAdapters(new PHPElementAdapterFactory(),
- PHPElement.class);
- platformManager.registerAdapters(new ResourceAdapterFactory(),
- IResource.class);
- // externalTools.startUp();
- getStandardDisplay().asyncExec(new Runnable() {
- public void run() {
- //initialize the variable context manager
- VariableContextManager.getDefault();
- }
- });
- }
+// public void shutdown() throws CoreException {
+// // moved down (see below):
+// // super.shutdown();
+// // externalTools.shutDown();
+// ColorManager.getDefault().dispose();
+// // save the information from the php index files if necessary
+// Collection collection = fIndexManagerMap.values();
+// Iterator iterator = collection.iterator();
+// IdentifierIndexManager indexManager = null;
+// while (iterator.hasNext()) {
+// indexManager = (IdentifierIndexManager) iterator.next();
+// indexManager.writeFile();
+// }
+// if (fImageDescriptorRegistry != null)
+// fImageDescriptorRegistry.dispose();
+// // unregisterAdapters();
+// super.shutdown();
+// if (fWorkingCopyManager != null) {
+// fWorkingCopyManager.shutdown();
+// fWorkingCopyManager = null;
+// }
+// if (fCompilationUnitDocumentProvider != null) {
+// fCompilationUnitDocumentProvider.shutdown();
+// fCompilationUnitDocumentProvider = null;
+// }
+// if (fJavaTextTools != null) {
+// fJavaTextTools.dispose();
+// fJavaTextTools = null;
+// }
+// // JavaDocLocations.shutdownJavadocLocations();
+// //
+// // JFaceResources.getFontRegistry().removeListener(fFontPropertyChangeListener);
+// // begin JavaCore#shutdown()
+// //savePluginPreferences();
+// savePluginPreferences();
+// IWorkspace workspace = ResourcesPlugin.getWorkspace();
+// workspace.removeResourceChangeListener(JavaModelManager.getJavaModelManager().deltaState);
+// workspace.removeSaveParticipant(this);
+// ((JavaModelManager) JavaModelManager.getJavaModelManager()).shutdown();
+// // end JavaCore#shutdown()
+// }
+ /**
+ * Installs backwards compatibility for the preference store.
+ */
+ private void installPreferenceStoreBackwardsCompatibility() {
+
+ /*
+ * Installs backwards compatibility: propagate the Java editor font from a
+ * pre-2.1 plug-in to the Platform UI's preference store to preserve
+ * the Java editor font from a pre-2.1 workspace. This is done only
+ * once.
+ */
+ String fontPropagatedKey= "fontPropagated"; //$NON-NLS-1$
+ if (getPreferenceStore().contains(JFaceResources.TEXT_FONT) && !getPreferenceStore().isDefault(JFaceResources.TEXT_FONT)) {
+ if (!getPreferenceStore().getBoolean(fontPropagatedKey))
+ PreferenceConverter.setValue(PlatformUI.getWorkbench().getPreferenceStore(), PreferenceConstants.EDITOR_TEXT_FONT, PreferenceConverter.getFontDataArray(getPreferenceStore(), JFaceResources.TEXT_FONT));
+ }
+ getPreferenceStore().setValue(fontPropagatedKey, true);
+
+ /*
+ * Backwards compatibility: set the Java editor font in this plug-in's
+ * preference store to let older versions access it. Since 2.1 the
+ * Java editor font is managed by the workbench font preference page.
+ */
+ PreferenceConverter.putValue(getPreferenceStore(), JFaceResources.TEXT_FONT, JFaceResources.getFontRegistry().getFontData(PreferenceConstants.EDITOR_TEXT_FONT));
+
+ fFontPropertyChangeListener= new IPropertyChangeListener() {
+ public void propertyChange(PropertyChangeEvent event) {
+ if (PreferenceConstants.EDITOR_TEXT_FONT.equals(event.getProperty()))
+ PreferenceConverter.putValue(getPreferenceStore(), JFaceResources.TEXT_FONT, JFaceResources.getFontRegistry().getFontData(PreferenceConstants.EDITOR_TEXT_FONT));
+ }
+ };
+ JFaceResources.getFontRegistry().addListener(fFontPropertyChangeListener);
+
+ /*
+ * Backwards compatibility: propagate the Java editor tab width from a
+ * pre-3.0 plug-in to the new preference key. This is done only once.
+ */
+ final String oldTabWidthKey= PreferenceConstants.EDITOR_TAB_WIDTH;
+ final String newTabWidthKey= AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH;
+ String tabWidthPropagatedKey= "tabWidthPropagated"; //$NON-NLS-1$
+ if (getPreferenceStore().contains(oldTabWidthKey) && !getPreferenceStore().isDefault(oldTabWidthKey)) {
+ if (!getPreferenceStore().getBoolean(tabWidthPropagatedKey))
+ getPreferenceStore().setValue(newTabWidthKey, getPreferenceStore().getInt(oldTabWidthKey));
+ }
+ getPreferenceStore().setValue(tabWidthPropagatedKey, true);
+
+ /*
+ * Backwards compatibility: set the Java editor tab width in this plug-in's
+ * preference store with the old key to let older versions access it.
+ * Since 3.0 the tab width is managed by the extended texteditor and
+ * uses a new key.
+ */
+ getPreferenceStore().putValue(oldTabWidthKey, getPreferenceStore().getString(newTabWidthKey));
+
+ fPropertyChangeListener= new IPropertyChangeListener() {
+ public void propertyChange(PropertyChangeEvent event) {
+ if (newTabWidthKey.equals(event.getProperty()))
+ getPreferenceStore().putValue(oldTabWidthKey, getPreferenceStore().getString(newTabWidthKey));
+ }
+ };
+ getPreferenceStore().addPropertyChangeListener(fPropertyChangeListener);
+
+ /*
+ * Backward compatibility for the refactoring preference key.
+ */
+// getPreferenceStore().setValue(
+// PreferenceConstants.REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD,
+// RefactoringCore.getConditionCheckingFailedSeverity());
+ }
+
+ /**
+ * Uninstalls backwards compatibility for the preference store.
+ */
+ private void uninstallPreferenceStoreBackwardsCompatibility() {
+ JFaceResources.getFontRegistry().removeListener(fFontPropertyChangeListener);
+ getPreferenceStore().removePropertyChangeListener(fPropertyChangeListener);
+ }
+ /* (non - Javadoc)
+ * Method declared in Plugin
+ */
+ public void start(BundleContext context) throws Exception {
+ super.start(context);
+
+ JavaCore.start(this, context);
+
+ registerAdapters();
+
+ // externalTools.startUp();
+ getStandardDisplay().asyncExec(new Runnable() {
+ public void run() {
+ //initialize the variable context manager
+ VariableContextManager.getDefault();
+ }
+ });
+
+// if (USE_WORKING_COPY_OWNERS) {
+ WorkingCopyOwner.setPrimaryBufferProvider(new WorkingCopyOwner() {
+ public IBuffer createBuffer(ICompilationUnit workingCopy) {
+ ICompilationUnit original= workingCopy.getPrimary();
+ IResource resource= original.getResource();
+ if (resource instanceof IFile)
+ return new DocumentAdapter(workingCopy, (IFile) resource);
+ return DocumentAdapter.NULL;
+ }
+ });
+// }
+
+ installPreferenceStoreBackwardsCompatibility();
+
+// AllTypesCache.initialize();
+
+ // Initialize AST provider
+// getASTProvider();
+ }
+// public void startup() throws CoreException {
+// super.startup();
+// // begin JavaCore.startup();
+// JavaModelManager manager = JavaModelManager.getJavaModelManager();
+// try {
+// manager.configurePluginDebugOptions();
+// // request state folder creation (workaround 19885)
+// // JavaCore.getPlugin().getStateLocation();
+// getStateLocation();
+// // retrieve variable values
+// // JavaCore.getPlugin().getPluginPreferences().addPropertyChangeListener(new
+// // JavaModelManager.PluginPreferencesListener());
+// getPluginPreferences().addPropertyChangeListener(
+// new JavaModelManager.PluginPreferencesListener());
+// // TODO khartlage temp-del
+// // manager.loadVariablesAndContainers();
+// final IWorkspace workspace = ResourcesPlugin.getWorkspace();
+// workspace.addResourceChangeListener(
+// manager.deltaState,
+// IResourceChangeEvent.PRE_BUILD
+// | IResourceChangeEvent.POST_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;
+// }
+// // end JavaCore.startup();
+// IAdapterManager platformManager = Platform.getAdapterManager();
+// platformManager.registerAdapters(new PHPElementAdapterFactory(),
+// PHPElement.class);
+// platformManager.registerAdapters(new ResourceAdapterFactory(),
+// IResource.class);
+// // externalTools.startUp();
+// getStandardDisplay().asyncExec(new Runnable() {
+// public void run() {
+// //initialize the variable context manager
+// VariableContextManager.getDefault();
+// }
+// });
+// }
+
+
+ private void registerAdapters() {
+ fJavaElementAdapterFactory= new JavaElementAdapterFactory();
+// fMarkerAdapterFactory= new MarkerAdapterFactory();
+// fEditorInputAdapterFactory= new EditorInputAdapterFactory();
+ fResourceAdapterFactory= new ResourceAdapterFactory();
+// fLogicalPackageAdapterFactory= new LogicalPackageAdapterFactory();
+
+ IAdapterManager manager= Platform.getAdapterManager();
+ manager.registerAdapters(fJavaElementAdapterFactory, IJavaElement.class);
+// manager.registerAdapters(fMarkerAdapterFactory, IMarker.class);
+// manager.registerAdapters(fEditorInputAdapterFactory, IEditorInput.class);
+ manager.registerAdapters(fResourceAdapterFactory, IResource.class);
+// manager.registerAdapters(fLogicalPackageAdapterFactory, LogicalPackage.class);
+ }
+
+ private void unregisterAdapters() {
+ IAdapterManager manager= Platform.getAdapterManager();
+ manager.unregisterAdapters(fJavaElementAdapterFactory);
+// manager.unregisterAdapters(fMarkerAdapterFactory);
+// manager.unregisterAdapters(fEditorInputAdapterFactory);
+ manager.unregisterAdapters(fResourceAdapterFactory);
+// manager.unregisterAdapters(fLogicalPackageAdapterFactory);
+ }
+
+ /**
+ * Returns a combined preference store, this store is read-only.
+ *
+ * @return the combined preference store
+ *
+ * @since 3.0
+ */
+ public IPreferenceStore getCombinedPreferenceStore() {
+ if (fCombinedPreferenceStore == null) {
+ IPreferenceStore generalTextStore= EditorsUI.getPreferenceStore();
+ fCombinedPreferenceStore= new ChainedPreferenceStore(new IPreferenceStore[] { getPreferenceStore(), new PreferencesAdapter(JavaCore.getPlugin().getPluginPreferences()), generalTextStore });
+ }
+ return fCombinedPreferenceStore;
+ }
+
+ public synchronized IBufferFactory getBufferFactory() {
+ if (fBufferFactory == null)
+ fBufferFactory= new CustomBufferFactory();
+ return fBufferFactory;
+ }
+ /**
+ * Returns the registry of the extensions to the <code>org.eclipse.jdt.ui.javaFoldingStructureProvider</code>
+ * extension point.
+ *
+ * @return the registry of contributed <code>IJavaFoldingStructureProvider</code>
+ * @since 3.0
+ */
+ public synchronized JavaFoldingStructureProviderRegistry getFoldingStructureProviderRegistry() {
+ if (fFoldingStructureProviderRegistry == null)
+ fFoldingStructureProviderRegistry= new JavaFoldingStructureProviderRegistry();
+ return fFoldingStructureProviderRegistry;
+ }
}
\ No newline at end of file
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.transform.OutputKeys;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
import net.sourceforge.phpeclipse.PHPeclipsePlugin;
-import org.apache.xml.serialize.OutputFormat;
-import org.apache.xml.serialize.Serializer;
-import org.apache.xml.serialize.SerializerFactory;
+
import org.eclipse.core.runtime.CoreException;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
Text pattern = document.createTextNode((String) iter.next());
node.appendChild(pattern);
}
+ Transformer transformer=TransformerFactory.newInstance().newTransformer();
+ transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
+ transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); //$NON-NLS-1$
+ DOMSource source = new DOMSource(document);
+ StreamResult result = new StreamResult(stream);
- OutputFormat format = new OutputFormat();
- format.setPreserveSpace(true);
- Serializer serializer = SerializerFactory.getSerializerFactory("xml").makeSerializer(stream, format); //$NON-NLS-1$
- serializer.asDOMSerializer().serialize(document);
+ transformer.transform(source, result);
} catch (ParserConfigurationException e) {
throwWriteException(e);
- } catch (IOException e) {
+ } catch (TransformerException e) {
throwWriteException(e);
- }
+ }
+// OutputFormat format = new OutputFormat();
+// format.setPreserveSpace(true);
+// Serializer serializer = SerializerFactory.getSerializerFactory("xml").makeSerializer(stream, format); //$NON-NLS-1$
+// serializer.asDOMSerializer().serialize(document);
+//
+// } catch (ParserConfigurationException e) {
+// throwWriteException(e);
+// } catch (IOException e) {
+// throwWriteException(e);
+// }
}
private static void throwReadException(Throwable t) throws CoreException {
import java.util.List;
import java.util.ResourceBundle;
+import net.sourceforge.phpdt.internal.ui.actions.FoldingActionGroup;
import net.sourceforge.phpdt.ui.IContextMenuConstants;
import net.sourceforge.phpdt.ui.actions.GotoMatchingBracketAction;
import net.sourceforge.phpdt.ui.actions.PHPdtActionConstants;
if (part instanceof PHPEditor) {
PHPEditor javaEditor= (PHPEditor) part;
javaEditor.getActionGroup().fillActionBars(getActionBars());
+ FoldingActionGroup foldingActions= javaEditor.getFoldingActionGroup();
+ if (foldingActions != null)
+ foldingActions.updateActionBars();
}
}
-import org.eclipse.core.resources.IResource;
+import net.sourceforge.phpeclipse.PHPeclipsePlugin;
+import org.eclipse.core.resources.IMarker;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.jface.text.Position;
+import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.AnnotationModelEvent;
import org.eclipse.jface.text.source.IAnnotationModel;
+import org.eclipse.ui.texteditor.MarkerAnnotation;
+
/**
* Event sent out by changes of the compilation unit annotation model.
*/
public class CompilationUnitAnnotationModelEvent extends AnnotationModelEvent {
- private boolean fIncludesMarkerAnnotationChanges;
+ private boolean fIncludesProblemMarkerAnnotations;
private IResource fUnderlyingResource;
-
/**
* Constructor for CompilationUnitAnnotationModelEvent.
* @param model
* @param underlyingResource The annotation model's underlying resource
- * @param includesMarkerAnnotationChanges
*/
- public CompilationUnitAnnotationModelEvent(IAnnotationModel model, IResource underlyingResource, boolean includesMarkerAnnotationChanges) {
+ public CompilationUnitAnnotationModelEvent(IAnnotationModel model, IResource underlyingResource) {
super(model);
- fIncludesMarkerAnnotationChanges= includesMarkerAnnotationChanges;
fUnderlyingResource= underlyingResource;
+ fIncludesProblemMarkerAnnotations= false;
+ }
+
+ private void testIfProblemMarker(Annotation annotation) {
+ if (fIncludesProblemMarkerAnnotations) {
+ return;
+ }
+ if (annotation instanceof JavaMarkerAnnotation) {
+ fIncludesProblemMarkerAnnotations= ((JavaMarkerAnnotation) annotation).isProblem();
+ } else if (annotation instanceof MarkerAnnotation) {
+ try {
+ IMarker marker= ((MarkerAnnotation) annotation).getMarker();
+ if (!marker.exists() || marker.isSubtypeOf(IMarker.PROBLEM)) {
+ fIncludesProblemMarkerAnnotations= true;
+ }
+ } catch (CoreException e) {
+ PHPeclipsePlugin.log(e);
+ }
+ }
+ }
+
+ /*
+ * @see org.eclipse.jface.text.source.AnnotationModelEvent#annotationAdded(org.eclipse.jface.text.source.Annotation)
+ */
+ public void annotationAdded(Annotation annotation) {
+ super.annotationAdded(annotation);
+ testIfProblemMarker(annotation);
+ }
+
+
+ /*
+ * @see org.eclipse.jface.text.source.AnnotationModelEvent#annotationRemoved(org.eclipse.jface.text.source.Annotation)
+ */
+ public void annotationRemoved(Annotation annotation) {
+ super.annotationRemoved(annotation);
+ testIfProblemMarker(annotation);
+ }
+
+ /*
+ * @see org.eclipse.jface.text.source.AnnotationModelEvent#annotationRemoved(org.eclipse.jface.text.source.Annotation, org.eclipse.jface.text.Position)
+ */
+ public void annotationRemoved(Annotation annotation, Position position) {
+ super.annotationRemoved(annotation, position);
+ testIfProblemMarker(annotation);
}
+ /*
+ * @see org.eclipse.jface.text.source.AnnotationModelEvent#annotationChanged(org.eclipse.jface.text.source.Annotation)
+ */
+ public void annotationChanged(Annotation annotation) {
+ testIfProblemMarker(annotation);
+ super.annotationChanged(annotation);
+ }
+
/**
- * Returns whether the change included marker annotations.
+ * Returns whether the change included problem marker annotations.
*
* @return <code>true</code> if the change included marker annotations
*/
- public boolean includesMarkerAnnotationChanges() {
- return fIncludesMarkerAnnotationChanges;
+ public boolean includesProblemMarkerAnnotationChanges() {
+ return fIncludesProblemMarkerAnnotations;
}
/**
--- /dev/null
+/**********************************************************************
+Copyright (c) 2000, 2003 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 implementation
+**********************************************************************/
+
+package net.sourceforge.phpeclipse.phpeditor;
+
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IResource;
+
+import net.sourceforge.phpdt.core.IBuffer;
+import net.sourceforge.phpdt.core.IBufferFactory;
+import net.sourceforge.phpdt.core.ICompilationUnit;
+import net.sourceforge.phpdt.core.IOpenable;
+
+
+/**
+ * Creates <code>IBuffer</code>s based on documents.
+ * @deprecated since 3.0 no longer used
+ */
+public class CustomBufferFactory implements IBufferFactory {
+
+ /*
+ * @see org.eclipse.jdt.core.IBufferFactory#createBuffer(org.eclipse.jdt.core.IOpenable)
+ */
+ public IBuffer createBuffer(IOpenable owner) {
+ if (owner instanceof ICompilationUnit) {
+ ICompilationUnit unit= (ICompilationUnit) owner;
+ ICompilationUnit original= unit.getPrimary();
+ IResource resource= original.getResource();
+ if (resource instanceof IFile) {
+ return new DocumentAdapter(unit, (IFile) resource);
+ }
+
+ }
+ return DocumentAdapter.NULL;
+ }
+}
\ No newline at end of file
import java.util.ArrayList;
+import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
+import java.util.Set;
import net.sourceforge.phpdt.core.BufferChangedEvent;
import net.sourceforge.phpdt.core.IBuffer;
import net.sourceforge.phpdt.core.IBufferChangedListener;
import net.sourceforge.phpdt.core.IOpenable;
import net.sourceforge.phpdt.core.JavaModelException;
+import net.sourceforge.phpeclipse.PHPeclipsePlugin;
+import org.eclipse.core.filebuffers.FileBuffers;
+import org.eclipse.core.filebuffers.ITextFileBuffer;
+import org.eclipse.core.filebuffers.ITextFileBufferManager;
+import org.eclipse.core.resources.IFile;
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.IStatus;
+import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.jface.text.Assert;
import org.eclipse.jface.text.BadLocationException;
+import org.eclipse.jface.text.DefaultLineTracker;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentListener;
-import org.eclipse.jface.text.ILineTracker;
-import org.eclipse.jface.text.IRegion;
import org.eclipse.swt.widgets.Display;
* Internal implementation of a NULL instanceof IBuffer.
*/
static private class NullBuffer implements IBuffer {
-
public void addBufferChangedListener(IBufferChangedListener listener) {}
-
public void append(char[] text) {}
-
public void append(String text) {}
-
public void close() {}
-
- public char getChar(int position) {
- return 0;
- }
-
- public char[] getCharacters() {
- return null;
- }
-
- public String getContents() {
- return null;
- }
-
- public int getLength() {
- return 0;
- }
-
- public IOpenable getOwner() {
- return null;
- }
-
- public String getText(int offset, int length) {
- return null;
- }
-
- public IResource getUnderlyingResource() {
- return null;
- }
-
- public boolean hasUnsavedChanges() {
- return false;
- }
-
- public boolean isClosed() {
- return false;
- }
-
- public boolean isReadOnly() {
- return true;
- }
-
+ public char getChar(int position) { return 0; }
+ public char[] getCharacters() { return null; }
+ public String getContents() { return null; }
+ public int getLength() { return 0; }
+ public IOpenable getOwner() { return null; }
+ public String getText(int offset, int length) { return null; }
+ public IResource getUnderlyingResource() { return null; }
+ public boolean hasUnsavedChanges() { return false; }
+ public boolean isClosed() { return false; }
+ public boolean isReadOnly() { return true; }
public void removeBufferChangedListener(IBufferChangedListener listener) {}
-
public void replace(int position, int length, char[] text) {}
-
public void replace(int position, int length, String text) {}
-
public void save(IProgressMonitor progress, boolean force) throws JavaModelException {}
-
public void setContents(char[] contents) {}
-
public void setContents(String contents) {}
- };
-
-
- /** NULL implementing <code>IBuffer</code> */
- public final static IBuffer NULL= new NullBuffer();
-
-
- /**
- * Executes a document set content call in the ui thread.
- */
- protected class DocumentSetCommand implements Runnable {
-
- private String fContents;
-
- public void run() {
- fDocument.set(fContents);
}
- public void set(String contents) {
- fContents= contents;
- Display.getDefault().syncExec(this);
- }
- };
- /**
- * Executes a document replace call in the ui thread.
- */
- protected class DocumentReplaceCommand implements Runnable {
+ /** NULL implementing <code>IBuffer</code> */
+ public final static IBuffer NULL= new NullBuffer();
+
- private int fOffset;
- private int fLength;
- private String fText;
+ /**
+ * Executes a document set content call in the ui thread.
+ */
+ protected class DocumentSetCommand implements Runnable {
+
+ private String fContents;
+
+ public void run() {
+ fDocument.set(fContents);
+ }
- public void run() {
- try {
- fDocument.replace(fOffset, fLength, fText);
- } catch (BadLocationException x) {
- // ignore
+ public void set(String contents) {
+ fContents= contents;
+ Display.getDefault().syncExec(this);
}
}
- public void replace(int offset, int length, String text) {
- fOffset= offset;
- fLength= length;
- fText= text;
- Display.getDefault().syncExec(this);
+ /**
+ * Executes a document replace call in the ui thread.
+ */
+ protected class DocumentReplaceCommand implements Runnable {
+
+ private int fOffset;
+ private int fLength;
+ private String fText;
+
+ public void run() {
+ try {
+ fDocument.replace(fOffset, fLength, fText);
+ } catch (BadLocationException x) {
+ // ignore
+ }
+ }
+
+ public void replace(int offset, int length, String text) {
+ fOffset= offset;
+ fLength= length;
+ fText= text;
+ Display.getDefault().syncExec(this);
+ }
}
- };
+
+ private static final boolean DEBUG_LINE_DELIMITERS= true;
private IOpenable fOwner;
+ private IFile fFile;
+ private ITextFileBuffer fTextFileBuffer;
private IDocument fDocument;
+
private DocumentSetCommand fSetCmd= new DocumentSetCommand();
private DocumentReplaceCommand fReplaceCmd= new DocumentReplaceCommand();
- private Object fProviderKey;
- private PHPDocumentProvider fProvider;
- private String fLineDelimiter;
- private ILineTracker fLineTracker;
+ private Set fLegalLineDelimiters;
private List fBufferListeners= new ArrayList(3);
-
private IStatus fStatus;
+
/**
* This method is <code>public</code> for test purposes only.
*/
- public DocumentAdapter(IOpenable owner, IDocument document, ILineTracker lineTracker, PHPDocumentProvider provider, Object providerKey) {
-
- Assert.isNotNull(document);
- Assert.isNotNull(lineTracker);
+ public DocumentAdapter(IOpenable owner, IFile file) {
fOwner= owner;
- fDocument= document;
- fLineTracker= lineTracker;
- fProvider= provider;
- fProviderKey= providerKey;
+ fFile= file;
- fDocument.addPrenotifiedDocumentListener(this);
+ initialize();
}
- /**
- * Sets the status of this document adapter.
- */
- public void setStatus(IStatus status) {
- fStatus= status;
+ private void initialize() {
+ ITextFileBufferManager manager= FileBuffers.getTextFileBufferManager();
+ IPath location= fFile.getFullPath();
+ try {
+ manager.connect(location, new NullProgressMonitor());
+ fTextFileBuffer= manager.getTextFileBuffer(location);
+ fDocument= fTextFileBuffer.getDocument();
+ } catch (CoreException x) {
+ fStatus= x.getStatus();
+ fDocument= manager.createEmptyDocument(location);
+ }
+ fDocument.addPrenotifiedDocumentListener(this);
}
/**
* Returns the status of this document adapter.
*/
public IStatus getStatus() {
- return fStatus;
+ if (fStatus != null)
+ return fStatus;
+ if (fTextFileBuffer != null)
+ return fTextFileBuffer.getStatus();
+ return null;
}
/**
public IDocument getDocument() {
return fDocument;
}
-
- /**
- * Returns the line delimiter of this buffer. As a document has a set of
- * valid line delimiters, this set must be reduced to size 1.
- */
- protected String getLineDelimiter() {
-
- if (fLineDelimiter == null) {
-
- try {
- fLineDelimiter= fDocument.getLineDelimiter(0);
- } catch (BadLocationException x) {
- }
-
- if (fLineDelimiter == null) {
- /*
- * Follow up fix for: 1GF5UU0: ITPJUI:WIN2000 - "Organize Imports" in java editor inserts lines in wrong format
- * The line delimiter must always be a legal document line delimiter.
- */
- String sysLineDelimiter= System.getProperty("line.separator"); //$NON-NLS-1$
- String[] delimiters= fDocument.getLegalLineDelimiters();
- Assert.isTrue(delimiters.length > 0);
- for (int i= 0; i < delimiters.length; i++) {
- if (delimiters[i].equals(sysLineDelimiter)) {
- fLineDelimiter= sysLineDelimiter;
- break;
- }
- }
-
- if (fLineDelimiter == null) {
- // system line delimiter is not a legal document line delimiter
- fLineDelimiter= delimiters[0];
- }
- }
- }
- return fLineDelimiter;
- }
-
- /**
- * Converts the given string to the line delimiter of this buffer.
- * This method is <code>public</code> for test purposes only.
- */
- public String normalize(String text) {
- fLineTracker.set(text);
-
- int lines= fLineTracker.getNumberOfLines();
- if (lines <= 1)
- return text;
-
- StringBuffer buffer= new StringBuffer(text);
-
- try {
- IRegion previous= fLineTracker.getLineInformation(0);
- for (int i= 1; i < lines; i++) {
- int lastLineEnd= previous.getOffset() + previous.getLength();
- int lineStart= fLineTracker.getLineInformation(i).getOffset();
- fLineTracker.replace(lastLineEnd, lineStart - lastLineEnd, getLineDelimiter());
- buffer.replace(lastLineEnd, lineStart, getLineDelimiter());
- previous= fLineTracker.getLineInformation(i);
- }
-
- // last line
- String delimiter= fLineTracker.getLineDelimiter(lines -1);
- if (delimiter != null && delimiter.length() > 0)
- buffer.replace(previous.getOffset() + previous.getLength(), buffer.length(), getLineDelimiter());
-
- return buffer.toString();
- } catch (BadLocationException x) {
- }
-
- return text;
- }
-
/*
* @see IBuffer#addBufferChangedListener(IBufferChangedListener)
*/
* @see IBuffer#append(String)
*/
public void append(String text) {
- fReplaceCmd.replace(fDocument.getLength(), 0, normalize(text));
+ if (DEBUG_LINE_DELIMITERS) {
+ validateLineDelimiters(text);
+ }
+ fReplaceCmd.replace(fDocument.getLength(), 0, text);
}
/*
fDocument= null;
d.removePrenotifiedDocumentListener(this);
+ if (fTextFileBuffer != null) {
+ ITextFileBufferManager manager= FileBuffers.getTextFileBufferManager();
+ try {
+ manager.disconnect(fTextFileBuffer.getLocation(), new NullProgressMonitor());
+ } catch (CoreException x) {
+ // ignore
+ }
+ fTextFileBuffer= null;
+ }
+
fireBufferChanged(new BufferChangedEvent(this, 0, 0, null));
fBufferListeners.clear();
}
* @see IBuffer#getOwner()
*/
public IOpenable getOwner() {
- return (IOpenable) fOwner;
+ return fOwner;
}
/*
* @see IBuffer#getUnderlyingResource()
*/
public IResource getUnderlyingResource() {
- return fProvider != null ? fProvider.getUnderlyingResource(fProviderKey) : null;
+ return fFile;
}
/*
* @see IBuffer#hasUnsavedChanges()
*/
public boolean hasUnsavedChanges() {
- return fProvider != null ? fProvider.canSaveDocument(fProviderKey) : false;
+ return fTextFileBuffer != null ? fTextFileBuffer.isDirty() : false;
}
/*
* @see IBuffer#replace(int, int, String)
*/
public void replace(int position, int length, String text) {
- fReplaceCmd.replace(position, length, normalize(text));
+ if (DEBUG_LINE_DELIMITERS) {
+ validateLineDelimiters(text);
+ }
+ fReplaceCmd.replace(position, length, text);
}
/*
* @see IBuffer#save(IProgressMonitor, boolean)
*/
public void save(IProgressMonitor progress, boolean force) throws JavaModelException {
- if (fProvider != null) {
- try {
- fProvider.saveDocumentContent(progress, fProviderKey, fDocument, force);
- } catch (CoreException e) {
- throw new JavaModelException(e);
- }
+ try {
+ if (fTextFileBuffer != null)
+ fTextFileBuffer.commit(progress, force);
+ } catch (CoreException e) {
+ throw new JavaModelException(e);
}
}
} else {
// set only if different
- String newContents= normalize(contents);
- int newLength= newContents.length();
+ if (DEBUG_LINE_DELIMITERS) {
+ validateLineDelimiters(contents);
+ }
- if (oldLength != newLength || !newContents.equals(fDocument.get()))
- fSetCmd.set(newContents);
+ if (!contents.equals(fDocument.get()))
+ fSetCmd.set(contents);
}
}
+
+ private void validateLineDelimiters(String contents) {
+
+ if (fLegalLineDelimiters == null) {
+ // collect all line delimiters in the document
+ HashSet existingDelimiters= new HashSet();
+
+ for (int i= fDocument.getNumberOfLines() - 1; i >= 0; i-- ) {
+ try {
+ String curr= fDocument.getLineDelimiter(i);
+ if (curr != null) {
+ existingDelimiters.add(curr);
+ }
+ } catch (BadLocationException e) {
+ PHPeclipsePlugin.log(e);
+ }
+ }
+ if (existingDelimiters.isEmpty()) {
+ return; // first insertion of a line delimiter: no test
+ }
+ fLegalLineDelimiters= existingDelimiters;
+
+ }
+
+ DefaultLineTracker tracker= new DefaultLineTracker();
+ tracker.set(contents);
+
+ int lines= tracker.getNumberOfLines();
+ if (lines <= 1)
+ return;
+
+ for (int i= 0; i < lines; i++) {
+ try {
+ String curr= tracker.getLineDelimiter(i);
+ if (curr != null && !fLegalLineDelimiters.contains(curr)) {
+ StringBuffer buf= new StringBuffer("New line delimiter added to new code: "); //$NON-NLS-1$
+ for (int k= 0; k < curr.length(); k++) {
+ buf.append(String.valueOf((int) curr.charAt(k)));
+ }
+ PHPeclipsePlugin.log(new Exception(buf.toString()));
+ }
+ } catch (BadLocationException e) {
+ PHPeclipsePlugin.log(e);
+ }
+ }
+ }
+
/*
* @see IDocumentListener#documentAboutToBeChanged(DocumentEvent)
*/
--- /dev/null
+/**********************************************************************
+Copyright (c) 2000, 2003 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 implementation
+**********************************************************************/
+package net.sourceforge.phpeclipse.phpeditor;
+
+import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions;
+import net.sourceforge.phpdt.ui.text.JavaTextTools;
+import net.sourceforge.phpeclipse.PHPeclipsePlugin;
+
+import org.eclipse.core.filebuffers.IDocumentSetupParticipant;
+import org.eclipse.jface.text.IDocument;
+
+/**
+ * The document setup participant for PHPDT.
+ */
+public class HTMLDocumentSetupParticipant implements IDocumentSetupParticipant {
+
+ public HTMLDocumentSetupParticipant() {
+ }
+
+ /*
+ * @see org.eclipse.core.filebuffers.IDocumentSetupParticipant#setup(org.eclipse.jface.text.IDocument)
+ */
+ public void setup(IDocument document) {
+ JavaTextTools tools= PHPeclipsePlugin.getDefault().getJavaTextTools();
+ tools.setupHTMLDocumentPartitioner(document, IPHPPartitions.PHP_PARTITIONING, null); //IPHPPartitions.PHP_PARTITIONING, null);
+ }
+}
--- /dev/null
+/**********************************************************************
+Copyright (c) 2000, 2003 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 implementation
+**********************************************************************/
+package net.sourceforge.phpeclipse.phpeditor;
+
+import org.eclipse.core.filebuffers.IDocumentFactory;
+
+import org.eclipse.jface.text.IDocument;
+
+
+/**
+ * The document factory for JDT UI,
+ */
+public class JavaDocumentFactory implements IDocumentFactory {
+
+ public JavaDocumentFactory() {
+ }
+
+ /*
+ * @see org.eclipse.core.filebuffers.IDocumentFactory#createDocument()
+ */
+ public IDocument createDocument() {
+ return new PartiallySynchronizedDocument();
+ }
+}
--- /dev/null
+/**********************************************************************
+Copyright (c) 2000, 2003 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 implementation
+**********************************************************************/
+package net.sourceforge.phpeclipse.phpeditor;
+
+import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions;
+import net.sourceforge.phpdt.ui.text.JavaTextTools;
+import net.sourceforge.phpeclipse.PHPeclipsePlugin;
+
+import org.eclipse.core.filebuffers.IDocumentSetupParticipant;
+import org.eclipse.jface.text.IDocument;
+
+/**
+ * The document setup participant for PHPDT.
+ */
+public class JavaDocumentSetupParticipant implements IDocumentSetupParticipant {
+
+ public JavaDocumentSetupParticipant() {
+ }
+
+ /*
+ * @see org.eclipse.core.filebuffers.IDocumentSetupParticipant#setup(org.eclipse.jface.text.IDocument)
+ */
+ public void setup(IDocument document) {
+ JavaTextTools tools= PHPeclipsePlugin.getDefault().getJavaTextTools();
+ tools.setupJavaDocumentPartitioner(document, IPHPPartitions.PHP_PARTITIONING, null); //IPHPPartitions.PHP_PARTITIONING, null);
+ }
+}
public class JavaMarkerAnnotation extends MarkerAnnotation implements IJavaAnnotation {
-// public static final String JAVA_MARKER_TYPE_PREFIX= "net.sourceforge.phpdt"; //$NON-NLS-1$
+ public static final String JAVA_MARKER_TYPE_PREFIX= "net.sourceforge.phpdt"; //$NON-NLS-1$
public static final String ERROR_ANNOTATION_TYPE= "net.sourceforge.phpdt.ui.error"; //$NON-NLS-1$
public static final String WARNING_ANNOTATION_TYPE= "net.sourceforge.phpdt.ui.warning"; //$NON-NLS-1$
public static final String INFO_ANNOTATION_TYPE= "net.sourceforge.phpdt.ui.info"; //$NON-NLS-1$
import java.util.ResourceBundle;
+import net.sourceforge.phpdt.internal.ui.IJavaHelpContextIds;
+
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.text.ITextOperationTarget;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.source.Annotation;
-import org.eclipse.jface.text.source.AnnotationEvent;
import org.eclipse.jface.text.source.IAnnotationModel;
+import org.eclipse.jface.text.source.VerticalRulerEvent;
import org.eclipse.ui.ISelectionListener;
+import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.eclipse.ui.texteditor.IUpdate;
-import org.eclipse.ui.texteditor.SelectMarkerRulerAction2;
+import org.eclipse.ui.texteditor.SelectAnnotationRulerAction;
//import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
//import org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionProcessor;
/**
* A special select marker ruler action which activates quick fix if clicked on a quick fixable problem.
*/
-public class JavaSelectMarkerRulerAction2 extends SelectMarkerRulerAction2 {
+public class JavaSelectMarkerRulerAction2 extends SelectAnnotationRulerAction {
public JavaSelectMarkerRulerAction2(ResourceBundle bundle, String prefix, ITextEditor editor) {
super(bundle, prefix, editor);
-// WorkbenchHelp.setHelp(this, IJavaHelpContextIds.JAVA_SELECT_MARKER_RULER_ACTION);
+ WorkbenchHelp.setHelp(this, IJavaHelpContextIds.JAVA_SELECT_MARKER_RULER_ACTION);
}
/*
- * @see org.eclipse.ui.texteditor.IAnnotationListener#annotationDefaultSelected(org.eclipse.ui.texteditor.AnnotationEvent)
+ * @see org.eclipse.ui.texteditor.IVerticalRulerListener#annotationDefaultSelected(org.eclipse.ui.texteditor.VerticalRulerEvent)
*/
- public void annotationDefaultSelected(AnnotationEvent event) {
- Annotation a= event.getAnnotation();
+ public void annotationDefaultSelected(VerticalRulerEvent event) {
+ Annotation annotation= event.getSelectedAnnotation();
IAnnotationModel model= getAnnotationModel();
- Position position= model.getPosition(a);
- if (isBreakpoint(a))
+// if (isOverrideIndicator(annotation)) {
+// ((OverrideIndicatorManager.OverrideIndicator)annotation).open();
+// return;
+// }
+
+ if (isBreakpoint(annotation))
triggerAction(ITextEditorActionConstants.RULER_DOUBLE_CLICK);
+ Position position= model.getPosition(annotation);
if (position == null)
return;
- if (isQuickFixTarget(a)) {
- ITextOperationTarget operation= (ITextOperationTarget) getTextEditor().getAdapter(ITextOperationTarget.class);
+// if (isQuickFixTarget(annotation)) {
+// ITextOperationTarget operation= (ITextOperationTarget) getTextEditor().getAdapter(ITextOperationTarget.class);
// final int opCode= PHPUnitEditor.CORRECTIONASSIST_PROPOSALS;
// if (operation != null && operation.canDoOperation(opCode)) {
// getTextEditor().selectAndReveal(position.getOffset(), position.getLength());
// operation.doOperation(opCode);
// return;
// }
- }
+// }
// default:
super.annotationDefaultSelected(event);
}
/**
- * @param ma
+ * Tells whether the given annotation is an override annotation.
+ *
+ * @param annotation the annotation
+ * @return <code>true</code> iff the annotation is an override annotation
+ */
+ private boolean isOverrideIndicator(Annotation annotation) {
+ return false; //annotation instanceof OverrideIndicatorManager.OverrideIndicator;
+ }
+
+ /**
+ * @param annotation
* @return
*/
- private boolean isBreakpoint(Annotation a) {
- return a.getType().equals("org.eclipse.debug.core.breakpoint");
- //|| a.getType().equals(JavaExpandHover.NO_BREAKPOINT_ANNOTATION); //$NON-NLS-1$
+ private boolean isBreakpoint(Annotation annotation) {
+ return annotation.getType().equals("org.eclipse.debug.core.breakpoint");
+ //|| annotation.getType().equals(JavaExpandHover.NO_BREAKPOINT_ANNOTATION); //$NON-NLS-1$
+
}
private boolean isQuickFixTarget(Annotation a) {
- // return a instanceof IJavaAnnotation && JavaCorrectionProcessor.hasCorrections((IJavaAnnotation) a) || a instanceof AssistAnnotation;
- return false;
+ return false; //JavaCorrectionProcessor.hasCorrections(a) || a instanceof AssistAnnotation;
}
private void triggerAction(String actionID) {
}
}
-
package net.sourceforge.phpeclipse.phpeditor;
+import java.util.ArrayList;
+import java.util.Hashtable;
+import java.util.Map;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.IRewriteTarget;
-import org.eclipse.jface.text.Region;
+import net.sourceforge.phpdt.core.JavaCore;
+import net.sourceforge.phpdt.internal.ui.text.SmartBackspaceManager;
+import net.sourceforge.phpdt.ui.PreferenceConstants;
+
+import org.eclipse.jface.preference.IPreferenceStore;
+import org.eclipse.jface.preference.PreferenceConverter;
+import org.eclipse.jface.text.Assert;
+import org.eclipse.jface.text.ITextPresentationListener;
import org.eclipse.jface.text.formatter.FormattingContextProperties;
-import org.eclipse.jface.text.formatter.IContentFormatterExtension2;
import org.eclipse.jface.text.formatter.IFormattingContext;
import org.eclipse.jface.text.information.IInformationPresenter;
import org.eclipse.jface.text.source.IOverviewRuler;
import org.eclipse.jface.text.source.IVerticalRuler;
-import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.jface.text.source.SourceViewerConfiguration;
+import org.eclipse.jface.text.source.projection.ProjectionViewer;
+import org.eclipse.jface.util.IPropertyChangeListener;
+import org.eclipse.jface.util.PropertyChangeEvent;
+import org.eclipse.swt.custom.StyledText;
+import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Point;
+import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Composite;
-
-//import net.sourceforge.phpdt.ui.text.JavaSourceViewerConfiguration;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants;
-public class JavaSourceViewer extends SourceViewer {
+public class JavaSourceViewer extends ProjectionViewer implements IPropertyChangeListener {
/**
* Text operation code for requesting the outline for the current input.
*/
public static final int OPEN_STRUCTURE= 52;
+ /**
+ * Text operation code for requesting the hierarchy for the current input.
+ */
+ public static final int SHOW_HIERARCHY= 53;
private IInformationPresenter fOutlinePresenter;
private IInformationPresenter fStructurePresenter;
+// private IInformationPresenter fHierarchyPresenter;
- public JavaSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, boolean showAnnotationsOverview, int styles) {
+ /**
+ * This viewer's foreground color.
+ * @since 3.0
+ */
+ private Color fForegroundColor;
+ /**
+ * The viewer's background color.
+ * @since 3.0
+ */
+ private Color fBackgroundColor;
+ /**
+ * This viewer's selection foreground color.
+ * @since 3.0
+ */
+ private Color fSelectionForegroundColor;
+ /**
+ * The viewer's selection background color.
+ * @since 3.0
+ */
+ private Color fSelectionBackgroundColor;
+ /**
+ * The preference store.
+ *
+ * @since 3.0
+ */
+ private IPreferenceStore fPreferenceStore;
+ /**
+ * Is this source viewer configured?
+ *
+ * @since 3.0
+ */
+ private boolean fIsConfigured;
+ /**
+ * The backspace manager of this viewer.
+ *
+ * @since 3.0
+ */
+ private SmartBackspaceManager fBackspaceManager;
+
+ public JavaSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, boolean showAnnotationsOverview, int styles, IPreferenceStore store) {
super(parent, verticalRuler, overviewRuler, showAnnotationsOverview, styles);
+ setPreferenceStore(store);
}
/*
+ * @see org.eclipse.jface.text.source.SourceViewer#createFormattingContext()
+ * @since 3.0
+ */
+// public IFormattingContext createFormattingContext() {
+//
+// IFormattingContext context= new CommentFormattingContext();
+// Map map= new Hashtable(JavaCore.getOptions());
+//
+// context.storeToMap(PreferenceConstants.getPreferenceStore(), map, false);
+// context.setProperty(FormattingContextProperties.CONTEXT_PREFERENCES, map);
+//
+// return context;
+// }
+
+ /*
* @see ITextOperationTarget#doOperation(int)
*/
public void doOperation(int operation) {
case OPEN_STRUCTURE:
fStructurePresenter.showInformation();
return;
- case FORMAT :
- {
- final Point selection= rememberSelection();
-
- final IDocument document= getDocument();
- IRegion region= new Region(selection.x, selection.y);
- if (region.getLength()==0) {
- region = new Region(0, document.getLength());
- }
- final IRewriteTarget target= getRewriteTarget();
- final IFormattingContext context= createFormattingContext();
-
- if (selection.y == 0) {
- context.setProperty(FormattingContextProperties.CONTEXT_DOCUMENT, Boolean.TRUE);
- } else {
- context.setProperty(FormattingContextProperties.CONTEXT_DOCUMENT, Boolean.FALSE);
- context.setProperty(FormattingContextProperties.CONTEXT_REGION, region);
- }
- try {
- setRedraw(false);
- startSequentialRewriteMode(false);
- target.beginCompoundChange();
-
- final String rememberedContents= document.get();
-
- try {
-
- if (fContentFormatter instanceof IContentFormatterExtension2) {
-
- final IContentFormatterExtension2 extension= (IContentFormatterExtension2)fContentFormatter;
- extension.format(document, context);
-
- } else
- fContentFormatter.format(document, region);
-
- } catch (RuntimeException x) {
- // firewall for https://bugs.eclipse.org/bugs/show_bug.cgi?id=47472
- // if something went wrong we undo the changes we just did
- // TODO to be removed
- document.set(rememberedContents);
- throw x;
- }
-
- } finally {
-
- target.endCompoundChange();
- stopSequentialRewriteMode();
- setRedraw(true);
-
- restoreSelection();
- context.dispose();
- }
- return;
- }
+ case SHOW_HIERARCHY:
+// fHierarchyPresenter.showInformation();
+ return;
}
super.doOperation(operation);
return fOutlinePresenter != null;
if (operation == OPEN_STRUCTURE)
return fStructurePresenter != null;
+ if (operation == SHOW_HIERARCHY)
+// return fHierarchyPresenter != null;
+ return false;
+
return super.canDoOperation(operation);
}
fStructurePresenter= ((PHPSourceViewerConfiguration)configuration).getOutlinePresenter(this, true);
fStructurePresenter.install(this);
}
+ if (configuration instanceof PHPSourceViewerConfiguration) {
+// fHierarchyPresenter= ((PHPSourceViewerConfiguration)configuration).getHierarchyPresenter(this, true);
+// fHierarchyPresenter.install(this);
+
+ if (fPreferenceStore != null) {
+ fPreferenceStore.addPropertyChangeListener(this);
+ initializeViewerColors();
+ }
+ }
+ fIsConfigured= true;
}
+
+
+ protected void initializeViewerColors() {
+ if (fPreferenceStore != null) {
+
+ StyledText styledText= getTextWidget();
+
+ // ----------- foreground color --------------------
+ Color color= fPreferenceStore.getBoolean(PreferenceConstants.EDITOR_FOREGROUND_DEFAULT_COLOR)
+ ? null
+ : createColor(fPreferenceStore, PreferenceConstants.EDITOR_FOREGROUND_COLOR, styledText.getDisplay());
+ styledText.setForeground(color);
+
+ if (fForegroundColor != null)
+ fForegroundColor.dispose();
+
+ fForegroundColor= color;
+
+ // ---------- background color ----------------------
+ color= fPreferenceStore.getBoolean(PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR)
+ ? null
+ : createColor(fPreferenceStore, PreferenceConstants.EDITOR_BACKGROUND_COLOR, styledText.getDisplay());
+ styledText.setBackground(color);
+
+ if (fBackgroundColor != null)
+ fBackgroundColor.dispose();
+
+ fBackgroundColor= color;
+
+ // ----------- selection foreground color --------------------
+ color= fPreferenceStore.getBoolean(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_FOREGROUND_DEFAULT_COLOR)
+ ? null
+ : createColor(fPreferenceStore, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_FOREGROUND_COLOR, styledText.getDisplay());
+ styledText.setSelectionForeground(color);
+
+ if (fSelectionForegroundColor != null)
+ fSelectionForegroundColor.dispose();
+
+ fSelectionForegroundColor= color;
+
+ // ---------- selection background color ----------------------
+ color= fPreferenceStore.getBoolean(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_BACKGROUND_DEFAULT_COLOR)
+ ? null
+ : createColor(fPreferenceStore, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_BACKGROUND_COLOR, styledText.getDisplay());
+ styledText.setSelectionBackground(color);
+
+ if (fSelectionBackgroundColor != null)
+ fSelectionBackgroundColor.dispose();
+
+ fSelectionBackgroundColor= color;
+ }
+ }
+
+ /**
+ * Creates a color from the information stored in the given preference store.
+ * Returns <code>null</code> if there is no such information available.
+ *
+ * @param store the store to read from
+ * @param key the key used for the lookup in the preference store
+ * @param display the display used create the color
+ * @return the created color according to the specification in the preference store
+ * @since 3.0
+ */
+ 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;
+ }
/*
- * @see TextViewer#handleDispose()
+ * @see org.eclipse.jface.text.source.ISourceViewerExtension2#unconfigure()
+ * @since 3.0
*/
- protected void handleDispose() {
+ public void unconfigure() {
if (fOutlinePresenter != null) {
fOutlinePresenter.uninstall();
fOutlinePresenter= null;
fStructurePresenter.uninstall();
fStructurePresenter= null;
}
+// if (fHierarchyPresenter != null) {
+// fHierarchyPresenter.uninstall();
+// fHierarchyPresenter= null;
+// }
+ if (fForegroundColor != null) {
+ fForegroundColor.dispose();
+ fForegroundColor= null;
+ }
+ if (fBackgroundColor != null) {
+ fBackgroundColor.dispose();
+ fBackgroundColor= null;
+ }
+ if (fPreferenceStore != null)
+ fPreferenceStore.removePropertyChangeListener(this);
+
+ super.unconfigure();
+
+ fIsConfigured= false;
+ }
+
+ /*
+ * @see org.eclipse.jface.text.source.SourceViewer#rememberSelection()
+ */
+ public Point rememberSelection() {
+ return super.rememberSelection();
+ }
+
+ /*
+ * @see org.eclipse.jface.text.source.SourceViewer#restoreSelection()
+ */
+ public void restoreSelection() {
+ super.restoreSelection();
+ }
+
+ /*
+ * @see org.eclipse.jface.util.IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent)
+ */
+ public void propertyChange(PropertyChangeEvent event) {
+ String property = event.getProperty();
+ if (PreferenceConstants.EDITOR_FOREGROUND_COLOR.equals(property)
+ || PreferenceConstants.EDITOR_FOREGROUND_DEFAULT_COLOR.equals(property)
+ || PreferenceConstants.EDITOR_BACKGROUND_COLOR.equals(property)
+ || PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR.equals(property)
+ || AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_FOREGROUND_COLOR.equals(property)
+ || AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_FOREGROUND_DEFAULT_COLOR.equals(property)
+ || AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_BACKGROUND_COLOR.equals(property)
+ || AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SELECTION_BACKGROUND_DEFAULT_COLOR.equals(property))
+ {
+ initializeViewerColors();
+ }
+ }
+
+ /**
+ * Sets the preference store on this viewer.
+ *
+ * @param store the preference store
+ *
+ * @since 3.0
+ */
+ public void setPreferenceStore(IPreferenceStore store) {
+ if (fIsConfigured && fPreferenceStore != null)
+ fPreferenceStore.removePropertyChangeListener(this);
+
+ fPreferenceStore= store;
+
+ if (fIsConfigured && fPreferenceStore != null) {
+ fPreferenceStore.addPropertyChangeListener(this);
+ initializeViewerColors();
+ }
+ }
+
+ /*
+ * @see org.eclipse.jface.text.source.SourceViewer#createControl(org.eclipse.swt.widgets.Composite, int)
+ */
+ protected void createControl(Composite parent, int styles) {
+ super.createControl(parent, styles);
+
+ fBackspaceManager= new SmartBackspaceManager();
+ fBackspaceManager.install(this);
+ }
+
+ /**
+ * Returns the backspace manager for this viewer.
+ *
+ * @return the backspace manager for this viewer, or <code>null</code> if
+ * there is none
+ * @since 3.0
+ */
+ public SmartBackspaceManager getBackspaceManager() {
+ return fBackspaceManager;
+ }
+
+ /*
+ * @see org.eclipse.jface.text.source.SourceViewer#handleDispose()
+ */
+ protected void handleDispose() {
+ if (fBackspaceManager != null) {
+ fBackspaceManager.uninstall();
+ fBackspaceManager= null;
+ }
+
super.handleDispose();
}
+
+ /**
+ * Prepends the text presentation listener at the beginning of the viewer's
+ * list of text presentation listeners. If the listener is already registered
+ * with the viewer this call moves the listener to the beginning of
+ * the list.
+ *
+ * @param listener the text presentation listener
+ * @since 3.0
+ */
+ public void prependTextPresentationListener(ITextPresentationListener listener) {
+
+ Assert.isNotNull(listener);
+
+ if (fTextPresentationListeners == null)
+ fTextPresentationListeners= new ArrayList();
+
+ fTextPresentationListeners.remove(listener);
+ fTextPresentationListeners.add(0, listener);
+ }
}
--- /dev/null
+/**********************************************************************
+Copyright (c) 2000, 2003 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 implementation
+**********************************************************************/
+package net.sourceforge.phpeclipse.phpeditor;
+
+import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions;
+import net.sourceforge.phpdt.ui.text.JavaTextTools;
+import net.sourceforge.phpeclipse.PHPeclipsePlugin;
+
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.ui.editors.text.StorageDocumentProvider;
+
+/**
+ * @since 3.0
+ */
+public class JavaStorageDocumentProvider extends StorageDocumentProvider {
+
+ public JavaStorageDocumentProvider() {
+ super();
+ }
+
+ /*
+ * @see org.eclipse.ui.editors.text.StorageDocumentProvider#setupDocument(java.lang.Object, org.eclipse.jface.text.IDocument)
+ */
+ protected void setupDocument(Object element, IDocument document) {
+
+ if (document != null) {
+ JavaTextTools tools= PHPeclipsePlugin.getDefault().getJavaTextTools();
+ tools.setupJavaDocumentPartitioner(document, IPHPPartitions.HTML, element);
+ }
+ }
+}
import java.util.Iterator;
import java.util.List;
-import net.sourceforge.phpdt.core.IBuffer;
-import net.sourceforge.phpdt.core.IBufferFactory;
import net.sourceforge.phpdt.core.ICompilationUnit;
import net.sourceforge.phpdt.core.IJavaModelStatusConstants;
-import net.sourceforge.phpdt.core.IOpenable;
import net.sourceforge.phpdt.core.IProblemRequestor;
-import net.sourceforge.phpdt.core.JavaModelException;
import net.sourceforge.phpdt.core.JavaCore;
+import net.sourceforge.phpdt.core.JavaModelException;
import net.sourceforge.phpdt.core.compiler.IProblem;
-import net.sourceforge.phpdt.internal.ui.PHPStatusConstants;
import net.sourceforge.phpdt.internal.ui.PHPUIStatus;
import net.sourceforge.phpdt.internal.ui.text.java.IProblemRequestorExtension;
import net.sourceforge.phpdt.ui.PreferenceConstants;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IMarkerDelta;
import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.IResourceRuleFactory;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
+import org.eclipse.core.runtime.jobs.ISchedulingRule;
import org.eclipse.jface.preference.IPreferenceStore;
+import org.eclipse.jface.text.Assert;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DefaultLineTracker;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IDocumentPartitioner;
import org.eclipse.jface.text.ILineTracker;
+import org.eclipse.jface.text.ISynchronizable;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.AnnotationModelEvent;
import org.eclipse.jface.text.source.IAnnotationModelListener;
import org.eclipse.jface.text.source.IAnnotationModelListenerExtension;
import org.eclipse.jface.text.source.IAnnotationPresentation;
+import org.eclipse.jface.text.source.ImageUtilities;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.ListenerList;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.editors.text.EditorsUI;
-import org.eclipse.ui.editors.text.FileDocumentProvider;
+import org.eclipse.ui.editors.text.TextFileDocumentProvider;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.texteditor.AbstractMarkerAnnotationModel;
import org.eclipse.ui.texteditor.AnnotationPreference;
import org.eclipse.ui.texteditor.AnnotationPreferenceLookup;
import org.eclipse.ui.texteditor.MarkerAnnotation;
+import org.eclipse.ui.texteditor.MarkerUtilities;
import org.eclipse.ui.texteditor.ResourceMarkerAnnotationModel;
/**
* The PHPDocumentProvider provides the IDocuments used by java editors.
*/
-public class PHPDocumentProvider extends FileDocumentProvider {
+public class PHPDocumentProvider extends TextFileDocumentProvider {
/**
* Here for visibility issues only.
*/
- protected class _FileSynchronizer extends FileSynchronizer {
- public _FileSynchronizer(IFileEditorInput fileEditorInput) {
- super(fileEditorInput);
- }
- };
- /**
- * Bundle of all required informations to allow working copy management.
- */
- protected class CompilationUnitInfo extends FileInfo {
-
- ICompilationUnit fCopy;
- public CompilationUnitInfo(
- IDocument document,
- IAnnotationModel model,
- _FileSynchronizer fileSynchronizer,
- ICompilationUnit copy) {
- super(document, model, fileSynchronizer);
- fCopy = copy;
- }
-
- public void setModificationStamp(long timeStamp) {
- fModificationStamp = timeStamp;
- }
- };
/**
- * Annotation model dealing with java marker annotations and temporary problems.
- * Also acts as problem requestor for its compilation unit. Initialiy inactive. Must explicitly be
- * activated.
- */
- protected class CompilationUnitAnnotationModel
- extends ResourceMarkerAnnotationModel
- implements IProblemRequestor, IProblemRequestorExtension {
- private List fCollectedProblems;
- private List fCurrentlyOverlaid = new ArrayList();
- private List fGeneratedAnnotations;
-
- private IFileEditorInput fInput;
- private boolean fIsActive = false;
- private List fPreviouslyOverlaid = null;
- private IProgressMonitor fProgressMonitor;
-
- private ReverseMap fReverseMap = new ReverseMap();
-
- public CompilationUnitAnnotationModel(IFileEditorInput input) {
- super(input.getFile());
- fInput = input;
- }
-
- /*
- * @see IProblemRequestor#acceptProblem(IProblem)
- */
- public void acceptProblem(IProblem problem) {
- if (isActive())
- fCollectedProblems.add(problem);
- }
-
- /*
- * @see AnnotationModel#addAnnotation(Annotation, Position, boolean)
- */
- protected void addAnnotation(Annotation annotation, Position position, boolean fireModelChanged) throws BadLocationException {
- super.addAnnotation(annotation, position, fireModelChanged);
-
- Object cached = fReverseMap.get(position);
- if (cached == null)
- fReverseMap.put(position, annotation);
- else if (cached instanceof List) {
- List list = (List) cached;
- list.add(annotation);
- } else if (cached instanceof Annotation) {
- List list = new ArrayList(2);
- list.add(cached);
- list.add(annotation);
- fReverseMap.put(position, list);
- }
- }
-
- /*
- * @see IProblemRequestor#beginReporting()
- */
- public void beginReporting() {
- ICompilationUnit unit = getWorkingCopy(fInput);
- if (unit != null) // && unit.getJavaProject().isOnClasspath(unit))
- fCollectedProblems = new ArrayList();
- else
- fCollectedProblems = null;
- }
-
- protected MarkerAnnotation createMarkerAnnotation(IMarker marker) {
- return new JavaMarkerAnnotation(marker);
- }
-
- protected Position createPositionFromProblem(IProblem problem) {
- int start = problem.getSourceStart();
- if (start < 0)
- return null;
-
- int length = problem.getSourceEnd() - problem.getSourceStart() + 1;
- if (length < 0)
- return null;
-
- return new Position(start, length);
- }
- /*
- * @see IProblemRequestor#endReporting()
- */
- public void endReporting() {
- if (!isActive())
- return;
-
- if (fProgressMonitor != null && fProgressMonitor.isCanceled())
- return;
-
-
- boolean isCanceled= false;
- boolean temporaryProblemsChanged= false;
-
- synchronized (fAnnotations) {
-
- fPreviouslyOverlaid= fCurrentlyOverlaid;
- fCurrentlyOverlaid= new ArrayList();
-
- if (fGeneratedAnnotations.size() > 0) {
- temporaryProblemsChanged= true;
- removeAnnotations(fGeneratedAnnotations, false, true);
- fGeneratedAnnotations.clear();
- }
-
- if (fCollectedProblems != null && fCollectedProblems.size() > 0) {
-
- ICompilationUnit cu= getWorkingCopy(fInput);
- Iterator e= fCollectedProblems.iterator();
- while (e.hasNext()) {
-
- IProblem problem= (IProblem) e.next();
-
- if (fProgressMonitor != null && fProgressMonitor.isCanceled()) {
- isCanceled= true;
- break;
- }
-
- Position position= createPositionFromProblem(problem);
- if (position != null) {
- try {
- ProblemAnnotation annotation= new ProblemAnnotation(problem, cu);
- addAnnotation(annotation, position, false);
- overlayMarkers(position, annotation);
- fGeneratedAnnotations.add(annotation);
-
- temporaryProblemsChanged= true;
- } catch (BadLocationException x) {
- // ignore invalid position
- }
- }
- }
-
- fCollectedProblems.clear();
- }
-
- removeMarkerOverlays(isCanceled);
- fPreviouslyOverlaid.clear();
- fPreviouslyOverlaid= null;
- }
-
- if (temporaryProblemsChanged)
- fireModelChanged();
- }
- /*
- * @see IProblemRequestor#endReporting()
- */
-// public void endReporting() {
-// if (!isActive())
-// return;
-//
-// if (fProgressMonitor != null && fProgressMonitor.isCanceled())
-// return;
-//
-// boolean isCanceled = false;
-// boolean temporaryProblemsChanged = false;
-// fPreviouslyOverlaid = fCurrentlyOverlaid;
-// fCurrentlyOverlaid = new ArrayList();
-//
-// synchronized (fAnnotations) {
-//
-// if (fGeneratedAnnotations.size() > 0) {
-// temporaryProblemsChanged = true;
-// removeAnnotations(fGeneratedAnnotations, false, true);
-// fGeneratedAnnotations.clear();
-// }
-//
-// if (fCollectedProblems != null && fCollectedProblems.size() > 0) {
-//
-// Iterator e = fCollectedProblems.iterator();
-// while (e.hasNext()) {
-//
-// IProblem problem = (IProblem) e.next();
-//
-// if (fProgressMonitor != null && fProgressMonitor.isCanceled()) {
-// isCanceled = true;
-// break;
-// }
-//
-// Position position = createPositionFromProblem(problem);
-// if (position != null) {
-//
-// ProblemAnnotation annotation = new ProblemAnnotation(problem);
-// overlayMarkers(position, annotation);
-// fGeneratedAnnotations.add(annotation);
-// addAnnotation(annotation, position, false);
-//
-// temporaryProblemsChanged = true;
-// }
-// }
-//
-// fCollectedProblems.clear();
-// }
-//
-// removeMarkerOverlays(isCanceled);
-// fPreviouslyOverlaid.clear();
-// fPreviouslyOverlaid = null;
-// }
-//
-// if (temporaryProblemsChanged)
-// fireModelChanged(new CompilationUnitAnnotationModelEvent(this, getResource(), false));
-// }
-
- private Object getAnnotations(Position position) {
- return fReverseMap.get(position);
- }
-
- /*
- * @see AnnotationModel#fireModelChanged()
- */
- protected void fireModelChanged() {
- fireModelChanged(new CompilationUnitAnnotationModelEvent(this, getResource(), true));
- }
-
- /*
- * @see IProblemRequestor#isActive()
- */
- public boolean isActive() {
- return fIsActive && (fCollectedProblems != null);
- }
-
- /*
- * @see AnnotationModel#removeAllAnnotations(boolean)
- */
- protected void removeAllAnnotations(boolean fireModelChanged) {
- super.removeAllAnnotations(fireModelChanged);
- fReverseMap.clear();
- }
-
- /*
- * @see AnnotationModel#removeAnnotation(Annotation, boolean)
- */
- protected void removeAnnotation(Annotation annotation, boolean fireModelChanged) {
- Position position = getPosition(annotation);
- Object cached = fReverseMap.get(position);
- if (cached instanceof List) {
- List list = (List) cached;
- list.remove(annotation);
- if (list.size() == 1) {
- fReverseMap.put(position, list.get(0));
- list.clear();
- }
- } else if (cached instanceof Annotation) {
- fReverseMap.remove(position);
- }
-
- super.removeAnnotation(annotation, fireModelChanged);
- }
-
- private void removeMarkerOverlays(boolean isCanceled) {
- if (isCanceled) {
- fCurrentlyOverlaid.addAll(fPreviouslyOverlaid);
- } else if (fPreviouslyOverlaid != null) {
- Iterator e = fPreviouslyOverlaid.iterator();
- while (e.hasNext()) {
- JavaMarkerAnnotation annotation = (JavaMarkerAnnotation) e.next();
- annotation.setOverlay(null);
- }
- }
- }
-
- /*
- * @see IProblemRequestorExtension#setIsActive(boolean)
- */
- public void setIsActive(boolean isActive) {
- if (fIsActive != isActive) {
- fIsActive = isActive;
- if (fIsActive)
- startCollectingProblems();
- else
- stopCollectingProblems();
- }
- }
-
- /*
- * @see IProblemRequestorExtension#setProgressMonitor(IProgressMonitor)
- */
- public void setProgressMonitor(IProgressMonitor monitor) {
- fProgressMonitor = monitor;
- }
-
- /**
- * Overlays value with problem annotation.
- * @param problemAnnotation
- */
- private void setOverlay(Object value, ProblemAnnotation problemAnnotation) {
- if (value instanceof JavaMarkerAnnotation) {
- JavaMarkerAnnotation annotation = (JavaMarkerAnnotation) value;
- if (annotation.isProblem()) {
- annotation.setOverlay(problemAnnotation);
- fPreviouslyOverlaid.remove(annotation);
- fCurrentlyOverlaid.add(annotation);
- }
- }
- }
-
- private void overlayMarkers(Position position, ProblemAnnotation problemAnnotation) {
- Object value = getAnnotations(position);
- if (value instanceof List) {
- List list = (List) value;
- for (Iterator e = list.iterator(); e.hasNext();)
- setOverlay(e.next(), problemAnnotation);
- } else {
- setOverlay(value, problemAnnotation);
- }
- }
-
- /**
- * Tells this annotation model to collect temporary problems from now on.
- */
- private void startCollectingProblems() {
- fCollectedProblems = new ArrayList();
- fGeneratedAnnotations = new ArrayList();
- }
-
- /**
- * Tells this annotation model to no longer collect temporary problems.
- */
- private void stopCollectingProblems() {
- if (fGeneratedAnnotations != null) {
- removeAnnotations(fGeneratedAnnotations, true, true);
- fGeneratedAnnotations.clear();
- }
- fCollectedProblems = null;
- fGeneratedAnnotations = null;
- }
-
- protected void update(IMarkerDelta[] markerDeltas) {
-
- super.update(markerDeltas);
-
- if (markerDeltas != null && markerDeltas.length > 0) {
- try {
- ICompilationUnit workingCopy = getWorkingCopy(fInput);
- if (workingCopy != null)
- workingCopy.reconcile(true, null);
- } catch (JavaModelException ex) {
- handleCoreException(ex, ex.getMessage());
- }
- }
- }
- }
- /**
- * Creates <code>IBuffer</code>s based on documents.
+ * Bundle of all required informations to allow working copy management.
*/
- protected class BufferFactory implements IBufferFactory {
-
- private IDocument internalGetDocument(IFileEditorInput input) throws CoreException {
- IDocument document = getDocument(input);
- if (document != null)
- return document;
- return PHPDocumentProvider.this.createDocument(input);
- }
+ /**
+ * Bundle of all required informations to allow working copy management.
+ */
+ static protected class CompilationUnitInfo extends FileInfo {
+ public ICompilationUnit fCopy;
+ }
+
+ /**
+ * Annotation model dealing with java marker annotations and temporary problems.
+ * Also acts as problem requestor for its compilation unit. Initialiy inactive. Must explicitly be
+ * activated.
+ */
+ protected static class CompilationUnitAnnotationModel extends ResourceMarkerAnnotationModel implements IProblemRequestor, IProblemRequestorExtension {
+
+ private static class ProblemRequestorState {
+ boolean fInsideReportingSequence= false;
+ List fReportedProblems;
+ }
+
+ private ThreadLocal fProblemRequestorState= new ThreadLocal();
+ private int fStateCount= 0;
+
+ private ICompilationUnit fCompilationUnit;
+ private List fGeneratedAnnotations;
+ private IProgressMonitor fProgressMonitor;
+ private boolean fIsActive= false;
+
+ private ReverseMap fReverseMap= new ReverseMap();
+ private List fPreviouslyOverlaid= null;
+ private List fCurrentlyOverlaid= new ArrayList();
- public IBuffer createBuffer(IOpenable owner) {
- if (owner instanceof ICompilationUnit) {
-
- ICompilationUnit unit = (ICompilationUnit) owner;
- ICompilationUnit original = (ICompilationUnit) unit.getOriginalElement();
- IResource resource = original.getResource();
- if (resource instanceof IFile) {
- IFileEditorInput providerKey = new FileEditorInput((IFile) resource);
-
- IDocument document = null;
- IStatus status = null;
-
- try {
- document = internalGetDocument(providerKey);
- } catch (CoreException x) {
- status = x.getStatus();
- document = new Document();
- initializeDocument(document, providerKey);
- }
-
- DocumentAdapter adapter =
- new DocumentAdapter(unit, document, new DefaultLineTracker(), PHPDocumentProvider.this, providerKey);
- adapter.setStatus(status);
- return adapter;
- }
+
+ public CompilationUnitAnnotationModel(IResource resource) {
+ super(resource);
+ }
+
+ public void setCompilationUnit(ICompilationUnit unit) {
+ fCompilationUnit= unit;
+ }
+
+ protected MarkerAnnotation createMarkerAnnotation(IMarker marker) {
+ String markerType= MarkerUtilities.getMarkerType(marker);
+ if (markerType != null && markerType.startsWith(JavaMarkerAnnotation.JAVA_MARKER_TYPE_PREFIX))
+ return new JavaMarkerAnnotation(marker);
+ return super.createMarkerAnnotation(marker);
+ }
+
+ /*
+ * @see org.eclipse.jface.text.source.AnnotationModel#createAnnotationModelEvent()
+ */
+ protected AnnotationModelEvent createAnnotationModelEvent() {
+ return new CompilationUnitAnnotationModelEvent(this, getResource());
+ }
+
+ protected Position createPositionFromProblem(IProblem problem) {
+ int start= problem.getSourceStart();
+ if (start < 0)
+ return null;
+
+ int length= problem.getSourceEnd() - problem.getSourceStart() + 1;
+ if (length < 0)
+ return null;
+
+ return new Position(start, length);
+ }
+
+ /*
+ * @see IProblemRequestor#beginReporting()
+ */
+ public void beginReporting() {
+ ProblemRequestorState state= (ProblemRequestorState) fProblemRequestorState.get();
+ if (state == null)
+ internalBeginReporting(false);
+ }
+
+ /*
+ * @see org.eclipse.jdt.internal.ui.text.java.IProblemRequestorExtension#beginReportingSequence()
+ */
+ public void beginReportingSequence() {
+ ProblemRequestorState state= (ProblemRequestorState) fProblemRequestorState.get();
+ if (state == null)
+ internalBeginReporting(true);
+ }
+
+ /**
+ * Sets up the infrastructure necessary for problem reporting.
+ *
+ * @param insideReportingSequence <code>true</code> if this method
+ * call is issued from inside a reporting sequence
+ */
+ private void internalBeginReporting(boolean insideReportingSequence) {
+ if (fCompilationUnit != null) {
+ // && fCompilationUnit.getJavaProject().isOnClasspath(fCompilationUnit)) {
+ ProblemRequestorState state= new ProblemRequestorState();
+ state.fInsideReportingSequence= insideReportingSequence;
+ state.fReportedProblems= new ArrayList();
+ synchronized (getLockObject()) {
+ fProblemRequestorState.set(state);
+ ++fStateCount;
+ }
+ }
+ }
- }
- return DocumentAdapter.NULL;
- }
- };
+ /*
+ * @see IProblemRequestor#acceptProblem(IProblem)
+ */
+ public void acceptProblem(IProblem problem) {
+ if (isActive()) {
+ ProblemRequestorState state= (ProblemRequestorState) fProblemRequestorState.get();
+ if (state != null)
+ state.fReportedProblems.add(problem);
+ }
+ }
+
+ /*
+ * @see IProblemRequestor#endReporting()
+ */
+ public void endReporting() {
+ ProblemRequestorState state= (ProblemRequestorState) fProblemRequestorState.get();
+ if (state != null && !state.fInsideReportingSequence)
+ internalEndReporting(state);
+ }
+
+ /*
+ * @see org.eclipse.jdt.internal.ui.text.java.IProblemRequestorExtension#endReportingSequence()
+ */
+ public void endReportingSequence() {
+ ProblemRequestorState state= (ProblemRequestorState) fProblemRequestorState.get();
+ if (state != null && state.fInsideReportingSequence)
+ internalEndReporting(state);
+ }
+
+ private void internalEndReporting(ProblemRequestorState state) {
+ int stateCount= 0;
+ synchronized(getLockObject()) {
+ -- fStateCount;
+ stateCount= fStateCount;
+ fProblemRequestorState.set(null);
+ }
+
+ if (stateCount == 0 && isActive())
+ reportProblems(state.fReportedProblems);
+ }
+
+ /**
+ * Signals the end of problem reporting.
+ */
+ private void reportProblems(List reportedProblems) {
+ if (fProgressMonitor != null && fProgressMonitor.isCanceled())
+ return;
+
+ boolean temporaryProblemsChanged= false;
+
+ synchronized (getLockObject()) {
+
+ boolean isCanceled= false;
+
+ fPreviouslyOverlaid= fCurrentlyOverlaid;
+ fCurrentlyOverlaid= new ArrayList();
+
+ if (fGeneratedAnnotations.size() > 0) {
+ temporaryProblemsChanged= true;
+ removeAnnotations(fGeneratedAnnotations, false, true);
+ fGeneratedAnnotations.clear();
+ }
+
+ if (reportedProblems != null && reportedProblems.size() > 0) {
+
+ Iterator e= reportedProblems.iterator();
+ while (e.hasNext()) {
+
+ if (fProgressMonitor != null && fProgressMonitor.isCanceled()) {
+ isCanceled= true;
+ break;
+ }
+
+ IProblem problem= (IProblem) e.next();
+ Position position= createPositionFromProblem(problem);
+ if (position != null) {
+
+ try {
+ ProblemAnnotation annotation= new ProblemAnnotation(problem, fCompilationUnit);
+ overlayMarkers(position, annotation);
+ addAnnotation(annotation, position, false);
+ fGeneratedAnnotations.add(annotation);
+
+ temporaryProblemsChanged= true;
+ } catch (BadLocationException x) {
+ // ignore invalid position
+ }
+ }
+ }
+ }
+
+ removeMarkerOverlays(isCanceled);
+ fPreviouslyOverlaid= null;
+ }
+
+ if (temporaryProblemsChanged)
+ fireModelChanged();
+ }
+ private void removeMarkerOverlays(boolean isCanceled) {
+ if (isCanceled) {
+ fCurrentlyOverlaid.addAll(fPreviouslyOverlaid);
+ } else if (fPreviouslyOverlaid != null) {
+ Iterator e= fPreviouslyOverlaid.iterator();
+ while (e.hasNext()) {
+ JavaMarkerAnnotation annotation= (JavaMarkerAnnotation) e.next();
+ annotation.setOverlay(null);
+ }
+ }
+ }
+
+ /**
+ * Overlays value with problem annotation.
+ * @param problemAnnotation
+ */
+ private void setOverlay(Object value, ProblemAnnotation problemAnnotation) {
+ if (value instanceof JavaMarkerAnnotation) {
+ JavaMarkerAnnotation annotation= (JavaMarkerAnnotation) value;
+ if (annotation.isProblem()) {
+ annotation.setOverlay(problemAnnotation);
+ fPreviouslyOverlaid.remove(annotation);
+ fCurrentlyOverlaid.add(annotation);
+ }
+ } else {
+ }
+ }
+
+ private void overlayMarkers(Position position, ProblemAnnotation problemAnnotation) {
+ Object value= getAnnotations(position);
+ if (value instanceof List) {
+ List list= (List) value;
+ for (Iterator e = list.iterator(); e.hasNext();)
+ setOverlay(e.next(), problemAnnotation);
+ } else {
+ setOverlay(value, problemAnnotation);
+ }
+ }
+
+ /**
+ * Tells this annotation model to collect temporary problems from now on.
+ */
+ private void startCollectingProblems() {
+ fGeneratedAnnotations= new ArrayList();
+ }
+
+ /**
+ * Tells this annotation model to no longer collect temporary problems.
+ */
+ private void stopCollectingProblems() {
+ if (fGeneratedAnnotations != null)
+ removeAnnotations(fGeneratedAnnotations, true, true);
+ fGeneratedAnnotations= null;
+ }
+
+ /*
+ * @see IProblemRequestor#isActive()
+ */
+ public boolean isActive() {
+ return fIsActive;
+ }
+
+ /*
+ * @see IProblemRequestorExtension#setProgressMonitor(IProgressMonitor)
+ */
+ public void setProgressMonitor(IProgressMonitor monitor) {
+ fProgressMonitor= monitor;
+ }
+
+ /*
+ * @see IProblemRequestorExtension#setIsActive(boolean)
+ */
+ public void setIsActive(boolean isActive) {
+ if (fIsActive != isActive) {
+ fIsActive= isActive;
+ if (fIsActive)
+ startCollectingProblems();
+ else
+ stopCollectingProblems();
+ }
+ }
+
+ private Object getAnnotations(Position position) {
+ return fReverseMap.get(position);
+ }
+
+ /*
+ * @see AnnotationModel#addAnnotation(Annotation, Position, boolean)
+ */
+ protected void addAnnotation(Annotation annotation, Position position, boolean fireModelChanged) throws BadLocationException {
+ super.addAnnotation(annotation, position, fireModelChanged);
+
+ Object cached= fReverseMap.get(position);
+ if (cached == null)
+ fReverseMap.put(position, annotation);
+ else if (cached instanceof List) {
+ List list= (List) cached;
+ list.add(annotation);
+ } else if (cached instanceof Annotation) {
+ List list= new ArrayList(2);
+ list.add(cached);
+ list.add(annotation);
+ fReverseMap.put(position, list);
+ }
+ }
+
+ /*
+ * @see AnnotationModel#removeAllAnnotations(boolean)
+ */
+ protected void removeAllAnnotations(boolean fireModelChanged) {
+ super.removeAllAnnotations(fireModelChanged);
+ fReverseMap.clear();
+ }
+
+ /*
+ * @see AnnotationModel#removeAnnotation(Annotation, boolean)
+ */
+ protected void removeAnnotation(Annotation annotation, boolean fireModelChanged) {
+ Position position= getPosition(annotation);
+ Object cached= fReverseMap.get(position);
+ if (cached instanceof List) {
+ List list= (List) cached;
+ list.remove(annotation);
+ if (list.size() == 1) {
+ fReverseMap.put(position, list.get(0));
+ list.clear();
+ }
+ } else if (cached instanceof Annotation) {
+ fReverseMap.remove(position);
+ }
+ super.removeAnnotation(annotation, fireModelChanged);
+ }
+ }
+
+
+
protected static class GlobalAnnotationModelListener implements IAnnotationModelListener, IAnnotationModelListenerExtension {
private ListenerList fListenerList;
private boolean indicateQuixFixableProblems() {
return PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_CORRECTION_INDICATION);
}
-
+
/*
* @see Annotation#paint
*/
public void paint(GC gc, Canvas canvas, Rectangle r) {
initializeImages();
if (fImage != null)
- drawImage(fImage, gc, canvas, r, SWT.CENTER, SWT.TOP);
+ ImageUtilities.drawImage(fImage, gc, canvas, r, SWT.CENTER, SWT.TOP);
}
-
/*
* @see IJavaAnnotation#getImage(Display)
*/
/* Preference key for temporary problems */
private final static String HANDLE_TEMPORARY_PROBLEMS = PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS;
- /** The buffer factory */
- private IBufferFactory fBufferFactory = new BufferFactory();
/** Indicates whether the save has been initialized by this provider */
private boolean fIsAboutToSave = false;
/** The save policy used by this provider */
private GlobalAnnotationModelListener fGlobalAnnotationModelListener;
public PHPDocumentProvider() {
-
- fPropertyListener = new IPropertyChangeListener() {
- public void propertyChange(PropertyChangeEvent event) {
- if (HANDLE_TEMPORARY_PROBLEMS.equals(event.getProperty()))
- enableHandlingTemporaryProblems();
- }
- };
-
- fGlobalAnnotationModelListener = new GlobalAnnotationModelListener();
-
- PHPeclipsePlugin.getDefault().getPreferenceStore().addPropertyChangeListener(fPropertyListener);
+ setParentDocumentProvider(new TextFileDocumentProvider(new JavaStorageDocumentProvider()));
+
+ fPropertyListener= new IPropertyChangeListener() {
+ public void propertyChange(PropertyChangeEvent event) {
+ if (HANDLE_TEMPORARY_PROBLEMS.equals(event.getProperty()))
+ enableHandlingTemporaryProblems();
+ }
+ };
+ fGlobalAnnotationModelListener= new GlobalAnnotationModelListener();
+ PHPeclipsePlugin.getDefault().getPreferenceStore().addPropertyChangeListener(fPropertyListener);
}
return (ICompilationUnit) element;
return null;
}
+
/*
+ * @see org.eclipse.ui.editors.text.TextFileDocumentProvider#createEmptyFileInfo()
+ */
+ protected FileInfo createEmptyFileInfo() {
+ return new CompilationUnitInfo();
+ }
+ /*
+ * @see org.eclipse.ui.editors.text.TextFileDocumentProvider#createAnnotationModel(org.eclipse.core.resources.IFile)
+ */
+ protected IAnnotationModel createAnnotationModel(IFile file) {
+ return new CompilationUnitAnnotationModel(file);
+ }
+ /*
* @see AbstractDocumentProvider#createElementInfo(Object)
*/
- protected ElementInfo createElementInfo(Object element) throws CoreException {
-
- if (!(element instanceof IFileEditorInput))
- return super.createElementInfo(element);
-
- IFileEditorInput input = (IFileEditorInput) element;
- ICompilationUnit original = createCompilationUnit(input.getFile());
- if (original != null) {
-
- try {
-
- try {
- refreshFile(input.getFile());
- } catch (CoreException x) {
- handleCoreException(x, PHPEditorMessages.getString("PHPDocumentProvider.error.createElementInfo")); //$NON-NLS-1$
- }
-
- IAnnotationModel m = createCompilationUnitAnnotationModel(input);
- IProblemRequestor r = m instanceof IProblemRequestor ? (IProblemRequestor) m : null;
- ICompilationUnit c = (ICompilationUnit) original.getSharedWorkingCopy(getProgressMonitor(), fBufferFactory, r);
-
- DocumentAdapter a = null;
- try {
- a = (DocumentAdapter) c.getBuffer();
- } catch (ClassCastException x) {
- IStatus status = new Status(IStatus.ERROR, PHPeclipsePlugin.PLUGIN_ID, PHPStatusConstants.TEMPLATE_IO_EXCEPTION, "Shared working copy has wrong buffer", x); //$NON-NLS-1$
- throw new CoreException(status);
- }
-
- _FileSynchronizer f = new _FileSynchronizer(input);
- f.install();
-
- CompilationUnitInfo info = new CompilationUnitInfo(a.getDocument(), m, f, c);
- info.setModificationStamp(computeModificationStamp(input.getFile()));
- info.fStatus = a.getStatus();
- info.fEncoding = getPersistedEncoding(input);
-
- if (r instanceof IProblemRequestorExtension) {
- IProblemRequestorExtension extension = (IProblemRequestorExtension) r;
- extension.setIsActive(isHandlingTemporaryProblems());
- }
- m.addAnnotationModelListener(fGlobalAnnotationModelListener);
-
- return info;
-
- } catch (JavaModelException x) {
- throw new CoreException(x.getStatus());
- }
- } else {
- return super.createElementInfo(element);
- }
- }
+// protected ElementInfo createElementInfo(Object element) throws CoreException {
+//
+// if (!(element instanceof IFileEditorInput))
+// return super.createElementInfo(element);
+//
+// IFileEditorInput input = (IFileEditorInput) element;
+// ICompilationUnit original = createCompilationUnit(input.getFile());
+// if (original != null) {
+//
+// try {
+//
+// try {
+// refreshFile(input.getFile());
+// } catch (CoreException x) {
+// handleCoreException(x, PHPEditorMessages.getString("PHPDocumentProvider.error.createElementInfo")); //$NON-NLS-1$
+// }
+//
+// IAnnotationModel m = createCompilationUnitAnnotationModel(input);
+// IProblemRequestor r = m instanceof IProblemRequestor ? (IProblemRequestor) m : null;
+// ICompilationUnit c = (ICompilationUnit) original.getSharedWorkingCopy(getProgressMonitor(), fBufferFactory, r);
+//
+// DocumentAdapter a = null;
+// try {
+// a = (DocumentAdapter) c.getBuffer();
+// } catch (ClassCastException x) {
+// IStatus status = new Status(IStatus.ERROR, PHPeclipsePlugin.PLUGIN_ID, PHPStatusConstants.TEMPLATE_IO_EXCEPTION, "Shared working copy has wrong buffer", x); //$NON-NLS-1$
+// throw new CoreException(status);
+// }
+//
+// _FileSynchronizer f = new _FileSynchronizer(input);
+// f.install();
+//
+// CompilationUnitInfo info = new CompilationUnitInfo(a.getDocument(), m, f, c);
+// info.setModificationStamp(computeModificationStamp(input.getFile()));
+// info.fStatus = a.getStatus();
+// info.fEncoding = getPersistedEncoding(input);
+//
+// if (r instanceof IProblemRequestorExtension) {
+// IProblemRequestorExtension extension = (IProblemRequestorExtension) r;
+// extension.setIsActive(isHandlingTemporaryProblems());
+// }
+// m.addAnnotationModelListener(fGlobalAnnotationModelListener);
+//
+// return info;
+//
+// } catch (JavaModelException x) {
+// throw new CoreException(x.getStatus());
+// }
+// } else {
+// return super.createElementInfo(element);
+// }
+// }
/*
* @see AbstractDocumentProvider#disposeElementInfo(Object, ElementInfo)
*/
- protected void disposeElementInfo(Object element, ElementInfo info) {
-
- if (info instanceof CompilationUnitInfo) {
- CompilationUnitInfo cuInfo = (CompilationUnitInfo) info;
- cuInfo.fCopy.destroy();
- cuInfo.fModel.removeAnnotationModelListener(fGlobalAnnotationModelListener);
- }
-
- super.disposeElementInfo(element, info);
- }
+// protected void disposeElementInfo(Object element, ElementInfo info) {
+//
+// if (info instanceof CompilationUnitInfo) {
+// CompilationUnitInfo cuInfo = (CompilationUnitInfo) info;
+// cuInfo.fCopy.destroy();
+// cuInfo.fModel.removeAnnotationModelListener(fGlobalAnnotationModelListener);
+// }
+//
+// super.disposeElementInfo(element, info);
+// }
/*
* @see AbstractDocumentProvider#doSaveDocument(IProgressMonitor, Object, IDocument, boolean)
*/
- protected void doSaveDocument(IProgressMonitor monitor, Object element, IDocument document, boolean overwrite)
- throws CoreException {
-
- ElementInfo elementInfo = getElementInfo(element);
- if (elementInfo instanceof CompilationUnitInfo) {
- CompilationUnitInfo info = (CompilationUnitInfo) elementInfo;
-
- // update structure, assumes lock on info.fCopy
- info.fCopy.reconcile();
-
- ICompilationUnit original = (ICompilationUnit) info.fCopy.getOriginalElement();
- IResource resource = original.getResource();
-
- if (resource == null) {
- // underlying resource has been deleted, just recreate file, ignore the rest
- super.doSaveDocument(monitor, element, document, overwrite);
- return;
- }
-
- if (resource != null && !overwrite)
- checkSynchronizationState(info.fModificationStamp, resource);
-
- if (fSavePolicy != null)
- fSavePolicy.preSave(info.fCopy);
-
- // inform about the upcoming content change
- fireElementStateChanging(element);
- try {
- fIsAboutToSave = true;
- // commit working copy
- info.fCopy.commit(overwrite, monitor);
- } catch (CoreException x) {
- // inform about the failure
- fireElementStateChangeFailed(element);
- throw x;
- } catch (RuntimeException x) {
- // inform about the failure
- fireElementStateChangeFailed(element);
- throw x;
- } finally {
- fIsAboutToSave = false;
- }
-
- // If here, the dirty state of the editor will change to "not dirty".
- // Thus, the state changing flag will be reset.
-
- AbstractMarkerAnnotationModel model = (AbstractMarkerAnnotationModel) info.fModel;
- model.updateMarkers(info.fDocument);
+// protected void doSaveDocument(IProgressMonitor monitor, Object element, IDocument document, boolean overwrite)
+// throws CoreException {
+//
+// ElementInfo elementInfo = getElementInfo(element);
+// if (elementInfo instanceof CompilationUnitInfo) {
+// CompilationUnitInfo info = (CompilationUnitInfo) elementInfo;
+//
+// // update structure, assumes lock on info.fCopy
+// info.fCopy.reconcile();
+//
+// ICompilationUnit original = (ICompilationUnit) info.fCopy.getOriginalElement();
+// IResource resource = original.getResource();
+//
+// if (resource == null) {
+// // underlying resource has been deleted, just recreate file, ignore the rest
+// super.doSaveDocument(monitor, element, document, overwrite);
+// return;
+// }
+//
+// if (resource != null && !overwrite)
+// checkSynchronizationState(info.fModificationStamp, resource);
+//
+// if (fSavePolicy != null)
+// fSavePolicy.preSave(info.fCopy);
+//
+// // inform about the upcoming content change
+// fireElementStateChanging(element);
+// try {
+// fIsAboutToSave = true;
+// // commit working copy
+// info.fCopy.commit(overwrite, monitor);
+// } catch (CoreException x) {
+// // inform about the failure
+// fireElementStateChangeFailed(element);
+// throw x;
+// } catch (RuntimeException x) {
+// // inform about the failure
+// fireElementStateChangeFailed(element);
+// throw x;
+// } finally {
+// fIsAboutToSave = false;
+// }
+//
+// // If here, the dirty state of the editor will change to "not dirty".
+// // Thus, the state changing flag will be reset.
+//
+// AbstractMarkerAnnotationModel model = (AbstractMarkerAnnotationModel) info.fModel;
+// model.updateMarkers(info.fDocument);
+//
+// if (resource != null)
+// info.setModificationStamp(computeModificationStamp(resource));
+//
+// if (fSavePolicy != null) {
+// ICompilationUnit unit = fSavePolicy.postSave(original);
+// if (unit != null) {
+// IResource r = unit.getResource();
+// IMarker[] markers = r.findMarkers(IMarker.MARKER, true, IResource.DEPTH_ZERO);
+// if (markers != null && markers.length > 0) {
+// for (int i = 0; i < markers.length; i++)
+// model.updateMarker(markers[i], info.fDocument, null);
+// }
+// }
+// }
+//
+// } else {
+// super.doSaveDocument(monitor, element, document, overwrite);
+// }
+// }
- if (resource != null)
- info.setModificationStamp(computeModificationStamp(resource));
+ /*
+ * @see org.eclipse.ui.editors.text.TextFileDocumentProvider#createFileInfo(java.lang.Object)
+ */
+ protected FileInfo createFileInfo(Object element) throws CoreException {
+ if (!(element instanceof IFileEditorInput))
+ return null;
+
+ IFileEditorInput input= (IFileEditorInput) element;
+ ICompilationUnit original= createCompilationUnit(input.getFile());
+ if (original == null)
+ return null;
+
+ FileInfo info= super.createFileInfo(element);
+ if (!(info instanceof CompilationUnitInfo))
+ return null;
+
+ CompilationUnitInfo cuInfo= (CompilationUnitInfo) info;
+ setUpSynchronization(cuInfo);
+
+ IProblemRequestor requestor= cuInfo.fModel instanceof IProblemRequestor ? (IProblemRequestor) cuInfo.fModel : null;
- if (fSavePolicy != null) {
- ICompilationUnit unit = fSavePolicy.postSave(original);
- if (unit != null) {
- IResource r = unit.getResource();
- IMarker[] markers = r.findMarkers(IMarker.MARKER, true, IResource.DEPTH_ZERO);
- if (markers != null && markers.length > 0) {
- for (int i = 0; i < markers.length; i++)
- model.updateMarker(markers[i], info.fDocument, null);
- }
+ original.becomeWorkingCopy(requestor, getProgressMonitor());
+ cuInfo.fCopy= original;
+
+ if (cuInfo.fModel instanceof CompilationUnitAnnotationModel) {
+ CompilationUnitAnnotationModel model= (CompilationUnitAnnotationModel) cuInfo.fModel;
+ model.setCompilationUnit(cuInfo.fCopy);
+ }
+
+ if (cuInfo.fModel != null)
+ cuInfo.fModel.addAnnotationModelListener(fGlobalAnnotationModelListener);
+
+ if (requestor instanceof IProblemRequestorExtension) {
+ IProblemRequestorExtension extension= (IProblemRequestorExtension) requestor;
+ extension.setIsActive(isHandlingTemporaryProblems());
+ }
+
+ return cuInfo;
+ }
+
+ private void setUpSynchronization(CompilationUnitInfo cuInfo) {
+ IDocument document= cuInfo.fTextFileBuffer.getDocument();
+ IAnnotationModel model= cuInfo.fModel;
+
+ if (document instanceof ISynchronizable && model instanceof ISynchronizable) {
+ Object lock= ((ISynchronizable) document).getLockObject();
+ ((ISynchronizable) model).setLockObject(lock);
}
- }
-
- } else {
- super.doSaveDocument(monitor, element, document, overwrite);
}
- }
-
- /**
- * Replaces createAnnotionModel of the super class.
- */
- protected IAnnotationModel createCompilationUnitAnnotationModel(Object element) throws CoreException {
- if ( !(element instanceof IFileEditorInput))
- throw new CoreException(PHPUIStatus.createError(
- IJavaModelStatusConstants.INVALID_RESOURCE_TYPE, "", null)); //$NON-NLS-1$
+
+ /*
+ * @see org.eclipse.ui.editors.text.TextFileDocumentProvider#disposeFileInfo(java.lang.Object, org.eclipse.ui.editors.text.TextFileDocumentProvider.FileInfo)
+ */
+ protected void disposeFileInfo(Object element, FileInfo info) {
+ if (info instanceof CompilationUnitInfo) {
+ CompilationUnitInfo cuInfo= (CompilationUnitInfo) info;
+
+ try {
+ cuInfo.fCopy.discardWorkingCopy();
+ } catch (JavaModelException x) {
+ handleCoreException(x, x.getMessage());
+ }
+
+ if (cuInfo.fModel != null)
+ cuInfo.fModel.removeAnnotationModelListener(fGlobalAnnotationModelListener);
+ }
+ super.disposeFileInfo(element, info);
+ }
+
+ protected void commitWorkingCopy(IProgressMonitor monitor, Object element, CompilationUnitInfo info, boolean overwrite) throws CoreException {
+
+ synchronized (info.fCopy) {
+ info.fCopy.reconcile();
+ }
+
+ IDocument document= info.fTextFileBuffer.getDocument();
+ IResource resource= info.fCopy.getResource();
+
+ Assert.isTrue(resource instanceof IFile);
+ if (!resource.exists()) {
+ // underlying resource has been deleted, just recreate file, ignore the rest
+ createFileFromDocument(monitor, (IFile) resource, document);
+ return;
+ }
+
+ if (fSavePolicy != null)
+ fSavePolicy.preSave(info.fCopy);
+
+ try {
- IFileEditorInput input= (IFileEditorInput) element;
- return new CompilationUnitAnnotationModel(input);
- }
+ fIsAboutToSave= true;
+ info.fCopy.commitWorkingCopy(overwrite, monitor);
+
+ } catch (CoreException x) {
+ // inform about the failure
+ fireElementStateChangeFailed(element);
+ throw x;
+ } catch (RuntimeException x) {
+ // inform about the failure
+ fireElementStateChangeFailed(element);
+ throw x;
+ } finally {
+ fIsAboutToSave= false;
+ }
+
+ // If here, the dirty state of the editor will change to "not dirty".
+ // Thus, the state changing flag will be reset.
+ if (info.fModel instanceof AbstractMarkerAnnotationModel) {
+ AbstractMarkerAnnotationModel model= (AbstractMarkerAnnotationModel) info.fModel;
+ model.updateMarkers(document);
+ }
+
+ if (fSavePolicy != null) {
+ ICompilationUnit unit= fSavePolicy.postSave(info.fCopy);
+ if (unit != null && info.fModel instanceof AbstractMarkerAnnotationModel) {
+ IResource r= unit.getResource();
+ IMarker[] markers= r.findMarkers(IMarker.MARKER, true, IResource.DEPTH_ZERO);
+ if (markers != null && markers.length > 0) {
+ AbstractMarkerAnnotationModel model= (AbstractMarkerAnnotationModel) info.fModel;
+ for (int i= 0; i < markers.length; i++)
+ model.updateMarker(document, markers[i], null);
+ }
+ }
+ }
+}
- // private IDocumentPartitioner createCSSPartitioner() {
- // return new DefaultPartitioner(getHTMLPartitionScanner(), TYPES);
- // }
+/*
+ * @see org.eclipse.ui.editors.text.TextFileDocumentProvider#createSaveOperation(java.lang.Object, org.eclipse.jface.text.IDocument, boolean)
+ */
+protected DocumentProviderOperation createSaveOperation(final Object element, final IDocument document, final boolean overwrite) throws CoreException {
+ final FileInfo info= getFileInfo(element);
+ if (info instanceof CompilationUnitInfo) {
+ return new DocumentProviderOperation() {
+ /*
+ * @see org.eclipse.ui.editors.text.TextFileDocumentProvider.DocumentProviderOperation#execute(org.eclipse.core.runtime.IProgressMonitor)
+ */
+ protected void execute(IProgressMonitor monitor) throws CoreException {
+ commitWorkingCopy(monitor, element, (CompilationUnitInfo) info, overwrite);
+ }
+ /*
+ * @see org.eclipse.ui.editors.text.TextFileDocumentProvider.DocumentProviderOperation#getSchedulingRule()
+ */
+ public ISchedulingRule getSchedulingRule() {
+ if (info.fElement instanceof IFileEditorInput) {
+ IFile file= ((IFileEditorInput) info.fElement).getFile();
+ IResourceRuleFactory ruleFactory= ResourcesPlugin.getWorkspace().getRuleFactory();
+ if (file == null || !file.exists())
+ return ruleFactory.createRule(file);
+ else
+ return ruleFactory.modifyRule(file);
+ } else
+ return null;
+ }
+ };
+ }
+ return null;
+}
/* (non-Javadoc)
* Method declared on AbstractDocumentProvider
*/
- protected IDocument createDocument(Object element) throws CoreException {
- if (element instanceof IEditorInput) {
- Document document = new PartiallySynchronizedDocument();
- if (setDocumentContent(document, (IEditorInput) element, getEncoding(element))) {
- initializeDocument(document, (IEditorInput) element);
-
- //
- // IDocument document = super.createDocument(element);
- // if (document != null) {
- // IDocumentPartitioner partitioner = null;
- // if (element instanceof FileEditorInput) {
- // IFile file = (IFile) ((FileEditorInput) element).getAdapter(IFile.class);
- // String filename = file.getLocation().toString();
- // String extension = filename.substring(filename.lastIndexOf("."), filename.length());
- // // 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();
- // }
- // document.setDocumentPartitioner(partitioner);
- // partitioner.connect(document);
- }
- return document;
- }
- return null;
- }
+// protected IDocument createDocument(Object element) throws CoreException {
+// if (element instanceof IEditorInput) {
+// Document document = new PartiallySynchronizedDocument();
+// if (setDocumentContent(document, (IEditorInput) element, getEncoding(element))) {
+// initializeDocument(document, (IEditorInput) element);
+//
+// //
+// // IDocument document = super.createDocument(element);
+// // if (document != null) {
+// // IDocumentPartitioner partitioner = null;
+// // if (element instanceof FileEditorInput) {
+// // IFile file = (IFile) ((FileEditorInput) element).getAdapter(IFile.class);
+// // String filename = file.getLocation().toString();
+// // String extension = filename.substring(filename.lastIndexOf("."), filename.length());
+// // // 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();
+// // }
+// // document.setDocumentPartitioner(partitioner);
+// // partitioner.connect(document);
+// }
+// return document;
+// }
+// return null;
+// }
// /**
// * Return a partitioner for .html files.
// return XML_PARTITION_SCANNER;
// }
- protected void initializeDocument(IDocument document, IEditorInput editorInput) {
- if (document != null) {
- JavaTextTools tools = PHPeclipsePlugin.getDefault().getJavaTextTools();
- IDocumentPartitioner partitioner = null;
- if (editorInput != null && editorInput instanceof FileEditorInput) {
- IFile file = (IFile) ((FileEditorInput) editorInput).getAdapter(IFile.class);
- String filename = file.getLocation().toString();
- String extension = filename.substring(filename.lastIndexOf("."), filename.length());
- partitioner = tools.createDocumentPartitioner(extension);
- } else {
- partitioner = tools.createDocumentPartitioner(".php");
- }
- document.setDocumentPartitioner(partitioner);
- partitioner.connect(document);
- }
- }
+// protected void initializeDocument(IDocument document, IEditorInput editorInput) {
+// if (document != null) {
+// JavaTextTools tools = PHPeclipsePlugin.getDefault().getJavaTextTools();
+// IDocumentPartitioner partitioner = null;
+// if (editorInput != null && editorInput instanceof FileEditorInput) {
+// IFile file = (IFile) ((FileEditorInput) editorInput).getAdapter(IFile.class);
+// String filename = file.getLocation().toString();
+// String extension = filename.substring(filename.lastIndexOf("."), filename.length());
+// partitioner = tools.createDocumentPartitioner(extension);
+// } else {
+// partitioner = tools.createDocumentPartitioner(".php");
+// }
+// document.setDocumentPartitioner(partitioner);
+// partitioner.connect(document);
+// }
+// }
/*
* @see org.eclipse.ui.texteditor.AbstractDocumentProvider#doResetDocument(java.lang.Object, org.eclipse.core.runtime.IProgressMonitor)
*/
- protected void doResetDocument(Object element, IProgressMonitor monitor) throws CoreException {
- if (element == null)
- return;
-
- ElementInfo elementInfo= getElementInfo(element);
- if (elementInfo instanceof CompilationUnitInfo) {
- CompilationUnitInfo info= (CompilationUnitInfo) elementInfo;
-
- IDocument document;
- IStatus status= null;
-
- try {
-
- ICompilationUnit original= (ICompilationUnit) info.fCopy.getOriginalElement();
- IResource resource= original.getResource();
- if (resource instanceof IFile) {
-
- IFile file= (IFile) resource;
-
- try {
- refreshFile(file, monitor);
- } catch (CoreException x) {
- handleCoreException(x, PHPEditorMessages.getString("CompilationUnitDocumentProvider.error.resetDocument")); //$NON-NLS-1$
- }
-
- IFileEditorInput input= new FileEditorInput(file);
- document= super.createDocument(input);
-
- } else {
- document= createEmptyDocument();
- }
-
- } catch (CoreException x) {
- document= createEmptyDocument();
- status= x.getStatus();
- }
-
- fireElementContentAboutToBeReplaced(element);
-
- removeUnchangedElementListeners(element, info);
- info.fDocument.set(document.get());
- info.fCanBeSaved= false;
- info.fStatus= status;
- addUnchangedElementListeners(element, info);
-
- fireElementContentReplaced(element);
- fireElementDirtyStateChanged(element, false);
-
- } else {
- super.doResetDocument(element, monitor);
- }
- }
+// protected void doResetDocument(Object element, IProgressMonitor monitor) throws CoreException {
+// if (element == null)
+// return;
+//
+// ElementInfo elementInfo= getElementInfo(element);
+// if (elementInfo instanceof CompilationUnitInfo) {
+// CompilationUnitInfo info= (CompilationUnitInfo) elementInfo;
+//
+// IDocument document;
+// IStatus status= null;
+//
+// try {
+//
+// ICompilationUnit original= (ICompilationUnit) info.fCopy.getOriginalElement();
+// IResource resource= original.getResource();
+// if (resource instanceof IFile) {
+//
+// IFile file= (IFile) resource;
+//
+// try {
+// refreshFile(file, monitor);
+// } catch (CoreException x) {
+// handleCoreException(x, PHPEditorMessages.getString("CompilationUnitDocumentProvider.error.resetDocument")); //$NON-NLS-1$
+// }
+//
+// IFileEditorInput input= new FileEditorInput(file);
+// document= super.createDocument(input);
+//
+// } else {
+// document= createEmptyDocument();
+// }
+//
+// } catch (CoreException x) {
+// document= createEmptyDocument();
+// status= x.getStatus();
+// }
+//
+// fireElementContentAboutToBeReplaced(element);
+//
+// removeUnchangedElementListeners(element, info);
+// info.fDocument.set(document.get());
+// info.fCanBeSaved= false;
+// info.fStatus= status;
+// addUnchangedElementListeners(element, info);
+//
+// fireElementContentReplaced(element);
+// fireElementDirtyStateChanged(element, false);
+//
+// } else {
+// super.doResetDocument(element, monitor);
+// }
+// }
/*
* @see AbstractDocumentProvider#resetDocument(Object)
return null;
}
- /**
- * Returns the working copy this document provider maintains for the given
- * element.
- *
- * @param element the given element
- * @return the working copy for the given element
- */
- ICompilationUnit getWorkingCopy(IEditorInput element) {
-
- ElementInfo elementInfo = getElementInfo(element);
- if (elementInfo instanceof CompilationUnitInfo) {
- CompilationUnitInfo info = (CompilationUnitInfo) elementInfo;
- return info.fCopy;
- }
-
- return null;
- }
-
- /**
- * Gets the BufferFactory.
- */
- public IBufferFactory getBufferFactory() {
- return fBufferFactory;
- }
-
- /**
- * Shuts down this document provider.
- */
- public void shutdown() {
+ /*
+ * @see org.eclipse.jdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#getWorkingCopy(java.lang.Object)
+ */
+ public ICompilationUnit getWorkingCopy(Object element) {
+ FileInfo fileInfo= getFileInfo(element);
+ if (fileInfo instanceof CompilationUnitInfo) {
+ CompilationUnitInfo info= (CompilationUnitInfo) fileInfo;
+ return info.fCopy;
+ }
+ return null;
+ }
- PHPeclipsePlugin.getDefault().getPreferenceStore().removePropertyChangeListener(fPropertyListener);
- Iterator e = getConnectedElements();
- while (e.hasNext())
- disconnect(e.next());
- }
+ /*
+ * @see org.eclipse.jdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#shutdown()
+ */
+ public void shutdown() {
+ PHPeclipsePlugin.getDefault().getPreferenceStore().removePropertyChangeListener(fPropertyListener);
+ Iterator e= getConnectedElementsIterator();
+ while (e.hasNext())
+ disconnect(e.next());
+ }
/**
* Returns the preference whether handling temporary problems is enabled.
}
/**
- * Switches the state of problem acceptance according to the value in the preference store.
- */
- protected void enableHandlingTemporaryProblems() {
- boolean enable = isHandlingTemporaryProblems();
- for (Iterator iter = getConnectedElements(); iter.hasNext();) {
- ElementInfo element = getElementInfo(iter.next());
- if (element instanceof CompilationUnitInfo) {
- CompilationUnitInfo info = (CompilationUnitInfo) element;
- if (info.fModel instanceof IProblemRequestorExtension) {
- IProblemRequestorExtension extension = (IProblemRequestorExtension) info.fModel;
- extension.setIsActive(enable);
- }
- }
- }
- }
+ * Switches the state of problem acceptance according to the value in the preference store.
+ */
+ protected void enableHandlingTemporaryProblems() {
+ boolean enable= isHandlingTemporaryProblems();
+ for (Iterator iter= getFileInfosIterator(); iter.hasNext();) {
+ FileInfo info= (FileInfo) iter.next();
+ if (info.fModel instanceof IProblemRequestorExtension) {
+ IProblemRequestorExtension extension= (IProblemRequestorExtension) info.fModel;
+ extension.setIsActive(enable);
+ }
+ }
+ }
/**
* Adds a listener that reports changes from all compilation unit annotation models.
fGlobalAnnotationModelListener.removeListener(listener);
}
- /**
- * Returns whether the given element is connected to this document provider.
- *
- * @param element the element
- * @return <code>true</code> if the element is connected, <code>false</code> otherwise
- */
- boolean isConnected(Object element) {
- return getElementInfo(element) != null;
- }
}
import net.sourceforge.phpdt.core.JavaCore;
import net.sourceforge.phpdt.core.JavaModelException;
import net.sourceforge.phpdt.internal.ui.actions.CompositeActionGroup;
+import net.sourceforge.phpdt.internal.ui.actions.FoldingActionGroup;
+import net.sourceforge.phpdt.internal.ui.text.CustomSourceInformationControl;
import net.sourceforge.phpdt.internal.ui.text.HTMLTextPresenter;
import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions;
import net.sourceforge.phpdt.internal.ui.text.PHPPairMatcher;
import net.sourceforge.phpdt.ui.PreferenceConstants;
import net.sourceforge.phpdt.ui.actions.GotoMatchingBracketAction;
import net.sourceforge.phpdt.ui.text.JavaTextTools;
+import net.sourceforge.phpdt.ui.text.folding.IJavaFoldingStructureProvider;
import net.sourceforge.phpeclipse.PHPeclipsePlugin;
import org.eclipse.core.resources.IMarker;
import org.eclipse.jface.text.source.IVerticalRuler;
import org.eclipse.jface.text.source.OverviewRuler;
import org.eclipse.jface.text.source.SourceViewerConfiguration;
+import org.eclipse.jface.text.source.projection.ProjectionSupport;
+import org.eclipse.jface.text.source.projection.ProjectionViewer;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.editors.text.DefaultEncodingSupport;
import org.eclipse.ui.editors.text.IEncodingSupport;
import org.eclipse.ui.part.IShowInTargetList;
+import org.eclipse.ui.texteditor.AbstractDecoratedTextEditor;
import org.eclipse.ui.texteditor.DefaultRangeIndicator;
-import org.eclipse.ui.texteditor.ExtendedTextEditor;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.ui.texteditor.IEditorStatusLine;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
/**
* PHP specific text editor.
*/
-public abstract class PHPEditor extends ExtendedTextEditor implements IViewPartInputProvider {
+public abstract class PHPEditor extends AbstractDecoratedTextEditor implements IViewPartInputProvider {
//extends StatusTextEditor implements IViewPartInputProvider { // extends TextEditor {
/**
* "Smart" runnable for updating the outline page's selection.
protected CompositeActionGroup fActionGroups;
protected CompositeActionGroup fContextMenuGroup;
+ /**
+ * This editor's projection support
+ * @since 3.0
+ */
+ private ProjectionSupport fProjectionSupport;
+ /**
+ * This editor's projection model updater
+ * @since 3.0
+ */
+ private IJavaFoldingStructureProvider fProjectionModelUpdater;
+ /**
+ * The action group for folding.
+ *
+ * @since 3.0
+ */
+ private FoldingActionGroup fFoldingGroup;
+
/** The information presenter. */
private InformationPresenter fInformationPresenter;
/** The annotation access */
super.doSetSelection(selection);
synchronizeOutlinePageSelection();
}
+ boolean isFoldingEnabled() {
+ return PHPeclipsePlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_FOLDING_ENABLED);
+ }
/*
* @see org.eclipse.ui.IWorkbenchPart#createPartControl(org.eclipse.swt.
* widgets.Composite)
//fSourceViewerDecorationSupport.install(getPreferenceStore());
- Preferences preferences = PHPeclipsePlugin.getDefault().getPluginPreferences();
+ ProjectionViewer projectionViewer= (ProjectionViewer) getSourceViewer();
+
+ fProjectionSupport= new ProjectionSupport(projectionViewer, getAnnotationAccess(), getSharedColors());
+ fProjectionSupport.addSummarizableAnnotationType("org.eclipse.ui.workbench.texteditor.error"); //$NON-NLS-1$
+ fProjectionSupport.addSummarizableAnnotationType("org.eclipse.ui.workbench.texteditor.warning"); //$NON-NLS-1$
+ fProjectionSupport.setHoverControlCreator(new IInformationControlCreator() {
+ public IInformationControl createInformationControl(Shell shell) {
+ return new CustomSourceInformationControl(shell, IDocument.DEFAULT_CONTENT_TYPE);
+ }
+ });
+ fProjectionSupport.install();
+
+ fProjectionModelUpdater= PHPeclipsePlugin.getDefault().getFoldingStructureProviderRegistry().getCurrentFoldingProvider();
+ if (fProjectionModelUpdater != null)
+ fProjectionModelUpdater.install(this, projectionViewer);
+
+ if (isFoldingEnabled())
+ projectionViewer.doOperation(ProjectionViewer.TOGGLE);
+ Preferences preferences = PHPeclipsePlugin.getDefault().getPluginPreferences();
preferences.addPropertyChangeListener(fPropertyChangeListener);
-
+
IInformationControlCreator informationControlCreator = new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell parent) {
boolean cutDown = false;
protected void createActions() {
super.createActions();
+ fFoldingGroup= new FoldingActionGroup(this, getViewer());
+
ResourceAction resAction= new TextOperationAction(PHPEditorMessages.getResourceBundle(), "ShowJavaDoc.", this, ISourceViewer.INFORMATION, true); //$NON-NLS-1$
resAction= new InformationDispatchAction(PHPEditorMessages.getResourceBundle(), "ShowJavaDoc.", (TextOperationAction) resAction); //$NON-NLS-1$
resAction.setActionDefinitionId(PHPEditorActionDefinitionIds.SHOW_JAVADOC);
// add annotation actions
action= new JavaSelectMarkerRulerAction2(PHPEditorMessages.getResourceBundle(), "Editor.RulerAnnotationSelection.", this); //$NON-NLS-1$
setAction("AnnotationAction", action); //$NON-NLS-1$
-
- // add annotation actions
- action= new JavaSelectMarkerRulerAction2(PHPEditorMessages.getResourceBundle(), "Editor.RulerAnnotationSelection.", this); //$NON-NLS-1$
- setAction("AnnotationAction", action); //$NON-NLS-1$
}
+ private void internalDoSetInput(IEditorInput input) throws CoreException {
+ super.doSetInput(input);
+
+ if (fEncodingSupport != null)
+ fEncodingSupport.reset();
+
+ setOutlinePageInput(fOutlinePage, input);
+
+ if (fProjectionModelUpdater != null)
+ fProjectionModelUpdater.initialize();
+
+// if (isShowingOverrideIndicators())
+// installOverrideIndicator(true);
+ }
+
+ /*
+ * @see org.eclipse.ui.texteditor.AbstractTextEditor#setPreferenceStore(org.eclipse.jface.preference.IPreferenceStore)
+ * @since 3.0
+ */
+ protected void setPreferenceStore(IPreferenceStore store) {
+ super.setPreferenceStore(store);
+ if (getSourceViewerConfiguration() instanceof PHPSourceViewerConfiguration) {
+ JavaTextTools textTools= PHPeclipsePlugin.getDefault().getJavaTextTools();
+ setSourceViewerConfiguration(new PHPSourceViewerConfiguration(textTools.getColorManager(), store, this, IPHPPartitions.PHP_PARTITIONING));
+ }
+ if (getSourceViewer() instanceof JavaSourceViewer)
+ ((JavaSourceViewer)getSourceViewer()).setPreferenceStore(store);
+ }
/** The <code>PHPEditor</code> implementation of this
* <code>AbstractTextEditor</code> method performs any extra
* disposal actions required by the php editor.
*/
public void dispose() {
+ if (fProjectionModelUpdater != null) {
+ fProjectionModelUpdater.uninstall();
+ fProjectionModelUpdater= null;
+ }
+
+ if (fProjectionSupport != null) {
+ fProjectionSupport.dispose();
+ fProjectionSupport= null;
+ }
// PHPEditorEnvironment.disconnect(this);
if (fOutlinePage != null)
fOutlinePage.setInput(null);
};
}
-
+ if (fProjectionSupport != null) {
+ Object adapter= fProjectionSupport.getAdapter(getSourceViewer(), required);
+ if (adapter != null)
+ return adapter;
+ }
+
return super.getAdapter(required);
}
// public Object getAdapter(Class required) {
if (PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE.equals(property)) {
if (event.getNewValue() instanceof Boolean) {
Boolean disable= (Boolean) event.getNewValue();
- configureInsertMode(OVERWRITE, !disable.booleanValue());
+ enableOverwriteMode(!disable.booleanValue());
}
+ return;
}
// if (PreferenceConstants.EDITOR_MARK_OCCURRENCES.equals(property)) {
// }
// }
// }
-
+ if (PreferenceConstants.EDITOR_FOLDING_PROVIDER.equals(property)) {
+ if (sourceViewer instanceof ProjectionViewer) {
+ ProjectionViewer projectionViewer= (ProjectionViewer) sourceViewer;
+ if (fProjectionModelUpdater != null)
+ fProjectionModelUpdater.uninstall();
+ // either freshly enabled or provider changed
+ fProjectionModelUpdater= PHPeclipsePlugin.getDefault().getFoldingStructureProviderRegistry().getCurrentFoldingProvider();
+ if (fProjectionModelUpdater != null) {
+ fProjectionModelUpdater.install(this, projectionViewer);
+ }
+ }
+ return;
+ }
} finally {
super.handlePreferenceStoreChanged(event);
}
if (!isEditingScriptRunning() && fUpdater != null)
fUpdater.post();
}
-
+ /*
+ * @see org.eclipse.ui.texteditor.AbstractTextEditor#handleElementContentReplaced()
+ */
+ protected void handleElementContentReplaced() {
+ super.handleElementContentReplaced();
+ if (fProjectionModelUpdater != null)
+ fProjectionModelUpdater.initialize();
+ }
/**
* Initializes the given line number ruler column from the preference store.
* @param rulerColumn the ruler column to be initialized
return getSourceViewer();
}
- protected final ISourceViewer createSourceViewer(Composite parent, IVerticalRuler verticalRuler, int styles) {
- ISourceViewer viewer= createJavaSourceViewer(parent, verticalRuler, getOverviewRuler(), isOverviewRulerVisible(), styles);
-
- StyledText text= viewer.getTextWidget();
- text.addBidiSegmentListener(new BidiSegmentListener() {
- public void lineGetSegments(BidiSegmentEvent event) {
- event.segments= getBidiLineSegments(event.lineOffset, event.lineText);
- }
- });
-
-// JavaUIHelp.setHelp(this, text, IJavaHelpContextIds.JAVA_EDITOR);
-
- // ensure source viewer decoration support has been created and configured
- getSourceViewerDecorationSupport(viewer);
-
- return viewer;
-
-// ISharedTextColors sharedColors = PHPeclipsePlugin.getDefault().getJavaTextTools().getColorManager();
-//
-// fOverviewRuler = new OverviewRuler(fAnnotationAccess, VERTICAL_RULER_WIDTH, sharedColors);
-// fOverviewRuler.addHeaderAnnotationType(AnnotationType.WARNING);
-// fOverviewRuler.addHeaderAnnotationType(AnnotationType.ERROR);
-//
-// ISourceViewer viewer = createJavaSourceViewer(parent, verticalRuler, fOverviewRuler, isOverviewRulerVisible(), styles);
-//
-// StyledText text = viewer.getTextWidget();
-// text.addBidiSegmentListener(new BidiSegmentListener() {
-// public void lineGetSegments(BidiSegmentEvent event) {
-// event.segments = getBidiLineSegments(event.lineOffset, event.lineText);
-// }
-// });
-//
-// // JavaUIHelp.setHelp(this, text, IJavaHelpContextIds.JAVA_EDITOR);
-//
-// fSourceViewerDecorationSupport = new SourceViewerDecorationSupport(viewer, fOverviewRuler, fAnnotationAccess, sharedColors);
-// configureSourceViewerDecorationSupport();
-//
-// return viewer;
- }
// protected void showOverviewRuler() {
// if (fOverviewRuler != null) {
// int styles) {
// return new SourceViewer(parent, ruler, overviewRuler, isOverviewRulerVisible(), styles);
// }
-
+ /*
+ * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
+ */
+ protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, boolean isOverviewRulerVisible, int styles, IPreferenceStore store) {
+ return new JavaSourceViewer(parent, verticalRuler, getOverviewRuler(), isOverviewRulerVisible(), styles, store);
+ }
/*
* @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
*/
- protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, boolean isOverviewRulerVisible, int styles) {
- return new JavaSourceViewer(parent, verticalRuler, getOverviewRuler(), isOverviewRulerVisible(), styles);
+ protected final ISourceViewer createSourceViewer(Composite parent, IVerticalRuler verticalRuler, int styles) {
+
+ ISourceViewer viewer= createJavaSourceViewer(parent, verticalRuler, getOverviewRuler(), isOverviewRulerVisible(), styles, getPreferenceStore());
+
+ StyledText text= viewer.getTextWidget();
+ text.addBidiSegmentListener(new BidiSegmentListener() {
+ public void lineGetSegments(BidiSegmentEvent event) {
+ event.segments= getBidiLineSegments(event.lineOffset, event.lineText);
+ }
+ });
+
+// JavaUIHelp.setHelp(this, text, IJavaHelpContextIds.JAVA_EDITOR);
+
+ // ensure source viewer decoration support has been created and configured
+ getSourceViewerDecorationSupport(viewer);
+
+ return viewer;
}
+ /*
+ * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
+ */
+// protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, boolean isOverviewRulerVisible, int styles) {
+// return new JavaSourceViewer(parent, verticalRuler, getOverviewRuler(), isOverviewRulerVisible(), styles);
+// }
/*
* @see AbstractTextEditor#affectsTextPresentation(PropertyChangeEvent)
*/
fOccurrenceAnnotations= null;
}
}
+// protected void uninstallOverrideIndicator() {
+// if (fOverrideIndicatorManager != null) {
+// fOverrideIndicatorManager.removeAnnotations();
+// fOverrideIndicatorManager= null;
+// }
+//}
+
+protected void installOverrideIndicator(boolean waitForReconcilation) {
+// uninstallOverrideIndicator();
+ IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput());
+// IJavaElement inputElement= getInputJavaElement();
+
+// if (model == null || inputElement == null)
+// return;
+
+// CompilationUnit ast= PHPeclipsePlugin.getDefault().getASTProvider().getAST(inputElement, true, null);
+// fOverrideIndicatorManager= new OverrideIndicatorManager(model, inputElement, ast);
+}
+
+/**
+ * Tells whether override indicators are shown.
+ *
+ * @return <code>true</code> if the override indicators are shown
+ * @since 3.0
+ */
+//protected boolean isShowingOverrideIndicators() {
+// AnnotationPreference preference= getAnnotationPreferenceLookup().getAnnotationPreference(OverrideIndicatorManager.ANNOTATION_TYPE);
+// IPreferenceStore store= getPreferenceStore();
+// return getBoolean(store, preference.getHighlightPreferenceKey())
+// || getBoolean(store, preference.getVerticalRulerPreferenceKey())
+// || getBoolean(store, preference.getOverviewRulerPreferenceKey())
+// || getBoolean(store, preference.getTextPreferenceKey());
+//}
+
+/**
+ * Returns the boolean preference for the given key.
+ *
+ * @param store the preference store
+ * @param key the preference key
+ * @return <code>true</code> if the key exists in the store and its value is <code>true</code>
+ * @since 3.0
+ */
+private boolean getBoolean(IPreferenceStore store, String key) {
+ return key != null && store.getBoolean(key);
+}
+
+ /**
+ * Returns the folding action group, or <code>null</code> if there is none.
+ *
+ * @return the folding action group, or <code>null</code> if there is none
+ * @since 3.0
+ */
+ protected FoldingActionGroup getFoldingActionGroup() {
+ return fFoldingGroup;
+ }
}
import java.util.Vector;
import net.sourceforge.phpdt.core.JavaCore;
+import net.sourceforge.phpdt.internal.ui.text.AbstractJavaScanner;
import net.sourceforge.phpdt.internal.ui.text.ContentAssistPreference;
import net.sourceforge.phpdt.internal.ui.text.HTMLTextPresenter;
import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions;
import net.sourceforge.phpdt.internal.ui.text.JavaAnnotationHover;
import net.sourceforge.phpdt.internal.ui.text.JavaElementProvider;
import net.sourceforge.phpdt.internal.ui.text.JavaOutlineInformationControl;
+import net.sourceforge.phpdt.internal.ui.text.JavaPresentationReconciler;
import net.sourceforge.phpdt.internal.ui.text.JavaReconciler;
import net.sourceforge.phpdt.internal.ui.text.java.JavaFormattingStrategy;
import net.sourceforge.phpdt.internal.ui.text.java.JavaReconcilingStrategy;
import net.sourceforge.phpdt.internal.ui.text.java.hover.JavaEditorTextHoverProxy;
import net.sourceforge.phpdt.internal.ui.text.phpdoc.PHPDocCompletionProcessor;
import net.sourceforge.phpdt.ui.PreferenceConstants;
+import net.sourceforge.phpdt.ui.text.IColorManager;
import net.sourceforge.phpdt.ui.text.JavaTextTools;
import net.sourceforge.phpeclipse.PHPeclipsePlugin;
import net.sourceforge.phpeclipse.phpeditor.html.HTMLFormattingStrategy;
import org.eclipse.jface.text.source.IAnnotationHover;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.SourceViewerConfiguration;
+import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Shell;
+import org.eclipse.ui.texteditor.ITextEditor;
/**
* Configuration for an <code>SourceViewer</code> which shows PHP code.
*/
// IPHPPartitionScannerConstants.HTML;
//IDocument.DEFAULT_CONTENT_TYPE;
private JavaTextTools fJavaTextTools;
- private PHPEditor fEditor;
+ private ITextEditor fTextEditor;
private ContentFormatter fFormatter;
private HTMLFormattingStrategy fFormattingStrategy;
/**
}
};
/**
+ * The document partitioning.
+ * @since 3.0
+ */
+ private String fDocumentPartitioning;
+ /**
+ * The Java source code scanner
+ * @since 3.0
+ */
+ private AbstractJavaScanner fCodeScanner;
+ /**
+ * The Java multi-line comment scanner
+ * @since 3.0
+ */
+ private AbstractJavaScanner fMultilineCommentScanner;
+ /**
+ * The Java single-line comment scanner
+ * @since 3.0
+ */
+ private AbstractJavaScanner fSinglelineCommentScanner;
+ /**
+ * The Java string scanner
+ * @since 3.0
+ */
+ private AbstractJavaScanner fStringScanner;
+ /**
+ * The Javadoc scanner
+ * @since 3.0
+ */
+ private AbstractJavaScanner fJavaDocScanner;
+ /**
+ * The preference store, can be read-only
+ * @since 3.0
+ */
+ private IPreferenceStore fPreferenceStore;
+ /**
+ * The color manager
+ * @since 3.0
+ */
+ private IColorManager fColorManager;
+
+ /**
+ * Creates a new Java source viewer configuration for viewers in the given editor
+ * using the given preference store, the color manager and the specified document partitioning.
+ * <p>
+ * Creates a Java source viewer configuration in the new setup without text tools. Clients are
+ * allowed to call {@link JavaSourceViewerConfiguration#handlePropertyChangeEvent(PropertyChangeEvent)}
+ * and disallowed to call {@link JavaSourceViewerConfiguration#getPreferenceStore()} on the resulting
+ * Java source viewer configuration.
+ * </p>
+ *
+ * @param colorManager the color manager
+ * @param preferenceStore the preference store, can be read-only
+ * @param editor the editor in which the configured viewer(s) will reside
+ * @param partitioning the document partitioning for this configuration
+ * @since 3.0
+ */
+ public PHPSourceViewerConfiguration(IColorManager colorManager, IPreferenceStore preferenceStore, ITextEditor editor, String partitioning) {
+ fColorManager= colorManager;
+ fPreferenceStore= preferenceStore;
+ fTextEditor= editor;
+ fDocumentPartitioning= partitioning;
+ fJavaTextTools = PHPeclipsePlugin.getDefault().getJavaTextTools();
+// initializeScanners();
+ }
+
+ /**
* Default constructor.
*/
public PHPSourceViewerConfiguration(JavaTextTools textTools,
PHPEditor editor) {
fJavaTextTools = textTools;
- fEditor = editor;
+ fTextEditor = editor;
}
/*
* @see SourceViewerConfiguration#getContentFormatter(ISourceViewer)
// private String[] getPartitionManagingPositionCategories() {
// return new String[] { DefaultPartitioner.CONTENT_TYPES_CATEGORY };
// }
- public PHPEditor getEditor() {
- return fEditor;
+ public ITextEditor getEditor() {
+ return fTextEditor;
}
/**
* Returns the preference store used by this configuration to initialize
// PHPEditorEnvironment.getPHPColorProvider();
// JavaColorManager provider =
// PHPEditorEnvironment.getPHPColorProvider();
- PresentationReconciler reconciler = new PresentationReconciler();
+ PresentationReconciler reconciler= new JavaPresentationReconciler();
+ reconciler.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer));
+
DefaultDamagerRepairer dr = new DefaultDamagerRepairer(getHTMLScanner());
reconciler.setDamager(dr, IDocument.DEFAULT_CONTENT_TYPE);
reconciler.setRepairer(dr, IDocument.DEFAULT_CONTENT_TYPE);
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.transform.OutputKeys;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
import net.sourceforge.phpeclipse.IPreferenceConstants;
import net.sourceforge.phpeclipse.PHPeclipsePlugin;
import net.sourceforge.phpeclipse.phpeditor.php.PHPKeyword;
import net.sourceforge.phpeclipse.phpeditor.php.PHPType;
-import org.apache.xml.serialize.OutputFormat;
-import org.apache.xml.serialize.Serializer;
-import org.apache.xml.serialize.SerializerFactory;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
// attributes.setNamedItem(usage);
}
}
- OutputFormat format = new OutputFormat();
- format.setPreserveSpace(true);
- try {
- Serializer serializer = SerializerFactory.getSerializerFactory("xml").makeSerializer(stream, format);
- serializer.asDOMSerializer().serialize(document);
- } catch (UnsupportedEncodingException e) {
- } catch (IOException e) {
- } //$NON-NLS-1$
- // Serializer serializer = SerializerFactory.getSerializer().makeSerializer(stream, format); //$NON-NLS-1$
- } catch (ParserConfigurationException e) {
- throwWriteException(e);
- // } catch (IOException e) {
- // throwWriteException(e);
- }
+ Transformer transformer=TransformerFactory.newInstance().newTransformer();
+ transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
+ transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); //$NON-NLS-1$
+ DOMSource source = new DOMSource(document);
+ StreamResult result = new StreamResult(stream);
+
+ transformer.transform(source, result);
+
+ } catch (ParserConfigurationException e) {
+ throwWriteException(e);
+ } catch (TransformerException e) {
+ throwWriteException(e);
+ }
+// OutputFormat format = new OutputFormat();
+// format.setPreserveSpace(true);
+// try {
+// Serializer serializer = SerializerFactory.getSerializerFactory("xml").makeSerializer(stream, format);
+// serializer.asDOMSerializer().serialize(document);
+// } catch (UnsupportedEncodingException e) {
+// } catch (IOException e) {
+// } //$NON-NLS-1$
+// // Serializer serializer = SerializerFactory.getSerializer().makeSerializer(stream, format); //$NON-NLS-1$
+// } catch (ParserConfigurationException e) {
+// throwWriteException(e);
+// }
}
private static void throwReadException(Throwable t) throws CoreException {
package net.sourceforge.phpeclipse.phpeditor;
+
import java.lang.reflect.InvocationTargetException;
import java.text.MessageFormat;
import java.util.ArrayList;
import org.eclipse.core.resources.IFile;
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.IStatus;
import org.eclipse.core.runtime.Preferences;
+
+import net.sourceforge.phpdt.internal.ui.text.java.IJavaReconcilingListener;
+
import org.eclipse.jface.action.Action;
+import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.text.IWidgetTokenKeeper;
import org.eclipse.jface.text.contentassist.ContentAssistant;
import org.eclipse.jface.text.contentassist.IContentAssistant;
+import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.text.source.IOverviewRuler;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.IVerticalRuler;
import org.eclipse.jface.text.source.SourceViewerConfiguration;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.ISelectionProvider;
+import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.VerifyKeyListener;
import org.eclipse.swt.events.VerifyEvent;
/**
* PHP specific text editor.
*/
-public class PHPUnitEditor extends PHPEditor {
- interface ITextConverter {
- void customizeDocumentCommand(IDocument document, DocumentCommand command);
- };
- // class AdaptedRulerLayout extends Layout {
- //
- // protected int fGap;
- // protected AdaptedSourceViewer fAdaptedSourceViewer;
- //
- // protected AdaptedRulerLayout(int gap, AdaptedSourceViewer asv) {
- // fGap = gap;
- // fAdaptedSourceViewer = asv;
- // }
- //
- // protected Point computeSize(Composite composite, int wHint, int hHint,
- // boolean flushCache) {
- // Control[] children = composite.getChildren();
- // Point s = children[children.length - 1].computeSize(SWT.DEFAULT,
- // SWT.DEFAULT, flushCache);
- // if (fAdaptedSourceViewer.isVerticalRulerVisible())
- // s.x += fAdaptedSourceViewer.getVerticalRuler().getWidth() + fGap;
- // return s;
- // }
- //
- // protected void layout(Composite composite, boolean flushCache) {
- // Rectangle clArea = composite.getClientArea();
- // if (fAdaptedSourceViewer.isVerticalRulerVisible()) {
- //
- // StyledText textWidget = fAdaptedSourceViewer.getTextWidget();
- // Rectangle trim = textWidget.computeTrim(0, 0, 0, 0);
- // int scrollbarHeight = trim.height;
- //
- // IVerticalRuler vr = fAdaptedSourceViewer.getVerticalRuler();
- // int vrWidth = vr.getWidth();
- //
- // int orWidth = 0;
- // if (fAdaptedSourceViewer.isOverviewRulerVisible()) {
- // OverviewRuler or = fAdaptedSourceViewer.getOverviewRuler();
- // orWidth = or.getWidth();
- // or.getControl().setBounds(clArea.width - orWidth, scrollbarHeight,
- // orWidth, clArea.height - 3 * scrollbarHeight);
- // }
- //
- // textWidget.setBounds(vrWidth + fGap, 0, clArea.width - vrWidth - orWidth -
- // 2 * fGap, clArea.height);
- // vr.getControl().setBounds(0, 0, vrWidth, clArea.height - scrollbarHeight);
- //
- // } else {
- // StyledText textWidget = fAdaptedSourceViewer.getTextWidget();
- // textWidget.setBounds(0, 0, clArea.width, clArea.height);
- // }
- // }
- // };
- //
- // class AdaptedSourceViewer extends SourceViewer { // extends
- // JavaCorrectionSourceViewer {
- //
- // private List fTextConverters;
- //
- // private OverviewRuler fOverviewRuler;
- // private boolean fIsOverviewRulerVisible;
- // /** The viewer's overview ruler hovering controller */
- // private AbstractHoverInformationControlManager
- // fOverviewRulerHoveringController;
- //
- // private boolean fIgnoreTextConverters = false;
- //
- // private IVerticalRuler fCachedVerticalRuler;
- // private boolean fCachedIsVerticalRulerVisible;
- //
- // public AdaptedSourceViewer(Composite parent, IVerticalRuler ruler, int
- // styles) {
- // super(parent, ruler, styles); //, CompilationUnitEditor.this);
- //
- // fCachedVerticalRuler = ruler;
- // fCachedIsVerticalRulerVisible = (ruler != null);
- // fOverviewRuler = new OverviewRuler(VERTICAL_RULER_WIDTH);
- //
- // delayedCreateControl(parent, styles);
- // }
- //
- // /*
- // * @see ISourceViewer#showAnnotations(boolean)
- // */
- // public void showAnnotations(boolean show) {
- // fCachedIsVerticalRulerVisible = (show && fCachedVerticalRuler != null);
- // // super.showAnnotations(show);
- // }
- //
- // public IContentAssistant getContentAssistant() {
- // return fContentAssistant;
- // }
- //
- // /*
- // * @see ITextOperationTarget#doOperation(int)
- // */
- // public void doOperation(int operation) {
- //
- // if (getTextWidget() == null)
- // return;
- //
- // switch (operation) {
- // case CONTENTASSIST_PROPOSALS :
- // String msg = fContentAssistant.showPossibleCompletions();
- // setStatusLineErrorMessage(msg);
- // return;
- // case UNDO :
- // fIgnoreTextConverters = true;
- // break;
- // case REDO :
- // fIgnoreTextConverters = true;
- // break;
- // }
- //
- // super.doOperation(operation);
- // }
- //
- // public void insertTextConverter(ITextConverter textConverter, int index) {
- // throw new UnsupportedOperationException();
- // }
- //
- // public void addTextConverter(ITextConverter textConverter) {
- // if (fTextConverters == null) {
- // fTextConverters = new ArrayList(1);
- // fTextConverters.add(textConverter);
- // } else if (!fTextConverters.contains(textConverter))
- // fTextConverters.add(textConverter);
- // }
- //
- // public void removeTextConverter(ITextConverter textConverter) {
- // if (fTextConverters != null) {
- // fTextConverters.remove(textConverter);
- // if (fTextConverters.size() == 0)
- // fTextConverters = null;
- // }
- // }
- //
- // /*
- // * @see TextViewer#customizeDocumentCommand(DocumentCommand)
- // */
- // protected void customizeDocumentCommand(DocumentCommand command) {
- // super.customizeDocumentCommand(command);
- // if (!fIgnoreTextConverters && fTextConverters != null) {
- // for (Iterator e = fTextConverters.iterator(); e.hasNext();)
- // ((ITextConverter) e.next()).customizeDocumentCommand(getDocument(),
- // command);
- // }
- // fIgnoreTextConverters = false;
- // }
- //
- // public IVerticalRuler getVerticalRuler() {
- // return fCachedVerticalRuler;
- // }
- //
- // public boolean isVerticalRulerVisible() {
- // return fCachedIsVerticalRulerVisible;
- // }
- //
- // public OverviewRuler getOverviewRuler() {
- // return fOverviewRuler;
- // }
- //
- // /*
- // * @see TextViewer#createControl(Composite, int)
- // */
- // protected void createControl(Composite parent, int styles) {
- // // do nothing here
- // }
- //
- // protected void delayedCreateControl(Composite parent, int styles) {
- // //create the viewer
- // super.createControl(parent, styles);
- //
- // Control control = getControl();
- // if (control instanceof Composite) {
- // Composite composite = (Composite) control;
- // composite.setLayout(new AdaptedRulerLayout(GAP_SIZE, this));
- // fOverviewRuler.createControl(composite, this);
- // }
- // }
- // protected void ensureOverviewHoverManagerInstalled() {
- // if (fOverviewRulerHoveringController == null && fAnnotationHover != null
- // && fHoverControlCreator != null) {
- // fOverviewRulerHoveringController =
- // new OverviewRulerHoverManager(fOverviewRuler, this, fAnnotationHover,
- // fHoverControlCreator);
- // fOverviewRulerHoveringController.install(fOverviewRuler.getControl());
- // }
- // }
- //
- // public void hideOverviewRuler() {
- // fIsOverviewRulerVisible = false;
- // Control control = getControl();
- // if (control instanceof Composite) {
- // Composite composite = (Composite) control;
- // composite.layout();
- // }
- // if (fOverviewRulerHoveringController != null) {
- // fOverviewRulerHoveringController.dispose();
- // fOverviewRulerHoveringController = null;
- // }
- // }
- //
- // public void showOverviewRuler() {
- // fIsOverviewRulerVisible = true;
- // Control control = getControl();
- // if (control instanceof Composite) {
- // Composite composite = (Composite) control;
- // composite.layout();
- // }
- // ensureOverviewHoverManagerInstalled();
- // }
- //
- // public boolean isOverviewRulerVisible() {
- // return fIsOverviewRulerVisible;
- // }
- //
- // /*
- // * @see ISourceViewer#setDocument(IDocument, IAnnotationModel, int, int)
- // */
- // public void setDocument(
- // IDocument document,
- // IAnnotationModel annotationModel,
- // int visibleRegionOffset,
- // int visibleRegionLength) {
- // super.setDocument(document, annotationModel, visibleRegionOffset,
- // visibleRegionLength);
- // fOverviewRuler.setModel(annotationModel);
- // }
- //
- // // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270
- // public void updateIndentationPrefixes() {
- // SourceViewerConfiguration configuration = getSourceViewerConfiguration();
- // String[] types = configuration.getConfiguredContentTypes(this);
- // for (int i = 0; i < types.length; i++) {
- // String[] prefixes = configuration.getIndentPrefixes(this, types[i]);
- // if (prefixes != null && prefixes.length > 0)
- // setIndentPrefixes(prefixes, types[i]);
- // }
- // }
- //
- // /*
- // * @see IWidgetTokenOwner#requestWidgetToken(IWidgetTokenKeeper)
- // */
- // public boolean requestWidgetToken(IWidgetTokenKeeper requester) {
- // if (WorkbenchHelp.isContextHelpDisplayed())
- // return false;
- // return super.requestWidgetToken(requester);
- // }
- //
- // /*
- // * @see
- // org.eclipse.jface.text.source.ISourceViewer#configure(org.eclipse.jface.text.source.SourceViewerConfiguration)
- // */
- // public void configure(SourceViewerConfiguration configuration) {
- // super.configure(configuration);
- // // prependAutoEditStrategy(new SmartBracesAutoEditStrategy(this),
- // IDocument.DEFAULT_CONTENT_TYPE);
- // }
- //
- // protected void handleDispose() {
- // fOverviewRuler = null;
- //
- // if (fOverviewRulerHoveringController != null) {
- // fOverviewRulerHoveringController.dispose();
- // fOverviewRulerHoveringController = null;
- // }
- //
- // super.handleDispose();
- // }
- //
- // };
- class AdaptedSourceViewer extends JavaSourceViewer {
- private List fTextConverters;
- private boolean fIgnoreTextConverters = false;
- // private JavaCorrectionAssistant fCorrectionAssistant;
- public AdaptedSourceViewer(Composite parent, IVerticalRuler verticalRuler,
- IOverviewRuler overviewRuler, boolean showAnnotationsOverview,
- int styles) {
- super(parent, verticalRuler, overviewRuler, showAnnotationsOverview,
- styles);
- }
- public IContentAssistant getContentAssistant() {
- return fContentAssistant;
- }
- /*
- * @see ITextOperationTarget#doOperation(int)
- */
- public void doOperation(int operation) {
- if (getTextWidget() == null)
- return;
- switch (operation) {
- case CONTENTASSIST_PROPOSALS :
- String msg = fContentAssistant.showPossibleCompletions();
- setStatusLineErrorMessage(msg);
- return;
- // case CORRECTIONASSIST_PROPOSALS:
- // fCorrectionAssistant.showPossibleCompletions();
- // return;
- case UNDO :
- fIgnoreTextConverters = true;
- break;
- case REDO :
- fIgnoreTextConverters = true;
- break;
- }
- super.doOperation(operation);
- }
- /*
- * @see ITextOperationTarget#canDoOperation(int)
- */
- public boolean canDoOperation(int operation) {
- // if (operation == CORRECTIONASSIST_PROPOSALS)
- // return isEditable();
- return super.canDoOperation(operation);
- }
- /*
- * @see TextViewer#handleDispose()
- */
- protected void handleDispose() {
- // if (fCorrectionAssistant != null) {
- // fCorrectionAssistant.uninstall();
- // fCorrectionAssistant= null;
- // }
- super.handleDispose();
- }
- public void insertTextConverter(ITextConverter textConverter, int index) {
- throw new UnsupportedOperationException();
- }
- public void addTextConverter(ITextConverter textConverter) {
- if (fTextConverters == null) {
- fTextConverters = new ArrayList(1);
- fTextConverters.add(textConverter);
- } else if (!fTextConverters.contains(textConverter))
- fTextConverters.add(textConverter);
- }
- public void removeTextConverter(ITextConverter textConverter) {
- if (fTextConverters != null) {
- fTextConverters.remove(textConverter);
- if (fTextConverters.size() == 0)
- fTextConverters = null;
- }
- }
- /*
- * @see TextViewer#customizeDocumentCommand(DocumentCommand)
- */
- protected void customizeDocumentCommand(DocumentCommand command) {
- super.customizeDocumentCommand(command);
- if (!fIgnoreTextConverters && fTextConverters != null) {
- for (Iterator e = fTextConverters.iterator(); e.hasNext();)
- ((ITextConverter) e.next()).customizeDocumentCommand(getDocument(),
- command);
- }
- fIgnoreTextConverters = false;
- }
- // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270
- public void updateIndentationPrefixes() {
- SourceViewerConfiguration configuration = getSourceViewerConfiguration();
- String[] types = configuration.getConfiguredContentTypes(this);
- for (int i = 0; i < types.length; i++) {
- String[] prefixes = configuration.getIndentPrefixes(this, types[i]);
- if (prefixes != null && prefixes.length > 0)
- setIndentPrefixes(prefixes, types[i]);
- }
- }
- /*
- * @see IWidgetTokenOwner#requestWidgetToken(IWidgetTokenKeeper)
- */
- public boolean requestWidgetToken(IWidgetTokenKeeper requester) {
- if (WorkbenchHelp.isContextHelpDisplayed())
- return false;
- return super.requestWidgetToken(requester);
- }
- /*
- * @see org.eclipse.jface.text.source.ISourceViewer#configure(org.eclipse.jface.text.source.SourceViewerConfiguration)
- */
- public void configure(SourceViewerConfiguration configuration) {
- super.configure(configuration);
- // fCorrectionAssistant= new
- // JavaCorrectionAssistant(CompilationUnitEditor.this);
- // fCorrectionAssistant.install(this);
- //TODO install SmartBracesAutoEditStrategy
- // prependAutoEditStrategy(new SmartBracesAutoEditStrategy(this),
- // IDocument.DEFAULT_CONTENT_TYPE);
- }
- };
- static class TabConverter implements ITextConverter {
- private int fTabRatio;
- private ILineTracker fLineTracker;
- public TabConverter() {
- }
- public void setNumberOfSpacesPerTab(int ratio) {
- fTabRatio = ratio;
- }
- public void setLineTracker(ILineTracker lineTracker) {
- fLineTracker = lineTracker;
- }
- private int insertTabString(StringBuffer buffer, int offsetInLine) {
- if (fTabRatio == 0)
- return 0;
- int remainder = offsetInLine % fTabRatio;
- remainder = fTabRatio - remainder;
- for (int i = 0; i < remainder; i++)
- buffer.append(' ');
- return remainder;
- }
- public void customizeDocumentCommand(IDocument document,
- DocumentCommand command) {
- String text = command.text;
- if (text == null)
- return;
- int index = text.indexOf('\t');
- if (index > -1) {
- StringBuffer buffer = new StringBuffer();
- fLineTracker.set(command.text);
- int lines = fLineTracker.getNumberOfLines();
- try {
- for (int i = 0; i < lines; i++) {
- int offset = fLineTracker.getLineOffset(i);
- int endOffset = offset + fLineTracker.getLineLength(i);
- String line = text.substring(offset, endOffset);
- int position = 0;
- if (i == 0) {
- IRegion firstLine = document
- .getLineInformationOfOffset(command.offset);
- position = command.offset - firstLine.getOffset();
- }
- int length = line.length();
- for (int j = 0; j < length; j++) {
- char c = line.charAt(j);
- if (c == '\t') {
- position += insertTabString(buffer, position);
- } else {
- buffer.append(c);
- ++position;
- }
- }
- }
- command.text = buffer.toString();
- } catch (BadLocationException x) {
- }
- }
- }
- };
- private static class ExitPolicy implements LinkedPositionUI.ExitPolicy {
- final char fExitCharacter;
- public ExitPolicy(char exitCharacter) {
- fExitCharacter = exitCharacter;
- }
- /*
- * @see org.phpeclipse.phpdt.internal.ui.text.link.LinkedPositionUI.ExitPolicy#doExit(org.phpeclipse.phpdt.internal.ui.text.link.LinkedPositionManager,
- * org.eclipse.swt.events.VerifyEvent, int, int)
- */
- public ExitFlags doExit(LinkedPositionManager manager, VerifyEvent event,
- int offset, int length) {
- if (event.character == fExitCharacter) {
- if (manager.anyPositionIncludes(offset, length))
- return new ExitFlags(LinkedPositionUI.COMMIT
- | LinkedPositionUI.UPDATE_CARET, false);
- else
- return new ExitFlags(LinkedPositionUI.COMMIT, true);
- }
- switch (event.character) {
- case '\b' :
- if (manager.getFirstPosition().length == 0)
- return new ExitFlags(0, false);
- else
- return null;
- case '\n' :
- case '\r' :
- return new ExitFlags(LinkedPositionUI.COMMIT, true);
- default :
- return null;
- }
- }
- }
- private static class BracketLevel {
- int fOffset;
- int fLength;
- LinkedPositionManager fManager;
- LinkedPositionUI fEditor;
- };
- private class BracketInserter
- implements
- VerifyKeyListener,
- LinkedPositionUI.ExitListener {
- private boolean fCloseBracketsPHP = true;
- private boolean fCloseStringsPHP = true;
- private boolean fCloseBracketsHTML = true;
- private boolean fCloseStringsHTML = true;
- private int fOffset;
- private int fLength;
- public void setCloseBracketsPHPEnabled(boolean enabled) {
- fCloseBracketsPHP = enabled;
- }
- public void setCloseStringsPHPEnabled(boolean enabled) {
- fCloseStringsPHP = enabled;
- }
- public void setCloseBracketsHTMLEnabled(boolean enabled) {
- fCloseBracketsHTML = enabled;
- }
- public void setCloseStringsHTMLEnabled(boolean enabled) {
- fCloseStringsHTML = enabled;
- }
- private boolean hasIdentifierToTheRight(IDocument document, int offset) {
- try {
- int end = offset;
- IRegion endLine = document.getLineInformationOfOffset(end);
- int maxEnd = endLine.getOffset() + endLine.getLength();
- while (end != maxEnd && Character.isWhitespace(document.getChar(end)))
- ++end;
- return end != maxEnd
- && Scanner.isPHPIdentifierPart(document.getChar(end));
- } catch (BadLocationException e) {
- // be conservative
- return true;
- }
- }
- private boolean hasIdentifierToTheLeft(IDocument document, int offset) {
- try {
- int start = offset;
- IRegion startLine = document.getLineInformationOfOffset(start);
- int minStart = startLine.getOffset();
- while (start != minStart
- && Character.isWhitespace(document.getChar(start - 1)))
- --start;
- return start != minStart
- && Scanner.isPHPIdentifierPart(document.getChar(start - 1));
- } catch (BadLocationException e) {
- return true;
- }
- }
- private boolean hasCharacterToTheRight(IDocument document, int offset,
- char character) {
- try {
- int end = offset;
- IRegion endLine = document.getLineInformationOfOffset(end);
- int maxEnd = endLine.getOffset() + endLine.getLength();
- while (end != maxEnd && Character.isWhitespace(document.getChar(end)))
- ++end;
- return end != maxEnd && document.getChar(end) == character;
- } catch (BadLocationException e) {
- // be conservative
- return true;
- }
- }
- /*
- * @see org.eclipse.swt.custom.VerifyKeyListener#verifyKey(org.eclipse.swt.events.VerifyEvent)
- */
- public void verifyKey(VerifyEvent event) {
- if (!event.doit)
- return;
- final ISourceViewer sourceViewer = getSourceViewer();
- IDocument document = sourceViewer.getDocument();
- final Point selection = sourceViewer.getSelectedRange();
- final int offset = selection.x;
- final int length = selection.y;
- try {
- ITypedRegion partition = document.getPartition(offset);
- String type = partition.getType();
- if (type.equals(IPHPPartitions.PHP_PARTITIONING)) {
- switch (event.character) {
- case '(' :
- if (hasCharacterToTheRight(document, offset + length, '('))
- return;
- // fall through
- case '[' :
- if (!fCloseBracketsPHP)
- return;
- if (hasIdentifierToTheRight(document, offset + length))
- return;
- // fall through
- case '"' :
- if (event.character == '"') {
- if (!fCloseStringsPHP)
- return;
- // changed for statements like echo "" print ""
- // if (hasIdentifierToTheLeft(document, offset) ||
- // hasIdentifierToTheRight(document, offset + length))
- if (hasIdentifierToTheRight(document, offset + length))
- return;
- }
- // ITypedRegion partition= document.getPartition(offset);
- // if (!
- // IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType()) &&
- // (partition.getOffset() != offset))
- // return;
- final char character = event.character;
- final char closingCharacter = getPeerCharacter(character);
- final StringBuffer buffer = new StringBuffer();
- buffer.append(character);
- buffer.append(closingCharacter);
- document.replace(offset, length, buffer.toString());
- LinkedPositionManager manager = new LinkedPositionManager(
- document);
- manager.addPosition(offset + 1, 0);
- fOffset = offset;
- fLength = 2;
- LinkedPositionUI editor = new LinkedPositionUI(sourceViewer,
- manager);
- editor.setCancelListener(this);
- editor.setExitPolicy(new ExitPolicy(closingCharacter));
- editor.setFinalCaretOffset(offset + 2);
- editor.enter();
- IRegion newSelection = editor.getSelectedRegion();
- sourceViewer.setSelectedRange(newSelection.getOffset(),
- newSelection.getLength());
- event.doit = false;
- }
- } else if (type.equals(IPHPPartitions.HTML)
- || type.equals(IDocument.DEFAULT_CONTENT_TYPE)) {
- switch (event.character) {
- case '(' :
- if (hasCharacterToTheRight(document, offset + length, '('))
- return;
- // fall through
- case '[' :
- if (!fCloseBracketsHTML)
- return;
- if (hasIdentifierToTheRight(document, offset + length))
- return;
- // fall through
- case '"' :
- if (event.character == '"') {
- if (!fCloseStringsHTML)
- return;
- if (hasIdentifierToTheLeft(document, offset)
- || hasIdentifierToTheRight(document, offset + length))
- return;
- }
- // ITypedRegion partition= document.getPartition(offset);
- // if (!
- // IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType()) &&
- // (partition.getOffset() != offset))
- // return;
- final char character = event.character;
- final char closingCharacter = getPeerCharacter(character);
- final StringBuffer buffer = new StringBuffer();
- buffer.append(character);
- buffer.append(closingCharacter);
- document.replace(offset, length, buffer.toString());
- LinkedPositionManager manager = new LinkedPositionManager(
- document);
- manager.addPosition(offset + 1, 0);
- fOffset = offset;
- fLength = 2;
- LinkedPositionUI editor = new LinkedPositionUI(sourceViewer,
- manager);
- editor.setCancelListener(this);
- editor.setExitPolicy(new ExitPolicy(closingCharacter));
- editor.setFinalCaretOffset(offset + 2);
- editor.enter();
- IRegion newSelection = editor.getSelectedRegion();
- sourceViewer.setSelectedRange(newSelection.getOffset(),
- newSelection.getLength());
- event.doit = false;
- }
- }
- } catch (BadLocationException e) {
- }
- }
- /*
- * @see org.phpeclipse.phpdt.internal.ui.text.link.LinkedPositionUI.ExitListener#exit(boolean)
- */
- public void exit(boolean accept) {
- if (accept)
- return;
- // remove brackets
- try {
- final ISourceViewer sourceViewer = getSourceViewer();
- IDocument document = sourceViewer.getDocument();
- document.replace(fOffset, fLength, null);
- } catch (BadLocationException e) {
- }
- }
- }
- /** The editor's save policy */
- protected ISavePolicy fSavePolicy;
- /**
- * Listener to annotation model changes that updates the error tick in the
- * tab image
- */
- private JavaEditorErrorTickUpdater fJavaEditorErrorTickUpdater;
- /** The editor's paint manager */
- // private PaintManager fPaintManager;
- /** The editor's bracket painter */
- private BracketPainter fBracketPainter;
- /** The editor's bracket matcher */
- private PHPPairMatcher fBracketMatcher;
- /** The editor's line painter */
- private LinePainter fLinePainter;
- /** The editor's print margin ruler painter */
- private PrintMarginPainter fPrintMarginPainter;
- /** The editor's problem painter */
- // private ProblemPainter fProblemPainter;
- /** The editor's tab converter */
- private TabConverter fTabConverter;
- /** History for structure select action */
- //private SelectionHistory fSelectionHistory;
- /** The preference property change listener for php core. */
- // private IPropertyChangeListener fPropertyChangeListener = new
- // PropertyChangeListener();
- /** The remembered java element */
- private IJavaElement fRememberedElement;
- /** The remembered selection */
- private ITextSelection fRememberedSelection;
- /** The remembered php element offset */
- private int fRememberedElementOffset;
- /** The bracket inserter. */
- private BracketInserter fBracketInserter = new BracketInserter();
-
- /** The standard action groups added to the menu */
- private GenerateActionGroup fGenerateActionGroup;
- private CompositeActionGroup fContextMenuGroup;
- // private class PropertyChangeListener implements IPropertyChangeListener {
- // /*
- // * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
- // */
- // public void
- // propertyChange(org.eclipse.core.runtime.Preferences.PropertyChangeEvent
- // event) {
- // handlePreferencePropertyChanged(event);
- // }
- // }
- /* Preference key for code formatter tab size */
- private final static String CODE_FORMATTER_TAB_SIZE = JavaCore.FORMATTER_TAB_SIZE;
- /** Preference key for matching brackets */
- private final static String MATCHING_BRACKETS = PreferenceConstants.EDITOR_MATCHING_BRACKETS;
- /** Preference key for matching brackets color */
- private final static String MATCHING_BRACKETS_COLOR = PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR;
- /** Preference key for highlighting current line */
- private final static String CURRENT_LINE = PreferenceConstants.EDITOR_CURRENT_LINE;
- /** Preference key for highlight color of current line */
- private final static String CURRENT_LINE_COLOR = PreferenceConstants.EDITOR_CURRENT_LINE_COLOR;
- /** Preference key for showing print marging ruler */
- private final static String PRINT_MARGIN = PreferenceConstants.EDITOR_PRINT_MARGIN;
- /** Preference key for print margin ruler color */
- private final static String PRINT_MARGIN_COLOR = PreferenceConstants.EDITOR_PRINT_MARGIN_COLOR;
- /** Preference key for print margin ruler column */
- private final static String PRINT_MARGIN_COLUMN = PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN;
- /** Preference key for inserting spaces rather than tabs */
- private final static String SPACES_FOR_TABS = PreferenceConstants.EDITOR_SPACES_FOR_TABS;
- /** Preference key for error indication */
- // private final static String ERROR_INDICATION =
- // PreferenceConstants.EDITOR_PROBLEM_INDICATION;
- /** Preference key for error color */
- // private final static String ERROR_INDICATION_COLOR =
- // PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR;
- /** Preference key for warning indication */
- // private final static String WARNING_INDICATION =
- // PreferenceConstants.EDITOR_WARNING_INDICATION;
- /** Preference key for warning color */
- // private final static String WARNING_INDICATION_COLOR =
- // PreferenceConstants.EDITOR_WARNING_INDICATION_COLOR;
- /** Preference key for task indication */
- private final static String TASK_INDICATION = PreferenceConstants.EDITOR_TASK_INDICATION;
- /** Preference key for task color */
- private final static String TASK_INDICATION_COLOR = PreferenceConstants.EDITOR_TASK_INDICATION_COLOR;
- /** Preference key for bookmark indication */
- private final static String BOOKMARK_INDICATION = PreferenceConstants.EDITOR_BOOKMARK_INDICATION;
- /** Preference key for bookmark color */
- private final static String BOOKMARK_INDICATION_COLOR = PreferenceConstants.EDITOR_BOOKMARK_INDICATION_COLOR;
- /** Preference key for search result indication */
- private final static String SEARCH_RESULT_INDICATION = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION;
- /** Preference key for search result color */
- private final static String SEARCH_RESULT_INDICATION_COLOR = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_COLOR;
- /** Preference key for unknown annotation indication */
- private final static String UNKNOWN_INDICATION = PreferenceConstants.EDITOR_UNKNOWN_INDICATION;
- /** Preference key for unknown annotation color */
- private final static String UNKNOWN_INDICATION_COLOR = PreferenceConstants.EDITOR_UNKNOWN_INDICATION_COLOR;
- /** Preference key for linked position color */
- private final static String LINKED_POSITION_COLOR = PreferenceConstants.EDITOR_LINKED_POSITION_COLOR;
- /** Preference key for shwoing the overview ruler */
- private final static String OVERVIEW_RULER = PreferenceConstants.EDITOR_OVERVIEW_RULER;
- /** Preference key for error indication in overview ruler */
- private final static String ERROR_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER;
- /** Preference key for warning indication in overview ruler */
- private final static String WARNING_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER;
- /** Preference key for task indication in overview ruler */
- private final static String TASK_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER;
- /** Preference key for bookmark indication in overview ruler */
- private final static String BOOKMARK_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER;
- /** Preference key for search result indication in overview ruler */
- private final static String SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER;
- /** Preference key for unknown annotation indication in overview ruler */
- private final static String UNKNOWN_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER;
- /** Preference key for automatically closing strings */
- private final static String CLOSE_STRINGS_PHP = PreferenceConstants.EDITOR_CLOSE_STRINGS_PHP;
- /** Preference key for automatically wrapping Java strings */
- private final static String WRAP_STRINGS = PreferenceConstants.EDITOR_WRAP_STRINGS;
- /** Preference key for automatically closing brackets and parenthesis */
- private final static String CLOSE_BRACKETS_PHP = PreferenceConstants.EDITOR_CLOSE_BRACKETS_PHP;
- /** Preference key for automatically closing phpdocs and comments */
- private final static String CLOSE_JAVADOCS = PreferenceConstants.EDITOR_CLOSE_JAVADOCS;
- /** Preference key for automatically adding phpdoc tags */
- private final static String ADD_JAVADOC_TAGS = PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS;
- /** Preference key for automatically formatting phpdocs */
- private final static String FORMAT_JAVADOCS = PreferenceConstants.EDITOR_FORMAT_JAVADOCS;
- /** Preference key for automatically closing strings */
- private final static String CLOSE_STRINGS_HTML = PreferenceConstants.EDITOR_CLOSE_STRINGS_HTML;
- /** Preference key for automatically closing brackets and parenthesis */
- private final static String CLOSE_BRACKETS_HTML = PreferenceConstants.EDITOR_CLOSE_BRACKETS_HTML;
- /** Preference key for smart paste */
- private final static String SMART_PASTE = PreferenceConstants.EDITOR_SMART_PASTE;
- // private final static class AnnotationInfo {
- // public String fColorPreference;
- // public String fOverviewRulerPreference;
- // public String fEditorPreference;
- // };
- // private final static Map ANNOTATION_MAP;
- // static {
- //
- // AnnotationInfo info;
- // ANNOTATION_MAP = new HashMap();
- //
- // info = new AnnotationInfo();
- // info.fColorPreference = TASK_INDICATION_COLOR;
- // info.fOverviewRulerPreference = TASK_INDICATION_IN_OVERVIEW_RULER;
- // info.fEditorPreference = TASK_INDICATION;
- // ANNOTATION_MAP.put(AnnotationType.TASK, info);
- //
- // info = new AnnotationInfo();
- // info.fColorPreference = ERROR_INDICATION_COLOR;
- // info.fOverviewRulerPreference = ERROR_INDICATION_IN_OVERVIEW_RULER;
- // info.fEditorPreference = ERROR_INDICATION;
- // ANNOTATION_MAP.put(AnnotationType.ERROR, info);
- //
- // info = new AnnotationInfo();
- // info.fColorPreference = WARNING_INDICATION_COLOR;
- // info.fOverviewRulerPreference = WARNING_INDICATION_IN_OVERVIEW_RULER;
- // info.fEditorPreference = WARNING_INDICATION;
- // ANNOTATION_MAP.put(AnnotationType.WARNING, info);
- //
- // info = new AnnotationInfo();
- // info.fColorPreference = BOOKMARK_INDICATION_COLOR;
- // info.fOverviewRulerPreference = BOOKMARK_INDICATION_IN_OVERVIEW_RULER;
- // info.fEditorPreference = BOOKMARK_INDICATION;
- // ANNOTATION_MAP.put(AnnotationType.BOOKMARK, info);
- //
- // info = new AnnotationInfo();
- // info.fColorPreference = SEARCH_RESULT_INDICATION_COLOR;
- // info.fOverviewRulerPreference =
- // SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER;
- // info.fEditorPreference = SEARCH_RESULT_INDICATION;
- // ANNOTATION_MAP.put(AnnotationType.SEARCH, info);
- //
- // info = new AnnotationInfo();
- // info.fColorPreference = UNKNOWN_INDICATION_COLOR;
- // info.fOverviewRulerPreference = UNKNOWN_INDICATION_IN_OVERVIEW_RULER;
- // info.fEditorPreference = UNKNOWN_INDICATION;
- // ANNOTATION_MAP.put(AnnotationType.UNKNOWN, info);
- // };
- //
- // private final static AnnotationType[] ANNOTATION_LAYERS =
- // new AnnotationType[] {
- // AnnotationType.UNKNOWN,
- // AnnotationType.BOOKMARK,
- // AnnotationType.TASK,
- // AnnotationType.SEARCH,
- // AnnotationType.WARNING,
- // AnnotationType.ERROR };
- /**
- * Creates a new php unit editor.
- */
- public PHPUnitEditor() {
- super();
- setDocumentProvider(PHPeclipsePlugin.getDefault()
- .getCompilationUnitDocumentProvider());
- setEditorContextMenuId("#PHPEditorContext"); //$NON-NLS-1$
- setRulerContextMenuId("#PHPRulerContext"); //$NON-NLS-1$
- setOutlinerContextMenuId("#PHPOutlinerContext"); //$NON-NLS-1$
- // don't set help contextId, we install our own help context
- fSavePolicy = null;
- fJavaEditorErrorTickUpdater = new JavaEditorErrorTickUpdater(this);
- }
- /*
- * @see AbstractTextEditor#createActions()
- */
- protected void createActions() {
- super.createActions();
- Action action;
- // Action action= new
- // TextOperationAction(PHPEditorMessages.getResourceBundle(),
- // "CorrectionAssistProposal.", this, CORRECTIONASSIST_PROPOSALS);
- // //$NON-NLS-1$
- // action.setActionDefinitionId(PHPEditorActionDefinitionIds.CORRECTION_ASSIST_PROPOSALS);
- // setAction("CorrectionAssistProposal", action); //$NON-NLS-1$
- // markAsStateDependentAction("CorrectionAssistProposal", true);
- // //$NON-NLS-1$
- //// WorkbenchHelp.setHelp(action, IJavaHelpContextIds.QUICK_FIX_ACTION);
- action = new ContentAssistAction(PHPEditorMessages.getResourceBundle(),
- "ContentAssistProposal.", this); //$NON-NLS-1$
- action
- .setActionDefinitionId(PHPEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS);
- setAction("ContentAssistProposal", action); //$NON-NLS-1$
- markAsStateDependentAction("ContentAssistProposal", true); //$NON-NLS-1$
- // WorkbenchHelp.setHelp(action,
- // IJavaHelpContextIds.CONTENT_ASSIST_ACTION);
- action = new TextOperationAction(PHPEditorMessages.getResourceBundle(),
- "ContentAssistContextInformation.", this,
- ISourceViewer.CONTENTASSIST_CONTEXT_INFORMATION); //$NON-NLS-1$
- action
- .setActionDefinitionId(PHPEditorActionDefinitionIds.CONTENT_ASSIST_CONTEXT_INFORMATION);
- setAction("ContentAssistContextInformation", action); //$NON-NLS-1$
- markAsStateDependentAction("ContentAssistContextInformation", true); //$NON-NLS-1$
- // WorkbenchHelp.setHelp(action,
- // IJavaHelpContextIds.PARAMETER_HINTS_ACTION);
- // action= new TextOperationAction(PHPEditorMessages.getResourceBundle(),
- // "ContentAssistCompletePrefix.", this, CONTENTASSIST_COMPLETE_PREFIX);
- // //$NON-NLS-1$
- // action.setActionDefinitionId(PHPEditorActionDefinitionIds.CONTENT_ASSIST_COMPLETE_PREFIX);
- // setAction("ContentAssistCompletePrefix", action); //$NON-NLS-1$
- // markAsStateDependentAction("ContentAssistCompletePrefix", true);
- // //$NON-NLS-1$
- //// WorkbenchHelp.setHelp(action,
- // IJavaHelpContextIds.PARAMETER_HINTS_ACTION);
- action = new TextOperationAction(PHPEditorMessages.getResourceBundle(),
- "Comment.", this, ITextOperationTarget.PREFIX); //$NON-NLS-1$
- action.setActionDefinitionId(PHPEditorActionDefinitionIds.COMMENT);
- setAction("Comment", action); //$NON-NLS-1$
- markAsStateDependentAction("Comment", true); //$NON-NLS-1$
- // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.COMMENT_ACTION);
- action = new TextOperationAction(PHPEditorMessages.getResourceBundle(),
- "Uncomment.", this, ITextOperationTarget.STRIP_PREFIX); //$NON-NLS-1$
- action.setActionDefinitionId(PHPEditorActionDefinitionIds.UNCOMMENT);
- setAction("Uncomment", action); //$NON-NLS-1$
- markAsStateDependentAction("Uncomment", true); //$NON-NLS-1$
- // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.UNCOMMENT_ACTION);
- action = new ToggleCommentAction(PHPEditorMessages.getResourceBundle(),
- "ToggleComment.", this, getSourceViewerConfiguration()
- .getDefaultPrefixes(getSourceViewer(), "")); //$NON-NLS-1$ //$NON-NLS-2$
- action.setActionDefinitionId(PHPEditorActionDefinitionIds.TOGGLE_COMMENT);
- setAction("ToggleComment", action); //$NON-NLS-1$
- markAsStateDependentAction("ToggleComment", true); //$NON-NLS-1$
- // WorkbenchHelp.setHelp(action,
- // IJavaHelpContextIds.TOGGLE_COMMENT_ACTION);
- action = new TextOperationAction(PHPEditorMessages.getResourceBundle(),
- "Format.", this, ISourceViewer.FORMAT); //$NON-NLS-1$
- action.setActionDefinitionId(PHPEditorActionDefinitionIds.FORMAT);
- setAction("Format", action); //$NON-NLS-1$
- markAsStateDependentAction("Format", true); //$NON-NLS-1$
- markAsSelectionDependentAction("Format", true); //$NON-NLS-1$
- // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.FORMAT_ACTION);
- action = new AddBlockCommentAction(PHPEditorMessages.getResourceBundle(),
- "AddBlockComment.", this); //$NON-NLS-1$
- action
- .setActionDefinitionId(PHPEditorActionDefinitionIds.ADD_BLOCK_COMMENT);
- setAction("AddBlockComment", action); //$NON-NLS-1$
- markAsStateDependentAction("AddBlockComment", true); //$NON-NLS-1$
- markAsSelectionDependentAction("AddBlockComment", true); //$NON-NLS-1$
- // WorkbenchHelp.setHelp(action,
- // IJavaHelpContextIds.ADD_BLOCK_COMMENT_ACTION);
- action = new RemoveBlockCommentAction(
- PHPEditorMessages.getResourceBundle(), "RemoveBlockComment.", this); //$NON-NLS-1$
- action
- .setActionDefinitionId(PHPEditorActionDefinitionIds.REMOVE_BLOCK_COMMENT);
- setAction("RemoveBlockComment", action); //$NON-NLS-1$
- markAsStateDependentAction("RemoveBlockComment", true); //$NON-NLS-1$
- markAsSelectionDependentAction("RemoveBlockComment", true); //$NON-NLS-1$
- // WorkbenchHelp.setHelp(action,
- // IJavaHelpContextIds.ADD_BLOCK_COMMENT_ACTION);
- // action= new IndentAction(PHPEditorMessages.getResourceBundle(),
- // "Indent.", this, false); //$NON-NLS-1$
- // action.setActionDefinitionId(PHPEditorActionDefinitionIds.INDENT);
- // setAction("Indent", action); //$NON-NLS-1$
- // markAsStateDependentAction("Indent", true); //$NON-NLS-1$
- // markAsSelectionDependentAction("Indent", true); //$NON-NLS-1$
- //// WorkbenchHelp.setHelp(action, IJavaHelpContextIds.INDENT_ACTION);
- //
- // action= new IndentAction(PHPEditorMessages.getResourceBundle(),
- // "Indent.", this, true); //$NON-NLS-1$
- // setAction("IndentOnTab", action); //$NON-NLS-1$
- // markAsStateDependentAction("IndentOnTab", true); //$NON-NLS-1$
- // markAsSelectionDependentAction("IndentOnTab", true); //$NON-NLS-1$
- //
- if (getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SMART_TAB)) {
- // don't replace Shift Right - have to make sure their enablement is
- // mutually exclusive
- // removeActionActivationCode(ITextEditorActionConstants.SHIFT_RIGHT);
- setActionActivationCode("IndentOnTab", '\t', -1, SWT.NONE); //$NON-NLS-1$
- }
- fGenerateActionGroup = new GenerateActionGroup(this,
- ITextEditorActionConstants.GROUP_EDIT);
- fActionGroups = new CompositeActionGroup(
- new ActionGroup[]{fGenerateActionGroup});
- // We have to keep the context menu group separate to have better control
- // over positioning
- fContextMenuGroup = new CompositeActionGroup(new ActionGroup[] { fGenerateActionGroup });
- // rg,
- // new LocalHistoryActionGroup(this, ITextEditorActionConstants.GROUP_EDIT)});
-
- }
- /*
- * @see JavaEditor#getElementAt(int)
- */
- protected IJavaElement getElementAt(int offset) {
- return getElementAt(offset, true);
- }
- /**
- * Returns the most narrow element including the given offset. If <code>reconcile</code>
- * is <code>true</code> the editor's input element is reconciled in
- * advance. If it is <code>false</code> this method only returns a result
- * if the editor's input element does not need to be reconciled.
- *
- * @param offset
- * the offset included by the retrieved element
- * @param reconcile
- * <code>true</code> if working copy should be reconciled
- */
- protected IJavaElement getElementAt(int offset, boolean reconcile) {
- IWorkingCopyManager manager = PHPeclipsePlugin.getDefault()
- .getWorkingCopyManager();
- ICompilationUnit unit = manager.getWorkingCopy(getEditorInput());
- if (unit != null) {
- try {
- if (reconcile) {
- synchronized (unit) {
- unit.reconcile();
- }
- return unit.getElementAt(offset);
- } else if (unit.isConsistent())
- return unit.getElementAt(offset);
- } catch (JavaModelException x) {
- PHPeclipsePlugin.log(x.getStatus());
- // nothing found, be tolerant and go on
- }
- }
- return null;
- }
- /*
- * @see JavaEditor#getCorrespondingElement(IJavaElement)
- */
- protected IJavaElement getCorrespondingElement(IJavaElement element) {
- try {
- return EditorUtility.getWorkingCopy(element, true);
- } catch (JavaModelException x) {
- PHPeclipsePlugin.log(x.getStatus());
- // nothing found, be tolerant and go on
- }
- return null;
- }
- public void createPartControl(Composite parent) {
- super.createPartControl(parent);
- // fPaintManager = new PaintManager(getSourceViewer());
- LinePainter linePainter;
- linePainter = new LinePainter(getSourceViewer());
- linePainter
- .setHighlightColor(new Color(Display.getCurrent(), 225, 235, 224));
- // fPaintManager.addPainter(linePainter);
- if (isBracketHighlightingEnabled())
- startBracketHighlighting();
- if (isLineHighlightingEnabled())
- startLineHighlighting();
- if (isPrintMarginVisible())
- showPrintMargin();
- // Iterator e = ANNOTATION_MAP.keySet().iterator();
- // while (e.hasNext()) {
- // AnnotationType type = (AnnotationType) e.next();
- // if (isAnnotationIndicationEnabled(type))
- // startAnnotationIndication(type);
- // }
- if (isTabConversionEnabled())
- startTabConversion();
- // if (isOverviewRulerVisible())
- // showOverviewRuler();
- //
- // Preferences preferences =
- // PHPeclipsePlugin.getDefault().getPluginPreferences();
- // preferences.addPropertyChangeListener(fPropertyChangeListener);
- IPreferenceStore preferenceStore = getPreferenceStore();
- boolean closeBracketsPHP = preferenceStore.getBoolean(CLOSE_BRACKETS_PHP);
- boolean closeStringsPHP = preferenceStore.getBoolean(CLOSE_STRINGS_PHP);
- boolean closeBracketsHTML = preferenceStore.getBoolean(CLOSE_BRACKETS_HTML);
- boolean closeStringsHTML = preferenceStore.getBoolean(CLOSE_STRINGS_HTML);
- fBracketInserter.setCloseBracketsPHPEnabled(closeBracketsPHP);
- fBracketInserter.setCloseStringsPHPEnabled(closeStringsPHP);
- fBracketInserter.setCloseBracketsHTMLEnabled(closeBracketsHTML);
- fBracketInserter.setCloseStringsHTMLEnabled(closeStringsHTML);
- ISourceViewer sourceViewer = getSourceViewer();
- if (sourceViewer instanceof ITextViewerExtension)
- ((ITextViewerExtension) sourceViewer)
- .prependVerifyKeyListener(fBracketInserter);
- }
- private static char getPeerCharacter(char character) {
- switch (character) {
- case '(' :
- return ')';
- case ')' :
- return '(';
- case '[' :
- return ']';
- case ']' :
- return '[';
- case '"' :
- return character;
- default :
- throw new IllegalArgumentException();
- }
- }
- /**
- * The compilation unit editor implementation of this <code>AbstractTextEditor</code>
- * method asks the user for the workspace path of a file resource and saves
- * the document there. See http://dev.eclipse.org/bugs/show_bug.cgi?id=6295
- */
- protected void performSaveAs(IProgressMonitor progressMonitor) {
- Shell shell = getSite().getShell();
- IEditorInput input = getEditorInput();
- SaveAsDialog dialog = new SaveAsDialog(shell);
- IFile original = (input instanceof IFileEditorInput)
- ? ((IFileEditorInput) input).getFile()
- : null;
- if (original != null)
- dialog.setOriginalFile(original);
- dialog.create();
- IDocumentProvider provider = getDocumentProvider();
- if (provider == null) {
- // editor has been programmatically closed while the dialog was open
- return;
- }
- if (provider.isDeleted(input) && original != null) {
- String message = PHPEditorMessages.getFormattedString(
- "CompilationUnitEditor.warning.save.delete", new Object[]{original
- .getName()}); //$NON-NLS-1$
- dialog.setErrorMessage(null);
- dialog.setMessage(message, IMessageProvider.WARNING);
- }
- if (dialog.open() == Dialog.CANCEL) {
- if (progressMonitor != null)
- progressMonitor.setCanceled(true);
- return;
- }
- IPath filePath = dialog.getResult();
- if (filePath == null) {
- if (progressMonitor != null)
- progressMonitor.setCanceled(true);
- return;
- }
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
- IFile file = workspace.getRoot().getFile(filePath);
- final IEditorInput newInput = new FileEditorInput(file);
- WorkspaceModifyOperation op = new WorkspaceModifyOperation() {
- public void execute(final IProgressMonitor monitor) throws CoreException {
- getDocumentProvider().saveDocument(monitor, newInput,
- getDocumentProvider().getDocument(getEditorInput()), true);
- }
- };
- boolean success = false;
- try {
- provider.aboutToChange(newInput);
- new ProgressMonitorDialog(shell).run(false, true, op);
- success = true;
- } catch (InterruptedException x) {
- } catch (InvocationTargetException x) {
- Throwable t = x.getTargetException();
- if (t instanceof CoreException) {
- CoreException cx = (CoreException) t;
- ErrorDialog.openError(shell, PHPEditorMessages
- .getString("CompilationUnitEditor.error.saving.title2"),
- PHPEditorMessages
- .getString("CompilationUnitEditor.error.saving.message2"), cx
- .getStatus()); //$NON-NLS-1$ //$NON-NLS-2$
- } else {
- MessageDialog.openError(shell, PHPEditorMessages
- .getString("CompilationUnitEditor.error.saving.title3"),
- PHPEditorMessages
- .getString("CompilationUnitEditor.error.saving.message3")
- + t.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
- }
- } finally {
- provider.changed(newInput);
- if (success)
- setInput(newInput);
- }
- if (progressMonitor != null)
- progressMonitor.setCanceled(!success);
- }
- /*
- * @see AbstractTextEditor#doSetInput(IEditorInput)
- */
- protected void doSetInput(IEditorInput input) throws CoreException {
- super.doSetInput(input);
- configureTabConverter();
- }
- private void startBracketHighlighting() {
- if (fBracketPainter == null) {
- ISourceViewer sourceViewer = getSourceViewer();
- fBracketPainter = new BracketPainter(sourceViewer);
- fBracketPainter.setHighlightColor(getColor(MATCHING_BRACKETS_COLOR));
- // fPaintManager.addPainter(fBracketPainter);
- }
- }
- private void stopBracketHighlighting() {
- if (fBracketPainter != null) {
- // fPaintManager.removePainter(fBracketPainter);
- fBracketPainter.deactivate(true);
- fBracketPainter.dispose();
- fBracketPainter = null;
- }
- }
- private boolean isBracketHighlightingEnabled() {
- IPreferenceStore store = getPreferenceStore();
- return store.getBoolean(MATCHING_BRACKETS);
- }
- private void startLineHighlighting() {
- if (fLinePainter == null) {
- ISourceViewer sourceViewer = getSourceViewer();
- fLinePainter = new LinePainter(sourceViewer);
- fLinePainter.setHighlightColor(getColor(CURRENT_LINE_COLOR));
- // fPaintManager.addPainter(fLinePainter);
- }
- }
- private void stopLineHighlighting() {
- if (fLinePainter != null) {
- // fPaintManager.removePainter(fLinePainter);
- fLinePainter.deactivate(true);
- fLinePainter.dispose();
- fLinePainter = null;
- }
- }
- private boolean isLineHighlightingEnabled() {
- IPreferenceStore store = getPreferenceStore();
- return store.getBoolean(CURRENT_LINE);
- }
- private void showPrintMargin() {
- if (fPrintMarginPainter == null) {
- fPrintMarginPainter = new PrintMarginPainter(getSourceViewer());
- fPrintMarginPainter.setMarginRulerColor(getColor(PRINT_MARGIN_COLOR));
- fPrintMarginPainter.setMarginRulerColumn(getPreferenceStore().getInt(
- PRINT_MARGIN_COLUMN));
- // fPaintManager.addPainter(fPrintMarginPainter);
- }
- }
- private void hidePrintMargin() {
- if (fPrintMarginPainter != null) {
- // fPaintManager.removePainter(fPrintMarginPainter);
- fPrintMarginPainter.deactivate(true);
- fPrintMarginPainter.dispose();
- fPrintMarginPainter = null;
- }
- }
- private boolean isPrintMarginVisible() {
- IPreferenceStore store = getPreferenceStore();
- return store.getBoolean(PRINT_MARGIN);
- }
- // private void startAnnotationIndication(AnnotationType annotationType) {
- // if (fProblemPainter == null) {
- // fProblemPainter = new ProblemPainter(this, getSourceViewer());
- //// fPaintManager.addPainter(fProblemPainter);
- // }
- // fProblemPainter.setColor(annotationType, getColor(annotationType));
- // fProblemPainter.paintAnnotations(annotationType, true);
- // fProblemPainter.paint(IPainter.CONFIGURATION);
- // }
- //
- // private void shutdownAnnotationIndication() {
- // if (fProblemPainter != null) {
- //
- // if (!fProblemPainter.isPaintingAnnotations()) {
- //// fPaintManager.removePainter(fProblemPainter);
- // fProblemPainter.deactivate(true);
- // fProblemPainter.dispose();
- // fProblemPainter = null;
- // } else {
- // fProblemPainter.paint(IPainter.CONFIGURATION);
- // }
- // }
- // }
- //
- // private void stopAnnotationIndication(AnnotationType annotationType) {
- // if (fProblemPainter != null) {
- // fProblemPainter.paintAnnotations(annotationType, false);
- // shutdownAnnotationIndication();
- // }
- // }
- //
- // private boolean isAnnotationIndicationEnabled(AnnotationType
- // annotationType) {
- // IPreferenceStore store = getPreferenceStore();
- // AnnotationInfo info = (AnnotationInfo) ANNOTATION_MAP.get(annotationType);
- // if (info != null)
- // return store.getBoolean(info.fEditorPreference);
- // return false;
- // }
- //
- // private boolean
- // isAnnotationIndicationInOverviewRulerEnabled(AnnotationType
- // annotationType) {
- // IPreferenceStore store = getPreferenceStore();
- // AnnotationInfo info = (AnnotationInfo) ANNOTATION_MAP.get(annotationType);
- // if (info != null)
- // return store.getBoolean(info.fOverviewRulerPreference);
- // return false;
- // }
- //
- // private void showAnnotationIndicationInOverviewRuler(AnnotationType
- // annotationType, boolean show) {
- // AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
- // OverviewRuler ruler = asv.getOverviewRuler();
- // if (ruler != null) {
- // ruler.setColor(annotationType, getColor(annotationType));
- // ruler.showAnnotation(annotationType, show);
- // ruler.update();
- // }
- // }
- //
- // private void setColorInOverviewRuler(AnnotationType annotationType, Color
- // color) {
- // AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
- // OverviewRuler ruler = asv.getOverviewRuler();
- // if (ruler != null) {
- // ruler.setColor(annotationType, color);
- // ruler.update();
- // }
- // }
- private void configureTabConverter() {
- if (fTabConverter != null) {
- IDocumentProvider provider = getDocumentProvider();
- if (provider instanceof PHPDocumentProvider) {
- PHPDocumentProvider cup = (PHPDocumentProvider) provider;
- fTabConverter.setLineTracker(cup.createLineTracker(getEditorInput()));
- }
- }
- }
- private int getTabSize() {
- Preferences preferences = PHPeclipsePlugin.getDefault()
- .getPluginPreferences();
- return preferences.getInt(CODE_FORMATTER_TAB_SIZE);
- }
- private void startTabConversion() {
- if (fTabConverter == null) {
- fTabConverter = new TabConverter();
- configureTabConverter();
- fTabConverter.setNumberOfSpacesPerTab(getTabSize());
- AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
- asv.addTextConverter(fTabConverter);
- // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270
- asv.updateIndentationPrefixes();
- }
- }
- private void stopTabConversion() {
- if (fTabConverter != null) {
- AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
- asv.removeTextConverter(fTabConverter);
- // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270
- asv.updateIndentationPrefixes();
- fTabConverter = null;
- }
- }
- private boolean isTabConversionEnabled() {
- IPreferenceStore store = getPreferenceStore();
- return store.getBoolean(SPACES_FOR_TABS);
- }
- // private void showOverviewRuler() {
- // AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
- // asv.showOverviewRuler();
- //
- // OverviewRuler overviewRuler = asv.getOverviewRuler();
- // if (overviewRuler != null) {
- // for (int i = 0; i < ANNOTATION_LAYERS.length; i++) {
- // AnnotationType type = ANNOTATION_LAYERS[i];
- // overviewRuler.setLayer(type, i);
- // if (isAnnotationIndicationInOverviewRulerEnabled(type))
- // showAnnotationIndicationInOverviewRuler(type, true);
- // }
- // }
- // }
- //
- // private void hideOverviewRuler() {
- // AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
- // asv.hideOverviewRuler();
- // }
- //
- // private boolean isOverviewRulerVisible() {
- // IPreferenceStore store = getPreferenceStore();
- // return store.getBoolean(OVERVIEW_RULER);
- // }
- private Color getColor(String key) {
- RGB rgb = PreferenceConverter.getColor(getPreferenceStore(), key);
- return getColor(rgb);
- }
- private Color getColor(RGB rgb) {
- JavaTextTools textTools = PHPeclipsePlugin.getDefault().getJavaTextTools();
- return textTools.getColorManager().getColor(rgb);
- }
- // private Color getColor(AnnotationType annotationType) {
- // AnnotationInfo info = (AnnotationInfo) ANNOTATION_MAP.get(annotationType);
- // if (info != null)
- // return getColor(info.fColorPreference);
- // return null;
- // }
- public void dispose() {
- ISourceViewer sourceViewer = getSourceViewer();
- if (sourceViewer instanceof ITextViewerExtension)
- ((ITextViewerExtension) sourceViewer)
- .removeVerifyKeyListener(fBracketInserter);
- // if (fPropertyChangeListener != null) {
- // Preferences preferences =
- // PHPeclipsePlugin.getDefault().getPluginPreferences();
- // preferences.removePropertyChangeListener(fPropertyChangeListener);
- // fPropertyChangeListener = null;
- // }
- if (fJavaEditorErrorTickUpdater != null) {
- fJavaEditorErrorTickUpdater.dispose();
- fJavaEditorErrorTickUpdater = null;
- }
- // if (fSelectionHistory != null)
- // fSelectionHistory.dispose();
- // if (fPaintManager != null) {
- // fPaintManager.dispose();
- // fPaintManager = null;
- // }
- if (fActionGroups != null) {
- fActionGroups.dispose();
- fActionGroups = null;
- }
- super.dispose();
- }
- // protected AnnotationType getAnnotationType(String preferenceKey) {
- // Iterator e = ANNOTATION_MAP.keySet().iterator();
- // while (e.hasNext()) {
- // AnnotationType type = (AnnotationType) e.next();
- // AnnotationInfo info = (AnnotationInfo) ANNOTATION_MAP.get(type);
- // if (info != null) {
- // if (preferenceKey.equals(info.fColorPreference)
- // || preferenceKey.equals(info.fEditorPreference)
- // || preferenceKey.equals(info.fOverviewRulerPreference))
- // return type;
- // }
- // }
- // return null;
- // }
- /*
- * @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent)
- */
- protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
- try {
- AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
- if (asv != null) {
- String p = event.getProperty();
- if (CLOSE_BRACKETS_PHP.equals(p)) {
- fBracketInserter.setCloseBracketsPHPEnabled(getPreferenceStore()
- .getBoolean(p));
- return;
- }
- if (CLOSE_STRINGS_PHP.equals(p)) {
- fBracketInserter.setCloseStringsPHPEnabled(getPreferenceStore()
- .getBoolean(p));
- return;
- }
- if (CLOSE_BRACKETS_HTML.equals(p)) {
- fBracketInserter.setCloseBracketsHTMLEnabled(getPreferenceStore()
- .getBoolean(p));
- return;
- }
- if (CLOSE_STRINGS_HTML.equals(p)) {
- fBracketInserter.setCloseStringsHTMLEnabled(getPreferenceStore()
- .getBoolean(p));
- return;
- }
- if (SPACES_FOR_TABS.equals(p)) {
- if (isTabConversionEnabled())
- startTabConversion();
- else
- stopTabConversion();
- return;
- }
- if (MATCHING_BRACKETS.equals(p)) {
- if (isBracketHighlightingEnabled())
- startBracketHighlighting();
- else
- stopBracketHighlighting();
- return;
- }
- if (MATCHING_BRACKETS_COLOR.equals(p)) {
- if (fBracketPainter != null)
- fBracketPainter
- .setHighlightColor(getColor(MATCHING_BRACKETS_COLOR));
- return;
- }
- if (CURRENT_LINE.equals(p)) {
- if (isLineHighlightingEnabled())
- startLineHighlighting();
- else
- stopLineHighlighting();
- return;
- }
- if (CURRENT_LINE_COLOR.equals(p)) {
- if (fLinePainter != null) {
- stopLineHighlighting();
- startLineHighlighting();
- }
- return;
- }
- if (PRINT_MARGIN.equals(p)) {
- if (isPrintMarginVisible())
- showPrintMargin();
- else
- hidePrintMargin();
- return;
- }
- if (PRINT_MARGIN_COLOR.equals(p)) {
- if (fPrintMarginPainter != null)
- fPrintMarginPainter
- .setMarginRulerColor(getColor(PRINT_MARGIN_COLOR));
- return;
- }
- if (PRINT_MARGIN_COLUMN.equals(p)) {
- if (fPrintMarginPainter != null)
- fPrintMarginPainter.setMarginRulerColumn(getPreferenceStore()
- .getInt(PRINT_MARGIN_COLUMN));
- return;
- }
- // if (OVERVIEW_RULER.equals(p)) {
- // if (isOverviewRulerVisible())
- // showOverviewRuler();
- // else
- // hideOverviewRuler();
- // return;
- // }
- // AnnotationType type = getAnnotationType(p);
- // if (type != null) {
- //
- // AnnotationInfo info = (AnnotationInfo) ANNOTATION_MAP.get(type);
- // if (info.fColorPreference.equals(p)) {
- // Color color = getColor(type);
- // if (fProblemPainter != null) {
- // fProblemPainter.setColor(type, color);
- // fProblemPainter.paint(IPainter.CONFIGURATION);
- // }
- // setColorInOverviewRuler(type, color);
- // return;
- // }
- //
- // if (info.fEditorPreference.equals(p)) {
- // if (isAnnotationIndicationEnabled(type))
- // startAnnotationIndication(type);
- // else
- // stopAnnotationIndication(type);
- // return;
- // }
- //
- // if (info.fOverviewRulerPreference.equals(p)) {
- // if (isAnnotationIndicationInOverviewRulerEnabled(type))
- // showAnnotationIndicationInOverviewRuler(type, true);
- // else
- // showAnnotationIndicationInOverviewRuler(type, false);
- // return;
- // }
- // }
- IContentAssistant c = asv.getContentAssistant();
- if (c instanceof ContentAssistant)
- ContentAssistPreference.changeConfiguration((ContentAssistant) c,
- getPreferenceStore(), event);
- }
- } finally {
- super.handlePreferenceStoreChanged(event);
- }
- }
- /*
- * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor#handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent)
- */
- protected void handlePreferencePropertyChanged(
- org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) {
- AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
- if (asv != null) {
- String p = event.getProperty();
- if (CODE_FORMATTER_TAB_SIZE.equals(p)) {
- asv.updateIndentationPrefixes();
- if (fTabConverter != null)
- fTabConverter.setNumberOfSpacesPerTab(getTabSize());
- }
- }
- super.handlePreferencePropertyChanged(event);
- }
- /**
- * Handles a property change event describing a change of the php core's
- * preferences and updates the preference related editor properties.
- *
- * @param event
- * the property change event
- */
- // protected void
- // handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent
- // event) {
- // AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
- // if (asv != null) {
- // String p = event.getProperty();
- // if (CODE_FORMATTER_TAB_SIZE.equals(p)) {
- // asv.updateIndentationPrefixes();
- // if (fTabConverter != null)
- // fTabConverter.setNumberOfSpacesPerTab(getTabSize());
- // }
- // }
- // }
- /*
- * @see PHPEditor#createJavaSourceViewer(Composite, IVerticalRuler, int)
- */
- protected ISourceViewer createJavaSourceViewer(Composite parent,
- IVerticalRuler verticalRuler, IOverviewRuler overviewRuler,
- boolean isOverviewRulerVisible, int styles) {
- return new AdaptedSourceViewer(parent, verticalRuler, overviewRuler,
- isOverviewRulerVisible, styles);
- }
- // protected ISourceViewer createJavaSourceViewer(Composite parent,
- // IVerticalRuler ruler, int styles) {
- // return new AdaptedSourceViewer(parent, ruler, styles);
- // }
- private boolean isValidSelection(int offset, int length) {
- IDocumentProvider provider = getDocumentProvider();
- if (provider != null) {
- IDocument document = provider.getDocument(getEditorInput());
- if (document != null) {
- int end = offset + length;
- int documentLength = document.getLength();
- return 0 <= offset && offset <= documentLength && 0 <= end
- && end <= documentLength;
- }
- }
- return false;
- }
- /*
- * @see AbstractTextEditor#canHandleMove(IEditorInput, IEditorInput)
- */
- protected boolean canHandleMove(IEditorInput originalElement,
- IEditorInput movedElement) {
- String oldExtension = ""; //$NON-NLS-1$
- if (originalElement instanceof IFileEditorInput) {
- IFile file = ((IFileEditorInput) originalElement).getFile();
- if (file != null) {
- String ext = file.getFileExtension();
- if (ext != null)
- oldExtension = ext;
- }
- }
- String newExtension = ""; //$NON-NLS-1$
- if (movedElement instanceof IFileEditorInput) {
- IFile file = ((IFileEditorInput) movedElement).getFile();
- if (file != null)
- newExtension = file.getFileExtension();
- }
- return oldExtension.equals(newExtension);
- }
- /*
- * @see AbstractTextEditor#editorContextMenuAboutToShow(IMenuManager)
- */
- public void editorContextMenuAboutToShow(IMenuManager menu) {
- super.editorContextMenuAboutToShow(menu);
- ActionContext context = new ActionContext(getSelectionProvider()
- .getSelection());
- fContextMenuGroup.setContext(context);
- fContextMenuGroup.fillContextMenu(menu);
- fContextMenuGroup.setContext(null);
- }
- /*
- * @see JavaEditor#setOutlinePageInput(JavaOutlinePage, IEditorInput)
- */
- protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input) {
- if (page != null) {
- IWorkingCopyManager manager = PHPeclipsePlugin.getDefault()
- .getWorkingCopyManager();
- page.setInput(manager.getWorkingCopy(input));
- }
- }
- /*
- * @see AbstractTextEditor#performSaveOperation(WorkspaceModifyOperation,
- * IProgressMonitor)
- */
- // protected void performSaveOperation(WorkspaceModifyOperation operation,
- // IProgressMonitor progressMonitor) {
- // IDocumentProvider p = getDocumentProvider();
- // if (p instanceof PHPDocumentProvider) {
- // PHPDocumentProvider cp = (PHPDocumentProvider) p;
- // cp.setSavePolicy(fSavePolicy);
- // }
- //
- // try {
- // super.performSaveOperation(operation, progressMonitor);
- // } finally {
- // if (p instanceof PHPDocumentProvider) {
- // PHPDocumentProvider cp = (PHPDocumentProvider) p;
- // cp.setSavePolicy(null);
- // }
- // }
- // }
- /*
- * @see org.eclipse.ui.texteditor.AbstractTextEditor#performSave(boolean,
- * org.eclipse.core.runtime.IProgressMonitor)
- */
- protected void performSave(boolean overwrite, IProgressMonitor progressMonitor) {
- IDocumentProvider p = getDocumentProvider();
- if (p instanceof PHPDocumentProvider) {
- PHPDocumentProvider cp = (PHPDocumentProvider) p;
- cp.setSavePolicy(fSavePolicy);
- }
- try {
- super.performSave(overwrite, progressMonitor);
- } finally {
- if (p instanceof PHPDocumentProvider) {
- PHPDocumentProvider cp = (PHPDocumentProvider) p;
- cp.setSavePolicy(null);
- }
- }
- }
- /*
- * @see AbstractTextEditor#doSaveAs
- */
- public void doSaveAs() {
- if (askIfNonWorkbenchEncodingIsOk()) {
- super.doSaveAs();
- }
- }
- /*
- * @see AbstractTextEditor#doSave(IProgressMonitor)
- */
- public void doSave(IProgressMonitor progressMonitor) {
- IDocumentProvider p = getDocumentProvider();
- if (p == null) {
- // editor has been closed
- return;
- }
- if (!askIfNonWorkbenchEncodingIsOk()) {
- progressMonitor.setCanceled(true);
- return;
- }
- if (p.isDeleted(getEditorInput())) {
- if (isSaveAsAllowed()) {
- /*
- * 1GEUSSR: ITPUI:ALL - User should never loose changes made in the
- * editors. Changed Behavior to make sure that if called inside a
- * regular save (because of deletion of input element) there is a way
- * to report back to the caller.
- */
- // performSaveAs(progressMonitor);
- super.doSave(progressMonitor);
- } else {
- /*
- * 1GF5YOX: ITPJUI:ALL - Save of delete file claims it's still there
- * Missing resources.
- */
- Shell shell = getSite().getShell();
- MessageDialog.openError(shell, PHPEditorMessages
- .getString("PHPUnitEditor.error.saving.title1"), PHPEditorMessages
- .getString("PHPUnitEditor.error.saving.message1")); //$NON-NLS-1$ //$NON-NLS-2$
- }
- } else {
- setStatusLineErrorMessage(null);
- super.doSave(progressMonitor);
- // IWorkingCopyManager manager=
- // JavaPlugin.getDefault().getWorkingCopyManager();
- // ICompilationUnit unit= manager.getWorkingCopy(getEditorInput());
- //
- // if (unit != null) {
- // synchronized (unit) {
- // performSaveOperation(createSaveOperation(false), progressMonitor);
- // }
- // } else
- // performSaveOperation(createSaveOperation(false), progressMonitor);
- }
- }
- /**
- * Asks the user if it is ok to store in non-workbench encoding.
- *
- * @return <true>if the user wants to continue
- */
- private boolean askIfNonWorkbenchEncodingIsOk() {
- IDocumentProvider provider = getDocumentProvider();
- if (provider instanceof IStorageDocumentProvider) {
- IEditorInput input = getEditorInput();
- IStorageDocumentProvider storageProvider = (IStorageDocumentProvider) provider;
- String encoding = storageProvider.getEncoding(input);
- String defaultEncoding = storageProvider.getDefaultEncoding();
- if (encoding != null && !encoding.equals(defaultEncoding)) {
- Shell shell = getSite().getShell();
- String title = PHPEditorMessages
- .getString("PHPUnitEditor.warning.save.nonWorkbenchEncoding.title"); //$NON-NLS-1$
- String msg;
- if (input != null)
- msg = MessageFormat
- .format(
- PHPEditorMessages
- .getString("PHPUnitEditor.warning.save.nonWorkbenchEncoding.message1"),
- new String[]{input.getName(), encoding}); //$NON-NLS-1$
- else
- msg = MessageFormat
- .format(
- PHPEditorMessages
- .getString("PHPUnitEditor.warning.save.nonWorkbenchEncoding.message2"),
- new String[]{encoding}); //$NON-NLS-1$
- return MessageDialog.openQuestion(shell, title, msg);
- }
- }
- return true;
- }
- /*
- * @see IReconcilingParticipant#reconciled()
- */
- public void reconciled() {
- if (synchronizeOutlineOnCursorMove()) {
- Shell shell = getSite().getShell();
- if (shell != null && !shell.isDisposed()) {
- shell.getDisplay().asyncExec(new Runnable() {
- public void run() {
- synchronizeOutlinePageSelection();
- }
- });
- }
- }
- }
-
- protected void updateStateDependentActions() {
- super.updateStateDependentActions();
- fGenerateActionGroup.editorStateChanged();
- }
-
- private boolean synchronizeOutlineOnCursorMove() {
- return PreferenceConstants.getPreferenceStore().getBoolean(
- PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE);
- }
+public class PHPUnitEditor extends PHPEditor{ //implements IJavaReconcilingListener {
+ interface ITextConverter {
+ void customizeDocumentCommand(IDocument document,
+ DocumentCommand command);
+ };
+ // class AdaptedRulerLayout extends Layout {
+ //
+ // protected int fGap;
+ // protected AdaptedSourceViewer fAdaptedSourceViewer;
+ //
+ // protected AdaptedRulerLayout(int gap, AdaptedSourceViewer asv) {
+ // fGap = gap;
+ // fAdaptedSourceViewer = asv;
+ // }
+ //
+ // protected Point computeSize(Composite composite, int wHint, int hHint,
+ // boolean flushCache) {
+ // Control[] children = composite.getChildren();
+ // Point s = children[children.length - 1].computeSize(SWT.DEFAULT,
+ // SWT.DEFAULT, flushCache);
+ // if (fAdaptedSourceViewer.isVerticalRulerVisible())
+ // s.x += fAdaptedSourceViewer.getVerticalRuler().getWidth() + fGap;
+ // return s;
+ // }
+ //
+ // protected void layout(Composite composite, boolean flushCache) {
+ // Rectangle clArea = composite.getClientArea();
+ // if (fAdaptedSourceViewer.isVerticalRulerVisible()) {
+ //
+ // StyledText textWidget = fAdaptedSourceViewer.getTextWidget();
+ // Rectangle trim = textWidget.computeTrim(0, 0, 0, 0);
+ // int scrollbarHeight = trim.height;
+ //
+ // IVerticalRuler vr = fAdaptedSourceViewer.getVerticalRuler();
+ // int vrWidth = vr.getWidth();
+ //
+ // int orWidth = 0;
+ // if (fAdaptedSourceViewer.isOverviewRulerVisible()) {
+ // OverviewRuler or = fAdaptedSourceViewer.getOverviewRuler();
+ // orWidth = or.getWidth();
+ // or.getControl().setBounds(clArea.width - orWidth, scrollbarHeight,
+ // orWidth, clArea.height - 3 * scrollbarHeight);
+ // }
+ //
+ // textWidget.setBounds(vrWidth + fGap, 0, clArea.width - vrWidth - orWidth
+ // -
+ // 2 * fGap, clArea.height);
+ // vr.getControl().setBounds(0, 0, vrWidth, clArea.height -
+ // scrollbarHeight);
+ //
+ // } else {
+ // StyledText textWidget = fAdaptedSourceViewer.getTextWidget();
+ // textWidget.setBounds(0, 0, clArea.width, clArea.height);
+ // }
+ // }
+ // };
+ //
+ // class AdaptedSourceViewer extends SourceViewer { // extends
+ // JavaCorrectionSourceViewer {
+ //
+ // private List fTextConverters;
+ //
+ // private OverviewRuler fOverviewRuler;
+ // private boolean fIsOverviewRulerVisible;
+ // /** The viewer's overview ruler hovering controller */
+ // private AbstractHoverInformationControlManager
+ // fOverviewRulerHoveringController;
+ //
+ // private boolean fIgnoreTextConverters = false;
+ //
+ // private IVerticalRuler fCachedVerticalRuler;
+ // private boolean fCachedIsVerticalRulerVisible;
+ //
+ // public AdaptedSourceViewer(Composite parent, IVerticalRuler ruler, int
+ // styles) {
+ // super(parent, ruler, styles); //, CompilationUnitEditor.this);
+ //
+ // fCachedVerticalRuler = ruler;
+ // fCachedIsVerticalRulerVisible = (ruler != null);
+ // fOverviewRuler = new OverviewRuler(VERTICAL_RULER_WIDTH);
+ //
+ // delayedCreateControl(parent, styles);
+ // }
+ //
+ // /*
+ // * @see ISourceViewer#showAnnotations(boolean)
+ // */
+ // public void showAnnotations(boolean show) {
+ // fCachedIsVerticalRulerVisible = (show && fCachedVerticalRuler != null);
+ // // super.showAnnotations(show);
+ // }
+ //
+ // public IContentAssistant getContentAssistant() {
+ // return fContentAssistant;
+ // }
+ //
+ // /*
+ // * @see ITextOperationTarget#doOperation(int)
+ // */
+ // public void doOperation(int operation) {
+ //
+ // if (getTextWidget() == null)
+ // return;
+ //
+ // switch (operation) {
+ // case CONTENTASSIST_PROPOSALS :
+ // String msg = fContentAssistant.showPossibleCompletions();
+ // setStatusLineErrorMessage(msg);
+ // return;
+ // case UNDO :
+ // fIgnoreTextConverters = true;
+ // break;
+ // case REDO :
+ // fIgnoreTextConverters = true;
+ // break;
+ // }
+ //
+ // super.doOperation(operation);
+ // }
+ //
+ // public void insertTextConverter(ITextConverter textConverter, int index)
+ // {
+ // throw new UnsupportedOperationException();
+ // }
+ //
+ // public void addTextConverter(ITextConverter textConverter) {
+ // if (fTextConverters == null) {
+ // fTextConverters = new ArrayList(1);
+ // fTextConverters.add(textConverter);
+ // } else if (!fTextConverters.contains(textConverter))
+ // fTextConverters.add(textConverter);
+ // }
+ //
+ // public void removeTextConverter(ITextConverter textConverter) {
+ // if (fTextConverters != null) {
+ // fTextConverters.remove(textConverter);
+ // if (fTextConverters.size() == 0)
+ // fTextConverters = null;
+ // }
+ // }
+ //
+ // /*
+ // * @see TextViewer#customizeDocumentCommand(DocumentCommand)
+ // */
+ // protected void customizeDocumentCommand(DocumentCommand command) {
+ // super.customizeDocumentCommand(command);
+ // if (!fIgnoreTextConverters && fTextConverters != null) {
+ // for (Iterator e = fTextConverters.iterator(); e.hasNext();)
+ // ((ITextConverter) e.next()).customizeDocumentCommand(getDocument(),
+ // command);
+ // }
+ // fIgnoreTextConverters = false;
+ // }
+ //
+ // public IVerticalRuler getVerticalRuler() {
+ // return fCachedVerticalRuler;
+ // }
+ //
+ // public boolean isVerticalRulerVisible() {
+ // return fCachedIsVerticalRulerVisible;
+ // }
+ //
+ // public OverviewRuler getOverviewRuler() {
+ // return fOverviewRuler;
+ // }
+ //
+ // /*
+ // * @see TextViewer#createControl(Composite, int)
+ // */
+ // protected void createControl(Composite parent, int styles) {
+ // // do nothing here
+ // }
+ //
+ // protected void delayedCreateControl(Composite parent, int styles) {
+ // //create the viewer
+ // super.createControl(parent, styles);
+ //
+ // Control control = getControl();
+ // if (control instanceof Composite) {
+ // Composite composite = (Composite) control;
+ // composite.setLayout(new AdaptedRulerLayout(GAP_SIZE, this));
+ // fOverviewRuler.createControl(composite, this);
+ // }
+ // }
+ // protected void ensureOverviewHoverManagerInstalled() {
+ // if (fOverviewRulerHoveringController == null && fAnnotationHover != null
+ // && fHoverControlCreator != null) {
+ // fOverviewRulerHoveringController =
+ // new OverviewRulerHoverManager(fOverviewRuler, this, fAnnotationHover,
+ // fHoverControlCreator);
+ // fOverviewRulerHoveringController.install(fOverviewRuler.getControl());
+ // }
+ // }
+ //
+ // public void hideOverviewRuler() {
+ // fIsOverviewRulerVisible = false;
+ // Control control = getControl();
+ // if (control instanceof Composite) {
+ // Composite composite = (Composite) control;
+ // composite.layout();
+ // }
+ // if (fOverviewRulerHoveringController != null) {
+ // fOverviewRulerHoveringController.dispose();
+ // fOverviewRulerHoveringController = null;
+ // }
+ // }
+ //
+ // public void showOverviewRuler() {
+ // fIsOverviewRulerVisible = true;
+ // Control control = getControl();
+ // if (control instanceof Composite) {
+ // Composite composite = (Composite) control;
+ // composite.layout();
+ // }
+ // ensureOverviewHoverManagerInstalled();
+ // }
+ //
+ // public boolean isOverviewRulerVisible() {
+ // return fIsOverviewRulerVisible;
+ // }
+ //
+ // /*
+ // * @see ISourceViewer#setDocument(IDocument, IAnnotationModel, int, int)
+ // */
+ // public void setDocument(
+ // IDocument document,
+ // IAnnotationModel annotationModel,
+ // int visibleRegionOffset,
+ // int visibleRegionLength) {
+ // super.setDocument(document, annotationModel, visibleRegionOffset,
+ // visibleRegionLength);
+ // fOverviewRuler.setModel(annotationModel);
+ // }
+ //
+ // // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270
+ // public void updateIndentationPrefixes() {
+ // SourceViewerConfiguration configuration = getSourceViewerConfiguration();
+ // String[] types = configuration.getConfiguredContentTypes(this);
+ // for (int i = 0; i < types.length; i++) {
+ // String[] prefixes = configuration.getIndentPrefixes(this, types[i]);
+ // if (prefixes != null && prefixes.length > 0)
+ // setIndentPrefixes(prefixes, types[i]);
+ // }
+ // }
+ //
+ // /*
+ // * @see IWidgetTokenOwner#requestWidgetToken(IWidgetTokenKeeper)
+ // */
+ // public boolean requestWidgetToken(IWidgetTokenKeeper requester) {
+ // if (WorkbenchHelp.isContextHelpDisplayed())
+ // return false;
+ // return super.requestWidgetToken(requester);
+ // }
+ //
+ // /*
+ // * @see
+ // org.eclipse.jface.text.source.ISourceViewer#configure(org.eclipse.jface.text.source.SourceViewerConfiguration)
+ // */
+ // public void configure(SourceViewerConfiguration configuration) {
+ // super.configure(configuration);
+ // // prependAutoEditStrategy(new SmartBracesAutoEditStrategy(this),
+ // IDocument.DEFAULT_CONTENT_TYPE);
+ // }
+ //
+ // protected void handleDispose() {
+ // fOverviewRuler = null;
+ //
+ // if (fOverviewRulerHoveringController != null) {
+ // fOverviewRulerHoveringController.dispose();
+ // fOverviewRulerHoveringController = null;
+ // }
+ //
+ // super.handleDispose();
+ // }
+ //
+ // };
+ class AdaptedSourceViewer extends JavaSourceViewer {
+ private List fTextConverters;
+ private boolean fIgnoreTextConverters = false;
+ // private JavaCorrectionAssistant fCorrectionAssistant;
+ public AdaptedSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, boolean showAnnotationsOverview, int styles, IPreferenceStore store) {
+ super(parent, verticalRuler, overviewRuler, showAnnotationsOverview, styles, store);
+ }
+// public AdaptedSourceViewer(Composite parent,
+// IVerticalRuler verticalRuler, IOverviewRuler overviewRuler,
+// boolean showAnnotationsOverview, int styles) {
+// super(parent, verticalRuler, overviewRuler,
+// showAnnotationsOverview, styles);
+// }
+ public IContentAssistant getContentAssistant() {
+ return fContentAssistant;
+ }
+ /*
+ * @see ITextOperationTarget#doOperation(int)
+ */
+ public void doOperation(int operation) {
+ if (getTextWidget() == null)
+ return;
+ switch (operation) {
+ case CONTENTASSIST_PROPOSALS :
+ String msg = fContentAssistant.showPossibleCompletions();
+ setStatusLineErrorMessage(msg);
+ return;
+ // case CORRECTIONASSIST_PROPOSALS:
+ // fCorrectionAssistant.showPossibleCompletions();
+ // return;
+ case UNDO :
+ fIgnoreTextConverters = true;
+ break;
+ case REDO :
+ fIgnoreTextConverters = true;
+ break;
+ }
+ super.doOperation(operation);
+ }
+ /*
+ * @see ITextOperationTarget#canDoOperation(int)
+ */
+ public boolean canDoOperation(int operation) {
+ // if (operation == CORRECTIONASSIST_PROPOSALS)
+ // return isEditable();
+ return super.canDoOperation(operation);
+ }
+ /*
+ * @see TextViewer#handleDispose()
+ */
+ protected void handleDispose() {
+ // if (fCorrectionAssistant != null) {
+ // fCorrectionAssistant.uninstall();
+ // fCorrectionAssistant= null;
+ // }
+ super.handleDispose();
+ }
+ public void insertTextConverter(ITextConverter textConverter, int index) {
+ throw new UnsupportedOperationException();
+ }
+ public void addTextConverter(ITextConverter textConverter) {
+ if (fTextConverters == null) {
+ fTextConverters = new ArrayList(1);
+ fTextConverters.add(textConverter);
+ } else if (!fTextConverters.contains(textConverter))
+ fTextConverters.add(textConverter);
+ }
+ public void removeTextConverter(ITextConverter textConverter) {
+ if (fTextConverters != null) {
+ fTextConverters.remove(textConverter);
+ if (fTextConverters.size() == 0)
+ fTextConverters = null;
+ }
+ }
+ /*
+ * @see TextViewer#customizeDocumentCommand(DocumentCommand)
+ */
+ protected void customizeDocumentCommand(DocumentCommand command) {
+ super.customizeDocumentCommand(command);
+ if (!fIgnoreTextConverters && fTextConverters != null) {
+ for (Iterator e = fTextConverters.iterator(); e.hasNext();)
+ ((ITextConverter) e.next()).customizeDocumentCommand(
+ getDocument(), command);
+ }
+ fIgnoreTextConverters = false;
+ }
+ // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270
+ public void updateIndentationPrefixes() {
+ SourceViewerConfiguration configuration = getSourceViewerConfiguration();
+ String[] types = configuration.getConfiguredContentTypes(this);
+ for (int i = 0; i < types.length; i++) {
+ String[] prefixes = configuration.getIndentPrefixes(this,
+ types[i]);
+ if (prefixes != null && prefixes.length > 0)
+ setIndentPrefixes(prefixes, types[i]);
+ }
+ }
+ /*
+ * @see IWidgetTokenOwner#requestWidgetToken(IWidgetTokenKeeper)
+ */
+ public boolean requestWidgetToken(IWidgetTokenKeeper requester) {
+ if (WorkbenchHelp.isContextHelpDisplayed())
+ return false;
+ return super.requestWidgetToken(requester);
+ }
+ /*
+ * @see org.eclipse.jface.text.source.ISourceViewer#configure(org.eclipse.jface.text.source.SourceViewerConfiguration)
+ */
+ public void configure(SourceViewerConfiguration configuration) {
+ super.configure(configuration);
+ // fCorrectionAssistant= new
+ // JavaCorrectionAssistant(CompilationUnitEditor.this);
+ // fCorrectionAssistant.install(this);
+ //TODO install SmartBracesAutoEditStrategy
+ // prependAutoEditStrategy(new SmartBracesAutoEditStrategy(this),
+ // IDocument.DEFAULT_CONTENT_TYPE);
+ }
+ };
+ static class TabConverter implements ITextConverter {
+ private int fTabRatio;
+ private ILineTracker fLineTracker;
+ public TabConverter() {
+ }
+ public void setNumberOfSpacesPerTab(int ratio) {
+ fTabRatio = ratio;
+ }
+ public void setLineTracker(ILineTracker lineTracker) {
+ fLineTracker = lineTracker;
+ }
+ private int insertTabString(StringBuffer buffer, int offsetInLine) {
+ if (fTabRatio == 0)
+ return 0;
+ int remainder = offsetInLine % fTabRatio;
+ remainder = fTabRatio - remainder;
+ for (int i = 0; i < remainder; i++)
+ buffer.append(' ');
+ return remainder;
+ }
+ public void customizeDocumentCommand(IDocument document,
+ DocumentCommand command) {
+ String text = command.text;
+ if (text == null)
+ return;
+ int index = text.indexOf('\t');
+ if (index > -1) {
+ StringBuffer buffer = new StringBuffer();
+ fLineTracker.set(command.text);
+ int lines = fLineTracker.getNumberOfLines();
+ try {
+ for (int i = 0; i < lines; i++) {
+ int offset = fLineTracker.getLineOffset(i);
+ int endOffset = offset + fLineTracker.getLineLength(i);
+ String line = text.substring(offset, endOffset);
+ int position = 0;
+ if (i == 0) {
+ IRegion firstLine = document
+ .getLineInformationOfOffset(command.offset);
+ position = command.offset - firstLine.getOffset();
+ }
+ int length = line.length();
+ for (int j = 0; j < length; j++) {
+ char c = line.charAt(j);
+ if (c == '\t') {
+ position += insertTabString(buffer, position);
+ } else {
+ buffer.append(c);
+ ++position;
+ }
+ }
+ }
+ command.text = buffer.toString();
+ } catch (BadLocationException x) {
+ }
+ }
+ }
+ };
+ private static class ExitPolicy implements LinkedPositionUI.ExitPolicy {
+ final char fExitCharacter;
+ public ExitPolicy(char exitCharacter) {
+ fExitCharacter = exitCharacter;
+ }
+ /*
+ * @see org.phpeclipse.phpdt.internal.ui.text.link.LinkedPositionUI.ExitPolicy#doExit(org.phpeclipse.phpdt.internal.ui.text.link.LinkedPositionManager,
+ * org.eclipse.swt.events.VerifyEvent, int, int)
+ */
+ public ExitFlags doExit(LinkedPositionManager manager,
+ VerifyEvent event, int offset, int length) {
+ if (event.character == fExitCharacter) {
+ if (manager.anyPositionIncludes(offset, length))
+ return new ExitFlags(LinkedPositionUI.COMMIT
+ | LinkedPositionUI.UPDATE_CARET, false);
+ else
+ return new ExitFlags(LinkedPositionUI.COMMIT, true);
+ }
+ switch (event.character) {
+ case '\b' :
+ if (manager.getFirstPosition().length == 0)
+ return new ExitFlags(0, false);
+ else
+ return null;
+ case '\n' :
+ case '\r' :
+ return new ExitFlags(LinkedPositionUI.COMMIT, true);
+ default :
+ return null;
+ }
+ }
+ }
+ private static class BracketLevel {
+ int fOffset;
+ int fLength;
+ LinkedPositionManager fManager;
+ LinkedPositionUI fEditor;
+ };
+ private class BracketInserter
+ implements
+ VerifyKeyListener,
+ LinkedPositionUI.ExitListener {
+ private boolean fCloseBracketsPHP = true;
+ private boolean fCloseStringsPHP = true;
+ private boolean fCloseBracketsHTML = true;
+ private boolean fCloseStringsHTML = true;
+ private int fOffset;
+ private int fLength;
+ public void setCloseBracketsPHPEnabled(boolean enabled) {
+ fCloseBracketsPHP = enabled;
+ }
+ public void setCloseStringsPHPEnabled(boolean enabled) {
+ fCloseStringsPHP = enabled;
+ }
+ public void setCloseBracketsHTMLEnabled(boolean enabled) {
+ fCloseBracketsHTML = enabled;
+ }
+ public void setCloseStringsHTMLEnabled(boolean enabled) {
+ fCloseStringsHTML = enabled;
+ }
+ private boolean hasIdentifierToTheRight(IDocument document, int offset) {
+ try {
+ int end = offset;
+ IRegion endLine = document.getLineInformationOfOffset(end);
+ int maxEnd = endLine.getOffset() + endLine.getLength();
+ while (end != maxEnd
+ && Character.isWhitespace(document.getChar(end)))
+ ++end;
+ return end != maxEnd
+ && Scanner.isPHPIdentifierPart(document.getChar(end));
+ } catch (BadLocationException e) {
+ // be conservative
+ return true;
+ }
+ }
+ private boolean hasIdentifierToTheLeft(IDocument document, int offset) {
+ try {
+ int start = offset;
+ IRegion startLine = document.getLineInformationOfOffset(start);
+ int minStart = startLine.getOffset();
+ while (start != minStart
+ && Character.isWhitespace(document.getChar(start - 1)))
+ --start;
+ return start != minStart
+ && Scanner.isPHPIdentifierPart(document
+ .getChar(start - 1));
+ } catch (BadLocationException e) {
+ return true;
+ }
+ }
+ private boolean hasCharacterToTheRight(IDocument document, int offset,
+ char character) {
+ try {
+ int end = offset;
+ IRegion endLine = document.getLineInformationOfOffset(end);
+ int maxEnd = endLine.getOffset() + endLine.getLength();
+ while (end != maxEnd
+ && Character.isWhitespace(document.getChar(end)))
+ ++end;
+ return end != maxEnd && document.getChar(end) == character;
+ } catch (BadLocationException e) {
+ // be conservative
+ return true;
+ }
+ }
+ /*
+ * @see org.eclipse.swt.custom.VerifyKeyListener#verifyKey(org.eclipse.swt.events.VerifyEvent)
+ */
+ public void verifyKey(VerifyEvent event) {
+ if (!event.doit)
+ return;
+ final ISourceViewer sourceViewer = getSourceViewer();
+ IDocument document = sourceViewer.getDocument();
+ final Point selection = sourceViewer.getSelectedRange();
+ final int offset = selection.x;
+ final int length = selection.y;
+ try {
+ ITypedRegion partition = document.getPartition(offset);
+ String type = partition.getType();
+ if (type.equals(IPHPPartitions.PHP_PARTITIONING)) {
+ switch (event.character) {
+ case '(' :
+ if (hasCharacterToTheRight(document, offset
+ + length, '('))
+ return;
+ // fall through
+ case '[' :
+ if (!fCloseBracketsPHP)
+ return;
+ if (hasIdentifierToTheRight(document, offset
+ + length))
+ return;
+ // fall through
+ case '"' :
+ if (event.character == '"') {
+ if (!fCloseStringsPHP)
+ return;
+ // changed for statements like echo "" print ""
+ // if (hasIdentifierToTheLeft(document, offset)
+ // ||
+ // hasIdentifierToTheRight(document, offset +
+ // length))
+ if (hasIdentifierToTheRight(document, offset
+ + length))
+ return;
+ }
+ // ITypedRegion partition=
+ // document.getPartition(offset);
+ // if (!
+ // IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType())
+ // &&
+ // (partition.getOffset() != offset))
+ // return;
+ final char character = event.character;
+ final char closingCharacter = getPeerCharacter(character);
+ final StringBuffer buffer = new StringBuffer();
+ buffer.append(character);
+ buffer.append(closingCharacter);
+ document.replace(offset, length, buffer.toString());
+ LinkedPositionManager manager = new LinkedPositionManager(
+ document);
+ manager.addPosition(offset + 1, 0);
+ fOffset = offset;
+ fLength = 2;
+ LinkedPositionUI editor = new LinkedPositionUI(
+ sourceViewer, manager);
+ editor.setCancelListener(this);
+ editor.setExitPolicy(new ExitPolicy(
+ closingCharacter));
+ editor.setFinalCaretOffset(offset + 2);
+ editor.enter();
+ IRegion newSelection = editor.getSelectedRegion();
+ sourceViewer.setSelectedRange(newSelection
+ .getOffset(), newSelection.getLength());
+ event.doit = false;
+ }
+ } else if (type.equals(IPHPPartitions.HTML)
+ || type.equals(IDocument.DEFAULT_CONTENT_TYPE)) {
+ switch (event.character) {
+ case '(' :
+ if (hasCharacterToTheRight(document, offset
+ + length, '('))
+ return;
+ // fall through
+ case '[' :
+ if (!fCloseBracketsHTML)
+ return;
+ if (hasIdentifierToTheRight(document, offset
+ + length))
+ return;
+ // fall through
+ case '"' :
+ if (event.character == '"') {
+ if (!fCloseStringsHTML)
+ return;
+ if (hasIdentifierToTheLeft(document, offset)
+ || hasIdentifierToTheRight(document,
+ offset + length))
+ return;
+ }
+ // ITypedRegion partition=
+ // document.getPartition(offset);
+ // if (!
+ // IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType())
+ // &&
+ // (partition.getOffset() != offset))
+ // return;
+ final char character = event.character;
+ final char closingCharacter = getPeerCharacter(character);
+ final StringBuffer buffer = new StringBuffer();
+ buffer.append(character);
+ buffer.append(closingCharacter);
+ document.replace(offset, length, buffer.toString());
+ LinkedPositionManager manager = new LinkedPositionManager(
+ document);
+ manager.addPosition(offset + 1, 0);
+ fOffset = offset;
+ fLength = 2;
+ LinkedPositionUI editor = new LinkedPositionUI(
+ sourceViewer, manager);
+ editor.setCancelListener(this);
+ editor.setExitPolicy(new ExitPolicy(
+ closingCharacter));
+ editor.setFinalCaretOffset(offset + 2);
+ editor.enter();
+ IRegion newSelection = editor.getSelectedRegion();
+ sourceViewer.setSelectedRange(newSelection
+ .getOffset(), newSelection.getLength());
+ event.doit = false;
+ }
+ }
+ } catch (BadLocationException e) {
+ }
+ }
+ /*
+ * @see org.phpeclipse.phpdt.internal.ui.text.link.LinkedPositionUI.ExitListener#exit(boolean)
+ */
+ public void exit(boolean accept) {
+ if (accept)
+ return;
+ // remove brackets
+ try {
+ final ISourceViewer sourceViewer = getSourceViewer();
+ IDocument document = sourceViewer.getDocument();
+ document.replace(fOffset, fLength, null);
+ } catch (BadLocationException e) {
+ }
+ }
+ }
+ /** The editor's save policy */
+ protected ISavePolicy fSavePolicy;
+ /**
+ * Listener to annotation model changes that updates the error tick in the
+ * tab image
+ */
+ private JavaEditorErrorTickUpdater fJavaEditorErrorTickUpdater;
+ /** The editor's paint manager */
+ // private PaintManager fPaintManager;
+ /** The editor's bracket painter */
+ private BracketPainter fBracketPainter;
+ /** The editor's bracket matcher */
+ private PHPPairMatcher fBracketMatcher;
+ /** The editor's line painter */
+ private LinePainter fLinePainter;
+ /** The editor's print margin ruler painter */
+ private PrintMarginPainter fPrintMarginPainter;
+ /** The editor's problem painter */
+ // private ProblemPainter fProblemPainter;
+ /** The editor's tab converter */
+ private TabConverter fTabConverter;
+ /** History for structure select action */
+ //private SelectionHistory fSelectionHistory;
+ /** The preference property change listener for php core. */
+ // private IPropertyChangeListener fPropertyChangeListener = new
+ // PropertyChangeListener();
+ /** The remembered java element */
+ private IJavaElement fRememberedElement;
+ /** The remembered selection */
+ private ITextSelection fRememberedSelection;
+ /** The remembered php element offset */
+ private int fRememberedElementOffset;
+ /** The bracket inserter. */
+ private BracketInserter fBracketInserter = new BracketInserter();
+
+ /** The standard action groups added to the menu */
+ private GenerateActionGroup fGenerateActionGroup;
+ private CompositeActionGroup fContextMenuGroup;
+ // private class PropertyChangeListener implements IPropertyChangeListener {
+ // /*
+ // * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
+ // */
+ // public void
+ // propertyChange(org.eclipse.core.runtime.Preferences.PropertyChangeEvent
+ // event) {
+ // handlePreferencePropertyChanged(event);
+ // }
+ // }
+ /* Preference key for code formatter tab size */
+ private final static String CODE_FORMATTER_TAB_SIZE = JavaCore.FORMATTER_TAB_SIZE;
+ /** Preference key for matching brackets */
+ private final static String MATCHING_BRACKETS = PreferenceConstants.EDITOR_MATCHING_BRACKETS;
+ /** Preference key for matching brackets color */
+ private final static String MATCHING_BRACKETS_COLOR = PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR;
+ /** Preference key for highlighting current line */
+ private final static String CURRENT_LINE = PreferenceConstants.EDITOR_CURRENT_LINE;
+ /** Preference key for highlight color of current line */
+ private final static String CURRENT_LINE_COLOR = PreferenceConstants.EDITOR_CURRENT_LINE_COLOR;
+ /** Preference key for showing print marging ruler */
+ private final static String PRINT_MARGIN = PreferenceConstants.EDITOR_PRINT_MARGIN;
+ /** Preference key for print margin ruler color */
+ private final static String PRINT_MARGIN_COLOR = PreferenceConstants.EDITOR_PRINT_MARGIN_COLOR;
+ /** Preference key for print margin ruler column */
+ private final static String PRINT_MARGIN_COLUMN = PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN;
+ /** Preference key for inserting spaces rather than tabs */
+ private final static String SPACES_FOR_TABS = PreferenceConstants.EDITOR_SPACES_FOR_TABS;
+ /** Preference key for error indication */
+ // private final static String ERROR_INDICATION =
+ // PreferenceConstants.EDITOR_PROBLEM_INDICATION;
+ /** Preference key for error color */
+ // private final static String ERROR_INDICATION_COLOR =
+ // PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR;
+ /** Preference key for warning indication */
+ // private final static String WARNING_INDICATION =
+ // PreferenceConstants.EDITOR_WARNING_INDICATION;
+ /** Preference key for warning color */
+ // private final static String WARNING_INDICATION_COLOR =
+ // PreferenceConstants.EDITOR_WARNING_INDICATION_COLOR;
+ /** Preference key for task indication */
+ private final static String TASK_INDICATION = PreferenceConstants.EDITOR_TASK_INDICATION;
+ /** Preference key for task color */
+ private final static String TASK_INDICATION_COLOR = PreferenceConstants.EDITOR_TASK_INDICATION_COLOR;
+ /** Preference key for bookmark indication */
+ private final static String BOOKMARK_INDICATION = PreferenceConstants.EDITOR_BOOKMARK_INDICATION;
+ /** Preference key for bookmark color */
+ private final static String BOOKMARK_INDICATION_COLOR = PreferenceConstants.EDITOR_BOOKMARK_INDICATION_COLOR;
+ /** Preference key for search result indication */
+ private final static String SEARCH_RESULT_INDICATION = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION;
+ /** Preference key for search result color */
+ private final static String SEARCH_RESULT_INDICATION_COLOR = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_COLOR;
+ /** Preference key for unknown annotation indication */
+ private final static String UNKNOWN_INDICATION = PreferenceConstants.EDITOR_UNKNOWN_INDICATION;
+ /** Preference key for unknown annotation color */
+ private final static String UNKNOWN_INDICATION_COLOR = PreferenceConstants.EDITOR_UNKNOWN_INDICATION_COLOR;
+ /** Preference key for linked position color */
+ private final static String LINKED_POSITION_COLOR = PreferenceConstants.EDITOR_LINKED_POSITION_COLOR;
+ /** Preference key for shwoing the overview ruler */
+ private final static String OVERVIEW_RULER = PreferenceConstants.EDITOR_OVERVIEW_RULER;
+ /** Preference key for error indication in overview ruler */
+ private final static String ERROR_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER;
+ /** Preference key for warning indication in overview ruler */
+ private final static String WARNING_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER;
+ /** Preference key for task indication in overview ruler */
+ private final static String TASK_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER;
+ /** Preference key for bookmark indication in overview ruler */
+ private final static String BOOKMARK_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER;
+ /** Preference key for search result indication in overview ruler */
+ private final static String SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER;
+ /** Preference key for unknown annotation indication in overview ruler */
+ private final static String UNKNOWN_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER;
+ /** Preference key for automatically closing strings */
+ private final static String CLOSE_STRINGS_PHP = PreferenceConstants.EDITOR_CLOSE_STRINGS_PHP;
+ /** Preference key for automatically wrapping Java strings */
+ private final static String WRAP_STRINGS = PreferenceConstants.EDITOR_WRAP_STRINGS;
+ /** Preference key for automatically closing brackets and parenthesis */
+ private final static String CLOSE_BRACKETS_PHP = PreferenceConstants.EDITOR_CLOSE_BRACKETS_PHP;
+ /** Preference key for automatically closing phpdocs and comments */
+ private final static String CLOSE_JAVADOCS = PreferenceConstants.EDITOR_CLOSE_JAVADOCS;
+ /** Preference key for automatically adding phpdoc tags */
+ private final static String ADD_JAVADOC_TAGS = PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS;
+ /** Preference key for automatically formatting phpdocs */
+ private final static String FORMAT_JAVADOCS = PreferenceConstants.EDITOR_FORMAT_JAVADOCS;
+ /** Preference key for automatically closing strings */
+ private final static String CLOSE_STRINGS_HTML = PreferenceConstants.EDITOR_CLOSE_STRINGS_HTML;
+ /** Preference key for automatically closing brackets and parenthesis */
+ private final static String CLOSE_BRACKETS_HTML = PreferenceConstants.EDITOR_CLOSE_BRACKETS_HTML;
+ /** Preference key for smart paste */
+ private final static String SMART_PASTE = PreferenceConstants.EDITOR_SMART_PASTE;
+ // private final static class AnnotationInfo {
+ // public String fColorPreference;
+ // public String fOverviewRulerPreference;
+ // public String fEditorPreference;
+ // };
+ // private final static Map ANNOTATION_MAP;
+ // static {
+ //
+ // AnnotationInfo info;
+ // ANNOTATION_MAP = new HashMap();
+ //
+ // info = new AnnotationInfo();
+ // info.fColorPreference = TASK_INDICATION_COLOR;
+ // info.fOverviewRulerPreference = TASK_INDICATION_IN_OVERVIEW_RULER;
+ // info.fEditorPreference = TASK_INDICATION;
+ // ANNOTATION_MAP.put(AnnotationType.TASK, info);
+ //
+ // info = new AnnotationInfo();
+ // info.fColorPreference = ERROR_INDICATION_COLOR;
+ // info.fOverviewRulerPreference = ERROR_INDICATION_IN_OVERVIEW_RULER;
+ // info.fEditorPreference = ERROR_INDICATION;
+ // ANNOTATION_MAP.put(AnnotationType.ERROR, info);
+ //
+ // info = new AnnotationInfo();
+ // info.fColorPreference = WARNING_INDICATION_COLOR;
+ // info.fOverviewRulerPreference = WARNING_INDICATION_IN_OVERVIEW_RULER;
+ // info.fEditorPreference = WARNING_INDICATION;
+ // ANNOTATION_MAP.put(AnnotationType.WARNING, info);
+ //
+ // info = new AnnotationInfo();
+ // info.fColorPreference = BOOKMARK_INDICATION_COLOR;
+ // info.fOverviewRulerPreference = BOOKMARK_INDICATION_IN_OVERVIEW_RULER;
+ // info.fEditorPreference = BOOKMARK_INDICATION;
+ // ANNOTATION_MAP.put(AnnotationType.BOOKMARK, info);
+ //
+ // info = new AnnotationInfo();
+ // info.fColorPreference = SEARCH_RESULT_INDICATION_COLOR;
+ // info.fOverviewRulerPreference =
+ // SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER;
+ // info.fEditorPreference = SEARCH_RESULT_INDICATION;
+ // ANNOTATION_MAP.put(AnnotationType.SEARCH, info);
+ //
+ // info = new AnnotationInfo();
+ // info.fColorPreference = UNKNOWN_INDICATION_COLOR;
+ // info.fOverviewRulerPreference = UNKNOWN_INDICATION_IN_OVERVIEW_RULER;
+ // info.fEditorPreference = UNKNOWN_INDICATION;
+ // ANNOTATION_MAP.put(AnnotationType.UNKNOWN, info);
+ // };
+ //
+ // private final static AnnotationType[] ANNOTATION_LAYERS =
+ // new AnnotationType[] {
+ // AnnotationType.UNKNOWN,
+ // AnnotationType.BOOKMARK,
+ // AnnotationType.TASK,
+ // AnnotationType.SEARCH,
+ // AnnotationType.WARNING,
+ // AnnotationType.ERROR };
+ /**
+ * Creates a new php unit editor.
+ */
+ public PHPUnitEditor() {
+ super();
+ setDocumentProvider(PHPeclipsePlugin.getDefault()
+ .getCompilationUnitDocumentProvider());
+ setEditorContextMenuId("#PHPEditorContext"); //$NON-NLS-1$
+ setRulerContextMenuId("#PHPRulerContext"); //$NON-NLS-1$
+ setOutlinerContextMenuId("#PHPOutlinerContext"); //$NON-NLS-1$
+ // don't set help contextId, we install our own help context
+ fSavePolicy = null;
+ fJavaEditorErrorTickUpdater = new JavaEditorErrorTickUpdater(this);
+ }
+ /*
+ * @see AbstractTextEditor#createActions()
+ */
+ protected void createActions() {
+ super.createActions();
+ Action action;
+ // Action action= new
+ // TextOperationAction(PHPEditorMessages.getResourceBundle(),
+ // "CorrectionAssistProposal.", this, CORRECTIONASSIST_PROPOSALS);
+ // //$NON-NLS-1$
+ // action.setActionDefinitionId(PHPEditorActionDefinitionIds.CORRECTION_ASSIST_PROPOSALS);
+ // setAction("CorrectionAssistProposal", action); //$NON-NLS-1$
+ // markAsStateDependentAction("CorrectionAssistProposal", true);
+ // //$NON-NLS-1$
+ //// WorkbenchHelp.setHelp(action,
+ // IJavaHelpContextIds.QUICK_FIX_ACTION);
+ action = new ContentAssistAction(PHPEditorMessages.getResourceBundle(),
+ "ContentAssistProposal.", this); //$NON-NLS-1$
+ action
+ .setActionDefinitionId(PHPEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS);
+ setAction("ContentAssistProposal", action); //$NON-NLS-1$
+ markAsStateDependentAction("ContentAssistProposal", true); //$NON-NLS-1$
+ // WorkbenchHelp.setHelp(action,
+ // IJavaHelpContextIds.CONTENT_ASSIST_ACTION);
+ action = new TextOperationAction(PHPEditorMessages.getResourceBundle(),
+ "ContentAssistContextInformation.", this,
+ ISourceViewer.CONTENTASSIST_CONTEXT_INFORMATION); //$NON-NLS-1$
+ action
+ .setActionDefinitionId(PHPEditorActionDefinitionIds.CONTENT_ASSIST_CONTEXT_INFORMATION);
+ setAction("ContentAssistContextInformation", action); //$NON-NLS-1$
+ markAsStateDependentAction("ContentAssistContextInformation", true); //$NON-NLS-1$
+ // WorkbenchHelp.setHelp(action,
+ // IJavaHelpContextIds.PARAMETER_HINTS_ACTION);
+ // action= new
+ // TextOperationAction(PHPEditorMessages.getResourceBundle(),
+ // "ContentAssistCompletePrefix.", this, CONTENTASSIST_COMPLETE_PREFIX);
+ // //$NON-NLS-1$
+ // action.setActionDefinitionId(PHPEditorActionDefinitionIds.CONTENT_ASSIST_COMPLETE_PREFIX);
+ // setAction("ContentAssistCompletePrefix", action); //$NON-NLS-1$
+ // markAsStateDependentAction("ContentAssistCompletePrefix", true);
+ // //$NON-NLS-1$
+ //// WorkbenchHelp.setHelp(action,
+ // IJavaHelpContextIds.PARAMETER_HINTS_ACTION);
+ action = new TextOperationAction(PHPEditorMessages.getResourceBundle(),
+ "Comment.", this, ITextOperationTarget.PREFIX); //$NON-NLS-1$
+ action.setActionDefinitionId(PHPEditorActionDefinitionIds.COMMENT);
+ setAction("Comment", action); //$NON-NLS-1$
+ markAsStateDependentAction("Comment", true); //$NON-NLS-1$
+ // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.COMMENT_ACTION);
+ action = new TextOperationAction(PHPEditorMessages.getResourceBundle(),
+ "Uncomment.", this, ITextOperationTarget.STRIP_PREFIX); //$NON-NLS-1$
+ action.setActionDefinitionId(PHPEditorActionDefinitionIds.UNCOMMENT);
+ setAction("Uncomment", action); //$NON-NLS-1$
+ markAsStateDependentAction("Uncomment", true); //$NON-NLS-1$
+ // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.UNCOMMENT_ACTION);
+
+ action = new ToggleCommentAction(PHPEditorMessages.getResourceBundle(),
+ "ToggleComment.", this); //$NON-NLS-1$
+ action
+ .setActionDefinitionId(PHPEditorActionDefinitionIds.TOGGLE_COMMENT);
+ setAction("ToggleComment", action); //$NON-NLS-1$
+ markAsStateDependentAction("ToggleComment", true); //$NON-NLS-1$
+ //WorkbenchHelp.setHelp(action,
+ // IJavaHelpContextIds.TOGGLE_COMMENT_ACTION);
+ configureToggleCommentAction();
+
+ // action = new
+ // ToggleCommentAction(PHPEditorMessages.getResourceBundle(),
+ // "ToggleComment.", this, getSourceViewerConfiguration()
+ // .getDefaultPrefixes(getSourceViewer(), "")); //$NON-NLS-1$
+ // //$NON-NLS-2$
+ // action.setActionDefinitionId(PHPEditorActionDefinitionIds.TOGGLE_COMMENT);
+ // setAction("ToggleComment", action); //$NON-NLS-1$
+ // markAsStateDependentAction("ToggleComment", true); //$NON-NLS-1$
+ // // WorkbenchHelp.setHelp(action,
+ // // IJavaHelpContextIds.TOGGLE_COMMENT_ACTION);
+
+ action = new TextOperationAction(PHPEditorMessages.getResourceBundle(),
+ "Format.", this, ISourceViewer.FORMAT); //$NON-NLS-1$
+ action.setActionDefinitionId(PHPEditorActionDefinitionIds.FORMAT);
+ setAction("Format", action); //$NON-NLS-1$
+ markAsStateDependentAction("Format", true); //$NON-NLS-1$
+ markAsSelectionDependentAction("Format", true); //$NON-NLS-1$
+ // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.FORMAT_ACTION);
+
+ action = new AddBlockCommentAction(PHPEditorMessages
+ .getResourceBundle(), "AddBlockComment.", this); //$NON-NLS-1$
+ action
+ .setActionDefinitionId(PHPEditorActionDefinitionIds.ADD_BLOCK_COMMENT);
+ setAction("AddBlockComment", action); //$NON-NLS-1$
+ markAsStateDependentAction("AddBlockComment", true); //$NON-NLS-1$
+ markAsSelectionDependentAction("AddBlockComment", true); //$NON-NLS-1$
+ // WorkbenchHelp.setHelp(action,
+ // IJavaHelpContextIds.ADD_BLOCK_COMMENT_ACTION);
+ action = new RemoveBlockCommentAction(PHPEditorMessages
+ .getResourceBundle(), "RemoveBlockComment.", this); //$NON-NLS-1$
+ action
+ .setActionDefinitionId(PHPEditorActionDefinitionIds.REMOVE_BLOCK_COMMENT);
+ setAction("RemoveBlockComment", action); //$NON-NLS-1$
+ markAsStateDependentAction("RemoveBlockComment", true); //$NON-NLS-1$
+ markAsSelectionDependentAction("RemoveBlockComment", true); //$NON-NLS-1$
+ // WorkbenchHelp.setHelp(action,
+ // IJavaHelpContextIds.ADD_BLOCK_COMMENT_ACTION);
+ // action= new IndentAction(PHPEditorMessages.getResourceBundle(),
+ // "Indent.", this, false); //$NON-NLS-1$
+ // action.setActionDefinitionId(PHPEditorActionDefinitionIds.INDENT);
+ // setAction("Indent", action); //$NON-NLS-1$
+ // markAsStateDependentAction("Indent", true); //$NON-NLS-1$
+ // markAsSelectionDependentAction("Indent", true); //$NON-NLS-1$
+ //// WorkbenchHelp.setHelp(action, IJavaHelpContextIds.INDENT_ACTION);
+ //
+ // action= new IndentAction(PHPEditorMessages.getResourceBundle(),
+ // "Indent.", this, true); //$NON-NLS-1$
+ // setAction("IndentOnTab", action); //$NON-NLS-1$
+ // markAsStateDependentAction("IndentOnTab", true); //$NON-NLS-1$
+ // markAsSelectionDependentAction("IndentOnTab", true); //$NON-NLS-1$
+ //
+ if (getPreferenceStore().getBoolean(
+ PreferenceConstants.EDITOR_SMART_TAB)) {
+ // don't replace Shift Right - have to make sure their enablement is
+ // mutually exclusive
+ // removeActionActivationCode(ITextEditorActionConstants.SHIFT_RIGHT);
+ setActionActivationCode("IndentOnTab", '\t', -1, SWT.NONE); //$NON-NLS-1$
+ }
+ fGenerateActionGroup = new GenerateActionGroup(this,
+ ITextEditorActionConstants.GROUP_EDIT);
+ fActionGroups = new CompositeActionGroup(
+ new ActionGroup[]{fGenerateActionGroup});
+ // We have to keep the context menu group separate to have better
+ // control
+ // over positioning
+ fContextMenuGroup = new CompositeActionGroup(
+ new ActionGroup[]{fGenerateActionGroup});
+ // rg,
+ // new LocalHistoryActionGroup(this,
+ // ITextEditorActionConstants.GROUP_EDIT)});
+
+ }
+ /*
+ * @see JavaEditor#getElementAt(int)
+ */
+ protected IJavaElement getElementAt(int offset) {
+ return getElementAt(offset, true);
+ }
+ /**
+ * Returns the most narrow element including the given offset. If
+ * <code>reconcile</code> is <code>true</code> the editor's input
+ * element is reconciled in advance. If it is <code>false</code> this
+ * method only returns a result if the editor's input element does not need
+ * to be reconciled.
+ *
+ * @param offset
+ * the offset included by the retrieved element
+ * @param reconcile
+ * <code>true</code> if working copy should be reconciled
+ */
+ protected IJavaElement getElementAt(int offset, boolean reconcile) {
+ IWorkingCopyManager manager = PHPeclipsePlugin.getDefault()
+ .getWorkingCopyManager();
+ ICompilationUnit unit = manager.getWorkingCopy(getEditorInput());
+ if (unit != null) {
+ try {
+ if (reconcile) {
+ synchronized (unit) {
+ unit.reconcile();
+ }
+ return unit.getElementAt(offset);
+ } else if (unit.isConsistent())
+ return unit.getElementAt(offset);
+ } catch (JavaModelException x) {
+ PHPeclipsePlugin.log(x.getStatus());
+ // nothing found, be tolerant and go on
+ }
+ }
+ return null;
+ }
+ /*
+ * @see JavaEditor#getCorrespondingElement(IJavaElement)
+ */
+ protected IJavaElement getCorrespondingElement(IJavaElement element) {
+ try {
+ return EditorUtility.getWorkingCopy(element, true);
+ } catch (JavaModelException x) {
+ PHPeclipsePlugin.log(x.getStatus());
+ // nothing found, be tolerant and go on
+ }
+ return null;
+ }
+ public void createPartControl(Composite parent) {
+ super.createPartControl(parent);
+ // fPaintManager = new PaintManager(getSourceViewer());
+ LinePainter linePainter;
+ linePainter = new LinePainter(getSourceViewer());
+ linePainter.setHighlightColor(new Color(Display.getCurrent(), 225, 235,
+ 224));
+ // fPaintManager.addPainter(linePainter);
+ if (isBracketHighlightingEnabled())
+ startBracketHighlighting();
+ if (isLineHighlightingEnabled())
+ startLineHighlighting();
+ if (isPrintMarginVisible())
+ showPrintMargin();
+ // Iterator e = ANNOTATION_MAP.keySet().iterator();
+ // while (e.hasNext()) {
+ // AnnotationType type = (AnnotationType) e.next();
+ // if (isAnnotationIndicationEnabled(type))
+ // startAnnotationIndication(type);
+ // }
+ if (isTabConversionEnabled())
+ startTabConversion();
+ // if (isOverviewRulerVisible())
+ // showOverviewRuler();
+ //
+ // Preferences preferences =
+ // PHPeclipsePlugin.getDefault().getPluginPreferences();
+ // preferences.addPropertyChangeListener(fPropertyChangeListener);
+ IPreferenceStore preferenceStore = getPreferenceStore();
+ boolean closeBracketsPHP = preferenceStore
+ .getBoolean(CLOSE_BRACKETS_PHP);
+ boolean closeStringsPHP = preferenceStore.getBoolean(CLOSE_STRINGS_PHP);
+ boolean closeBracketsHTML = preferenceStore
+ .getBoolean(CLOSE_BRACKETS_HTML);
+ boolean closeStringsHTML = preferenceStore
+ .getBoolean(CLOSE_STRINGS_HTML);
+ fBracketInserter.setCloseBracketsPHPEnabled(closeBracketsPHP);
+ fBracketInserter.setCloseStringsPHPEnabled(closeStringsPHP);
+ fBracketInserter.setCloseBracketsHTMLEnabled(closeBracketsHTML);
+ fBracketInserter.setCloseStringsHTMLEnabled(closeStringsHTML);
+ ISourceViewer sourceViewer = getSourceViewer();
+ if (sourceViewer instanceof ITextViewerExtension)
+ ((ITextViewerExtension) sourceViewer)
+ .prependVerifyKeyListener(fBracketInserter);
+ }
+ private static char getPeerCharacter(char character) {
+ switch (character) {
+ case '(' :
+ return ')';
+ case ')' :
+ return '(';
+ case '[' :
+ return ']';
+ case ']' :
+ return '[';
+ case '"' :
+ return character;
+ default :
+ throw new IllegalArgumentException();
+ }
+ }
+
+ private void startBracketHighlighting() {
+ if (fBracketPainter == null) {
+ ISourceViewer sourceViewer = getSourceViewer();
+ fBracketPainter = new BracketPainter(sourceViewer);
+ fBracketPainter
+ .setHighlightColor(getColor(MATCHING_BRACKETS_COLOR));
+ // fPaintManager.addPainter(fBracketPainter);
+ }
+ }
+ private void stopBracketHighlighting() {
+ if (fBracketPainter != null) {
+ // fPaintManager.removePainter(fBracketPainter);
+ fBracketPainter.deactivate(true);
+ fBracketPainter.dispose();
+ fBracketPainter = null;
+ }
+ }
+ private boolean isBracketHighlightingEnabled() {
+ IPreferenceStore store = getPreferenceStore();
+ return store.getBoolean(MATCHING_BRACKETS);
+ }
+ private void startLineHighlighting() {
+ if (fLinePainter == null) {
+ ISourceViewer sourceViewer = getSourceViewer();
+ fLinePainter = new LinePainter(sourceViewer);
+ fLinePainter.setHighlightColor(getColor(CURRENT_LINE_COLOR));
+ // fPaintManager.addPainter(fLinePainter);
+ }
+ }
+ private void stopLineHighlighting() {
+ if (fLinePainter != null) {
+ // fPaintManager.removePainter(fLinePainter);
+ fLinePainter.deactivate(true);
+ fLinePainter.dispose();
+ fLinePainter = null;
+ }
+ }
+ private boolean isLineHighlightingEnabled() {
+ IPreferenceStore store = getPreferenceStore();
+ return store.getBoolean(CURRENT_LINE);
+ }
+ private void showPrintMargin() {
+ if (fPrintMarginPainter == null) {
+ fPrintMarginPainter = new PrintMarginPainter(getSourceViewer());
+ fPrintMarginPainter
+ .setMarginRulerColor(getColor(PRINT_MARGIN_COLOR));
+ fPrintMarginPainter.setMarginRulerColumn(getPreferenceStore()
+ .getInt(PRINT_MARGIN_COLUMN));
+ // fPaintManager.addPainter(fPrintMarginPainter);
+ }
+ }
+ private void hidePrintMargin() {
+ if (fPrintMarginPainter != null) {
+ // fPaintManager.removePainter(fPrintMarginPainter);
+ fPrintMarginPainter.deactivate(true);
+ fPrintMarginPainter.dispose();
+ fPrintMarginPainter = null;
+ }
+ }
+ private boolean isPrintMarginVisible() {
+ IPreferenceStore store = getPreferenceStore();
+ return store.getBoolean(PRINT_MARGIN);
+ }
+ // private void startAnnotationIndication(AnnotationType annotationType) {
+ // if (fProblemPainter == null) {
+ // fProblemPainter = new ProblemPainter(this, getSourceViewer());
+ //// fPaintManager.addPainter(fProblemPainter);
+ // }
+ // fProblemPainter.setColor(annotationType, getColor(annotationType));
+ // fProblemPainter.paintAnnotations(annotationType, true);
+ // fProblemPainter.paint(IPainter.CONFIGURATION);
+ // }
+ //
+ // private void shutdownAnnotationIndication() {
+ // if (fProblemPainter != null) {
+ //
+ // if (!fProblemPainter.isPaintingAnnotations()) {
+ //// fPaintManager.removePainter(fProblemPainter);
+ // fProblemPainter.deactivate(true);
+ // fProblemPainter.dispose();
+ // fProblemPainter = null;
+ // } else {
+ // fProblemPainter.paint(IPainter.CONFIGURATION);
+ // }
+ // }
+ // }
+ //
+ // private void stopAnnotationIndication(AnnotationType annotationType) {
+ // if (fProblemPainter != null) {
+ // fProblemPainter.paintAnnotations(annotationType, false);
+ // shutdownAnnotationIndication();
+ // }
+ // }
+ //
+ // private boolean isAnnotationIndicationEnabled(AnnotationType
+ // annotationType) {
+ // IPreferenceStore store = getPreferenceStore();
+ // AnnotationInfo info = (AnnotationInfo)
+ // ANNOTATION_MAP.get(annotationType);
+ // if (info != null)
+ // return store.getBoolean(info.fEditorPreference);
+ // return false;
+ // }
+ //
+ // private boolean
+ // isAnnotationIndicationInOverviewRulerEnabled(AnnotationType
+ // annotationType) {
+ // IPreferenceStore store = getPreferenceStore();
+ // AnnotationInfo info = (AnnotationInfo)
+ // ANNOTATION_MAP.get(annotationType);
+ // if (info != null)
+ // return store.getBoolean(info.fOverviewRulerPreference);
+ // return false;
+ // }
+ //
+ // private void showAnnotationIndicationInOverviewRuler(AnnotationType
+ // annotationType, boolean show) {
+ // AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
+ // OverviewRuler ruler = asv.getOverviewRuler();
+ // if (ruler != null) {
+ // ruler.setColor(annotationType, getColor(annotationType));
+ // ruler.showAnnotation(annotationType, show);
+ // ruler.update();
+ // }
+ // }
+ //
+ // private void setColorInOverviewRuler(AnnotationType annotationType, Color
+ // color) {
+ // AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
+ // OverviewRuler ruler = asv.getOverviewRuler();
+ // if (ruler != null) {
+ // ruler.setColor(annotationType, color);
+ // ruler.update();
+ // }
+ // }
+
+ private int getTabSize() {
+ Preferences preferences = PHPeclipsePlugin.getDefault()
+ .getPluginPreferences();
+ return preferences.getInt(CODE_FORMATTER_TAB_SIZE);
+ }
+
+ private boolean isTabConversionEnabled() {
+ IPreferenceStore store = getPreferenceStore();
+ return store.getBoolean(SPACES_FOR_TABS);
+ }
+ // private void showOverviewRuler() {
+ // AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
+ // asv.showOverviewRuler();
+ //
+ // OverviewRuler overviewRuler = asv.getOverviewRuler();
+ // if (overviewRuler != null) {
+ // for (int i = 0; i < ANNOTATION_LAYERS.length; i++) {
+ // AnnotationType type = ANNOTATION_LAYERS[i];
+ // overviewRuler.setLayer(type, i);
+ // if (isAnnotationIndicationInOverviewRulerEnabled(type))
+ // showAnnotationIndicationInOverviewRuler(type, true);
+ // }
+ // }
+ // }
+ //
+ // private void hideOverviewRuler() {
+ // AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
+ // asv.hideOverviewRuler();
+ // }
+ //
+ // private boolean isOverviewRulerVisible() {
+ // IPreferenceStore store = getPreferenceStore();
+ // return store.getBoolean(OVERVIEW_RULER);
+ // }
+ private Color getColor(String key) {
+ RGB rgb = PreferenceConverter.getColor(getPreferenceStore(), key);
+ return getColor(rgb);
+ }
+ private Color getColor(RGB rgb) {
+ JavaTextTools textTools = PHPeclipsePlugin.getDefault()
+ .getJavaTextTools();
+ return textTools.getColorManager().getColor(rgb);
+ }
+ // private Color getColor(AnnotationType annotationType) {
+ // AnnotationInfo info = (AnnotationInfo)
+ // ANNOTATION_MAP.get(annotationType);
+ // if (info != null)
+ // return getColor(info.fColorPreference);
+ // return null;
+ // }
+ public void dispose() {
+ ISourceViewer sourceViewer = getSourceViewer();
+ if (sourceViewer instanceof ITextViewerExtension)
+ ((ITextViewerExtension) sourceViewer)
+ .removeVerifyKeyListener(fBracketInserter);
+ // if (fPropertyChangeListener != null) {
+ // Preferences preferences =
+ // PHPeclipsePlugin.getDefault().getPluginPreferences();
+ // preferences.removePropertyChangeListener(fPropertyChangeListener);
+ // fPropertyChangeListener = null;
+ // }
+ if (fJavaEditorErrorTickUpdater != null) {
+ fJavaEditorErrorTickUpdater.dispose();
+ fJavaEditorErrorTickUpdater = null;
+ }
+ // if (fSelectionHistory != null)
+ // fSelectionHistory.dispose();
+ // if (fPaintManager != null) {
+ // fPaintManager.dispose();
+ // fPaintManager = null;
+ // }
+ if (fActionGroups != null) {
+ fActionGroups.dispose();
+ fActionGroups = null;
+ }
+ super.dispose();
+ }
+ // protected AnnotationType getAnnotationType(String preferenceKey) {
+ // Iterator e = ANNOTATION_MAP.keySet().iterator();
+ // while (e.hasNext()) {
+ // AnnotationType type = (AnnotationType) e.next();
+ // AnnotationInfo info = (AnnotationInfo) ANNOTATION_MAP.get(type);
+ // if (info != null) {
+ // if (preferenceKey.equals(info.fColorPreference)
+ // || preferenceKey.equals(info.fEditorPreference)
+ // || preferenceKey.equals(info.fOverviewRulerPreference))
+ // return type;
+ // }
+ // }
+ // return null;
+ // }
+ /*
+ * @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent)
+ */
+ protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
+ try {
+ AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
+ if (asv != null) {
+ String p = event.getProperty();
+ if (CLOSE_BRACKETS_PHP.equals(p)) {
+ fBracketInserter
+ .setCloseBracketsPHPEnabled(getPreferenceStore()
+ .getBoolean(p));
+ return;
+ }
+ if (CLOSE_STRINGS_PHP.equals(p)) {
+ fBracketInserter
+ .setCloseStringsPHPEnabled(getPreferenceStore()
+ .getBoolean(p));
+ return;
+ }
+ if (CLOSE_BRACKETS_HTML.equals(p)) {
+ fBracketInserter
+ .setCloseBracketsHTMLEnabled(getPreferenceStore()
+ .getBoolean(p));
+ return;
+ }
+ if (CLOSE_STRINGS_HTML.equals(p)) {
+ fBracketInserter
+ .setCloseStringsHTMLEnabled(getPreferenceStore()
+ .getBoolean(p));
+ return;
+ }
+ if (SPACES_FOR_TABS.equals(p)) {
+ if (isTabConversionEnabled())
+ startTabConversion();
+ else
+ stopTabConversion();
+ return;
+ }
+ if (MATCHING_BRACKETS.equals(p)) {
+ if (isBracketHighlightingEnabled())
+ startBracketHighlighting();
+ else
+ stopBracketHighlighting();
+ return;
+ }
+ if (MATCHING_BRACKETS_COLOR.equals(p)) {
+ if (fBracketPainter != null)
+ fBracketPainter
+ .setHighlightColor(getColor(MATCHING_BRACKETS_COLOR));
+ return;
+ }
+ if (CURRENT_LINE.equals(p)) {
+ if (isLineHighlightingEnabled())
+ startLineHighlighting();
+ else
+ stopLineHighlighting();
+ return;
+ }
+ if (CURRENT_LINE_COLOR.equals(p)) {
+ if (fLinePainter != null) {
+ stopLineHighlighting();
+ startLineHighlighting();
+ }
+ return;
+ }
+ if (PRINT_MARGIN.equals(p)) {
+ if (isPrintMarginVisible())
+ showPrintMargin();
+ else
+ hidePrintMargin();
+ return;
+ }
+ if (PRINT_MARGIN_COLOR.equals(p)) {
+ if (fPrintMarginPainter != null)
+ fPrintMarginPainter
+ .setMarginRulerColor(getColor(PRINT_MARGIN_COLOR));
+ return;
+ }
+ if (PRINT_MARGIN_COLUMN.equals(p)) {
+ if (fPrintMarginPainter != null)
+ fPrintMarginPainter
+ .setMarginRulerColumn(getPreferenceStore()
+ .getInt(PRINT_MARGIN_COLUMN));
+ return;
+ }
+ // if (OVERVIEW_RULER.equals(p)) {
+ // if (isOverviewRulerVisible())
+ // showOverviewRuler();
+ // else
+ // hideOverviewRuler();
+ // return;
+ // }
+ // AnnotationType type = getAnnotationType(p);
+ // if (type != null) {
+ //
+ // AnnotationInfo info = (AnnotationInfo)
+ // ANNOTATION_MAP.get(type);
+ // if (info.fColorPreference.equals(p)) {
+ // Color color = getColor(type);
+ // if (fProblemPainter != null) {
+ // fProblemPainter.setColor(type, color);
+ // fProblemPainter.paint(IPainter.CONFIGURATION);
+ // }
+ // setColorInOverviewRuler(type, color);
+ // return;
+ // }
+ //
+ // if (info.fEditorPreference.equals(p)) {
+ // if (isAnnotationIndicationEnabled(type))
+ // startAnnotationIndication(type);
+ // else
+ // stopAnnotationIndication(type);
+ // return;
+ // }
+ //
+ // if (info.fOverviewRulerPreference.equals(p)) {
+ // if (isAnnotationIndicationInOverviewRulerEnabled(type))
+ // showAnnotationIndicationInOverviewRuler(type, true);
+ // else
+ // showAnnotationIndicationInOverviewRuler(type, false);
+ // return;
+ // }
+ // }
+ IContentAssistant c = asv.getContentAssistant();
+ if (c instanceof ContentAssistant)
+ ContentAssistPreference.changeConfiguration(
+ (ContentAssistant) c, getPreferenceStore(), event);
+ }
+ } finally {
+ super.handlePreferenceStoreChanged(event);
+ }
+ }
+ /*
+ * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor#handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent)
+ */
+ protected void handlePreferencePropertyChanged(
+ org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) {
+ AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
+ if (asv != null) {
+ String p = event.getProperty();
+ if (CODE_FORMATTER_TAB_SIZE.equals(p)) {
+ asv.updateIndentationPrefixes();
+ if (fTabConverter != null)
+ fTabConverter.setNumberOfSpacesPerTab(getTabSize());
+ }
+ }
+ super.handlePreferencePropertyChanged(event);
+ }
+ /**
+ * Handles a property change event describing a change of the php core's
+ * preferences and updates the preference related editor properties.
+ *
+ * @param event
+ * the property change event
+ */
+ // protected void
+ // handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent
+ // event) {
+ // AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
+ // if (asv != null) {
+ // String p = event.getProperty();
+ // if (CODE_FORMATTER_TAB_SIZE.equals(p)) {
+ // asv.updateIndentationPrefixes();
+ // if (fTabConverter != null)
+ // fTabConverter.setNumberOfSpacesPerTab(getTabSize());
+ // }
+ // }
+ // }
+
+ /*
+ * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor#createJavaSourceViewer(org.eclipse.swt.widgets.Composite, org.eclipse.jface.text.source.IVerticalRuler, org.eclipse.jface.text.source.IOverviewRuler, boolean, int)
+ */
+ protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, boolean isOverviewRulerVisible, int styles, IPreferenceStore store) {
+ return new AdaptedSourceViewer(parent, verticalRuler, overviewRuler, isOverviewRulerVisible, styles, store);
+ }
+ // protected ISourceViewer createJavaSourceViewer(Composite parent,
+ // IVerticalRuler ruler, int styles) {
+ // return new AdaptedSourceViewer(parent, ruler, styles);
+ // }
+ private boolean isValidSelection(int offset, int length) {
+ IDocumentProvider provider = getDocumentProvider();
+ if (provider != null) {
+ IDocument document = provider.getDocument(getEditorInput());
+ if (document != null) {
+ int end = offset + length;
+ int documentLength = document.getLength();
+ return 0 <= offset && offset <= documentLength && 0 <= end
+ && end <= documentLength;
+ }
+ }
+ return false;
+ }
+ /*
+ * @see AbstractTextEditor#canHandleMove(IEditorInput, IEditorInput)
+ */
+ protected boolean canHandleMove(IEditorInput originalElement,
+ IEditorInput movedElement) {
+ String oldExtension = ""; //$NON-NLS-1$
+ if (originalElement instanceof IFileEditorInput) {
+ IFile file = ((IFileEditorInput) originalElement).getFile();
+ if (file != null) {
+ String ext = file.getFileExtension();
+ if (ext != null)
+ oldExtension = ext;
+ }
+ }
+ String newExtension = ""; //$NON-NLS-1$
+ if (movedElement instanceof IFileEditorInput) {
+ IFile file = ((IFileEditorInput) movedElement).getFile();
+ if (file != null)
+ newExtension = file.getFileExtension();
+ }
+ return oldExtension.equals(newExtension);
+ }
+ /*
+ * @see AbstractTextEditor#editorContextMenuAboutToShow(IMenuManager)
+ */
+ public void editorContextMenuAboutToShow(IMenuManager menu) {
+ super.editorContextMenuAboutToShow(menu);
+ ActionContext context = new ActionContext(getSelectionProvider()
+ .getSelection());
+ fContextMenuGroup.setContext(context);
+ fContextMenuGroup.fillContextMenu(menu);
+ fContextMenuGroup.setContext(null);
+ }
+ /*
+ * @see JavaEditor#setOutlinePageInput(JavaOutlinePage, IEditorInput)
+ */
+ protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input) {
+ if (page != null) {
+ IWorkingCopyManager manager = PHPeclipsePlugin.getDefault()
+ .getWorkingCopyManager();
+ page.setInput(manager.getWorkingCopy(input));
+ }
+ }
+ /*
+ * @see AbstractTextEditor#performSaveOperation(WorkspaceModifyOperation,
+ * IProgressMonitor)
+ */
+ // protected void performSaveOperation(WorkspaceModifyOperation operation,
+ // IProgressMonitor progressMonitor) {
+ // IDocumentProvider p = getDocumentProvider();
+ // if (p instanceof PHPDocumentProvider) {
+ // PHPDocumentProvider cp = (PHPDocumentProvider) p;
+ // cp.setSavePolicy(fSavePolicy);
+ // }
+ //
+ // try {
+ // super.performSaveOperation(operation, progressMonitor);
+ // } finally {
+ // if (p instanceof PHPDocumentProvider) {
+ // PHPDocumentProvider cp = (PHPDocumentProvider) p;
+ // cp.setSavePolicy(null);
+ // }
+ // }
+ // }
+ /*
+ * @see AbstractTextEditor#doSave(IProgressMonitor)
+ */
+ public void doSave(IProgressMonitor progressMonitor) {
+
+ IDocumentProvider p = getDocumentProvider();
+ if (p == null) {
+ // editor has been closed
+ return;
+ }
+
+ if (p.isDeleted(getEditorInput())) {
+
+ if (isSaveAsAllowed()) {
+
+ /*
+ * 1GEUSSR: ITPUI:ALL - User should never loose changes made in
+ * the editors. Changed Behavior to make sure that if called
+ * inside a regular save (because of deletion of input element)
+ * there is a way to report back to the caller.
+ */
+ performSaveAs(progressMonitor);
+
+ } else {
+
+ /*
+ * 1GF5YOX: ITPJUI:ALL - Save of delete file claims it's still
+ * there Missing resources.
+ */
+ Shell shell = getSite().getShell();
+ MessageDialog
+ .openError(
+ shell,
+ PHPEditorMessages
+ .getString("PHPUnitEditor.error.saving.title1"), PHPEditorMessages.getString("PHPUnitEditor.error.saving.message1")); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ } else {
+
+ setStatusLineErrorMessage(null);
+
+ IWorkingCopyManager manager = PHPeclipsePlugin.getDefault()
+ .getWorkingCopyManager();
+ ICompilationUnit unit = manager.getWorkingCopy(getEditorInput());
+
+ if (unit != null) {
+ synchronized (unit) {
+ performSave(false, progressMonitor);
+ }
+ } else
+ performSave(false, progressMonitor);
+ }
+ }
+
+ public boolean isSaveAsAllowed() {
+ return true;
+ }
+
+ /**
+ * The compilation unit editor implementation of this
+ * <code>AbstractTextEditor</code> method asks the user for the workspace
+ * path of a file resource and saves the document there. See
+ * http://dev.eclipse.org/bugs/show_bug.cgi?id=6295
+ *
+ * @param progressMonitor
+ * the progress monitor
+ */
+ protected void performSaveAs(IProgressMonitor progressMonitor) {
+
+ Shell shell = getSite().getShell();
+ IEditorInput input = getEditorInput();
+
+ SaveAsDialog dialog = new SaveAsDialog(shell);
+
+ IFile original = (input instanceof IFileEditorInput)
+ ? ((IFileEditorInput) input).getFile()
+ : null;
+ if (original != null)
+ dialog.setOriginalFile(original);
+
+ dialog.create();
+
+ IDocumentProvider provider = getDocumentProvider();
+ if (provider == null) {
+ // editor has been programmatically closed while the dialog was open
+ return;
+ }
+
+ if (provider.isDeleted(input) && original != null) {
+ String message = PHPEditorMessages
+ .getFormattedString(
+ "CompilationUnitEditor.warning.save.delete", new Object[]{original.getName()}); //$NON-NLS-1$
+ dialog.setErrorMessage(null);
+ dialog.setMessage(message, IMessageProvider.WARNING);
+ }
+
+ if (dialog.open() == Window.CANCEL) {
+ if (progressMonitor != null)
+ progressMonitor.setCanceled(true);
+ return;
+ }
+
+ IPath filePath = dialog.getResult();
+ if (filePath == null) {
+ if (progressMonitor != null)
+ progressMonitor.setCanceled(true);
+ return;
+ }
+
+ IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
+ IFile file = workspaceRoot.getFile(filePath);
+ final IEditorInput newInput = new FileEditorInput(file);
+
+ boolean success = false;
+ try {
+
+ provider.aboutToChange(newInput);
+ getDocumentProvider().saveDocument(progressMonitor, newInput,
+ getDocumentProvider().getDocument(getEditorInput()), true);
+ success = true;
+
+ } catch (CoreException x) {
+ IStatus status = x.getStatus();
+ if (status == null || status.getSeverity() != IStatus.CANCEL)
+ ErrorDialog
+ .openError(
+ shell,
+ PHPEditorMessages
+ .getString("CompilationUnitEditor.error.saving.title2"), PHPEditorMessages.getString("CompilationUnitEditor.error.saving.message2"), x.getStatus()); //$NON-NLS-1$ //$NON-NLS-2$
+ } finally {
+ provider.changed(newInput);
+ if (success)
+ setInput(newInput);
+ }
+
+ if (progressMonitor != null)
+ progressMonitor.setCanceled(!success);
+ }
+
+ /*
+ * @see AbstractTextEditor#doSetInput(IEditorInput)
+ */
+ protected void doSetInput(IEditorInput input) throws CoreException {
+ super.doSetInput(input);
+ configureTabConverter();
+ configureToggleCommentAction();
+ }
+
+ // /*
+ // * @see
+ // org.eclipse.jdt.internal.ui.javaeditor.JavaEditor#installOverrideIndicator(boolean)
+ // * @since 3.0
+ // */
+ // protected void installOverrideIndicator(boolean waitForReconcilation) {
+ // IAnnotationModel model=
+ // getDocumentProvider().getAnnotationModel(getEditorInput());
+ // if (!waitForReconcilation)
+ // super.installOverrideIndicator(false);
+ // else {
+ // uninstallOverrideIndicator();
+ // IJavaElement inputElement= getInputJavaElement();
+ // if (model == null || inputElement == null)
+ // return;
+ //
+ // fOverrideIndicatorManager= new OverrideIndicatorManager(model,
+ // inputElement, null);
+ // addReconcileListener(fOverrideIndicatorManager);
+ // }
+ // }
+ //
+ // /*
+ // * @see
+ // org.eclipse.jdt.internal.ui.javaeditor.JavaEditor#uninstallOverrideIndicator()
+ // * @since 3.0
+ // */
+ // protected void uninstallOverrideIndicator() {
+ // if (fOverrideIndicatorManager != null)
+ // removeReconcileListener(fOverrideIndicatorManager);
+ // super.uninstallOverrideIndicator();
+ // }
+
+ /**
+ * Configures the toggle comment action
+ *
+ * @since 3.0
+ */
+ private void configureToggleCommentAction() {
+ IAction action = getAction("ToggleComment"); //$NON-NLS-1$
+ if (action instanceof ToggleCommentAction) {
+ ISourceViewer sourceViewer = getSourceViewer();
+ SourceViewerConfiguration configuration = getSourceViewerConfiguration();
+ ((ToggleCommentAction) action).configure(sourceViewer,
+ configuration);
+ }
+ }
+
+ private void configureTabConverter() {
+ if (fTabConverter != null) {
+ IDocumentProvider provider = getDocumentProvider();
+ if (provider instanceof PHPDocumentProvider) {
+ PHPDocumentProvider cup = (PHPDocumentProvider) provider;
+ fTabConverter.setLineTracker(cup
+ .createLineTracker(getEditorInput()));
+ }
+ }
+ }
+
+ private void startTabConversion() {
+ if (fTabConverter == null) {
+ fTabConverter = new TabConverter();
+ configureTabConverter();
+ fTabConverter.setNumberOfSpacesPerTab(getTabSize());
+ AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
+ asv.addTextConverter(fTabConverter);
+ // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270
+ asv.updateIndentationPrefixes();
+ }
+ }
+
+ private void stopTabConversion() {
+ if (fTabConverter != null) {
+ AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
+ asv.removeTextConverter(fTabConverter);
+ // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270
+ asv.updateIndentationPrefixes();
+ fTabConverter = null;
+ }
+ }
+
+ /*
+ * @see org.eclipse.ui.texteditor.AbstractTextEditor#performSave(boolean,
+ * org.eclipse.core.runtime.IProgressMonitor)
+ */
+ protected void performSave(boolean overwrite,
+ IProgressMonitor progressMonitor) {
+ IDocumentProvider p = getDocumentProvider();
+ if (p instanceof PHPDocumentProvider) {
+ PHPDocumentProvider cp = (PHPDocumentProvider) p;
+ cp.setSavePolicy(fSavePolicy);
+ }
+ try {
+ super.performSave(overwrite, progressMonitor);
+ } finally {
+ if (p instanceof PHPDocumentProvider) {
+ PHPDocumentProvider cp = (PHPDocumentProvider) p;
+ cp.setSavePolicy(null);
+ }
+ }
+ }
+ /*
+ * @see AbstractTextEditor#doSaveAs
+ */
+ public void doSaveAs() {
+ if (askIfNonWorkbenchEncodingIsOk()) {
+ super.doSaveAs();
+ }
+ }
+
+ /**
+ * Asks the user if it is ok to store in non-workbench encoding.
+ *
+ * @return <true>if the user wants to continue
+ */
+ private boolean askIfNonWorkbenchEncodingIsOk() {
+ IDocumentProvider provider = getDocumentProvider();
+ if (provider instanceof IStorageDocumentProvider) {
+ IEditorInput input = getEditorInput();
+ IStorageDocumentProvider storageProvider = (IStorageDocumentProvider) provider;
+ String encoding = storageProvider.getEncoding(input);
+ String defaultEncoding = storageProvider.getDefaultEncoding();
+ if (encoding != null && !encoding.equals(defaultEncoding)) {
+ Shell shell = getSite().getShell();
+ String title = PHPEditorMessages
+ .getString("PHPUnitEditor.warning.save.nonWorkbenchEncoding.title"); //$NON-NLS-1$
+ String msg;
+ if (input != null)
+ msg = MessageFormat
+ .format(
+ PHPEditorMessages
+ .getString("PHPUnitEditor.warning.save.nonWorkbenchEncoding.message1"),
+ new String[]{input.getName(), encoding}); //$NON-NLS-1$
+ else
+ msg = MessageFormat
+ .format(
+ PHPEditorMessages
+ .getString("PHPUnitEditor.warning.save.nonWorkbenchEncoding.message2"),
+ new String[]{encoding}); //$NON-NLS-1$
+ return MessageDialog.openQuestion(shell, title, msg);
+ }
+ }
+ return true;
+ }
+ /*
+ * @see IReconcilingParticipant#reconciled()
+ */
+ public void reconciled() {
+ if (synchronizeOutlineOnCursorMove()) {
+ Shell shell = getSite().getShell();
+ if (shell != null && !shell.isDisposed()) {
+ shell.getDisplay().asyncExec(new Runnable() {
+ public void run() {
+ synchronizeOutlinePageSelection();
+ }
+ });
+ }
+ }
+ }
+
+ protected void updateStateDependentActions() {
+ super.updateStateDependentActions();
+ fGenerateActionGroup.editorStateChanged();
+ }
+
+ private boolean synchronizeOutlineOnCursorMove() {
+ return PreferenceConstants.getPreferenceStore().getBoolean(
+ PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE);
+ }
- /**
- * Returns the updated java element for the old java element.
- */
- private IJavaElement findElement(IJavaElement element) {
- if (element == null)
- return null;
- IWorkingCopyManager manager = PHPeclipsePlugin.getDefault()
- .getWorkingCopyManager();
- ICompilationUnit unit = manager.getWorkingCopy(getEditorInput());
- if (unit != null) {
- try {
- synchronized (unit) {
- unit.reconcile();
- }
- IJavaElement[] findings = unit.findElements(element);
- if (findings != null && findings.length > 0)
- return findings[0];
- } catch (JavaModelException x) {
- PHPeclipsePlugin.log(x.getStatus());
- // nothing found, be tolerant and go on
- }
- }
- return null;
- }
- /**
- * Returns the offset of the given Java element.
- */
- private int getOffset(IJavaElement element) {
- if (element instanceof ISourceReference) {
- ISourceReference sr = (ISourceReference) element;
- try {
- ISourceRange srcRange = sr.getSourceRange();
- if (srcRange != null)
- return srcRange.getOffset();
- } catch (JavaModelException e) {
- }
- }
- return -1;
- }
- /*
- * @see AbstractTextEditor#rememberSelection()
- */
- protected void rememberSelection() {
- ISelectionProvider sp = getSelectionProvider();
- fRememberedSelection = (sp == null ? null : (ITextSelection) sp
- .getSelection());
- if (fRememberedSelection != null) {
- fRememberedElement = getElementAt(fRememberedSelection.getOffset(), true);
- fRememberedElementOffset = getOffset(fRememberedElement);
- }
- }
- /*
- * @see AbstractTextEditor#restoreSelection()
- */
- protected void restoreSelection() {
- try {
- if (getSourceViewer() == null || fRememberedSelection == null)
- return;
- IJavaElement newElement = findElement(fRememberedElement);
- int newOffset = getOffset(newElement);
- int delta = (newOffset > -1 && fRememberedElementOffset > -1) ? newOffset
- - fRememberedElementOffset : 0;
- if (isValidSelection(delta + fRememberedSelection.getOffset(),
- fRememberedSelection.getLength()))
- selectAndReveal(delta + fRememberedSelection.getOffset(),
- fRememberedSelection.getLength());
- } finally {
- fRememberedSelection = null;
- fRememberedElement = null;
- fRememberedElementOffset = -1;
- }
- }
-}
+ /**
+ * Returns the updated java element for the old java element.
+ */
+ private IJavaElement findElement(IJavaElement element) {
+ if (element == null)
+ return null;
+ IWorkingCopyManager manager = PHPeclipsePlugin.getDefault()
+ .getWorkingCopyManager();
+ ICompilationUnit unit = manager.getWorkingCopy(getEditorInput());
+ if (unit != null) {
+ try {
+ synchronized (unit) {
+ unit.reconcile();
+ }
+ IJavaElement[] findings = unit.findElements(element);
+ if (findings != null && findings.length > 0)
+ return findings[0];
+ } catch (JavaModelException x) {
+ PHPeclipsePlugin.log(x.getStatus());
+ // nothing found, be tolerant and go on
+ }
+ }
+ return null;
+ }
+ /**
+ * Returns the offset of the given Java element.
+ */
+ private int getOffset(IJavaElement element) {
+ if (element instanceof ISourceReference) {
+ ISourceReference sr = (ISourceReference) element;
+ try {
+ ISourceRange srcRange = sr.getSourceRange();
+ if (srcRange != null)
+ return srcRange.getOffset();
+ } catch (JavaModelException e) {
+ }
+ }
+ return -1;
+ }
+ /*
+ * @see AbstractTextEditor#rememberSelection()
+ */
+ protected void rememberSelection() {
+ ISelectionProvider sp = getSelectionProvider();
+ fRememberedSelection = (sp == null ? null : (ITextSelection) sp
+ .getSelection());
+ if (fRememberedSelection != null) {
+ fRememberedElement = getElementAt(fRememberedSelection.getOffset(),
+ true);
+ fRememberedElementOffset = getOffset(fRememberedElement);
+ }
+ }
+ /*
+ * @see AbstractTextEditor#restoreSelection()
+ */
+ protected void restoreSelection() {
+ try {
+ if (getSourceViewer() == null || fRememberedSelection == null)
+ return;
+ IJavaElement newElement = findElement(fRememberedElement);
+ int newOffset = getOffset(newElement);
+ int delta = (newOffset > -1 && fRememberedElementOffset > -1)
+ ? newOffset - fRememberedElementOffset
+ : 0;
+ if (isValidSelection(delta + fRememberedSelection.getOffset(),
+ fRememberedSelection.getLength()))
+ selectAndReveal(delta + fRememberedSelection.getOffset(),
+ fRememberedSelection.getLength());
+ } finally {
+ fRememberedSelection = null;
+ fRememberedElement = null;
+ fRememberedElementOffset = -1;
+ }
+ }
+
+// /*
+// * @see org.eclipse.jdt.internal.ui.text.java.IJavaReconcilingListener#aboutToBeReconciled()
+// * @since 3.0
+// */
+// public void aboutToBeReconciled() {
+//
+// // Notify AST provider
+// PHPeclipsePlugin.getDefault().getASTProvider().aboutToBeReconciled(getInputJavaElement());
+//
+// // Notify listeners
+// Object[] listeners = fReconcilingListeners.getListeners();
+// for (int i = 0, length= listeners.length; i < length; ++i)
+// ((IJavaReconcilingListener)listeners[i]).aboutToBeReconciled();
+// }
+//
+// /*
+// * @see org.eclipse.jdt.internal.ui.text.java.IJavaReconcilingListener#reconciled(CompilationUnit, boolean, IProgressMonitor)
+// * @since 3.0
+// */
+// public void reconciled(net.sourceforge.phpdt.core.dom.CompilationUnit ast, boolean forced, IProgressMonitor progressMonitor) {
+//
+// // Always notify AST provider
+// PHPeclipsePlugin.getDefault().getASTProvider().reconciled(ast, getInputJavaElement());
+//
+// // Notify listeners
+// Object[] listeners = fReconcilingListeners.getListeners();
+// for (int i = 0, length= listeners.length; i < length; ++i)
+// ((IJavaReconcilingListener)listeners[i]).reconciled(ast, forced, progressMonitor);
+//
+// // Update Java Outline page selection
+// if (!forced && !progressMonitor.isCanceled()) {
+// Shell shell= getSite().getShell();
+// if (shell != null && !shell.isDisposed()) {
+// shell.getDisplay().asyncExec(new Runnable() {
+// public void run() {
+// selectionChanged();
+// }
+// });
+// }
+// }
+// }
+}
\ No newline at end of file
--- /dev/null
+/**********************************************************************
+Copyright (c) 2000, 2003 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 implementation
+**********************************************************************/
+package net.sourceforge.phpeclipse.phpeditor;
+
+import org.eclipse.jface.text.BadLocationException;
+import org.eclipse.jface.text.BadPositionCategoryException;
+import org.eclipse.jface.text.Document;
+import org.eclipse.jface.text.ISynchronizable;
+import org.eclipse.jface.text.Position;
+
+
+/**
+ * Document that can also be used by a background reconciler.
+ */
+public class PartiallySynchronizedDocument extends Document implements ISynchronizable {
+
+ private final Object fInternalLockObject= new Object();
+ private Object fLockObject;
+
+ /*
+ * @see org.eclipse.jface.text.ISynchronizable#setLockObject(java.lang.Object)
+ */
+ public void setLockObject(Object lockObject) {
+ fLockObject= lockObject;
+ }
+
+ /*
+ * @see org.eclipse.jface.text.ISynchronizable#getLockObject()
+ */
+ public Object getLockObject() {
+ return fLockObject == null ? fInternalLockObject : fLockObject;
+ }
+
+ /*
+ * @see IDocumentExtension#startSequentialRewrite(boolean)
+ */
+ public void startSequentialRewrite(boolean normalized) {
+ synchronized (getLockObject()) {
+ super.startSequentialRewrite(normalized);
+ }
+ }
+
+ /*
+ * @see IDocumentExtension#stopSequentialRewrite()
+ */
+ public void stopSequentialRewrite() {
+ synchronized (getLockObject()) {
+ super.stopSequentialRewrite();
+ }
+ }
+
+ /*
+ * @see IDocument#get()
+ */
+ public String get() {
+ synchronized (getLockObject()) {
+ return super.get();
+ }
+ }
+
+ /*
+ * @see IDocument#get(int, int)
+ */
+ public String get(int offset, int length) throws BadLocationException {
+ synchronized (getLockObject()) {
+ return super.get(offset, length);
+ }
+ }
+
+ /*
+ * @see IDocument#getChar(int)
+ */
+ public char getChar(int offset) throws BadLocationException {
+ synchronized (getLockObject()) {
+ return super.getChar(offset);
+ }
+ }
+
+ /*
+ * @see IDocument#replace(int, int, String)
+ */
+ public void replace(int offset, int length, String text) throws BadLocationException {
+ synchronized (getLockObject()) {
+ super.replace(offset, length, text);
+ }
+ }
+
+ /*
+ * @see IDocument#set(String)
+ */
+ public void set(String text) {
+ synchronized (getLockObject()) {
+ super.set(text);
+ }
+ }
+
+ /*
+ * @see org.eclipse.jface.text.AbstractDocument#addPosition(java.lang.String, org.eclipse.jface.text.Position)
+ */
+ public void addPosition(String category, Position position) throws BadLocationException, BadPositionCategoryException {
+ synchronized (getLockObject()) {
+ super.addPosition(category, position);
+ }
+ }
+
+ /*
+ * @see org.eclipse.jface.text.AbstractDocument#removePosition(java.lang.String, org.eclipse.jface.text.Position)
+ */
+ public void removePosition(String category, Position position) throws BadPositionCategoryException {
+ synchronized (getLockObject()) {
+ super.removePosition(category, position);
+ }
+ }
+
+ /*
+ * @see org.eclipse.jface.text.AbstractDocument#getPositions(java.lang.String)
+ */
+ public Position[] getPositions(String category) throws BadPositionCategoryException {
+ synchronized (getLockObject()) {
+ return super.getPositions(category);
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+/**********************************************************************
+Copyright (c) 2000, 2003 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 implementation
+**********************************************************************/
+package net.sourceforge.phpeclipse.phpeditor;
+
+import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions;
+import net.sourceforge.phpdt.ui.text.JavaTextTools;
+import net.sourceforge.phpeclipse.PHPeclipsePlugin;
+
+import org.eclipse.core.filebuffers.IDocumentSetupParticipant;
+import org.eclipse.jface.text.IDocument;
+
+/**
+ * The document setup participant for PHPDT.
+ */
+public class SmartyDocumentSetupParticipant implements IDocumentSetupParticipant {
+
+ public SmartyDocumentSetupParticipant() {
+ }
+
+ /*
+ * @see org.eclipse.core.filebuffers.IDocumentSetupParticipant#setup(org.eclipse.jface.text.IDocument)
+ */
+ public void setup(IDocument document) {
+ JavaTextTools tools= PHPeclipsePlugin.getDefault().getJavaTextTools();
+ tools.setupSmartyDocumentPartitioner(document, IPHPPartitions.PHP_PARTITIONING, null); //IPHPPartitions.PHP_PARTITIONING, null);
+ }
+}
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
-
package net.sourceforge.phpeclipse.phpeditor;
+import java.util.HashMap;
+import java.util.Map;
import java.util.ResourceBundle;
import net.sourceforge.phpeclipse.PHPeclipsePlugin;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
+import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextOperationTarget;
import org.eclipse.jface.text.ITextSelection;
+import org.eclipse.jface.text.ITypedRegion;
+import org.eclipse.jface.text.Region;
+import org.eclipse.jface.text.TextUtilities;
+import org.eclipse.jface.text.source.ISourceViewer;
+import org.eclipse.jface.text.source.SourceViewerConfiguration;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.widgets.Display;
/**
- * An action which toggles the single line comment prefixes on the selected lines.
+ * An action which toggles comment prefixes on the selected lines.
*
* @since 3.0
*/
/** The text operation target */
private ITextOperationTarget fOperationTarget;
+ /** The document partitioning */
+ private String fDocumentPartitioning;
/** The comment prefixes */
- private String[] fCommentPrefixes;
+ private Map fPrefixesMap;
/**
* Creates and initializes the action for the given text editor. The action
* (described in <code>ResourceAction</code> constructor), or
* <code>null</code> if none
* @param editor the text editor
- * @see ResourceAction#ResourceAction
+ * @see ResourceAction#ResourceAction(ResourceBundle, String, int)
*/
- public ToggleCommentAction(ResourceBundle bundle, String prefix, ITextEditor editor, String[] commentPrefixes) {
+ public ToggleCommentAction(ResourceBundle bundle, String prefix, ITextEditor editor) {
super(bundle, prefix, editor);
- fCommentPrefixes= commentPrefixes;
}
/**
* Implementation of the <code>IAction</code> prototype. Checks if the selected
- * lines are all commented or not and uncomment/comments them respectively.
+ * lines are all commented or not and uncomments/comments them respectively.
*/
public void run() {
- if (fOperationTarget == null)
+ if (fOperationTarget == null || fDocumentPartitioning == null || fPrefixesMap == null)
return;
ITextEditor editor= getTextEditor();
- if (!(editor instanceof PHPEditor))
+ if (editor == null)
return;
if (!validateEditorInputState())
* Is the given selection single-line commented?
*
* @param selection Selection to check
- * @return <code>true</code> iff all selected lines are single-line commented
+ * @return <code>true</code> iff all selected lines are commented
*/
private boolean isSelectionCommented(ISelection selection) {
if (!(selection instanceof ITextSelection))
return false;
- ITextSelection ts= (ITextSelection) selection;
- if (ts.getStartLine() < 0 || ts.getEndLine() < 0)
+ ITextSelection textSelection= (ITextSelection) selection;
+ if (textSelection.getStartLine() < 0 || textSelection.getEndLine() < 0)
return false;
IDocument document= getTextEditor().getDocumentProvider().getDocument(getTextEditor().getEditorInput());
- OUTER: for (int i= ts.getStartLine(); i <= ts.getEndLine(); i++) {
- for (int j= 0; j < fCommentPrefixes.length; j++) {
- try {
- if (fCommentPrefixes[j].length() == 0)
- continue;
- String s= document.get(document.getLineOffset(i), document.getLineLength(i));
- int index= s.indexOf(fCommentPrefixes[j]);
- if (index >= 0 && s.substring(0, index).trim().length() == 0)
- continue OUTER;
- } catch (BadLocationException e) {
- // should not happen
- PHPeclipsePlugin.log(e);
- }
+
+ try {
+
+ IRegion block= getTextBlockFromSelection(textSelection, document);
+ ITypedRegion[] regions= TextUtilities.computePartitioning(document, fDocumentPartitioning, block.getOffset(), block.getLength(), false);
+
+ int lineCount= 0;
+ int[] lines= new int[regions.length * 2]; // [startline, endline, startline, endline, ...]
+ for (int i= 0, j= 0; i < regions.length; i++, j+= 2) {
+ // start line of region
+ lines[j]= getFirstCompleteLineOfRegion(regions[i], document);
+ // end line of region
+ int length= regions[i].getLength();
+ int offset= regions[i].getOffset() + length;
+ if (length > 0)
+ offset--;
+ lines[j + 1]= (lines[j] == -1 ? -1 : document.getLineOfOffset(offset));
+ lineCount += lines[j + 1] - lines[j] + 1;
}
- return false;
+
+ // Perform the check
+ for (int i= 0, j= 0; i < regions.length; i++, j += 2) {
+ String[] prefixes= (String[]) fPrefixesMap.get(regions[i].getType());
+ if (prefixes != null && prefixes.length > 0 && lines[j] >= 0 && lines[j + 1] >= 0)
+ if (!isBlockCommented(lines[j], lines[j + 1], prefixes, document))
+ return false;
+ }
+
+ return true;
+
+ } catch (BadLocationException x) {
+ // should not happen
+ PHPeclipsePlugin.log(x);
}
- return true;
+
+ return false;
}
/**
+ * Creates a region describing the text block (something that starts at
+ * the beginning of a line) completely containing the current selection.
+ *
+ * @param selection The selection to use
+ * @param document The document
+ * @return the region describing the text block comprising the given selection
+ */
+ private IRegion getTextBlockFromSelection(ITextSelection selection, IDocument document) {
+
+ try {
+ IRegion line= document.getLineInformationOfOffset(selection.getOffset());
+ int length= selection.getLength() == 0 ? line.getLength() : selection.getLength() + (selection.getOffset() - line.getOffset());
+ return new Region(line.getOffset(), length);
+
+ } catch (BadLocationException x) {
+ // should not happen
+ PHPeclipsePlugin.log(x);
+ }
+
+ return null;
+ }
+
+ /**
+ * Returns the index of the first line whose start offset is in the given text range.
+ *
+ * @param region the text range in characters where to find the line
+ * @param document The document
+ * @return the first line whose start index is in the given range, -1 if there is no such line
+ */
+ private int getFirstCompleteLineOfRegion(IRegion region, IDocument document) {
+
+ try {
+
+ int startLine= document.getLineOfOffset(region.getOffset());
+
+ int offset= document.getLineOffset(startLine);
+ if (offset >= region.getOffset())
+ return startLine;
+
+ offset= document.getLineOffset(startLine + 1);
+ return (offset > region.getOffset() + region.getLength() ? -1 : startLine + 1);
+
+ } catch (BadLocationException x) {
+ // should not happen
+ PHPeclipsePlugin.log(x);
+ }
+
+ return -1;
+ }
+
+ /**
+ * Determines whether each line is prefixed by one of the prefixes.
+ *
+ * @param startLine Start line in document
+ * @param endLine End line in document
+ * @param prefixes Possible comment prefixes
+ * @param document The document
+ * @return <code>true</code> iff each line from <code>startLine</code>
+ * to and including <code>endLine</code> is prepended by one
+ * of the <code>prefixes</code>, ignoring whitespace at the
+ * begin of line
+ */
+ private boolean isBlockCommented(int startLine, int endLine, String[] prefixes, IDocument document) {
+
+ try {
+
+ // check for occurrences of prefixes in the given lines
+ for (int i= startLine; i <= endLine; i++) {
+
+ IRegion line= document.getLineInformation(i);
+ String text= document.get(line.getOffset(), line.getLength());
+
+ int[] found= TextUtilities.indexOf(prefixes, text, 0);
+
+ if (found[0] == -1)
+ // found a line which is not commented
+ return false;
+
+ String s= document.get(line.getOffset(), found[0]);
+ s= s.trim();
+ if (s.length() != 0)
+ // found a line which is not commented
+ return false;
+
+ }
+
+ return true;
+
+ } catch (BadLocationException x) {
+ // should not happen
+ PHPeclipsePlugin.log(x);
+ }
+
+ return false;
+ }
+
+ /**
* Implementation of the <code>IUpdate</code> prototype method discovers
* the operation through the current editor's
* <code>ITextOperationTarget</code> adapter, and sets the enabled state
super.setEditor(editor);
fOperationTarget= null;
}
+
+ public void configure(ISourceViewer sourceViewer, SourceViewerConfiguration configuration) {
+ fPrefixesMap= null;
+
+ String[] types= configuration.getConfiguredContentTypes(sourceViewer);
+ Map prefixesMap= new HashMap(types.length);
+ for (int i= 0; i < types.length; i++) {
+ String type= types[i];
+ String[] prefixes= configuration.getDefaultPrefixes(sourceViewer, type);
+ if (prefixes != null && prefixes.length > 0) {
+ int emptyPrefixes= 0;
+ for (int j= 0; j < prefixes.length; j++)
+ if (prefixes[j].length() == 0)
+ emptyPrefixes++;
+
+ if (emptyPrefixes > 0) {
+ String[] nonemptyPrefixes= new String[prefixes.length - emptyPrefixes];
+ for (int j= 0, k= 0; j < prefixes.length; j++) {
+ String prefix= prefixes[j];
+ if (prefix.length() != 0) {
+ nonemptyPrefixes[k]= prefix;
+ k++;
+ }
+ }
+ prefixes= nonemptyPrefixes;
+ }
+
+ prefixesMap.put(type, prefixes);
+ }
+ }
+ fDocumentPartitioning= configuration.getConfiguredDocumentPartitioning(sourceViewer);
+ fPrefixesMap= prefixesMap;
+ }
}
* @see org.eclipse.jdt.internal.ui.javaeditor.IWorkingCopyManagerExtension#setWorkingCopy(org.eclipse.ui.IEditorInput, org.eclipse.jdt.core.ICompilationUnit)
*/
public void setWorkingCopy(IEditorInput input, ICompilationUnit workingCopy) {
- if (fDocumentProvider.isConnected(input)) {
+ if (fDocumentProvider.getDocument(input) != null) {
if (fMap == null)
fMap= new HashMap();
fMap.put(input, workingCopy);
}
}
-
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.IWorkingCopyManagerExtension#removeWorkingCopy(org.eclipse.ui.IEditorInput)
*/