From: khartlage Date: Thu, 19 Aug 2004 21:00:33 +0000 (+0000) Subject: misc changes X-Git-Url: http://git.phpeclipse.com misc changes --- diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/compiler/ITerminalSymbols.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/compiler/ITerminalSymbols.java index e3d1074..fd7fb91 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/compiler/ITerminalSymbols.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/core/compiler/ITerminalSymbols.java @@ -196,4 +196,7 @@ public interface ITerminalSymbols { public final static int TokenNameCLASS_C = 1072; public final static int TokenNameMETHOD_C = 1073; public final static int TokenNameFUNC_C = 1074; + + // special tokens not normally used in the parser + public final static int TokenNamethis_PHP_COMPLETION = 2000; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CompilationUnit.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CompilationUnit.java index 2fc911b..95511d9 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CompilationUnit.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/core/CompilationUnit.java @@ -1095,7 +1095,7 @@ public void reconcile(boolean forceProblemDetection, IProgressMonitor monitor) t // } ReconcileWorkingCopyOperation op = new ReconcileWorkingCopyOperation(this, createAST, astLevel, forceProblemDetection, workingCopyOwner); op.runOperation(monitor); -// return op.ast; +// return op.ast; return null; } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/AbstractToggleLinkingAction.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/AbstractToggleLinkingAction.java new file mode 100644 index 0000000..5c9c025 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/AbstractToggleLinkingAction.java @@ -0,0 +1,43 @@ +/******************************************************************************* + * 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.ui.actions; + +import net.sourceforge.phpdt.internal.ui.IJavaHelpContextIds; +import net.sourceforge.phpdt.internal.ui.PHPUiImages; + +import org.eclipse.jface.action.Action; +import org.eclipse.ui.help.WorkbenchHelp; + + +/** + * This is an action template for actions that toggle whether + * it links its selection to the active editor. + * + * @since 3.0 + */ +public abstract class AbstractToggleLinkingAction extends Action { + + /** + * Constructs a new action. + */ + public AbstractToggleLinkingAction() { + super(ActionMessages.getString("ToggleLinkingAction.label")); //$NON-NLS-1$ + setDescription(ActionMessages.getString("ToggleLinkingAction.description")); //$NON-NLS-1$ + setToolTipText(ActionMessages.getString("ToggleLinkingAction.tooltip")); //$NON-NLS-1$ + PHPUiImages.setLocalImageDescriptors(this, "synced.gif"); //$NON-NLS-1$ + WorkbenchHelp.setHelp(this, IJavaHelpContextIds.LINK_EDITOR_ACTION); + } + + /** + * Runs the action. + */ + public abstract void run(); +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/ActionMessages.properties b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/ActionMessages.properties index b51f21d..bc3ebe5 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/ActionMessages.properties +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/actions/ActionMessages.properties @@ -230,8 +230,6 @@ ActionUtil.notOnBuildPath.message=The resource is not on the build path of a PHP SelectAllAction.label= Select A&ll SelectAllAction.tooltip= Select All -AddJARToClasspathAction.label=Add to Build Path -AddJARToClasspathAction.toolTip=Add JAR to the PHP build path -AddJARToClasspathAction.progressMessage=Adding to build path... -AddJARToClasspathAction.error.title=Add To Build Path -AddJARToClasspathAction.error.message=Problems occurred while adding to the build path. +ToggleLinkingAction.label=Lin&k With Editor +ToggleLinkingAction.tooltip=Link with Editor +ToggleLinkingAction.description=Link with active editor \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaCompositeReconcilingStrategy.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaCompositeReconcilingStrategy.java new file mode 100644 index 0000000..2a77746 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaCompositeReconcilingStrategy.java @@ -0,0 +1,138 @@ +/******************************************************************************* + * 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.ui.text; + +import net.sourceforge.phpdt.internal.ui.text.java.IProblemRequestorExtension; +import net.sourceforge.phpdt.internal.ui.text.java.JavaReconcilingStrategy; +import net.sourceforge.phpdt.internal.ui.text.spelling.SpellReconcileStrategy; +import net.sourceforge.phpdt.ui.PreferenceConstants; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.reconciler.DirtyRegion; +import org.eclipse.jface.text.reconciler.IReconcilingStrategy; +import org.eclipse.jface.text.source.IAnnotationModel; +import org.eclipse.ui.texteditor.IDocumentProvider; +import org.eclipse.ui.texteditor.ITextEditor; + +/** + * Reconciling strategy for Java code. This is a composite strategy containing the + * regular java model reconciler and the comment spell checking strategy. + * + * @since 3.0 + */ +public class JavaCompositeReconcilingStrategy extends CompositeReconcilingStrategy { + + private ITextEditor fEditor; + private JavaReconcilingStrategy fJavaStrategy; + + /** + * Creates a new Java reconciling strategy. + * + * @param editor the editor of the strategy's reconciler + * @param documentPartitioning the document partitioning this strategy uses for configuration + */ + public JavaCompositeReconcilingStrategy(ITextEditor editor, String documentPartitioning) { + fEditor= editor; + fJavaStrategy= new JavaReconcilingStrategy(editor); + setReconcilingStrategies(new IReconcilingStrategy[] { + fJavaStrategy, + new SpellReconcileStrategy(editor, documentPartitioning, PreferenceConstants.getPreferenceStore()) + }); + } + + /** + * Returns the problem requestor for the editor's input element. + * + * @return the problem requestor for the editor's input element + */ + private IProblemRequestorExtension getProblemRequestorExtension() { + IDocumentProvider p= fEditor.getDocumentProvider(); + if (p == null) { + // work around for https://bugs.eclipse.org/bugs/show_bug.cgi?id=51522 + p= PHPeclipsePlugin.getDefault().getCompilationUnitDocumentProvider(); + } + IAnnotationModel m= p.getAnnotationModel(fEditor.getEditorInput()); + if (m instanceof IProblemRequestorExtension) + return (IProblemRequestorExtension) m; + return null; + } + + /* + * @see org.eclipse.jface.text.reconciler.CompositeReconcilingStrategy#reconcile(org.eclipse.jface.text.reconciler.DirtyRegion, org.eclipse.jface.text.IRegion) + */ + public void reconcile(DirtyRegion dirtyRegion, IRegion subRegion) { + IProblemRequestorExtension e= getProblemRequestorExtension(); + if (e != null) { + try { + e.beginReportingSequence(); + super.reconcile(dirtyRegion, subRegion); + } finally { + e.endReportingSequence(); + } + } else { + super.reconcile(dirtyRegion, subRegion); + } + } + + /* + * @see org.eclipse.jface.text.reconciler.CompositeReconcilingStrategy#reconcile(org.eclipse.jface.text.IRegion) + */ + public void reconcile(IRegion partition) { + IProblemRequestorExtension e= getProblemRequestorExtension(); + if (e != null) { + try { + e.beginReportingSequence(); + super.reconcile(partition); + } finally { + e.endReportingSequence(); + } + } else { + super.reconcile(partition); + } + } + + /** + * Tells this strategy whether to inform its listeners. + * + * @param notify true if listeners should be notified + */ + public void notifyListeners(boolean notify) { + fJavaStrategy.notifyListeners(notify); + } + + /* + * @see org.eclipse.jface.text.reconciler.CompositeReconcilingStrategy#initialReconcile() + */ + public void initialReconcile() { + IProblemRequestorExtension e= getProblemRequestorExtension(); + if (e != null) { + try { + e.beginReportingSequence(); + super.initialReconcile(); + } finally { + e.endReportingSequence(); + } + } else { + super.initialReconcile(); + } + } + + /** + * Called before reconciling is started. + * + * @since 3.0 + */ + public void aboutToBeReconciled() { + fJavaStrategy.aboutToBeReconciled(); + + } +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaReconciler.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaReconciler.java index 880922e..a2f5b2c 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaReconciler.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/JavaReconciler.java @@ -12,12 +12,29 @@ package net.sourceforge.phpdt.internal.ui.text; -import net.sourceforge.phpdt.internal.ui.text.java.JavaReconcilingStrategy; +import net.sourceforge.phpdt.core.ElementChangedEvent; +import net.sourceforge.phpdt.core.IElementChangedListener; +import net.sourceforge.phpdt.core.JavaCore; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; +import net.sourceforge.phpeclipse.phpeditor.PHPUnitEditor; +import org.eclipse.core.resources.IMarkerDelta; +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.jface.text.IDocument; import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.reconciler.IReconcilingStrategy; +import org.eclipse.jface.text.reconciler.DirtyRegion; import org.eclipse.jface.text.reconciler.MonoReconciler; +import org.eclipse.swt.events.ShellAdapter; +import org.eclipse.swt.events.ShellEvent; +import org.eclipse.swt.events.ShellListener; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.IEditorInput; +import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.IPartListener; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchPartSite; @@ -25,7 +42,6 @@ import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.texteditor.ITextEditor; - /** * A reconciler that is also activated on editor activation. */ @@ -34,58 +50,171 @@ public class JavaReconciler extends MonoReconciler { /** * Internal part listener for activating the reconciler. */ - class PartListener implements IPartListener { + private class PartListener implements IPartListener { /* - * @see IPartListener#partActivated(IWorkbenchPart) + * @see org.eclipse.ui.IPartListener#partActivated(org.eclipse.ui.IWorkbenchPart) */ public void partActivated(IWorkbenchPart part) { - if (part == fTextEditor) + if (part == fTextEditor && hasJavaModelChanged()) JavaReconciler.this.forceReconciling(); } /* - * @see IPartListener#partBroughtToTop(IWorkbenchPart) + * @see org.eclipse.ui.IPartListener#partBroughtToTop(org.eclipse.ui.IWorkbenchPart) */ public void partBroughtToTop(IWorkbenchPart part) { } /* - * @see IPartListener#partClosed(IWorkbenchPart) + * @see org.eclipse.ui.IPartListener#partClosed(org.eclipse.ui.IWorkbenchPart) */ public void partClosed(IWorkbenchPart part) { } /* - * @see IPartListener#partDeactivated(IWorkbenchPart) + * @see org.eclipse.ui.IPartListener#partDeactivated(org.eclipse.ui.IWorkbenchPart) */ public void partDeactivated(IWorkbenchPart part) { + if (part == fTextEditor) + setJavaModelChanged(false); } /* - * @see IPartListener#partOpened(IWorkbenchPart) + * @see org.eclipse.ui.IPartListener#partOpened(org.eclipse.ui.IWorkbenchPart) */ public void partOpened(IWorkbenchPart part) { } - }; + } + + /** + * Internal Shell activation listener for activating the reconciler. + */ + private class ActivationListener extends ShellAdapter { + + private Control fControl; + + public ActivationListener(Control control) { + fControl= control; + } + + /* + * @see org.eclipse.swt.events.ShellListener#shellActivated(org.eclipse.swt.events.ShellEvent) + */ + public void shellActivated(ShellEvent e) { + if (!fControl.isDisposed() && fControl.isVisible() && hasJavaModelChanged()) + JavaReconciler.this.forceReconciling(); + } + + /* + * @see org.eclipse.swt.events.ShellListener#shellDeactivated(org.eclipse.swt.events.ShellEvent) + */ + public void shellDeactivated(ShellEvent e) { + setJavaModelChanged(false); + } + } + + /** + * Internal Java element changed listener + * + * @since 3.0 + */ + private class ElementChangedListener implements IElementChangedListener { + /* + * @see org.eclipse.jdt.core.IElementChangedListener#elementChanged(org.eclipse.jdt.core.ElementChangedEvent) + */ + public void elementChanged(ElementChangedEvent event) { + setJavaModelChanged(true); + } + } + + /** + * Internal resource change listener. + * + * @since 3.0 + */ + class ResourceChangeListener implements IResourceChangeListener { + + private IResource getResource() { + IEditorInput input= fTextEditor.getEditorInput(); + if (input instanceof IFileEditorInput) { + IFileEditorInput fileInput= (IFileEditorInput) input; + return fileInput.getFile(); + } + return null; + } + + /* + * @see IResourceChangeListener#resourceChanged(org.eclipse.core.resources.IResourceChangeEvent) + */ + public void resourceChanged(IResourceChangeEvent e) { + IResourceDelta delta= e.getDelta(); + IResource resource= getResource(); + if (delta != null && resource != null) { + IResourceDelta child= delta.findMember(resource.getFullPath()); + if (child != null) { + IMarkerDelta[] deltas= child.getMarkerDeltas(); + if (deltas.length > 0) + forceReconciling(); + } + } + } + } /** The reconciler's editor */ private ITextEditor fTextEditor; /** The part listener */ private IPartListener fPartListener; - + /** The shell listener */ + private ShellListener fActivationListener; + /** + * The mutex that keeps us from running multiple reconcilers on one editor. + * TODO remove once we have ensured that there is only one reconciler per editor. + */ + private Object fMutex; + /** + * The Java element changed listener. + * @since 3.0 + */ + private IElementChangedListener fJavaElementChangedListener; + /** + * Tells whether the Java model sent out a changed event. + * @since 3.0 + */ + private volatile boolean fHasJavaModelChanged= true; + /** + * The resource change listener. + * @since 3.0 + */ + private IResourceChangeListener fResourceChangeListener; + private boolean fIninitalProcessDone= false; /** * Creates a new reconciler. */ - public JavaReconciler(ITextEditor editor, IReconcilingStrategy strategy, boolean isIncremental) { + public JavaReconciler(ITextEditor editor, JavaCompositeReconcilingStrategy strategy, boolean isIncremental) { super(strategy, isIncremental); fTextEditor= editor; + + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=63898 + // when re-using editors, a new reconciler is set up by the source viewer + // and the old one uninstalled. However, the old reconciler may still be + // running. + // To avoid having to reconcilers calling CompilationUnitEditor.reconciled, + // we synchronized on a lock object provided by the editor. + // The critical section is really the entire run() method of the reconciler + // thread, but synchronizing process() only will keep JavaReconcilingStrategy + // from running concurrently on the same editor. + // TODO remove once we have ensured that there is only one reconciler per editor. + if (editor instanceof PHPUnitEditor) + fMutex= ((PHPUnitEditor) editor).getReconcilerLock(); + else + fMutex= new Object(); // Null Object } /* - * @see IReconciler#install(ITextViewer) + * @see org.eclipse.jface.text.reconciler.IReconciler#install(org.eclipse.jface.text.ITextViewer) */ public void install(ITextViewer textViewer) { super.install(textViewer); @@ -94,10 +223,21 @@ public class JavaReconciler extends MonoReconciler { IWorkbenchPartSite site= fTextEditor.getSite(); IWorkbenchWindow window= site.getWorkbenchWindow(); window.getPartService().addPartListener(fPartListener); + + fActivationListener= new ActivationListener(textViewer.getTextWidget()); + Shell shell= window.getShell(); + shell.addShellListener(fActivationListener); + + fJavaElementChangedListener= new ElementChangedListener(); + JavaCore.addElementChangedListener(fJavaElementChangedListener); + + fResourceChangeListener= new ResourceChangeListener(); + IWorkspace workspace= PHPeclipsePlugin.getWorkspace(); + workspace.addResourceChangeListener(fResourceChangeListener); } /* - * @see IReconciler#uninstall() + * @see org.eclipse.jface.text.reconciler.IReconciler#uninstall() */ public void uninstall() { @@ -106,30 +246,196 @@ public class JavaReconciler extends MonoReconciler { window.getPartService().removePartListener(fPartListener); fPartListener= null; + Shell shell= window.getShell(); + if (shell != null && !shell.isDisposed()) + shell.removeShellListener(fActivationListener); + fActivationListener= null; + + JavaCore.removeElementChangedListener(fJavaElementChangedListener); + fJavaElementChangedListener= null; + + IWorkspace workspace= PHPeclipsePlugin.getWorkspace(); + workspace.removeResourceChangeListener(fResourceChangeListener); + fResourceChangeListener= null; + super.uninstall(); } - /* - * @see AbstractReconciler#forceReconciling() + /* + * @see org.eclipse.jface.text.reconciler.AbstractReconciler#forceReconciling() */ protected void forceReconciling() { + if (!fIninitalProcessDone) + return; + super.forceReconciling(); - IReconcilingStrategy strategy= getReconcilingStrategy(IDocument.DEFAULT_CONTENT_TYPE); - if (strategy instanceof JavaReconcilingStrategy) { - JavaReconcilingStrategy java= (JavaReconcilingStrategy) strategy; - java.notifyParticipants(false); - } + JavaCompositeReconcilingStrategy strategy= (JavaCompositeReconcilingStrategy) getReconcilingStrategy(IDocument.DEFAULT_CONTENT_TYPE); + strategy.notifyListeners(false); } /* - * @see AbstractReconciler#reconcilerReset() + * @see org.eclipse.jface.text.reconciler.AbstractReconciler#aboutToReconcile() + * @since 3.0 + */ + protected void aboutToBeReconciled() { + JavaCompositeReconcilingStrategy strategy= (JavaCompositeReconcilingStrategy) getReconcilingStrategy(IDocument.DEFAULT_CONTENT_TYPE); + strategy.aboutToBeReconciled(); + } + + /* + * @see org.eclipse.jface.text.reconciler.AbstractReconciler#reconcilerReset() */ protected void reconcilerReset() { super.reconcilerReset(); - IReconcilingStrategy strategy= getReconcilingStrategy(IDocument.DEFAULT_CONTENT_TYPE); - if (strategy instanceof JavaReconcilingStrategy) { - JavaReconcilingStrategy java= (JavaReconcilingStrategy) strategy; - java.notifyParticipants(true); + JavaCompositeReconcilingStrategy strategy= (JavaCompositeReconcilingStrategy) getReconcilingStrategy(IDocument.DEFAULT_CONTENT_TYPE); + strategy.notifyListeners(true); + } + + /* + * @see org.eclipse.jface.text.reconciler.MonoReconciler#initialProcess() + */ + protected void initialProcess() { + // TODO remove once we have ensured that there is only one reconciler per editor. + synchronized (fMutex) { + super.initialProcess(); + } + fIninitalProcessDone= true; + } + + /* + * @see org.eclipse.jface.text.reconciler.MonoReconciler#process(org.eclipse.jface.text.reconciler.DirtyRegion) + */ + protected void process(DirtyRegion dirtyRegion) { + // TODO remove once we have ensured that there is only one reconciler per editor. + synchronized (fMutex) { + super.process(dirtyRegion); } } + + /** + * Tells whether the Java Model has changed or not. + * + * @return true iff the Java Model has changed + * @since 3.0 + */ + private synchronized boolean hasJavaModelChanged() { + return fHasJavaModelChanged; + } + + /** + * Sets whether the Java Model has changed or not. + * + * @param state true iff the java model has changed + * @since 3.0 + */ + private synchronized void setJavaModelChanged(boolean state) { + fHasJavaModelChanged= state; + } } +///** +// * A reconciler that is also activated on editor activation. +// */ +//public class JavaReconciler extends MonoReconciler { +// +// /** +// * Internal part listener for activating the reconciler. +// */ +// class PartListener implements IPartListener { +// +// /* +// * @see IPartListener#partActivated(IWorkbenchPart) +// */ +// public void partActivated(IWorkbenchPart part) { +// if (part == fTextEditor) +// JavaReconciler.this.forceReconciling(); +// } +// +// /* +// * @see IPartListener#partBroughtToTop(IWorkbenchPart) +// */ +// public void partBroughtToTop(IWorkbenchPart part) { +// } +// +// /* +// * @see IPartListener#partClosed(IWorkbenchPart) +// */ +// public void partClosed(IWorkbenchPart part) { +// } +// +// /* +// * @see IPartListener#partDeactivated(IWorkbenchPart) +// */ +// public void partDeactivated(IWorkbenchPart part) { +// } +// +// /* +// * @see IPartListener#partOpened(IWorkbenchPart) +// */ +// public void partOpened(IWorkbenchPart part) { +// } +// }; +// +// +// /** The reconciler's editor */ +// private ITextEditor fTextEditor; +// /** The part listener */ +// private IPartListener fPartListener; +// +// +// /** +// * Creates a new reconciler. +// */ +// public JavaReconciler(ITextEditor editor, IReconcilingStrategy strategy, boolean isIncremental) { +// super(strategy, isIncremental); +// fTextEditor= editor; +// } +// +// /* +// * @see IReconciler#install(ITextViewer) +// */ +// public void install(ITextViewer textViewer) { +// super.install(textViewer); +// +// fPartListener= new PartListener(); +// IWorkbenchPartSite site= fTextEditor.getSite(); +// IWorkbenchWindow window= site.getWorkbenchWindow(); +// window.getPartService().addPartListener(fPartListener); +// } +// +// /* +// * @see IReconciler#uninstall() +// */ +// public void uninstall() { +// +// IWorkbenchPartSite site= fTextEditor.getSite(); +// IWorkbenchWindow window= site.getWorkbenchWindow(); +// window.getPartService().removePartListener(fPartListener); +// fPartListener= null; +// +// super.uninstall(); +// } +// +// /* +// * @see AbstractReconciler#forceReconciling() +// */ +// protected void forceReconciling() { +// super.forceReconciling(); +// IReconcilingStrategy strategy= getReconcilingStrategy(IDocument.DEFAULT_CONTENT_TYPE); +// if (strategy instanceof JavaReconcilingStrategy) { +// JavaReconcilingStrategy java= (JavaReconcilingStrategy) strategy; +// java.notifyParticipants(false); +// } +// } +// +// /* +// * @see AbstractReconciler#reconcilerReset() +// */ +// protected void reconcilerReset() { +// super.reconcilerReset(); +// IReconcilingStrategy strategy= getReconcilingStrategy(IDocument.DEFAULT_CONTENT_TYPE); +// if (strategy instanceof JavaReconcilingStrategy) { +// JavaReconcilingStrategy java= (JavaReconcilingStrategy) strategy; +// java.notifyParticipants(true); +// } +// } +//} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/IProblemRequestorExtension.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/IProblemRequestorExtension.java index 2ffc389..a5af585 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/IProblemRequestorExtension.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/IProblemRequestorExtension.java @@ -32,4 +32,20 @@ public interface IProblemRequestorExtension { * @param isActive the state of this problem requestor */ void setIsActive(boolean isActive); + + /** + * Informs the problem requestor that a sequence of reportings is about to start. While + * a sequence is active, multiple peering calls of beginReporting and + * endReporting can appear. + * + * @since 3.0 + */ + void beginReportingSequence(); + + /** + * Informs the problem requestor that the sequence of reportings has been finished. + * + * @since 3.0 + */ + void endReportingSequence(); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/JavaReconcilingStrategy.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/JavaReconcilingStrategy.java index d12ddf9..8294154 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/JavaReconcilingStrategy.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/java/JavaReconcilingStrategy.java @@ -1,13 +1,10 @@ -/******************************************************************************* - * 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 +/*********************************************************************************************************************************** + * 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 - *******************************************************************************/ + * Contributors: IBM Corporation - initial API and implementation + **********************************************************************************************************************************/ package net.sourceforge.phpdt.internal.ui.text.java; @@ -17,6 +14,7 @@ import net.sourceforge.phpdt.ui.IWorkingCopyManager; import net.sourceforge.phpeclipse.PHPeclipsePlugin; import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.reconciler.DirtyRegion; @@ -31,14 +29,24 @@ public class JavaReconcilingStrategy implements IReconcilingStrategy, IReconcili private ITextEditor fEditor; private IWorkingCopyManager fManager; + private IDocumentProvider fDocumentProvider; + private IProgressMonitor fProgressMonitor; + private boolean fNotify = true; + private IJavaReconcilingListener fJavaReconcilingListener; + + private boolean fIsJavaReconcilingListener; + public JavaReconcilingStrategy(ITextEditor editor) { fEditor = editor; fManager = PHPeclipsePlugin.getDefault().getWorkingCopyManager(); fDocumentProvider = PHPeclipsePlugin.getDefault().getCompilationUnitDocumentProvider(); + fIsJavaReconcilingListener = fEditor instanceof IJavaReconcilingListener; + if (fIsJavaReconcilingListener) + fJavaReconcilingListener = (IJavaReconcilingListener) fEditor; } private IProblemRequestorExtension getProblemRequestorExtension() { @@ -49,7 +57,7 @@ public class JavaReconcilingStrategy implements IReconcilingStrategy, IReconcili } private void reconcile() { - // // try { + // // try { // // /* fix for missing cancel flag communication */ // IProblemRequestorExtension extension = getProblemRequestorExtension(); @@ -57,9 +65,9 @@ public class JavaReconcilingStrategy implements IReconcilingStrategy, IReconcili // extension.setProgressMonitor(fProgressMonitor); // // // reconcile - //// synchronized (unit) { - //// unit.reconcile(true, fProgressMonitor); - //// } + //// synchronized (unit) { + //// unit.reconcile(true, fProgressMonitor); + //// } // // Parser parser = new Parser(); // parser.initializeScanner(); @@ -67,7 +75,7 @@ public class JavaReconcilingStrategy implements IReconcilingStrategy, IReconcili // String text = fEditor.getDocumentProvider().getDocument(fEditor.getEditorInput()).get(); // parser.init(text); // parser.reportSyntaxError(); - //// checkAndReportBracketAnomalies(parser.problemReporter()); + //// checkAndReportBracketAnomalies(parser.problemReporter()); // // /* fix for missing cancel flag communication */ // if (extension != null) @@ -84,37 +92,52 @@ public class JavaReconcilingStrategy implements IReconcilingStrategy, IReconcili // } // JDT implementation: - ICompilationUnit unit = fManager.getWorkingCopy(fEditor.getEditorInput()); - if (unit != null) { - try { - - /* fix for missing cancel flag communication */ - IProblemRequestorExtension extension = getProblemRequestorExtension(); - if (extension != null) - extension.setProgressMonitor(fProgressMonitor); + try { + ICompilationUnit unit = fManager.getWorkingCopy(fEditor.getEditorInput()); + if (unit != null) { + try { - // reconcile - synchronized (unit) { - unit.reconcile(true, fProgressMonitor); - } + /* fix for missing cancel flag communication */ + IProblemRequestorExtension extension = getProblemRequestorExtension(); + if (extension != null) + extension.setProgressMonitor(fProgressMonitor); - /* fix for missing cancel flag communication */ - if (extension != null) - extension.setProgressMonitor(null); + // reconcile + synchronized (unit) { + unit.reconcile(true, fProgressMonitor); + } - // update participants - try { - if (fEditor instanceof IReconcilingParticipant && fNotify && !fProgressMonitor.isCanceled()) { - IReconcilingParticipant p = (IReconcilingParticipant) fEditor; - p.reconciled(); + /* fix for missing cancel flag communication */ + if (extension != null) + extension.setProgressMonitor(null); + + // update participants + try { + if (fEditor instanceof IReconcilingParticipant && fNotify && !fProgressMonitor.isCanceled()) { + IReconcilingParticipant p = (IReconcilingParticipant) fEditor; + p.reconciled(); + } + } finally { + fNotify = true; } - } finally { - fNotify = true; - } - } catch (JavaModelException x) { - // swallow exception + } catch (JavaModelException x) { + // swallow exception + } + } + } finally { + // Always notify listeners, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=55969 for the final solution + try { + if (fIsJavaReconcilingListener) { + IProgressMonitor pm = fProgressMonitor; + if (pm == null) + pm = new NullProgressMonitor(); + fJavaReconcilingListener.reconciled(null, !fNotify, pm); + } + } finally { + fNotify = true; } + } } @@ -155,9 +178,30 @@ public class JavaReconcilingStrategy implements IReconcilingStrategy, IReconcili /** * Tells this strategy whether to inform its participants. * - * @param notify true if participant should be notified + * @param notify + * true if participant should be notified */ public void notifyParticipants(boolean notify) { fNotify = notify; } -} + + /** + * Tells this strategy whether to inform its listeners. + * + * @param notify + * true if listeners should be notified + */ + public void notifyListeners(boolean notify) { + fNotify = notify; + } + + /** + * Called before reconciling is started. + * + * @since 3.0 + */ + public void aboutToBeReconciled() { + if (fIsJavaReconcilingListener) + fJavaReconcilingListener.aboutToBeReconciled(); + } +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/DeclarationEngine.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/DeclarationEngine.java index f3f9132..e7c66c1 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/DeclarationEngine.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/template/DeclarationEngine.java @@ -35,7 +35,7 @@ public class DeclarationEngine { private int fLastSignificantToken; private IFile fFile; - private String fFileName; +// private String fFileName; /** * Creates the template engine for a particular context type. @@ -47,11 +47,11 @@ public class DeclarationEngine { fLastSignificantToken = lastSignificantToken; fFile = file; - if (fFile != null) { - fFileName = fFile.getFullPath().toString(); - } else { - fFileName = ""; - } +// if (fFile != null) { +// fFileName = fFile.getFullPath().toString(); +// } else { +// fFileName = ""; +// } } /** @@ -128,9 +128,15 @@ public class DeclarationEngine { if (type != PHPIdentifierLocation.METHOD && type != PHPIdentifierLocation.VARIABLE) { continue; // for loop } - if (!fFileName.equals(location.getFilename())) { + break; + case ITerminalSymbols.TokenNamethis_PHP_COMPLETION: + if (type != PHPIdentifierLocation.METHOD && type != PHPIdentifierLocation.VARIABLE) { continue; // for loop } + // check all filenames of the subclasses +// if (!fFileName.equals(location.getFilename())) { +// continue; // for loop +// } break; case ITerminalSymbols.TokenNamenew : if (type != PHPIdentifierLocation.CLASS && type != PHPIdentifierLocation.CONSTRUCTOR) { diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/builder/IdentifierIndexManager.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/builder/IdentifierIndexManager.java index 6772af2..262d596 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/builder/IdentifierIndexManager.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/builder/IdentifierIndexManager.java @@ -1,4 +1,5 @@ package net.sourceforge.phpeclipse.builder; + import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.FileNotFoundException; @@ -28,6 +29,7 @@ import net.sourceforge.phpeclipse.obfuscator.PHPIdentifier; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IStatus; + /** * Manages the identifer index information for a specific project * @@ -35,27 +37,29 @@ import org.eclipse.core.runtime.IStatus; public class IdentifierIndexManager { public class LineCreator implements ITerminalSymbols { private Scanner fScanner; + private int fToken; + public LineCreator() { fScanner = new Scanner(true, false, false, false, true, null, null); } + /** * Add the information of the current identifier to the line * * @param typeOfIdentifier - * the type of the identifier ('c'lass, 'd'efine, 'f'unction, - * 'm'ethod(class), 'v'ariable(class) 'g'lobal variable) + * the type of the identifier ('c'lass, 'd'efine, 'f'unction, 'm'ethod(class), 'v'ariable(class) 'g'lobal variable) * @param identifier - * current identifier + * current identifier * @param line - * Buffer for the current index line + * Buffer for the current index line * @param phpdocOffset - * the offset of the PHPdoc comment if available + * the offset of the PHPdoc comment if available * @param phpdocLength - * the length of the PHPdoc comment if available + * the length of the PHPdoc comment if available */ - private void addIdentifierInformation(char typeOfIdentifier, - char[] identifier, StringBuffer line, int phpdocOffset, int phpdocLength) { + private void addIdentifierInformation(char typeOfIdentifier, char[] identifier, StringBuffer line, int phpdocOffset, + int phpdocLength) { line.append('\t'); line.append(typeOfIdentifier); line.append(identifier); @@ -68,6 +72,23 @@ public class IdentifierIndexManager { line.append(phpdocLength); } } + + private void addClassVariableInformation(char typeOfIdentifier, char[] identifier, StringBuffer line, int phpdocOffset, + int phpdocLength) { + line.append('\t'); + line.append(typeOfIdentifier); + line.append(identifier); + line.append("\to"); // Offset + // we don't store the '$' in the index for class variables: + line.append(fScanner.getCurrentTokenStartPosition()+1); + if (phpdocOffset >= 0) { + line.append("\tp"); // phpdoc offset + line.append(phpdocOffset); + line.append("\tl"); // phpdoc length + line.append(phpdocLength); + } + } + /** * Get the next token from input */ @@ -77,19 +98,18 @@ public class IdentifierIndexManager { if (Scanner.DEBUG) { int currentEndPosition = fScanner.getCurrentTokenEndPosition(); int currentStartPosition = fScanner.getCurrentTokenStartPosition(); - System.out.print(currentStartPosition + "," + currentEndPosition - + ": "); + System.out.print(currentStartPosition + "," + currentEndPosition + ": "); System.out.println(fScanner.toStringAction(fToken)); } return; } catch (InvalidInputException e) { // ignore errors -// e.printStackTrace(); + // e.printStackTrace(); } fToken = TokenNameERROR; } - private void parseDeclarations(char[] parent, StringBuffer buf, - boolean goBack) { + + private void parseDeclarations(char[] parent, StringBuffer buf, boolean goBack) { char[] ident; char[] classVariable; int counter = 0; @@ -100,22 +120,23 @@ public class IdentifierIndexManager { phpdocOffset = -1; if (fToken == TokenNameCOMMENT_PHPDOC) { phpdocOffset = fScanner.getCurrentTokenStartPosition(); - phpdocLength = fScanner.getCurrentTokenEndPosition() - - fScanner.getCurrentTokenStartPosition() + 1; + phpdocLength = fScanner.getCurrentTokenEndPosition() - fScanner.getCurrentTokenStartPosition() + 1; getNextToken(); if (fToken == TokenNameEOF || fToken == TokenNameERROR) { break; } } - if (fToken == TokenNamevar || fToken == TokenNamepublic + if (fToken == TokenNamevar || fToken == TokenNamestatic || fToken == TokenNamefinal || fToken == TokenNamepublic || fToken == TokenNameprotected || fToken == TokenNameprivate) { - getNextToken(); + while (fToken == TokenNamevar || fToken == TokenNamestatic || fToken == TokenNamefinal || fToken == TokenNamepublic + || fToken == TokenNameprotected || fToken == TokenNameprivate) { + getNextToken(); + } if (fToken == TokenNameVariable) { ident = fScanner.getCurrentIdentifierSource(); classVariable = new char[ident.length - 1]; System.arraycopy(ident, 1, classVariable, 0, ident.length - 1); - addIdentifierInformation('v', classVariable, buf, phpdocOffset, - phpdocLength); + addClassVariableInformation('v', classVariable, buf, phpdocOffset, phpdocLength); getNextToken(); } } else if (fToken == TokenNamefunction) { @@ -127,33 +148,28 @@ public class IdentifierIndexManager { ident = fScanner.getCurrentIdentifierSource(); if (parent != null && equalCharArrays(parent, ident)) { // constructor function - addIdentifierInformation('k', ident, buf, phpdocOffset, - phpdocLength); + addIdentifierInformation('k', ident, buf, phpdocOffset, phpdocLength); } else { if (parent != null) { // class method function - addIdentifierInformation('m', ident, buf, phpdocOffset, - phpdocLength); + addIdentifierInformation('m', ident, buf, phpdocOffset, phpdocLength); } else { // nested function ?! - addIdentifierInformation('f', ident, buf, phpdocOffset, - phpdocLength); + addIdentifierInformation('f', ident, buf, phpdocOffset, phpdocLength); } } getNextToken(); parseDeclarations(null, buf, true); } - } else if (fToken == TokenNameclass) { + } else if (fToken == TokenNameclass || fToken == TokenNameinterface) { getNextToken(); if (fToken == TokenNameIdentifier) { ident = fScanner.getCurrentIdentifierSource(); - addIdentifierInformation('c', ident, buf, phpdocOffset, - phpdocLength); + addIdentifierInformation('c', ident, buf, phpdocOffset, phpdocLength); getNextToken(); //skip tokens for classname, extends and others until we have // the opening '{' - while (fToken != TokenNameLBRACE && fToken != TokenNameEOF - && fToken != TokenNameERROR) { + while (fToken != TokenNameLBRACE && fToken != TokenNameEOF && fToken != TokenNameERROR) { getNextToken(); } parseDeclarations(ident, buf, true); @@ -161,34 +177,25 @@ public class IdentifierIndexManager { } else if (fToken == TokenNameIdentifier) { ident = fScanner.getCurrentIdentifierSource(); getNextToken(); - if (ident.length==6 && - ident[0]=='d' && - ident[1]=='e' && - ident[2]=='f' && - ident[3]=='i' && - ident[4]=='n' && - ident[5]=='e') { + if (ident.length == 6 && ident[0] == 'd' && ident[1] == 'e' && ident[2] == 'f' && ident[3] == 'i' && ident[4] == 'n' + && ident[5] == 'e') { if (fToken == TokenNameLPAREN) { getNextToken(); if (fToken == TokenNameStringDoubleQuote) { ident = fScanner.getCurrentStringLiteralSource(); - addIdentifierInformation('d', ident, buf, phpdocOffset, - phpdocLength); + addIdentifierInformation('d', ident, buf, phpdocOffset, phpdocLength); getNextToken(); } } } } else if (fToken == TokenNameglobal) { // global variable - while (fToken != TokenNameEOF && fToken != TokenNameERROR && - fToken != TokenNameSEMICOLON && - fToken != TokenNameLBRACE && - fToken != TokenNameRBRACE ) { - getNextToken(); + while (fToken != TokenNameEOF && fToken != TokenNameERROR && fToken != TokenNameSEMICOLON && fToken != TokenNameLBRACE + && fToken != TokenNameRBRACE) { + getNextToken(); if (fToken == TokenNameVariable) { ident = fScanner.getCurrentIdentifierSource(); - addIdentifierInformation('g', ident, buf, phpdocOffset, - phpdocLength); + addIdentifierInformation('g', ident, buf, phpdocOffset, phpdocLength); } } } else if (fToken == TokenNameLBRACE) { @@ -209,6 +216,7 @@ public class IdentifierIndexManager { e.printStackTrace(); } } + synchronized public void parseIdentifiers(char[] charArray, StringBuffer buf) { char[] ident; String identifier; @@ -224,8 +232,7 @@ public class IdentifierIndexManager { phpdocOffset = -1; if (fToken == TokenNameCOMMENT_PHPDOC) { phpdocOffset = fScanner.getCurrentTokenStartPosition(); - phpdocLength = fScanner.getCurrentTokenEndPosition() - - fScanner.getCurrentTokenStartPosition() + 1; + phpdocLength = fScanner.getCurrentTokenEndPosition() - fScanner.getCurrentTokenStartPosition() + 1; getNextToken(); if (fToken == TokenNameEOF || fToken == TokenNameERROR) { break; @@ -238,22 +245,19 @@ public class IdentifierIndexManager { } if (fToken == TokenNameIdentifier) { ident = fScanner.getCurrentIdentifierSource(); - addIdentifierInformation('f', ident, buf, phpdocOffset, - phpdocLength); + addIdentifierInformation('f', ident, buf, phpdocOffset, phpdocLength); getNextToken(); parseDeclarations(null, buf, true); } - } else if (fToken == TokenNameclass) { + } else if (fToken == TokenNameclass || fToken == TokenNameinterface) { getNextToken(); if (fToken == TokenNameIdentifier) { ident = fScanner.getCurrentIdentifierSource(); - addIdentifierInformation('c', ident, buf, phpdocOffset, - phpdocLength); + addIdentifierInformation('c', ident, buf, phpdocOffset, phpdocLength); getNextToken(); //skip fTokens for classname, extends and others until we have // the opening '{' - while (fToken != TokenNameLBRACE && fToken != TokenNameEOF - && fToken != TokenNameERROR) { + while (fToken != TokenNameLBRACE && fToken != TokenNameEOF && fToken != TokenNameERROR) { getNextToken(); } parseDeclarations(ident, buf, true); @@ -261,25 +265,18 @@ public class IdentifierIndexManager { } else if (fToken == TokenNameVariable) { // global variable ident = fScanner.getCurrentIdentifierSource(); - addIdentifierInformation('g', ident, buf, phpdocOffset, - phpdocLength); - getNextToken(); + addIdentifierInformation('g', ident, buf, phpdocOffset, phpdocLength); + getNextToken(); } else if (fToken == TokenNameIdentifier) { ident = fScanner.getCurrentIdentifierSource(); getNextToken(); - if (ident.length==6 && - ident[0]=='d' && - ident[1]=='e' && - ident[2]=='f' && - ident[3]=='i' && - ident[4]=='n' && - ident[5]=='e') { + if (ident.length == 6 && ident[0] == 'd' && ident[1] == 'e' && ident[2] == 'f' && ident[3] == 'i' && ident[4] == 'n' + && ident[5] == 'e') { if (fToken == TokenNameLPAREN) { getNextToken(); if (fToken == TokenNameStringDoubleQuote) { ident = fScanner.getCurrentStringLiteralSource(); - addIdentifierInformation('d', ident, buf, phpdocOffset, - phpdocLength); + addIdentifierInformation('d', ident, buf, phpdocOffset, phpdocLength); getNextToken(); } } @@ -294,6 +291,7 @@ public class IdentifierIndexManager { } } } + class StringComparator implements Comparator { public int compare(Object o1, Object o2) { String s1 = (String) o1; @@ -301,19 +299,25 @@ public class IdentifierIndexManager { return s1.compareTo(s2); // return s1.toUpperCase().compareTo(s2.toUpperCase()); } + public boolean equals(Object o) { String s = (String) o; return compare(this, o) == 0; } } + private HashMap fFileMap; + private String fFilename; + private TreeMap fIndentifierMap; + public IdentifierIndexManager(String filename) { fFilename = filename; initialize(); readFile(); } + /** * Check if 2 char arrays are equal * @@ -332,9 +336,11 @@ public class IdentifierIndexManager { } return true; } + public LineCreator createLineCreator() { return new LineCreator(); } + /** * Add the information for a given IFile resource * @@ -343,12 +349,14 @@ public class IdentifierIndexManager { // InputStream iStream; LineCreator lineCreator = createLineCreator(); try { - addInputStream(new BufferedInputStream(fileToParse.getContents()), fileToParse.getProjectRelativePath().toString(), lineCreator); + addInputStream(new BufferedInputStream(fileToParse.getContents()), fileToParse.getProjectRelativePath().toString(), + lineCreator); } catch (CoreException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } + /** * @param fileToParse * @param lineCreator @@ -359,14 +367,13 @@ public class IdentifierIndexManager { StringBuffer lineBuffer = new StringBuffer(); lineBuffer.append(filePath); int lineLength = lineBuffer.length(); - lineCreator.parseIdentifiers(Util.getInputStreamAsCharArray(stream, -1, - null), lineBuffer); -// if (lineLength != lineBuffer.length()) { - // always add the file for Open Include Action + lineCreator.parseIdentifiers(Util.getInputStreamAsCharArray(stream, -1, null), lineBuffer); + // if (lineLength != lineBuffer.length()) { + // always add the file for Open Include Action addLine(lineBuffer.toString()); -// } - } catch (IOException e) { - e.printStackTrace(); + // } + } catch (IOException e) { + e.printStackTrace(); } finally { try { if (stream != null) { @@ -376,9 +383,9 @@ public class IdentifierIndexManager { } } } + /** - * Adds a line of the index file for function, class, class-method and - * class-variable names + * Adds a line of the index file for function, class, class-method and class-variable names * * @param line */ @@ -404,78 +411,71 @@ public class IdentifierIndexManager { token = tokenizer.nextToken(); //System.out.println(token); switch (token.charAt(0)) { - case 'c' : - // class name - identifier = token.substring(1); - classname = identifier; - phpIdentifier = new PHPIdentifierLocation(identifier, - PHPIdentifier.CLASS, phpFileName); - break; - case 'd' : - // define - identifier = token.substring(1); - phpIdentifier = new PHPIdentifierLocation(identifier, - PHPIdentifier.DEFINE, phpFileName); - break; - case 'f' : - // function name - identifier = token.substring(1); - phpIdentifier = new PHPIdentifierLocation(identifier, - PHPIdentifier.FUNCTION, phpFileName); - break; - case 'g' : - // global variable - identifier = token.substring(1); - phpIdentifier = new PHPIdentifierLocation(identifier, - PHPIdentifier.GLOBAL_VARIABLE, phpFileName); - break; - case 'k' : - // constructor function name - identifier = token.substring(1); - phpIdentifier = new PHPIdentifierLocation(identifier, - PHPIdentifier.CONSTRUCTOR, phpFileName); - break; - case 'm' : - //method inside a class - identifier = token.substring(1); - phpIdentifier = new PHPIdentifierLocation(identifier, - PHPIdentifier.METHOD, phpFileName, classname); - break; - case 'v' : - // variable inside a class - identifier = token.substring(1); - phpIdentifier = new PHPIdentifierLocation(identifier, - PHPIdentifier.VARIABLE, phpFileName, classname); - break; - case 'o' : - // offset information - identifier = null; - if (phpIdentifier != null) { - offset = token.substring(1); - phpIdentifier.setOffset(Integer.parseInt(offset)); - } - break; - case 'p' : - // PHPdoc offset information - identifier = null; - if (phpIdentifier != null) { - offset = token.substring(1); - phpIdentifier.setPHPDocOffset(Integer.parseInt(offset)); - } - break; - case 'l' : - // PHPdoc length information - identifier = null; - if (phpIdentifier != null) { - offset = token.substring(1); - phpIdentifier.setPHPDocLength(Integer.parseInt(offset)); - } - break; - default : - PHPeclipsePlugin.log(IStatus.ERROR, "Unknown token character in IdentifierIndexManager: "+token.charAt(0)); - identifier = null; - phpIdentifier = null; - classname = null; + case 'c': + // class name + identifier = token.substring(1); + classname = identifier; + phpIdentifier = new PHPIdentifierLocation(identifier, PHPIdentifier.CLASS, phpFileName); + break; + case 'd': + // define + identifier = token.substring(1); + phpIdentifier = new PHPIdentifierLocation(identifier, PHPIdentifier.DEFINE, phpFileName); + break; + case 'f': + // function name + identifier = token.substring(1); + phpIdentifier = new PHPIdentifierLocation(identifier, PHPIdentifier.FUNCTION, phpFileName); + break; + case 'g': + // global variable + identifier = token.substring(1); + phpIdentifier = new PHPIdentifierLocation(identifier, PHPIdentifier.GLOBAL_VARIABLE, phpFileName); + break; + case 'k': + // constructor function name + identifier = token.substring(1); + phpIdentifier = new PHPIdentifierLocation(identifier, PHPIdentifier.CONSTRUCTOR, phpFileName); + break; + case 'm': + //method inside a class + identifier = token.substring(1); + phpIdentifier = new PHPIdentifierLocation(identifier, PHPIdentifier.METHOD, phpFileName, classname); + break; + case 'v': + // variable inside a class + identifier = token.substring(1); + phpIdentifier = new PHPIdentifierLocation(identifier, PHPIdentifier.VARIABLE, phpFileName, classname); + break; + case 'o': + // offset information + identifier = null; + if (phpIdentifier != null) { + offset = token.substring(1); + phpIdentifier.setOffset(Integer.parseInt(offset)); + } + break; + case 'p': + // PHPdoc offset information + identifier = null; + if (phpIdentifier != null) { + offset = token.substring(1); + phpIdentifier.setPHPDocOffset(Integer.parseInt(offset)); + } + break; + case 'l': + // PHPdoc length information + identifier = null; + if (phpIdentifier != null) { + offset = token.substring(1); + phpIdentifier.setPHPDocLength(Integer.parseInt(offset)); + } + break; + default: + PHPeclipsePlugin.log(IStatus.ERROR, "Unknown token character in IdentifierIndexManager: " + token.charAt(0)); + identifier = null; + phpIdentifier = null; + classname = null; } if (identifier != null && phpIdentifier != null) { tokenExists = true; @@ -498,10 +498,11 @@ public class IdentifierIndexManager { } } } -// if (tokenExists) { - fFileMap.put(phpFileName, line); -// } + // if (tokenExists) { + fFileMap.put(phpFileName, line); + // } } + /** * Change the information for a given IFile resource * @@ -510,9 +511,9 @@ public class IdentifierIndexManager { removeFile(fileToParse); addFile(fileToParse); } + /** - * Get a list of all PHPIdentifierLocation object's associated with an - * identifier + * Get a list of all PHPIdentifierLocation object's associated with an identifier * * @param identifier * @return @@ -520,6 +521,7 @@ public class IdentifierIndexManager { public List getLocations(String identifier) { return (List) fIndentifierMap.get(identifier); } + /** * Initialize (i.e. clear) the current index information * @@ -528,6 +530,7 @@ public class IdentifierIndexManager { fIndentifierMap = new TreeMap(new StringComparator()); fFileMap = new HashMap(); } + private void readFile() { FileReader fileReader; try { @@ -549,6 +552,7 @@ public class IdentifierIndexManager { e.printStackTrace(); } } + /** * Remove the information for a given IFile resource * @@ -556,14 +560,14 @@ public class IdentifierIndexManager { public void removeFile(IFile fileToParse) { // String line = (String) // fFileMap.get(fileToParse.getLocation().toString()); - String line = (String) fFileMap.get(fileToParse.getFullPath().toString()); + String line = (String) fFileMap.get(fileToParse.getProjectRelativePath().toString()); if (line != null) { removeLine(line); } } + /** - * Removes a line of the index file for function, class, class-method and - * class-variable names + * Removes a line of the index file for function, class, class-method and class-variable names * * @param line */ @@ -582,73 +586,66 @@ public class IdentifierIndexManager { //System.out.println(token); } else { return; - } + } int offset = -1; // all the other tokens are identifiers: while (tokenizer.hasMoreTokens()) { token = tokenizer.nextToken(); //System.out.println(token); switch (token.charAt(0)) { - case 'c' : - // class name - identifier = token.substring(1); - classname = identifier; - phpIdentifier = new PHPIdentifierLocation(identifier, - PHPIdentifier.CLASS, phpFileName); - break; - case 'd' : - // define - identifier = token.substring(1); - phpIdentifier = new PHPIdentifierLocation(identifier, - PHPIdentifier.DEFINE, phpFileName); - break; - case 'f' : - // function name - identifier = token.substring(1); - phpIdentifier = new PHPIdentifierLocation(identifier, - PHPIdentifier.FUNCTION, phpFileName); - break; - case 'g' : - // global variable - identifier = token.substring(1); - phpIdentifier = new PHPIdentifierLocation(identifier, - PHPIdentifier.GLOBAL_VARIABLE, phpFileName); - break; - case 'k' : - // constructor function name - identifier = token.substring(1); - phpIdentifier = new PHPIdentifierLocation(identifier, - PHPIdentifier.CONSTRUCTOR, phpFileName); - break; - case 'm' : - //method inside a class - identifier = token.substring(1); - phpIdentifier = new PHPIdentifierLocation(identifier, - PHPIdentifier.METHOD, phpFileName, classname); - break; - case 'o' : - // offset information - identifier = null; - break; - case 'p' : - // PHPdoc offset information - identifier = null; - break; - case 'l' : - // PHPdoc length information - identifier = null; - break; - case 'v' : - // variable inside a class - identifier = token.substring(1); - phpIdentifier = new PHPIdentifierLocation(identifier, - PHPIdentifier.VARIABLE, phpFileName, classname); - break; - default : - PHPeclipsePlugin.log(IStatus.ERROR, "Unknown token character in IdentifierIndexManager: "+token.charAt(0)); - identifier = null; - phpIdentifier = null; - classname = null; + case 'c': + // class name + identifier = token.substring(1); + classname = identifier; + phpIdentifier = new PHPIdentifierLocation(identifier, PHPIdentifier.CLASS, phpFileName); + break; + case 'd': + // define + identifier = token.substring(1); + phpIdentifier = new PHPIdentifierLocation(identifier, PHPIdentifier.DEFINE, phpFileName); + break; + case 'f': + // function name + identifier = token.substring(1); + phpIdentifier = new PHPIdentifierLocation(identifier, PHPIdentifier.FUNCTION, phpFileName); + break; + case 'g': + // global variable + identifier = token.substring(1); + phpIdentifier = new PHPIdentifierLocation(identifier, PHPIdentifier.GLOBAL_VARIABLE, phpFileName); + break; + case 'k': + // constructor function name + identifier = token.substring(1); + phpIdentifier = new PHPIdentifierLocation(identifier, PHPIdentifier.CONSTRUCTOR, phpFileName); + break; + case 'm': + //method inside a class + identifier = token.substring(1); + phpIdentifier = new PHPIdentifierLocation(identifier, PHPIdentifier.METHOD, phpFileName, classname); + break; + case 'o': + // offset information + identifier = null; + break; + case 'p': + // PHPdoc offset information + identifier = null; + break; + case 'l': + // PHPdoc length information + identifier = null; + break; + case 'v': + // variable inside a class + identifier = token.substring(1); + phpIdentifier = new PHPIdentifierLocation(identifier, PHPIdentifier.VARIABLE, phpFileName, classname); + break; + default: + PHPeclipsePlugin.log(IStatus.ERROR, "Unknown token character in IdentifierIndexManager: " + token.charAt(0)); + identifier = null; + phpIdentifier = null; + classname = null; } if (identifier != null && phpIdentifier != null) { ArrayList list = (ArrayList) fIndentifierMap.get(identifier); @@ -668,6 +665,7 @@ public class IdentifierIndexManager { } fFileMap.remove(phpFileName); } + /** * Save the current index information in the projects index file * @@ -691,6 +689,7 @@ public class IdentifierIndexManager { e.printStackTrace(); } } + /** * @param fromKey * @param toKey @@ -709,9 +708,9 @@ public class IdentifierIndexManager { ArrayList list = new ArrayList(); String fileName; int index; - while(iter.hasNext()) { + while (iter.hasNext()) { fileName = (String) iter.next(); - if ((index=fileName.indexOf(filePattern))!=-1 && fileName.length()==(index+filePattern.length())) { + if ((index = fileName.indexOf(filePattern)) != -1 && fileName.length() == (index + filePattern.length())) { list.add(fileName); } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/PHPIdentifier.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/PHPIdentifier.java index 895d942..f932b4d 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/PHPIdentifier.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/obfuscator/PHPIdentifier.java @@ -94,6 +94,8 @@ public class PHPIdentifier { return "define - "; case FUNCTION : return "function - "; + case GLOBAL_VARIABLE : + return "global variable - "; case METHOD : return "method - "; case VARIABLE : diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaOutlinePage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaOutlinePage.java index 2155406..b35bfb7 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaOutlinePage.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaOutlinePage.java @@ -10,7 +10,6 @@ *******************************************************************************/ package net.sourceforge.phpeclipse.phpeditor; - import java.util.Enumeration; import java.util.Hashtable; import java.util.List; @@ -22,7 +21,6 @@ import net.sourceforge.phpdt.core.IElementChangedListener; import net.sourceforge.phpdt.core.IJavaElement; import net.sourceforge.phpdt.core.IJavaElementDelta; import net.sourceforge.phpdt.core.IMember; -import net.sourceforge.phpdt.core.IMethod; import net.sourceforge.phpdt.core.IParent; import net.sourceforge.phpdt.core.ISourceRange; import net.sourceforge.phpdt.core.ISourceReference; @@ -30,6 +28,7 @@ import net.sourceforge.phpdt.core.IType; import net.sourceforge.phpdt.core.JavaCore; import net.sourceforge.phpdt.core.JavaModelException; import net.sourceforge.phpdt.internal.ui.PHPUiImages; +import net.sourceforge.phpdt.internal.ui.actions.AbstractToggleLinkingAction; import net.sourceforge.phpdt.internal.ui.actions.CompositeActionGroup; import net.sourceforge.phpdt.internal.ui.dnd.JdtViewerDragAdapter; import net.sourceforge.phpdt.internal.ui.dnd.TransferDragSourceListener; @@ -55,6 +54,7 @@ import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IStatusLineManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.MenuManager; +import org.eclipse.jface.action.Separator; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.text.Assert; import org.eclipse.jface.text.ITextSelection; @@ -62,11 +62,13 @@ import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.ListenerList; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.IBaseLabelProvider; +import org.eclipse.jface.viewers.IPostSelectionProvider; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.LabelProviderChangedEvent; +import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.Viewer; @@ -75,7 +77,6 @@ import org.eclipse.swt.SWT; import org.eclipse.swt.custom.BusyIndicator; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.Transfer; -import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; @@ -102,1070 +103,1196 @@ import org.eclipse.ui.texteditor.TextOperationAction; import org.eclipse.ui.views.contentoutline.IContentOutlinePage; import org.eclipse.ui.views.navigator.LocalSelectionTransfer; +/** + * The content outline page of the Java editor. The viewer implements a proprietary update mechanism based on Java model deltas. It + * does not react on domain changes. It is specified to show the content of ICompilationUnits and IClassFiles. Pulishes its context + * menu under JavaPlugin.getDefault().getPluginId() + ".outline". + */ +public class JavaOutlinePage extends Page implements IContentOutlinePage, IAdaptable, IPostSelectionProvider { + static Object[] NO_CHILDREN = new Object[0]; + /** + * The element change listener of the java outline viewer. + * + * @see IElementChangedListener + */ + class ElementChangedListener implements IElementChangedListener { + public void elementChanged(final ElementChangedEvent e) { -/** - * The content outline page of the Java editor. The viewer implements a proprietary - * update mechanism based on Java model deltas. It does not react on domain changes. - * It is specified to show the content of ICompilationUnits and IClassFiles. - * Pulishes its context menu under JavaPlugin.getDefault().getPluginId() + ".outline". - */ -public class JavaOutlinePage extends Page implements IContentOutlinePage, IAdaptable { - - static Object[] NO_CHILDREN= new Object[0]; - - /** - * The element change listener of the java outline viewer. - * @see IElementChangedListener - */ - class ElementChangedListener implements IElementChangedListener { - - public void elementChanged(final ElementChangedEvent e) { - - if (getControl() == null) - return; - - Display d= getControl().getDisplay(); - if (d != null) { - d.asyncExec(new Runnable() { - public void run() { - ICompilationUnit cu= (ICompilationUnit) fInput; - IJavaElement base= cu; - if (fTopLevelTypeOnly) { - base= getMainType(cu); - if (base == null) { - if (fOutlineViewer != null) - fOutlineViewer.refresh(true); - return; - } - } - IJavaElementDelta delta= findElement(base, e.getDelta()); - if (delta != null && fOutlineViewer != null) { - fOutlineViewer.reconcile(delta); - } - } - }); - } - } - - protected IJavaElementDelta findElement(IJavaElement unit, IJavaElementDelta delta) { - - if (delta == null || unit == null) - return null; - - IJavaElement element= delta.getElement(); - - if (unit.equals(element)) - return delta; - - if (element.getElementType() > IJavaElement.CLASS_FILE) - return null; - - IJavaElementDelta[] children= delta.getAffectedChildren(); - if (children == null || children.length == 0) - return null; - - for (int i= 0; i < children.length; i++) { - IJavaElementDelta d= findElement(unit, children[i]); - if (d != null) - return d; - } - - return null; - } - }; - - static class NoClassElement extends WorkbenchAdapter implements IAdaptable { - /* - * @see java.lang.Object#toString() - */ - public String toString() { - return PHPEditorMessages.getString("JavaOutlinePage.error.NoTopLevelType"); //$NON-NLS-1$ - } - - /* - * @see org.eclipse.core.runtime.IAdaptable#getAdapter(Class) - */ - public Object getAdapter(Class clas) { - if (clas == IWorkbenchAdapter.class) - return this; - return null; - } - } - - /** - * Content provider for the children of an ICompilationUnit or - * an IClassFile - * @see ITreeContentProvider - */ - class ChildrenProvider implements ITreeContentProvider { - - private Object[] NO_CLASS= new Object[] {new NoClassElement()}; - private ElementChangedListener fListener; - - protected boolean matches(IJavaElement element) { - if (element.getElementType() == IJavaElement.METHOD) { - String name= element.getElementName(); - return (name != null && name.indexOf('<') >= 0); - } - return false; - } - - protected IJavaElement[] filter(IJavaElement[] children) { - boolean initializers= false; - for (int i= 0; i < children.length; i++) { - if (matches(children[i])) { - initializers= true; - break; - } - } - - if (!initializers) - return children; - - Vector v= new Vector(); - for (int i= 0; i < children.length; i++) { - if (matches(children[i])) - continue; - v.addElement(children[i]); - } - - IJavaElement[] result= new IJavaElement[v.size()]; - v.copyInto(result); - return result; - } - - public Object[] getChildren(Object parent) { - if (parent instanceof IParent) { - IParent c= (IParent) parent; - try { - return filter(c.getChildren()); - } catch (JavaModelException x) { - PHPeclipsePlugin.log(x); - } - } - return NO_CHILDREN; - } - - public Object[] getElements(Object parent) { - if (fTopLevelTypeOnly) { - if (parent instanceof ICompilationUnit) { - try { - IType type= getMainType((ICompilationUnit) parent); - return type != null ? type.getChildren() : NO_CLASS; - } catch (JavaModelException e) { - PHPeclipsePlugin.log(e); - } - } -// else if (parent instanceof IClassFile) { -// try { -// IType type= getMainType((IClassFile) parent); -// return type != null ? type.getChildren() : NO_CLASS; -// } catch (JavaModelException e) { -// JavaPlugin.log(e); -// } -// } - } - return getChildren(parent); - } - - public Object getParent(Object child) { - if (child instanceof IJavaElement) { - IJavaElement e= (IJavaElement) child; - return e.getParent(); - } - return null; - } - - public boolean hasChildren(Object parent) { - if (parent instanceof IParent) { - IParent c= (IParent) parent; - try { - IJavaElement[] children= filter(c.getChildren()); - return (children != null && children.length > 0); - } catch (JavaModelException x) { - PHPeclipsePlugin.log(x); - } - } - return false; - } - - public boolean isDeleted(Object o) { - return false; - } - - public void dispose() { - if (fListener != null) { - JavaCore.removeElementChangedListener(fListener); - fListener= null; - } - } - - /* - * @see IContentProvider#inputChanged(Viewer, Object, Object) - */ - public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { - boolean isCU= (newInput instanceof ICompilationUnit); - - if (isCU && fListener == null) { - fListener= new ElementChangedListener(); - JavaCore.addElementChangedListener(fListener); - } else if (!isCU && fListener != null) { - JavaCore.removeElementChangedListener(fListener); - fListener= null; - } - } - }; - - - class JavaOutlineViewer extends TreeViewer { - - /** - * Indicates an item which has been reused. At the point of - * its reuse it has been expanded. This field is used to - * communicate between internalExpandToLevel and - * reuseTreeItem. - */ - private Item fReusedExpandedItem; - private boolean fReorderedMembers; - - public JavaOutlineViewer(Tree tree) { - super(tree); - setAutoExpandLevel(ALL_LEVELS); - } - - /** - * Investigates the given element change event and if affected incrementally - * updates the outline. - */ - public void reconcile(IJavaElementDelta delta) { - fReorderedMembers= false; - if (getSorter() == null) { - if (fTopLevelTypeOnly - && delta.getElement() instanceof IType - && (delta.getKind() & IJavaElementDelta.ADDED) != 0) - { - refresh(true); - - } else { - Widget w= findItem(fInput); - if (w != null && !w.isDisposed()) - update(w, delta); - if (fReorderedMembers) { - refresh(false); - fReorderedMembers= false; - } - } - } else { - // just for now - refresh(true); - } - } - - /* - * @see TreeViewer#internalExpandToLevel - */ - protected void internalExpandToLevel(Widget node, int level) { - if (node instanceof Item) { - Item i= (Item) node; - if (i.getData() instanceof IJavaElement) { - IJavaElement je= (IJavaElement) i.getData(); - if (je.getElementType() == IJavaElement.IMPORT_CONTAINER || isInnerType(je)) { - if (i != fReusedExpandedItem) { - setExpanded(i, false); - return; - } - } - } - } - super.internalExpandToLevel(node, level); - } - - protected void reuseTreeItem(Item item, Object element) { - - // remove children - Item[] c= getChildren(item); - if (c != null && c.length > 0) { - - if (getExpanded(item)) - fReusedExpandedItem= item; - - for (int k= 0; k < c.length; k++) { - if (c[k].getData() != null) - disassociate(c[k]); - c[k].dispose(); - } - } - - updateItem(item, element); - updatePlus(item, element); - internalExpandToLevel(item, ALL_LEVELS); - - fReusedExpandedItem= null; - } - - protected boolean mustUpdateParent(IJavaElementDelta delta, IJavaElement element) { - if (element instanceof IMethod) { - if ((delta.getKind() & IJavaElementDelta.ADDED) != 0) { - try { - return ((IMethod)element).isMainMethod(); - } catch (JavaModelException e) { - PHPeclipsePlugin.log(e.getStatus()); - } - } - return "main".equals(element.getElementName()); //$NON-NLS-1$ - } - return false; - } - - protected ISourceRange getSourceRange(IJavaElement element) throws JavaModelException { - if (element instanceof IMember)// && !(element instanceof IInitializer)) - return ((IMember) element).getNameRange(); - if (element instanceof ISourceReference) - return ((ISourceReference) element).getSourceRange(); - return null; - } - - protected boolean overlaps(ISourceRange range, int start, int end) { - return start <= (range.getOffset() + range.getLength() - 1) && range.getOffset() <= end; - } - - protected boolean filtered(IJavaElement parent, IJavaElement child) { - - Object[] result= new Object[] { child }; - ViewerFilter[] filters= getFilters(); - for (int i= 0; i < filters.length; i++) { - result= filters[i].filter(this, parent, result); - if (result.length == 0) - return true; - } - - return false; - } - - protected void update(Widget w, IJavaElementDelta delta) { - - Item item; - - IJavaElement parent= delta.getElement(); - IJavaElementDelta[] affected= delta.getAffectedChildren(); - Item[] children= getChildren(w); - - boolean doUpdateParent= false; - - Vector deletions= new Vector(); - Vector additions= new Vector(); - - for (int i= 0; i < affected.length; i++) { - IJavaElementDelta affectedDelta= affected[i]; - IJavaElement affectedElement= affectedDelta.getElement(); - int status= affected[i].getKind(); - - // find tree item with affected element - int j; - for (j= 0; j < children.length; j++) - if (affectedElement.equals(children[j].getData())) - break; - - if (j == children.length) { - // addition - if ((status & IJavaElementDelta.CHANGED) != 0 && - (affectedDelta.getFlags() & IJavaElementDelta.F_MODIFIERS) != 0 && - !filtered(parent, affectedElement)) - { - additions.addElement(affectedDelta); - } - continue; - } - - item= children[j]; - - // removed - if ((status & IJavaElementDelta.REMOVED) != 0) { - deletions.addElement(item); - doUpdateParent= doUpdateParent || mustUpdateParent(affectedDelta, affectedElement); - - // changed - } else if ((status & IJavaElementDelta.CHANGED) != 0) { - int change= affectedDelta.getFlags(); - doUpdateParent= doUpdateParent || mustUpdateParent(affectedDelta, affectedElement); - - if ((change & IJavaElementDelta.F_MODIFIERS) != 0) { - if (filtered(parent, affectedElement)) - deletions.addElement(item); - else - updateItem(item, affectedElement); - } - - if ((change & IJavaElementDelta.F_CONTENT) != 0) - updateItem(item, affectedElement); - - if ((change & IJavaElementDelta.F_CHILDREN) != 0) - update(item, affectedDelta); - - if ((change & IJavaElementDelta.F_REORDER) != 0) - fReorderedMembers= true; - } - } - - // find all elements to add - IJavaElementDelta[] add= delta.getAddedChildren(); - if (additions.size() > 0) { - IJavaElementDelta[] tmp= new IJavaElementDelta[add.length + additions.size()]; - System.arraycopy(add, 0, tmp, 0, add.length); - for (int i= 0; i < additions.size(); i++) - tmp[i + add.length]= (IJavaElementDelta) additions.elementAt(i); - add= tmp; - } - - // add at the right position - go2: for (int i= 0; i < add.length; i++) { - - try { - - IJavaElement e= add[i].getElement(); - if (filtered(parent, e)) - continue go2; - - doUpdateParent= doUpdateParent || mustUpdateParent(add[i], e); - ISourceRange rng= getSourceRange(e); - int start= rng.getOffset(); - int end= start + rng.getLength() - 1; - - Item last= null; - item= null; - children= getChildren(w); - - for (int j= 0; j < children.length; j++) { - item= children[j]; - IJavaElement r= (IJavaElement) item.getData(); - - if (r == null) { - // parent node collapsed and not be opened before -> do nothing - continue go2; - } - - - try { - rng= getSourceRange(r); - if (overlaps(rng, start, end)) { - - // be tolerant if the delta is not correct, or if - // the tree has been updated other than by a delta - reuseTreeItem(item, e); - continue go2; - - } else if (rng.getOffset() > start) { - - if (last != null && deletions.contains(last)) { - // reuse item - deletions.removeElement(last); - reuseTreeItem(last, (Object) e); - } else { - // nothing to reuse - createTreeItem(w, (Object) e, j); - } - continue go2; - } - - } catch (JavaModelException x) { - // stumbled over deleted element - } - - last= item; - } - - // add at the end of the list - if (last != null && deletions.contains(last)) { - // reuse item - deletions.removeElement(last); - reuseTreeItem(last, e); - } else { - // nothing to reuse - createTreeItem(w, e, -1); - } - - } catch (JavaModelException x) { - // the element to be added is not present -> don't add it - } - } - - - // remove items which haven't been reused - Enumeration e= deletions.elements(); - while (e.hasMoreElements()) { - item= (Item) e.nextElement(); - disassociate(item); - item.dispose(); - } - - if (doUpdateParent) - updateItem(w, delta.getElement()); - } - - - - /* - * @see ContentViewer#handleLabelProviderChanged(LabelProviderChangedEvent) - */ - protected void handleLabelProviderChanged(LabelProviderChangedEvent event) { - Object input= getInput(); - if (event instanceof ProblemsLabelChangedEvent) { - ProblemsLabelChangedEvent e= (ProblemsLabelChangedEvent) event; - if (e.isMarkerChange() && input instanceof ICompilationUnit) { - return; // marker changes can be ignored - } - } - // look if the underlying resource changed - Object[] changed= event.getElements(); - if (changed != null) { - IResource resource= getUnderlyingResource(); - if (resource != null) { - for (int i= 0; i < changed.length; i++) { - if (changed[i] != null && changed[i].equals(resource)) { - // change event to a full refresh - event= new LabelProviderChangedEvent((IBaseLabelProvider) event.getSource()); - break; - } - } - } - } - super.handleLabelProviderChanged(event); - } - - private IResource getUnderlyingResource() { - Object input= getInput(); - if (input instanceof ICompilationUnit) { - ICompilationUnit cu= (ICompilationUnit) input; - if (cu.isWorkingCopy()) { - return cu.getOriginalElement().getResource(); - } else { - return cu.getResource(); - } - } -// else if (input instanceof IClassFile) { -// return ((IClassFile) input).getResource(); -// } - return null; - } - - - }; - - class LexicalSortingAction extends Action { - - private JavaElementSorter fSorter= new JavaElementSorter(); - - public LexicalSortingAction() { - super(); -// WorkbenchHelp.setHelp(this, IJavaHelpContextIds.LEXICAL_SORTING_OUTLINE_ACTION); - setText(PHPEditorMessages.getString("JavaOutlinePage.Sort.label")); //$NON-NLS-1$ - PHPUiImages.setLocalImageDescriptors(this, "alphab_sort_co.gif"); //$NON-NLS-1$ - setToolTipText(PHPEditorMessages.getString("JavaOutlinePage.Sort.tooltip")); //$NON-NLS-1$ - setDescription(PHPEditorMessages.getString("JavaOutlinePage.Sort.description")); //$NON-NLS-1$ - - boolean checked= PHPeclipsePlugin.getDefault().getPreferenceStore().getBoolean("LexicalSortingAction.isChecked"); //$NON-NLS-1$ - valueChanged(checked, false); - } - - public void run() { - valueChanged(isChecked(), true); - } - - private void valueChanged(final boolean on, boolean store) { - setChecked(on); - BusyIndicator.showWhile(fOutlineViewer.getControl().getDisplay(), new Runnable() { - public void run() { - fOutlineViewer.setSorter(on ? fSorter : null); } - }); - - if (store) - PHPeclipsePlugin.getDefault().getPreferenceStore().setValue("LexicalSortingAction.isChecked", on); //$NON-NLS-1$ - } - }; - - class ClassOnlyAction extends Action { - - public ClassOnlyAction() { - super(); -// WorkbenchHelp.setHelp(this, IJavaHelpContextIds.GO_INTO_TOP_LEVEL_TYPE_ACTION); - setText(PHPEditorMessages.getString("JavaOutlinePage.GoIntoTopLevelType.label")); //$NON-NLS-1$ - setToolTipText(PHPEditorMessages.getString("JavaOutlinePage.GoIntoTopLevelType.tooltip")); //$NON-NLS-1$ - setDescription(PHPEditorMessages.getString("JavaOutlinePage.GoIntoTopLevelType.description")); //$NON-NLS-1$ - PHPUiImages.setLocalImageDescriptors(this, "gointo_toplevel_type.gif"); //$NON-NLS-1$ - - IPreferenceStore preferenceStore= PHPeclipsePlugin.getDefault().getPreferenceStore(); - boolean showclass= preferenceStore.getBoolean("GoIntoTopLevelTypeAction.isChecked"); //$NON-NLS-1$ - setTopLevelTypeOnly(showclass); - } + if (getControl() == null) + return; - /* - * @see org.eclipse.jface.action.Action#run() - */ - public void run() { - setTopLevelTypeOnly(!fTopLevelTypeOnly); - } + Display d = getControl().getDisplay(); + if (d != null) { + d.asyncExec(new Runnable() { + public void run() { + ICompilationUnit cu = (ICompilationUnit) fInput; + IJavaElement base = cu; + if (fTopLevelTypeOnly) { + base = getMainType(cu); + if (base == null) { + if (fOutlineViewer != null) + fOutlineViewer.refresh(true); + return; + } + } + IJavaElementDelta delta = findElement(base, e.getDelta()); + if (delta != null && fOutlineViewer != null) { + fOutlineViewer.reconcile(delta); + } + } + }); + } + } - private void setTopLevelTypeOnly(boolean show) { - fTopLevelTypeOnly= show; - setChecked(show); - fOutlineViewer.refresh(false); - - IPreferenceStore preferenceStore= PHPeclipsePlugin.getDefault().getPreferenceStore(); - preferenceStore.setValue("GoIntoTopLevelTypeAction.isChecked", show); //$NON-NLS-1$ - } - }; - - /** A flag to show contents of top level type only */ - private boolean fTopLevelTypeOnly; - - private IJavaElement fInput; - private String fContextMenuID; - private Menu fMenu; - private JavaOutlineViewer fOutlineViewer; - private PHPEditor fEditor; - - private MemberFilterActionGroup fMemberFilterActionGroup; - - private ListenerList fSelectionChangedListeners= new ListenerList(); - private Hashtable fActions= new Hashtable(); - - private TogglePresentationAction fTogglePresentation; - private GotoErrorAction fPreviousError; - private GotoErrorAction fNextError; - private TextEditorAction fShowJavadoc; - private TextOperationAction fUndo; - private TextOperationAction fRedo; - - private CompositeActionGroup fActionGroups; -// private CCPActionGroup fCCPActionGroup; + protected IJavaElementDelta findElement(IJavaElement unit, IJavaElementDelta delta) { - private IPropertyChangeListener fPropertyChangeListener; - - public JavaOutlinePage(String contextMenuID, PHPEditor editor) { - super(); - - Assert.isNotNull(editor); - - fContextMenuID= contextMenuID; - fEditor= editor; - - fTogglePresentation= new TogglePresentationAction(); - fPreviousError= new GotoErrorAction("PreviousError.", false); //$NON-NLS-1$ - fPreviousError.setImageDescriptor(PHPUiImages.DESC_TOOL_GOTO_PREV_ERROR); - fNextError= new GotoErrorAction("NextError.", true); //$NON-NLS-1$ - fNextError.setImageDescriptor(PHPUiImages.DESC_TOOL_GOTO_NEXT_ERROR); - fShowJavadoc= (TextEditorAction) fEditor.getAction("ShowJavaDoc"); //$NON-NLS-1$ - fUndo= (TextOperationAction) fEditor.getAction(ITextEditorActionConstants.UNDO); - fRedo= (TextOperationAction) fEditor.getAction(ITextEditorActionConstants.REDO); - - fTogglePresentation.setEditor(editor); - fPreviousError.setEditor(editor); - fNextError.setEditor(editor); - - fPropertyChangeListener= new IPropertyChangeListener() { - public void propertyChange(PropertyChangeEvent event) { - doPropertyChange(event); - } - }; - PHPeclipsePlugin.getDefault().getPreferenceStore().addPropertyChangeListener(fPropertyChangeListener); - } - - /** - * Returns the primary type of a compilation unit (has the same - * name as the compilation unit). - * - * @param compilationUnit the compilation unit - * @return returns the primary type of the compilation unit, or - * null if is does not have one - */ - protected IType getMainType(ICompilationUnit compilationUnit) { - String name= compilationUnit.getElementName(); - int index= name.indexOf('.'); - if (index != -1) - name= name.substring(0, index); - IType type= compilationUnit.getType(name); - return type.exists() ? type : null; - } + if (delta == null || unit == null) + return null; + + IJavaElement element = delta.getElement(); + + if (unit.equals(element)) + return delta; + + if (element.getElementType() > IJavaElement.CLASS_FILE) + return null; + + IJavaElementDelta[] children = delta.getAffectedChildren(); + if (children == null || children.length == 0) + return null; + + for (int i = 0; i < children.length; i++) { + IJavaElementDelta d = findElement(unit, children[i]); + if (d != null) + return d; + } + + return null; + } + }; + + static class NoClassElement extends WorkbenchAdapter implements IAdaptable { + /* + * @see java.lang.Object#toString() + */ + public String toString() { + return PHPEditorMessages.getString("JavaOutlinePage.error.NoTopLevelType"); //$NON-NLS-1$ + } + + /* + * @see org.eclipse.core.runtime.IAdaptable#getAdapter(Class) + */ + public Object getAdapter(Class clas) { + if (clas == IWorkbenchAdapter.class) + return this; + return null; + } + } + + /** + * Content provider for the children of an ICompilationUnit or an IClassFile + * + * @see ITreeContentProvider + */ + class ChildrenProvider implements ITreeContentProvider { + + private Object[] NO_CLASS = new Object[] { new NoClassElement() }; + + private ElementChangedListener fListener; + + protected boolean matches(IJavaElement element) { + if (element.getElementType() == IJavaElement.METHOD) { + String name = element.getElementName(); + return (name != null && name.indexOf('<') >= 0); + } + return false; + } + + protected IJavaElement[] filter(IJavaElement[] children) { + boolean initializers = false; + for (int i = 0; i < children.length; i++) { + if (matches(children[i])) { + initializers = true; + break; + } + } + + if (!initializers) + return children; - /** - * Returns the primary type of a class file. + Vector v = new Vector(); + for (int i = 0; i < children.length; i++) { + if (matches(children[i])) + continue; + v.addElement(children[i]); + } + + IJavaElement[] result = new IJavaElement[v.size()]; + v.copyInto(result); + return result; + } + + public Object[] getChildren(Object parent) { + if (parent instanceof IParent) { + IParent c = (IParent) parent; + try { + return filter(c.getChildren()); + } catch (JavaModelException x) { + PHPeclipsePlugin.log(x); + } + } + return NO_CHILDREN; + } + + public Object[] getElements(Object parent) { + if (fTopLevelTypeOnly) { + if (parent instanceof ICompilationUnit) { + try { + IType type = getMainType((ICompilationUnit) parent); + return type != null ? type.getChildren() : NO_CLASS; + } catch (JavaModelException e) { + PHPeclipsePlugin.log(e); + } + } + // else if (parent instanceof IClassFile) { + // try { + // IType type= getMainType((IClassFile) parent); + // return type != null ? type.getChildren() : NO_CLASS; + // } catch (JavaModelException e) { + // JavaPlugin.log(e); + // } + // } + } + return getChildren(parent); + } + + public Object getParent(Object child) { + if (child instanceof IJavaElement) { + IJavaElement e = (IJavaElement) child; + return e.getParent(); + } + return null; + } + + public boolean hasChildren(Object parent) { + if (parent instanceof IParent) { + IParent c = (IParent) parent; + try { + IJavaElement[] children = filter(c.getChildren()); + return (children != null && children.length > 0); + } catch (JavaModelException x) { + PHPeclipsePlugin.log(x); + } + } + return false; + } + + public boolean isDeleted(Object o) { + return false; + } + + public void dispose() { + if (fListener != null) { + JavaCore.removeElementChangedListener(fListener); + fListener = null; + } + } + + /* + * @see IContentProvider#inputChanged(Viewer, Object, Object) + */ + public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { + boolean isCU = (newInput instanceof ICompilationUnit); + + if (isCU && fListener == null) { + fListener = new ElementChangedListener(); + JavaCore.addElementChangedListener(fListener); + } else if (!isCU && fListener != null) { + JavaCore.removeElementChangedListener(fListener); + fListener = null; + } + } + }; + + class JavaOutlineViewer extends TreeViewer { + + /** + * Indicates an item which has been reused. At the point of its reuse it has been expanded. This field is used to communicate + * between internalExpandToLevel and reuseTreeItem. + */ + private Item fReusedExpandedItem; + + private boolean fReorderedMembers; + private boolean fForceFireSelectionChanged; + + public JavaOutlineViewer(Tree tree) { + super(tree); + setAutoExpandLevel(ALL_LEVELS); + } + + /** + * Investigates the given element change event and if affected incrementally updates the outline. + */ + /** + * Investigates the given element change event and if affected + * incrementally updates the Java outline. * - * @param classFile the class file - * @return returns the primary type of the class file, or null - * if is does not have one - */ -// protected IType getMainType(IClassFile classFile) { -// try { -// IType type= classFile.getType(); -// return type != null && type.exists() ? type : null; -// } catch (JavaModelException e) { -// return null; -// } -// } - - /* (non-Javadoc) - * Method declared on Page + * @param delta the Java element delta used to reconcile the Java outline */ - public void init(IPageSite pageSite) { - super.init(pageSite); - } - - private void doPropertyChange(PropertyChangeEvent event) { - if (fOutlineViewer != null) { - if (PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER.equals(event.getProperty())) { - fOutlineViewer.refresh(false); + public void reconcile(IJavaElementDelta delta) { + fReorderedMembers= false; + fForceFireSelectionChanged= false; + if (getSorter() == null) { + if (fTopLevelTypeOnly + && delta.getElement() instanceof IType + && (delta.getKind() & IJavaElementDelta.ADDED) != 0) + { + refresh(true); + + } else { + Widget w= findItem(fInput); + if (w != null && !w.isDisposed()) + update(w, delta); + if (fForceFireSelectionChanged) + fireSelectionChanged(new SelectionChangedEvent(getSite().getSelectionProvider(), this.getSelection())); + if (fReorderedMembers) { + refresh(false); + fReorderedMembers= false; } - } - } - - /* - * @see ISelectionProvider#addSelectionChangedListener(ISelectionChangedListener) - */ - public void addSelectionChangedListener(ISelectionChangedListener listener) { - if (fOutlineViewer != null) - fOutlineViewer.addPostSelectionChangedListener(listener); - else - fSelectionChangedListeners.add(listener); - } - - /* - * @see ISelectionProvider#removeSelectionChangedListener(ISelectionChangedListener) - */ - public void removeSelectionChangedListener(ISelectionChangedListener listener) { - if (fOutlineViewer != null) - fOutlineViewer.removePostSelectionChangedListener(listener); - else - fSelectionChangedListeners.remove(listener); - } - - /* - * @see ISelectionProvider#setSelection(ISelection) - */ - public void setSelection(ISelection selection) { - if (fOutlineViewer != null) - fOutlineViewer.setSelection(selection); - } - - /* - * @see ISelectionProvider#getSelection() - */ - public ISelection getSelection() { - if (fOutlineViewer == null) - return StructuredSelection.EMPTY; - return fOutlineViewer.getSelection(); - } - - private void registerToolbarActions() { - - IToolBarManager toolBarManager= getSite().getActionBars().getToolBarManager(); - if (toolBarManager != null) { - toolBarManager.add(new ClassOnlyAction()); - toolBarManager.add(new LexicalSortingAction()); - - fMemberFilterActionGroup= new MemberFilterActionGroup(fOutlineViewer, "JavaOutlineViewer"); //$NON-NLS-1$ - fMemberFilterActionGroup.contributeToToolBar(toolBarManager); - } - } - - /* - * @see IPage#createControl - */ - public void createControl(Composite parent) { - - Tree tree= new Tree(parent, SWT.MULTI); - - AppearanceAwareLabelProvider lprovider= new AppearanceAwareLabelProvider( - AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS | JavaElementLabels.F_APP_TYPE_SIGNATURE, - AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS - ); - - fOutlineViewer= new JavaOutlineViewer(tree); - fOutlineViewer.setContentProvider(new ChildrenProvider()); - fOutlineViewer.setLabelProvider(new DecoratingJavaLabelProvider(lprovider)); - - Object[] listeners= fSelectionChangedListeners.getListeners(); - for (int i= 0; i < listeners.length; i++) { - fSelectionChangedListeners.remove(listeners[i]); - fOutlineViewer.addPostSelectionChangedListener((ISelectionChangedListener) listeners[i]); - } - - MenuManager manager= new MenuManager(fContextMenuID, fContextMenuID); - manager.setRemoveAllWhenShown(true); - manager.addMenuListener(new IMenuListener() { - public void menuAboutToShow(IMenuManager manager) { - contextMenuAboutToShow(manager); } - }); - fMenu= manager.createContextMenu(tree); - tree.setMenu(fMenu); - - IPageSite site= getSite(); - site.registerContextMenu(PHPeclipsePlugin.getPluginId() + ".outline", manager, fOutlineViewer); //$NON-NLS-1$ - site.setSelectionProvider(fOutlineViewer); - - // we must create the groups after we have set the selection provider to the site - fActionGroups= new CompositeActionGroup(new ActionGroup[] { -// new OpenViewActionGroup(this), -// fCCPActionGroup= new CCPActionGroup(this), - new GenerateActionGroup(this)}); -// new RefactorActionGroup(this), -// new JavaSearchActionGroup(this)}); - - // register global actions - IActionBars bars= site.getActionBars(); - - bars.setGlobalActionHandler(ITextEditorActionConstants.UNDO, fUndo); - bars.setGlobalActionHandler(ITextEditorActionConstants.REDO, fRedo); - bars.setGlobalActionHandler(ITextEditorActionConstants.PREVIOUS, fPreviousError); - bars.setGlobalActionHandler(ITextEditorActionConstants.NEXT, fNextError); -// bars.setGlobalActionHandler(PHPdtActionConstants.SHOW_PHP_DOC, fShowJavadoc); - bars.setGlobalActionHandler(IJavaEditorActionConstants.TOGGLE_PRESENTATION, fTogglePresentation); - // http://dev.eclipse.org/bugs/show_bug.cgi?id=18968 - bars.setGlobalActionHandler(IJavaEditorActionConstants.PREVIOUS_ERROR, fPreviousError); - bars.setGlobalActionHandler(IJavaEditorActionConstants.NEXT_ERROR, fNextError); - - fActionGroups.fillActionBars(bars); - - IStatusLineManager statusLineManager= site.getActionBars().getStatusLineManager(); - if (statusLineManager != null) { - StatusBarUpdater updater= new StatusBarUpdater(statusLineManager); - fOutlineViewer.addPostSelectionChangedListener(updater); + } else { + // just for now + refresh(true); } - - registerToolbarActions(); - - fOutlineViewer.setInput(fInput); - fOutlineViewer.getControl().addKeyListener(new KeyAdapter() { - public void keyPressed(KeyEvent e) { - handleKeyReleased(e); - } - }); - - initDragAndDrop(); } +// public void reconcile(IJavaElementDelta delta) { +// fReorderedMembers = false; +// if (getSorter() == null) { +// if (fTopLevelTypeOnly && delta.getElement() instanceof IType && (delta.getKind() & IJavaElementDelta.ADDED) != 0) { +// refresh(true); +// +// } else { +// Widget w = findItem(fInput); +// if (w != null && !w.isDisposed()) +// update(w, delta); +// if (fReorderedMembers) { +// refresh(false); +// fReorderedMembers = false; +// } +// } +// } else { +// // just for now +// refresh(true); +// } +// } - public void dispose() { - - if (fEditor == null) - return; - - if (fMemberFilterActionGroup != null) { - fMemberFilterActionGroup.dispose(); - fMemberFilterActionGroup= null; - } - - - fEditor.outlinePageClosed(); - fEditor= null; + /* + * @see TreeViewer#internalExpandToLevel + */ + protected void internalExpandToLevel(Widget node, int level) { + if (node instanceof Item) { + Item i = (Item) node; + if (i.getData() instanceof IJavaElement) { + IJavaElement je = (IJavaElement) i.getData(); + if (je.getElementType() == IJavaElement.IMPORT_CONTAINER || isInnerType(je)) { + if (i != fReusedExpandedItem) { + setExpanded(i, false); + return; + } + } + } + } + super.internalExpandToLevel(node, level); + } - fSelectionChangedListeners.clear(); - fSelectionChangedListeners= null; + protected void reuseTreeItem(Item item, Object element) { - if (fPropertyChangeListener != null) { - PHPeclipsePlugin.getDefault().getPreferenceStore().removePropertyChangeListener(fPropertyChangeListener); - fPropertyChangeListener= null; - } - - if (fMenu != null && !fMenu.isDisposed()) { - fMenu.dispose(); - fMenu= null; - } - - if (fActionGroups != null) - fActionGroups.dispose(); - - fTogglePresentation.setEditor(null); - fPreviousError.setEditor(null); - fNextError.setEditor(null); - - fOutlineViewer= null; - - super.dispose(); - } - - public Control getControl() { - if (fOutlineViewer != null) - return fOutlineViewer.getControl(); - return null; - } - - public void setInput(IJavaElement inputElement) { - fInput= inputElement; - if (fOutlineViewer != null) - fOutlineViewer.setInput(fInput); - } - - public void select(ISourceReference reference) { - if (fOutlineViewer != null) { - - ISelection s= fOutlineViewer.getSelection(); - if (s instanceof IStructuredSelection) { - IStructuredSelection ss= (IStructuredSelection) s; - List elements= ss.toList(); - if (!elements.contains(reference)) { - s= (reference == null ? StructuredSelection.EMPTY : new StructuredSelection(reference)); - fOutlineViewer.setSelection(s, true); - } - } - } - } - - public void setAction(String actionID, IAction action) { - Assert.isNotNull(actionID); - if (action == null) - fActions.remove(actionID); - else - fActions.put(actionID, action); - } - - public IAction getAction(String actionID) { - Assert.isNotNull(actionID); - return (IAction) fActions.get(actionID); - } + // remove children + Item[] c = getChildren(item); + if (c != null && c.length > 0) { - /** - * Answer the property defined by key. - */ - public Object getAdapter(Class key) { - if (key == IShowInSource.class) { - return getShowInSource(); - } - if (key == IShowInTargetList.class) { - return new IShowInTargetList() { - public String[] getShowInTargetIds() { - return new String[] { JavaUI.ID_PACKAGES }; - } + if (getExpanded(item)) + fReusedExpandedItem = item; - }; - } - if (key == IShowInTarget.class) { - return getShowInTarget(); - } + for (int k = 0; k < c.length; k++) { + if (c[k].getData() != null) + disassociate(c[k]); + c[k].dispose(); + } + } - return null; - } + updateItem(item, element); + updatePlus(item, element); + internalExpandToLevel(item, ALL_LEVELS); - /** - * Convenience method to add the action installed under the given actionID to the - * specified group of the menu. - */ - protected void addAction(IMenuManager menu, String group, String actionID) { - IAction action= getAction(actionID); - if (action != null) { - if (action instanceof IUpdate) - ((IUpdate) action).update(); - - if (action.isEnabled()) { - IMenuManager subMenu= menu.findMenuUsingPath(group); - if (subMenu != null) - subMenu.add(action); - else - menu.appendToGroup(group, action); - } - } - } - - protected void contextMenuAboutToShow(IMenuManager menu) { - - PHPeclipsePlugin.createStandardGroups(menu); - - IStructuredSelection selection= (IStructuredSelection)getSelection(); - fActionGroups.setContext(new ActionContext(selection)); - fActionGroups.fillContextMenu(menu); - } - - /* - * @see Page#setFocus() - */ - public void setFocus() { - if (fOutlineViewer != null) - fOutlineViewer.getControl().setFocus(); - } - - /** - * Checkes whether a given Java element is an inner type. + fReusedExpandedItem = null; + fForceFireSelectionChanged= true; + } + + protected boolean mustUpdateParent(IJavaElementDelta delta, IJavaElement element) { +// if (element instanceof IMethod) { +// if ((delta.getKind() & IJavaElementDelta.ADDED) != 0) { +// try { +// return ((IMethod) element).isMainMethod(); +// } catch (JavaModelException e) { +// PHPeclipsePlugin.log(e.getStatus()); +// } +// } +// return "main".equals(element.getElementName()); //$NON-NLS-1$ +// } + return false; + } + /* + * @see org.eclipse.jface.viewers.AbstractTreeViewer#isExpandable(java.lang.Object) */ - private boolean isInnerType(IJavaElement element) { - - if (element.getElementType() == IJavaElement.TYPE) { - IJavaElement parent= element.getParent(); - int type= parent.getElementType(); - return (type != IJavaElement.COMPILATION_UNIT && type != IJavaElement.CLASS_FILE); + public boolean isExpandable(Object element) { + if (hasFilters()) { + return getFilteredChildren(element).length > 0; } - - return false; - } - - /** - * Handles key events in viewer. - */ - private void handleKeyReleased(KeyEvent event) { - - if (event.stateMask != 0) - return; - - IAction action= null; -// if (event.character == SWT.DEL) { -// action= fCCPActionGroup.getDeleteAction(); -// } - - if (action != null && action.isEnabled()) - action.run(); - } - - /** - * Returns the IShowInSource for this view. - */ - protected IShowInSource getShowInSource() { - return new IShowInSource() { - public ShowInContext getShowInContext() { - return new ShowInContext( - null, - getSite().getSelectionProvider().getSelection()); - } - }; + return super.isExpandable(element); } + protected ISourceRange getSourceRange(IJavaElement element) throws JavaModelException { + if (element instanceof IMember)// && !(element instanceof IInitializer)) + return ((IMember) element).getNameRange(); + if (element instanceof ISourceReference) + return ((ISourceReference) element).getSourceRange(); + return null; + } + + protected boolean overlaps(ISourceRange range, int start, int end) { + return start <= (range.getOffset() + range.getLength() - 1) && range.getOffset() <= end; + } + + protected boolean filtered(IJavaElement parent, IJavaElement child) { + + Object[] result = new Object[] { child }; + ViewerFilter[] filters = getFilters(); + for (int i = 0; i < filters.length; i++) { + result = filters[i].filter(this, parent, result); + if (result.length == 0) + return true; + } + + return false; + } + + protected void update(Widget w, IJavaElementDelta delta) { + + Item item; + + IJavaElement parent = delta.getElement(); + IJavaElementDelta[] affected = delta.getAffectedChildren(); + Item[] children = getChildren(w); + + boolean doUpdateParent = false; + boolean doUpdateParentsPlus = false; + + Vector deletions = new Vector(); + Vector additions = new Vector(); + + for (int i = 0; i < affected.length; i++) { + IJavaElementDelta affectedDelta = affected[i]; + IJavaElement affectedElement = affectedDelta.getElement(); + int status = affected[i].getKind(); + + // find tree item with affected element + int j; + for (j = 0; j < children.length; j++) + if (affectedElement.equals(children[j].getData())) + break; + + if (j == children.length) { + // remove from collapsed parent + if ((status & IJavaElementDelta.REMOVED) != 0) { + doUpdateParentsPlus = true; + continue; + } + // addition + if ((status & IJavaElementDelta.CHANGED) != 0 && (affectedDelta.getFlags() & IJavaElementDelta.F_MODIFIERS) != 0 + && !filtered(parent, affectedElement)) { + additions.addElement(affectedDelta); + } + continue; + } + + item = children[j]; + + // removed + if ((status & IJavaElementDelta.REMOVED) != 0) { + deletions.addElement(item); + doUpdateParent = doUpdateParent || mustUpdateParent(affectedDelta, affectedElement); + + // changed + } else if ((status & IJavaElementDelta.CHANGED) != 0) { + int change = affectedDelta.getFlags(); + doUpdateParent = doUpdateParent || mustUpdateParent(affectedDelta, affectedElement); + + if ((change & IJavaElementDelta.F_MODIFIERS) != 0) { + if (filtered(parent, affectedElement)) + deletions.addElement(item); + else + updateItem(item, affectedElement); + } + + if ((change & IJavaElementDelta.F_CONTENT) != 0) + updateItem(item, affectedElement); + + if ((change & IJavaElementDelta.F_CHILDREN) != 0) + update(item, affectedDelta); + + if ((change & IJavaElementDelta.F_REORDER) != 0) + fReorderedMembers = true; + } + } + + // find all elements to add + IJavaElementDelta[] add = delta.getAddedChildren(); + if (additions.size() > 0) { + IJavaElementDelta[] tmp = new IJavaElementDelta[add.length + additions.size()]; + System.arraycopy(add, 0, tmp, 0, add.length); + for (int i = 0; i < additions.size(); i++) + tmp[i + add.length] = (IJavaElementDelta) additions.elementAt(i); + add = tmp; + } + + // add at the right position + go2: for (int i = 0; i < add.length; i++) { + + try { + + IJavaElement e = add[i].getElement(); + if (filtered(parent, e)) + continue go2; + + doUpdateParent = doUpdateParent || mustUpdateParent(add[i], e); + ISourceRange rng = getSourceRange(e); + int start = rng.getOffset(); + int end = start + rng.getLength() - 1; - /** - * Returns the IShowInTarget for this view. + Item last = null; + item = null; + children = getChildren(w); + + for (int j = 0; j < children.length; j++) { + item = children[j]; + IJavaElement r = (IJavaElement) item.getData(); + + if (r == null) { + // parent node collapsed and not be opened before -> do nothing + continue go2; + } + + try { + rng = getSourceRange(r); + if (overlaps(rng, start, end)) { + + // be tolerant if the delta is not correct, or if + // the tree has been updated other than by a delta + reuseTreeItem(item, e); + continue go2; + + } else if (rng.getOffset() > start) { + + if (last != null && deletions.contains(last)) { + // reuse item + deletions.removeElement(last); + reuseTreeItem(last, (Object) e); + } else { + // nothing to reuse + createTreeItem(w, (Object) e, j); + } + continue go2; + } + + } catch (JavaModelException x) { + // stumbled over deleted element + } + + last = item; + } + + // add at the end of the list + if (last != null && deletions.contains(last)) { + // reuse item + deletions.removeElement(last); + reuseTreeItem(last, e); + } else { + // nothing to reuse + createTreeItem(w, e, -1); + } + + } catch (JavaModelException x) { + // the element to be added is not present -> don't add it + } + } + + // remove items which haven't been reused + Enumeration e = deletions.elements(); + while (e.hasMoreElements()) { + item = (Item) e.nextElement(); + disassociate(item); + item.dispose(); + } + + if (doUpdateParent) + updateItem(w, delta.getElement()); + if (!doUpdateParent && doUpdateParentsPlus && w instanceof Item) + updatePlus((Item) w, delta.getElement()); + } + + /* + * @see ContentViewer#handleLabelProviderChanged(LabelProviderChangedEvent) + */ + protected void handleLabelProviderChanged(LabelProviderChangedEvent event) { + Object input = getInput(); + if (event instanceof ProblemsLabelChangedEvent) { + ProblemsLabelChangedEvent e = (ProblemsLabelChangedEvent) event; + if (e.isMarkerChange() && input instanceof ICompilationUnit) { + return; // marker changes can be ignored + } + } + // look if the underlying resource changed + Object[] changed = event.getElements(); + if (changed != null) { + IResource resource = getUnderlyingResource(); + if (resource != null) { + for (int i = 0; i < changed.length; i++) { + if (changed[i] != null && changed[i].equals(resource)) { + // change event to a full refresh + event = new LabelProviderChangedEvent((IBaseLabelProvider) event.getSource()); + break; + } + } + } + } + super.handleLabelProviderChanged(event); + } + + private IResource getUnderlyingResource() { + Object input = getInput(); + if (input instanceof ICompilationUnit) { + ICompilationUnit cu = (ICompilationUnit) input; + if (cu.isWorkingCopy()) { + return cu.getOriginalElement().getResource(); + } else { + return cu.getResource(); + } + } + // else if (input instanceof IClassFile) { + // return ((IClassFile) input).getResource(); + // } + return null; + } + + }; + + class LexicalSortingAction extends Action { + + private JavaElementSorter fSorter = new JavaElementSorter(); + + public LexicalSortingAction() { + super(); + // WorkbenchHelp.setHelp(this, IJavaHelpContextIds.LEXICAL_SORTING_OUTLINE_ACTION); + setText(PHPEditorMessages.getString("JavaOutlinePage.Sort.label")); //$NON-NLS-1$ + PHPUiImages.setLocalImageDescriptors(this, "alphab_sort_co.gif"); //$NON-NLS-1$ + setToolTipText(PHPEditorMessages.getString("JavaOutlinePage.Sort.tooltip")); //$NON-NLS-1$ + setDescription(PHPEditorMessages.getString("JavaOutlinePage.Sort.description")); //$NON-NLS-1$ + + boolean checked = PHPeclipsePlugin.getDefault().getPreferenceStore().getBoolean("LexicalSortingAction.isChecked"); //$NON-NLS-1$ + valueChanged(checked, false); + } + + public void run() { + valueChanged(isChecked(), true); + } + + private void valueChanged(final boolean on, boolean store) { + setChecked(on); + BusyIndicator.showWhile(fOutlineViewer.getControl().getDisplay(), new Runnable() { + public void run() { + fOutlineViewer.setSorter(on ? fSorter : null); + } + }); + + if (store) + PHPeclipsePlugin.getDefault().getPreferenceStore().setValue("LexicalSortingAction.isChecked", on); //$NON-NLS-1$ + } + }; + + class ClassOnlyAction extends Action { + + public ClassOnlyAction() { + super(); + // WorkbenchHelp.setHelp(this, IJavaHelpContextIds.GO_INTO_TOP_LEVEL_TYPE_ACTION); + setText(PHPEditorMessages.getString("JavaOutlinePage.GoIntoTopLevelType.label")); //$NON-NLS-1$ + setToolTipText(PHPEditorMessages.getString("JavaOutlinePage.GoIntoTopLevelType.tooltip")); //$NON-NLS-1$ + setDescription(PHPEditorMessages.getString("JavaOutlinePage.GoIntoTopLevelType.description")); //$NON-NLS-1$ + PHPUiImages.setLocalImageDescriptors(this, "gointo_toplevel_type.gif"); //$NON-NLS-1$ + + IPreferenceStore preferenceStore = PHPeclipsePlugin.getDefault().getPreferenceStore(); + boolean showclass = preferenceStore.getBoolean("GoIntoTopLevelTypeAction.isChecked"); //$NON-NLS-1$ + setTopLevelTypeOnly(showclass); + } + + /* + * @see org.eclipse.jface.action.Action#run() + */ + public void run() { + setTopLevelTypeOnly(!fTopLevelTypeOnly); + } + + private void setTopLevelTypeOnly(boolean show) { + fTopLevelTypeOnly = show; + setChecked(show); + fOutlineViewer.refresh(false); + + IPreferenceStore preferenceStore = PHPeclipsePlugin.getDefault().getPreferenceStore(); + preferenceStore.setValue("GoIntoTopLevelTypeAction.isChecked", show); //$NON-NLS-1$ + } + }; + + /** + * This action toggles whether this Java Outline page links its selection to the active editor. + * + * @since 3.0 + */ + public class ToggleLinkingAction extends AbstractToggleLinkingAction { + + JavaOutlinePage fJavaOutlinePage; + + /** + * Constructs a new action. + * + * @param outlinePage + * the Java outline page + */ + public ToggleLinkingAction(JavaOutlinePage outlinePage) { + boolean isLinkingEnabled = PreferenceConstants.getPreferenceStore().getBoolean( + PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE); + setChecked(isLinkingEnabled); + fJavaOutlinePage = outlinePage; + } + + /** + * Runs the action. + */ + public void run() { + PreferenceConstants.getPreferenceStore().setValue(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE, isChecked()); + if (isChecked() && fEditor != null) + fEditor.synchronizeOutlinePage(fEditor.computeHighlightRangeSourceReference(), false); + } + + } + + /** A flag to show contents of top level type only */ + private boolean fTopLevelTypeOnly; + + private IJavaElement fInput; + + private String fContextMenuID; + + private Menu fMenu; + + private JavaOutlineViewer fOutlineViewer; + + private PHPEditor fEditor; + + private MemberFilterActionGroup fMemberFilterActionGroup; + + private ListenerList fSelectionChangedListeners = new ListenerList(); + + private ListenerList fPostSelectionChangedListeners = new ListenerList(); + + private Hashtable fActions = new Hashtable(); + + private TogglePresentationAction fTogglePresentation; + + private GotoErrorAction fPreviousError; + + private GotoErrorAction fNextError; + + private TextEditorAction fShowJavadoc; + + private TextOperationAction fUndo; + + private TextOperationAction fRedo; + + private ToggleLinkingAction fToggleLinkingAction; + + private CompositeActionGroup fActionGroups; + + // private CCPActionGroup fCCPActionGroup; + + private IPropertyChangeListener fPropertyChangeListener; + /** + * Custom filter action group. + * @since 3.0 */ - protected IShowInTarget getShowInTarget() { - return new IShowInTarget() { - public boolean show(ShowInContext context) { - ISelection sel= context.getSelection(); - if (sel instanceof ITextSelection) { - ITextSelection tsel= (ITextSelection) sel; - int offset= tsel.getOffset(); - IJavaElement element= fEditor.getElementAt(offset); - if (element != null) { - setSelection(new StructuredSelection(element)); - return true; - } - } - return false; - } - }; - } +// private CustomFiltersActionGroup fCustomFiltersActionGroup; - private void initDragAndDrop() { - int ops= DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK; - Transfer[] transfers= new Transfer[] { - LocalSelectionTransfer.getInstance() - }; - - // Drop Adapter -// TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] { -// new SelectionTransferDropAdapter(fOutlineViewer) -// }; -// fOutlineViewer.addDropSupport(ops | DND.DROP_DEFAULT, transfers, new DelegatingDropAdapter(dropListeners)); - - // Drag Adapter - TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] { - new SelectionTransferDragAdapter(fOutlineViewer) - }; - fOutlineViewer.addDragSupport(ops, transfers, new JdtViewerDragAdapter(fOutlineViewer, dragListeners)); - } -} + public JavaOutlinePage(String contextMenuID, PHPEditor editor) { + super(); + + Assert.isNotNull(editor); + + fContextMenuID = contextMenuID; + fEditor = editor; + + fTogglePresentation = new TogglePresentationAction(); + fPreviousError = new GotoErrorAction("PreviousError.", false); //$NON-NLS-1$ + fPreviousError.setImageDescriptor(PHPUiImages.DESC_TOOL_GOTO_PREV_ERROR); + fNextError = new GotoErrorAction("NextError.", true); //$NON-NLS-1$ + fNextError.setImageDescriptor(PHPUiImages.DESC_TOOL_GOTO_NEXT_ERROR); + fShowJavadoc = (TextEditorAction) fEditor.getAction("ShowJavaDoc"); //$NON-NLS-1$ + fUndo = (TextOperationAction) fEditor.getAction(ITextEditorActionConstants.UNDO); + fRedo = (TextOperationAction) fEditor.getAction(ITextEditorActionConstants.REDO); + + fTogglePresentation.setEditor(editor); + fPreviousError.setEditor(editor); + fNextError.setEditor(editor); + + fPropertyChangeListener = new IPropertyChangeListener() { + public void propertyChange(PropertyChangeEvent event) { + doPropertyChange(event); + } + }; + PHPeclipsePlugin.getDefault().getPreferenceStore().addPropertyChangeListener(fPropertyChangeListener); + } + + /** + * Returns the primary type of a compilation unit (has the same name as the compilation unit). + * + * @param compilationUnit + * the compilation unit + * @return returns the primary type of the compilation unit, or null if is does not have one + */ + protected IType getMainType(ICompilationUnit compilationUnit) { + String name = compilationUnit.getElementName(); + int index = name.indexOf('.'); + if (index != -1) + name = name.substring(0, index); + IType type = compilationUnit.getType(name); + return type.exists() ? type : null; + } + + /** + * Returns the primary type of a class file. + * + * @param classFile + * the class file + * @return returns the primary type of the class file, or null if is does not have one + */ + // protected IType getMainType(IClassFile classFile) { + // try { + // IType type= classFile.getType(); + // return type != null && type.exists() ? type : null; + // } catch (JavaModelException e) { + // return null; + // } + // } + /* + * (non-Javadoc) Method declared on Page + */ + public void init(IPageSite pageSite) { + super.init(pageSite); + } + + private void doPropertyChange(PropertyChangeEvent event) { + if (fOutlineViewer != null) { + if (PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER.equals(event.getProperty())) { + fOutlineViewer.refresh(false); + } + } + } + + /* + * @see ISelectionProvider#addSelectionChangedListener(ISelectionChangedListener) + */ + public void addSelectionChangedListener(ISelectionChangedListener listener) { + if (fOutlineViewer != null) + fOutlineViewer.addPostSelectionChangedListener(listener); + else + fSelectionChangedListeners.add(listener); + } + + /* + * @see ISelectionProvider#removeSelectionChangedListener(ISelectionChangedListener) + */ + public void removeSelectionChangedListener(ISelectionChangedListener listener) { + if (fOutlineViewer != null) + fOutlineViewer.removePostSelectionChangedListener(listener); + else + fSelectionChangedListeners.remove(listener); + } + + /* + * @see ISelectionProvider#setSelection(ISelection) + */ + public void setSelection(ISelection selection) { + if (fOutlineViewer != null) + fOutlineViewer.setSelection(selection); + } + + /* + * @see ISelectionProvider#getSelection() + */ + public ISelection getSelection() { + if (fOutlineViewer == null) + return StructuredSelection.EMPTY; + return fOutlineViewer.getSelection(); + } + + // private void registerToolbarActions() { + // + // IToolBarManager toolBarManager = getSite().getActionBars().getToolBarManager(); + // if (toolBarManager != null) { + // toolBarManager.add(new ClassOnlyAction()); + // toolBarManager.add(new LexicalSortingAction()); + // + // fMemberFilterActionGroup = new MemberFilterActionGroup(fOutlineViewer, "JavaOutlineViewer"); //$NON-NLS-1$ + // fMemberFilterActionGroup.contributeToToolBar(toolBarManager); + // + // } + // } + + private void registerToolbarActions(IActionBars actionBars) { + + IToolBarManager toolBarManager = actionBars.getToolBarManager(); + if (toolBarManager != null) { + toolBarManager.add(new LexicalSortingAction()); + + fMemberFilterActionGroup = new MemberFilterActionGroup(fOutlineViewer, "org.eclipse.jdt.ui.JavaOutlinePage"); //$NON-NLS-1$ + fMemberFilterActionGroup.contributeToToolBar(toolBarManager); + + // fCustomFiltersActionGroup.fillActionBars(actionBars); + + IMenuManager menu = actionBars.getMenuManager(); + menu.add(new Separator("EndFilterGroup")); //$NON-NLS-1$ + + fToggleLinkingAction = new ToggleLinkingAction(this); + menu.add(new ClassOnlyAction()); + menu.add(fToggleLinkingAction); + } + } + + /* + * @see IPage#createControl + */ + public void createControl(Composite parent) { + + Tree tree = new Tree(parent, SWT.MULTI); + + AppearanceAwareLabelProvider lprovider = new AppearanceAwareLabelProvider(AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS + | JavaElementLabels.F_APP_TYPE_SIGNATURE, AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS); + + fOutlineViewer = new JavaOutlineViewer(tree); + fOutlineViewer.setContentProvider(new ChildrenProvider()); + fOutlineViewer.setLabelProvider(new DecoratingJavaLabelProvider(lprovider)); + + Object[] listeners = fSelectionChangedListeners.getListeners(); + for (int i = 0; i < listeners.length; i++) { + fSelectionChangedListeners.remove(listeners[i]); + fOutlineViewer.addPostSelectionChangedListener((ISelectionChangedListener) listeners[i]); + } + + listeners = fPostSelectionChangedListeners.getListeners(); + for (int i = 0; i < listeners.length; i++) { + fPostSelectionChangedListeners.remove(listeners[i]); + fOutlineViewer.addPostSelectionChangedListener((ISelectionChangedListener) listeners[i]); + } + + MenuManager manager = new MenuManager(fContextMenuID, fContextMenuID); + manager.setRemoveAllWhenShown(true); + manager.addMenuListener(new IMenuListener() { + public void menuAboutToShow(IMenuManager manager) { + contextMenuAboutToShow(manager); + } + }); + fMenu = manager.createContextMenu(tree); + tree.setMenu(fMenu); + + IPageSite site = getSite(); + site.registerContextMenu(PHPeclipsePlugin.getPluginId() + ".outline", manager, fOutlineViewer); //$NON-NLS-1$ + site.setSelectionProvider(fOutlineViewer); + + // we must create the groups after we have set the selection provider to the site + fActionGroups = new CompositeActionGroup(new ActionGroup[] { + // new OpenViewActionGroup(this), + // fCCPActionGroup= new CCPActionGroup(this), + new GenerateActionGroup(this) }); + // new RefactorActionGroup(this), + // new JavaSearchActionGroup(this)}); + + // register global actions + IActionBars bars = site.getActionBars(); + + bars.setGlobalActionHandler(ITextEditorActionConstants.UNDO, fUndo); + bars.setGlobalActionHandler(ITextEditorActionConstants.REDO, fRedo); + bars.setGlobalActionHandler(ITextEditorActionConstants.PREVIOUS, fPreviousError); + bars.setGlobalActionHandler(ITextEditorActionConstants.NEXT, fNextError); + // bars.setGlobalActionHandler(PHPdtActionConstants.SHOW_PHP_DOC, fShowJavadoc); + bars.setGlobalActionHandler(IJavaEditorActionConstants.TOGGLE_PRESENTATION, fTogglePresentation); + // http://dev.eclipse.org/bugs/show_bug.cgi?id=18968 + bars.setGlobalActionHandler(IJavaEditorActionConstants.PREVIOUS_ERROR, fPreviousError); + bars.setGlobalActionHandler(IJavaEditorActionConstants.NEXT_ERROR, fNextError); + + fActionGroups.fillActionBars(bars); + + IStatusLineManager statusLineManager = site.getActionBars().getStatusLineManager(); + if (statusLineManager != null) { + StatusBarUpdater updater = new StatusBarUpdater(statusLineManager); + fOutlineViewer.addPostSelectionChangedListener(updater); + } + + registerToolbarActions(bars); + + fOutlineViewer.setInput(fInput); + // fOutlineViewer.getControl().addKeyListener(new KeyAdapter() { + // public void keyPressed(KeyEvent e) { + // handleKeyReleased(e); + // } + // }); + // + // initDragAndDrop(); + } + + public void dispose() { + + if (fEditor == null) + return; + + if (fMemberFilterActionGroup != null) { + fMemberFilterActionGroup.dispose(); + fMemberFilterActionGroup = null; + } + + fEditor.outlinePageClosed(); + fEditor = null; + + fSelectionChangedListeners.clear(); + fSelectionChangedListeners = null; + + fPostSelectionChangedListeners.clear(); + fPostSelectionChangedListeners = null; + + if (fPropertyChangeListener != null) { + PHPeclipsePlugin.getDefault().getPreferenceStore().removePropertyChangeListener(fPropertyChangeListener); + fPropertyChangeListener = null; + } + + if (fMenu != null && !fMenu.isDisposed()) { + fMenu.dispose(); + fMenu = null; + } + + if (fActionGroups != null) + fActionGroups.dispose(); + + fTogglePresentation.setEditor(null); + fPreviousError.setEditor(null); + fNextError.setEditor(null); + + fOutlineViewer = null; + + super.dispose(); + } + + public Control getControl() { + if (fOutlineViewer != null) + return fOutlineViewer.getControl(); + return null; + } + + public void setInput(IJavaElement inputElement) { + fInput = inputElement; + if (fOutlineViewer != null) + fOutlineViewer.setInput(fInput); + } + + public void select(ISourceReference reference) { + if (fOutlineViewer != null) { + + ISelection s = fOutlineViewer.getSelection(); + if (s instanceof IStructuredSelection) { + IStructuredSelection ss = (IStructuredSelection) s; + List elements = ss.toList(); + if (!elements.contains(reference)) { + s = (reference == null ? StructuredSelection.EMPTY : new StructuredSelection(reference)); + fOutlineViewer.setSelection(s, true); + } + } + } + } + + public void setAction(String actionID, IAction action) { + Assert.isNotNull(actionID); + if (action == null) + fActions.remove(actionID); + else + fActions.put(actionID, action); + } + + public IAction getAction(String actionID) { + Assert.isNotNull(actionID); + return (IAction) fActions.get(actionID); + } + + /** + * Answer the property defined by key. + */ + public Object getAdapter(Class key) { + if (key == IShowInSource.class) { + return getShowInSource(); + } + if (key == IShowInTargetList.class) { + return new IShowInTargetList() { + public String[] getShowInTargetIds() { + return new String[] { JavaUI.ID_PACKAGES }; + } + + }; + } + if (key == IShowInTarget.class) { + return getShowInTarget(); + } + + return null; + } + + /** + * Convenience method to add the action installed under the given actionID to the specified group of the menu. + */ + protected void addAction(IMenuManager menu, String group, String actionID) { + IAction action = getAction(actionID); + if (action != null) { + if (action instanceof IUpdate) + ((IUpdate) action).update(); + + if (action.isEnabled()) { + IMenuManager subMenu = menu.findMenuUsingPath(group); + if (subMenu != null) + subMenu.add(action); + else + menu.appendToGroup(group, action); + } + } + } + + protected void contextMenuAboutToShow(IMenuManager menu) { + + PHPeclipsePlugin.createStandardGroups(menu); + + IStructuredSelection selection = (IStructuredSelection) getSelection(); + fActionGroups.setContext(new ActionContext(selection)); + fActionGroups.fillContextMenu(menu); + } + + /* + * @see Page#setFocus() + */ + public void setFocus() { + if (fOutlineViewer != null) + fOutlineViewer.getControl().setFocus(); + } + + /** + * Checkes whether a given Java element is an inner type. + */ + private boolean isInnerType(IJavaElement element) { + + if (element.getElementType() == IJavaElement.TYPE) { + IJavaElement parent = element.getParent(); + int type = parent.getElementType(); + return (type != IJavaElement.COMPILATION_UNIT && type != IJavaElement.CLASS_FILE); + } + + return false; + } + + /** + * Handles key events in viewer. + */ + private void handleKeyReleased(KeyEvent event) { + + if (event.stateMask != 0) + return; + + IAction action = null; + // if (event.character == SWT.DEL) { + // action= fCCPActionGroup.getDeleteAction(); + // } + + if (action != null && action.isEnabled()) + action.run(); + } + + /** + * Returns the IShowInSource for this view. + */ + protected IShowInSource getShowInSource() { + return new IShowInSource() { + public ShowInContext getShowInContext() { + return new ShowInContext(null, getSite().getSelectionProvider().getSelection()); + } + }; + } + + /** + * Returns the IShowInTarget for this view. + */ + protected IShowInTarget getShowInTarget() { + return new IShowInTarget() { + public boolean show(ShowInContext context) { + ISelection sel = context.getSelection(); + if (sel instanceof ITextSelection) { + ITextSelection tsel = (ITextSelection) sel; + int offset = tsel.getOffset(); + IJavaElement element = fEditor.getElementAt(offset); + if (element != null) { + setSelection(new StructuredSelection(element)); + return true; + } + } + return false; + } + }; + } + + private void initDragAndDrop() { + int ops = DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK; + Transfer[] transfers = new Transfer[] { LocalSelectionTransfer.getInstance() }; + + // Drop Adapter + // TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] { + // new SelectionTransferDropAdapter(fOutlineViewer) + // }; + // fOutlineViewer.addDropSupport(ops | DND.DROP_DEFAULT, transfers, new DelegatingDropAdapter(dropListeners)); + + // Drag Adapter + TransferDragSourceListener[] dragListeners = new TransferDragSourceListener[] { new SelectionTransferDragAdapter(fOutlineViewer) }; + fOutlineViewer.addDragSupport(ops, transfers, new JdtViewerDragAdapter(fOutlineViewer, dragListeners)); + } + + /* + * @see org.eclipse.jface.text.IPostSelectionProvider#addPostSelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener) + */ + public void addPostSelectionChangedListener(ISelectionChangedListener listener) { + if (fOutlineViewer != null) + fOutlineViewer.addPostSelectionChangedListener(listener); + else + fPostSelectionChangedListeners.add(listener); + } + + /* + * @see org.eclipse.jface.text.IPostSelectionProvider#removePostSelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener) + */ + public void removePostSelectionChangedListener(ISelectionChangedListener listener) { + if (fOutlineViewer != null) + fOutlineViewer.removePostSelectionChangedListener(listener); + else + fPostSelectionChangedListeners.remove(listener); + } +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaSourceViewer.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaSourceViewer.java index e3e75ac..c5f8376 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaSourceViewer.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/JavaSourceViewer.java @@ -21,6 +21,7 @@ import org.eclipse.jface.preference.PreferenceConverter; import org.eclipse.jface.text.Assert; import org.eclipse.jface.text.ITextPresentationListener; import org.eclipse.jface.text.information.IInformationPresenter; +import org.eclipse.jface.text.reconciler.IReconciler; import org.eclipse.jface.text.source.IOverviewRuler; import org.eclipse.jface.text.source.IVerticalRuler; import org.eclipse.jface.text.source.SourceViewerConfiguration; @@ -401,4 +402,23 @@ public class JavaSourceViewer extends ProjectionViewer implements IPropertyChang fTextPresentationListeners.remove(listener); fTextPresentationListeners.add(0, listener); } + /** + * Sets the given reconciler. + * + * @param reconciler the reconciler + * @since 3.0 + */ + void setReconciler(IReconciler reconciler) { + fReconciler= reconciler; + } + + /** + * Returns the reconciler. + * + * @return the reconciler or null if not set + * @since 3.0 + */ + Object getReconciler() { + return fReconciler; + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPEditor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPEditor.java index 3da3755..d7b5126 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPEditor.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPEditor.java @@ -1,16 +1,16 @@ package net.sourceforge.phpeclipse.phpeditor; /********************************************************************** -Copyright (c) 2000, 2002 IBM Corp. and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Common Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/cpl-v10.html - -Contributors: - IBM Corporation - Initial implementation - Klaus Hartlage - www.eclipseproject.de -**********************************************************************/ + Copyright (c) 2000, 2002 IBM Corp. and others. + All rights reserved. This program and the accompanying materials + are made available under the terms of the Common Public License v1.0 + which accompanies this distribution, and is available at + http://www.eclipse.org/legal/cpl-v10.html + + Contributors: + IBM Corporation - Initial implementation + Klaus Hartlage - www.eclipseproject.de + **********************************************************************/ import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; @@ -20,6 +20,8 @@ import java.util.ResourceBundle; import java.util.StringTokenizer; import net.sourceforge.phpdt.core.ICompilationUnit; +import net.sourceforge.phpdt.core.IImportContainer; +import net.sourceforge.phpdt.core.IImportDeclaration; import net.sourceforge.phpdt.core.IJavaElement; import net.sourceforge.phpdt.core.IJavaProject; import net.sourceforge.phpdt.core.IMember; @@ -72,12 +74,14 @@ import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.ITextViewerExtension2; import org.eclipse.jface.text.ITextViewerExtension3; +import org.eclipse.jface.text.ITextViewerExtension5; import org.eclipse.jface.text.ITypedRegion; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.Region; import org.eclipse.jface.text.TextSelection; import org.eclipse.jface.text.information.IInformationProvider; import org.eclipse.jface.text.information.InformationPresenter; +import org.eclipse.jface.text.reconciler.IReconciler; import org.eclipse.jface.text.source.Annotation; import org.eclipse.jface.text.source.IAnnotationModel; import org.eclipse.jface.text.source.IAnnotationModelExtension; @@ -91,6 +95,7 @@ import org.eclipse.jface.text.source.projection.ProjectionViewer; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.ListenerList; import org.eclipse.jface.util.PropertyChangeEvent; +import org.eclipse.jface.viewers.IPostSelectionProvider; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ISelectionProvider; @@ -135,6 +140,7 @@ import org.eclipse.ui.editors.text.EditorsUI; import org.eclipse.ui.editors.text.IEncodingSupport; import org.eclipse.ui.part.IShowInTargetList; import org.eclipse.ui.texteditor.AbstractDecoratedTextEditor; +import org.eclipse.ui.texteditor.AnnotationPreference; import org.eclipse.ui.texteditor.ChainedPreferenceStore; import org.eclipse.ui.texteditor.DefaultRangeIndicator; import org.eclipse.ui.texteditor.IDocumentProvider; @@ -144,17 +150,80 @@ import org.eclipse.ui.texteditor.MarkerAnnotation; import org.eclipse.ui.texteditor.ResourceAction; import org.eclipse.ui.texteditor.TextEditorAction; import org.eclipse.ui.texteditor.TextOperationAction; +import org.eclipse.ui.views.contentoutline.ContentOutline; import org.eclipse.ui.views.contentoutline.IContentOutlinePage; import org.eclipse.ui.views.tasklist.TaskList; /** * PHP specific text editor. */ -public abstract class PHPEditor extends AbstractDecoratedTextEditor implements IViewPartInputProvider { -//extends StatusTextEditor implements IViewPartInputProvider { // extends TextEditor { +public abstract class PHPEditor extends AbstractDecoratedTextEditor implements IViewPartInputProvider { + //extends StatusTextEditor implements IViewPartInputProvider { // extends + // TextEditor { + /** - * "Smart" runnable for updating the outline page's selection. - */ + * Internal implementation class for a change listener. + * + * @since 3.0 + */ + protected abstract class AbstractSelectionChangedListener implements ISelectionChangedListener { + + /** + * Installs this selection changed listener with the given selection provider. If the selection provider is a post selection + * provider, post selection changed events are the preferred choice, otherwise normal selection changed events are requested. + * + * @param selectionProvider + */ + public void install(ISelectionProvider selectionProvider) { + if (selectionProvider == null) + return; + + if (selectionProvider instanceof IPostSelectionProvider) { + IPostSelectionProvider provider = (IPostSelectionProvider) selectionProvider; + provider.addPostSelectionChangedListener(this); + } else { + selectionProvider.addSelectionChangedListener(this); + } + } + + /** + * Removes this selection changed listener from the given selection provider. + * + * @param selectionProvider + * the selection provider + */ + public void uninstall(ISelectionProvider selectionProvider) { + if (selectionProvider == null) + return; + + if (selectionProvider instanceof IPostSelectionProvider) { + IPostSelectionProvider provider = (IPostSelectionProvider) selectionProvider; + provider.removePostSelectionChangedListener(this); + } else { + selectionProvider.removeSelectionChangedListener(this); + } + } + } + + /** + * Updates the Java outline page selection and this editor's range indicator. + * + * @since 3.0 + */ + private class EditorSelectionChangedListener extends AbstractSelectionChangedListener { + + /* + * @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent) + */ + public void selectionChanged(SelectionChangedEvent event) { + // XXX: see https://bugs.eclipse.org/bugs/show_bug.cgi?id=56161 + PHPEditor.this.selectionChanged(); + } + } + + /** + * "Smart" runnable for updating the outline page's selection. + */ class OutlinePageSelectionUpdater implements Runnable { /** Has the runnable already been posted? */ @@ -185,6 +254,7 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements } } }; + class SelectionChangedListener implements ISelectionChangedListener { public void selectionChanged(SelectionChangedEvent event) { doSelectionChanged(event); @@ -192,404 +262,413 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements }; /** - * Adapts an options {@link java.util.Map} to {@link org.eclipse.jface.preference.IPreferenceStore}. - *

- * This preference store is read-only i.e. write access - * throws an {@link java.lang.UnsupportedOperationException}. - *

- * - * @since 3.0 - */ - private static class OptionsAdapter implements IPreferenceStore { + * Adapts an options {@link java.util.Map}to {@link org.eclipse.jface.preference.IPreferenceStore}. + *

+ * This preference store is read-only i.e. write access throws an {@link java.lang.UnsupportedOperationException}. + *

+ * + * @since 3.0 + */ + private static class OptionsAdapter implements IPreferenceStore { + /** + * A property change event filter. + */ + public interface IPropertyChangeEventFilter { + + /** + * Should the given event be filtered? + * + * @param event + * The property change event. + * @return true iff the given event should be filtered. + */ + public boolean isFiltered(PropertyChangeEvent event); - /** - * A property change event filter. - */ - public interface IPropertyChangeEventFilter { + } - /** - * Should the given event be filtered? - * @param event The property change event. - * @return true iff the given event should be filtered. - */ - public boolean isFiltered(PropertyChangeEvent event); + /** + * Property change listener. Listens for events in the options Map and fires a + * {@link org.eclipse.jface.util.PropertyChangeEvent}on this adapter with arguments from the received event. + */ + private class PropertyChangeListener implements IPropertyChangeListener { - } - /** - * Property change listener. Listens for events in the options Map and - * fires a {@link org.eclipse.jface.util.PropertyChangeEvent} - * on this adapter with arguments from the received event. - */ - private class PropertyChangeListener implements IPropertyChangeListener { - - /** - * {@inheritDoc} - */ - public void propertyChange(PropertyChangeEvent event) { - if (getFilter().isFiltered(event)) - return; - - if (event.getNewValue() == null) - fOptions.remove(event.getProperty()); - else - fOptions.put(event.getProperty(), event.getNewValue()); - - firePropertyChangeEvent(event.getProperty(), event.getOldValue(), event.getNewValue()); - } - } + /** + * {@inheritDoc} + */ + public void propertyChange(PropertyChangeEvent event) { + if (getFilter().isFiltered(event)) + return; - /** Listeners on this adapter */ - private ListenerList fListeners= new ListenerList(); + if (event.getNewValue() == null) + fOptions.remove(event.getProperty()); + else + fOptions.put(event.getProperty(), event.getNewValue()); - /** Listener on the adapted options Map */ - private IPropertyChangeListener fListener= new PropertyChangeListener(); + firePropertyChangeEvent(event.getProperty(), event.getOldValue(), event.getNewValue()); + } + } - /** Adapted options Map */ - private Map fOptions; + /** Listeners on this adapter */ + private ListenerList fListeners = new ListenerList(); - /** Preference store through which events are received. */ - private IPreferenceStore fMockupPreferenceStore; + /** Listener on the adapted options Map */ + private IPropertyChangeListener fListener = new PropertyChangeListener(); - /** Property event filter. */ - private IPropertyChangeEventFilter fFilter; - - /** - * Initialize with the given options. - * - * @param options The options to wrap - * @param mockupPreferenceStore the mock-up preference store - * @param filter the property change filter - */ - public OptionsAdapter(Map options, IPreferenceStore mockupPreferenceStore, IPropertyChangeEventFilter filter) { - fMockupPreferenceStore= mockupPreferenceStore; - fOptions= options; - setFilter(filter); - } + /** Adapted options Map */ + private Map fOptions; - /** - * {@inheritDoc} - */ - public void addPropertyChangeListener(IPropertyChangeListener listener) { - if (fListeners.size() == 0) - fMockupPreferenceStore.addPropertyChangeListener(fListener); - fListeners.add(listener); - } + /** Preference store through which events are received. */ + private IPreferenceStore fMockupPreferenceStore; - /** - * {@inheritDoc} - */ - public void removePropertyChangeListener(IPropertyChangeListener listener) { - fListeners.remove(listener); - if (fListeners.size() == 0) - fMockupPreferenceStore.removePropertyChangeListener(fListener); - } + /** Property event filter. */ + private IPropertyChangeEventFilter fFilter; - /** - * {@inheritDoc} - */ - public boolean contains(String name) { - return fOptions.containsKey(name); - } + /** + * Initialize with the given options. + * + * @param options + * The options to wrap + * @param mockupPreferenceStore + * the mock-up preference store + * @param filter + * the property change filter + */ + public OptionsAdapter(Map options, IPreferenceStore mockupPreferenceStore, IPropertyChangeEventFilter filter) { + fMockupPreferenceStore = mockupPreferenceStore; + fOptions = options; + setFilter(filter); + } - /** - * {@inheritDoc} - */ - public void firePropertyChangeEvent(String name, Object oldValue, Object newValue) { - PropertyChangeEvent event= new PropertyChangeEvent(this, name, oldValue, newValue); - Object[] listeners= fListeners.getListeners(); - for (int i= 0; i < listeners.length; i++) - ((IPropertyChangeListener) listeners[i]).propertyChange(event); - } + /** + * {@inheritDoc} + */ + public void addPropertyChangeListener(IPropertyChangeListener listener) { + if (fListeners.size() == 0) + fMockupPreferenceStore.addPropertyChangeListener(fListener); + fListeners.add(listener); + } - /** - * {@inheritDoc} - */ - public boolean getBoolean(String name) { - boolean value= BOOLEAN_DEFAULT_DEFAULT; - String s= (String) fOptions.get(name); - if (s != null) - value= s.equals(TRUE); - return value; - } + /** + * {@inheritDoc} + */ + public void removePropertyChangeListener(IPropertyChangeListener listener) { + fListeners.remove(listener); + if (fListeners.size() == 0) + fMockupPreferenceStore.removePropertyChangeListener(fListener); + } - /** - * {@inheritDoc} - */ - public boolean getDefaultBoolean(String name) { - return BOOLEAN_DEFAULT_DEFAULT; - } + /** + * {@inheritDoc} + */ + public boolean contains(String name) { + return fOptions.containsKey(name); + } - /** - * {@inheritDoc} - */ - public double getDefaultDouble(String name) { - return DOUBLE_DEFAULT_DEFAULT; - } + /** + * {@inheritDoc} + */ + public void firePropertyChangeEvent(String name, Object oldValue, Object newValue) { + PropertyChangeEvent event = new PropertyChangeEvent(this, name, oldValue, newValue); + Object[] listeners = fListeners.getListeners(); + for (int i = 0; i < listeners.length; i++) + ((IPropertyChangeListener) listeners[i]).propertyChange(event); + } - /** - * {@inheritDoc} - */ - public float getDefaultFloat(String name) { - return FLOAT_DEFAULT_DEFAULT; - } + /** + * {@inheritDoc} + */ + public boolean getBoolean(String name) { + boolean value = BOOLEAN_DEFAULT_DEFAULT; + String s = (String) fOptions.get(name); + if (s != null) + value = s.equals(TRUE); + return value; + } - /** - * {@inheritDoc} - */ - public int getDefaultInt(String name) { - return INT_DEFAULT_DEFAULT; - } + /** + * {@inheritDoc} + */ + public boolean getDefaultBoolean(String name) { + return BOOLEAN_DEFAULT_DEFAULT; + } - /** - * {@inheritDoc} - */ - public long getDefaultLong(String name) { - return LONG_DEFAULT_DEFAULT; - } + /** + * {@inheritDoc} + */ + public double getDefaultDouble(String name) { + return DOUBLE_DEFAULT_DEFAULT; + } - /** - * {@inheritDoc} - */ - public String getDefaultString(String name) { - return STRING_DEFAULT_DEFAULT; - } + /** + * {@inheritDoc} + */ + public float getDefaultFloat(String name) { + return FLOAT_DEFAULT_DEFAULT; + } - /** - * {@inheritDoc} - */ - public double getDouble(String name) { - double value= DOUBLE_DEFAULT_DEFAULT; - String s= (String) fOptions.get(name); - if (s != null) { - try { - value= new Double(s).doubleValue(); - } catch (NumberFormatException e) { - } - } - return value; - } + /** + * {@inheritDoc} + */ + public int getDefaultInt(String name) { + return INT_DEFAULT_DEFAULT; + } - /** - * {@inheritDoc} - */ - public float getFloat(String name) { - float value= FLOAT_DEFAULT_DEFAULT; - String s= (String) fOptions.get(name); - if (s != null) { - try { - value= new Float(s).floatValue(); - } catch (NumberFormatException e) { - } - } - return value; - } + /** + * {@inheritDoc} + */ + public long getDefaultLong(String name) { + return LONG_DEFAULT_DEFAULT; + } - /** - * {@inheritDoc} - */ - public int getInt(String name) { - int value= INT_DEFAULT_DEFAULT; - String s= (String) fOptions.get(name); - if (s != null) { - try { - value= new Integer(s).intValue(); - } catch (NumberFormatException e) { - } - } - return value; - } + /** + * {@inheritDoc} + */ + public String getDefaultString(String name) { + return STRING_DEFAULT_DEFAULT; + } - /** - * {@inheritDoc} - */ - public long getLong(String name) { - long value= LONG_DEFAULT_DEFAULT; - String s= (String) fOptions.get(name); - if (s != null) { - try { - value= new Long(s).longValue(); - } catch (NumberFormatException e) { - } - } - return value; - } + /** + * {@inheritDoc} + */ + public double getDouble(String name) { + double value = DOUBLE_DEFAULT_DEFAULT; + String s = (String) fOptions.get(name); + if (s != null) { + try { + value = new Double(s).doubleValue(); + } catch (NumberFormatException e) { + } + } + return value; + } - /** - * {@inheritDoc} - */ - public String getString(String name) { - String value= (String) fOptions.get(name); - if (value == null) - value= STRING_DEFAULT_DEFAULT; - return value; - } + /** + * {@inheritDoc} + */ + public float getFloat(String name) { + float value = FLOAT_DEFAULT_DEFAULT; + String s = (String) fOptions.get(name); + if (s != null) { + try { + value = new Float(s).floatValue(); + } catch (NumberFormatException e) { + } + } + return value; + } - /** - * {@inheritDoc} - */ - public boolean isDefault(String name) { - return false; - } + /** + * {@inheritDoc} + */ + public int getInt(String name) { + int value = INT_DEFAULT_DEFAULT; + String s = (String) fOptions.get(name); + if (s != null) { + try { + value = new Integer(s).intValue(); + } catch (NumberFormatException e) { + } + } + return value; + } - /** - * {@inheritDoc} - */ - public boolean needsSaving() { - return !fOptions.isEmpty(); - } + /** + * {@inheritDoc} + */ + public long getLong(String name) { + long value = LONG_DEFAULT_DEFAULT; + String s = (String) fOptions.get(name); + if (s != null) { + try { + value = new Long(s).longValue(); + } catch (NumberFormatException e) { + } + } + return value; + } - /** - * {@inheritDoc} - */ - public void putValue(String name, String value) { - throw new UnsupportedOperationException(); - } + /** + * {@inheritDoc} + */ + public String getString(String name) { + String value = (String) fOptions.get(name); + if (value == null) + value = STRING_DEFAULT_DEFAULT; + return value; + } - /** - * {@inheritDoc} - */ - public void setDefault(String name, double value) { - throw new UnsupportedOperationException(); - } + /** + * {@inheritDoc} + */ + public boolean isDefault(String name) { + return false; + } - /** - * {@inheritDoc} - */ - public void setDefault(String name, float value) { - throw new UnsupportedOperationException(); - } + /** + * {@inheritDoc} + */ + public boolean needsSaving() { + return !fOptions.isEmpty(); + } - /** - * {@inheritDoc} - */ - public void setDefault(String name, int value) { - throw new UnsupportedOperationException(); - } + /** + * {@inheritDoc} + */ + public void putValue(String name, String value) { + throw new UnsupportedOperationException(); + } - /** - * {@inheritDoc} - */ - public void setDefault(String name, long value) { - throw new UnsupportedOperationException(); - } + /** + * {@inheritDoc} + */ + public void setDefault(String name, double value) { + throw new UnsupportedOperationException(); + } - /** - * {@inheritDoc} - */ - public void setDefault(String name, String defaultObject) { - throw new UnsupportedOperationException(); - } + /** + * {@inheritDoc} + */ + public void setDefault(String name, float value) { + throw new UnsupportedOperationException(); + } - /** - * {@inheritDoc} - */ - public void setDefault(String name, boolean value) { - throw new UnsupportedOperationException(); - } + /** + * {@inheritDoc} + */ + public void setDefault(String name, int value) { + throw new UnsupportedOperationException(); + } - /** - * {@inheritDoc} - */ - public void setToDefault(String name) { - throw new UnsupportedOperationException(); - } + /** + * {@inheritDoc} + */ + public void setDefault(String name, long value) { + throw new UnsupportedOperationException(); + } - /** - * {@inheritDoc} - */ - public void setValue(String name, double value) { - throw new UnsupportedOperationException(); - } + /** + * {@inheritDoc} + */ + public void setDefault(String name, String defaultObject) { + throw new UnsupportedOperationException(); + } - /** - * {@inheritDoc} - */ - public void setValue(String name, float value) { - throw new UnsupportedOperationException(); - } + /** + * {@inheritDoc} + */ + public void setDefault(String name, boolean value) { + throw new UnsupportedOperationException(); + } - /** - * {@inheritDoc} - */ - public void setValue(String name, int value) { - throw new UnsupportedOperationException(); - } + /** + * {@inheritDoc} + */ + public void setToDefault(String name) { + throw new UnsupportedOperationException(); + } - /** - * {@inheritDoc} - */ - public void setValue(String name, long value) { - throw new UnsupportedOperationException(); - } + /** + * {@inheritDoc} + */ + public void setValue(String name, double value) { + throw new UnsupportedOperationException(); + } - /** - * {@inheritDoc} - */ - public void setValue(String name, String value) { - throw new UnsupportedOperationException(); - } + /** + * {@inheritDoc} + */ + public void setValue(String name, float value) { + throw new UnsupportedOperationException(); + } - /** - * {@inheritDoc} - */ - public void setValue(String name, boolean value) { - throw new UnsupportedOperationException(); - } + /** + * {@inheritDoc} + */ + public void setValue(String name, int value) { + throw new UnsupportedOperationException(); + } - /** - * Returns the adapted options Map. - * - * @return Returns the adapted options Map. - */ - public Map getOptions() { - return fOptions; - } + /** + * {@inheritDoc} + */ + public void setValue(String name, long value) { + throw new UnsupportedOperationException(); + } - /** - * Returns the mock-up preference store, events are received through this preference store. - * @return Returns the mock-up preference store. - */ - public IPreferenceStore getMockupPreferenceStore() { - return fMockupPreferenceStore; - } + /** + * {@inheritDoc} + */ + public void setValue(String name, String value) { + throw new UnsupportedOperationException(); + } + + /** + * {@inheritDoc} + */ + public void setValue(String name, boolean value) { + throw new UnsupportedOperationException(); + } + + /** + * Returns the adapted options Map. + * + * @return Returns the adapted options Map. + */ + public Map getOptions() { + return fOptions; + } + + /** + * Returns the mock-up preference store, events are received through this preference store. + * + * @return Returns the mock-up preference store. + */ + public IPreferenceStore getMockupPreferenceStore() { + return fMockupPreferenceStore; + } + + /** + * Set the event filter to the given filter. + * + * @param filter + * The new filter. + */ + public void setFilter(IPropertyChangeEventFilter filter) { + fFilter = filter; + } + + /** + * Returns the event filter. + * + * @return The event filter. + */ + public IPropertyChangeEventFilter getFilter() { + return fFilter; + } + } - /** - * Set the event filter to the given filter. - * - * @param filter The new filter. - */ - public void setFilter(IPropertyChangeEventFilter filter) { - fFilter= filter; - } - - /** - * Returns the event filter. - * - * @return The event filter. - */ - public IPropertyChangeEventFilter getFilter() { - return fFilter; - } - } /* - * Link mode. - */ - class MouseClickListener - implements KeyListener, MouseListener, MouseMoveListener, FocusListener, PaintListener, IPropertyChangeListener, IDocumentListener, ITextInputListener { + * Link mode. + */ + class MouseClickListener implements KeyListener, MouseListener, MouseMoveListener, FocusListener, PaintListener, + IPropertyChangeListener, IDocumentListener, ITextInputListener { /** The session is active. */ private boolean fActive; /** The currently active style range. */ private IRegion fActiveRegion; + /** The currently active style range as position. */ private Position fRememberedPosition; + /** The hand cursor. */ private Cursor fCursor; /** The link color. */ private Color fColor; + /** The key modifier mask. */ private int fKeyModifierMask; @@ -641,7 +720,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements if (fKeyModifierMask == -1) { // Fallback to stored state mask fKeyModifierMask = getPreferenceStore().getInt(BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK); - }; + } + ; } private int computeStateMask(String modifiers) { @@ -725,8 +805,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements } /** - * Creates a color from the information stored in the given preference store. - * Returns null if there is no such information available. + * Creates a color from the information stored in the given preference store. Returns null if there is no such + * information available. */ private Color createColor(IPreferenceStore store, String key, Display display) { @@ -764,11 +844,11 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements // remove style if (!redrawAll && viewer instanceof ITextViewerExtension2) - ((ITextViewerExtension2) viewer).invalidateTextPresentation(offset, length); + ((ITextViewerExtension2) viewer).invalidateTextPresentation(offset, length); else viewer.invalidateTextPresentation(); - // remove underline + // remove underline if (viewer instanceof ITextViewerExtension3) { ITextViewerExtension3 extension = (ITextViewerExtension3) viewer; offset = extension.modelOffset2WidgetOffset(offset); @@ -787,7 +867,7 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements fActiveRegion = null; } - // will eventually be replaced by a method provided by jdt.core + // will eventually be replaced by a method provided by jdt.core private IRegion selectWord(IDocument document, int anchor) { try { @@ -849,7 +929,7 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements // return selectWord(viewer.getDocument(), offset); // // } catch (JavaModelException e) { - // return null; + // return null; // } } @@ -956,7 +1036,7 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements fActive = true; - // removed for #25871 + // removed for #25871 // // ISourceViewer viewer= getSourceViewer(); // if (viewer == null) @@ -967,7 +1047,7 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements // return; // // highlightRegion(viewer, region); - // activateCursor(viewer); + // activateCursor(viewer); } /* @@ -986,6 +1066,7 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements */ public void mouseDoubleClick(MouseEvent e) { } + /* * @see org.eclipse.swt.events.MouseListener#mouseDown(org.eclipse.swt.events.MouseEvent) */ @@ -1124,7 +1205,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements } /* - * @see org.eclipse.jface.text.ITextInputListener#inputDocumentAboutToBeChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument) + * @see org.eclipse.jface.text.ITextInputListener#inputDocumentAboutToBeChanged(org.eclipse.jface.text.IDocument, + * org.eclipse.jface.text.IDocument) */ public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) { if (oldInput == null) @@ -1134,7 +1216,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements } /* - * @see org.eclipse.jface.text.ITextInputListener#inputDocumentChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument) + * @see org.eclipse.jface.text.ITextInputListener#inputDocumentChanged(org.eclipse.jface.text.IDocument, + * org.eclipse.jface.text.IDocument) */ public void inputDocumentChanged(IDocument oldInput, IDocument newInput) { if (newInput == null) @@ -1195,7 +1278,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements } private boolean includes(IRegion region, IRegion position) { - return position.getOffset() >= region.getOffset() && position.getOffset() + position.getLength() <= region.getOffset() + region.getLength(); + return position.getOffset() >= region.getOffset() + && position.getOffset() + position.getLength() <= region.getOffset() + region.getLength(); } private Point getMinimumLocation(StyledText text, int offset, int length) { @@ -1230,10 +1314,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements }; /** - * This action dispatches into two behaviours: If there is no current text - * hover, the javadoc is displayed using information presenter. If there is - * a current text hover, it is converted into a information presenter in - * order to make it sticky. + * This action dispatches into two behaviours: If there is no current text hover, the javadoc is displayed using information + * presenter. If there is a current text hover, it is converted into a information presenter in order to make it sticky. */ class InformationDispatchAction extends TextEditorAction { @@ -1301,8 +1383,10 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements public IRegion getSubject(ITextViewer textViewer, int offset) { return hoverRegion; } + /* - * @see org.eclipse.jface.text.information.IInformationProvider#getInformation(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion) + * @see org.eclipse.jface.text.information.IInformationProvider#getInformation(org.eclipse.jface.text.ITextViewer, + * org.eclipse.jface.text.IRegion) */ public String getInformation(ITextViewer textViewer, IRegion subject) { return hoverInfo; @@ -1342,38 +1426,41 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements } }; -// static protected class AnnotationAccess implements IAnnotationAccess { -// /* -// * @see org.eclipse.jface.text.source.IAnnotationAccess#getType(org.eclipse.jface.text.source.Annotation) -// */ -// public Object getType(Annotation annotation) { -// if (annotation instanceof IJavaAnnotation) { -// IJavaAnnotation javaAnnotation = (IJavaAnnotation) annotation; -// // if (javaAnnotation.isRelevant()) -// // return javaAnnotation.getAnnotationType(); -// } -// return null; -// } -// -// /* -// * @see org.eclipse.jface.text.source.IAnnotationAccess#isMultiLine(org.eclipse.jface.text.source.Annotation) -// */ -// public boolean isMultiLine(Annotation annotation) { -// return true; -// } -// -// /* -// * @see org.eclipse.jface.text.source.IAnnotationAccess#isTemporary(org.eclipse.jface.text.source.Annotation) -// */ -// public boolean isTemporary(Annotation annotation) { -// if (annotation instanceof IJavaAnnotation) { -// IJavaAnnotation javaAnnotation = (IJavaAnnotation) annotation; -// if (javaAnnotation.isRelevant()) -// return javaAnnotation.isTemporary(); -// } -// return false; -// } -// }; + // static protected class AnnotationAccess implements IAnnotationAccess { + // /* + // * @see + // org.eclipse.jface.text.source.IAnnotationAccess#getType(org.eclipse.jface.text.source.Annotation) + // */ + // public Object getType(Annotation annotation) { + // if (annotation instanceof IJavaAnnotation) { + // IJavaAnnotation javaAnnotation = (IJavaAnnotation) annotation; + // // if (javaAnnotation.isRelevant()) + // // return javaAnnotation.getAnnotationType(); + // } + // return null; + // } + // + // /* + // * @see + // org.eclipse.jface.text.source.IAnnotationAccess#isMultiLine(org.eclipse.jface.text.source.Annotation) + // */ + // public boolean isMultiLine(Annotation annotation) { + // return true; + // } + // + // /* + // * @see + // org.eclipse.jface.text.source.IAnnotationAccess#isTemporary(org.eclipse.jface.text.source.Annotation) + // */ + // public boolean isTemporary(Annotation annotation) { + // if (annotation instanceof IJavaAnnotation) { + // IJavaAnnotation javaAnnotation = (IJavaAnnotation) annotation; + // if (javaAnnotation.isRelevant()) + // return javaAnnotation.isTemporary(); + // } + // return false; + // } + // }; private class PropertyChangeListener implements org.eclipse.core.runtime.Preferences.IPropertyChangeListener { /* @@ -1383,132 +1470,146 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements handlePreferencePropertyChanged(event); } }; - + /** - * Finds and marks occurrence annotations. - * - * @since 3.0 - */ - class OccurrencesFinderJob extends Job implements IDocumentListener { - - private IDocument fDocument; - private boolean fCancelled= false; - private IProgressMonitor fProgressMonitor; - private Position[] fPositions; - - public OccurrencesFinderJob(IDocument document, Position[] positions) { - super("Occurrences Marker"); //$NON-NLS-1$ - fDocument= document; - fPositions= positions; - fDocument.addDocumentListener(this); - } - - private boolean isCancelled() { - return fCancelled || fProgressMonitor.isCanceled(); - } - - /* - * @see Job#run(org.eclipse.core.runtime.IProgressMonitor) - */ - public IStatus run(IProgressMonitor progressMonitor) { - - fProgressMonitor= progressMonitor; - - try { - - if (isCancelled()) - return Status.CANCEL_STATUS; - - ITextViewer textViewer= getViewer(); - if (textViewer == null) - return Status.CANCEL_STATUS; - - IDocument document= textViewer.getDocument(); - if (document == null) - return Status.CANCEL_STATUS; - - IDocumentProvider documentProvider= getDocumentProvider(); - if (documentProvider == null) - return Status.CANCEL_STATUS; - - IAnnotationModel annotationModel= documentProvider.getAnnotationModel(getEditorInput()); - if (annotationModel == null) - return Status.CANCEL_STATUS; - - // Add occurrence annotations - int length= fPositions.length; - Map annotationMap= new HashMap(length); - for (int i= 0; i < length; i++) { - - if (isCancelled()) - return Status.CANCEL_STATUS; - - String message; - Position position= fPositions[i]; - - // Create & add annotation - try { - message= document.get(position.offset, position.length); - } catch (BadLocationException ex) { - // Skip this match - continue; - } - annotationMap.put( - new Annotation("net.sourceforge.phpdt.ui.occurrences", false, message), //$NON-NLS-1$ - position); - } - - if (isCancelled()) - return Status.CANCEL_STATUS; - - synchronized (annotationModel) { - if (annotationModel instanceof IAnnotationModelExtension) { - ((IAnnotationModelExtension)annotationModel).replaceAnnotations(fOccurrenceAnnotations, annotationMap); - } else { - removeOccurrenceAnnotations(); - Iterator iter= annotationMap.entrySet().iterator(); - while (iter.hasNext()) { - Map.Entry mapEntry= (Map.Entry)iter.next(); - annotationModel.addAnnotation((Annotation)mapEntry.getKey(), (Position)mapEntry.getValue()); - } - } - fOccurrenceAnnotations= (Annotation[])annotationMap.keySet().toArray(new Annotation[annotationMap.keySet().size()]); - } - } finally { - fDocument.removeDocumentListener(this); - } - return Status.OK_STATUS; - } + * Finds and marks occurrence annotations. + * + * @since 3.0 + */ + class OccurrencesFinderJob extends Job implements IDocumentListener { - /* - * @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent) - */ - public void documentAboutToBeChanged(DocumentEvent event) { - fCancelled= true; - } + private IDocument fDocument; + + private boolean fCancelled = false; + + private IProgressMonitor fProgressMonitor; + + private Position[] fPositions; + + public OccurrencesFinderJob(IDocument document, Position[] positions) { + super("Occurrences Marker"); //$NON-NLS-1$ + fDocument = document; + fPositions = positions; + fDocument.addDocumentListener(this); + } + + private boolean isCancelled() { + return fCancelled || fProgressMonitor.isCanceled(); + } + + /* + * @see Job#run(org.eclipse.core.runtime.IProgressMonitor) + */ + public IStatus run(IProgressMonitor progressMonitor) { + + fProgressMonitor = progressMonitor; + + try { + + if (isCancelled()) + return Status.CANCEL_STATUS; + + ITextViewer textViewer = getViewer(); + if (textViewer == null) + return Status.CANCEL_STATUS; + + IDocument document = textViewer.getDocument(); + if (document == null) + return Status.CANCEL_STATUS; + + IDocumentProvider documentProvider = getDocumentProvider(); + if (documentProvider == null) + return Status.CANCEL_STATUS; + + IAnnotationModel annotationModel = documentProvider.getAnnotationModel(getEditorInput()); + if (annotationModel == null) + return Status.CANCEL_STATUS; + + // Add occurrence annotations + int length = fPositions.length; + Map annotationMap = new HashMap(length); + for (int i = 0; i < length; i++) { + + if (isCancelled()) + return Status.CANCEL_STATUS; + + String message; + Position position = fPositions[i]; + + // Create & add annotation + try { + message = document.get(position.offset, position.length); + } catch (BadLocationException ex) { + // Skip this match + continue; + } + annotationMap.put(new Annotation("net.sourceforge.phpdt.ui.occurrences", false, message), //$NON-NLS-1$ + position); + } + + if (isCancelled()) + return Status.CANCEL_STATUS; + + synchronized (annotationModel) { + if (annotationModel instanceof IAnnotationModelExtension) { + ((IAnnotationModelExtension) annotationModel).replaceAnnotations(fOccurrenceAnnotations, annotationMap); + } else { + removeOccurrenceAnnotations(); + Iterator iter = annotationMap.entrySet().iterator(); + while (iter.hasNext()) { + Map.Entry mapEntry = (Map.Entry) iter.next(); + annotationModel.addAnnotation((Annotation) mapEntry.getKey(), (Position) mapEntry.getValue()); + } + } + fOccurrenceAnnotations = (Annotation[]) annotationMap.keySet().toArray(new Annotation[annotationMap.keySet().size()]); + } + } finally { + fDocument.removeDocumentListener(this); + } + return Status.OK_STATUS; + } + + /* + * @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent) + */ + public void documentAboutToBeChanged(DocumentEvent event) { + fCancelled = true; + } + + /* + * @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent) + */ + public void documentChanged(DocumentEvent event) { + } + } + + /** + * Updates the selection in the editor's widget with the selection of the outline page. + */ + class OutlineSelectionChangedListener extends AbstractSelectionChangedListener { + public void selectionChanged(SelectionChangedEvent event) { + doSelectionChanged(event); + } + } + + /** + * Holds the current occurrence annotations. + * + * @since 3.0 + */ + private Annotation[] fOccurrenceAnnotations = null; - /* - * @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent) - */ - public void documentChanged(DocumentEvent event) { - } - } - - - /** - * Holds the current occurrence annotations. - * @since 3.0 - */ - private Annotation[] fOccurrenceAnnotations= null; - private Job fOccurrencesFinderJob; - + /** Preference key for showing the line number ruler */ -// private final static String LINE_NUMBER_RULER = PreferenceConstants.EDITOR_LINE_NUMBER_RULER; + // private final static String LINE_NUMBER_RULER = + // PreferenceConstants.EDITOR_LINE_NUMBER_RULER; /** Preference key for the foreground color of the line numbers */ - // private final static String LINE_NUMBER_COLOR = PreferenceConstants.EDITOR_LINE_NUMBER_RULER_COLOR; + // private final static String LINE_NUMBER_COLOR = + // PreferenceConstants.EDITOR_LINE_NUMBER_RULER_COLOR; /** Preference key for the link color */ private final static String LINK_COLOR = PreferenceConstants.EDITOR_LINK_COLOR; + /** Preference key for compiler task tags */ private final static String COMPILER_TASK_TAGS = JavaCore.COMPILER_TASK_TAGS; @@ -1517,73 +1618,96 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements // private AbstractContentOutlinePage fOutlinePage; /** The outline page */ protected JavaOutlinePage fOutlinePage; + /** Outliner context menu Id */ protected String fOutlinerContextMenuId; - /** - * The editor selection changed listener. - * - * @since 3.0 - */ -// private EditorSelectionChangedListener fEditorSelectionChangedListener; - /** Indicates whether this editor should react on outline page selection changes */ + + /** + * The editor selection changed listener. + * + * @since 3.0 + */ + // private EditorSelectionChangedListener fEditorSelectionChangedListener; + /** + * Indicates whether this editor should react on outline page selection changes + */ private int fIgnoreOutlinePageSelection; - - /** The outline page selection updater */ - private OutlinePageSelectionUpdater fUpdater; + + /** The outline page selection updater */ + private OutlinePageSelectionUpdater fUpdater; + // protected PHPSyntaxParserThread fValidationThread = null; // private IPreferenceStore fPHPPrefStore; /** The selection changed listener */ - protected ISelectionChangedListener fSelectionChangedListener = new SelectionChangedListener(); + // protected ISelectionChangedListener fSelectionChangedListener = new + // SelectionChangedListener(); + /** + * The editor selection changed listener. + * + * @since 3.0 + */ + private EditorSelectionChangedListener fEditorSelectionChangedListener; + + /** The selection changed listener */ + protected AbstractSelectionChangedListener fOutlineSelectionChangedListener = new OutlineSelectionChangedListener(); /** The editor's bracket matcher */ private PHPPairMatcher fBracketMatcher = new PHPPairMatcher(BRACKETS); - /** The line number ruler column */ -// private LineNumberRulerColumn fLineNumberRulerColumn; + // private LineNumberRulerColumn fLineNumberRulerColumn; /** This editor's encoding support */ private DefaultEncodingSupport fEncodingSupport; + /** The mouse listener */ private MouseClickListener fMouseListener; 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; - + * 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 */ -// protected IAnnotationAccess fAnnotationAccess = new AnnotationAccess(); + // protected IAnnotationAccess fAnnotationAccess = new AnnotationAccess(); /** The overview ruler */ protected OverviewRuler isOverviewRulerVisible; + /** The source viewer decoration support */ //protected SourceViewerDecorationSupport fSourceViewerDecorationSupport; /** The overview ruler */ //protected OverviewRuler fOverviewRuler; - /** The preference property change listener for java core. */ private org.eclipse.core.runtime.Preferences.IPropertyChangeListener fPropertyChangeListener = new PropertyChangeListener(); + /** * Returns the most narrow java element including the given offset * - * @param offset the offset inside of the requested element + * @param offset + * the offset inside of the requested element */ abstract protected IJavaElement getElementAt(int offset); @@ -1591,9 +1715,10 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements * Returns the java element of this editor's input corresponding to the given IJavaElement */ abstract protected IJavaElement getCorrespondingElement(IJavaElement element); + /** - * Sets the input of the editor's outline page. - */ + * Sets the input of the editor's outline page. + */ abstract protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input); /** @@ -1602,47 +1727,60 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements public PHPEditor() { super(); } - - - /* - * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#initializeKeyBindingScopes() - */ - protected void initializeKeyBindingScopes() { - setKeyBindingScopes(new String[] { "net.sourceforge.phpdt.ui.phpEditorScope" }); //$NON-NLS-1$ - } - - /* - * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#initializeEditor() - */ - protected void initializeEditor() { - //jsurfer old code - JavaTextTools textTools= PHPeclipsePlugin.getDefault().getJavaTextTools(); - setSourceViewerConfiguration(new PHPSourceViewerConfiguration(textTools, this)); //, IJavaPartitions.JAVA_PARTITIONING)); - setRangeIndicator(new DefaultRangeIndicator()); -// IPreferenceStore store= PHPeclipsePlugin.getDefault().getPreferenceStore(); -// setPreferenceStore(store); - IPreferenceStore store= createCombinedPreferenceStore(null); - setPreferenceStore(store); - - // TODO changed in 3.x ? - if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE)) - fUpdater= new OutlinePageSelectionUpdater(); - // jsurfer end - -// IPreferenceStore store= createCombinedPreferenceStore(null); -// setPreferenceStore(store); -// JavaTextTools textTools= PHPeclipsePlugin.getDefault().getJavaTextTools(); -// setSourceViewerConfiguration(new JavaSourceViewerConfiguration(textTools.getColorManager(), store, this, IJavaPartitions.JAVA_PARTITIONING)); -// fMarkOccurrenceAnnotations= store.getBoolean(PreferenceConstants.EDITOR_MARK_OCCURRENCES); -// fStickyOccurrenceAnnotations= store.getBoolean(PreferenceConstants.EDITOR_STICKY_OCCURRENCES); -// fMarkTypeOccurrences= store.getBoolean(PreferenceConstants.EDITOR_MARK_TYPE_OCCURRENCES); -// fMarkMethodOccurrences= store.getBoolean(PreferenceConstants.EDITOR_MARK_METHOD_OCCURRENCES); -// fMarkConstantOccurrences= store.getBoolean(PreferenceConstants.EDITOR_MARK_CONSTANT_OCCURRENCES); -// fMarkFieldOccurrences= store.getBoolean(PreferenceConstants.EDITOR_MARK_FIELD_OCCURRENCES); -// fMarkLocalVariableypeOccurrences= store.getBoolean(PreferenceConstants.EDITOR_MARK_LOCAL_VARIABLE_OCCURRENCES); -// fMarkExceptionOccurrences= store.getBoolean(PreferenceConstants.EDITOR_MARK_EXCEPTION_OCCURRENCES); -// fMarkMethodExitPoints= store.getBoolean(PreferenceConstants.EDITOR_MARK_METHOD_EXIT_POINTS); - } + + /* + * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#initializeKeyBindingScopes() + */ + protected void initializeKeyBindingScopes() { + setKeyBindingScopes(new String[] { "net.sourceforge.phpdt.ui.phpEditorScope" }); //$NON-NLS-1$ + } + + /* + * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#initializeEditor() + */ + protected void initializeEditor() { + //jsurfer old code + JavaTextTools textTools = PHPeclipsePlugin.getDefault().getJavaTextTools(); + setSourceViewerConfiguration(new PHPSourceViewerConfiguration(textTools, this)); //, IJavaPartitions.JAVA_PARTITIONING)); + setRangeIndicator(new DefaultRangeIndicator()); + // IPreferenceStore store= + // PHPeclipsePlugin.getDefault().getPreferenceStore(); + // setPreferenceStore(store); + IPreferenceStore store = createCombinedPreferenceStore(null); + setPreferenceStore(store); + + // TODO changed in 3.x ? + if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE)) + fUpdater = new OutlinePageSelectionUpdater(); + // jsurfer end + + // IPreferenceStore store= createCombinedPreferenceStore(null); + // setPreferenceStore(store); + // JavaTextTools textTools= + // PHPeclipsePlugin.getDefault().getJavaTextTools(); + // setSourceViewerConfiguration(new + // JavaSourceViewerConfiguration(textTools.getColorManager(), store, + // this, IJavaPartitions.JAVA_PARTITIONING)); + // fMarkOccurrenceAnnotations= + // store.getBoolean(PreferenceConstants.EDITOR_MARK_OCCURRENCES); + // fStickyOccurrenceAnnotations= + // store.getBoolean(PreferenceConstants.EDITOR_STICKY_OCCURRENCES); + // fMarkTypeOccurrences= + // store.getBoolean(PreferenceConstants.EDITOR_MARK_TYPE_OCCURRENCES); + // fMarkMethodOccurrences= + // store.getBoolean(PreferenceConstants.EDITOR_MARK_METHOD_OCCURRENCES); + // fMarkConstantOccurrences= + // store.getBoolean(PreferenceConstants.EDITOR_MARK_CONSTANT_OCCURRENCES); + // fMarkFieldOccurrences= + // store.getBoolean(PreferenceConstants.EDITOR_MARK_FIELD_OCCURRENCES); + // fMarkLocalVariableypeOccurrences= + // store.getBoolean(PreferenceConstants.EDITOR_MARK_LOCAL_VARIABLE_OCCURRENCES); + // fMarkExceptionOccurrences= + // store.getBoolean(PreferenceConstants.EDITOR_MARK_EXCEPTION_OCCURRENCES); + // fMarkMethodExitPoints= + // store.getBoolean(PreferenceConstants.EDITOR_MARK_METHOD_EXIT_POINTS); + } + /* * @see org.eclipse.ui.texteditor.AbstractTextEditor#updatePropertyDependentActions() */ @@ -1685,12 +1823,14 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements public void updatedTitleImage(Image image) { setTitleImage(image); } + /* * @see net.sourceforge.phpdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput() */ public Object getViewPartInput() { return getEditorInput().getAdapter(IResource.class); } + /* * @see org.eclipse.ui.texteditor.AbstractTextEditor#doSetSelection(ISelection) */ @@ -1698,39 +1838,40 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements super.doSetSelection(selection); synchronizeOutlinePageSelection(); } - boolean isFoldingEnabled() { - return PHPeclipsePlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_FOLDING_ENABLED); - } + + boolean isFoldingEnabled() { + return PHPeclipsePlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_FOLDING_ENABLED); + } + /* - * @see org.eclipse.ui.IWorkbenchPart#createPartControl(org.eclipse.swt. - * widgets.Composite) + * @see org.eclipse.ui.IWorkbenchPart#createPartControl(org.eclipse.swt. widgets.Composite) */ public void createPartControl(Composite parent) { super.createPartControl(parent); //fSourceViewerDecorationSupport.install(getPreferenceStore()); - 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); - } - }); + 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(); + + 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; @@ -1743,11 +1884,18 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements fInformationPresenter.setSizeConstraints(60, 10, true, true); fInformationPresenter.install(getSourceViewer()); + fEditorSelectionChangedListener = new EditorSelectionChangedListener(); + fEditorSelectionChangedListener.install(getSelectionProvider()); + + if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE)) + enableOverwriteMode(false); + + // getEditorSite().getShell().addShellListener(fActivationListener); } /** * Returns this document's complete text. - * + * * @return the document's complete text */ public String get() { @@ -1756,14 +1904,14 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements } /** - * Sets the outliner's context menu ID. - */ + * Sets the outliner's context menu ID. + */ protected void setOutlinerContextMenuId(String menuId) { fOutlinerContextMenuId = menuId; } /** - * Returns the standard action group of this editor. + * Returns the standard action group of this editor. */ protected ActionGroup getActionGroup() { return fActionGroups; @@ -1773,125 +1921,154 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements // return fOutlinePage; // } - /** The PHPEditor implementation of this - * AbstractTextEditor method extend the - * actions to add those specific to the receiver + /** + * The PHPEditor implementation of this AbstractTextEditor method extend the actions to add those + * specific to the receiver */ 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(net.sourceforge.phpdt.ui.actions.PHPEditorActionDefinitionIds.SHOW_JAVADOC); - setAction("ShowJavaDoc", resAction); //$NON-NLS-1$ -// WorkbenchHelp.setHelp(resAction, IJavaHelpContextIds.SHOW_JAVADOC_ACTION); - - Action action= new GotoMatchingBracketAction(this); - action.setActionDefinitionId(PHPEditorActionDefinitionIds.GOTO_MATCHING_BRACKET); - setAction(GotoMatchingBracketAction.GOTO_MATCHING_BRACKET, action); - -// action= new TextOperationAction(PHPEditorMessages.getResourceBundle(),"ShowOutline.", this, JavaSourceViewer.SHOW_OUTLINE, true); //$NON-NLS-1$ -// action.setActionDefinitionId(PHPEditorActionDefinitionIds.SHOW_OUTLINE); -// setAction(PHPEditorActionDefinitionIds.SHOW_OUTLINE, action); -//// WorkbenchHelp.setHelp(action, IJavaHelpContextIds.SHOW_OUTLINE_ACTION); -// -// action= new TextOperationAction(PHPEditorMessages.getResourceBundle(),"OpenStructure.", this, JavaSourceViewer.OPEN_STRUCTURE, true); //$NON-NLS-1$ -// action.setActionDefinitionId(PHPEditorActionDefinitionIds.SHOW_OUTLINE.OPEN_STRUCTURE); -// setAction(PHPEditorActionDefinitionIds.SHOW_OUTLINE.OPEN_STRUCTURE, action); -//// WorkbenchHelp.setHelp(action, IJavaHelpContextIds.OPEN_STRUCTURE_ACTION); -// -// action= new TextOperationAction(PHPEditorMessages.getResourceBundle(),"OpenHierarchy.", this, JavaSourceViewer.SHOW_HIERARCHY, true); //$NON-NLS-1$ -// action.setActionDefinitionId(PHPEditorActionDefinitionIds.SHOW_OUTLINE.OPEN_HIERARCHY); -// setAction(PHPEditorActionDefinitionIds.SHOW_OUTLINE.OPEN_HIERARCHY, action); -//// WorkbenchHelp.setHelp(action, IJavaHelpContextIds.OPEN_HIERARCHY_ACTION); - - fEncodingSupport= new DefaultEncodingSupport(); - fEncodingSupport.initialize(this); - -// fSelectionHistory= new SelectionHistory(this); -// -// action= new StructureSelectEnclosingAction(this, fSelectionHistory); -// action.setActionDefinitionId(PHPEditorActionDefinitionIds.SELECT_ENCLOSING); -// setAction(StructureSelectionAction.ENCLOSING, action); -// -// action= new StructureSelectNextAction(this, fSelectionHistory); -// action.setActionDefinitionId(PHPEditorActionDefinitionIds.SELECT_NEXT); -// setAction(StructureSelectionAction.NEXT, action); -// -// action= new StructureSelectPreviousAction(this, fSelectionHistory); -// action.setActionDefinitionId(PHPEditorActionDefinitionIds.SELECT_PREVIOUS); -// setAction(StructureSelectionAction.PREVIOUS, action); -// -// StructureSelectHistoryAction historyAction= new StructureSelectHistoryAction(this, fSelectionHistory); -// historyAction.setActionDefinitionId(PHPEditorActionDefinitionIds.SELECT_LAST); -// setAction(StructureSelectionAction.HISTORY, historyAction); -// fSelectionHistory.setHistoryAction(historyAction); -// -// action= GoToNextPreviousMemberAction.newGoToNextMemberAction(this); -// action.setActionDefinitionId(PHPEditorActionDefinitionIds.GOTO_NEXT_MEMBER); -// setAction(GoToNextPreviousMemberAction.NEXT_MEMBER, action); -// -// action= GoToNextPreviousMemberAction.newGoToPreviousMemberAction(this); -// action.setActionDefinitionId(PHPEditorActionDefinitionIds.GOTO_PREVIOUS_MEMBER); -// setAction(GoToNextPreviousMemberAction.PREVIOUS_MEMBER, action); -// -// action= new QuickFormatAction(); -// action.setActionDefinitionId(PHPEditorActionDefinitionIds.QUICK_FORMAT); -// setAction(IJavaEditorActionDefinitionIds.QUICK_FORMAT, action); -// -// action= new RemoveOccurrenceAnnotations(this); -// action.setActionDefinitionId(PHPEditorActionDefinitionIds.REMOVE_OCCURRENCE_ANNOTATIONS); -// setAction("RemoveOccurrenceAnnotations", action); //$NON-NLS-1$ - // add annotation actions - action= new JavaSelectMarkerRulerAction2(PHPEditorMessages.getResourceBundle(), "Editor.RulerAnnotationSelection.", this); //$NON-NLS-1$ - setAction("AnnotationAction", action); //$NON-NLS-1$ + 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(net.sourceforge.phpdt.ui.actions.PHPEditorActionDefinitionIds.SHOW_JAVADOC); + setAction("ShowJavaDoc", resAction); //$NON-NLS-1$ + // WorkbenchHelp.setHelp(resAction, + // IJavaHelpContextIds.SHOW_JAVADOC_ACTION); + + Action action = new GotoMatchingBracketAction(this); + action.setActionDefinitionId(PHPEditorActionDefinitionIds.GOTO_MATCHING_BRACKET); + setAction(GotoMatchingBracketAction.GOTO_MATCHING_BRACKET, action); + + // action= new + // TextOperationAction(PHPEditorMessages.getResourceBundle(),"ShowOutline.", + // this, JavaSourceViewer.SHOW_OUTLINE, true); //$NON-NLS-1$ + // action.setActionDefinitionId(PHPEditorActionDefinitionIds.SHOW_OUTLINE); + // setAction(PHPEditorActionDefinitionIds.SHOW_OUTLINE, action); + //// WorkbenchHelp.setHelp(action, + // IJavaHelpContextIds.SHOW_OUTLINE_ACTION); + // + // action= new + // TextOperationAction(PHPEditorMessages.getResourceBundle(),"OpenStructure.", + // this, JavaSourceViewer.OPEN_STRUCTURE, true); //$NON-NLS-1$ + // action.setActionDefinitionId(PHPEditorActionDefinitionIds.SHOW_OUTLINE.OPEN_STRUCTURE); + // setAction(PHPEditorActionDefinitionIds.SHOW_OUTLINE.OPEN_STRUCTURE, + // action); + //// WorkbenchHelp.setHelp(action, + // IJavaHelpContextIds.OPEN_STRUCTURE_ACTION); + // + // action= new + // TextOperationAction(PHPEditorMessages.getResourceBundle(),"OpenHierarchy.", + // this, JavaSourceViewer.SHOW_HIERARCHY, true); //$NON-NLS-1$ + // action.setActionDefinitionId(PHPEditorActionDefinitionIds.SHOW_OUTLINE.OPEN_HIERARCHY); + // setAction(PHPEditorActionDefinitionIds.SHOW_OUTLINE.OPEN_HIERARCHY, + // action); + //// WorkbenchHelp.setHelp(action, + // IJavaHelpContextIds.OPEN_HIERARCHY_ACTION); + + fEncodingSupport = new DefaultEncodingSupport(); + fEncodingSupport.initialize(this); + + // fSelectionHistory= new SelectionHistory(this); + // + // action= new StructureSelectEnclosingAction(this, fSelectionHistory); + // action.setActionDefinitionId(PHPEditorActionDefinitionIds.SELECT_ENCLOSING); + // setAction(StructureSelectionAction.ENCLOSING, action); + // + // action= new StructureSelectNextAction(this, fSelectionHistory); + // action.setActionDefinitionId(PHPEditorActionDefinitionIds.SELECT_NEXT); + // setAction(StructureSelectionAction.NEXT, action); + // + // action= new StructureSelectPreviousAction(this, fSelectionHistory); + // action.setActionDefinitionId(PHPEditorActionDefinitionIds.SELECT_PREVIOUS); + // setAction(StructureSelectionAction.PREVIOUS, action); + // + // StructureSelectHistoryAction historyAction= new + // StructureSelectHistoryAction(this, fSelectionHistory); + // historyAction.setActionDefinitionId(PHPEditorActionDefinitionIds.SELECT_LAST); + // setAction(StructureSelectionAction.HISTORY, historyAction); + // fSelectionHistory.setHistoryAction(historyAction); + // + // action= GoToNextPreviousMemberAction.newGoToNextMemberAction(this); + // action.setActionDefinitionId(PHPEditorActionDefinitionIds.GOTO_NEXT_MEMBER); + // setAction(GoToNextPreviousMemberAction.NEXT_MEMBER, action); + // + // action= + // GoToNextPreviousMemberAction.newGoToPreviousMemberAction(this); + // action.setActionDefinitionId(PHPEditorActionDefinitionIds.GOTO_PREVIOUS_MEMBER); + // setAction(GoToNextPreviousMemberAction.PREVIOUS_MEMBER, action); + // + // action= new QuickFormatAction(); + // action.setActionDefinitionId(PHPEditorActionDefinitionIds.QUICK_FORMAT); + // setAction(IJavaEditorActionDefinitionIds.QUICK_FORMAT, action); + // + // action= new RemoveOccurrenceAnnotations(this); + // action.setActionDefinitionId(PHPEditorActionDefinitionIds.REMOVE_OCCURRENCE_ANNOTATIONS); + // setAction("RemoveOccurrenceAnnotations", 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); - } + private void internalDoSetInput(IEditorInput input) throws CoreException { + super.doSetInput(input); - /* - * @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 viewer= (JavaSourceViewer)getSourceViewer(); + if (viewer.getReconciler() == null) { + IReconciler reconciler= getSourceViewerConfiguration().getReconciler(viewer); + if (reconciler != null) { + reconciler.install(viewer); + viewer.setReconciler(reconciler); + } } - if (getSourceViewer() instanceof JavaSourceViewer) - ((JavaSourceViewer)getSourceViewer()).setPreferenceStore(store); } - /** The PHPEditor implementation of this - * AbstractTextEditor method performs any extra - * disposal actions required by the php editor. + + if (fEncodingSupport != null) + fEncodingSupport.reset(); + + setOutlinePageInput(fOutlinePage, input); + + if (fProjectionModelUpdater != null) + fProjectionModelUpdater.initialize(); + +// if (isShowingOverrideIndicators()) +// installOverrideIndicator(false); + } + + /* + * @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 PHPEditor implementation of this AbstractTextEditor 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; - } + if (fProjectionModelUpdater != null) { + fProjectionModelUpdater.uninstall(); + fProjectionModelUpdater = null; + } + + if (fProjectionSupport != null) { + fProjectionSupport.dispose(); + fProjectionSupport = null; + } // PHPEditorEnvironment.disconnect(this); if (fOutlinePage != null) fOutlinePage.setInput(null); @@ -1913,44 +2090,47 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements fPropertyChangeListener = null; } -// if (fSourceViewerDecorationSupport != null) { -// fSourceViewerDecorationSupport.dispose(); -// fSourceViewerDecorationSupport = null; -// } + // if (fSourceViewerDecorationSupport != null) { + // fSourceViewerDecorationSupport.dispose(); + // fSourceViewerDecorationSupport = null; + // } if (fBracketMatcher != null) { fBracketMatcher.dispose(); fBracketMatcher = null; } + + if (fEditorSelectionChangedListener != null) { + fEditorSelectionChangedListener.uninstall(getSelectionProvider()); + fEditorSelectionChangedListener = null; + } + super.dispose(); } - /** The PHPEditor implementation of this - * AbstractTextEditor method performs any extra - * revert behavior required by the php editor. + /** + * The PHPEditor implementation of this AbstractTextEditor method performs any extra revert behavior + * required by the php editor. */ // public void doRevertToSaved() { // super.doRevertToSaved(); // if (fOutlinePage != null) // fOutlinePage.update(); // } - - /** The PHPEditor implementation of this - * AbstractTextEditor method performs any extra - * save behavior required by the php editor. + /** + * The PHPEditor implementation of this AbstractTextEditor method performs any extra save behavior + * required by the php editor. */ // public void doSave(IProgressMonitor monitor) { // super.doSave(monitor); // compile or not, according to the user preferences - // IPreferenceStore store = getPreferenceStore(); - + // IPreferenceStore store = getPreferenceStore(); // the parse on save was changed to the eclipse "builders" concept // if (store.getBoolean(PHPeclipsePlugin.PHP_PARSE_ON_SAVE)) { // IAction a = PHPParserAction.getInstance(); // if (a != null) // a.run(); // } - // if (SWT.getPlatform().equals("win32")) { // IAction a = ShowExternalPreviewAction.getInstance(); // if (a != null) @@ -1959,10 +2139,9 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements // if (fOutlinePage != null) // fOutlinePage.update(); // } - - /** The PHPEditor implementation of this - * AbstractTextEditor method performs any extra - * save as behavior required by the php editor. + /** + * The PHPEditor implementation of this AbstractTextEditor method performs any extra save as + * behavior required by the php editor. */ // public void doSaveAs() { // super.doSaveAs(); @@ -1970,8 +2149,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements // fOutlinePage.update(); // } /* - * @see StatusTextEditor#getStatusHeader(IStatus) - */ + * @see StatusTextEditor#getStatusHeader(IStatus) + */ protected String getStatusHeader(IStatus status) { if (fEncodingSupport != null) { String message = fEncodingSupport.getStatusHeader(status); @@ -2004,9 +2183,10 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements } return super.getStatusMessage(status); } - /** The PHPEditor implementation of this - * AbstractTextEditor method performs sets the - * input of the outline page after AbstractTextEditor has set input. + + /** + * The PHPEditor implementation of this AbstractTextEditor method performs sets the input of the + * outline page after AbstractTextEditor has set input. */ // protected void doSetInput(IEditorInput input) throws CoreException { // super.doSetInput(input); @@ -2015,24 +2195,24 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements // fEncodingSupport.reset(); // if (fOutlinePage != null) // fOutlinePage.setInput(input); - // // setOutlinePageInput(fOutlinePage, input); - // } + // // setOutlinePageInput(fOutlinePage, input); + // } protected void doSetInput(IEditorInput input) throws CoreException { super.doSetInput(input); if (fEncodingSupport != null) fEncodingSupport.reset(); setOutlinePageInput(fOutlinePage, input); } + /* * @see org.phpeclipse.phpdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput() */ // public Object getViewPartInput() { // return getEditorInput().getAdapter(IFile.class); // } - - /** The PHPEditor implementation of this - * AbstractTextEditor method adds any - * PHPEditor specific entries. + /** + * The PHPEditor implementation of this AbstractTextEditor method adds any PHPEditor specific + * entries. */ public void editorContextMenuAboutToShow(MenuManager menu) { super.editorContextMenuAboutToShow(menu); @@ -2043,7 +2223,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements fContextMenuGroup.setContext(context); fContextMenuGroup.fillContextMenu(menu); fContextMenuGroup.setContext(null); - // addAction(menu, ITextEditorActionConstants.GROUP_EDIT, "Format"); //$NON-NLS-1$ + // addAction(menu, ITextEditorActionConstants.GROUP_EDIT, "Format"); + // //$NON-NLS-1$ // // ActionContext context = // new ActionContext(getSelectionProvider().getSelection()); @@ -2056,20 +2237,9 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements * Creates the outline page used with this editor. */ protected JavaOutlinePage createOutlinePage() { - - // AbstractContentOutlinePage page = new PHPContentOutlinePage(getDocumentProvider(), this); - // - // page.addSelectionChangedListener(fSelectionChangedListener); - // // setOutlinePageInput(page, getEditorInput()); - // if (getEditorInput() != null) - // fOutlinePage.setInput(getEditorInput()); - // - // return page; JavaOutlinePage page = new JavaOutlinePage(fOutlinerContextMenuId, this); - - page.addSelectionChangedListener(fSelectionChangedListener); + fOutlineSelectionChangedListener.install(page); setOutlinePageInput(page, getEditorInput()); - return page; } @@ -2078,43 +2248,69 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements */ public void outlinePageClosed() { if (fOutlinePage != null) { - fOutlinePage.removeSelectionChangedListener(fSelectionChangedListener); + fOutlineSelectionChangedListener.uninstall(fOutlinePage); fOutlinePage = null; resetHighlightRange(); } } + /** - * Synchronizes the outliner selection with the actual cursor - * position in the editor. + * Synchronizes the outliner selection with the given element position in the editor. + * + * @param element + * the java element to select */ - public void synchronizeOutlinePageSelection() { - - // if (isEditingScriptRunning()) - // return; - - ISourceViewer sourceViewer = getSourceViewer(); - if (sourceViewer == null || fOutlinePage == null) - return; - - StyledText styledText = sourceViewer.getTextWidget(); - if (styledText == null) - return; + protected void synchronizeOutlinePage(ISourceReference element) { + synchronizeOutlinePage(element, true); + } - int caret = 0; - if (sourceViewer instanceof ITextViewerExtension3) { - ITextViewerExtension3 extension = (ITextViewerExtension3) sourceViewer; - caret = extension.widgetOffset2ModelOffset(styledText.getCaretOffset()); - } else { - int offset = sourceViewer.getVisibleRegion().getOffset(); - caret = offset + styledText.getCaretOffset(); + /** + * Synchronizes the outliner selection with the given element position in the editor. + * + * @param element + * the java element to select + * @param checkIfOutlinePageActive + * true if check for active outline page needs to be done + */ + protected void synchronizeOutlinePage(ISourceReference element, boolean checkIfOutlinePageActive) { + if (fOutlinePage != null && element != null && !(checkIfOutlinePageActive && isJavaOutlinePageActive())) { + fOutlineSelectionChangedListener.uninstall(fOutlinePage); + fOutlinePage.select(element); + fOutlineSelectionChangedListener.install(fOutlinePage); } + } - IJavaElement element = getElementAt(caret); - if (element instanceof ISourceReference) { - fOutlinePage.removeSelectionChangedListener(fSelectionChangedListener); - fOutlinePage.select((ISourceReference) element); - fOutlinePage.addSelectionChangedListener(fSelectionChangedListener); - } + /** + * Synchronizes the outliner selection with the actual cursor position in the editor. + */ + public void synchronizeOutlinePageSelection() { + synchronizeOutlinePage(computeHighlightRangeSourceReference()); + + // ISourceViewer sourceViewer = getSourceViewer(); + // if (sourceViewer == null || fOutlinePage == null) + // return; + // + // StyledText styledText = sourceViewer.getTextWidget(); + // if (styledText == null) + // return; + // + // int caret = 0; + // if (sourceViewer instanceof ITextViewerExtension3) { + // ITextViewerExtension3 extension = (ITextViewerExtension3) + // sourceViewer; + // caret = + // extension.widgetOffset2ModelOffset(styledText.getCaretOffset()); + // } else { + // int offset = sourceViewer.getVisibleRegion().getOffset(); + // caret = offset + styledText.getCaretOffset(); + // } + // + // IJavaElement element = getElementAt(caret); + // if (element instanceof ISourceReference) { + // fOutlinePage.removeSelectionChangedListener(fSelectionChangedListener); + // fOutlinePage.select((ISourceReference) element); + // fOutlinePage.addSelectionChangedListener(fSelectionChangedListener); + // } } protected void setSelection(ISourceReference reference, boolean moveCursor) { @@ -2167,7 +2363,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements } } // else if (reference instanceof IImportDeclaration) { - // String name= ((IImportDeclaration) reference).getElementName(); + // String name= ((IImportDeclaration) + // reference).getElementName(); // if (name != null && name.length() > 0) { // String content= reference.getSource(); // if (content != null) { @@ -2176,7 +2373,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements // } // } // } else if (reference instanceof IPackageDeclaration) { - // String name= ((IPackageDeclaration) reference).getElementName(); + // String name= ((IPackageDeclaration) + // reference).getElementName(); // if (name != null && name.length() > 0) { // String content= reference.getSource(); // if (content != null) { @@ -2206,12 +2404,14 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements } public void setSelection(IJavaElement element) { - - if (element == null || element instanceof ICompilationUnit) { // || element instanceof IClassFile) { + if (element == null || element instanceof ICompilationUnit) { // || + // element + // instanceof + // IClassFile) + // { /* - * If the element is an ICompilationUnit this unit is either the input - * of this editor or not being displayed. In both cases, nothing should - * happened. (http://dev.eclipse.org/bugs/show_bug.cgi?id=5128) + * If the element is an ICompilationUnit this unit is either the input of this editor or not being displayed. In both cases, + * nothing should happened. (http://dev.eclipse.org/bugs/show_bug.cgi?id=5128) */ return; } @@ -2219,33 +2419,32 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements IJavaElement corresponding = getCorrespondingElement(element); if (corresponding instanceof ISourceReference) { ISourceReference reference = (ISourceReference) corresponding; - // set hightlight range + // set highlight range setSelection(reference, true); // set outliner selection if (fOutlinePage != null) { - fOutlinePage.removeSelectionChangedListener(fSelectionChangedListener); + fOutlineSelectionChangedListener.uninstall(fOutlinePage); fOutlinePage.select(reference); - fOutlinePage.addSelectionChangedListener(fSelectionChangedListener); + fOutlineSelectionChangedListener.install(fOutlinePage); } } } - public synchronized void editingScriptStarted() { - ++ fIgnoreOutlinePageSelection; - } - - public synchronized void editingScriptEnded() { - -- fIgnoreOutlinePageSelection; - } - - public synchronized boolean isEditingScriptRunning() { - return (fIgnoreOutlinePageSelection > 0); - } - - /** The PHPEditor implementation of this - * AbstractTextEditor method performs gets - * the java content outline page if request is for a an - * outline page. + public synchronized void editingScriptStarted() { + ++fIgnoreOutlinePageSelection; + } + + public synchronized void editingScriptEnded() { + --fIgnoreOutlinePageSelection; + } + + public synchronized boolean isEditingScriptRunning() { + return (fIgnoreOutlinePageSelection > 0); + } + + /** + * The PHPEditor implementation of this AbstractTextEditor method performs gets the java content + * outline page if request is for a an outline page. */ public Object getAdapter(Class required) { @@ -2267,13 +2466,14 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements }; } if (fProjectionSupport != null) { - Object adapter= fProjectionSupport.getAdapter(getSourceViewer(), required); - if (adapter != null) - return adapter; - } - + Object adapter = fProjectionSupport.getAdapter(getSourceViewer(), required); + if (adapter != null) + return adapter; + } + return super.getAdapter(required); } + // public Object getAdapter(Class required) { // if (IContentOutlinePage.class.equals(required)) { // if (fOutlinePage == null) { @@ -2313,9 +2513,10 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements editingScriptEnded(); } } + /* - * @see AbstractTextEditor#adjustHighlightRange(int, int) - */ + * @see AbstractTextEditor#adjustHighlightRange(int, int) + */ protected void adjustHighlightRange(int offset, int length) { try { @@ -2324,12 +2525,20 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements while (element instanceof ISourceReference) { ISourceRange range = ((ISourceReference) element).getSourceRange(); if (offset < range.getOffset() + range.getLength() && range.getOffset() < offset + length) { + + ISourceViewer viewer = getSourceViewer(); + if (viewer instanceof ITextViewerExtension5) { + ITextViewerExtension5 extension = (ITextViewerExtension5) viewer; + extension.exposeModelRange(new Region(range.getOffset(), range.getLength())); + } + setHighlightRange(range.getOffset(), range.getLength(), true); if (fOutlinePage != null) { - fOutlinePage.removeSelectionChangedListener(fSelectionChangedListener); + fOutlineSelectionChangedListener.uninstall(fOutlinePage); fOutlinePage.select((ISourceReference) element); - fOutlinePage.addSelectionChangedListener(fSelectionChangedListener); + fOutlineSelectionChangedListener.install(fOutlinePage); } + return; } element = element.getParent(); @@ -2339,8 +2548,16 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements PHPeclipsePlugin.log(x.getStatus()); } - resetHighlightRange(); + ISourceViewer viewer = getSourceViewer(); + if (viewer instanceof ITextViewerExtension5) { + ITextViewerExtension5 extension = (ITextViewerExtension5) viewer; + extension.exposeModelRange(new Region(offset, length)); + } else { + resetHighlightRange(); + } + } + protected boolean isActivePart() { IWorkbenchWindow window = getSite().getWorkbenchWindow(); IPartService service = window.getPartService(); @@ -2348,10 +2565,11 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements return part != null && part.equals(this); } - // public void openContextHelp() { - // IDocument doc = this.getDocumentProvider().getDocument(this.getEditorInput()); - // ITextSelection selection = (ITextSelection) this.getSelectionProvider().getSelection(); + // IDocument doc = + // this.getDocumentProvider().getDocument(this.getEditorInput()); + // ITextSelection selection = (ITextSelection) + // this.getSelectionProvider().getSelection(); // int pos = selection.getOffset(); // String word = getFunctionName(doc, pos); // openContextHelp(word); @@ -2367,7 +2585,8 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements // IHelpResource helpResource = new PHPFunctionHelpResource(word); // WorkbenchHelp.getHelpSupport().displayHelpResource(helpResource); // } else { - // // showMessage(shell, dialogTitle, ActionMessages.getString("Open help not available"), false); //$NON-NLS-1$ + // // showMessage(shell, dialogTitle, ActionMessages.getString("Open help + // not available"), false); //$NON-NLS-1$ // } // } @@ -2404,28 +2623,30 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements } return; } - -// if (OVERVIEW_RULER.equals(property)) { -// if (isOverviewRulerVisible()) -// showOverviewRuler(); -// else -// hideOverviewRuler(); -// return; -// } - -// if (LINE_NUMBER_RULER.equals(property)) { -// if (isLineNumberRulerVisible()) -// showLineNumberRuler(); -// else -// hideLineNumberRuler(); -// return; -// } - -// if (fLineNumberRulerColumn != null -// && (LINE_NUMBER_COLOR.equals(property) || PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT.equals(property) || PREFERENCE_COLOR_BACKGROUND.equals(property))) { -// -// initializeLineNumberRulerColumn(fLineNumberRulerColumn); -// } + + // if (OVERVIEW_RULER.equals(property)) { + // if (isOverviewRulerVisible()) + // showOverviewRuler(); + // else + // hideOverviewRuler(); + // return; + // } + + // if (LINE_NUMBER_RULER.equals(property)) { + // if (isLineNumberRulerVisible()) + // showLineNumberRuler(); + // else + // hideLineNumberRuler(); + // return; + // } + + // if (fLineNumberRulerColumn != null + // && (LINE_NUMBER_COLOR.equals(property) || + // PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT.equals(property) || + // PREFERENCE_COLOR_BACKGROUND.equals(property))) { + // + // initializeLineNumberRulerColumn(fLineNumberRulerColumn); + // } if (isJavaEditorHoverProperty(property)) updateHoverBehavior(); @@ -2438,64 +2659,74 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements return; } -// if (PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE.equals(property)) { -// if ((event.getNewValue() instanceof Boolean) && ((Boolean)event.getNewValue()).booleanValue()) -// fEditorSelectionChangedListener.selectionChanged(); -// return; -// } - - if (PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE.equals(property)) { - if (event.getNewValue() instanceof Boolean) { - Boolean disable= (Boolean) event.getNewValue(); - enableOverwriteMode(!disable.booleanValue()); - } - return; - } - -// if (PreferenceConstants.EDITOR_MARK_OCCURRENCES.equals(property)) { -// if (event.getNewValue() instanceof Boolean) { -// boolean markOccurrenceAnnotations= ((Boolean)event.getNewValue()).booleanValue(); -// if (markOccurrenceAnnotations != fMarkOccurrenceAnnotations) { -// fMarkOccurrenceAnnotations= markOccurrenceAnnotations; -// if (!fMarkOccurrenceAnnotations) -// uninstallOccurrencesFinder(); -// else -// installOccurrencesFinder(); -// } -// } -// } -// if (PreferenceConstants.EDITOR_STICKY_OCCURRENCES.equals(property)) { -// if (event.getNewValue() instanceof Boolean) { -// boolean stickyOccurrenceAnnotations= ((Boolean)event.getNewValue()).booleanValue(); -// if (stickyOccurrenceAnnotations != fStickyOccurrenceAnnotations) { -// fStickyOccurrenceAnnotations= stickyOccurrenceAnnotations; -//// if (!fMarkOccurrenceAnnotations) -//// uninstallOccurrencesFinder(); -//// else -//// installOccurrencesFinder(); -// } -// } -// } - 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; - } + // if + // (PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE.equals(property)) + // { + // if ((event.getNewValue() instanceof Boolean) && + // ((Boolean)event.getNewValue()).booleanValue()) + // fEditorSelectionChangedListener.selectionChanged(); + // return; + // } + + if (PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE.equals(property)) { + if (event.getNewValue() instanceof Boolean) { + Boolean disable = (Boolean) event.getNewValue(); + enableOverwriteMode(!disable.booleanValue()); + } + return; + } + + // if (PreferenceConstants.EDITOR_MARK_OCCURRENCES.equals(property)) + // { + // if (event.getNewValue() instanceof Boolean) { + // boolean markOccurrenceAnnotations= + // ((Boolean)event.getNewValue()).booleanValue(); + // if (markOccurrenceAnnotations != fMarkOccurrenceAnnotations) { + // fMarkOccurrenceAnnotations= markOccurrenceAnnotations; + // if (!fMarkOccurrenceAnnotations) + // uninstallOccurrencesFinder(); + // else + // installOccurrencesFinder(); + // } + // } + // } + // if + // (PreferenceConstants.EDITOR_STICKY_OCCURRENCES.equals(property)) + // { + // if (event.getNewValue() instanceof Boolean) { + // boolean stickyOccurrenceAnnotations= + // ((Boolean)event.getNewValue()).booleanValue(); + // if (stickyOccurrenceAnnotations != fStickyOccurrenceAnnotations) + // { + // fStickyOccurrenceAnnotations= stickyOccurrenceAnnotations; + //// if (!fMarkOccurrenceAnnotations) + //// uninstallOccurrencesFinder(); + //// else + //// installOccurrencesFinder(); + // } + // } + // } + 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); } } // /* - // * @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent) + // * @see + // AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent) // */ // protected void handlePreferenceStoreChanged(PropertyChangeEvent event) { // @@ -2507,15 +2738,17 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements // // String property = event.getProperty(); // - // // if (JavaSourceViewerConfiguration.PREFERENCE_TAB_WIDTH.equals(property)) { - // // Object value= event.getNewValue(); - // // if (value instanceof Integer) { - // // sourceViewer.getTextWidget().setTabs(((Integer) value).intValue()); - // // } else if (value instanceof String) { - // // sourceViewer.getTextWidget().setTabs(Integer.parseInt((String) value)); - // // } - // // return; - // // } + // // if + // (JavaSourceViewerConfiguration.PREFERENCE_TAB_WIDTH.equals(property)) { + // // Object value= event.getNewValue(); + // // if (value instanceof Integer) { + // // sourceViewer.getTextWidget().setTabs(((Integer) value).intValue()); + // // } else if (value instanceof String) { + // // sourceViewer.getTextWidget().setTabs(Integer.parseInt((String) + // value)); + // // } + // // return; + // // } // // if (IPreferenceConstants.LINE_NUMBER_RULER.equals(property)) { // if (isLineNumberRulerVisible()) @@ -2552,22 +2785,22 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements /** * Shows the line number ruler column. */ -// private void showLineNumberRuler() { -// IVerticalRuler v = getVerticalRuler(); -// if (v instanceof CompositeRuler) { -// CompositeRuler c = (CompositeRuler) v; -// c.addDecorator(1, createLineNumberRulerColumn()); -// } -// } + // private void showLineNumberRuler() { + // IVerticalRuler v = getVerticalRuler(); + // if (v instanceof CompositeRuler) { + // CompositeRuler c = (CompositeRuler) v; + // c.addDecorator(1, createLineNumberRulerColumn()); + // } + // } private boolean isJavaEditorHoverProperty(String property) { return PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS.equals(property); } /** - * Return whether the browser like links should be enabled - * according to the preference store settings. - * @return true if the browser like links should be enabled - */ + * Return whether the browser like links should be enabled according to the preference store settings. + * + * @return true if the browser like links should be enabled + */ private boolean isBrowserLikeLinks() { IPreferenceStore store = getPreferenceStore(); return store.getBoolean(BROWSER_LIKE_LINKS); @@ -2592,199 +2825,244 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements fMouseListener = null; } } + /** - * Handles a property change event describing a change - * of the java core's preferences and updates the preference - * related editor properties. + * Handles a property change event describing a change of the java core's preferences and updates the preference related editor + * properties. * - * @param event the property change event + * @param event + * the property change event */ protected void handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) { if (COMPILER_TASK_TAGS.equals(event.getProperty())) { ISourceViewer sourceViewer = getSourceViewer(); if (sourceViewer != null - && affectsTextPresentation(new PropertyChangeEvent(event.getSource(), event.getProperty(), event.getOldValue(), event.getNewValue()))) + && affectsTextPresentation(new PropertyChangeEvent(event.getSource(), event.getProperty(), event.getOldValue(), event + .getNewValue()))) sourceViewer.invalidateTextPresentation(); } } /** - * Return whether the line number ruler column should be - * visible according to the preference store settings. + * Return whether the line number ruler column should be visible according to the preference store settings. + * * @return true if the line numbers should be visible */ -// protected boolean isLineNumberRulerVisible() { -// IPreferenceStore store = getPreferenceStore(); -// return store.getBoolean(LINE_NUMBER_RULER); -// } + // protected boolean isLineNumberRulerVisible() { + // IPreferenceStore store = getPreferenceStore(); + // return store.getBoolean(LINE_NUMBER_RULER); + // } /** * Hides the line number ruler column. */ -// private void hideLineNumberRuler() { -// IVerticalRuler v = getVerticalRuler(); -// if (v instanceof CompositeRuler) { -// CompositeRuler c = (CompositeRuler) v; -// try { -// c.removeDecorator(1); -// } catch (Throwable e) { -// } -// } -// } + // private void hideLineNumberRuler() { + // IVerticalRuler v = getVerticalRuler(); + // if (v instanceof CompositeRuler) { + // CompositeRuler c = (CompositeRuler) v; + // try { + // c.removeDecorator(1); + // } catch (Throwable e) { + // } + // } + // } + /* + * @see AbstractTextEditor#handleCursorPositionChanged() + */ + protected void handleCursorPositionChanged() { + super.handleCursorPositionChanged(); + if (!isEditingScriptRunning() && fUpdater != null) + fUpdater.post(); + } + + /* + * @see org.eclipse.ui.texteditor.AbstractTextEditor#handleElementContentReplaced() + */ + protected void handleElementContentReplaced() { + super.handleElementContentReplaced(); + if (fProjectionModelUpdater != null) + fProjectionModelUpdater.initialize(); + } - /* - * @see AbstractTextEditor#handleCursorPositionChanged() - */ - protected void handleCursorPositionChanged() { - super.handleCursorPositionChanged(); - 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 + * + * @param rulerColumn + * the ruler column to be initialized */ -// protected void initializeLineNumberRulerColumn(LineNumberRulerColumn rulerColumn) { -// JavaTextTools textTools = PHPeclipsePlugin.getDefault().getJavaTextTools(); -// IColorManager manager = textTools.getColorManager(); -// -// IPreferenceStore store = getPreferenceStore(); -// if (store != null) { -// -// RGB rgb = null; -// // foreground color -// if (store.contains(LINE_NUMBER_COLOR)) { -// if (store.isDefault(LINE_NUMBER_COLOR)) -// rgb = PreferenceConverter.getDefaultColor(store, LINE_NUMBER_COLOR); -// else -// rgb = PreferenceConverter.getColor(store, LINE_NUMBER_COLOR); -// } -// rulerColumn.setForeground(manager.getColor(rgb)); -// -// rgb = null; -// // background color -// if (!store.getBoolean(PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT)) { -// if (store.contains(PREFERENCE_COLOR_BACKGROUND)) { -// if (store.isDefault(PREFERENCE_COLOR_BACKGROUND)) -// rgb = PreferenceConverter.getDefaultColor(store, PREFERENCE_COLOR_BACKGROUND); -// else -// rgb = PreferenceConverter.getColor(store, PREFERENCE_COLOR_BACKGROUND); -// } -// } -// rulerColumn.setBackground(manager.getColor(rgb)); -// } -// } - + // protected void initializeLineNumberRulerColumn(LineNumberRulerColumn + // rulerColumn) { + // JavaTextTools textTools = + // PHPeclipsePlugin.getDefault().getJavaTextTools(); + // IColorManager manager = textTools.getColorManager(); + // + // IPreferenceStore store = getPreferenceStore(); + // if (store != null) { + // + // RGB rgb = null; + // // foreground color + // if (store.contains(LINE_NUMBER_COLOR)) { + // if (store.isDefault(LINE_NUMBER_COLOR)) + // rgb = PreferenceConverter.getDefaultColor(store, LINE_NUMBER_COLOR); + // else + // rgb = PreferenceConverter.getColor(store, LINE_NUMBER_COLOR); + // } + // rulerColumn.setForeground(manager.getColor(rgb)); + // + // rgb = null; + // // background color + // if (!store.getBoolean(PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT)) { + // if (store.contains(PREFERENCE_COLOR_BACKGROUND)) { + // if (store.isDefault(PREFERENCE_COLOR_BACKGROUND)) + // rgb = PreferenceConverter.getDefaultColor(store, + // PREFERENCE_COLOR_BACKGROUND); + // else + // rgb = PreferenceConverter.getColor(store, PREFERENCE_COLOR_BACKGROUND); + // } + // } + // rulerColumn.setBackground(manager.getColor(rgb)); + // } + // } /** * Creates a new line number ruler column that is appropriately initialized. */ -// protected IVerticalRulerColumn createLineNumberRulerColumn() { -// fLineNumberRulerColumn = new LineNumberRulerColumn(); -// initializeLineNumberRulerColumn(fLineNumberRulerColumn); -// return fLineNumberRulerColumn; -// } - + // protected IVerticalRulerColumn createLineNumberRulerColumn() { + // fLineNumberRulerColumn = new LineNumberRulerColumn(); + // initializeLineNumberRulerColumn(fLineNumberRulerColumn); + // return fLineNumberRulerColumn; + // } /* * @see AbstractTextEditor#createVerticalRuler() */ -// protected IVerticalRuler createVerticalRuler() { -// CompositeRuler ruler = new CompositeRuler(); -// ruler.addDecorator(0, new AnnotationRulerColumn(VERTICAL_RULER_WIDTH)); -// if (isLineNumberRulerVisible()) -// ruler.addDecorator(1, createLineNumberRulerColumn()); -// return ruler; + // protected IVerticalRuler createVerticalRuler() { + // CompositeRuler ruler = new CompositeRuler(); + // ruler.addDecorator(0, new AnnotationRulerColumn(VERTICAL_RULER_WIDTH)); + // if (isLineNumberRulerVisible()) + // ruler.addDecorator(1, createLineNumberRulerColumn()); + // return ruler; + // } +// private static IRegion getSignedSelection(ITextViewer viewer) { +// +// StyledText text = viewer.getTextWidget(); +// int caretOffset = text.getCaretOffset(); +// Point selection = text.getSelection(); +// +// // caret left +// int offset, length; +// if (caretOffset == selection.x) { +// offset = selection.y; +// length = selection.x - selection.y; +// +// // caret right +// } else { +// offset = selection.x; +// length = selection.y - selection.x; +// } +// +// return new Region(offset, length); // } - - private static IRegion getSignedSelection(ITextViewer viewer) { - - StyledText text = viewer.getTextWidget(); - int caretOffset = text.getCaretOffset(); - Point selection = text.getSelection(); - - // caret left - int offset, length; - if (caretOffset == selection.x) { - offset = selection.y; - length = selection.x - selection.y; - - // caret right - } else { - offset = selection.x; - length = selection.y - selection.x; - } - - return new Region(offset, length); - } - + protected IRegion getSignedSelection(ISourceViewer sourceViewer) { + StyledText text= sourceViewer.getTextWidget(); + Point selection= text.getSelectionRange(); + + if (text.getCaretOffset() == selection.x) { + selection.x= selection.x + selection.y; + selection.y= -selection.y; + } + + selection.x= widgetOffset2ModelOffset(sourceViewer, selection.x); + + return new Region(selection.x, selection.y); + } /** Preference key for matching brackets */ protected final static String MATCHING_BRACKETS = PreferenceConstants.EDITOR_MATCHING_BRACKETS; + /** Preference key for matching brackets color */ protected final static String MATCHING_BRACKETS_COLOR = PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR; + /** Preference key for highlighting current line */ protected final static String CURRENT_LINE = PreferenceConstants.EDITOR_CURRENT_LINE; + /** Preference key for highlight color of current line */ protected final static String CURRENT_LINE_COLOR = PreferenceConstants.EDITOR_CURRENT_LINE_COLOR; + /** Preference key for showing print marging ruler */ protected final static String PRINT_MARGIN = PreferenceConstants.EDITOR_PRINT_MARGIN; + /** Preference key for print margin ruler color */ protected final static String PRINT_MARGIN_COLOR = PreferenceConstants.EDITOR_PRINT_MARGIN_COLOR; + /** Preference key for print margin ruler column */ protected final static String PRINT_MARGIN_COLUMN = PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN; + /** Preference key for error indication */ -// protected final static String ERROR_INDICATION = PreferenceConstants.EDITOR_PROBLEM_INDICATION; + // protected final static String ERROR_INDICATION = + // PreferenceConstants.EDITOR_PROBLEM_INDICATION; /** Preference key for error color */ -// protected final static String ERROR_INDICATION_COLOR = PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR; + // protected final static String ERROR_INDICATION_COLOR = + // PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR; /** Preference key for warning indication */ -// protected final static String WARNING_INDICATION = PreferenceConstants.EDITOR_WARNING_INDICATION; + // protected final static String WARNING_INDICATION = + // PreferenceConstants.EDITOR_WARNING_INDICATION; /** Preference key for warning color */ -// protected final static String WARNING_INDICATION_COLOR = PreferenceConstants.EDITOR_WARNING_INDICATION_COLOR; + // protected final static String WARNING_INDICATION_COLOR = + // PreferenceConstants.EDITOR_WARNING_INDICATION_COLOR; /** Preference key for task indication */ protected final static String TASK_INDICATION = PreferenceConstants.EDITOR_TASK_INDICATION; + /** Preference key for task color */ protected final static String TASK_INDICATION_COLOR = PreferenceConstants.EDITOR_TASK_INDICATION_COLOR; + /** Preference key for bookmark indication */ protected final static String BOOKMARK_INDICATION = PreferenceConstants.EDITOR_BOOKMARK_INDICATION; + /** Preference key for bookmark color */ protected final static String BOOKMARK_INDICATION_COLOR = PreferenceConstants.EDITOR_BOOKMARK_INDICATION_COLOR; + /** Preference key for search result indication */ protected final static String SEARCH_RESULT_INDICATION = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION; + /** Preference key for search result color */ protected final static String SEARCH_RESULT_INDICATION_COLOR = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_COLOR; + /** Preference key for unknown annotation indication */ protected final static String UNKNOWN_INDICATION = PreferenceConstants.EDITOR_UNKNOWN_INDICATION; + /** Preference key for unknown annotation color */ protected final static String UNKNOWN_INDICATION_COLOR = PreferenceConstants.EDITOR_UNKNOWN_INDICATION_COLOR; + /** Preference key for shwoing the overview ruler */ protected final static String OVERVIEW_RULER = PreferenceConstants.EDITOR_OVERVIEW_RULER; + /** Preference key for error indication in overview ruler */ protected final static String ERROR_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER; + /** Preference key for warning indication in overview ruler */ protected final static String WARNING_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER; + /** Preference key for task indication in overview ruler */ protected final static String TASK_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER; + /** Preference key for bookmark indication in overview ruler */ protected final static String BOOKMARK_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER; + /** Preference key for search result indication in overview ruler */ protected 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 */ protected final static String UNKNOWN_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER; + // /** Preference key for compiler task tags */ - // private final static String COMPILER_TASK_TAGS= JavaCore.COMPILER_TASK_TAGS; + // private final static String COMPILER_TASK_TAGS= + // JavaCore.COMPILER_TASK_TAGS; /** Preference key for browser like links */ private final static String BROWSER_LIKE_LINKS = PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS; + /** Preference key for key modifier of browser like links */ private final static String BROWSER_LIKE_LINKS_KEY_MODIFIER = PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER; + /** - * Preference key for key modifier mask of browser like links. - * The value is only used if the value of EDITOR_BROWSER_LIKE_LINKS - * cannot be resolved to valid SWT modifier bits. + * Preference key for key modifier mask of browser like links. The value is only used if the value of + * EDITOR_BROWSER_LIKE_LINKS cannot be resolved to valid SWT modifier bits. * * @since 2.1.1 */ @@ -2811,65 +3089,68 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements } } -// protected void configureSourceViewerDecorationSupport() { -// -// fSourceViewerDecorationSupport.setCharacterPairMatcher(fBracketMatcher); -// -// fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys( -// AnnotationType.UNKNOWN, -// UNKNOWN_INDICATION_COLOR, -// UNKNOWN_INDICATION, -// UNKNOWN_INDICATION_IN_OVERVIEW_RULER, -// 0); -// fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys( -// AnnotationType.BOOKMARK, -// BOOKMARK_INDICATION_COLOR, -// BOOKMARK_INDICATION, -// BOOKMARK_INDICATION_IN_OVERVIEW_RULER, -// 1); -// fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys( -// AnnotationType.TASK, -// TASK_INDICATION_COLOR, -// TASK_INDICATION, -// TASK_INDICATION_IN_OVERVIEW_RULER, -// 2); -// fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys( -// AnnotationType.SEARCH, -// SEARCH_RESULT_INDICATION_COLOR, -// SEARCH_RESULT_INDICATION, -// SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER, -// 3); -// fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys( -// AnnotationType.WARNING, -// WARNING_INDICATION_COLOR, -// WARNING_INDICATION, -// WARNING_INDICATION_IN_OVERVIEW_RULER, -// 4); -// fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys( -// AnnotationType.ERROR, -// ERROR_INDICATION_COLOR, -// ERROR_INDICATION, -// ERROR_INDICATION_IN_OVERVIEW_RULER, -// 5); -// -// fSourceViewerDecorationSupport.setCursorLinePainterPreferenceKeys(CURRENT_LINE, CURRENT_LINE_COLOR); -// fSourceViewerDecorationSupport.setMarginPainterPreferenceKeys(PRINT_MARGIN, PRINT_MARGIN_COLOR, PRINT_MARGIN_COLUMN); -// fSourceViewerDecorationSupport.setMatchingCharacterPainterPreferenceKeys(MATCHING_BRACKETS, MATCHING_BRACKETS_COLOR); -// -// fSourceViewerDecorationSupport.setSymbolicFontName(getFontPropertyPreferenceKey()); -// -// } + // protected void configureSourceViewerDecorationSupport() { + // + // fSourceViewerDecorationSupport.setCharacterPairMatcher(fBracketMatcher); + // + // fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys( + // AnnotationType.UNKNOWN, + // UNKNOWN_INDICATION_COLOR, + // UNKNOWN_INDICATION, + // UNKNOWN_INDICATION_IN_OVERVIEW_RULER, + // 0); + // fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys( + // AnnotationType.BOOKMARK, + // BOOKMARK_INDICATION_COLOR, + // BOOKMARK_INDICATION, + // BOOKMARK_INDICATION_IN_OVERVIEW_RULER, + // 1); + // fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys( + // AnnotationType.TASK, + // TASK_INDICATION_COLOR, + // TASK_INDICATION, + // TASK_INDICATION_IN_OVERVIEW_RULER, + // 2); + // fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys( + // AnnotationType.SEARCH, + // SEARCH_RESULT_INDICATION_COLOR, + // SEARCH_RESULT_INDICATION, + // SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER, + // 3); + // fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys( + // AnnotationType.WARNING, + // WARNING_INDICATION_COLOR, + // WARNING_INDICATION, + // WARNING_INDICATION_IN_OVERVIEW_RULER, + // 4); + // fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys( + // AnnotationType.ERROR, + // ERROR_INDICATION_COLOR, + // ERROR_INDICATION, + // ERROR_INDICATION_IN_OVERVIEW_RULER, + // 5); + // + // fSourceViewerDecorationSupport.setCursorLinePainterPreferenceKeys(CURRENT_LINE, + // CURRENT_LINE_COLOR); + // fSourceViewerDecorationSupport.setMarginPainterPreferenceKeys(PRINT_MARGIN, + // PRINT_MARGIN_COLOR, PRINT_MARGIN_COLUMN); + // fSourceViewerDecorationSupport.setMatchingCharacterPainterPreferenceKeys(MATCHING_BRACKETS, + // MATCHING_BRACKETS_COLOR); + // + // fSourceViewerDecorationSupport.setSymbolicFontName(getFontPropertyPreferenceKey()); + // + // } /** - * Returns the Java element wrapped by this editors input. - * - * @return the Java element wrapped by this editors input. - * @since 3.0 - */ - abstract protected IJavaElement getInputJavaElement(); + * Returns the Java element wrapped by this editors input. + * + * @return the Java element wrapped by this editors input. + * @since 3.0 + */ + abstract protected IJavaElement getInputJavaElement(); /** - * Jumps to the matching bracket. - */ + * Jumps to the matching bracket. + */ public void gotoMatchingBracket() { ISourceViewer sourceViewer = getSourceViewer(); @@ -2928,10 +3209,13 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements sourceViewer.setSelectedRange(targetOffset, selection.getLength()); sourceViewer.revealRange(targetOffset, selection.getLength()); } + /** - * Ses the given message as error message to this editor's status line. - * @param msg message to be set - */ + * Ses the given message as error message to this editor's status line. + * + * @param msg + * message to be set + */ protected void setStatusLineErrorMessage(String msg) { IEditorStatusLine statusLine = (IEditorStatusLine) getAdapter(IEditorStatusLine.class); if (statusLine != null) @@ -2939,14 +3223,17 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements } /** - * Returns a segmentation of the line of the given document appropriate for bidi rendering. - * The default implementation returns only the string literals of a php code line as segments. - * - * @param document the document - * @param lineOffset the offset of the line - * @return the line's bidi segmentation - * @throws BadLocationException in case lineOffset is not valid in document - */ + * Returns a segmentation of the line of the given document appropriate for bidi rendering. The default implementation returns + * only the string literals of a php code line as segments. + * + * @param document + * the document + * @param lineOffset + * the offset of the line + * @return the line's bidi segmentation + * @throws BadLocationException + * in case lineOffset is not valid in document + */ public static int[] getBidiLineSegments(IDocument document, int lineOffset) throws BadLocationException { IRegion line = document.getLineInformationOfOffset(lineOffset); @@ -2989,14 +3276,17 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements return segments; } + /** - * Returns a segmentation of the given line appropriate for bidi rendering. The default - * implementation returns only the string literals of a php code line as segments. - * - * @param lineOffset the offset of the line - * @param line the content of the line - * @return the line's bidi segmentation - */ + * Returns a segmentation of the given line appropriate for bidi rendering. The default implementation returns only the string + * literals of a php code line as segments. + * + * @param lineOffset + * the offset of the line + * @param line + * the content of the line + * @return the line's bidi segmentation + */ protected int[] getBidiLineSegments(int lineOffset, String line) { IDocumentProvider provider = getDocumentProvider(); if (provider != null && line != null && line.length() > 0) { @@ -3025,111 +3315,123 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements // event.segments = getBidiLineSegments(event.lineOffset, event.lineText); // } // }); - // // JavaUIHelp.setHelp(this, text, IJavaHelpContextIds.JAVA_EDITOR); + // // JavaUIHelp.setHelp(this, text, IJavaHelpContextIds.JAVA_EDITOR); // return viewer; // } - public final ISourceViewer getViewer() { - return getSourceViewer(); + return getSourceViewer(); } - -// protected void showOverviewRuler() { -// if (fOverviewRuler != null) { -// if (getSourceViewer() instanceof ISourceViewerExtension) { -// ((ISourceViewerExtension) getSourceViewer()).showAnnotationsOverview(true); -// fSourceViewerDecorationSupport.updateOverviewDecorations(); -// } -// } -// } -// -// protected void hideOverviewRuler() { -// if (getSourceViewer() instanceof ISourceViewerExtension) { -// fSourceViewerDecorationSupport.hideAnnotationOverview(); -// ((ISourceViewerExtension) getSourceViewer()).showAnnotationsOverview(false); -// } -// } + // protected void showOverviewRuler() { + // if (fOverviewRuler != null) { + // if (getSourceViewer() instanceof ISourceViewerExtension) { + // ((ISourceViewerExtension) + // getSourceViewer()).showAnnotationsOverview(true); + // fSourceViewerDecorationSupport.updateOverviewDecorations(); + // } + // } + // } + // + // protected void hideOverviewRuler() { + // if (getSourceViewer() instanceof ISourceViewerExtension) { + // fSourceViewerDecorationSupport.hideAnnotationOverview(); + // ((ISourceViewerExtension) + // getSourceViewer()).showAnnotationsOverview(false); + // } + // } -// protected boolean isOverviewRulerVisible() { -// IPreferenceStore store = getPreferenceStore(); -// return store.getBoolean(OVERVIEW_RULER); -// } + // protected boolean isOverviewRulerVisible() { + // IPreferenceStore store = getPreferenceStore(); + // return store.getBoolean(OVERVIEW_RULER); + // } /* * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int) */ -// protected ISourceViewer createJavaSourceViewer( -// Composite parent, -// IVerticalRuler ruler, -// IOverviewRuler overviewRuler, -// boolean isOverviewRulerVisible, -// 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); - } + // protected ISourceViewer createJavaSourceViewer( + // Composite parent, + // IVerticalRuler ruler, + // IOverviewRuler overviewRuler, + // boolean isOverviewRulerVisible, + // int styles) { + // return new SourceViewer(parent, ruler, overviewRuler, + // isOverviewRulerVisible(), styles); + // } /* - * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int) - */ - 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); + * @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); + } - // ensure source viewer decoration support has been created and configured - getSourceViewerDecorationSupport(viewer); - - return viewer; - } - /** - * Creates and returns the preference store for this Java editor with the given input. - * - * @param input The editor input for which to create the preference store - * @return the preference store for this editor - * - * @since 3.0 - */ - private IPreferenceStore createCombinedPreferenceStore(IEditorInput input) { - List stores= new ArrayList(3); - - IJavaProject project= EditorUtility.getJavaProject(input); - if (project != null) - stores.add(new OptionsAdapter(project.getOptions(false), PHPeclipsePlugin.getDefault().getMockupPreferenceStore(), new OptionsAdapter.IPropertyChangeEventFilter() { - - public boolean isFiltered(PropertyChangeEvent event) { - IJavaElement inputJavaElement= getInputJavaElement(); - IJavaProject javaProject= inputJavaElement != null ? inputJavaElement.getJavaProject() : null; - if (javaProject == null) - return true; - - return !javaProject.getProject().equals(event.getSource()); - } - - })); - - stores.add(PHPeclipsePlugin.getDefault().getPreferenceStore()); - stores.add(new PreferencesAdapter(JavaCore.getPlugin().getPluginPreferences())); - stores.add(EditorsUI.getPreferenceStore()); - - return new ChainedPreferenceStore((IPreferenceStore[]) stores.toArray(new IPreferenceStore[stores.size()])); - } - /* - * @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#createSourceViewer(Composite, IVerticalRuler, int) + */ + 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; + } + + /** + * Creates and returns the preference store for this Java editor with the given input. + * + * @param input + * The editor input for which to create the preference store + * @return the preference store for this editor + * + * @since 3.0 + */ + private IPreferenceStore createCombinedPreferenceStore(IEditorInput input) { + List stores = new ArrayList(3); + + IJavaProject project = EditorUtility.getJavaProject(input); + if (project != null) + stores.add(new OptionsAdapter(project.getOptions(false), PHPeclipsePlugin.getDefault().getMockupPreferenceStore(), + new OptionsAdapter.IPropertyChangeEventFilter() { + + public boolean isFiltered(PropertyChangeEvent event) { + IJavaElement inputJavaElement = getInputJavaElement(); + IJavaProject javaProject = inputJavaElement != null ? inputJavaElement.getJavaProject() : null; + if (javaProject == null) + return true; + + return !javaProject.getProject().equals(event.getSource()); + } + + })); + + stores.add(PHPeclipsePlugin.getDefault().getPreferenceStore()); + stores.add(new PreferencesAdapter(JavaCore.getPlugin().getPluginPreferences())); + stores.add(EditorsUI.getPreferenceStore()); + + return new ChainedPreferenceStore((IPreferenceStore[]) stores.toArray(new IPreferenceStore[stores.size()])); + } + + /* + * @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) */ @@ -3177,7 +3479,7 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements } selectAndReveal(errorPosition.getOffset(), errorPosition.getLength()); -// setStatusLineErrorMessage(nextError.getMessage()); + // setStatusLineErrorMessage(nextError.getMessage()); } else { @@ -3233,78 +3535,173 @@ public abstract class PHPEditor extends AbstractDecoratedTextEditor implements return nextError; } + void removeOccurrenceAnnotations() { - IDocumentProvider documentProvider= getDocumentProvider(); - if (documentProvider == null) - return; - - IAnnotationModel annotationModel= documentProvider.getAnnotationModel(getEditorInput()); - if (annotationModel == null || fOccurrenceAnnotations == null) - return; - - synchronized (annotationModel) { - if (annotationModel instanceof IAnnotationModelExtension) { - ((IAnnotationModelExtension)annotationModel).replaceAnnotations(fOccurrenceAnnotations, null); - } else { - for (int i= 0, length= fOccurrenceAnnotations.length; i < length; i++) - annotationModel.removeAnnotation(fOccurrenceAnnotations[i]); - } - fOccurrenceAnnotations= null; - } -} -// protected void uninstallOverrideIndicator() { -// if (fOverrideIndicatorManager != null) { -// fOverrideIndicatorManager.removeAnnotations(); -// fOverrideIndicatorManager= null; -// } -//} + IDocumentProvider documentProvider = getDocumentProvider(); + if (documentProvider == null) + return; -protected void installOverrideIndicator(boolean waitForReconcilation) { -// uninstallOverrideIndicator(); - IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput()); -// IJavaElement inputElement= getInputJavaElement(); + IAnnotationModel annotationModel = documentProvider.getAnnotationModel(getEditorInput()); + if (annotationModel == null || fOccurrenceAnnotations == null) + return; + + synchronized (annotationModel) { + if (annotationModel instanceof IAnnotationModelExtension) { + ((IAnnotationModelExtension) annotationModel).replaceAnnotations(fOccurrenceAnnotations, null); + } else { + for (int i = 0, length = fOccurrenceAnnotations.length; i < length; i++) + annotationModel.removeAnnotation(fOccurrenceAnnotations[i]); + } + fOccurrenceAnnotations = null; + } + } -// if (model == null || inputElement == null) -// return; + // protected void uninstallOverrideIndicator() { + // if (fOverrideIndicatorManager != null) { + // fOverrideIndicatorManager.removeAnnotations(); + // fOverrideIndicatorManager= null; + // } + //} -// CompilationUnit ast= PHPeclipsePlugin.getDefault().getASTProvider().getAST(inputElement, true, null); -// fOverrideIndicatorManager= new OverrideIndicatorManager(model, inputElement, ast); -} + protected void installOverrideIndicator(boolean waitForReconcilation) { + // uninstallOverrideIndicator(); + IAnnotationModel model = getDocumentProvider().getAnnotationModel(getEditorInput()); + // IJavaElement inputElement= getInputJavaElement(); -/** - * Tells whether override indicators are shown. - * - * @return true 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()); -//} + // if (model == null || inputElement == null) + // return; -/** - * Returns the boolean preference for the given key. - * - * @param store the preference store - * @param key the preference key - * @return true if the key exists in the store and its value is true - * @since 3.0 - */ -private boolean getBoolean(IPreferenceStore store, String key) { - return key != null && store.getBoolean(key); -} + // CompilationUnit ast= + // PHPeclipsePlugin.getDefault().getASTProvider().getAST(inputElement, + // true, null); + // fOverrideIndicatorManager= new OverrideIndicatorManager(model, + // inputElement, ast); + } /** - * Returns the folding action group, or null if there is none. + * Tells whether override indicators are shown. * - * @return the folding action group, or null if there is none + * @return true if the override indicators are shown * @since 3.0 */ - protected FoldingActionGroup getFoldingActionGroup() { - return fFoldingGroup; - } -} +// 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 true if the key exists in the store and its value is true + * @since 3.0 + */ + private boolean getBoolean(IPreferenceStore store, String key) { + return key != null && store.getBoolean(key); + } + + /** + * Returns the folding action group, or null if there is none. + * + * @return the folding action group, or null if there is none + * @since 3.0 + */ + protected FoldingActionGroup getFoldingActionGroup() { + return fFoldingGroup; + } + + /** + * React to changed selection. + * + * @since 3.0 + */ + protected void selectionChanged() { + if (getSelectionProvider() == null) + return; + ISourceReference element = computeHighlightRangeSourceReference(); + if (getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE)) + synchronizeOutlinePage(element); + setSelection(element, false); + // updateStatusLine(); + } + + private boolean isJavaOutlinePageActive() { + IWorkbenchPart part = getActivePart(); + return part instanceof ContentOutline && ((ContentOutline) part).getCurrentPage() == fOutlinePage; + } + + private IWorkbenchPart getActivePart() { + IWorkbenchWindow window = getSite().getWorkbenchWindow(); + IPartService service = window.getPartService(); + IWorkbenchPart part = service.getActivePart(); + return part; + } + + /** + * Computes and returns the source reference that includes the caret and serves as provider for the outline page selection and the + * editor range indication. + * + * @return the computed source reference + * @since 3.0 + */ + protected ISourceReference computeHighlightRangeSourceReference() { + ISourceViewer sourceViewer = getSourceViewer(); + if (sourceViewer == null) + return null; + + StyledText styledText = sourceViewer.getTextWidget(); + if (styledText == null) + return null; + + int caret = 0; + if (sourceViewer instanceof ITextViewerExtension5) { + ITextViewerExtension5 extension = (ITextViewerExtension5) sourceViewer; + caret = extension.widgetOffset2ModelOffset(styledText.getCaretOffset()); + } else { + int offset = sourceViewer.getVisibleRegion().getOffset(); + caret = offset + styledText.getCaretOffset(); + } + + IJavaElement element = getElementAt(caret, false); + + if (!(element instanceof ISourceReference)) + return null; + + if (element.getElementType() == IJavaElement.IMPORT_DECLARATION) { + + IImportDeclaration declaration = (IImportDeclaration) element; + IImportContainer container = (IImportContainer) declaration.getParent(); + ISourceRange srcRange = null; + + try { + srcRange = container.getSourceRange(); + } catch (JavaModelException e) { + } + + if (srcRange != null && srcRange.getOffset() == caret) + return container; + } + + return (ISourceReference) element; + } + + /** + * Returns the most narrow java element including the given offset. + * + * @param offset + * the offset inside of the requested element + * @param reconcile + * true if editor input should be reconciled in advance + * @return the most narrow java element + * @since 3.0 + */ + protected IJavaElement getElementAt(int offset, boolean reconcile) { + return getElementAt(offset); + } +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPSourceViewerConfiguration.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPSourceViewerConfiguration.java index 401ca2c..5ecde70 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPSourceViewerConfiguration.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPSourceViewerConfiguration.java @@ -18,6 +18,7 @@ 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.JavaCompositeReconcilingStrategy; import net.sourceforge.phpdt.internal.ui.text.JavaElementProvider; import net.sourceforge.phpdt.internal.ui.text.JavaOutlineInformationControl; import net.sourceforge.phpdt.internal.ui.text.JavaPresentationReconciler; @@ -307,16 +308,34 @@ public class PHPSourceViewerConfiguration extends SourceViewerConfiguration { /* * @see SourceViewerConfiguration#getReconciler(ISourceViewer) */ + /* + * @see SourceViewerConfiguration#getReconciler(ISourceViewer) + */ public IReconciler getReconciler(ISourceViewer sourceViewer) { - if (getEditor() != null && getEditor().isEditable()) { - JavaReconciler reconciler = new JavaReconciler(getEditor(), - new JavaReconcilingStrategy(getEditor()), false); + + final ITextEditor editor= getEditor(); + if (editor != null && editor.isEditable()) { + + JavaCompositeReconcilingStrategy strategy= new JavaCompositeReconcilingStrategy(editor, getConfiguredDocumentPartitioning(sourceViewer)); + JavaReconciler reconciler= new JavaReconciler(editor, strategy, false); + reconciler.setIsIncrementalReconciler(false); reconciler.setProgressMonitor(new NullProgressMonitor()); reconciler.setDelay(500); + return reconciler; } return null; } +// public IReconciler getReconciler(ISourceViewer sourceViewer) { +// if (getEditor() != null && getEditor().isEditable()) { +// JavaReconciler reconciler = new JavaReconciler(getEditor(), +// new JavaReconcilingStrategy(getEditor()), false); +// reconciler.setProgressMonitor(new NullProgressMonitor()); +// reconciler.setDelay(500); +// return reconciler; +// } +// return null; +// } /* * @see SourceViewerConfiguration#getConfiguredTextHoverStateMasks(ISourceViewer, * String) diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPUnitEditor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPUnitEditor.java index 34ceb6f..a7cc596 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPUnitEditor.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/PHPUnitEditor.java @@ -7,15 +7,19 @@ import java.util.List; import net.sourceforge.phpdt.core.ICompilationUnit; import net.sourceforge.phpdt.core.IJavaElement; +import net.sourceforge.phpdt.core.IMember; import net.sourceforge.phpdt.core.ISourceRange; import net.sourceforge.phpdt.core.ISourceReference; import net.sourceforge.phpdt.core.JavaCore; import net.sourceforge.phpdt.core.JavaModelException; +import net.sourceforge.phpdt.core.dom.CompilationUnit; import net.sourceforge.phpdt.internal.compiler.parser.Scanner; import net.sourceforge.phpdt.internal.ui.actions.CompositeActionGroup; import net.sourceforge.phpdt.internal.ui.text.ContentAssistPreference; import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions; import net.sourceforge.phpdt.internal.ui.text.PHPPairMatcher; +import net.sourceforge.phpdt.internal.ui.text.SmartBackspaceManager; +import net.sourceforge.phpdt.internal.ui.text.java.IJavaReconcilingListener; import net.sourceforge.phpdt.internal.ui.text.link.LinkedPositionManager; import net.sourceforge.phpdt.internal.ui.text.link.LinkedPositionUI; import net.sourceforge.phpdt.internal.ui.text.link.LinkedPositionUI.ExitFlags; @@ -25,6 +29,7 @@ import net.sourceforge.phpdt.ui.actions.GenerateActionGroup; import net.sourceforge.phpdt.ui.text.JavaTextTools; import net.sourceforge.phpeclipse.PHPeclipsePlugin; +import org.eclipse.core.internal.runtime.ListenerList; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; @@ -47,7 +52,6 @@ import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.ILineTracker; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextOperationTarget; -import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.text.ITextViewerExtension; import org.eclipse.jface.text.ITypedRegion; import org.eclipse.jface.text.IWidgetTokenKeeper; @@ -58,7 +62,6 @@ 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; @@ -70,13 +73,17 @@ import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IEditorInput; +import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IFileEditorInput; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.actions.ActionContext; import org.eclipse.ui.actions.ActionGroup; import org.eclipse.ui.dialogs.SaveAsDialog; import org.eclipse.ui.editors.text.IStorageDocumentProvider; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.part.FileEditorInput; +import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants; import org.eclipse.ui.texteditor.ContentAssistAction; import org.eclipse.ui.texteditor.IDocumentProvider; import org.eclipse.ui.texteditor.ITextEditorActionConstants; @@ -504,7 +511,358 @@ public class PHPUnitEditor extends PHPEditor { //implements // IDocument.DEFAULT_CONTENT_TYPE); } }; + /** + * Remembers data related to the current selection to be able to + * restore it later. + * + * @since 3.0 + */ + private class RememberedSelection { + /** The remembered selection start. */ + private RememberedOffset fStartOffset= new RememberedOffset(); + /** The remembered selection end. */ + private RememberedOffset fEndOffset= new RememberedOffset(); + + /** + * Remember current selection. + */ + public void remember() { + /* https://bugs.eclipse.org/bugs/show_bug.cgi?id=52257 + * This method may be called inside an async call posted + * to the UI thread, so protect against intermediate disposal + * of the editor. + */ + ISourceViewer viewer= getSourceViewer(); + if (viewer != null) { + IRegion selection= getSignedSelection(viewer); + int startOffset= selection.getOffset(); + int endOffset= startOffset + selection.getLength(); + + fStartOffset.setOffset(startOffset); + fEndOffset.setOffset(endOffset); + } + } + + /** + * Restore remembered selection. + */ + public void restore() { + /* https://bugs.eclipse.org/bugs/show_bug.cgi?id=52257 + * This method may be called inside an async call posted + * to the UI thread, so protect against intermediate disposal + * of the editor. + */ + if (getSourceViewer() == null) + return; + + try { + + int startOffset, endOffset; + int revealStartOffset, revealEndOffset; + if (showsHighlightRangeOnly()) { + IJavaElement newStartElement= fStartOffset.getElement(); + startOffset= fStartOffset.getRememberedOffset(newStartElement); + revealStartOffset= fStartOffset.getRevealOffset(newStartElement, startOffset); + if (revealStartOffset == -1) + startOffset= -1; + + IJavaElement newEndElement= fEndOffset.getElement(); + endOffset= fEndOffset.getRememberedOffset(newEndElement); + revealEndOffset= fEndOffset.getRevealOffset(newEndElement, endOffset); + if (revealEndOffset == -1) + endOffset= -1; + } else { + startOffset= fStartOffset.getOffset(); + revealStartOffset= startOffset; + endOffset= fEndOffset.getOffset(); + revealEndOffset= endOffset; + } + + if (startOffset == -1) { + startOffset= endOffset; // fallback to caret offset + revealStartOffset= revealEndOffset; + } + + if (endOffset == -1) { + endOffset= startOffset; // fallback to other offset + revealEndOffset= revealStartOffset; + } + + IJavaElement element; + if (endOffset == -1) { + // fallback to element selection + element= fEndOffset.getElement(); + if (element == null) + element= fStartOffset.getElement(); + if (element != null) + setSelection(element); + return; + } + + if (isValidSelection(revealStartOffset, revealEndOffset - revealStartOffset) && isValidSelection(startOffset, endOffset - startOffset)) + selectAndReveal(startOffset, endOffset - startOffset, revealStartOffset, revealEndOffset - revealStartOffset); + } finally { + fStartOffset.clear(); + fEndOffset.clear(); + } + } + + 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; + } + + } + /** + * Remembers additional data for a given + * offset to be able restore it later. + * + * @since 3.0 + */ + private class RememberedOffset { + /** Remembered line for the given offset */ + private int fLine; + /** Remembered column for the given offset*/ + private int fColumn; + /** Remembered Java element for the given offset*/ + private IJavaElement fElement; + /** Remembered Java element line for the given offset*/ + private int fElementLine; + + /** + * Store visual properties of the given offset. + * + * @param offset Offset in the document + */ + public void setOffset(int offset) { + try { + IDocument document= getSourceViewer().getDocument(); + fLine= document.getLineOfOffset(offset); + fColumn= offset - document.getLineOffset(fLine); + fElement= getElementAt(offset, true); + + fElementLine= -1; + if (fElement instanceof IMember) { + ISourceRange range= ((IMember) fElement).getNameRange(); + if (range != null) + fElementLine= document.getLineOfOffset(range.getOffset()); + } + if (fElementLine == -1) + fElementLine= document.getLineOfOffset(getOffset(fElement)); + } catch (BadLocationException e) { + // should not happen + PHPeclipsePlugin.log(e); + clear(); + } catch (JavaModelException e) { + // should not happen + PHPeclipsePlugin.log(e.getStatus()); + clear(); + } + } + + /** + * Return offset recomputed from stored visual properties. + * + * @return Offset in the document + */ + public int getOffset() { + IJavaElement newElement= getElement(); + + int offset= getRememberedOffset(newElement); + + if (offset != -1 && !containsOffset(newElement, offset) && (offset == 0 || !containsOffset(newElement, offset - 1))) + return -1; + + return offset; + } + + /** + * Return offset recomputed from stored visual properties. + * + * @param newElement Enclosing element + * @return Offset in the document + */ + public int getRememberedOffset(IJavaElement newElement) { + try { + if (newElement == null) + return -1; + + IDocument document= getSourceViewer().getDocument(); + int newElementLine= -1; + if (newElement instanceof IMember) { + ISourceRange range= ((IMember) newElement).getNameRange(); + if (range != null) + newElementLine= document.getLineOfOffset(range.getOffset()); + } + if (newElementLine == -1) + newElementLine= document.getLineOfOffset(getOffset(newElement)); + if (newElementLine == -1) + return -1; + + int newLine= fLine + newElementLine - fElementLine; + if (newLine < 0 || newLine >= document.getNumberOfLines()) + return -1; + int maxColumn= document.getLineLength(newLine); + String lineDelimiter= document.getLineDelimiter(newLine); + if (lineDelimiter != null) + maxColumn= maxColumn - lineDelimiter.length(); + int offset; + if (fColumn > maxColumn) + offset= document.getLineOffset(newLine) + maxColumn; + else + offset= document.getLineOffset(newLine) + fColumn; + + return offset; + } catch (BadLocationException e) { + // should not happen + PHPeclipsePlugin.log(e); + return -1; + } catch (JavaModelException e) { + // should not happen + PHPeclipsePlugin.log(e.getStatus()); + return -1; + } + } + + /** + * Returns the offset used to reveal the given element based on the given selection offset. + * @param element the element + * @param offset the selection offset + * @return the offset to reveal the given element based on the given selection offset + */ + public int getRevealOffset(IJavaElement element, int offset) { + if (element == null || offset == -1) + return -1; + + if (containsOffset(element, offset)) { + if (offset > 0) { + IJavaElement alternateElement= getElementAt(offset, false); + if (element.getHandleIdentifier().equals(alternateElement.getParent().getHandleIdentifier())) + return offset - 1; // Solves test case 2 from https://bugs.eclipse.org/bugs/show_bug.cgi?id=47727#c3 + } + return offset; + } else if (offset > 0 && containsOffset(element, offset - 1)) + return offset - 1; // Solves test case 1 from https://bugs.eclipse.org/bugs/show_bug.cgi?id=47727#c3 + + return -1; + } + + /** + * Return Java element recomputed from stored visual properties. + * + * @return Java element + */ + public IJavaElement getElement() { + if (fElement == null) + return null; + + return findElement(fElement); + } + + /** + * Clears the stored position + */ + public void clear() { + fLine= -1; + fColumn= -1; + fElement= null; + fElementLine= -1; + } + + /** + * Does the given Java element contain the given offset? + * @param element Java element + * @param offset Offset + * @return true iff the Java element contains the offset + */ + private boolean containsOffset(IJavaElement element, int offset) { + int elementOffset= getOffset(element); + int elementLength= getLength(element); + return (elementOffset > -1 && elementLength > -1) ? (offset >= elementOffset && offset < elementOffset + elementLength) : false; + } + /** + * Returns the offset of the given Java element. + * + * @param element Java element + * @return 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; + } + + /** + * Returns the length of the given Java element. + * + * @param element Java element + * @return Length of the given Java element + */ + private int getLength(IJavaElement element) { + if (element instanceof ISourceReference) { + ISourceReference sr= (ISourceReference) element; + try { + ISourceRange srcRange= sr.getSourceRange(); + if (srcRange != null) + return srcRange.getLength(); + } catch (JavaModelException e) { + } + } + return -1; + } + + /** + * Returns the updated java element for the old java element. + * + * @param element Old Java element + * @return Updated 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(ICompilationUnit.NO_AST, false, null, null); + 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; + } + + } + static class TabConverter implements ITextConverter { private int fTabRatio; @@ -862,8 +1220,12 @@ public class PHPUnitEditor extends PHPEditor { //implements /** The remembered java element */ private IJavaElement fRememberedElement; - /** The remembered selection */ - private ITextSelection fRememberedSelection; + /** + * The remembered selection. + * @since 3.0 + */ + private RememberedSelection fRememberedSelection= new RememberedSelection(); + /** The remembered php element offset */ private int fRememberedElementOffset; @@ -1060,6 +1422,22 @@ public class PHPUnitEditor extends PHPEditor { //implements /** * Creates a new php unit editor. */ + + /** + * Reconciling listeners. + * @since 3.0 + */ + private ListenerList fReconcilingListeners= new ListenerList(); + + /** + * Mutex for the reconciler. See https://bugs.eclipse.org/bugs/show_bug.cgi?id=63898 + * for a description of the problem. + *

+ * TODO remove once the underlying problem is solved. + *

+ */ + private final Object fReconcilerLock= new Object(); + public PHPUnitEditor() { super(); setDocumentProvider(PHPeclipsePlugin.getDefault() @@ -1746,28 +2124,6 @@ public class PHPUnitEditor extends PHPEditor { //implements } /* - * @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 org.eclipse.jdt.internal.ui.javaeditor.JavaEditor#getInputElement() */ protected IJavaElement getInputJavaElement() { @@ -1795,6 +2151,7 @@ public class PHPUnitEditor extends PHPEditor { //implements page.setInput(manager.getWorkingCopy(input)); } } + /* * @see AbstractTextEditor#performSaveOperation(WorkspaceModifyOperation, @@ -2115,26 +2472,47 @@ public class PHPUnitEditor extends PHPEditor { //implements return true; } + /* + * @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 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(); - } + * @see org.eclipse.jdt.internal.ui.text.java.IJavaReconcilingListener#reconciled(CompilationUnit, boolean, IProgressMonitor) + * @since 3.0 + */ + public void reconciled(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(); + } + }); + } + } + } private boolean synchronizeOutlineOnCursorMove() { return PreferenceConstants.getPreferenceStore().getBoolean( @@ -2182,86 +2560,147 @@ public class PHPUnitEditor extends PHPEditor { //implements 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; - } - } +// 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(); - // } - // }); - // } - // } - // } + /** + * Tells whether this is the active editor in the active page. + * + * @return true if this is the active editor in the active page + * @see IWorkbenchPage#getActiveEditor(); + */ + protected final boolean isActiveEditor() { + IWorkbenchWindow window= getSite().getWorkbenchWindow(); + IWorkbenchPage page= window.getActivePage(); + if (page == null) + return false; + IEditorPart activeEditor= page.getActiveEditor(); + return activeEditor != null && activeEditor.equals(this); + } + + /** + * Adds the given listener. + * Has no effect if an identical listener was not already registered. + * + * @param listener The reconcile listener to be added + * @since 3.0 + */ + final void addReconcileListener(IJavaReconcilingListener listener) { + synchronized (fReconcilingListeners) { + fReconcilingListeners.add(listener); + } + } + + /** + * Removes the given listener. + * Has no effect if an identical listener was not already registered. + * + * @param listener the reconcile listener to be removed + * @since 3.0 + */ + final void removeReconcileListener(IJavaReconcilingListener listener) { + synchronized (fReconcilingListeners) { + fReconcilingListeners.remove(listener); + } + } + + protected void updateStateDependentActions() { + super.updateStateDependentActions(); + fGenerateActionGroup.editorStateChanged(); + } + + /* + * @see AbstractTextEditor#rememberSelection() + */ + protected void rememberSelection() { + fRememberedSelection.remember(); + } + + /* + * @see AbstractTextEditor#restoreSelection() + */ + protected void restoreSelection() { + fRememberedSelection.restore(); + } + + /* + * @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 org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#isPrefQuickDiffAlwaysOn() + */ + protected boolean isPrefQuickDiffAlwaysOn() { + // reestablishes the behaviour from AbstractDecoratedTextEditor which was hacked by JavaEditor + // to disable the change bar for the class file (attached source) java editor. + IPreferenceStore store= getPreferenceStore(); + return store.getBoolean(AbstractDecoratedTextEditorPreferenceConstants.QUICK_DIFF_ALWAYS_ON); + } + + /* + * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor#getAdapter(java.lang.Class) + */ + public Object getAdapter(Class required) { + if (SmartBackspaceManager.class.equals(required)) { + if (getSourceViewer() instanceof JavaSourceViewer) { + return ((JavaSourceViewer) getSourceViewer()).getBackspaceManager(); + } + } + + return super.getAdapter(required); + } + /** + * Returns the mutex for the reconciler. See https://bugs.eclipse.org/bugs/show_bug.cgi?id=63898 + * for a description of the problem. + *

+ * TODO remove once the underlying problem is solved. + *

+ * @return the lock reconcilers may use to synchronize on + */ + public Object getReconcilerLock() { + return fReconcilerLock; + } + } \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPCompletionProcessor.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPCompletionProcessor.java index 69f3124..d0d7f92 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPCompletionProcessor.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/phpeditor/php/PHPCompletionProcessor.java @@ -282,12 +282,23 @@ public class PHPCompletionProcessor implements IContentAssistProcessor { scanner.setPHPMode(true); int beforeLastToken = ITerminalSymbols.TokenNameEOF; int lastToken = ITerminalSymbols.TokenNameEOF; + char[] ident; try { token = scanner.getNextToken(); lastToken = token; while (token != ITerminalSymbols.TokenNameERROR && token != ITerminalSymbols.TokenNameEOF) { beforeLastToken = lastToken; + if (lastToken==ITerminalSymbols.TokenNameVariable) { + ident = scanner.getCurrentTokenSource(); + if (ident[0]=='$' && + ident[0]=='t' && + ident[0]=='h' && + ident[0]=='i' && + ident[0]=='s') { + beforeLastToken = ITerminalSymbols.TokenNamethis_PHP_COMPLETION; + } + } lastToken = token; // System.out.println(scanner.toStringAction(lastToken)); token = scanner.getNextToken(); @@ -534,61 +545,7 @@ public class PHPCompletionProcessor implements IContentAssistProcessor { // } } } - - final ICompilationUnit unit = fManager.getWorkingCopy(fEditor - .getEditorInput()); - - // get buffer contents - final IBuffer buffer; - CompilationUnitDeclaration unitDecl=null; - try { - buffer = unit.getBuffer(); - - if (project != null && buffer != null) { - - // 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(null, - problemFactory, new CompilerOptions(null)); - //, true/*report local declarations*/); - unitDecl = parser.parseCompletionUnit( - new net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit() { - public char[] getContents() { - return buffer.getCharacters(); - } - - public char[] getMainTypeName() { - return null; - } - - public char[][] getPackageName() { - return null; - } - - public char[] getFileName() { - return null; - } - }, true /* full parse to find local elements */); - - } -// System.out.println(unit.toString()); - } catch (Exception e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - + ContextType phpContextType = ContextTypeRegistry.getInstance() .getContextType("php"); //$NON-NLS-1$ ((CompilationUnitContextType) phpContextType).setContextParameters( @@ -599,7 +556,8 @@ public class PHPCompletionProcessor implements IContentAssistProcessor { int lastSignificantToken = getLastToken(viewer, offset, context, sqlTable); boolean useClassMembers = (lastSignificantToken == ITerminalSymbols.TokenNameMINUS_GREATER) || (lastSignificantToken == ITerminalSymbols.TokenNameVariable) - || (lastSignificantToken == ITerminalSymbols.TokenNamenew); + || (lastSignificantToken == ITerminalSymbols.TokenNamenew) + || (lastSignificantToken == ITerminalSymbols.TokenNamethis_PHP_COMPLETION); boolean emptyPrefix = prefix == null || prefix.equals(""); if (fTemplateEngine != null) { IPHPCompletionProposal[] templateResults = new IPHPCompletionProposal[0];