diff options
Diffstat (limited to 'bundles/org.eclipse.wst.sse.ui/src/org/eclipse')
278 files changed, 0 insertions, 58098 deletions
diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/EditorExecutionContext.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/EditorExecutionContext.java deleted file mode 100644 index b40d9a5bc0..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/EditorExecutionContext.java +++ /dev/null @@ -1,157 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui; - -import java.lang.reflect.InvocationTargetException; - -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.ISafeRunnable; -import org.eclipse.core.runtime.SafeRunner; -import org.eclipse.core.runtime.jobs.ISchedulingRule; -import org.eclipse.jface.operation.IRunnableWithProgress; -import org.eclipse.swt.widgets.Display; -import org.eclipse.ui.IWorkbench; -import org.eclipse.ui.IWorkbenchPartSite; -import org.eclipse.ui.IWorkbenchWindow; -import org.eclipse.ui.progress.IWorkbenchSiteProgressService; -import org.eclipse.wst.sse.core.internal.IExecutionDelegate; -import org.eclipse.wst.sse.ui.internal.Logger; -import org.eclipse.wst.sse.ui.internal.SSEUIPlugin; - -class EditorExecutionContext implements IExecutionDelegate { - - /** - * Reusable runnable for the Display execution queue to cut down on - * garbage creation. Will make use of the progress service if possible. - */ - private static class ReusableUIRunner implements Runnable, IRunnableWithProgress { - private StructuredTextEditor editor; - private ISafeRunnable fRunnable = null; - - ReusableUIRunner(StructuredTextEditor part) { - super(); - editor = part; - } - - /* - * Expected to only be run by Display queue in the UI Thread - * - * @see java.lang.Runnable#run() - */ - public void run() { - IWorkbenchPartSite site = editor.getEditorPart().getSite(); - final IWorkbenchWindow workbenchWindow = (site == null) ? null : site.getWorkbenchWindow(); - final IWorkbenchSiteProgressService jobService = (IWorkbenchSiteProgressService) ((site == null) ? null : site.getAdapter(IWorkbenchSiteProgressService.class)); - /* - * Try to use the progress service so the workbench can give more - * feedback to the user (although editors seem to make less use of - * the service than views - - * https://bugs.eclipse.org/bugs/show_bug.cgi?id=86221 . - */ - if (workbenchWindow != null && jobService != null) { - /* - * Doc is ambiguous, but it must be run from the UI thread - - * https://bugs.eclipse.org/bugs/show_bug.cgi?id=165180 - */ - try { - jobService.runInUI(workbenchWindow, this, (ISchedulingRule) editor.getEditorPart().getEditorInput().getAdapter(IResource.class)); - } - catch (InvocationTargetException e) { - Logger.logException(e); - } - catch (InterruptedException e) { - Logger.logException(e); - } - } - else { - /* - * Run it directly and direct the UI of the editor. See - * StructuredTextEditor's begin/end background job for other - * activities to best accommodate (for example, there is a - * "timed delay" before the editor itself leaves - * background-update mode). NOTE: this execute method itself - * is always called from inside of an ILock block, so another - * block is not not needed here for all these sycnExec's. - */ - IWorkbench workbench = SSEUIPlugin.getInstance().getWorkbench(); - final Display display = workbench.getDisplay(); - if (display != null && !display.isDisposed()) { - editor.beginBackgroundOperation(); - try { - /* - * Here's where the document update/modification - * occurs - */ - SafeRunner.run(fRunnable); - } - finally { - /* - * This 'end' is just a signal to editor that this - * particular update is done. Its up to the editor to - * decide exactly when to leave its "background mode" - */ - editor.endBackgroundOperation(); - } - } - fRunnable = null; - } - } - - /* - * (non-Javadoc) - * - * @see - * org.eclipse.jface.operation.IRunnableWithProgress#run(org.eclipse - * .core.runtime.IProgressMonitor) - */ - public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { - if (fRunnable != null) - SafeRunner.run(fRunnable); - } - - void setRunnable(ISafeRunnable r) { - fRunnable = r; - } - } - - StructuredTextEditor fEditor; - private ReusableUIRunner fReusableRunner; - - public EditorExecutionContext(StructuredTextEditor editor) { - super(); - fEditor = editor; - fReusableRunner = new ReusableUIRunner(fEditor); - } - - /* - * (non-Javadoc) - * - * @see - * org.eclipse.wst.sse.core.internal.IExecutionDelegate#execute(java.lang - * .Runnable) - */ - public void execute(final ISafeRunnable runnable) { - IWorkbench workbench = SSEUIPlugin.getInstance().getWorkbench(); - final Display display = workbench.getDisplay(); - if (display.getThread() == Thread.currentThread()) { - // *If already in display thread, we can simply run, "as usual"*/ - SafeRunner.run(runnable); - } - else { - // *otherwise run through the reusable runner */ - fReusableRunner.setRunnable(runnable); - display.syncExec(fReusableRunner); - } - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/EncodingSupport.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/EncodingSupport.java deleted file mode 100644 index fd054ef577..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/EncodingSupport.java +++ /dev/null @@ -1,139 +0,0 @@ -/*******************************************************************************
- * Copyright (c) 2008 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.sse.ui;
-
-import org.eclipse.ui.editors.text.DefaultEncodingSupport;
-import org.eclipse.ui.editors.text.IEncodingSupport;
-import org.eclipse.ui.texteditor.StatusTextEditor;
-import org.eclipse.wst.sse.ui.internal.ExtendedConfigurationBuilder;
-
-/**
- * An implementation that will try to use a <b>provisional</b> configuration
- * if IEncodingSupport.class as a delegate. A delegate, if found, will be
- * asked for encoding information before defaulting to the superclass
- * implementation, but will be told to set the encoding after the superclass
- * has. Delegates should not duplicate any functionality in the
- * DefaultEncodingSupport implementation as they may be executed in addition
- * to the default behavior.
- */
-class EncodingSupport extends DefaultEncodingSupport {
- private String[] fConfigurationPoints = null;
- /** The editor this support is associated with. */
- private StatusTextEditor fStatusTextEditor;
-
- IEncodingSupport fSupportDelegate = null;
-
- EncodingSupport(String[] configurationPoints) {
- super();
- fConfigurationPoints = configurationPoints;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.editors.text.DefaultEncodingSupport#dispose()
- */
- public void dispose() {
- super.dispose();
-
- if (fSupportDelegate instanceof DefaultEncodingSupport) {
- ((DefaultEncodingSupport) fSupportDelegate).dispose();
- }
- fSupportDelegate = null;
- fStatusTextEditor = null;
- }
-
- /*
- * (non-Javadoc)
- *
- * @seeorg.eclipse.ui.editors.text.DefaultEncodingSupport#
- * getDefaultEncoding()
- */
- public String getDefaultEncoding() {
- IEncodingSupport delegate = getEncodingSupportDelegate();
- if (delegate != null) {
- return delegate.getDefaultEncoding();
- }
-
- return super.getDefaultEncoding();
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.editors.text.DefaultEncodingSupport#getEncoding ()
- */
- public String getEncoding() {
- IEncodingSupport delegate = getEncodingSupportDelegate();
- if (delegate != null) {
- return delegate.getEncoding();
- }
-
- return super.getEncoding();
- }
-
- IEncodingSupport getEncodingSupportDelegate() {
- if (fSupportDelegate == null) {
- ExtendedConfigurationBuilder builder = ExtendedConfigurationBuilder.getInstance();
- for (int i = 0; fSupportDelegate == null && i < fConfigurationPoints.length; i++) {
- fSupportDelegate = (IEncodingSupport) builder.getConfiguration(IEncodingSupport.class.getName(), fConfigurationPoints[i]);
- }
- }
- return fSupportDelegate;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.eclipse.ui.editors.text.DefaultEncodingSupport#initialize(org.eclipse
- * .ui.texteditor.StatusTextEditor)
- */
- public void initialize(StatusTextEditor textEditor) {
- super.initialize(textEditor);
- fStatusTextEditor = textEditor;
-
- IEncodingSupport encodingSupportDelegate = getEncodingSupportDelegate();
- if (encodingSupportDelegate instanceof DefaultEncodingSupport) {
- ((DefaultEncodingSupport) encodingSupportDelegate).initialize(textEditor);
- }
- }
-
- void reinitialize(String[] configurationPoints) {
- if (fSupportDelegate instanceof DefaultEncodingSupport) {
- ((DefaultEncodingSupport) fSupportDelegate).dispose();
- }
- fSupportDelegate = null;
-
- fConfigurationPoints = configurationPoints;
-
- IEncodingSupport encodingSupportDelegate = getEncodingSupportDelegate();
- if (encodingSupportDelegate instanceof DefaultEncodingSupport) {
- ((DefaultEncodingSupport) encodingSupportDelegate).initialize(fStatusTextEditor);
- }
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.editors.text.DefaultEncodingSupport#setEncoding
- * (java.lang.String, boolean)
- */
- protected void setEncoding(String encoding, boolean overwrite) {
- super.setEncoding(encoding, overwrite);
-
- IEncodingSupport delegate = getEncodingSupportDelegate();
- if (delegate != null && overwrite) {
- delegate.setEncoding(encoding);
- }
- }
-}
diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/FoldingActionGroup.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/FoldingActionGroup.java deleted file mode 100644 index 04222353ed..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/FoldingActionGroup.java +++ /dev/null @@ -1,184 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2006, 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui; - -import java.util.ResourceBundle; - -import org.eclipse.jface.action.IAction; -import org.eclipse.jface.action.IMenuManager; -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.text.ITextOperationTarget; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.source.projection.IProjectionListener; -import org.eclipse.jface.text.source.projection.ProjectionViewer; -import org.eclipse.ui.actions.ActionGroup; -import org.eclipse.ui.editors.text.IFoldingCommandIds; -import org.eclipse.ui.texteditor.ITextEditor; -import org.eclipse.ui.texteditor.IUpdate; -import org.eclipse.ui.texteditor.ResourceAction; -import org.eclipse.ui.texteditor.TextOperationAction; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; -import org.eclipse.wst.sse.ui.internal.SSEUIPlugin; -import org.eclipse.wst.sse.ui.internal.projection.AbstractStructuredFoldingStrategy; - -class FoldingActionGroup extends ActionGroup { - private static abstract class PreferenceAction extends ResourceAction implements IUpdate { - PreferenceAction(ResourceBundle bundle, String prefix, int style) { - super(bundle, prefix, style); - } - } - - private ProjectionViewer fViewer; - - private final PreferenceAction fToggle; - private final TextOperationAction fExpand; - private final TextOperationAction fExpandAll; - private final IProjectionListener fProjectionListener; - private final TextOperationAction fCollapse; - private final TextOperationAction fCollapseAll; - - - /** - * Creates a new projection action group for <code>editor</code>. If - * the supplied viewer is not an instance of <code>ProjectionViewer</code>, - * the action group is disabled. - * - * @param editor - * the text editor to operate on - * @param viewer - * the viewer of the editor - */ - public FoldingActionGroup(final ITextEditor editor, ITextViewer viewer) { - if (!(viewer instanceof ProjectionViewer)) { - fToggle = null; - fExpand = null; - fExpandAll = null; - fCollapse = null; - fCollapseAll = null; - fProjectionListener = null; - return; - } - - fViewer = (ProjectionViewer) viewer; - - fProjectionListener = new IProjectionListener() { - - public void projectionEnabled() { - update(); - } - - public void projectionDisabled() { - update(); - } - }; - - fViewer.addProjectionListener(fProjectionListener); - - fToggle = new PreferenceAction(SSEUIMessages.getResourceBundle(), "Projection_Toggle_", IAction.AS_CHECK_BOX) { //$NON-NLS-1$ - public void run() { - IPreferenceStore store = SSEUIPlugin.getDefault().getPreferenceStore(); - boolean current = store.getBoolean(AbstractStructuredFoldingStrategy.FOLDING_ENABLED); - store.setValue(AbstractStructuredFoldingStrategy.FOLDING_ENABLED, !current); - } - - public void update() { - ITextOperationTarget target = (ITextOperationTarget) editor.getAdapter(ITextOperationTarget.class); - - boolean isEnabled = (target != null && target.canDoOperation(ProjectionViewer.TOGGLE)); - setEnabled(isEnabled); - } - }; - - IPreferenceStore store = SSEUIPlugin.getDefault().getPreferenceStore(); - boolean checked = store.getBoolean(AbstractStructuredFoldingStrategy.FOLDING_ENABLED); - fToggle.setChecked(checked); - fToggle.setActionDefinitionId(IFoldingCommandIds.FOLDING_TOGGLE); - editor.setAction("FoldingToggle", fToggle); //$NON-NLS-1$ - - fExpand = new TextOperationAction(SSEUIMessages.getResourceBundle(), "Projection_Expand_", editor, ProjectionViewer.EXPAND, true); //$NON-NLS-1$ - fExpand.setActionDefinitionId(IFoldingCommandIds.FOLDING_EXPAND); - editor.setAction("FoldingExpand", fExpand); //$NON-NLS-1$ - - fExpandAll = new TextOperationAction(SSEUIMessages.getResourceBundle(), "Projection_ExpandAll_", editor, ProjectionViewer.EXPAND_ALL, true); //$NON-NLS-1$ - fExpandAll.setActionDefinitionId(IFoldingCommandIds.FOLDING_EXPAND_ALL); - editor.setAction("FoldingExpandAll", fExpandAll); //$NON-NLS-1$ - - fCollapse = new TextOperationAction(SSEUIMessages.getResourceBundle(), "Projection_Collapse_", editor, ProjectionViewer.COLLAPSE, true); //$NON-NLS-1$ - fCollapse.setActionDefinitionId(IFoldingCommandIds.FOLDING_COLLAPSE); - editor.setAction("FoldingCollapse", fCollapse); //$NON-NLS-1$ - - fCollapseAll = new TextOperationAction(SSEUIMessages.getResourceBundle(), "Projection_CollapseAll_", editor, ProjectionViewer.COLLAPSE_ALL, true); //$NON-NLS-1$ - fCollapseAll.setActionDefinitionId(IFoldingCommandIds.FOLDING_COLLAPSE_ALL); - editor.setAction("FoldingCollapseAll", fCollapseAll); //$NON-NLS-1$ - } - - /** - * Returns <code>true</code> if the group is enabled. - * - * <pre> - * Invariant: isEnabled() <=> fViewer and all actions are != null. - * </pre> - * - * @return <code>true</code> if the group is enabled - */ - protected boolean isEnabled() { - return fViewer != null; - } - - /* - * @see org.eclipse.ui.actions.ActionGroup#dispose() - */ - public void dispose() { - if (isEnabled()) { - fViewer.removeProjectionListener(fProjectionListener); - fViewer = null; - } - super.dispose(); - } - - /** - * Updates the actions. - */ - protected void update() { - if (isEnabled()) { - fToggle.update(); - fToggle.setChecked(fViewer.isProjectionMode()); - fExpand.update(); - fExpandAll.update(); - fCollapse.update(); - fCollapseAll.update(); - } - } - - /** - * Fills the menu with all folding actions. - * - * @param manager - * the menu manager for the folding submenu - */ - public void fillMenu(IMenuManager manager) { - if (isEnabled()) { - update(); - manager.add(fToggle); - manager.add(fExpand); - manager.add(fExpandAll); - manager.add(fCollapse); - manager.add(fCollapseAll); - } - } - - /* - * @see org.eclipse.ui.actions.ActionGroup#updateActionBars() - */ - public void updateActionBars() { - update(); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/IContentSelectionProvider.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/IContentSelectionProvider.java deleted file mode 100644 index 84ab1917fc..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/IContentSelectionProvider.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.eclipse.wst.sse.ui; - -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.TreeViewer; - -/** - * Allows contributors to redefine a selection when provided with the current - * selection. - * - */ -public interface IContentSelectionProvider { - ISelection getSelection(TreeViewer viewer, ISelection selection); -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/ISemanticHighlighting.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/ISemanticHighlighting.java deleted file mode 100644 index 40d6f8ca6e..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/ISemanticHighlighting.java +++ /dev/null @@ -1,86 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009, 2011 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui; - -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.text.Position; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion; - -/** - * This interface defines preferences and consumability for semantic highlighting. - * The preference keys provided by the implementation are stored within the preference store - * provided by the implementation. When a region is consumable by the semantic highlighting, - * the implementation provides an array of positions to style. - * - * @since 3.1 - * - */ -public interface ISemanticHighlighting { - - /** - * The preference key that controls the text's bold attribute for the semantic highlighting - * @return the bold preference key - */ - public String getBoldPreferenceKey(); - - /** - * The preference key that controls the text's underline attribute for the semantic highlighting - * @return the underline preference key - */ - public String getUnderlinePreferenceKey(); - - /** - * The preference key that controls the text's strikethrough attribute for the semantic highlighting - * @return the strikethrough preference key - */ - public String getStrikethroughPreferenceKey(); - - /** - * The preference key that controls the text's italic attribute for the semantic highlighting - * @return the italic preference key - */ - public String getItalicPreferenceKey(); - - /** - * The preference key that controls the text's color attribute for the semantic highlighting - * @return the foreground color preference key - */ - public String getColorPreferenceKey(); - - /** - * The preference store that maintains the preferences for the semantic highlighting - * @return the preference store for the semantic highlighting - */ - public IPreferenceStore getPreferenceStore(); - - /** - * The preference key that controls if the semantic highlighting is enabled - * @return the enabled state preference key - */ - public String getEnabledPreferenceKey(); - - /** - * @return the display name - */ - public String getDisplayName(); - - /** - * Returns an array of positions iff the semantic highlighting consumes any part of the structured document region. - * <p> - * NOTE: Implementors are not allowed to keep a reference on the region or on any object - * retrieved from the region. - * </p> - * - * @param region the structured document region - * @return an array of positions to consume iff the semantic highlighting consumes any part of the structured document region, otherwise null - */ - public Position[] consumes(IStructuredDocumentRegion region); -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/ISemanticHighlightingExtension.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/ISemanticHighlightingExtension.java deleted file mode 100644 index fdaef10916..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/ISemanticHighlightingExtension.java +++ /dev/null @@ -1,39 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui; - -import org.eclipse.jface.text.Position; -import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion; - -/** - * Extends {@link org.eclipse.wst.sse.ui.ISemanticHighlighting} allowing clients to - * define consumability with respect to indexed regions containing the structured - * document region. - * - * @since 3.2 - */ -public interface ISemanticHighlightingExtension { - - /** - * Returns an array of positions iff the semantic highlighting consumes any part of the structured document region - * - * <p> - * NOTE: Implementors are not allowed to keep a reference on the either regions or on any object - * retrieved from the regions. - * </p> - * - * @param documentRegion the structured document region - * @param indexedRegion the indexed region that contains the <code>documentRegion</code> - * @return an array of positions to consume iff the semantic highlighting consumes any part of the structured document region, otherwise null - */ - public Position[] consumes(IStructuredDocumentRegion documentRegion, IndexedRegion indexedRegion); -}
\ No newline at end of file diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/ISemanticHighlightingExtension2.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/ISemanticHighlightingExtension2.java deleted file mode 100644 index 4277e7e8ab..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/ISemanticHighlightingExtension2.java +++ /dev/null @@ -1,27 +0,0 @@ -/****************************************************************************** - * Copyright (c) 2011 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - ******************************************************************************/ -package org.eclipse.wst.sse.ui; - -/** - * This interface defines extends {@link ISemanticHighlighting} to provide a preference - * key for background styling when not using a <code>styleString</code> associated with - * the semantic highlighting - * - * @since 3.3 - * - */ -public interface ISemanticHighlightingExtension2 { - /** - * The preference key that controls the text's background color attribute for the semantic highlighting - * @return the background color preference key - */ - String getBackgroundColorPreferenceKey(); -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/StructuredSourceViewerDecorationSupport.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/StructuredSourceViewerDecorationSupport.java deleted file mode 100644 index 72486bdc4a..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/StructuredSourceViewerDecorationSupport.java +++ /dev/null @@ -1,46 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui; - -import org.eclipse.jface.text.source.AnnotationPainter; -import org.eclipse.jface.text.source.IAnnotationAccess; -import org.eclipse.jface.text.source.IOverviewRuler; -import org.eclipse.jface.text.source.ISharedTextColors; -import org.eclipse.jface.text.source.ISourceViewer; -import org.eclipse.ui.texteditor.AnnotationPreference; -import org.eclipse.ui.texteditor.SourceViewerDecorationSupport; - -class StructuredSourceViewerDecorationSupport extends SourceViewerDecorationSupport { - public StructuredSourceViewerDecorationSupport(ISourceViewer sourceViewer, IOverviewRuler overviewRuler, IAnnotationAccess annotationAccess, ISharedTextColors sharedTextColors) { - super(sourceViewer, overviewRuler, annotationAccess, sharedTextColors); - } - - protected AnnotationPainter createAnnotationPainter() { - /* - * The new squiggly drawer depends on the presentation reconciler to - * draw its squiggles. Unfortunately, StructuredTextEditors cannot use - * the presentation reconciler because it conflicts with its - * highlighter. Overriding createAnnotationPainter so that it is - * forced to use the old squiggly painter instead of the new one. See - * https://bugs.eclipse.org/bugs/show_bug.cgi?id=201928 - */ - AnnotationPainter painter = super.createAnnotationPainter(); - // dont use new squiggly painter - painter.addTextStyleStrategy(AnnotationPreference.STYLE_SQUIGGLES, null); - // use old one - painter.addDrawingStrategy(AnnotationPreference.STYLE_SQUIGGLES, new AnnotationPainter.SquigglesStrategy()); - // dont use new problem underline painter - painter.addTextStyleStrategy(AnnotationPreference.STYLE_PROBLEM_UNDERLINE, null); - // use old one - painter.addDrawingStrategy(AnnotationPreference.STYLE_PROBLEM_UNDERLINE, new AnnotationPainter.SquigglesStrategy()); - return painter; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/StructuredTextEditor.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/StructuredTextEditor.java deleted file mode 100644 index e6010d5142..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/StructuredTextEditor.java +++ /dev/null @@ -1,3689 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2011 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui; - -import java.io.IOException; -import java.lang.reflect.Method; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.ResourceBundle; -import java.util.Set; -import java.util.Timer; -import java.util.TimerTask; - -import org.eclipse.core.commands.AbstractHandler; -import org.eclipse.core.commands.ExecutionEvent; -import org.eclipse.core.commands.ExecutionException; -import org.eclipse.core.commands.IHandler; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IConfigurationElement; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.ISafeRunnable; -import org.eclipse.core.runtime.ListenerList; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.SafeRunner; -import org.eclipse.core.runtime.content.IContentType; -import org.eclipse.core.runtime.content.IContentTypeManager; -import org.eclipse.debug.ui.actions.IToggleBreakpointsTarget; -import org.eclipse.emf.common.command.Command; -import org.eclipse.jface.action.Action; -import org.eclipse.jface.action.IAction; -import org.eclipse.jface.action.IMenuManager; -import org.eclipse.jface.action.IStatusLineManager; -import org.eclipse.jface.action.MenuManager; -import org.eclipse.jface.action.Separator; -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.preference.PreferenceConverter; -import org.eclipse.jface.text.AbstractInformationControlManager; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.DefaultInformationControl; -import org.eclipse.jface.text.IBlockTextSelection; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IInformationControl; -import org.eclipse.jface.text.IInformationControlCreator; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ISelectionValidator; -import org.eclipse.jface.text.ITextHover; -import org.eclipse.jface.text.ITextOperationTarget; -import org.eclipse.jface.text.ITextSelection; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.ITextViewerExtension; -import org.eclipse.jface.text.ITextViewerExtension2; -import org.eclipse.jface.text.ITextViewerExtension5; -import org.eclipse.jface.text.ITypedRegion; -import org.eclipse.jface.text.Region; -import org.eclipse.jface.text.TextSelection; -import org.eclipse.jface.text.contentassist.ContentAssistEvent; -import org.eclipse.jface.text.contentassist.ContentAssistant; -import org.eclipse.jface.text.contentassist.ICompletionListener; -import org.eclipse.jface.text.contentassist.ICompletionProposal; -import org.eclipse.jface.text.contentassist.IContentAssistant; -import org.eclipse.jface.text.information.IInformationPresenter; -import org.eclipse.jface.text.information.IInformationProvider; -import org.eclipse.jface.text.information.InformationPresenter; -import org.eclipse.jface.text.reconciler.DirtyRegion; -import org.eclipse.jface.text.reconciler.IReconciler; -import org.eclipse.jface.text.source.Annotation; -import org.eclipse.jface.text.source.ContentAssistantFacade; -import org.eclipse.jface.text.source.DefaultCharacterPairMatcher; -import org.eclipse.jface.text.source.ICharacterPairMatcher; -import org.eclipse.jface.text.source.ISourceViewer; -import org.eclipse.jface.text.source.IVerticalRuler; -import org.eclipse.jface.text.source.LineChangeHover; -import org.eclipse.jface.text.source.SourceViewerConfiguration; -import org.eclipse.jface.text.source.projection.ProjectionSupport; -import org.eclipse.jface.text.source.projection.ProjectionViewer; -import org.eclipse.jface.util.PropertyChangeEvent; -import org.eclipse.jface.util.SafeRunnable; -import org.eclipse.jface.viewers.DoubleClickEvent; -import org.eclipse.jface.viewers.IDoubleClickListener; -import org.eclipse.jface.viewers.ILabelProvider; -import org.eclipse.jface.viewers.IPostSelectionProvider; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.ISelectionChangedListener; -import org.eclipse.jface.viewers.ISelectionProvider; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.viewers.SelectionChangedEvent; -import org.eclipse.swt.SWT; -import org.eclipse.swt.custom.StyledText; -import org.eclipse.swt.custom.VerifyKeyListener; -import org.eclipse.swt.dnd.DND; -import org.eclipse.swt.dnd.DropTarget; -import org.eclipse.swt.events.VerifyEvent; -import org.eclipse.swt.graphics.Color; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.graphics.RGB; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.Menu; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.IEditorActionBarContributor; -import org.eclipse.ui.IEditorInput; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.IEditorSite; -import org.eclipse.ui.IFileEditorInput; -import org.eclipse.ui.IPageLayout; -import org.eclipse.ui.IPartListener; -import org.eclipse.ui.ISharedImages; -import org.eclipse.ui.IStorageEditorInput; -import org.eclipse.ui.IWorkbenchActionConstants; -import org.eclipse.ui.IWorkbenchPart; -import org.eclipse.ui.PartInitException; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.contexts.IContextService; -import org.eclipse.ui.editors.text.EditorsUI; -import org.eclipse.ui.editors.text.ITextEditorHelpContextIds; -import org.eclipse.ui.editors.text.TextEditor; -import org.eclipse.ui.handlers.IHandlerService; -import org.eclipse.ui.help.IWorkbenchHelpSystem; -import org.eclipse.ui.part.IShowInTargetList; -import org.eclipse.ui.progress.IWorkbenchSiteProgressService; -import org.eclipse.ui.texteditor.ChainedPreferenceStore; -import org.eclipse.ui.texteditor.DefaultRangeIndicator; -import org.eclipse.ui.texteditor.IAbstractTextEditorHelpContextIds; -import org.eclipse.ui.texteditor.IDocumentProvider; -import org.eclipse.ui.texteditor.IStatusField; -import org.eclipse.ui.texteditor.ITextEditor; -import org.eclipse.ui.texteditor.ITextEditorActionConstants; -import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds; -import org.eclipse.ui.texteditor.ITextEditorExtension; -import org.eclipse.ui.texteditor.ITextEditorExtension2; -import org.eclipse.ui.texteditor.ITextEditorExtension3; -import org.eclipse.ui.texteditor.ITextEditorExtension4; -import org.eclipse.ui.texteditor.ITextEditorExtension5; -import org.eclipse.ui.texteditor.IUpdate; -import org.eclipse.ui.texteditor.IWorkbenchActionDefinitionIds; -import org.eclipse.ui.texteditor.SourceViewerDecorationSupport; -import org.eclipse.ui.texteditor.TextOperationAction; -import org.eclipse.ui.views.contentoutline.IContentOutlinePage; -import org.eclipse.ui.views.properties.IPropertySheetPage; -import org.eclipse.wst.sse.core.StructuredModelManager; -import org.eclipse.wst.sse.core.internal.document.IDocumentCharsetDetector; -import org.eclipse.wst.sse.core.internal.encoding.EncodingMemento; -import org.eclipse.wst.sse.core.internal.provisional.IModelStateListener; -import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel; -import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument; -import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegion; -import org.eclipse.wst.sse.core.internal.text.IExecutionDelegatable; -import org.eclipse.wst.sse.core.internal.undo.IStructuredTextUndoManager; -import org.eclipse.wst.sse.core.utils.StringUtils; -import org.eclipse.wst.sse.ui.internal.ExtendedConfigurationBuilder; -import org.eclipse.wst.sse.ui.internal.ExtendedEditorActionBuilder; -import org.eclipse.wst.sse.ui.internal.ExtendedEditorDropTargetAdapter; -import org.eclipse.wst.sse.ui.internal.IExtendedContributor; -import org.eclipse.wst.sse.ui.internal.IModelProvider; -import org.eclipse.wst.sse.ui.internal.IPopupMenuContributor; -import org.eclipse.wst.sse.ui.internal.IStructuredTextEditorActionConstants; -import org.eclipse.wst.sse.ui.internal.Logger; -import org.eclipse.wst.sse.ui.internal.ReadOnlyAwareDropTargetAdapter; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; -import org.eclipse.wst.sse.ui.internal.SSEUIPlugin; -import org.eclipse.wst.sse.ui.internal.StorageModelProvider; -import org.eclipse.wst.sse.ui.internal.StructuredTextViewer; -import org.eclipse.wst.sse.ui.internal.UnknownContentTypeDialog; -import org.eclipse.wst.sse.ui.internal.actions.ActionDefinitionIds; -import org.eclipse.wst.sse.ui.internal.actions.StructuredTextEditorActionConstants; -import org.eclipse.wst.sse.ui.internal.contentoutline.ConfigurableContentOutlinePage; -import org.eclipse.wst.sse.ui.internal.debug.BreakpointRulerAction; -import org.eclipse.wst.sse.ui.internal.debug.EditBreakpointAction; -import org.eclipse.wst.sse.ui.internal.debug.ManageBreakpointAction; -import org.eclipse.wst.sse.ui.internal.debug.ToggleBreakpointAction; -import org.eclipse.wst.sse.ui.internal.debug.ToggleBreakpointsTarget; -import org.eclipse.wst.sse.ui.internal.derived.HTMLTextPresenter; -import org.eclipse.wst.sse.ui.internal.editor.EditorModelUtil; -import org.eclipse.wst.sse.ui.internal.editor.IHelpContextIds; -import org.eclipse.wst.sse.ui.internal.editor.SelectionConvertor; -import org.eclipse.wst.sse.ui.internal.editor.StructuredModelDocumentProvider; -import org.eclipse.wst.sse.ui.internal.extension.BreakpointProviderBuilder; -import org.eclipse.wst.sse.ui.internal.handlers.AddBlockCommentHandler; -import org.eclipse.wst.sse.ui.internal.handlers.RemoveBlockCommentHandler; -import org.eclipse.wst.sse.ui.internal.handlers.ToggleLineCommentHandler; -import org.eclipse.wst.sse.ui.internal.hyperlink.OpenHyperlinkAction; -import org.eclipse.wst.sse.ui.internal.preferences.EditorPreferenceNames; -import org.eclipse.wst.sse.ui.internal.projection.AbstractStructuredFoldingStrategy; -import org.eclipse.wst.sse.ui.internal.properties.ConfigurablePropertySheetPage; -import org.eclipse.wst.sse.ui.internal.properties.ShowPropertiesAction; -import org.eclipse.wst.sse.ui.internal.provisional.extensions.ConfigurationPointCalculator; -import org.eclipse.wst.sse.ui.internal.provisional.extensions.ISourceEditingTextTools; -import org.eclipse.wst.sse.ui.internal.provisional.extensions.breakpoint.NullSourceEditingTextTools; -import org.eclipse.wst.sse.ui.internal.provisional.preferences.CommonEditorPreferenceNames; -import org.eclipse.wst.sse.ui.internal.quickoutline.QuickOutlineHandler; -import org.eclipse.wst.sse.ui.internal.quickoutline.QuickOutlinePopupDialog; -import org.eclipse.wst.sse.ui.internal.reconcile.DirtyRegionProcessor; -import org.eclipse.wst.sse.ui.internal.reconcile.DocumentRegionProcessor; -import org.eclipse.wst.sse.ui.internal.selection.SelectionHistory; -import org.eclipse.wst.sse.ui.internal.style.SemanticHighlightingManager; -import org.eclipse.wst.sse.ui.internal.text.DocumentRegionEdgeMatcher; -import org.eclipse.wst.sse.ui.internal.text.SourceInfoProvider; -import org.eclipse.wst.sse.ui.internal.util.Assert; -import org.eclipse.wst.sse.ui.internal.util.EditorUtility; -import org.eclipse.wst.sse.ui.quickoutline.AbstractQuickOutlineConfiguration; -import org.eclipse.wst.sse.ui.reconcile.ISourceReconcilingListener; -import org.eclipse.wst.sse.ui.typing.AbstractCharacterPairInserter; -import org.eclipse.wst.sse.ui.views.contentoutline.ContentOutlineConfiguration; -import org.eclipse.wst.sse.ui.views.properties.PropertySheetConfiguration; - -/** - * A Text Editor for editing structured models and structured documents. - * <p>This class is not meant to be subclassed.</p> - * <p> - * New content types may associate source viewer, content outline, and - * property sheet configurations to extend the existing functionality. - * </p> - * - * @see org.eclipse.wst.sse.ui.StructuredTextViewerConfiguration - * @see org.eclipse.wst.sse.ui.views.contentoutline.ContentOutlineConfiguration - * @see org.eclipse.wst.sse.ui.views.properties.PropertySheetConfiguration - * - * @since 1.0 - */ - -public class StructuredTextEditor extends TextEditor { - private class GotoMatchingBracketHandler extends AbstractHandler { - public Object execute(ExecutionEvent arg0) throws ExecutionException { - gotoMatchingBracket(); - return null; - } - } - - private class InternalModelStateListener implements IModelStateListener { - public void modelAboutToBeChanged(IStructuredModel model) { - if (getTextViewer() != null) { - // getTextViewer().setRedraw(false); - } - } - - public void modelAboutToBeReinitialized(IStructuredModel structuredModel) { - if (getTextViewer() != null) { - // getTextViewer().setRedraw(false); - getTextViewer().unconfigure(); - setStatusLineMessage(null); - } - } - - public void modelChanged(IStructuredModel model) { - if (getSourceViewer() != null) { - // getTextViewer().setRedraw(true); - // Since the model can be changed on a background - // thread, we will update menus on display thread, - // if we are not already on display thread, - // and if there is not an update already pending. - // (we can get lots of 'modelChanged' events in rapid - // succession, so only need to do one. - if (!fUpdateMenuTextPending) { - runOnDisplayThreadIfNeededed(new Runnable() { - public void run() { - updateMenuText(); - fUpdateMenuTextPending = false; - } - }); - } - - } - } - - public void modelDirtyStateChanged(IStructuredModel model, boolean isDirty) { - // do nothing - } - - public void modelReinitialized(IStructuredModel structuredModel) { - try { - if (getSourceViewer() != null) { - SourceViewerConfiguration cfg = getSourceViewerConfiguration(); - getSourceViewer().configure(cfg); - } - } - catch (Exception e) { - // https://w3.opensource.ibm.com/bugzilla/show_bug.cgi?id=1166 - // investigate each error case post beta - Logger.logException("problem trying to configure after model change", e); //$NON-NLS-1$ - } - finally { - // so we don't freeze workbench (eg. during page language or - // content type change) - ((ITextViewerExtension) getSourceViewer()).setRedraw(true); - - IWorkbenchSiteProgressService service = (IWorkbenchSiteProgressService) getSite().getService(IWorkbenchSiteProgressService.class); - if (service != null) { - service.warnOfContentChange(); - } - } - } - - // Note: this one should probably be used to - // control viewer - // instead of viewer having its own listener - public void modelResourceDeleted(IStructuredModel model) { - // do nothing - } - - public void modelResourceMoved(IStructuredModel originalmodel, IStructuredModel movedmodel) { - // do nothing - } - - /** - * This 'Runnable' should be very brief, and should not "call out" to - * other code especially if it depends on the state of the model. - * - * @param r - */ - private void runOnDisplayThreadIfNeededed(Runnable r) { - // if there is no Display at all (that is, running headless), - // or if we are already running on the display thread, then - // simply execute the runnable. - if (getDisplay() == null || (Thread.currentThread() == getDisplay().getThread())) { - r.run(); - } - else { - // otherwise force the runnable to run on the display thread. - getDisplay().asyncExec(r); - } - } - } - - /** - * Listens to double-click and selection from the outline page - */ - private class OutlinePageListener implements IDoubleClickListener, ISelectionChangedListener { - public void doubleClick(DoubleClickEvent event) { - if (event.getSelection().isEmpty()) - return; - - int start = -1; - int length = 0; - if (event.getSelection() instanceof IStructuredSelection) { - ISelection currentSelection = getSelectionProvider().getSelection(); - if (currentSelection instanceof IStructuredSelection) { - Object current = ((IStructuredSelection) currentSelection).toArray(); - Object newSelection = ((IStructuredSelection) event.getSelection()).toArray(); - if (!current.equals(newSelection)) { - IStructuredSelection selection = (IStructuredSelection) event.getSelection(); - Object o = selection.getFirstElement(); - if (o instanceof IndexedRegion) { - start = ((IndexedRegion) o).getStartOffset(); - length = ((IndexedRegion) o).getEndOffset() - start; - } - else if (o instanceof ITextRegion) { - start = ((ITextRegion) o).getStart(); - length = ((ITextRegion) o).getEnd() - start; - } - else if (o instanceof IRegion) { - start = ((ITextRegion) o).getStart(); - length = ((ITextRegion) o).getLength(); - } - } - } - } - else if (event.getSelection() instanceof ITextSelection) { - start = ((ITextSelection) event.getSelection()).getOffset(); - length = ((ITextSelection) event.getSelection()).getLength(); - } - if (start > -1) { - getSourceViewer().setRangeIndication(start, length, false); - selectAndReveal(start, length); - } - } - - public void selectionChanged(SelectionChangedEvent event) { - /* - * Do not allow selection from other parts to affect selection in - * the text widget if it has focus, or if we're still firing a - * change of selection. Selection events "bouncing" off of other - * parts are all that we can receive if we have focus (since we - * forwarded our selection to the service just a moment ago), and - * only the user should affect selection if we have focus. - */ - - /* The isFiringSelection check only works if a selection listener */ - if (event.getSelection().isEmpty() || fStructuredSelectionProvider.isFiringSelection()) - return; - - if (getSourceViewer() != null && getSourceViewer().getTextWidget() != null && !getSourceViewer().getTextWidget().isDisposed() && !getSourceViewer().getTextWidget().isFocusControl()) { - int start = -1; - int length = 0; - if (event.getSelection() instanceof IStructuredSelection) { - ISelection current = getSelectionProvider().getSelection(); - if (current instanceof IStructuredSelection) { - Object[] currentSelection = ((IStructuredSelection) current).toArray(); - Object[] newSelection = ((IStructuredSelection) event.getSelection()).toArray(); - if (!Arrays.equals(currentSelection, newSelection)) { - if (newSelection.length > 0) { - /* - * No ordering is guaranteed for multiple - * selection - */ - Object o = newSelection[0]; - if (o instanceof IndexedRegion) { - start = ((IndexedRegion) o).getStartOffset(); - int end = ((IndexedRegion) o).getEndOffset(); - if (newSelection.length > 1) { - for (int i = 1; i < newSelection.length; i++) { - start = Math.min(start, ((IndexedRegion) newSelection[i]).getStartOffset()); - end = Math.max(end, ((IndexedRegion) newSelection[i]).getEndOffset()); - } - length = end - start; - } - } - else if (o instanceof ITextRegion) { - start = ((ITextRegion) o).getStart(); - int end = ((ITextRegion) o).getEnd(); - if (newSelection.length > 1) { - for (int i = 1; i < newSelection.length; i++) { - start = Math.min(start, ((ITextRegion) newSelection[i]).getStart()); - end = Math.max(end, ((ITextRegion) newSelection[i]).getEnd()); - } - length = end - start; - } - } - else if (o instanceof IRegion) { - start = ((IRegion) o).getOffset(); - int end = start + ((IRegion) o).getLength(); - if (newSelection.length > 1) { - for (int i = 1; i < newSelection.length; i++) { - start = Math.min(start, ((IRegion) newSelection[i]).getOffset()); - end = Math.max(end, ((IRegion) newSelection[i]).getOffset() + ((IRegion) newSelection[i]).getLength()); - } - length = end - start; - } - } - } - } - } - } - else if (event.getSelection() instanceof ITextSelection) { - start = ((ITextSelection) event.getSelection()).getOffset(); - } - if (start > -1) { - updateRangeIndication(event.getSelection()); - selectAndReveal(start, length); - } - } - } - } - - private class ShowInTargetListAdapter implements IShowInTargetList { - /** - * Array of ID Strings that define the default show in targets for - * this editor. - * - * @see org.eclipse.ui.part.IShowInTargetList#getShowInTargetIds() - * @return the array of ID Strings that define the default show in - * targets for this editor. - */ - public String[] getShowInTargetIds() { - return fShowInTargetIds; - } - } - - /** - * A post selection provider that wraps the provider implemented in - * AbstractTextEditor to provide a StructuredTextSelection to post - * selection listeners. Listens to selection changes from the source - * viewer. - */ - private static class StructuredSelectionProvider implements IPostSelectionProvider, ISelectionValidator { - /** - * A "hybrid" text and structured selection class containing the text - * selection and a list of selected model objects. The determination - * of which model objects matches the text selection is responsibility - * of the StructuredSelectionProvider which created this selection - * object. - */ - private static class StructuredTextSelection extends TextSelection implements IStructuredSelection { - private Object[] selectedStructured; - - StructuredTextSelection(IDocument document, int offset, int length, Object[] selectedObjects) { - super(document, offset, length); - selectedStructured = selectedObjects; - } - - StructuredTextSelection(IDocument document, ITextSelection selection, Object[] selectedObjects) { - this(document, selection.getOffset(), selection.getLength(), selectedObjects); - } - - public Object getFirstElement() { - Object[] selectedStructures = getSelectedStructures(); - return selectedStructures.length > 0 ? selectedStructures[0] : null; - } - - private Object[] getSelectedStructures() { - return (selectedStructured != null) ? selectedStructured : new Object[0]; - } - - public boolean isEmpty() { - // https://bugs.eclipse.org/bugs/show_bug.cgi?id=191327 - return super.isEmpty() || getSelectedStructures().length == 0; - } - - public Iterator iterator() { - return toList().iterator(); - } - - public int size() { - return (selectedStructured != null) ? selectedStructured.length : 0; - } - - public Object[] toArray() { - return getSelectedStructures(); - } - - public List toList() { - return Arrays.asList(getSelectedStructures()); - } - - public String toString() { - return getOffset() + ":" + getLength() + "@" + getSelectedStructures(); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - - private ISelectionProvider fParentProvider = null; - private boolean isFiringSelection = false; - private ListenerList listeners = new ListenerList(); - private ListenerList postListeners = new ListenerList(); - private ISelection fLastSelection = null; - private ISelectionProvider fLastSelectionProvider = null; - private SelectionChangedEvent fLastUpdatedSelectionChangedEvent = null; - private StructuredTextEditor fEditor; - /* - * Responsible for finding the selected objects within a text - * selection. Set/reset by the StructuredTextEditor based on a - * per-model adapter on input. - */ - SelectionConvertor selectionConvertor = new SelectionConvertor(); - - StructuredSelectionProvider(ISelectionProvider parentProvider, StructuredTextEditor structuredTextEditor) { - fParentProvider = parentProvider; - fEditor = structuredTextEditor; - fParentProvider.addSelectionChangedListener(new ISelectionChangedListener() { - public void selectionChanged(SelectionChangedEvent event) { - handleSelectionChanged(event); - } - }); - if (fParentProvider instanceof IPostSelectionProvider) { - ((IPostSelectionProvider) fParentProvider).addPostSelectionChangedListener(new ISelectionChangedListener() { - public void selectionChanged(SelectionChangedEvent event) { - handlePostSelectionChanged(event); - } - }); - } - } - - public void addPostSelectionChangedListener(ISelectionChangedListener listener) { - postListeners.add(listener); - } - - public void addSelectionChangedListener(ISelectionChangedListener listener) { - listeners.add(listener); - } - - public void dispose() { - fEditor = null; - listeners.clear(); - postListeners.clear(); - selectionConvertor = null; - } - - private void fireSelectionChanged(final SelectionChangedEvent event, ListenerList listenerList) { - Object[] listeners = listenerList.getListeners(); - isFiringSelection = true; - for (int i = 0; i < listeners.length; ++i) { - final ISelectionChangedListener l = (ISelectionChangedListener) listeners[i]; - SafeRunner.run(new SafeRunnable() { - public void run() { - l.selectionChanged(event); - } - }); - } - isFiringSelection = false; - } - - private ISelectionProvider getParentProvider() { - return fParentProvider; - } - - public ISelection getSelection() { - fLastSelection = null; - fLastSelectionProvider = null; - fLastUpdatedSelectionChangedEvent = null; - - /* - * When a client explicitly asks for selection, provide the hybrid - * result. - */ - ISelection selection = getParentProvider().getSelection(); - if (!(selection instanceof IStructuredSelection) && selection instanceof ITextSelection) { - IStructuredModel structuredModel = null; - StructuredTextEditor localEditor = getStructuredTextEditor(); - if (localEditor != null) { - structuredModel = localEditor.getInternalModel(); - if (structuredModel != null) { - if (localEditor.isBlockSelectionModeEnabled()) { - /* - * Block selection handling - find the overlapping - * objects on each line, keeping in mind that the - * selected block may not overlap actual lines or - * columns of the document. - * IBlockTextSelection.getRegions() should handle - * that for us... - */ - IBlockTextSelection blockSelection = (IBlockTextSelection) selection; - IRegion[] regions = blockSelection.getRegions(); - Set blockObjects = new LinkedHashSet(); - for (int i = 0; i < regions.length; i++) { - Object[] objects = selectionConvertor.getElements(structuredModel, regions[i].getOffset(), regions[i].getLength()); - for (int j = 0; j < objects.length; j++) { - blockObjects.add(objects[j]); - } - } - selection = new StructuredTextSelection(getDocument(), (ITextSelection) selection, blockObjects.toArray()); - } - else { - int start = ((ITextSelection) selection).getOffset(); - int end = start + ((ITextSelection) selection).getLength(); - selection = new StructuredTextSelection(getDocument(), (ITextSelection) selection, selectionConvertor.getElements(structuredModel, start, end)); - } - } - } - if (selection == null) { - selection = new StructuredTextSelection(getDocument(), (ITextSelection) selection, new Object[0]); - } - } - - return selection; - } - - private StructuredTextEditor getStructuredTextEditor() { - return fEditor; - } - - void handlePostSelectionChanged(SelectionChangedEvent event) { - SelectionChangedEvent updatedEvent = null; - if (fLastSelection == event.getSelection() && fLastSelectionProvider == event.getSelectionProvider()) { - updatedEvent = fLastUpdatedSelectionChangedEvent; - } - else { - updatedEvent = updateEvent(event); - } - // only update the range indicator on post selection - StructuredTextEditor localEditor = fEditor; - - if (localEditor != null) { - localEditor.updateRangeIndication(updatedEvent.getSelection()); - fireSelectionChanged(updatedEvent, postListeners); - } - } - - void handleSelectionChanged(SelectionChangedEvent event) { - SelectionChangedEvent updatedEvent = event; - if (fLastSelection != event.getSelection() || fLastSelectionProvider != event.getSelectionProvider()) { - fLastSelection = event.getSelection(); - fLastSelectionProvider = event.getSelectionProvider(); - fLastUpdatedSelectionChangedEvent = updatedEvent = updateEvent(event); - } - fireSelectionChanged(updatedEvent, listeners); - } - - IDocument getDocument() { - return fEditor.getDocumentProvider().getDocument(fEditor.getEditorInput()); - } - - - boolean isFiringSelection() { - return isFiringSelection; - } - - public boolean isValid(ISelection selection) { - // ISSUE: is not clear default behavior should be true? - // But not clear is this default would apply for our editor. - boolean result = true; - // if editor is "gone", can not be valid - StructuredTextEditor e = getStructuredTextEditor(); - if (e == null || e.fEditorDisposed) { - result = false; - } - // else defer to parent - else if (getParentProvider() instanceof ISelectionValidator) { - result = ((ISelectionValidator) getParentProvider()).isValid(selection); - } - return result; - } - - public void removePostSelectionChangedListener(ISelectionChangedListener listener) { - postListeners.remove(listener); - } - - public void removeSelectionChangedListener(ISelectionChangedListener listener) { - listeners.remove(listener); - } - - public void setSelection(ISelection selection) { - if (isFiringSelection()) { - return; - } - - fLastSelection = null; - fLastSelectionProvider = null; - fLastUpdatedSelectionChangedEvent = null; - - ISelection textSelection = updateSelection(selection); - getParentProvider().setSelection(textSelection); - StructuredTextEditor localEditor = getStructuredTextEditor(); - if (localEditor != null) { - localEditor.updateRangeIndication(textSelection); - } - } - - /** - * Create a corresponding event that contains a - * StructuredTextselection - * - * @param event - * @return - */ - private SelectionChangedEvent updateEvent(SelectionChangedEvent event) { - ISelection selection = event.getSelection(); - if (selection instanceof ITextSelection && !(selection instanceof IStructuredSelection)) { - IStructuredModel structuredModel = null; - StructuredTextEditor localEditor = getStructuredTextEditor(); - if (localEditor != null) { - structuredModel = localEditor.getInternalModel(); - if (structuredModel != null) { - int start = ((ITextSelection) selection).getOffset(); - int end = start + ((ITextSelection) selection).getLength(); - selection = new StructuredTextSelection(getDocument(), (ITextSelection) event.getSelection(), selectionConvertor.getElements(structuredModel, start, end)); - } - } - if (selection == null) - selection = new StructuredTextSelection(getDocument(), (ITextSelection) event.getSelection(), new Object[0]); - } - SelectionChangedEvent newEvent = new SelectionChangedEvent(event.getSelectionProvider(), selection); - return newEvent; - } - - /** - * Create a corresponding StructuredTextselection - * - * @param selection - * @return - */ - private ISelection updateSelection(ISelection selection) { - ISelection updated = selection; - if (selection instanceof IStructuredSelection && !(selection instanceof ITextSelection) && !selection.isEmpty()) { - Object[] selectedObjects = ((IStructuredSelection) selection).toArray(); - if (selectedObjects.length > 0) { - int start = -1; - int length = 0; - - // no ordering is guaranteed for multiple selection - Object o = selectedObjects[0]; - if (o instanceof IndexedRegion) { - start = ((IndexedRegion) o).getStartOffset(); - int end = ((IndexedRegion) o).getEndOffset(); - if (selectedObjects.length > 1) { - for (int i = 1; i < selectedObjects.length; i++) { - start = Math.min(start, ((IndexedRegion) selectedObjects[i]).getStartOffset()); - end = Math.max(end, ((IndexedRegion) selectedObjects[i]).getEndOffset()); - } - length = end - start; - } - } - else if (o instanceof ITextRegion) { - start = ((ITextRegion) o).getStart(); - int end = ((ITextRegion) o).getEnd(); - if (selectedObjects.length > 1) { - for (int i = 1; i < selectedObjects.length; i++) { - start = Math.min(start, ((ITextRegion) selectedObjects[i]).getStart()); - end = Math.max(end, ((ITextRegion) selectedObjects[i]).getEnd()); - } - length = end - start; - } - } - - if (start > -1) { - updated = new StructuredTextSelection(getDocument(), start, length, selectedObjects); - } - } - } - return updated; - } - } - - class TimeOutExpired extends TimerTask { - public void run() { - final byte[] result = new byte[1]; // Did the busy state end successfully? - getDisplay().syncExec(new Runnable() { - public void run() { - if (getDisplay() != null && !getDisplay().isDisposed()) - endBusyStateInternal(result); - } - }); - if (result[0] == 1) { - fBusyTimer.cancel(); - } - } - - } - - private class ConfigurationAndTarget { - private String fTargetId; - private StructuredTextViewerConfiguration fConfiguration; - - public ConfigurationAndTarget(String targetId, StructuredTextViewerConfiguration config) { - fTargetId = targetId; - fConfiguration = config; - } - - public String getTargetId() { - return fTargetId; - } - - public StructuredTextViewerConfiguration getConfiguration() { - return fConfiguration; - } - } - - private class CharacterPairListener implements VerifyKeyListener { - private CharacterPairing[] fInserters = new CharacterPairing[0]; - private ICompletionListener fCompletionListener; - private boolean fIsCompleting = false; - - public void installCompletionListener() { - ISourceViewer viewer = getSourceViewer(); - if (viewer instanceof StructuredTextViewer) { - fCompletionListener = new ICompletionListener() { - - public void assistSessionStarted(ContentAssistEvent event) { - fIsCompleting = true; - } - - public void assistSessionEnded(ContentAssistEvent event) { - fIsCompleting = false; - } - - public void selectionChanged(ICompletionProposal proposal, boolean smartToggle) { - } - - }; - ContentAssistantFacade facade = ((StructuredTextViewer) viewer).getContentAssistFacade(); - if (facade != null) - facade.addCompletionListener(fCompletionListener); - } - } - - /** - * Add the pairing to the list of inserters - * @param pairing - */ - void addInserter(CharacterPairing pairing) { - List pairings = new ArrayList(Arrays.asList(fInserters)); - pairings.add(pairing); - fInserters = (CharacterPairing[]) pairings.toArray(new CharacterPairing[pairings.size()]); - } - - void prioritize() { - Arrays.sort(fInserters); - } - - /** - * Perform cleanup on the character pair inserters - */ - void dispose() { - ISourceViewer viewer = getSourceViewer(); - if (viewer instanceof StructuredTextViewer) { - ContentAssistantFacade facade = ((StructuredTextViewer) viewer).getContentAssistFacade(); - if (facade != null) - facade.removeCompletionListener(fCompletionListener); - } - - for (int i = 0; i < fInserters.length; i++) { - final AbstractCharacterPairInserter inserter = fInserters[i].inserter; - SafeRunner.run(new ISafeRunnable() { - public void handleException(Throwable exception) { - // rely on default logging - } - - public void run() throws Exception { - inserter.dispose(); - } - }); - } - } - - public void verifyKey(final VerifyEvent event) { - if (!event.doit || getInsertMode() != SMART_INSERT || fIsCompleting || isBlockSelectionModeEnabled() && isMultilineSelection()) - return; - final boolean[] paired = { false }; - for (int i = 0; i < fInserters.length; i++) { - final CharacterPairing pairing = fInserters[i]; - // use a SafeRunner -- this is a critical function (typing) - SafeRunner.run(new ISafeRunnable() { - public void run() throws Exception { - final AbstractCharacterPairInserter inserter = pairing.inserter; - if (inserter.hasPair(event.character)) { - if (pair(event, inserter, pairing.partitions)) - paired[0] = true; - } - } - - public void handleException(Throwable exception) { - // rely on default logging - } - }); - if (paired[0]) - return; - } - } - - private boolean pair(VerifyEvent event, AbstractCharacterPairInserter inserter, Set partitions) { - final ISourceViewer viewer = getSourceViewer(); - final IDocument document = getSourceViewer().getDocument(); - if (document != null) { - try { - final Point selection = viewer.getSelectedRange(); - final int offset = selection.x; - final ITypedRegion partition = document.getPartition(offset); - if (partitions.contains(partition.getType())) { - // Don't modify if the editor input cannot be changed - if (!validateEditorInputState()) - return false; - event.doit = !inserter.pair(viewer, event.character); - return true; - } - } catch (BadLocationException e) { - } - } - return false; - } - - private boolean isMultilineSelection() { - ISelection selection = getSelectionProvider().getSelection(); - if (selection instanceof ITextSelection) { - ITextSelection ts = (ITextSelection) selection; - return ts.getStartLine() != ts.getEndLine(); - } - return false; - } - } - - /** - * Representation of a character pairing that includes its priority based on - * its content type and how close it is to the content type of the file - * in the editor. - */ - private class CharacterPairing implements Comparable { - int priority; - AbstractCharacterPairInserter inserter; - Set partitions; - public int compareTo(Object o) { - if (o == this) - return 0; - return this.priority - ((CharacterPairing) o).priority; - } - } - - private class PartListener implements IPartListener { - - private ITextEditor fEditor; - - public PartListener(ITextEditor editor) { - fEditor = editor; - } - - public void partActivated(IWorkbenchPart part) { - if (part.getAdapter(ITextEditor.class) == fEditor) { - IReconciler reconciler = getSourceViewerConfiguration().getReconciler(getSourceViewer()); - if (reconciler instanceof DocumentRegionProcessor) { - ((DocumentRegionProcessor) reconciler).forceReconciling(); - } - } - } - - public void partBroughtToTop(IWorkbenchPart part) { - } - - public void partClosed(IWorkbenchPart part) { - } - - public void partDeactivated(IWorkbenchPart part) { - } - - public void partOpened(IWorkbenchPart part) { - } - - } - - /** - * Not API. May be removed in the future. - */ - protected final static char[] BRACKETS = {'{', '}', '(', ')', '[', ']'}; - - private static final long BUSY_STATE_DELAY = 1000; - /** - * Not API. May be removed in the future. - */ - protected static final String DOT = "."; //$NON-NLS-1$ - private static final String EDITOR_CONTEXT_MENU_ID = "org.eclipse.wst.sse.ui.StructuredTextEditor.EditorContext"; //$NON-NLS-1$ - private static final String EDITOR_CONTEXT_MENU_SUFFIX = ".source.EditorContext"; //$NON-NLS-1$ - - /** Non-NLS strings */ - private static final String EDITOR_KEYBINDING_SCOPE_ID = "org.eclipse.wst.sse.ui.structuredTextEditorScope"; //$NON-NLS-1$ - /** - * Not API. May be removed in the future. - */ - public static final String GROUP_NAME_ADDITIONS = IWorkbenchActionConstants.MB_ADDITIONS; //$NON-NLS-1$ - - private static final String REDO_ACTION_DESC = SSEUIMessages.Redo___0___UI_; //$NON-NLS-1$ = "Redo: {0}." - private static final String REDO_ACTION_DESC_DEFAULT = SSEUIMessages.Redo_Text_Change__UI_; //$NON-NLS-1$ = "Redo Text Change." - private static final String REDO_ACTION_TEXT = SSEUIMessages._Redo__0___Ctrl_Y_UI_; //$NON-NLS-1$ = "&Redo {0} @Ctrl+Y" - private static final String REDO_ACTION_TEXT_DEFAULT = SSEUIMessages._Redo_Text_Change__Ctrl_Y_UI_; //$NON-NLS-1$ = "&Redo Text Change @Ctrl+Y" - private static final String RULER_CONTEXT_MENU_ID = "org.eclipse.wst.sse.ui.StructuredTextEditor.RulerContext"; //$NON-NLS-1$ - private static final String RULER_CONTEXT_MENU_SUFFIX = ".source.RulerContext"; //$NON-NLS-1$ - - private final static String UNDERSCORE = "_"; //$NON-NLS-1$ - /** Translatable strings */ - private static final String UNDO_ACTION_DESC = SSEUIMessages.Undo___0___UI_; //$NON-NLS-1$ = "Undo: {0}." - - private static final String UNDO_ACTION_DESC_DEFAULT = SSEUIMessages.Undo_Text_Change__UI_; //$NON-NLS-1$ = "Undo Text Change." - private static final String UNDO_ACTION_TEXT = SSEUIMessages._Undo__0___Ctrl_Z_UI_; //$NON-NLS-1$ = "&Undo {0} @Ctrl+Z" - private static final String UNDO_ACTION_TEXT_DEFAULT = SSEUIMessages._Undo_Text_Change__Ctrl_Z_UI_; //$NON-NLS-1$ = "&Undo Text Change @Ctrl+Z" - // development time/debug variables only - private int adapterRequests; - - private long adapterTime; - private boolean fBackgroundJobEnded; - private boolean fBusyState; - private Timer fBusyTimer; - boolean fDirtyBeforeDocumentEvent = false; - int validateEditCount = 0; - private ExtendedEditorDropTargetAdapter fDropAdapter; - private DropTarget fDropTarget; - boolean fEditorDisposed = false; - private IEditorPart fEditorPart; - private InternalModelStateListener fInternalModelStateListener; - private IContentOutlinePage fOutlinePage; - - private OutlinePageListener fOutlinePageListener = null; - /** This editor's projection support */ - private ProjectionSupport fProjectionSupport; - private IPropertySheetPage fPropertySheetPage; - - private ISourceReconcilingListener[] fReconcilingListeners = new ISourceReconcilingListener[0]; - private IPartListener fPartListener; - - /** The ruler context menu to be disposed. */ - private Menu fRulerContextMenu; - /** The ruler context menu manager to be disposed. */ - private MenuManager fRulerContextMenuManager; - - String[] fShowInTargetIds = new String[]{IPageLayout.ID_RES_NAV, IPageLayout.ID_PROJECT_EXPLORER, IPageLayout.ID_OUTLINE}; - - private IAction fShowPropertiesAction = null; - private IStructuredModel fStructuredModel; - StructuredSelectionProvider fStructuredSelectionProvider = null; - /** The text context menu to be disposed. */ - private Menu fTextContextMenu; - /** The text context menu manager to be disposed. */ - private MenuManager fTextContextMenuManager; - private String fViewerConfigurationTargetId; - /** The selection history of the editor */ - private SelectionHistory fSelectionHistory; - /** The information presenter. */ - private InformationPresenter fInformationPresenter; - private boolean fUpdateMenuTextPending; - /** The quick outline handler */ - private QuickOutlineHandler fOutlineHandler; - - private boolean shouldClose = false; - private long startPerfTime; - private boolean fisReleased; - /** - * The action group for folding. - */ - private FoldingActionGroup fFoldingGroup; - - private ILabelProvider fStatusLineLabelProvider; - - private SemanticHighlightingManager fSemanticManager; - - private boolean fSelectionChangedFromGoto = false; - - private final CharacterPairListener fPairInserter = new CharacterPairListener(); - - /** - * Creates a new Structured Text Editor. - */ - public StructuredTextEditor() { - super(); - initializeDocumentProvider(null); - } - - private IStructuredModel aboutToSaveModel() { - IStructuredModel model = getInternalModel(); - if (model != null) { - model.aboutToChangeModel(); - } - return model; - } - - protected void addSourceMenuActions(IMenuManager menu) { - IMenuManager subMenu= new MenuManager(SSEUIMessages.SourceMenu_label, IStructuredTextEditorActionConstants.SOURCE_CONTEXT_MENU_ID); - subMenu.add(new Separator(IStructuredTextEditorActionConstants.SOURCE_BEGIN)); - subMenu.add(new Separator(IStructuredTextEditorActionConstants.SOURCE_ADDITIONS)); - subMenu.add(new Separator(IStructuredTextEditorActionConstants.SOURCE_END)); - menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, subMenu); - } - - protected void addRefactorMenuActions(IMenuManager menu) { - IMenuManager subMenu = new MenuManager(SSEUIMessages.RefactorMenu_label, IStructuredTextEditorActionConstants.REFACTOR_CONTEXT_MENU_ID); - menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, subMenu); - } - - protected void addContextMenuActions(IMenuManager menu) { - // Only offer actions that affect the text if the viewer allows - // modification and supports any of these operations - - // Some Design editors (DTD) rely on this view for their own uses - menu.appendToGroup(IWorkbenchActionConstants.GROUP_ADD, fShowPropertiesAction); - } - - private void addExtendedContextMenuActions(IMenuManager menu) { - IEditorActionBarContributor c = getEditorSite().getActionBarContributor(); - if (c instanceof IPopupMenuContributor) { - ((IPopupMenuContributor) c).contributeToPopupMenu(menu); - } - else { - ExtendedEditorActionBuilder builder = new ExtendedEditorActionBuilder(); - IExtendedContributor pmc = builder.readActionExtensions(getConfigurationPoints()); - if (pmc != null) { - pmc.setActiveEditor(this); - pmc.contributeToPopupMenu(menu); - } - } - } - - protected void addExtendedRulerContextMenuActions(IMenuManager menu) { - // none at this level - } - - - - /** - * Starts background mode. - * <p> - * Not API. May be removed in the future. - * </p> - */ - void beginBackgroundOperation() { - fBackgroundJobEnded = false; - // if already in busy state, no need to do anything - // and, we only start, or reset, the timed busy - // state when we get the "endBackgroundOperation" call. - if (!inBusyState()) { - beginBusyStateInternal(); - } - } - - private void beginBusyStateInternal() { - - fBusyState = true; - startBusyTimer(); - - ISourceViewer viewer = getSourceViewer(); - if (viewer instanceof StructuredTextViewer) { - ((StructuredTextViewer) viewer).beginBackgroundUpdate(); - - } - showBusy(true); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.ITextEditor#close(boolean) - */ - public void close(final boolean save) { - /* - * Instead of us closing directly, we have to close with our - * containing (multipage) editor, if it exists. - */ - if (getSite() == null) { - // if site hasn't been set yet, then we're not - // completely open - // so set a flag not to open - shouldClose = true; - } - else { - if (getEditorPart() != null) { - Display display = getSite().getShell().getDisplay(); - display.asyncExec(new Runnable() { - - public void run() { - getSite().getPage().closeEditor(getEditorPart(), save); - } - }); - } - else { - super.close(save); - } - } - } - - private void activateContexts(IContextService service) { - if(service == null) - return; - - String[] definitions = getDefinitions(getConfigurationPoints()); - - if(definitions != null) { - String[] contexts = null; - for(int i = 0; i < definitions.length; i++) { - contexts = StringUtils.unpack(definitions[i]); - for(int j = 0; j < contexts.length; j++) - service.activateContext(contexts[j].trim()); - } - } - - } - - private String[] getDefinitions(String[] ids) { - ExtendedConfigurationBuilder builder = ExtendedConfigurationBuilder.getInstance(); - String[] definitions = null; - - /* Iterate through the configuration ids until one is found that has - * an activecontexts definition - */ - for(int i = 0; i < ids.length; i++) { - definitions = builder.getDefinitions("activecontexts", ids[i]); //$NON-NLS-1$ - if(definitions != null && definitions.length > 0) - return definitions; - } - return null; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#collectContextMenuPreferencePages() - */ - protected String[] collectContextMenuPreferencePages() { - List allIds = new ArrayList(0); - - // get contributed preference pages - ExtendedConfigurationBuilder builder = ExtendedConfigurationBuilder.getInstance(); - String[] configurationIds = getConfigurationPoints(); - for (int i = 0; i < configurationIds.length; i++) { - String[] definitions = builder.getDefinitions("preferencepages", configurationIds[i]); //$NON-NLS-1$ - for (int j = 0; j < definitions.length; j++) { - String someIds = definitions[j]; - if (someIds != null && someIds.length() > 0) { - // supports multiple comma-delimited page IDs in one - // element - String[] ids = StringUtils.unpack(someIds); - for (int k = 0; k < ids.length; k++) { - // trim, just to keep things clean - String id = ids[k].trim(); - if (!allIds.contains(id)) { - allIds.add(id); - } - } - } - } - } - - // add pages contributed by super - String[] superPages = super.collectContextMenuPreferencePages(); - for (int m = 0; m < superPages.length; m++) { - // trim, just to keep things clean - String id = superPages[m].trim(); - if (!allIds.contains(id)) { - allIds.add(id); - } - } - - return (String[]) allIds.toArray(new String[0]); - } - - /** - * Compute and set double-click action for the vertical ruler - */ - private void computeAndSetDoubleClickAction() { - /* - * Make double-clicking on the ruler toggle a breakpoint instead of - * toggling a bookmark. For lines where a breakpoint won't be created, - * create a bookmark through the contributed RulerDoubleClick action. - */ - setAction(ITextEditorActionConstants.RULER_DOUBLE_CLICK, new ToggleBreakpointAction(this, getVerticalRuler(), getAction(ITextEditorActionConstants.RULER_DOUBLE_CLICK))); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.ExtendedTextEditor#configureSourceViewerDecorationSupport(org.eclipse.ui.texteditor.SourceViewerDecorationSupport) - */ - protected void configureSourceViewerDecorationSupport(SourceViewerDecorationSupport support) { - support.setCharacterPairMatcher(createCharacterPairMatcher()); - support.setMatchingCharacterPainterPreferenceKeys(EditorPreferenceNames.MATCHING_BRACKETS, EditorPreferenceNames.MATCHING_BRACKETS_COLOR); - - super.configureSourceViewerDecorationSupport(support); - } - - protected void createActions() { - super.createActions(); - ResourceBundle resourceBundle = SSEUIMessages.getResourceBundle(); - IWorkbenchHelpSystem helpSystem = SSEUIPlugin.getDefault().getWorkbench().getHelpSystem(); - // TextView Action - moving the selected text to - // the clipboard - // override the cut/paste/delete action to make - // them run on read-only - // files - Action action = new TextOperationAction(resourceBundle, "Editor_Cut_", this, ITextOperationTarget.CUT); //$NON-NLS-1$ - action.setActionDefinitionId(IWorkbenchActionDefinitionIds.CUT); - setAction(ITextEditorActionConstants.CUT, action); - helpSystem.setHelp(action, IAbstractTextEditorHelpContextIds.CUT_ACTION); - // TextView Action - inserting the clipboard - // content at the current - // position - // override the cut/paste/delete action to make - // them run on read-only - // files - action = new TextOperationAction(resourceBundle, "Editor_Paste_", this, ITextOperationTarget.PASTE); //$NON-NLS-1$ - action.setActionDefinitionId(IWorkbenchActionDefinitionIds.PASTE); - setAction(ITextEditorActionConstants.PASTE, action); - helpSystem.setHelp(action, IAbstractTextEditorHelpContextIds.PASTE_ACTION); - // TextView Action - deleting the selected text or - // if selection is - // empty the character at the right of the current - // position - // override the cut/paste/delete action to make - // them run on read-only - // files - action = new TextOperationAction(resourceBundle, "Editor_Delete_", this, ITextOperationTarget.DELETE); //$NON-NLS-1$ - action.setActionDefinitionId(IWorkbenchActionDefinitionIds.DELETE); - setAction(ITextEditorActionConstants.DELETE, action); - helpSystem.setHelp(action, IAbstractTextEditorHelpContextIds.DELETE_ACTION); - // SourceView Action - requesting content assist to - // show completetion - // proposals for the current insert position - action = new TextOperationAction(resourceBundle, StructuredTextEditorActionConstants.ACTION_NAME_CONTENTASSIST_PROPOSALS + UNDERSCORE, this, ISourceViewer.CONTENTASSIST_PROPOSALS); - helpSystem.setHelp(action, IHelpContextIds.CONTMNU_CONTENTASSIST_HELPID); - action.setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS); - setAction(StructuredTextEditorActionConstants.ACTION_NAME_CONTENTASSIST_PROPOSALS, action); - markAsStateDependentAction(StructuredTextEditorActionConstants.ACTION_NAME_CONTENTASSIST_PROPOSALS, true); - // SourceView Action - requesting content assist to - // show the content - // information for the current insert position - action = new TextOperationAction(SSEUIMessages.getResourceBundle(), StructuredTextEditorActionConstants.ACTION_NAME_CONTENTASSIST_CONTEXT_INFORMATION + UNDERSCORE, this, ISourceViewer.CONTENTASSIST_CONTEXT_INFORMATION); - action.setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_CONTEXT_INFORMATION); - setAction(StructuredTextEditorActionConstants.ACTION_NAME_CONTENTASSIST_CONTEXT_INFORMATION, action); - markAsStateDependentAction(StructuredTextEditorActionConstants.ACTION_NAME_CONTENTASSIST_CONTEXT_INFORMATION, true); - // StructuredTextViewer Action - requesting format - // of the whole - // document - action = new TextOperationAction(resourceBundle, StructuredTextEditorActionConstants.ACTION_NAME_FORMAT_DOCUMENT + UNDERSCORE, this, StructuredTextViewer.FORMAT_DOCUMENT); - helpSystem.setHelp(action, IHelpContextIds.CONTMNU_FORMAT_DOC_HELPID); - action.setActionDefinitionId(ActionDefinitionIds.FORMAT_DOCUMENT); - setAction(StructuredTextEditorActionConstants.ACTION_NAME_FORMAT_DOCUMENT, action); - markAsStateDependentAction(StructuredTextEditorActionConstants.ACTION_NAME_FORMAT_DOCUMENT, true); - markAsSelectionDependentAction(StructuredTextEditorActionConstants.ACTION_NAME_FORMAT_DOCUMENT, true); - // StructuredTextViewer Action - requesting format - // of the active - // elements - action = new TextOperationAction(resourceBundle, StructuredTextEditorActionConstants.ACTION_NAME_FORMAT_ACTIVE_ELEMENTS + UNDERSCORE, this, StructuredTextViewer.FORMAT_ACTIVE_ELEMENTS); - helpSystem.setHelp(action, IHelpContextIds.CONTMNU_FORMAT_ELEMENTS_HELPID); - action.setActionDefinitionId(ActionDefinitionIds.FORMAT_ACTIVE_ELEMENTS); - setAction(StructuredTextEditorActionConstants.ACTION_NAME_FORMAT_ACTIVE_ELEMENTS, action); - markAsStateDependentAction(StructuredTextEditorActionConstants.ACTION_NAME_FORMAT_ACTIVE_ELEMENTS, true); - markAsSelectionDependentAction(StructuredTextEditorActionConstants.ACTION_NAME_FORMAT_ACTIVE_ELEMENTS, true); - - // StructuredTextEditor Action - add breakpoints (falling back to the - // current double-click if they can't be added) - action = new ToggleBreakpointAction(this, getVerticalRuler()); - setAction(ActionDefinitionIds.TOGGLE_BREAKPOINTS, action); - // StructuredTextEditor Action - manage breakpoints - action = new ManageBreakpointAction(this, getVerticalRuler()); - setAction(ActionDefinitionIds.MANAGE_BREAKPOINTS, action); - // StructuredTextEditor Action - edit breakpoints - action = new EditBreakpointAction(this, getVerticalRuler()); - setAction(ActionDefinitionIds.EDIT_BREAKPOINTS, action); - // StructuredTextViewer Action - open file on selection - action = new OpenHyperlinkAction(resourceBundle, StructuredTextEditorActionConstants.ACTION_NAME_OPEN_FILE + UNDERSCORE, this, getSourceViewer()); - action.setActionDefinitionId(ActionDefinitionIds.OPEN_FILE); - setAction(StructuredTextEditorActionConstants.ACTION_NAME_OPEN_FILE, action); - - computeAndSetDoubleClickAction(); - - //add handlers to handler service - IHandlerService handlerService = (IHandlerService) getSite().getService(IHandlerService.class); - if (handlerService != null) { - - IHandler gotoHandler = new GotoMatchingBracketHandler(); - handlerService.activateHandler(ActionDefinitionIds.GOTO_MATCHING_BRACKET, gotoHandler); - - fOutlineHandler = new QuickOutlineHandler(); - handlerService.activateHandler(ActionDefinitionIds.SHOW_OUTLINE, fOutlineHandler); - - IHandler toggleCommentHandler = new ToggleLineCommentHandler(); - handlerService.activateHandler(ActionDefinitionIds.TOGGLE_COMMENT, toggleCommentHandler); - - IHandler addCommentBlockHandler = new AddBlockCommentHandler(); - handlerService.activateHandler(ActionDefinitionIds.ADD_BLOCK_COMMENT, addCommentBlockHandler); - - IHandler removeCommentBlockHandler = new RemoveBlockCommentHandler(); - handlerService.activateHandler(ActionDefinitionIds.REMOVE_BLOCK_COMMENT, removeCommentBlockHandler); - } - - fShowPropertiesAction = new ShowPropertiesAction(getEditorPart(), getSelectionProvider()); - fFoldingGroup = new FoldingActionGroup(this, getSourceViewer()); - } - - protected LineChangeHover createChangeHover() { - return super.createChangeHover(); //new StructuredLineChangeHover(); - } - - protected ICharacterPairMatcher createCharacterPairMatcher() { - ICharacterPairMatcher matcher = null; - ExtendedConfigurationBuilder builder = ExtendedConfigurationBuilder.getInstance(); - String[] ids = getConfigurationPoints(); - for (int i = 0; matcher == null && i < ids.length; i++) { - matcher = (ICharacterPairMatcher) builder.getConfiguration(DocumentRegionEdgeMatcher.ID, ids[i]); - } - if (matcher == null) { - matcher = new DefaultCharacterPairMatcher(new char[]{'(', ')', '{', '}', '[', ']', '<', '>', '"', '"', '\'', '\''}); - } - return matcher; - } - - /** - * Create a preference store that combines the source editor preferences - * with the base editor's preferences. - * - * @return IPreferenceStore - */ - private IPreferenceStore createCombinedPreferenceStore() { - IPreferenceStore sseEditorPrefs = SSEUIPlugin.getDefault().getPreferenceStore(); - IPreferenceStore baseEditorPrefs = EditorsUI.getPreferenceStore(); - return new ChainedPreferenceStore(new IPreferenceStore[]{sseEditorPrefs, baseEditorPrefs}); - } - - private ContentOutlineConfiguration createContentOutlineConfiguration() { - ContentOutlineConfiguration cfg = null; - ExtendedConfigurationBuilder builder = ExtendedConfigurationBuilder.getInstance(); - String[] ids = getConfigurationPoints(); - for (int i = 0; cfg == null && i < ids.length; i++) { - cfg = (ContentOutlineConfiguration) builder.getConfiguration(ExtendedConfigurationBuilder.CONTENTOUTLINECONFIGURATION, ids[i]); - } - return cfg; - } - - protected void createModelDependentFields() { - if (fStructuredSelectionProvider != null) { - SelectionConvertor convertor = (SelectionConvertor) fStructuredModel.getAdapter(SelectionConvertor.class); - if (convertor != null) - fStructuredSelectionProvider.selectionConvertor = convertor; - else - fStructuredSelectionProvider.selectionConvertor = new SelectionConvertor(); - } - } - - /** - * {@inheritDoc} - * <p> - * Use StructuredTextViewerConfiguration if a viewerconfiguration has not - * already been set. Also initialize StructuredTextViewer. - * </p> - * - * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#createPartControl(org.eclipse.swt.widgets.Composite) - */ - public void createPartControl(Composite parent) { - IContextService contextService = (IContextService) getSite().getService(IContextService.class); - if (contextService != null) - contextService.activateContext(EDITOR_KEYBINDING_SCOPE_ID); - - if (getSourceViewerConfiguration() == null) { - ConfigurationAndTarget cat = createSourceViewerConfiguration(); - fViewerConfigurationTargetId = cat.getTargetId(); - StructuredTextViewerConfiguration newViewerConfiguration = cat.getConfiguration(); - setSourceViewerConfiguration(newViewerConfiguration); - } - - super.createPartControl(parent); - - // instead of calling setInput twice, use initializeSourceViewer() to - // handle source viewer initialization previously handled by setInput - initializeSourceViewer(); - - // update editor context menu, vertical ruler context menu, infopop - if (getInternalModel() != null) { - updateEditorControlsForContentType(getInternalModel().getContentTypeIdentifier()); - } - else { - updateEditorControlsForContentType(null); - } - - // used for Show Tooltip Description - IInformationControlCreator informationControlCreator = new IInformationControlCreator() { - public IInformationControl createInformationControl(Shell shell) { - boolean cutDown = false; - int style = cutDown ? SWT.NONE : (SWT.V_SCROLL | SWT.H_SCROLL); - return new DefaultInformationControl(shell, SWT.RESIZE | SWT.TOOL, style, new HTMLTextPresenter(cutDown)); - } - }; - - fInformationPresenter = new InformationPresenter(informationControlCreator); - fInformationPresenter.setSizeConstraints(60, 10, true, true); - fInformationPresenter.install(getSourceViewer()); - addReconcilingListeners(getSourceViewerConfiguration(), getTextViewer()); - fPartListener = new PartListener(this); - getSite().getWorkbenchWindow().getPartService().addPartListener(fPartListener); - installSemanticHighlighting(); - if (fOutlineHandler != null) { - IInformationPresenter presenter = configureOutlinePresenter(getSourceViewer(), getSourceViewerConfiguration()); - if (presenter != null) { - presenter.install(getSourceViewer()); - fOutlineHandler.configure(presenter); - } - } - installCharacterPairing(); - ISourceViewer viewer = getSourceViewer(); - if (viewer instanceof ITextViewerExtension) { - ((ITextViewerExtension) viewer).appendVerifyKeyListener(fPairInserter); - fPairInserter.installCompletionListener(); - } - - if (Platform.getProduct() != null) { - String viewID = Platform.getProduct().getProperty("idPerspectiveHierarchyView"); //$NON-NLS-1$); - if (viewID != null) { - // make sure the specified view ID is known - if (PlatformUI.getWorkbench().getViewRegistry().find(viewID) != null) { - fShowInTargetIds = new String[]{viewID, IPageLayout.ID_PROJECT_EXPLORER, IPageLayout.ID_RES_NAV, IPageLayout.ID_OUTLINE}; - } - } - } - } - - protected PropertySheetConfiguration createPropertySheetConfiguration() { - PropertySheetConfiguration cfg = null; - ExtendedConfigurationBuilder builder = ExtendedConfigurationBuilder.getInstance(); - String[] ids = getConfigurationPoints(); - for (int i = 0; cfg == null && i < ids.length; i++) { - cfg = (PropertySheetConfiguration) builder.getConfiguration(ExtendedConfigurationBuilder.PROPERTYSHEETCONFIGURATION, ids[i]); - } - return cfg; - } - - /** - * Loads the Show In Target IDs from the Extended Configuration extension - * point. - * - * @return - */ - private String[] createShowInTargetIds() { - List allIds = new ArrayList(0); - ExtendedConfigurationBuilder builder = ExtendedConfigurationBuilder.getInstance(); - String[] configurationIds = getConfigurationPoints(); - for (int i = 0; i < configurationIds.length; i++) { - String[] definitions = builder.getDefinitions("showintarget", configurationIds[i]); //$NON-NLS-1$ - for (int j = 0; j < definitions.length; j++) { - String someIds = definitions[j]; - if (someIds != null && someIds.length() > 0) { - String[] ids = StringUtils.unpack(someIds); - for (int k = 0; k < ids.length; k++) { - // trim, just to keep things clean - String id = ids[k].trim(); - if (!allIds.contains(id)) { - allIds.add(id); - } - } - } - } - } - - if (!allIds.contains(IPageLayout.ID_RES_NAV)) { - allIds.add(IPageLayout.ID_RES_NAV); - } - if (!allIds.contains(IPageLayout.ID_PROJECT_EXPLORER)) { - allIds.add(IPageLayout.ID_PROJECT_EXPLORER); - } - if (!allIds.contains(IPageLayout.ID_OUTLINE)) { - allIds.add(IPageLayout.ID_OUTLINE); - } - return (String[]) allIds.toArray(new String[0]); - } - - /** - * @return - */ - private ISourceEditingTextTools createSourceEditingTextTools() { - ISourceEditingTextTools tools = null; - ExtendedConfigurationBuilder builder = ExtendedConfigurationBuilder.getInstance(); - String[] ids = getConfigurationPoints(); - for (int i = 0; tools == null && i < ids.length; i++) { - tools = (ISourceEditingTextTools) builder.getConfiguration(NullSourceEditingTextTools.ID, ids[i]); - } - if (tools == null) { - tools = NullSourceEditingTextTools.getInstance(); - ((NullSourceEditingTextTools) tools).setTextEditor(this); - } - Method method = null; //$NON-NLS-1$ - try { - method = tools.getClass().getMethod("setTextEditor", new Class[]{StructuredTextEditor.class}); //$NON-NLS-1$ - } - catch (NoSuchMethodException e) { - } - if (method == null) { - try { - method = tools.getClass().getMethod("setTextEditor", new Class[]{ITextEditor.class}); //$NON-NLS-1$ - } - catch (NoSuchMethodException e) { - } - } - if (method == null) { - try { - method = tools.getClass().getMethod("setTextEditor", new Class[]{IEditorPart.class}); //$NON-NLS-1$ - } - catch (NoSuchMethodException e) { - } - } - if (method != null) { - if (!method.isAccessible()) { - method.setAccessible(true); - } - try { - method.invoke(tools, new Object[]{this}); - } - catch (Exception e) { - Logger.logException("Problem creating ISourceEditingTextTools implementation", e); //$NON-NLS-1$ - } - } - - return tools; - } - - /** - * Creates the source viewer to be used by this editor - */ - protected ISourceViewer createSourceViewer(Composite parent, IVerticalRuler verticalRuler, int styles) { - fAnnotationAccess = createAnnotationAccess(); - fOverviewRuler = createOverviewRuler(getSharedColors()); - StructuredTextViewer sourceViewer = createStructedTextViewer(parent, verticalRuler, styles); - initSourceViewer(sourceViewer); - return sourceViewer; - } - - private ConfigurationAndTarget createSourceViewerConfiguration() { - ConfigurationAndTarget cat = null; - StructuredTextViewerConfiguration cfg = null; - ExtendedConfigurationBuilder builder = ExtendedConfigurationBuilder.getInstance(); - String[] ids = getConfigurationPoints(); - for (int i = 0; cfg == null && i < ids.length; i++) { - cfg = (StructuredTextViewerConfiguration) builder.getConfiguration(ExtendedConfigurationBuilder.SOURCEVIEWERCONFIGURATION, ids[i]); - cat = new ConfigurationAndTarget(ids[i], cfg); - } - if (cfg == null) { - cfg = new StructuredTextViewerConfiguration(); - String targetid = getClass().getName() + "#default"; //$NON-NLS-1$ - cat = new ConfigurationAndTarget(targetid, cfg); - } - return cat; - } - - protected StructuredTextViewer createStructedTextViewer(Composite parent, IVerticalRuler verticalRuler, int styles) { - return new StructuredTextViewer(parent, verticalRuler, getOverviewRuler(), isOverviewRulerVisible(), styles); - } - - protected void createUndoRedoActions() { - // overridden to add icons to actions - // https://bugs.eclipse.org/bugs/show_bug.cgi?id=111877 - super.createUndoRedoActions(); - IAction action = getAction(ITextEditorActionConstants.UNDO); - if (action != null) { - action.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_TOOL_UNDO)); - } - - action = getAction(ITextEditorActionConstants.REDO); - if (action != null) { - action.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_TOOL_REDO)); - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.IWorkbenchPart#dispose() - */ - public void dispose() { - Logger.trace("Source Editor", "StructuredTextEditor::dispose entry"); //$NON-NLS-1$ //$NON-NLS-2$ - if (org.eclipse.wst.sse.core.internal.util.Debug.perfTestAdapterClassLoading) { - System.out.println("Total calls to getAdapter: " + adapterRequests); //$NON-NLS-1$ - System.out.println("Total time in getAdapter: " + adapterTime); //$NON-NLS-1$ - System.out.println("Average time per call: " + (adapterTime / adapterRequests)); //$NON-NLS-1$ - } - - ISourceViewer viewer = getSourceViewer(); - if (viewer instanceof ITextViewerExtension) - ((ITextViewerExtension) viewer).removeVerifyKeyListener(fPairInserter); - - // dispose of information presenter - if (fInformationPresenter != null) { - fInformationPresenter.dispose(); - fInformationPresenter = null; - } - - if (fOutlineHandler != null) { - fOutlineHandler.dispose(); - } - // dispose of selection history - if (fSelectionHistory != null) { - fSelectionHistory.dispose(); - fSelectionHistory = null; - } - - if (fProjectionSupport != null) { - fProjectionSupport.dispose(); - fProjectionSupport = null; - } - - if (fFoldingGroup != null) { - fFoldingGroup.dispose(); - fFoldingGroup = null; - } - - // dispose of menus that were being tracked - if (fTextContextMenu != null) { - fTextContextMenu.dispose(); - } - if (fRulerContextMenu != null) { - fRulerContextMenu.dispose(); - } - if (fTextContextMenuManager != null) { - fTextContextMenuManager.removeMenuListener(getContextMenuListener()); - fTextContextMenuManager.removeAll(); - fTextContextMenuManager.dispose(); - } - if (fRulerContextMenuManager != null) { - fRulerContextMenuManager.removeMenuListener(getContextMenuListener()); - fRulerContextMenuManager.removeAll(); - fRulerContextMenuManager.dispose(); - } - - // added this 2/20/2004 based on probe results -- - // seems should be handled by setModel(null), but - // that's a more radical change. - // and, technically speaking, should not be needed, - // but makes a memory leak - // less severe. - if (fStructuredModel != null) { - fStructuredModel.removeModelStateListener(getInternalModelStateListener()); - } - - // BUG155335 - if there was no document provider, there was nothing - // added - // to document, so nothing to remove - if (getDocumentProvider() != null) { - IDocument doc = getDocumentProvider().getDocument(getEditorInput()); - if (doc != null) { - if (doc instanceof IExecutionDelegatable) { - ((IExecutionDelegatable) doc).setExecutionDelegate(null); - } - } - } - - // some things in the configuration need to clean - // up after themselves - if (fOutlinePage != null) { - if (fOutlinePage instanceof ConfigurableContentOutlinePage && fOutlinePageListener != null) { - ((ConfigurableContentOutlinePage) fOutlinePage).removeDoubleClickListener(fOutlinePageListener); - } - if (fOutlinePageListener != null) { - fOutlinePage.removeSelectionChangedListener(fOutlinePageListener); - } - } - - fEditorDisposed = true; - disposeModelDependentFields(); - - if (fDropTarget != null) - fDropTarget.dispose(); - - if (fPartListener != null) { - getSite().getWorkbenchWindow().getPartService().removePartListener(fPartListener); - fPartListener = null; - } - - uninstallSemanticHighlighting(); - - if (fPairInserter != null) - fPairInserter.dispose(); - - - setPreferenceStore(null); - - /* - * Strictly speaking, but following null outs should not be needed, - * but in the event of a memory leak, they make the memory leak less - * severe - */ - fDropAdapter = null; - fDropTarget = null; - - if (fStructuredSelectionProvider != null) { - fStructuredSelectionProvider.dispose(); - } - - setStatusLineMessage(null); - - super.dispose(); - - Logger.trace("Source Editor", "StructuredTextEditor::dispose exit"); //$NON-NLS-1$ //$NON-NLS-2$ - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#disposeDocumentProvider() - */ - protected void disposeDocumentProvider() { - if (fStructuredModel != null && !fisReleased && !(getDocumentProvider() instanceof IModelProvider)) { - fStructuredModel.releaseFromEdit(); - fisReleased = true; - } - super.disposeDocumentProvider(); - } - - /** - * Disposes model specific editor helpers such as statusLineHelper. - * Basically any code repeated in update() & dispose() should be placed - * here. - */ - private void disposeModelDependentFields() { - if(fStructuredSelectionProvider != null) - fStructuredSelectionProvider.selectionConvertor = new SelectionConvertor(); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.ITextEditor#doRevertToSaved() - */ - public void doRevertToSaved() { - super.doRevertToSaved(); - if (fOutlinePage != null && fOutlinePage instanceof IUpdate) { - ((IUpdate) fOutlinePage).update(); - } - // reset undo - IDocument doc = getDocumentProvider().getDocument(getEditorInput()); - if (doc instanceof IStructuredDocument) { - ((IStructuredDocument) doc).getUndoManager().getCommandStack().flush(); - } - - // update menu text - updateMenuText(); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.ISaveablePart#doSave(org.eclipse.core.runtime.IProgressMonitor) - */ - public void doSave(IProgressMonitor progressMonitor) { - IStructuredModel model = null; - try { - model = aboutToSaveModel(); - updateEncodingMemento(); - super.doSave(progressMonitor); - } - finally { - savedModel(model); - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.AbstractTextEditor#doSetInput(org.eclipse.ui.IEditorInput) - */ - protected void doSetInput(IEditorInput input) throws CoreException { - IEditorInput oldInput = getEditorInput(); - if (oldInput != null) { - IDocument olddoc = getDocumentProvider().getDocument(oldInput); - if (olddoc != null && olddoc instanceof IExecutionDelegatable) { - ((IExecutionDelegatable) olddoc).setExecutionDelegate(null); - } - } - - if (fStructuredModel != null && !(getDocumentProvider() instanceof IModelProvider)) { - fStructuredModel.releaseFromEdit(); - } - - //attempt to get the model for the given input - super.doSetInput(input); - IStructuredModel model = tryToGetModel(input); - - /* if could not get the model prompt user to update content type - * if preferences allow, then try to get model again - */ - if(model == null && SSEUIPlugin.getDefault().getPreferenceStore().getBoolean(EditorPreferenceNames.SHOW_UNKNOWN_CONTENT_TYPE_MSG)) { - // display a dialog informing user of unknown content type giving them chance to update preferences - UnknownContentTypeDialog dialog = new UnknownContentTypeDialog(getSite().getShell(), SSEUIPlugin.getDefault().getPreferenceStore(), EditorPreferenceNames.SHOW_UNKNOWN_CONTENT_TYPE_MSG); - dialog.open(); - - //try to get model again in hopes user updated preferences - super.doSetInput(input); - model = tryToGetModel(input); - - //still could not get the model to open this editor so log - if(model == null) { - logUnexpectedDocumentKind(input); - } - } - - if (fStructuredModel != null || model != null) { - setModel(model); - } - - if (getInternalModel() != null) { - updateEditorControlsForContentType(getInternalModel().getContentTypeIdentifier()); - } - else { - updateEditorControlsForContentType(null); - } - - // start editor with smart insert mode - setInsertMode(SMART_INSERT); - } - - /** - * <p>Attempts to get the {@link IStructuredModel} for the given {@link IEditorInput}</p> - * - * @param input the {@link IEditorInput} to try and get the {@link IStructuredModel} for - * - * @return The {@link IStructuredModel} associated with the given {@link IEditorInput} or - * <code>null</code> if no associated {@link IStructuredModel} could be found. - */ - private IStructuredModel tryToGetModel(IEditorInput input) { - IStructuredModel model = null; - - IDocument newDocument = getDocumentProvider().getDocument(input); - if (newDocument instanceof IExecutionDelegatable) { - ((IExecutionDelegatable) newDocument).setExecutionDelegate(new EditorExecutionContext(this)); - } - - // if we have a Model provider, get the model from it - if (getDocumentProvider() instanceof IModelProvider) { - model = ((IModelProvider) getDocumentProvider()).getModel(getEditorInput()); - if (!model.isShared()) { - EditorModelUtil.addFactoriesTo(model); - } - } - else if (newDocument instanceof IStructuredDocument) { - // corresponding releaseFromEdit occurs in dispose() - model = StructuredModelManager.getModelManager().getModelForEdit((IStructuredDocument) newDocument); - EditorModelUtil.addFactoriesTo(model); - } - - return model; - } - - /** - * Sets up this editor's context menu before it is made visible. - * <p> - * Not API. May be reduced to protected method in the future. - * </p> - * - * @param menu - * the menu - */ - public void editorContextMenuAboutToShow(IMenuManager menu) { - /* - * To be consistent with the Java Editor, we want to remove ShiftRight - * and ShiftLeft from the context menu. - */ - super.editorContextMenuAboutToShow(menu); - menu.remove(ITextEditorActionConstants.SHIFT_LEFT); - menu.remove(ITextEditorActionConstants.SHIFT_RIGHT); - - addContextMenuActions(menu); - addSourceMenuActions(menu); - addRefactorMenuActions(menu); - addExtendedContextMenuActions(menu); - } - - /** - * End background mode. - * <p> - * Not API. May be removed in the future. - * </p> - */ - void endBackgroundOperation() { - fBackgroundJobEnded = true; - // note, we don't immediately end our 'internal busy' state, - // since we may get many calls in a short period of - // time. We always wait for the time out. - resetBusyState(); - } - - /** - * Note this method can be called indirectly from background job operation - * ... but expected to be gaurded there with ILock, plus, can be called - * directly from timer thread, so the timer's run method guards with ILock - * too. - * - * Set result[0] to 1 if the busy state was ended successfully - */ - private void endBusyStateInternal(byte[] result) { - if (fBackgroundJobEnded) { - result[0] = 1; - showBusy(false); - - ISourceViewer viewer = getSourceViewer(); - if (viewer instanceof StructuredTextViewer) { - ((StructuredTextViewer) viewer).endBackgroundUpdate(); - } - fBusyState = false; - } - else { - // we will only be in this branch for a back ground job that is - // taking - // longer than our normal time-out period (meaning we got notified - // of - // the timeout "inbetween" calls to 'begin' and - // 'endBackgroundOperation'. - // (which, remember, can only happen since there are many calls to - // begin/end in a short period of time, and we only "reset" on the - // 'ends'). - // In this event, there's really nothing to do, we're still in - // "busy state" - // and should start a new reset cycle once endBackgroundjob is - // called. - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class) - */ - public Object getAdapter(Class required) { - if (org.eclipse.wst.sse.core.internal.util.Debug.perfTestAdapterClassLoading) { - startPerfTime = System.currentTimeMillis(); - } - Object result = null; - // text editor - IStructuredModel internalModel = getInternalModel(); - if (ITextEditor.class.equals(required) || ITextEditorExtension5.class.equals(required) || ITextEditorExtension4.class.equals(required) || ITextEditorExtension3.class.equals(required) || ITextEditorExtension2.class.equals(required) || ITextEditorExtension.class.equals(required)) { - result = this; - } - else if (IWorkbenchSiteProgressService.class.equals(required)) { - return getEditorPart().getSite().getAdapter(IWorkbenchSiteProgressService.class); - } - // content outline page - else if (IContentOutlinePage.class.equals(required)) { - if (fOutlinePage == null || fOutlinePage.getControl() == null || fOutlinePage.getControl().isDisposed()) { - ContentOutlineConfiguration cfg = createContentOutlineConfiguration(); - if (cfg != null) { - ConfigurableContentOutlinePage outlinePage = new ConfigurableContentOutlinePage(); - outlinePage.setConfiguration(cfg); - if (internalModel != null) { - outlinePage.setInputContentTypeIdentifier(internalModel.getContentTypeIdentifier()); - outlinePage.setInput(internalModel); - } - - if (fOutlinePageListener == null) { - fOutlinePageListener = new OutlinePageListener(); - } - - outlinePage.addSelectionChangedListener(fOutlinePageListener); - outlinePage.addDoubleClickListener(fOutlinePageListener); - - fOutlinePage = outlinePage; - } - } - result = fOutlinePage; - } - // property sheet page, but only if the input's editable - else if (IPropertySheetPage.class.equals(required) && isEditable()) { - if (fPropertySheetPage == null || fPropertySheetPage.getControl() == null || fPropertySheetPage.getControl().isDisposed()) { - PropertySheetConfiguration cfg = createPropertySheetConfiguration(); - if (cfg != null) { - ConfigurablePropertySheetPage propertySheetPage = new ConfigurablePropertySheetPage(); - propertySheetPage.setConfiguration(cfg); - fPropertySheetPage = propertySheetPage; - } - } - result = fPropertySheetPage; - } - else if (IDocument.class.equals(required)) { - result = getDocumentProvider().getDocument(getEditorInput()); - } - else if (ISourceEditingTextTools.class.equals(required)) { - result = createSourceEditingTextTools(); - } - else if (IToggleBreakpointsTarget.class.equals(required)) { - result = ToggleBreakpointsTarget.getInstance(); - } - else if (ITextEditorExtension4.class.equals(required)) { - result = this; - } - else if (IShowInTargetList.class.equals(required)) { - result = new ShowInTargetListAdapter(); - } - else if (IVerticalRuler.class.equals(required)) { - return getVerticalRuler(); - } - else if (SelectionHistory.class.equals(required)) { - if (fSelectionHistory == null) - fSelectionHistory = new SelectionHistory(this); - result = fSelectionHistory; - } - else if (IResource.class.equals(required)) { - IEditorInput input = getEditorInput(); - if (input != null) { - result = input.getAdapter(required); - } - } - else { - if (result == null && internalModel != null) { - result = internalModel.getAdapter(required); - } - // others - if (result == null) - result = super.getAdapter(required); - } - if (result == null) { -// Logger.log(Logger.INFO_DEBUG, "StructuredTextEditor.getAdapter returning null for " + required); //$NON-NLS-1$ - } - if (org.eclipse.wst.sse.core.internal.util.Debug.perfTestAdapterClassLoading) { - long stop = System.currentTimeMillis(); - adapterRequests++; - adapterTime += (stop - startPerfTime); - } - if (org.eclipse.wst.sse.core.internal.util.Debug.perfTestAdapterClassLoading) { - System.out.println("Total calls to getAdapter: " + adapterRequests); //$NON-NLS-1$ - System.out.println("Total time in getAdapter: " + adapterTime); //$NON-NLS-1$ - System.out.println("Average time per call: " + (adapterTime / adapterRequests)); //$NON-NLS-1$ - } - return result; - } - - private String[] getConfigurationPoints() { - String contentTypeIdentifierID = null; - if (getInternalModel() != null) { - contentTypeIdentifierID = getInternalModel().getContentTypeIdentifier(); - } - return ConfigurationPointCalculator.getConfigurationPoints(this, contentTypeIdentifierID, ConfigurationPointCalculator.SOURCE, StructuredTextEditor.class); - } - - /** - * added checks to overcome bug such that if we are shutting down in an - * error condition, then viewer will have already been disposed. - */ - protected String getCursorPosition() { - String result = null; - // this may be too expensive in terms of - // performance, to do this check - // every time, just to gaurd against error - // condition. - // perhaps there's a better way? - if (getSourceViewer() != null && getSourceViewer().getTextWidget() != null && !getSourceViewer().getTextWidget().isDisposed()) { - result = super.getCursorPosition(); - } - else { - result = "0:0"; //$NON-NLS-1$ - } - return result; - } - - - Display getDisplay() { - return PlatformUI.getWorkbench().getDisplay(); - } - - /** - * Returns this editor part. - * <p> - * Not API. May be removed in the future. - * </p> - * - * @return this editor part - */ - public IEditorPart getEditorPart() { - if (fEditorPart == null) - return this; - return fEditorPart; - } - - IStructuredModel getInternalModel() { - return fStructuredModel; - } - - private InternalModelStateListener getInternalModelStateListener() { - if (fInternalModelStateListener == null) { - fInternalModelStateListener = new InternalModelStateListener(); - } - return fInternalModelStateListener; - } - - /** - * Returns this editor's StructuredModel. - * <p> - * Not API. Will be removed in the future. - * </p> - * - * @return returns this editor's IStructuredModel - * @deprecated - This method allowed for uncontrolled access to the model - * instance and will be removed in the future. It is - * recommended that the current document provider be asked for - * the current document and the IModelManager then asked for - * the corresponding model with - * getExistingModelFor*(IDocument). Supported document - * providers ensure that the document maps to a shared - * structured model. - */ - public IStructuredModel getModel() { - IDocumentProvider documentProvider = getDocumentProvider(); - - if (documentProvider == null) { - // this indicated an error in startup sequence - Logger.trace(getClass().getName(), "Program Info Only: document provider was null when model requested"); //$NON-NLS-1$ //$NON-NLS-2$ - } - - // Remember if we entered this method without a model existing - boolean initialModelNull = (fStructuredModel == null); - - if (fStructuredModel == null && documentProvider != null) { - // lazily set the model instance, although this is an ABNORMAL - // CODE PATH - if (documentProvider instanceof IModelProvider) { - fStructuredModel = ((IModelProvider) documentProvider).getModel(getEditorInput()); - fisReleased = false; - } - else { - IDocument doc = documentProvider.getDocument(getEditorInput()); - if (doc instanceof IStructuredDocument) { - /* - * Called in this manner because getExistingModel can skip - * some calculations always performed in getModelForEdit - */ - IStructuredModel model = StructuredModelManager.getModelManager().getExistingModelForEdit(doc); - if (model == null) { - model = StructuredModelManager.getModelManager().getModelForEdit((IStructuredDocument) doc); - } - fStructuredModel = model; - fisReleased = false; - } - } - - EditorModelUtil.addFactoriesTo(fStructuredModel); - - if (initialModelNull && fStructuredModel != null) { - /* - * DMW: 9/1/2002 -- why is update called here? No change has - * been indicated? I'd like to remove, but will leave for now - * to avoid breaking this hack. Should measure/breakpoint to - * see how large the problem is. May cause performance - * problems. - * - * DMW: 9/8/2002 -- not sure why this was here initially, but - * the intent/hack must have been to call update if this was - * the first time fStructuredModel was set. So, I added the - * logic to check for that "first time" case. It would appear - * we don't really need. may remove in future when can test - * more. - */ - update(); - } - } - return fStructuredModel; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.part.IWorkbenchPartOrientation#getOrientation() - */ - public int getOrientation() { - // https://bugs.eclipse.org/bugs/show_bug.cgi?id=88714 - return SWT.LEFT_TO_RIGHT; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.ITextEditor#getSelectionProvider() - */ - public ISelectionProvider getSelectionProvider() { - if (fStructuredSelectionProvider == null) { - ISelectionProvider parentProvider = super.getSelectionProvider(); - if (parentProvider != null) { - fStructuredSelectionProvider = new StructuredSelectionProvider(parentProvider, this); - fStructuredSelectionProvider.addPostSelectionChangedListener(new ISelectionChangedListener() { - public void selectionChanged(SelectionChangedEvent event) { - updateStatusLine(event.getSelection()); - } - }); - if (fStructuredModel != null) { - SelectionConvertor convertor = (SelectionConvertor) fStructuredModel.getAdapter(SelectionConvertor.class); - if (convertor != null) { - fStructuredSelectionProvider.selectionConvertor = convertor; - } - } - } - } - if (fStructuredSelectionProvider == null) { - return super.getSelectionProvider(); - } - return fStructuredSelectionProvider; - } - - /* (non-Javadoc) - * @see org.eclipse.ui.texteditor.AbstractTextEditor#getStatusLineManager() - * - * Overridden to use the top-level editor part's status line - */ - protected IStatusLineManager getStatusLineManager() { - return getEditorPart().getEditorSite().getActionBars().getStatusLineManager(); - } - - /** - * Returns the editor's source viewer. This method was created to expose - * the protected final getSourceViewer() method. - * <p> - * Not API. May be removed in the future. - * </p> - * - * @return the editor's source viewer - */ - public StructuredTextViewer getTextViewer() { - return (StructuredTextViewer) getSourceViewer(); - } - - /** - * Jumps to the matching bracket. - */ - void gotoMatchingBracket() { - ICharacterPairMatcher matcher = createCharacterPairMatcher(); - if (matcher == null) - return; - - ISourceViewer sourceViewer = getSourceViewer(); - IDocument document = sourceViewer.getDocument(); - if (document == null) - return; - - IRegion selection = getSignedSelection(sourceViewer); - - int selectionLength = Math.abs(selection.getLength()); - if (selectionLength > 1) { - setStatusLineErrorMessage(SSEUIMessages.GotoMatchingBracket_error_invalidSelection); - sourceViewer.getTextWidget().getDisplay().beep(); - return; - } - - int sourceCaretOffset = selection.getOffset() + selection.getLength(); - IRegion region = matcher.match(document, sourceCaretOffset); - if (region == null) { - setStatusLineErrorMessage(SSEUIMessages.GotoMatchingBracket_error_noMatchingBracket); - sourceViewer.getTextWidget().getDisplay().beep(); - return; - } - - int offset = region.getOffset(); - int length = region.getLength(); - - if (length < 1) - return; - - int anchor = matcher.getAnchor(); - - // go to after the match if matching to the right - int targetOffset = (ICharacterPairMatcher.RIGHT == anchor) ? offset : offset + length; - - boolean visible = false; - if (sourceViewer instanceof ITextViewerExtension5) { - ITextViewerExtension5 extension = (ITextViewerExtension5) sourceViewer; - visible = (extension.modelOffset2WidgetOffset(targetOffset) > -1); - } - else { - IRegion visibleRegion = sourceViewer.getVisibleRegion(); - // http://dev.eclipse.org/bugs/show_bug.cgi?id=34195 - visible = (targetOffset >= visibleRegion.getOffset() && targetOffset <= visibleRegion.getOffset() + visibleRegion.getLength()); - } - - if (!visible) { - setStatusLineErrorMessage(SSEUIMessages.GotoMatchingBracket_error_bracketOutsideSelectedElement); - sourceViewer.getTextWidget().getDisplay().beep(); - return; - } - - if (selection.getLength() < 0) - targetOffset -= selection.getLength(); - - if (sourceViewer != null) { - sourceViewer.setSelectedRange(targetOffset, selection.getLength()); - sourceViewer.revealRange(targetOffset, selection.getLength()); - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.AbstractTextEditor#handleCursorPositionChanged() - */ - protected void handleCursorPositionChanged() { - super.handleCursorPositionChanged(); - updateStatusField(StructuredTextEditorActionConstants.STATUS_CATEGORY_OFFSET); - } - - protected void handleElementContentReplaced() { - super.handleElementContentReplaced(); - - // queue a full revalidation of content - IDocument document = getDocumentProvider().getDocument(getEditorInput()); - SourceViewerConfiguration sourceViewerConfiguration = getSourceViewerConfiguration(); - if (document != null && sourceViewerConfiguration != null && sourceViewerConfiguration.getReconciler(getSourceViewer()) instanceof DirtyRegionProcessor) { - ((DirtyRegionProcessor) sourceViewerConfiguration.getReconciler(getSourceViewer())).processDirtyRegion(new DirtyRegion(0, document.getLength(), DirtyRegion.INSERT, document.get())); - } - - /* - * https://bugs.eclipse.org/bugs/show_bug.cgi?id=129906 - update - * selection to listeners - */ - ISelectionProvider selectionProvider = getSelectionProvider(); - ISelection originalSelection = selectionProvider.getSelection(); - if (selectionProvider instanceof StructuredSelectionProvider && originalSelection instanceof ITextSelection) { - ITextSelection textSelection = (ITextSelection) originalSelection; - // make sure the old selection is actually still valid - if (!textSelection.isEmpty() && (document == null || textSelection.getOffset() + textSelection.getLength() <= document.getLength())) { - SelectionChangedEvent syntheticEvent = new SelectionChangedEvent(selectionProvider, new TextSelection(textSelection.getOffset(), textSelection.getLength())); - ((StructuredSelectionProvider) selectionProvider).handleSelectionChanged(syntheticEvent); - ((StructuredSelectionProvider) selectionProvider).handlePostSelectionChanged(syntheticEvent); - } - else { - SelectionChangedEvent syntheticEvent = new SelectionChangedEvent(selectionProvider, new TextSelection(0, 0)); - ((StructuredSelectionProvider) selectionProvider).handleSelectionChanged(syntheticEvent); - ((StructuredSelectionProvider) selectionProvider).handlePostSelectionChanged(syntheticEvent); - } - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.AbstractTextEditor#handlePreferenceStoreChanged(org.eclipse.jface.util.PropertyChangeEvent) - */ - protected void handlePreferenceStoreChanged(PropertyChangeEvent event) { - String property = event.getProperty(); - - if (EditorPreferenceNames.EDITOR_TEXT_HOVER_MODIFIERS.equals(property)) { - updateHoverBehavior(); - } - - //enable or disable as you type validation - else if(CommonEditorPreferenceNames.EVALUATE_TEMPORARY_PROBLEMS.equals(property)) { - IReconciler reconciler = this.getSourceViewerConfiguration().getReconciler(this.getSourceViewer()); - if (reconciler instanceof DocumentRegionProcessor) { - ((DocumentRegionProcessor) reconciler).setValidatorStrategyEnabled(isValidationEnabled()); - } - } - - else if (AbstractStructuredFoldingStrategy.FOLDING_ENABLED.equals(property)) { - if (getSourceViewer() instanceof ProjectionViewer) { - // install projection support if it has not even been - // installed yet - if (isFoldingEnabled() && (fProjectionSupport == null)) { - installProjectionSupport(); - } - ProjectionViewer pv = (ProjectionViewer) getSourceViewer(); - if (pv.isProjectionMode() != isFoldingEnabled()) { - if (pv.canDoOperation(ProjectionViewer.TOGGLE)) { - pv.doOperation(ProjectionViewer.TOGGLE); - } - } - } - } - - // update content assist preferences - else if (EditorPreferenceNames.CODEASSIST_PROPOSALS_BACKGROUND.equals(property)) { - ISourceViewer sourceViewer = getSourceViewer(); - if (sourceViewer != null) { - SourceViewerConfiguration configuration = getSourceViewerConfiguration(); - if (configuration != null) { - IContentAssistant contentAssistant = configuration.getContentAssistant(sourceViewer); - if (contentAssistant instanceof ContentAssistant) { - ContentAssistant assistant = (ContentAssistant) contentAssistant; - RGB rgb = PreferenceConverter.getColor(getPreferenceStore(), EditorPreferenceNames.CODEASSIST_PROPOSALS_BACKGROUND); - Color color = EditorUtility.getColor(rgb); - assistant.setProposalSelectorBackground(color); - } - } - } - } - - // update content assist preferences - else if (EditorPreferenceNames.CODEASSIST_PROPOSALS_FOREGROUND.equals(property)) { - ISourceViewer sourceViewer = getSourceViewer(); - if (sourceViewer != null) { - SourceViewerConfiguration configuration = getSourceViewerConfiguration(); - if (configuration != null) { - IContentAssistant contentAssistant = configuration.getContentAssistant(sourceViewer); - if (contentAssistant instanceof ContentAssistant) { - ContentAssistant assistant = (ContentAssistant) contentAssistant; - RGB rgb = PreferenceConverter.getColor(getPreferenceStore(), EditorPreferenceNames.CODEASSIST_PROPOSALS_FOREGROUND); - Color color = EditorUtility.getColor(rgb); - assistant.setProposalSelectorForeground(color); - } - } - } - } - - // update content assist preferences - else if (EditorPreferenceNames.CODEASSIST_PARAMETERS_BACKGROUND.equals(property)) { - ISourceViewer sourceViewer = getSourceViewer(); - if (sourceViewer != null) { - SourceViewerConfiguration configuration = getSourceViewerConfiguration(); - if (configuration != null) { - IContentAssistant contentAssistant = configuration.getContentAssistant(sourceViewer); - if (contentAssistant instanceof ContentAssistant) { - ContentAssistant assistant = (ContentAssistant) contentAssistant; - RGB rgb = PreferenceConverter.getColor(getPreferenceStore(), EditorPreferenceNames.CODEASSIST_PARAMETERS_BACKGROUND); - Color color = EditorUtility.getColor(rgb); - assistant.setContextInformationPopupBackground(color); - assistant.setContextSelectorBackground(color); - } - } - } - } - - // update content assist preferences - else if (EditorPreferenceNames.CODEASSIST_PARAMETERS_FOREGROUND.equals(property)) { - ISourceViewer sourceViewer = getSourceViewer(); - if (sourceViewer != null) { - SourceViewerConfiguration configuration = getSourceViewerConfiguration(); - if (configuration != null) { - IContentAssistant contentAssistant = configuration.getContentAssistant(sourceViewer); - if (contentAssistant instanceof ContentAssistant) { - ContentAssistant assistant = (ContentAssistant) contentAssistant; - RGB rgb = PreferenceConverter.getColor(getPreferenceStore(), EditorPreferenceNames.CODEASSIST_PARAMETERS_FOREGROUND); - Color color = EditorUtility.getColor(rgb); - assistant.setContextInformationPopupForeground(color); - assistant.setContextSelectorForeground(color); - } - } - } - } - - super.handlePreferenceStoreChanged(event); - } - - private boolean inBusyState() { - return fBusyState; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.IEditorPart#init(org.eclipse.ui.IEditorSite, - * org.eclipse.ui.IEditorInput) - */ - public void init(IEditorSite site, IEditorInput input) throws PartInitException { - // if we've gotten an error elsewhere, before - // we've actually opened, then don't open. - if (shouldClose) { - setSite(site); - close(false); - } - else { - super.init(site, input); - } - } - - /** - * Set the document provider for this editor. - * <p> - * Not API. May be removed in the future. - * </p> - * - * @param documentProvider - * documentProvider to initialize - */ - public void initializeDocumentProvider(IDocumentProvider documentProvider) { - if (documentProvider != null) { - setDocumentProvider(documentProvider); - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.AbstractTextEditor#initializeDragAndDrop(org.eclipse.jface.text.source.ISourceViewer) - */ - protected void initializeDragAndDrop(ISourceViewer viewer) { - IPreferenceStore store = getPreferenceStore(); - if (store != null && store.getBoolean(PREFERENCE_TEXT_DRAG_AND_DROP_ENABLED)) - initializeDrop(viewer); - } - - protected void initializeDrop(ITextViewer textViewer) { - int operations = DND.DROP_COPY | DND.DROP_MOVE; - fDropTarget = new DropTarget(textViewer.getTextWidget(), operations); - fDropAdapter = new ReadOnlyAwareDropTargetAdapter(true); - fDropAdapter.setTargetEditor(this); - fDropAdapter.setTargetIDs(getConfigurationPoints()); - fDropAdapter.setTextViewer(textViewer); - fDropTarget.setTransfer(fDropAdapter.getTransfers()); - fDropTarget.addDropListener(fDropAdapter); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#initializeEditor() - */ - protected void initializeEditor() { - super.initializeEditor(); - - setPreferenceStore(createCombinedPreferenceStore()); - - setRangeIndicator(new DefaultRangeIndicator()); - setEditorContextMenuId(EDITOR_CONTEXT_MENU_ID); - initializeDocumentProvider(null); - // set the infopop for source viewer - String helpId = getHelpContextId(); - // no infopop set or using default text editor help, use default - if (helpId == null || ITextEditorHelpContextIds.TEXT_EDITOR.equals(helpId)) - helpId = IHelpContextIds.XML_SOURCE_VIEW_HELPID; - setHelpContextId(helpId); - // defect 203158 - disable ruler context menu for - // beta - // setRulerContextMenuId(RULER_CONTEXT_MENU_ID); - configureInsertMode(SMART_INSERT, true); - - // enable the base source editor activity when editor opens - try { - // FIXME: - commented out to avoid minor dependancy during - // transition to org.eclipse - // WTPActivityBridge.getInstance().enableActivity(CORE_SSE_ACTIVITY_ID, - // true); - } - catch (Exception t) { - // if something goes wrong with enabling activity, just log the - // error but dont - // have it break the editor - Logger.log(Logger.WARNING_DEBUG, t.getMessage(), t); - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.editors.text.TextEditor#initializeKeyBindingScopes() - */ - protected void initializeKeyBindingScopes() { - setKeyBindingScopes(new String[]{EDITOR_KEYBINDING_SCOPE_ID}); - } - - /** - * Initializes the editor's source viewer and other items that were source - * viewer-dependent. - */ - private void initializeSourceViewer() { - IAction openHyperlinkAction = getAction(StructuredTextEditorActionConstants.ACTION_NAME_OPEN_FILE); - if (openHyperlinkAction instanceof OpenHyperlinkAction) { - ((OpenHyperlinkAction) openHyperlinkAction).setHyperlinkDetectors(getSourceViewerConfiguration().getHyperlinkDetectors(getSourceViewer())); - } - - // do not even install projection support until folding is actually - // enabled - if (isFoldingEnabled()) { - installProjectionSupport(); - } - } - - protected void initSourceViewer(StructuredTextViewer sourceViewer) { - // ensure decoration support is configured - getSourceViewerDecorationSupport(sourceViewer); - } - - protected void installTextDragAndDrop(ISourceViewer viewer) { - // do nothing - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.editors.text.TextEditor#installEncodingSupport() - */ - protected void installEncodingSupport() { - fEncodingSupport = new EncodingSupport(getConfigurationPoints()); - fEncodingSupport.initialize(this); - } - - /** - * Install everything necessary to get document folding working and enable - * document folding - */ - private void installProjectionSupport() { - 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 parent) { - return new DefaultInformationControl(parent); - } - }); - fProjectionSupport.install(); - - if (isFoldingEnabled()) - projectionViewer.doOperation(ProjectionViewer.TOGGLE); - } - - /** - * Return whether document folding should be enabled according to the - * preference store settings. - * - * @return <code>true</code> if document folding should be enabled - */ - private boolean isFoldingEnabled() { - IPreferenceStore store = getPreferenceStore(); - // check both preference store and vm argument - return (store.getBoolean(AbstractStructuredFoldingStrategy.FOLDING_ENABLED)); - } - - /** - * Determine if the user preference for as you type validation is enabled or not - */ - private boolean isValidationEnabled() { - return getPreferenceStore().getBoolean(CommonEditorPreferenceNames.EVALUATE_TEMPORARY_PROBLEMS); - } - - /** - * <p>Logs a warning about how this {@link StructuredTextEditor} just opened an {@link IEditorInput} - * it was not designed to open.</p> - * - * @param input the {@link IEditorInput} this {@link StructuredTextEditor} was not designed to open - * to log the message about. - */ - private void logUnexpectedDocumentKind(IEditorInput input) { - Logger.log(Logger.WARNING, "StructuredTextEditor being used without StructuredDocument"); //$NON-NLS-1$ - String name = null; - if (input != null) { - name = input.getName(); - } - else { - name = "input was null"; //$NON-NLS-1$ - } - Logger.log(Logger.WARNING, " Input Name: " + name); //$NON-NLS-1$ - String implClass = null; - IDocument document = getDocumentProvider().getDocument(input); - if (document != null) { - implClass = document.getClass().getName(); - } - else { - implClass = "document was null"; //$NON-NLS-1$ - } - Logger.log(Logger.WARNING, " Unexpected IDocumentProvider implementation: " + getDocumentProvider().getClass().getName()); //$NON-NLS-1$ - Logger.log(Logger.WARNING, " Unexpected IDocument implementation: " + implClass); //$NON-NLS-1$ - } - - /* - * @see org.eclipse.ui.texteditor.AbstractTextEditor#performRevert() - */ - protected void performRevert() { - ProjectionViewer projectionViewer = (ProjectionViewer) getSourceViewer(); - projectionViewer.setRedraw(false); - try { - - boolean projectionMode = projectionViewer.isProjectionMode(); - if (projectionMode) { - projectionViewer.disableProjection(); - } - - super.performRevert(); - - if (projectionMode) { - projectionViewer.enableProjection(); - } - - } - finally { - projectionViewer.setRedraw(true); - } - } - - /** - * {@inheritDoc} - * <p> - * Not API. May be reduced to protected method in the future. - * </p> - */ - public void rememberSelection() { - /* - * This method was made public for use by editors that use - * StructuredTextEditor (like some clients) - */ - super.rememberSelection(); - } - - - /** - * both starts and resets the busy state timer - */ - private void resetBusyState() { - // reset the "busy" timeout - if (fBusyTimer != null) { - fBusyTimer.cancel(); - } - startBusyTimer(); - } - - /** - * {@inheritDoc} - * <p> - * Not API. May be reduced to protected method in the future. - * </p> - */ - public void restoreSelection() { - /* - * This method was made public for use by editors that use - * StructuredTextEditor (like some clients) - */ - // catch odd case where source viewer has no text - // widget (defect - // 227670) - if ((getSourceViewer() != null) && (getSourceViewer().getTextWidget() != null)) - super.restoreSelection(); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.AbstractTextEditor#rulerContextMenuAboutToShow(org.eclipse.jface.action.IMenuManager) - */ - protected void rulerContextMenuAboutToShow(IMenuManager menu) { - super.rulerContextMenuAboutToShow(menu); - - IMenuManager foldingMenu = new MenuManager(SSEUIMessages.Folding, "projection"); //$NON-NLS-1$ - menu.appendToGroup(ITextEditorActionConstants.GROUP_RULERS, foldingMenu); - - IAction action = getAction("FoldingToggle"); //$NON-NLS-1$ - foldingMenu.add(action); - action = getAction("FoldingExpandAll"); //$NON-NLS-1$ - foldingMenu.add(action); - action = getAction("FoldingCollapseAll"); //$NON-NLS-1$ - foldingMenu.add(action); - - IStructuredModel internalModel = getInternalModel(); - if (internalModel != null) { - boolean debuggingAvailable = BreakpointProviderBuilder.getInstance().isAvailable(internalModel.getContentTypeIdentifier(), BreakpointRulerAction.getFileExtension(getEditorInput())); - if (debuggingAvailable) { - // append actions to "debug" group (created in - // AbstractDecoratedTextEditor.rulerContextMenuAboutToShow(IMenuManager) - menu.appendToGroup("debug", getAction(ActionDefinitionIds.TOGGLE_BREAKPOINTS)); //$NON-NLS-1$ - menu.appendToGroup("debug", getAction(ActionDefinitionIds.MANAGE_BREAKPOINTS)); //$NON-NLS-1$ - menu.appendToGroup("debug", getAction(ActionDefinitionIds.EDIT_BREAKPOINTS)); //$NON-NLS-1$ - } - addExtendedRulerContextMenuActions(menu); - } - } - - /** - * {@inheritDoc} - * <p> - * Overridden to expose part activation handling for multi-page editors. - * </p> - * <p> - * Not API. May be reduced to protected method in the future. - * </p> - * - * @see org.eclipse.ui.texteditor.AbstractTextEditor#safelySanityCheckState(org.eclipse.ui.IEditorInput) - */ - public void safelySanityCheckState(IEditorInput input) { - super.safelySanityCheckState(input); - } - - protected void sanityCheckState(IEditorInput input) { - try { - ++validateEditCount; - super.sanityCheckState(input); - } - finally { - --validateEditCount; - } - } - - private void savedModel(IStructuredModel model) { - if (model != null) { - model.changedModel(); - } - } - - /** - * Ensure that the correct IDocumentProvider is used. For direct models, a - * special provider is used. For StorageEditorInputs, use a custom - * provider that creates a usable ResourceAnnotationModel. For everything - * else, use the base support. - * - * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#setDocumentProvider(org.eclipse.ui.IEditorInput) - */ - protected void setDocumentProvider(IEditorInput input) { - if (input instanceof IStructuredModel) { - // largely untested - setDocumentProvider(StructuredModelDocumentProvider.getInstance()); - } - else if (input instanceof IStorageEditorInput && !(input instanceof IFileEditorInput)) { - setDocumentProvider(StorageModelProvider.getInstance()); - } - else { - super.setDocumentProvider(input); - } - } - - /** - * Set editor part associated with this editor. - * <p> - * Not API. May be removed in the future. - * </p> - * - * @param editorPart - * editor part associated with this editor - */ - public void setEditorPart(IEditorPart editorPart) { - fEditorPart = editorPart; - } - - /** - * Sets the model field within this editor. - * - * @deprecated - can eventually be eliminated - */ - private void setModel(IStructuredModel newModel) { - Assert.isNotNull(getDocumentProvider(), "document provider can not be null when setting model"); //$NON-NLS-1$ - if (fStructuredModel != null) { - fStructuredModel.removeModelStateListener(getInternalModelStateListener()); - } - fStructuredModel = newModel; - if (fStructuredModel != null) { - fStructuredModel.addModelStateListener(getInternalModelStateListener()); - } - // update() should be called whenever the model is - // set or changed - update(); - } - - /** - * Sets the editor's source viewer configuration which it uses to - * configure it's internal source viewer. This method was overwritten so - * that viewer configuration could be set after editor part was created. - */ - protected void setSourceViewerConfiguration(SourceViewerConfiguration config) { - SourceViewerConfiguration oldSourceViewerConfiguration = getSourceViewerConfiguration(); - super.setSourceViewerConfiguration(config); - StructuredTextViewer stv = getTextViewer(); - if (stv != null) { - /* - * There should be no need to unconfigure before configure because - * configure will also unconfigure before configuring - */ - removeReconcilingListeners(oldSourceViewerConfiguration, stv); - stv.unconfigure(); - setStatusLineMessage(null); - stv.configure(config); - addReconcilingListeners(config, stv); - } - } - - private void removeReconcilingListeners(SourceViewerConfiguration config, StructuredTextViewer stv) { - IReconciler reconciler = config.getReconciler(stv); - if (reconciler instanceof DocumentRegionProcessor) { - for (int i = 0; i < fReconcilingListeners.length; i++) { - ((DocumentRegionProcessor) reconciler).removeReconcilingListener(fReconcilingListeners[i]); - } - } - } - - private void addReconcilingListeners(SourceViewerConfiguration config, StructuredTextViewer stv) { - try { - List reconcilingListeners = new ArrayList(fReconcilingListeners.length); - String[] ids = getConfigurationPoints(); - for (int i = 0; i < ids.length; i++) { - reconcilingListeners.addAll(ExtendedConfigurationBuilder.getInstance().getConfigurations("sourceReconcilingListener", ids[i])); //$NON-NLS-1$ - } - fReconcilingListeners = (ISourceReconcilingListener[]) reconcilingListeners.toArray(new ISourceReconcilingListener[reconcilingListeners.size()]); - } - catch (ClassCastException e) { - Logger.log(Logger.ERROR, "Configuration has a reconciling listener that does not implement ISourceReconcilingListener."); //$NON-NLS-1$ - } - - IReconciler reconciler = config.getReconciler(stv); - if (reconciler instanceof DocumentRegionProcessor) { - for (int i = 0; i < fReconcilingListeners.length; i++) - ((DocumentRegionProcessor) reconciler).addReconcilingListener(fReconcilingListeners[i]); - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.part.WorkbenchPart#showBusy(boolean) - */ - public void showBusy(boolean busy) { - // no-op - super.showBusy(busy); - } - - private void startBusyTimer() { - // TODO: we need a resettable timer, so not so - // many are created - fBusyTimer = new Timer(true); - fBusyTimer.schedule(new TimeOutExpired(), BUSY_STATE_DELAY); - } - - protected void uninstallTextDragAndDrop(ISourceViewer viewer) { - // do nothing - } - - /** - * Update should be called whenever the model is set or changed (as in - * swapped) - * <p> - * Not API. May be removed in the future. - * </p> - */ - public void update() { - if (fOutlinePage != null && fOutlinePage instanceof ConfigurableContentOutlinePage) { - ContentOutlineConfiguration cfg = createContentOutlineConfiguration(); - ((ConfigurableContentOutlinePage) fOutlinePage).setConfiguration(cfg); - IStructuredModel internalModel = getInternalModel(); - ((ConfigurableContentOutlinePage) fOutlinePage).setInputContentTypeIdentifier(internalModel.getContentTypeIdentifier()); - ((ConfigurableContentOutlinePage) fOutlinePage).setInput(internalModel); - } - if (fPropertySheetPage != null && fPropertySheetPage instanceof ConfigurablePropertySheetPage) { - PropertySheetConfiguration cfg = createPropertySheetConfiguration(); - ((ConfigurablePropertySheetPage) fPropertySheetPage).setConfiguration(cfg); - } - disposeModelDependentFields(); - - fShowInTargetIds = createShowInTargetIds(); - - if (getSourceViewerConfiguration() instanceof StructuredTextViewerConfiguration && fStatusLineLabelProvider != null) { - fStatusLineLabelProvider.dispose(); - } - - String configurationId = fViewerConfigurationTargetId; - updateSourceViewerConfiguration(); - - /* Only reinstall if the configuration id has changed */ - if (configurationId != null && !configurationId.equals(fViewerConfigurationTargetId)) { - uninstallSemanticHighlighting(); - installSemanticHighlighting(); - } - - if (getSourceViewerConfiguration() instanceof StructuredTextViewerConfiguration) { - fStatusLineLabelProvider = ((StructuredTextViewerConfiguration) getSourceViewerConfiguration()).getStatusLineLabelProvider(getSourceViewer()); - updateStatusLine(null); - } - - if (fEncodingSupport != null && fEncodingSupport instanceof EncodingSupport) { - ((EncodingSupport) fEncodingSupport).reinitialize(getConfigurationPoints()); - } - - createModelDependentFields(); - } - - /** - * Updates all content dependent actions. - */ - protected void updateContentDependentActions() { - super.updateContentDependentActions(); - // super.updateContentDependentActions only updates - // the enable/disable - // state of all - // the content dependent actions. - // StructuredTextEditor's undo and redo actions - // have a detail label and - // description. - // They needed to be updated. - if (!fEditorDisposed) - updateMenuText(); - } - - - /** - * Updates the editor context menu by creating a new context menu with the - * given menu id - * - * @param contextMenuId - * Cannot be null - */ - private void updateEditorContextMenuId(String contextMenuId) { - // update editor context menu id if updating to a new id or if context - // menu is not already set up - if (!contextMenuId.equals(getEditorContextMenuId()) || (fTextContextMenu == null)) { - setEditorContextMenuId(contextMenuId); - - if (getSourceViewer() != null) { - StyledText styledText = getSourceViewer().getTextWidget(); - if (styledText != null) { - // dispose of previous context menu - if (fTextContextMenu != null) { - fTextContextMenu.dispose(); - } - if (fTextContextMenuManager != null) { - fTextContextMenuManager.removeMenuListener(getContextMenuListener()); - fTextContextMenuManager.removeAll(); - fTextContextMenuManager.dispose(); - } - - fTextContextMenuManager = new MenuManager(getEditorContextMenuId(), getEditorContextMenuId()); - fTextContextMenuManager.setRemoveAllWhenShown(true); - fTextContextMenuManager.addMenuListener(getContextMenuListener()); - - fTextContextMenu = fTextContextMenuManager.createContextMenu(styledText); - styledText.setMenu(fTextContextMenu); - - getSite().registerContextMenu(getEditorContextMenuId(), fTextContextMenuManager, getSelectionProvider()); - - // also register this menu for source page part and - // structured text editor ids - String partId = getSite().getId(); - if (partId != null) { - getSite().registerContextMenu(partId + EDITOR_CONTEXT_MENU_SUFFIX, fTextContextMenuManager, getSelectionProvider()); - } - getSite().registerContextMenu(EDITOR_CONTEXT_MENU_ID, fTextContextMenuManager, getSelectionProvider()); - } - } - } - } - - /** - * Updates editor context menu, vertical ruler menu, help context id for - * new content type - * - * @param contentType - */ - private void updateEditorControlsForContentType(String contentType) { - if (contentType == null) { - updateEditorContextMenuId(EDITOR_CONTEXT_MENU_ID); - updateRulerContextMenuId(RULER_CONTEXT_MENU_ID); - updateHelpContextId(ITextEditorHelpContextIds.TEXT_EDITOR); - } - else { - updateEditorContextMenuId(contentType + EDITOR_CONTEXT_MENU_SUFFIX); - updateRulerContextMenuId(contentType + RULER_CONTEXT_MENU_SUFFIX); - updateHelpContextId(contentType + "_source_HelpId"); //$NON-NLS-1$ - - /* Activate the contexts defined for this editor */ - activateContexts((IContextService) getSite().getService(IContextService.class)); - } - } - - private void updateEncodingMemento() { - boolean failed = false; - IStructuredModel internalModel = getInternalModel(); - if (internalModel != null) { - IStructuredDocument doc = internalModel.getStructuredDocument(); - EncodingMemento memento = doc.getEncodingMemento(); - IDocumentCharsetDetector detector = internalModel.getModelHandler().getEncodingDetector(); - if (memento != null && detector != null) { - detector.set(doc); - try { - String newEncoding = detector.getEncoding(); - if (newEncoding != null) { - memento.setDetectedCharsetName(newEncoding); - } - } - catch (IOException e) { - failed = true; - } - } - /** - * Be sure to use the new value but only if no exception - * occurred. (we may find cases we need to do more error recovery - * there) should be near impossible to get IOException from - * processing the _document_ - */ - if (!failed) { - doc.setEncodingMemento(memento); - } - } - } - - /** - * Updates the help context of the editor with the given help context id - * - * @param helpContextId - * Cannot be null - */ - private void updateHelpContextId(String helpContextId) { - if (!helpContextId.equals(getHelpContextId())) { - setHelpContextId(helpContextId); - - if (getSourceViewer() != null) { - StyledText styledText = getSourceViewer().getTextWidget(); - if (styledText != null) { - IWorkbenchHelpSystem helpSystem = PlatformUI.getWorkbench().getHelpSystem(); - helpSystem.setHelp(styledText, getHelpContextId()); - } - } - } - } - - /* - * Update the hovering behavior depending on the preferences. - */ - private void updateHoverBehavior() { - SourceViewerConfiguration configuration = getSourceViewerConfiguration(); - String[] types = configuration.getConfiguredContentTypes(getSourceViewer()); - - for (int i = 0; i < types.length; i++) { - - String t = types[i]; - - ISourceViewer sourceViewer = getSourceViewer(); - if (sourceViewer instanceof ITextViewerExtension2) { - // Remove existing hovers - ((ITextViewerExtension2) sourceViewer).removeTextHovers(t); - - int[] stateMasks = configuration.getConfiguredTextHoverStateMasks(getSourceViewer(), t); - - if (stateMasks != null) { - for (int j = 0; j < stateMasks.length; j++) { - int stateMask = stateMasks[j]; - ITextHover textHover = configuration.getTextHover(sourceViewer, t, stateMask); - ((ITextViewerExtension2) sourceViewer).setTextHover(textHover, t, stateMask); - } - } - else { - ITextHover textHover = configuration.getTextHover(sourceViewer, t); - ((ITextViewerExtension2) sourceViewer).setTextHover(textHover, t, ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK); - } - } - else - sourceViewer.setTextHover(configuration.getTextHover(sourceViewer, t), t); - } - } - - private void updateMenuText() { - ITextViewer viewer = getTextViewer(); - StyledText widget = null; - if (viewer != null) - widget = viewer.getTextWidget(); - - if (fStructuredModel != null && !fStructuredModel.isModelStateChanging() && viewer != null && widget != null && !widget.isDisposed()) { - // performance: don't force an update of the action bars unless - // required as it is expensive - String previousUndoText = null; - String previousUndoDesc = null; - String previousRedoText = null; - String previousRedoDesc = null; - boolean updateActions = false; - IAction undoAction = getAction(ITextEditorActionConstants.UNDO); - IAction redoAction = getAction(ITextEditorActionConstants.REDO); - if (undoAction != null) { - previousUndoText = undoAction.getText(); - previousUndoDesc = undoAction.getDescription(); - updateActions = updateActions || previousUndoText == null || previousUndoDesc == null; - undoAction.setText(UNDO_ACTION_TEXT_DEFAULT); - undoAction.setDescription(UNDO_ACTION_DESC_DEFAULT); - } - if (redoAction != null) { - previousRedoText = redoAction.getText(); - previousRedoDesc = redoAction.getDescription(); - updateActions = updateActions || previousRedoText == null || previousRedoDesc == null; - redoAction.setText(REDO_ACTION_TEXT_DEFAULT); - redoAction.setDescription(REDO_ACTION_DESC_DEFAULT); - } - if (fStructuredModel.getUndoManager() != null) { - IStructuredTextUndoManager undoManager = fStructuredModel.getUndoManager(); - // get undo command - Command undoCommand = undoManager.getUndoCommand(); - // set undo label and description - if (undoAction != null) { - undoAction.setEnabled(undoManager.undoable()); - if (undoCommand != null) { - String label = undoCommand.getLabel(); - if (label != null) { - String customText = MessageFormat.format(UNDO_ACTION_TEXT, new String[]{label}); - updateActions = updateActions || customText == null || previousUndoText == null || !customText.equals(previousUndoText); - undoAction.setText(customText); - } - String desc = undoCommand.getDescription(); - if (desc != null) { - String customDesc = MessageFormat.format(UNDO_ACTION_DESC, new String[]{desc}); - updateActions = updateActions || customDesc == null || previousRedoDesc == null || !customDesc.equals(previousUndoDesc); - undoAction.setDescription(customDesc); - } - } - } - // get redo command - Command redoCommand = undoManager.getRedoCommand(); - // set redo label and description - if (redoAction != null) { - redoAction.setEnabled(undoManager.redoable()); - if (redoCommand != null) { - String label = redoCommand.getLabel(); - if (label != null) { - String customText = MessageFormat.format(REDO_ACTION_TEXT, new String[]{label}); - updateActions = updateActions || customText == null || previousRedoText == null || !customText.equals(previousRedoText); - redoAction.setText(customText); - } - String desc = redoCommand.getDescription(); - if (desc != null) { - String customDesc = MessageFormat.format(REDO_ACTION_DESC, new String[]{desc}); - updateActions = updateActions || customDesc == null || previousRedoDesc == null || !customDesc.equals(previousRedoDesc); - redoAction.setDescription(customDesc); - } - } - } - } - // tell the action bars to update - if (updateActions) { - if (getEditorSite().getActionBars() != null) { - getEditorSite().getActionBars().updateActionBars(); - } - else if (getEditorPart() != null && getEditorPart().getEditorSite().getActionBars() != null) { - getEditorPart().getEditorSite().getActionBars().updateActionBars(); - } - } - } - } - - void updateRangeIndication(ISelection selection) { - boolean rangeUpdated = false; - if (selection instanceof IStructuredSelection && !((IStructuredSelection) selection).isEmpty()) { - Object[] objects = ((IStructuredSelection) selection).toArray(); - if (objects.length > 0 && objects[0] instanceof IndexedRegion) { - int start = ((IndexedRegion) objects[0]).getStartOffset(); - int end = ((IndexedRegion) objects[0]).getEndOffset(); - if (objects.length > 1) { - for (int i = 1; i < objects.length; i++) { - start = Math.min(start, ((IndexedRegion) objects[i]).getStartOffset()); - end = Math.max(end, ((IndexedRegion) objects[i]).getEndOffset()); - } - } - getSourceViewer().setRangeIndication(start, end - start, false); - rangeUpdated = true; - } - } - if (!rangeUpdated && getSourceViewer() != null) { - if (selection instanceof ITextSelection) { - getSourceViewer().setRangeIndication(((ITextSelection) selection).getOffset(), ((ITextSelection) selection).getLength(), false); - } - else { - getSourceViewer().removeRangeIndication(); - } - } - } - - - /** - * Updates the editor vertical ruler menu by creating a new vertical ruler - * context menu with the given menu id - * - * @param rulerMenuId - * Cannot be null - */ - private void updateRulerContextMenuId(String rulerMenuId) { - // update ruler context menu id if updating to a new id or if context - // menu is not already set up - if (!rulerMenuId.equals(getRulerContextMenuId()) || (fRulerContextMenu == null)) { - setRulerContextMenuId(rulerMenuId); - - if (getVerticalRuler() != null) { - // dispose of previous ruler context menu - if (fRulerContextMenu != null) { - fRulerContextMenu.dispose(); - } - if (fRulerContextMenuManager != null) { - fRulerContextMenuManager.removeMenuListener(getContextMenuListener()); - fRulerContextMenuManager.removeAll(); - fRulerContextMenuManager.dispose(); - } - - fRulerContextMenuManager = new MenuManager(getRulerContextMenuId(), getRulerContextMenuId()); - fRulerContextMenuManager.setRemoveAllWhenShown(true); - fRulerContextMenuManager.addMenuListener(getContextMenuListener()); - - Control rulerControl = getVerticalRuler().getControl(); - fRulerContextMenu = fRulerContextMenuManager.createContextMenu(rulerControl); - rulerControl.setMenu(fRulerContextMenu); - - getSite().registerContextMenu(getRulerContextMenuId(), fRulerContextMenuManager, getSelectionProvider()); - - // also register this menu for source page part and structured - // text editor ids - String partId = getSite().getId(); - if (partId != null) { - getSite().registerContextMenu(partId + RULER_CONTEXT_MENU_SUFFIX, fRulerContextMenuManager, getSelectionProvider()); - } - getSite().registerContextMenu(RULER_CONTEXT_MENU_ID, fRulerContextMenuManager, getSelectionProvider()); - } - } - } - - private void updateSourceViewerConfiguration() { - SourceViewerConfiguration configuration = getSourceViewerConfiguration(); - // no need to update source viewer configuration if one does not exist - // yet - if (configuration == null) { - return; - } - // do not configure source viewer configuration twice - boolean configured = false; - - // structuredtextviewer only works with - // structuredtextviewerconfiguration - if (!(configuration instanceof StructuredTextViewerConfiguration)) { - ConfigurationAndTarget cat = createSourceViewerConfiguration(); - fViewerConfigurationTargetId = cat.getTargetId(); - configuration = cat.getConfiguration(); - setSourceViewerConfiguration(configuration); - configured = true; - } - else { - ConfigurationAndTarget cat = createSourceViewerConfiguration(); - StructuredTextViewerConfiguration newViewerConfiguration = cat.getConfiguration(); - if (!(cat.getTargetId().equals(fViewerConfigurationTargetId))) { - // d282894 use newViewerConfiguration - fViewerConfigurationTargetId = cat.getTargetId(); - configuration = newViewerConfiguration; - setSourceViewerConfiguration(configuration); - configured = true; - } - } - - if (getSourceViewer() != null) { - // not sure if really need to reconfigure when input changes - // (maybe only need to reset viewerconfig's document) - if (!configured) - getSourceViewer().configure(configuration); - IAction openHyperlinkAction = getAction(StructuredTextEditorActionConstants.ACTION_NAME_OPEN_FILE); - if (openHyperlinkAction instanceof OpenHyperlinkAction) { - ((OpenHyperlinkAction) openHyperlinkAction).setHyperlinkDetectors(getSourceViewerConfiguration().getHyperlinkDetectors(getSourceViewer())); - } - } - } - - protected void updateStatusField(String category) { - super.updateStatusField(category); - - if (category == null) - return; - - if (StructuredTextEditorActionConstants.STATUS_CATEGORY_OFFSET.equals(category)) { - IStatusField field = getStatusField(category); - ISourceViewer sourceViewer = getSourceViewer(); - if (field != null && sourceViewer != null) { - Point selection = sourceViewer.getTextWidget().getSelection(); - int offset1 = widgetOffset2ModelOffset(sourceViewer, selection.x); - int offset2 = widgetOffset2ModelOffset(sourceViewer, selection.y); - String text = null; - if (offset1 != offset2) - text = "[" + offset1 + "-" + offset2 + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - else - text = "[ " + offset1 + " ]"; //$NON-NLS-1$ //$NON-NLS-2$ - field.setText(text == null ? fErrorLabel : text); - } - } - } - - public Annotation gotoAnnotation(boolean forward) { - Annotation result = super.gotoAnnotation(forward); - if(result != null) - fSelectionChangedFromGoto = true; - return result; - } - - void updateStatusLine(ISelection selection) { - // Bug 210481 - Don't update the status line if the selection - // was caused by go to navigation - if(fSelectionChangedFromGoto) { - fSelectionChangedFromGoto = false; - return; - } - IStatusLineManager statusLineManager = getEditorSite().getActionBars().getStatusLineManager(); - if (fStatusLineLabelProvider != null && statusLineManager != null) { - String text = null; - Image image = null; - if (selection instanceof IStructuredSelection && !selection.isEmpty()) { - Object firstElement = ((IStructuredSelection) selection).getFirstElement(); - if (firstElement != null) { - text = fStatusLineLabelProvider.getText(firstElement); - image = fStatusLineLabelProvider.getImage((firstElement)); - } - } - if (image == null) { - statusLineManager.setMessage(text); - } - else { - statusLineManager.setMessage(image, text); - } - } - } - - /** - * Returns the signed current selection. - * The length will be negative if the resulting selection - * is right-to-left (RtoL). - * <p> - * The selection offset is model based. - * </p> - * - * @param sourceViewer the source viewer - * @return a region denoting the current signed selection, for a resulting RtoL selections length is < 0 - */ - 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); - } - - protected SourceViewerDecorationSupport getSourceViewerDecorationSupport(ISourceViewer viewer) { - /* Removed workaround for Bug [206913] source annotations are not painting in source editors. - * With the new presentation reconciler, we no longer need to force the painting. This - * actually caused Bug [219776] Wrong annotation display on macs. We forced the - * Squiggles strategy, even when the native problem underline was specified for annotations */ - return super.getSourceViewerDecorationSupport(viewer); - } - - private void installCharacterPairing() { - IStructuredModel model = getInternalModel(); - if (model != null) { - IConfigurationElement[] elements = Platform.getExtensionRegistry().getConfigurationElementsFor(SSEUIPlugin.ID, "characterPairing"); //$NON-NLS-1$ - IContentTypeManager mgr = Platform.getContentTypeManager(); - IContentType type = mgr.getContentType(model.getContentTypeIdentifier()); - if (type != null) { - for (int i = 0; i < elements.length; i++) { - // Create the inserter - IConfigurationElement element = elements[i]; - try { - IConfigurationElement[] contentTypes = element.getChildren("contentTypeIdentifier"); - for (int j = 0; j < contentTypes.length; j++) { - String id = contentTypes[j].getAttribute("id"); - if (id != null) { - IContentType targetType = mgr.getContentType(id); - int priority = calculatePriority(type, targetType, 0); - if (priority >= 0) { - final CharacterPairing pairing = new CharacterPairing(); - pairing.priority = priority; - String[] partitions = StringUtils.unpack(contentTypes[j].getAttribute("partitions")); - pairing.partitions = new HashSet(partitions.length); - // Only add the inserter if there is at least one partition for the content type - for (int k = 0; k < partitions.length; k++) { - pairing.partitions.add(partitions[k]); - } - - pairing.inserter = (AbstractCharacterPairInserter) element.createExecutableExtension("class"); - if (pairing.inserter != null && partitions.length > 0) { - fPairInserter.addInserter(pairing); - /* use a SafeRunner since this method is also invoked during Part creation */ - SafeRunner.run(new ISafeRunnable() { - public void run() throws Exception { - pairing.inserter.initialize(); - } - - public void handleException(Throwable exception) { - // rely on default logging - } - }); - } - } - } - } - } catch (CoreException e) { - Logger.logException(e); - } - } - fPairInserter.prioritize(); - } - } - } - - /** - * Calculates the priority of the target content type. The closer <code>targetType</code> - * is to <code>type</code> the higher its priority. - * - * @param type - * @param targetType - * @param priority - * @return - */ - private int calculatePriority(IContentType type, IContentType targetType, int priority) { - if (type == null || targetType == null) - return -1; - if (type.getId().equals(targetType.getId())) - return priority; - return calculatePriority(type.getBaseType(), targetType, ++priority); - } - - /** - * Installs semantic highlighting on the editor - */ - private void installSemanticHighlighting() { - IStructuredModel model = getInternalModel(); - if (fSemanticManager == null && model != null) { - fSemanticManager = new SemanticHighlightingManager(); - fSemanticManager.install(getSourceViewer(), getPreferenceStore(), getSourceViewerConfiguration(), model.getContentTypeIdentifier()); - } - } - - /** - * Uninstalls semantic highlighting on the editor and performs cleanup - */ - private void uninstallSemanticHighlighting() { - if (fSemanticManager != null) { - fSemanticManager.uninstall(); - fSemanticManager = null; - } - } - - private IInformationPresenter configureOutlinePresenter(ISourceViewer sourceViewer, SourceViewerConfiguration config) { - InformationPresenter presenter = null; - - // Get the quick outline configuration - AbstractQuickOutlineConfiguration cfg = null; - ExtendedConfigurationBuilder builder = ExtendedConfigurationBuilder.getInstance(); - String[] ids = getConfigurationPoints(); - for (int i = 0; cfg == null && i < ids.length; i++) { - cfg = (AbstractQuickOutlineConfiguration) builder.getConfiguration(ExtendedConfigurationBuilder.QUICKOUTLINECONFIGURATION, ids[i]); - } - - if (cfg != null) { - presenter = new InformationPresenter(getOutlinePresenterControlCreator(cfg)); - presenter.setDocumentPartitioning(config.getConfiguredDocumentPartitioning(sourceViewer)); - presenter.setAnchor(AbstractInformationControlManager.ANCHOR_GLOBAL); - IInformationProvider provider = new SourceInfoProvider(this); - String[] contentTypes = config.getConfiguredContentTypes(sourceViewer); - for (int i = 0; i < contentTypes.length; i++) { - presenter.setInformationProvider(provider, contentTypes[i]); - } - presenter.setSizeConstraints(50, 20, true, false); - } - return presenter; - } - - /** - * Returns the outline presenter control creator. The creator is a - * factory creating outline presenter controls for the given source viewer. - * - * @param sourceViewer the source viewer to be configured by this configuration - * @return an information control creator - */ - private IInformationControlCreator getOutlinePresenterControlCreator(final AbstractQuickOutlineConfiguration config) { - return new IInformationControlCreator() { - public IInformationControl createInformationControl(Shell parent) { - int shellStyle = SWT.RESIZE; - return new QuickOutlinePopupDialog(parent, shellStyle, getInternalModel(), config); - } - }; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/StructuredTextInvocationContext.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/StructuredTextInvocationContext.java deleted file mode 100644 index 241265c248..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/StructuredTextInvocationContext.java +++ /dev/null @@ -1,53 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui; - -import java.util.Map; - -import org.eclipse.jface.text.source.ISourceViewer; -import org.eclipse.jface.text.source.TextInvocationContext; - -/** - * Provisional API: This class/interface is part of an interim API that is - * still under development and expected to change significantly before - * reaching stability. It is being made available at this early stage to - * solicit feedback from pioneering adopters on the understanding that any - * code that uses this API will almost certainly be broken (repeatedly) as the - * API evolves. - * - * This class is not intended to be instantiated by clients. - * - * Structured Text quick assist invocation context. - */ -public final class StructuredTextInvocationContext extends TextInvocationContext { - private Map fAttributes; - - /** - * @param sourceViewer - * @param offset - * @param length - * @param attributes - */ - public StructuredTextInvocationContext(ISourceViewer sourceViewer, int offset, int length, Map attributes) { - super(sourceViewer, offset, length); - fAttributes = attributes; - } - - /** - * @param attributeName - * @return the value of this attribute, or <tt>null</tt> when no such - * attribute is defined or that attribute's value has been set to - * <tt>null</tt> - */ - public Object getAttribute(String attributeName) { - return (fAttributes != null ? fAttributes.get(attributeName) : null); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/StructuredTextMultiPassContentFormatter.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/StructuredTextMultiPassContentFormatter.java deleted file mode 100644 index 88d48e5c97..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/StructuredTextMultiPassContentFormatter.java +++ /dev/null @@ -1,123 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui; - -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.TypedPosition; -import org.eclipse.jface.text.formatter.FormattingContextProperties; -import org.eclipse.jface.text.formatter.IFormattingContext; -import org.eclipse.jface.text.formatter.IFormattingStrategy; -import org.eclipse.jface.text.formatter.MultiPassContentFormatter; -import org.eclipse.wst.sse.core.internal.Logger; -import org.eclipse.wst.sse.ui.internal.ExtendedConfigurationBuilder; - -/** - * Extends the MultiPassContentFormatter to allow clients to contribute - * additional slave formatting strategies via the - * <code>org.eclipse.wst.sse.ui.editorConfiguration</code> extension point - */ -class StructuredTextMultiPassContentFormatter extends MultiPassContentFormatter { - /** - * The value of "type" attribute in the provisionalConfiguration element - */ - private static final String SLAVE_FORMATTING_STRATEGY_EXTENDED_ID = "slaveformattingstrategy"; //$NON-NLS-1$ - /** - * list of partition types that already have a formatting strategy - */ - private List fInstalledPartitionTypes; - - /** - * Creates a new content formatter. - * - * @param partitioning - * the document partitioning for this formatter - * @param type - * the default content type - */ - public StructuredTextMultiPassContentFormatter(final String partitioning, final String type) { - super(partitioning, type); - } - - protected void formatMaster(IFormattingContext context, IDocument document, int offset, int length) { - // for debugging purposes - long startTime = System.currentTimeMillis(); - - super.formatMaster(context, document, offset, length); - - if (Logger.DEBUG_FORMAT) { - long endTime = System.currentTimeMillis(); - System.out.println("formatModel time: " + (endTime - startTime)); //$NON-NLS-1$ - } - } - - /* - * Overwritten to check for additional slave formatting strategies - * contributed via the editorConfiguration extension point. - */ - protected void formatSlave(IFormattingContext context, IDocument document, int offset, int length, String type) { - List installedTypes = getInstalledPartitionTypes(); - if (installedTypes.contains(type)) { - // we've already set the slave formatter strategy so just perform - // as normal - super.formatSlave(context, document, offset, length, type); - } - else { - boolean findExtendedSlaveFormatter = true; - - // need to figure out if there's already a slave formatter set, so - // just attempt to format as normal - super.formatSlave(context, document, offset, length, type); - - // now, determine if slave formatter was already set by checking - // context (it would be set if there's already one) - Object contextPartition = context.getProperty(FormattingContextProperties.CONTEXT_PARTITION); - if (contextPartition instanceof TypedPosition) { - String contextType = ((TypedPosition) contextPartition).getType(); - if (contextType == type) { - // there's already a slave formatter set, so just add it - // to the list of installed partition types for future - // reference - installedTypes.add(type); - findExtendedSlaveFormatter = false; - } - } - // no slave formatter is set yet, so try to find one contributed - // via the editorConfiguration extension point - if (findExtendedSlaveFormatter) { - Object configuration = ExtendedConfigurationBuilder.getInstance().getConfiguration(SLAVE_FORMATTING_STRATEGY_EXTENDED_ID, type); - if (configuration instanceof IFormattingStrategy) { - // found a formatter, so add it in - setSlaveStrategy((IFormattingStrategy) configuration, type); - // try to format slave again now that one is set - super.formatSlave(context, document, offset, length, type); - } - // note that we've already checked this partition type for - // future reference - installedTypes.add(type); - } - } - } - - /** - * Get the list of partition types that have already been evaluated for - * slave formatting strategies for this formatter. - * - * @return List - */ - private List getInstalledPartitionTypes() { - if (fInstalledPartitionTypes == null) - fInstalledPartitionTypes = new ArrayList(); - return fInstalledPartitionTypes; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/StructuredTextViewerConfiguration.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/StructuredTextViewerConfiguration.java deleted file mode 100644 index 65d733d67c..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/StructuredTextViewerConfiguration.java +++ /dev/null @@ -1,719 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2011 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui; - -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.jface.dialogs.IDialogSettings; -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.preference.PreferenceConverter; -import org.eclipse.jface.text.DefaultInformationControl; -import org.eclipse.jface.text.IAutoEditStrategy; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IDocumentExtension3; -import org.eclipse.jface.text.IDocumentPartitioner; -import org.eclipse.jface.text.IInformationControl; -import org.eclipse.jface.text.IInformationControlCreator; -import org.eclipse.jface.text.ITextDoubleClickStrategy; -import org.eclipse.jface.text.ITextHover; -import org.eclipse.jface.text.IUndoManager; -import org.eclipse.jface.text.contentassist.IContentAssistProcessor; -import org.eclipse.jface.text.contentassist.IContentAssistant; -import org.eclipse.jface.text.formatter.IContentFormatter; -import org.eclipse.jface.text.hyperlink.IHyperlinkPresenter; -import org.eclipse.jface.text.hyperlink.MultipleHyperlinkPresenter; -import org.eclipse.jface.text.information.IInformationPresenter; -import org.eclipse.jface.text.information.IInformationProvider; -import org.eclipse.jface.text.information.InformationPresenter; -import org.eclipse.jface.text.presentation.IPresentationReconciler; -import org.eclipse.jface.text.quickassist.IQuickAssistAssistant; -import org.eclipse.jface.text.quickassist.QuickAssistAssistant; -import org.eclipse.jface.text.reconciler.IReconciler; -import org.eclipse.jface.text.source.Annotation; -import org.eclipse.jface.text.source.IAnnotationHover; -import org.eclipse.jface.text.source.ISourceViewer; -import org.eclipse.jface.viewers.ILabelProvider; -import org.eclipse.swt.SWT; -import org.eclipse.swt.graphics.Color; -import org.eclipse.swt.graphics.RGB; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.IWorkbenchPreferenceConstants; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.editors.text.EditorsUI; -import org.eclipse.ui.editors.text.TextSourceViewerConfiguration; -import org.eclipse.ui.texteditor.ChainedPreferenceStore; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredPartitioning; -import org.eclipse.wst.sse.core.internal.text.rules.StructuredTextPartitioner; -import org.eclipse.wst.sse.ui.contentassist.StructuredContentAssistProcessor; -import org.eclipse.wst.sse.ui.internal.ExtendedConfigurationBuilder; -import org.eclipse.wst.sse.ui.internal.SSEUIPlugin; -import org.eclipse.wst.sse.ui.internal.StructuredTextAnnotationHover; -import org.eclipse.wst.sse.ui.internal.contentassist.StructuredContentAssistant; -import org.eclipse.wst.sse.ui.internal.correction.CompoundQuickAssistProcessor; -import org.eclipse.wst.sse.ui.internal.derived.HTMLTextPresenter; -import org.eclipse.wst.sse.ui.internal.preferences.EditorPreferenceNames; -import org.eclipse.wst.sse.ui.internal.provisional.style.LineStyleProvider; -import org.eclipse.wst.sse.ui.internal.provisional.style.ReconcilerHighlighter; -import org.eclipse.wst.sse.ui.internal.provisional.style.StructuredPresentationReconciler; -import org.eclipse.wst.sse.ui.internal.reconcile.StructuredRegionProcessor; -import org.eclipse.wst.sse.ui.internal.rules.StructuredDocumentDamagerRepairer; -import org.eclipse.wst.sse.ui.internal.taginfo.AnnotationHoverProcessor; -import org.eclipse.wst.sse.ui.internal.taginfo.BestMatchHover; -import org.eclipse.wst.sse.ui.internal.taginfo.ProblemAnnotationHoverProcessor; -import org.eclipse.wst.sse.ui.internal.taginfo.TextHoverManager; -import org.eclipse.wst.sse.ui.internal.util.EditorUtility; - - -/** - * Configuration for the source viewer used by StructuredTextEditor.<br /> - * Note: While ISourceViewer is passed in for each get configuration, clients - * should create a new viewer configuration instance for each instance of - * source viewer as some methods return the same instance of an object, - * regardless of the sourceviewer. - * <p> - * Clients should subclass and override just those methods which must be - * specific to their needs. - * </p> - * - * @see org.eclipse.wst.sse.ui.StructuredTextEditor - * @see org.eclipse.wst.sse.ui.internal.StructuredTextViewer - * @since 1.0 - */ -public class StructuredTextViewerConfiguration extends TextSourceViewerConfiguration { - /** - * One instance per configuration because creating a second assistant that - * is added to a viewer can cause odd key-eating by the wrong one. - */ - private StructuredContentAssistant fContentAssistant = null; - - /* - * One instance per configuration because it's just like content assistant - */ - private IQuickAssistAssistant fQuickAssistant = null; - /* - * One instance per configuration - */ - private IReconciler fReconciler; - /** - * Extended configuration provisionalConfiguration type to contribute - * additional auto edit strategies - */ - private final String AUTOEDITSTRATEGY = "autoeditstrategy"; //$NON-NLS-1$ - - private final String CONTENT_ASSIST_SIZE = "contentassistsize"; - - private ReconcilerHighlighter fHighlighter = null; - - /** - * Creates a structured text viewer configuration. - */ - public StructuredTextViewerConfiguration() { - super(); - // initialize fPreferenceStore with same preference store used in - // StructuredTextEditor - fPreferenceStore = createCombinedPreferenceStore(); - } - - /** - * Create a preference store that combines the source editor preferences - * with the base editor's preferences. - * - * @return IPreferenceStore - */ - private IPreferenceStore createCombinedPreferenceStore() { - IPreferenceStore sseEditorPrefs = SSEUIPlugin.getDefault().getPreferenceStore(); - IPreferenceStore baseEditorPrefs = EditorsUI.getPreferenceStore(); - return new ChainedPreferenceStore(new IPreferenceStore[]{sseEditorPrefs, baseEditorPrefs}); - } - - /** - * Note: Clients cannot override this method because this method returns a - * specially configured Annotation Hover for the StructuredTextViewer - * - * (non-Javadoc) - * @see org.eclipse.ui.editors.text.TextSourceViewerConfiguration#getAnnotationHover(org.eclipse.jface.text.source.ISourceViewer) - */ - final public IAnnotationHover getAnnotationHover(ISourceViewer sourceViewer) { - return new StructuredTextAnnotationHover() { - protected boolean isIncluded(Annotation annotation) { - return isShowInVerticalRuler(annotation); - } - }; - } - - /** - * Get color for the preference key. Assumes fPreferenceStore is not null. - * - * @param key - * @return Color for preference key or null if none found - */ - private Color getColor(String key) { - RGB rgb = PreferenceConverter.getColor(fPreferenceStore, key); - return EditorUtility.getColor(rgb); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.source.SourceViewerConfiguration#getAutoEditStrategies(org.eclipse.jface.text.source.ISourceViewer, java.lang.String) - */ - public IAutoEditStrategy[] getAutoEditStrategies(ISourceViewer sourceViewer, String contentType) { - List allStrategies = new ArrayList(0); - - IAutoEditStrategy[] superStrategies = super.getAutoEditStrategies(sourceViewer, contentType); - for (int i = 0; i < superStrategies.length; i++) { - allStrategies.add(superStrategies[i]); - } - - // add auto edit strategies contributed by clients - List extendedAutoEdits = ExtendedConfigurationBuilder.getInstance().getConfigurations(AUTOEDITSTRATEGY, contentType); - if (!extendedAutoEdits.isEmpty()) { - allStrategies.addAll(extendedAutoEdits); - } - - return (IAutoEditStrategy[]) allStrategies.toArray(new IAutoEditStrategy[allStrategies.size()]); - } - - /** - * Returns the configured partitioning for the given source viewer. The - * partitioning is used when the querying content types from the source - * viewer's input document.<br /> - * Note: Clients cannot override this method at this time. - * - * @param sourceViewer - * the source viewer to be configured by this configuration - * @return the configured partitioning - * @see #getConfiguredContentTypes(ISourceViewer) - */ - final public String getConfiguredDocumentPartitioning(ISourceViewer sourceViewer) { - /* - * This implementation returns default structured text partitioning - */ - return IStructuredPartitioning.DEFAULT_STRUCTURED_PARTITIONING; - } - - public int[] getConfiguredTextHoverStateMasks(ISourceViewer sourceViewer, String contentType) { - /* - * This implementation returns configured text hover state masks for - * StructuredTextViewers - */ - TextHoverManager.TextHoverDescriptor[] hoverDescs = SSEUIPlugin.getDefault().getTextHoverManager().getTextHovers(); - int stateMasks[] = new int[hoverDescs.length]; - int stateMasksLength = 0; - for (int i = 0; i < hoverDescs.length; i++) { - if (hoverDescs[i].isEnabled()) { - int j = 0; - int stateMask = computeStateMask(hoverDescs[i].getModifierString()); - while (j < stateMasksLength) { - if (stateMasks[j] == stateMask) - break; - j++; - } - if (j == stateMasksLength) - stateMasks[stateMasksLength++] = stateMask; - } - } - if (stateMasksLength == hoverDescs.length) - return stateMasks; - - int[] shortenedStateMasks = new int[stateMasksLength]; - System.arraycopy(stateMasks, 0, shortenedStateMasks, 0, stateMasksLength); - return shortenedStateMasks; - } - - /** - * Returns the content assistant ready to be used with the given source - * viewer.<br /> - * Note: The same instance of IContentAssistant is returned regardless of - * the source viewer passed in. - * <p> - * Clients should generally not override this method. Instead, clients - * wanting to add their own processors should override - * <code>getContentAssistProcessors(ISourceViewer, String)</code> - * </p> - * - * @param sourceViewer - * the source viewer to be configured by this configuration - * @return a content assistant - * @see #getContentAssistProcessors(ISourceViewer, String) - */ - public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) { - /* - * Note: This method was made final so that StructuredContentAssist is - * always used and content assist extension point always works. - */ - if (fContentAssistant == null) { - fContentAssistant = new StructuredContentAssistant(); - - // content assistant configurations - fContentAssistant.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer)); - fContentAssistant.enableAutoActivation(true); - fContentAssistant.setProposalPopupOrientation(IContentAssistant.PROPOSAL_OVERLAY); - fContentAssistant.setContextInformationPopupOrientation(IContentAssistant.CONTEXT_INFO_ABOVE); - fContentAssistant.setInformationControlCreator(getInformationControlCreator(sourceViewer)); - fContentAssistant.enableColoredLabels(PlatformUI.getPreferenceStore().getBoolean(IWorkbenchPreferenceConstants.USE_COLORED_LABELS)); - - // set content assist preferences - if (fPreferenceStore != null) { - int delay = fPreferenceStore.getInt(EditorPreferenceNames.CODEASSIST_AUTOACTIVATION_DELAY); - fContentAssistant.setAutoActivationDelay(delay); - - Color color = getColor(EditorPreferenceNames.CODEASSIST_PROPOSALS_BACKGROUND); - fContentAssistant.setProposalSelectorBackground(color); - - color = getColor(EditorPreferenceNames.CODEASSIST_PROPOSALS_FOREGROUND); - fContentAssistant.setProposalSelectorForeground(color); - - color = getColor(EditorPreferenceNames.CODEASSIST_PARAMETERS_BACKGROUND); - fContentAssistant.setContextInformationPopupBackground(color); - fContentAssistant.setContextSelectorBackground(color); - - color = getColor(EditorPreferenceNames.CODEASSIST_PARAMETERS_FOREGROUND); - fContentAssistant.setContextInformationPopupForeground(color); - fContentAssistant.setContextSelectorForeground(color); - } - - // add content assist processors for each partition type - String[] types = getConfiguredContentTypes(sourceViewer); - for (int i = 0; i < types.length; i++) { - String type = types[i]; - - // add all content assist processors for current partiton type - IContentAssistProcessor[] processors = getContentAssistProcessors(sourceViewer, type); - if (processors != null) { - for (int j = 0; j < processors.length; j++) { - fContentAssistant.setContentAssistProcessor(processors[j], type); - } - } - } - IDialogSettings dialogSettings = SSEUIPlugin.getInstance().getDialogSettings(); - if(dialogSettings != null) { - IDialogSettings section = dialogSettings.getSection(CONTENT_ASSIST_SIZE); - if(section == null) { - section = dialogSettings.addNewSection(CONTENT_ASSIST_SIZE); - } - fContentAssistant.setRestoreCompletionProposalSize(section); - } - } - return fContentAssistant; - } - - /** - * <p>Returns a {@link StructuredContentAssistProcessor} which can be contributed to through - * the <tt>org.eclipse.wst.sse.ui.completionProposal</tt> extension point.</p> - * - * <p>If an extender of this class overrides this method and does not include an - * implementation of a {@link StructuredContentAssistProcessor} in their returned - * processors then all of the contributions by the aforementioned extension point - * will be left out.</p> - * - * @param sourceViewer - * the source viewer to be configured by this configuration - * @param partitionType - * the partition type for which the content assist processors - * are applicable - * @return IContentAssistProcessors or null if should not be supported - */ - protected IContentAssistProcessor[] getContentAssistProcessors(ISourceViewer sourceViewer, String partitionType) { - IContentAssistProcessor processor = new StructuredContentAssistProcessor( - fContentAssistant, partitionType, sourceViewer, null); - return new IContentAssistProcessor[]{processor}; - } - - /** - * Returns the content formatter ready to be used with the given source - * viewer. - * <p> - * It is not recommended that clients override this method as it may - * become <code>final</code> in the future and replaced by an extensible - * framework. - * </p> - * - * @param sourceViewer - * the source viewer to be configured by this configuration - * @return a content formatter or <code>null</code> if formatting should - * not be supported - */ - public IContentFormatter getContentFormatter(ISourceViewer sourceViewer) { - // try to use the StructuredTextMultiPassContentFormatter so that it - // picks up any additional formatting strategies contributed via the - // editorConfiguration extension point - IContentFormatter formatter = null; - if (sourceViewer != null) { - IDocument document = sourceViewer.getDocument(); - if (document instanceof IDocumentExtension3) { - String partitioning = getConfiguredDocumentPartitioning(sourceViewer); - IDocumentPartitioner partitioner = ((IDocumentExtension3) document).getDocumentPartitioner(partitioning); - if (partitioner instanceof StructuredTextPartitioner) { - String defaultPartitionType = ((StructuredTextPartitioner) partitioner).getDefaultPartitionType(); - formatter = new StructuredTextMultiPassContentFormatter(partitioning, defaultPartitionType); - } - } - } - - return formatter; - } - - /** - * Returns the double-click strategy ready to be used in this viewer when - * double clicking onto text of the given content type. Note that if - * clients want to contribute their own doubleclick strategy, they should - * use <code>org.eclipse.wst.sse.ui.editorConfiguration</code> extension - * point's <code>doubleClickStrategy</code> element instead of - * overriding this method. If clients do override this method, please - * remember to call <code>super.getDoubleClickStrategy()</code>. - * - * @param sourceViewer - * the source viewer to be configured by this configuration - * @param contentType - * the content type for which the strategy is applicable - * @return a double-click strategy or <code>null</code> if double - * clicking should not be supported - */ - public ITextDoubleClickStrategy getDoubleClickStrategy(ISourceViewer sourceViewer, String contentType) { - ITextDoubleClickStrategy strategy = null; - Object extendedStrategy = ExtendedConfigurationBuilder.getInstance().getConfiguration(ExtendedConfigurationBuilder.DOUBLECLICKSTRATEGY, contentType); - if (extendedStrategy instanceof ITextDoubleClickStrategy) { - strategy = (ITextDoubleClickStrategy) extendedStrategy; - } - else { - strategy = super.getDoubleClickStrategy(sourceViewer, contentType); - } - return strategy; - } - - /** - * Returns the hyperlink presenter for the given source viewer.<br /> - * Note: Clients cannot override this method, and although it's no longer - * necessary, it must remain for binary compatibility. - * - * @param sourceViewer - * the source viewer to be configured by this configuration - * @return a hyperlink presenter specially configured for - * StructuredTextViewer - */ - final public IHyperlinkPresenter getHyperlinkPresenter(ISourceViewer sourceViewer) { - if (fPreferenceStore == null) { - return super.getHyperlinkPresenter(sourceViewer); - } - return new MultipleHyperlinkPresenter(fPreferenceStore); - } - - /** - * Returns the information control creator. The creator is a factory - * creating information controls for the given source viewer.<br /> - * Note: Clients cannot override this method at this time. - * - * @param sourceViewer - * the source viewer to be configured by this configuration - * @return the information control creator - */ - final public IInformationControlCreator getInformationControlCreator(ISourceViewer sourceViewer) { - // used by hover help - return new IInformationControlCreator() { - public IInformationControl createInformationControl(Shell parent) { - return new DefaultInformationControl(parent, new HTMLTextPresenter(true)); - } - }; - } - - /** - * Returns the information presenter ready to be used with the given - * source viewer. - * <p> - * Clients cannot override this method. Instead, clients wanting to add - * their own information providers should override - * <code>getInformationProvider(ISourceViewer, String)</code> - * </p> - * - * @param sourceViewer - * the source viewer to be configured by this configuration - * @return a content assistant - * @see #getInformationProvider(ISourceViewer, String) - */ - final public IInformationPresenter getInformationPresenter(ISourceViewer sourceViewer) { - InformationPresenter presenter = new InformationPresenter(getInformationPresenterControlCreator(sourceViewer)); - - // information presenter configurations - presenter.setSizeConstraints(60, 10, true, true); - presenter.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer)); - - // add information providers for each partition type - String[] types = getConfiguredContentTypes(sourceViewer); - for (int i = 0; i < types.length; i++) { - String type = types[i]; - - IInformationProvider provider = getInformationProvider(sourceViewer, type); - if (provider != null) { - presenter.setInformationProvider(provider, type); - } - } - - return presenter; - } - - /** - * Returns the information provider that will be used for information - * presentation in the given source viewer and for the given partition - * type. - * - * @param sourceViewer - * the source viewer to be configured by this configuration - * @param partitionType - * the partition type for which the information provider is - * applicable - * @return IInformationProvider or null if should not be supported - * @deprecated instead of overriding this method to provide documentation - * information, adopters should use the - * <code>documentationTextHover</code> element in the - * <code>org.eclipse.wst.sse.ui.editorConfiguration</code> - * extension point - */ - protected IInformationProvider getInformationProvider(ISourceViewer sourceViewer, String partitionType) { - ITextHover bestMatchHover = new BestMatchHover(partitionType); - return new TextHoverInformationProvider(bestMatchHover); - } - - /** - * Returns the information presenter control creator. The creator is a - * factory creating the presenter controls for the given source viewer. - * - * @param sourceViewer - * the source viewer to be configured by this configuration - * @return an information control creator - */ - private IInformationControlCreator getInformationPresenterControlCreator(ISourceViewer sourceViewer) { - return new IInformationControlCreator() { - public IInformationControl createInformationControl(Shell parent) { - int shellStyle = SWT.RESIZE | SWT.TOOL; - int style = SWT.V_SCROLL | SWT.H_SCROLL; - return new DefaultInformationControl(parent, shellStyle, style, new HTMLTextPresenter(false)); - } - }; - } - - /** - * Returns the line style providers that will be used for syntax - * highlighting in the given source viewer. - * <p> - * Not fully API since return type LineStyleProvider is not API. - * </p> - * - * @param sourceViewer - * the source viewer to be configured by this configuration - * @param partitionType - * the partition type for which the lineStyleProviders are - * applicable - * @return LineStyleProvders or null if should not be supported - */ - public LineStyleProvider[] getLineStyleProviders(ISourceViewer sourceViewer, String partitionType) { - return null; - } - - /** - * See <code>getLineStyleProviders(ISourceViewer, String)</code> for - * alternative way to provide highlighting information. - * - * @param sourceViewer - * the source viewer to be configured by this configuration - * @return always returns null - * @see #getLineStyleProviders(ISourceViewer, String) - */ - public IPresentationReconciler getPresentationReconciler(ISourceViewer sourceViewer) { - StructuredPresentationReconciler reconciler = new StructuredPresentationReconciler(); - reconciler.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer)); - - String[] contentTypes = getConfiguredContentTypes(sourceViewer); - - if(contentTypes != null) { - StructuredDocumentDamagerRepairer dr = null; - - for (int i = 0; i < contentTypes.length; i++) { - if (fHighlighter != null) { - LineStyleProvider provider = fHighlighter.getProvider(contentTypes[i]); - if (provider == null) - continue; - - dr = new StructuredDocumentDamagerRepairer(provider); - dr.setDocument(sourceViewer.getDocument()); - reconciler.setDamager(dr, contentTypes[i]); - reconciler.setRepairer(dr, contentTypes[i]); - } - } - } - - return reconciler; - } - - /* (non-Javadoc) - * @see org.eclipse.ui.editors.text.TextSourceViewerConfiguration#getOverviewRulerAnnotationHover(org.eclipse.jface.text.source.ISourceViewer) - */ - public IAnnotationHover getOverviewRulerAnnotationHover(ISourceViewer sourceViewer) { - return new StructuredTextAnnotationHover(true) { - protected boolean isIncluded(Annotation annotation) { - return isShowInOverviewRuler(annotation); - } - }; - } - - /* - * @see org.eclipse.jface.text.source.SourceViewerConfiguration#getQuickAssistAssistant(org.eclipse.jface.text.source.ISourceViewer) - */ - public IQuickAssistAssistant getQuickAssistAssistant(ISourceViewer sourceViewer) { - if (fQuickAssistant == null) { - IQuickAssistAssistant assistant = new QuickAssistAssistant(); - assistant.setQuickAssistProcessor(new CompoundQuickAssistProcessor()); - assistant.setInformationControlCreator(getQuickAssistAssistantInformationControlCreator()); - - // Waiting for color preferences, see: - // https://bugs.eclipse.org/bugs/show_bug.cgi?id=133731 - // set content assist preferences - if (fPreferenceStore != null) { - Color color = getColor(EditorPreferenceNames.CODEASSIST_PROPOSALS_BACKGROUND); - assistant.setProposalSelectorBackground(color); - - color = getColor(EditorPreferenceNames.CODEASSIST_PROPOSALS_FOREGROUND); - assistant.setProposalSelectorForeground(color); - } - fQuickAssistant = assistant; - } - return fQuickAssistant; - } - - /** - * Returns the information control creator for the quick assist assistant. - * - * @return the information control creator - */ - private IInformationControlCreator getQuickAssistAssistantInformationControlCreator() { - return new IInformationControlCreator() { - public IInformationControl createInformationControl(Shell parent) { - return new DefaultInformationControl(parent, new HTMLTextPresenter(true)); - } - }; - } - - /** - * Returns the reconciler ready to be used with the given source viewer.<br /> - * Note: The same instance of IReconciler is returned regardless of the - * source viewer passed in. - * <p> - * Clients cannot override this method. Instead, clients wanting to add - * their own reconciling strategy should use the - * <code>org.eclipse.wst.sse.ui.extensions.sourcevalidation</code> - * extension point. - * </p> - * - * @param sourceViewer - * the source viewer to be configured by this configuration - * @return a reconciler - */ - final public IReconciler getReconciler(ISourceViewer sourceViewer) { - IReconciler reconciler = null; - - if (sourceViewer != null) { - //Only create reconciler if sourceViewer is present - if (fReconciler == null && sourceViewer != null) { - StructuredRegionProcessor newReconciler = new StructuredRegionProcessor(); - - // reconciler configurations - newReconciler.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer)); - - fReconciler = newReconciler; - } - reconciler = fReconciler; - } - - return reconciler; - } - - /** - * @since 2.0 - * @param treeViewer - * @return a label provider providing the status line contents - */ - public ILabelProvider getStatusLineLabelProvider(ISourceViewer sourceViewer) { - return null; - } - - /** - * Create documentation hovers based on hovers contributed via - * <code>org.eclipse.wst.sse.ui.editorConfiguration</code> extension - * point - * - * @param partitionType - * @return - */ - private ITextHover[] createDocumentationHovers(String partitionType) { - List extendedTextHover = ExtendedConfigurationBuilder.getInstance().getConfigurations(ExtendedConfigurationBuilder.DOCUMENTATIONTEXTHOVER, partitionType); - ITextHover[] hovers = (ITextHover[]) extendedTextHover.toArray(new ITextHover[extendedTextHover.size()]); - return hovers; - } - - public ITextHover getTextHover(ISourceViewer sourceViewer, String contentType, int stateMask) { - ITextHover textHover = null; - - /* - * Returns a default problem, annotation, and best match hover - * depending on stateMask - */ - TextHoverManager.TextHoverDescriptor[] hoverDescs = SSEUIPlugin.getDefault().getTextHoverManager().getTextHovers(); - int i = 0; - while (i < hoverDescs.length && textHover == null) { - if (hoverDescs[i].isEnabled() && computeStateMask(hoverDescs[i].getModifierString()) == stateMask) { - String hoverType = hoverDescs[i].getId(); - if (TextHoverManager.PROBLEM_HOVER.equalsIgnoreCase(hoverType)) - textHover = new ProblemAnnotationHoverProcessor(); - else if (TextHoverManager.ANNOTATION_HOVER.equalsIgnoreCase(hoverType)) - textHover = new AnnotationHoverProcessor(); - else if (TextHoverManager.COMBINATION_HOVER.equalsIgnoreCase(hoverType)) - textHover = new BestMatchHover(contentType); - else if (TextHoverManager.DOCUMENTATION_HOVER.equalsIgnoreCase(hoverType)) { - ITextHover[] hovers = createDocumentationHovers(contentType); - if (hovers.length > 0) { - textHover = hovers[0]; - } - } - } - i++; - } - return textHover; - } - - /** - * Returns the undo manager for the given source viewer.<br /> - * Note: Clients cannot override this method because this method returns a - * specially configured undo manager for the StructuredTextViewer. - * - * @param sourceViewer - * the source viewer to be configured by this configuration - * @return an undo manager specially configured for StructuredTextViewer - */ - final public IUndoManager getUndoManager(ISourceViewer sourceViewer) { - /* - * This implementation returns an UndoManager that is used exclusively - * in StructuredTextViewer - */ - return new StructuredTextViewerUndoManager(); - } - - public void setHighlighter(ReconcilerHighlighter highlighter) { - fHighlighter = highlighter; - } - - /** - * @return the associated content assistnat - */ - protected StructuredContentAssistant getContentAssistant() { - return this.fContentAssistant; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/StructuredTextViewerUndoManager.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/StructuredTextViewerUndoManager.java deleted file mode 100644 index 1564bc57da..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/StructuredTextViewerUndoManager.java +++ /dev/null @@ -1,200 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui; - -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.ITextSelection; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.IUndoManager; -import org.eclipse.jface.viewers.ISelectionChangedListener; -import org.eclipse.jface.viewers.SelectionChangedEvent; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument; -import org.eclipse.wst.sse.core.internal.undo.IStructuredTextUndoManager; -import org.eclipse.wst.sse.ui.internal.StructuredTextViewer; - - -/** - * Undo manager exclusively for StructuredTextViewers ONLY. This undo manager - * is aware that structured documents have their own undo manager. This - * handles communication between IUndoManager and IStructuredTextUndoManager. - */ -class StructuredTextViewerUndoManager implements IUndoManager { - class UndoNotifier implements ISelectionChangedListener { - public void selectionChanged(SelectionChangedEvent event) { - if ((fUndoManager != null) && (event != null)) { - if (event.getSelection() instanceof ITextSelection) { - fUndoManager.forceEndOfPendingCommand(this, ((ITextSelection) event.getSelection()).getOffset(), ((ITextSelection) event.getSelection()).getLength()); - } - } - } - - } - - private StructuredTextViewer fTextViewer = null; - private IStructuredTextUndoManager fUndoManager = null; - private ISelectionChangedListener fUndoNotifier = new UndoNotifier(); - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.text.IUndoManager#beginCompoundChange() - */ - public void beginCompoundChange() { - // forward the request to the model-based undo manager - if (fUndoManager != null) - fUndoManager.beginRecording(fTextViewer); - } - - /** - * Associates a viewer to this undo manager and also attempts to get the - * correct document-specific undo manager. - * - * @param viewer - - * Assumes viewer instanceof StructuredTextViewer - */ - public void connect(ITextViewer viewer) { - // future_TODO could probably optimize this to check if already - // connected to same viewer/undo manager, dont do anything - - // disconnect from any old manager/viewer - disconnect(); - - // connect to new viewer/undo manager - fTextViewer = (StructuredTextViewer) viewer; - IDocument doc = fTextViewer.getDocument(); - if (doc instanceof IStructuredDocument) { - IStructuredDocument structuredDocument = (IStructuredDocument) doc; - setDocument(structuredDocument); - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.text.IUndoManager#disconnect() - */ - public void disconnect() { - // disconnect the viewer from the undo manager - if (fUndoManager != null) { - fTextViewer.removeSelectionChangedListener(fUndoNotifier); - fUndoManager.disconnect(fTextViewer); - } - - // null out the viewer and undo manager - fTextViewer = null; - fUndoManager = null; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.text.IUndoManager#endCompoundChange() - */ - public void endCompoundChange() { - // forward the request to the model-based undo manager - if (fUndoManager != null) - fUndoManager.endRecording(fTextViewer); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.text.IUndoManager#redo() - */ - public void redo() { - // forward the request to the model-based undo manager - if (fUndoManager != null) - fUndoManager.redo(fTextViewer); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.text.IUndoManager#redoable() - */ - public boolean redoable() { - boolean canRedo = false; - - // forward the request to the model-based undo manager - if (fUndoManager != null) - canRedo = fUndoManager.redoable(); - - return canRedo; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.text.IUndoManager#reset() - */ - public void reset() { - // cannot really reset model-based undo manager because other clients - // will be affected - } - - /** - * Disconnect from the old undo manager and connect to the undo manager - * associated with the new document. - * - * @param document - - * assumes document is not null - */ - public void setDocument(IStructuredDocument document) { - if (fUndoManager != null) { - fTextViewer.removeSelectionChangedListener(fUndoNotifier); - fUndoManager.disconnect(fTextViewer); - } - - fUndoManager = document.getUndoManager(); - if (fUndoManager != null) { - fUndoManager.connect(fTextViewer); - fTextViewer.addSelectionChangedListener(fUndoNotifier); - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.text.IUndoManager#setMaximalUndoLevel(int) - */ - public void setMaximalUndoLevel(int undoLevel) { - // cannot really set maximal undo level on model-based undo manager - // because other clients will be affected - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.text.IUndoManager#undo() - */ - public void undo() { - // forward the request to the model-based undo manager - if (fUndoManager != null) - fUndoManager.undo(fTextViewer); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.text.IUndoManager#undoable() - */ - public boolean undoable() { - boolean canUndo = false; - - // forward the request to the model-based undo manager - if (fUndoManager != null) - canUndo = fUndoManager.undoable(); - - return canUndo; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/TextHoverInformationProvider.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/TextHoverInformationProvider.java deleted file mode 100644 index b6e2c1f564..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/TextHoverInformationProvider.java +++ /dev/null @@ -1,43 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui; - -import org.eclipse.jface.text.IInformationControlCreator; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ITextHover; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.information.IInformationProvider; -import org.eclipse.jface.text.information.IInformationProviderExtension; -import org.eclipse.jface.text.information.IInformationProviderExtension2; - -class TextHoverInformationProvider implements IInformationProvider, IInformationProviderExtension, IInformationProviderExtension2 { - private ITextHover fTextHover; - - public TextHoverInformationProvider(ITextHover hover) { - fTextHover = hover; - } - - public String getInformation(ITextViewer textViewer, IRegion subject) { - return (String) getInformation2(textViewer, subject); - } - - public Object getInformation2(ITextViewer textViewer, IRegion subject) { - return fTextHover.getHoverInfo(textViewer, subject); - } - - public IInformationControlCreator getInformationPresenterControlCreator() { - return null; - } - - public IRegion getSubject(ITextViewer textViewer, int offset) { - return fTextHover.getHoverRegion(textViewer, offset); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/contentassist/AutoActivationDelegate.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/contentassist/AutoActivationDelegate.java deleted file mode 100644 index 932db6163e..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/contentassist/AutoActivationDelegate.java +++ /dev/null @@ -1,24 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.contentassist; - -public abstract class AutoActivationDelegate { - - public char[] getCompletionProposalAutoActivationCharacters() { - return null; - } - - public char[] getContextInformationAutoActivationCharacters() { - return null; - } - - public abstract void dispose(); -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/contentassist/CompletionProposalInvocationContext.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/contentassist/CompletionProposalInvocationContext.java deleted file mode 100644 index 9ac2f0cb39..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/contentassist/CompletionProposalInvocationContext.java +++ /dev/null @@ -1,131 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.contentassist; - -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.wst.sse.ui.internal.Logger; - -/** - * <p>Helpful class for passing around information about the invocation context - * of a content assist request</p> - * - * @base org.eclipse.jdt.ui.text.java.ContentAssistInvocationContext - */ -public class CompletionProposalInvocationContext { - /** the viewer that was used to invoke content assist */ - private final ITextViewer fViewer; - - /** the character offset where content assist was invoked in the viewer */ - private final int fInvocationOffset; - - /** the partition type where content assist was invoked */ - private String fPartitionType; - - /** - * <p>Create a new context</p> - * - * @param viewer {@link ITextViewer} that was used to invoke content assist - * @param invocationOffset character offset where content assist was invoked in the viewer - */ - public CompletionProposalInvocationContext(ITextViewer viewer, int invocationOffset) { - fViewer = viewer; - fInvocationOffset = invocationOffset; - fPartitionType = null; - } - - /** - * @return {@link IDocument} that content assist was invoked on - */ - public IDocument getDocument() { - return fViewer.getDocument(); - } - - /** - * @return {@link ITextViewer} that was used to invoke content assist - */ - public ITextViewer getViewer() { - return fViewer; - } - - /** - * @return character offset where content assist was invoked in the viewer - */ - public int getInvocationOffset() { - return fInvocationOffset; - } - - /** - * @return the partition type where content assist was invoked - */ - public String getInvocationPartitionType() { - if(fPartitionType == null) { - fPartitionType = ""; //$NON-NLS-1$ - try { - fPartitionType = this.getDocument().getPartition(this.fInvocationOffset).getType(); - } catch (BadLocationException e) { - // should never happen, nothing we can do about it if it does - Logger.logException("Could not get the partition type at content assist invocation offset", e); //$NON-NLS-1$ - } - } - return fPartitionType; - } - - /** - * <p>Invocation contexts are equal if they describe the same context and are of the same type. - * This implementation checks for <code>null</code> values and class equality. Subclasses - * should extend this method by adding checks for their context relevant fields (but not - * necessarily cached values).</p> - * <p> - * Example: - * - * <pre> - * class MyContext extends ContentAssistInvocationContext { - * private final Object fState; - * private Object fCachedInfo; - * - * ... - * - * public boolean equals(Object obj) { - * if (!super.equals(obj)) - * return false; - * MyContext other= (MyContext) obj; - * return fState.equals(other.fState); - * } - * } - * </pre> - * - * </p> - * <p> - * Subclasses should also extend {@link Object#hashCode()}. - * </p> - * - * @param obj {@inheritDoc} - * @return {@inheritDoc} - */ - public boolean equals(Object obj) { - boolean equal = false; - if(obj instanceof CompletionProposalInvocationContext) { - CompletionProposalInvocationContext other = (CompletionProposalInvocationContext) obj; - equal = (fViewer == null && other.fViewer == null || fViewer != null && fViewer.equals(other.fViewer)) && - fInvocationOffset == other.fInvocationOffset; - } - return equal; - } - - /** - * @see java.lang.Object#hashCode() - */ - public int hashCode() { - return 23459213 << 5 | (fViewer == null ? 0 : fViewer.hashCode() << 3) | fInvocationOffset; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/contentassist/ICompletionProposalComputer.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/contentassist/ICompletionProposalComputer.java deleted file mode 100644 index b4f608a5ce..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/contentassist/ICompletionProposalComputer.java +++ /dev/null @@ -1,72 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.contentassist; - -import java.util.List; - -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.jface.text.contentassist.ICompletionProposal; -import org.eclipse.jface.text.contentassist.IContextInformation; - -/** - * <p>Computes completions and context information displayed by the SSE editor content assistant. - * Contributions to the <tt>org.eclipse.wst.sse.ui.completionProposal</tt> extension point - * must implement this interface.</p> - * - * @base org.eclipse.jdt.ui.text.java.IJavaCompletionProposalComputer - */ -public interface ICompletionProposalComputer { - /** - * Informs the computer that a content assist session has started. This call will always be - * followed by a {@link #sessionEnded()} call, but not necessarily by calls to - * {@link #computeCompletionProposals(CompletionProposalInvocationContext, IProgressMonitor) computeCompletionProposals} - * or - * {@link #computeContextInformation(CompletionProposalInvocationContext, IProgressMonitor) computeContextInformation}. - */ - void sessionStarted(); - - /** - * Returns a list of completion proposals valid at the given invocation context. - * - * @param context the context of the content assist invocation - * @param monitor a progress monitor to report progress. The monitor is private to this - * invocation, i.e. there is no need for the receiver to spawn a sub monitor. - * @return a list of completion proposals (element type: {@link ICompletionProposal}) - */ - List computeCompletionProposals(CompletionProposalInvocationContext context, IProgressMonitor monitor); - - /** - * Returns context information objects valid at the given invocation context. - * - * @param context the context of the content assist invocation - * @param monitor a progress monitor to report progress. The monitor is private to this - * invocation, i.e. there is no need for the receiver to spawn a sub monitor. - * @return a list of context information objects (element type: {@link IContextInformation}) - */ - List computeContextInformation(CompletionProposalInvocationContext context, IProgressMonitor monitor); - - /** - * Returns the reason why this computer was unable to produce any completion proposals or - * context information. - * - * @return an error message or <code>null</code> if no error occurred - */ - String getErrorMessage(); - - /** - * Informs the computer that a content assist session has ended. This call will always be after - * any calls to - * {@linkplain #computeCompletionProposals(CompletionProposalInvocationContext, IProgressMonitor) computeCompletionProposals} - * and - * {@linkplain #computeContextInformation(CompletionProposalInvocationContext, IProgressMonitor) computeContextInformation}. - */ - void sessionEnded(); -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/contentassist/StructuredContentAssistProcessor.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/contentassist/StructuredContentAssistProcessor.java deleted file mode 100644 index 78efc28069..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/contentassist/StructuredContentAssistProcessor.java +++ /dev/null @@ -1,943 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010, 2011 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.contentassist; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; - -import org.eclipse.core.runtime.Assert; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.core.runtime.SubProgressMonitor; -import org.eclipse.jface.action.LegacyActionTools; -import org.eclipse.jface.bindings.TriggerSequence; -import org.eclipse.jface.bindings.keys.KeySequence; -import org.eclipse.jface.dialogs.IDialogConstants; -import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.resource.JFaceResources; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.ITextInputListener; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.contentassist.ContentAssistEvent; -import org.eclipse.jface.text.contentassist.ContentAssistant; -import org.eclipse.jface.text.contentassist.ICompletionListener; -import org.eclipse.jface.text.contentassist.ICompletionListenerExtension; -import org.eclipse.jface.text.contentassist.ICompletionProposal; -import org.eclipse.jface.text.contentassist.IContentAssistProcessor; -import org.eclipse.jface.text.contentassist.IContentAssistantExtension2; -import org.eclipse.jface.text.contentassist.IContentAssistantExtension3; -import org.eclipse.jface.text.contentassist.IContextInformation; -import org.eclipse.jface.text.contentassist.IContextInformationValidator; -import org.eclipse.jface.util.IPropertyChangeListener; -import org.eclipse.jface.util.PropertyChangeEvent; -import org.eclipse.osgi.util.NLS; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Link; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.dialogs.PreferencesUtil; -import org.eclipse.ui.keys.IBindingService; -import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds; -import org.eclipse.wst.sse.core.StructuredModelManager; -import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument; -import org.eclipse.wst.sse.ui.internal.ExtendedConfigurationBuilder; -import org.eclipse.wst.sse.ui.internal.IReleasable; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; -import org.eclipse.wst.sse.ui.internal.SSEUIPlugin; -import org.eclipse.wst.sse.ui.internal.contentassist.CompletionProposalCategory; -import org.eclipse.wst.sse.ui.internal.contentassist.CompletionProposalComputerRegistry; -import org.eclipse.wst.sse.ui.internal.contentassist.CompletionProposoalCatigoriesConfigurationRegistry; -import org.eclipse.wst.sse.ui.internal.contentassist.CompoundContentAssistProcessor; -import org.eclipse.wst.sse.ui.internal.contentassist.ContextInformationValidator; -import org.eclipse.wst.sse.ui.internal.contentassist.OptionalMessageDialog; -import org.eclipse.wst.sse.ui.preferences.ICompletionProposalCategoriesConfigurationReader; -import org.eclipse.wst.sse.ui.preferences.ICompletionProposalCategoriesConfigurationWriter; - - -/** - * <p>A content assist processor that aggregates the proposals of the - * {@link org.eclipse.wst.sse.ui.contentassist.ICompletionProposalComputer}s contributed via the - * <code>org.eclipse.wst.sse.ui.completionProposal</code> extension point.</p> - * <p> - * Extenders may extend: - * <ul> - * <li>{@link #propertyChange(PropertyChangeEvent)}to react to property change events - * that occur in the {@link IPreferenceStore} given to the constructor in case the behavior - * of the processor needs to change according to user preferences</li> - * <li>{@link #getCompletionProposalAutoActivationCharacters()}</li> - * <li>{@link #getContextInformationAutoActivationCharacters()}</li> - * <li>{@link #filterAndSortProposals(List, IProgressMonitor, CompletionProposalInvocationContext)} - * to add sorting and filtering</li> - * <li>{@link #filterAndSortContextInformation(List, IProgressMonitor)} to add sorting and filtering</li> - * <li>{@link #createProgressMonitor()} to change the way progress is reported</li> - * <li>{@link #createContext(ITextViewer, int)} to provide the context object - * passed to the computers</li> - * <li>{@link #getContextInformationValidator()} to add context validation (needed if any - * contexts are provided)</li> - * <li>{@link #getErrorMessage()} to change error reporting</li> - * </ul> - * </p> - * - * @base org.eclipse.jdt.internal.ui.text.java.ContentAssistProcessor - */ -public class StructuredContentAssistProcessor implements IContentAssistProcessor, IPropertyChangeListener, IReleasable { - - /** Legacy editor configuration extension point. */ - private static final String CONTENT_ASSIST_PROCESSOR_EXTENDED_ID = "contentassistprocessor"; //$NON-NLS-1$ - - /** Content assist processors added through the now legacy editor configuration extension point */ - private List fLegacyExtendedContentAssistProcessors; - - /** - * Dialog settings key for the "all categories are disabled" warning dialog. See - * {@link OptionalMessageDialog}. - */ - private static final String PREF_WARN_ABOUT_EMPTY_ASSIST_CATEGORY= "EmptyDefaultAssistCategory"; //$NON-NLS-1$ - - /** - * Used to sort categories by their page order so they are cycled in the correct order - */ - private final Comparator PAGE_ORDER_COMPARATOR = new Comparator() { - public int compare(Object o1, Object o2) { - CompletionProposalCategory d1= (CompletionProposalCategory) o1; - CompletionProposalCategory d2= (CompletionProposalCategory) o2; - - return d1.getPageSortRank(fContentTypeID) - d2.getPageSortRank(fContentTypeID); - } - }; - - /** - * Used to sort categories by their default page order so they are - * ordered correctly on the default page - */ - private final Comparator DEFAULT_PAGE_ORDER_COMPARATOR = new Comparator() { - public int compare(Object o1, Object o2) { - CompletionProposalCategory d1= (CompletionProposalCategory) o1; - CompletionProposalCategory d2= (CompletionProposalCategory) o2; - - return d1.getDefaultPageSortRank(fContentTypeID) - d2.getDefaultPageSortRank(fContentTypeID); - } - }; - - /** List of {@link CompletionProposalCategory}s supported by this processor */ - private List fCategories; - - /** content type ID this processor is associated with */ - String fContentTypeID; - - /** partition type ID this processor is associated with */ - private final String fPartitionTypeID; - - /** Content assistant used for giving the user status messages and listening to completion results*/ - private ContentAssistant fAssistant; - - /* cycling stuff */ - private int fRepetition= -1; - private List fCategoryIteration = null; - private String fIterationGesture = null; - private int fNumberOfComputedResults = 0; - private String fErrorMessage; - - /** Optionally specified preference store for listening to property change events */ - private IPreferenceStore fPreferenceStore; - - /** The viewer this processor is associated with */ - private ITextViewer fViewer; - - /** - * the {@link ITextInputListener} used to set the content type when - * a document is set for this processors associated viewer. - */ - private ITextInputListener fTextInputListener; - - private CompletionListener fCompletionListener; - - /** the context information validator for this processor */ - private IContextInformationValidator fContextInformationValidator; - - private AutoActivationDelegate fAutoActivation; - - /** - * <p>Create a new content assist processor for a specific partition type. - * The content type will be determined when a document is set on the viewer</p> - * - * <p>If the given {@link IPreferenceStore} is not <code>null</code> then this - * processor will be registered as a {@link IPropertyChangeListener} on the given store - * so that implementers of this class can change the way the processor acts based on - * user preferences</p> - * - * @param assistant {@link ContentAssistant} to use - * @param partitionTypeID the partition type this processor is for - * @param viewer {@link ITextViewer} this processor is acting in - * @param preferenceStore This processor will be registered as a {@link IPropertyChangeListener} - * on this store and the processor itself will take care of removing itself as a listener, if - * <code>null</code> then will not be registered as a {@link IPropertyChangeListener} - */ - public StructuredContentAssistProcessor(ContentAssistant assistant, String partitionTypeID, - ITextViewer viewer, IPreferenceStore preferenceStore) { - - Assert.isNotNull(partitionTypeID); - Assert.isNotNull(assistant); - - //be sure the registry has been loaded, none blocking - CompletionProposalComputerRegistry.getDefault().initialize(); - - //register on the preference store - this.fPreferenceStore = preferenceStore; - if(this.fPreferenceStore != null) { - this.fPreferenceStore.addPropertyChangeListener(this); - } - - //The content type can not be determined until a document has been set - this.fContentTypeID = null; - this.fViewer = viewer; - if(viewer != null) { - this.fTextInputListener = new TextInputListener(); - viewer.addTextInputListener(this.fTextInputListener); - - if(viewer.getDocument() != null) { - /* it is highly unlike the document has already been set, but check - * just for sanity - */ - this.fTextInputListener.inputDocumentChanged(null, viewer.getDocument()); - } - } - - //set the associated partition type - this.fPartitionTypeID = partitionTypeID; - - //add completion listener - fAssistant = assistant; - fCompletionListener = new CompletionListener(); - fAssistant.addCompletionListener(fCompletionListener); - - //lazy load these to speed up initial editor opening - fLegacyExtendedContentAssistProcessors = null; - fCategories = null; - } - - /** - * <p>Collect the proposals using the extension points</p> - * - * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#computeCompletionProposals(org.eclipse.jface.text.ITextViewer, int) - */ - public final ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) { - clearState(); - - IProgressMonitor monitor= createProgressMonitor(); - monitor.beginTask(SSEUIMessages.ContentAssist_computing_proposals, getProposalCategories().size() + 1); - - CompletionProposalInvocationContext context = createContext(viewer, offset); - - monitor.subTask(SSEUIMessages.ContentAssist_collecting_proposals); - List proposals = collectProposals(viewer, offset, monitor, context); - - monitor.subTask(SSEUIMessages.ContentAssist_sorting_proposals); - List filtered = filterAndSortProposals(proposals, monitor, context); - fNumberOfComputedResults= filtered.size(); - - ICompletionProposal[] result= (ICompletionProposal[]) filtered.toArray(new ICompletionProposal[filtered.size()]); - monitor.done(); - - return result; - } - - /** - * <p>Collect the context information using the extension points</p> - * - * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#computeContextInformation(org.eclipse.jface.text.ITextViewer, int) - */ - public IContextInformation[] computeContextInformation(ITextViewer viewer, int offset) { - clearState(); - - IProgressMonitor monitor= createProgressMonitor(); - monitor.beginTask(SSEUIMessages.ContentAssist_computing_contexts, getProposalCategories().size() + 1); - - monitor.subTask(SSEUIMessages.ContentAssist_collecting_contexts); - List proposals= collectContextInformation(viewer, offset, monitor); - - monitor.subTask(SSEUIMessages.ContentAssist_sorting_contexts); - List filtered= filterAndSortContextInformation(proposals, monitor); - fNumberOfComputedResults= filtered.size(); - - IContextInformation[] result= (IContextInformation[]) filtered.toArray(new IContextInformation[filtered.size()]); - monitor.done(); - return result; - } - - /** - * <p>Default implementation is to return <code>null</code></p> - * <p>Extenders may override</p> - * - * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getCompletionProposalAutoActivationCharacters() - */ - public char[] getCompletionProposalAutoActivationCharacters() { - return (fAutoActivation != null) ? fAutoActivation.getCompletionProposalAutoActivationCharacters() : null; - } - - /** - * <p>Default implementation is to return <code>null</code></p> - * <p>Extenders may override</p> - * - * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getContextInformationAutoActivationCharacters() - */ - public char[] getContextInformationAutoActivationCharacters() { - return (fAutoActivation != null) ? fAutoActivation.getContextInformationAutoActivationCharacters() : null; - } - - /** - * <p>Extenders may override this function to change error reporting</p> - * - * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getErrorMessage() - */ - public String getErrorMessage() { - if (fErrorMessage != null) - return fErrorMessage; - if (fNumberOfComputedResults > 0) - return null; - return SSEUIMessages.ContentAssist_no_completions; - } - - /** - * @see org.eclipse.wst.sse.ui.contentassist.StructuredContentAssistProcessor#getContextInformationValidator() - */ - public IContextInformationValidator getContextInformationValidator() { - if (this.fContextInformationValidator == null) { - this.fContextInformationValidator = new ContextInformationValidator(); - } - return this.fContextInformationValidator; - } - - public void install(ITextViewer viewer) { - if (fPreferenceStore != null) { - fPreferenceStore.addPropertyChangeListener(this); - } - if (fViewer != null) { - fViewer.removeTextInputListener(fTextInputListener); - } - fViewer = viewer; - if (fViewer != null) { - fViewer.addTextInputListener(fTextInputListener); - } - if (fAssistant != null) { - fAssistant.addCompletionListener(fCompletionListener); - } - } - - /** - * <p>Extenders may override, but should always be sure to call the super implementation</p> - * - * @see org.eclipse.wst.sse.ui.internal.IReleasable#release() - */ - public void release() { - if (fAutoActivation != null) { - fAutoActivation.dispose(); - fAutoActivation = null; - } - if(this.fPreferenceStore != null) { - this.fPreferenceStore.removePropertyChangeListener(this); - } - - if(this.fViewer != null) { - this.fViewer.removeTextInputListener(this.fTextInputListener); - this.fViewer = null; - } - if (this.fAssistant != null) { - this.fAssistant.removeCompletionListener(fCompletionListener); - } - } - - /** - * <p>Intended to be overridden by extenders wishing to change the behavior - * of the processor based on user preferences from the store optionally - * associated with this processor. If no store was given to the constructor - * when creating this assistant then this method will never be invoked.</p> - * - * <p>The default implementation does not react to the events in any way</p> - * - * @see org.eclipse.jface.util.IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent) - */ - public void propertyChange(PropertyChangeEvent event) { - } - - /** - * <p>Filters and sorts the proposals. The passed list may be modified - * and returned, or a new list may be created and returned.</p> - * - * <p>The default implementation does not do any sorting or filtering.</p> - * <p>Extenders may override this function.</p> - * - * @param proposals the list of collected proposals (element type: - * {@link ICompletionProposal}) - * @param monitor a progress monitor - * @param context TODO - * @return the list of filtered and sorted proposals, ready for - * display (element type: {@link ICompletionProposal}) - */ - protected List filterAndSortProposals(List proposals, IProgressMonitor monitor, CompletionProposalInvocationContext context) { - return proposals; - } - - /** - * <p>Filters and sorts the context information objects. The passed - * list may be modified and returned, or a new list may be created - * and returned.</p> - * - * <p>The default implementation does not do any sorting or filtering</p> - * <p>Extenders may override this method</p> - * - * @param contexts the list of collected proposals (element type: - * {@link IContextInformation}) - * @param monitor a progress monitor - * @return the list of filtered and sorted proposals, ready for - * display (element type: {@link IContextInformation}) - */ - protected List filterAndSortContextInformation(List contexts, IProgressMonitor monitor) { - return contexts; - } - - /** - * <p>Creates a progress monitor.</p> - * <p>The default implementation creates a {@link NullProgressMonitor}.</p> - * - * <p>Extenders may override this method</p> - * - * @return a progress monitor - */ - protected IProgressMonitor createProgressMonitor() { - return new NullProgressMonitor(); - } - - /** - * <p>Creates the context that is passed to the completion proposal - * computers.</p> - * - * <p>Extenders may override this method</p> - * - * @param viewer the viewer that content assist is invoked on - * @param offset the content assist offset - * @return the context to be passed to the computers - */ - protected CompletionProposalInvocationContext createContext(ITextViewer viewer, int offset) { - return new CompletionProposalInvocationContext(viewer, offset); - } - - /** - * @return the associated preference store - */ - protected IPreferenceStore getPreferenceStore() { - return this.fPreferenceStore; - } - - /** - * Clears the state - */ - private void clearState() { - fErrorMessage=null; - fNumberOfComputedResults= 0; - } - - /** - * <p>Collects the proposals from the extensions.</p> - * - * @param viewer the text viewer - * @param offset the offset - * @param monitor the progress monitor - * @param context the code assist invocation context - * @return the list of proposals - */ - private List collectProposals(ITextViewer viewer, int offset, IProgressMonitor monitor, CompletionProposalInvocationContext context) { - List proposals = new ArrayList(); - List categories = getCategories(); - for (Iterator it = categories.iterator(); it.hasNext();) { - CompletionProposalCategory cat = (CompletionProposalCategory) it.next(); - List computed = cat.computeCompletionProposals(context, this.fContentTypeID, this.fPartitionTypeID, new SubProgressMonitor(monitor, 1)); - proposals.addAll(computed); - if (fErrorMessage == null) { - fErrorMessage= cat.getErrorMessage(); - } - } - - // if default page - // Deal with adding in proposals from processors added through the legacy extension - if (isFirstPage() && getLegacyExtendedContentAssistProcessors() != null && - !getLegacyExtendedContentAssistProcessors().isEmpty()) { - - Iterator iter = getLegacyExtendedContentAssistProcessors().iterator(); - while (iter.hasNext()) { - IContentAssistProcessor legacyProcessor = (IContentAssistProcessor) iter.next(); - ICompletionProposal[] legacyComputed = legacyProcessor.computeCompletionProposals(viewer, offset); - if (legacyComputed != null) { - proposals.addAll(Arrays.asList(legacyComputed)); - } - } - } - - return proposals; - } - - /** - * <p>Collects the context information from the extensions.</p> - * - * @param viewer - * @param offset - * @param monitor - * @return - */ - private List collectContextInformation(ITextViewer viewer, int offset, IProgressMonitor monitor) { - List proposals = new ArrayList(); - CompletionProposalInvocationContext context= createContext(viewer, offset); - - List providers= getCategories(); - for (Iterator it= providers.iterator(); it.hasNext();) { - CompletionProposalCategory cat= (CompletionProposalCategory) it.next(); - List computed= cat.computeContextInformation(context, this.fContentTypeID, this.fPartitionTypeID, new SubProgressMonitor(monitor, 1)); - proposals.addAll(computed); - if (fErrorMessage == null) { - fErrorMessage= cat.getErrorMessage(); - } - } - - // Deal with adding in contexts from processors added through the legacy extension - if (getLegacyExtendedContentAssistProcessors() != null && - !getLegacyExtendedContentAssistProcessors().isEmpty()) { - - Iterator iter = getLegacyExtendedContentAssistProcessors().iterator(); - while (iter.hasNext()) { - IContentAssistProcessor legacyProcessor = (IContentAssistProcessor) iter.next(); - IContextInformation[] legacyComputed = legacyProcessor.computeContextInformation(viewer, offset); - if(legacyComputed != null) { - proposals.addAll(Arrays.asList(legacyComputed)); - } - } - } - - return proposals; - } - - /** - * @return the next set of categories - */ - private List getCategories() { - List categories; - if (fCategoryIteration == null) { - categories = getProposalCategories(); - } else { - int iteration= fRepetition % fCategoryIteration.size(); - fAssistant.setStatusMessage(createIterationMessage()); - fAssistant.setEmptyMessage(createEmptyMessage()); - fRepetition++; - - categories = (List) fCategoryIteration.get(iteration); - } - - return categories; - } - - /** - * This may show the warning dialog if all categories are disabled - */ - private void resetCategoryIteration() { - fCategoryIteration = getCategoryIteration(); - } - - /** - * @return {@link List} of {@link List}s of {@link CompletionProposalCategory}s, this is - * the ordered list of the completion categories to cycle through - */ - private List getCategoryIteration() { - List sequence= new ArrayList(); - sequence.add(getDefaultCategories()); - for (Iterator it= getSortedOwnPageCategories().iterator(); it.hasNext();) { - CompletionProposalCategory cat= (CompletionProposalCategory) it.next(); - sequence.add(Collections.singletonList(cat)); - } - return sequence; - } - - /** - * @return the sorted categories for the default page - */ - private List getDefaultCategories() { - // default mix - enable all included computers - List included= getDefaultCategoriesUnchecked(); - - if (included.size() == 0 && CompletionProposalComputerRegistry.getDefault().hasUninstalledComputers()) { - if (informUserAboutEmptyDefaultCategory()) { - // preferences were restored - recompute the default categories - included= getDefaultCategoriesUnchecked(); - } - CompletionProposalComputerRegistry.getDefault().resetUnistalledComputers(); - } - - Collections.sort(included, DEFAULT_PAGE_ORDER_COMPARATOR); - - return included; - } - - /** - * <p>Gets the default categories with no error checking.</p> - * - * @return the default {@link CompletionProposalCategory}s - */ - private List getDefaultCategoriesUnchecked() { - List included = new ArrayList(); - for (Iterator it = getProposalCategories().iterator(); it.hasNext();) { - CompletionProposalCategory category = (CompletionProposalCategory) it.next(); - if (category.isIncludedOnDefaultPage(this.fContentTypeID) && category.hasComputers(fContentTypeID, fPartitionTypeID)) - included.add(category); - } - return included; - } - - /** - * <p>Informs the user about the fact that there are no enabled categories in the default content - * assist set and shows a link to the preferences.</p> - * - * @return <code>true</code> if the default should be restored - */ - private boolean informUserAboutEmptyDefaultCategory() { - /*If warn about empty default category and there are associated properties for this - * processors content type and those properties have an associated properties page then - * display warning message to user. - */ - ICompletionProposalCategoriesConfigurationReader properties = CompletionProposoalCatigoriesConfigurationRegistry.getDefault().getReadableConfiguration(this.fContentTypeID); - if (OptionalMessageDialog.isDialogEnabled(PREF_WARN_ABOUT_EMPTY_ASSIST_CATEGORY) && - properties instanceof ICompletionProposalCategoriesConfigurationWriter && - ((ICompletionProposalCategoriesConfigurationWriter)properties).hasAssociatedPropertiesPage()) { - - ICompletionProposalCategoriesConfigurationWriter propertiesExtension = (ICompletionProposalCategoriesConfigurationWriter)properties; - - final Shell shell= SSEUIPlugin.getActiveWorkbenchShell(); - String title= SSEUIMessages.ContentAssist_all_disabled_title; - String message= SSEUIMessages.ContentAssist_all_disabled_message; - // see PreferencePage#createControl for the 'defaults' label - final String restoreButtonLabel= JFaceResources.getString("defaults"); //$NON-NLS-1$ - final String linkMessage= NLS.bind(SSEUIMessages.ContentAssist_all_disabled_preference_link, LegacyActionTools.removeMnemonics(restoreButtonLabel)); - final int restoreId= IDialogConstants.CLIENT_ID + 10; - final int settingsId= IDialogConstants.CLIENT_ID + 11; - final OptionalMessageDialog dialog= new OptionalMessageDialog(PREF_WARN_ABOUT_EMPTY_ASSIST_CATEGORY, shell, title, null /* default image */, message, MessageDialog.WARNING, new String[] { restoreButtonLabel, IDialogConstants.CLOSE_LABEL }, 1) { - /* - * @see org.eclipse.jdt.internal.ui.dialogs.OptionalMessageDialog#createCustomArea(org.eclipse.swt.widgets.Composite) - */ - protected Control createCustomArea(Composite composite) { - // wrap link and checkbox in one composite without space - Composite parent= new Composite(composite, SWT.NONE); - GridLayout layout= new GridLayout(); - layout.marginHeight= 0; - layout.marginWidth= 0; - layout.verticalSpacing= 0; - parent.setLayout(layout); - - Composite linkComposite= new Composite(parent, SWT.NONE); - layout= new GridLayout(); - layout.marginHeight= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); - layout.marginWidth= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); - layout.horizontalSpacing= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); - linkComposite.setLayout(layout); - - Link link= new Link(linkComposite, SWT.NONE); - link.setText(linkMessage); - link.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent e) { - setReturnCode(settingsId); - close(); - } - }); - GridData gridData= new GridData(SWT.FILL, SWT.BEGINNING, true, false); - gridData.widthHint= this.getMinimumMessageWidth(); - link.setLayoutData(gridData); - - // create checkbox and "don't show this message" prompt - super.createCustomArea(parent); - - return parent; - } - - /* - * @see org.eclipse.jface.dialogs.MessageDialog#createButtonsForButtonBar(org.eclipse.swt.widgets.Composite) - */ - protected void createButtonsForButtonBar(Composite parent) { - Button[] buttons= new Button[2]; - buttons[0]= createButton(parent, restoreId, restoreButtonLabel, false); - buttons[1]= createButton(parent, IDialogConstants.CLOSE_ID, IDialogConstants.CLOSE_LABEL, true); - setButtons(buttons); - } - }; - int returnValue = dialog.open(); - - //based on user actions either reset defaults or open preference dialog - if (restoreId == returnValue || settingsId == returnValue) { - if (restoreId == returnValue) { - propertiesExtension.loadDefaults(); - propertiesExtension.saveConfiguration(); - } - if (settingsId == returnValue) { - PreferencesUtil.createPreferenceDialogOn(shell, - propertiesExtension.getPropertiesPageID(), null, null).open(); - } - - return true; - } - } - return false; - } - - /** - * @return a sorted {@link List} of {@link CompletionProposalCategory}s that - * should be displayed on their own content assist page - */ - private List getSortedOwnPageCategories() { - ArrayList sorted= new ArrayList(); - for (Iterator it= getProposalCategories().iterator(); it.hasNext();) { - CompletionProposalCategory category= (CompletionProposalCategory) it.next(); - if (category.isDisplayedOnOwnPage(this.fContentTypeID) && - category.hasComputers(fContentTypeID, fPartitionTypeID)) { - - sorted.add(category); - } - } - Collections.sort(sorted, PAGE_ORDER_COMPARATOR); - return sorted; - } - - /** - * @return a user message describing that there are no content assist suggestions for the current page - */ - private String createEmptyMessage() { - return NLS.bind(SSEUIMessages.ContentAssist_no_message, new String[]{getCategoryLabel(fRepetition)}); - } - - /** - * @return user message describing what the next page of content assist holds - */ - private String createIterationMessage() { - return NLS.bind(SSEUIMessages.ContentAssist_toggle_affordance_update_message, - new String[]{ getCategoryLabel(fRepetition), fIterationGesture, getCategoryLabel(fRepetition + 1) }); - } - - /** - * @param repetition which category to get the label for - * @return the label of the category - */ - private String getCategoryLabel(int repetition) { - int iteration= (fCategoryIteration != null ? repetition % fCategoryIteration.size() : 0); - if (iteration == 0) - return SSEUIMessages.ContentAssist_defaultProposalCategory_title; - return ((CompletionProposalCategory) ((List) fCategoryIteration.get(iteration)).get(0)).getDisplayName(); - } - - /** - * @return {@link String} representing the user command to iterate to the next page - */ - private String getIterationGesture() { - TriggerSequence binding= getIterationBinding(); - return binding != null ? - NLS.bind(SSEUIMessages.ContentAssist_press, new Object[] { binding.format() }) - : SSEUIMessages.ContentAssist_click; - } - - /** - * @return {@link KeySequence} used by user to iterate to the next page - */ - private KeySequence getIterationBinding() { - final IBindingService bindingSvc= (IBindingService) PlatformUI.getWorkbench().getAdapter(IBindingService.class); - TriggerSequence binding= bindingSvc.getBestActiveBindingFor(ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS); - if (binding instanceof KeySequence) - return (KeySequence) binding; - return null; - } - - /** - * @return <code>true</code> if displaying first page, <code>false</code> otherwise - */ - private boolean isFirstPage() { - return fCategoryIteration == null || fCategoryIteration.size() == 1 || fRepetition % fCategoryIteration.size() == 1; - } - - /** - * <p><b>NOTE: </b>This method should be used over accessing the - * {@link #fLegacyExtendedContentAssistProcessors} field directly so as to - * facilitate the lazy initialization of the field.</p> - * - * @return the legacy extended content assist processors - */ - private List getLegacyExtendedContentAssistProcessors() { - if(fLegacyExtendedContentAssistProcessors == null) { - fLegacyExtendedContentAssistProcessors = - ExtendedConfigurationBuilder.getInstance().getConfigurations( - CONTENT_ASSIST_PROCESSOR_EXTENDED_ID, fPartitionTypeID); - } - - return fLegacyExtendedContentAssistProcessors; - } - - /** - * <p><b>NOTE: </b>This method should be used over accessing the {@link #fCategories} - * field directly so as to facilitate the lazy initialization of the field.</p> - * - * @return the categories associated with the content type this processor is associated with - */ - private List getProposalCategories() { - if(fCategories == null) { - fCategories = - CompletionProposalComputerRegistry.getDefault().getProposalCategories(fContentTypeID); - } - - return fCategories; - } - - /** - * The completion listener class for this processor. - */ - private final class CompletionListener implements ICompletionListener, ICompletionListenerExtension { - /** - * @see org.eclipse.jface.text.contentassist.ICompletionListener#assistSessionStarted(org.eclipse.jface.text.contentassist.ContentAssistEvent) - */ - public void assistSessionStarted(ContentAssistEvent event) { - if (event.processor == StructuredContentAssistProcessor.this || - (event.processor instanceof CompoundContentAssistProcessor && - ((CompoundContentAssistProcessor)event.processor).containsProcessor(StructuredContentAssistProcessor.this))) { - - fIterationGesture= getIterationGesture(); - KeySequence binding= getIterationBinding(); - - // This may show the warning dialog if all categories are disabled - resetCategoryIteration(); - for (Iterator it= StructuredContentAssistProcessor.this.getProposalCategories().iterator(); it.hasNext();) { - CompletionProposalCategory cat= (CompletionProposalCategory) it.next(); - cat.sessionStarted(); - } - - fRepetition= 0; - if (event.assistant instanceof IContentAssistantExtension2) { - IContentAssistantExtension2 extension= (IContentAssistantExtension2) event.assistant; - - if (fCategoryIteration.size() == 1) { - extension.setRepeatedInvocationMode(false); - extension.setShowEmptyList(false); - } else { - extension.setRepeatedInvocationMode(true); - extension.setStatusLineVisible(true); - extension.setStatusMessage(createIterationMessage()); - extension.setShowEmptyList(true); - if (extension instanceof IContentAssistantExtension3) { - IContentAssistantExtension3 ext3= (IContentAssistantExtension3) extension; - ((ContentAssistant) ext3).setRepeatedInvocationTrigger(binding); - } - } - } - } - } - - /** - * @see org.eclipse.jface.text.contentassist.ICompletionListener#assistSessionEnded(org.eclipse.jface.text.contentassist.ContentAssistEvent) - */ - public void assistSessionEnded(ContentAssistEvent event) { - if (event.processor == StructuredContentAssistProcessor.this || (event.processor instanceof CompoundContentAssistProcessor && ((CompoundContentAssistProcessor)event.processor).containsProcessor(StructuredContentAssistProcessor.this))) { - for (Iterator it= StructuredContentAssistProcessor.this.getProposalCategories().iterator(); it.hasNext();) { - CompletionProposalCategory cat= (CompletionProposalCategory) it.next(); - cat.sessionEnded(); - } - - fCategoryIteration= null; - fRepetition= -1; - fIterationGesture= null; - if (event.assistant instanceof IContentAssistantExtension2) { - IContentAssistantExtension2 extension= (IContentAssistantExtension2) event.assistant; - extension.setShowEmptyList(false); - extension.setRepeatedInvocationMode(false); - extension.setStatusLineVisible(false); - if (extension instanceof IContentAssistantExtension3) { - IContentAssistantExtension3 ext3= (IContentAssistantExtension3) extension; - ((ContentAssistant) ext3).setRepeatedInvocationTrigger(null); - } - } - } - } - - /** - * @see org.eclipse.jface.text.contentassist.ICompletionListener#selectionChanged(org.eclipse.jface.text.contentassist.ICompletionProposal, boolean) - */ - public void selectionChanged(ICompletionProposal proposal, boolean smartToggle) { - //ignore - } - - /** - * @see org.eclipse.jface.text.contentassist.ICompletionListenerExtension#assistSessionRestarted(org.eclipse.jface.text.contentassist.ContentAssistEvent) - */ - public void assistSessionRestarted(ContentAssistEvent event) { - fRepetition= 0; - } - } - - /** - * - */ - private class TextInputListener implements ITextInputListener { - - /** - * <p>Set the content type based on the new document if it has not already been - * set yet.</p> - * - * @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(fContentTypeID == null) { - if(newInput instanceof IStructuredDocument) { - IStructuredModel model = null; - try { - model = StructuredModelManager.getModelManager().getModelForRead((IStructuredDocument)newInput); - if(model != null) { - fContentTypeID = model.getContentTypeIdentifier(); - if (fAutoActivation != null) { - fAutoActivation.dispose(); - } - fAutoActivation = CompletionProposalComputerRegistry.getDefault().getActivator(fContentTypeID, fPartitionTypeID); - } - } finally { - if(model != null) { - model.releaseFromRead(); - } - } - } - } - } - - /** - * <p>Ignored</p> - * - * @see org.eclipse.jface.text.ITextInputListener#inputDocumentAboutToBeChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument) - */ - public void inputDocumentAboutToBeChanged(IDocument oldInput, - IDocument newInput) { - //ignore - } - } - - protected void setAutoActivationDelay(int delay) { - fAssistant.setAutoActivationDelay(delay); - } - -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/AbstractDropAction.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/AbstractDropAction.java deleted file mode 100644 index cd54849831..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/AbstractDropAction.java +++ /dev/null @@ -1,94 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal; - -import org.eclipse.core.runtime.IAdaptable; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.ITextSelection; -import org.eclipse.jface.text.TextSelection; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.ISelectionProvider; -import org.eclipse.swt.dnd.DropTargetEvent; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.texteditor.ITextEditor; -import org.eclipse.wst.sse.ui.internal.provisional.extensions.ISourceEditingTextTools; - -/** - */ -public abstract class AbstractDropAction implements IDropAction { - - /* - * Replaces targetEditor's current selection by "text" - */ - protected boolean insert(String text, IEditorPart targetEditor) { - if (text == null || text.length() == 0) { - return true; - } - - ITextSelection textSelection = null; - IDocument doc = null; - ISelection selection = null; - - ISourceEditingTextTools tools = (ISourceEditingTextTools) targetEditor.getAdapter(ISourceEditingTextTools.class); - if (tools != null) { - doc = tools.getDocument(); - selection = tools.getSelection(); - } - - ITextEditor textEditor = null; - if (targetEditor instanceof ITextEditor) { - textEditor = (ITextEditor) targetEditor; - } - if (textEditor == null) { - textEditor = (ITextEditor) ((IAdaptable) targetEditor).getAdapter(ITextEditor.class); - } - if (textEditor == null && tools != null && tools.getEditorPart() instanceof ITextEditor) { - textEditor = (ITextEditor) tools.getEditorPart(); - } - if (textEditor == null && tools != null && tools.getEditorPart() != null) { - textEditor = (ITextEditor) tools.getEditorPart().getAdapter(ITextEditor.class); - } - - if (selection == null && textEditor != null) { - selection = textEditor.getSelectionProvider().getSelection(); - } - if (doc == null && textEditor != null) { - doc = textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput()); - } - - if (selection instanceof ITextSelection) { - textSelection = (ITextSelection) selection; - try { - doc.replace(textSelection.getOffset(), textSelection.getLength(), text); - } - catch (BadLocationException e) { - return false; - } - } - if (textEditor != null && textSelection != null) { - ISelectionProvider sp = textEditor.getSelectionProvider(); - ITextSelection sel = new TextSelection(textSelection.getOffset(), text.length()); - sp.setSelection(sel); - textEditor.selectAndReveal(sel.getOffset(), sel.getLength()); - } - - return true; - } - - public boolean isSupportedData(Object data) { - return true; - } - - public abstract boolean run(DropTargetEvent event, IEditorPart targetEditor); -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/CaretMediator.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/CaretMediator.java deleted file mode 100644 index 33f0311667..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/CaretMediator.java +++ /dev/null @@ -1,284 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal; - -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.jobs.Job; -import org.eclipse.swt.SWT; -import org.eclipse.swt.custom.StyledText; -import org.eclipse.swt.events.KeyEvent; -import org.eclipse.swt.events.KeyListener; -import org.eclipse.swt.events.MouseEvent; -import org.eclipse.swt.events.MouseListener; -import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.Event; -import org.eclipse.swt.widgets.Listener; -import org.eclipse.wst.sse.core.internal.util.Debug; -import org.eclipse.wst.sse.core.internal.util.Utilities; -import org.eclipse.wst.sse.ui.internal.view.events.CaretEvent; -import org.eclipse.wst.sse.ui.internal.view.events.ICaretListener; - -/** - * Has the responsibility of listening for key events, and mouse events, - * deciding if the caret has moved (without a text change), and if so, will - * notify CaretListeners that the caret has moved. Objects which are - * interested in ALL caret postion changes will also have to listen for - * textChanged events. - * - * @deprecated - use base selection notification - */ -public class CaretMediator implements Listener { - - class CaretMediatorListener implements KeyListener, MouseListener { - public void keyPressed(KeyEvent e) { - internalKeyPressed(e); - } - - public void keyReleased(KeyEvent e) { - internalKeyReleased(e); - } - - public void mouseDoubleClick(MouseEvent e) { - } - - public void mouseDown(MouseEvent e) { - internalMouseDown(e); - } - - public void mouseUp(MouseEvent e) { - internalMouseUp(e); - } - } - - class RefreshDelayJob extends Job { - private int fDelay = 0; - RefreshDelayJob(int delay) { - super(SSEUIMessages.caret_update); //$NON-NLS-1$ - setSystem(true); - fDelay = delay; - } - - /** - * Setup a delayed CaretEvent firing - */ - void touch() { - cancel(); - schedule(fDelay); - } - - protected IStatus run(IProgressMonitor monitor) { - handleEvent(null); - return Status.OK_STATUS; - } - } - - RefreshDelayJob fDelayer = null; - private static final int DELAY = 300; - - /** used just for debug print outs */ - private long endTime; - private long startTime; - - protected ICaretListener[] fCaretListeners; - protected CaretMediatorListener internalListener; - protected StyledText textWidget; - - /** - * CaretMediator constructor comment. - */ - public CaretMediator() { - super(); - } - - /** - * CaretMediator constructor comment. Must always provide the widget its - * supposed to listen to. - */ - public CaretMediator(StyledText styledTextWidget) { - this(); - setTextWidget(styledTextWidget); - } - - public synchronized void addCaretListener(ICaretListener listener) { - if (Debug.debugStructuredDocument) { - System.out.println("CaretMediator::addCaretListener. Request to add an instance of " + listener.getClass() + " as a listener on caretlistner.");//$NON-NLS-2$//$NON-NLS-1$ - } - // make sure listener is not already in listening array - // (and if it is, print a warning to aid debugging, if needed) - - if (Utilities.contains(fCaretListeners, listener)) { - if (Debug.displayWarnings) { - System.out.println("CaretMediator::addCaretListener. listener " + listener + " was added more than once. ");//$NON-NLS-2$//$NON-NLS-1$ - } - } else { - if (Debug.debugStructuredDocument) { - System.out.println("CaretMediator::addCaretListener. Adding an instance of " + listener.getClass() + " as a listener on caret mediator.");//$NON-NLS-2$//$NON-NLS-1$ - } - int oldSize = 0; - if (fCaretListeners != null) { - // normally won't be null, but we need to be sure, for first - // time through - oldSize = fCaretListeners.length; - } - int newSize = oldSize + 1; - ICaretListener[] newListeners = new ICaretListener[newSize]; - if (fCaretListeners != null) { - System.arraycopy(fCaretListeners, 0, newListeners, 0, oldSize); - } - // add listener to last position - newListeners[newSize - 1] = listener; - // - // now switch new for old - fCaretListeners = newListeners; - - } - } - - protected void fireCaretEvent(CaretEvent event) { - if (fCaretListeners != null) { - // we must assign listeners to local variable to be thread safe, - // since the add and remove listner methods - // can change this object's actual instance of the listener array - // from another thread - // (and since object assignment is atomic, we don't need to - // synchronize - ICaretListener[] holdListeners = fCaretListeners; - // - for (int i = 0; i < holdListeners.length; i++) { - holdListeners[i].caretMoved(event); - } - } - } - - public void handleEvent(Event e) { - Display display = null; - - if (Debug.debugCaretMediator) { - endTime = System.currentTimeMillis(); - System.out.println("Timer fired: " + (endTime - startTime)); //$NON-NLS-1$ - } - - // check if 'okToUse' - if (textWidget != null && !textWidget.isDisposed()) { - display = textWidget.getDisplay(); - if ((display != null) && (!display.isDisposed())) { - display.asyncExec(new Runnable() { - public void run() { - if (textWidget != null && !textWidget.isDisposed()) { - fireCaretEvent(new CaretEvent(textWidget, textWidget.getCaretOffset())); - } - } - }); - } - } - } - - protected void internalKeyPressed(KeyEvent e) { - fDelayer.cancel(); - } - - protected void internalKeyReleased(KeyEvent e) { - switch (e.keyCode) { - case SWT.ARROW_DOWN : - case SWT.ARROW_UP : - case SWT.ARROW_LEFT : - case SWT.ARROW_RIGHT : - case SWT.HOME : - case SWT.END : - case SWT.PAGE_DOWN : - case SWT.PAGE_UP : { - fDelayer.touch(); - break; - } - default : { - // always update cursor postion, even during normal typing - // (the logic may look funny, since we always to the same - // thing, but we haven't always done the same thing, so I - // wanted to leave that fact documented via code.) - fDelayer.touch(); - } - } - } - - protected void internalMouseDown(MouseEvent e) { - fDelayer.cancel(); - } - - protected void internalMouseUp(MouseEvent e) { - // Note, even during a swipe select, when the mouse button goes up, - // and the widget is - // queried for the current caret postion, it always returns the - // beginning of the selection, - // which is desirable (at least for the known use of this feature, - // which is to signal - // that the property sheet can update itself. - fDelayer.touch(); - } - - public void release() { - fDelayer.cancel(); - if (textWidget != null && !textWidget.isDisposed()) { - textWidget.removeKeyListener(internalListener); - textWidget.removeMouseListener(internalListener); - textWidget = null; - } - } - - public synchronized void removeCaretListener(ICaretListener listener) { - if ((fCaretListeners != null) && (listener != null)) { - // if its not in the listeners, we'll ignore the request - if (Utilities.contains(fCaretListeners, listener)) { - int oldSize = fCaretListeners.length; - int newSize = oldSize - 1; - ICaretListener[] newListeners = new ICaretListener[newSize]; - int index = 0; - for (int i = 0; i < oldSize; i++) { - if (fCaretListeners[i] == listener) { // ignore - } else { - // copy old to new if its not the one we are removing - newListeners[index++] = fCaretListeners[i]; - } - } - // now that we have a new array, let's switch it for the old - // one - fCaretListeners = newListeners; - } - } - } - - public void setTextWidget(StyledText newTextWidget) { - if(fDelayer == null) { - fDelayer = new RefreshDelayJob(DELAY); - } - - // unhook from previous, if any - if (this.textWidget != null) { - fDelayer.cancel(); - this.textWidget.removeKeyListener(internalListener); - this.textWidget.removeMouseListener(internalListener); - } - - this.textWidget = newTextWidget; - - if (internalListener == null) { - internalListener = new CaretMediatorListener(); - } - - if (this.textWidget != null) { - this.textWidget.addKeyListener(internalListener); - this.textWidget.addMouseListener(internalListener); - } - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/CustomFilterPropertyTester.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/CustomFilterPropertyTester.java deleted file mode 100644 index d646039df5..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/CustomFilterPropertyTester.java +++ /dev/null @@ -1,32 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal; - -import org.eclipse.core.expressions.PropertyTester; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.views.contentoutline.IContentOutlinePage; -import org.eclipse.wst.sse.ui.internal.contentoutline.ConfigurableContentOutlinePage; - -public class CustomFilterPropertyTester extends PropertyTester { - /* - * (non-Javadoc) - * - * @see org.eclipse.core.expressions.IPropertyTester#test(java.lang.Object, - * java.lang.String, java.lang.Object[], java.lang.Object) - */ - public boolean test(Object receiver, String property, Object[] args, Object expectedValue) { - if (receiver instanceof IEditorPart){ - return ((IEditorPart) receiver).getAdapter(IContentOutlinePage.class) instanceof ConfigurableContentOutlinePage; - } - return false; - } - -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/ExtendedConfigurationBuilder.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/ExtendedConfigurationBuilder.java deleted file mode 100644 index 8ec6fa861a..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/ExtendedConfigurationBuilder.java +++ /dev/null @@ -1,280 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.eclipse.core.runtime.IConfigurationElement; -import org.eclipse.core.runtime.Platform; -import org.eclipse.swt.custom.BusyIndicator; -import org.eclipse.wst.sse.core.utils.StringUtils; -import org.eclipse.wst.sse.ui.internal.extension.RegistryReader; -import org.osgi.framework.Bundle; - - -/** - * Simple generic ID to class to mapping. Loads a specified class defined in a - * configuration element with the matching type and target ID. Example - * plugin.xml section: - * - * <extension - * point="org.eclipse.wst.sse.ui.editorConfiguration">contentoutlineconfiguration - * target="org.eclipse.wst.sse.dtd.core.dtdsource" - * class="org.eclipse.wst.sse.ui.dtd.views.contentoutline.DTDContentOutlineConfiguration"/> - * </extension> - * - * Used in code by getConfiguration("contentoutlineconfiguration", - * "org.eclipse.wst.dtd.ui.StructuredTextEditorDTD"); - * - */ -public class ExtendedConfigurationBuilder extends RegistryReader { - /** - * Extension type to pass into getConfigurations to get content outline - * configuration - */ - public static final String CONTENTOUTLINECONFIGURATION = "contentOutlineConfiguration"; //$NON-NLS-1$ - /** - * Extension type to pass into getConfigurations to get property sheet - * configuration - */ - public static final String PROPERTYSHEETCONFIGURATION = "propertySheetConfiguration"; //$NON-NLS-1$ - /** - * Extension type to pass into getConfigurations to get source viewer - * configuration - */ - public static final String SOURCEVIEWERCONFIGURATION = "sourceViewerConfiguration"; //$NON-NLS-1$ - /** - * Extension type to pass into getConfigurations to get documentation text - * hover - */ - public static final String DOCUMENTATIONTEXTHOVER = "documentationTextHover"; //$NON-NLS-1$ - /** - * Extension type to pass into getConfigurations to get double click - * strategy - */ - public static final String DOUBLECLICKSTRATEGY = "doubleClickStrategy"; //$NON-NLS-1$ - /** - * Extension type to pass into getConfigurations to get quick outline - * configuration - */ - public static final String QUICKOUTLINECONFIGURATION = "quickOutlineConfiguration"; //$NON-NLS-1$ - - private static final String ATT_CLASS = "class"; //$NON-NLS-1$ - private static final String ATT_TARGET = "target"; //$NON-NLS-1$ - private static final String ATT_TYPE = "type"; //$NON-NLS-1$ - private static final String CONFIGURATION = "provisionalConfiguration"; //$NON-NLS-1$ - private static Map configurationMap = null; - private final static boolean debugTime = "true".equalsIgnoreCase(Platform.getDebugOption("org.eclipse.wst.sse.ui/extendedconfigurationbuilder/time")); //$NON-NLS-1$ //$NON-NLS-2$ - private static final String DEFINITION = "provisionalDefinition"; //$NON-NLS-1$ - private static final String EP_EXTENDEDCONFIGURATION = "editorConfiguration"; //$NON-NLS-1$ - private static ExtendedConfigurationBuilder instance = null; - public static final String VALUE = "value"; //$NON-NLS-1$ - - /** - * Creates an extension. If the extension plugin has not been loaded a - * busy cursor will be activated during the duration of the load. - * - * @param element - * the config element defining the extension - * @param classAttribute - * the name of the attribute carrying the class - * @returns the extension object if successful. If an error occurs when - * createing executable extension, the exception is logged, and - * null returned. - */ - static Object createExtension(final IConfigurationElement element, final String classAttribute, final String targetID) { - final Object[] result = new Object[1]; - String pluginId = element.getDeclaringExtension().getNamespace(); - Bundle bundle = Platform.getBundle(pluginId); - if (bundle.getState() == Bundle.ACTIVE) { - try { - result[0] = element.createExecutableExtension(classAttribute); - } - catch (Exception e) { - // catch and log ANY exception while creating the extension - Logger.logException("error loading class " + classAttribute + " for " + targetID, e); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - else { - BusyIndicator.showWhile(null, new Runnable() { - public void run() { - try { - result[0] = element.createExecutableExtension(classAttribute); - } - catch (Exception e) { - // catch and log ANY exception from extension point - Logger.logException("error loading class " + classAttribute + " for " + targetID, e); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - }); - } - return result[0]; - } - - public synchronized static ExtendedConfigurationBuilder getInstance() { - if (instance == null) - instance = new ExtendedConfigurationBuilder(); - return instance; - } - - long time0 = 0; - - private ExtendedConfigurationBuilder() { - super(); - } - - private List createConfigurations(List configurations, String extensionType, String targetID) { - if (configurations == null) - return new ArrayList(0); - List result = new ArrayList(1); - for (int i = 0; i < configurations.size(); i++) { - IConfigurationElement element = (IConfigurationElement) configurations.get(i); - if ((element.getName().equals(extensionType) || (element.getName().equals(CONFIGURATION) && extensionType.equals(element.getAttribute(ATT_TYPE))))) { - String[] targets = StringUtils.unpack(element.getAttribute(ATT_TARGET)); - for (int j = 0; j < targets.length; j++) { - if (targetID.equals(targets[j].trim())) { - Object o = createExtension(element, ATT_CLASS, targetID); - if (o != null) { - result.add(o); - } - } - } - } - } - return result; - } - - private IConfigurationElement[] findConfigurationElements(List configurations, String extensionType, String targetID) { - if (configurations == null) - return new IConfigurationElement[0]; - List result = new ArrayList(1); - for (int i = 0; i < configurations.size(); i++) { - IConfigurationElement element = (IConfigurationElement) configurations.get(i); - if ((element.getName().equals(extensionType) || (element.getName().equals(DEFINITION) && extensionType.equals(element.getAttribute(ATT_TYPE))))) { - String[] targets = StringUtils.unpack(element.getAttribute(ATT_TARGET)); - for (int j = 0; j < targets.length; j++) { - if (targetID.equals(targets[j].trim())) { - result.add(element); - } - } - } - } - return (IConfigurationElement[]) result.toArray(new IConfigurationElement[0]); - } - - /** - * Returns a configuration for the given extensionType matching the - * targetID, if one is available. If more than one configuration is - * defined, the first one found is returned. - * - * @param extensionType - * @param targetID - * @return a configuration object, if one was defined - */ - public Object getConfiguration(String extensionType, String targetID) { - if (targetID == null || targetID.length() == 0) - return null; - List configurations = getConfigurations(extensionType, targetID); - if (configurations.isEmpty()) - return null; - return configurations.get(0); - } - - /** - * Returns all configurations for the given extensionType matching the - * targetID, if any are available. - * - * @param extensionType - * @param targetID - * @return a List of configuration objects, which may or may not be empty - */ - public List getConfigurations(String extensionType, String targetID) { - if (targetID == null || targetID.length() == 0) - return new ArrayList(0); - if (configurationMap == null) { - configurationMap = new HashMap(0); - synchronized (configurationMap) { - readRegistry(Platform.getExtensionRegistry(), SSEUIPlugin.ID, EP_EXTENDEDCONFIGURATION); - if (debugTime) { - System.out.println(getClass().getName() + "#readRegistry(): " + (System.currentTimeMillis() - time0) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ - time0 = System.currentTimeMillis(); - } - } - } - List extensions = (List) configurationMap.get(extensionType); - List configurations = createConfigurations(extensions, extensionType, targetID); - if (debugTime) { - if (!configurations.isEmpty()) - System.out.println(getClass().getName() + "#getConfiguration(" + extensionType + ", " + targetID + "): configurations loaded in " + (System.currentTimeMillis() - time0) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ - else - System.out.println(getClass().getName() + "#getConfiguration(" + extensionType + ", " + targetID + "): ran in " + (System.currentTimeMillis() - time0) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ - } - return configurations; - } - - /** - * Returns all declared definitions for the given extensionType matching - * the targetID, if any are available. - * - * @param extensionType - * @param targetID - * @return An array containing the definitions, empty if none were - * declared - */ - public String[] getDefinitions(String extensionType, String targetID) { - if (targetID == null || targetID.length() == 0) - return new String[0]; - if (debugTime) { - time0 = System.currentTimeMillis(); - } - if (configurationMap == null) { - configurationMap = new HashMap(0); - synchronized (configurationMap) { - readRegistry(Platform.getExtensionRegistry(), SSEUIPlugin.ID, EP_EXTENDEDCONFIGURATION); - if (debugTime) { - System.out.println(getClass().getName() + "#readRegistry(): " + (System.currentTimeMillis() - time0) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ - time0 = System.currentTimeMillis(); - } - } - } - List definitions = (List) configurationMap.get(extensionType); - IConfigurationElement[] elements = findConfigurationElements(definitions, extensionType, targetID); - String[] values = new String[elements.length]; - for (int i = 0; i < values.length; i++) { - values[i] = elements[i].getAttribute(VALUE); - } - if (debugTime) { - if (values.length > 0) - System.out.println(getClass().getName() + "#getDefinitions(" + extensionType + ", " + targetID + "): definition loaded in " + (System.currentTimeMillis() - time0) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ - else - System.out.println(getClass().getName() + "#getDefinitions(" + extensionType + ", " + targetID + "): ran in " + (System.currentTimeMillis() - time0) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ - } - return values; - } - - protected boolean readElement(IConfigurationElement element) { - String name = element.getName(); - if (name.equals(CONFIGURATION) || name.equals(DEFINITION)) - name = element.getAttribute(ATT_TYPE); - List configurations = (List) configurationMap.get(name); - if (configurations == null) { - configurations = new ArrayList(1); - configurationMap.put(name, configurations); - } - configurations.add(element); - return true; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/ExtendedEditorActionBuilder.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/ExtendedEditorActionBuilder.java deleted file mode 100644 index 0277646c12..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/ExtendedEditorActionBuilder.java +++ /dev/null @@ -1,789 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2007 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.eclipse.core.runtime.IConfigurationElement; -import org.eclipse.core.runtime.IExtensionRegistry; -import org.eclipse.core.runtime.Platform; -import org.eclipse.jface.action.ActionContributionItem; -import org.eclipse.jface.action.IAction; -import org.eclipse.jface.action.IContributionItem; -import org.eclipse.jface.action.IMenuListener; -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.text.IDocument; -import org.eclipse.jface.text.ITextSelection; -import org.eclipse.swt.graphics.Point; -import org.eclipse.ui.IActionBars; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.IEditorSite; -import org.eclipse.ui.IKeyBindingService; -import org.eclipse.ui.IWorkbenchActionConstants; -import org.eclipse.ui.IWorkbenchPage; -import org.eclipse.ui.part.MultiPageEditorSite; -import org.eclipse.ui.texteditor.IUpdate; -import org.eclipse.wst.sse.ui.internal.extension.ActionDescriptor; -import org.eclipse.wst.sse.ui.internal.extension.IExtendedEditorActionProxyForDelayLoading; -import org.eclipse.wst.sse.ui.internal.extension.RegistryReader; -import org.eclipse.wst.sse.ui.internal.provisional.extensions.ISourceEditingTextTools; - - -/** - * This class reads the registry for extensions that plug into 'editorActions' - * extension point. - */ - -public class ExtendedEditorActionBuilder extends RegistryReader { - - public class ExtendedContributor implements IExtendedContributor, IMenuListener { - private IExtendedSimpleEditor activeExtendedEditor = null; - - private List cache; - private Map map = new HashMap(); - private IMenuManager menuBar = null; - - private Set menus = new HashSet(); - - public ExtendedContributor(List cache) { - this.cache = cache; - } - - private IExtendedSimpleEditor computeExtendedEditor(final IEditorPart editor) { - IExtendedSimpleEditor simpleEditor = null; - if (editor instanceof IExtendedSimpleEditor) { - simpleEditor = (IExtendedSimpleEditor) editor; - } - if (editor != null && simpleEditor == null) { - final ISourceEditingTextTools tools = (ISourceEditingTextTools) editor.getAdapter(ISourceEditingTextTools.class); - if (tools != null) { - simpleEditor = new IExtendedSimpleEditor() { - public int getCaretPosition() { - return tools.getCaretOffset(); - } - - public IDocument getDocument() { - return tools.getDocument(); - } - - public IEditorPart getEditorPart() { - return tools.getEditorPart(); - } - - public Point getSelectionRange() { - ITextSelection selection = tools.getSelection(); - return new Point(selection.getOffset(), selection.getOffset() + selection.getLength()); - } - - }; - } - } - return simpleEditor; - } - - public void contributeToMenu(IMenuManager menu) { - menuBar = menu; - long time0 = System.currentTimeMillis(); - for (int i = 0; i < cache.size(); i++) { - Object obj = cache.get(i); - if (obj instanceof IConfigurationElement) { - IConfigurationElement menuElement = (IConfigurationElement) obj; - if ((menuElement.getName()).equals(TAG_MENU)) { - contributeMenu(menuElement, menu, true); - if (debugMenu) - System.out.println(getClass().getName() + "#contributeToMenu() added: " + menuElement.getAttribute(ATT_ID)); //$NON-NLS-1$ - } - } - else if (obj instanceof ActionDescriptor) { - try { - ActionDescriptor ad = (ActionDescriptor) obj; - IMenuManager mm = contributeMenuAction(ad, menu, true, false); - if (mm != null) { - map.put(ad.getContributionItem(), mm); - mm.addMenuListener(this); - menus.add(mm); - if (debugMenu) - System.out.println(getClass().getName() + "#contributeToMenu() added: " + ad.getId()); //$NON-NLS-1$ - } - } - catch (Exception e) { - Logger.logException("contributing to menu", e); //$NON-NLS-1$ - } - } - } - if (debugContributeTime) - System.out.println(getClass().getName() + "#contributeToMenu(): ran in " + (System.currentTimeMillis() - time0) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ - } - - public void contributeToPopupMenu(IMenuManager menu) { - long time0 = System.currentTimeMillis(); - for (int i = 0; i < cache.size(); i++) { - Object obj = cache.get(i); - if (obj instanceof IConfigurationElement) { - IConfigurationElement menuElement = (IConfigurationElement) obj; - if ((menuElement.getName()).equals(TAG_POPUPMENU)) { - contributeMenu(menuElement, menu, true); - } - } - else if (obj instanceof ActionDescriptor) { - try { - ActionDescriptor ad = (ActionDescriptor) obj; - IAction a = ad.getAction(); - if (a instanceof IExtendedEditorAction) { - // uncaught exceptions could cause the menu to not - // be shown - try { - if (((ad.getPopupMenuPath() != null) || (ad.getPopupMenuGroup() != null)) && (a instanceof IExtendedEditorActionProxyForDelayLoading)) { - ((IExtendedEditorActionProxyForDelayLoading)a).realize(); - } - - IExtendedEditorAction eea = (IExtendedEditorAction) a; - eea.setActiveExtendedEditor(activeExtendedEditor); - eea.update(); - if (eea.isVisible()) { - IMenuManager parent = contributeMenuAction(ad, menu, true, true); - if (debugPopup && parent != null) - System.out.println(getClass().getName() + "#contributeToPopupMenu() added: " + ad.getId()); //$NON-NLS-1$ - } - } - catch (Exception e) { - Logger.logException(e); - } - - } - else { - IMenuManager parent = contributeMenuAction(ad, menu, true, true); - if (debugPopup && parent != null) - System.out.println(getClass().getName() + "#contributeToPopupMenu() added: " + ad.getId()); //$NON-NLS-1$ - } - } - catch (Exception e) { - Logger.logException("contributing to popup", e); //$NON-NLS-1$ - } - } - } - if (debugContributeTime) - System.out.println(getClass().getName() + "#contributeToPopupMenu(): ran in " + (System.currentTimeMillis() - time0) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ - } - - public void contributeToStatusLine(IStatusLineManager manager) { - // nothing from here - } - - public void contributeToToolBar(IToolBarManager manager) { - long time0 = System.currentTimeMillis(); - for (int i = 0; i < cache.size(); i++) { - Object obj = cache.get(i); - if (obj instanceof ActionDescriptor) { - try { - ActionDescriptor ad = (ActionDescriptor) obj; - IAction a = ad.getAction(); - if (a instanceof IExtendedEditorAction) { - if (((ad.getToolbarPath() != null) || (ad.getToolbarGroup() != null)) && (a instanceof IExtendedEditorActionProxyForDelayLoading)) { - ((IExtendedEditorActionProxyForDelayLoading)a).realize(); - } - IExtendedEditorAction eea = (IExtendedEditorAction) a; - eea.setActiveExtendedEditor(activeExtendedEditor); - eea.update(); - if (eea.isVisible()) { - boolean contributed = contributeToolbarAction(ad, manager, true); - if (debugToolbar && contributed) - System.out.println(getClass().getName() + "#contributeToToolBar() added: " + ad.getId()); //$NON-NLS-1$ - } - else { - if (debugToolbar) - System.out.println(getClass().getName() + "#contributeToToolBar(): [skipped] " + ad.getId()); //$NON-NLS-1$ - } - } - else { - boolean contributed = contributeToolbarAction(ad, manager, true); - if (debugToolbar && contributed) - System.out.println(getClass().getName() + "#contributeToToolBar() added: " + ad.getId()); //$NON-NLS-1$ - } - } - catch (Exception e) { - Logger.logException("contributing to toolbar", e); //$NON-NLS-1$ - } - } - } - if (debugContributeTime) - System.out.println(getClass().getName() + "#contributeToToolBar(): ran in " + (System.currentTimeMillis() - time0) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ - } - - public void dispose() { - Iterator it = menus.iterator(); - while (it.hasNext()) { - Object o = it.next(); - if (o instanceof IMenuManager) { - ((IMenuManager) o).removeMenuListener(this); - } - } - } - - public void init(IActionBars bars, IWorkbenchPage page) { - // nothing from here - } - - public void menuAboutToShow(IMenuManager menu) { - // slows down the menu and interferes with it for other editors; - // optimize on visibility - IEditorSite site = null; - boolean activeEditorIsVisible = false; - - if (activeExtendedEditor != null && activeExtendedEditor.getEditorPart() != null) - site = activeExtendedEditor.getEditorPart().getEditorSite(); - if (site == null) - return; - - // Eclipse bug 48784 - [MPE] ClassCast exception Workbench page - // isPartVisiable for MultiPageSite - if (site instanceof MultiPageEditorSite) { - Object multiPageEditor = ((MultiPageEditorSite) site).getMultiPageEditor(); - activeEditorIsVisible = multiPageEditor.equals(site.getPage().getActiveEditor()) || multiPageEditor.equals(site.getPage().getActivePart()); - } - else { - activeEditorIsVisible = site.getWorkbenchWindow().getPartService().getActivePart().equals(activeExtendedEditor.getEditorPart()); - } - // due to a delay class loading, don't return now -// if (!activeEditorIsVisible) -// return; - - IContributionItem[] items = menu.getItems(); - if (items == null || items.length == 0) - return; - - for (int i = 0; i < items.length; ++i) { - // add menu listener to submenu - if (items[i] instanceof IMenuManager) { - ((IMenuManager) items[i]).addMenuListener(this); - menus.add(items[i]); - } - } - - Set keys = map.keySet(); - Iterator it = keys.iterator(); - boolean needActionContributionItemUpdate = false; - while (it.hasNext()) { - IContributionItem item = (IContributionItem) it.next(); - IMenuManager mm = (IMenuManager) map.get(item); - if (menu.getId() != null && menu.getId().equals(mm.getId()) && item instanceof ActionContributionItem) { - try { - IAction action = ((ActionContributionItem) item).getAction(); - - if (action instanceof IExtendedEditorActionProxyForDelayLoading) { - IExtendedEditorActionProxyForDelayLoading eea = (IExtendedEditorActionProxyForDelayLoading)action; - if (eea.isBundleActive() == true && eea.isRealized() == false) { - eea.realize(); - needActionContributionItemUpdate = true; - } - } - - if (activeEditorIsVisible || needActionContributionItemUpdate) { - if (action instanceof IUpdate) { - ((IUpdate) action).update(); - } - } - - if (activeEditorIsVisible || needActionContributionItemUpdate) { - boolean visible = true; - if (action instanceof IExtendedEditorAction) { - visible = ((IExtendedEditorAction) action).isVisible(); - } - item.setVisible(visible); - } - - if (needActionContributionItemUpdate) { - ((ActionContributionItem)item).update(); - } - - } - catch (Exception e) { - Logger.logException("updating actions", e); //$NON-NLS-1$ - } - } - } - if (activeEditorIsVisible || needActionContributionItemUpdate) { - if (needActionContributionItemUpdate) { - // the action is realized so that need to update the menu w/ - // force set to true - menu.update(true); - } else { - menu.update(false); - } - } - } - - public void setActiveEditor(IEditorPart editor) { - activeExtendedEditor = computeExtendedEditor(editor); - IKeyBindingService svc = (editor != null) ? editor.getEditorSite().getKeyBindingService() : null; - for (int i = 0; i < cache.size(); i++) { - Object obj = cache.get(i); - if (obj instanceof ActionDescriptor) { - ActionDescriptor ad = (ActionDescriptor) obj; - try { - IAction action = ad.getAction(); - if (action instanceof IExtendedEditorAction) { - ((IExtendedEditorAction) action).setActiveExtendedEditor(activeExtendedEditor); - ((IExtendedEditorAction) action).update(); - // update visibility right now so that the menu - // will show/hide properly - if (!((IExtendedEditorAction) action).isVisible() && ad.getContributionItem() != null) - ad.getContributionItem().setVisible(false); - if (svc != null && action.getActionDefinitionId() != null) { - svc.registerAction(action); - } - } - } - catch (Exception e) { - Logger.logException("setting active editor on actions", e); //$NON-NLS-1$ - } - } - } - - if (menuBar != null && editor != null) { - // Class clz = editor.getClass(); - // while (clz != null) { - // if (clz.getName().equals(targetID)) { - // contributeToMenu(menuBar); - // break; - // } - // clz = clz.getSuperclass(); - // } - if (targetIDs.contains(editor.getEditorSite().getId())) { - contributeToMenu(menuBar); - } - } - - updateToolbarActions(); - } - - public void updateToolbarActions() { - for (int i = 0; i < cache.size(); i++) { - Object obj = cache.get(i); - if (obj instanceof ActionDescriptor) { - try { - ActionDescriptor ad = (ActionDescriptor) obj; - if (ad.getToolbarPath() != null) { - IAction action = ad.getAction(); - if (action instanceof IUpdate) { - ((IUpdate) action).update(); - } - } - } - catch (Exception e) { - Logger.logException("updating toolbar actions", e); //$NON-NLS-1$ - } - } - } - } - } - - public static final String ATT_ID = "id"; //$NON-NLS-1$ - public static final String ATT_LABEL = "label"; //$NON-NLS-1$ - public static final String ATT_NAME = "name"; //$NON-NLS-1$ - public static final String ATT_PATH = "path"; //$NON-NLS-1$ - - public static final String ATT_TARGET_ID = "targetID"; //$NON-NLS-1$ - protected final static boolean debugContributeTime = "true".equalsIgnoreCase(Platform.getDebugOption("org.eclipse.wst.sse.ui/extendededitoractionbuilder/contributetime")); //$NON-NLS-1$ //$NON-NLS-2$ - - protected final static boolean debugMenu = "true".equalsIgnoreCase(Platform.getDebugOption("org.eclipse.wst.sse.ui/extendededitoractionbuilder/debugmenu")); //$NON-NLS-1$ //$NON-NLS-2$; - protected final static boolean debugPopup = "true".equalsIgnoreCase(Platform.getDebugOption("org.eclipse.wst.sse.ui/extendededitoractionbuilder/debugpopup")); //$NON-NLS-1$ //$NON-NLS-2$; - protected final static boolean debugReadTime = "true".equalsIgnoreCase(Platform.getDebugOption("org.eclipse.wst.sse.ui/extendededitoractionbuilder/readtime")); //$NON-NLS-1$ //$NON-NLS-2$ - protected final static boolean debugToolbar = "true".equalsIgnoreCase(Platform.getDebugOption("org.eclipse.wst.sse.ui/extendededitoractionbuilder/debugtoolbar")); //$NON-NLS-1$ //$NON-NLS-2$; - - private static final String EXTENDED_EDITOR = "extendedEditor"; //$NON-NLS-1$ - - public static final String PL_EXTENDED_EDITOR_ACTIONS = "extendedEditorActions"; //$NON-NLS-1$ - - public static final String PLUGIN_ID = "org.eclipse.wst.sse.ui"; //$NON-NLS-1$ - public static final String TAG_ACTION = "action"; //$NON-NLS-1$ - - public static final String TAG_CONTRIBUTION_TYPE = "editorContribution"; //$NON-NLS-1$ - - public static final String TAG_MENU = "menu"; //$NON-NLS-1$ - public static final String TAG_POPUPMENU = "popupmenu"; //$NON-NLS-1$ - public static final String TAG_RULERMENU = "rulermenu"; //$NON-NLS-1$ - public static final String TAG_SEPARATOR = "separator"; //$NON-NLS-1$ - - protected List readingCache; - - protected String targetContributionTag; - protected List targetIDs; - - /** - * The constructor. - */ - public ExtendedEditorActionBuilder() { - super(); - } - - /** - * Creates a menu from the information in the menu configuration element - * and adds it into the provided menu manager. If 'appendIfMissing' is - * true, and menu path slot is not found, it will be created and menu will - * be added into it. Otherwise, add operation will fail. - */ - protected void contributeMenu(IConfigurationElement menuElement, IMenuManager mng, boolean appendIfMissing) { - // Get config data. - String id = menuElement.getAttribute(ATT_ID); - String label = menuElement.getAttribute(ATT_LABEL); - String path = menuElement.getAttribute(ATT_PATH); - if (label == null) { - Logger.log(Logger.ERROR, "Invalid Menu Extension (label == null): " + id); //$NON-NLS-1$ - return; - } - - // Calculate menu path and group. - String group = null; - if (path != null) { - int loc = path.lastIndexOf('/'); - if (loc != -1) { - group = path.substring(loc + 1); - path = path.substring(0, loc); - } - else { - // assume that path represents a slot - // so actual path portion should be null - group = path; - path = null; - } - } - - // Find parent menu. - IMenuManager parent = mng; - if (path != null) { - parent = mng.findMenuUsingPath(path); - if (parent == null) { - // Logger.log("Invalid Menu Extension (Path is invalid): " + - // id);//$NON-NLS-1$ - return; - } - // IMenuManager.findMenuUsingPath() returns invisible menu item if - // the manager can't find - // the specified path and create new MenuManager for it. - // I don't know this is a specification or bug. - // Anyway, to ensure the menu can be visible, setVisible(true) - // needs to be called. - parent.setVisible(true); - } - - // Find reference group. - if (group == null) - group = IWorkbenchActionConstants.MB_ADDITIONS; - IContributionItem sep = parent.find(group); - if (sep == null) { - if (appendIfMissing) - parent.add(new Separator(group)); - else { - Logger.log(Logger.ERROR, "Invalid Menu Extension (Group is invalid): " + id); //$NON-NLS-1$ - return; - } - } - - // If the menu does not exist create it. - IMenuManager newMenu = parent.findMenuUsingPath(id); - if (newMenu == null) - newMenu = new MenuManager(label, id); - - // Create separators. - IConfigurationElement[] children = menuElement.getChildren(TAG_SEPARATOR); - for (int i = 0; i < children.length; i++) { - contributeSeparator(newMenu, children[i]); - } - - // Add new menu - try { - parent.insertAfter(group, newMenu); - } - catch (IllegalArgumentException e) { - Logger.log(Logger.ERROR, "Invalid Menu Extension (Group is missing): " + id); //$NON-NLS-1$ - } - } - - /** - * Contributes action from action descriptor into the provided menu - * manager. - */ - protected IMenuManager contributeMenuAction(ActionDescriptor ad, IMenuManager menu, boolean appendIfMissing, boolean popupmenu) { - if (ad.getContributionItem() == null || ad.getAction() == null) - return null; - - // Get config data. - String mpath = popupmenu ? ad.getPopupMenuPath() : ad.getMenuPath(); - String mgroup = popupmenu ? ad.getPopupMenuGroup() : ad.getMenuGroup(); - if (mpath == null && mgroup == null) - return null; - - // Find parent menu. - IMenuManager parent = menu; - if (mpath != null) { - parent = parent.findMenuUsingPath(mpath); - if (parent == null) { - // Logger.log("Invalid Menu Extension (Path is invalid): " + - // ad.getId()); //$NON-NLS-1$ - return null; - } - // IMenuManager.findMenuUsingPath() returns invisible menu item if - // the manager can't find - // the specified path and create new MenuManager for it. - // I don't know this is a specification or bug. - // Anyway, to ensure the menu can be visible, setVisible(true) - // needs to be called. - parent.setVisible(true); - } - - // First remove existing menu item - IContributionItem item = parent.find(ad.getId()); - if (item != null) { - parent.remove(ad.getId()); - } - - // Find reference group. - if (mgroup == null) - mgroup = IWorkbenchActionConstants.MB_ADDITIONS; - IContributionItem sep = parent.find(mgroup); - if (sep == null) { - if (appendIfMissing) - parent.add(sep = new Separator(mgroup)); - else { - Logger.log(Logger.ERROR, "Invalid Menu Extension (Group is invalid): " + ad.getId()); //$NON-NLS-1$ - return null; - } - } - - // Add action. - try { - if (popupmenu) { - // Context menu need a newly created contribution item - if (sep != null && sep.isGroupMarker()) - parent.appendToGroup(sep.getId(), ad.getAction()); - else - parent.insertAfter(mgroup, ad.getAction()); - } - else { - // Normal menu need to add existing contribution item to - // remove it from menu listener - if (sep != null && sep.isGroupMarker()) - parent.appendToGroup(sep.getId(), ad.getContributionItem()); - else - parent.insertAfter(mgroup, ad.getContributionItem()); - } - } - catch (IllegalArgumentException e) { - Logger.log(Logger.ERROR, "Invalid Menu Extension (Group is missing): " + ad.getId()); //$NON-NLS-1$ - parent = null; - } - - return parent; - } - - /** - * Creates a named menu separator from the information in the - * configuration element. If the separator already exists do not create a - * second. - */ - protected boolean contributeSeparator(IMenuManager menu, IConfigurationElement element) { - String id = element.getAttribute(ATT_NAME); - if (id == null || id.length() <= 0) - return false; - IContributionItem sep = menu.find(id); - if (sep != null) - return false; - menu.add(new Separator(id)); - return true; - } - - /** - * Contributes action from the action descriptor into the provided tool - * bar manager. - */ - protected boolean contributeToolbarAction(ActionDescriptor ad, IToolBarManager toolbar, boolean appendIfMissing) { - if (ad.getContributionItem() == null || ad.getAction() == null) - return false; - - // Get config data. - String tpath = ad.getToolbarPath(); - String tgroup = ad.getToolbarGroup(); - if (tpath == null && tgroup == null) - return false; - - // First remove existing toolbar item - IContributionItem item = toolbar.find(ad.getId()); - if (item != null) { - toolbar.remove(ad.getId()); - } - - // Find reference group. - if (tgroup == null) - tgroup = IWorkbenchActionConstants.MB_ADDITIONS; - IContributionItem sep = toolbar.find(tgroup); - if (sep == null) { - if (appendIfMissing) - toolbar.add(new Separator(tgroup)); - else { - Logger.log(Logger.ERROR, "Invalid Toolbar Extension (Group is invalid): " + ad.getId()); //$NON-NLS-1$ - return false; - } - } - - // Add action to tool bar. - try { - if (sep != null && sep.isGroupMarker()) - toolbar.appendToGroup(sep.getId(), ad.getAction()); - else - toolbar.insertAfter(tgroup, ad.getAction()); - } - catch (IllegalArgumentException e) { - Logger.log(Logger.ERROR, "Invalid Toolbar Extension (Group is missing): " + ad.getId()); //$NON-NLS-1$ - return false; - } - return true; - } - - /** - * This factory method returns a new ActionDescriptor for the - * configuration element. It should be implemented by subclasses. - */ - protected ActionDescriptor createActionDescriptor(IConfigurationElement element) { - ActionDescriptor ad = null; - try { - ad = new ActionDescriptor(element); - // these cases like "class not found" are handled - // at lower level, so no action if formed. In that - // case, we also don't want to form an action descriptor. - if ((ad != null) && (ad.getAction() == null)) { - ad = null; - } - } - catch (Exception e) { - Logger.traceException(EXTENDED_EDITOR, e); - ad = null; - } - return ad; - } - - /** - * Returns the name of the part ID attribute that is expected in the - * target extension. - */ - protected String getTargetID(IConfigurationElement element) { - String value = element.getAttribute(ATT_TARGET_ID); - return value != null ? value : "???"; //$NON-NLS-1$ - } - - /** - * Reads editor contributor if specified directly in the 'editor' - * extension point, and all external contributions for this editor's ID - * registered in 'editorActions' extension point. - */ - public IExtendedContributor readActionExtensions(String editorId) { - return readActionExtensions(new String[]{editorId}); - } - - /** - * Reads editor contributor if specified directly in the 'editor' - * extension point, and all external contributions for this editor's ID - * registered in 'editorActions' extension point. - */ - public IExtendedContributor readActionExtensions(String[] ids) { - long time0 = System.currentTimeMillis(); - ExtendedContributor ext = null; - readContributions(ids, TAG_CONTRIBUTION_TYPE, PL_EXTENDED_EDITOR_ACTIONS); - if (debugReadTime) { - String idlist = ""; //$NON-NLS-1$ - if (ids.length > 0) { - for (int i = 0; i < ids.length; i++) { - idlist += ids[i]; - if (i < ids.length - 1) - idlist += ","; //$NON-NLS-1$ - } - } - System.out.println(getClass().getName() + "#readActionExtensions(" + idlist + "): read in " + (System.currentTimeMillis() - time0) + "ms [" + (readingCache != null ? readingCache.size() : 0) + " contributions]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ - } - if (readingCache != null) { - ext = new ExtendedContributor(readingCache); - readingCache = null; - } - return ext; - } - - /** - * Reads the contributions from the registry for the provided workbench - * part and the provided extension point IDs. - */ - protected void readContributions(String[] ids, String tag, String extensionPoint) { - readingCache = null; - targetIDs = Arrays.asList(ids); - targetContributionTag = tag; - IExtensionRegistry registry = Platform.getExtensionRegistry(); - readRegistry(registry, PLUGIN_ID, extensionPoint); - } - - /** - * Implements abstract method to handle the provided XML element in the - * registry. - */ - protected boolean readElement(IConfigurationElement element) { - String tag = element.getName(); - if (tag.equals(targetContributionTag)) { - String id = getTargetID(element); - if (id == null || !targetIDs.contains(id)) { - // This is not of interest to us - don't go deeper - return true; - } - } - else if (tag.equals(TAG_MENU)) { - if (readingCache == null) - readingCache = new ArrayList(); - readingCache.add(element); - return true; // just cache the element - don't go into it - } - else if (tag.equals(TAG_POPUPMENU)) { - if (readingCache == null) - readingCache = new ArrayList(); - readingCache.add(element); - return true; // just cache the element - don't go into it - } - else if (tag.equals(TAG_RULERMENU)) { - if (readingCache == null) - readingCache = new ArrayList(); - readingCache.add(element); - return true; // just cache the element - don't go into it - } - else if (tag.equals(TAG_ACTION)) { - if (readingCache == null) - readingCache = new ArrayList(); - ActionDescriptor ad = createActionDescriptor(element); - if (ad != null) - readingCache.add(ad); - return true; // just cache the action - don't go into - } - else { - return false; - } - - readElementChildren(element); - return true; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/ExtendedEditorDropTargetAdapter.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/ExtendedEditorDropTargetAdapter.java deleted file mode 100644 index bf0b04ef20..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/ExtendedEditorDropTargetAdapter.java +++ /dev/null @@ -1,213 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal; - -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.swt.dnd.DND; -import org.eclipse.swt.dnd.DropTargetAdapter; -import org.eclipse.swt.dnd.DropTargetEvent; -import org.eclipse.swt.dnd.FileTransfer; -import org.eclipse.swt.dnd.Transfer; -import org.eclipse.swt.dnd.TransferData; -import org.eclipse.swt.graphics.Point; -import org.eclipse.ui.IEditorPart; -import org.eclipse.wst.sse.ui.StructuredTextEditor; -import org.eclipse.wst.sse.ui.internal.TransferBuilder.TransferProxyForDelayLoading; - -/** - * ExtendedEditorDropTargetAdapter - */ -public class ExtendedEditorDropTargetAdapter extends DropTargetAdapter { - private String[] editorIds; - private Point originalRange = null; - private IEditorPart targetEditor = null; - private ITextViewer textViewer = null; - - private Transfer[] transfers = null; - - private boolean useProxy; - - /** - * @deprecated use ExtendedEditorDropTargetAdapter(boolean useProxy) for - * the performance - */ - public ExtendedEditorDropTargetAdapter() { - this(false); - } - - public ExtendedEditorDropTargetAdapter(boolean useProxy) { - super(); - this.useProxy = useProxy; - } - - protected boolean doDrop(Transfer transfer, DropTargetEvent event) { - TransferBuilder tb = new TransferBuilder(useProxy); - - IDropAction[] as = null; - if (editorIds != null && editorIds.length > 0) - as = tb.getDropActions(editorIds, transfer); - else - as = tb.getDropActions(getTargetEditor().getClass().getName(), transfer); - - for (int i = 0; i < as.length; ++i) { - IDropAction da = as[i]; - Transfer actualTransfer; - if (transfer instanceof TransferProxyForDelayLoading) { - actualTransfer = ((TransferProxyForDelayLoading) transfer).getTransferClass(); - } - else { - actualTransfer = transfer; - } - if (actualTransfer instanceof FileTransfer) { - if (event.data == null) { - Logger.log(Logger.ERROR, "No data in DropTargetEvent from " + event.widget); //$NON-NLS-1$ - return false; - } - String[] strs = (String[]) event.data; - boolean[] bs = new boolean[strs.length]; - int c = 0; - for (int j = 0; j < strs.length; ++j) { - bs[j] = false; - if (da.isSupportedData(strs[j])) { - event.data = new String[]{strs[j]}; - if (!da.run(event, targetEditor)) { - bs[j] = true; - c++; - } - } - else { - bs[j] = true; - c++; - } - } - if (c == 0) { - return true; - } - - int k = 0; - String[] rests = new String[c]; - for (int j = 0; j < strs.length; ++j) { - if (bs[j]) - rests[k++] = strs[j]; - } - event.data = rests; - } - else if (da.isSupportedData(event.data)) { - if (da.run(event, targetEditor)) { - return true; - } - } - } - - return false; - } - - /** - */ - public void dragEnter(DropTargetEvent event) { - TransferData data = null; - Transfer[] ts = getTransfers(); - for (int i = 0; i < ts.length; i++) { - for (int j = 0; j < event.dataTypes.length; j++) { - if (ts[i].isSupportedType(event.dataTypes[j])) { - data = event.dataTypes[j]; - break; - } - } - if (data != null) { - event.currentDataType = data; - break; - } - } - - if (textViewer != null) { - originalRange = textViewer.getSelectedRange(); - } - } - - public void dragLeave(DropTargetEvent event) { - if (textViewer != null) { - textViewer.setSelectedRange(originalRange.x, originalRange.y); - } - else { - originalRange = null; - } - } - - /** - * Scroll the visible area as needed - */ - public void dragOver(DropTargetEvent event) { - event.operations &= ~DND.DROP_MOVE; - event.detail = DND.DROP_COPY; - event.feedback |= DND.FEEDBACK_SCROLL; - } - - /** - */ - public void drop(DropTargetEvent event) { - if (event.operations == DND.DROP_NONE) - return; - - Transfer[] ts = getTransfers(); - for (int i = 0; i < ts.length; i++) { - if (ts[i].isSupportedType(event.currentDataType)) { - if (doDrop(ts[i], event)) { - IEditorPart part = targetEditor; - if (targetEditor instanceof StructuredTextEditor){ - part = ((StructuredTextEditor) targetEditor).getEditorPart(); - } - targetEditor.getSite().getPage().activate(part); - break; - } - } - } - } - - public IEditorPart getTargetEditor() { - return targetEditor; - } - - public ITextViewer getTextViewer() { - return textViewer; - } - - /** - * @return org.eclipse.swt.dnd.Transfer[] - */ - public Transfer[] getTransfers() { - if (transfers == null) { - TransferBuilder tb = new TransferBuilder(useProxy); - if (editorIds == null || editorIds.length == 0) - transfers = tb.getDropTargetTransfers(getTargetEditor().getClass().getName()); - else - transfers = tb.getDropTargetTransfers(editorIds); - } - return transfers; - } - - /** - */ - public void setTargetEditor(IEditorPart targetEditor) { - this.targetEditor = targetEditor; - } - - public void setTargetIDs(String[] ids) { - editorIds = ids; - } - - public void setTextViewer(ITextViewer textViewer) { - this.textViewer = textViewer; - } - -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/FileDropAction.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/FileDropAction.java deleted file mode 100644 index a68de9ef38..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/FileDropAction.java +++ /dev/null @@ -1,47 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IWorkspaceRoot; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.Path; -import org.eclipse.swt.dnd.DropTargetEvent; -import org.eclipse.ui.IEditorPart; - -/** - * Action for file drop - */ -public class FileDropAction extends AbstractDropAction { - public boolean run(DropTargetEvent event, IEditorPart targetEditor) { - String[] strs = (String[]) event.data; - if (strs == null || strs.length == 0) { - return false; - } - - String str = ""; //$NON-NLS-1$ - for (int i = 0; i < strs.length; ++i) { - IPath path = new Path(strs[i]); - IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); - IFile file = root.getFileForLocation(path); - if (file != null) { - path = file.getProjectRelativePath(); - } - - str += "\"" + path.toString() + "\""; //$NON-NLS-1$ //$NON-NLS-2$ - } - - return insert(str, targetEditor); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/FormatProcessorsExtensionReader.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/FormatProcessorsExtensionReader.java deleted file mode 100644 index a8f10aba1f..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/FormatProcessorsExtensionReader.java +++ /dev/null @@ -1,102 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import org.eclipse.core.runtime.IConfigurationElement; -import org.eclipse.core.runtime.IExtensionRegistry; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.content.IContentType; -import org.eclipse.core.runtime.content.IContentTypeManager; -import org.eclipse.wst.sse.core.internal.format.IStructuredFormatProcessor; -import org.eclipse.wst.sse.ui.internal.extension.RegistryReader; -import org.osgi.framework.Bundle; - -public class FormatProcessorsExtensionReader extends RegistryReader { - private static FormatProcessorsExtensionReader instance; - - public synchronized static FormatProcessorsExtensionReader getInstance() { - if (instance == null) { - instance = new FormatProcessorsExtensionReader(); - - IExtensionRegistry registry = Platform.getExtensionRegistry(); - instance.readRegistry(registry, "org.eclipse.wst.sse.core", "formatProcessors"); //$NON-NLS-1$ //$NON-NLS-2$ - } - return instance; - } - - private Map map = new HashMap(); -// TODO: private field never read locally - String processorClassName; - - public IStructuredFormatProcessor getFormatProcessor(String contentTypeId) { - if (contentTypeId == null) - return null; - - IStructuredFormatProcessor formatProcessor = null; - if (map.containsKey(contentTypeId)) { - formatProcessor = (IStructuredFormatProcessor) map.get(contentTypeId); - } else { - IContentTypeManager manager = Platform.getContentTypeManager(); - IContentType queryContentType = manager.getContentType(contentTypeId); - boolean found = false; - for (Iterator iter = map.keySet().iterator(); iter.hasNext();) { - String elementContentTypeId = (String) iter.next(); - IContentType elementContentType = manager.getContentType(elementContentTypeId); - if (queryContentType.isKindOf(elementContentType)) { - formatProcessor = (IStructuredFormatProcessor) map.get(elementContentTypeId); - map.put(contentTypeId, formatProcessor); - found = true; - break; - } - } - - if (!found) - map.put(contentTypeId, null); - } - - return formatProcessor; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.sse.ui.internal.extension.RegistryReader#readElement(org.eclipse.core.runtime.IConfigurationElement) - */ - protected boolean readElement(IConfigurationElement element) { - if (element.getName().equals("processor")) { //$NON-NLS-1$ - String contentTypeId = element.getAttribute("contentTypeId"); //$NON-NLS-1$ - String processorClassName = element.getAttribute("class"); //$NON-NLS-1$ - String pluginID = element.getDeclaringExtension().getNamespace(); - Bundle bundle = Platform.getBundle(pluginID); - - try { - IStructuredFormatProcessor processor = (IStructuredFormatProcessor)bundle.loadClass(processorClassName).newInstance(); - map.put(contentTypeId, processor); - - return true; - } catch (InstantiationException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } - } - - return false; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/GotoAnnotationAction.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/GotoAnnotationAction.java deleted file mode 100644 index 67de28a3ba..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/GotoAnnotationAction.java +++ /dev/null @@ -1,378 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.Iterator; - -import org.eclipse.core.resources.IMarker; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.Preferences; -import org.eclipse.jface.action.IStatusLineManager; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.ITextSelection; -import org.eclipse.jface.text.Position; -import org.eclipse.jface.text.source.Annotation; -import org.eclipse.jface.text.source.IAnnotationModel; -import org.eclipse.jface.viewers.ISelectionChangedListener; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.viewers.SelectionChangedEvent; -import org.eclipse.jface.viewers.StructuredSelection; -import org.eclipse.ui.IEditorActionBarContributor; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.IPageLayout; -import org.eclipse.ui.IViewPart; -import org.eclipse.ui.IWorkbenchPage; -import org.eclipse.ui.IWorkbenchWindow; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.editors.text.EditorsUI; -import org.eclipse.ui.part.EditorActionBarContributor; -import org.eclipse.ui.texteditor.AnnotationPreference; -import org.eclipse.ui.texteditor.IEditorStatusLine; -import org.eclipse.ui.texteditor.ITextEditor; -import org.eclipse.ui.texteditor.SimpleMarkerAnnotation; -import org.eclipse.ui.texteditor.TextEditorAction; - -/** - * Based on org.eclipse.jdt.internal.ui.javaeditor.GotoAnnotationAction and - * the org.eclipse.jdt.internal.ui.JavaEditor's gotoError() method. Rewritten - * based on 3.0M7 version to operate generically. - * - * @deprecated - use org.eclipse.ui.texteditor.GotoAnnotationAction - * - */ -public class GotoAnnotationAction extends TextEditorAction { - - private static final boolean _debug = "true".equalsIgnoreCase(Platform.getDebugOption("org.eclipse.wst.sse.ui/gotoNextAnnotation")); //$NON-NLS-1$ //$NON-NLS-2$ - - /** - * Clears the status line on selection changed. - */ - protected class StatusLineClearer implements ISelectionChangedListener { - IStatusLineManager fStatusLineManager = null; - - protected StatusLineClearer(IStatusLineManager mgr) { - super(); - fStatusLineManager = mgr; - } - - /* - * @see ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent) - */ - public void selectionChanged(SelectionChangedEvent event) { - getTextEditor().getSelectionProvider().removeSelectionChangedListener(StatusLineClearer.this); - - fStatusLineManager.setErrorMessage(null, null); - fStatusLineManager.setMessage(null, null); - } - } - - private boolean fForward; - private String fLabel; - - private String fPrefix; - - /** - * @param prefix - * @param editor - */ - public GotoAnnotationAction(String prefix, boolean forward) { - super(SSEUIMessages.getResourceBundle(), prefix, null); - fForward = forward; - fPrefix = prefix; - fLabel = SSEUIMessages.getResourceBundle().getString(fPrefix); - } - - /* - * This is the default label used for description - */ - public String getDefaultLabel() { - return fLabel; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.action.Action#getDescription() - */ - public String getDescription() { - return getDefaultLabel(); - } - - /** - * Returns the annotation closest to the given range respecting the given - * direction. If an annotation is found, the annotations current position - * is copied into the provided annotation position. - * - * @param offset - * the region offset - * @param length - * the region length - * @param forward - * <code>true</code> for forwards, <code>false</code> for - * backward - * @param annotationPosition - * the position of the found annotation - * @return the found annotation - */ - protected Annotation getNextAnnotation(final int offset, final int length, boolean forward, Position annotationPosition) { - Annotation nextAnnotation = null; - Position nextAnnotationPosition = null; - Annotation containingAnnotation = null; - Position containingAnnotationPosition = null; - boolean currentAnnotation = false; - - IDocument document = getTextEditor().getDocumentProvider().getDocument(getTextEditor().getEditorInput()); - int endOfDocument = document.getLength(); - int distance = Integer.MAX_VALUE; - - IAnnotationModel model = getTextEditor().getDocumentProvider().getAnnotationModel(getTextEditor().getEditorInput()); - // external files may not have an annotation model - if (model != null) { - Iterator e = model.getAnnotationIterator(); - while (e.hasNext()) { - Annotation a = (Annotation) e.next(); - if (!isNavigationTarget(a)) - continue; - - Position p = model.getPosition(a); - if (p == null) - continue; - - if (forward && p.offset == offset || !forward && p.offset + p.getLength() == offset + length) { - if (containingAnnotation == null || (forward && p.length >= containingAnnotationPosition.length || !forward && p.length >= containingAnnotationPosition.length)) { - containingAnnotation = a; - containingAnnotationPosition = p; - currentAnnotation = p.length == length; - } - } - else { - int currentDistance = 0; - - if (forward) { - currentDistance = p.getOffset() - offset; - if (currentDistance < 0) { - currentDistance = endOfDocument + currentDistance; - } - - if (currentDistance < distance || currentDistance == distance && p.length < nextAnnotationPosition.length) { - distance = currentDistance; - nextAnnotation = a; - nextAnnotationPosition = p; - } - } - else { - currentDistance = offset + length - (p.getOffset() + p.length); - if (currentDistance < 0) - currentDistance = endOfDocument + currentDistance; - - if (currentDistance < distance || currentDistance == distance && p.length < nextAnnotationPosition.length) { - distance = currentDistance; - nextAnnotation = a; - nextAnnotationPosition = p; - } - } - } - } - } - if (containingAnnotationPosition != null && (!currentAnnotation || nextAnnotation == null)) { - annotationPosition.setOffset(containingAnnotationPosition.getOffset()); - annotationPosition.setLength(containingAnnotationPosition.getLength()); - return containingAnnotation; - } - if (nextAnnotationPosition != null) { - annotationPosition.setOffset(nextAnnotationPosition.getOffset()); - annotationPosition.setLength(nextAnnotationPosition.getLength()); - } - - return nextAnnotation; - } - - private IStatusLineManager getStatusLineManager() { - // The original JavaEditor M7 implementation made use of an adapter, - // but that approach - // fails with a MultiPageEditorSite - - IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); - if (window == null) - return null; - IWorkbenchPage page = window.getActivePage(); - if (page == null) - return null; - IEditorPart editor = page.getActiveEditor(); - if (editor == null) - return null; - IEditorActionBarContributor contributor = editor.getEditorSite().getActionBarContributor(); - if (contributor instanceof EditorActionBarContributor) { - return ((EditorActionBarContributor) contributor).getActionBars().getStatusLineManager(); - } - return null; - } - - public String getText() { - return getDefaultLabel(); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.action.Action#getToolTipText() - */ - public String getToolTipText() { - return getDefaultLabel(); - } - - /** - * Jumps to the error next according to the given direction based off - * JavaEditor#gotoAnnotation() - * - * @param forward - * is the direction - */ - public void gotoAnnotation(boolean forward) { - ITextSelection selection = (ITextSelection) getTextEditor().getSelectionProvider().getSelection(); - Position position = new Position(0, 0); - if (false /* delayed - see bug 18316 */) { - getNextAnnotation(selection.getOffset(), selection.getLength(), forward, position); - getTextEditor().selectAndReveal(position.getOffset(), position.getLength()); - } - else /* no delay - see bug 18316 */{ - Annotation annotation = getNextAnnotation(selection.getOffset(), selection.getLength(), forward, position); - IEditorStatusLine editorStatusLine = (IEditorStatusLine) getTextEditor().getAdapter(IEditorStatusLine.class); - if (editorStatusLine != null) { - editorStatusLine.setMessage(true, null, null); - editorStatusLine.setMessage(false, null, null); - } - else { - IStatusLineManager mgr = getStatusLineManager(); - if (mgr != null) { - mgr.setErrorMessage(null); - mgr.setMessage(null, null); - } - } - if (annotation != null) { - updateAnnotationViews(annotation); - if (_debug) { - System.out.println("select and reveal " + annotation.getType() + "@" + position.getOffset() + ":" + position.getLength()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } - getTextEditor().selectAndReveal(position.getOffset(), position.getLength()); - if (editorStatusLine != null) { - editorStatusLine.setMessage(true, null, null); - editorStatusLine.setMessage(false, annotation.getText(), null); - } - else { - IStatusLineManager mgr = getStatusLineManager(); - if (mgr != null) { - mgr.setErrorMessage(null); - mgr.setMessage(null, annotation.getText()); - } - getTextEditor().getSelectionProvider().addSelectionChangedListener(new StatusLineClearer(mgr)); - } - } - } - } - - /** - * Returns whether the given annotation is configured as a target for the - * "Go to Next/Previous Annotation" actions - * - * @param annotation - * the annotation - * @return <code>true</code> if this is a target, <code>false</code> - * otherwise - * @see Eclipse 3.0 - */ - protected boolean isNavigationTarget(Annotation annotation) { - Preferences preferences = EditorsUI.getPluginPreferences(); - AnnotationPreference preference = EditorsUI.getAnnotationPreferenceLookup().getAnnotationPreference(annotation); - // See bug 41689 - // String key= forward ? preference.getIsGoToNextNavigationTargetKey() - // : preference.getIsGoToPreviousNavigationTargetKey(); - String key = preference == null ? null : preference.getIsGoToNextNavigationTargetKey(); - return (key != null && preferences.getBoolean(key)); - } - - public void run() { - gotoAnnotation(fForward); - } - - public void setEditor(ITextEditor editor) { - super.setEditor(editor); - update(); - } - - /** - * Updates the annotation views that show the given annotation. - * - * @param annotation - * the annotation - */ - protected void updateAnnotationViews(Annotation annotation) { - IMarker marker = null; - if (annotation instanceof SimpleMarkerAnnotation) - marker = ((SimpleMarkerAnnotation) annotation).getMarker(); - - if (marker != null) { - try { - IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); - if (window != null) { - IWorkbenchPage page = window.getActivePage(); - if (page != null) { - IViewPart view = null; - if (marker.isSubtypeOf(IMarker.PROBLEM)) { - view = page.findView(IPageLayout.ID_PROBLEM_VIEW); - } - else if (marker.isSubtypeOf(IMarker.TASK)) { - view = page.findView(IPageLayout.ID_TASK_LIST); - } - else if (marker.isSubtypeOf(IMarker.BOOKMARK)) { - view = page.findView(IPageLayout.ID_BOOKMARKS); - } -// else if (marker.isSubtypeOf(IBreakpoint.BREAKPOINT_MARKER)) { -// view = page.findView(IDebugUIConstants.ID_BREAKPOINT_VIEW); -// } - - if (view == null) { - view = page.findView("org.eclipse.ui.views.AllMarkersView"); - } - // If the view isn't open on this perspective, don't - // interact with it - if (view != null) { - Method method = view.getClass().getMethod("setSelection", new Class[]{IStructuredSelection.class, boolean.class}); //$NON-NLS-1$ - if (method != null) { - method.invoke(view, new Object[]{new StructuredSelection(marker), Boolean.TRUE}); - page.bringToTop(view); - } - } - } - } - } - // ignore exceptions, don't update any of the lists, just set - // statusline - catch (CoreException x) { - // - } - catch (NoSuchMethodException x) { - // - } - catch (IllegalAccessException x) { - // - } - catch (InvocationTargetException x) { - // - } - } - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/IActionValidator.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/IActionValidator.java deleted file mode 100644 index 7995be73d0..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/IActionValidator.java +++ /dev/null @@ -1,17 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal; - -public interface IActionValidator { - boolean isValidAction(); -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/IDropAction.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/IDropAction.java deleted file mode 100644 index 7c751bb22f..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/IDropAction.java +++ /dev/null @@ -1,37 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal; - - - -import org.eclipse.swt.dnd.DropTargetEvent; -import org.eclipse.ui.IEditorPart; - -/** - */ -public interface IDropAction { - - - /** - * @param data - * DropTargetEvent.data will be passed. - * @return boolean true for supported data type - */ - public boolean isSupportedData(Object data); - - /** - * @return boolean true for the action is actually processed false for the - * action is not processed. - */ - public boolean run(DropTargetEvent event, IEditorPart targetEditor); -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/IExtendedContributor.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/IExtendedContributor.java deleted file mode 100644 index e178a360a6..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/IExtendedContributor.java +++ /dev/null @@ -1,30 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal; - - - -import org.eclipse.jface.action.IMenuManager; -import org.eclipse.jface.action.IStatusLineManager; -import org.eclipse.jface.action.IToolBarManager; -import org.eclipse.ui.IEditorActionBarContributor; - -public interface IExtendedContributor extends IEditorActionBarContributor, IPopupMenuContributor { - public void contributeToMenu(IMenuManager menu); - - public void contributeToStatusLine(IStatusLineManager manager); - - public void contributeToToolBar(IToolBarManager manager); - - public void updateToolbarActions(); -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/IExtendedEditorAction.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/IExtendedEditorAction.java deleted file mode 100644 index 1bfe47cb93..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/IExtendedEditorAction.java +++ /dev/null @@ -1,38 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal; - - - -import org.eclipse.ui.texteditor.IUpdate; - -public interface IExtendedEditorAction extends IUpdate { - - /** - * Returns whether this action item is visible - * - * @return <code>true</code> if this item is visible, and - * <code>false</code> otherwise - */ - public boolean isVisible(); - - /** - * Sets the active editor for the action. Implementors should disconnect - * from the old editor, connect to the new editor, and update the action - * to reflect the new editor. - * - * @param targetEditor - * the new editor target - */ - public void setActiveExtendedEditor(IExtendedSimpleEditor targetEditor); -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/IExtendedMarkupEditor.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/IExtendedMarkupEditor.java deleted file mode 100644 index 4f646d3910..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/IExtendedMarkupEditor.java +++ /dev/null @@ -1,47 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal; - - - -import java.util.List; - -import org.w3c.dom.Document; -import org.w3c.dom.Node; - -/** - * IExtendedMarkupEditor - * - * @deprecated use the editor's ISourceEditingTextTools adapter and cast to - * IDOMSourceEditingTextTools when appropriate - */ -public interface IExtendedMarkupEditor { - - /** - * @deprecated - use the IDOMSourceEditingTextTools.getNode(int) method - * with ISourceEditingTextTools.getCaretOffset() - * @return - */ - public Node getCaretNode(); - - /** - * @deprecated - use method on IDOMSourceEditingTextTools - */ - public Document getDOMDocument(); - - /** - * @deprecated - some editors will provide the list of selected nodes as - * part of ISourceEditingTextTools.getSelection() - */ - public List getSelectedNodes(); -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/IExtendedSimpleEditor.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/IExtendedSimpleEditor.java deleted file mode 100644 index b187827576..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/IExtendedSimpleEditor.java +++ /dev/null @@ -1,33 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal; - -/** - * @deprecated, obtain a ISourceEditingTextTools adapter from the editor part - */ - -import org.eclipse.jface.text.IDocument; -import org.eclipse.swt.graphics.Point; -import org.eclipse.ui.IEditorPart; - -public interface IExtendedSimpleEditor { - - public int getCaretPosition(); - - public IDocument getDocument(); - - public IEditorPart getEditorPart(); - - public Point getSelectionRange(); - -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/IModelProvider.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/IModelProvider.java deleted file mode 100644 index f25e2884d8..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/IModelProvider.java +++ /dev/null @@ -1,21 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal; - -import org.eclipse.ui.texteditor.IDocumentProvider; -import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel; - - -public interface IModelProvider extends IDocumentProvider { - IStructuredModel getModel(Object element); -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/IPopupMenuContributor.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/IPopupMenuContributor.java deleted file mode 100644 index 964720427a..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/IPopupMenuContributor.java +++ /dev/null @@ -1,22 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal; - - - -import org.eclipse.jface.action.IMenuManager; - -public interface IPopupMenuContributor { - - public void contributeToPopupMenu(IMenuManager menu); -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/IReleasable.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/IReleasable.java deleted file mode 100644 index 44a599d3c2..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/IReleasable.java +++ /dev/null @@ -1,20 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal; - -public interface IReleasable { - /** - * Generic catch-all for releasing resources and other references - */ - void release(); -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/ISourceViewerActionBarContributor.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/ISourceViewerActionBarContributor.java deleted file mode 100644 index 228a96823a..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/ISourceViewerActionBarContributor.java +++ /dev/null @@ -1,29 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal; - - - -import org.eclipse.ui.IEditorActionBarContributor; - -public interface ISourceViewerActionBarContributor extends IEditorActionBarContributor { - - /** - * Enables disables actions that are specific to the source viewer (and - * should only work when the source viewer is enabled) - * - * @param enabled - * true if source viewer is currently enabled, false otherwise - */ - public void setViewerSpecificContributionsEnabled(boolean enabled); -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/IStructuredTextEditorActionConstants.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/IStructuredTextEditorActionConstants.java deleted file mode 100644 index d4b131c60a..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/IStructuredTextEditorActionConstants.java +++ /dev/null @@ -1,21 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal; - -public interface IStructuredTextEditorActionConstants { - String SOURCE_CONTEXT_MENU_ID = "sourcePopupMenuId"; //$NON-NLS-1$ - String SOURCE_BEGIN = "sourceBegin"; //$NON-NLS-1$ - String SOURCE_ADDITIONS = "additions"; //$NON-NLS-1$ - String SOURCE_END = "sourceEnd"; //$NON-NLS-1$ - - String REFACTOR_CONTEXT_MENU_ID = "refactorPopupMenuId"; //$NON-NLS-1$ -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/ITemporaryAnnotation.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/ITemporaryAnnotation.java deleted file mode 100644 index 68f6441d5f..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/ITemporaryAnnotation.java +++ /dev/null @@ -1,17 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal; - -public interface ITemporaryAnnotation { - Object getKey(); -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/Logger.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/Logger.java deleted file mode 100644 index 906e3f2529..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/Logger.java +++ /dev/null @@ -1,180 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal; - - - -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.Status; -import org.osgi.framework.Bundle; - -import com.ibm.icu.util.StringTokenizer; - -/** - * Small convenience class to log messages to plugin's log file and also, if - * desired, the console. This class should only be used by classes in this - * plugin. Other plugins should make their own copy, with appropriate ID. - */ -public class Logger { - private static final String PLUGIN_ID = "org.eclipse.wst.sse.ui"; //$NON-NLS-1$ - - public static final int ERROR = IStatus.ERROR; // 4 - public static final int ERROR_DEBUG = 200 + ERROR; - public static final int INFO = IStatus.INFO; // 1 - public static final int INFO_DEBUG = 200 + INFO; - - public static final int OK = IStatus.OK; // 0 - - public static final int OK_DEBUG = 200 + OK; - - private static final String TRACEFILTER_LOCATION = "/debug/tracefilter"; //$NON-NLS-1$ - public static final int WARNING = IStatus.WARNING; // 2 - public static final int WARNING_DEBUG = 200 + WARNING; - - /** - * Adds message to log. - * - * @param level - * severity level of the message (OK, INFO, WARNING, ERROR, - * OK_DEBUG, INFO_DEBUG, WARNING_DEBUG, ERROR_DEBUG) - * @param message - * text to add to the log - * @param exception - * exception thrown - */ - protected static void _log(int level, String message, Throwable exception) { - if (level == OK_DEBUG || level == INFO_DEBUG || level == WARNING_DEBUG || level == ERROR_DEBUG) { - if (!isDebugging()) - return; - } - - int severity = IStatus.OK; - switch (level) { - case INFO_DEBUG : - case INFO : - severity = IStatus.INFO; - break; - case WARNING_DEBUG : - case WARNING : - severity = IStatus.WARNING; - break; - case ERROR_DEBUG : - case ERROR : - severity = IStatus.ERROR; - } - message = (message != null) ? message : "null"; //$NON-NLS-1$ - Status statusObj = new Status(severity, PLUGIN_ID, severity, message, exception); - _log(statusObj); - - } - - /** - * Adds {@link IStatus} to the log. - * - * @param statusObj {@link IStatus} to add to the log - */ - protected static void _log(IStatus statusObj) { - Bundle bundle = Platform.getBundle(PLUGIN_ID); - if (bundle != null) { - Platform.getLog(bundle).log(statusObj); - } - } - - /** - * Prints message to log if category matches /debug/tracefilter option. - * - * @param message - * text to print - * @param category - * category of the message, to be compared with - * /debug/tracefilter - */ - protected static void _trace(String category, String message, Throwable exception) { - if (isTracing(category)) { - message = (message != null) ? message : "null"; //$NON-NLS-1$ - Status statusObj = new Status(IStatus.OK, PLUGIN_ID, IStatus.OK, message, exception); - Bundle bundle = Platform.getBundle(PLUGIN_ID); - if (bundle != null) - Platform.getLog(bundle).log(statusObj); - - } - } - - /** - * @return true if the platform is debugging - */ - public static boolean isDebugging() { - return Platform.inDebugMode(); - } - - /** - * Determines if currently tracing a category - * - * @param category - * @return true if tracing category, false otherwise - */ - public static boolean isTracing(String category) { - if (!isDebugging()) - return false; - - String traceFilter = Platform.getDebugOption(PLUGIN_ID + TRACEFILTER_LOCATION); - if (traceFilter != null) { - StringTokenizer tokenizer = new StringTokenizer(traceFilter, ","); //$NON-NLS-1$ - while (tokenizer.hasMoreTokens()) { - String cat = tokenizer.nextToken().trim(); - if (category.equals(cat)) { - return true; - } - } - } - return false; - } - - public static void log(int level, String message) { - _log(level, message, null); - } - - public static void log(int level, String message, Throwable exception) { - _log(level, message, exception); - } - - /** - * <p>Allows an already constructed status to be logged</p> - * - * @param status {@link IStatus} to log. - */ - public static void log(IStatus status) { - _log(status); - } - - public static void logException(String message, Throwable exception) { - _log(ERROR, message, exception); - } - - public static void logException(Throwable exception) { - _log(ERROR, exception.getMessage(), exception); - } - - public static void trace(String category, String message) { - _trace(category, message, null); - } - - public static void traceException(String category, String message, Throwable exception) { - _trace(category, message, exception); - } - - public static void traceException(String category, Throwable exception) { - _trace(category, exception.getMessage(), exception); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/PreferenceInitializer.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/PreferenceInitializer.java deleted file mode 100644 index 20c8cca6ea..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/PreferenceInitializer.java +++ /dev/null @@ -1,87 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal; - -import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer; -import org.eclipse.jface.action.Action; -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.preference.PreferenceConverter; -import org.eclipse.jface.resource.ColorRegistry; -import org.eclipse.swt.SWT; -import org.eclipse.swt.graphics.RGB; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.editors.text.EditorsUI; -import org.eclipse.wst.sse.ui.internal.preferences.EditorPreferenceNames; -import org.eclipse.wst.sse.ui.internal.preferences.ui.ColorHelper; -import org.eclipse.wst.sse.ui.internal.projection.AbstractStructuredFoldingStrategy; -import org.eclipse.wst.sse.ui.internal.provisional.preferences.CommonEditorPreferenceNames; - - -public class PreferenceInitializer extends AbstractPreferenceInitializer { - /* (non-Javadoc) - * @see org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer#initializeDefaultPreferences() - */ - public void initializeDefaultPreferences() { - IPreferenceStore store = SSEUIPlugin.getDefault().getPreferenceStore(); - ColorRegistry registry = PlatformUI.getWorkbench().getThemeManager().getCurrentTheme().getColorRegistry(); - - // use the base annotation & quick diff preference page - EditorsUI.useAnnotationsPreferencePage(store); - EditorsUI.useQuickDiffPreferencePage(store); - - // let annotations show up in the vertical ruler if that's what the - // preference is - // // these annotation preferences have a different default value than - // the one the base provides - // store.setDefault("errorIndicationInVerticalRuler", false); - // //$NON-NLS-1$ - // store.setDefault("warningIndicationInVerticalRuler", false); - // //$NON-NLS-1$ - - // these annotation preferences are not part of base text editor - // preference - store.setDefault(CommonEditorPreferenceNames.EVALUATE_TEMPORARY_PROBLEMS, true); - - setMatchingBracketsPreferences(store, registry); - - // hover help preferences are not part of base text editor preference - String mod2Name = Action.findModifierString(SWT.MOD2); // SWT.COMMAND - // on Mac; - // SWT.CONTROL - // elsewhere - store.setDefault(EditorPreferenceNames.EDITOR_TEXT_HOVER_MODIFIERS, "combinationHover|true|0;problemHover|false|0;documentationHover|false|0;annotationHover|true|" + mod2Name); //$NON-NLS-1$ - - // set default read-only foreground color scale value - store.setDefault(EditorPreferenceNames.READ_ONLY_FOREGROUND_SCALE, 30); - - // set default enable folding value - store.setDefault(AbstractStructuredFoldingStrategy.FOLDING_ENABLED, true); - - // set default for show message dialog when unknown content type in editor - store.setDefault(EditorPreferenceNames.SHOW_UNKNOWN_CONTENT_TYPE_MSG, true); - - // set content assist defaults - store.setDefault(EditorPreferenceNames.CODEASSIST_AUTOACTIVATION_DELAY, 500); - PreferenceConverter.setDefault(store, EditorPreferenceNames.CODEASSIST_PROPOSALS_BACKGROUND, ColorHelper.findRGB(registry, EditorPreferenceNames.CODEASSIST_PROPOSALS_BACKGROUND, new RGB(255, 255, 255))); - PreferenceConverter.setDefault(store, EditorPreferenceNames.CODEASSIST_PROPOSALS_FOREGROUND, ColorHelper.findRGB(registry, EditorPreferenceNames.CODEASSIST_PROPOSALS_FOREGROUND, new RGB(0, 0, 0))); - PreferenceConverter.setDefault(store, EditorPreferenceNames.CODEASSIST_PARAMETERS_BACKGROUND, ColorHelper.findRGB(registry, EditorPreferenceNames.CODEASSIST_PARAMETERS_BACKGROUND, new RGB(255, 255, 255))); - PreferenceConverter.setDefault(store, EditorPreferenceNames.CODEASSIST_PARAMETERS_FOREGROUND, ColorHelper.findRGB(registry, EditorPreferenceNames.CODEASSIST_PARAMETERS_FOREGROUND, new RGB(0, 0, 0))); - - store.setDefault(EditorPreferenceNames.SEMANTIC_HIGHLIGHTING, true); - } - - private void setMatchingBracketsPreferences(IPreferenceStore store, ColorRegistry registry) { - // matching brackets is not part of base text editor preference - store.setDefault(EditorPreferenceNames.MATCHING_BRACKETS, true); - PreferenceConverter.setDefault(store, EditorPreferenceNames.MATCHING_BRACKETS_COLOR, ColorHelper.findRGB(registry, EditorPreferenceNames.MATCHING_BRACKETS_COLOR, new RGB(192, 192, 192))); - } -}
\ No newline at end of file diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/ReadOnlyAwareDropTargetAdapter.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/ReadOnlyAwareDropTargetAdapter.java deleted file mode 100644 index 69a968bf53..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/ReadOnlyAwareDropTargetAdapter.java +++ /dev/null @@ -1,52 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal; - - -import org.eclipse.jface.text.IDocument; -import org.eclipse.swt.dnd.DND; -import org.eclipse.swt.dnd.DropTargetEvent; -import org.eclipse.swt.graphics.Point; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument; - - -public class ReadOnlyAwareDropTargetAdapter extends ExtendedEditorDropTargetAdapter { - - /** - * @deprecated - use ReadOnlyAwareDropTargetAdapter(boolean useProxy) for - * the performance - */ - public ReadOnlyAwareDropTargetAdapter() { - super(); - } - - public ReadOnlyAwareDropTargetAdapter(boolean useProxy) { - super(useProxy); - } - - public void drop(DropTargetEvent event) { - IDocument document = getTextViewer().getDocument(); - if (document instanceof IStructuredDocument) { - Point range = getTextViewer().getSelectedRange(); - if (((IStructuredDocument) document).containsReadOnly(range.x, range.y)) { - event.operations = DND.DROP_NONE; - event.detail = DND.DROP_NONE; - getTextViewer().getTextWidget().redraw(); - getTextViewer().getTextWidget().update(); - getTextViewer().getTextWidget().getDisplay().beep(); - } - } - super.drop(event); - } - -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/SSEUIMessages.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/SSEUIMessages.java deleted file mode 100644 index 114cee3f00..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/SSEUIMessages.java +++ /dev/null @@ -1,475 +0,0 @@ -/********************************************************************** - * Copyright (c) 2005, 2011 IBM Corporation and others. All rights reserved. This - * program and the accompanying materials are made available under the terms of - * the Eclipse Public License v1.0 which accompanies this distribution, and is - * available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM - Initial API and implementation - **********************************************************************/ -package org.eclipse.wst.sse.ui.internal; - -import java.util.MissingResourceException; -import java.util.ResourceBundle; - -import org.eclipse.osgi.util.NLS; - -/** - * Strings used by SSE UI - * - * @plannedfor 1.0 - */ -public class SSEUIMessages extends NLS { - private static final String BUNDLE_NAME = "org.eclipse.wst.sse.ui.internal.SSEUIPluginResources";//$NON-NLS-1$ - private static ResourceBundle fResourceBundle; - - public static ResourceBundle getResourceBundle() { - try { - if (fResourceBundle == null) - fResourceBundle = ResourceBundle.getBundle(BUNDLE_NAME); - } - catch (MissingResourceException x) { - fResourceBundle = null; - } - return fResourceBundle; - } - - private SSEUIMessages() { - // cannot create new instance - } - - static { - // load message values from bundle file - NLS.initializeMessages(BUNDLE_NAME, SSEUIMessages.class); - } - - public static String Error_opening_file_UI_; - public static String _UI_File_is_read_only; - public static String _32concat_EXC_; - public static String Multiple_errors; - public static String _Undo_Text_Change__Ctrl_Z_UI_; - public static String Undo_Text_Change__UI_; - public static String _Undo__0___Ctrl_Z_UI_; - public static String Undo___0___UI_; - public static String _Redo_Text_Change__Ctrl_Y_UI_; - public static String Redo_Text_Change__UI_; - public static String _Redo__0___Ctrl_Y_UI_; - public static String Redo___0___UI_; - public static String Format_Document_UI_; - public static String Format_Active_Elements_UI_; - public static String Text_Cut_UI_; - public static String Text_Paste_UI_; - - public static String Cleanup_Document_UI_; - - public static String Editor_Cut_label; - public static String Editor_Cut_tooltip; - public static String Editor_Cut_image; - public static String Editor_Cut_description; - public static String Editor_Copy_label; - public static String Editor_Copy_tooltip; - public static String Editor_Copy_image; - public static String Editor_Copy_description; - public static String Editor_Paste_label; - public static String Editor_Paste_tooltip; - public static String Editor_Paste_image; - public static String Editor_Paste_description; - public static String Editor_Delete_label; - public static String Editor_Delete_tooltip; - public static String Editor_Delete_image; - public static String Editor_Delete_description; - - public static String ContentAssistProposals_label; - public static String ContentAssistProposals_tooltip; - public static String ContentAssistProposals_description; - public static String QuickFix_label; - public static String QuickFix_tooltip; - public static String QuickFix_image; - public static String QuickFix_description; - public static String ToggleComment_label; - public static String ToggleComment_tooltip; - public static String ToggleComment_image; - public static String ToggleComment_description; - public static String ToggleComment_progress; - public static String AddBlockComment_label; - public static String AddBlockComment_tooltip; - public static String AddBlockComment_image; - public static String AddBlockComment_description; - public static String RemoveBlockComment_label; - public static String RemoveBlockComment_tooltip; - public static String RemoveBlockComment_image; - public static String RemoveBlockComment_description; - public static String CleanupDocument_label; - public static String CleanupDocument_tooltip; - public static String CleanupDocument_image; - public static String CleanupDocument_description; - public static String FormatDocument_label; - public static String FormatDocument_tooltip; - public static String FormatDocument_image; - public static String FormatDocument_description; - public static String FormatActiveElements_label; - public static String FormatActiveElements_tooltip; - public static String FormatActiveElements_image; - public static String FormatActiveElements_description; - public static String OpenFileFromSource_label; - public static String OpenFileFromSource_tooltip; - public static String OpenFileFromSource_image; - public static String OpenFileFromSource_description; - public static String StructureSelectEnclosing_label; - public static String StructureSelectEnclosing_tooltip; - public static String StructureSelectEnclosing_description; - public static String StructureSelectNext_label; - public static String StructureSelectNext_tooltip; - public static String StructureSelectNext_description; - public static String StructureSelectPrevious_label; - public static String StructureSelectPrevious_tooltip; - public static String StructureSelectPrevious_description; - public static String StructureSelectHistory_label; - public static String StructureSelectHistory_tooltip; - public static String StructureSelectHistory_description; - public static String Text_Shift_Right_UI_; - public static String Text_Shift_Left_UI_; - - public static String _4concat; - public static String Content_type__UI_; - public static String Foreground_UI_; - public static String Foreground_Color_Selector_Button; - public static String Background_UI_; - public static String Background_Color_Selector_Button; - public static String Bold_UI_; - public static String Italics_UI; - public static String Restore_Default_UI_; - public static String Sample_text__UI_; - - public static String AddBreakpoint_label; - public static String AddBreakpoint_tooltip; - public static String AddBreakpoint_description; - public static String AddBreakpoint_error_dialog_title; - public static String AddBreakpoint_error_dialog_message; - public static String ToggleBreakpoint_label; - public static String ToggleBreakpoint_tooltip; - public static String ToggleBreakpoint_description; - public static String EnableBreakpoint_label; - public static String EnableBreakpoint_tooltip; - public static String EnableBreakpoint_description; - public static String DisableBreakpoint_label; - public static String DisableBreakpoint_tooltip; - public static String DisableBreakpoint_description; - public static String ManageBreakpoints_add_label; - public static String ManageBreakpoints_remove_label; - public static String ManageBreakpoints_tooltip; - public static String ManageBreakpoints_error_adding_title1; - public static String ManageBreakpoints_error_adding_message1; - - public static String AbstractColorPageDescription; - public static String SyntaxColoring_Link; - public static String SyntaxColoring_Description; - public static String EditorModelUtil_0; - public static String EditorModelUtil_1; - - // TODO: These should be removed when ContentSettingsPropertyPage is - // deleted - // web content settings - public static String UI_Default_HTML_DOCTYPE_ID___1; - public static String UI_CSS_profile___2; - public static String UI_Target_Device___3; - - public static String Editor_ToggleInsertMode_label; - - // - // These strings are used in Workbench menu bar - // - public static String ExpandSelectionToMenu_label; - public static String SourceMenu_label; - public static String RefactorMenu_label; - - public static String FindOccurrencesActionProvider_0; - public static String RemoveAction_0; - public static String ShowPropertiesAction_0; - public static String ContentOutlineConfiguration_0; - public static String ContentOutlineConfiguration_1; - public static String AbstractOpenOn_0; - public static String FormatActionDelegate_jobName; - public static String FormatActionDelegate_errorStatusMessage; - public static String FormatActionDelegate_3; - public static String FormatActionDelegate_4; - public static String FormatActionDelegate_5; - - public static String TranslucencyPreferenceTab_0; - public static String TranslucencyPreferenceTab_1; - public static String StructuredTextEditorPreferencePage_2; - public static String StructuredTextEditorPreferencePage_6; - public static String StructuredTextEditorPreferencePage_20; - public static String StructuredTextEditorPreferencePage_23; - public static String StructuredTextEditorPreferencePage_24; - public static String StructuredTextEditorPreferencePage_30; - public static String StructuredTextEditorPreferencePage_37; - public static String StructuredTextEditorPreferencePage_38; - public static String StructuredTextEditorPreferencePage_40; - public static String StructuredTextEditorPreferencePage_41; - public static String StructuredTextEditorPreferencePage_42; - public static String StructuredTextEditorPreferencePage_43; - public static String StructuredTextEditorPreferencePage_44; - public static String TaskTagPreferenceTab_0; - public static String TaskTagPreferenceTab_1; - public static String TaskTagPreferenceTab_2; - public static String TaskTagPreferenceTab_3; - public static String TaskTagPreferenceTab_5; - public static String TaskTagPreferenceTab_6; - public static String TaskTagPreferenceTab_7; - public static String TaskTagPreferenceTab_12; - public static String TaskTagPreferenceTab_13; - public static String TaskTagPreferenceTab_14; - public static String TaskTagPreferenceTab_15; - public static String TaskTagPreferenceTab_16; - public static String TaskTagPreferenceTab_17; - public static String TaskTagPreferenceTab_18; - public static String TaskTagPreferenceTab_19; - public static String TaskTagPreferenceTab_20; - public static String TaskTagPreferenceTab_22; - public static String TaskTagPreferenceTab_23; - public static String TaskTagPreferenceTab_24; - public static String TaskTagPreferenceTab_25; - public static String TaskTagPreferenceTab_26; - public static String TaskTagPreferenceTab_27; - public static String TaskTagPreferenceTab_28; - public static String TaskTagPreferenceTab_29; - public static String TaskTagPreferenceTab_30; - public static String TaskTagPreferenceTab_31; - public static String TaskTagPreferencePage_32; - public static String TaskTagPreferenceTab_33; - public static String TaskTagExclusionTab_01; - public static String TaskTagExclusionTab_02; - public static String TaskTagExclusionTab_03; - - public static String PropertyPreferencePage_01; - public static String PropertyPreferencePage_02; - - public static String FilePreferencePage_0; - public static String NoModificationCompletionProposal_0; - public static String ToggleBreakpointAction_0; - public static String ManageBreakpointAction_0; - public static String ManageBreakpointAction_1; - public static String EditBreakpointAction_0; - // Used in Structured Text Editor Preference Page / Hovers Tab - public static String TextHoverPreferenceTab_title; - public static String TextHoverPreferenceTab_hoverPreferences; - public static String TextHoverPreferenceTab_keyModifier; - public static String TextHoverPreferenceTab_description; - public static String TextHoverPreferenceTab_modifierIsNotValid; - public static String TextHoverPreferenceTab_modifierIsNotValidForHover; - public static String TextHoverPreferenceTab_duplicateModifier; - public static String TextHoverPreferenceTab_nameColumnTitle; - public static String TextHoverPreferenceTab_modifierColumnTitle; - public static String TextHoverPreferenceTab_delimiter; - public static String TextHoverPreferenceTab_insertDelimiterAndModifierAndDelimiter; - public static String TextHoverPreferenceTab_insertModifierAndDelimiter; - public static String TextHoverPreferenceTab_insertDelimiterAndModifier; - - // used dynamically - public static String combinationHover_label; - public static String combinationHover_desc; - public static String problemHover_label; - public static String problemHover_desc; - public static String documentationHover_label; - public static String documentationHover_desc; - public static String annotationHover_label; - public static String annotationHover_desc; - - public static String EditStructuredTextEditorPreferencesAction_0; - public static String StructuredTextEditorPreferencePage_0; - public static String StructuredTextEditorPreferencePage_1; - public static String PreferenceManager_0; - - public static String OccurrencesSearchQuery_0; - public static String OccurrencesSearchQuery_2; - public static String ShowView_errorTitle; - public static String proc_dirty_regions_0; - - public static String textHoverMakeStickyHint; - - // Encoding - public static String EncodingPreferencePage_0; - public static String EncodingPreferencePage_1; - - public static String caret_update; - public static String EmptyFilePreferencePage_0; - - public static String OffsetStatusLineContributionItem_0; - public static String OffsetStatusLineContributionItem_2; - public static String OffsetStatusLineContributionItem_3; - public static String OffsetStatusLineContributionItem_4; - public static String OffsetStatusLineContributionItem_5; - public static String OffsetStatusLineContributionItem_6; - public static String OffsetStatusLineContributionItem_7; - public static String OffsetStatusLineContributionItem_8; - public static String OffsetStatusLineContributionItem_9; - public static String OffsetStatusLineContributionItem_10; - public static String OffsetStatusLineContributionItem_11; - public static String OffsetStatusLineContributionItem_12; - public static String OffsetStatusLineContributionItem_13; - public static String OffsetStatusLineContributionItem_14; - public static String OffsetStatusLineContributionItem_15; - public static String OffsetStatusLineContributionItem_16; - public static String OffsetStatusLineContributionItem_17; - public static String OffsetStatusLineContributionItem_18; - public static String OffsetStatusLineContributionItem_19; - public static String OffsetStatusLineContributionItem_20; - - /* - * *****Below are possibly unused strings that may be removed ***** - */ - public static String Save_label; - public static String An_error_has_occurred_when_ERROR_; - public static String Problems_During_Save_As_UI_; - public static String Save_could_not_be_complete_UI_; - public static String SemanticHighlightingReconciler_0; - public static String ManageBreakpoints_error_removing_title1; - public static String ManageBreakpoints_error_removing_message1; - public static String ManageBreakpoints_error_retrieving_message; - public static String JSPSourcePreferencePageDescription; - public static String Editor_error_save_message; - public static String Editor_error_save_title; - public static String Editor_warning_save_delete; - - public static String Previous_annotation; - public static String Next_annotation; - - public static String AnnotationTypes_Errors; - public static String AnnotationTypes_Warnings; - public static String AnnotationTypes_Tasks; - public static String AnnotationTypes_SearchResults; - public static String AnnotationTypes_Bookmarks; - public static String AnnotationTypes_Others; - - public static String Editor_ConvertToWindows_label; - public static String Editor_ConvertToWindows_tooltip; - public static String Editor_ConvertToWindows_image; - public static String Editor_ConvertToWindows_description; - - public static String Editor_ConvertToUNIX_label; - public static String Editor_ConvertToUNIX_tooltip; - public static String Editor_ConvertToUNIX_image; - public static String Editor_ConvertToUNIX_description; - - public static String Editor_ConvertToMac_label; - public static String Editor_ConvertToMac_tooltip; - public static String Editor_ConvertToMac_image; - public static String Editor_ConvertToMac_description; - public static String ConvertLineDelimitersMenu_label; - public static String FindOccurrences_label; - - public static String ConvertLineDelimitersToCRLFActionDelegate_jobName; - public static String ConvertLineDelimitersToCRLFActionDelegate_errorStatusMessage; - public static String ConvertLineDelimitersToCRLFActionDelegate_3; - public static String ConvertLineDelimitersToCRLFActionDelegate_4; - - public static String TextHoverPreferenceTab_annotationRollover; - public static String TextHoverPreferenceTab_showAffordance; - public static String TextHoverPreferenceTab_enabled; - - public static String BasicFindOccurrencesAction_0; - public static String BasicSearchLabelProvider_0; - public static String NavigationPreferenceTab_0; - public static String OccurrencesSearchQuery_1; - public static String FileModelProvider_0; - public static String JFaceNodeAdapter_0; - - public static String ConfigureProjectSettings; - public static String ConfigureWorkspaceSettings; - public static String EnableProjectSettings; - - public static String GotoMatchingBracket_label; - public static String GotoMatchingBracket_description; - public static String GotoMatchingBracket_tooltip; - public static String GotoMatchingBracket_error_invalidSelection; - public static String GotoMatchingBracket_error_noMatchingBracket; - public static String GotoMatchingBracket_error_bracketOutsideSelectedElement; - - public static String LoadingReferencedGrammars; - - public static String Folding; - public static String StructuredTextEditorPreferencePage_3; - public static String Projection_Toggle_label; - public static String Projection_Toggle_tooltip; - public static String Projection_Toggle_description; - public static String Projection_Toggle_image; - public static String Projection_ExpandAll_label; - public static String Projection_ExpandAll_tooltip; - public static String Projection_ExpandAll_description; - public static String Projection_ExpandAll_image; - public static String Projection_CollapseAll_label; - public static String Projection_CollapseAll_tooltip; - public static String Projection_CollapseAll_description; - public static String Projection_CollapseAll_image; - - // These strings are accessed using resource bundle and in properties - // file, need to use '.' instead of '_' in some keys - public static String Editor_ManageBookmarks_tooltip; - public static String Editor_ManageBookmarks_image; - public static String Editor_ManageBookmarks_description; - public static String Editor_ManageBookmarks_add_label; - public static String Editor_ManageBookmarks_remove_label; - public static String Editor_ManageBookmarks_add_dialog_title; - public static String Editor_ManageBookmarks_add_dialog_message; - public static String Editor_ManageBookmarks_error_dialog_title; - public static String Editor_ManageBookmarks_error_dialog_message; - public static String Editor_ManageTasks_tooltip; - public static String Editor_ManageTasks_image; - public static String Editor_ManageTasks_description; - public static String Editor_ManageTasks_add_label; - public static String Editor_ManageTasks_remove_label; - public static String Editor_ManageTasks_add_dialog_title; - public static String Editor_ManageTasks_add_dialog_message; - public static String Editor_ManageTasks_error_dialog_title; - public static String Editor_ManageTasks_error_dialog_message; - /* - * *****Above are possibly unused strings that may be removed***** - */ - - public static String StructuredTextEditorPreferencePage_39; - public static String StructuredTextEditor_0; - public static String UnknownContentTypeDialog_0; - public static String UnknownContentTypeDialog_1; - public static String UnknownContentTypeDialog_2; - public static String StyledTextColorPicker_0; - - public static String TextSearchLabelProvider_matchCountFormat; - - //content assist messages - public static String ContentAssist_computing_proposals; - public static String ContentAssist_collecting_proposals; - public static String ContentAssist_sorting_proposals; - public static String ContentAssist_collecting_contexts; - public static String ContentAssist_computing_contexts; - public static String ContentAssist_sorting_contexts; - public static String ContentAssist_no_completions; - public static String ContentAssist_all_disabled_title; - public static String ContentAssist_all_disabled_message; - public static String ContentAssist_all_disabled_preference_link; - public static String ContentAssist_no_message; - public static String ContentAssist_toggle_affordance_update_message; - public static String ContentAssist_defaultProposalCategory_title; - public static String ContentAssist_press; - public static String ContentAssist_click; - public static String OptionalMessageDialog_dontShowAgain; - - //content assist preference messages - public static String CodeAssistAdvancedConfigurationBlock_page_description; - public static String CodeAssistAdvancedConfigurationBlock_no_shortcut; - public static String CodeAssistAdvancedConfigurationBlock_Up; - public static String CodeAssistAdvancedConfigurationBlock_Down; - public static String CodeAssistAdvancedConfigurationBlock_separate_table_description; - public static String CodeAssistAdvancedConfigurationBlock_default_table_description; - public static String CodeAssistAdvancedConfigurationBlock_default_table_category_column_title; - public static String CodeAssistAdvancedConfigurationBlock_PagesDown; - public static String CodeAssistAdvancedConfigurationBlock_PagesUp; - public static String CodeAssistAdvancedConfigurationBlock_separate_table_category_column_title; - - // Validation - public static String Validation_Title; - public static String Validation_Workspace; - public static String Validation_Project; - public static String Validation_jobName; - -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/SSEUIPlugin.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/SSEUIPlugin.java deleted file mode 100644 index d46cf03352..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/SSEUIPlugin.java +++ /dev/null @@ -1,99 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal; - - - -import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.IWorkbenchWindow; -import org.eclipse.ui.forms.FormColors; -import org.eclipse.ui.forms.widgets.FormToolkit; -import org.eclipse.ui.plugin.AbstractUIPlugin; -import org.eclipse.wst.sse.ui.internal.provisional.registry.AdapterFactoryRegistry; -import org.eclipse.wst.sse.ui.internal.provisional.registry.AdapterFactoryRegistryImpl; -import org.eclipse.wst.sse.ui.internal.taginfo.TextHoverManager; -import org.osgi.framework.BundleContext; - - -public class SSEUIPlugin extends AbstractUIPlugin { - - public final static String ID = "org.eclipse.wst.sse.ui"; //$NON-NLS-1$ - - static SSEUIPlugin instance = null; - - private FormToolkit fDialogsFormToolkit; - - public static SSEUIPlugin getDefault() { - return instance; - } - - public synchronized static SSEUIPlugin getInstance() { - return instance; - } - - private TextHoverManager fTextHoverManager; - - public SSEUIPlugin() { - super(); - instance = this; - } - - public AdapterFactoryRegistry getAdapterFactoryRegistry() { - return AdapterFactoryRegistryImpl.getInstance(); - - } - - /** - * Return text hover manager - * - * @return TextHoverManager - */ - public TextHoverManager getTextHoverManager() { - if (fTextHoverManager == null) { - fTextHoverManager = new TextHoverManager(); - } - return fTextHoverManager; - } - - public void start(BundleContext context) throws Exception { - super.start(context); - } - - public FormToolkit getDialogsFormToolkit() { - if (fDialogsFormToolkit == null) { - FormColors colors= new FormColors(Display.getCurrent()); - colors.setBackground(null); - colors.setForeground(null); - fDialogsFormToolkit= new FormToolkit(colors); - } - return fDialogsFormToolkit; - } - - public void stop(BundleContext context) throws Exception { - super.stop(context); - } - - /** - * <p>A utility function for getting the active workbench shell.</p> - * - * @return the active workbench {@link Shell} - */ - public static Shell getActiveWorkbenchShell() { - IWorkbenchWindow window = getDefault().getWorkbench().getActiveWorkbenchWindow(); - if (window != null) { - return window.getShell(); - } - return null; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/SSEUIPluginResources.properties b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/SSEUIPluginResources.properties deleted file mode 100644 index 64765db3ce..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/SSEUIPluginResources.properties +++ /dev/null @@ -1,450 +0,0 @@ -############################################################################### -# Copyright (c) 2001, 2011 IBM Corporation and others. -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Eclipse Public License v1.0 -# which accompanies this distribution, and is available at -# http://www.eclipse.org/legal/epl-v10.html -# -# Contributors: -# IBM Corporation - initial API and implementation -# Jens Lukowski/Innoopract - initial renaming/restructuring -# -############################################################################### -Error_opening_file_UI_=Error opening file -_UI_File_is_read_only=File {0} is read-only. -_32concat_EXC_=Editor could not be open on {0} -Multiple_errors=Multiple annotations found at this line: -_Undo_Text_Change__Ctrl_Z_UI_=&Undo Text Change -Undo_Text_Change__UI_=Undo Text Change. -_Undo__0___Ctrl_Z_UI_=&Undo {0} -Undo___0___UI_=Undo: {0}. -_Redo_Text_Change__Ctrl_Y_UI_=&Redo Text Change -Redo_Text_Change__UI_=Redo Text Change. -_Redo__0___Ctrl_Y_UI_=&Redo {0} -Redo___0___UI_=Redo: {0}. -Format_Document_UI_=Format -Format_Active_Elements_UI_=Format Active Elements -Text_Cut_UI_=Text Cut -Text_Paste_UI_=Text Paste -############################################################################### -Cleanup_Document_UI_=Cleanup Document - -Editor_Cut_label=Cu&t -Editor_Cut_tooltip=Cut -Editor_Cut_image= -Editor_Cut_description=Cut - -Editor_Copy_label=&Copy -Editor_Copy_tooltip=Copy -Editor_Copy_image= -Editor_Copy_description=Copy - -Editor_Paste_label=&Paste -Editor_Paste_tooltip=Paste -Editor_Paste_image= -Editor_Paste_description=Paste - -Editor_Delete_label=&Delete@Delete -Editor_Delete_tooltip=Delete -Editor_Delete_image= -Editor_Delete_description=Delete - -ContentAssistProposals_label=Con&tent Assist -ContentAssistProposals_tooltip=Content Assist -ContentAssistProposals_description=Content Assist - -QuickFix_label=&Quick Fix -QuickFix_tooltip=Quick Fix -QuickFix_image= -QuickFix_description=Quick Fix - -ToggleComment_label=Togg&le Comment -ToggleComment_tooltip=Toggle Comment -ToggleComment_image= -ToggleComment_description=Toggle Comment -ToggleComment_progress=Toggling line comments... -AddBlockComment_label=Add &Block Comment -AddBlockComment_tooltip=Add Block Comment -AddBlockComment_image= -AddBlockComment_description=Add Block Comment -RemoveBlockComment_label=Remove Bloc&k Comment -RemoveBlockComment_tooltip=Remove Block Comment -RemoveBlockComment_image= -RemoveBlockComment_description=Remove Block Comment -CleanupDocument_label=C&leanup Document... -CleanupDocument_tooltip=Cleanup Document -CleanupDocument_image= -CleanupDocument_description=Cleanup Document -FormatDocument_label=&Format -FormatDocument_tooltip=Format -FormatDocument_image= -FormatDocument_description=Format -FormatActiveElements_label=Format Act&ive Elements -FormatActiveElements_tooltip=Format Active Elements -FormatActiveElements_image= -FormatActiveElements_description=Format Active Elements -OpenFileFromSource_label=Op&en Selection -OpenFileFromSource_tooltip=Open an editor on the selected link -OpenFileFromSource_image= -OpenFileFromSource_description=Open an editor on the selected link -StructureSelectEnclosing_label=&Enclosing Element -StructureSelectEnclosing_tooltip=Expand selection to include enclosing element -StructureSelectEnclosing_description=Expand selection to include enclosing element -StructureSelectNext_label=&Next Element -StructureSelectNext_tooltip=Expand selection to include next sibling -StructureSelectNext_description=Expand selection to include next sibling -StructureSelectPrevious_label=&Previous Element -StructureSelectPrevious_tooltip=Expand selection to include previous sibling -StructureSelectPrevious_description=Expand selection to include previous sibling -StructureSelectHistory_label=&Restore Last Selection -StructureSelectHistory_tooltip=Restore last selection -StructureSelectHistory_description=Restore last selection -Text_Shift_Right_UI_=Text Shift Right -Text_Shift_Left_UI_=Text Shift Left - -_4concat=''{0}'' is not a valid input -## The following strings are for "XML->XML Source->XML Style" Preferences, "Web Tools->Source->HTML Style" Preferences, and "Web Tools->Source->JavaScript Style" Preferences -Content_type__UI_=Co&ntent type: -Foreground_UI_=&Foreground: -Foreground_Color_Selector_Button=Foreground Color Selector -Background_UI_=Backgr&ound: -Background_Color_Selector_Button=Background Color Selector -Bold_UI_=B&old -Italics_UI=Italics -Restore_Default_UI_=&Restore Default -Sample_text__UI_=&Sample text: -## -AddBreakpoint_label=Add &Breakpoint -AddBreakpoint_tooltip=Add Breakpoint -AddBreakpoint_description=Add Breakpoint -AddBreakpoint_error_dialog_title=Add Breakpoint -AddBreakpoint_error_dialog_message=Cannot add breakpoint -## -ToggleBreakpoint_label=Toggle Breakpoint -ToggleBreakpoint_tooltip=Toggle Breakpoint -ToggleBreakpoint_description=Toggle Breakpoint -## -EnableBreakpoint_label=Enable Breakpoint -EnableBreakpoint_tooltip=Enable Breakpoint -EnableBreakpoint_description=Enable Breakpoint -## -DisableBreakpoint_label=Disable Breakpoint -DisableBreakpoint_tooltip=Disable Breakpoint -DisableBreakpoint_description=Disable Breakpoint -## -ManageBreakpoints_add_label=Add &Breakpoint -ManageBreakpoints_remove_label=Remove Breakpoint -ManageBreakpoints_tooltip=Add/Remove Breakpoint -ManageBreakpoints_error_adding_title1=Add Breakpoint -ManageBreakpoints_error_adding_message1=Cannot add breakpoint - -AbstractColorPageDescription=Customize the syntax highlighting by selecting the type of text whose style you want to customize from either the combo box or the sample text area -## -EditorModelUtil_0=model in invalid state -EditorModelUtil_1=There was a problem adding adapter factories - -# web content settings -UI_Default_HTML_DOCTYPE_ID___1=&Document type: -UI_CSS_profile___2=&CSS profile: -UI_Target_Device___3=&Target device: - -Editor_ToggleInsertMode_label=Sma&rt Insert Mode - -########################################################################## -# These strings are used in Workbench menu bar -########################################################################## -ExpandSelectionToMenu_label=E&xpand Selection To -SourceMenu_label=&Source -RefactorMenu_label=Refac&tor -# -FindOccurrencesActionProvider_0=Current selection does not resolve to a searchable element -RemoveAction_0=Remove Property -ShowPropertiesAction_0=P&roperties -ContentOutlineConfiguration_0=Collapse All -ContentOutlineConfiguration_1=&Link with Editor -AbstractOpenOn_0=Current text selection does not resolve to a file -FormatActionDelegate_jobName=Formatting... -FormatActionDelegate_errorStatusMessage=Exceptions occurred while formatting documents -FormatActionDelegate_3=Formatting {0} -FormatActionDelegate_4=Exception occurred while formatting document {0} -FormatActionDelegate_5=MalformedInputException occurred while formatting document {0} -TranslucencyPreferenceTab_0=Read-Only text style -TranslucencyPreferenceTab_1=Read-Only contrast percentage: -StructuredTextEditorPreferencePage_2=Matching brackets highlight -StructuredTextEditorPreferencePage_6=The following preferences apply to the HTML, JSP, XML, and other source editors. -StructuredTextEditorPreferencePage_20=Highlight &matching brackets -StructuredTextEditorPreferencePage_23=Appearance co&lor options: -StructuredTextEditorPreferencePage_24=C&olor: -StructuredTextEditorPreferencePage_30=&Report problems as you type -StructuredTextEditorPreferencePage_37=Empty input -StructuredTextEditorPreferencePage_38=is not a valid input. -StructuredTextEditorPreferencePage_39=Inform when &unsupported content type is in editor -StructuredTextEditorPreferencePage_40=Also see the <a>''{0}''</a> preferences. -StructuredTextEditorPreferencePage_41=Completion proposal background -StructuredTextEditorPreferencePage_42=Completion proposal foreground -StructuredTextEditorPreferencePage_43=Parameter hints background -StructuredTextEditorPreferencePage_44=Parameter hints foreground -TaskTagPreferenceTab_0=Low -TaskTagPreferenceTab_1=Normal -TaskTagPreferenceTab_2=High -TaskTagPreferenceTab_3=N/A -TaskTagPreferenceTab_5=Task Tag -TaskTagPreferenceTab_6=Tag: -TaskTagPreferenceTab_7=Priority: -TaskTagPreferenceTab_12=Tag -TaskTagPreferenceTab_13=Priority -TaskTagPreferenceTab_14=&New... -TaskTagPreferenceTab_15=Ed&it... -TaskTagPreferenceTab_16=&Remove -TaskTagPreferenceTab_17=&Select All -TaskTagPreferenceTab_18=Deselect A&ll -TaskTagPreferenceTab_19=Note: tags are case insensitive -TaskTagPreferenceTab_20=&Task Tags -TaskTagPreferenceTab_22=Task Tags Settings Changed -TaskTagPreferenceTab_23=The task tags settings have changed. Make these changes effective now? -TaskTagPreferenceTab_24=Yes -TaskTagPreferenceTab_25=No -TaskTagPreferenceTab_26=Cancel -TaskTagPreferenceTab_27=Scanning files for tasks -TaskTagPreferenceTab_28=detection aborted -TaskTagPreferenceTab_29=detection completed -TaskTagPreferenceTab_30=detection encountered errors -TaskTagPreferenceTab_31=&Enable searching for Task Tags -TaskTagPreferencePage_32=&Clean and redetect Tasks -TaskTagPreferenceTab_33=Ta&gs in comments indicating Tasks: -TaskTagExclusionTab_01=&Filters -TaskTagExclusionTab_02=Sca&n the selected Content Types: -TaskTagExclusionTab_03=Affected Content T&ypes: - -PropertyPreferencePage_01=Project Specific Configuration -PropertyPreferencePage_02=Select the project to configure: - -FilePreferencePage_0=Expand the tree to edit preferences for a specific content type. -NoModificationCompletionProposal_0=No corrections available -ToggleBreakpointAction_0=Toggle &Breakpoints -ManageBreakpointAction_0=&Enable Breakpoints -ManageBreakpointAction_1=&Disable Breakpoints -EditBreakpointAction_0=Breakpoint &Properties... -## Used in Structured Text Editor Preference Page / Hovers Tab -TextHoverPreferenceTab_title=Hovers -TextHoverPreferenceTab_hoverPreferences=Text &Hover key modifier preferences: -TextHoverPreferenceTab_keyModifier=Pressed key &modifier while hovering: -TextHoverPreferenceTab_description=Description: -TextHoverPreferenceTab_modifierIsNotValid=Modifier ''{0}'' is not valid. -TextHoverPreferenceTab_modifierIsNotValidForHover=Modifier ''{0}'' for ''{1}'' hover is not valid. -TextHoverPreferenceTab_duplicateModifier=''{0}'' hover uses the same modifier as ''{1}'' hover. -TextHoverPreferenceTab_nameColumnTitle=Text Hover Name -TextHoverPreferenceTab_modifierColumnTitle=Pressed Key Modifier While Hovering -TextHoverPreferenceTab_delimiter=+ -TextHoverPreferenceTab_insertDelimiterAndModifierAndDelimiter=\ + {0} + -TextHoverPreferenceTab_insertModifierAndDelimiter=\ {0} + -TextHoverPreferenceTab_insertDelimiterAndModifier=\ + {0} -combinationHover_label=Combined Hover -combinationHover_desc=Tries the hovers in the sequence listed in the table below this one and uses the one which fits best for the selected element and the current context. -problemHover_label=Problem Description -problemHover_desc=Shows the description of the selected problem. -documentationHover_label=Documentation Description -documentationHover_desc=Shows the documentation of the selected element. -annotationHover_label=Annotation Description -annotationHover_desc=Shows the description of the selected annotation. -EditStructuredTextEditorPreferencesAction_0=Editor Preferences -StructuredTextEditorPreferencePage_0=Appearance -StructuredTextEditorPreferencePage_1=Enable &semantic highlighting -PreferenceManager_0=Original Error: - -OccurrencesSearchQuery_0={0} - {1} occurrences in {2} -OccurrencesSearchQuery_2=file -ShowView_errorTitle=Problems Showing View -proc_dirty_regions_0 = Processing Dirty Regions - -textHoverMakeStickyHint=Press ''{0}'' for focus. - -## Encoding -EncodingPreferencePage_0=Encoding settings for Web and XML files: -EncodingPreferencePage_1=Use 3 byte BOM (Byte Order Mark) when saving UTF-8 encoded files -caret_update=caret update -EmptyFilePreferencePage_0=This category ID has been replaced by 'org.eclipse.wst.xml.ui.preferences.xml' and 'org.eclipse.wst.html.ui.preferences.web' -OffsetStatusLineContributionItem_0=Selection Information: -OffsetStatusLineContributionItem_2=Partitions -OffsetStatusLineContributionItem_3=ITextRegions -OffsetStatusLineContributionItem_4=Structured Model Content-Type: -OffsetStatusLineContributionItem_5=Model Handler: -OffsetStatusLineContributionItem_6=Document Class: -OffsetStatusLineContributionItem_7=Document Provider Class: -OffsetStatusLineContributionItem_8=Partitionings: -OffsetStatusLineContributionItem_9=Start -OffsetStatusLineContributionItem_10=Length -OffsetStatusLineContributionItem_11=Type -OffsetStatusLineContributionItem_12=Input Type: -OffsetStatusLineContributionItem_13=Partitioner: -OffsetStatusLineContributionItem_14=Structured Selection -OffsetStatusLineContributionItem_15=Start -OffsetStatusLineContributionItem_16=Length -OffsetStatusLineContributionItem_17=Text Length -OffsetStatusLineContributionItem_18=Context -OffsetStatusLineContributionItem_19=Workbench Selection -OffsetStatusLineContributionItem_20=Indexed Regions - -StructuredTextEditor_0=Unsupported content type warning -UnknownContentTypeDialog_0=Unsupported Content Type -UnknownContentTypeDialog_1=Do not show this message again -UnknownContentTypeDialog_2=Unsupported content type in editor.\nTo associate file extension with a supported content type,\nplease see <a>Content Types Preference Page</a> - -################################################################################ -## Below are possibly unused strings that may be removed -################################################################################ -Save_label=&Save -An_error_has_occurred_when_ERROR_=An error has occurred when retrieving resources for the source editor. The Eclipse Workbench installation may have been corrupted. -## save as problems (next two) should match what is in workbench -Problems_During_Save_As_UI_=Problems During Save As... -Save_could_not_be_complete_UI_=Save could not be completed. -SemanticHighlightingReconciler_0=Semantic Highlighting Job -ManageBreakpoints_error_removing_title1=Remove Breakpoint -ManageBreakpoints_error_removing_message1=Cannot remove breakpoint -ManageBreakpoints_error_retrieving_message=Retrieving markers failed: -JSPSourcePreferencePageDescription=Embedded content type\'s source preferences will be used. Select the file type for customization -# The following lines copied from org\eclipse\ui\editors\text\TextEditorMessages.properties in org.eclipse.ui plugin -Editor_error_save_message=Save could not be completed. {0} -Editor_error_save_title=Problems During Save As... -Editor_warning_save_delete=The original file ''{0}'' has been deleted. - -# actions -Previous_annotation=Previous Annotation -Next_annotation=Next Annotation -# Annotation Types -AnnotationTypes_Errors=Errors -AnnotationTypes_Warnings=Warnings -AnnotationTypes_Tasks=Tasks -AnnotationTypes_SearchResults=Search Results -AnnotationTypes_Bookmarks=Bookmarks -AnnotationTypes_Others=Others - -Editor_ConvertToWindows_label=&Windows -Editor_ConvertToWindows_tooltip=Converts line delimiters to Windows -Editor_ConvertToWindows_image= -Editor_ConvertToWindows_description=Converts line delimiters to Windows - -Editor_ConvertToUNIX_label=&UNIX -Editor_ConvertToUNIX_tooltip=Converts line delimiters to UNIX -Editor_ConvertToUNIX_image= -Editor_ConvertToUNIX_description=Converts line delimiters to UNIX - -Editor_ConvertToMac_label=&Mac -Editor_ConvertToMac_tooltip=Converts line delimiters to Mac -Editor_ConvertToMac_image= -Editor_ConvertToMac_description=Converts line delimiters to Mac -ConvertLineDelimitersMenu_label=Co&nvert Line Delimiters to -FindOccurrences_label=O&ccurrences in File - -ConvertLineDelimitersToCRLFActionDelegate_jobName=Converting line delimiters -ConvertLineDelimitersToCRLFActionDelegate_errorStatusMessage=Exceptions occurred while converting line delimiters -ConvertLineDelimitersToCRLFActionDelegate_3=Converting line delimiters for {0} -ConvertLineDelimitersToCRLFActionDelegate_4=Exception occurred while converting line delimiters for document {0} -TextHoverPreferenceTab_annotationRollover=&Enable annotation roll-over (on new editors) -TextHoverPreferenceTab_showAffordance=&Show affordance in hover on how to make it sticky -TextHoverPreferenceTab_enabled=&Enabled - -BasicFindOccurrencesAction_0=region match: -BasicSearchLabelProvider_0=line -NavigationPreferenceTab_0=Modifier ''{0}'' is not valid. -OccurrencesSearchQuery_1={0} - 1 Occurrence in {1} -FileModelProvider_0=Error reloading {0} -JFaceNodeAdapter_0=Update Outline - -ConfigureProjectSettings=Configure Project Specific Settings... -ConfigureWorkspaceSettings=Configure Workspace Settings... -EnableProjectSettings=Enable &project specific settings - -LoadingReferencedGrammars=Loading referenced grammars - -## Folding -Folding=Folding -StructuredTextEditorPreferencePage_3=Enable &folding -Projection_Toggle_label= &Enable Folding -Projection_Toggle_tooltip= Toggles Folding -Projection_Toggle_description= Toggles folding for the current editor -Projection_Toggle_image= -Projection_ExpandAll_label= Expand &All -Projection_ExpandAll_tooltip= Expands All Collapsed Regions -Projection_ExpandAll_description= Expands any collapsed regions in the current editor -Projection_ExpandAll_image= -Projection_CollapseAll_label= Collapse A&ll -Projection_CollapseAll_tooltip= Collapses All Expanded Regions -Projection_CollapseAll_description= Collapse any expanded regions in the current editor -Projection_CollapseAll_image= - -## These are copied from org.eclipse.ui.texteditor.EditorMessages.properties -## They are needed temporarily until CMVC defect 203158 / Bugzilla defect 20054 is fixed -Editor_ManageBookmarks_tooltip=Adds and Removes Bookmarks -Editor_ManageBookmarks_image= -Editor_ManageBookmarks_description=Adds and removes Bookmarks -Editor_ManageBookmarks_add_label=Add Boo&kmark... -Editor_ManageBookmarks_remove_label=Remove Boo&kmark -Editor_ManageBookmarks_add_dialog_title=Add Bookmark -Editor_ManageBookmarks_add_dialog_message=Enter Bookmark name -Editor_ManageBookmarks_error_dialog_title=Managing Bookmarks -Editor_ManageBookmarks_error_dialog_message=Problems managing bookmarks - -Editor_ManageTasks_tooltip=Adds and Removes Tasks -Editor_ManageTasks_image= -Editor_ManageTasks_description=Adds and removes Tasks -Editor_ManageTasks_add_label=Add &Task... -Editor_ManageTasks_remove_label=Remove &Task -Editor_ManageTasks_add_dialog_title=Add Task -Editor_ManageTasks_add_dialog_message=Enter Task description -Editor_ManageTasks_error_dialog_title=Managing Tasks -Editor_ManageTasks_error_dialog_message=Problems managing tasks -################################################################################ -## Above are possibly unused strings that may be removed -############################################################################### -StyledTextColorPicker_0=Pick a color -SyntaxColoring_Link=Default colors and font can be configured on the <a href=\"org.eclipse.ui.preferencePages.GeneralTextEditor\">Text Editors</a> and on the <a href=\"org.eclipse.ui.preferencePages.ColorsAndFonts\">Colors and Fonts</a> preference pages. Decorations for annotations can be configured on the <a href=\"org.eclipse.ui.editors.preferencePages.Annotations\">Annotations</a> preference page. -SyntaxColoring_Description=Customize the syntax highlighting by selecting the type of text whose style you want to customize from either the list or the example text area. - -GotoMatchingBracket_label= Matching &Bracket -GotoMatchingBracket_tooltip=Go to Matching Bracket -GotoMatchingBracket_description=Go to Matching Bracket -GotoMatchingBracket_error_invalidSelection=No bracket selected -GotoMatchingBracket_error_noMatchingBracket=No matching bracket found -GotoMatchingBracket_error_bracketOutsideSelectedElement=Matching bracket is outside the selected element - -TextSearchLabelProvider_matchCountFormat=({0} matches) - - -################################################## -## Content Assist Strings -################################################## -ContentAssist_computing_proposals=Computing completion proposals -ContentAssist_collecting_proposals=Collecting completion proposals -ContentAssist_sorting_proposals=Sorting completion proposals -ContentAssist_collecting_contexts=Collecting context information -ContentAssist_computing_contexts=Computing context information -ContentAssist_sorting_contexts=Sorting context information -ContentAssist_no_completions=No completions available. -ContentAssist_all_disabled_title=Content Assist Problem -ContentAssist_all_disabled_message=Some content proposal kinds have been uninstalled. It is recommended to review the content assist settings. -ContentAssist_all_disabled_preference_link=Change the settings on the <a>Content Assist preference page</a> or click ''{0}'' to restore the default behavior. -ContentAssist_no_message= No {0} -ContentAssist_toggle_affordance_update_message={1} to show {2} -ContentAssist_defaultProposalCategory_title=Default Proposals -ContentAssist_press=Press ''{0}'' -ContentAssist_click=Click -OptionalMessageDialog_dontShowAgain= Do not show this &message again - -################################################## -## Content Assist Properties page Strings -################################################## -CodeAssistAdvancedConfigurationBlock_page_description=Configure the behavior of the content assist ({0}) command. -CodeAssistAdvancedConfigurationBlock_no_shortcut=no shortcut -CodeAssistAdvancedConfigurationBlock_Up=&Up -CodeAssistAdvancedConfigurationBlock_Down=D&own -CodeAssistAdvancedConfigurationBlock_default_table_description=Select the proposal &categories contained in the 'default' content assist list: -CodeAssistAdvancedConfigurationBlock_default_table_category_column_title=Default Proposal Categories -CodeAssistAdvancedConfigurationBlock_PagesDown=Do&wn -CodeAssistAdvancedConfigurationBlock_PagesUp=U&p -CodeAssistAdvancedConfigurationBlock_separate_table_description=Select the &enablement and order of proposal categories that are cycled through when repeatedly invoking content assist: -CodeAssistAdvancedConfigurationBlock_separate_table_category_column_title=Content Assist Pages -Validation_Title=Validation Settings Changed -Validation_Workspace=The validation settings have changed. A full validation is required for changes to take effect. Validate now? -Validation_Project=The validation settings have changed. A validation of the project is required for changes to take effect. Validate the project now? -Validation_jobName=Validating...
\ No newline at end of file diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/ShowViewAction.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/ShowViewAction.java deleted file mode 100644 index 6e3aa6392c..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/ShowViewAction.java +++ /dev/null @@ -1,99 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal; - -import org.eclipse.jface.action.Action; -import org.eclipse.jface.dialogs.ErrorDialog; -import org.eclipse.jface.resource.ImageDescriptor; -import org.eclipse.swt.widgets.Event; -import org.eclipse.ui.IWorkbenchPage; -import org.eclipse.ui.IWorkbenchWindow; -import org.eclipse.ui.PartInitException; - -/** - * Surfaces a View. - * - * @author Nitin Dahyabhai - */ -public abstract class ShowViewAction extends Action { - /** - * - */ - public ShowViewAction() { - super(); - } - - /** - * @param text - */ - public ShowViewAction(String text) { - super(text); - } - - /** - * @param text - * @param image - */ - public ShowViewAction(String text, ImageDescriptor image) { - super(text, image); - } - - /** - * @param text - * @param style - */ - public ShowViewAction(String text, int style) { - super(text, style); - } - - /** - * @return - */ - protected abstract String getViewID(); - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.action.Action#run() - */ - public void run() { - super.run(); - showView(); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.action.Action#runWithEvent(org.eclipse.swt.widgets.Event) - */ - public void runWithEvent(Event event) { - super.runWithEvent(event); - showView(); - } - - /** - * - */ - private void showView() { - IWorkbenchWindow window = SSEUIPlugin.getDefault().getWorkbench().getActiveWorkbenchWindow(); - IWorkbenchPage page = window.getActivePage(); - if (page != null) { - try { - page.showView(getViewID()); - } catch (PartInitException e) { - ErrorDialog.openError(window.getShell(), SSEUIMessages.ShowView_errorTitle, //$NON-NLS-1$ - e.getMessage(), e.getStatus()); - } - } - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/StorageModelProvider.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/StorageModelProvider.java deleted file mode 100644 index 18815a78ed..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/StorageModelProvider.java +++ /dev/null @@ -1,764 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2011 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal; - -import java.io.IOException; -import java.io.InputStream; -import java.io.Reader; -import java.util.HashMap; -import java.util.Map; - -import org.eclipse.core.resources.IEncodedStorage; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.IStorage; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.QualifiedName; -import org.eclipse.core.runtime.content.IContentDescription; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.source.AnnotationModel; -import org.eclipse.jface.text.source.IAnnotationModel; -import org.eclipse.osgi.util.NLS; -import org.eclipse.ui.IEditorInput; -import org.eclipse.ui.IPathEditorInput; -import org.eclipse.ui.IStorageEditorInput; -import org.eclipse.ui.editors.text.FileDocumentProvider; -import org.eclipse.ui.editors.text.ILocationProvider; -import org.eclipse.ui.editors.text.StorageDocumentProvider; -import org.eclipse.ui.texteditor.DocumentProviderRegistry; -import org.eclipse.ui.texteditor.IDocumentProvider; -import org.eclipse.ui.texteditor.IElementStateListener; -import org.eclipse.wst.sse.core.StructuredModelManager; -import org.eclipse.wst.sse.core.internal.encoding.CodedReaderCreator; -import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument; -import org.eclipse.wst.sse.core.internal.util.Utilities; -import org.eclipse.wst.sse.ui.internal.debug.BreakpointRulerAction; -import org.eclipse.wst.sse.ui.internal.editor.EditorModelUtil; -import org.eclipse.wst.sse.ui.internal.extension.BreakpointProviderBuilder; -import org.eclipse.wst.sse.ui.internal.provisional.extensions.breakpoint.IExtendedStorageEditorInput; - -/** - * A StorageDocumentProvider that is IStructuredModel aware - */ -public class StorageModelProvider extends StorageDocumentProvider implements IModelProvider { - - private class InternalElementStateListener implements IElementStateListener { - public void elementContentAboutToBeReplaced(Object element) { - if (debugElementStatelistener) { - System.out.println("StorageModelProvider: elementContentAboutToBeReplaced: " + ((IEditorInput) element).getName()); //$NON-NLS-1$ - } - // we just forward the event - StorageModelProvider.this.fireElementContentAboutToBeReplaced(element); - } - - public void elementContentReplaced(Object element) { - if (debugElementStatelistener) { - System.out.println("StorageModelProvider: elementContentReplaced: " + ((IEditorInput) element).getName()); //$NON-NLS-1$ - } - - StorageInfo info = (StorageInfo) getElementInfo(element); - - if (info == null) - return; - - /** - * Force a reload of the markers into annotations since their - * previous Positions have been deleted. Disconnecting and - * reconnecting forces a call to the private catchupWithMarkers - * method. - */ - if (info.fModel != null) { - info.fModel.disconnect(info.fDocument); - } - - Reader reader = null; - IStructuredDocument innerdocument = null; - try { - // update document from input's contents - CodedReaderCreator codedReaderCreator = new CodedReaderCreator(calculateID((IStorageEditorInput) element), Utilities.getMarkSupportedStream(((IStorageEditorInput) element).getStorage().getContents())); - reader = codedReaderCreator.getCodedReader(); - - innerdocument = (IStructuredDocument) info.fDocument; - - int originalLengthToReplace = innerdocument.getLength(); - - StringBuffer stringBuffer = new StringBuffer(); - int bufferSize = 2048; - char[] buffer = new char[bufferSize]; - int nRead = 0; - boolean eof = false; - while (!eof) { - nRead = reader.read(buffer, 0, bufferSize); - if (nRead == -1) { - eof = true; - } - else { - stringBuffer.append(buffer, 0, nRead); - } - } - innerdocument.replaceText(this, 0, originalLengthToReplace, stringBuffer.toString(), true); - } - catch (CoreException e) { - Logger.logException(e); - } - catch (IOException e) { - Logger.logException(e); - } - finally { - if (reader != null) { - try { - reader.close(); - } - catch (IOException e1) { - // would be highly unusual - Logger.logException(e1); - } - } - } - - // forward the event - if (info.fCanBeSaved) { - info.fCanBeSaved = false; - addUnchangedElementListeners(element, info); - } - fireElementContentReplaced(element); - fireElementDirtyStateChanged(element, false); - - if (info != null && info.fModel != null) { - info.fModel.connect(info.fDocument); - } - } - - public void elementDeleted(Object element) { - if (debugElementStatelistener) { - System.out.println("StorageModelProvider: elementDeleted: " + ((IEditorInput) element).getName()); //$NON-NLS-1$ - } - // we just forward the event - StorageModelProvider.this.fireElementDeleted(element); - } - - public void elementDirtyStateChanged(Object element, boolean isDirty) { - if (debugElementStatelistener) { - System.out.println("StorageModelProvider: elementDirtyStateChanged: " + ((IEditorInput) element).getName() + " (" + isDirty + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } - // we just forward the event - StorageModelProvider.this.fireElementDirtyStateChanged(element, isDirty); - } - - public void elementMoved(Object originalElement, Object movedElement) { - if (debugElementStatelistener) { - System.out.println("StorageModelProvider: elementMoved " + originalElement + " --> " + movedElement); //$NON-NLS-1$ //$NON-NLS-2$ - } - // we just forward the event - StorageModelProvider.this.fireElementMoved(originalElement, movedElement); - } - } - - /** - * Collection of info that goes with a model. - */ - private class ModelInfo { - public IEditorInput fElement; - public boolean fShouldReleaseOnInfoDispose; - public IStructuredModel fStructuredModel; - - public ModelInfo(IStructuredModel structuredModel, IEditorInput element, boolean selfCreated) { - fElement = element; - fStructuredModel = structuredModel; - fShouldReleaseOnInfoDispose = selfCreated; - } - } - - static final boolean debugElementStatelistener = "true".equalsIgnoreCase(Platform.getDebugOption("org.eclipse.wst.sse.ui/storagemodelprovider/elementstatelistener")); //$NON-NLS-1$ //$NON-NLS-2$ - static final boolean debugOperations = "true".equalsIgnoreCase(Platform.getDebugOption("org.eclipse.wst.sse.ui/storagemodelprovider/operations")); //$NON-NLS-1$ //$NON-NLS-2$ - - private static StorageModelProvider fInstance = null; - - public synchronized static StorageModelProvider getInstance() { - if (fInstance == null) - fInstance = new StorageModelProvider(); - return fInstance; - } - - private IElementStateListener fInternalListener; - /** IStructuredModel information of all connected elements */ - private Map fModelInfoMap = new HashMap(); - private boolean fReuseModelDocument = true; - - private StorageModelProvider() { - super(); - fInternalListener = new InternalElementStateListener(); - } - - String calculateBaseLocation(IStorageEditorInput input) { - String location = null; - if (input instanceof IPathEditorInput) { - IPath path = ((IPathEditorInput) input).getPath(); - if (path != null) { - location = path.toString(); - } - } - if (location == null && input instanceof ILocationProvider) { - IPath path = ((ILocationProvider) input).getPath(input); - if (path != null) { - location = path.toString(); - } - } - if (location == null) { - try { - IStorage storage = input.getStorage(); - if (storage != null) { - IPath storagePath = storage.getFullPath(); - String name = storage.getName(); - if (storagePath != null) { - /* - * If the path's last segment and the name are - * different, the IStorage contract is not being - * honored - * (https://bugs.eclipse.org/bugs/show_bug.cgi? - * id=73098). Favor the name - */ - if (!storagePath.lastSegment().equals(name)) { - IPath workingPath = storagePath.addTrailingSeparator(); - location = workingPath.append(name).toString(); - } - else { - location = storagePath.makeAbsolute().toString(); - } - } - if (location == null) - location = name; - } - } - catch (CoreException e) { - Logger.logException(e); - } - finally { - if (location == null) - location = input.getName(); - } - } - return location; - } - - String calculateID(IStorageEditorInput input) { - /** - * Typically CVS will return a path of "filename.ext" and the input's - * name will be "filename.ext version". The path must be used to load - * the model so that the suffix will be available to compute the - * contentType properly. The editor input name can then be set as the - * base location for display on the editor title bar. - * - */ - String path = null; - if (input instanceof ILocationProvider) { - IPath ipath = ((ILocationProvider) input).getPath(input); - if (ipath != null) { - path = ipath.toString(); - } - } - if (path == null) { - try { - IStorage storage = input.getStorage(); - if (storage != null) { - IPath storagePath = storage.getFullPath(); - String name = storage.getName(); - if (storagePath != null) { - // If they are different, the IStorage contract is not - // being honored - // (https://bugs.eclipse.org/bugs/show_bug.cgi?id=73098). - // Favor the name. - if (!storagePath.lastSegment().equals(name)) { - IPath workingPath = storagePath.addTrailingSeparator(); - path = workingPath.append(name).toString(); - } - else { - path = storagePath.makeAbsolute().toString(); - } - } - if (path == null) - path = name; - } - } - catch (CoreException e) { - Logger.logException(e); - } - finally { - if (path == null) - path = input.getName(); //$NON-NLS-1$ - } - } - /* - * Prepend the hash to the path value so that we have a 1:1:1 match - * between editor inputs, element info, and models. The editor manager - * should help prevent needlessly duplicated models as long as two - * editor inputs from the same storage indicate they're equals(). - */ - path = input.hashCode() + "#" + path; //$NON-NLS-1$ - return path; - } - - // public boolean canSaveDocument(Object element) { - // return false; - // } - - protected IAnnotationModel createAnnotationModel(Object element) throws CoreException { - IAnnotationModel model = null; - if (debugOperations) { - if (element instanceof IStorageEditorInput) - System.out.println("StorageModelProvider: createAnnotationModel for " + ((IStorageEditorInput) element).getStorage().getFullPath()); //$NON-NLS-1$ - else - System.out.println("StorageModelProvider: createAnnotationModel for " + element); //$NON-NLS-1$ - } - if (element instanceof IStorageEditorInput) { - IStorageEditorInput input = (IStorageEditorInput) element; - String contentType = (getModel(input) != null ? getModel(input).getContentTypeIdentifier() : null); - String ext = BreakpointRulerAction.getFileExtension((IEditorInput) element); - IResource res = BreakpointProviderBuilder.getInstance().getResource(input, contentType, ext); - String id = input.getName(); - if (input.getStorage() != null && input.getStorage().getFullPath() != null) { - id = input.getStorage().getFullPath().toString(); - } - // we can only create a resource marker annotationmodel off of a - // valid resource - if (res != null) - model = new StructuredResourceMarkerAnnotationModel(res, id); - else - model = new AnnotationModel(); - } - if (model == null) { - model = super.createAnnotationModel(element); - } - return model; - } - - protected IDocument createDocument(Object element) { - if (debugOperations) { - if (element instanceof IStorageEditorInput) - try { - System.out.println("StorageModelProvider: createDocument for " + ((IStorageEditorInput) element).getStorage().getFullPath()); //$NON-NLS-1$ - } - catch (CoreException e) { - System.out.println("StorageModelProvider: createDocument for " + element + "(exception caught)"); //$NON-NLS-1$ //$NON-NLS-2$ - } - else { - System.out.println("StorageModelProvider: createDocument for " + element); //$NON-NLS-1$ - } - } - - // The following is largely copied from FileModelProvider - - IDocument document = null; - if (element instanceof IEditorInput) { - // create a new IDocument for the element; should always reflect - // the contents of the resource - ModelInfo info = getModelInfoFor((IEditorInput) element); - if (info == null) { - throw new IllegalArgumentException("no corresponding model info found"); //$NON-NLS-1$ - } - IStructuredModel model = info.fStructuredModel; - if (model != null) { - if (!fReuseModelDocument && element instanceof IStorageEditorInput) { - Reader reader = null; - IStructuredDocument innerdocument = null; - try { - // update document from input's contents - - CodedReaderCreator codedReaderCreator = new CodedReaderCreator(calculateID((IStorageEditorInput) element), Utilities.getMarkSupportedStream(((IStorageEditorInput) element).getStorage().getContents())); - reader = codedReaderCreator.getCodedReader(); - - innerdocument = model.getStructuredDocument(); - - int originalLengthToReplace = innerdocument.getLength(); - - /* - * TODO_future: we could implement with sequential - * rewrite, if we don't pickup automatically from - * FileBuffer support, so not so much has to be pulled - * into memory (as an extra big string), but we need - * to carry that API through so that StructuredModel - * is not notified until done. - */ - - // innerdocument.startSequentialRewrite(true); - // innerdocument.replaceText(this, 0, - // innerdocument.getLength(), ""); - StringBuffer stringBuffer = new StringBuffer(); - int bufferSize = 2048; - char[] buffer = new char[bufferSize]; - int nRead = 0; - boolean eof = false; - while (!eof) { - nRead = reader.read(buffer, 0, bufferSize); - if (nRead == -1) { - eof = true; - } - else { - stringBuffer.append(buffer, 0, nRead); - // innerdocument.replaceText(this, - // innerdocument.getLength(), 0, new - // String(buffer, 0, nRead)); - } - } - // ignore read-only settings if reverting whole - // document - innerdocument.replaceText(this, 0, originalLengthToReplace, stringBuffer.toString(), true); - model.setDirtyState(false); - - } - catch (CoreException e) { - Logger.logException(e); - } - catch (IOException e) { - Logger.logException(e); - } - finally { - if (reader != null) { - try { - reader.close(); - } - catch (IOException e1) { - // would be highly unusual - Logger.logException(e1); - } - } - // if (innerdocument != null) { - // innerdocument.stopSequentialRewrite(); - // } - } - - } - document = model.getStructuredDocument(); - } - } - return document; - } - - /** - * Also create ModelInfo - extra resource synchronization classes should - * be stored within the ModelInfo - */ - protected ElementInfo createElementInfo(Object element) throws CoreException { - // create the corresponding ModelInfo if necessary - if (debugOperations) { - if (element instanceof IStorageEditorInput) - try { - System.out.println("StorageModelProvider: createElementInfo for " + ((IStorageEditorInput) element).getStorage().getFullPath()); //$NON-NLS-1$ - } - catch (CoreException e) { - System.out.println("StorageModelProvider: createElementInfo for " + element + "(exception caught)"); //$NON-NLS-1$ //$NON-NLS-2$ - } - else - System.out.println("storageModelProvider: createElementInfo for " + element); //$NON-NLS-1$ - } - - if (getModelInfoFor((IEditorInput) element) == null) { - createModelInfo((IEditorInput) element); - } - - ElementInfo info = super.createElementInfo(element); - return info; - } - - public void createModelInfo(IEditorInput input) { - if (getModelInfoFor(input) == null) { - IStructuredModel structuredModel = selfCreateModel(input); - if (structuredModel != null) { - createModelInfo(input, structuredModel, true); - } - } - } - - /** - * To be used when model is provided to us, ensures that when setInput is - * used on this input, the given model will be used. - */ - public void createModelInfo(IEditorInput input, IStructuredModel structuredModel, boolean releaseModelOnDisconnect) { - // we have to make sure factories are added, whether we created or - // not. - if (getModelInfoFor(input) != null || getModelInfoFor(structuredModel) != null) { - if (debugOperations) { - if (input instanceof IStorageEditorInput) { - - try { - System.out.println("StorageModelProvider: DUPLICATE createModelInfo for " + ((IStorageEditorInput) input).getStorage().getFullPath()); //$NON-NLS-1$ - } - catch (CoreException e) { - System.out.println("StorageModelProvider: DUPLICATE createModelInfo for " + input + "(exception caught)"); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - else { - System.out.println("storageModelProvider: DUPLICATE createModelInfo for " + input); //$NON-NLS-1$ - } - } - return; - } - - if (debugOperations) { - if (input instanceof IStorageEditorInput) { - try { - System.out.println("StorageModelProvider: createModelInfo for " + ((IStorageEditorInput) input).getStorage().getFullPath()); //$NON-NLS-1$ - } - catch (CoreException e) { - System.out.println("StorageModelProvider: createModelInfo for " + input + "(exception caught)"); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - else { - System.out.println("StorageModelProvider: createModelInfo for " + input); //$NON-NLS-1$ - } - } - - - if (input instanceof IExtendedStorageEditorInput) { - ((IExtendedStorageEditorInput) input).addElementStateListener(fInternalListener); - } - - EditorModelUtil.addFactoriesTo(structuredModel); - - ModelInfo modelInfo = new ModelInfo(structuredModel, input, releaseModelOnDisconnect); - fModelInfoMap.put(input, modelInfo); - } - - protected void disposeElementInfo(Object element, ElementInfo info) { - if (debugOperations) { - if (element instanceof IStorageEditorInput) { - try { - System.out.println("StorageModelProvider: disposeElementInfo for " + ((IStorageEditorInput) element).getStorage().getFullPath()); //$NON-NLS-1$ - } - catch (CoreException e) { - System.out.println("StorageModelProvider: disposeElementInfo for " + element + "(exception caught)"); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - else { - System.out.println("StorageModelProvider: disposeElementInfo for " + element); //$NON-NLS-1$ - } - } - - if (element instanceof IEditorInput) { - IEditorInput input = (IEditorInput) element; - ModelInfo modelInfo = getModelInfoFor(input); - disposeModelInfo(modelInfo); - } - super.disposeElementInfo(element, info); - } - - /** - * disconnect from this model info - * - * @param info - */ - public void disposeModelInfo(ModelInfo info) { - if (debugOperations) { - if (info.fElement instanceof IStorageEditorInput) { - try { - System.out.println("StorageModelProvider: disposeModelInfo for " + ((IStorageEditorInput) info.fElement).getStorage().getFullPath()); //$NON-NLS-1$ - } - catch (CoreException e) { - System.out.println("StorageModelProvider: disposeModelInfo for " + info.fElement + "(exception caught)"); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - else { - System.out.println("StorageModelProvider: disposeModelInfo for " + info.fElement); //$NON-NLS-1$ - } - } - - if (info.fElement instanceof IStorageEditorInput) { - if (info.fElement instanceof IExtendedStorageEditorInput) { - ((IExtendedStorageEditorInput) info.fElement).removeElementStateListener(fInternalListener); - } - if (info.fShouldReleaseOnInfoDispose) { - info.fStructuredModel.releaseFromEdit(); - } - } - fModelInfoMap.remove(info.fElement); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.AbstractDocumentProvider#doResetDocument(java.lang.Object, - * org.eclipse.core.runtime.IProgressMonitor) - */ - protected void doResetDocument(Object element, IProgressMonitor monitor) throws CoreException { - fReuseModelDocument = false; - super.doResetDocument(element, monitor); - fReuseModelDocument = true; - } - - /** - * @see org.eclipse.ui.texteditor.AbstractDocumentProvider#doSaveDocument(org.eclipse.core.runtime.IProgressMonitor, - * java.lang.Object, org.eclipse.jface.text.IDocument, boolean) - */ - protected void doSaveDocument(IProgressMonitor monitor, Object element, IDocument document, boolean overwrite) throws CoreException { - IDocumentProvider provider = null; - // BUG119211 - try to use registered document provider if possible - if (element instanceof IEditorInput) { - provider = DocumentProviderRegistry.getDefault().getDocumentProvider((IEditorInput) element); - } - if (provider == null) - provider = new FileDocumentProvider(); - provider.saveDocument(monitor, element, document, overwrite); - } - - /* (non-Javadoc) - * @see org.eclipse.ui.editors.text.StorageDocumentProvider#getPersistedEncoding(java.lang.Object) - */ - protected String getPersistedEncoding(Object element) { - String charset = super.getPersistedEncoding(element); - if (charset == null && element instanceof IStorageEditorInput) { - IStorage storage; - try { - storage = ((IStorageEditorInput) element).getStorage(); - if (storage != null && !(storage instanceof IEncodedStorage)) { - InputStream contents = null; - try { - contents = storage.getContents(); - if (contents != null) { - QualifiedName[] detectionOptions = new QualifiedName[]{IContentDescription.BYTE_ORDER_MARK, IContentDescription.CHARSET}; - IContentDescription description = Platform.getContentTypeManager().getDescriptionFor(contents, storage.getName(), detectionOptions); - if (description != null) { - charset = description.getCharset(); - } - } - - } - catch (IOException e) { - } - finally { - if (contents != null) - try { - contents.close(); - } - catch (IOException e) { - // do nothing - } - } - } - } - catch (CoreException e) { - Logger.logException(e); - } - } - return charset; - } - - public IStructuredModel getModel(IEditorInput element) { - IStructuredModel result = null; - ModelInfo info = getModelInfoFor(element); - if (info != null) { - result = info.fStructuredModel; - } - return result; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.sse.ui.IModelProvider#getModel(java.lang.Object) - */ - public IStructuredModel getModel(Object element) { - if (element instanceof IEditorInput) - return getModel((IEditorInput) element); - return null; - } - - private ModelInfo getModelInfoFor(IEditorInput element) { - ModelInfo result = (ModelInfo) fModelInfoMap.get(element); - return result; - } - - private ModelInfo getModelInfoFor(IStructuredModel structuredModel) { - ModelInfo result = null; - if (structuredModel != null) { - ModelInfo[] modelInfos = (ModelInfo[]) fModelInfoMap.values().toArray(new ModelInfo[0]); - for (int i = 0; i < modelInfos.length; i++) { - ModelInfo info = modelInfos[i]; - if (structuredModel.equals(info.fStructuredModel)) { - result = info; - break; - } - } - } - return result; - } - - /** - * Method loadModel. - * - * @param input - * @return IStructuredModel - */ - public IStructuredModel loadModel(IStorageEditorInput input) { - return loadModel(input, false); - } - - /** - * Method loadModel. - * - * @param input - * @param logExceptions - * @return IStructuredModel - */ - public IStructuredModel loadModel(IStorageEditorInput input, boolean logExceptions) { - String id = calculateID(input); - if (id == null) { - return null; - } - - InputStream contents = null; - try { - contents = input.getStorage().getContents(); - } - catch (CoreException noStorageExc) { - if (logExceptions) - Logger.logException(NLS.bind(SSEUIMessages._32concat_EXC_, new Object[]{input.getName()}), noStorageExc); - } - - IStructuredModel model = null; - try { - // first parameter must be unique - model = StructuredModelManager.getModelManager().getModelForEdit(id, contents, null); - model.setBaseLocation(calculateBaseLocation(input)); - } - catch (IOException e) { - if (logExceptions) - Logger.logException(NLS.bind(SSEUIMessages._32concat_EXC_, new Object[]{input}), e); - } - finally { - if (contents != null) { - try { - contents.close(); - } - catch (IOException e) { - // nothing - } - catch (Exception e) { - Logger.logException(e); - } - } - } - return model; - } - - /** - * @param input - * @return - */ - private IStructuredModel selfCreateModel(IEditorInput input) { - return loadModel((IStorageEditorInput) input); - } - -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/StructuredDocumentToTextAdapter.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/StructuredDocumentToTextAdapter.java deleted file mode 100644 index 4a276fd591..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/StructuredDocumentToTextAdapter.java +++ /dev/null @@ -1,1332 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.jobs.ILock; -import org.eclipse.jface.text.AbstractDocument; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.ConfigurableLineTracker; -import org.eclipse.jface.text.DefaultLineTracker; -import org.eclipse.jface.text.DocumentEvent; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IDocumentAdapter; -import org.eclipse.jface.text.IDocumentAdapterExtension; -import org.eclipse.jface.text.IDocumentListener; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.IRepairableDocument; -import org.eclipse.jface.text.ITextStore; -import org.eclipse.jface.text.Region; -import org.eclipse.jface.text.TextUtilities; -import org.eclipse.jface.text.projection.ProjectionDocument; -import org.eclipse.swt.custom.StyledText; -import org.eclipse.swt.custom.TextChangeListener; -import org.eclipse.swt.custom.TextChangedEvent; -import org.eclipse.swt.custom.TextChangingEvent; -import org.eclipse.swt.widgets.Display; -import org.eclipse.ui.PlatformUI; -import org.eclipse.wst.sse.core.internal.ILockable; -import org.eclipse.wst.sse.core.internal.provisional.events.IStructuredDocumentListener; -import org.eclipse.wst.sse.core.internal.provisional.events.NewDocumentEvent; -import org.eclipse.wst.sse.core.internal.provisional.events.NoChangeEvent; -import org.eclipse.wst.sse.core.internal.provisional.events.RegionChangedEvent; -import org.eclipse.wst.sse.core.internal.provisional.events.RegionsReplacedEvent; -import org.eclipse.wst.sse.core.internal.provisional.events.StructuredDocumentEvent; -import org.eclipse.wst.sse.core.internal.provisional.events.StructuredDocumentRegionsReplacedEvent; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegionList; -import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegion; -import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegionList; -import org.eclipse.wst.sse.core.internal.util.Debug; -import org.eclipse.wst.sse.core.internal.util.Utilities; -import org.eclipse.wst.sse.ui.internal.util.Assert; - - -/** - * Adapts IStructuredDocument events and methods to StyledTextContent events - * and methods - */ -public class StructuredDocumentToTextAdapter implements IDocumentAdapter, IDocumentAdapterExtension { - - private class DocumentClone extends AbstractDocument { - - - /** - * Creates a new document clone with the given content. - * - * @param content - * the content - * @param lineDelimiters - * the line delimiters - */ - public DocumentClone(String content, String[] lineDelimiters) { - super(); - setTextStore(new StringTextStore(content)); - ConfigurableLineTracker tracker = new ConfigurableLineTracker(lineDelimiters); - setLineTracker(tracker); - getTracker().set(content); - completeInitialization(); - } - } - - // A pre-notification listener for the viewer's Document - class DocumentListener implements IDocumentListener { - protected boolean allTextChanged = false; - - protected DocumentEvent currentEvent; - - synchronized public void documentAboutToBeChanged(DocumentEvent event) { - if (isStoppedForwardingChanges()) - return; - - pendingDocumentChangedEvent = true; - allTextChanged = event.getOffset() <= 0 && event.getLength() >= StructuredDocumentToTextAdapter.this.getDocument().getLength(); - currentEvent = event; - - StructuredDocumentToTextAdapter.this.relayTextChanging(event.getOffset(), event.getLength(), event.getText()); - } - - synchronized public void documentChanged(DocumentEvent event) { - if (isStoppedForwardingChanges()) - return; - - if (currentEvent != null && event == currentEvent) { - if (allTextChanged) { - StructuredDocumentToTextAdapter.this.relayTextSet(); - } - else { - // temp work around for immediate thread - // problem. - // should have more general solution - // soon. 'syncExec' are rumored to be - // prone to hang. - StructuredDocumentToTextAdapter.this.relayTextChanged(); - } - } - - currentEvent = null; - pendingDocumentChangedEvent = false; - handlePendingEvents(); - lastEvent = null; - - } - } - - private static class StringTextStore implements ITextStore { - - private String fContent; - - /** - * Creates a new string text store with the given content. - * - * @param content - * the content - */ - public StringTextStore(String content) { - Assert.isNotNull(content, "content can not be null when setting text store"); //$NON-NLS-1$ - fContent = content; - } - - /* - * @see org.eclipse.jface.text.ITextStore#get(int) - */ - public char get(int offset) { - return fContent.charAt(offset); - } - - /* - * @see org.eclipse.jface.text.ITextStore#get(int, int) - */ - public String get(int offset, int length) { - return fContent.substring(offset, offset + length); - } - - /* - * @see org.eclipse.jface.text.ITextStore#getLength() - */ - public int getLength() { - return fContent.length(); - } - - /* - * @see org.eclipse.jface.text.ITextStore#replace(int, int, - * java.lang.String) - */ - public void replace(int offset, int length, String text) { - } - - /* - * @see org.eclipse.jface.text.ITextStore#set(java.lang.String) - */ - public void set(String text) { - } - - } - - /** - * Changes to the Document/IStructuredDocument can extend beyond the text - * change area and require more redrawing to keep the hilighting correct. - * The event must be saved so that the redraw is only sent after a - * textChanged event is received. - */ - class StructuredDocumentListener implements IStructuredDocumentListener { - - public void newModel(NewDocumentEvent structuredDocumentEvent) { - - if (isStoppedForwardingChanges()) { - // if - // (StructuredDocumentToTextAdapter.this.fStopRelayingChanges) - // { - if (Debug.debugStructuredDocument) { - System.out.println("skipped relaying StructuredDocumentEvent " + structuredDocumentEvent.getClass().getName()); //$NON-NLS-1$ - } - return; - } - // should use textSet when all contents have - // changed - // otherwise need to use the pair of - // textChanging and - // textChanged. - StructuredDocumentToTextAdapter.this.lastEvent = structuredDocumentEvent; - } - - public void noChange(final NoChangeEvent structuredDocumentEvent) { - - if (Debug.debugStructuredDocument) { - System.out.println("skipped relaying StructuredDocumentEvent " + structuredDocumentEvent.getClass().getName()); //$NON-NLS-1$ - } - if (structuredDocumentEvent.reason == NoChangeEvent.READ_ONLY_STATE_CHANGE) { - if (pendingDocumentChangedEvent) { - if (lastEventQueue == null) { - lastEventQueue = new ArrayList(); - } - lastEventQueue.add(structuredDocumentEvent); - } - else { - StructuredDocumentToTextAdapter.this.lastEvent = structuredDocumentEvent; - } - } - } - - public void nodesReplaced(StructuredDocumentRegionsReplacedEvent structuredDocumentEvent) { - - if (isStoppedForwardingChanges()) { - // if - // (StructuredDocumentToTextAdapter.this.fStopRelayingChanges) - // { - if (Debug.debugStructuredDocument) { - System.out.println("not relaying StructuredDocumentEvent " + structuredDocumentEvent.getClass().getName()); //$NON-NLS-1$ - } - return; - } - if (Debug.debugStructuredDocument) { - System.out.println("saving StructuredDocumentEvent " + structuredDocumentEvent.getClass().getName()); //$NON-NLS-1$ - } - StructuredDocumentToTextAdapter.this.lastEvent = structuredDocumentEvent; - } - - public void regionChanged(RegionChangedEvent structuredDocumentEvent) { - - if (isStoppedForwardingChanges()) { - // if - // (StructuredDocumentToTextAdapter.this.fStopRelayingChanges) - // { - if (Debug.debugStructuredDocument) { - System.out.println("not relaying StructuredDocumentEvent " + structuredDocumentEvent.getClass().getName()); //$NON-NLS-1$ - } - return; - } - if (Debug.debugStructuredDocument) { - System.out.println("saving StructuredDocumentEvent " + structuredDocumentEvent.getClass().getName()); //$NON-NLS-1$ - } - StructuredDocumentToTextAdapter.this.lastEvent = structuredDocumentEvent; - } - - public void regionsReplaced(RegionsReplacedEvent structuredDocumentEvent) { - - if (isStoppedForwardingChanges()) { - // if - // (StructuredDocumentToTextAdapter.this.fStopRelayingChanges) - // { - if (Debug.debugStructuredDocument) { - System.out.println("not relaying StructuredDocumentEvent " + structuredDocumentEvent.getClass().getName()); //$NON-NLS-1$ - } - return; - } - if (Debug.debugStructuredDocument) { - System.out.println("saving StructuredDocumentEvent " + structuredDocumentEvent.getClass().getName()); //$NON-NLS-1$ - } - StructuredDocumentToTextAdapter.this.lastEvent = structuredDocumentEvent; - } - } - - private static final String EMPTY_STRING = ""; //$NON-NLS-1$ - - private final static boolean redrawBackground = true; - - /** The visible child document. */ - private ProjectionDocument fChildDocument; - - /** The master document */ - private IDocument fDocument; - /** The document clone for the non-forwarding case. */ - private IDocument fDocumentClone; - - // only use this temp work around if on GTK - // it causes funny "cursor blinking" if used on windows - private final boolean forceRedrawOnRegionChanged = Platform.getWS().equals("gtk"); //$NON-NLS-1$ - /** The original content */ - private String fOriginalContent; - /** The original line delimiters */ - private String[] fOriginalLineDelimiters; - - private int fStopRelayingChangesRequests = 0; - - private StyledText fStyledTextWidget; - - /** The registered text changed listeners */ - TextChangeListener[] fTextChangeListeners; - protected DocumentListener internalDocumentListener; - - // The listeners for relaying DocumentEvents and - // requesting repaints - // after modification - private IStructuredDocumentListener internalStructuredDocumentListener; - - protected StructuredDocumentEvent lastEvent = null; - List lastEventQueue; - boolean pendingDocumentChangedEvent; - - private static final boolean DEBUG = false; - - /** - * TEST ONLY - TEST ONLY - TEST ONLY NOT API use this constructor only for - * tests. Creates a new document adapter which is initiallly not connected - * to any document. - */ - public StructuredDocumentToTextAdapter() { - - internalStructuredDocumentListener = new StructuredDocumentListener(); - internalDocumentListener = new DocumentListener(); - // for testing only - // setDocument(getModelManager().createStructuredDocumentFor(ContentTypeIdentifierForXML.ContentTypeID_XML)); - } - - /** - * Creates a new document adapter which is initiallly not connected to any - * document. - */ - public StructuredDocumentToTextAdapter(StyledText styledTextWidget) { - - // do not use 'this()' in this case - super(); - internalStructuredDocumentListener = new StructuredDocumentListener(); - internalDocumentListener = new DocumentListener(); - fStyledTextWidget = styledTextWidget; - } - - private void _setDocument(IDocument newDoc) { - if (fDocument instanceof IStructuredDocument) { - ((IStructuredDocument) fDocument).removeDocumentChangedListener(internalStructuredDocumentListener); - } - fDocument = newDoc; - if (!isStoppedForwardingChanges()) { - fDocumentClone = null; - fOriginalContent = getDocument() != null ? getDocument().get() : null; - fOriginalLineDelimiters = getDocument() != null ? getDocument().getLegalLineDelimiters() : null; - } - - if (DEBUG && fDocument != null && !(fDocument instanceof ILockable)) { - - System.out.println("Warning: non ILockable document used in StructuredDocumentToTextAdapter"); //$NON-NLS-1$ - System.out.println(" document updates on non-display thread will not be safe if editor open"); //$NON-NLS-1$ - } - if (fDocument instanceof IStructuredDocument) { - ((IStructuredDocument) fDocument).addDocumentChangedListener(internalStructuredDocumentListener); - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.swt.custom.StyledTextContent#addTextChangeListener(org.eclipse.swt.custom.TextChangeListener) - */ - public synchronized void addTextChangeListener(TextChangeListener listener) { - - // make sure listener is not already in listening - // (and if it is, print a warning to aid debugging, - // if needed) - - if (Utilities.contains(fTextChangeListeners, listener)) { - if (Debug.displayWarnings) { - System.out.println("StructuredDocumentToTextAdapter::addTextChangedListeners. listener " + listener + " was added more than once. "); //$NON-NLS-2$//$NON-NLS-1$ - } - } - else { - if (Debug.debugStructuredDocument) { - System.out.println("StructuredDocumentToTextAdapter::addTextChangedListeners. Adding an instance of " + listener.getClass() + " as a listener on text adapter."); //$NON-NLS-2$//$NON-NLS-1$ - } - int oldSize = 0; - if (fTextChangeListeners != null) { - // normally won't be null, but we need to be - // sure, for first time through - oldSize = fTextChangeListeners.length; - } - int newSize = oldSize + 1; - TextChangeListener[] newListeners = new TextChangeListener[newSize]; - if (fTextChangeListeners != null) { - System.arraycopy(fTextChangeListeners, 0, newListeners, 0, oldSize); - } - // add listener to last position - newListeners[newSize - 1] = listener; - // - // now switch new for old - fTextChangeListeners = newListeners; - // - } - } - - /* - * @see org.eclipse.swt.custom.StyledTextContent#getCharCount() - */ - public int getCharCount() { - - // getDocument can sometimes be null during startup - // and dispose - int result = 0; - IDocument doc = getDocument(); - if (doc != null) { - result = getSafeDocument().getLength(); - } - return result; - } - - private IDocument getClonedDocument() { - if (fDocumentClone == null) { - String content = fOriginalContent == null ? "" : fOriginalContent; //$NON-NLS-1$ - String[] delims = fOriginalLineDelimiters == null ? DefaultLineTracker.DELIMITERS : fOriginalLineDelimiters; - fDocumentClone = new DocumentClone(content, delims); - } - return fDocumentClone; - } - - Display getDisplay() { - - // Note: the workbench should always have a display - // (unless running headless), whereas Display.getCurrent() - // only returns the display if the currently executing thread - // has one. - if (PlatformUI.isWorkbenchRunning()) - return PlatformUI.getWorkbench().getDisplay(); - else - return null; - } - - /** - * Returns the visible document. - * - * @return IDocument - */ - protected IDocument getDocument() { - - if (fChildDocument == null) - return fDocument; - return fChildDocument; - } - - /** - * Returns region in master document of given region (should be region in - * projection document) - * - * @return region if no projection document exists, region of master - * document if possible, null otherwise - */ - private IRegion getProjectionToMasterRegion(IRegion region) { - IRegion originalRegion = region; - if (fChildDocument != null) { - try { - originalRegion = fChildDocument.getProjectionMapping().toOriginRegion(region); - } - catch (BadLocationException e) { - Logger.logException(e); - } - } - - return originalRegion; - } - - /** - * Returns offset in projection document of given offset (should be offset - * in master document) - * - * @return offset if no projection document exists, offset of projection - * document if possible, -1 otherwise - */ - private int getMasterToProjectionOffset(int offset) { - int originalOffset = offset; - if (fChildDocument != null) { - try { - originalOffset = fChildDocument.getProjectionMapping().toImageOffset(offset); - } - catch (BadLocationException e) { - Logger.logException(e); - } - } - - return originalOffset; - } - - /** - * Return the line at the given character offset without delimiters. - * <p> - * - * @param offset - * offset of the line to return. Does not include delimiters of - * preceeding lines. Offset 0 is the first character of the - * document. - * @return the line text without delimiters - */ - public java.lang.String getLine(int lineNumber) { - - String result = null; - if (lineNumber >= getLineCount()) { - if (Debug.displayWarnings) { - System.out.println("Development Debug: IStructuredDocument:getLine() error. lineNumber requested (" + lineNumber + ") was greater than number of lines(" + getLineCount() + "). EmptyString returned"); //$NON-NLS-1$//$NON-NLS-3$//$NON-NLS-2$ - } - result = EMPTY_STRING; - } - else { - IDocument doc = getSafeDocument(); - if (doc == null) { - result = EMPTY_STRING; - } - else { - try { - IRegion r = doc.getLineInformation(lineNumber); - if (r.getLength() > 0) { - result = doc.get(r.getOffset(), r.getLength()); - } - else { - result = EMPTY_STRING; - } - } - catch (BadLocationException e) { - result = EMPTY_STRING; - } - } - } - return result; - } - - /** - * Tries to repair the line information. - * - * @param document - * the document - * @see IRepairableDocument#repairLineInformation() - * @see Eclipse 3.0 - */ - private void repairLineInformation(IDocument document) { - if (document instanceof IRepairableDocument) { - IRepairableDocument repairable = (IRepairableDocument) document; - repairable.repairLineInformation(); - } - } - - /** - * Return the line index at the given character offset. - * <p> - * - * @param offset - * offset of the line to return. The first character of the - * document is at offset 0. An offset of getLength() is valid - * and should answer the number of lines. - * @return the line index. The first line is at index 0. If the character - * at offset is a delimiter character, answer the line index of - * the line that is delimited. For example, text = "\r\n\r\n", - * delimiter = "\r\n", then: getLineAtOffset(0) == 0 - * getLineAtOffset(1) == 0 getLineAtOffset(2) == 1 - * getLineAtOffset(3) == 1 getLineAtOffset(4) == 2 - */ - public int getLineAtOffset(int offset) { - - int result = 0; - IDocument doc = getSafeDocument(); - if (doc != null) { - try { - result = doc.getLineOfOffset(offset); - } - catch (BadLocationException x) { - repairLineInformation(doc); - try { - result = doc.getLineOfOffset(offset); - } - catch (BadLocationException x2) { - // should not occur, but seems to for projection - // documents, related to repainting overview ruler - result = 0; - } - } - } - return result; - } - - public int getLineCount() { - int result = 0; - IDocument doc = getSafeDocument(); - if (doc != null) { - result = doc.getNumberOfLines(); - } - return result; - } - - /* - * @see org.eclipse.swt.custom.StyledTextContent#getLineDelimiter - */ - public String getLineDelimiter() { - String result = null; - if (getParentDocument() instanceof IStructuredDocument) { - result = ((IStructuredDocument) getParentDocument()).getLineDelimiter(); - } - else { - IDocument doc = getSafeDocument(); - result = TextUtilities.getDefaultLineDelimiter(doc); - } - return result; - } - - /** - * Return the character offset of the first character of the given line. - * <p> - * - * @param lineIndex - * index of the line. The first line is at index 0. - * @return offset offset of the first character of the line. The first - * character of the document is at offset 0. The return value - * should include line delimiters. For example, text = - * "\r\ntest\r\n", delimiter = "\r\n", then: getOffsetAtLine(0) == - * 0 getOffsetAtLine(1) == 2 getOffsetAtLine(2) == 8 NOTE: When - * there is no text (i.e., no lines), getOffsetAtLine(0) is a - * valid call that should return 0. - */ - public int getOffsetAtLine(int lineIndex) { - - int result = 0; - IDocument doc = getSafeDocument(); - if (doc != null) { - try { - result = doc.getLineOffset(lineIndex); - } - catch (BadLocationException e) { - result = 0; - } - } - return result; - } - - /** - * Returns the parent document - * - * @return the parent document - */ - private IDocument getParentDocument() { - return fDocument; - } - - /** - * This is the document to use for request from the StyledText widget. Its - * either the live documnet or a clone of it, depending on stop/resume - * state. - */ - private IDocument getSafeDocument() { - IDocument result = null; - if (isStoppedForwardingChanges()) { - result = getClonedDocument(); - } - else { - // note, this document can be normal structured text document, - // or the projection/child document - result = getDocument(); - } - return result; - } - - /** - * @return org.eclipse.swt.custom.StyledText - */ - StyledText getStyledTextWidget() { - return fStyledTextWidget; - } - - /** - * Returns a string representing the content at the given range. - * <p> - * - * @param start - * the start offset of the text to return. Offset 0 is the - * first character of the document. - * @param length - * the length of the text to return - * @return the text at the given range - */ - public String getTextRange(int start, int length) { - String result = null; - try { - IDocument doc = getSafeDocument(); - result = doc.get(start, length); - } - catch (BadLocationException e) { - result = EMPTY_STRING; - } - return result; - } - - /** - * assume only for "no change" events, for now - */ - protected void handlePendingEvents() { - - if (lastEventQueue == null) - return; - - Iterator iterator = lastEventQueue.iterator(); - while (iterator.hasNext()) { - NoChangeEvent noChangeEvent = (NoChangeEvent) iterator.next(); - redrawNoChange(noChangeEvent); - } - - lastEventQueue = null; - lastEvent = null; - } - - boolean isStoppedForwardingChanges() { - return fStopRelayingChangesRequests > 0; - } - - /** - * this method is assumed to be called only for read only region changes. - */ - protected void redrawNoChange(NoChangeEvent structuredDocumentEvent) { - - if (isStoppedForwardingChanges()) - return; - if (Debug.debugStructuredDocument) { - System.out.println("maybe redraw stuff"); //$NON-NLS-1$ - } - - int startOffset = structuredDocumentEvent.getOffset(); - int length = structuredDocumentEvent.getLength(); - redrawRangeWithLength(startOffset, length); - - } - - /** - * Request a redraw of the text range occupied by the given - * StructuredDocumentRegionsReplacedEvent - * - * @param structuredDocumentEvent - */ - protected void redrawNodesReplaced(StructuredDocumentRegionsReplacedEvent structuredDocumentEvent) { - - if (isStoppedForwardingChanges()) - return; - if (Debug.debugStructuredDocument) { - System.out.println("maybe redraw stuff"); //$NON-NLS-1$ - } - // just the new stuff - IStructuredDocumentRegionList newStructuredDocumentRegions = structuredDocumentEvent.getNewStructuredDocumentRegions(); - - int nNewNodes = newStructuredDocumentRegions.getLength(); - if (nNewNodes > 0) { - IStructuredDocumentRegion firstNode = newStructuredDocumentRegions.item(0); - IStructuredDocumentRegion lastNode = newStructuredDocumentRegions.item(nNewNodes - 1); - redrawRange(firstNode.getStartOffset(), lastNode.getEndOffset()); - } - } - - /** - * Redraws the give offsets in terms of the StructuredDocument. If only - * part of the model is visible, ensures that only the visible portion of - * the given range is redrawn. - * - * @param startModelOffset - * @param endModelOffset - */ - private void redrawRange(final int startModelOffset, final int endModelOffset) { - - if (getDocument() == null) - return; - if (Debug.debugStructuredDocument) { - System.out.println("redraw stuff: " + startModelOffset + "-" + endModelOffset); //$NON-NLS-1$ //$NON-NLS-2$ - } - if (fChildDocument == null) { - Runnable runnable = new Runnable() { - public void run() { - getStyledTextWidget().redrawRange(startModelOffset, endModelOffset - startModelOffset, redrawBackground); - } - }; - runOnDisplayThreadIfNeedede(runnable); - - } - else { - int high = getDocument().getLength(); - int startOffset = getMasterToProjectionOffset(startModelOffset); - - int endOffset = getMasterToProjectionOffset(endModelOffset); - - // if offsets were not visible, just try to redraw everything in - // the child document - // // not visible - // if (endOffset < 0 || startOffset > high) - // return; - // restrict lower bound - if (startOffset < 0) { - startOffset = 0; - } - // restrict upper bound - // if (endOffset > high) { - // endOffset = high; - // } - if (endOffset < 0) { - endOffset = high; - } - - int length = endOffset - startOffset; - // redrawBackground with false would be faster - // but assumes background (or font) is not - // changing - final int finalStartOffset = startOffset; - final int finallength = length; - - Runnable runnable = new Runnable() { - public void run() { - getStyledTextWidget().redrawRange(finalStartOffset, finallength, redrawBackground); - } - }; - runOnDisplayThreadIfNeedede(runnable); - - } - } - - /** - * Redraws the give offsets in terms of the Flat Node model. If only part - * of the model is visible, ensures that only the visible portion of the - * given range is redrawn. - * - * @param startModelOffset - * @param endModelOffset - */ - private void redrawRangeWithLength(final int startModelOffset, final int length) { - - if (getDocument() == null) - return; - if (Debug.debugStructuredDocument) { - System.out.println("redraw stuff: " + startModelOffset + "-" + length); //$NON-NLS-1$ //$NON-NLS-2$ - } - if (fChildDocument == null) { - Runnable runnable = new Runnable() { - public void run() { - getStyledTextWidget().redrawRange(startModelOffset, length, redrawBackground); - } - }; - runOnDisplayThreadIfNeedede(runnable); - } - else { - int high = getDocument().getLength(); - // TODO need to take into account segmented visible regions - int startOffset = getMasterToProjectionOffset(startModelOffset); - // not visible - if (startOffset > high || length < 1) - return; - // restrict lower bound - if (startOffset < 0) { - startOffset = 0; - } - int endOffset = startOffset + length - 1; - // restrict upper bound - if (endOffset > high) { - endOffset = high; - } - - // note: length of the child documnet should be - // updated, - // need to investigate why its not at this - // point, but is - // probably just because the document event - // handling is not - // completely finished. - int newLength = endOffset - startOffset; // d283007 - - // redrawBackground with false would be faster - // but assumes background (or font) is not - // changing - final int finalStartOffset = startOffset; - final int finalNewLength = newLength; - Runnable runnable = new Runnable() { - public void run() { - getStyledTextWidget().redrawRange(finalStartOffset, finalNewLength, redrawBackground); - } - }; - runOnDisplayThreadIfNeedede(runnable); - } - } - - /** - * Request a redraw of the text range occupied by the given - * RegionChangedEvent for certain (not all) ITextRegion contexts - * - * @param structuredDocumentEvent - */ - protected void redrawRegionChanged(RegionChangedEvent structuredDocumentEvent) { - - if (isStoppedForwardingChanges()) { - return; - } - if (Debug.debugStructuredDocument) { - System.out.println("maybe redraw stuff"); //$NON-NLS-1$ - } - - - // (nsd) TODO: try to make this reliable somehow - // without being directly content dependent - // if ((region instanceof ITextRegionContainer) || - // (type == XMLJSPRegionContexts.BLOCK_TEXT) || - // (type == XMLJSPRegionContexts.JSP_CONTENT)) { - // IStructuredDocumentRegion flatNode = - // structuredDocumentEvent.getStructuredDocumentRegion(); - // // redraw background of false is faster, - // // but assumes background (or font) is not - // changing - // redrawRange(flatNode.getStartOffset(region), - // flatNode.getEndOffset(region)); - // } - if (forceRedrawOnRegionChanged) { - // workaround for redrawing problems on Linux-GTK - int startOffset = structuredDocumentEvent.getOffset(); - int endOffset = structuredDocumentEvent.getOffset() + structuredDocumentEvent.getLength(); - try { - IRegion startLine = structuredDocumentEvent.fDocument.getLineInformationOfOffset(startOffset); - IRegion endLine = structuredDocumentEvent.fDocument.getLineInformationOfOffset(endOffset); - if (startLine != null && endLine != null) { - redrawRange(startLine.getOffset(), endLine.getOffset() + endLine.getLength()); - } - } - catch (BadLocationException e) { - // nothing for now - } - } - } - - /** - * Request a redraw of the text range occupied by the given - * RegionsReplacedEvent - * - * @param structuredDocumentEvent - */ - protected void redrawRegionsReplaced(RegionsReplacedEvent structuredDocumentEvent) { - - if (isStoppedForwardingChanges()) - return; - if (Debug.debugStructuredDocument) { - System.out.println("maybe redraw stuff"); //$NON-NLS-1$ - } - ITextRegionList newRegions = structuredDocumentEvent.getNewRegions(); - int nRegions = newRegions.size(); - if (nRegions > 0) { - ITextRegion firstRegion = newRegions.get(0); - ITextRegion lastRegion = newRegions.get(nRegions - 1); - IStructuredDocumentRegion flatNode = structuredDocumentEvent.getStructuredDocumentRegion(); - redrawRange(flatNode.getStartOffset(firstRegion), flatNode.getEndOffset(lastRegion)); - } - } - - protected void redrawTextChanged() { - - if (lastEvent != null) { - // update display, since some cases can effect - // highlighting beyond the changed text area. - if (lastEvent instanceof StructuredDocumentRegionsReplacedEvent) - redrawNodesReplaced((StructuredDocumentRegionsReplacedEvent) lastEvent); - if (lastEvent instanceof RegionsReplacedEvent) - redrawRegionsReplaced((RegionsReplacedEvent) lastEvent); - if (lastEvent instanceof RegionChangedEvent) - redrawRegionChanged((RegionChangedEvent) lastEvent); - // moved following line to 'document changed' so - // the "last event" can be - // re-drawn after pending re-draws - // lastEvent = null; - } - } - - /** - * Sends a text replace event to all registered listeners. - */ - protected void relayTextChanged() { - - if (isStoppedForwardingChanges()) { - if (Debug.debugStructuredDocument && getDocument() != null) { - System.out.println("NOT relaying text changed (" + getDocument().getLength() + ")"); //$NON-NLS-1$ //$NON-NLS-2$ - } - return; - } - if (Debug.debugStructuredDocument && getDocument() != null) { - System.out.println("relaying text changed (" + getDocument().getLength() + ")"); //$NON-NLS-1$ //$NON-NLS-2$ - } - final TextChangedEvent textChangedEvent = new TextChangedEvent(this); - - // we must assign listeners to local variable, since - // the add and remove listener - // methods can change the actual instance of the - // listener array from another thread - - Runnable runnable = new Runnable() { - public void run() { - if (fTextChangeListeners != null) { - Object[] holdListeners = fTextChangeListeners; - for (int i = 0; i < holdListeners.length; i++) { - // this is a safe cast, since addListeners - // requires a IStructuredDocumentListener - ((TextChangeListener) holdListeners[i]).textChanged(textChangedEvent); - } - } - } - }; - runOnDisplayThreadIfNeedede(runnable); - redrawTextChanged(); - } - - /** - * Sends a text change to all registered listeners - */ - protected void relayTextChanging(int requestedStart, int requestedLength, String requestedChange) { - - if (getDocument() == null) - return; - if (isStoppedForwardingChanges()) { - if (Debug.debugStructuredDocument && getDocument() != null) { - System.out.println("NOT relaying text changing: " + requestedStart + ":" + getDocument().getLength()); //$NON-NLS-1$ //$NON-NLS-2$ - } - return; - } - if (Debug.debugStructuredDocument && getDocument() != null) { - System.out.println("relaying text changing: " + requestedStart + ":" + getDocument().getLength()); //$NON-NLS-1$ //$NON-NLS-2$ - } - lastEvent = null; - try { - final TextChangingEvent textChangingEvent = new TextChangingEvent(this); - - textChangingEvent.start = requestedStart; - textChangingEvent.replaceCharCount = requestedLength; - textChangingEvent.newCharCount = (requestedChange == null ? 0 : requestedChange.length()); - textChangingEvent.replaceLineCount = getDocument().getNumberOfLines(requestedStart, requestedLength) - 1; - textChangingEvent.newText = requestedChange; - textChangingEvent.newLineCount = (requestedChange == null ? 0 : getDocument().computeNumberOfLines(requestedChange)); - - // we must assign listeners to local variable, - // since the add and remove listner - // methods can change the actual instance of the - // listener array from another thread - Runnable runnable = new Runnable() { - public void run() { - if (fTextChangeListeners != null) { - TextChangeListener[] holdListeners = fTextChangeListeners; - for (int i = 0; i < holdListeners.length; i++) { - // this is a safe cast, since - // addListeners requires a - // IStructuredDocumentListener - holdListeners[i].textChanging(textChangingEvent); - } - } - } - }; - runOnDisplayThreadIfNeedede(runnable); - } - catch (BadLocationException e) { - // log for now, unless we find reason not to - Logger.log(Logger.INFO, e.getMessage()); - } - } - - /** - * Sends a text set event to all registered listeners. Widget should - * redraw itself automatically. - */ - protected void relayTextSet() { - - if (isStoppedForwardingChanges()) { - if (Debug.debugStructuredDocument && getDocument() != null) { - System.out.println("NOT relaying text set (" + getDocument().getLength() + ")"); //$NON-NLS-1$ //$NON-NLS-2$ - } - return; - } - if (Debug.debugStructuredDocument && getDocument() != null) { - System.out.println("relaying text set (" + getDocument().getLength() + ")"); //$NON-NLS-1$ //$NON-NLS-2$ - } - lastEvent = null; - final TextChangedEvent textChangedEvent = new TextChangedEvent(this); - - // we must assign listeners to local variable, since - // the add and remove listner - // methods can change the actual instance of the - // listener array from another thread - Runnable runnable = new Runnable() { - public void run() { - if (fTextChangeListeners != null) { - TextChangeListener[] holdListeners = fTextChangeListeners; - for (int i = 0; i < holdListeners.length; i++) { - holdListeners[i].textSet(textChangedEvent); - } - } - } - }; - runOnDisplayThreadIfNeedede(runnable); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.swt.custom.StyledTextContent#removeTextChangeListener(org.eclipse.swt.custom.TextChangeListener) - */ - public synchronized void removeTextChangeListener(final TextChangeListener listener) { - - if ((fTextChangeListeners != null) && (listener != null)) { - // if its not in the listeners, we'll ignore the - // request - if (!Utilities.contains(fTextChangeListeners, listener)) { - if (Debug.displayWarnings) { - System.out.println("StructuredDocumentToTextAdapter::removeTextChangedListeners. listener " + listener + " was not present. "); //$NON-NLS-2$//$NON-NLS-1$ - } - } - else { - if (Debug.debugStructuredDocument) { - System.out.println("StructuredDocumentToTextAdapter::addTextChangedListeners. Removing an instance of " + listener.getClass() + " as a listener on text adapter."); //$NON-NLS-2$//$NON-NLS-1$ - } - final int oldSize = fTextChangeListeners.length; - int newSize = oldSize - 1; - final TextChangeListener[] newListeners = new TextChangeListener[newSize]; - - Runnable runnable = new Runnable() { - public void run() { - int index = 0; - for (int i = 0; i < oldSize; i++) { - if (fTextChangeListeners[i] != listener) { - // copy old to new if its not the - // one we are removing - newListeners[index++] = fTextChangeListeners[i]; - } - } - } - }; - runOnDisplayThreadIfNeedede(runnable); - // now that we have a new array, let's - // switch it for the old one - fTextChangeListeners = newListeners; - } - } - } - - /** - * Replace the text with "newText" starting at position "start" for a - * length of "replaceLength". - * <p> - * Implementors have to notify TextChanged listeners after the content has - * been updated. The TextChangedEvent should be set as follows: - * <ul> - * <li>event.type = SWT.TextReplaced - * <li>event.start = start of the replaced text - * <li>event.numReplacedLines = number of replaced lines - * <li>event.numNewLines = number of new lines - * <li>event.replacedLength = length of the replaced text - * <li>event.newLength = length of the new text - * </ul> - * <b>NOTE: </b> numNewLines is the number of inserted lines and - * numReplacedLines is the number of deleted lines based on the change - * that occurs visually. For example: - * <ul> - * <li>(replacedText, newText) ==> (numReplacedLines, numNewLines) - * <li>("", "\n") ==> (0, 1) - * <li>("\n\n", "a") ==> (2, 0) - * <li>("a", "\n\n") ==> (0, 2) - * <li>("\n", "") ==> (1, 0) - * </ul> - * </p> - * - * @param start - * start offset of text to replace, none of the offsets include - * delimiters of preceeding lines, offset 0 is the first - * character of the document - * @param replaceLength - * start offset of text to replace - * @param newText - * start offset of text to replace - */ - public void replaceTextRange(int start, int replaceLength, String text) { - - if (getParentDocument() instanceof IStructuredDocument) { - // the structuredDocument initiates the "changing" - // and "changed" events. - // they are both fired by the time this method - // returns. - IRegion region = getProjectionToMasterRegion(new Region(start, replaceLength)); - if (region != null) { - ((IStructuredDocument) getParentDocument()).replaceText(this, region.getOffset(), region.getLength(), text); - return; - } - } - // default is to just try and replace text range in current document - try { - getDocument().replace(start, replaceLength, text); - } - catch (BadLocationException e) { - // log for now, unless we find reason not to - Logger.log(Logger.INFO, e.getMessage()); - } - } - - /** - * @see org.eclipse.jface.text.IDocumentAdapterExtension#resumeForwardingDocumentChanges() - */ - public void resumeForwardingDocumentChanges() { - - // from re-reading the textSet API in StyledText, we - // must call - // textSet if all the contents changed. If all the - // contents did - // not change, we need to call the pair of APIs, - // textChanging and - // textChanged. So, if we ever keep careful track of - // changes - // during stop forwarding and resume forwarding, we - // can - // investigate change make use of the pair of APIs. - fStopRelayingChangesRequests--; - if (fStopRelayingChangesRequests == 0) { - // fIsForwarding= true; - fDocumentClone = null; - fOriginalContent = null; - fOriginalLineDelimiters = null; - // fireTextSet(); - relayTextSet(); - } - } - - /** - * This 'Runnable' should be very brief, and should not "call out" to - * other code which itself might call syncExec, or deadlock might occur. - * - * @param r - */ - private void runOnDisplayThreadIfNeedede(Runnable r) { - // if there is no Display at all (that is, running headless), - // or if we are already running on the display thread, then - // simply execute the runnable. - if (getDisplay() == null || (Thread.currentThread() == getDisplay().getThread())) { - r.run(); - } - else { - // otherwise force the runnable to run on the display thread. - // - // Its unclear if we need this at all, once - // we "force" document update to always take place on display - // thread. - IDocument doc = getDocument(); - if (doc instanceof ILockable) { - - ILock lock = null; - try { - lock = ((ILockable) doc).getLockObject(); - lock.acquire(); - getDisplay().syncExec(r); - } - finally { - if (lock != null) { - lock.release(); - } - } - } - else { - // else, ignore!, since risk of deadlock - throw new IllegalStateException("non lockable document used for structuredDocumentToTextAdapter"); //$NON-NLS-1$ - } - } - } - - /** - * @param newModel - */ - public void setDocument(IDocument document) { - - if (getDocument() != null) { - getDocument().removePrenotifiedDocumentListener(internalDocumentListener); - } - lastEvent = null; - if (document instanceof ProjectionDocument) { - fChildDocument = (ProjectionDocument) document; - _setDocument(fChildDocument.getMasterDocument()); - } - else { - fChildDocument = null; - _setDocument(document); - } - if (getDocument() != null) { - getDocument().addPrenotifiedDocumentListener(internalDocumentListener); - } - } - - /** - * @see IDocument#setText - */ - public void setText(String string) { - - if (isStoppedForwardingChanges()) { - fDocumentClone = null; - fOriginalContent = getDocument().get(); - fOriginalLineDelimiters = getDocument().getLegalLineDelimiters(); - } - else if (getParentDocument() instanceof IStructuredDocument) { - ((IStructuredDocument) getDocument()).setText(this, string); - } - else { - getDocument().set(string); - } - relayTextSet(); - } - - /** - * This method was added to make testing easier. Normally, the widget is - * specified on the constructor. - */ - public void setWidget(StyledText widget) { - - fStyledTextWidget = widget; - } - - /** - * @see org.eclipse.jface.text.IDocumentAdapterExtension#stopForwardingDocumentChanges() - */ - public void stopForwardingDocumentChanges() { - - fStopRelayingChangesRequests++; - // only need to take snapshot on first request - if (fStopRelayingChangesRequests == 1) { - fDocumentClone = null; - fOriginalContent = getDocument().get(); - fOriginalLineDelimiters = getDocument().getLegalLineDelimiters(); - } - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/StructuredLineChangeHover.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/StructuredLineChangeHover.java deleted file mode 100644 index 69d5d280e1..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/StructuredLineChangeHover.java +++ /dev/null @@ -1,48 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal; - -import org.eclipse.jface.text.DefaultInformationControl; -import org.eclipse.jface.text.IInformationControl; -import org.eclipse.jface.text.IInformationControlCreator; -import org.eclipse.jface.text.source.LineChangeHover; -import org.eclipse.swt.widgets.Shell; - -/** - * Escapes diff hover presentation text (converts < to < > to > etc...) - * so that html in the diff file (displayed in hover) isn't presented as style - * (bold, italic, colors, etc...) - * - * @deprecated - */ -public class StructuredLineChangeHover extends LineChangeHover { - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.text.source.IAnnotationHoverExtension#getHoverControlCreator() - */ - public IInformationControlCreator getHoverControlCreator() { - // use the default information control creator that just displays text - // as text, not html content - // because there is no special html that should be presented when just - // showing diff - // in the future, sourceviewer should be used instead of this plain - // text control like java uses - // SourceViewerInformationControl - return new IInformationControlCreator() { - public IInformationControl createInformationControl(Shell parent) { - return new DefaultInformationControl(parent); - } - }; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/StructuredMarkerAnnotation.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/StructuredMarkerAnnotation.java deleted file mode 100644 index 2a725b5e7e..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/StructuredMarkerAnnotation.java +++ /dev/null @@ -1,129 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal; - - -import org.eclipse.core.resources.IMarker; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.jface.resource.JFaceResources; -import org.eclipse.jface.text.source.IAnnotationPresentation; -import org.eclipse.swt.SWT; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.widgets.Display; -import org.eclipse.ui.ISharedImages; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.texteditor.MarkerAnnotation; -import org.eclipse.wst.sse.ui.internal.reconcile.TemporaryAnnotation; - - -/** - * This is overridden to get around the problem of being registered as a - * org.eclipse.wst.validation.core.problemmarker rather than a - * org.eclipse.core.resource.problemmarker causing all problems to be skipped - * in the OverviewRuler - */ -public class StructuredMarkerAnnotation extends MarkerAnnotation implements IAnnotationPresentation { - // controls if icon should be painted gray - private boolean fIsGrayed = false; - String fAnnotationType = null; - - StructuredMarkerAnnotation(IMarker marker) { - super(marker); - } - - public final String getAnnotationType() { - if (fAnnotationType==null){ - initAnnotationType(); - } - return fAnnotationType; - } - - /** - * Eventually will have to use IAnnotationPresentation & - * IAnnotationExtension - * - * @see org.eclipse.ui.texteditor.MarkerAnnotation#getImage(org.eclipse.swt.widgets.Display) - */ - protected Image getImage(Display display) { - Image image = null; - String annotationType = getAnnotationType(); - if (annotationType == TemporaryAnnotation.ANNOT_ERROR) { - image = PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJS_ERROR_TSK); - } - else if (annotationType == TemporaryAnnotation.ANNOT_WARNING) { - image = PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJS_WARN_TSK); - } - else if (annotationType == TemporaryAnnotation.ANNOT_INFO) { - image = PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJS_INFO_TSK); - } - - if (image != null && isGrayed()) - setImage(getGrayImage(display, image)); - else - setImage(image); - - return super.getImage(display); - } - - private Image getGrayImage(Display display, Image image) { - if (image != null) { - String key = Integer.toString(image.hashCode()); - // make sure we cache the gray image - Image grayImage = JFaceResources.getImageRegistry().get(key); - if (grayImage == null) { - grayImage = new Image(display, image, SWT.IMAGE_GRAY); - JFaceResources.getImageRegistry().put(key, grayImage); - } - image = grayImage; - } - return image; - } - - public final boolean isGrayed() { - return fIsGrayed; - } - - public final void setGrayed(boolean grayed) { - fIsGrayed = grayed; - } - - /** - * Initializes the annotation's icon representation and its drawing layer - * based upon the properties of the underlying marker. - */ - protected void initAnnotationType() { - - IMarker marker = getMarker(); - fAnnotationType = TemporaryAnnotation.ANNOT_UNKNOWN; - try { - if (marker.exists() && marker.isSubtypeOf(IMarker.PROBLEM)) { - int severity = marker.getAttribute(IMarker.SEVERITY, -1); - switch (severity) { - case IMarker.SEVERITY_ERROR : - fAnnotationType = TemporaryAnnotation.ANNOT_ERROR; - break; - case IMarker.SEVERITY_WARNING : - fAnnotationType = TemporaryAnnotation.ANNOT_WARNING; - break; - case IMarker.SEVERITY_INFO : - fAnnotationType = TemporaryAnnotation.ANNOT_INFO; - break; - } - } - - } - catch (CoreException e) { - Logger.logException(e); - } - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/StructuredResourceMarkerAnnotationModel.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/StructuredResourceMarkerAnnotationModel.java deleted file mode 100644 index 73d6babd46..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/StructuredResourceMarkerAnnotationModel.java +++ /dev/null @@ -1,118 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2007 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal; - -import org.eclipse.core.resources.IMarker; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.jface.text.Position; -import org.eclipse.ui.texteditor.MarkerAnnotation; -import org.eclipse.ui.texteditor.MarkerUtilities; -import org.eclipse.ui.texteditor.ResourceMarkerAnnotationModel; -import org.eclipse.wst.sse.ui.internal.provisional.extensions.breakpoint.IBreakpointConstants; - - -/** - * Source editor resource marker annotation model implementation - */ -public class StructuredResourceMarkerAnnotationModel extends ResourceMarkerAnnotationModel { - /** - * Loading of markers when working with non-IResources is accomplished by - * adding the markers to the workspace root with an additional key, whose - * value uses '/' for segment separators when representing paths, - * determining whether they're added into the annotation model. - * - * Setters of this attribute should use '/'for segment separators when - * representing paths. - */ - public final static String SECONDARY_ID_KEY = IBreakpointConstants.RESOURCE_PATH; - - protected IResource fMarkerResource; - protected String fSecondaryMarkerAttributeValue; - - /** - * Constructor - * - * @param resource - */ - public StructuredResourceMarkerAnnotationModel(IResource resource) { - super(resource); - fMarkerResource = resource; - } - - public StructuredResourceMarkerAnnotationModel(IResource resource, String secondaryID) { - super(resource); - fMarkerResource = resource; - fSecondaryMarkerAttributeValue = secondaryID; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.AbstractMarkerAnnotationModel#createMarkerAnnotation(org.eclipse.core.resources.IMarker) - */ - protected MarkerAnnotation createMarkerAnnotation(IMarker marker) { - /* - * We need to do some special processing if marker is a validation - * (aka problem) marker or if marker is a breakpoint marker so create - * a special marker annotation for those markers. Otherwise, use - * default. - */ - if (MarkerUtilities.isMarkerType(marker, IMarker.PROBLEM)) { - return new StructuredMarkerAnnotation(marker); - } - return super.createMarkerAnnotation(marker); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.AbstractMarkerAnnotationModel#getMarkerPosition(org.eclipse.core.resources.IMarker) - */ - public Position getMarkerPosition(IMarker marker) { - Position pos = super.getMarkerPosition(marker); - - // if ((pos == null || pos.getLength() == 0) && marker.getType() == - // IInternalDebugUIConstants.ANN_INSTR_POINTER_CURRENT) { - if (pos == null || pos.getLength() == 0) { - // We probably should create position from marker if marker - // attributes specify a valid position - pos = createPositionFromMarker(marker); - } - - return pos; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.AbstractMarkerAnnotationModel#isAcceptable(org.eclipse.core.resources.IMarker) - */ - protected boolean isAcceptable(IMarker marker) { - try { - Object attr = marker.getAttribute(IBreakpointConstants.ATTR_HIDDEN); - if (attr != null && Boolean.TRUE.equals(attr)) - return false; - } - catch (CoreException e) { - // ignore - } - - if (fSecondaryMarkerAttributeValue == null) - return super.isAcceptable(marker); - String markerSecondaryMarkerAttributeValue = marker.getAttribute(SECONDARY_ID_KEY, ""); //$NON-NLS-1$ - boolean isSameFile = fSecondaryMarkerAttributeValue.equalsIgnoreCase(markerSecondaryMarkerAttributeValue); - return super.isAcceptable(marker) && isSameFile; - } - -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/StructuredResourceMarkerAnnotationModelFactory.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/StructuredResourceMarkerAnnotationModelFactory.java deleted file mode 100644 index 6e5b235d84..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/StructuredResourceMarkerAnnotationModelFactory.java +++ /dev/null @@ -1,49 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal; - -import org.eclipse.core.filebuffers.FileBuffers; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.IPath; -import org.eclipse.jface.text.source.IAnnotationModel; -import org.eclipse.ui.texteditor.ResourceMarkerAnnotationModelFactory; - -/** - * - * @author nsd - * - * Used by the org.eclipse.core.filebuffers.annotationModelCreation extension - * point - */ -public class StructuredResourceMarkerAnnotationModelFactory extends ResourceMarkerAnnotationModelFactory { - - public StructuredResourceMarkerAnnotationModelFactory() { - super(); - } - - /* - * @see org.eclipse.core.filebuffers.IAnnotationModelFactory#createAnnotationModel(org.eclipse.core.runtime.IPath) - */ - public IAnnotationModel createAnnotationModel(IPath location) { - IAnnotationModel model = null; - IFile file = FileBuffers.getWorkspaceFileAtLocation(location); - if (file != null) { - model = new StructuredResourceMarkerAnnotationModel(file); - } - else { - model = new StructuredResourceMarkerAnnotationModel(ResourcesPlugin.getWorkspace().getRoot(), location.toString()); - } - return model; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/StructuredTextAnnotationHover.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/StructuredTextAnnotationHover.java deleted file mode 100644 index 624a3f7d36..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/StructuredTextAnnotationHover.java +++ /dev/null @@ -1,81 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal; - -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import org.eclipse.jface.internal.text.html.HTMLPrinter; -import org.eclipse.jface.text.source.DefaultAnnotationHover; - -/** - * Determines all messages for the given line and collects, concatenates, and - * formats them in HTML. Use of the internal HTMLPrinter was observed in - * org.eclipse.jdt.internal.ui.text.HTMLAnnotationHover . - */ -public class StructuredTextAnnotationHover extends DefaultAnnotationHover { - - public StructuredTextAnnotationHover() { - super(); - } - - public StructuredTextAnnotationHover(boolean showLineNumber) { - super(showLineNumber); - } - - /* - * Formats a message as HTML text. - */ - protected String formatSingleMessage(String message) { - StringBuffer buffer = new StringBuffer(); - HTMLPrinter.addPageProlog(buffer); - HTMLPrinter.addParagraph(buffer, HTMLPrinter.convertToHTMLContent(message)); - HTMLPrinter.addPageEpilog(buffer); - return buffer.toString(); - } - - /* - * Formats several message as HTML text. - */ - protected String formatMultipleMessages(List messages) { - StringBuffer buffer = new StringBuffer(); - HTMLPrinter.addPageProlog(buffer); - HTMLPrinter.addParagraph(buffer, HTMLPrinter.convertToHTMLContent(SSEUIMessages.Multiple_errors)); - - HTMLPrinter.startBulletList(buffer); - Set collectedMessages = new HashSet(); - Iterator e = messages.iterator(); - while (e.hasNext()) { - String converted = HTMLPrinter.convertToHTMLContent((String) e.next()); - collectedMessages.add(converted); - } - e = collectedMessages.iterator(); - while (e.hasNext()) { - HTMLPrinter.addBullet(buffer, e.next().toString()); - } - HTMLPrinter.endBulletList(buffer); - - HTMLPrinter.addPageEpilog(buffer); - return buffer.toString(); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.sse.ui.IReleasable#release() - */ - public void release() { - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/StructuredTextLineBreakingReader.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/StructuredTextLineBreakingReader.java deleted file mode 100644 index 7fe3debf01..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/StructuredTextLineBreakingReader.java +++ /dev/null @@ -1,114 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal; - - - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.Reader; - -import org.eclipse.swt.graphics.GC; - -/* - * Not a real reader. Could change if requested - */ -public class StructuredTextLineBreakingReader { - private GC fGC; - private int fIndex; - private String fLine; - private int fMaxWidth; - - private BufferedReader fReader; - - /** - * Creates a reader that breaks an input text to fit in a given width. - * - * @param reader - * Reader of the input text - * @param gc - * The graphic context that defines the currently used font - * sizes - * @param maxLineWidth - * The max width (pixes) where the text has to fit in - */ - public StructuredTextLineBreakingReader(Reader reader, GC gc, int maxLineWidth) { - fReader = new BufferedReader(reader); - fGC = gc; - fMaxWidth = maxLineWidth; - fLine = null; - fIndex = 0; - } - - private int findNextBreakIndex(int currIndex) { - int currWidth = 0; - int lineLength = fLine.length(); - - while (currIndex < lineLength) { - char ch = fLine.charAt(currIndex); - int nextIndex = currIndex + 1; - // leading whitespaces are counted to the following word - if (Character.isWhitespace(ch)) { - while (nextIndex < lineLength && Character.isWhitespace(fLine.charAt(nextIndex))) { - nextIndex++; - } - } - while (nextIndex < lineLength && !Character.isWhitespace(fLine.charAt(nextIndex))) { - nextIndex++; - } - String word = fLine.substring(currIndex, nextIndex); - int wordWidth = fGC.textExtent(word).x; - int nextWidth = wordWidth + currWidth; - if (nextWidth > fMaxWidth && wordWidth < fMaxWidth) { - return currIndex; - } - currWidth = nextWidth; - currIndex = nextIndex; - } - return currIndex; - } - - private int findWordBegin(int idx) { - while (idx < fLine.length() && Character.isWhitespace(fLine.charAt(idx))) { - idx++; - } - return idx; - } - - /** - * Reads the next line. The lengths of the line will not exceed the gived - * maximum width. - */ - public String readLine() throws IOException { - if (fLine == null) { - String line = fReader.readLine(); - if (line == null) { - return null; - } - int lineLen = fGC.textExtent(line).x; - if (lineLen < fMaxWidth) { - return line; - } - fLine = line; - fIndex = 0; - } - int breakIdx = findNextBreakIndex(fIndex); - String res = fLine.substring(fIndex, breakIdx); - if (breakIdx < fLine.length()) { - fIndex = findWordBegin(breakIdx); - } else { - fLine = null; - } - return res; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/StructuredTextSelectionChangedEvent.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/StructuredTextSelectionChangedEvent.java deleted file mode 100644 index bb8dc2d953..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/StructuredTextSelectionChangedEvent.java +++ /dev/null @@ -1,35 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal; - - - -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.ISelectionProvider; - -/** - * This event is used by the SourceEditorTreeViewer to tell the - * ViewerSelectionManager that the selection really came from a user click on - * the content outliner, instead of being set programatically. - */ -public class StructuredTextSelectionChangedEvent extends org.eclipse.jface.viewers.SelectionChangedEvent { - - /** - * Comment for <code>serialVersionUID</code> - */ - private static final long serialVersionUID = 1L; - - public StructuredTextSelectionChangedEvent(ISelectionProvider source, ISelection selection) { - super(source, selection); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/StructuredTextViewer.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/StructuredTextViewer.java deleted file mode 100644 index 73150612b7..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/StructuredTextViewer.java +++ /dev/null @@ -1,971 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal; - -import java.util.ArrayList; - -import org.eclipse.core.runtime.Assert; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.DocumentRewriteSession; -import org.eclipse.jface.text.DocumentRewriteSessionType; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IDocumentAdapter; -import org.eclipse.jface.text.IDocumentExtension4; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ITextPresentationListener; -import org.eclipse.jface.text.ITextSelection; -import org.eclipse.jface.text.ITextViewerExtension2; -import org.eclipse.jface.text.Region; -import org.eclipse.jface.text.TextSelection; -import org.eclipse.jface.text.contentassist.IContentAssistant; -import org.eclipse.jface.text.contentassist.IContentAssistantExtension2; -import org.eclipse.jface.text.contentassist.IContentAssistantExtension4; -import org.eclipse.jface.text.formatter.FormattingContext; -import org.eclipse.jface.text.formatter.FormattingContextProperties; -import org.eclipse.jface.text.formatter.IContentFormatterExtension; -import org.eclipse.jface.text.formatter.IFormattingContext; -import org.eclipse.jface.text.hyperlink.IHyperlinkDetector; -import org.eclipse.jface.text.information.IInformationPresenter; -import org.eclipse.jface.text.projection.ProjectionDocument; -import org.eclipse.jface.text.quickassist.IQuickAssistAssistant; -import org.eclipse.jface.text.reconciler.IReconciler; -import org.eclipse.jface.text.source.ContentAssistantFacade; -import org.eclipse.jface.text.source.IAnnotationModel; -import org.eclipse.jface.text.source.IOverviewRuler; -import org.eclipse.jface.text.source.IVerticalRuler; -import org.eclipse.jface.text.source.SourceViewerConfiguration; -import org.eclipse.jface.text.source.projection.ProjectionViewer; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.VerifyEvent; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.wst.sse.core.internal.cleanup.StructuredContentCleanupHandler; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument; -import org.eclipse.wst.sse.core.internal.undo.IDocumentSelectionMediator; -import org.eclipse.wst.sse.core.internal.undo.IStructuredTextUndoManager; -import org.eclipse.wst.sse.core.internal.undo.UndoDocumentEvent; -import org.eclipse.wst.sse.ui.StructuredTextViewerConfiguration; -import org.eclipse.wst.sse.ui.internal.provisional.style.AbstractLineStyleProvider; -import org.eclipse.wst.sse.ui.internal.provisional.style.CompatibleHighlighter; -import org.eclipse.wst.sse.ui.internal.provisional.style.Highlighter; -import org.eclipse.wst.sse.ui.internal.provisional.style.LineStyleProvider; -import org.eclipse.wst.sse.ui.internal.provisional.style.ReconcilerHighlighter; -import org.eclipse.wst.sse.ui.internal.reconcile.StructuredRegionProcessor; -import org.eclipse.wst.sse.ui.internal.util.PlatformStatusLineUtil; - -/** - * <p> - * Like {@link org.eclipse.wst.sse.ui.StructuredTextEditor}, this class is not - * meant to be subclassed.<br /> - */ -public class StructuredTextViewer extends ProjectionViewer implements IDocumentSelectionMediator { - /** Text operation codes */ - private static final int BASE = ProjectionViewer.COLLAPSE_ALL; // see - // ProjectionViewer.COLLAPSE_ALL - private static final int CLEANUP_DOCUMENT = BASE + 4; - public static final int FORMAT_ACTIVE_ELEMENTS = BASE + 3; - - private static final String FORMAT_ACTIVE_ELEMENTS_TEXT = SSEUIMessages.Format_Active_Elements_UI_; //$NON-NLS-1$ - public static final int FORMAT_DOCUMENT = BASE + 2; - private static final String FORMAT_DOCUMENT_TEXT = SSEUIMessages.Format_Document_UI_; //$NON-NLS-1$ - private static final String TEXT_CUT = SSEUIMessages.Text_Cut_UI_; //$NON-NLS-1$ - private static final String TEXT_PASTE = SSEUIMessages.Text_Paste_UI_; //$NON-NLS-1$ - private static final String TEXT_SHIFT_LEFT = SSEUIMessages.Text_Shift_Left_UI_; //$NON-NLS-1$ = "Text Shift Left" - private static final String TEXT_SHIFT_RIGHT = SSEUIMessages.Text_Shift_Right_UI_; //$NON-NLS-1$ = "Text Shift Right" - private static final boolean TRACE_EXCEPTIONS = true; - - /* - * Max length of chars to format before it is considered a "big format" - * This is used to indication a small unrestricted rewrite session. - */ - private final int MAX_SMALL_FORMAT_LENGTH = 1000; - private boolean fBackgroundupdateInProgress; - private StructuredContentCleanupHandler fContentCleanupHandler = null; - //private IDocumentAdapter fDocAdapter; - - private Highlighter fHighlighter; - - private ReconcilerHighlighter fRecHighlighter = null; - - // private ViewerSelectionManager fViewerSelectionManager; - private SourceViewerConfiguration fConfiguration; - /* - * True if formatter has been set - */ - private boolean fFormatterSet = false; - - private ContentAssistantFacade fContentAssistantFacade; - - /** - * @see org.eclipse.jface.text.source.SourceViewer#SourceViewer(Composite, - * IVerticalRuler, IOverviewRuler, boolean, int) - */ - public StructuredTextViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, boolean showAnnotationsOverview, int styles) { - super(parent, verticalRuler, overviewRuler, showAnnotationsOverview, styles); - } - - /** - * - */ - private void beep() { - getTextWidget().getDisplay().beep(); - } - - public void beginBackgroundUpdate() { - fBackgroundupdateInProgress = true; - setRedraw(false); - } - - protected void createControl(Composite parent, int styles) { - // Forces LEFT_TO_RIGHT orientation unless otherwise suggested - if ((styles & SWT.LEFT_TO_RIGHT) == 0 && (styles & SWT.RIGHT_TO_LEFT) == 0) - styles |= SWT.LEFT_TO_RIGHT; - super.createControl(parent, styles); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.text.ITextOperationTarget#canDoOperation(int) - */ - public boolean canDoOperation(int operation) { - if (fBackgroundupdateInProgress) { - return false; - } - switch (operation) { - case CONTENTASSIST_PROPOSALS : { - // (pa) if position isn't READ_ONLY (containsReadOnly() - // returns false), - // Otherwise, you DO want content assist (return true) - IDocument doc = getDocument(); - if (doc != null && doc instanceof IStructuredDocument) { - return isEditable() && (!((IStructuredDocument) doc).containsReadOnly(getSelectedRange().x, 0)); - } - break; - } - case CLEANUP_DOCUMENT : { - return (fContentCleanupHandler != null && isEditable()); - } - case FORMAT_DOCUMENT : - case FORMAT_ACTIVE_ELEMENTS : { - // if formatter not set yet, contentformatter can be null - return ((fContentFormatter != null || !fFormatterSet) && isEditable()); - } - } - return super.canDoOperation(operation); - } - - /** - * Should be identical to superclass version. Plus, we get our own special - * Highlighter. Plus we uninstall before installing. - */ - public void configure(SourceViewerConfiguration configuration) { - - if (getTextWidget() == null) - return; - - setDocumentPartitioning(configuration.getConfiguredDocumentPartitioning(this)); - - // always uninstall highlighter and null it out on new configuration - if (fHighlighter != null) { - fHighlighter.uninstall(); - fHighlighter = null; - } - - if(fRecHighlighter != null) { - fRecHighlighter.uninstall(); - fRecHighlighter = null; - } - - // Bug 230297 - Uninstall presentation reconciler in preparation of a new one - if(fPresentationReconciler != null) { - fPresentationReconciler.uninstall(); - fPresentationReconciler = null; - } - - IReconciler newReconciler = configuration.getReconciler(this); - - if (newReconciler != fReconciler || newReconciler == null || fReconciler == null) { - - if (fReconciler != null) { - fReconciler.uninstall(); - } - - fReconciler = newReconciler; - - if (fReconciler != null) { - fReconciler.install(this); - // https://w3.opensource.ibm.com/bugzilla/show_bug.cgi?id=3858 - // still need set document on the reconciler (strategies) - if (fReconciler instanceof StructuredRegionProcessor) - ((StructuredRegionProcessor) fReconciler).setDocument(getDocument()); - } - } - - IContentAssistant newAssistant = configuration.getContentAssistant(this); - if (newAssistant != fContentAssistant || newAssistant == null || fContentAssistant == null) { - if (fContentAssistant != null) - fContentAssistant.uninstall(); - - fContentAssistant = newAssistant; - - if (fContentAssistant != null) { - fContentAssistant.install(this); - if (fContentAssistant instanceof IContentAssistantExtension2 && fContentAssistant instanceof IContentAssistantExtension4) - fContentAssistantFacade= new ContentAssistantFacade(fContentAssistant); - fContentAssistantInstalled = true; - } - else { - // 248036 - // disable the content assist operation if no content - // assistant - enableOperation(CONTENTASSIST_PROPOSALS, false); - fContentAssistantInstalled = false; - } - } - - IQuickAssistAssistant quickAssistant = configuration.getQuickAssistAssistant(this); - if (quickAssistant != fQuickAssistAssistant || quickAssistant == null || fQuickAssistAssistant == null) { - if (fQuickAssistAssistant != null) - fQuickAssistAssistant.uninstall(); - - fQuickAssistAssistant = quickAssistant; - - if (fQuickAssistAssistant != null) { - fQuickAssistAssistant.install(this); - fQuickAssistAssistantInstalled = true; - } - else { - // 248036 - // disable the content assist operation if no content - // assistant - enableOperation(QUICK_ASSIST, false); - fQuickAssistAssistantInstalled = false; - } - } - - fContentFormatter = configuration.getContentFormatter(this); - - // do not uninstall old information presenter if it's the same - IInformationPresenter newInformationPresenter = configuration.getInformationPresenter(this); - if (newInformationPresenter == null || fInformationPresenter == null || !(newInformationPresenter.equals(fInformationPresenter))) { - if (fInformationPresenter != null) - fInformationPresenter.uninstall(); - fInformationPresenter = newInformationPresenter; - if (fInformationPresenter != null) - fInformationPresenter.install(this); - } - - // disconnect from the old undo manager before setting the new one - if (fUndoManager != null) { - fUndoManager.disconnect(); - } - setUndoManager(configuration.getUndoManager(this)); - - // release old annotation hover before setting new one - if (fAnnotationHover instanceof StructuredTextAnnotationHover) { - ((StructuredTextAnnotationHover) fAnnotationHover).release(); - } - setAnnotationHover(configuration.getAnnotationHover(this)); - - // release old annotation hover before setting new one - if (fOverviewRulerAnnotationHover instanceof StructuredTextAnnotationHover) { - ((StructuredTextAnnotationHover) fOverviewRulerAnnotationHover).release(); - } - setOverviewRulerAnnotationHover(configuration.getOverviewRulerAnnotationHover(this)); - - getTextWidget().setTabs(configuration.getTabWidth(this)); - setHoverControlCreator(configuration.getInformationControlCreator(this)); - - // if hyperlink manager has already been created, uninstall it - if (fHyperlinkManager != null) { - setHyperlinkDetectors(null, SWT.NONE); - } - setHyperlinkPresenter(configuration.getHyperlinkPresenter(this)); - IHyperlinkDetector[] hyperlinkDetectors = configuration.getHyperlinkDetectors(this); - int eventStateMask = configuration.getHyperlinkStateMask(this); - setHyperlinkDetectors(hyperlinkDetectors, eventStateMask); - - String[] types = configuration.getConfiguredContentTypes(this); - - // clear autoindent/autoedit strategies - fAutoIndentStrategies = null; - - for (int i = 0; i < types.length; i++) { - String t = types[i]; - setAutoEditStrategies(configuration.getAutoEditStrategies(this, t), t); - setTextDoubleClickStrategy(configuration.getDoubleClickStrategy(this, t), t); - - int[] stateMasks = configuration.getConfiguredTextHoverStateMasks(this, t); - if (stateMasks != null) { - for (int j = 0; j < stateMasks.length; j++) { - int stateMask = stateMasks[j]; - setTextHover(configuration.getTextHover(this, t, stateMask), t, stateMask); - } - } - else { - setTextHover(configuration.getTextHover(this, t), t, ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK); - } - - String[] prefixes = configuration.getIndentPrefixes(this, t); - if (prefixes != null && prefixes.length > 0) - setIndentPrefixes(prefixes, t); - - prefixes = configuration.getDefaultPrefixes(this, t); - if (prefixes != null && prefixes.length > 0) - setDefaultPrefixes(prefixes, t); - - // Bug 230297 - Add LineStyleProviders from the new configuration if - // the document is set - if(getDocument() != null) { - // add highlighter/linestyleprovider - LineStyleProvider[] providers = ((StructuredTextViewerConfiguration) configuration).getLineStyleProviders(this, t); - if (providers != null) { - for (int j = 0; j < providers.length; ++j) { - - if(fRecHighlighter == null) { - fRecHighlighter = new ReconcilerHighlighter(); - ((StructuredTextViewerConfiguration) configuration).setHighlighter(fRecHighlighter); - } - if (providers[j] instanceof AbstractLineStyleProvider) { - ((AbstractLineStyleProvider) providers[j]).init((IStructuredDocument) getDocument(), fRecHighlighter); - fRecHighlighter.addProvider(t, providers[j]); - } - else { - // init with compatibility instance - if (fHighlighter == null) { - fHighlighter = new CompatibleHighlighter(); - } - Logger.log(Logger.INFO_DEBUG, "CompatibleHighlighter installing compatibility for " + providers[j].getClass()); //$NON-NLS-1$ - providers[j].init((IStructuredDocument) getDocument(), fHighlighter); - fHighlighter.addProvider(t, providers[j]); - } - } - } - } - } - - // initialize highlighter after linestyleproviders were added - if (fHighlighter != null) { - fHighlighter.setDocumentPartitioning(configuration.getConfiguredDocumentPartitioning(this)); - fHighlighter.setDocument((IStructuredDocument) getDocument()); - fHighlighter.install(this); - } - - if (fRecHighlighter != null) - fRecHighlighter.install(this); - - activatePlugins(); - - fConfiguration = configuration; - - // Update the viewer's presentation reconciler - fPresentationReconciler = configuration.getPresentationReconciler(this); - - if(fPresentationReconciler != null) - fPresentationReconciler.install(this); - } - - /** - * @param document - * @param startOffset - * @param endOffset - * @return - */ - private boolean containsReadOnly(IDocument document, int startOffset, int endOffset) { - - int start = startOffset; - int end = endOffset; - IStructuredDocument structuredDocument = null; - if (document instanceof IStructuredDocument) { - structuredDocument = (IStructuredDocument) document; - } - else { - if (document instanceof ProjectionDocument) { - IDocument doc = ((ProjectionDocument) document).getMasterDocument(); - if (doc instanceof IStructuredDocument) { - structuredDocument = (IStructuredDocument) doc; - int adjust = ((ProjectionDocument) document).getProjectionMapping().getCoverage().getOffset(); - start = adjust + start; - end = adjust + end; - } - } - } - if (structuredDocument == null) { - return false; - } - else { - int length = end - start; - return structuredDocument.containsReadOnly(start, length); - } - } - - /** - * @deprecated - present for compatibility only - */ - protected IDocumentAdapter createDocumentAdapter() { - return super.createDocumentAdapter(); - } - - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.text.ITextOperationTarget#doOperation(int) - */ - public void doOperation(int operation) { - - Point selection = getTextWidget().getSelection(); - int cursorPosition = selection.x; - int selectionLength = selection.y - selection.x; - switch (operation) { - case CUT : - beginRecording(TEXT_CUT, TEXT_CUT, cursorPosition, selectionLength); - super.doOperation(operation); - selection = getTextWidget().getSelection(); - cursorPosition = selection.x; - selectionLength = selection.y - selection.x; - endRecording(cursorPosition, selectionLength); - break; - case PASTE : - beginRecording(TEXT_PASTE, TEXT_PASTE, cursorPosition, selectionLength); - super.doOperation(operation); - selection = getTextWidget().getSelection(); - cursorPosition = selection.x; - selectionLength = selection.y - selection.x; - endRecording(cursorPosition, selectionLength); - break; - case CONTENTASSIST_PROPOSALS : - // maybe not configured? - if (fContentAssistant != null && isEditable()) { - // CMVC 263269 - // need an explicit check here because the - // contentAssistAction is no longer being updated on - // cursor - // position - if (canDoOperation(CONTENTASSIST_PROPOSALS)) { - String err = fContentAssistant.showPossibleCompletions(); - if (err != null) { - // don't wanna beep if there is no error - PlatformStatusLineUtil.displayTemporaryErrorMessage(this, err); - } - } - else - beep(); - } - break; - case CONTENTASSIST_CONTEXT_INFORMATION : - if (fContentAssistant != null) { - String err = fContentAssistant.showContextInformation(); - if (err != null) { - // don't wanna beep if there is no error - PlatformStatusLineUtil.displayTemporaryErrorMessage(this, err); - } - } - break; - case SHIFT_RIGHT : - beginRecording(TEXT_SHIFT_RIGHT, TEXT_SHIFT_RIGHT, cursorPosition, selectionLength); - updateIndentationPrefixes(); - super.doOperation(SHIFT_RIGHT); - selection = getTextWidget().getSelection(); - cursorPosition = selection.x; - selectionLength = selection.y - selection.x; - endRecording(cursorPosition, selectionLength); - break; - case SHIFT_LEFT : - beginRecording(TEXT_SHIFT_LEFT, TEXT_SHIFT_LEFT, cursorPosition, selectionLength); - updateIndentationPrefixes(); - super.doOperation(SHIFT_LEFT); - selection = getTextWidget().getSelection(); - cursorPosition = selection.x; - selectionLength = selection.y - selection.x; - endRecording(cursorPosition, selectionLength); - break; - case FORMAT_DOCUMENT : - DocumentRewriteSession rewriteSession = null; - IDocument document = getDocument(); - try { - /* - * This command will actually format selection if text is - * selected, otherwise format entire document - */ - // begin recording - beginRecording(FORMAT_DOCUMENT_TEXT, FORMAT_DOCUMENT_TEXT, cursorPosition, selectionLength); - boolean formatDocument = false; - IRegion region = null; - Point s = getSelectedRange(); - if (s.y > 0) { - // only format currently selected text - region = new Region(s.x, s.y); - } - else { - // no selection, so format entire document - region = getModelCoverage(); - formatDocument = true; - } - - if (document instanceof IDocumentExtension4) { - IDocumentExtension4 extension = (IDocumentExtension4) document; - DocumentRewriteSessionType type = (selection.y == 0 || selection.y > MAX_SMALL_FORMAT_LENGTH) ? DocumentRewriteSessionType.UNRESTRICTED : DocumentRewriteSessionType.UNRESTRICTED_SMALL; - rewriteSession = (extension.getActiveRewriteSession() != null) ? null : extension.startRewriteSession(type); - } - else { - setRedraw(false); - } - - if (fContentFormatter instanceof IContentFormatterExtension) { - IContentFormatterExtension extension = (IContentFormatterExtension) fContentFormatter; - IFormattingContext context = new FormattingContext(); - context.setProperty(FormattingContextProperties.CONTEXT_DOCUMENT, Boolean.valueOf(formatDocument)); - context.setProperty(FormattingContextProperties.CONTEXT_REGION, region); - extension.format(document, context); - } - else { - fContentFormatter.format(document, region); - } - } - finally { - try { - if (rewriteSession != null) { - IDocumentExtension4 extension = (IDocumentExtension4) document; - extension.stopRewriteSession(rewriteSession); - } - else { - setRedraw(true); - } - } - finally { - // end recording - selection = getTextWidget().getSelection(); - cursorPosition = selection.x; - selectionLength = selection.y - selection.x; - endRecording(cursorPosition, selectionLength); - } - } - break; - case FORMAT_ACTIVE_ELEMENTS : - rewriteSession = null; - document = getDocument(); - try { - /* - * This command will format the node at cursor position - * (and all its children) - */ - // begin recording - beginRecording(FORMAT_ACTIVE_ELEMENTS_TEXT, FORMAT_ACTIVE_ELEMENTS_TEXT, cursorPosition, selectionLength); - IRegion region = null; - Point s = getSelectedRange(); - if (s.y > -1) { - // only format node at cursor position - region = new Region(s.x, s.y); - } - - if (document instanceof IDocumentExtension4) { - IDocumentExtension4 extension = (IDocumentExtension4) document; - DocumentRewriteSessionType type = (selection.y == 0 || selection.y > MAX_SMALL_FORMAT_LENGTH) ? DocumentRewriteSessionType.UNRESTRICTED : DocumentRewriteSessionType.UNRESTRICTED_SMALL; - rewriteSession = (extension.getActiveRewriteSession() != null) ? null : extension.startRewriteSession(type); - } - else { - setRedraw(false); - } - - if (fContentFormatter instanceof IContentFormatterExtension) { - IContentFormatterExtension extension = (IContentFormatterExtension) fContentFormatter; - IFormattingContext context = new FormattingContext(); - context.setProperty(FormattingContextProperties.CONTEXT_DOCUMENT, Boolean.FALSE); - context.setProperty(FormattingContextProperties.CONTEXT_REGION, region); - extension.format(getDocument(), context); - } - else { - fContentFormatter.format(getDocument(), region); - } - } - finally { - try { - if (rewriteSession != null) { - IDocumentExtension4 extension = (IDocumentExtension4) document; - extension.stopRewriteSession(rewriteSession); - } - else { - setRedraw(true); - } - } - finally { - // end recording - selection = getTextWidget().getSelection(); - cursorPosition = selection.x; - selectionLength = selection.y - selection.x; - endRecording(cursorPosition, selectionLength); - } - } - break; - default : - super.doOperation(operation); - } - } - - private void endRecording(int cursorPosition, int selectionLength) { - IDocument doc = getDocument(); - if (doc instanceof IStructuredDocument) { - IStructuredDocument structuredDocument = (IStructuredDocument) doc; - IStructuredTextUndoManager undoManager = structuredDocument.getUndoManager(); - - // https://bugs.eclipse.org/bugs/show_bug.cgi?id=198617 - // undo after paste in document with folds - wrong behavior - IRegion widgetSelection = new Region(cursorPosition, selectionLength); - IRegion documentSelection = widgetRange2ModelRange(widgetSelection); - if (documentSelection == null) - documentSelection = widgetSelection; - undoManager.endRecording(this, documentSelection.getOffset(), documentSelection.getLength()); - } - else { - // TODO: how to handle other document types? - } - } - - private void beginRecording(String label, String description, int cursorPosition, int selectionLength) { - IDocument doc = getDocument(); - if (doc instanceof IStructuredDocument) { - IStructuredDocument structuredDocument = (IStructuredDocument) doc; - IStructuredTextUndoManager undoManager = structuredDocument.getUndoManager(); - - // https://bugs.eclipse.org/bugs/show_bug.cgi?id=198617 - // undo after paste in document with folds - wrong behavior - IRegion widgetSelection = new Region(cursorPosition, selectionLength); - IRegion documentSelection = widgetRange2ModelRange(widgetSelection); - if (documentSelection == null) - documentSelection = widgetSelection; - undoManager.beginRecording(this, label, description, documentSelection.getOffset(), documentSelection.getLength()); - } - else { - // TODO: how to handle other document types? - } - } - - public void endBackgroundUpdate() { - fBackgroundupdateInProgress = false; - setRedraw(true); - } - - protected void handleDispose() { - Logger.trace("Source Editor", "StructuredTextViewer::handleDispose entry"); //$NON-NLS-1$ //$NON-NLS-2$ - - // before we dispose, we set a special "empty" selection, to prevent - // the "leak one document" that - // otherwise occurs when editor closed (since last selection stays in - // SelectedResourceManager. - // the occurance of the "leak" isn't so bad, but makes debugging other - // leaks very hard. - setSelection(TextSelection.emptySelection()); - - if (fHighlighter != null) { - fHighlighter.uninstall(); - fHighlighter = null; - } - - if (fRecHighlighter != null) { - fRecHighlighter.uninstall(); - fRecHighlighter = null; - } - super.handleDispose(); - - Logger.trace("Source Editor", "StructuredTextViewer::handleDispose exit"); //$NON-NLS-1$ //$NON-NLS-2$ - } - - /* - * Overridden for special support of background update and read-only - * regions - */ - protected void handleVerifyEvent(VerifyEvent e) { - IRegion modelRange = event2ModelRange(e); - if (exposeModelRange(modelRange)) { - e.doit = false; - return; - } - - if (fEventConsumer != null) { - fEventConsumer.processEvent(e); - if (!e.doit) - return; - } - if (fBackgroundupdateInProgress) { - e.doit = false; - beep(); - return; - } - - // for read-only support - if (containsReadOnly(getVisibleDocument(), e.start, e.end)) { - e.doit = false; - beep(); - return; - } - - try { - super.handleVerifyEvent(e); - } - catch (Exception x) { - /* - * Note, we catch and log any exception, since an otherwise can - * actually prevent typing! see - * https://bugs.eclipse.org/bugs/show_bug.cgi?id=111318 - */ - - if (TRACE_EXCEPTIONS) - Logger.logException("StructuredTextViewer.exception.verifyText", x); //$NON-NLS-1$ - } - } - - public int modelLine2WidgetLine(int modelLine) { - /** - * need to override this method as a workaround for Bug 85709 - */ - if (fInformationMapping == null) { - IDocument document = getDocument(); - if (document != null) { - try { - IRegion modelLineRegion = getDocument().getLineInformation(modelLine); - IRegion region = getModelCoverage(); - if (modelLineRegion != null && region != null) { - int modelEnd = modelLineRegion.getOffset() + modelLineRegion.getLength(); - int regionEnd = region.getOffset() + region.getLength(); - // returns -1 if modelLine is invalid - if ((modelLineRegion.getOffset() < region.getOffset()) || (modelEnd > regionEnd)) - return -1; - } - } - catch (BadLocationException e) { - // returns -1 if modelLine is invalid - return -1; - } - } - } - return super.modelLine2WidgetLine(modelLine); - } - - public int modelOffset2WidgetOffset(int modelOffset) { - /** - * need to override this method as a workaround for Bug 85709 - */ - if (fInformationMapping == null) { - IRegion region = getModelCoverage(); - if (region != null) { - // returns -1 if modelOffset is invalid - if (modelOffset < region.getOffset() || modelOffset > (region.getOffset() + region.getLength())) - return -1; - } - } - return super.modelOffset2WidgetOffset(modelOffset); - } - - public IRegion modelRange2WidgetRange(IRegion modelRange) { - // need to override this method as workaround for Bug85709 - if (fInformationMapping == null) { - IRegion region = getModelCoverage(); - if (region != null && modelRange != null) { - int modelEnd = modelRange.getOffset() + modelRange.getLength(); - int regionEnd = region.getOffset() + region.getLength(); - // returns null if modelRange is invalid - if ((modelRange.getOffset() < region.getOffset()) || (modelEnd > regionEnd)) - return null; - } - } - return super.modelRange2WidgetRange(modelRange); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.text.source.ISourceViewer#setDocument(org.eclipse.jface.text.IDocument, - * org.eclipse.jface.text.source.IAnnotationModel, int, int) - */ - public void setDocument(IDocument document, IAnnotationModel annotationModel, int modelRangeOffset, int modelRangeLength) { - // partial fix for: - // https://w3.opensource.ibm.com/bugzilla/show_bug.cgi?id=1970 - // when our document is set, especially to null during close, - // immediately uninstall the reconciler. - // this is to avoid an unnecessary final "reconcile" - // that blocks display thread - if (document == null) { - if (fReconciler != null) { - fReconciler.uninstall(); - } - } - - super.setDocument(document, annotationModel, modelRangeOffset, modelRangeLength); - - if (document instanceof IStructuredDocument) { - IStructuredDocument structuredDocument = (IStructuredDocument) document; - - // notify highlighter - updateHighlighter(structuredDocument); - - // set the formatter again now that document has been set - if (!fFormatterSet && fConfiguration != null) { - fContentFormatter = fConfiguration.getContentFormatter(this); - fFormatterSet = true; - } - - // set document in the viewer-based undo manager - if (fUndoManager != null) { - fUndoManager.disconnect(); - fUndoManager.connect(this); - } - // CaretEvent is not sent to ViewerSelectionManager after Save As. - // Need to notify ViewerSelectionManager here. - // notifyViewerSelectionManager(getSelectedRange().x, - // getSelectedRange().y); - } - } - - public ContentAssistantFacade getContentAssistFacade() { - return fContentAssistantFacade; - } - - /** - * Uninstalls anything that was installed by configure - */ - public void unconfigure() { - Logger.trace("Source Editor", "StructuredTextViewer::unconfigure entry"); //$NON-NLS-1$ //$NON-NLS-2$ - if (fHighlighter != null) { - fHighlighter.uninstall(); - fHighlighter = null; - } - - if (fRecHighlighter != null) { - fRecHighlighter.uninstall(); - fRecHighlighter = null; - } - - if (fAnnotationHover instanceof StructuredTextAnnotationHover) { - ((StructuredTextAnnotationHover) fAnnotationHover).release(); - } - - if (fOverviewRulerAnnotationHover instanceof StructuredTextAnnotationHover) { - ((StructuredTextAnnotationHover) fOverviewRulerAnnotationHover).release(); - } - - super.unconfigure(); - fConfiguration = null; - Logger.trace("Source Editor", "StructuredTextViewer::unconfigure exit"); //$NON-NLS-1$ //$NON-NLS-2$ - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.sse.core.undo.IDocumentSelectionMediator#undoOperationSelectionChanged(org.eclipse.wst.sse.core.undo.UndoDocumentEvent) - */ - public void undoOperationSelectionChanged(UndoDocumentEvent event) { - if (event.getRequester() != null && event.getRequester().equals(this) && event.getDocument().equals(getDocument())) { - // BUG107687: Undo/redo do not scroll editor - ITextSelection selection = new TextSelection(event.getOffset(), event.getLength()); - setSelection(selection, true); - } - } - - private void updateHighlighter(IStructuredDocument document) { - boolean documentSet = false; - - // if highlighter has not been created yet, initialize and install it - if (fRecHighlighter == null && fConfiguration instanceof StructuredTextViewerConfiguration) { - String[] types = fConfiguration.getConfiguredContentTypes(this); - for (int i = 0; i < types.length; i++) { - String t = types[i]; - - // add highlighter/linestyleprovider - LineStyleProvider[] providers = ((StructuredTextViewerConfiguration) fConfiguration).getLineStyleProviders(this, t); - if (providers != null) { - for (int j = 0; j < providers.length; ++j) { - - if(fRecHighlighter == null) { - fRecHighlighter = new ReconcilerHighlighter(); - ((StructuredTextViewerConfiguration) fConfiguration).setHighlighter(fRecHighlighter); - } - if (providers[j] instanceof AbstractLineStyleProvider) { - ((AbstractLineStyleProvider) providers[j]).init(document, fRecHighlighter); - fRecHighlighter.addProvider(t, providers[j]); - } - else { - // init with compatibility instance - if (fHighlighter == null) { - fHighlighter = new CompatibleHighlighter(); - } - Logger.log(Logger.INFO_DEBUG, "CompatibleHighlighter installing compatibility for " + providers[j].getClass()); //$NON-NLS-1$ - providers[j].init(document, fHighlighter); - fHighlighter.addProvider(t, providers[j]); - } - } - } - } - - if(fRecHighlighter != null) - fRecHighlighter.install(this); - if(fHighlighter != null) { - fHighlighter.setDocumentPartitioning(fConfiguration.getConfiguredDocumentPartitioning(this)); - // https://bugs.eclipse.org/bugs/show_bug.cgi?id=203347 - // make sure to set document before install - fHighlighter.setDocument(document); - fHighlighter.install(this); - documentSet = true; - } - } - if (fHighlighter != null && !documentSet) - fHighlighter.setDocument(document); - - // install content type independent plugins - if (fPresentationReconciler != null) - fPresentationReconciler.uninstall(); - // 228847 - XSL Content Assist tests fail with Null Pointer on Highlighter - if(fConfiguration != null) - fPresentationReconciler = fConfiguration.getPresentationReconciler(this); - - if (fPresentationReconciler != null) - fPresentationReconciler.install(this); - - } - - /** - * Make sure indentation is correct before using. - */ - private void updateIndentationPrefixes() { - SourceViewerConfiguration configuration = fConfiguration; - if (fConfiguration != null) { - String[] types = configuration.getConfiguredContentTypes(this); - for (int i = 0; i < types.length; i++) { - String[] prefixes = configuration.getIndentPrefixes(this, types[i]); - if (prefixes != null && prefixes.length > 0) - setIndentPrefixes(prefixes, types[i]); - } - } - } - - /** - * Prepends the text presentation listener at the beginning of the viewer's - * list of text presentation listeners. If the listener is already registered - * with the viewer this call moves the listener to the beginning of - * the list. - * - * @param listener the text presentation listener - * @since 3.1 - */ - public void prependTextPresentationListener(ITextPresentationListener listener) { - - Assert.isNotNull(listener); - - if (fTextPresentationListeners == null) - fTextPresentationListeners= new ArrayList(); - - fTextPresentationListeners.remove(listener); - fTextPresentationListeners.add(0, listener); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/TextDropAction.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/TextDropAction.java deleted file mode 100644 index 82bc336d46..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/TextDropAction.java +++ /dev/null @@ -1,27 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal; - - - -import org.eclipse.swt.dnd.DropTargetEvent; -import org.eclipse.ui.IEditorPart; - -/** - * TextDropAction - */ -public class TextDropAction extends AbstractDropAction { - public boolean run(DropTargetEvent event, IEditorPart targetEditor) { - return insert((String) event.data, targetEditor); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/TransferBuilder.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/TransferBuilder.java deleted file mode 100644 index 1d7d64a3eb..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/TransferBuilder.java +++ /dev/null @@ -1,667 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2007 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal; - - - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IConfigurationElement; -import org.eclipse.core.runtime.IExtensionRegistry; -import org.eclipse.core.runtime.Platform; -import org.eclipse.swt.custom.BusyIndicator; -import org.eclipse.swt.dnd.Transfer; -import org.eclipse.swt.dnd.TransferData; -import org.eclipse.wst.sse.ui.internal.extension.DropActionProxy; -import org.eclipse.wst.sse.ui.internal.extension.RegistryReader; -import org.osgi.framework.Bundle; - - -/** - * Builds drop target transfers, drag source transfers, and drop actions - */ -public class TransferBuilder extends RegistryReader { - - public static final String ATT_CLASS = "class"; //$NON-NLS-1$ - public static final String ATT_ID = "id"; //$NON-NLS-1$ - public static final String ATT_METHOD = "method"; //$NON-NLS-1$ - public static final String ATT_PRIORITY = "priority"; //$NON-NLS-1$ - public static final String ATT_SINGLETON = "singleton"; //$NON-NLS-1$ - public static final String ATT_TARGET_ID = "targetID"; //$NON-NLS-1$ - public static final String ATT_TRANSFER_ID = "transferID"; //$NON-NLS-1$ - - private final static boolean debugTime = "true".equalsIgnoreCase(Platform.getDebugOption("org.eclipse.wst.sse.ui/transferbuilder/time")); //$NON-NLS-1$ //$NON-NLS-2$ - - public static final String PL_DRAG_SOURCE_TRANSFERS = "dragSourceTransfers"; //$NON-NLS-1$ - public static final String PL_DROP_TARGET_TRANSFERS = "dropTargetTransfers"; //$NON-NLS-1$ - - public static final String PLUGIN_ID = "org.eclipse.wst.sse.ui"; //$NON-NLS-1$ - - public static final String[] PRIORITIES = {"highest", "high", "mid", "low", "lowest"}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ - - public static final String TAG_DRAG_SOURCE_CONTRIBUTION = "dragSourceContribution"; //$NON-NLS-1$ - public static final String TAG_DROP_ACTION = "dropAction"; //$NON-NLS-1$ - public static final String TAG_DROP_TARGET_CONTRIBUTION = "dropTargetContribution"; //$NON-NLS-1$ - - public static final String TAG_TRANSFER = "transfer"; //$NON-NLS-1$ - - public static final String TRUE = "true"; //$NON-NLS-1$ - - private boolean useProxy; - - class TransferProxyForDelayLoading extends Transfer { - private IConfigurationElement element; - private String classAttribute; - private Transfer proxy; - private Method getTypeIdsMethod, getTypeNamesMethod, javaToNativeMethod, nativeToJavaMethod; - - TransferProxyForDelayLoading() { - super(); - } - - TransferProxyForDelayLoading(IConfigurationElement elm, String clsAttr) { - super(); - this.element = elm; - this.classAttribute = clsAttr; - } - - private Transfer newInstance() { - if ((element != null) && (classAttribute != null)) { - Object o = createExtension(element, classAttribute); - if (o instanceof Transfer) { - element = null; - classAttribute = null; - return (Transfer)o; - } - } - return null; - } - - public TransferData[] getSupportedTypes() { - if (proxy == null) { - proxy = newInstance(); - } - if (proxy != null) { - return proxy.getSupportedTypes(); - } - return new TransferData[0]; - } - protected int[] getTypeIds() { - if (proxy == null) { - proxy = newInstance(); - } - if (proxy != null) { - if (getTypeIdsMethod == null) { - Class runtimeClass = proxy.getClass(); - NoSuchMethodException e = null; - while (runtimeClass != null) { - try { - getTypeIdsMethod = runtimeClass.getDeclaredMethod("getTypeIds", new Class[0]);//$NON-NLS-1$ - getTypeIdsMethod.setAccessible(true); - break; - } catch (NoSuchMethodException e1) { - e = e1; - runtimeClass = runtimeClass.getSuperclass(); - } catch (SecurityException e2) { - runtimeClass = runtimeClass.getSuperclass(); - } - } - if ((getTypeIdsMethod == null) && (e != null)) { - Logger.logException(e); - } - } - if (getTypeIdsMethod != null) { - try { - // changed Integer[] return type to int[] - int[] r = (int[])getTypeIdsMethod.invoke(proxy, new Object[0]); - if ((r != null) && (r.length > 0)) { - int[] ret = new int[r.length]; - for(int i = 0; i < r.length; i++) { - ret[i] = r[i]; - } - return ret; - } - } catch (IllegalAccessException e2) { - Logger.logException(e2); - } catch (InvocationTargetException e3) { - Logger.logException(e3); - } - } - } - return new int[0]; - } - protected String[] getTypeNames() { - if (proxy == null) { - proxy = newInstance(); - } - if (proxy != null) { - if (getTypeNamesMethod == null) { - Class runtimeClass = proxy.getClass(); - NoSuchMethodException e = null; - while (runtimeClass != null) { - try { - getTypeNamesMethod = runtimeClass.getDeclaredMethod("getTypeNames", new Class[0]);//$NON-NLS-1$ - getTypeNamesMethod.setAccessible(true); - break; - } catch (NoSuchMethodException e1) { - e = e1; - runtimeClass = runtimeClass.getSuperclass(); - } catch (SecurityException e2) { - runtimeClass = runtimeClass.getSuperclass(); - } - } - if ((getTypeNamesMethod == null) && (e != null)) { - Logger.logException(e); - } - } - if (getTypeNamesMethod != null) { - try { - return (String[])getTypeNamesMethod.invoke(proxy, new Object[0]); - } catch (IllegalAccessException e2) { - Logger.logException(e2); - } catch (InvocationTargetException e3) { - Logger.logException(e3); - } - } - } - return new String[0]; - } - public boolean isSupportedType(TransferData transferData) { - if (proxy == null) { - proxy = newInstance(); - } - if (proxy != null) { - return proxy.isSupportedType(transferData); - } - return false; - } - protected void javaToNative(Object object, TransferData transferData) { - if (proxy == null) { - proxy = newInstance(); - } - if (proxy != null) { - if (javaToNativeMethod == null) { - Class runtimeClass = proxy.getClass(); - NoSuchMethodException e = null; - while (runtimeClass != null) { - try { - javaToNativeMethod = runtimeClass.getDeclaredMethod("javaToNative", new Class[]{object.getClass(), transferData.getClass()});//$NON-NLS-1$ - javaToNativeMethod.setAccessible(true); - break; - } catch (NoSuchMethodException e1) { - e = e1; - runtimeClass = runtimeClass.getSuperclass(); - } catch (SecurityException e2) { - runtimeClass = runtimeClass.getSuperclass(); - } - } - if ((javaToNativeMethod == null) && (e != null)) { - Logger.logException(e); - } - } - if (javaToNativeMethod != null) { - try { - javaToNativeMethod.invoke(proxy, new Object[]{object, transferData}); - } catch (IllegalAccessException e2) { - Logger.logException(e2); - } catch (InvocationTargetException e3) { - Logger.logException(e3); - } - } - } - } - protected Object nativeToJava(TransferData transferData) { - if (proxy == null) { - proxy = newInstance(); - } - if (proxy != null) { - if (nativeToJavaMethod == null) { - Class runtimeClass = proxy.getClass(); - NoSuchMethodException e = null; - while (runtimeClass != null) { - try { - nativeToJavaMethod = runtimeClass.getDeclaredMethod("nativeToJava", new Class[]{transferData.getClass()});//$NON-NLS-1$ - nativeToJavaMethod.setAccessible(true); - break; - } catch (NoSuchMethodException e1) { - e = e1; - runtimeClass = runtimeClass.getSuperclass(); - } catch (SecurityException e2) { - runtimeClass = runtimeClass.getSuperclass(); - } - } - if ((nativeToJavaMethod == null) && (e != null)) { - Logger.logException(e); - } - } - if (nativeToJavaMethod != null) { - try { - return nativeToJavaMethod.invoke(proxy, new Object[]{transferData}); - } catch (IllegalAccessException e2) { - Logger.logException(e2); - } catch (InvocationTargetException e3) { - Logger.logException(e3); - } - } - } - return new Object(); - } - Transfer getTransferClass() { - if (proxy == null) { - proxy = newInstance(); - } - return proxy; - } - - public String toString() { - String clazz = element.getAttribute(classAttribute); - return clazz != null ? clazz : super.toString(); - } - } - /** - * @param element - * @param classAttribute - * @return Object - * @throws CoreException - */ - static Object createExecutableExtension(final IConfigurationElement element, final String classAttribute) throws CoreException { - - Object obj = null; - - String singleton = element.getAttribute(ATT_SINGLETON); - String method = element.getAttribute(ATT_METHOD); - if (TRUE.equalsIgnoreCase(singleton) && method != null) { - try { - String name = element.getAttribute(ATT_CLASS); - String pluginId = element.getDeclaringExtension().getNamespace(); - Class cls = Platform.getBundle(pluginId).loadClass(name); - Method mtd = cls.getMethod(method, new Class[]{}); - - obj = mtd.invoke(null, null); - } catch (ClassNotFoundException e) { - obj = null; - } catch (NoSuchMethodException e) { - obj = null; - } catch (IllegalAccessException e) { - obj = null; - } catch (InvocationTargetException e) { - obj = null; - } - } else { - obj = element.createExecutableExtension(classAttribute); - } - - return obj; - } - - /** - * Creates an extension. If the extension plugin has not been loaded a - * busy cursor will be activated during the duration of the load. - * - * @param element - * @param classAttribute - * @return Object - * @throws CoreException - */ - public static Object createExtension(final IConfigurationElement element, final String classAttribute) { - // If plugin has been loaded create extension. - // Otherwise, show busy cursor then create extension. - final Object[] result = new Object[1]; - String pluginId = element.getDeclaringExtension().getNamespace(); - Bundle bundle = Platform.getBundle(pluginId); - if (bundle.getState() == Bundle.ACTIVE) { - try { - return createExecutableExtension(element, classAttribute); - } catch (CoreException e) { - handleCreateExecutableException(result, e); - } - } else { - BusyIndicator.showWhile(null, new Runnable() { - public void run() { - try { - result[0] = createExecutableExtension(element, classAttribute); - } catch (Exception e) { - handleCreateExecutableException(result, e); - } - } - }); - } - return result[0]; - } - - /** - * @param result - * @param e - */ - protected static void handleCreateExecutableException(Object[] result, Throwable e) { - Logger.logException(e); - result[0] = null; - - } - - protected List cache; - protected String targetContributionTag; - - protected List targetIDs; - - /** - * @param element - * @return IDropAction - */ - protected IDropAction createDropAction(IConfigurationElement element) { - Object obj = null; - obj = createExtension(element, ATT_CLASS); - if (obj == null) - return null; - return (obj instanceof IDropAction) ? (IDropAction) DropActionProxy.newInstance(obj) : null; - } - - /** - * @param transferId - * @return IDropAction[] - */ - protected IDropAction[] createDropActions(String transferId) { - if (cache == null) - return new IDropAction[0]; - - final int num = cache.size(); - if (num == 0) - return new IDropAction[0]; - - IDropAction[] as = new IDropAction[num]; - int j = 0; - for (int p = 0; p < PRIORITIES.length; p++) { - for (int i = 0; i < num; i++) { - Object obj = cache.get(i); - if (!(obj instanceof IConfigurationElement)) - continue; - - IConfigurationElement element = (IConfigurationElement) obj; - if (!(TAG_DROP_ACTION.equals(element.getName())) || !(transferId.equals(element.getAttribute(ATT_TRANSFER_ID)))) - continue; - - if (PRIORITIES[p].equals(element.getAttribute(ATT_PRIORITY)) || (p == 2 && element.getAttribute(ATT_PRIORITY) == null)) { - IDropAction a = createDropAction(element); - if (a != null) { - as[j] = a; - j++; - } - } - } - } - - if (num == j) - return as; - - IDropAction[] as2 = new IDropAction[j]; - for (int i = 0; i < j; i++) { - as2[i] = as[i]; - } - - return as2; - } - - /** - * @param element - * @return Transfer - */ - protected Transfer createTransfer(IConfigurationElement element) { - Object obj = null; - if (useProxy) { - obj = new TransferProxyForDelayLoading(element, ATT_CLASS); - } else { - obj = createExtension(element, ATT_CLASS); - } - if (obj == null) - return null; - return (obj instanceof Transfer) ? (Transfer) obj : null; - } - - /** - * @return Transfer[] - */ - protected Transfer[] createTransfers() { - if (cache == null) - return new Transfer[0]; - - final int num = cache.size(); - if (num == 0) - return new Transfer[0]; - - Transfer[] ts = new Transfer[num]; - int j = 0; - for (int p = 0; p < PRIORITIES.length; p++) { - for (int i = 0; i < num; i++) { - Object obj = cache.get(i); - if (!(obj instanceof IConfigurationElement)) - continue; - - IConfigurationElement element = (IConfigurationElement) obj; - if (!TAG_TRANSFER.equals(element.getName())) - continue; - - if (PRIORITIES[p].equals(element.getAttribute(ATT_PRIORITY)) || (p == 2 && element.getAttribute(ATT_PRIORITY) == null)) { - Transfer t = createTransfer(element); - if (t != null) { - ts[j] = t; - j++; - } - } - } - } - - if (num == j) - return ts; - - Transfer[] ts2 = new Transfer[j]; - for (int i = 0; i < j; i++) { - ts2[i] = ts[i]; - } - - return ts2; - } - - /** - * @param editorId - * @return Transfer[] - */ - public Transfer[] getDragSourceTransfers(String editorId) { - return getDragSourceTransfers(new String[]{editorId}); - } - - /** - * @param editorIds - * @return Transfer[] - */ - public Transfer[] getDragSourceTransfers(String[] editorIds) { - long time0 = System.currentTimeMillis(); - readContributions(editorIds, TAG_DRAG_SOURCE_CONTRIBUTION, PL_DRAG_SOURCE_TRANSFERS); - Transfer[] transfers = createTransfers(); - if (debugTime) - System.out.println(getClass().getName() + "#getDragSourceTransfers(" + editorIds + "): " + transfers.length + " transfers created in " + (System.currentTimeMillis() - time0) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ - return transfers; - } - - /** - * @deprecated use getDropActions(String editorId, Transfer transfer) for the performance - * @param editorId - * @param className - * @return IDropAction[] - */ - public IDropAction[] getDropActions(String editorId, String transferClassName) { - return getDropActions(new String[]{editorId}, transferClassName); - } - - /** - * @param editorId - * @param class - * @return IDropAction[] - */ - public IDropAction[] getDropActions(String editorId, Transfer transfer) { - return getDropActions(new String[]{editorId}, transfer); - } - /** - * @deprecated use getDropActions(String[] editorIds, Transfer transfer) for the performance - * @param editorId - * @param className - * @return IDropAction[] - */ - public IDropAction[] getDropActions(String[] editorIds, String transferClassName) { - long time0 = System.currentTimeMillis(); - readContributions(editorIds, TAG_DROP_TARGET_CONTRIBUTION, PL_DROP_TARGET_TRANSFERS); - String transferId = getTransferIdOfClassName(transferClassName); - IDropAction[] actions = createDropActions(transferId); - if (debugTime) - System.out.println(getClass().getName() + "#getDropActions(" + editorIds + "): " + actions.length + " drop actions created in " + (System.currentTimeMillis() - time0) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ - return actions; - } - - /** - * @param editorId - * @param class - * @return IDropAction[] - */ - public IDropAction[] getDropActions(String[] editorIds, Transfer transfer) { - String transferClassName; - if (transfer instanceof TransferProxyForDelayLoading) { - transferClassName = ((TransferProxyForDelayLoading)transfer).getTransferClass().getClass().getName(); - } else { - transferClassName = transfer.getClass().getName(); - } - return getDropActions(editorIds, transferClassName); - } - /** - * @param editorId - * @return Transfer[] - */ - public Transfer[] getDropTargetTransfers(String editorId) { - return getDropTargetTransfers(new String[]{editorId}); - } - - /** - * @param editorIds - * @return Transfer[] - */ - public Transfer[] getDropTargetTransfers(String[] editorIds) { - long time0 = System.currentTimeMillis(); - readContributions(editorIds, TAG_DROP_TARGET_CONTRIBUTION, PL_DROP_TARGET_TRANSFERS); - Transfer[] transfers = createTransfers(); - if (debugTime) { - String idlist = ""; //$NON-NLS-1$ - if (editorIds.length > 0) { - for (int i = 0; i < editorIds.length; i++) { - idlist += editorIds[i]; - if (i < editorIds.length - 1) - idlist += ","; //$NON-NLS-1$ - } - } - System.out.println(getClass().getName() + "#getDropTargetTransfers(" + idlist + "): " + transfers.length + " transfers created in " + (System.currentTimeMillis() - time0) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ - } - return transfers; - } - - /** - * Returns the name of the part ID attribute that is expected in the - * target extension. - * - * @param element - * @return String - */ - protected String getTargetID(IConfigurationElement element) { - String value = element.getAttribute(ATT_TARGET_ID); - return value != null ? value : "???"; //$NON-NLS-1$ - } - - /** - * @param className - * @return String - */ - private String getTransferIdOfClassName(String className) { - String id = ""; //$NON-NLS-1$ - final int num = cache.size(); - if (className == null || cache == null || num == 0) - return id; - - for (int i = 0; i < num; i++) { - Object obj = cache.get(i); - if (obj instanceof IConfigurationElement) { - IConfigurationElement element = (IConfigurationElement) obj; - if (className.equals(element.getAttribute(ATT_CLASS))) { - id = element.getAttribute(ATT_ID); - break; - } - } - } - - return (id.length() != 0 ? id : className); - } - - /** - * Reads the contributions from the registry for the provided workbench - * part and the provided extension point ID. - * - * @param id - * @param tag - * @param extensionPoint - */ - protected void readContributions(String[] ids, String tag, String extensionPoint) { - cache = null; - targetIDs = Arrays.asList(ids); - targetContributionTag = tag; - IExtensionRegistry registry = Platform.getExtensionRegistry(); - readRegistry(registry, PLUGIN_ID, extensionPoint); - } - - protected boolean readElement(IConfigurationElement element) { - String tag = element.getName(); - if (tag.equals(targetContributionTag)) { - String id = getTargetID(element); - if (id == null || !targetIDs.contains(id)) { - // This is not of interest to us - don't go deeper - return true; - } - } else if (tag.equals(TAG_TRANSFER)) { - if (cache == null) - cache = new ArrayList(); - cache.add(element); - return true; // just cache the element - don't go into it - } else if (tag.equals(TAG_DROP_ACTION)) { - if (cache == null) - cache = new ArrayList(); - //cache.add(createActionDescriptor(element)); - cache.add(element); - return true; // just cache the action - don't go into - } else { - return false; - } - - readElementChildren(element); - return true; - } - /** - * @deprecated - use TransferBuilder(boolean useProxy) for the performance - */ - public TransferBuilder() { - this(false); - } - - public TransferBuilder(boolean useProxy) { - super(); - this.useProxy = useProxy; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/UnknownContentTypeDialog.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/UnknownContentTypeDialog.java deleted file mode 100644 index 9bd2f8982f..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/UnknownContentTypeDialog.java +++ /dev/null @@ -1,67 +0,0 @@ -package org.eclipse.wst.sse.ui.internal; - -import org.eclipse.jface.dialogs.IDialogConstants; -import org.eclipse.jface.dialogs.MessageDialogWithToggle; -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.preference.PreferenceDialog; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Link; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.dialogs.PreferencesUtil; - -/** - * Message dialog informing user that an editor was open on unsupported - * content type - */ -public class UnknownContentTypeDialog extends MessageDialogWithToggle { - - public UnknownContentTypeDialog(Shell parent, IPreferenceStore store, String key) { - // set message to null in super so that message does not appear twice - super(parent, SSEUIMessages.UnknownContentTypeDialog_0, null, null, INFORMATION, new String[]{IDialogConstants.OK_LABEL}, 0, SSEUIMessages.UnknownContentTypeDialog_1, false); - setPrefStore(store); - setPrefKey(key); - } - - protected void buttonPressed(int buttonId) { - super.buttonPressed(buttonId); - - // overwritten so that value stored is boolean, not string - if (buttonId != IDialogConstants.CANCEL_ID && getToggleState() && getPrefStore() != null && getPrefKey() != null) { - switch (buttonId) { - case IDialogConstants.YES_ID : - case IDialogConstants.YES_TO_ALL_ID : - case IDialogConstants.PROCEED_ID : - case IDialogConstants.OK_ID : - getPrefStore().setValue(getPrefKey(), false); - break; - case IDialogConstants.NO_ID : - case IDialogConstants.NO_TO_ALL_ID : - getPrefStore().setValue(getPrefKey(), true); - break; - } - } - - } - - protected Control createMessageArea(Composite composite) { - super.createMessageArea(composite); - Link messageLink = new Link(composite, SWT.NONE); - messageLink.setText(SSEUIMessages.UnknownContentTypeDialog_2); - messageLink.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent e) { - linkClicked(); - } - }); - return composite; - } - - private void linkClicked() { - String pageId = "org.eclipse.ui.preferencePages.ContentTypes"; //$NON-NLS-1$ - PreferenceDialog dialog = PreferencesUtil.createPreferenceDialogOn(getShell(), pageId, new String[]{pageId}, null); - dialog.open(); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/actions/ActionContributor.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/actions/ActionContributor.java deleted file mode 100644 index 5002931362..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/actions/ActionContributor.java +++ /dev/null @@ -1,400 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * David Carver/STAR - [212330] can't contribute to the XML or any SSE based menu - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.actions; - -//import java.util.ResourceBundle; - -import java.util.ResourceBundle; - -import org.eclipse.core.runtime.Platform; -import org.eclipse.jface.action.GroupMarker; -import org.eclipse.jface.action.IAction; -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.search.ui.IContextMenuConstants; -import org.eclipse.ui.IActionBars; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.IWorkbenchActionConstants; -import org.eclipse.ui.IWorkbenchPage; -import org.eclipse.ui.editors.text.TextEditorActionContributor; -import org.eclipse.ui.texteditor.ITextEditor; -import org.eclipse.ui.texteditor.ITextEditorActionConstants; -import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds; -import org.eclipse.ui.texteditor.ITextEditorExtension; -import org.eclipse.ui.texteditor.RetargetTextEditorAction; -import org.eclipse.wst.sse.ui.internal.ExtendedEditorActionBuilder; -import org.eclipse.wst.sse.ui.internal.GotoAnnotationAction; -import org.eclipse.wst.sse.ui.internal.IExtendedContributor; -import org.eclipse.wst.sse.ui.internal.ISourceViewerActionBarContributor; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; -import org.eclipse.wst.sse.ui.internal.ui.OffsetStatusLineContributionItem; - -/** - * This class should not be used inside multi page editor's - * ActionBarContributor, since cascaded init() call from the - * ActionBarContributor will causes exception and it leads to lose whole - * toolbars. - * - * Instead, use SourcePageActionContributor for source page contributor of - * multi page editor. - * - * Note that this class is still valid for single page editor - */ -public class ActionContributor extends TextEditorActionContributor implements ISourceViewerActionBarContributor, IExtendedContributor { - - public static final boolean _showDebugStatus = "true".equalsIgnoreCase(Platform.getDebugOption("org.eclipse.wst.sse.ui/actioncontributor/debugstatusfields")) || Platform.inDebugMode() || Platform.inDevelopmentMode(); //$NON-NLS-1$ //$NON-NLS-2$ - - private static final String[] EDITOR_IDS = {"org.eclipse.wst.sse.ui.StructuredTextEditor"}; //$NON-NLS-1$ - - protected IExtendedContributor extendedContributor; - protected RetargetTextEditorAction fAddBlockComment = null; - - protected Separator fCommandsSeparator = null; - - private OffsetStatusLineContributionItem fDebugStatusOffset = null; - protected MenuManager fExpandSelectionToMenu = null; - protected GroupMarker fMenuAdditionsGroupMarker = null; - protected GotoAnnotationAction fNextAnnotation = null; - - protected GotoAnnotationAction fPreviousAnnotation = null; - protected RetargetTextEditorAction fRemoveBlockComment = null; - protected RetargetTextEditorAction fShiftLeft = null; - protected RetargetTextEditorAction fShiftRight = null; - protected RetargetTextEditorAction fStructureSelectEnclosingAction = null; - protected RetargetTextEditorAction fStructureSelectHistoryAction = null; - protected RetargetTextEditorAction fStructureSelectNextAction = null; - protected RetargetTextEditorAction fStructureSelectPreviousAction = null; - - protected RetargetTextEditorAction fToggleComment = null; - protected RetargetTextEditorAction fToggleInsertModeAction; - protected GroupMarker fToolbarAdditionsGroupMarker = null; - protected Separator fToolbarSeparator = null; - - protected RetargetTextEditorAction fGotoMatchingBracketAction = null; - - public ActionContributor() { - super(); - - ResourceBundle resourceBundle = SSEUIMessages.getResourceBundle(); - - fCommandsSeparator = new Separator(); - - // edit commands - fStructureSelectEnclosingAction = new RetargetTextEditorAction(resourceBundle, StructuredTextEditorActionConstants.ACTION_NAME_STRUCTURE_SELECT_ENCLOSING + StructuredTextEditorActionConstants.UNDERSCORE); - fStructureSelectEnclosingAction.setActionDefinitionId(ActionDefinitionIds.STRUCTURE_SELECT_ENCLOSING); - - fStructureSelectNextAction = new RetargetTextEditorAction(resourceBundle, StructuredTextEditorActionConstants.ACTION_NAME_STRUCTURE_SELECT_NEXT + StructuredTextEditorActionConstants.UNDERSCORE); - fStructureSelectNextAction.setActionDefinitionId(ActionDefinitionIds.STRUCTURE_SELECT_NEXT); - - fStructureSelectPreviousAction = new RetargetTextEditorAction(resourceBundle, StructuredTextEditorActionConstants.ACTION_NAME_STRUCTURE_SELECT_PREVIOUS + StructuredTextEditorActionConstants.UNDERSCORE); - fStructureSelectPreviousAction.setActionDefinitionId(ActionDefinitionIds.STRUCTURE_SELECT_PREVIOUS); - - fStructureSelectHistoryAction = new RetargetTextEditorAction(resourceBundle, StructuredTextEditorActionConstants.ACTION_NAME_STRUCTURE_SELECT_HISTORY + StructuredTextEditorActionConstants.UNDERSCORE); - fStructureSelectHistoryAction.setActionDefinitionId(ActionDefinitionIds.STRUCTURE_SELECT_HISTORY); - - fExpandSelectionToMenu = new MenuManager(SSEUIMessages.ExpandSelectionToMenu_label); //$NON-NLS-1$ - fExpandSelectionToMenu.add(fStructureSelectEnclosingAction); - fExpandSelectionToMenu.add(fStructureSelectNextAction); - fExpandSelectionToMenu.add(fStructureSelectPreviousAction); - fExpandSelectionToMenu.add(fStructureSelectHistoryAction); - - // source commands - fShiftRight = new RetargetTextEditorAction(resourceBundle, ITextEditorActionConstants.SHIFT_RIGHT + StructuredTextEditorActionConstants.UNDERSCORE); - fShiftRight.setActionDefinitionId(ITextEditorActionDefinitionIds.SHIFT_RIGHT); - - fShiftLeft = new RetargetTextEditorAction(resourceBundle, ITextEditorActionConstants.SHIFT_LEFT + StructuredTextEditorActionConstants.UNDERSCORE); - fShiftLeft.setActionDefinitionId(ITextEditorActionDefinitionIds.SHIFT_LEFT); - - fToggleComment = new RetargetTextEditorAction(resourceBundle, StructuredTextEditorActionConstants.ACTION_NAME_TOGGLE_COMMENT + StructuredTextEditorActionConstants.UNDERSCORE); - fToggleComment.setActionDefinitionId(ActionDefinitionIds.TOGGLE_COMMENT); - - fAddBlockComment = new RetargetTextEditorAction(resourceBundle, StructuredTextEditorActionConstants.ACTION_NAME_ADD_BLOCK_COMMENT + StructuredTextEditorActionConstants.UNDERSCORE); - fAddBlockComment.setActionDefinitionId(ActionDefinitionIds.ADD_BLOCK_COMMENT); - - fRemoveBlockComment = new RetargetTextEditorAction(resourceBundle, StructuredTextEditorActionConstants.ACTION_NAME_REMOVE_BLOCK_COMMENT + StructuredTextEditorActionConstants.UNDERSCORE); - fRemoveBlockComment.setActionDefinitionId(ActionDefinitionIds.REMOVE_BLOCK_COMMENT); - - // goto prev/next error - // CMVC 249017 for JavaEditor consistancy - fPreviousAnnotation = new GotoAnnotationAction("Previous_annotation", false); //$NON-NLS-1$ - fPreviousAnnotation.setActionDefinitionId("org.eclipse.ui.navigate.previous"); //$NON-NLS-1$ - - fNextAnnotation = new GotoAnnotationAction("Next_annotation", true); //$NON-NLS-1$ - fNextAnnotation.setActionDefinitionId("org.eclipse.ui.navigate.next"); //$NON-NLS-1$ - - fGotoMatchingBracketAction = new RetargetTextEditorAction(resourceBundle, StructuredTextEditorActionConstants.ACTION_NAME_GOTO_MATCHING_BRACKET + StructuredTextEditorActionConstants.UNDERSCORE); - fGotoMatchingBracketAction.setActionDefinitionId(ActionDefinitionIds.GOTO_MATCHING_BRACKET); - - // Read action extensions. - ExtendedEditorActionBuilder builder = new ExtendedEditorActionBuilder(); - extendedContributor = builder.readActionExtensions(getExtensionIDs()); - - fMenuAdditionsGroupMarker = new GroupMarker(StructuredTextEditorActionConstants.GROUP_NAME_MENU_ADDITIONS); - fToolbarSeparator = new Separator(); - fToolbarAdditionsGroupMarker = new GroupMarker(StructuredTextEditorActionConstants.GROUP_NAME_TOOLBAR_ADDITIONS); - - fToggleInsertModeAction = new RetargetTextEditorAction(resourceBundle, "Editor.ToggleInsertMode.", IAction.AS_CHECK_BOX); //$NON-NLS-1$ - fToggleInsertModeAction.setActionDefinitionId(ITextEditorActionDefinitionIds.TOGGLE_INSERT_MODE); - - if (_showDebugStatus) { - fDebugStatusOffset = new OffsetStatusLineContributionItem(StructuredTextEditorActionConstants.STATUS_CATEGORY_OFFSET, true, 20); - } - } - - protected void addToMenu(IMenuManager menu) { - // edit commands -/* IMenuManager editMenu = menu.findMenuUsingPath(IWorkbenchActionConstants.M_EDIT); - if (editMenu != null) { - editMenu.add(fCommandsSeparator); - editMenu.add(fToggleInsertModeAction); - editMenu.add(fCommandsSeparator); - editMenu.add(fExpandSelectionToMenu); - editMenu.add(fCommandsSeparator); - editMenu.add(fMenuAdditionsGroupMarker); - } - - // source commands - String sourceMenuLabel = SSEUIMessages.SourceMenu_label; //$NON-NLS-1$ - String sourceMenuId = "sourceMenuId"; // This is just a menu id. No //$NON-NLS-1$ - // need to translate. - // //$NON-NLS-1$ - IMenuManager sourceMenu = new MenuManager(sourceMenuLabel, sourceMenuId); - menu.insertAfter(IWorkbenchActionConstants.M_EDIT, sourceMenu); - if (sourceMenu != null) { - sourceMenu.add(fCommandsSeparator); - sourceMenu.add(fToggleComment); - sourceMenu.add(fAddBlockComment); - sourceMenu.add(fRemoveBlockComment); - sourceMenu.add(fShiftRight); - sourceMenu.add(fShiftLeft); - } - - IMenuManager gotoMenu = menu.findMenuUsingPath(IWorkbenchActionConstants.GO_TO); - if (gotoMenu != null) { - gotoMenu.add(fGotoMatchingBracketAction); - } -*/ - } - - protected void addToPopupMenu(IMenuManager menu) { - // add nothing - } - - protected void addToStatusLine(IStatusLineManager manager) { - if (_showDebugStatus) { - manager.add(fDebugStatusOffset); - } - } - - protected void addToToolBar(IToolBarManager toolBarManager) { -/* toolBarManager.add(fToolbarSeparator); - toolBarManager.add(fToolbarAdditionsGroupMarker); -*/ } - - /** - * @see org.eclipse.ui.part.EditorActionBarContributor#contributeToMenu(IMenuManager) - */ - public void contributeToMenu(IMenuManager menu) { - super.contributeToMenu(menu); - - IMenuManager editMenu= menu.findMenuUsingPath(IWorkbenchActionConstants.M_EDIT); - if (editMenu != null) { - editMenu.appendToGroup(IContextMenuConstants.GROUP_ADDITIONS, fToggleInsertModeAction); - } -/* - addToMenu(menu); -*/ - if (extendedContributor != null) { - extendedContributor.contributeToMenu(menu); - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.sse.ui.extension.IPopupMenuContributor#contributeToPopupMenu(org.eclipse.jface.action.IMenuManager) - */ - public void contributeToPopupMenu(IMenuManager menu) { -/* - addToPopupMenu(menu); -*/ - if (extendedContributor != null) { - extendedContributor.contributeToPopupMenu(menu); - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.part.EditorActionBarContributor#contributeToStatusLine(org.eclipse.jface.action.IStatusLineManager) - */ - public void contributeToStatusLine(IStatusLineManager manager) { - super.contributeToStatusLine(manager); - - addToStatusLine(manager); - - if (extendedContributor != null) { - extendedContributor.contributeToStatusLine(manager); - } - } - - /** - * @see org.eclipse.ui.part.EditorActionBarContributor#contributeToToolBar(IToolBarManager) - */ - public void contributeToToolBar(IToolBarManager toolBarManager) { - super.contributeToToolBar(toolBarManager); - -/* addToToolBar(toolBarManager); -*/ - if (extendedContributor != null) { - extendedContributor.contributeToToolBar(toolBarManager); - } - } - - /** - * @see org.eclipse.ui.part.EditorActionBarContributor#dispose() - */ - public void dispose() { - // need to call setActiveEditor before super.dispose because in both - // setActiveEditor & super.setActiveEditor if getEditorPart == - // activeEditor, - // the method is just returned. so to get both methods to run, - // setActiveEditor - // needs to be called so that it correctly calls super.setActiveEditor - setActiveEditor(null); - - super.dispose(); - - if (extendedContributor != null) - extendedContributor.dispose(); - } - - protected String[] getExtensionIDs() { - return EDITOR_IDS; - } - - /** - * @param editor - * @return - */ - protected ITextEditor getTextEditor(IEditorPart editor) { - ITextEditor textEditor = null; - if (editor instanceof ITextEditor) - textEditor = (ITextEditor) editor; - if (textEditor == null && editor != null) - textEditor = (ITextEditor) editor.getAdapter(ITextEditor.class); - return textEditor; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.IEditorActionBarContributor#init(org.eclipse.ui.IActionBars, - * org.eclipse.ui.IWorkbenchPage) - */ - public void init(IActionBars bars, IWorkbenchPage page) { - super.init(bars, page); - } - - /** - * @see org.eclipse.ui.IEditorActionBarContributor#setActiveEditor(IEditorPart) - */ - public void setActiveEditor(IEditorPart activeEditor) { - if (getActiveEditorPart() == activeEditor) - return; - super.setActiveEditor(activeEditor); - - ITextEditor textEditor = getTextEditor(activeEditor); - -/* IActionBars actionBars = getActionBars(); - if (actionBars != null) { - actionBars.setGlobalActionHandler(ITextEditorActionDefinitionIds.GOTO_NEXT_ANNOTATION, fNextAnnotation); - actionBars.setGlobalActionHandler(ITextEditorActionDefinitionIds.GOTO_PREVIOUS_ANNOTATION, fPreviousAnnotation); - actionBars.setGlobalActionHandler(ActionFactory.PREVIOUS.getId(), fPreviousAnnotation); - actionBars.setGlobalActionHandler(ActionFactory.NEXT.getId(), fNextAnnotation); - - if (textEditor != null) { - actionBars.setGlobalActionHandler(IDEActionFactory.ADD_TASK.getId(), getAction(textEditor, IDEActionFactory.ADD_TASK.getId())); - actionBars.setGlobalActionHandler(IDEActionFactory.BOOKMARK.getId(), getAction(textEditor, IDEActionFactory.BOOKMARK.getId())); - } - } - - fStructureSelectEnclosingAction.setAction(getAction(textEditor, StructuredTextEditorActionConstants.ACTION_NAME_STRUCTURE_SELECT_ENCLOSING)); - fStructureSelectNextAction.setAction(getAction(textEditor, StructuredTextEditorActionConstants.ACTION_NAME_STRUCTURE_SELECT_NEXT)); - fStructureSelectPreviousAction.setAction(getAction(textEditor, StructuredTextEditorActionConstants.ACTION_NAME_STRUCTURE_SELECT_PREVIOUS)); - fStructureSelectHistoryAction.setAction(getAction(textEditor, StructuredTextEditorActionConstants.ACTION_NAME_STRUCTURE_SELECT_HISTORY)); - - fShiftRight.setAction(getAction(textEditor, ITextEditorActionConstants.SHIFT_RIGHT)); - fShiftLeft.setAction(getAction(textEditor, ITextEditorActionConstants.SHIFT_LEFT)); - - fToggleComment.setAction(getAction(textEditor, StructuredTextEditorActionConstants.ACTION_NAME_TOGGLE_COMMENT)); - fAddBlockComment.setAction(getAction(textEditor, StructuredTextEditorActionConstants.ACTION_NAME_ADD_BLOCK_COMMENT)); - fRemoveBlockComment.setAction(getAction(textEditor, StructuredTextEditorActionConstants.ACTION_NAME_REMOVE_BLOCK_COMMENT)); - - // go to prev/next error - // CMVC 249017 for JavaEditor consistancy - fPreviousAnnotation.setEditor(textEditor); - fNextAnnotation.setEditor(textEditor); - fGotoMatchingBracketAction.setAction(getAction(textEditor, StructuredTextEditorActionConstants.ACTION_NAME_GOTO_MATCHING_BRACKET)); -*/ - fToggleInsertModeAction.setAction(getAction(textEditor, ITextEditorActionConstants.TOGGLE_INSERT_MODE)); - - if (extendedContributor != null) { - extendedContributor.setActiveEditor(activeEditor); - } - - if (_showDebugStatus && textEditor instanceof ITextEditorExtension) { - ((ITextEditorExtension) textEditor).setStatusField(fDebugStatusOffset, StructuredTextEditorActionConstants.STATUS_CATEGORY_OFFSET); - fDebugStatusOffset.setActiveEditor(textEditor); - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.sse.ui.ISourceViewerActionBarContributor#setViewerSpecificContributionsEnabled(boolean) - */ - public void setViewerSpecificContributionsEnabled(boolean enabled) { - fToggleInsertModeAction.setEnabled(enabled); -/* fShiftRight.setEnabled(enabled); - fShiftLeft.setEnabled(enabled); - fNextAnnotation.setEnabled(enabled); - fPreviousAnnotation.setEnabled(enabled); -*/ - /* - * fComment.setEnabled(enabled); fUncomment.setEnabled(enabled); - */ -/* - fToggleComment.setEnabled(enabled); - fAddBlockComment.setEnabled(enabled); - fRemoveBlockComment.setEnabled(enabled); -*/ - // convert line delimiters are not source viewer-specific - - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.sse.ui.extension.IExtendedContributor#updateToolbarActions() - */ - public void updateToolbarActions() { - if (extendedContributor != null) { - extendedContributor.updateToolbarActions(); - } - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/actions/ActionDefinitionIds.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/actions/ActionDefinitionIds.java deleted file mode 100644 index ae26969be3..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/actions/ActionDefinitionIds.java +++ /dev/null @@ -1,58 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.actions; - - - -/******************************************************************************* - * Copyright (c) 2001, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ - -/** - * Defines the definitions ids for editor actions. - */ -public interface ActionDefinitionIds { - // TODO: Can these be better defined with a "plugin prefix" to be more - // portable? - public final static String ADD_BLOCK_COMMENT = "org.eclipse.wst.sse.ui.add.block.comment";//$NON-NLS-1$ - - public final static String CLEANUP_DOCUMENT = "org.eclipse.wst.sse.ui.cleanup.document";//$NON-NLS-1$ - public final static String COMMENT = "org.eclipse.wst.sse.ui.comment";//$NON-NLS-1$ - public final static String EDIT_BREAKPOINTS = "org.eclipse.wst.sse.ui.breakpoints.edit";//$NON-NLS-1$ - public final static String FIND_OCCURRENCES = "org.eclipse.wst.sse.ui.search.find.occurrences";//$NON-NLS-1$ - public final static String FORMAT_ACTIVE_ELEMENTS = "org.eclipse.wst.sse.ui.format.active.elements";//$NON-NLS-1$ - public final static String FORMAT_DOCUMENT = "org.eclipse.wst.sse.ui.format.document";//$NON-NLS-1$ - public final static String MANAGE_BREAKPOINTS = "org.eclipse.wst.sse.ui.breakpoints.manage";//$NON-NLS-1$ - public final static String OPEN_FILE = "org.eclipse.wst.sse.ui.open.file.from.source";//$NON-NLS-1$ - public final static String REMOVE_BLOCK_COMMENT = "org.eclipse.wst.sse.ui.remove.block.comment";//$NON-NLS-1$ - public final static String STRUCTURE_SELECT_ENCLOSING = "org.eclipse.wst.sse.ui.structure.select.enclosing";//$NON-NLS-1$ - public final static String STRUCTURE_SELECT_HISTORY = "org.eclipse.wst.sse.ui.structure.select.last";//$NON-NLS-1$ - public final static String STRUCTURE_SELECT_NEXT = "org.eclipse.wst.sse.ui.structure.select.next";//$NON-NLS-1$ - public final static String STRUCTURE_SELECT_PREVIOUS = "org.eclipse.wst.sse.ui.structure.select.previous";//$NON-NLS-1$ - public final static String TOGGLE_COMMENT = "org.eclipse.wst.sse.ui.toggle.comment";//$NON-NLS-1$ - public final static String TOGGLE_BREAKPOINTS = "org.eclipse.wst.sse.ui.breakpoints.toggle";//$NON-NLS-1$ - public final static String UNCOMMENT = "org.eclipse.wst.sse.ui.uncomment";//$NON-NLS-1$ - public final static String SHOW_OUTLINE = "org.eclipse.wst.sse.ui.quick_outline";//$NON-NLS-1$ - - // registered command IDs, so we pick up the declared key bindings - public static final String GOTO_MATCHING_BRACKET= "org.eclipse.wst.sse.ui.goto.matching.bracket"; //$NON-NLS-1$ -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/actions/ActiveEditorActionHandler.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/actions/ActiveEditorActionHandler.java deleted file mode 100644 index 54586eb3ad..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/actions/ActiveEditorActionHandler.java +++ /dev/null @@ -1,286 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.actions; - -import org.eclipse.jface.action.IAction; -import org.eclipse.jface.action.IMenuCreator; -import org.eclipse.jface.resource.ImageDescriptor; -import org.eclipse.jface.util.IPropertyChangeListener; -import org.eclipse.swt.events.HelpListener; -import org.eclipse.swt.widgets.Event; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.IWorkbenchSite; -import org.eclipse.ui.texteditor.ITextEditor; - -/** - * @deprecated actions are not properly activated with this handler so do not - * use - */ -public class ActiveEditorActionHandler implements IAction { - - private String fActionId; - private IWorkbenchSite fSite; - private IAction fTargetAction; - - public ActiveEditorActionHandler(IWorkbenchSite site, String id) { - super(); - fActionId = id; - fSite = site; - } - - /** - * @see org.eclipse.jface.action.IAction#addPropertyChangeListener(org.eclipse.jface.util.IPropertyChangeListener) - */ - public void addPropertyChangeListener(IPropertyChangeListener listener) { - } - - /** - * @see org.eclipse.jface.action.IAction#getAccelerator() - */ - public int getAccelerator() { - updateTargetAction(); - return (fTargetAction != null ? fTargetAction.getAccelerator() : 0); - } - - /** - * @see org.eclipse.jface.action.IAction#getActionDefinitionId() - */ - public String getActionDefinitionId() { - updateTargetAction(); - return (fTargetAction != null ? fTargetAction.getActionDefinitionId() : null); - } - - /** - * @see org.eclipse.jface.action.IAction#getDescription() - */ - public String getDescription() { - updateTargetAction(); - return (fTargetAction != null ? fTargetAction.getDescription() : null); - } - - /** - * @see org.eclipse.jface.action.IAction#getDisabledImageDescriptor() - */ - public ImageDescriptor getDisabledImageDescriptor() { - updateTargetAction(); - return (fTargetAction != null ? fTargetAction.getDisabledImageDescriptor() : null); - } - - /** - * @see org.eclipse.jface.action.IAction#getHelpListener() - */ - public HelpListener getHelpListener() { - updateTargetAction(); - return (fTargetAction != null ? fTargetAction.getHelpListener() : null); - } - - /** - * @see org.eclipse.jface.action.IAction#getHoverImageDescriptor() - */ - public ImageDescriptor getHoverImageDescriptor() { - updateTargetAction(); - return (fTargetAction != null ? fTargetAction.getHoverImageDescriptor() : null); - } - - /** - * @see org.eclipse.jface.action.IAction#getId() - */ - public String getId() { - return getClass().getName() + hashCode(); - } - - /** - * @see org.eclipse.jface.action.IAction#getImageDescriptor() - */ - public ImageDescriptor getImageDescriptor() { - updateTargetAction(); - return (fTargetAction != null ? fTargetAction.getImageDescriptor() : null); - } - - /** - * @see org.eclipse.jface.action.IAction#getMenuCreator() - */ - public IMenuCreator getMenuCreator() { - return null; - } - - /** - * @see org.eclipse.jface.action.IAction#getStyle() - */ - public int getStyle() { - return IAction.AS_PUSH_BUTTON; - } - - /** - * @see org.eclipse.jface.action.IAction#getText() - */ - public String getText() { - updateTargetAction(); - return (fTargetAction != null ? fTargetAction.getText() : null); - } - - /** - * @see org.eclipse.jface.action.IAction#getToolTipText() - */ - public String getToolTipText() { - updateTargetAction(); - return (fTargetAction != null ? fTargetAction.getToolTipText() : null); - } - - /** - * @see org.eclipse.jface.action.IAction#isChecked() - */ - public boolean isChecked() { - updateTargetAction(); - return (fTargetAction != null ? fTargetAction.isChecked() : true); - } - - /** - * @see org.eclipse.jface.action.IAction#isEnabled() - */ - public boolean isEnabled() { - updateTargetAction(); - return (fTargetAction != null ? fTargetAction.isEnabled() : false); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.action.IAction#isHandled() - */ - public boolean isHandled() { - updateTargetAction(); - return (fTargetAction != null ? fTargetAction.isHandled() : false); - } - - /** - * @see org.eclipse.jface.action.IAction#removePropertyChangeListener(org.eclipse.jface.util.IPropertyChangeListener) - */ - public void removePropertyChangeListener(IPropertyChangeListener listener) { - } - - /** - * @see org.eclipse.jface.action.IAction#run() - */ - public void run() { - updateTargetAction(); - if (fTargetAction != null) - fTargetAction.run(); - } - - /** - * @see org.eclipse.jface.action.IAction#runWithEvent(org.eclipse.swt.widgets.Event) - */ - public void runWithEvent(Event event) { - updateTargetAction(); - if (fTargetAction != null) - fTargetAction.runWithEvent(event); - } - - /** - * NOT SUPPORTED - * - * @see org.eclipse.jface.action.IAction#setAccelerator(int) - */ - public void setAccelerator(int keycode) { - } - - /** - * @see org.eclipse.jface.action.IAction#setActionDefinitionId(java.lang.String) - */ - public void setActionDefinitionId(String id) { - } - - /** - * @see org.eclipse.jface.action.IAction#setChecked(boolean) - */ - public void setChecked(boolean checked) { - } - - /** - * @see org.eclipse.jface.action.IAction#setDescription(java.lang.String) - */ - public void setDescription(String text) { - } - - /** - * @see org.eclipse.jface.action.IAction#setDisabledImageDescriptor(org.eclipse.jface.resource.ImageDescriptor) - */ - public void setDisabledImageDescriptor(ImageDescriptor newImage) { - } - - /** - * @see org.eclipse.jface.action.IAction#setEnabled(boolean) - */ - public void setEnabled(boolean enabled) { - } - - /** - * @see org.eclipse.jface.action.IAction#setHelpListener(org.eclipse.swt.events.HelpListener) - */ - public void setHelpListener(HelpListener listener) { - } - - /** - * @see org.eclipse.jface.action.IAction#setHoverImageDescriptor(org.eclipse.jface.resource.ImageDescriptor) - */ - public void setHoverImageDescriptor(ImageDescriptor newImage) { - } - - /** - * @see org.eclipse.jface.action.IAction#setId(java.lang.String) - */ - public void setId(String id) { - } - - /** - * @see org.eclipse.jface.action.IAction#setImageDescriptor(org.eclipse.jface.resource.ImageDescriptor) - */ - public void setImageDescriptor(ImageDescriptor newImage) { - } - - /** - * @see org.eclipse.jface.action.IAction#setMenuCreator(org.eclipse.jface.action.IMenuCreator) - */ - public void setMenuCreator(IMenuCreator creator) { - } - - /** - * @see org.eclipse.jface.action.IAction#setText(java.lang.String) - */ - public void setText(String text) { - } - - /** - * @see org.eclipse.jface.action.IAction#setToolTipText(java.lang.String) - */ - public void setToolTipText(String text) { - } - - private void updateTargetAction() { - if (fSite != null && fSite.getWorkbenchWindow() != null && fSite.getWorkbenchWindow().getActivePage() != null) { - IEditorPart part = fSite.getWorkbenchWindow().getActivePage().getActiveEditor(); - ITextEditor editor = null; - if (part instanceof ITextEditor) - editor = (ITextEditor) part; - else - editor = (ITextEditor) (part != null ? part.getAdapter(ITextEditor.class) : null); - if (editor != null) { - fTargetAction = editor.getAction(fActionId); - } else { - fTargetAction = null; - } - } else - fTargetAction = null; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/actions/CleanupAction.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/actions/CleanupAction.java deleted file mode 100644 index 804df2cef5..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/actions/CleanupAction.java +++ /dev/null @@ -1,85 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.actions; - -import java.util.ResourceBundle; - -import org.eclipse.jface.dialogs.Dialog; -import org.eclipse.jface.text.ITextSelection; -import org.eclipse.jface.window.Window; -import org.eclipse.swt.custom.BusyIndicator; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.texteditor.ITextEditor; -import org.eclipse.ui.texteditor.TextEditorAction; -import org.eclipse.wst.sse.core.internal.cleanup.IStructuredCleanupProcessor; -import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel; -import org.eclipse.wst.sse.ui.StructuredTextEditor; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; - -public abstract class CleanupAction extends TextEditorAction { - protected Dialog fCleanupDialog; - - public CleanupAction(ResourceBundle bundle, String prefix, ITextEditor editor) { - super(bundle, prefix, editor); - } - - protected abstract Dialog getCleanupDialog(Shell shell); - - protected abstract IStructuredCleanupProcessor getCleanupProcessor(); - - public void run() { - if (getTextEditor() instanceof StructuredTextEditor) { - final StructuredTextEditor editor = (StructuredTextEditor) getTextEditor(); - Dialog cleanupDialog = getCleanupDialog(editor.getSite().getShell()); - if (cleanupDialog != null) { - if (cleanupDialog.open() == Window.OK) { - // setup runnable - Runnable runnable = new Runnable() { - public void run() { - IStructuredCleanupProcessor cleanupProcessor = getCleanupProcessor(); - if (cleanupProcessor != null) - cleanupProcessor.cleanupModel(editor.getModel()); - } - }; - - // TODO: make independent of 'model'. - IStructuredModel model = editor.getModel(); - if (model != null) { - try { - // begin recording - ITextSelection selection = (ITextSelection) editor.getSelectionProvider().getSelection(); - model.beginRecording(this, SSEUIMessages.Cleanup_Document_UI_, SSEUIMessages.Cleanup_Document_UI_, selection.getOffset(), selection.getLength()); //$NON-NLS-1$ //$NON-NLS-2$ - - // tell the model that we are about to make a big - // model change - model.aboutToChangeModel(); - - // run - BusyIndicator.showWhile(editor.getTextViewer().getControl().getDisplay(), runnable); - } finally { - // tell the model that we are done with the big - // model - // change - model.changedModel(); - - // end recording - ITextSelection selection = (ITextSelection) editor.getSelectionProvider().getSelection(); - model.endRecording(this, selection.getOffset(), selection.getLength()); - } - } - } - - } - } - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/actions/FormatActionDelegate.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/actions/FormatActionDelegate.java deleted file mode 100644 index ed11b90c5d..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/actions/FormatActionDelegate.java +++ /dev/null @@ -1,248 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.actions; - -import java.io.IOException; - -import org.eclipse.core.filebuffers.FileBuffers; -import org.eclipse.core.filebuffers.ITextFileBuffer; -import org.eclipse.core.filebuffers.ITextFileBufferManager; -import org.eclipse.core.filebuffers.LocationKind; -import org.eclipse.core.resources.IContainer; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.MultiStatus; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.SubProgressMonitor; -import org.eclipse.core.runtime.content.IContentDescription; -import org.eclipse.core.runtime.content.IContentType; -import org.eclipse.core.runtime.jobs.Job; -import org.eclipse.osgi.util.NLS; -import org.eclipse.swt.widgets.Display; -import org.eclipse.ui.PlatformUI; -import org.eclipse.wst.sse.core.internal.exceptions.MalformedInputExceptionWithDetail; -import org.eclipse.wst.sse.core.internal.format.IStructuredFormatProcessor; -import org.eclipse.wst.sse.ui.internal.FormatProcessorsExtensionReader; -import org.eclipse.wst.sse.ui.internal.Logger; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; -import org.eclipse.wst.sse.ui.internal.SSEUIPlugin; - -public class FormatActionDelegate extends ResourceActionDelegate { - - class FormatJob extends Job { - - public FormatJob(String name) { - super(name); - } - - protected IStatus run(IProgressMonitor monitor) { - IStatus status = Status.OK_STATUS; - - Object[] elements = fSelection.toArray(); - monitor.beginTask("", elements.length); //$NON-NLS-1$ - for (int i = 0; i < elements.length; i++) { - if (elements[i] instanceof IResource) { - process(new SubProgressMonitor(monitor, 1), (IResource) elements[i]); - } - else { - monitor.worked(1); - } - } - monitor.done(); - - if (fErrorStatus.getChildren().length > 0) { - status = fErrorStatus; - fErrorStatus = new MultiStatus(SSEUIPlugin.ID, IStatus.ERROR, SSEUIMessages.FormatActionDelegate_errorStatusMessage, null); //$NON-NLS-1$ - } - - return status; - } - - } - - private MultiStatus fErrorStatus = new MultiStatus(SSEUIPlugin.ID, IStatus.ERROR, SSEUIMessages.FormatActionDelegate_errorStatusMessage, null); //$NON-NLS-1$ - - protected void format(IProgressMonitor monitor, IFile file) { - if(monitor == null || monitor.isCanceled()) - return; - - try { - monitor.beginTask("", 100); - IContentDescription contentDescription = file.getContentDescription(); - monitor.worked(5); - if (contentDescription != null) { - IContentType contentType = contentDescription.getContentType(); - IStructuredFormatProcessor formatProcessor = getFormatProcessor(contentType.getId()); - if (formatProcessor != null && (monitor == null || !monitor.isCanceled())) { - String message = NLS.bind(SSEUIMessages.FormatActionDelegate_3, new String[]{file.getFullPath().toString().substring(1)}); monitor.subTask(message); - formatProcessor.setProgressMonitor(monitor); - formatProcessor.formatFile(file); - } - } - monitor.worked(95); - monitor.done(); - } catch (MalformedInputExceptionWithDetail e) { - String message = NLS.bind(SSEUIMessages.FormatActionDelegate_5, new String[]{file.getFullPath().toString()}); - fErrorStatus.add(new Status(IStatus.ERROR, SSEUIPlugin.ID, IStatus.ERROR, message, e)); - } catch (IOException e) { - String message = NLS.bind(SSEUIMessages.FormatActionDelegate_4, new String[]{file.getFullPath().toString()}); - fErrorStatus.add(new Status(IStatus.ERROR, SSEUIPlugin.ID, IStatus.ERROR, message, e)); - } catch (CoreException e) { - String message = NLS.bind(SSEUIMessages.FormatActionDelegate_4, new String[]{file.getFullPath().toString()}); - fErrorStatus.add(new Status(IStatus.ERROR, SSEUIPlugin.ID, IStatus.ERROR, message, e)); - } - } - - private Display getDisplay() { - - // Note: the workbench should always have a display - // (unless running headless), whereas Display.getCurrent() - // only returns the display if the currently executing thread - // has one. - if (PlatformUI.isWorkbenchRunning()) - return PlatformUI.getWorkbench().getDisplay(); - else - return null; - } - - protected void format(final IProgressMonitor monitor, IResource resource) { - if (resource instanceof IFile) { - final IFile file = (IFile) resource; - - // BUG 178598 - If the resource is shared, and it's possible to - // get the workbench Display, the UI thread is asked to execute the - // format of the file when it can - try { - ITextFileBufferManager manager= FileBuffers.getTextFileBufferManager(); - ITextFileBuffer buffer = null; - - try { - if(manager != null) { - manager.connect(file.getFullPath(), LocationKind.IFILE, monitor); - buffer = manager.getTextFileBuffer(resource.getFullPath(), LocationKind.IFILE); - } - - if(buffer != null && buffer.isShared()) { - Display display = getDisplay(); - display.syncExec(new Runnable() { - public void run() { - format(monitor, file); - } - }); - } - else - format(monitor, file); - } - finally { - if(manager != null) - manager.disconnect(file.getFullPath(), LocationKind.IFILE, new SubProgressMonitor(monitor, 1)); - } - } - catch(CoreException e) { - String message = NLS.bind(SSEUIMessages.FormatActionDelegate_4, new String[]{file.getFullPath().toString()}); - fErrorStatus.add(new Status(IStatus.ERROR, SSEUIPlugin.ID, IStatus.ERROR, message, e)); - } - finally { - if(monitor != null) - monitor.done(); - } - - } else if (resource instanceof IContainer) { - IContainer container = (IContainer) resource; - - try { - IResource[] members = container.members(); - monitor.beginTask("", members.length); - for (int i = 0; i < members.length; i++) { - if (monitor != null && !monitor.isCanceled()) - format(new SubProgressMonitor(monitor, 1), members[i]); - } - monitor.done(); - } catch (CoreException e) { - String message = NLS.bind(SSEUIMessages.FormatActionDelegate_4, new String[]{resource.getFullPath().toString()}); - fErrorStatus.add(new Status(IStatus.ERROR, SSEUIPlugin.ID, IStatus.ERROR, message, e)); - } - } - } - - protected IStructuredFormatProcessor getFormatProcessor(String contentTypeId) { - return FormatProcessorsExtensionReader.getInstance().getFormatProcessor(contentTypeId); - } - - protected Job getJob() { - return new FormatJob(SSEUIMessages.FormatActionDelegate_jobName); //$NON-NLS-1$ - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.sse.ui.edit.util.ResourceActionDelegate#process(org.eclipse.core.runtime.IProgressMonitor, - * org.eclipse.core.resources.IResource) - */ - protected void process(IProgressMonitor monitor, IResource resource) { - monitor.beginTask("", 100); - format(new SubProgressMonitor(monitor, 98), resource); - - try { - resource.refreshLocal(IResource.DEPTH_INFINITE, new SubProgressMonitor(monitor, 2)); - } catch (CoreException e) { - String message = NLS.bind(SSEUIMessages.FormatActionDelegate_4, new String[]{resource.getFullPath().toString()}); - fErrorStatus.add(new Status(IStatus.ERROR, SSEUIPlugin.ID, IStatus.ERROR, message, e)); - } - monitor.done(); - } - - /* (non-Javadoc) - * @see org.eclipse.wst.sse.ui.internal.actions.ResourceActionDelegate#processorAvailable(org.eclipse.core.resources.IResource) - */ - protected boolean processorAvailable(IResource resource) { - boolean result = false; - if (resource.isAccessible()) { - try { - if (resource instanceof IFile) { - IFile file = (IFile) resource; - - IStructuredFormatProcessor formatProcessor = null; - IContentDescription contentDescription = file.getContentDescription(); - if (contentDescription != null) { - IContentType contentType = contentDescription.getContentType(); - formatProcessor = getFormatProcessor(contentType.getId()); - } - if (formatProcessor != null) - result = true; - } - else if (resource instanceof IContainer) { - IContainer container = (IContainer) resource; - IResource[] members; - members = container.members(); - for (int i = 0; i < members.length; i++) { - boolean available = processorAvailable(members[i]); - - if (available) { - result = true; - break; - } - } - } - } - catch (CoreException e) { - Logger.logException(e); - } - } - - return result; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/actions/ResourceActionDelegate.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/actions/ResourceActionDelegate.java deleted file mode 100644 index 290792808e..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/actions/ResourceActionDelegate.java +++ /dev/null @@ -1,104 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.actions; - -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.jobs.Job; -import org.eclipse.jface.action.IAction; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.ui.IActionDelegate; -import org.eclipse.ui.IWorkbenchPage; -import org.eclipse.ui.IWorkbenchPart; -import org.eclipse.ui.IWorkbenchWindow; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.progress.IWorkbenchSiteProgressService; - -public class ResourceActionDelegate implements IActionDelegate { - protected IStructuredSelection fSelection; - - private IWorkbenchSiteProgressService getActiveProgressService() { - IWorkbenchSiteProgressService service = null; - if (PlatformUI.isWorkbenchRunning()) { - IWorkbenchWindow activeWorkbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); - if (activeWorkbenchWindow != null) { - IWorkbenchPage activePage = activeWorkbenchWindow.getActivePage(); - if (activePage != null) { - IWorkbenchPart activePart = activePage.getActivePart(); - if (activePart != null) { - service = (IWorkbenchSiteProgressService) activePart.getSite().getAdapter(IWorkbenchSiteProgressService.class); - } - } - } - } - return service; - } - - protected Job getJob() { - // ResourceActionDelegate does not create background job - // subclass creates the background job for the action - return null; - } - - protected boolean processorAvailable(IResource resource) { - // ResourceActionDelegate returns false by default - // subclass returns true if processor is available; false otherwise - return false; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction) - */ - public void run(IAction action) { - if (fSelection != null && !fSelection.isEmpty()) { - Job job = getJob(); - if (job != null) { - IWorkbenchSiteProgressService progressService = getActiveProgressService(); - if (progressService != null) { - progressService.schedule(job); - } - else { - job.schedule(); - } - } - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action.IAction, - * org.eclipse.jface.viewers.ISelection) - */ - public void selectionChanged(IAction action, ISelection selection) { - if (selection instanceof IStructuredSelection) { - fSelection = (IStructuredSelection) selection; - boolean available = false; - - Object[] elements = fSelection.toArray(); - for (int i = 0; i < elements.length; i++) { - if (elements[i] instanceof IResource) { - available = processorAvailable((IResource) elements[i]); - - if (available) - break; - } - } - - action.setEnabled(available); - } - } - -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/actions/StructuredTextEditorActionConstants.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/actions/StructuredTextEditorActionConstants.java deleted file mode 100644 index 286d8cc604..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/actions/StructuredTextEditorActionConstants.java +++ /dev/null @@ -1,48 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.actions; - - - -public interface StructuredTextEditorActionConstants { - public final static String ACTION_NAME_ADD_BLOCK_COMMENT = "AddBlockComment";//$NON-NLS-1$ - public final static String ACTION_NAME_CLEANUP_DOCUMENT = "CleanupDocument";//$NON-NLS-1$ - public final static String ACTION_NAME_COMMENT = "Comment";//$NON-NLS-1$ - public final static String ACTION_NAME_CONTENTASSIST_CONTEXT_INFORMATION = "ContentAssistContextInformation";//$NON-NLS-1$ - public final static String ACTION_NAME_CONTENTASSIST_PROPOSALS = "ContentAssistProposals";//$NON-NLS-1$ - public final static String ACTION_NAME_FIND_OCCURRENCES = "FindOccurrences"; //$NON-NLS-1$ - public final static String ACTION_NAME_FORMAT_ACTIVE_ELEMENTS = "FormatActiveElements";//$NON-NLS-1$ - public final static String ACTION_NAME_FORMAT_DOCUMENT = "FormatDocument";//$NON-NLS-1$ - public final static String ACTION_NAME_MANAGE_BREAKPOINTS = "ManageBreakpoints";//$NON-NLS-1$ - public final static String ACTION_NAME_OPEN_FILE = "OpenFileFromSource";//$NON-NLS-1$ - public final static String ACTION_NAME_REMOVE_BLOCK_COMMENT = "RemoveBlockComment";//$NON-NLS-1$ - public final static String ACTION_NAME_STRUCTURE_SELECT_ENCLOSING = "StructureSelectEnclosing";//$NON-NLS-1$ - public final static String ACTION_NAME_STRUCTURE_SELECT_HISTORY = "StructureSelectHistory";//$NON-NLS-1$ - public final static String ACTION_NAME_STRUCTURE_SELECT_NEXT = "StructureSelectNext";//$NON-NLS-1$ - public final static String ACTION_NAME_STRUCTURE_SELECT_PREVIOUS = "StructureSelectPrevious";//$NON-NLS-1$ - public final static String ACTION_NAME_TOGGLE_COMMENT = "ToggleComment";//$NON-NLS-1$ - public final static String ACTION_NAME_UNCOMMENT = "Uncomment";//$NON-NLS-1$ - public final static String ACTION_NAME_GOTO_MATCHING_BRACKET = "GotoMatchingBracket";//$NON-NLS-1$ - public final static String ACTION_NAME_SHOW_OUTLINE = "ShowQuickOutline"; //$NON-NLS-1$ - - /** - * @deprecated use UNDERSCORE instead - */ - public final static String DOT = ".";//$NON-NLS-1$ - public final static String UNDERSCORE = "_"; //$NON-NLS-1$ - - public final static String GROUP_NAME_MENU_ADDITIONS = "MenuAdditions";//$NON-NLS-1$ - public final static String GROUP_NAME_TOOLBAR_ADDITIONS = "ToolbarAdditions";//$NON-NLS-1$ - - public final static String STATUS_CATEGORY_OFFSET = "Offset";//$NON-NLS-1$ -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/comment/BlockCommentingStrategy.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/comment/BlockCommentingStrategy.java deleted file mode 100644 index 5dade3e41b..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/comment/BlockCommentingStrategy.java +++ /dev/null @@ -1,138 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.comment; - -import java.util.List; - -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ITypedRegion; -import org.eclipse.jface.text.Region; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion; -import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegion; -import org.eclipse.wst.sse.ui.internal.Logger; - -/** - * <p>Represents a Block Comment commenting strategy</p> - */ -public class BlockCommentingStrategy extends CommentingStrategy { - /** the prefix of the block comment associated with this strategy */ - private String fPrefix; - - /** the suffix of the block comment associated with this strategy */ - private String fSuffix; - - /** - * @param prefix the prefix of the block comment associated with this strategy - * @param suffix the suffix of the block comment associated with this strategy - */ - public BlockCommentingStrategy(String prefix, String suffix) { - super(); - this.fPrefix = prefix; - this.fSuffix = suffix; - } - - /** - * <p>When applying a block comment it also removes any block comments associated - * with this strategy that would now be enclosed by the new block comment</p> - * - * @see org.eclipse.wst.sse.ui.internal.comment.CommentingStrategy#apply( - * org.eclipse.wst.sse.core.internal.provisional.IStructuredModel, int, int) - */ - public void apply(IStructuredDocument document, int offset, int length) throws BadLocationException { - int commentPrefixOffset = offset; - int commentSuffixOffset = commentPrefixOffset + length; - - try { - document.replace(commentSuffixOffset, 0, " " + this.fSuffix); //$NON-NLS-1$ - this.remove(document, commentPrefixOffset + this.fPrefix.length(), length, false); - document.replace(commentPrefixOffset, 0, this.fPrefix + " "); //$NON-NLS-1$ - } - catch (BadLocationException e) { - Logger.log(Logger.WARNING_DEBUG, e.getMessage(), e); - } - } - - /** - * @see org.eclipse.wst.sse.ui.internal.comment.CommentingStrategy#remove( - * org.eclipse.jface.text.IDocument, int, int) - */ - public void remove(IStructuredDocument document, int offset, int length, boolean removeEnclosing) throws BadLocationException { - IRegion region = new Region(offset, length); - ITypedRegion[] typedRegions = document.computePartitioning(region.getOffset(), region.getLength()); - List commentRegions = this.getAssociatedCommentedRegions(typedRegions); - - //remove in reverse order as to not effect offset of other regions - for(int i = commentRegions.size()-1; i >= 0; --i) { - try { - //get the comment region - ITypedRegion typedRegion = (ITypedRegion)commentRegions.get(i); - IRegion commentRegion = new Region(typedRegion.getOffset(), typedRegion.getLength()); - - /* because of the nature of structured regions the comment region could actually be a - * sub region that needs to be drilled down too - */ - if(!this.alreadyCommenting(document, commentRegion)) { - IStructuredDocumentRegion structuredRegion = - document.getRegionAtCharacterOffset(commentRegion.getOffset()); - - commentRegion = new Region(structuredRegion.getStartOffset(), structuredRegion.getLength()); - - if(!this.alreadyCommenting(document, commentRegion)) { - ITextRegion enclosedRegion = structuredRegion.getRegionAtCharacterOffset(typedRegion.getOffset()); - int enclosedOffset = structuredRegion.getStartOffset(enclosedRegion); - commentRegion = new Region(enclosedOffset, structuredRegion.getTextEndOffset(enclosedRegion)-enclosedOffset); - } - } - - //at this point should have found the comment region, if not there is an issue - if(this.alreadyCommenting(document, commentRegion)) { - String regionContent = document.get(commentRegion.getOffset(), commentRegion.getLength()); - - //if found the comment prefix and suffix then uncomment, otherwise log error - int commentPrefixOffset = commentRegion.getOffset() + regionContent.indexOf(this.fPrefix); - int commentSuffixOffset = commentRegion.getOffset(); - commentSuffixOffset += regionContent.lastIndexOf(this.fSuffix); - - //remove comment block depending on if its an enclosing comment block and weather that is allowed - if(removeEnclosing || (commentPrefixOffset >= offset && commentSuffixOffset <= offset+length)) { - uncomment(document, commentPrefixOffset, this.fPrefix, commentSuffixOffset, this.fSuffix); - } - } else { - Logger.log(Logger.ERROR, - "BlockCommentingStrategy#remove could not find the commenting region to remove"); //$NON-NLS-1$ - } - } catch(BadLocationException e) { - Logger.logException("This should only ever happen if something has gone wrong with the partitioning", e); //$NON-NLS-1$ - } - } - } - - /** - * <p>A region is already commented by this strategy if it starts with the strategy's associated - * prefix and ends with its associated suffix, ignoring any trailing or leading whitespace</p> - * - * @see org.eclipse.wst.sse.ui.internal.comment.CommentingStrategy#alreadyCommenting( - * org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IRegion) - */ - public boolean alreadyCommenting(IStructuredDocument document, IRegion region) throws BadLocationException { - String regionContent = document.get(region.getOffset(), region.getLength()).trim(); - return regionContent.startsWith(this.fPrefix) && regionContent.endsWith(this.fSuffix); - } - - /** - * @see org.eclipse.wst.sse.ui.internal.comment.CommentingStrategy#clone() - */ - public Object clone() { - return new BlockCommentingStrategy(this.fPrefix, this.fSuffix); - } -}
\ No newline at end of file diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/comment/CommentingStrategy.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/comment/CommentingStrategy.java deleted file mode 100644 index c46248c4fd..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/comment/CommentingStrategy.java +++ /dev/null @@ -1,355 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.comment; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ITypedRegion; -import org.eclipse.jface.text.Region; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument; -import org.eclipse.wst.sse.ui.internal.Logger; - -/** - * <p>Defines a commenting strategy defined by the <code>org.eclipse.wst.sse.ui.commentinStrategy</code> - * extension point and tracked by the {@link CommentingStrategyRegistry}. Though it is important to - * note it is not a one to one relationship of {@link CommentingStrategy}s to extensions, there is actually - * one {@link CommentingStrategy} for each content type defined for each - * <code>org.eclipse.wst.sse.ui.commentinStrategy</code> extension.<p> - * - * <p>The expected use case is that a {@link CommentingStrategy} is created off the basic configuration - * of the extension point and then cloned for each associated content type and then each clone has - * its partition information set using {@link #setPartitionInformation}. - * Then the {@link CommentingStrategyRegistry} can be used to retrieve applicable {@link CommentingStrategy}s - * and apply them to documents.</p> - * - * <p>It is important to note that any instance of a {@link CommentingStrategy} is only valid for a specific - * content type ID but this relationship is tracked by the {@link CommentingStrategyRegistry} and not by - * the strategy itself. Thus any reference to the strategy being valid for specific or general partition - * types is implying it is already only valid for a specific content type</p> - */ -public abstract class CommentingStrategy { - /** <code>true</code> if this strategy has any required partition types, <code>false</code> otherwise */ - private boolean fHasRequiredPartitionTypes; - - /** - * <p>required partition type IDs that must be seen for this strategy to be valid, the number of them - * that must be seen for the strategy to be valid is determined by {@link #fRequireAllRequiredPartitionTypes} - * this requirement is waved if the optional {@link #fAssociatedCommentPartitionTypeID} is specified and - * present because this strategy must be valid if its {@link #fAssociatedCommentPartitionTypeID} is present</p> - * - * @see #fRequireAllRequiredPartitionTypes - * @see #fAssociatedCommentPartitionTypeID - */ - private List fRequriedPartitionTypeIDs; - - /** - * <p>if <code>true</code> then {@link #fAllowablePartitionTypeIDs} is ignored because - * this strategy is valid for any partition type, if <code>false</code> then this - * strategy is only valid for those partition types listed in {@link #fAllowablePartitionTypeIDs}</p> - * - * @see #fAllowablePartitionTypeIDs - */ - private boolean fAllPartitionTypesAllowable; - - /** - * <p>the partition types that this strategy is valid for, it is also automatically valid for - * any partition types listed in {@link #fRequriedPartitionTypeIDs} and the optionally - * specified {@link #fAssociatedCommentPartitionTypeID}</p> - * - * @see #fAllPartitionTypesAllowable - * @see #fRequriedPartitionTypeIDs - * @see #fAssociatedCommentPartitionTypeID - */ - private List fAllowablePartitionTypeIDs; - - /** - * an optional associated comment partition type ID, if this partition type is seen then the - * the {@link #fRequriedPartitionTypeIDs} requirement is waved as to weather this strategy is - * valid or not - * - * @see #fRequriedPartitionTypeIDs - */ - private String fAssociatedCommentPartitionTypeID; - - /** - * <p>Default constructor, the specific initialization is done by - * {@link #setPartitionInformation}</p> - */ - public CommentingStrategy() { - this.fAssociatedCommentPartitionTypeID = null; - this.fRequriedPartitionTypeIDs = Collections.EMPTY_LIST; - this.fAllowablePartitionTypeIDs = Collections.EMPTY_LIST; - this.fHasRequiredPartitionTypes = false; - this.fAllPartitionTypesAllowable = false; - } - - /** - * <p>Used to set up the partition information for this strategy</p> - * <p>This information is used to determine if a strategy is valid for a set of - * {@link ITypedRegion}s.</p> - * - * @param allowablePartitionTypeIDs the partition types this strategy is valid for, the strategy will also - * be considered valid for any of the required partition types - * @param allPartitionTypesAllowable if <code>true</code> then this strategy is valid for any partition types - * thus ignoring the <code>allowablePartitionTypeIDs</code>, <code>false</code> otherwise - * @param requiredPartitionTypeIDs partition type IDs that must be seen for this strategy to be valid, there - * are exceptions to this rule, see {@link #isApplicableFor(ITypedRegion[])} - * @param requireAllRequiredPartitionTypes <code>true</code> if all of the <code>requiredPartitionTypeIDs must - * be seen for this strategy to be valid, <code>false</code> otherwise, there are exceptions to these rules, see - * {@link #isApplicableFor(ITypedRegion[])} - * @param associatedCommentPartitionTypeID optional comment partition type associated with this strategy, - * maybe <code>null</code> - * - * @see #isApplicableFor(ITypedRegion[]) - */ - protected final void setPartitionInformation(List allowablePartitionTypeIDs, boolean allPartitionTypesAllowable, - List requiredPartitionTypeIDs, String associatedCommentPartitionTypeID) { - - this.fAllPartitionTypesAllowable = allPartitionTypesAllowable; - - this.fRequriedPartitionTypeIDs = requiredPartitionTypeIDs; - if(this.fRequriedPartitionTypeIDs == null) { - this.fRequriedPartitionTypeIDs = Collections.EMPTY_LIST; - } - - this.fHasRequiredPartitionTypes = this.fRequriedPartitionTypeIDs.size() != 0; - - this.fAllowablePartitionTypeIDs = allowablePartitionTypeIDs; - if(this.fAllowablePartitionTypeIDs == null) { - this.fAllowablePartitionTypeIDs = Collections.EMPTY_LIST; - } - - this.fAssociatedCommentPartitionTypeID = associatedCommentPartitionTypeID; - } - - /** - * <p>Applies this strategy to the given model starting at the given offset for the given length</p> - * - * @param document {@link IStructuredDocument} to apply this strategy too - * @param offset the offset to start this comment at - * @param length the length of the region to apply this comment too - * - * @throws BadLocationException it is not the fault of the strategy if callers passes a bad - * <code>offset</code> and/or <code>length</code> for the given <code>model</code> - */ - public abstract void apply(IStructuredDocument document, int offset, int length) throws BadLocationException; - - /** - * <p>Remove any comments associated with this strategy from the given model for the given offset to - * the given length. Weather a comment surrounding the given range should be removed can also be - * specified</p> - * - * @param document {@link IStructuredDocument} to remove comments associated with this strategy from - * @param offset the location to start removing comments associated with this strategy from - * @param length the length of the region to remove associated comments from - * @param removeEnclosing weather a comment should be removed if it incloses the region specified - * by the given <code>offset</code> and <code>length</code> - * - * @throws BadLocationException it is not the fault of the strategy if callers passes a bad - * <code>offset</code> and/or <code>length</code> for the given <code>model</code> - */ - public abstract void remove(IStructuredDocument document, int offset, int length, boolean removeEnclosing) throws BadLocationException; - - /** - * <p>Determines if the given region is a comment region commented by this strategy.</p> - * - * @param document {@link IStructuredDocument} containing the given <code>region</code> - * @param region determine if this region is a comment region commented by this strategy - * @return <code>true</code> if the given <code>region</code> has already been - * commented by this strategy, <code>false</code> otherwise - * - * @throws BadLocationException it is not the fault of the strategy if callers passes a bad - * <code>offset</code> and/or <code>length</code> for the given <code>model</code> - */ - public abstract boolean alreadyCommenting(IStructuredDocument document, IRegion region) throws BadLocationException; - - /** - * <p>Implementers should return a copy of themselves</p> - * <p>Allows the {@link CommentingStrategyRegistry} to create a {@link CommentingStrategy} for - * each of its associated content types.</p> - * - * @return implementers should return an object of type {@link CommentingStrategy} - * - * @see java.lang.Object#clone() - */ - public abstract Object clone(); - - /** - * <p>Determines if this strategy is applicable for the given regions for either commenting or un-commenting. - * For this strategy to be applicable the given regions must contain at least one or all of the - * {@link #fRequriedPartitionTypeIDs} (depending on the value of {@link #fRequireAllRequiredPartitionTypes}) - * or contain at least one region of type {@link #fAssociatedCommentPartitionTypeID}. Also if the value of - * {@link #fAllPartitionTypesAllowable} is <code>false</code> the given regions must all be of type - * {@link #fAllowablePartitionTypeIDs} and/or {@link #fRequriedPartitionTypeIDs} and/or - * {@link #fAssociatedCommentPartitionTypeID} otherwise the regions can be of any type except for they still - * must beet the required partition type requirements</p> - * - * @param regions determine if this strategy is applicable for these regions - * @return <code>true</code> if this strategy is applicable for the given <code>regions</code> - * <code>false</code> otherwise. - */ - public final boolean isApplicableFor(ITypedRegion[] regions) { - List partitionTypeIDs = getPartitionTypeIDs(regions); - - boolean foundAssociatedCommentPartitions = false; - if(this.fAssociatedCommentPartitionTypeID != null) { - foundAssociatedCommentPartitions = partitionTypeIDs.contains(this.fAssociatedCommentPartitionTypeID); - if(foundAssociatedCommentPartitions) { - //remove all instances of the comment partition type - boolean removed; - do { - removed = partitionTypeIDs.remove(this.fAssociatedCommentPartitionTypeID); - } while(removed); - } - } - - //determine if required partitions requirements are met - boolean requiredPartitionsRequirementsMet = !this.fHasRequiredPartitionTypes || - partitionTypeIDs.removeAll(this.fRequriedPartitionTypeIDs); - - //determine if allowable partitions requirements are met - boolean allowablePartitionsRequirementsMet = false; - if(this.fAllPartitionTypesAllowable) { - allowablePartitionsRequirementsMet = true; - } else { - partitionTypeIDs.removeAll(this.fAllowablePartitionTypeIDs); - - //at this point all required partitions and allowable partitions have been removed - allowablePartitionsRequirementsMet = partitionTypeIDs.size() == 0; - } - - return (requiredPartitionsRequirementsMet || foundAssociatedCommentPartitions) && allowablePartitionsRequirementsMet; - } - - /** - * <p>Convenience method to take a list of regions and create one encompassing region to pass to - * {@link #alreadyCommenting(IDocument, IRegion)}</p> - * - * @param document {@link IDocument} that contains the given <code>regions</code> - * @param regions {@link IRegion}s to combine into one region and pass onto - * {@link #alreadyCommenting(IDocument, IRegion)} - * - * @return the result of a call to {@link #alreadyCommenting(IDocument, IRegion)} combining - * all of the given <code>regions</code> into one region - * - * @throws BadLocationException it is not the fault of the strategy if callers passes a bad - * <code>offset</code> and/or <code>length</code> for the given <code>model</code> - */ - public final boolean alreadyCommenting(IStructuredDocument document, IRegion[] regions) throws BadLocationException { - boolean alreadyCommenting = false; - if(regions != null && regions.length > 0) { - //create one region spanning all the given regions - int offset = regions[0].getOffset(); - int length = regions[regions.length-1].getOffset() + - regions[regions.length-1].getLength() - offset; - - IRegion region = new Region(offset, length); - alreadyCommenting = this.alreadyCommenting(document, region); - } - - return alreadyCommenting; - } - /** - * <p>Given a list of {@link ITypedRegion}s returns the sub set of that list that - * are of the comment region type associated with this strategy</p> - * - * @param typedRegions {@link ITypedRegion}s to filter down to only the comment regions - * associated with this strategy - * - * @return {@link List} of {@link ITypedRegion}s from the given <code>typedRegions</code> - * that are of the comment partition type associated with this strategy - */ - protected List getAssociatedCommentedRegions(ITypedRegion[] typedRegions) { - List commentedRegions = new ArrayList(); - - for(int i = 0; i < typedRegions.length; ++i) { - if(typedRegions[i].getType().equals(this.fAssociatedCommentPartitionTypeID)) { - commentedRegions.add(typedRegions[i]); - } - } - - return commentedRegions; - } - - /** - * <p>Given a list of {@link ITypedRegion}s returns a list of the partition - * type IDs taken from the given regions.</p> - * - * @param regions {@link ITypedRegion}s to get the partition type IDs from - * @return {@link List} of the partition type IDs taken from the given <code>regions</code> - */ - private static List getPartitionTypeIDs(ITypedRegion[] regions) { - List partitionTypes = new ArrayList(regions.length); - for(int i = 0; i < regions.length; ++i) { - partitionTypes.add(regions[i].getType()); - } - - return partitionTypes; - } - - /** - * <p>This method modifies the given document to remove the given comment - * prefix at the given comment prefix offset and the given comment - * suffix at the given comment suffix offset. In the case of removing - * a line comment that does not have a suffix, pass <code>null</code> - * for the comment suffix and it and its associated offset will - * be ignored.</p> - * - * <p><b>NOTE:</b> it is a good idea if a model is at hand when calling this to - * warn the model of an impending update</p> - * - * @param document the document to remove the comment from - * @param commentPrefixOffset the offset of the comment prefix - * @param commentSuffixOffset the offset of the comment suffix - * (ignored if <code>commentSuffix</code> is <code>null</code>) - * @param commentPrefix the prefix of the comment to remove from its associated given offset - * @param commentSuffix the suffix of the comment to remove from its associated given offset, - * or null if there is not suffix to remove for this comment - */ - protected static void uncomment(IDocument document, int commentPrefixOffset, String commentPrefix, - int commentSuffixOffset, String commentSuffix) { - - try { - //determine if there is a space after the comment prefix that should also be removed - int commentPrefixLength = commentPrefix.length(); - String postCommentPrefixChar = document.get(commentPrefixOffset + commentPrefix.length(), 1); - if(postCommentPrefixChar.equals(" ")) { - commentPrefixLength++; - } - - //remove the comment prefix - document.replace(commentPrefixOffset, commentPrefixLength, ""); //$NON-NLS-1$ - - if(commentSuffix != null) { - commentSuffixOffset -= commentPrefixLength; - - //determine if there is a space before the comment suffix that should also be removed - int commentSuffixLength = commentSuffix.length(); - String preCommentSuffixChar = document.get(commentSuffixOffset-1, 1); - if(preCommentSuffixChar.equals(" ")) { - commentSuffixLength++; - commentSuffixOffset--; - } - - //remove the comment suffix - document.replace(commentSuffixOffset, commentSuffixLength, ""); //$NON-NLS-1$ - } - } - catch (BadLocationException e) { - Logger.log(Logger.WARNING_DEBUG, e.getMessage(), e); - } - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/comment/CommentingStrategyRegistry.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/comment/CommentingStrategyRegistry.java deleted file mode 100644 index dbc9582541..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/comment/CommentingStrategyRegistry.java +++ /dev/null @@ -1,351 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.comment; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IConfigurationElement; -import org.eclipse.core.runtime.IExtensionRegistry; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.InvalidRegistryObjectException; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.content.IContentType; -import org.eclipse.jface.text.ITypedRegion; -import org.eclipse.wst.sse.ui.internal.Logger; -import org.eclipse.wst.sse.ui.internal.SSEUIPlugin; - -/** - * <p>The registry of {@link CommentingStrategy}s defined by the <code>org.eclipse.wst.sse.ui.commentinStrategy</code> - * extension point.</p> - */ -public class CommentingStrategyRegistry { - /** The extension schema name of the extension point */ - private static final String EXTENSION_POINT = "commentingStrategy"; //$NON-NLS-1$ - - /** The extension schema name of proposal block comment child elements. */ - private static final String ELEM_PROPOSAL_BLOCK_COMMENTING_STRATEGY = "blockCommentingStrategy"; //$NON-NLS-1$ - - /** The extension schema name of proposal line comment child elements. */ - private static final String ELEM_PROPOSAL_LINE_COMMENTING_STRATEGY = "lineCommentingStrategy"; //$NON-NLS-1$ - - /** The extension schema name of the content type child elements. */ - private static final String ELEM_CONTENT_TYPE = "contentType"; //$NON-NLS-1$ - - /** The extension schema name of the required partition types child elements */ - private static final String ELEM_REQUIRED_PARTITION_TYPES= "requiredPartitionTypes"; //$NON-NLS-1$ - - /** The extension schema name of the allowable partition types child elements */ - private static final String ELEM_ALLOWABLE_PARTITION_TYPES= "allowablePartitionTypes"; //$NON-NLS-1$ - - /** The extension schema name of partition type child elements */ - private static final String ELEM_PARTITION_TYPE= "partitionType"; //$NON-NLS-1$ - - /** The extension schema name of the prefix attribute */ - private static final String ATTR_PREFIX = "prefix"; //$NON-NLS-1$ - - /** The extension schema name of the suffix attribute */ - private static final String ATTR_SUFFIX = "suffix"; //$NON-NLS-1$ - - /** The extension schema name of the associatedCommentPartitionTypeID attribute */ - private static final String ATTR_ASSOCIATED_COMMENT_PARTITION_TPYPE_ID = "associatedCommentPartitionTypeID"; //$NON-NLS-1$ - - /** The extension schema name of the anyPartitionType attribute */ - private static final String ATTR_ANY_PARTITION_TYPE = "anyPartitionType"; //$NON-NLS-1$ - - /** The extension schema name for ID attribute */ - private static final String ATTR_ID= "id"; //$NON-NLS-1$ - - /** the singleton instance of the registry */ - private static CommentingStrategyRegistry fSingleton = null; - - /** <code>true</code> if this registry has been loaded. */ - private boolean fLoaded; - - /** - * <p>Registry of content type IDs to {@link BlockCommentingStrategy}s</p> - * - * <code>{@link Map}<{@link String}, {@link List}<{@link BlockContentType}>></code> - * <ul> - * <li><b>key:</b> content type ID</li> - * <li><b>value:</b> {@link List} of associated {@link BlockContentType}s</li> - * <ul> - */ - private Map fBlockCommentTypes; - - /** - * <p>Registry of content type IDs to {@link LineCommentingStrategy}s</p> - * - * <code>{@link Map}<{@link String}, {@link List}<{@link LineContentType}>></code> - * <ul> - * <li><b>key:</b> content type ID</li> - * <li><b>value:</b> {@link List} of associated {@link LineContentType}s</li> - * <ul> - */ - private Map fLineCommentTypes; - - /** - * @return the single instance of the {@link CommentingStrategyRegistry} - */ - public static synchronized CommentingStrategyRegistry getDefault() { - if(fSingleton == null) { - fSingleton = new CommentingStrategyRegistry(); - } - - return fSingleton; - } - - /** - * Singleton constructor for the registry - */ - private CommentingStrategyRegistry() { - this.fLoaded = false; - this.fBlockCommentTypes = new HashMap(); - this.fLineCommentTypes = new HashMap(); - } - - /** - * @param contentTypeID get only {@link BlockCommentingStrategy}s associated with this content type - * @param regions get only {@link BlockCommentingStrategy}s associated with these types of regions - * @return all the {@link BlockCommentingStrategy}s associated with the given content type and regions - */ - public CommentingStrategy getBlockCommentingStrategy(String contentTypeID, ITypedRegion[] regions) { - return getCommentingStrategy(contentTypeID, regions, this.fBlockCommentTypes); - } - - /** - * @param contentTypeID get only {@link LineCommentingStrategy}s associated with this content type - * @param regions get only {@link LineCommentingStrategy}s associated with these types of regions - * @return all the {@link LineCommentingStrategy}s associated with the given content type and regions - */ - public CommentingStrategy getLineCommentingStrategy(String contentTypeID, ITypedRegion[] regions) { - return getCommentingStrategy(contentTypeID, regions, this.fLineCommentTypes); - } - - /** - * <p>get all the {@link CommentingStrategy}s associated with the given content type and regions - * from the given registry</p> - * - * @param contentTypeID get only {@link CommentingStrategy}s associated with this content type - * @param regions get only {@link CommentingStrategy}s associated with these types of regions - * @param registry get the {@link CommentingStrategy}s from this registry - * @return all the {@link CommentingStrategy}s associated with the given content type and regions - * from the given registry - */ - private CommentingStrategy getCommentingStrategy(String contentTypeID, ITypedRegion[] regions, Map registry) { - ensureExtensionPointRead(); - - CommentingStrategy match = null; - IContentType contentType = Platform.getContentTypeManager().getContentType(contentTypeID); - - /* get all the commenting strategies for the given content type id, - * including those registered for parent content types - */ - List possibleCommentingStrategies = new ArrayList(); - while(contentType != null) { - List contentTypeCommentingStrategies = (List)registry.get(contentType.getId()); - if(contentTypeCommentingStrategies != null && contentTypeCommentingStrategies.size() > 0) { - possibleCommentingStrategies.addAll(contentTypeCommentingStrategies); - } - contentType = contentType.getBaseType(); - } - - /* find the commenting strategy applicable for the given regions, - * because strategies were added starting from the most specific - * content type first, the most specific strategy will always be chosen - */ - for(int i = 0; i < possibleCommentingStrategies.size() && match == null; ++i) { - CommentingStrategy commentType = (CommentingStrategy)possibleCommentingStrategies.get(i); - if(commentType.isApplicableFor(regions)) { - match = commentType; - } - } - - return match; - } - - /** - * <p>Ensures that the extensions are read and this registry is built</p> - */ - private void ensureExtensionPointRead() { - if(!fLoaded) { - load(); - fLoaded = true; - } - } - - /** - * <p>Load the extension points into the registry</p> - */ - private void load() { - IExtensionRegistry extensionRegistry = Platform.getExtensionRegistry(); - List extensionElements = new ArrayList(Arrays.asList(extensionRegistry.getConfigurationElementsFor(SSEUIPlugin.ID, EXTENSION_POINT))); - - //for each extension - for (Iterator iter= extensionElements.iterator(); iter.hasNext();) { - IConfigurationElement element = (IConfigurationElement) iter.next(); - try { - CommentingStrategy newCommentingStrategy = null; - Map commentingStrategyRegistry = null; - //either a block or line commenting strategy - if(element.getName().equals(ELEM_PROPOSAL_BLOCK_COMMENTING_STRATEGY)) { - String prefix = element.getAttribute(ATTR_PREFIX); - checkExtensionAttributeNotNull(prefix, ATTR_PREFIX, element); - - String suffix = element.getAttribute(ATTR_SUFFIX); - checkExtensionAttributeNotNull(suffix, ATTR_SUFFIX, element); - - if(prefix != null && suffix != null) { - newCommentingStrategy = new BlockCommentingStrategy(prefix, suffix); - commentingStrategyRegistry = this.fBlockCommentTypes; - } - } else if(element.getName().equals(ELEM_PROPOSAL_LINE_COMMENTING_STRATEGY)) { - String prefix = element.getAttribute(ATTR_PREFIX); - checkExtensionAttributeNotNull(prefix, ATTR_PREFIX, element); - - if(prefix != null) { - newCommentingStrategy = new LineCommentingStrategy(prefix); - commentingStrategyRegistry = this.fLineCommentTypes; - } - } - - //add the new strategy to the registry - if(commentingStrategyRegistry != null && newCommentingStrategy != null) { - addCommentingStrategyToRegistry(element, commentingStrategyRegistry, newCommentingStrategy); - } else { - Logger.log(Logger.WARNING, "Invalid CommentingStrategy extension: " + element); //$NON-NLS-1$ - } - } catch (CoreException e) { - Logger.logException(e); - } catch (InvalidRegistryObjectException x) { - /* Element is not valid any longer as the contributing plug-in was unloaded or for - * some other reason. Do not include the extension in the list and log it - */ - String message = "The extension ''" + element.toString() + "'' is invalid."; //$NON-NLS-1$ //$NON-NLS-2$ - IStatus status= new Status(IStatus.WARNING, SSEUIPlugin.ID, IStatus.WARNING, message, x); - Logger.log(status); - } - } - } - - /** - * <p>Checks that the given attribute value is not <code>null</code>.</p> - * - * @param value the object to check if not null - * @param attribute the attribute - * - * @throws InvalidRegistryObjectException if the registry element is no longer valid - * @throws CoreException if <code>value</code> is <code>null</code> - */ - private static void checkExtensionAttributeNotNull(Object value, String attribute, - IConfigurationElement element) throws InvalidRegistryObjectException, CoreException { - - if (value == null) { - String message = "The extension \"" + element.getDeclaringExtension().getUniqueIdentifier() + //$NON-NLS-1$ - "\" from plug-in \"" + element.getContributor().getName() + //$NON-NLS-1$ - "\" did not specify a value for the required \"" + attribute + //$NON-NLS-1$ - "\" attribute for the element \"" + element.getName() + "\". Disabling the extension."; //$NON-NLS-1$ //$NON-NLS-2$ - IStatus status= new Status(IStatus.WARNING, SSEUIPlugin.ID, IStatus.OK, message, null); - throw new CoreException(status); - } - } - - /** - * <p>Using the content type element children of the given element add a copy of the given - * base commenting strategy to the given registry</p> - * - * @param element a {@link IConfigurationElement} with contentType element children - * @param commentingStrategyRegistry {@link Map} of content type ids to {@link CommentingStrategy}s to register - * the given {@link CommentingStrategy} with based on the <code>element</code> - * @param baseCommentingStrategy {@link CommentingStrategy} that will be cloned and configured for each - * content type in the given <code>element</code> - */ - private static void addCommentingStrategyToRegistry(IConfigurationElement element, - Map commentingStrategyRegistry, CommentingStrategy baseCommentingStrategy) { - - //get all the content type elements - IConfigurationElement[] contentTypeElements = element.getChildren(ELEM_CONTENT_TYPE); - if(contentTypeElements.length > 0) { - for(int contentTypeIndex = 0; contentTypeIndex < contentTypeElements.length; ++contentTypeIndex) { - try { - String contentTypeID = contentTypeElements[contentTypeIndex].getAttribute(ATTR_ID); - checkExtensionAttributeNotNull(contentTypeID, ATTR_ID, contentTypeElements[contentTypeIndex]); - - List commentTypes = (List)commentingStrategyRegistry.get(contentTypeID); - if(commentTypes == null) { - commentTypes = new ArrayList(); - commentingStrategyRegistry.put(contentTypeID, commentTypes); - } - - //this element is required - List allowablePartitionTypeIDs = new ArrayList(); - IConfigurationElement[] allowablePartitionTypes = - contentTypeElements[contentTypeIndex].getChildren(ELEM_ALLOWABLE_PARTITION_TYPES); - boolean anyPartitionType = false; - //determine anyPartitionType attribute value - String anyPartitionTypeValue = allowablePartitionTypes[0].getAttribute(ATTR_ANY_PARTITION_TYPE); - if(anyPartitionTypeValue != null) { - anyPartitionType = Boolean.valueOf(anyPartitionTypeValue).booleanValue(); - } - - //get the optional partition types - allowablePartitionTypes = allowablePartitionTypes[0].getChildren(ELEM_PARTITION_TYPE); - if(allowablePartitionTypes.length > 0) { - for (int partitionTypeIndex = 0; partitionTypeIndex < allowablePartitionTypes.length; ++partitionTypeIndex) { - String partitionTypeID = allowablePartitionTypes[partitionTypeIndex].getAttribute(ATTR_ID); - checkExtensionAttributeNotNull(partitionTypeID, ATTR_ID, allowablePartitionTypes[partitionTypeIndex]); - - allowablePartitionTypeIDs.add(partitionTypeID); - } - } - - //this element is optional - List requiredPartitionTypeIDs = new ArrayList(); - IConfigurationElement[] requiredPartitionTypes = - contentTypeElements[contentTypeIndex].getChildren(ELEM_REQUIRED_PARTITION_TYPES); - if(requiredPartitionTypes.length > 0) { - //get the required partition types - requiredPartitionTypes = requiredPartitionTypes[0].getChildren(ELEM_PARTITION_TYPE); - if(requiredPartitionTypes.length > 0) { - for (int partitionTypeIndex = 0; partitionTypeIndex < requiredPartitionTypes.length; ++partitionTypeIndex) { - String partitionTypeID = requiredPartitionTypes[partitionTypeIndex].getAttribute(ATTR_ID); - checkExtensionAttributeNotNull(partitionTypeID, ATTR_ID, requiredPartitionTypes[partitionTypeIndex]); - - requiredPartitionTypeIDs.add(partitionTypeID); - } - } - } - - //get the optional associated comment partition type ID - String associatedCommentPartitionTypeID = - contentTypeElements[contentTypeIndex].getAttribute(ATTR_ASSOCIATED_COMMENT_PARTITION_TPYPE_ID); - - //register the strategy - CommentingStrategy newCommentingStrategy = (CommentingStrategy)baseCommentingStrategy.clone(); - newCommentingStrategy.setPartitionInformation(allowablePartitionTypeIDs, anyPartitionType, - requiredPartitionTypeIDs, associatedCommentPartitionTypeID); - commentTypes.add(newCommentingStrategy); - } catch(CoreException e) { - Logger.logException(e); - } - } - } else { - Logger.log(Logger.WARNING, "The commmenting strategy element: " + element +//$NON-NLS-1$ - " does not contain any required " + ELEM_CONTENT_TYPE + "s"); //$NON-NLS-1$ //$NON-NLS-2$ - } - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/comment/LineCommentingStrategy.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/comment/LineCommentingStrategy.java deleted file mode 100644 index b8d8697076..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/comment/LineCommentingStrategy.java +++ /dev/null @@ -1,83 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.comment; - -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IRegion; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument; - -/** - * <p>Represents a Line Comment commenting strategy</p> - */ -public class LineCommentingStrategy extends CommentingStrategy { - /** the prefix of the line comment associated with this strategy */ - private String fPrefix; - - /** - * @param prefix the prefix of the line comment associated with this strategy - */ - public LineCommentingStrategy(String prefix) { - super(); - this.fPrefix = prefix; - } - - /** - * <p>Assumes that the given offset is at the begining of a line and adds the line - * comment prefix there</p> - * - * @see org.eclipse.wst.sse.ui.internal.comment.CommentingStrategy#apply( - * org.eclipse.wst.sse.core.internal.provisional.IStructuredModel, int, int) - */ - public void apply(IStructuredDocument document, int offset, int length) - throws BadLocationException { - - document.replace(offset, 0, this.fPrefix + " "); - } - - /** - * <p>Assumes that the given offset is at the beginning of a line that is commented and removes - * the comment prefix from the beginning of the line, leading whitespace on the line will not - * prevent this method from finishing correctly</p> - * - * @see org.eclipse.wst.sse.ui.internal.comment.CommentingStrategy#remove( - * org.eclipse.wst.sse.core.internal.provisional.IStructuredModel, int, int, boolean) - */ - public void remove(IStructuredDocument document, int offset, int length, boolean removeEnclosing) throws BadLocationException{ - String content = document.get(offset, length); - int innerOffset = content.indexOf(this.fPrefix); - if(innerOffset > 0) { - offset += innerOffset; - } - - uncomment(document, offset, this.fPrefix, -1, null); - } - - /** - * <p>A region is already commented if it begins with the the associated prefix ignoring any - * leading whitespace</p> - * - * @see org.eclipse.wst.sse.ui.internal.comment.CommentingStrategy#alreadyCommenting( - * org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IRegion) - */ - public boolean alreadyCommenting(IStructuredDocument document, IRegion region) - throws BadLocationException { - - String regionContent = document.get(region.getOffset(), region.getLength()).trim(); - return regionContent.startsWith(this.fPrefix); - } - - /** - * @see org.eclipse.wst.sse.ui.internal.comment.CommentingStrategy#clone() - */ - public Object clone() { - return new LineCommentingStrategy(this.fPrefix); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentassist/CompletionProposalCategory.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentassist/CompletionProposalCategory.java deleted file mode 100644 index 83abfa3cbc..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentassist/CompletionProposalCategory.java +++ /dev/null @@ -1,374 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.contentassist; - -import java.net.URL; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.FileLocator; -import org.eclipse.core.runtime.IConfigurationElement; -import org.eclipse.core.runtime.Path; -import org.eclipse.core.runtime.SubProgressMonitor; -import org.eclipse.jface.action.LegacyActionTools; -import org.eclipse.jface.resource.ImageDescriptor; -import org.eclipse.wst.sse.core.internal.util.Assert; -import org.eclipse.wst.sse.ui.contentassist.CompletionProposalInvocationContext; -import org.eclipse.wst.sse.ui.preferences.ICompletionProposalCategoriesConfigurationReader; -import org.osgi.framework.Bundle; - -/** - * Describes a category extension to the - * <code>org.eclipse.wst.sse.ui.completionProposal</code> extension point. - */ -public final class CompletionProposalCategory { - /** The extension schema name of the icon attribute. */ - private static final String ICON= "icon"; //$NON-NLS-1$ - - /** The extension schema name of the ID attribute. */ - private static final String ID= "id"; //$NON-NLS-1$ - - /** The extension schema name of the name attribute. */ - private static final String NAME= "name"; //$NON-NLS-1$ - - /** ID of this completion category */ - private final String fId; - - /** Name of this completion category */ - private final String fName; - - /** The image descriptor for this category, or <code>null</code> if none specified. */ - private final ImageDescriptor fImage; - - /** The last error reported by this category */ - private String fLastError = null; - - /** - * <p>Construct the category by parsing the given element.</p> - * - * @param element {@link IConfigurationElement} containing the configuration of this category - * @throws CoreException if the given {@link IConfigurationElement} does not contain the correct - * elements and attributes. - */ - CompletionProposalCategory(IConfigurationElement element) throws CoreException { - Assert.isLegal(element != null); - - //get & verify ID - fId = element.getAttribute(ID); - ContentAssistUtils.checkExtensionAttributeNotNull(fId, ID, element); - - //get & verify optional name - String name= element.getAttribute(NAME); - if (name == null) { - fName = fId; - } else { - fName= name; - } - - //get & verify optional icon - String icon= element.getAttribute(ICON); - ImageDescriptor img= null; - if (icon != null) { - Bundle bundle= ContentAssistUtils.getBundle(element); - if (bundle != null) { - Path path= new Path(icon); - URL url= FileLocator.find(bundle, path, null); - img= ImageDescriptor.createFromURL(url); - } - } - fImage= img; - } - - /** - * <p>Creates a category with the given name and ID</p> - * - * @param id the unique ID of the new category - * @param name the name of the new category - */ - CompletionProposalCategory(String id, String name) { - fId= id; - fName= name; - fImage= null; - } - - /** - * <p>Returns the unique identifier of the category</p> - * - * @return Returns the id - */ - public String getId() { - return fId; - } - - /** - * <p>Returns the human readable name of the category. - * It may contain mnemonics.</p> - * - * @return Returns the name - */ - public String getName() { - return fName; - } - - /** - * <p>Returns the human readable name of the category - * without mnemonic hint in order to be displayed - * in a message.</p> - * - * @return Returns the name - */ - public String getDisplayName() { - return LegacyActionTools.removeMnemonics(fName); - } - - /** - * <p>Returns the image descriptor of the category.</p> - * - * @return the image descriptor of the category - */ - public ImageDescriptor getImageDescriptor() { - return fImage; - } - - /** - * @return <code>true</code> if this category should be displayed on - * its own content assist page, <code>false</code> otherwise - */ - public boolean isDisplayedOnOwnPage(String contentTypeID) { - boolean displayOnOwnPage = ICompletionProposalCategoriesConfigurationReader.DEFAULT_DISPLAY_ON_OWN_PAGE; - - ICompletionProposalCategoriesConfigurationReader properties = - CompletionProposoalCatigoriesConfigurationRegistry.getDefault().getReadableConfiguration(contentTypeID); - if(properties != null) { - displayOnOwnPage = properties.shouldDisplayOnOwnPage(this.fId); - } - - return displayOnOwnPage; - } - - /** - * @return <code>true</code> if this category should be displayed in - * the default content assist page, <code>false</code> otherwise - */ - public boolean isIncludedOnDefaultPage(String contentTypeID) { - boolean includeOnDefaultPage = ICompletionProposalCategoriesConfigurationReader.DEFAULT_INCLUDE_ON_DEFAULTS_PAGE; - - ICompletionProposalCategoriesConfigurationReader properties = - CompletionProposoalCatigoriesConfigurationRegistry.getDefault().getReadableConfiguration(contentTypeID); - if(properties != null) { - includeOnDefaultPage = properties.shouldDisplayOnDefaultPage(this.fId); - } - - return includeOnDefaultPage; - } - - /** - * <p>Given a content type ID determines the rank of this - * category for sorting the content assist pages</p> - * - * @return the sort rank of this category - */ - public int getPageSortRank(String contentTypeID) { - int sortOrder = ICompletionProposalCategoriesConfigurationReader.DEFAULT_SORT_ORDER; - - ICompletionProposalCategoriesConfigurationReader properties = - CompletionProposoalCatigoriesConfigurationRegistry.getDefault().getReadableConfiguration(contentTypeID); - if(properties != null) { - sortOrder = properties.getPageSortOrder(this.fId); - } - - return sortOrder; - } - - /** - * <p>Given a content type ID determines the rank of this - * category for sorting on the default content assist page - * with other categories</p> - * - * @return the sort rank of this category - */ - public int getDefaultPageSortRank(String contentTypeID) { - int sortOrder = ICompletionProposalCategoriesConfigurationReader.DEFAULT_SORT_ORDER; - - ICompletionProposalCategoriesConfigurationReader properties = - CompletionProposoalCatigoriesConfigurationRegistry.getDefault().getReadableConfiguration(contentTypeID); - if(properties != null) { - sortOrder = properties.getDefaultPageSortOrder(this.fId); - } - - return sortOrder; - } - - /** - * <p><b>NOTE: </b> enablement is not the same as weather a category - * should be displayed on its own page or the default page, it describes - * if the category should be used at all. Currently categories are always - * enabled. There maybe cases in the future where a category should be - * disabled entirely though.</p> - * - * @return <code>true</code> if this category is enabled, - * <code>false</code> otherwise - */ - public boolean isEnabled() { - return true; - } - - /** - * @return <code>true</code> if the category contains any computers, <code>false</code> - * otherwise - */ - public boolean hasComputers() { - List descriptors= CompletionProposalComputerRegistry.getDefault().getProposalComputerDescriptors(); - for (Iterator it= descriptors.iterator(); it.hasNext();) { - CompletionProposalComputerDescriptor desc= (CompletionProposalComputerDescriptor) it.next(); - if (desc.getCategory() == this) { - return true; - } - } - return false; - } - - /** - * @param contentTypeID the content type ID - * @param partitionTypeID the partition - * @return <code>true</code> if the category contains any computers, in the given partition type - * in the given content type, <code>false</code> otherwise - */ - public boolean hasComputers(String contentTypeID, String partitionTypeID) { - List descriptors = CompletionProposalComputerRegistry.getDefault().getProposalComputerDescriptors(contentTypeID, partitionTypeID); - for (Iterator it = descriptors.iterator(); it.hasNext();) { - CompletionProposalComputerDescriptor desc= (CompletionProposalComputerDescriptor) it.next(); - if (desc.getCategory() == this) { - return true; - } - } - return false; - } - - /** - * @param contentTypeID the content type ID - * @return <code>true</code> if the category contains any computers, in the given partition type - * in the given content type, <code>false</code> otherwise - */ - public boolean hasComputers(String contentTypeID) { - List descriptors = CompletionProposalComputerRegistry.getDefault().getProposalComputerDescriptors(contentTypeID); - for (Iterator it = descriptors.iterator(); it.hasNext();) { - CompletionProposalComputerDescriptor desc= (CompletionProposalComputerDescriptor) it.next(); - if (desc.getCategory() == this) { - return true; - } - } - return false; - } - - /** - * <p>Safely computes completion proposals of all computers of this category through their - * extension.</p> - * - * @param context the invocation context passed on to the extension - * @param contentTypeID the content type ID where the invocation occurred - * @param partitionTypeID the partition type where the invocation occurred - * @param monitor the progress monitor passed on to the extension - * @return the list of computed completion proposals (element type: - * {@link org.eclipse.jface.text.contentassist.ICompletionProposal}) - */ - public List computeCompletionProposals(CompletionProposalInvocationContext context, - String contentTypeID, String partitionTypeID, SubProgressMonitor monitor) { - - fLastError = null; - List result = new ArrayList(); - List descriptors = new ArrayList(CompletionProposalComputerRegistry.getDefault().getProposalComputerDescriptors(contentTypeID, partitionTypeID)); - for (Iterator it = descriptors.iterator(); it.hasNext();) { - CompletionProposalComputerDescriptor desc = (CompletionProposalComputerDescriptor) it.next(); - if (desc.getCategory() == this) { - result.addAll(desc.computeCompletionProposals(context, monitor)); - } - - if (fLastError == null && desc.getErrorMessage() != null) { - fLastError = desc.getErrorMessage(); - } - } - return result; - } - - /** - * <p>Safely computes context information objects of all computers of this category through their - * extension.</p> - * - * @param context the invocation context passed on to the extension - * @param contentTypeID the content type ID where the invocation occurred - * @param partitionTypeID the partition type where the invocation occurred - * @param monitor the progress monitor passed on to the extension - * @return the list of computed context information objects (element type: - * {@link org.eclipse.jface.text.contentassist.IContextInformation}) - */ - public List computeContextInformation(CompletionProposalInvocationContext context, - String contentTypeID, String partitionTypeID, SubProgressMonitor monitor) { - - fLastError= null; - List result= new ArrayList(); - List descriptors= new ArrayList(CompletionProposalComputerRegistry.getDefault().getProposalComputerDescriptors(contentTypeID, partitionTypeID)); - for (Iterator it= descriptors.iterator(); it.hasNext();) { - CompletionProposalComputerDescriptor desc= (CompletionProposalComputerDescriptor) it.next(); - if (desc.getCategory() == this && (isIncludedOnDefaultPage(contentTypeID) || isDisplayedOnOwnPage(contentTypeID))) { - result.addAll(desc.computeContextInformation(context, monitor)); - } - if (fLastError == null) { - fLastError= desc.getErrorMessage(); - } - } - return result; - } - - /** - * @return the last error message reported by a computer in this category - */ - public String getErrorMessage() { - return fLastError; - } - - /** - * <p>Notifies the computers in this category of a proposal computation session start.</p> - */ - public void sessionStarted() { - List descriptors= new ArrayList(CompletionProposalComputerRegistry.getDefault().getProposalComputerDescriptors()); - for (Iterator it= descriptors.iterator(); it.hasNext();) { - CompletionProposalComputerDescriptor desc= (CompletionProposalComputerDescriptor) it.next(); - if (desc.getCategory() == this) - desc.sessionStarted(); - if (fLastError == null) - fLastError= desc.getErrorMessage(); - } - } - - /** - * <p>Notifies the computers in this category of a proposal computation session end.</p> - */ - public void sessionEnded() { - List descriptors= new ArrayList(CompletionProposalComputerRegistry.getDefault().getProposalComputerDescriptors()); - for (Iterator it= descriptors.iterator(); it.hasNext();) { - CompletionProposalComputerDescriptor desc= (CompletionProposalComputerDescriptor) it.next(); - if (desc.getCategory() == this) - desc.sessionEnded(); - if (fLastError == null) - fLastError= desc.getErrorMessage(); - } - } - - /** - * @see java.lang.Object#toString() - */ - public String toString() { - return fId + ": " + fName; //$NON-NLS-1$ - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentassist/CompletionProposalComputerDescriptor.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentassist/CompletionProposalComputerDescriptor.java deleted file mode 100644 index d36cca04a3..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentassist/CompletionProposalComputerDescriptor.java +++ /dev/null @@ -1,648 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.contentassist; - -import java.util.Collections; -import java.util.Iterator; -import java.util.List; - -import org.eclipse.core.runtime.Assert; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IConfigurationElement; -import org.eclipse.core.runtime.IContributor; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.InvalidRegistryObjectException; -import org.eclipse.core.runtime.PerformanceStats; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.Status; -import org.eclipse.wst.sse.ui.contentassist.CompletionProposalInvocationContext; -import org.eclipse.wst.sse.ui.contentassist.ICompletionProposalComputer; -import org.eclipse.wst.sse.ui.internal.Logger; -import org.eclipse.wst.sse.ui.internal.SSEUIPlugin; -import org.osgi.framework.Bundle; - -/** - * Wraps an {@link ICompletionProposalComputer} provided by an extension to the - * <code>org.eclipse.wst.sse.ui.completionProposal</code> extension point. - * Instances are immutable. Instances can be obtained from a - * {@link CompletionProposalComputerRegistry}. - * - * @see CompletionProposalComputerRegistry - */ -final class CompletionProposalComputerDescriptor { - /** The default category id. */ - private static final String DEFAULT_CATEGORY_ID= "org.eclipse.wst.sse.ui.defaultProposalCategory"; //$NON-NLS-1$ - - /** The extension schema name of the category id attribute. */ - private static final String ATTR_CATEGORY_ID= "categoryId"; //$NON-NLS-1$ - - /** The extension schema name for element ID attributes */ - private static final String ATTR_ID= "id"; //$NON-NLS-1$ - - /** The extension schema name for element name attributes */ - private static final String ATTR_NAME= "name"; //$NON-NLS-1$ - - /** The extension schema name of the class attribute. */ - private static final String ATTR_CLASS= "class"; //$NON-NLS-1$ - - /** The extension schema name of the activate attribute. */ - private static final String ATTRACTIVATE= "activate"; //$NON-NLS-1$ - - /** The extension schema name of the content type child elements. */ - private static final String ELEM_CONTENT_TYPE = "contentType"; //$NON-NLS-1$ - - /** The extension schema name of the partition type child elements. */ - private static final String ELEM_PARTITION_TYPE= "partitionType"; //$NON-NLS-1$ - - /** The name of the performance event used to trace extensions. */ - private static final String PERFORMANCE_EVENT= SSEUIPlugin.ID + "/perf/content_assist/extensions"; //$NON-NLS-1$ - - /** - * If <code>true</code>, execution time of extensions is measured and the data forwarded to - * core's {@link PerformanceStats} service. - */ - private static final boolean MEASURE_PERFORMANCE= PerformanceStats.isEnabled(PERFORMANCE_EVENT); - - /** - * Independently of the {@link PerformanceStats} service, any operation that takes longer than - * {@value} milliseconds will be flagged as an violation. This timeout does not apply to the - * first invocation, as it may take longer due to plug-in initialization etc. See also - * {@link #fIsReportingDelay}. - */ - private static final long MAX_DELAY= 500000; - - /* log constants */ - private static final String COMPUTE_COMPLETION_PROPOSALS= "computeCompletionProposals()"; //$NON-NLS-1$ - private static final String COMPUTE_CONTEXT_INFORMATION= "computeContextInformation()"; //$NON-NLS-1$ - private static final String SESSION_STARTED= "sessionStarted()"; //$NON-NLS-1$ - private static final String SESSION_ENDED= "sessionEnded()"; //$NON-NLS-1$ - - /** The identifier of the extension. */ - private final String fId; - - /** The name of the extension. */ - private final String fName; - - /** The class name of the provided <code>ISSECompletionProposalComputer</code>. */ - private final String fClass; - - /** The activate attribute value. */ - private final boolean fActivate; - - /** The configuration element of this extension. */ - private final IConfigurationElement fElement; - - /** The computer, if instantiated, <code>null</code> otherwise. */ - private ICompletionProposalComputer fComputer; - - /** The UI category. */ - private final CompletionProposalCategory fCategory; - - /** The first error message in the most recent operation, or <code>null</code>. */ - private String fLastError; - - /** - * Tells whether to inform the user when <code>MAX_DELAY</code> has been exceeded. - * We start timing execution after the first session because the first may take - * longer due to plug-in activation and initialization. - */ - private boolean fIsReportingDelay = false; - - /** The start of the last operation. */ - private long fStart; - - /** - * Tells whether we tried to load the computer. - * @since 3.4 - */ - boolean fTriedLoadingComputer = false; - - /** - * <p>Creates a new descriptor.</p> - * <p><b>NOTE: </b> This will not add this new descriptor to the given - * {@link CompletionProposalComputerRegistry}. That can not be done - * until this descriptor is done being constructed. Therefore be sure - * to call {@link #addToRegistry()} after creating a new descriptor.</p> - * - * @param element the configuration element to read - * @param categories the categories - * - * @throws InvalidRegistryObjectException if this extension is no longer valid - * @throws CoreException if the extension contains invalid values - */ - CompletionProposalComputerDescriptor(IConfigurationElement element, List categories) throws InvalidRegistryObjectException, CoreException { - Assert.isLegal(element != null); - fElement = element; - - //get & verify ID - fId = fElement.getAttribute(ATTR_ID); - ContentAssistUtils.checkExtensionAttributeNotNull(fId, ATTR_ID, fElement); - - //get & verify optional name - String name= fElement.getAttribute(ATTR_NAME); - if (name == null) { - fName= fId; - } else { - fName= name; - } - - //get & verify activate plugin attribute - String activateAttribute= fElement.getAttribute(ATTRACTIVATE); - fActivate = Boolean.valueOf(activateAttribute).booleanValue(); - - //get & verify class - fClass= fElement.getAttribute(ATTR_CLASS); - ContentAssistUtils.checkExtensionAttributeNotNull(fClass, ATTR_CLASS, fElement); - - //get & verify optional category id - String categoryId= fElement.getAttribute(ATTR_CATEGORY_ID); - if (categoryId == null) { - categoryId= DEFAULT_CATEGORY_ID; - } - - //find the category with the determined category id - CompletionProposalCategory category= null; - for (Iterator it= categories.iterator(); it.hasNext();) { - CompletionProposalCategory cat= (CompletionProposalCategory) it.next(); - if (cat.getId().equals(categoryId)) { - category= cat; - break; - } - } - - /* create a category if it does not exist - * else just set the category - */ - if (category == null) { - fCategory = new CompletionProposalCategory(categoryId, fName); - - /* will add the new category to the registers list of categories, - * by the magic of object references - */ - categories.add(fCategory); - } else { - fCategory = category; - } - } - - /** - * <p>Adds this descriptor to the {@link CompletionProposalComputerRegistry}.</p> - * <p><b>NOTE: </b>Must be done after descriptor creation or the descriptor will - * not be added to the registry. Can not be done in constructor because - * descriptor must be constructed before it can be added to the registry</p> - * - * - * @throws InvalidRegistryObjectException - * @throws CoreException - */ - void addToRegistry() throws InvalidRegistryObjectException, CoreException { - parseActivationAndAddToRegistry(this.fElement, this); - } - - /** - * @return the category that the wrapped {@link ICompletionProposalComputer} is - * associated with. - */ - CompletionProposalCategory getCategory() { - return fCategory; - } - - /** - * @return the contributor of the described {@link ICompletionProposalComputer} - */ - IContributor getContributor() { - try { - return fElement.getContributor(); - } catch (InvalidRegistryObjectException e) { - return null; - } - } - - /** - * @return Returns the id of the described {@link ICompletionProposalComputer} - */ - public String getId() { - return fId; - } - - /** - * @return the name of the described {@link ICompletionProposalComputer} - */ - public String getName() { - return fName; - } - - /** - * Returns a new instance of the computer as described in the - * extension's xml. Note that the safest way to access the computer - * is by using the - * {@linkplain #computeCompletionProposals(ContentAssistInvocationContext, IProgressMonitor) computeCompletionProposals} - * and - * {@linkplain #computeContextInformation(ContentAssistInvocationContext, IProgressMonitor) computeContextInformation} - * methods. These delegate the functionality to the contributed - * computer, but handle instance creation and any exceptions thrown. - * - * @return a new instance of the completion proposal computer as - * described by this descriptor - * - * @throws CoreException if the creation fails - * @throws InvalidRegistryObjectException if the extension is not - * valid any longer (e.g. due to plug-in unloading) - */ - public ICompletionProposalComputer createComputer() throws CoreException, InvalidRegistryObjectException { - return (ICompletionProposalComputer) fElement.createExecutableExtension(ATTR_CLASS); - } - - /** - * <p>Safely computes completion proposals through the described extension.</p> - * - * @param context the invocation context passed on to the extension - * @param monitor the progress monitor passed on to the extension - * @return the list of computed completion proposals (element type: - * {@link org.eclipse.jface.text.contentassist.ICompletionProposal}) - */ - public List computeCompletionProposals(CompletionProposalInvocationContext context, IProgressMonitor monitor) { - List completionProposals = Collections.EMPTY_LIST; - if (isEnabled()) { - IStatus status = null; - try { - // plugin must be active to get computer - ICompletionProposalComputer computer = getComputer(true); - if (computer != null) { - try { - PerformanceStats stats= startMeter(context, computer); - //ask the computer for the proposals - List proposals = computer.computeCompletionProposals(context, monitor); - stopMeter(stats, COMPUTE_COMPLETION_PROPOSALS); - - if (proposals != null) { - fLastError = computer.getErrorMessage(); - completionProposals = proposals; - } else { - status = createAPIViolationStatus(COMPUTE_COMPLETION_PROPOSALS); - } - } finally { - fIsReportingDelay = true; - } - } - } catch (InvalidRegistryObjectException x) { - status= createExceptionStatus(x); - } catch (CoreException x) { - status= createExceptionStatus(x); - } catch (RuntimeException x) { - status= createExceptionStatus(x); - } finally { - monitor.done(); - } - - if(status != null) { - Logger.log(status); - } - } - - return completionProposals; - } - - /** - * <p>Safely computes context information objects through the described extension.</p> - * - * @param context the invocation context passed on to the extension - * @param monitor the progress monitor passed on to the extension - * @return the list of computed context information objects (element type: - * {@link org.eclipse.jface.text.contentassist.IContextInformation}) - */ - public List computeContextInformation(CompletionProposalInvocationContext context, IProgressMonitor monitor) { - List contextInformation = Collections.EMPTY_LIST; - if (isEnabled()) { - IStatus status = null; - try { - // plugin must be active to get computer - ICompletionProposalComputer computer = getComputer(true); - if (computer != null) { - PerformanceStats stats= startMeter(context, computer); - List proposals= computer.computeContextInformation(context, monitor); - stopMeter(stats, COMPUTE_CONTEXT_INFORMATION); - - if (proposals != null) { - fLastError= computer.getErrorMessage(); - contextInformation = proposals; - } else { - status = createAPIViolationStatus(COMPUTE_CONTEXT_INFORMATION); - } - } - } catch (InvalidRegistryObjectException x) { - status= createExceptionStatus(x); - } catch (CoreException x) { - status= createExceptionStatus(x); - } catch (RuntimeException x) { - status= createExceptionStatus(x); - } finally { - monitor.done(); - } - - if(status != null) { - Logger.log(status); - } - } - - return contextInformation; - } - - /** - * <p>Notifies the described extension of a proposal computation session start.</p> - * - * <p><b>Note: </b>This method is called every time code assist is invoked and - * is <strong>not</strong> filtered by content type or partition type.</p> - */ - public void sessionStarted() { - if (isEnabled()) { - IStatus status = null; - try { - // plugin must be active to get computer - ICompletionProposalComputer computer = getComputer(true); - if (computer != null) { - PerformanceStats stats = startMeter(SESSION_STARTED, computer); - computer.sessionStarted(); - stopMeter(stats, SESSION_ENDED); - } - } catch (InvalidRegistryObjectException x) { - status= createExceptionStatus(x); - } catch (CoreException x) { - status= createExceptionStatus(x); - } catch (RuntimeException x) { - status= createExceptionStatus(x); - } - - if(status != null) { - Logger.log(status); - } - } - } - - /** - * <p>Notifies the described extension of a proposal computation session end.</p> - * - * <p><b>Note: </b>This method is called every time code assist is invoked and - * is <strong>not</strong> filtered by content type or partition type.</p> - */ - public void sessionEnded() { - if (isEnabled()) { - IStatus status = null; - try { - // plugin must be active to get computer - ICompletionProposalComputer computer = getComputer(true); - if (computer != null) { - PerformanceStats stats= startMeter(SESSION_ENDED, computer); - computer.sessionEnded(); - stopMeter(stats, SESSION_ENDED); - } - } catch (InvalidRegistryObjectException x) { - status= createExceptionStatus(x); - } catch (CoreException x) { - status= createExceptionStatus(x); - } catch (RuntimeException x) { - status= createExceptionStatus(x); - } - - if(status != null) { - Logger.log(status); - } - } - } - - /** - * @return the error message from the described {@link ICompletionProposalComputer} - */ - public String getErrorMessage() { - return fLastError; - } - - /** - * @see java.lang.Object#toString() - */ - public String toString() { - return fId + ": " + fName; //$NON-NLS-1$ - } - - /** - * <p>Parses the given configuration element for its activation context, - * that is to say the content types and partiton types and updates the registry - * to associated the given computer descriptor with the parsed activation contexts.</P> - * - * <p>This is useful for parsing both <tt>proposalComputer</tt> elements and - * <tt>proposalComputerExtendedActivation</tt> elements.</p> - * - * @param element {@link IConfigurationElement} containing the activation context - * @param desc {@link CompletionProposalComputerDescriptor} to associate with the parsed activation context - * - * @throws InvalidRegistryObjectException - * @throws CoreException - */ - protected static void parseActivationAndAddToRegistry(IConfigurationElement element, - CompletionProposalComputerDescriptor desc) throws InvalidRegistryObjectException, CoreException { - - /* if this descriptor is specific to a content type/s add it to the registry as such - * else add to registry for all content types - */ - IConfigurationElement[] contentTypes = element.getChildren(ELEM_CONTENT_TYPE); - if(contentTypes.length > 0) { - for(int contentTypeIndex = 0; contentTypeIndex < contentTypes.length; ++contentTypeIndex) { - String contentTypeID = contentTypes[contentTypeIndex].getAttribute(ATTR_ID); - ContentAssistUtils.checkExtensionAttributeNotNull(contentTypeID, ATTR_ID, contentTypes[contentTypeIndex]); - - /* if this descriptor is for specific partition types in the content type - * add it to the registry as such - * else add to the registry for all partition types in the content type - */ - IConfigurationElement[] partitionTypes = contentTypes[contentTypeIndex].getChildren(ELEM_PARTITION_TYPE); - if(partitionTypes.length > 0) { - for (int partitionTypeIndex = 0; partitionTypeIndex < partitionTypes.length; ++partitionTypeIndex) { - String partitionTypeID = partitionTypes[partitionTypeIndex].getAttribute(ATTR_ID); - ContentAssistUtils.checkExtensionAttributeNotNull(partitionTypeID, ATTR_ID, partitionTypes[partitionTypeIndex]); - - CompletionProposalComputerRegistry.getDefault().putDescription(contentTypeID, partitionTypeID, desc); - CompletionProposalComputerRegistry.getDefault().putAutoActivator(contentTypeID, partitionTypeID, partitionTypes[partitionTypeIndex]); - } - } else { - CompletionProposalComputerRegistry.getDefault().putDescription(contentTypeID, null, desc); - } - } - } else { - Logger.log(Logger.WARNING, "The configuration element: " + element + " does not contain any content types."); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - - /** - * @return <code>true</code> if the plugin that contains the {@link IConfigurationElement} - * associated with this descriptor is loaded, <code>false</code> otherwise. - */ - private boolean isPluginLoaded() { - Bundle bundle= getBundle(); - return bundle != null && bundle.getState() == Bundle.ACTIVE; - } - - /** - * @return the {@link Bundle} that contains the {@link IConfigurationElement} associated - * with this descriptor - */ - private Bundle getBundle() { - String namespace= fElement.getDeclaringExtension().getContributor().getName(); - Bundle bundle= Platform.getBundle(namespace); - return bundle; - } - - /** - * <p>Returns a cached instance of the computer as described in the - * extension's xml. If the computer is not yet created and - * <code>canCreate</code> is <code>true</code> then {@link #createComputer()} - * is called and the result cached.</p> - * - * @param canCreate <code>true</code> if the proposal computer can be created - * @return a new instance of the completion proposal computer as - * described by this descriptor - * - * @throws CoreException if the creation fails - * @throws InvalidRegistryObjectException if the extension is not - * valid any longer (e.g. due to plug-in unloading) - */ - private synchronized ICompletionProposalComputer getComputer(boolean canCreate) throws CoreException, InvalidRegistryObjectException { - if (fComputer == null && canCreate && !fTriedLoadingComputer && (fActivate || isPluginLoaded())) { - fTriedLoadingComputer= true; - fComputer= createComputer(); - } - return fComputer; - } - - /** - * @return the enablement state of the category this describer is associated with - */ - private boolean isEnabled() { - return fCategory.isEnabled(); - } - - /** - * <p>Starts the meter for measuring the computers performance</p> - * - * @param context - * @param computer - * @return - */ - private PerformanceStats startMeter(Object context, ICompletionProposalComputer computer) { - final PerformanceStats stats; - if (MEASURE_PERFORMANCE) { - stats= PerformanceStats.getStats(PERFORMANCE_EVENT, computer); - stats.startRun(context.toString()); - } else { - stats= null; - } - - if (fIsReportingDelay) { - fStart= System.currentTimeMillis(); - } - - return stats; - } - - /** - * <p>Stops the meter for measuring the computers performance</p> - * - * @param context - * @param computer - * @return - */ - private void stopMeter(final PerformanceStats stats, String operation) { - if (MEASURE_PERFORMANCE) { - stats.endRun(); - if (stats.isFailure()) { - IStatus status= createPerformanceStatus(operation); - Logger.log(status); - return; - } - } - - if (fIsReportingDelay) { - long current= System.currentTimeMillis(); - if (current - fStart > MAX_DELAY) { - IStatus status= createPerformanceStatus(operation); - Logger.log(status); - } - } - } - - /** - * @return A message explaining that the described {@link ICompletionProposalComputer} failed in some way - */ - private String createBlameMessage() { - return "The ''" + getName() + "'' proposal computer from the ''" + //$NON-NLS-1$ //$NON-NLS-2$ - fElement.getDeclaringExtension().getContributor().getName() + "'' plug-in did not complete normally."; //$NON-NLS-1$ - } - - /** - * <p>Create a status message describing that the extension has become invalid</p> - * - * @param x the associated {@link InvalidRegistryObjectException} - * @return the created {@link IStatus} - */ - private IStatus createExceptionStatus(InvalidRegistryObjectException x) { - String blame= createBlameMessage(); - String reason= "The extension has become invalid."; //$NON-NLS-1$ - return new Status(IStatus.INFO, SSEUIPlugin.ID, IStatus.OK, blame + " " + reason, x); //$NON-NLS-1$ - } - - /** - * <p>create a status message explaining that the extension could not be instantiated</p> - * - * @param x the associated {@link CoreException} - * @return the created {@link IStatus} - */ - private IStatus createExceptionStatus(CoreException x) { - String blame = createBlameMessage(); - String reason = "Unable to instantiate the extension."; //$NON-NLS-1$ - return new Status(IStatus.ERROR, SSEUIPlugin.ID, IStatus.OK, blame + " " + reason, x); //$NON-NLS-1$ - } - - /** - * <p>Create a status message explaining the extension has thrown a runtime exception</p> - * - * @param x the associated {@link RuntimeException} - * @return the created {@link IStatus} - */ - private IStatus createExceptionStatus(RuntimeException x) { - String blame= createBlameMessage(); - String reason= "The extension has thrown a runtime exception."; //$NON-NLS-1$ - return new Status(IStatus.WARNING, SSEUIPlugin.ID, IStatus.OK, blame + " " + reason, x); //$NON-NLS-1$ - } - - /** - * <p>Create a status message explaining the extension has violated the API of the extension point</p> - * - * @param operation the operation that created the API violation - * @return the created {@link IStatus} - */ - private IStatus createAPIViolationStatus(String operation) { - String blame = createBlameMessage(); - String reason = "The extension violated the API contract of the ''" + operation + "'' operation."; //$NON-NLS-1$ //$NON-NLS-2$ - return new Status(IStatus.WARNING, SSEUIPlugin.ID, IStatus.OK, blame + " " + reason, null); //$NON-NLS-1$ - } - - /** - * <p>Create a status message explaining that the extension took to long during an operation</p> - * - * @param operation the operation that took to long - * @return the created {@link IStatus} - */ - private IStatus createPerformanceStatus(String operation) { - String blame= createBlameMessage(); - String reason = "The extension took too long to return from the ''" + operation + "'' operation."; //$NON-NLS-1$ //$NON-NLS-2$ - return new Status(IStatus.WARNING, SSEUIPlugin.ID, IStatus.OK, blame + " " + reason, null); //$NON-NLS-1$ - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentassist/CompletionProposalComputerRegistry.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentassist/CompletionProposalComputerRegistry.java deleted file mode 100644 index f3189a58a8..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentassist/CompletionProposalComputerRegistry.java +++ /dev/null @@ -1,559 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.contentassist; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.eclipse.core.runtime.Assert; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IConfigurationElement; -import org.eclipse.core.runtime.IExtensionRegistry; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.InvalidRegistryObjectException; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.content.IContentType; -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.wst.sse.ui.contentassist.AutoActivationDelegate; -import org.eclipse.wst.sse.ui.internal.Logger; -import org.eclipse.wst.sse.ui.internal.SSEUIPlugin; - - -/** - * <p>A registry for all extensions to the - * <code>org.eclipse.wst.sse.ui.completionProposal</code> - * extension point.</p> - */ -public final class CompletionProposalComputerRegistry { - - /** The extension schema name of the extension point */ - private static final String EXTENSION_POINT = "completionProposal"; //$NON-NLS-1$ - - /** The extension schema name of proposal category child elements. */ - private static final String ELEM_PROPOSAL_CATEGORY = "proposalCategory"; //$NON-NLS-1$ - - /** The extension schema name of proposal computer child elements. */ - private static final String ELEM_PROPOSAL_COMPUTER = "proposalComputer"; //$NON-NLS-1$ - - /** The extension schema name of proposal computer activation child elements. */ - private static final String ELEM_PROPOSAL_COMPUTER_EXTENDED_ACTIVATION = "proposalComputerExtendedActivation"; //$NON-NLS-1$ - - /** The extension schema name for element ID attributes */ - private static final String ATTR_ID= "id"; //$NON-NLS-1$ - - /** The extension schema name for the partition's auto-activation class */ - private static final String ATTR_AUTO_ACTIVATION_CLASS = "autoActivationDelegate"; //$NON-NLS-1$ - - /** preference key to keep track of the last known number of content assist computers */ - private static final String NUM_COMPUTERS_PREF_KEY = "content_assist_number_of_computers"; //$NON-NLS-1$ - - /** - * A fake partition type ID stating used to say a {@link CompletionProposalComputerDescriptor} should - * be associated with all partition types in a given content type. - */ - private static final String ALL_PARTITION_TYPES_ID = "all_partition_types_fake_ID"; //$NON-NLS-1$ - - /** State where in the registry has not yet been loaded */ - private static final byte NONE = 0; - - /** State where the registry is being initialized */ - private static final byte INITIALIZING = 1; - - /** State where in the registry is currently being loaded */ - private static final byte LOADING = 2; - - /** State where in the registry has been loaded */ - private static final byte LOADED = 3; - - /** The singleton instance. */ - private static CompletionProposalComputerRegistry fgSingleton= null; - - /** - * @return the singleton instance of the registry - */ - public static synchronized CompletionProposalComputerRegistry getDefault() { - if (fgSingleton == null) { - fgSingleton= new CompletionProposalComputerRegistry(); - } - - return fgSingleton; - } - - /** - * <code>{@link Map}<{@link String}, {@link CompletionProposalContentTypeContext}></code> - * <ul> - * <li><b>key:</b> content type ID</li> - * <li><b>value:</b> the context for the associated content type ID</li> - * <ul> - */ - private final Map fActivationContexts; - - /** - * <code>{@link Map}<{@link String}, {@link CompletionProposalComputerDescriptor}></code> - * <ul> - * <li><b>key:</b> descriptor ID</li> - * <li><b>value:</b> descriptor</li> - * <ul> - */ - private final Map fDescriptors = new HashMap(); - - /** A map maintaining the relationship between content types, partition types and their associated {@link AutoActivationDelegate}s*/ - private Map fAutoActivators = new HashMap(); - - /** The {@link CompletionProposalCategory}s tracked by this registry */ - private final List fCategories = new ArrayList(); - - /** Unmodifiable public list of the {@link CompletionProposalCategory}s tracked by this registry */ - private final List fPublicCategories = Collections.unmodifiableList(fCategories); - - /** - * <p>The current state of the registry</p> - * - * @see #NONE - * @see #LOADING - * @see #LOADED - */ - private byte fState; - - /** - * Lock that is held while loading, operations waiting for - * load to finish can lock on this as well - */ - private final Object fLoadingLock; - - /** <code>true</code> if computers have been uninstalled since last load */ - private boolean fHasUninstalledComputers= false; - - /** - * Creates a new instance. - */ - private CompletionProposalComputerRegistry() { - this.fActivationContexts = new HashMap(); - this.fState = CompletionProposalComputerRegistry.NONE; - this.fLoadingLock = new Object(); - } - - /** - * <p>Calling this when the registry has not yet been loaded will start a - * {@link Thread} to start loading the registry. All other operations on - * the registry will be blocked until the loading has completed. If - * the registry has already been loaded or is loading then this - * method does nothing.</p> - */ - public synchronized void initialize() { - if(fState == CompletionProposalComputerRegistry.NONE) { - fState = CompletionProposalComputerRegistry.INITIALIZING; - new Thread() { - public void run() { - CompletionProposalComputerRegistry.this.load(); - } - }.start(); - } - } - - /** - * <p><b>NOTE: </b>The returned list is read-only and is sorted in the order that the - * extensions were read in. There are no duplicate elements in the returned list. - * The returned list may change if plug-ins are loaded or unloaded while the - * application is running.</p> - * - * @return the list of proposal categories contributed to the - * <code>org.eclipse.wst.sse.ui.completionProposal</code> extension point (element type: - * {@link CompletionProposalCategory}) - */ - public List getProposalCategories() { - internalEnsureLoaded(); - return fPublicCategories; - } - - /** - * <p><b>NOTE: </b>The returned list is read-only and is sorted in the order that the - * extensions were read in. There are no duplicate elements in the returned list. - * The returned list may change if plug-ins are loaded or unloaded while the - * application is running.</p> - * - * @param contentTypeID get the {@link CompletionProposalCategory}s associated with this ID - * @return the {@link CompletionProposalCategory}s associated with the given content type ID - */ - public List getProposalCategories(String contentTypeID) { - internalEnsureLoaded(); - List result = new ArrayList(); - for(int i = 0; i < fCategories.size(); ++i) { - CompletionProposalCategory category = ((CompletionProposalCategory)fCategories.get(i)); - if(category.hasComputers(contentTypeID)) { - result.add(category); - } - } - - return Collections.unmodifiableList(result); - } - - /** - * @return <code>true</code> if the registry detected that computers got uninstalled since the last run - * <code>false</code> otherwise or if {@link #resetUnistalledComputers()} has been called - */ - public boolean hasUninstalledComputers() { - return fHasUninstalledComputers; - } - - /** - * <p>Clears the setting that uninstalled computers have been detected. - * This setting is used to decide weather a helpful message should be - * displayed to the user</p> - */ - public void resetUnistalledComputers() { - fHasUninstalledComputers = false; - } - - /** - * <p>Adds the given {@link CompletionProposalComputerDescriptor} to the registry.</p> - * - * @param contentTypeID the ID of the content type to associated the descriptor with - * @param partitionTypeID the ID of the partition type in the content type to associate - * the descriptor with, or <code>null</code> to associate with all partition types in - * the content type. - * @param descriptor the {@link CompletionProposalComputerDescriptor} to associate with - * the given content type and partition type - */ - void putDescription(String contentTypeID, String partitionTypeID, - CompletionProposalComputerDescriptor descriptor) { - - if(partitionTypeID == null) { - partitionTypeID = ALL_PARTITION_TYPES_ID; - } - - CompletionProposalContentTypeContext context = getContext(contentTypeID); - context.putDescriptor(partitionTypeID, descriptor); - } - - void putAutoActivator(String contentTypeID, String partitionTypeID, IConfigurationElement element) { - String autoActivationClass = element.getAttribute(ATTR_AUTO_ACTIVATION_CLASS); - if (autoActivationClass == null) - return; - - Map partitionMap = (Map) fAutoActivators.get(contentTypeID); - if (partitionMap == null) { - partitionMap = new HashMap(); - fAutoActivators.put(contentTypeID, partitionMap); - } - partitionMap.put(partitionTypeID, new Activator(element)); - } - - public AutoActivationDelegate getActivator(String contentTypeID, String partitionTypeID) { - Map partitionMap = (Map) fAutoActivators.get(contentTypeID); - if (partitionMap != null) { - Activator activator = (Activator) partitionMap.get(partitionTypeID); - if (activator != null) { - return activator.createAutoActivation(); - } - } - return null; - } - - /** - * @param contentTypeID get only descriptors associated with this content type - * @param partitionTypeID get only descriptors associated with this partition type as well - * as describers associated with any partition type in the given content type - * @return all of the {@link CompletionProposalComputerDescriptor}s associated with the - * given content type and partition type (including any describers associated with all - * partition types in the given content type) - */ - List getProposalComputerDescriptors(String contentTypeID, String partitionTypeID) { - internalEnsureLoaded(); - - Set descriptorsSet = new HashSet(); - List contexts = this.getContexts(contentTypeID); - for(int i = 0; i < contexts.size(); ++i) { - CompletionProposalContentTypeContext contentSpecificContext = - (CompletionProposalContentTypeContext)contexts.get(i); - - //add all descriptors specific to the given content type and the given partition type - descriptorsSet.addAll(contentSpecificContext.getDescriptors(partitionTypeID)); - - //add all descriptors specific to the given content type but not specific to a partition type - descriptorsSet.addAll(contentSpecificContext.getDescriptors(ALL_PARTITION_TYPES_ID)); - } - - List descriptors = new ArrayList(descriptorsSet); - return descriptors != null ? Collections.unmodifiableList(descriptors) : Collections.EMPTY_LIST; - } - - /** - * @param contentTypeID get only descriptors associated with this content type - * @return all of the {@link CompletionProposalComputerDescriptor}s associated with the - * given content type - */ - List getProposalComputerDescriptors(String contentTypeID) { - internalEnsureLoaded(); - - Set descriptorsSet = new HashSet(); - - List contexts = this.getContexts(contentTypeID); - for(int i = 0; i < contexts.size(); ++i) { - CompletionProposalContentTypeContext contentSpecificContext = - (CompletionProposalContentTypeContext)contexts.get(i); - - //add all descriptors specific to the given content type - descriptorsSet.addAll(contentSpecificContext.getDescriptors()); - } - - List descriptors = new ArrayList(descriptorsSet); - return descriptors != null ? Collections.unmodifiableList(descriptors) : Collections.EMPTY_LIST; - } - - /** - * @return Unmodifiable list of all of the {@link CompletionProposalComputerDescriptor}s associated with - * this registry - */ - List getProposalComputerDescriptors() { - internalEnsureLoaded(); - return Collections.unmodifiableList( new ArrayList(fDescriptors.values())); - } - - /** - * <p>This method performs differently depending on the state of the registry</p> - * <ul> - * <li>{@link #NONE} - forces the registry to load now on the current thread</li> - * <li>{@link #LOADING} - blocks until the registry has finished loading on - * whichever thread it is being loaded on</li> - * <li>{@link #LOADED} - immediately returns</li> - * </ul> - */ - private void internalEnsureLoaded() { - switch (fState) { - case CompletionProposalComputerRegistry.NONE: - case CompletionProposalComputerRegistry.INITIALIZING: { - load(); - break; - } - case CompletionProposalComputerRegistry.LOADING: { - //as soon as this lock is released the loading process is done - synchronized (fLoadingLock) { - //sanity check - Assert.isTrue(fState == CompletionProposalComputerRegistry.LOADED, - "The state of the registry should be guaranteed to be LOADED " + //$NON-NLS-1$ - " once the loading lock has been released."); //$NON-NLS-1$ - } - break; - } - } - } - - /** - * <p>Loads the completion proposal extension points if they - * have not been loaded already</p> - */ - private void load() { - /* hold this lock while loading, others waiting for load to - * finish can synchronize on this lock to be guaranteed the load - * will be done when the lock is released - */ - synchronized (fLoadingLock) { - if(fState == CompletionProposalComputerRegistry.NONE || fState == CompletionProposalComputerRegistry.INITIALIZING) { - //update the state - fState = CompletionProposalComputerRegistry.LOADING; - - IExtensionRegistry registry= Platform.getExtensionRegistry(); - List extensionElements= new ArrayList(Arrays.asList(registry.getConfigurationElementsFor(SSEUIPlugin.ID, EXTENSION_POINT))); - - Map loadedDescriptors = new HashMap(); - List extendedComputerActivations = new ArrayList(); - - //get the categories and remove them from the extension elements - List categories= getCategories(extensionElements); - - //deal with the proposal computers and set aside the proposal computer activation extensions - for (Iterator iter= extensionElements.iterator(); iter.hasNext();) { - IConfigurationElement element= (IConfigurationElement) iter.next(); - try { - if (element.getName().equals(ELEM_PROPOSAL_COMPUTER)) { - //create the descriptor and add it to the registry - CompletionProposalComputerDescriptor desc = new CompletionProposalComputerDescriptor(element, categories); - desc.addToRegistry(); - loadedDescriptors.put(desc.getId(), desc); - } else if(element.getName().equals(ELEM_PROPOSAL_COMPUTER_EXTENDED_ACTIVATION)) { - extendedComputerActivations.add(element); - } - - } catch (InvalidRegistryObjectException x) { - /* - * Element is not valid any longer as the contributing plug-in was unloaded or for - * some other reason. Do not include the extension in the list and log it - */ - String message = "The extension ''" + element.toString() + "'' is invalid."; //$NON-NLS-1$ //$NON-NLS-2$ - IStatus status= new Status(IStatus.WARNING, SSEUIPlugin.ID, IStatus.OK, message, x); - Logger.log(status); - } catch (CoreException x) { - Logger.log(x.getStatus()); - } - } - - //deal with extended computer activations - for(int i = 0; i < extendedComputerActivations.size(); ++i) { - IConfigurationElement element = (IConfigurationElement)extendedComputerActivations.get(i); - String proposalComputerID = element.getAttribute(ATTR_ID); - CompletionProposalComputerDescriptor descriptor = - (CompletionProposalComputerDescriptor)loadedDescriptors.get(proposalComputerID); - if(descriptor != null) { - try { - //add the extra activation contexts to the registry - CompletionProposalComputerDescriptor.parseActivationAndAddToRegistry(element, descriptor); - } catch (InvalidRegistryObjectException x) { - /* - * Element is not valid any longer as the contributing plug-in was unloaded or for - * some other reason. Do not include the extension in the list and log it - */ - String message = "The extension ''" + element.toString() + "'' is invalid."; //$NON-NLS-1$ //$NON-NLS-2$ - IStatus status= new Status(IStatus.WARNING, SSEUIPlugin.ID, IStatus.OK, message, x); - Logger.log(status); - } catch (CoreException x) { - Logger.log(x.getStatus()); - } - - } else { - //activation extension has invalid computer ID - Logger.log(Logger.WARNING, "Configuration element " + element + //$NON-NLS-1$ - " intented to extend an existing completion proposal computer" + //$NON-NLS-1$ - " specified an invalid completion proposal computer ID " + //$NON-NLS-1$ - proposalComputerID); - } - } - - fCategories.clear(); - fCategories.addAll(categories); - - fDescriptors.clear(); - fDescriptors.putAll(loadedDescriptors); - - updateUninstalledComputerCount(); - - //update the state - fState = CompletionProposalComputerRegistry.LOADED; - } - } - } - - /** - * <p>Updates the uninstalled computer count</p> - */ - private void updateUninstalledComputerCount() { - IPreferenceStore preferenceStore = SSEUIPlugin.getDefault().getPreferenceStore(); - int lastNumberOfComputers= preferenceStore.getInt(NUM_COMPUTERS_PREF_KEY); - int currNumber= fDescriptors.size(); - fHasUninstalledComputers= lastNumberOfComputers > currNumber; - preferenceStore.putValue(NUM_COMPUTERS_PREF_KEY, Integer.toString(currNumber)); - } - - /** - * <p>Configures the categories found in the given {@link IConfigurationElement}s - * and removes them from the given list.</p> - * - * @param extensionElements {@link IConfigurationElement}s that include proposal - * category extensions - * @return {@link CompletionProposalCategory}s created from the given - * {@link IConfigurationElement}s that defined new proposal categories. - */ - private List getCategories(List extensionElements) { - List categories= new ArrayList(); - for (Iterator iter= extensionElements.iterator(); iter.hasNext();) { - IConfigurationElement element= (IConfigurationElement) iter.next(); - try { - if (element.getName().equals(ELEM_PROPOSAL_CATEGORY)) { - iter.remove(); // remove from list to leave only computers - - CompletionProposalCategory category= new CompletionProposalCategory(element); - categories.add(category); - } - } catch (InvalidRegistryObjectException x) { - /* Element is not valid any longer as the contributing plug-in was unloaded or for - * some other reason. Do not include the extension in the list and log it - */ - String message = "The extension ''" + element.toString() + "'' has become invalid."; //$NON-NLS-1$ //$NON-NLS-2$ - IStatus status= new Status(IStatus.WARNING, SSEUIPlugin.ID, IStatus.OK, message, x); - Logger.log(status); - } catch (CoreException x) { - Logger.log(x.getStatus()); - } - } - - return categories; - } - - /** - * <p>Gets the {@link CompletionProposalContentTypeContext} associated with the given content type, - * if one does not already exist then one is created</p> - * - * @param contentTypeID get the {@link CompletionProposalContentTypeContext} associated with this content type - * @return the existing or new {@link CompletionProposalContentTypeContext} associated with the given content type - */ - private CompletionProposalContentTypeContext getContext(String contentTypeID) { - CompletionProposalContentTypeContext context = (CompletionProposalContentTypeContext)this.fActivationContexts.get(contentTypeID); - if(context == null) { - context = new CompletionProposalContentTypeContext(contentTypeID); - this.fActivationContexts.put(contentTypeID, context); - } - - return context; - } - - /** - * <p>Gets all of the {@link CompletionProposalContentTypeContext}s associated with - * the given content type ID. A context is considered associated if its associated content type ID - * is either the given content type ID or is a base content type ID of the given content type ID.</p> - * - * @param contentTypeID get the contexts for this content type ID - * @return {@link List} of {@link CompletionProposalContentTypeContext}s associated with the given - * content type ID - */ - private List getContexts(String contentTypeID) { - List contexts = new ArrayList(); - IContentType contentType = Platform.getContentTypeManager().getContentType(contentTypeID); - - while(contentType != null) { - Object context = this.fActivationContexts.get(contentType.getId()); - if(context != null) { - contexts.add(context); - } - - contentType = contentType.getBaseType(); - } - - return contexts; - } - - private static class Activator { - IConfigurationElement fElement; - - public Activator(IConfigurationElement element) { - fElement = element; - } - - AutoActivationDelegate createAutoActivation() { - AutoActivationDelegate activation = null; - if (fElement != null) { - try { - activation = (AutoActivationDelegate) fElement.createExecutableExtension(ATTR_AUTO_ACTIVATION_CLASS); - } catch (CoreException e) { - } - } - return activation; - } - - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentassist/CompletionProposalContentTypeContext.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentassist/CompletionProposalContentTypeContext.java deleted file mode 100644 index 75ffdf0d4e..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentassist/CompletionProposalContentTypeContext.java +++ /dev/null @@ -1,147 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.contentassist; - -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * <p>There should be one context for each content type. It keeps track - * of the describers associated with different partition types for its unique - * content type.</p> - */ -public class CompletionProposalContentTypeContext { - - /** the content type this context is associated with */ - private final String fContentTypeID; - - /** - * - * <code>{@link Map}<{@link String}, {@link Set}<{@link CompletionProposalComputerDescriptor}>></code> - * <ul> - * <li><b>key:</b> partition type ID</li> - * <li><b>value:</b> {@link Set} of associated computer descriptors</li> - * </ul> - */ - private Map fPartitionTypesToDescriptors; - - /** - * <p>Create a new context for the given content type ID.</p> - * <p>There should only ever be one context for any unique content type</p> - * @param contentTypeID the content type this context is for - */ - public CompletionProposalContentTypeContext(String contentTypeID) { - this.fContentTypeID = contentTypeID; - this.fPartitionTypesToDescriptors = new HashMap(); - } - - /** - * <p>Adds a describer to this context for a given partition type. There - * can be more then one describer for one partition type.</p> - * - * @param partitionTypeID the partition type to associate the given descriptor with - * @param descriptor {@link CompletionProposalComputerDescriptor} to associate with the given - * partition type in this context - */ - public void putDescriptor(String partitionTypeID, CompletionProposalComputerDescriptor descriptor) { - Set descriptors = (Set)this.fPartitionTypesToDescriptors.get(partitionTypeID); - if(descriptors != null) { - descriptors.add(descriptor); - } else { - descriptors = new HashSet(); - descriptors.add(descriptor); - this.fPartitionTypesToDescriptors.put(partitionTypeID, descriptors); - } - } - - /** - * @return All of the {@link CompletionProposalComputerDescriptor}s associated with - * any partition type in this context - */ - public Set getDescriptors() { - Set allDescriptors = new HashSet(); - Collection descriptorSets = this.fPartitionTypesToDescriptors.values(); - Iterator iter = descriptorSets.iterator(); - while(iter.hasNext()) { - Set descriptorSet = (Set)iter.next(); - allDescriptors.addAll(descriptorSet); - } - - return Collections.unmodifiableSet(allDescriptors); - } - - /** - * @param partitionTypeID get {@link CompletionProposalComputerDescriptor}s for only this partition type - * for this context - * @return {@link CompletionProposalComputerDescriptor}s assoicated with the given partition type - * in this context - */ - public Set getDescriptors(String partitionTypeID) { - Set descriptors = (Set)this.fPartitionTypesToDescriptors.get(partitionTypeID); - return descriptors != null ? Collections.unmodifiableSet(descriptors) : Collections.EMPTY_SET; - } - - /** - * @return the content type this context is for - */ - public String getContentTypeID() { - return fContentTypeID; - } - - /** - * @return the hash code of the content type ID - * - * @see java.lang.Object#hashCode() - */ - public int hashCode() { - return fContentTypeID.hashCode(); - } - - /** - * <p>Two {@link CompletionProposalContentTypeContext} are equal if they have the - * same content type ID.</p> - * - * @see java.lang.Object#equals(java.lang.Object) - */ - public boolean equals(Object obj) { - boolean equal = false; - if(obj instanceof CompletionProposalContentTypeContext) { - equal = this.fContentTypeID.equals(((CompletionProposalContentTypeContext)obj).fContentTypeID); - } - - return equal; - } - - /** - * @see java.lang.Object#toString() - */ - public String toString() { - StringBuffer buff = new StringBuffer(this.fContentTypeID); - Set partitions = this.fPartitionTypesToDescriptors.keySet(); - Iterator partitionsIter = partitions.iterator(); - while(partitionsIter.hasNext()) { - String partitionType = (String)partitionsIter.next(); - buff.append("\n\t" + partitionType); //$NON-NLS-1$ - List descriptors = (List)this.fPartitionTypesToDescriptors.get(partitionType); - for(int i = 0; i < descriptors.size(); ++i) { - buff.append("\n\t\t" + descriptors.get(i).toString()); //$NON-NLS-1$ - } - } - - return buff.toString(); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentassist/CompletionProposoalCatigoriesConfigurationRegistry.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentassist/CompletionProposoalCatigoriesConfigurationRegistry.java deleted file mode 100644 index a84944a4a5..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentassist/CompletionProposoalCatigoriesConfigurationRegistry.java +++ /dev/null @@ -1,175 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.contentassist; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IConfigurationElement; -import org.eclipse.core.runtime.IExtensionRegistry; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.InvalidRegistryObjectException; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.Status; -import org.eclipse.wst.sse.ui.internal.Logger; -import org.eclipse.wst.sse.ui.internal.SSEUIPlugin; -import org.eclipse.wst.sse.ui.preferences.ICompletionProposalCategoriesConfigurationReader; -import org.eclipse.wst.sse.ui.preferences.ICompletionProposalCategoriesConfigurationWriter; - -/** - * <p>A registry for all extensions to the - * <code>org.eclipse.wst.sse.ui.completionProposalCategoriesConfiguration</code> - * extension point.</p> - */ -public final class CompletionProposoalCatigoriesConfigurationRegistry { - /** The extension schema name of the extension point */ - private static final String EXTENSION_POINT = "completionProposalCategoriesConfiguration"; //$NON-NLS-1$ - - /** The extension schema name of categories properties child elements */ - private static final String ELEM_CATEGORIES_PROPERTIES = "categoriesConfiguration"; //$NON-NLS-1$ - - /** The extension schema name of the content type id attribute */ - private static final String ATTR_CONTENT_TYPE_ID = "contentTypeID"; //$NON-NLS-1$ - - /** The extension schema name of the class attribute */ - private static final String ATTR_CLASS = "class"; //$NON-NLS-1$ - - /** The singleton instance. */ - private static CompletionProposoalCatigoriesConfigurationRegistry fgSingleton = null; - - /** <code>true</code> if this registry has been loaded. */ - private boolean fLoaded; - - /** - * <code>{@link Map}<{@link String}, {@link ICompletionProposalCategoriesConfigurationReader}></code> - * <ul> - * <li><b>key:</b> Content Type ID</li> - * <li><b>value:</b> Categories Properties</li> - */ - private Map fPropertiesByContentTypeID; - - /** - * @return the singleton instance of this registry - */ - public static synchronized CompletionProposoalCatigoriesConfigurationRegistry getDefault() { - if (fgSingleton == null) { - fgSingleton = new CompletionProposoalCatigoriesConfigurationRegistry(); - } - - return fgSingleton; - } - - /** - * Private constructor to create singleton instance - */ - private CompletionProposoalCatigoriesConfigurationRegistry() { - this.fLoaded = false; - this.fPropertiesByContentTypeID = new HashMap(); - } - - /** - * @param contentTypeID get the {@link ICompletionProposalCategoriesConfigurationReader} associated - * with the given content type - * @return the {@link ICompletionProposalCategoriesConfigurationReader} associated - * with the given content type, or <code>null</code> if one does not exist. - */ - public ICompletionProposalCategoriesConfigurationReader getReadableConfiguration(String contentTypeID) { - this.ensureLoaded(); - return (ICompletionProposalCategoriesConfigurationReader)this.fPropertiesByContentTypeID.get(contentTypeID); - } - - /** - * @param contentTypeID get the {@link ICompletionProposalCategoriesConfigurationWriter} associated - * with the given content type - * @return the {@link ICompletionProposalCategoriesConfigurationWriter} associated - * with the given content type, or <code>null</code> if one does not exist. - */ - public ICompletionProposalCategoriesConfigurationWriter getWritableConfiguration(String contentTypeID) { - this.ensureLoaded(); - - ICompletionProposalCategoriesConfigurationReader reader = getReadableConfiguration(contentTypeID); - ICompletionProposalCategoriesConfigurationWriter writer = null; - if(reader instanceof ICompletionProposalCategoriesConfigurationWriter) { - writer = (ICompletionProposalCategoriesConfigurationWriter)reader; - } - - return writer; - } - - /** - * Ensures the <code>org.eclipse.wst.sse.ui.completionProposalCategoriesConfiguration</code> - * extensions have been loaded - */ - private void ensureLoaded() { - if(!this.fLoaded) { - this.load(); - this.fLoaded = true; - } - } - - /** - * Loads the <code>org.eclipse.wst.sse.ui.completionProposalCategoriesConfiguration</code> extensions - */ - private void load() { - //get the extensions - IExtensionRegistry registry= Platform.getExtensionRegistry(); - List extensionElements= new ArrayList(Arrays.asList(registry.getConfigurationElementsFor(SSEUIPlugin.ID, EXTENSION_POINT))); - - //for each element get its attributes and add it to the map of properties - Iterator elementsIter = extensionElements.iterator(); - while(elementsIter.hasNext()) { - IConfigurationElement element = (IConfigurationElement)elementsIter.next(); - - try { - if(element.getName().equals(ELEM_CATEGORIES_PROPERTIES)) { - String contentTypeID = element.getAttribute(ATTR_CONTENT_TYPE_ID); - ContentAssistUtils.checkExtensionAttributeNotNull(contentTypeID, ATTR_CONTENT_TYPE_ID, element); - - String pageClass = element.getAttribute(ATTR_CLASS); - ContentAssistUtils.checkExtensionAttributeNotNull(pageClass, ATTR_CLASS, element); - - ICompletionProposalCategoriesConfigurationReader props = - (ICompletionProposalCategoriesConfigurationReader)element.createExecutableExtension(ATTR_CLASS); - - if(!this.fPropertiesByContentTypeID.containsKey(contentTypeID)){ - this.fPropertiesByContentTypeID.put(contentTypeID, props); - } else { - Logger.log(Logger.ERROR, "Extension " + element.getDeclaringExtension() + //$NON-NLS-1$ - " is attempting to to define itself as the proposal cateigories" + //$NON-NLS-1$ - " configuration for content type " + contentTypeID + " when another" + //$NON-NLS-1$ //$NON-NLS-2$ - " extensions has already done so."); //$NON-NLS-1$ - } - } else { - //extension specified element that is not valid for this extension - Logger.log(Logger.WARNING, "The element " + element + " is not valid for the" + //$NON-NLS-1$ //$NON-NLS-2$ - "org.eclipse.wst.sse.ui.completionProposalCategoriesConfiguration" + //$NON-NLS-1$ - " extension point. Only " + ELEM_CATEGORIES_PROPERTIES + //$NON-NLS-1$ - " elements are valid."); //$NON-NLS-1$ - } - } catch (InvalidRegistryObjectException x) { - /* - * Element is not valid any longer as the contributing plug-in was unloaded - * or for some other reason. - */ - String message = "The extension ''" + element.toString() + "'' has become invalid."; //$NON-NLS-1$ //$NON-NLS-2$ - IStatus status= new Status(IStatus.WARNING, SSEUIPlugin.ID, IStatus.OK, message, x); - Logger.log(status); - } catch (CoreException x) { - Logger.log(x.getStatus()); - } - } - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentassist/CompoundContentAssistProcessor.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentassist/CompoundContentAssistProcessor.java deleted file mode 100644 index 7e89b4395e..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentassist/CompoundContentAssistProcessor.java +++ /dev/null @@ -1,570 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ - -package org.eclipse.wst.sse.ui.internal.contentassist; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.LinkedHashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; - -import org.eclipse.core.runtime.Assert; -import org.eclipse.jface.contentassist.IContentAssistSubjectControl; -import org.eclipse.jface.contentassist.ISubjectControlContentAssistProcessor; -import org.eclipse.jface.contentassist.ISubjectControlContextInformationPresenter; -import org.eclipse.jface.contentassist.ISubjectControlContextInformationValidator; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.TextPresentation; -import org.eclipse.jface.text.contentassist.ICompletionProposal; -import org.eclipse.jface.text.contentassist.IContentAssistProcessor; -import org.eclipse.jface.text.contentassist.IContextInformation; -import org.eclipse.jface.text.contentassist.IContextInformationExtension; -import org.eclipse.jface.text.contentassist.IContextInformationPresenter; -import org.eclipse.jface.text.contentassist.IContextInformationValidator; -import org.eclipse.swt.graphics.Image; -import org.eclipse.wst.sse.ui.contentassist.StructuredContentAssistProcessor; -import org.eclipse.wst.sse.ui.internal.IReleasable; -import org.eclipse.wst.sse.ui.internal.Logger; - -/** - * <p>A processor that aggregates the proposals of multiple other processors. - * When proposals are requested, the contained processors are queried in the - * order they were added to the compound object. Copied from - * org.eclipse.jdt.internal.ui.text.CompoundContentAssistProcessor. - * Modification was made to add a dispose() method.</p> - */ -public class CompoundContentAssistProcessor implements IContentAssistProcessor, ISubjectControlContentAssistProcessor, IReleasable { - - /** the compound processors */ - private final Set fProcessors = new LinkedHashSet(); - - /** Aggregated error message from the compound processors */ - private String fErrorMessage; - - /** - * Creates a new instance. - */ - public CompoundContentAssistProcessor() { - } - - /** - * Creates a new instance with one child processor. - * - * @param processor - * the processor to add - */ - public CompoundContentAssistProcessor(IContentAssistProcessor processor) { - add(processor); - } - - /** - * Adds a processor to this compound processor. - * - * @param processor - * the processor to add - */ - public void add(IContentAssistProcessor processor) { - Assert.isNotNull(processor); - fProcessors.add(processor); - } - - /** - * @param processor check to see if this {@link IContentAssistProcessor} is one - * in this compound processor. - * - * @return <code>true</code> if this compound processor contains the given processor, - * <code>false</code> otherwise - */ - public boolean containsProcessor(IContentAssistProcessor processor) { - return fProcessors.contains(processor); - } - - /** - * Removes a processor from this compound processor. - * - * @param processor - * the processor to remove - */ - public void remove(IContentAssistProcessor processor) { - fProcessors.remove(processor); - } - - /** - * Creates a new instance and adds all specified processors. - * - * @param processors - */ - public CompoundContentAssistProcessor(IContentAssistProcessor[] processors) { - for (int i = 0; i < processors.length; i++) { - add(processors[i]); - } - } - - /* - * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#computeCompletionProposals(org.eclipse.jface.text.ITextViewer, - * int) - */ - public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int documentOffset) { - fErrorMessage = null; - List ret = new LinkedList(); - for (Iterator it = fProcessors.iterator(); it.hasNext();) { - IContentAssistProcessor p = (IContentAssistProcessor) it.next(); - try { - // isolate calls to each processor - ICompletionProposal[] proposals = p.computeCompletionProposals(viewer, documentOffset); - if (proposals != null && proposals.length > 0) { - ret.addAll(Arrays.asList(proposals)); - fErrorMessage = null; // Hide previous errors - } - else { - if (fErrorMessage == null && ret.isEmpty()) { - String errorMessage = p.getErrorMessage(); - if (errorMessage != null) { - fErrorMessage = errorMessage; - } - } - } - } - catch (Exception e) { - Logger.logException(e); - } - } - return (ICompletionProposal[]) ret.toArray(new ICompletionProposal[ret.size()]); - } - - /** - * {@inheritDoc} - * <p> - * The returned objects are wrapper objects around the real information - * containers. - * </p> - * - * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#computeContextInformation(org.eclipse.jface.text.ITextViewer, - * int) - */ - public IContextInformation[] computeContextInformation(ITextViewer viewer, int documentOffset) { - fErrorMessage = null; - List ret = new LinkedList(); - for (Iterator it = fProcessors.iterator(); it.hasNext();) { - IContentAssistProcessor p = (IContentAssistProcessor) it.next(); - IContextInformation[] informations = p.computeContextInformation(viewer, documentOffset); - if (informations != null && informations.length > 0) { - for (int i = 0; i < informations.length; i++) - ret.add(new WrappedContextInformation(informations[i], p)); - fErrorMessage = null; // Hide previous errors - } else { - if (fErrorMessage == null && ret.isEmpty()) { - String errorMessage = p.getErrorMessage(); - if (errorMessage != null) { - fErrorMessage = errorMessage; - } - } - } - } - return (IContextInformation[]) ret.toArray(new IContextInformation[ret.size()]); - } - - /* - * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getCompletionProposalAutoActivationCharacters() - */ - public char[] getCompletionProposalAutoActivationCharacters() { - Set ret = new LinkedHashSet(); - for (Iterator it = fProcessors.iterator(); it.hasNext();) { - IContentAssistProcessor p = (IContentAssistProcessor) it.next(); - char[] chars = p.getCompletionProposalAutoActivationCharacters(); - if (chars != null) - for (int i = 0; i < chars.length; i++) - ret.add(new Character(chars[i])); - } - - char[] chars = new char[ret.size()]; - int i = 0; - for (Iterator it = ret.iterator(); it.hasNext(); i++) { - Character ch = (Character) it.next(); - chars[i] = ch.charValue(); - } - return chars; - } - - /* - * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getContextInformationAutoActivationCharacters() - */ - public char[] getContextInformationAutoActivationCharacters() { - Set ret = new LinkedHashSet(); - for (Iterator it = fProcessors.iterator(); it.hasNext();) { - IContentAssistProcessor p = (IContentAssistProcessor) it.next(); - char[] chars = p.getContextInformationAutoActivationCharacters(); - if (chars != null) - for (int i = 0; i < chars.length; i++) - ret.add(new Character(chars[i])); - } - - char[] chars = new char[ret.size()]; - int i = 0; - for (Iterator it = ret.iterator(); it.hasNext(); i++) { - Character ch = (Character) it.next(); - chars[i] = ch.charValue(); - } - return chars; - } - - /** - * Returns the error message of one of - * contained processor if any, or <code>null</code> if no processor has an - * error message. - * - * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getErrorMessage() - * @return {@inheritDoc} - */ - public String getErrorMessage() { - return fErrorMessage; - } - - /** - * {@inheritDoc} - * <p> - * The returned validator is a wrapper around the validators provided by - * the child processors. - * </p> - * - * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getContextInformationValidator() - */ - public IContextInformationValidator getContextInformationValidator() { - boolean hasValidator = false; - boolean hasPresenter = false; - boolean hasExtension = false; - - Iterator itp = fProcessors.iterator(); - while (itp.hasNext() && (!hasPresenter || !hasExtension)) { - IContentAssistProcessor p = (IContentAssistProcessor) itp.next(); - IContextInformationValidator v = p.getContextInformationValidator(); - if (v != null) { - hasValidator = true; - if (v instanceof IContextInformationPresenter) { - hasPresenter = true; - } - if (v instanceof ISubjectControlContextInformationPresenter || v instanceof ISubjectControlContextInformationValidator) { - hasExtension = true; - } - } - } - - CompoundContentAssistValidator validator = null; - if (hasPresenter && hasExtension) - validator = new CompoundContentAssistValidatorPresenterEx(); - else if (hasPresenter) - validator = new CompoundContentAssistValidatorPresenter(); - else if (hasExtension) - validator = new CompoundContentAssistValidatorEx(); - else if (hasValidator) - validator = new CompoundContentAssistValidator(); - - if (validator != null) - for (Iterator it = fProcessors.iterator(); it.hasNext();) { - IContentAssistProcessor p = (IContentAssistProcessor) it.next(); - IContextInformationValidator v = p.getContextInformationValidator(); - if (v != null) - validator.add(v); - } - - return validator; - } - - /* - * @see ISubjectControlContentAssistProcessor#computeCompletionProposals(IContentAssistSubjectControl, - * int) - */ - public ICompletionProposal[] computeCompletionProposals(IContentAssistSubjectControl contentAssistSubjectControl, int documentOffset) { - fErrorMessage = null; - List ret = new LinkedList(); - for (Iterator it = fProcessors.iterator(); it.hasNext();) { - Object o = it.next(); - if (o instanceof ISubjectControlContentAssistProcessor) { - ISubjectControlContentAssistProcessor p = (ISubjectControlContentAssistProcessor) o; - ICompletionProposal[] proposals = p.computeCompletionProposals(contentAssistSubjectControl, documentOffset); - if (proposals != null && proposals.length > 0) { - ret.addAll(Arrays.asList(proposals)); - fErrorMessage = null; // Hide previous errors - } else { - if (fErrorMessage == null && ret.isEmpty()) { - String errorMessage = p.getErrorMessage(); - if (errorMessage != null) { - fErrorMessage = errorMessage; - } - } - } - } - } - - return (ICompletionProposal[]) ret.toArray(new ICompletionProposal[ret.size()]); - } - - /** - * {@inheritDoc} - * <p> - * The returned objects are wrapper objects around the real information - * containers. - * </p> - * - * @see org.eclipse.jface.contentassist.ISubjectControlContentAssistProcessor#computeContextInformation(org.eclipse.jface.text.contentassist.IContentAssistSubject, - * int) - */ - public IContextInformation[] computeContextInformation(IContentAssistSubjectControl contentAssistSubjectControl, int documentOffset) { - fErrorMessage = null; - List ret = new LinkedList(); - for (Iterator it = fProcessors.iterator(); it.hasNext();) { - Object o = it.next(); - if (o instanceof ISubjectControlContentAssistProcessor) { - ISubjectControlContentAssistProcessor p = (ISubjectControlContentAssistProcessor) o; - IContextInformation[] informations = p.computeContextInformation(contentAssistSubjectControl, documentOffset); - if (informations != null && informations.length > 0) { - for (int i = 0; i < informations.length; i++) - ret.add(new WrappedContextInformation(informations[i], p)); - fErrorMessage = null; // Hide previous errors - } else { - if (fErrorMessage == null && ret.isEmpty()) { - String errorMessage = p.getErrorMessage(); - if (errorMessage != null) { - fErrorMessage = errorMessage; - } - } - } - } - } - return (IContextInformation[]) ret.toArray(new IContextInformation[ret.size()]); - } - - /** - * Dispose of any content assist processors that need disposing - * @deprecated use {@link #release()} - */ - public void dispose() { - this.release(); - } - - public void install(ITextViewer viewer) { - for (Iterator it = fProcessors.iterator(); it.hasNext();) { - IContentAssistProcessor p = (IContentAssistProcessor) it.next(); - if (p instanceof StructuredContentAssistProcessor) { - ((StructuredContentAssistProcessor) p).install(viewer); - } - } - } - - /** - * @see org.eclipse.wst.sse.ui.internal.IReleasable#release() - */ - public void release() { - // go through list of content assist processors and dispose - for (Iterator it = fProcessors.iterator(); it.hasNext();) { - IContentAssistProcessor p = (IContentAssistProcessor) it.next(); - if (p instanceof IReleasable) { - ((IReleasable) p).release(); - } - } - } - - private static class WrappedContextInformation implements IContextInformation, IContextInformationExtension { - private IContextInformation fInfo; - private IContentAssistProcessor fProcessor; - - WrappedContextInformation(IContextInformation info, IContentAssistProcessor processor) { - fInfo = info; - fProcessor = processor; - } - - /* - * @see java.lang.Object#equals(java.lang.Object) - */ - public boolean equals(Object obj) { - return fInfo.equals(obj); - } - - /* - * @see org.eclipse.jface.text.contentassist.IContextInformation#getContextDisplayString() - */ - public String getContextDisplayString() { - return fInfo.getContextDisplayString(); - } - - /* - * @see org.eclipse.jface.text.contentassist.IContextInformation#getImage() - */ - public Image getImage() { - return fInfo.getImage(); - } - - /* - * @see org.eclipse.jface.text.contentassist.IContextInformation#getInformationDisplayString() - */ - public String getInformationDisplayString() { - return fInfo.getInformationDisplayString(); - } - - /* - * @see java.lang.Object#hashCode() - */ - public int hashCode() { - return fInfo.hashCode(); - } - - /* - * @see java.lang.Object#toString() - */ - public String toString() { - return fInfo.toString(); - } - - IContentAssistProcessor getProcessor() { - return fProcessor; - } - - IContextInformation getContextInformation() { - return fInfo; - } - - public int getContextInformationPosition() { - int position = -1; - if (fInfo instanceof IContextInformationExtension) - position = ((IContextInformationExtension)fInfo).getContextInformationPosition(); - return position; - } - } - - private static class CompoundContentAssistValidator implements IContextInformationValidator { - List fValidators = new ArrayList(); - IContextInformationValidator fValidator; - - void add(IContextInformationValidator validator) { - fValidators.add(validator); - } - - /* - * @see org.eclipse.jface.text.contentassist.IContextInformationValidator#install(org.eclipse.jface.text.contentassist.IContextInformation, - * org.eclipse.jface.text.ITextViewer, int) - */ - public void install(IContextInformation info, ITextViewer viewer, int documentPosition) { - // install either the validator in the info, or all validators - fValidator = getValidator(info); - IContextInformation realInfo = getContextInformation(info); - if (fValidator != null) - fValidator.install(realInfo, viewer, documentPosition); - else { - for (Iterator it = fValidators.iterator(); it.hasNext();) { - IContextInformationValidator v = (IContextInformationValidator) it.next(); - v.install(realInfo, viewer, documentPosition); - } - } - } - - IContextInformationValidator getValidator(IContextInformation info) { - if (info instanceof WrappedContextInformation) { - WrappedContextInformation wrap = (WrappedContextInformation) info; - return wrap.getProcessor().getContextInformationValidator(); - } - - return null; - } - - IContextInformation getContextInformation(IContextInformation info) { - IContextInformation realInfo = info; - if (info instanceof WrappedContextInformation) { - WrappedContextInformation wrap = (WrappedContextInformation) info; - realInfo = wrap.getContextInformation(); - } - - return realInfo; - } - - /* - * @see org.eclipse.jface.text.contentassist.IContextInformationValidator#isContextInformationValid(int) - */ - public boolean isContextInformationValid(int documentPosition) { - // use either the validator in the info, or all validators - boolean isValid = false; - if (fValidator != null) - isValid = fValidator.isContextInformationValid(documentPosition); - else { - for (Iterator it = fValidators.iterator(); it.hasNext();) { - IContextInformationValidator v = (IContextInformationValidator) it.next(); - isValid |= v.isContextInformationValid(documentPosition); - } - } - return isValid; - } - - } - - private static class CompoundContentAssistValidatorPresenter extends CompoundContentAssistValidator implements IContextInformationPresenter { - public boolean updatePresentation(int offset, TextPresentation presentation) { - // use either the validator in the info, or all validators - boolean presentationUpdated = false; - if (fValidator instanceof IContextInformationPresenter) - presentationUpdated = ((IContextInformationPresenter) fValidator).updatePresentation(offset, presentation); - else { - for (Iterator it = fValidators.iterator(); it.hasNext();) { - IContextInformationValidator v = (IContextInformationValidator) it.next(); - if (v instanceof IContextInformationPresenter) - presentationUpdated |= ((IContextInformationPresenter) v).updatePresentation(offset, presentation); - } - } - return presentationUpdated; - } - } - - private static class CompoundContentAssistValidatorEx extends CompoundContentAssistValidator implements ISubjectControlContextInformationValidator { - /* - * @see ISubjectControlContextInformationValidator#install(IContextInformation, - * IContentAssistSubjectControl, int) - */ - public void install(IContextInformation info, IContentAssistSubjectControl contentAssistSubjectControl, int documentPosition) { - // install either the validator in the info, or all validators - fValidator = getValidator(info); - IContextInformation realInfo = getContextInformation(info); - if (fValidator instanceof ISubjectControlContextInformationValidator) - ((ISubjectControlContextInformationValidator) fValidator).install(realInfo, contentAssistSubjectControl, documentPosition); - else { - for (Iterator it = fValidators.iterator(); it.hasNext();) { - if (it.next() instanceof ISubjectControlContextInformationValidator) - ((ISubjectControlContextInformationValidator) it.next()).install(realInfo, contentAssistSubjectControl, documentPosition); - } - } - } - - } - - private static class CompoundContentAssistValidatorPresenterEx extends CompoundContentAssistValidatorPresenter implements ISubjectControlContextInformationPresenter, ISubjectControlContextInformationValidator { - /* - * @see ISubjectControlContextInformationPresenter#install(IContextInformation, - * IContentAssistSubjectControl, int) - */ - public void install(IContextInformation info, IContentAssistSubjectControl contentAssistSubjectControl, int documentPosition) { - // install either the validator in the info, or all validators - fValidator = getValidator(info); - IContextInformation realInfo = getContextInformation(info); - - if (fValidator instanceof ISubjectControlContextInformationValidator) - ((ISubjectControlContextInformationValidator) fValidator).install(realInfo, contentAssistSubjectControl, documentPosition); - else { - for (Iterator it = fValidators.iterator(); it.hasNext();) { - if (it.next() instanceof ISubjectControlContextInformationValidator) - ((ISubjectControlContextInformationValidator) it.next()).install(realInfo, contentAssistSubjectControl, documentPosition); - } - } - } - - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentassist/ContentAssistUtils.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentassist/ContentAssistUtils.java deleted file mode 100644 index 9b1fa9299e..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentassist/ContentAssistUtils.java +++ /dev/null @@ -1,146 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.contentassist; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IConfigurationElement; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.InvalidRegistryObjectException; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.Status; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.wst.sse.core.StructuredModelManager; -import org.eclipse.wst.sse.core.internal.provisional.IModelManager; -import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel; -import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion; -import org.eclipse.wst.sse.ui.internal.SSEUIPlugin; -import org.osgi.framework.Bundle; - - -/** - * @author pavery - * - */ -public class ContentAssistUtils { - - /** - * Returns the closest IndexedRegion for the offset and viewer allowing - * for differences between viewer offsets and model positions. note: this - * method returns an IndexedRegion for read only - * - * @param viewer - * the viewer whose document is used to compute the proposals - * @param documentOffset - * an offset within the document for which completions should - * be computed - * @return an IndexedRegion - */ - public static IndexedRegion getNodeAt(ITextViewer viewer, int documentOffset) { - - if (viewer == null) - return null; - - IndexedRegion node = null; - IModelManager mm = StructuredModelManager.getModelManager(); - IStructuredModel model = null; - if (mm != null) - model = mm.getExistingModelForRead(viewer.getDocument()); - try { - if (model != null) { - int lastOffset = documentOffset; - node = model.getIndexedRegion(documentOffset); - while (node == null && lastOffset >= 0) { - lastOffset--; - node = model.getIndexedRegion(lastOffset); - } - } - } finally { - if (model != null) - model.releaseFromRead(); - } - return node; - } - - /** - * Returns the closest IStructuredDocumentRegion for the offest and - * viewer. - * - * @param viewer - * @param documentOffset - * @return the closest IStructuredDocumentRegion for the offest and - * viewer. - */ - public static IStructuredDocumentRegion getStructuredDocumentRegion(ITextViewer viewer, int documentOffset) { - IStructuredDocumentRegion sdRegion = null; - if (viewer == null || viewer.getDocument() == null) - return null; - - int lastOffset = documentOffset; - IStructuredDocument doc = (IStructuredDocument) viewer.getDocument(); - sdRegion = doc.getRegionAtCharacterOffset(documentOffset); - while (sdRegion == null && lastOffset >= 0) { - lastOffset--; - sdRegion = doc.getRegionAtCharacterOffset(lastOffset); - } - return sdRegion; - } - - /** - * @return the bundle that defined the {@link IConfigurationElement} that defines - * this category. - */ - public static Bundle getBundle(IConfigurationElement element) { - String namespace= element.getDeclaringExtension().getContributor().getName(); - Bundle bundle= Platform.getBundle(namespace); - return bundle; - } - - /** - * <p>Checks that the given attribute value is not <code>null</code>.</p> - * - * @param value the object to check if not null - * @param attribute the attribute - * - * @throws InvalidRegistryObjectException if the registry element is no longer valid - * @throws CoreException if <code>value</code> is <code>null</code> - */ - public static void checkExtensionAttributeNotNull(Object value, String attribute, - IConfigurationElement element) throws InvalidRegistryObjectException, CoreException { - - if (value == null) { - String message = "The extension \"" + element.getDeclaringExtension().getUniqueIdentifier() + //$NON-NLS-1$ - "\" from plug-in \"" + element.getContributor().getName() + //$NON-NLS-1$ - "\" did not specify a value for the required \"" + attribute + //$NON-NLS-1$ - "\" attribute for the element \"" + element.getName() + "\". Disabling the extension."; //$NON-NLS-1$ //$NON-NLS-2$ - IStatus status= new Status(IStatus.WARNING, SSEUIPlugin.ID, IStatus.OK, message, null); - throw new CoreException(status); - } - } - - /** - * @param textViewer check to see if this viewer is empty - * @return <code>true</code> if there is no text or it's all white space, - * <code>false</code> otherwise - */ - public static boolean isViewerEmpty(ITextViewer textViewer) { - boolean isEmpty = false; - String text = textViewer.getTextWidget().getText(); - if ((text == null) || ((text != null) && text.trim().equals(""))) { //$NON-NLS-1$ - isEmpty = true; - } - return isEmpty; - } - -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentassist/ContextInformationValidator.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentassist/ContextInformationValidator.java deleted file mode 100644 index cbaf65f465..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentassist/ContextInformationValidator.java +++ /dev/null @@ -1,90 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.contentassist; - -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.contentassist.IContextInformation; -import org.eclipse.jface.text.contentassist.IContextInformationValidator; -import org.eclipse.wst.sse.core.StructuredModelManager; -import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel; -import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument; - -/** - * <p>A {@link IContextInformationValidator} for structured documents</p> - */ -public class ContextInformationValidator implements IContextInformationValidator { - - /** the installed document position */ - private int fDocumentPosition; - - /** the installed document */ - private IStructuredDocument fDocument; - - /** the installed region start*/ - private IndexedRegion fRegion; - - /** - * <p>Default constructor</p> - */ - public ContextInformationValidator() { - fDocumentPosition = -1; - fDocument = null; - } - - /** - * @see org.eclipse.jface.text.contentassist.IContextInformationValidator#install(org.eclipse.jface.text.contentassist.IContextInformation, - * org.eclipse.jface.text.ITextViewer, int) - */ - public void install(IContextInformation info, ITextViewer viewer, int documentPosition) { - fDocumentPosition = documentPosition; - fDocument = (IStructuredDocument)viewer.getDocument(); - } - - /** - * @see org.eclipse.jface.text.contentassist.IContextInformationValidator#isContextInformationValid(int) - */ - public boolean isContextInformationValid(int documentPosition) { - /* - * determine whether or not this context info should still be - * showing... if cursor still within the same region then it's valid - */ - boolean result = false; - - calculateInstalledIndexedRegion(); - - if (fRegion != null) { - int start = fRegion.getStartOffset(); - int end = fRegion.getEndOffset(); - result = (documentPosition < end) && (documentPosition > start + 1); - } - return result; - } - - /** - * @return {@link IndexedRegion} that this validator was installed on - */ - private void calculateInstalledIndexedRegion() { - if (fRegion == null) { - IStructuredModel model = null; - try { - model = StructuredModelManager.getModelManager().getModelForRead(fDocument); - if (model != null) { - fRegion = model.getIndexedRegion(fDocumentPosition); - } - } - finally { - if (model != null) - model.releaseFromRead(); - } - } - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentassist/CustomCompletionProposal.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentassist/CustomCompletionProposal.java deleted file mode 100644 index f39ba52bd8..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentassist/CustomCompletionProposal.java +++ /dev/null @@ -1,334 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.contentassist; - -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.DocumentEvent; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.ITextViewerExtension5; -import org.eclipse.jface.text.contentassist.CompletionProposal; -import org.eclipse.jface.text.contentassist.ICompletionProposal; -import org.eclipse.jface.text.contentassist.ICompletionProposalExtension; -import org.eclipse.jface.text.contentassist.ICompletionProposalExtension2; -import org.eclipse.jface.text.contentassist.IContextInformation; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.graphics.Point; -import org.eclipse.wst.sse.core.internal.util.Debug; - -/** - * An implementation of ICompletionProposal whose values can be read after - * creation. - */ -public class CustomCompletionProposal implements ICompletionProposal, ICompletionProposalExtension, ICompletionProposalExtension2, IRelevanceCompletionProposal { - - private String fAdditionalProposalInfo; - - private IContextInformation fContextInformation; - - private int fCursorPosition = 0; - - private String fDisplayString; - - private String fAlternateMatch; - - private Image fImage; - - private int fRelevance = IRelevanceConstants.R_NONE; - - private int fReplacementLength = 0; - - private int fReplacementOffset = 0; - - private String fReplacementString = null; - - private boolean fUpdateLengthOnValidate; - - private char[] fTriggers; - - /** - * Constructor with relevance and replacement length update flag. - * - * If the <code>updateReplacementLengthOnValidate</code> flag is true, - * then when the user types, the replacement length will be incremented by - * the number of new characters inserted from the original position. - * Otherwise the replacement length will not change on validate. - * - * ex. - * - * <tag |name="attr"> - the replacement length is 4 <tag i|name="attr"> - - * the replacement length is now 5 <tag id|name="attr"> - the replacement - * length is now 6 <tag |name="attr"> - the replacementlength is now 4 - * again <tag |name="attr"> - the replacment length remains 4 - * - */ - public CustomCompletionProposal(String replacementString, int replacementOffset, int replacementLength, int cursorPosition, Image image, String displayString, IContextInformation contextInformation, String additionalProposalInfo, int relevance, boolean updateReplacementLengthOnValidate) { - this(replacementString, replacementOffset, replacementLength, cursorPosition, image, displayString, null, contextInformation, additionalProposalInfo, relevance, updateReplacementLengthOnValidate); - } - - public CustomCompletionProposal(String replacementString, int replacementOffset, int replacementLength, int cursorPosition, Image image, String displayString, IContextInformation contextInformation, String additionalProposalInfo, int relevance) { - this(replacementString, replacementOffset, replacementLength, cursorPosition, image, displayString, contextInformation, additionalProposalInfo, relevance, true); - } - - public CustomCompletionProposal(String replacementString, int replacementOffset, int replacementLength, int cursorPosition, Image image, String displayString, String alternateMatch, IContextInformation contextInformation, String additionalProposalInfo, int relevance, boolean updateReplacementLengthOnValidate) { - fReplacementString = replacementString; - fReplacementOffset = replacementOffset; - fReplacementLength = replacementLength; - fCursorPosition = cursorPosition; - fImage = image; - fDisplayString = displayString; - fAlternateMatch = alternateMatch; - fContextInformation = contextInformation; - fAdditionalProposalInfo = additionalProposalInfo; - fRelevance = relevance; - fUpdateLengthOnValidate = updateReplacementLengthOnValidate; - } - - public void apply(IDocument document) { - CompletionProposal proposal = new CompletionProposal(getReplacementString(), getReplacementOffset(), getReplacementLength(), getCursorPosition(), getImage(), getDisplayString(), getContextInformation(), getAdditionalProposalInfo()); - proposal.apply(document); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension#apply(org.eclipse.jface.text.IDocument, - * char, int) - */ - public void apply(IDocument document, char trigger, int offset) { - CompletionProposal proposal = new CompletionProposal(getReplacementString(), getReplacementOffset(), getReplacementLength(), getCursorPosition(), getImage(), getDisplayString(), getContextInformation(), getAdditionalProposalInfo()); - // we currently don't do anything special for which character - // selected the proposal, and where the cursor offset is - // but we might in the future... - proposal.apply(document); - // we want to ContextInformationPresenter.updatePresentation() here - } - - public void apply(ITextViewer viewer, char trigger, int stateMask, int offset) { - IDocument document = viewer.getDocument(); - // CMVC 252634 to compensate for "invisible" initial region - int caretOffset = viewer.getTextWidget().getCaretOffset(); - if (viewer instanceof ITextViewerExtension5) { - ITextViewerExtension5 extension = (ITextViewerExtension5) viewer; - caretOffset = extension.widgetOffset2ModelOffset(caretOffset); - } - else { - caretOffset = viewer.getTextWidget().getCaretOffset() + viewer.getVisibleRegion().getOffset(); - } - - if (caretOffset == getReplacementOffset()) { - apply(document); - } - else { - // replace the text without affecting the caret Position as this - // causes the cursor to move on its own - try { - int endOffsetOfChanges = getReplacementString().length() + getReplacementOffset(); - // Insert the portion of the new text that comes after the - // current caret position - if (endOffsetOfChanges >= caretOffset) { - int postCaretReplacementLength = getReplacementOffset() + getReplacementLength() - caretOffset; - int preCaretReplacementLength = getReplacementString().length() - (endOffsetOfChanges - caretOffset); - if (postCaretReplacementLength < 0) { - if (Debug.displayWarnings) { - System.out.println("** postCaretReplacementLength was negative: " + postCaretReplacementLength); //$NON-NLS-1$ - } - // This is just a quick fix while I figure out what - // replacement length is supposed to be - // in each case, otherwise we'll get negative - // replacment length sometimes - postCaretReplacementLength = 0; - } - document.replace(caretOffset, postCaretReplacementLength, getReplacementString().substring(preCaretReplacementLength)); - } - // Insert the portion of the new text that comes before the - // current caret position - // Done second since offsets would change for the post text - // otherwise - // Outright insertions are handled here - if (caretOffset > getReplacementOffset()) { - int preCaretTextLength = caretOffset - getReplacementOffset(); - document.replace(getReplacementOffset(), preCaretTextLength, getReplacementString().substring(0, preCaretTextLength)); - } - } - catch (BadLocationException x) { - apply(document); - } - catch (StringIndexOutOfBoundsException e) { - apply(document); - } - } - } - - public String getAdditionalProposalInfo() { - // return fProposal.getAdditionalProposalInfo(); - return fAdditionalProposalInfo; - } - - public IContextInformation getContextInformation() { - // return fProposal.getContextInformation(); - return fContextInformation; - } - - public void setContextInformation(IContextInformation contextInfo) { - fContextInformation = contextInfo; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension#getContextInformationPosition() - */ - public int getContextInformationPosition() { - // https://bugs.eclipse.org/bugs/show_bug.cgi?id=110355 - // return getCursorPosition(); - if (getContextInformation() == null) - return getReplacementOffset() - 1; - return getReplacementOffset() + getCursorPosition(); - } - - public int getCursorPosition() { - return fCursorPosition; - } - - public void setCursorPosition(int pos) { - fCursorPosition = pos; - } - - public void setDisplayString(String newDisplayString) { - fDisplayString = newDisplayString; - } - - public String getDisplayString() { - // return fProposal.getDisplayString(); - return fDisplayString; - } - - public Image getImage() { - // return fProposal.getImage(); - return fImage; - } - - public int getRelevance() { - return fRelevance; - } - - public void setReplacementLength(int newReplacementLength) { - fReplacementLength = newReplacementLength; - } - - public int getReplacementLength() { - return fReplacementLength; - } - - public int getReplacementOffset() { - return fReplacementOffset; - } - - public String getReplacementString() { - return fReplacementString; - } - - public Point getSelection(IDocument document) { - // return fProposal.getSelection(document); - CompletionProposal proposal = new CompletionProposal(getReplacementString(), getReplacementOffset(), getReplacementLength(), getCursorPosition(), getImage(), getDisplayString(), getContextInformation(), getAdditionalProposalInfo()); - return proposal.getSelection(document); - } - - /** - * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension#getTriggerCharacters() - */ - - public char[] getTriggerCharacters() { - return fTriggers; - } - - public void setTriggerCharacters(char[] triggers) { - fTriggers = triggers; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension#isValidFor(org.eclipse.jface.text.IDocument, - * int) - */ - public boolean isValidFor(IDocument document, int offset) { - return validate(document, offset, null); - } - - /** - * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#selected(org.eclipse.jface.text.ITextViewer, - * boolean) - */ - public void selected(ITextViewer viewer, boolean smartToggle) { - } - - // code is borrowed from JavaCompletionProposal - protected boolean startsWith(IDocument document, int offset, String word) { - - int wordLength = word == null ? 0 : word.length(); - if (offset > fReplacementOffset + wordLength) - return false; - - try { - int length = offset - fReplacementOffset; - String start = document.get(fReplacementOffset, length); - - return (word != null && word.substring(0, length).equalsIgnoreCase(start)) || (fAlternateMatch != null && length <= fAlternateMatch.length() && fAlternateMatch.substring(0, length).equalsIgnoreCase(start)); - } - catch (BadLocationException x) { - } - - return false; - } - - /** - * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#unselected(org.eclipse.jface.text.ITextViewer) - */ - public void unselected(ITextViewer viewer) { - } - - /** - * borrowed from JavaCompletionProposal - * - * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#validate(org.eclipse.jface.text.IDocument, - * int, org.eclipse.jface.text.DocumentEvent) - */ - public boolean validate(IDocument document, int offset, DocumentEvent event) { - if (offset < fReplacementOffset) - return false; - boolean validated = startsWith(document, offset, fDisplayString); - - if (fUpdateLengthOnValidate && event != null) { - fReplacementLength += event.fText.length() - event.fLength; //adjust the replacement length by the event's text replacement - } - return validated; - } - - /** - * @param replacementOffset - * The fReplacementOffset to set. - */ - public void setReplacementOffset(int replacementOffset) { - fReplacementOffset = replacementOffset; - } - - /** - * @param replacementString - * The fReplacementString to set. - */ - public void setReplacementString(String replacementString) { - fReplacementString = replacementString; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentassist/IRelevanceCompletionProposal.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentassist/IRelevanceCompletionProposal.java deleted file mode 100644 index 7e3f7a6df5..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentassist/IRelevanceCompletionProposal.java +++ /dev/null @@ -1,28 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.contentassist; - - -/** - * CompletionProposal with a relevance value. The relevance value is used to - * sort the completion proposals. Proposals with higher relevance should be - * listed before proposals with lower relevance. - * - * @author pavery - */ -public interface IRelevanceCompletionProposal { - /** - * Returns the relevance of the proposal. - */ - int getRelevance(); -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentassist/IRelevanceConstants.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentassist/IRelevanceConstants.java deleted file mode 100644 index ba5a16ed30..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentassist/IRelevanceConstants.java +++ /dev/null @@ -1,17 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.contentassist; - -public interface IRelevanceConstants { - int R_NONE = 0; -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentassist/OptionalMessageDialog.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentassist/OptionalMessageDialog.java deleted file mode 100644 index 04cde16639..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentassist/OptionalMessageDialog.java +++ /dev/null @@ -1,145 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.contentassist; - -import org.eclipse.jface.dialogs.IDialogConstants; -import org.eclipse.jface.dialogs.IDialogSettings; -import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; -import org.eclipse.wst.sse.ui.internal.SSEUIPlugin; - -/** - * <p>This is a <code>MessageDialog</code> which allows the user - * to choose that the dialog isn't shown again the next time.</p> - * - * @base org.eclipse.jdt.internal.ui.dialogs.OptionalMessageDialog - */ -public class OptionalMessageDialog extends MessageDialog { - - // String constants for widgets - private static final String CHECKBOX_TEXT = SSEUIMessages.OptionalMessageDialog_dontShowAgain; - - // Dialog store id constants - private static final String STORE_ID = "ContentAssist_OptionalMessageDialog.hide."; //$NON-NLS-1$ - - public static final int NOT_SHOWN = IDialogConstants.CLIENT_ID + 1; - - private final String fId; - private final String fCheckBoxText; - - private Button fHideDialogCheckBox; - - - /** - * Opens the dialog but only if the user hasn't chosen to hide it. - * - * @return the index of the pressed button or {@link SWT#DEFAULT} if the dialog got dismissed - * without pressing a button (e.g. via Esc) or {{@link #NOT_SHOWN} if the dialog was not - * shown - */ - public static int open(String id, Shell parent, String title, Image titleImage, String message, int dialogType, String[] buttonLabels, int defaultButtonIndex) { - return open(id, parent, title, titleImage, message, dialogType, buttonLabels, defaultButtonIndex, CHECKBOX_TEXT); - } - - /** - * Opens the dialog but only if the user hasn't chosen to hide it. - * - * @return the index of the pressed button or {@link SWT#DEFAULT} if the dialog got dismissed - * without pressing a button (e.g. via Esc) or {{@link #NOT_SHOWN} if the dialog was not - * shown - */ - public static int open(String id, Shell parent, String title, Image titleImage, String message, int dialogType, String[] buttonLabels, int defaultButtonIndex, String checkboxText) { - if (!isDialogEnabled(id)) - return OptionalMessageDialog.NOT_SHOWN; - - MessageDialog dialog= new OptionalMessageDialog(id, parent, title, titleImage, message, dialogType, buttonLabels, defaultButtonIndex, checkboxText); - return dialog.open(); - } - - protected OptionalMessageDialog(String id, Shell parent, String title, Image titleImage, String message, int dialogType, String[] buttonLabels, int defaultButtonIndex) { - this(id, parent, title, titleImage, message, dialogType, buttonLabels, defaultButtonIndex, CHECKBOX_TEXT); - } - - protected OptionalMessageDialog(String id, Shell parent, String title, Image titleImage, String message, int dialogType, String[] buttonLabels, int defaultButtonIndex, String checkBoxText) { - super(parent, title, titleImage, message, dialogType, buttonLabels, defaultButtonIndex); - fId= id; - fCheckBoxText= checkBoxText; - } - - protected Control createCustomArea(Composite parent) { - Composite composite= new Composite(parent, SWT.NONE); - GridLayout layout= new GridLayout(); - layout.marginHeight= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); - layout.marginWidth= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); - layout.horizontalSpacing= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); - composite.setLayout(layout); - composite.setLayoutData(new GridData(GridData.FILL_BOTH)); - - fHideDialogCheckBox= new Button(composite, SWT.CHECK | SWT.LEFT); - fHideDialogCheckBox.setText(fCheckBoxText); - fHideDialogCheckBox.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent e) { - setDialogEnabled(fId, !((Button)e.widget).getSelection()); - } - }); - applyDialogFont(fHideDialogCheckBox); - return fHideDialogCheckBox; - } - - //--------------- Configuration handling -------------- - - /** - * Returns this dialog - * - * @return the settings to be used - */ - private static IDialogSettings getDialogSettings() { - IDialogSettings settings= SSEUIPlugin.getDefault().getDialogSettings(); - settings= settings.getSection(STORE_ID); - if (settings == null) - settings= SSEUIPlugin.getDefault().getDialogSettings().addNewSection(STORE_ID); - return settings; - } - - /** - * Answers whether the optional dialog is enabled and should be shown. - */ - public static boolean isDialogEnabled(String key) { - IDialogSettings settings= getDialogSettings(); - return !settings.getBoolean(key); - } - - /** - * Sets whether the optional dialog is enabled and should be shown. - */ - public static void setDialogEnabled(String key, boolean isEnabled) { - IDialogSettings settings= getDialogSettings(); - settings.put(key, !isEnabled); - } - - /** - * Clears all remembered information about hidden dialogs - */ - public static void clearAllRememberedStates() { - IDialogSettings settings= SSEUIPlugin.getDefault().getDialogSettings(); - settings.addNewSection(STORE_ID); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentassist/StructuredContentAssistant.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentassist/StructuredContentAssistant.java deleted file mode 100644 index 8d124cebd9..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentassist/StructuredContentAssistant.java +++ /dev/null @@ -1,124 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.contentassist; - -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.contentassist.ContentAssistant; -import org.eclipse.jface.text.contentassist.IContentAssistProcessor; -import org.eclipse.wst.sse.ui.internal.IReleasable; - -/** - * <p>Content assistant that uses {@link CompoundContentAssistProcessor}s so that multiple - * processors can be registered for each partition type</p> - */ -public class StructuredContentAssistant extends ContentAssistant { - /** need to retain copy of all releasable processors so they can be released on uninstall */ - private List fReleasableProcessors; - - /** - * <code>true</code> if a content assist processor has been added to this assistant, - * <code>false</code> otherwise - */ - private boolean fIsInitalized; - - private boolean fProcessorsReleased = false; - - /** - * <p>Construct the assistant</p> - */ - public StructuredContentAssistant() { - this.fIsInitalized = false; - this.fReleasableProcessors = new ArrayList(); - } - - /** - * <p>Each set content assist processor is placed inside a - * CompoundContentAssistProcessor which allows multiple processors per - * partition type</p> - * - * @param processor - * the content assist processor to register, or - * <code>null</code> to remove an existing one - * @param contentType - * the content type under which to register - * - * @see org.eclipse.jface.text.contentassist.ContentAssistant#setContentAssistProcessor(org.eclipse.jface.text.contentassist.IContentAssistProcessor, java.lang.String) - */ - public void setContentAssistProcessor(IContentAssistProcessor processor, String partitionType) { - this.fIsInitalized = true; - - CompoundContentAssistProcessor compoundProcessor = getExistingContentAssistProcessor(partitionType); - if(compoundProcessor == null) { - compoundProcessor = new CompoundContentAssistProcessor(); - this.fReleasableProcessors.add(compoundProcessor); - } - - compoundProcessor.add(processor); - super.setContentAssistProcessor(compoundProcessor, partitionType); - } - - /** - * Returns true if content assist has been initialized with some content - * assist processors. False otherwise. - * - * @return true if content assistant has been initialized - */ - public boolean isInitialized() { - return this.fIsInitalized; - } - - /** - * - * @param partitionType - * @return - */ - private CompoundContentAssistProcessor getExistingContentAssistProcessor(String partitionType) { - CompoundContentAssistProcessor compoundContentAssistProcessor = null; - IContentAssistProcessor processor = super.getContentAssistProcessor(partitionType); - if (processor != null) { - if (processor instanceof CompoundContentAssistProcessor) { - compoundContentAssistProcessor = (CompoundContentAssistProcessor) processor; - } - } - return compoundContentAssistProcessor; - } - - public void install(ITextViewer textViewer) { - if (fProcessorsReleased) { - if (this.fReleasableProcessors != null && !this.fReleasableProcessors.isEmpty()) { - for(int i = 0; i < this.fReleasableProcessors.size(); ++i) { - ((CompoundContentAssistProcessor)this.fReleasableProcessors.get(i)).install(textViewer); - } - } - fProcessorsReleased = false; - } - super.install(textViewer); - } - - /** - * @see org.eclipse.jface.text.contentassist.ContentAssistant#uninstall() - */ - public void uninstall() { - // dispose of all content assist processors - if (this.fReleasableProcessors != null && !this.fReleasableProcessors.isEmpty()) { - for(int i = 0; i < this.fReleasableProcessors.size(); ++i) { - ((IReleasable)this.fReleasableProcessors.get(i)).release(); - } - } - fProcessorsReleased = true; - super.uninstall(); - } -}
\ No newline at end of file diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentoutline/ConfigurableContentOutlinePage.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentoutline/ConfigurableContentOutlinePage.java deleted file mode 100644 index a55306a21a..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentoutline/ConfigurableContentOutlinePage.java +++ /dev/null @@ -1,762 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2011 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.contentoutline; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.eclipse.core.runtime.IAdaptable; -import org.eclipse.core.runtime.ListenerList; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.SafeRunner; -import org.eclipse.jface.action.GroupMarker; -import org.eclipse.jface.action.IContributionItem; -import org.eclipse.jface.action.IContributionManager; -import org.eclipse.jface.action.IMenuListener; -import org.eclipse.jface.action.IMenuManager; -import org.eclipse.jface.action.IStatusLineManager; -import org.eclipse.jface.action.MenuManager; -import org.eclipse.jface.util.DelegatingDragAdapter; -import org.eclipse.jface.util.DelegatingDropAdapter; -import org.eclipse.jface.util.SafeRunnable; -import org.eclipse.jface.util.TransferDragSourceListener; -import org.eclipse.jface.util.TransferDropTargetListener; -import org.eclipse.jface.viewers.ColumnViewerToolTipSupport; -import org.eclipse.jface.viewers.DoubleClickEvent; -import org.eclipse.jface.viewers.IContentProvider; -import org.eclipse.jface.viewers.IDoubleClickListener; -import org.eclipse.jface.viewers.ILabelProvider; -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.SelectionChangedEvent; -import org.eclipse.jface.viewers.StructuredSelection; -import org.eclipse.jface.viewers.TreeViewer; -import org.eclipse.jface.viewers.Viewer; -import org.eclipse.swt.dnd.DND; -import org.eclipse.swt.dnd.DragSource; -import org.eclipse.swt.dnd.DropTarget; -import org.eclipse.swt.dnd.Transfer; -import org.eclipse.swt.events.KeyListener; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Menu; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.ISelectionListener; -import org.eclipse.ui.IWorkbenchActionConstants; -import org.eclipse.ui.IWorkbenchPage; -import org.eclipse.ui.IWorkbenchPart; -import org.eclipse.ui.part.IPageSite; -import org.eclipse.ui.part.IShowInSource; -import org.eclipse.ui.part.IShowInTarget; -import org.eclipse.ui.part.IShowInTargetList; -import org.eclipse.ui.part.ShowInContext; -import org.eclipse.ui.views.contentoutline.ContentOutlinePage; -import org.eclipse.ui.views.contentoutline.IContentOutlinePage; -import org.eclipse.wst.sse.ui.views.contentoutline.ContentOutlineConfiguration; -import org.eclipse.wst.sse.ui.views.contentoutline.ContentOutlineFilterProcessor; - - -public class ConfigurableContentOutlinePage extends ContentOutlinePage implements IAdaptable { - /* - * Menu listener to create the additions group and add any menu items - * contributed by the configuration; required since the context menu is - * cleared every time it is shown - */ - class AdditionGroupAdder implements IMenuListener { - public void menuAboutToShow(IMenuManager manager) { - IContributionItem[] items = manager.getItems(); - if (items.length > 0 && items[items.length - 1].getId() != null) { - manager.insertAfter(items[items.length - 1].getId(), new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS)); - } - else { - manager.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS)); - } - - // add configuration's menu items - IMenuListener listener = getConfiguration().getMenuListener(getTreeViewer()); - if (listener != null) { - listener.menuAboutToShow(manager); - } - } - } - - /** - * Provides double-click registration so it can be done before the Control - * is created. - */ - class DoubleClickProvider implements IDoubleClickListener { - private IDoubleClickListener[] listeners = null; - - void addDoubleClickListener(IDoubleClickListener newListener) { - if (listeners == null) { - listeners = new IDoubleClickListener[]{newListener}; - } - else { - IDoubleClickListener[] newListeners = new IDoubleClickListener[listeners.length + 1]; - System.arraycopy(listeners, 0, newListeners, 0, listeners.length); - newListeners[listeners.length] = newListener; - listeners = newListeners; - } - } - - public void doubleClick(DoubleClickEvent event) { - fireDoubleClickEvent(event); - } - - private void fireDoubleClickEvent(final DoubleClickEvent event) { - IDoubleClickListener[] firingListeners = listeners; - for (int i = 0; i < firingListeners.length; ++i) { - final IDoubleClickListener l = firingListeners[i]; - SafeRunner.run(new SafeRunnable() { - public void run() { - l.doubleClick(event); - } - }); - } - } - - void removeDoubleClickListener(IDoubleClickListener oldListener) { - if (listeners != null) { - if (listeners.length == 1 && listeners[0].equals(oldListener)) { - listeners = null; - } - else { - List newListeners = new ArrayList(Arrays.asList(listeners)); - newListeners.remove(oldListener); - listeners = (IDoubleClickListener[]) newListeners.toArray(new IDoubleClickListener[listeners.length - 1]); - } - } - } - } - - /** - * Listens to post selection from the selection service, applying it to - * the tree viewer. - */ - class PostSelectionServiceListener implements ISelectionListener { - public void selectionChanged(IWorkbenchPart part, ISelection selection) { - // from selection service - if (_DEBUG) { - _DEBUG_TIME = System.currentTimeMillis(); - } /* - * Bug 136310, unless this page is that part's - * IContentOutlinePage, ignore the selection change - */ - if (part == null || part.getAdapter(IContentOutlinePage.class) == ConfigurableContentOutlinePage.this) { - ISelection validContentSelection = getConfiguration().getSelection(getTreeViewer(), selection); - - boolean isLinked = getConfiguration().isLinkedWithEditor(getTreeViewer()); - if (isLinked) { - if (!getTreeViewer().getSelection().equals(validContentSelection)) { - try { - fIsReceivingSelection = true; - getTreeViewer().setSelection(validContentSelection, true); - } - finally { - fIsReceivingSelection = false; - } - } - } - } - if (_DEBUG) { - System.out.println("(O:" + (System.currentTimeMillis() - _DEBUG_TIME) + "ms) " + part + " : " + selection); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } - } - } - - /** - * Forwards post-selection from the tree viewer to the listeners while - * acting as this page's selection provider. - */ - private class SelectionProvider implements IPostSelectionProvider { - private class PostSelectionChangedListener implements ISelectionChangedListener { - public void selectionChanged(SelectionChangedEvent event) { - if (!isFiringSelection() && !fIsReceivingSelection) { - fireSelectionChanged(event, postListeners); - updateStatusLine(getSite().getActionBars().getStatusLineManager(), event.getSelection()); - } - } - } - - private class SelectionChangedListener implements ISelectionChangedListener { - public void selectionChanged(SelectionChangedEvent event) { - if (!isFiringSelection() && !fIsReceivingSelection) { - fireSelectionChanged(event, listeners); - } - } - } - - private boolean isFiringSelection = false; - private ListenerList listeners = new ListenerList(); - private ListenerList postListeners = new ListenerList(); - private ISelectionChangedListener postSelectionChangedListener = new PostSelectionChangedListener(); - private ISelectionChangedListener selectionChangedListener = new SelectionChangedListener(); - - public void addPostSelectionChangedListener(ISelectionChangedListener listener) { - postListeners.add(listener); - } - - public void addSelectionChangedListener(ISelectionChangedListener listener) { - listeners.add(listener); - } - - public void fireSelectionChanged(final SelectionChangedEvent event, ListenerList listenerList) { - isFiringSelection = true; - Object[] listeners = listenerList.getListeners(); - for (int i = 0; i < listeners.length; ++i) { - final ISelectionChangedListener l = (ISelectionChangedListener) listeners[i]; - SafeRunner.run(new SafeRunnable() { - public void run() { - l.selectionChanged(event); - } - }); - } - isFiringSelection = false; - } - - public ISelectionChangedListener getPostSelectionChangedListener() { - return postSelectionChangedListener; - } - - public ISelection getSelection() { - if (getTreeViewer() != null) { - return getTreeViewer().getSelection(); - } - return StructuredSelection.EMPTY; - } - - public ISelectionChangedListener getSelectionChangedListener() { - return selectionChangedListener; - } - - public boolean isFiringSelection() { - return isFiringSelection; - } - - public void removePostSelectionChangedListener(ISelectionChangedListener listener) { - postListeners.remove(listener); - } - - public void removeSelectionChangedListener(ISelectionChangedListener listener) { - listeners.remove(listener); - } - - public void setSelection(ISelection selection) { - if (!isFiringSelection) { - getTreeViewer().setSelection(selection); - } - } - } - - private class ShowInTarget implements IShowInTarget { - /* - * @see org.eclipse.ui.part.IShowInTarget#show(org.eclipse.ui.part.ShowInContext) - */ - public boolean show(ShowInContext context) { - setSelection(context.getSelection()); - return getTreeViewer().getSelection().equals(context.getSelection()); - } - } - - protected static final ContentOutlineConfiguration NULL_CONFIGURATION = new ContentOutlineConfiguration() { - public IContentProvider getContentProvider(TreeViewer viewer) { - return new ITreeContentProvider() { - public void dispose() { - } - - public Object[] getChildren(Object parentElement) { - return null; - } - - public Object[] getElements(Object inputElement) { - return null; - } - - public Object getParent(Object element) { - return null; - } - - public boolean hasChildren(Object element) { - return false; - } - - public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { - } - }; - } - }; - - private static final String OUTLINE_CONTEXT_MENU_ID = "org.eclipse.wst.sse.ui.StructuredTextEditor.OutlineContext"; //$NON-NLS-1$ - - private static final String OUTLINE_CONTEXT_MENU_SUFFIX = ".source.OutlineContext"; //$NON-NLS-1$ - private static final boolean _DEBUG = "true".equalsIgnoreCase(Platform.getDebugOption("org.eclipse.wst.sse.ui/contentOutline")); //$NON-NLS-1$ //$NON-NLS-2$; - - private long _DEBUG_TIME = 0; - - private TransferDragSourceListener[] fActiveDragListeners; - private TransferDropTargetListener[] fActiveDropListeners; - private ContentOutlineConfiguration fConfiguration; - - private Menu fContextMenu; - private String fContextMenuId; - - private MenuManager fContextMenuManager; - private DoubleClickProvider fDoubleClickProvider = null; - - private DelegatingDragAdapter fDragAdapter; - private DragSource fDragSource; - private DelegatingDropAdapter fDropAdapter; - private DropTarget fDropTarget; - private IEditorPart fEditor; - private IMenuListener fGroupAdder = null; - private Object fInput = null; - - private String fInputContentTypeIdentifier = null; - private ISelectionListener fSelectionListener = null; - - SelectionProvider fSelectionProvider = null; - - boolean fIsReceivingSelection; - - /** - * A ContentOutlinePage that abstract as much behavior as possible away - * from the Controls and varies it by content type. - */ - public ConfigurableContentOutlinePage() { - super(); - fGroupAdder = new AdditionGroupAdder(); - fSelectionProvider = new SelectionProvider(); - } - - /** - * Adds a listener to a list of those notified when someone double-clicks - * in the page. - * - * @param newListener - the listener to add - */ - public void addDoubleClickListener(IDoubleClickListener newListener) { - if (fDoubleClickProvider == null) { - fDoubleClickProvider = new DoubleClickProvider(); - } - fDoubleClickProvider.addDoubleClickListener(newListener); - } - - private String computeContextMenuID() { - String id = null; - if (fInputContentTypeIdentifier != null) { - id = fInputContentTypeIdentifier + OUTLINE_CONTEXT_MENU_SUFFIX; - } - return id; - } - - /** - * @see ContentOutlinePage#createControl - */ - public void createControl(Composite parent) { - super.createControl(parent); - ColumnViewerToolTipSupport.enableFor(getTreeViewer()); - - IWorkbenchPage page = getSite().getWorkbenchWindow().getActivePage(); - if (page != null) { - fEditor = page.getActiveEditor(); - } - - fDragAdapter = new DelegatingDragAdapter(); - fDragSource = new DragSource(getControl(), DND.DROP_COPY | DND.DROP_MOVE); - fDropAdapter = new DelegatingDropAdapter(); - fDropTarget = new DropTarget(getControl(), DND.DROP_COPY | DND.DROP_MOVE); - - setConfiguration(getConfiguration()); - - /* - * ContentOutlinePage only implements ISelectionProvider while the - * tree viewer implements both ISelectionProvider and - * IPostSelectionProvider. Use an ISelectionProvider that listens to - * post selection from the tree viewer and forward only post selection - * to the selection service. - */ - getTreeViewer().addPostSelectionChangedListener(fSelectionProvider.getPostSelectionChangedListener()); - getTreeViewer().addSelectionChangedListener(fSelectionProvider.getSelectionChangedListener()); - if (fDoubleClickProvider == null) { - fDoubleClickProvider = new DoubleClickProvider(); - } - getTreeViewer().addDoubleClickListener(fDoubleClickProvider); - getSite().setSelectionProvider(fSelectionProvider); - } - - public void dispose() { - getSite().getWorkbenchWindow().getSelectionService().removePostSelectionListener(getSelectionServiceListener()); - if (fDoubleClickProvider != null) { - getTreeViewer().removeDoubleClickListener(fDoubleClickProvider); - } - - // dispose menu controls - if (fContextMenu != null) { - fContextMenu.dispose(); - } - if (fContextMenuManager != null) { - fContextMenuManager.removeMenuListener(fGroupAdder); - fContextMenuManager.removeAll(); - fContextMenuManager.dispose(); - } - - fDropTarget.dispose(); - fDragSource.dispose(); - - IStatusLineManager statusLineManager = getSite().getActionBars().getStatusLineManager(); - if (statusLineManager != null) { - statusLineManager.setMessage(null); - } - setConfiguration(NULL_CONFIGURATION); - super.dispose(); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class) - */ - public Object getAdapter(Class key) { - Object adapter = null; - if (key.equals(IShowInTarget.class)) { - adapter = new ShowInTarget(); - } - final IEditorPart editor = fEditor; - - if (key.equals(IShowInSource.class) && editor != null) { - adapter = new IShowInSource() { - public ShowInContext getShowInContext() { - return new ShowInContext(editor.getEditorInput(), editor.getEditorSite().getSelectionProvider().getSelection()); - } - }; - } - else if (key.equals(IShowInTargetList.class) && editor != null) { - adapter = editor.getAdapter(key); - } - return adapter; - } - - /** - * @return the currently used ContentOutlineConfiguration - */ - public ContentOutlineConfiguration getConfiguration() { - if (fConfiguration == null) { - fConfiguration = NULL_CONFIGURATION; - } - return fConfiguration; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.viewers.ISelectionProvider#getSelection() - */ - public ISelection getSelection() { - return fSelectionProvider.getSelection(); - } - - ISelectionListener getSelectionServiceListener() { - if (fSelectionListener == null) { - fSelectionListener = new PostSelectionServiceListener(); - } - return fSelectionListener; - } - - - /* - * (non-Javadoc) - * - * @see - * org.eclipse.ui.part.IPageBookViewPage#init(org.eclipse.ui.part.IPageSite - * ) - */ - public void init(IPageSite pageSite) { - super.init(pageSite); - pageSite.getWorkbenchWindow().getSelectionService().addPostSelectionListener(getSelectionServiceListener()); - } - - /** - * Removes a listener to a list of those notified when someone - * double-clicks in the page. - * - * @param oldListener - the listener to remove - */ - public void removeDoubleClickListener(IDoubleClickListener oldListener) { - if (fDoubleClickProvider != null) { - fDoubleClickProvider.removeDoubleClickListener(oldListener); - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.views.contentoutline.ContentOutlinePage#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent) - */ - public void selectionChanged(SelectionChangedEvent event) { - if (!fIsReceivingSelection) - super.selectionChanged(event); - } - - /** - * Configures (or reconfigures) the page according to the given - * configuration. - * - * @param configuration - */ - public void setConfiguration(ContentOutlineConfiguration configuration) { - // intentionally do not check to see if the new configuration != old - // configuration - if (getTreeViewer() != null) { - // remove the key listeners - if (getControl() != null && !getControl().isDisposed()) { - KeyListener[] listeners = getConfiguration().getKeyListeners(getTreeViewer()); - if (listeners != null) { - for (int i = 0; i < listeners.length; i++) { - getControl().removeKeyListener(listeners[i]); - } - } - } - - IContributionManager toolbar = getSite().getActionBars().getToolBarManager(); - if (toolbar != null) { - IContributionItem[] toolbarItems = getConfiguration().getToolbarContributions(getTreeViewer()); - if (toolbarItems != null && toolbarItems.length > 0) { - for (int i = 0; i < toolbarItems.length; i++) { - toolbar.remove(toolbarItems[i]); - } - toolbar.update(false); - } - } - - IContributionManager menubar = getSite().getActionBars().getMenuManager(); - if (menubar != null) { - IContributionItem[] menuItems = getConfiguration().getMenuContributions(getTreeViewer()); - if (menuItems != null && menuItems.length > 0) { - for (int i = 0; i < menuItems.length; i++) { - menubar.remove(menuItems[i]); - } - menubar.remove(IWorkbenchActionConstants.MB_ADDITIONS); - menubar.update(false); - } - } - // clear the DnD listeners and transfer types - if (fDragAdapter != null && !fDragAdapter.isEmpty() && fDragSource != null && !fDragSource.isDisposed() && fDragSource.getTransfer().length > 0) { - if (fActiveDragListeners != null) { - for (int i = 0; i < fActiveDragListeners.length; i++) { - fDragAdapter.removeDragSourceListener(fActiveDragListeners[i]); - } - } - fActiveDragListeners = null; - fDragSource.removeDragListener(fDragAdapter); - fDragSource.setTransfer(new Transfer[0]); - } - if (fDropAdapter != null && !fDropAdapter.isEmpty() && fDropTarget != null && !fDropTarget.isDisposed() && fDropTarget.getTransfer().length > 0) { - if (fActiveDropListeners != null) { - for (int i = 0; i < fActiveDropListeners.length; i++) { - fDropAdapter.removeDropTargetListener(fActiveDropListeners[i]); - } - } - fActiveDropListeners = null; - fDropTarget.removeDropListener(fDropAdapter); - fDropTarget.setTransfer(new Transfer[0]); - } - getConfiguration().getContentProvider(getTreeViewer()).inputChanged(getTreeViewer(), fInput, null); - // release any ties to this tree viewer - getConfiguration().unconfigure(getTreeViewer()); - } - - fConfiguration = configuration; - - if (getTreeViewer() != null && getControl() != null && !getControl().isDisposed()) { - // (re)set the providers - getTreeViewer().setLabelProvider(getConfiguration().getLabelProvider(getTreeViewer())); - getTreeViewer().setContentProvider(getConfiguration().getContentProvider(getTreeViewer())); - - // view toolbar - IContributionManager toolbar = getSite().getActionBars().getToolBarManager(); - if (toolbar != null) { - IContributionItem[] toolbarItems = getConfiguration().getToolbarContributions(getTreeViewer()); - if (toolbarItems != null) { - for (int i = 0; i < toolbarItems.length; i++) { - toolbar.add(toolbarItems[i]); - } - toolbar.update(true); - } - } - // view menu - IContributionManager menu = getSite().getActionBars().getMenuManager(); - if (menu != null) { - IContributionItem[] menuItems = getConfiguration().getMenuContributions(getTreeViewer()); - if (menuItems != null) { - for (int i = 0; i < menuItems.length; i++) { - menuItems[i].setVisible(true); - menu.add(menuItems[i]); - menuItems[i].update(); - } - menu.update(true); - } - } - // add the allowed DnD listeners and types - TransferDragSourceListener[] dragListeners = getConfiguration().getTransferDragSourceListeners(getTreeViewer()); - if (fDragAdapter != null && dragListeners.length > 0) { - for (int i = 0; i < dragListeners.length; i++) { - fDragAdapter.addDragSourceListener(dragListeners[i]); - } - fActiveDragListeners = dragListeners; - fDragSource.addDragListener(fDragAdapter); - fDragSource.setTransfer(fDragAdapter.getTransfers()); - } - TransferDropTargetListener[] dropListeners = getConfiguration().getTransferDropTargetListeners(getTreeViewer()); - if (fDropAdapter != null && dropListeners.length > 0) { - for (int i = 0; i < dropListeners.length; i++) { - fDropAdapter.addDropTargetListener(dropListeners[i]); - } - fActiveDropListeners = dropListeners; - fDropTarget.addDropListener(fDropAdapter); - fDropTarget.setTransfer(fDropAdapter.getTransfers()); - } - // add the key listeners - KeyListener[] listeners = getConfiguration().getKeyListeners(getTreeViewer()); - if (listeners != null) { - for (int i = 0; i < listeners.length; i++) { - getControl().addKeyListener(listeners[i]); - } - } - } - - if (fInput != null) { - setInput(fInput); - } - } - - /** - * @param editor - * The IEditorPart that "owns" this page. Used to support the - * "Show In..." menu. - */ - public void setEditorPart(IEditorPart editor) { - fEditor = editor; - } - - /** - * @param newInput - * The input for the page's viewer. Should only be set after a - * configuration has been applied. - */ - public void setInput(Object newInput) { - fInput = newInput; - /* - * Intentionally not optimized for checking new input vs. old input so - * that any existing content providers can be updated - */ - if (getControl() != null && !getControl().isDisposed()) { - getTreeViewer().setInput(fInput); - updateContextMenuId(); - } - } - - /** - * @param id - the content type identifier to use for further extension - */ - public void setInputContentTypeIdentifier(String id) { - fInputContentTypeIdentifier = id; - } - - /** - * Updates the outline page's context menu for the current input - */ - private void updateContextMenuId() { - String computedContextMenuId = null; - // update outline view's context menu control and ID - - if (fEditor == null) { - IWorkbenchPage page = getSite().getWorkbenchWindow().getActivePage(); - if (page != null) { - fEditor = page.getActiveEditor(); - } - } - - computedContextMenuId = computeContextMenuID(); - - if (computedContextMenuId == null) { - computedContextMenuId = OUTLINE_CONTEXT_MENU_ID; - } - - /* - * Update outline context menu id if updating to a new id or if - * context menu is not already set up - */ - if (!computedContextMenuId.equals(fContextMenuId) || (fContextMenu == null)) { - fContextMenuId = computedContextMenuId; - - if (getControl() != null && !getControl().isDisposed()) { - // dispose of previous context menu - if (fContextMenu != null) { - fContextMenu.dispose(); - } - if (fContextMenuManager != null) { - fContextMenuManager.removeMenuListener(fGroupAdder); - fContextMenuManager.removeAll(); - fContextMenuManager.dispose(); - } - - fContextMenuManager = new MenuManager(fContextMenuId, fContextMenuId); - fContextMenuManager.setRemoveAllWhenShown(true); - - fContextMenuManager.addMenuListener(fGroupAdder); - - fContextMenu = fContextMenuManager.createContextMenu(getControl()); - getControl().setMenu(fContextMenu); - - getSite().registerContextMenu(fContextMenuId, fContextMenuManager, this); - - /* - * also register this menu for source page part and structured - * text outline view ids - */ - if (fEditor != null) { - String partId = fEditor.getSite().getId(); - if (partId != null) { - getSite().registerContextMenu(partId + OUTLINE_CONTEXT_MENU_SUFFIX, fContextMenuManager, this); - } - } - getSite().registerContextMenu(OUTLINE_CONTEXT_MENU_ID, fContextMenuManager, this); - } - } - } - - void updateStatusLine(IStatusLineManager mgr, ISelection selection) { - String text = null; - Image image = null; - ILabelProvider statusLineLabelProvider = getConfiguration().getStatusLineLabelProvider(getTreeViewer()); - if (statusLineLabelProvider != null && selection instanceof IStructuredSelection && !selection.isEmpty()) { - Object firstElement = ((IStructuredSelection) selection).getFirstElement(); - text = statusLineLabelProvider.getText(firstElement); - image = statusLineLabelProvider.getImage(firstElement); - } - if (image == null) { - mgr.setMessage(text); - } - else { - mgr.setMessage(image, text); - } - } - - public ContentOutlineFilterProcessor getOutlineFilterProcessor() { - return getConfiguration().getOutlineFilterProcessor(getTreeViewer()); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentoutline/IJFaceNodeAdapter.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentoutline/IJFaceNodeAdapter.java deleted file mode 100644 index 4789341493..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentoutline/IJFaceNodeAdapter.java +++ /dev/null @@ -1,57 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.contentoutline; - - - -import org.eclipse.swt.graphics.Image; -import org.eclipse.wst.sse.core.internal.provisional.INodeAdapter; - - -/** - * Adapter interface to provide JFace-style children and property information. - * The factory returning this adapter is expected to implement - * IJFaceNodeAdapterFactory - * - */ -public interface IJFaceNodeAdapter extends INodeAdapter { - - /** - * Returns the child elements of the given parent element. - * The result is not modified by the viewer. - * - * @param node the parent object - * @return an array of child elements - */ - public Object[] getChildren(Object node); - - /** - * Returns an enumeration with the elements belonging to the passed - * element. These are the top level items in a list, tree, table, etc... - */ - public Object[] getElements(Object node); - - /** - * Fetches the label image specific to this object instance. - */ - public Image getLabelImage(Object node); - - /** - * Fetches the label text specific to this object instance. - */ - public String getLabelText(Object node); - - public Object getParent(Object node); - - public boolean hasChildren(Object node); -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentoutline/IJFaceNodeAdapterFactory.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentoutline/IJFaceNodeAdapterFactory.java deleted file mode 100644 index cf7a53ed63..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentoutline/IJFaceNodeAdapterFactory.java +++ /dev/null @@ -1,26 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.contentoutline; - -import java.util.Collection; - -public interface IJFaceNodeAdapterFactory { - public void addListener(Object listener); - - /** - * returns "copy" so no one can modify our list. Its is a shallow copy. - */ - public Collection getListeners(); - - public void removeListener(Object listener); -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentoutline/PropertyChangeUpdateAction.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentoutline/PropertyChangeUpdateAction.java deleted file mode 100644 index fef880b8b2..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentoutline/PropertyChangeUpdateAction.java +++ /dev/null @@ -1,80 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.contentoutline; - -import org.eclipse.jface.action.Action; -import org.eclipse.jface.action.IAction; -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.ui.texteditor.IUpdate; - -/** - * An IAction.AS_CHECK_BOX action that sets and gets its checked state along - * with a value from a preference store. Should be used with - * PropertyChangeUpdateActionContributionItem to listen to changes in the - * store and update the checked state from PropertyChangeEvents. - */ -public class PropertyChangeUpdateAction extends Action implements IUpdate { - private String fPreferenceKey; - private IPreferenceStore fStore; - private boolean fUpdateFromPropertyChange = true; - - public PropertyChangeUpdateAction(String text, IPreferenceStore store, String preferenceKey, boolean defaultValue) { - super(text, IAction.AS_CHECK_BOX); - fPreferenceKey = preferenceKey; - fStore = store; - fStore.setDefault(getPreferenceKey(), defaultValue); - setId(getPreferenceKey()); - setChecked(getPreferenceStore().getBoolean(getPreferenceKey())); - } - - /** - * @return Returns the orderPreferenceKey. - */ - public String getPreferenceKey() { - return fPreferenceKey; - } - - /** - * @return Returns the store. - */ - public IPreferenceStore getPreferenceStore() { - return fStore; - } - - /** - * @return Returns the updateFromPropertyChange. - */ - public boolean isUpdateFromPropertyChange() { - return fUpdateFromPropertyChange; - } - - public final void run() { - super.run(); - fStore.setValue(getPreferenceKey(), isChecked()); - if (!isUpdateFromPropertyChange()) - update(); - } - - /** - * @param updateFromPropertyChange - * The updateFromPropertyChange to set. - */ - public void setUpdateFromPropertyChange(boolean updateFromPropertyChange) { - fUpdateFromPropertyChange = updateFromPropertyChange; - } - - public void update() { - setChecked(fStore.getBoolean(getPreferenceKey())); - } - -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentoutline/PropertyChangeUpdateActionContributionItem.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentoutline/PropertyChangeUpdateActionContributionItem.java deleted file mode 100644 index 67d0aec21f..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentoutline/PropertyChangeUpdateActionContributionItem.java +++ /dev/null @@ -1,85 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.contentoutline; - -import org.eclipse.core.runtime.Platform; -import org.eclipse.jface.action.ActionContributionItem; -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.util.IPropertyChangeListener; -import org.eclipse.jface.util.PropertyChangeEvent; -import org.eclipse.ui.texteditor.IUpdate; - -/** - * A listener on the given action's PreferenceStore. It calls .update() on the - * action when the given key changes value. - */ -public class PropertyChangeUpdateActionContributionItem extends ActionContributionItem { - - private class PreferenceUpdateListener implements IPropertyChangeListener { - public void propertyChange(PropertyChangeEvent event) { - if (event.getProperty().equals(fProperty)) { - if (debug) { - System.out.println(fProperty + " preference changed, updating " + getAction()); //$NON-NLS-1$ - } - ((IUpdate) getAction()).update(); - } - } - } - - static final boolean debug = "true".equalsIgnoreCase(Platform.getDebugOption("org.eclipse.wst.sse.ui/propertyChangeUpdateActionContributionItem")); //$NON-NLS-1$ //$NON-NLS-2$; - - private IPropertyChangeListener fListener = null; - - protected String fProperty = null; - private IPreferenceStore fStore; - - public PropertyChangeUpdateActionContributionItem(PropertyChangeUpdateAction action) { - super(action); - fProperty = action.getPreferenceKey(); - fStore = action.getPreferenceStore(); - fListener = new PreferenceUpdateListener(); - connect(); - } - - public void connect() { - if (debug) { - System.out.println("PropertyChangeUpdateActionContributionItem started listening for " + fProperty); //$NON-NLS-1$ - } - if (fStore != null) { - fStore.addPropertyChangeListener(fListener); - } - } - - public void disconnect() { - if (debug) { - System.out.println("PropertyChangeUpdateActionContributionItem stopped listening for " + fProperty); //$NON-NLS-1$ - } - if (fStore != null) { - fStore.removePropertyChangeListener(fListener); - } - } - - public void dispose() { - super.dispose(); - disconnect(); - fProperty = null; - fStore = null; - } - - public String toString() { - if (getAction().getId() != null) - return super.toString(); - else - return getClass().getName() + "(text=" + getAction().getText() + ")"; //$NON-NLS-1$ //$NON-NLS-2$ - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentproperties/ui/ComboList.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentproperties/ui/ComboList.java deleted file mode 100644 index 8b8eb59087..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentproperties/ui/ComboList.java +++ /dev/null @@ -1,287 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2006 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.contentproperties.ui; - - - -import java.util.ArrayList; -import java.util.Hashtable; -import java.util.List; -import java.util.Map; - -import org.eclipse.swt.events.FocusListener; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.widgets.Combo; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.wst.sse.ui.internal.Logger; - - -/** - * @deprecated People should manage their own combo/list - */ -public class ComboList { - private Combo combo; - - - private List list; - - public ComboList(Composite parent, int style) { - combo = new Combo(parent, style); - list = new ArrayList(); - } - - - /* - * following methods is original method of Combo class. - */ - public void add(String key) { - checkError(); - combo.add(key); - list.add(key); - } - - public void add(String key, int index) { - checkError(); - combo.add(key, index); - list.add(index, key); - } - - public void add(String key, String value) { - checkError(); - combo.add(key); - list.add(value); - } - - public void add(String key, String value, int index) { - checkError(); - combo.add(key, index); - list.add(index, value); - } - - public void addFocusListener(FocusListener listener) { - combo.addFocusListener(listener); - } - - public void addModifyListener(org.eclipse.swt.events.ModifyListener listener) { - combo.addModifyListener(listener); - } - - public void addSelectionListener(org.eclipse.swt.events.SelectionListener listener) { - combo.addSelectionListener(listener); - - } - - private void checkError() { - if (!isConsistency()) { - Logger.log(Logger.WARNING, "Difference between the number of keys[" + combo.getItemCount() + "] and the number of values[" + list.size() + "] in ComboList"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } - } - - public org.eclipse.swt.graphics.Point computeSize(int wHint, int hHint) { - return combo.computeSize(wHint, hHint); - } - - public Map createHashtable() { - checkError(); - Map m = new Hashtable(); - for (int i = 0; i < list.size(); i++) - m.put(combo.getItem(i), list.get(i)); - return m; - } - - public void deselect(int i) { - combo.deselect(i); - } - - public void deselectAll() { - combo.deselectAll(); - } - - public boolean equals(Object obj) { - return combo.equals(obj); - } - - private void exchangePosition(int i, int j) { - String tmpKey = getItem(i); - Object tmpValue = list.remove(i); - - combo.setItem(i, getItem(j)); - list.add(i, list.remove(j - 1)); - - combo.setItem(j, tmpKey); - list.add(j, tmpValue); - } - - public boolean existsAsKey(String str) { - if (combo.indexOf(str) >= 0) - return true; - else - return false; - } - - public boolean existsAsValue(String str) { - if (list.indexOf(str) >= 0) - return true; - else - return false; - } - - public boolean getEnabled() { - return combo.getEnabled(); - } - - public String getItem(int index) { - return combo.getItem(index); - } - - public int getItemCount() { - return combo.getItemCount(); - } - - public String getKey(String value) { - if (value == null) - return null; - int index = -1; - checkError(); - for (int i = 0; i < list.size(); i++) { - if (!list.get(i).equals(value)) - continue; - index = i; - break; - } - if (index != -1) - return combo.getItem(index); - else - return null; - } - - public Object getLayoutData() { - return combo.getLayoutData(); - } - - public String getSelectedValue() { - checkError(); - int index = getSelectionIndex(); - if (index < 0) - return null; - return getValue(getItem(index)); - } - - public int getSelectionIndex() { - return combo.getSelectionIndex(); - } - - public String getText() { - return combo.getText(); - } - - public String getValue(String key) { - if (key == null) - return null; - int index = -1; - checkError(); - for (int i = 0; i < combo.getItemCount(); i++) { - if (!combo.getItem(i).equals(key)) - continue; - index = i; - break; - } - if (index != -1) - return (String) list.get(index); - else - return null; - } - - public int indexOf(String str) { - return combo.indexOf(str); - } - - - public boolean isConsistency() { - - if (list.size() == combo.getItemCount()) - return true; - else - return false; - } - - - public void remove(int index) { - checkError(); - combo.remove(index); - list.remove(index); - } - - public void remove(String str) { - checkError(); - combo.remove(str); - list.remove(str); - } - - public void select(int index) { - combo.select(index); - } - - public void setEnabled(boolean enabled) { - combo.setEnabled(enabled); - } - - public boolean setFocus() { - return combo.setFocus(); - } - - public void setItem(int index, String str) { - checkError(); - combo.setItem(index, str); - list.remove(index); - list.add(index, str); - } - - public void setItem(String[] strArray) { - checkError(); - combo.setItems(strArray); - for (int i = 0; i < strArray.length; i++) - list.add(strArray[i]); - } - - public void setLayout(org.eclipse.swt.widgets.Layout lo) { - combo.setLayout(lo); - } - - public void setLayoutData(Object layoutData) { - combo.setLayoutData(layoutData); - } - - public void setSelection(Point point) { - combo.setSelection(point); - } - - public void setText(String str) { - combo.setText(str); - } - - public void sortByKey(int offset) { - if (offset < 0 || offset > this.combo.getItemCount() - 1) - return; - checkError(); - // - for (int i = offset; i < combo.getItemCount() - 1; i++) { - for (int j = i + 1; j < combo.getItemCount(); j++) { - if (getItem(i).compareTo(getItem(j)) > 0) { - exchangePosition(i, j); - } - } - } - } - -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentproperties/ui/ComboListOnPropertyPage.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentproperties/ui/ComboListOnPropertyPage.java deleted file mode 100644 index f46c5177af..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentproperties/ui/ComboListOnPropertyPage.java +++ /dev/null @@ -1,39 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2006 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.contentproperties.ui; - - - -import org.eclipse.swt.widgets.Composite; - -/** - * @deprecated People should manage their own combo/list - */ -public final class ComboListOnPropertyPage extends ComboList { - - - private String currentApplyValue; - - public ComboListOnPropertyPage(Composite parent, int style) { - super(parent, style); - } - - public final String getApplyValue() { - return currentApplyValue; - } - - public final void setApplyValue(String currentApplyValue) { - this.currentApplyValue = currentApplyValue; - } - -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentproperties/ui/ContentSettingsPropertyPage.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentproperties/ui/ContentSettingsPropertyPage.java deleted file mode 100644 index f937860171..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentproperties/ui/ContentSettingsPropertyPage.java +++ /dev/null @@ -1,297 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2006 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.contentproperties.ui; - -import java.util.Hashtable; -import java.util.Map; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Status; -import org.eclipse.swt.SWT; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.dialogs.PropertyPage; -import org.eclipse.wst.sse.core.StructuredModelManager; -import org.eclipse.wst.sse.core.internal.provisional.IModelManager; -import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel; -import org.eclipse.wst.sse.internal.contentproperties.ContentSettings; -import org.eclipse.wst.sse.internal.contentproperties.ContentSettingsCreator; -import org.eclipse.wst.sse.internal.contentproperties.IContentSettings; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; -import org.eclipse.wst.sse.ui.internal.SSEUIPlugin; - -/** - * @deprecated Please use - * org.eclipse.wst.html.ui.internal.contentproperties.ui.WebContentSettingsPropertyPage - * or - * eclipse.wst.css.ui.internal.contentproperties.ui.CSSWebContentSettingsPropertyPage - * instead - */ -public abstract class ContentSettingsPropertyPage extends PropertyPage { - private static final IStatus STATUS_ERROR = new Status(IStatus.ERROR, SSEUIPlugin.ID, IStatus.INFO, "ERROR", null); //$NON-NLS-1$ - - // for validateEdit() - private static final IStatus STATUS_OK = new Status(IStatus.OK, SSEUIPlugin.ID, IStatus.OK, "OK", null); //$NON-NLS-1$ - - /** - * Method validateEdit. - * - * @param file - * org.eclipse.core.resources.IFile - * @param context - * org.eclipse.swt.widgets.Shell - * @return IStatus - */ - private static IStatus validateEdit(IFile file, Shell context) { - if (file == null || !file.exists()) - return STATUS_ERROR; - if (!(file.isReadOnly())) - return STATUS_OK; - - IPath location = file.getLocation(); - - final long beforeModifiedFromJavaIO = (location != null) ? location.toFile().lastModified() : IResource.NULL_STAMP; - final long beforeModifiedFromIFile = file.getModificationStamp(); - - IStatus status = ResourcesPlugin.getWorkspace().validateEdit(new IFile[]{file}, context); - if (!status.isOK()) - return status; - - final long afterModifiedFromJavaIO = (location != null) ? location.toFile().lastModified() : IResource.NULL_STAMP; - final long afterModifiedFromIFile = file.getModificationStamp(); - - if (beforeModifiedFromJavaIO != afterModifiedFromJavaIO || beforeModifiedFromIFile != afterModifiedFromIFile) { - IModelManager manager = StructuredModelManager.getModelManager(); - IStructuredModel model = manager.getExistingModelForRead(file); - if (model != null) { - if (!model.isDirty()) { - try { - file.refreshLocal(IResource.DEPTH_ONE, null); - } - catch (CoreException e) { - return STATUS_ERROR; - } - finally { - model.releaseFromRead(); - } - } - else { - model.releaseFromRead(); - } - } - } - - if ((beforeModifiedFromJavaIO != afterModifiedFromJavaIO) || (beforeModifiedFromIFile != afterModifiedFromIFile)) { - // the file is replaced. Modification cannot be - // applied. - return STATUS_ERROR; - } - return STATUS_OK; - } - - protected ComboListOnPropertyPage[] combo; - protected Composite composite; - - protected IContentSettings contentSettings; - protected final String CSS_LABEL = SSEUIMessages.UI_CSS_profile___2; //$NON-NLS-1$ - protected final String DEVICE_LABEL = SSEUIMessages.UI_Target_Device___3; //$NON-NLS-1$ - - protected final String DOCUMENT_LABEL = SSEUIMessages.UI_Default_HTML_DOCTYPE_ID___1; //$NON-NLS-1$ - protected int numberOfCombo; - protected int numCols = 1; - protected int numRows = 1; - protected Composite propertyPage; - - public ContentSettingsPropertyPage() { - super(); - } - - private void cleanUp() { - // Are There any way to guarantee to call cleanUp() to re-load - // downloaded .contentsettings file - // after ContentSettings.releaseCache() in ContentSettingSelfHandler - // class, which is called by resourceChangeEvent - } - - - protected ComboListOnPropertyPage createComboBoxOf(String title) { - - Label label = new Label(propertyPage, SWT.LEFT); - label.setText(title); - if (title != null && title.startsWith(SSEUIMessages.UI_Default_HTML_DOCTYPE_ID___1)) { //$NON-NLS-1$ - GridData data = new GridData(); - data.horizontalIndent = 10; - label.setLayoutData(data); - } - ComboListOnPropertyPage combo = new ComboListOnPropertyPage(propertyPage, SWT.READ_ONLY); - GridData data = new GridData(); - data.verticalAlignment = GridData.FILL; - // data.horizontalAlignment= GridData.FILL; - data.grabExcessHorizontalSpace = true; - combo.setLayoutData(data); - return combo; - } - - - - protected Composite createComposite(Composite parent, int numColumns, int numRows) { - Composite composite = new Composite(parent, SWT.NONE); - - // GridLayout - GridLayout layout = new GridLayout(); - layout.numColumns = numColumns; - composite.setLayout(layout); - - // GridData - GridData data = new GridData(); - data.verticalAlignment = GridData.FILL; - data.horizontalAlignment = GridData.FILL; - data.grabExcessHorizontalSpace = true; - // data.horizontalSpan=numColumns; - // data.verticalSpan=numRows; - - composite.setLayoutData(data); - return composite; - } - - - protected Control createContents(Composite parent) { - - contentSettings = ContentSettingsCreator.create(); - - propertyPage = createComposite(parent, numCols, numRows); - - createSettingsPageGUI(); - - return propertyPage; - - - } - - protected abstract void createSettingsPageGUI(); - - // protected abstract void applySelectedPropertyValue(String str,int - // index); - protected abstract void deleteNoneProperty(int index); - - - - protected boolean isInitValueChanged(String before, String after) { - if (before == null && after == null) - return false; - if (before != null && before.equals(after)) - return false; - return true; - } - - - - protected void performDefaults() { - super.performDefaults(); - // selected(applied) item is restored. - for (int i = 0; i < numberOfCombo; i++) { - // String appliedValue = combo[i].getApplyValue(); - // setSelectionItem(combo[i],appliedValue); - combo[i].select(0); // select none. - - } - - } - - public boolean performOk() { - Map properties = new Hashtable(); - if (validateState() == false) { - cleanUp(); - return true; - } - for (int i = 0; i < numberOfCombo; i++) { - // get selected item in Combo box. - String str = combo[i].getSelectedValue(); - if (str == null) - continue; - // if no change, skip setProperty - if (!isInitValueChanged(combo[i].getApplyValue(), str)) - continue; - // if NONE is selected, delete attr instance (and write - // .contentsettings.) - if (str != null && str.length() == 0) - deleteNoneProperty(i); - else - putSelectedPropertyInto(properties, str, i); - // applySelectedPropertyValue(str,i); - - // set apply value in ComboListOnPropertyPage. - combo[i].setApplyValue(str); - } - if (properties != null && !properties.isEmpty()) - contentSettings.setProperties((IResource) super.getElement(), properties); - if (properties != null) - properties.clear(); - properties = null; - if (!contentSettings.existsProperties((IResource) super.getElement())) - contentSettings.deleteAllProperties((IResource) super.getElement()); - return true; - } - - protected abstract void putSelectedPropertyInto(Map properties, String str, int i); - - - protected void setSelectionItem(ComboListOnPropertyPage combo, String value) { - if (combo.getItemCount() <= 0) - return; - combo.setApplyValue(value); - String item = combo.getKey(value); - if (item != null) - combo.select(combo.indexOf(item)); - else - combo.select(0); - - } - - /* - * Validate Edit. Similar function will be in HTMLCommand.java - * ContentSettingsPropertyPage.java CSSActionManager.java - * DesignRedoAction.java DesignUndoAction.java - * HTMLConversionProcessor.java - */ - private boolean validateState() { - - // get IFile of .contentsettings - final String name = ContentSettings.getContentSettingsName(); - final IResource resource = (IResource) super.getElement(); - final IProject project = resource.getProject(); - IFile file = project.getFile(name); - - if (file != null && !file.exists()) - return true; // Is this really OK? - // If false should be returned, - // This statemant can be removed, - // since ModelManagerUtil.validateEdit() - // returns error to this case. - - Shell shell = getControl().getShell(); - IStatus status = validateEdit(file, shell); - return status.isOK() ? true : false; - } - -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/correction/AnnotationQuery.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/correction/AnnotationQuery.java deleted file mode 100644 index b8d1936614..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/correction/AnnotationQuery.java +++ /dev/null @@ -1,175 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.correction; - -import java.util.Map; - -import org.eclipse.jface.text.source.Annotation; -import org.eclipse.wst.sse.ui.internal.reconcile.TemporaryAnnotation; - -/* - * Copied from org.eclipse.ui.internal.ide.registry.MarkerQuery - */ -class AnnotationQuery { - /** - * The annotation type targetted by this query. May be <code>null</code>. - */ - private String type; - - /** - * A sorted list of the attributes targetted by this query. The list is - * sorted from least to greatest according to <code>Sting.compare</code> - */ - private String[] attributes; - - /** - * Cached hash code value - */ - private int hashCode; - - /** - * Creates a new annotation query with the given type and attributes. - * <p> - * The type may be <code>null</code>. The attributes may be empty, but - * not <code>null</code>. - * </p> - * - * @param problemType - * the targeted annotation type - * @param markerAttributes - * the targeted annotation attributes - */ - public AnnotationQuery(String annotationType, String[] annotationAttributes) { - if (annotationAttributes == null) { - throw new IllegalArgumentException(); - } - - type = annotationType; - attributes = annotationAttributes; - computeHashCode(); - } - - /** - * Performs a query against the given annotation. - * <p> - * Returns a <code>AnnotationQueryResult</code> if the marker is - * appropriate for this query (correct type and has all of the query - * attributes), otherwise <code>null</code> is returned. - * - * @param annotation - * the annotation to perform the query against - * @return a annotation query result or <code>null</code> - */ - public AnnotationQueryResult performQuery(Annotation anno) { - if (!(anno instanceof TemporaryAnnotation)) - return null; - - Map annoAttributes = ((TemporaryAnnotation) anno).getAttributes(); - /* - * https://bugs.eclipse.org/bugs/show_bug.cgi?id=243660 - * - * May be null if the original validation IMessage contained no - * attributes or this annotation was not based on a validation - * IMessage - */ - if (annoAttributes == null) { - return null; - } - - // Check type - if (type != null) { - String problemType = (String) annoAttributes.get("problemType"); //$NON-NLS-1$; - if (!type.equals(problemType)) - return null; - } - - String[] values = new String[attributes.length]; - for (int i = 0; i < attributes.length; i++) { - Object value = annoAttributes.get(attributes[i]); - if (value == null) { - return null; - } - values[i] = value.toString(); - } - // Create and return the result - return new AnnotationQueryResult(values); - } - - /* - * (non-Javadoc) Method declared on Object. - */ - public boolean equals(Object o) { - if (!(o instanceof AnnotationQuery)) { - return false; - } - - if (o == this) { - return true; - } - - AnnotationQuery mq = (AnnotationQuery) o; - if (!(type == null ? mq.type == null : type.equals(mq.type))) { - return false; - } - - if (attributes.length != mq.attributes.length) { - return false; - } - - for (int i = 0; i < attributes.length; i++) { - if (!(attributes[i].equals(mq.attributes[i]))) { - return false; - } - } - - return true; - } - - /* - * (non-Javadoc) Method declared on Object. - */ - public int hashCode() { - return hashCode; - } - - /** - * Computes the hash code for this instance. - */ - public void computeHashCode() { - hashCode = 19; - - if (type != null) { - hashCode = hashCode * 37 + type.hashCode(); - } - - for (int i = 0; i < attributes.length; i++) { - hashCode = hashCode * 37 + attributes[i].hashCode(); - } - } - - /** - * Returns the targetted marker type. May be <code>null</code> - * - * @return the targetted marker type - */ - public String getType() { - return type; - } - - /** - * Returns the targetted attributes. The array may be empty. - * - * @return the targetted attributes - */ - public String[] getAttributes() { - return attributes; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/correction/AnnotationQueryResult.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/correction/AnnotationQueryResult.java deleted file mode 100644 index 51d1675952..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/correction/AnnotationQueryResult.java +++ /dev/null @@ -1,87 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.correction; - -/* - * Copied from rg.eclipse.ui.internal.ide.registr.MarkerQueryResult - */ -class AnnotationQueryResult { - /** - * An ordered collection of annotation attribute values. - */ - private String[] values; - - /** - * Cached hash code value - */ - private int hashCode; - - /** - * Creates a new annotation query result with the given values. - * <p> - * The values may not be empty. - * </p> - * - * @param annotationAttributeValues - * the target annotation's attribute values - */ - public AnnotationQueryResult(String[] annotationAttributeValues) { - if (annotationAttributeValues == null) { - throw new IllegalArgumentException(); - } - values = annotationAttributeValues; - computeHashCode(); - } - - /* - * (non-Javadoc) Method declared on Object. - */ - public boolean equals(Object o) { - if (!(o instanceof AnnotationQueryResult)) { - return false; - } - - if (o == this) { - return true; - } - - AnnotationQueryResult mqr = (AnnotationQueryResult) o; - if (values.length != mqr.values.length) { - return false; - } - - for (int i = 0; i < values.length; i++) { - if (!(values[i].equals(mqr.values[i]))) { - return false; - } - } - - return true; - } - - /* - * (non-Javadoc) Method declared on Object. - */ - public int hashCode() { - return hashCode; - } - - /** - * Computes the hash code for this instance. - */ - public void computeHashCode() { - hashCode = 19; - - for (int i = 0; i < values.length; i++) { - hashCode = hashCode * 37 + values[i].hashCode(); - } - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/correction/CompoundQuickAssistProcessor.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/correction/CompoundQuickAssistProcessor.java deleted file mode 100644 index 7e410d49a6..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/correction/CompoundQuickAssistProcessor.java +++ /dev/null @@ -1,211 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.correction; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.TextUtilities; -import org.eclipse.jface.text.contentassist.ICompletionProposal; -import org.eclipse.jface.text.quickassist.IQuickAssistInvocationContext; -import org.eclipse.jface.text.quickassist.IQuickAssistProcessor; -import org.eclipse.jface.text.source.Annotation; -import org.eclipse.jface.text.source.ISourceViewer; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredPartitioning; -import org.eclipse.wst.sse.ui.internal.ExtendedConfigurationBuilder; -import org.eclipse.wst.sse.ui.internal.Logger; - -/** - * A quick assist processor that will allow for more than one quick assist - * processor. It includes quick assist processors contributed via the - * quickAssistProcessor extended configuration extension point. It also - * includes quick assist processors contributed via validators. - */ -public class CompoundQuickAssistProcessor implements IQuickAssistProcessor { - private final String QUICK_ASSIST_PROCESSOR_EXTENDED_ID = IQuickAssistProcessor.class.getName(); - private Map fProcessors; - private IQuickAssistProcessor fQuickFixProcessor; - /** - * list of partition types where extended processors have been installed - */ - private List fInstalledExtendedContentTypes; - - private Set getQuickAssistProcessors(String partitionType) { - if (fInstalledExtendedContentTypes == null || !fInstalledExtendedContentTypes.contains(partitionType)) { - // get extended quick assist processors that have not already - // been set - List processors = ExtendedConfigurationBuilder.getInstance().getConfigurations(QUICK_ASSIST_PROCESSOR_EXTENDED_ID, partitionType); - if (processors != null && !processors.isEmpty()) { - Iterator iter = processors.iterator(); - while (iter.hasNext()) { - IQuickAssistProcessor processor = (IQuickAssistProcessor) iter.next(); - setQuickAssistProcessor(partitionType, processor); - } - } - // add partition type to list of extended partition types - // installed (regardless of whether or not any extended content - // assist processors were installed because dont want to look it - // up every time) - if (fInstalledExtendedContentTypes == null) - fInstalledExtendedContentTypes = new ArrayList(); - fInstalledExtendedContentTypes.add(partitionType); - } - - Set processors = null; - if (fProcessors != null) - processors = (Set) fProcessors.get(partitionType); - - return processors; - } - - /** - * Gets all the quick assist processors relevant to the partion which is - * calcuated from the given document and offset. - * - * @param invocationContext - * @return Set of quick assist processors or null if none exist - */ - private Set getQuickAssistProcessors(IQuickAssistInvocationContext invocationContext) { - Set processsors = null; - - ISourceViewer sourceViewer = invocationContext.getSourceViewer(); - if (sourceViewer != null) { - IDocument document = sourceViewer.getDocument(); - try { - String partitionType; - if (document != null) - partitionType = TextUtilities.getContentType(document, IStructuredPartitioning.DEFAULT_STRUCTURED_PARTITIONING, invocationContext.getOffset(), true); - else - partitionType = IDocument.DEFAULT_CONTENT_TYPE; - - processsors = getQuickAssistProcessors(partitionType); - } - catch (BadLocationException x) { - Logger.log(Logger.WARNING_DEBUG, x.getMessage(), x); - } - } - - return processsors; - } - - /** - * Gets the quick assist processor for validator contributed quick fixes - * - * @return IQuickAssistProcessor - */ - private IQuickAssistProcessor getQuickFixProcessor() { - if (fQuickFixProcessor == null) - fQuickFixProcessor = new SourceValidationQuickAssistProcessor(); - - return fQuickFixProcessor; - } - - /** - * Associates a quick assist processor to a partition type and adds it to - * the list of processors in this compound processor. - * - * @param partitionType - * @param processor - */ - private void setQuickAssistProcessor(String partitionType, IQuickAssistProcessor processor) { - if (fProcessors == null) - fProcessors = new HashMap(); - - Set processors = (Set) fProcessors.get(partitionType); - - if (processor == null && processors != null) { - // removing quick assist processor for this partition type - processors.clear(); - // check if it's the only - fProcessors.remove(partitionType); - } - else { - if (processors == null) { - processors = new LinkedHashSet(); - } - processors.add(processor); - fProcessors.put(partitionType, processors); - } - } - - public boolean canAssist(IQuickAssistInvocationContext invocationContext) { - Set processors = getQuickAssistProcessors(invocationContext); - if (processors != null) { - // iterate through list of processors until one processor says - // canAssist - for (Iterator it = processors.iterator(); it.hasNext();) { - IQuickAssistProcessor p = (IQuickAssistProcessor) it.next(); - if (p.canAssist(invocationContext)) - return true; - } - } - return false; - } - - public boolean canFix(Annotation annotation) { - // only quick fix processor contributes fixes so just check it - IQuickAssistProcessor processor = getQuickFixProcessor(); - return processor.canFix(annotation); - } - - public ICompletionProposal[] computeQuickAssistProposals(IQuickAssistInvocationContext invocationContext) { - List proposalsList = new ArrayList(); - - // first get list of fixes - IQuickAssistProcessor processor = getQuickFixProcessor(); - ICompletionProposal[] proposals = processor.computeQuickAssistProposals(invocationContext); - if (proposals != null && proposals.length > 0) { - proposalsList.addAll(Arrays.asList(proposals)); - } - - // no fixes, so try adding assists - if (proposalsList.isEmpty()) { - Set processors = getQuickAssistProcessors(invocationContext); - if (processors != null) { - // iterate through list of processors until one processor says - // canAssist - for (Iterator it = processors.iterator(); it.hasNext();) { - IQuickAssistProcessor assistProcessor = (IQuickAssistProcessor) it.next(); - ICompletionProposal[] assistProposals = assistProcessor.computeQuickAssistProposals(invocationContext); - if (assistProposals != null && assistProposals.length > 0) { - proposalsList.addAll(Arrays.asList(assistProposals)); - } - } - } - } - - /* - * Java editor currently returns a no modification completion proposal - * but it seems better to just return null so user does not get - * annoying proposal popup - */ - if (proposalsList.isEmpty()) { - // proposalsList.add(new NoModificationCompletionProposal()); - return null; - } - - return (ICompletionProposal[]) proposalsList.toArray(new ICompletionProposal[proposalsList.size()]); - } - - public String getErrorMessage() { - // never have error messages - return null; - } - -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/correction/ContributedProcessorDescriptor.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/correction/ContributedProcessorDescriptor.java deleted file mode 100644 index d64572a0d2..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/correction/ContributedProcessorDescriptor.java +++ /dev/null @@ -1,39 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2007 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.correction; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IConfigurationElement; - -/** - * @deprecated since 2.0 RC0 Use - * org.eclipse.jface.text.quickassist.IQuickAssistProcessor; - */ -public class ContributedProcessorDescriptor { - private static final String CLASS = "class"; //$NON-NLS-1$ - - private IConfigurationElement fConfigurationElement; - private Object fProcessorInstance; - - public ContributedProcessorDescriptor(IConfigurationElement element) { - fConfigurationElement = element; - fProcessorInstance = null; - } - - public Object getProcessor() throws CoreException { - if (fProcessorInstance == null && fConfigurationElement != null) { - fProcessorInstance = fConfigurationElement.createExecutableExtension(CLASS); - } - return fProcessorInstance; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/correction/CorrectionAssistantProvider.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/correction/CorrectionAssistantProvider.java deleted file mode 100644 index e044939d70..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/correction/CorrectionAssistantProvider.java +++ /dev/null @@ -1,34 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2007 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.correction; - -import org.eclipse.jface.text.contentassist.IContentAssistant; -import org.eclipse.jface.text.source.ISourceViewer; - -/** - * Provides the appropriate correction assistant for a given source viewer. - * This class should only be a placeholder until the base implements a common - * way for quickfix/quick assist. - * - * @deprecated since 2.0 RC0 Use - * org.eclipse.jface.text.quickassist.IQuickAssistProcessor; - */ -abstract public class CorrectionAssistantProvider { - /** - * Returns the correction assistant for the given sourceviewer. - * - * @param sourceViewer - * @return - */ - abstract public IContentAssistant getCorrectionAssistant(ISourceViewer sourceViewer); -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/correction/IQuickAssistProcessor.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/correction/IQuickAssistProcessor.java deleted file mode 100644 index 6720223719..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/correction/IQuickAssistProcessor.java +++ /dev/null @@ -1,34 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2007 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.correction; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.jface.text.contentassist.ICompletionProposal; -import org.eclipse.wst.sse.ui.internal.StructuredTextViewer; - -/** - * @deprecated since 2.0 RC0 Use - * org.eclipse.jface.text.quickassist.IQuickAssistProcessor; - */ -public interface IQuickAssistProcessor { - /** - * Returns true if the processor can assist at the given offset. This test - * should be an optimistic guess and be extremly cheap. - */ - boolean canAssist(StructuredTextViewer viewer, int offset); - - /** - * Collects proposals for assistant at the given offset. - */ - ICompletionProposal[] getProposals(StructuredTextViewer viewer, int offset) throws CoreException; -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/correction/IQuickFixProcessor.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/correction/IQuickFixProcessor.java deleted file mode 100644 index c93d21e05c..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/correction/IQuickFixProcessor.java +++ /dev/null @@ -1,34 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2007 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.correction; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.jface.text.contentassist.ICompletionProposal; -import org.eclipse.jface.text.source.Annotation; - -/** - * @deprecated since 2.0 RC0 Use - * org.eclipse.jface.text.quickassist.IQuickAssistProcessor; - */ -public interface IQuickFixProcessor { - /** - * Returns true if the processor can fix the given problem. This test - * should be an optimistic guess and be extremly cheap. - */ - boolean canFix(Annotation annnotation); - - /** - * Collects proposals for fixing the given problem. - */ - ICompletionProposal[] getProposals(Annotation annnotation) throws CoreException; -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/correction/NoModificationCompletionProposal.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/correction/NoModificationCompletionProposal.java deleted file mode 100644 index babb1a8158..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/correction/NoModificationCompletionProposal.java +++ /dev/null @@ -1,77 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.correction; - -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.contentassist.ICompletionProposal; -import org.eclipse.jface.text.contentassist.IContextInformation; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.graphics.Point; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; - -public class NoModificationCompletionProposal implements ICompletionProposal { - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.text.contentassist.ICompletionProposal#apply(org.eclipse.jface.text.IDocument) - */ - public void apply(IDocument document) { - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.text.contentassist.ICompletionProposal#getAdditionalProposalInfo() - */ - public String getAdditionalProposalInfo() { - return null; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.text.contentassist.ICompletionProposal#getContextInformation() - */ - public IContextInformation getContextInformation() { - return null; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.text.contentassist.ICompletionProposal#getDisplayString() - */ - public String getDisplayString() { - return SSEUIMessages.NoModificationCompletionProposal_0; //$NON-NLS-1$ - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.text.contentassist.ICompletionProposal#getImage() - */ - public Image getImage() { - return null; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.text.contentassist.ICompletionProposal#getSelection(org.eclipse.jface.text.IDocument) - */ - public Point getSelection(IDocument document) { - return null; - } - -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/correction/QuickFixRegistry.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/correction/QuickFixRegistry.java deleted file mode 100644 index 2be196f602..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/correction/QuickFixRegistry.java +++ /dev/null @@ -1,137 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.correction; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IConfigurationElement; -import org.eclipse.jface.text.quickassist.IQuickAssistProcessor; -import org.eclipse.jface.text.source.Annotation; -import org.eclipse.wst.sse.core.internal.Logger; - -public class QuickFixRegistry { - private static QuickFixRegistry instance; - - public synchronized static QuickFixRegistry getInstance() { - if (instance == null) { - instance = new QuickFixRegistry(); - new QuickFixRegistryReader().addHelp(instance); - } - return instance; - } - - /** - * Table of queries for marker resolutions - */ - private Map resolutionQueries = new HashMap(); - /** - * Resolution class attribute name in configuration element - */ - private static final String ATT_CLASS = "class"; //$NON-NLS-1$ - - /** - * Adds a resolution query to the registry. - * - * @param query - * a marker query - * @param result - * a result for the given query - * @param element - * the configuration element defining the result - */ - void addResolutionQuery(AnnotationQuery query, AnnotationQueryResult result, IConfigurationElement element) { - addQuery(resolutionQueries, query, result, element); - } - - /** - * Adds a query to the given table. - * - * @param table - * the table to which the query is added - * @param query - * a marker query - * @param result - * a result for the given query - * @param element - * the configuration element defining the result - */ - private void addQuery(Map table, AnnotationQuery query, AnnotationQueryResult result, IConfigurationElement element) { - - // See if the query is already in the table - Map results = (Map) table.get(query); - if (results == null) { - // Create a new results table - results = new HashMap(); - - // Add the query to the table - table.put(query, results); - } - - if (results.containsKey(result)) { - Collection currentElements = (Collection) results.get(result); - currentElements.add(element); - } - else { - Collection elements = new HashSet(); - elements.add(element); - - // Add the new result - results.put(result, elements); - } - } - - public IQuickAssistProcessor[] getQuickFixProcessors(Annotation anno) { - // Collect all matches - List processors = new ArrayList(); - for (Iterator iter = resolutionQueries.keySet().iterator(); iter.hasNext();) { - AnnotationQuery query = (AnnotationQuery) iter.next(); - AnnotationQueryResult result = null; - try { - /* AnnotationQuery objects are contributed by extension point */ - result = query.performQuery(anno); - } - catch (Exception e) { - Logger.logException(e); - } - if (result != null) { - // See if a matching result is registered - Map resultsTable = (Map) resolutionQueries.get(query); - - if (resultsTable.containsKey(result)) { - - Iterator elements = ((Collection) resultsTable.get(result)).iterator(); - while (elements.hasNext()) { - IConfigurationElement element = (IConfigurationElement) elements.next(); - - IQuickAssistProcessor processor = null; - try { - processor = (IQuickAssistProcessor) element.createExecutableExtension(ATT_CLASS); - } - catch (CoreException e) { - } - if (processor != null) { - processors.add(processor); - } - - } - } - } - } - return (IQuickAssistProcessor[]) processors.toArray(new IQuickAssistProcessor[processors.size()]); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/correction/QuickFixRegistryReader.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/correction/QuickFixRegistryReader.java deleted file mode 100644 index 4341bde6d4..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/correction/QuickFixRegistryReader.java +++ /dev/null @@ -1,93 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.correction; - -import java.util.ArrayList; - -import org.eclipse.core.runtime.IConfigurationElement; -import org.eclipse.core.runtime.IExtensionRegistry; -import org.eclipse.core.runtime.Platform; -import org.eclipse.wst.sse.ui.internal.SSEUIPlugin; -import org.eclipse.wst.sse.ui.internal.extension.RegistryReader; - -public class QuickFixRegistryReader extends RegistryReader { - private static final String QUICKFIXPROCESSOR = "quickFixProcessor"; //$NON-NLS-1$ - private static final String ATT_PROBLEMTYPE = "problemType"; //$NON-NLS-1$ - - private static final String ATTRIBUTE = "attribute"; //$NON-NLS-1$ - private static final String ATT_NAME = "name"; //$NON-NLS-1$ - private static final String ATT_VALUE = "value"; //$NON-NLS-1$ - - private ArrayList currentAttributeNames; - - private ArrayList currentAttributeValues; - - private QuickFixRegistry quickFixProcessorRegistry; - - protected boolean readElement(IConfigurationElement element) { - if (element.getName().equals(QUICKFIXPROCESSOR)) { - readQuickFixProcessorElement(element); - return true; - } - if (element.getName().equals(ATTRIBUTE)) { - readAttributeElement(element); - return true; - } - return false; - } - - /** - * Processes a resolution configuration element. - */ - private void readQuickFixProcessorElement(IConfigurationElement element) { - // read type - String type = element.getAttribute(ATT_PROBLEMTYPE); - - // read attributes and values - currentAttributeNames = new ArrayList(); - currentAttributeValues = new ArrayList(); - readElementChildren(element); - String[] attributeNames = (String[]) currentAttributeNames.toArray(new String[currentAttributeNames.size()]); - String[] attributeValues = (String[]) currentAttributeValues.toArray(new String[currentAttributeValues.size()]); - - // add query to the registry - AnnotationQuery query = new AnnotationQuery(type, attributeNames); - AnnotationQueryResult result = new AnnotationQueryResult(attributeValues); - quickFixProcessorRegistry.addResolutionQuery(query, result, element); - } - - /** - * Get the marker help that is defined in the plugin registry and add it - * to the given marker help registry. - * <p> - * Warning: The marker help registry must be passed in because this method - * is called during the process of setting up the marker help registry and - * at this time it has not been safely setup with the plugin. - * </p> - */ - public void addHelp(QuickFixRegistry registry) { - IExtensionRegistry extensionRegistry = Platform.getExtensionRegistry(); - quickFixProcessorRegistry = registry; - readRegistry(extensionRegistry, SSEUIPlugin.ID, QUICKFIXPROCESSOR); - } - - /** - * Processes an attribute sub element. - */ - private void readAttributeElement(IConfigurationElement element) { - String name = element.getAttribute(ATT_NAME); - String value = element.getAttribute(ATT_VALUE); - if (name != null && value != null) { - currentAttributeNames.add(name); - currentAttributeValues.add(value); - } - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/correction/SourceValidationQuickAssistProcessor.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/correction/SourceValidationQuickAssistProcessor.java deleted file mode 100644 index 9033fd531b..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/correction/SourceValidationQuickAssistProcessor.java +++ /dev/null @@ -1,118 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.correction; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.eclipse.jface.text.Position; -import org.eclipse.jface.text.contentassist.ICompletionProposal; -import org.eclipse.jface.text.quickassist.IQuickAssistInvocationContext; -import org.eclipse.jface.text.quickassist.IQuickAssistProcessor; -import org.eclipse.jface.text.quickassist.IQuickFixableAnnotation; -import org.eclipse.jface.text.source.Annotation; -import org.eclipse.jface.text.source.IAnnotationModel; -import org.eclipse.jface.text.source.IAnnotationModelExtension2; -import org.eclipse.jface.text.source.ISourceViewer; -import org.eclipse.wst.sse.ui.StructuredTextInvocationContext; -import org.eclipse.wst.sse.ui.internal.reconcile.TemporaryAnnotation; - -/** - * This quick assist processor will provide quick fixes for source validation - * errors (Temporary Annotation) - */ -public class SourceValidationQuickAssistProcessor implements IQuickAssistProcessor { - public boolean canAssist(IQuickAssistInvocationContext invocationContext) { - return false; - } - - public boolean canFix(Annotation annotation) { - if (annotation instanceof IQuickFixableAnnotation) { - if (((IQuickFixableAnnotation) annotation).isQuickFixableStateSet()) { - return ((IQuickFixableAnnotation) annotation).isQuickFixable(); - } - } - return false; - } - - public ICompletionProposal[] computeQuickAssistProposals(IQuickAssistInvocationContext quickAssistContext) { - ISourceViewer viewer = quickAssistContext.getSourceViewer(); - int documentOffset = quickAssistContext.getOffset(); - int length = viewer != null ? viewer.getSelectedRange().y : 0; - - IAnnotationModel model = viewer.getAnnotationModel(); - if (model == null) - return null; - - List allProposals = new ArrayList(); - if (model instanceof IAnnotationModelExtension2) { - Iterator iter = ((IAnnotationModelExtension2) model).getAnnotationIterator(documentOffset, length, true, true); - while (iter.hasNext()) { - List processors = new ArrayList(); - Annotation anno = (Annotation) iter.next(); - if (canFix(anno)) { - // first check to see if annotation already has a quick - // fix processor attached to it - if (anno instanceof TemporaryAnnotation) { - Object o = ((TemporaryAnnotation) anno).getAdditionalFixInfo(); - if (o instanceof IQuickAssistProcessor) { - processors.add(o); - } - } - - // get all relevant quick fixes for this annotation - QuickFixRegistry registry = QuickFixRegistry.getInstance(); - processors.addAll(Arrays.asList(registry.getQuickFixProcessors(anno))); - - // set up context - Map attributes = null; - if (anno instanceof TemporaryAnnotation) { - attributes = ((TemporaryAnnotation) anno).getAttributes(); - } - Position pos = model.getPosition(anno); - StructuredTextInvocationContext sseContext = new StructuredTextInvocationContext(viewer, pos.getOffset(), pos.getLength(), attributes); - - // call each processor - for (int i = 0; i < processors.size(); ++i) { - List proposals = new ArrayList(); - collectProposals((IQuickAssistProcessor) processors.get(i), anno, sseContext, proposals); - - if (proposals.size() > 0) { - allProposals.addAll(proposals); - } - } - - } - } - } - - if (allProposals.isEmpty()) - return null; - - return (ICompletionProposal[]) allProposals.toArray(new ICompletionProposal[allProposals.size()]); - } - - private void collectProposals(IQuickAssistProcessor processor, Annotation annotation, IQuickAssistInvocationContext invocationContext, List proposalsList) { - ICompletionProposal[] proposals = processor.computeQuickAssistProposals(invocationContext); - if (proposals != null && proposals.length > 0) { - proposalsList.addAll(Arrays.asList(proposals)); - } - } - - - public String getErrorMessage() { - return null; - } - -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/correction/StructuredCorrectionProcessor.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/correction/StructuredCorrectionProcessor.java deleted file mode 100644 index d19427cbae..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/correction/StructuredCorrectionProcessor.java +++ /dev/null @@ -1,161 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2007 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.correction; - -import java.util.ArrayList; -import java.util.Iterator; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.Position; -import org.eclipse.jface.text.contentassist.ICompletionProposal; -import org.eclipse.jface.text.contentassist.IContentAssistProcessor; -import org.eclipse.jface.text.contentassist.IContextInformation; -import org.eclipse.jface.text.contentassist.IContextInformationValidator; -import org.eclipse.jface.text.source.Annotation; -import org.eclipse.jface.text.source.IAnnotationModel; -import org.eclipse.jface.text.source.ISourceViewer; -import org.eclipse.wst.sse.ui.internal.Logger; -import org.eclipse.wst.sse.ui.internal.StructuredTextViewer; - -/** - * @deprecated since 2.0 RC0 Use - * org.eclipse.jface.text.quickassist.IQuickAssistProcessor; - */ -public class StructuredCorrectionProcessor implements IContentAssistProcessor { - protected IAnnotationModel fAnnotationModel; - protected IQuickAssistProcessor fQuickAssistProcessor; - protected IQuickFixProcessor fQuickFixProcessor; - - public StructuredCorrectionProcessor(ISourceViewer sourceViewer) { - fAnnotationModel = sourceViewer.getAnnotationModel(); - } - - protected void addQuickAssistProposals(StructuredTextViewer viewer, ArrayList proposals, int documentOffset) { - try { - IQuickAssistProcessor processor = getQuickAssistProcessor(); - if (processor != null && processor.canAssist(viewer, documentOffset)) { - ICompletionProposal[] res = processor.getProposals(viewer, documentOffset); - if (res != null) { - for (int k = 0; k < res.length; k++) { - proposals.add(res[k]); - } - } - } - } catch (CoreException e) { - // log for now, unless we find reason not to - Logger.log(Logger.INFO, e.getMessage()); - } - } - - protected void addQuickFixProposals(StructuredTextViewer viewer, ArrayList proposals, int documentOffset) { - Iterator iter = fAnnotationModel.getAnnotationIterator(); - while (iter.hasNext()) { - Annotation annotation = (Annotation) iter.next(); - Position pos = fAnnotationModel.getPosition(annotation); - if (pos != null && documentOffset >= pos.offset && documentOffset <= pos.offset + pos.length) { - IQuickFixProcessor processor = getQuickFixProcessor(); - if (processor != null && processor.canFix(annotation)) { - try { - ICompletionProposal[] res = processor.getProposals(annotation); - if (res != null) { - for (int k = 0; k < res.length; k++) { - proposals.add(res[k]); - } - } - } catch (CoreException e) { - // log for now, unless we find reason not to - Logger.log(Logger.INFO, e.getMessage()); - } - } - } - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#computeCompletionProposals(org.eclipse.jface.text.ITextViewer, - * int) - */ - public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int documentOffset) { - ArrayList proposals = new ArrayList(); - - if (viewer instanceof StructuredTextViewer) { - addQuickFixProposals((StructuredTextViewer) viewer, proposals, documentOffset); - - if (proposals.isEmpty()) { - addQuickAssistProposals((StructuredTextViewer) viewer, proposals, documentOffset); - } - } - - if (proposals.isEmpty()) - proposals.add(new NoModificationCompletionProposal()); - - return (ICompletionProposal[]) proposals.toArray(new ICompletionProposal[proposals.size()]); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#computeContextInformation(org.eclipse.jface.text.ITextViewer, - * int) - */ - public IContextInformation[] computeContextInformation(ITextViewer viewer, int documentOffset) { - return null; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getCompletionProposalAutoActivationCharacters() - */ - public char[] getCompletionProposalAutoActivationCharacters() { - return null; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getContextInformationAutoActivationCharacters() - */ - public char[] getContextInformationAutoActivationCharacters() { - return null; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getContextInformationValidator() - */ - public IContextInformationValidator getContextInformationValidator() { - return null; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getErrorMessage() - */ - public String getErrorMessage() { - return null; - } - - protected IQuickAssistProcessor getQuickAssistProcessor() { - return null; - } - - protected IQuickFixProcessor getQuickFixProcessor() { - return null; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/debug/BreakpointRulerAction.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/debug/BreakpointRulerAction.java deleted file mode 100644 index 7da59b4645..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/debug/BreakpointRulerAction.java +++ /dev/null @@ -1,318 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * Pete Carapetyan/Genuitec - 244835 - Enable/Disable breakpoint action does not refresh its label - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.debug; - -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IMarker; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IPath; -import org.eclipse.debug.core.DebugPlugin; -import org.eclipse.debug.core.IBreakpointManager; -import org.eclipse.debug.core.model.IBreakpoint; -import org.eclipse.jface.action.Action; -import org.eclipse.jface.action.IMenuListener; -import org.eclipse.jface.action.IMenuManager; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.Position; -import org.eclipse.jface.text.source.IAnnotationModel; -import org.eclipse.jface.text.source.IVerticalRulerInfo; -import org.eclipse.swt.events.MouseEvent; -import org.eclipse.swt.events.MouseListener; -import org.eclipse.ui.IEditorInput; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.IFileEditorInput; -import org.eclipse.ui.IPartService; -import org.eclipse.ui.IStorageEditorInput; -import org.eclipse.ui.IWorkbench; -import org.eclipse.ui.IWorkbenchWindow; -import org.eclipse.ui.texteditor.AbstractMarkerAnnotationModel; -import org.eclipse.ui.texteditor.IDocumentProvider; -import org.eclipse.ui.texteditor.ITextEditor; -import org.eclipse.ui.texteditor.ITextEditorExtension; -import org.eclipse.ui.texteditor.IUpdate; -import org.eclipse.wst.sse.core.StructuredModelManager; -import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel; -import org.eclipse.wst.sse.ui.internal.Logger; -import org.eclipse.wst.sse.ui.internal.SSEUIPlugin; -import org.eclipse.wst.sse.ui.internal.extension.BreakpointProviderBuilder; -import org.eclipse.wst.sse.ui.internal.provisional.extensions.breakpoint.IBreakpointProvider; - - -public abstract class BreakpointRulerAction extends Action implements IUpdate { - - protected class MouseUpdater implements MouseListener { - public void mouseDoubleClick(MouseEvent e) { - // do nothing (here) - } - - public void mouseDown(MouseEvent e) { - update(); - } - - public void mouseUp(MouseEvent e) { - // do nothing - } - } - - public static final String getFileExtension(IEditorInput input) { - IPath path = null; - if (input instanceof IStorageEditorInput) { - try { - path = ((IStorageEditorInput) input).getStorage().getFullPath(); - } catch (CoreException e) { - Logger.logException(e); - } - } - if (path != null) { - return path.getFileExtension(); - } - String name = input.getName(); - int index = name.lastIndexOf('.'); - if (index == -1) - return null; - if (index == (name.length() - 1)) - return ""; //$NON-NLS-1$ - return name.substring(index + 1); - } - - public static final IResource getResource(IEditorInput input) { - IResource resource = null; - - if (input instanceof IFileEditorInput) - resource = ((IFileEditorInput) input).getFile(); - if (resource == null) - resource = (IResource) input.getAdapter(IFile.class); - if (resource == null) - resource = (IResource) input.getAdapter(IResource.class); - - IEditorPart editorPart = null; - if (resource == null) { - IWorkbench workbench = SSEUIPlugin.getDefault().getWorkbench(); - if (workbench != null) { - IWorkbenchWindow window = workbench.getActiveWorkbenchWindow(); - if (window != null) { - IPartService service = window.getPartService(); - if (service != null) { - Object part = service.getActivePart(); - if (part != null && part instanceof IEditorPart) { - editorPart = (IEditorPart) part; - if (editorPart != null) { - IStructuredModel model = null; - ITextEditor textEditor = null; - try { - if (editorPart instanceof ITextEditor) { - textEditor = (ITextEditor) editorPart; - } - if (textEditor == null) { - textEditor = (ITextEditor) editorPart.getAdapter(ITextEditor.class); - } - if (textEditor != null) { - IDocument textDocument = textEditor.getDocumentProvider().getDocument(input); - model = StructuredModelManager.getModelManager().getExistingModelForRead(textDocument); - if (model != null) { - resource = BreakpointProviderBuilder.getInstance().getResource(input, model.getContentTypeIdentifier(), getFileExtension(input)); - } - } - if (resource == null) { - IBreakpointProvider[] providers = BreakpointProviderBuilder.getInstance().getBreakpointProviders(editorPart, null, getFileExtension(input)); - for (int i = 0; i < providers.length && resource == null; i++) { - resource = providers[i].getResource(input); - } - } - } catch (Exception e) { - Logger.logException(e); - } finally { - if (model != null) { - model.releaseFromRead(); - } - } - } - - } - } - } - - } - } - return resource; - } - - protected MouseListener fMouseListener = null; - - protected IVerticalRulerInfo fRulerInfo = null; - protected ITextEditor fTextEditor = null; - - private IMenuListener menuListener; - - public BreakpointRulerAction(ITextEditor editor, IVerticalRulerInfo rulerInfo) { - super(); - fTextEditor = editor; - if (rulerInfo != null) { - fRulerInfo = rulerInfo; - fMouseListener = new MouseUpdater(); - rulerInfo.getControl().addMouseListener(fMouseListener); - } - if (editor instanceof ITextEditorExtension) { - ITextEditorExtension extension = (ITextEditorExtension) editor; - menuListener = new IMenuListener() { - public void menuAboutToShow(IMenuManager manager) { - update(); - } - }; - extension.addRulerContextMenuListener(menuListener); - } - } - - /** - * Returns the <code>AbstractMarkerAnnotationModel</code> of the - * editor's input. - * - * @return the marker annotation model - */ - protected AbstractMarkerAnnotationModel getAnnotationModel() { - IDocumentProvider provider = fTextEditor.getDocumentProvider(); - IAnnotationModel model = provider.getAnnotationModel(fTextEditor.getEditorInput()); - if (model instanceof AbstractMarkerAnnotationModel) - return (AbstractMarkerAnnotationModel) model; - return null; - } - - protected IBreakpoint[] getBreakpoints(IMarker[] markers) { - IBreakpointManager manager = DebugPlugin.getDefault().getBreakpointManager(); - List breakpoints = new ArrayList(markers.length); - for (int i = 0; i < markers.length; i++) { - IBreakpoint breakpoint = manager.getBreakpoint(markers[i]); - if (breakpoint != null) { - breakpoints.add(breakpoint); - } - } - return (IBreakpoint[]) breakpoints.toArray(new IBreakpoint[0]); - } - - /** - * Returns the <code>IDocument</code> of the editor's input. - * - * @return the document of the editor's input - */ - protected IDocument getDocument() { - IDocumentProvider provider = fTextEditor.getDocumentProvider(); - return provider.getDocument(fTextEditor.getEditorInput()); - } - - /** - * Returns all breakpoint markers which include the ruler's line of activity. - * - * @return an array of markers which include the ruler's line of activity - */ - protected IMarker[] getMarkers() { - List markers = new ArrayList(); - - IResource resource = getResource(); - IDocument document = getDocument(); - AbstractMarkerAnnotationModel annotationModel = getAnnotationModel(); - - if (resource != null && annotationModel != null && resource.exists()) { - try { - IMarker[] allMarkers = resource.findMarkers(IBreakpoint.BREAKPOINT_MARKER, true, IResource.DEPTH_ZERO); - if (allMarkers != null) { - for (int i = 0; i < allMarkers.length; i++) { - if (includesRulerLine(annotationModel.getMarkerPosition(allMarkers[i]), document)) { - markers.add(allMarkers[i]); - } - } - } - } catch (CoreException x) { - // - } - } - - return (IMarker[]) markers.toArray(new IMarker[0]); - } - - protected IResource getResource() { - IEditorInput input = getTextEditor().getEditorInput(); - IResource resource = getResource(input); - return resource; - } - - /** - * @return Returns the rulerInfo. - */ - public IVerticalRulerInfo getRulerInfo() { - return fRulerInfo; - } - - /** - * @return Returns the textEditor. - */ - public ITextEditor getTextEditor() { - return fTextEditor; - } - - protected boolean hasMarkers() { - IResource resource = getResource(); - IDocument document = getDocument(); - AbstractMarkerAnnotationModel model = getAnnotationModel(); - - if (resource != null && model != null && resource.exists()) { - try { - IMarker[] allMarkers = resource.findMarkers(IBreakpoint.LINE_BREAKPOINT_MARKER, true, IResource.DEPTH_ZERO); - if (allMarkers != null) { - for (int i = 0; i < allMarkers.length; i++) { - if (includesRulerLine(model.getMarkerPosition(allMarkers[i]), document)) { - return true; - } - } - } - } catch (CoreException x) { - // - } - } - return false; - } - - /** - * Checks whether a position includes the ruler's line of activity. - * - * @param position - * the position to be checked - * @param document - * the document the position refers to - * @return <code>true</code> if the line is included by the given - * position - */ - protected boolean includesRulerLine(Position position, IDocument document) { - if (position != null && fRulerInfo != null) { - try { - int markerLine = document.getLineOfOffset(position.getOffset()); - int line = getRulerInfo().getLineOfLastMouseButtonActivity(); - if (line == markerLine) - return true; - // commented because of "1GEUOZ9: ITPJUI:ALL - Confusing UI - // for - // multiline Bookmarks and Tasks" - // return (markerLine <= line && line <= - // document.getLineOfOffset(position.getOffset() + - // position.getLength())); - } catch (BadLocationException x) { - // - } - } - return false; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/debug/DebugTextEditor.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/debug/DebugTextEditor.java deleted file mode 100644 index c733782029..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/debug/DebugTextEditor.java +++ /dev/null @@ -1,438 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2006 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.debug; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.core.filebuffers.FileBuffers; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IMarker; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.content.IContentDescription; -import org.eclipse.core.runtime.content.IContentType; -import org.eclipse.core.runtime.content.IContentTypeManager; -import org.eclipse.jface.action.IAction; -import org.eclipse.jface.action.IMenuManager; -import org.eclipse.jface.action.Separator; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.source.IAnnotationModel; -import org.eclipse.ui.IEditorActionBarContributor; -import org.eclipse.ui.IEditorInput; -import org.eclipse.ui.IFileEditorInput; -import org.eclipse.ui.IPageLayout; -import org.eclipse.ui.IPathEditorInput; -import org.eclipse.ui.IStorageEditorInput; -import org.eclipse.ui.editors.text.FileDocumentProvider; -import org.eclipse.ui.editors.text.ILocationProvider; -import org.eclipse.ui.editors.text.StorageDocumentProvider; -import org.eclipse.ui.editors.text.TextEditor; -import org.eclipse.ui.part.IShowInTargetList; -import org.eclipse.ui.texteditor.AbstractDocumentProvider; -import org.eclipse.ui.texteditor.IDocumentProvider; -import org.eclipse.ui.texteditor.IElementStateListener; -import org.eclipse.ui.texteditor.ITextEditorActionConstants; -import org.eclipse.ui.texteditor.MarkerRulerAction; -import org.eclipse.wst.sse.core.utils.StringUtils; -import org.eclipse.wst.sse.ui.internal.ExtendedConfigurationBuilder; -import org.eclipse.wst.sse.ui.internal.ExtendedEditorActionBuilder; -import org.eclipse.wst.sse.ui.internal.IExtendedContributor; -import org.eclipse.wst.sse.ui.internal.IPopupMenuContributor; -import org.eclipse.wst.sse.ui.internal.Logger; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; -import org.eclipse.wst.sse.ui.internal.StructuredResourceMarkerAnnotationModel; -import org.eclipse.wst.sse.ui.internal.actions.ActionDefinitionIds; -import org.eclipse.wst.sse.ui.internal.extension.BreakpointProviderBuilder; -import org.eclipse.wst.sse.ui.internal.provisional.extensions.ConfigurationPointCalculator; -import org.eclipse.wst.sse.ui.internal.provisional.extensions.breakpoint.IExtendedStorageEditorInput; - - -/** - * @author nitin - * - * A text editor capable of using the IBreakpointProvider framework. - * - * This class is intended to be used by clients who wish to use the - * IBreakpointProvider framework but not the StructuredTextEditor, e.g. VBS - * source editors. It is provided AS-IS and marked internal as it is - * unsupported and subject to change at any time. - */ -public class DebugTextEditor extends TextEditor { - - private class ShowInTargetLister implements IShowInTargetList { - public String[] getShowInTargetIds() { - return fShowInTargetIds; - } - } - - /** - * DocumentProvider for IStorageEditorInputs - supports - * IExtendedStorageEditorInput notifications and assigning breakpoint - * markers. - */ - class StorageInputDocumentProvider extends StorageDocumentProvider implements IElementStateListener { - protected IAnnotationModel createAnnotationModel(Object element) throws CoreException { - IAnnotationModel model = null; - IStorageEditorInput storageInput = (IStorageEditorInput) element; - String ext = BreakpointRulerAction.getFileExtension(storageInput); - IContentType[] types = getEditorInputContentTypes(storageInput); - IResource res = null; - for (int i = 0; res == null && i < types.length; i++) { - res = BreakpointProviderBuilder.getInstance().getResource(storageInput, types[i].getId(), ext); - } - String id = storageInput.getName(); - if (storageInput.getStorage() != null) { - IPath fullPath = storageInput.getStorage().getFullPath(); - if (fullPath != null) - id = fullPath.toString(); - else - id = storageInput.getName(); - } - if (res != null) - model = new StructuredResourceMarkerAnnotationModel(res, id); - else - model = new StructuredResourceMarkerAnnotationModel(ResourcesPlugin.getWorkspace().getRoot(), id); - - return model; - } - - protected AbstractDocumentProvider.ElementInfo createElementInfo(Object element) throws CoreException { - if (element instanceof IExtendedStorageEditorInput) { - ((IExtendedStorageEditorInput) element).addElementStateListener(this); - } - return super.createElementInfo(element); - } - - protected void disposeElementInfo(Object element, ElementInfo info) { - if (element instanceof IExtendedStorageEditorInput) { - ((IExtendedStorageEditorInput) element).removeElementStateListener(this); - } - super.disposeElementInfo(element, info); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.editors.text.StorageDocumentProvider#doSaveDocument(org.eclipse.core.runtime.IProgressMonitor, - * java.lang.Object, org.eclipse.jface.text.IDocument, boolean) - */ - protected void doSaveDocument(IProgressMonitor monitor, Object element, IDocument document, boolean overwrite) throws CoreException { - // untested - new FileDocumentProvider().saveDocument(monitor, element, document, overwrite); - } - - public void elementContentAboutToBeReplaced(Object element) { - fireElementContentAboutToBeReplaced(element); - } - - public void elementContentReplaced(Object element) { - fireElementContentReplaced(element); - } - - public void elementDeleted(Object element) { - fireElementDeleted(element); - } - - public void elementDirtyStateChanged(Object element, boolean isDirty) { - fireElementDirtyStateChanged(element, isDirty); - } - - public void elementMoved(Object originalElement, Object movedElement) { - fireElementMoved(originalElement, movedElement); - } - } - - String[] fShowInTargetIds = new String[]{IPageLayout.ID_RES_NAV}; - private IShowInTargetList fShowInTargetListAdapter = new ShowInTargetLister(); - - IDocumentProvider fStorageInputDocumentProvider = null; - - public DebugTextEditor() { - super(); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.editors.text.TextEditor#createActions() - */ - protected void createActions() { - super.createActions(); - - // StructuredTextEditor Action - toggle breakpoints - IAction action = new ToggleBreakpointAction(this, getVerticalRuler()) { - protected String getContentType(IDocument document) { - ILocationProvider provider = (ILocationProvider) getEditorInput().getAdapter(ILocationProvider.class); - if (provider != null) { - IPath location = provider.getPath(getEditorInput()); - return detectContentType(location).getId(); - } - else if (getEditorInput() instanceof IPathEditorInput) { - IPath location = ((IPathEditorInput) getEditorInput()).getPath(); - return detectContentType(location).getId(); - } - return IContentTypeManager.CT_TEXT; - } - }; - setAction(ActionDefinitionIds.TOGGLE_BREAKPOINTS, action); - // StructuredTextEditor Action - manage breakpoints - action = new ManageBreakpointAction(this, getVerticalRuler()); - setAction(ActionDefinitionIds.MANAGE_BREAKPOINTS, action); - // StructuredTextEditor Action - edit breakpoints - action = new EditBreakpointAction(this, getVerticalRuler()); - setAction(ActionDefinitionIds.EDIT_BREAKPOINTS, action); - } - - /** - * Loads the Show In Target IDs from the Extended Configuration extension - * point. - * - * @return - */ - protected String[] createShowInTargetIds() { - List allIds = new ArrayList(0); - ExtendedConfigurationBuilder builder = ExtendedConfigurationBuilder.getInstance(); - String[] configurationIds = getConfigurationPoints(); - for (int i = 0; i < configurationIds.length; i++) { - String[] definitions = builder.getDefinitions("showintarget", configurationIds[i]); //$NON-NLS-1$ - for (int j = 0; j < definitions.length; j++) { - String someIds = definitions[j]; - if (someIds != null && someIds.length() > 0) { - String[] ids = StringUtils.unpack(someIds); - for (int k = 0; k < ids.length; k++) { - // trim, just to keep things clean - String id = ids[k].trim(); - if (!allIds.contains(id)) { - allIds.add(id); - } - } - } - } - } - - if (!allIds.contains(IPageLayout.ID_RES_NAV)) { - allIds.add(IPageLayout.ID_RES_NAV); - } - return (String[]) allIds.toArray(new String[0]); - } - - IContentType detectContentType(IPath location) { - IContentType type = null; - - IResource resource = FileBuffers.getWorkspaceFileAtLocation(location); - if (resource != null) { - if (resource.getType() == IResource.FILE && resource.isAccessible()) { - IContentDescription d = null; - try { - // Optimized description lookup, might not succeed - d = ((IFile) resource).getContentDescription(); - if (d != null) { - type = d.getContentType(); - } - } - catch (CoreException e) { - // Should not be possible given the accessible and file - // type check above - } - if (type == null) { - type = Platform.getContentTypeManager().findContentTypeFor(resource.getName()); - } - } - } - else { - File file = FileBuffers.getSystemFileAtLocation(location); - if (file != null) { - InputStream input = null; - try { - input = new FileInputStream(file); - type = Platform.getContentTypeManager().findContentTypeFor(input, location.toOSString()); - } - catch (FileNotFoundException e) { - } - catch (IOException e) { - } - finally { - if (input != null) { - try { - input.close(); - } - catch (IOException e1) { - } - } - } - if (type == null) { - type = Platform.getContentTypeManager().findContentTypeFor(file.getName()); - } - } - } - if (type == null) { - type = Platform.getContentTypeManager().getContentType(IContentTypeManager.CT_TEXT); - } - return type; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.AbstractTextEditor#editorContextMenuAboutToShow(org.eclipse.jface.action.IMenuManager) - */ - protected void editorContextMenuAboutToShow(IMenuManager menu) { - super.editorContextMenuAboutToShow(menu); - - IEditorActionBarContributor c = getEditorSite().getActionBarContributor(); - if (c instanceof IPopupMenuContributor) { - ((IPopupMenuContributor) c).contributeToPopupMenu(menu); - } - else { - ExtendedEditorActionBuilder builder = new ExtendedEditorActionBuilder(); - IExtendedContributor pmc = builder.readActionExtensions(getConfigurationPoints()); - if (pmc != null) { - pmc.setActiveEditor(this); - pmc.contributeToPopupMenu(menu); - } - } - } - - /** - * @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class) - */ - public Object getAdapter(Class required) { - // Navigate action set menu - if (IShowInTargetList.class.equals(required)) - return fShowInTargetListAdapter; - return super.getAdapter(required); - } - - - protected String[] getConfigurationPoints() { - return ConfigurationPointCalculator.getConfigurationPoints(this, getInputContentType(getEditorInput()), ConfigurationPointCalculator.SOURCE, DebugTextEditor.class); - } - - IContentType[] getEditorInputContentTypes(IEditorInput input) { - IContentType[] types = null; - IResource resource = null; - - if (input.getAdapter(IFile.class) != null) { - resource = (IFile) input.getAdapter(IFile.class); - } - else if (input.getAdapter(IFile.class) != null) { - resource = (IResource) input.getAdapter(IResource.class); - } - if (resource.getType() == IResource.FILE && resource.isAccessible()) { - IContentDescription d = null; - try { - // optimized description lookup, might not succeed - d = ((IFile) resource).getContentDescription(); - if (d != null) { - types = new IContentType[]{d.getContentType()}; - } - } - catch (CoreException e) { - // should not be possible given the accessible and file type - // check above - } - } - if (types == null) { - types = Platform.getContentTypeManager().findContentTypesFor(input.getName()); - } - return types; - } - - /** - * @param editorInput - * @return - */ - private String getInputContentType(IEditorInput editorInput) { - IContentType[] types = getEditorInputContentTypes(editorInput); - if (types != null) { - return types[0].getId(); - } - return null; - } - - /** - * - * @return - */ - private boolean isDebuggingAvailable() { - boolean debuggingAvailable = false; - IContentType[] types = getEditorInputContentTypes(getEditorInput()); - for (int i = 0; !debuggingAvailable && i < types.length; i++) { - debuggingAvailable = debuggingAvailable || BreakpointProviderBuilder.getInstance().isAvailable(types[i].getId(), BreakpointRulerAction.getFileExtension(getEditorInput())); - } - return debuggingAvailable; - } - - protected void rulerContextMenuAboutToShow(IMenuManager menu) { - if (isDebuggingAvailable()) { - menu.add(getAction(ActionDefinitionIds.TOGGLE_BREAKPOINTS)); - menu.add(getAction(ActionDefinitionIds.MANAGE_BREAKPOINTS)); - menu.add(getAction(ActionDefinitionIds.EDIT_BREAKPOINTS)); - menu.add(new Separator()); - } - else { - Logger.log(Logger.INFO, getClass().getName() + " could not enable debugging actions"); //$NON-NLS-1$ - } - super.rulerContextMenuAboutToShow(menu); - } - - /** - * Ensure that the correct IDocumentProvider is used. For IFile and Files, - * the default provider with a specified AnnotationModelFactory is used. - * For StorageEditorInputs, use a custom provider that creates a usable - * ResourceAnnotationModel - * - * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#setDocumentProvider(org.eclipse.ui.IEditorInput) - */ - protected void setDocumentProvider(IEditorInput input) { - if (input instanceof IStorageEditorInput && !(input instanceof IFileEditorInput)) { - if (fStorageInputDocumentProvider == null) { - fStorageInputDocumentProvider = new StorageInputDocumentProvider(); - } - setDocumentProvider(fStorageInputDocumentProvider); - } - else { - super.setDocumentProvider(input); - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.AbstractTextEditor#updateContentDependentActions() - */ - protected void updateContentDependentActions() { - super.updateContentDependentActions(); - if (isDebuggingAvailable()) { - setAction(ITextEditorActionConstants.RULER_DOUBLE_CLICK, getAction(ActionDefinitionIds.TOGGLE_BREAKPOINTS)); - } - else { - // The Default Text Editor uses editorContribution to perform this - // mapping, but since it relies on the IEditorSite ID, it can't be - // relied on for MultiPageEditorParts. Instead, force the action - // registration manually. - setAction(ITextEditorActionConstants.RULER_DOUBLE_CLICK, new MarkerRulerAction(SSEUIMessages.getResourceBundle(), "Editor.ManageBookmarks.", this, getVerticalRuler(), IMarker.BOOKMARK, true)); //$NON-NLS-1$ - } - fShowInTargetIds = createShowInTargetIds(); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/debug/EditBreakpointAction.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/debug/EditBreakpointAction.java deleted file mode 100644 index 15b988d3dd..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/debug/EditBreakpointAction.java +++ /dev/null @@ -1,63 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.debug; - -import org.eclipse.debug.core.model.IBreakpoint; -import org.eclipse.jface.text.source.IVerticalRuler; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.ISelectionChangedListener; -import org.eclipse.jface.viewers.ISelectionProvider; -import org.eclipse.jface.viewers.StructuredSelection; -import org.eclipse.ui.dialogs.PropertyDialogAction; -import org.eclipse.ui.texteditor.ITextEditor; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; - -public class EditBreakpointAction extends BreakpointRulerAction { - protected IBreakpoint[] breakpoints = null; - - /** - * @param editor - * @param rulerInfo - */ - public EditBreakpointAction(ITextEditor editor, IVerticalRuler rulerInfo) { - super(editor, rulerInfo); - setText(SSEUIMessages.EditBreakpointAction_0); //$NON-NLS-1$ - } - - public void run() { - PropertyDialogAction action = new PropertyDialogAction(getTextEditor().getEditorSite(), new ISelectionProvider() { - public void addSelectionChangedListener(ISelectionChangedListener listener) { - // do nothing - } - - public ISelection getSelection() { - return new StructuredSelection(breakpoints); - } - - public void removeSelectionChangedListener(ISelectionChangedListener listener) { - // do nothing - } - - public void setSelection(ISelection selection) { - // do nothing - } - }); - action.run(); - } - - public void update() { - boolean enableThisAction = hasMarkers(); - setEnabled(enableThisAction); - breakpoints = getBreakpoints(getMarkers()); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/debug/ManageBreakpointAction.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/debug/ManageBreakpointAction.java deleted file mode 100644 index 8d7ff2d262..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/debug/ManageBreakpointAction.java +++ /dev/null @@ -1,90 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.debug; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.debug.core.model.IBreakpoint; -import org.eclipse.jface.text.source.IVerticalRuler; -import org.eclipse.ui.texteditor.ITextEditor; -import org.eclipse.wst.sse.ui.internal.Logger; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; - -/** - * ManageBreakpointAction - Enables and Disables - */ -public class ManageBreakpointAction extends BreakpointRulerAction { - - protected IBreakpoint[] breakpoints = null; - private boolean doEnable = true; - - /** - * @param editor - * @param rulerInfo - */ - public ManageBreakpointAction(ITextEditor editor, IVerticalRuler rulerInfo) { - super(editor, rulerInfo); - setEnabled(true); - } - - /** - * - */ - protected void disableBreakpoints(IBreakpoint[] breakpoints) { - for (int i = 0; i < breakpoints.length; i++) { - try { - breakpoints[i].setEnabled(false); - } catch (CoreException e) { - Logger.logException(e); - } - } - } - - protected void enableBreakpoints(IBreakpoint[] breakpoints) { - for (int i = 0; i < breakpoints.length; i++) { - try { - breakpoints[i].setEnabled(true); - } catch (CoreException e) { - Logger.logException(e); - } - } - } - - public void run() { - if (doEnable) - enableBreakpoints(breakpoints); - else - disableBreakpoints(breakpoints); - } - - public void update() { - // doEnable means "enable" instead of "disable" - doEnable = true; - breakpoints = getBreakpoints(getMarkers()); - for (int i = 0; doEnable && i < breakpoints.length; i++) { - IBreakpoint breakpoint = breakpoints[i]; - try { - if (breakpoint.isEnabled()) { - doEnable = false; - } - } catch (CoreException e) { - Logger.logException("breakpoint not responding to isEnabled: " + breakpoint, e); //$NON-NLS-1$ - } - } - setEnabled(breakpoints != null && breakpoints.length > 0); - if (doEnable) - setText(SSEUIMessages.ManageBreakpointAction_0); //$NON-NLS-1$ - else - setText(SSEUIMessages.ManageBreakpointAction_1); //$NON-NLS-1$ - } - -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/debug/ToggleBreakpointAction.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/debug/ToggleBreakpointAction.java deleted file mode 100644 index 8cdb84fc5b..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/debug/ToggleBreakpointAction.java +++ /dev/null @@ -1,227 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.debug; - -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.MultiStatus; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.content.IContentType; -import org.eclipse.debug.core.DebugPlugin; -import org.eclipse.debug.core.IBreakpointManager; -import org.eclipse.debug.core.model.IBreakpoint; -import org.eclipse.debug.ui.DebugUITools; -import org.eclipse.debug.ui.IDebugUIConstants; -import org.eclipse.jface.action.IAction; -import org.eclipse.jface.dialogs.ErrorDialog; -import org.eclipse.jface.resource.ImageDescriptor; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.source.IVerticalRulerInfo; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.IEditorInput; -import org.eclipse.ui.ISelectionListener; -import org.eclipse.ui.texteditor.IDocumentProvider; -import org.eclipse.ui.texteditor.IDocumentProviderExtension4; -import org.eclipse.ui.texteditor.ITextEditor; -import org.eclipse.wst.sse.core.StructuredModelManager; -import org.eclipse.wst.sse.core.internal.provisional.IModelManager; -import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel; -import org.eclipse.wst.sse.core.internal.util.Debug; -import org.eclipse.wst.sse.ui.internal.Logger; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; -import org.eclipse.wst.sse.ui.internal.SSEUIPlugin; -import org.eclipse.wst.sse.ui.internal.extension.BreakpointProviderBuilder; -import org.eclipse.wst.sse.ui.internal.provisional.extensions.ISourceEditingTextTools; -import org.eclipse.wst.sse.ui.internal.provisional.extensions.breakpoint.IBreakpointProvider; - -/** - * ToggleBreakpointAction - */ -public class ToggleBreakpointAction extends BreakpointRulerAction { - IAction fFallbackAction; - - /** - * @param editor - * @param rulerInfo - */ - public ToggleBreakpointAction(ITextEditor editor, IVerticalRulerInfo rulerInfo) { - super(editor, rulerInfo); - setText(SSEUIMessages.ToggleBreakpointAction_0); //$NON-NLS-1$ - } - - public ToggleBreakpointAction(ITextEditor editor, IVerticalRulerInfo rulerInfo, IAction fallbackAction) { - this(editor, rulerInfo); - fFallbackAction = fallbackAction; - } - - protected boolean createBreakpoints(int lineNumber) { - /* - * Note: we'll always allow processing to continue, even for a "read - * only" IStorageEditorInput, for the ActiveScript debugger. But this - * means sometimes the ActiveScript provider might get an input from - * CVS or something that is not related to debugging. - */ - - ITextEditor editor = getTextEditor(); - IEditorInput input = editor.getEditorInput(); - IDocument document = editor.getDocumentProvider().getDocument(input); - if (document == null) - return false; - - String contentType = getContentType(document); - IBreakpointProvider[] providers = BreakpointProviderBuilder.getInstance().getBreakpointProviders(editor, contentType, getFileExtension(input)); - - int pos = -1; - ISourceEditingTextTools tools = (ISourceEditingTextTools) editor.getAdapter(ISourceEditingTextTools.class); - if (tools != null) { - pos = tools.getCaretOffset(); - } - - final int n = providers.length; - List errors = new ArrayList(0); - for (int i = 0; i < n; i++) { - try { - if (Debug.debugBreakpoints) - System.out.println(providers[i].getClass().getName() + " adding breakpoint to line " + lineNumber); //$NON-NLS-1$ - IStatus status = providers[i].addBreakpoint(document, input, lineNumber, pos); - if (status != null && !status.isOK()) { - errors.add(status); - } - } - catch (CoreException e) { - errors.add(e.getStatus()); - } - catch (Exception t) { - Logger.logException("exception while adding breakpoint", t); //$NON-NLS-1$ - } - } - - IStatus status = null; - if (errors.size() > 0) { - Shell shell = editor.getSite().getShell(); - if (errors.size() > 1) { - status = new MultiStatus(SSEUIPlugin.ID, IStatus.OK, (IStatus[]) errors.toArray(new IStatus[0]), SSEUIMessages.ManageBreakpoints_error_adding_message1, null); //$NON-NLS-1$ - } - else { - status = (IStatus) errors.get(0); - } - if ((status.getSeverity() > IStatus.INFO) || (Platform.inDebugMode() && !status.isOK())) { - Platform.getLog(SSEUIPlugin.getDefault().getBundle()).log(status); - } - /* - * Show for conditions more severe than INFO or when no - * breakpoints were created - */ - if (status.getSeverity() > IStatus.INFO && getBreakpoints(getMarkers()).length < 1) { - ErrorDialog.openError(shell, SSEUIMessages.ManageBreakpoints_error_adding_title1, status.getMessage(), status); //$NON-NLS-1$ //$NON-NLS-2$ - return false; - } - } - /* - * Although no errors were reported, no breakpoints exist on this line - * after having run the existing providers. Run the fallback action. - */ - if ((status == null || status.getSeverity() < IStatus.WARNING) && fFallbackAction != null && !hasMarkers()) { - if (fFallbackAction instanceof ISelectionListener) { - ((ISelectionListener) fFallbackAction).selectionChanged(null, null); - } - fFallbackAction.run(); - } - return true; - } - - protected String getContentType(IDocument document) { - IModelManager mgr = StructuredModelManager.getModelManager(); - String contentType = null; - - IDocumentProvider provider = fTextEditor.getDocumentProvider(); - if (provider instanceof IDocumentProviderExtension4) { - try { - IContentType type = ((IDocumentProviderExtension4) provider).getContentType(fTextEditor.getEditorInput()); - if (type != null) - contentType = type.getId(); - } - catch (CoreException e) { - /* - * A failure accessing the underlying store really isn't - * interesting, although it can be a problem for - * IStorageEditorInputs. - */ - } - } - - if (contentType == null) { - IStructuredModel model = null; - try { - model = mgr.getExistingModelForRead(document); - if (model != null) { - contentType = model.getContentTypeIdentifier(); - } - } - finally { - if (model != null) { - model.releaseFromRead(); - } - } - } - return contentType; - } - - protected void removeBreakpoints(int lineNumber) { - IBreakpointManager breakpointManager = DebugPlugin.getDefault().getBreakpointManager(); - IBreakpoint[] breakpoints = getBreakpoints(getMarkers()); - for (int i = 0; i < breakpoints.length; i++) { - try { - breakpointManager.removeBreakpoint(breakpoints[i], true); - } - catch (CoreException e) { - Logger.logException(e); - } - } - } - - public void run() { - int lineNumber = fRulerInfo.getLineOfLastMouseButtonActivity() + 1; - boolean doAdd = !hasMarkers(); - if (doAdd) - createBreakpoints(lineNumber); - else - removeBreakpoints(lineNumber); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.IUpdate#update() - */ - public void update() { - } - - /* - * (non-Javadoc) - * @see org.eclipse.jface.action.Action#getImageDescriptor() - * overriding for lazy loading - */ - public ImageDescriptor getImageDescriptor() { - - ImageDescriptor image = super.getImageDescriptor(); - if (image == null){ - image = DebugUITools.getImageDescriptor(IDebugUIConstants.IMG_OBJS_BREAKPOINT); - setImageDescriptor(image); - } - return image; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/debug/ToggleBreakpointsTarget.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/debug/ToggleBreakpointsTarget.java deleted file mode 100644 index 57c8c5ef72..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/debug/ToggleBreakpointsTarget.java +++ /dev/null @@ -1,189 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.debug; - -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.core.resources.IMarker; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.debug.core.DebugPlugin; -import org.eclipse.debug.core.IBreakpointManager; -import org.eclipse.debug.core.model.IBreakpoint; -import org.eclipse.debug.ui.actions.IToggleBreakpointsTarget; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.ITextSelection; -import org.eclipse.jface.text.Position; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.ui.IWorkbenchPart; -import org.eclipse.ui.texteditor.AbstractMarkerAnnotationModel; -import org.eclipse.ui.texteditor.ITextEditor; - -/** - * @author nsd - */ -public class ToggleBreakpointsTarget implements IToggleBreakpointsTarget { - static final IToggleBreakpointsTarget instance = new ToggleBreakpointsTarget(); - - public static IToggleBreakpointsTarget getInstance() { - return instance; - } - - /** - * - */ - private ToggleBreakpointsTarget() { - super(); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.debug.ui.actions.IToggleBreakpointsTarget#canToggleLineBreakpoints(org.eclipse.ui.IWorkbenchPart, - * org.eclipse.jface.viewers.ISelection) - */ - public boolean canToggleLineBreakpoints(IWorkbenchPart part, ISelection selection) { - ITextEditor editor = (ITextEditor) part.getAdapter(ITextEditor.class); - if (selection instanceof ITextSelection) { - ITextSelection textSelection = (ITextSelection) selection; - IDocument document = editor.getDocumentProvider().getDocument(editor.getEditorInput()); - if (document != null && textSelection.getOffset() > -1) { - int lineNumber = -1; - try { - lineNumber = document.getLineOfOffset(textSelection.getOffset()); - } - catch (BadLocationException e) { - } - if (lineNumber >= 0) { - ToggleBreakpointAction toggler = new ToggleBreakpointAction(editor, null); - toggler.update(); - return toggler.isEnabled(); - } - } - } - return false; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.debug.ui.actions.IToggleBreakpointsTarget#canToggleMethodBreakpoints(org.eclipse.ui.IWorkbenchPart, - * org.eclipse.jface.viewers.ISelection) - */ - public boolean canToggleMethodBreakpoints(IWorkbenchPart part, ISelection selection) { - return false; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.debug.ui.actions.IToggleBreakpointsTarget#canToggleWatchpoints(org.eclipse.ui.IWorkbenchPart, - * org.eclipse.jface.viewers.ISelection) - */ - public boolean canToggleWatchpoints(IWorkbenchPart part, ISelection selection) { - return false; - } - - private IBreakpoint[] getBreakpoints(IResource resource, IDocument document, AbstractMarkerAnnotationModel model, int lineNumber) { - List markers = new ArrayList(); - if (resource != null && model != null && resource.exists()) { - try { - IMarker[] allMarkers = resource.findMarkers(IBreakpoint.LINE_BREAKPOINT_MARKER, true, IResource.DEPTH_ZERO); - if (allMarkers != null) { - for (int i = 0; i < allMarkers.length; i++) { - Position p = model.getMarkerPosition(allMarkers[i]); - int markerLine = -1; - try { - markerLine = document.getLineOfOffset(p.getOffset()); - } - catch (BadLocationException e1) { - } - if (markerLine == lineNumber) { - markers.add(allMarkers[i]); - } - } - } - } - catch (CoreException x) { - } - } - IBreakpointManager manager = DebugPlugin.getDefault().getBreakpointManager(); - List breakpoints = new ArrayList(markers.size()); - for (int i = 0; i < markers.size(); i++) { - IBreakpoint breakpoint = manager.getBreakpoint((IMarker) markers.get(i)); - if (breakpoint != null) { - breakpoints.add(breakpoint); - } - } - return (IBreakpoint[]) breakpoints.toArray(new IBreakpoint[0]); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.debug.ui.actions.IToggleBreakpointsTarget#toggleLineBreakpoints(org.eclipse.ui.IWorkbenchPart, - * org.eclipse.jface.viewers.ISelection) - */ - public void toggleLineBreakpoints(IWorkbenchPart part, ISelection selection) throws CoreException { - ITextEditor editor = (ITextEditor) part.getAdapter(ITextEditor.class); - if (selection instanceof ITextSelection) { - ITextSelection textSelection = (ITextSelection) selection; - IDocument document = editor.getDocumentProvider().getDocument(editor.getEditorInput()); - int lineNumber = -1; - try { - lineNumber = document.getLineOfOffset(textSelection.getOffset()); - } - catch (BadLocationException e) { - } - if (lineNumber >= 0) { - ToggleBreakpointAction toggler = new ToggleBreakpointAction(editor, null); - toggler.update(); - if (toggler.isEnabled()) { - IResource resource = toggler.getResource(); - AbstractMarkerAnnotationModel model = toggler.getAnnotationModel(); - IBreakpoint[] breakpoints = getBreakpoints(resource, document, model, lineNumber); - if (breakpoints.length > 0) { - IBreakpointManager breakpointManager = DebugPlugin.getDefault().getBreakpointManager(); - for (int i = 0; i < breakpoints.length; i++) { - breakpoints[i].getMarker().delete(); - breakpointManager.removeBreakpoint(breakpoints[i], true); - } - } - else { - toggler.createBreakpoints(lineNumber + 1); - } - } - } - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.debug.ui.actions.IToggleBreakpointsTarget#toggleMethodBreakpoints(org.eclipse.ui.IWorkbenchPart, - * org.eclipse.jface.viewers.ISelection) - */ - public void toggleMethodBreakpoints(IWorkbenchPart part, ISelection selection) throws CoreException { - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.debug.ui.actions.IToggleBreakpointsTarget#toggleWatchpoints(org.eclipse.ui.IWorkbenchPart, - * org.eclipse.jface.viewers.ISelection) - */ - public void toggleWatchpoints(IWorkbenchPart part, ISelection selection) throws CoreException { - } - -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/derived/HTML2TextReader.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/derived/HTML2TextReader.java deleted file mode 100644 index 434c37c8e6..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/derived/HTML2TextReader.java +++ /dev/null @@ -1,343 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ - -package org.eclipse.wst.sse.ui.internal.derived; - -import java.io.IOException; -import java.io.PushbackReader; -import java.io.Reader; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import org.eclipse.jface.text.TextPresentation; -import org.eclipse.swt.SWT; -import org.eclipse.swt.custom.StyleRange; - -/* - * Copied from org.eclipse.jdt.internal.ui.text.HTML2TextReader Modifications - * were made to add br/ tag and fix warnings - */ -/** - * Reads the text contents from a reader of HTML contents and translates the - * tags or cut them out. - */ -public class HTML2TextReader extends SubstitutionTextReader { - - private static final String EMPTY_STRING= ""; //$NON-NLS-1$ - private static final Map fgEntityLookup; - private static final Set fgTags; - - static { - - fgTags= new HashSet(); - fgTags.add("b"); //$NON-NLS-1$ - fgTags.add("br"); //$NON-NLS-1$ - fgTags.add("br/");//$NON-NLS-1$ - fgTags.add("h1"); //$NON-NLS-1$ - fgTags.add("h2"); //$NON-NLS-1$ - fgTags.add("h3"); //$NON-NLS-1$ - fgTags.add("h4"); //$NON-NLS-1$ - fgTags.add("h5"); //$NON-NLS-1$ - fgTags.add("h6"); //$NON-NLS-1$ - fgTags.add("hr"); //$NON-NLS-1$ - fgTags.add("p"); //$NON-NLS-1$ - fgTags.add("dl"); //$NON-NLS-1$ - fgTags.add("dt"); //$NON-NLS-1$ - fgTags.add("dd"); //$NON-NLS-1$ - fgTags.add("li"); //$NON-NLS-1$ - fgTags.add("ul"); //$NON-NLS-1$ - fgTags.add("pre"); //$NON-NLS-1$ - fgTags.add("html"); //$NON-NLS-1$ - fgTags.add("head"); //$NON-NLS-1$ - fgTags.add("body"); //$NON-NLS-1$ - fgTags.add("code"); //$NON-NLS-1$ - fgTags.add("font"); //$NON-NLS-1$ - fgTags.add("blockquote"); //$NON-NLS-1$ - fgTags.add("a"); //$NON-NLS-1$ - fgTags.add("tt"); //$NON-NLS-1$ - fgTags.add("tl"); //$NON-NLS-1$ - fgTags.add("em"); //$NON-NLS-1$ - fgTags.add("i"); //$NON-NLS-1$ - - fgEntityLookup= new HashMap(7); - fgEntityLookup.put("lt", "<"); //$NON-NLS-1$ //$NON-NLS-2$ - fgEntityLookup.put("gt", ">"); //$NON-NLS-1$ //$NON-NLS-2$ - fgEntityLookup.put("nbsp", " "); //$NON-NLS-1$ //$NON-NLS-2$ - fgEntityLookup.put("amp", "&"); //$NON-NLS-1$ //$NON-NLS-2$ - fgEntityLookup.put("circ", "^"); //$NON-NLS-1$ //$NON-NLS-2$ - fgEntityLookup.put("tilde", "~"); //$NON-NLS-2$ //$NON-NLS-1$ - fgEntityLookup.put("quot", "\""); //$NON-NLS-1$ //$NON-NLS-2$ - } - - private int fCounter= 0; - private TextPresentation fTextPresentation; - private int fBold= 0; - private int fStartOffset= -1; - private boolean fInParagraph= false; - private boolean fIsPreformattedText= false; - private boolean fIgnore= false; - private boolean fHeaderDetected= false; - - /** - * Transforms the html text from the reader to formatted text. - * @param presentation If not <code>null</code>, formattings will be applied to - * the presentation. - */ - public HTML2TextReader(Reader reader, TextPresentation presentation) { - super(new PushbackReader(reader)); - fTextPresentation= presentation; - } - - public int read() throws IOException { - int c= super.read(); - if (c != -1) - ++ fCounter; - return c; - } - - protected void startBold() { - if (fBold == 0) - fStartOffset= fCounter; - ++ fBold; - } - - protected void startPreformattedText() { - fIsPreformattedText= true; - setSkipWhitespace(false); - } - - protected void stopPreformattedText() { - fIsPreformattedText= false; - setSkipWhitespace(true); - } - - protected void stopBold() { - -- fBold; - if (fBold == 0) { - if (fTextPresentation != null) { - fTextPresentation.addStyleRange(new StyleRange(fStartOffset, fCounter - fStartOffset, null, null, SWT.BOLD)); - } - fStartOffset= -1; - } - } - - /* - * @see org.eclipse.jdt.internal.ui.text.SubstitutionTextReader#computeSubstitution(int) - */ - protected String computeSubstitution(int c) throws IOException { - - if (c == '<') - return processHTMLTag(); - else if (fIgnore) - return EMPTY_STRING; - else if (c == '&') - return processEntity(); - else if (fIsPreformattedText) - return processPreformattedText(c); - - return null; - } - - private String html2Text(String html) { - - if (html == null || html.length() == 0) - return EMPTY_STRING; - - String tag= html; - if ('/' == tag.charAt(0)) - tag= tag.substring(1); - - final int ws = tag.indexOf(' '); - if (ws > 0) { - tag = tag.substring(0, ws); - } - - if ("head".equals(html) && !fHeaderDetected) { //$NON-NLS-1$ - fHeaderDetected= true; - fIgnore= true; - return EMPTY_STRING; - } - - if ("/head".equals(html) && fHeaderDetected && fIgnore) { //$NON-NLS-1$ - fIgnore= false; - return EMPTY_STRING; - } - - if (fIgnore) - return EMPTY_STRING; - - if (!fgTags.contains(tag)) - return '<' + html + '>'; - - if ("pre".equals(html)) { //$NON-NLS-1$ - startPreformattedText(); - return EMPTY_STRING; - } - - if ("/pre".equals(html)) { //$NON-NLS-1$ - stopPreformattedText(); - return EMPTY_STRING; - } - - if (fIsPreformattedText) - return EMPTY_STRING; - - if ("b".equals(html)) { //$NON-NLS-1$ - startBold(); - return EMPTY_STRING; - } - - if ("h5".equals(html) || "dt".equals(html)) { //$NON-NLS-1$ //$NON-NLS-2$ - startBold(); - return EMPTY_STRING; - } - - if ("dl".equals(html)) //$NON-NLS-1$ - return LINE_DELIM; - - if ("dd".equals(html)) //$NON-NLS-1$ - return "\t"; //$NON-NLS-1$ - - if ("li".equals(html)) //$NON-NLS-1$ - return LINE_DELIM + "\t" + "- "; //$NON-NLS-1$ //$NON-NLS-2$ - - if ("/b".equals(html)) { //$NON-NLS-1$ - stopBold(); - return EMPTY_STRING; - } - - if ("p".equals(html)) { //$NON-NLS-1$ - fInParagraph= true; - return LINE_DELIM; - } - - if ("br".equals(html) || "br/".equals(html)) //$NON-NLS-1$ //$NON-NLS-2$ - return LINE_DELIM; - - if ("/p".equals(html)) { //$NON-NLS-1$ - boolean inParagraph= fInParagraph; - fInParagraph= false; - return inParagraph ? EMPTY_STRING : LINE_DELIM; - } - - if ("/h5".equals(html) || "/dt".equals(html)) { //$NON-NLS-1$ //$NON-NLS-2$ - stopBold(); - return LINE_DELIM; - } - - if ("/dd".equals(html)) //$NON-NLS-1$ - return LINE_DELIM; - - return EMPTY_STRING; - } - - /* - * A '<' has been read. Process a html tag - */ - private String processHTMLTag() throws IOException { - - StringBuffer buf= new StringBuffer(); - int ch; - do { - - ch= nextChar(); - - while (ch != -1 && ch != '>') { - buf.append(Character.toLowerCase((char) ch)); - ch= nextChar(); - if (ch == '"'){ - buf.append(Character.toLowerCase((char) ch)); - ch= nextChar(); - while (ch != -1 && ch != '"'){ - buf.append(Character.toLowerCase((char) ch)); - ch= nextChar(); - } - } - if (ch == '<'){ - unread(ch); - return '<' + buf.toString(); - } - } - - if (ch == -1) - return null; - - int tagLen= buf.length(); - // needs special treatment for comments - if ((tagLen >= 3 && "!--".equals(buf.substring(0, 3))) //$NON-NLS-1$ - && !(tagLen >= 5 && "--".equals(buf.substring(tagLen - 2)))) { //$NON-NLS-1$ - // unfinished comment - buf.append(ch); - } else { - break; - } - } while (true); - - return html2Text(buf.toString()); - } - - private String processPreformattedText(int c) { - if (c == '\r' || c == '\n') - fCounter++; - return null; - } - - - private void unread(int ch) throws IOException { - ((PushbackReader) getReader()).unread(ch); - } - - protected String entity2Text(String symbol) { - if (symbol.length() > 1 && symbol.charAt(0) == '#') { - int ch; - try { - if (symbol.charAt(1) == 'x') { - ch= Integer.parseInt(symbol.substring(2), 16); - } else { - ch= Integer.parseInt(symbol.substring(1), 10); - } - return EMPTY_STRING + (char)ch; - } catch (NumberFormatException e) { - // log problem? - } - } else { - String str= (String) fgEntityLookup.get(symbol); - if (str != null) { - return str; - } - } - return "&" + symbol; // not found //$NON-NLS-1$ - } - - /* - * A '&' has been read. Process a entity - */ - private String processEntity() throws IOException { - StringBuffer buf= new StringBuffer(); - int ch= nextChar(); - while (Character.isLetterOrDigit((char)ch) || ch == '#') { - buf.append((char) ch); - ch= nextChar(); - } - - if (ch == ';') - return entity2Text(buf.toString()); - - buf.insert(0, '&'); - if (ch != -1) - buf.append((char) ch); - return buf.toString(); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/derived/HTMLTextPresenter.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/derived/HTMLTextPresenter.java deleted file mode 100644 index d56b2d58a3..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/derived/HTMLTextPresenter.java +++ /dev/null @@ -1,205 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.derived; - -import java.io.IOException; -import java.io.Reader; -import java.io.StringReader; -import java.util.Iterator; - -import org.eclipse.jface.text.DefaultInformationControl; -import org.eclipse.jface.text.Region; -import org.eclipse.jface.text.TextPresentation; -import org.eclipse.swt.custom.StyleRange; -import org.eclipse.swt.graphics.Drawable; -import org.eclipse.swt.graphics.GC; -import org.eclipse.swt.widgets.Display; -import org.eclipse.wst.sse.ui.internal.Logger; - -/* - * Copied from org.eclipse.jdt.internal.ui.text.HTMLTextPresenter - * Modifications were made to use own Logger to log exception, and the - * ellipses constant - */ -public class HTMLTextPresenter implements DefaultInformationControl.IInformationPresenter, DefaultInformationControl.IInformationPresenterExtension { - private static final String ELLIPSES = "..."; //$NON-NLS-1$ - private static final String LINE_DELIM = System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ - - private int fCounter; - private boolean fEnforceUpperLineLimit; - - public HTMLTextPresenter(boolean enforceUpperLineLimit) { - super(); - fEnforceUpperLineLimit = enforceUpperLineLimit; - } - - public HTMLTextPresenter() { - this(true); - } - - protected Reader createReader(String hoverInfo, TextPresentation presentation) { - return new HTML2TextReader(new StringReader(hoverInfo), presentation); - } - - protected void adaptTextPresentation(TextPresentation presentation, int offset, int insertLength) { - - int yoursStart = offset; - int yoursEnd = offset + insertLength - 1; - yoursEnd = Math.max(yoursStart, yoursEnd); - - Iterator e = presentation.getAllStyleRangeIterator(); - while (e.hasNext()) { - - StyleRange range = (StyleRange) e.next(); - - int myStart = range.start; - int myEnd = range.start + range.length - 1; - myEnd = Math.max(myStart, myEnd); - - if (myEnd < yoursStart) - continue; - - if (myStart < yoursStart) - range.length += insertLength; - else - range.start += insertLength; - } - } - - private void append(StringBuffer buffer, String string, TextPresentation presentation) { - - int length = string.length(); - buffer.append(string); - - if (presentation != null) - adaptTextPresentation(presentation, fCounter, length); - - fCounter += length; - } - - private String getIndent(String line) { - int length = line.length(); - - int i = 0; - while (i < length && Character.isWhitespace(line.charAt(i))) - ++i; - - return (i == length ? line : line.substring(0, i)) + " "; //$NON-NLS-1$ - } - - /** - * @see IHoverInformationPresenter#updatePresentation(Display display, - * String, TextPresentation, int, int) - * @deprecated Use {@link #updatePresentation(Drawable, String, TextPresentation, int, int)} - * instead - */ - public String updatePresentation(Display display, String hoverInfo, TextPresentation presentation, int maxWidth, int maxHeight) { - return updatePresentation((Drawable)display, hoverInfo, presentation, maxWidth, maxHeight); - } - - /* - * @see IHoverInformationPresenterExtension#updatePresentation(Drawable drawable, String, TextPresentation, int, int) - * @since 3.2 - */ - public String updatePresentation(Drawable drawable, String hoverInfo, TextPresentation presentation, int maxWidth, int maxHeight) { - - if (hoverInfo == null) - return null; - - GC gc = new GC(drawable); - try { - - StringBuffer buffer = new StringBuffer(); - int maxNumberOfLines = Math.round(maxHeight / gc.getFontMetrics().getHeight()); - - fCounter = 0; - LineBreakingReader reader = new LineBreakingReader(createReader(hoverInfo, presentation), gc, maxWidth); - - boolean lastLineFormatted = false; - String lastLineIndent = null; - - String line = reader.readLine(); - boolean lineFormatted = reader.isFormattedLine(); - boolean firstLineProcessed = false; - - while (line != null) { - - if (fEnforceUpperLineLimit && maxNumberOfLines <= 0) - break; - - if (firstLineProcessed) { - if (!lastLineFormatted) - append(buffer, LINE_DELIM, null); - else { - append(buffer, LINE_DELIM, presentation); - if (lastLineIndent != null) - append(buffer, lastLineIndent, presentation); - } - } - - append(buffer, line, null); - firstLineProcessed = true; - - lastLineFormatted = lineFormatted; - if (!lineFormatted) - lastLineIndent = null; - else if (lastLineIndent == null) - lastLineIndent = getIndent(line); - - line = reader.readLine(); - lineFormatted = reader.isFormattedLine(); - - maxNumberOfLines--; - } - - if (line != null && buffer.length() > 0) { - append(buffer, LINE_DELIM, lineFormatted ? presentation : null); - append(buffer, ELLIPSES, presentation); - } - - return trim(buffer, presentation); - - } catch (IOException e) { - Logger.log(Logger.WARNING_DEBUG, e.getMessage(), e); - return null; - - } finally { - gc.dispose(); - } - } - - private String trim(StringBuffer buffer, TextPresentation presentation) { - - int length = buffer.length(); - - int end = length - 1; - while (end >= 0 && Character.isWhitespace(buffer.charAt(end))) - --end; - - if (end == -1) - return ""; //$NON-NLS-1$ - - if (end < length - 1) - buffer.delete(end + 1, length); - else - end = length; - - int start = 0; - while (start < end && Character.isWhitespace(buffer.charAt(start))) - ++start; - - buffer.delete(0, start); - presentation.setResultWindow(new Region(start, buffer.length())); - return buffer.toString(); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/derived/LineBreakingReader.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/derived/LineBreakingReader.java deleted file mode 100644 index cea5449f96..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/derived/LineBreakingReader.java +++ /dev/null @@ -1,124 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2006 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.derived; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.Reader; -import com.ibm.icu.text.BreakIterator; - -import org.eclipse.swt.graphics.GC; - -/** - * Copied from org.eclipse.jdt.internal.ui.text.LineBreakingReader. - * Modifications were made to fix warnings. - */ -/* - * Not a real reader. Could change if requested - */ -public class LineBreakingReader { - private GC fGC; - - private String fLine; - - private BreakIterator fLineBreakIterator; - private int fMaxWidth; - private int fOffset; - - - private BufferedReader fReader; - - /** - * Creates a reader that breaks an input text to fit in a given width. - * - * @param reader - * Reader of the input text - * @param gc - * The graphic context that defines the currently used font - * sizes - * @param maxLineWidth - * The max width (pixes) where the text has to fit in - */ - public LineBreakingReader(Reader reader, GC gc, int maxLineWidth) { - fReader = new BufferedReader(reader); - fGC = gc; - fMaxWidth = maxLineWidth; - fOffset = 0; - fLine = null; - fLineBreakIterator = BreakIterator.getLineInstance(); - } - - private int findNextBreakOffset(int currOffset) { - int currWidth = 0; - int nextOffset = fLineBreakIterator.following(currOffset); - while (nextOffset != BreakIterator.DONE) { - String word = fLine.substring(currOffset, nextOffset); - int wordWidth = fGC.textExtent(word).x; - int nextWidth = wordWidth + currWidth; - if (nextWidth > fMaxWidth) { - if (currWidth > 0) { - return currOffset; - } - return nextOffset; - } - currWidth = nextWidth; - currOffset = nextOffset; - nextOffset = fLineBreakIterator.next(); - } - return nextOffset; - } - - private int findWordBegin(int idx) { - while (idx < fLine.length() && Character.isWhitespace(fLine.charAt(idx))) { - idx++; - } - return idx; - } - - public boolean isFormattedLine() { - return fLine != null; - } - - /** - * Reads the next line. The lengths of the line will not exceed the gived - * maximum width. - */ - public String readLine() throws IOException { - if (fLine == null) { - String line = fReader.readLine(); - if (line == null) - return null; - - int lineLen = fGC.textExtent(line).x; - if (lineLen < fMaxWidth) { - return line; - } - fLine = line; - fLineBreakIterator.setText(line); - fOffset = 0; - } - int breakOffset = findNextBreakOffset(fOffset); - String res; - if (breakOffset != BreakIterator.DONE) { - res = fLine.substring(fOffset, breakOffset); - fOffset = findWordBegin(breakOffset); - if (fOffset == fLine.length()) { - fLine = null; - } - } else { - res = fLine.substring(fOffset); - fLine = null; - } - return res; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/derived/SingleCharReader.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/derived/SingleCharReader.java deleted file mode 100644 index 56945ff660..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/derived/SingleCharReader.java +++ /dev/null @@ -1,66 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2006 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.derived; - -import java.io.IOException; -import java.io.Reader; - -/* - * Copied from org.eclipse.jdt.internal.corext.javadoc.SingleCharReader. - * Modification was made to fix statement unnecessarily nested within else - * clause warning in read(..). - */ -public abstract class SingleCharReader extends Reader { - - /** - * @see Reader#read() - */ - public abstract int read() throws IOException; - - /** - * @see Reader#read(char[],int,int) - */ - public int read(char cbuf[], int off, int len) throws IOException { - int end = off + len; - for (int i = off; i < end; i++) { - int ch = read(); - if (ch == -1) { - if (i == off) { - return -1; - } - return i - off; - } - cbuf[i] = (char) ch; - } - return len; - } - - /** - * @see Reader#ready() - */ - public boolean ready() throws IOException { - return true; - } - - /** - * Gets the content as a String - */ - public String getString() throws IOException { - StringBuffer buf = new StringBuffer(); - int ch; - while ((ch = read()) != -1) { - buf.append((char) ch); - } - return buf.toString(); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/derived/SubstitutionTextReader.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/derived/SubstitutionTextReader.java deleted file mode 100644 index 4d2a78f252..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/derived/SubstitutionTextReader.java +++ /dev/null @@ -1,158 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2006 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.derived; - -import java.io.IOException; -import java.io.Reader; - -/* - * Copied from org.eclipse.jdt.internal.ui.text.SubstitutionTextReader. - * Modifications were made to read() to allow whitespaces and fixed statement - * unnecessarily nested within else clause warning in nextChar() - */ -/** - * Reads the text contents from a reader and computes for each character a - * potential substitution. The substitution may eat more characters than only - * the one passed into the computation routine. - */ -public abstract class SubstitutionTextReader extends SingleCharReader { - - protected static final String LINE_DELIM = System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ - - private Reader fReader; - protected boolean fWasWhiteSpace; - private int fCharAfterWhiteSpace; - - /** - * Tells whether white space characters are skipped. - */ - private boolean fSkipWhiteSpace = true; - - private boolean fReadFromBuffer; - private StringBuffer fBuffer; - private int fIndex; - - - protected SubstitutionTextReader(Reader reader) { - fReader = reader; - fBuffer = new StringBuffer(); - fIndex = 0; - fReadFromBuffer = false; - fCharAfterWhiteSpace = -1; - fWasWhiteSpace = true; - } - - /** - * Implement to compute the substitution for the given character and if - * necessary subsequent characters. Use <code>nextChar</code> to read - * subsequent characters. - */ - protected abstract String computeSubstitution(int c) throws IOException; - - /** - * Returns the internal reader. - */ - protected Reader getReader() { - return fReader; - } - - /** - * Returns the next character. - */ - protected int nextChar() throws IOException { - fReadFromBuffer = (fBuffer.length() > 0); - if (fReadFromBuffer) { - char ch = fBuffer.charAt(fIndex++); - if (fIndex >= fBuffer.length()) { - fBuffer.setLength(0); - fIndex = 0; - } - return ch; - } - int ch = fCharAfterWhiteSpace; - if (ch == -1) { - ch = fReader.read(); - } - if (fSkipWhiteSpace && Character.isWhitespace((char) ch)) { - do { - ch = fReader.read(); - } while (Character.isWhitespace((char) ch)); - if (ch != -1) { - fCharAfterWhiteSpace = ch; - return ' '; - } - } else { - fCharAfterWhiteSpace = -1; - } - return ch; - } - - /** - * @see Reader#read() - */ - public int read() throws IOException { - int c; - do { - - c = nextChar(); - while (!fReadFromBuffer) { - String s = computeSubstitution(c); - if (s == null) - break; - if (s.length() > 0) - fBuffer.insert(0, s); - c = nextChar(); - } - - } while (fSkipWhiteSpace && fWasWhiteSpace && ((c == ' ') && !fReadFromBuffer)); - /* - * SSE: For above and below check, if whitespace is read from buffer, - * do not skip - */ - fWasWhiteSpace = ((c == ' ' && !fReadFromBuffer) || c == '\r' || c == '\n'); - return c; - } - - /** - * @see Reader#ready() - */ - public boolean ready() throws IOException { - return fReader.ready(); - } - - /** - * @see Reader#close() - */ - public void close() throws IOException { - fReader.close(); - } - - /** - * @see Reader#reset() - */ - public void reset() throws IOException { - fReader.reset(); - fWasWhiteSpace = true; - fCharAfterWhiteSpace = -1; - fBuffer.setLength(0); - fIndex = 0; - } - - protected final void setSkipWhitespace(boolean state) { - fSkipWhiteSpace = state; - } - - protected final boolean isSkippingWhitespace() { - return fSkipWhiteSpace; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/edit/util/SharedEditorPluginImageHelper.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/edit/util/SharedEditorPluginImageHelper.java deleted file mode 100644 index 3a9b0c9448..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/edit/util/SharedEditorPluginImageHelper.java +++ /dev/null @@ -1,58 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.edit.util; - -import org.eclipse.jface.resource.ImageDescriptor; -import org.eclipse.swt.graphics.Image; -import org.eclipse.wst.sse.ui.internal.editor.EditorPluginImageHelper; -import org.eclipse.wst.sse.ui.internal.editor.EditorPluginImages; - - -public class SharedEditorPluginImageHelper { - public static final String IMG_DLCL_COLLAPSEALL = EditorPluginImages.IMG_DLCL_COLLAPSEALL; - public static final String IMG_DLCL_DELETE = EditorPluginImages.IMG_DLCL_DELETE; - public static final String IMG_DLCL_SYNCED = EditorPluginImages.IMG_DLCL_SYNCED; - public static final String IMG_ELCL_COLLAPSEALL = EditorPluginImages.IMG_ELCL_COLLAPSEALL; - public static final String IMG_ELCL_DELETE = EditorPluginImages.IMG_ELCL_DELETE; - public static final String IMG_ELCL_SYNCED = EditorPluginImages.IMG_ELCL_SYNCED; - - /** - * Retrieves the specified image from the source editor plugin's image - * registry. Note: The returned <code>Image</code> is managed by the - * workbench; clients must <b>not </b> dispose of the returned image. - * - * @param symbolicName - * the symbolic name of the image; there are constants declared - * in this class for build-in images that come with the source - * editor - * @return the image, or <code>null</code> if not found - */ - public static Image getImage(String symbolicName) { - return EditorPluginImageHelper.getInstance().getImage(symbolicName); - } - - /** - * Retrieves the image descriptor for specified image from the source - * editor plugin's image registry. Unlike <code>Image</code>s, image - * descriptors themselves do not need to be disposed. - * - * @param symbolicName - * the symbolic name of the image; there are constants declared - * in this interface for build-in images that come with the - * source editor - * @return the image descriptor, or <code>null</code> if not found - */ - public static ImageDescriptor getImageDescriptor(String symbolicName) { - return EditorPluginImageHelper.getInstance().getImageDescriptor(symbolicName); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/editor/EditorModelUtil.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/editor/EditorModelUtil.java deleted file mode 100644 index 93d620a3da..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/editor/EditorModelUtil.java +++ /dev/null @@ -1,80 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2006 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.editor; - -import java.util.Iterator; - -import org.eclipse.core.runtime.SafeRunner; -import org.eclipse.jface.util.SafeRunnable; -import org.eclipse.wst.sse.core.internal.model.FactoryRegistry; -import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel; -import org.eclipse.wst.sse.ui.internal.Logger; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; -import org.eclipse.wst.sse.ui.internal.SSEUIPlugin; -import org.eclipse.wst.sse.ui.internal.provisional.registry.AdapterFactoryProvider; -import org.eclipse.wst.sse.ui.internal.provisional.registry.AdapterFactoryRegistry; -import org.eclipse.wst.sse.ui.internal.provisional.registry.AdapterFactoryRegistryExtension; -import org.eclipse.wst.sse.ui.internal.util.Assert; - - -/** - * INTERNAL USAGE ONLY - * - * Adds adapter factories intended solely for use when the model is - * interacting with a UI. - * - * @author nsd - */ -public class EditorModelUtil { - - public static void addFactoriesTo(final IStructuredModel structuredModel) { - if (structuredModel == null) - return; - - AdapterFactoryRegistry adapterRegistry = SSEUIPlugin.getDefault().getAdapterFactoryRegistry(); - String contentTypeId = structuredModel.getContentTypeIdentifier(); - - Iterator adapterFactoryProviders = null; - if (adapterRegistry instanceof AdapterFactoryRegistryExtension) { - adapterFactoryProviders = ((AdapterFactoryRegistryExtension) adapterRegistry).getAdapterFactories(contentTypeId); - } - else { - adapterFactoryProviders = adapterRegistry.getAdapterFactories(); - } - - FactoryRegistry factoryRegistry = structuredModel.getFactoryRegistry(); - Assert.isNotNull(factoryRegistry, SSEUIMessages.EditorModelUtil_0); //$NON-NLS-1$ - // Add all those appropriate for this particular type of content - while (adapterFactoryProviders.hasNext()) { - try { - final AdapterFactoryProvider provider = (AdapterFactoryProvider) adapterFactoryProviders.next(); - /* - * ContentType might have already been checked above, this - * check is here for backwards compatability for those that - * don't specify a content type - */ - if (provider.isFor(structuredModel.getModelHandler())) { - SafeRunner.run(new SafeRunnable(SSEUIMessages.EditorModelUtil_1) { //$NON-NLS-1$ - public void run() { - provider.addAdapterFactories(structuredModel); - } - }); - } - } - catch (Exception e) { - Logger.logException(e); - } - } - } - -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/editor/EditorPluginImageHelper.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/editor/EditorPluginImageHelper.java deleted file mode 100644 index f78633f744..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/editor/EditorPluginImageHelper.java +++ /dev/null @@ -1,155 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.editor; - -import java.util.HashMap; - -import org.eclipse.jface.resource.ImageDescriptor; -import org.eclipse.jface.resource.ImageRegistry; -import org.eclipse.jface.resource.JFaceResources; -import org.eclipse.swt.graphics.Image; -import org.eclipse.ui.plugin.AbstractUIPlugin; -import org.eclipse.wst.sse.ui.internal.SSEUIPlugin; - - -/** - * Helper class to handle images provided by this plug-in. - * - * NOTE: For internal use only. For images used externally, please use the - * Shared***ImageHelper class instead. - * - * @author amywu - */ -public class EditorPluginImageHelper { - private static EditorPluginImageHelper instance = null; - - /** - * Gets the instance. - * - * @return Returns a EditorPluginImageHelper - */ - public synchronized static EditorPluginImageHelper getInstance() { - if (instance == null) - instance = new EditorPluginImageHelper(); - return instance; - } - - // save a descriptor for each image - private HashMap fImageDescRegistry = null; - private final String PLUGINID = SSEUIPlugin.ID; - - /** - * Creates an image from the given resource and adds the image to the - * image registry. - * - * @param resource - * @return Image - */ - private Image createImage(String resource) { - ImageDescriptor desc = getImageDescriptor(resource); - Image image = null; - - if (desc != null) { - image = desc.createImage(); - // dont add the missing image descriptor image to the image - // registry - if (!desc.equals(ImageDescriptor.getMissingImageDescriptor())) - getImageRegistry().put(resource, image); - } - return image; - } - - /** - * Creates an image descriptor from the given imageFilePath and adds the - * image descriptor to the image descriptor registry. If an image - * descriptor could not be created, the default "missing" image descriptor - * is returned but not added to the image descriptor registry. - * - * @param imageFilePath - * @return ImageDescriptor image descriptor for imageFilePath or default - * "missing" image descriptor if resource could not be found - */ - private ImageDescriptor createImageDescriptor(String imageFilePath) { - ImageDescriptor imageDescriptor = AbstractUIPlugin.imageDescriptorFromPlugin(PLUGINID, imageFilePath); - if (imageDescriptor != null) { - getImageDescriptorRegistry().put(imageFilePath, imageDescriptor); - } else { - imageDescriptor = ImageDescriptor.getMissingImageDescriptor(); - } - - return imageDescriptor; - } - - /** - * Retrieves the image associated with resource from the image registry. - * If the image cannot be retrieved, attempt to find and load the image at - * the location specified in resource. - * - * @param resource - * the image to retrieve - * @return Image the image associated with resource or null if one could - * not be found - */ - public Image getImage(String resource) { - Image image = getImageRegistry().get(resource); - if (image == null) { - // create an image - image = createImage(resource); - } - return image; - } - - /** - * Retrieves the image descriptor associated with resource from the image - * descriptor registry. If the image descriptor cannot be retrieved, - * attempt to find and load the image descriptor at the location specified - * in resource. - * - * @param resource - * the image descriptor to retrieve - * @return ImageDescriptor the image descriptor assocated with resource or - * the default "missing" image descriptor if one could not be - * found - */ - public ImageDescriptor getImageDescriptor(String resource) { - ImageDescriptor imageDescriptor = null; - Object o = getImageDescriptorRegistry().get(resource); - if (o == null) { - //create a descriptor - imageDescriptor = createImageDescriptor(resource); - } else { - imageDescriptor = (ImageDescriptor) o; - } - return imageDescriptor; - } - - /** - * Returns the image descriptor registry for this plugin. - * - * @return HashMap - image descriptor registry for this plugin - */ - private HashMap getImageDescriptorRegistry() { - if (fImageDescRegistry == null) - fImageDescRegistry = new HashMap(); - return fImageDescRegistry; - } - - /** - * Returns the image registry for this plugin. - * - * @return ImageRegistry - image registry for this plugin - */ - private ImageRegistry getImageRegistry() { - return JFaceResources.getImageRegistry(); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/editor/EditorPluginImages.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/editor/EditorPluginImages.java deleted file mode 100644 index 7b388440f2..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/editor/EditorPluginImages.java +++ /dev/null @@ -1,33 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.editor; - -/** - * Bundle of most images used by the Source Editor plug-in. - */ -public class EditorPluginImages { - - public static final String IMG_CTOOL16_SPELLCHECK = "icons/full/ctool16/spellcheck.gif"; //$NON-NLS-1$ - public static final String IMG_DLCL_COLLAPSEALL = "icons/full/dlcl16/collapseall.gif"; //$NON-NLS-1$ - public static final String IMG_DLCL_DELETE = "icons/full/dlcl16/delete.gif"; //$NON-NLS-1$ - public static final String IMG_DLCL_SYNCED = "icons/full/dlcl16/synced.gif"; //$NON-NLS-1$ - public static final String IMG_DTOOL16_SPELLCHECK = "icons/full/dtool16/spellcheck.gif"; //$NON-NLS-1$ - public static final String IMG_ELCL_COLLAPSEALL = "icons/full/elcl16/collapseall.gif"; //$NON-NLS-1$ - public static final String IMG_ELCL_DELETE = "icons/full/elcl16/delete.gif"; //$NON-NLS-1$ - public static final String IMG_ELCL_SYNCED = "icons/full/elcl16/synced.gif"; //$NON-NLS-1$ - public static final String IMG_ETOOL16_SPELLCHECK = "icons/full/etool16/spellcheck.gif"; //$NON-NLS-1$ - public static final String IMG_OBJ_OCC_MATCH = "icons/full/obj16/occ_match.gif"; //$NON-NLS-1$ - - public static final String IMG_OBJ_PREFERENCES = "icons/full/obj16/preferences.gif"; //$NON-NLS-1$ - public static final String IMG_OBJ_PROP_PS = "icons/full/obj16/prop_ps.gif"; //$NON-NLS-1$ -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/editor/IHelpContextIds.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/editor/IHelpContextIds.java deleted file mode 100644 index 3ce54608af..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/editor/IHelpContextIds.java +++ /dev/null @@ -1,58 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.editor; - -import org.eclipse.wst.sse.ui.internal.SSEUIPlugin; - -/** - * Help context ids for the Source Editor. - * <p> - * This interface contains constants only; it is not intended to be - * implemented. - * </p> - * - */ -public interface IHelpContextIds { - - // org.eclipse.wst.sse.ui. - public static final String PREFIX = SSEUIPlugin.ID + "."; //$NON-NLS-1$ - // Abstract Source Editor Context Menu - // Content Assist - public static final String CONTMNU_CONTENTASSIST_HELPID = PREFIX + "xmlm1010"; //$NON-NLS-1$ - // Format Document - public static final String CONTMNU_FORMAT_DOC_HELPID = PREFIX + "xmlm1030"; //$NON-NLS-1$ - // Format Active Elements - public static final String CONTMNU_FORMAT_ELEMENTS_HELPID = PREFIX + "xmlm1040"; //$NON-NLS-1$ - // Cleanup Document - // public static final String CONTMNU_CLEANUP_DOC_HELPID = PREFIX + - // "xmlm1050"; //$NON-NLS-1$ - - // Properties - public static final String CONTMNU_PROPERTIES_HELPID = PREFIX + "xmlm1070"; //$NON-NLS-1$ - - // Structured Text Editor Preference Page - // Appearance - public static final String PREFSTE_APPEARANCE_HELPID = PREFIX + "sted0001"; //$NON-NLS-1$ - // Hovers - public static final String PREFSTE_HOVERS_HELPID = PREFIX + "sted0003"; //$NON-NLS-1$ - -// // Read-Only Text Style -// public static final String PREFWEBX_READONLY_HELPID = PREFIX + "webx0001"; //$NON-NLS-1$ - - // Web and XML Preference Page - // Task Tags - public static final String PREFWEBX_TASKTAGS_HELPID = PREFIX + "webx0000"; //$NON-NLS-1$ - - // Source Editor View - public static final String XML_SOURCE_VIEW_HELPID = PREFIX + "xmlm2000"; //$NON-NLS-1$ -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/editor/SelectionConvertor.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/editor/SelectionConvertor.java deleted file mode 100644 index b6f5601b79..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/editor/SelectionConvertor.java +++ /dev/null @@ -1,62 +0,0 @@ -/*******************************************************************************
- * Copyright (c) 2008 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.sse.ui.internal.editor;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
-import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion;
-
-/**
- * This class/interface is part of an experimental API that is still under
- * development and expected to change significantly before reaching stability.
- * It is being made available at this early stage to solicit feedback from
- * pioneering adopters on the understanding that any code that uses this API
- * will almost certainly be broken (repeatedly) as the API evolves.
- */
-public class SelectionConvertor {
- /**
- * @param model
- * @param start
- * @param end
- * @return the most specific mapping of this text selection to
- * implementors of IndexedRegion
- */
- public Object[] getElements(IStructuredModel model, int start, int end) {
- Object[] localSelectedStructures = null;
- if (model != null) {
- IndexedRegion region = model.getIndexedRegion(start);
- if (region != null) {
- if (end <= region.getEndOffset()) {
- // single selection
- localSelectedStructures = new Object[1];
- localSelectedStructures[0] = region;
- }
- else {
- // multiple selection
- int maxLength = model.getStructuredDocument().getLength();
- List structures = new ArrayList(2);
- while (region != null && region.getEndOffset() <= end && region.getEndOffset() < maxLength) {
- structures.add(region);
- region = model.getIndexedRegion(region.getEndOffset() + 1);
- }
- localSelectedStructures = structures.toArray();
- }
- }
- }
- if (localSelectedStructures == null) {
- localSelectedStructures = new Object[0];
- }
- return localSelectedStructures;
- }
-}
diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/editor/StructuredModelDocumentProvider.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/editor/StructuredModelDocumentProvider.java deleted file mode 100644 index 91069ec442..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/editor/StructuredModelDocumentProvider.java +++ /dev/null @@ -1,263 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.editor; - -import java.io.IOException; -import java.io.UnsupportedEncodingException; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.content.IContentType; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.source.IAnnotationModel; -import org.eclipse.ui.texteditor.IDocumentProvider; -import org.eclipse.ui.texteditor.IDocumentProviderExtension; -import org.eclipse.ui.texteditor.IDocumentProviderExtension4; -import org.eclipse.ui.texteditor.IElementStateListener; -import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel; - - -/** - * @author nitin - */ -public class StructuredModelDocumentProvider implements IDocumentProvider, IDocumentProviderExtension, IDocumentProviderExtension4 { - private static StructuredModelDocumentProvider _instance = null; - - /** - * @return Returns the instance. - */ - public static StructuredModelDocumentProvider getInstance() { - return _instance; - } - - { - _instance = new StructuredModelDocumentProvider(); - } - - private StructuredModelDocumentProvider() { - super(); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.IDocumentProvider#aboutToChange(java.lang.Object) - */ - public void aboutToChange(Object element) { - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.IDocumentProvider#addElementStateListener(org.eclipse.ui.texteditor.IElementStateListener) - */ - public void addElementStateListener(IElementStateListener listener) { - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.IDocumentProvider#canSaveDocument(java.lang.Object) - */ - public boolean canSaveDocument(Object element) { - return ((IStructuredModel) element).isDirty(); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.IDocumentProvider#changed(java.lang.Object) - */ - public void changed(Object element) { - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.IDocumentProvider#connect(java.lang.Object) - */ - public void connect(Object element) throws CoreException { - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.IDocumentProvider#disconnect(java.lang.Object) - */ - public void disconnect(Object element) { - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.IDocumentProvider#getAnnotationModel(java.lang.Object) - */ - public IAnnotationModel getAnnotationModel(Object element) { - return null; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.IDocumentProvider#getDocument(java.lang.Object) - */ - public IDocument getDocument(Object element) { - return ((IStructuredModel) element).getStructuredDocument(); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.IDocumentProvider#getModificationStamp(java.lang.Object) - */ - public long getModificationStamp(Object element) { - return ((IStructuredModel) element).getSynchronizationStamp(); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.IDocumentProviderExtension#getStatus(java.lang.Object) - */ - public IStatus getStatus(Object element) { - return Status.OK_STATUS; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.IDocumentProvider#getSynchronizationStamp(java.lang.Object) - */ - public long getSynchronizationStamp(Object element) { - return 0; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.IDocumentProvider#isDeleted(java.lang.Object) - */ - public boolean isDeleted(Object element) { - return false; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.IDocumentProviderExtension#isModifiable(java.lang.Object) - */ - public boolean isModifiable(Object element) { - return true; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.IDocumentProviderExtension#isReadOnly(java.lang.Object) - */ - public boolean isReadOnly(Object element) { - return false; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.IDocumentProviderExtension#isStateValidated(java.lang.Object) - */ - public boolean isStateValidated(Object element) { - return false; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.IDocumentProvider#mustSaveDocument(java.lang.Object) - */ - public boolean mustSaveDocument(Object element) { - return ((IStructuredModel) element).isDirty(); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.IDocumentProvider#removeElementStateListener(org.eclipse.ui.texteditor.IElementStateListener) - */ - public void removeElementStateListener(IElementStateListener listener) { - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.IDocumentProvider#resetDocument(java.lang.Object) - */ - public void resetDocument(Object element) throws CoreException { - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.IDocumentProvider#saveDocument(org.eclipse.core.runtime.IProgressMonitor, - * java.lang.Object, org.eclipse.jface.text.IDocument, boolean) - */ - public void saveDocument(IProgressMonitor monitor, Object element, IDocument document, boolean overwrite) throws CoreException { - try { - ((IStructuredModel) element).save(); - } - catch (UnsupportedEncodingException e) { - } - catch (IOException e) { - } - catch (CoreException e) { - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.IDocumentProviderExtension#setCanSaveDocument(java.lang.Object) - */ - public void setCanSaveDocument(Object element) { - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.IDocumentProviderExtension#synchronize(java.lang.Object) - */ - public void synchronize(Object element) throws CoreException { - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.IDocumentProviderExtension#updateStateCache(java.lang.Object) - */ - public void updateStateCache(Object element) throws CoreException { - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.IDocumentProviderExtension#validateState(java.lang.Object, - * java.lang.Object) - */ - public void validateState(Object element, Object computationContext) throws CoreException { - } - - public IContentType getContentType(Object element) throws CoreException { - return Platform.getContentTypeManager().getContentType(((IStructuredModel) element).getContentTypeIdentifier()); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/extension/ActionDescriptor.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/extension/ActionDescriptor.java deleted file mode 100644 index 50108ff6a2..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/extension/ActionDescriptor.java +++ /dev/null @@ -1,378 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2006 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.extension; - - - -import com.ibm.icu.util.StringTokenizer; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IConfigurationElement; -import org.eclipse.core.runtime.Platform; -import org.eclipse.jface.action.Action; -import org.eclipse.jface.action.ActionContributionItem; -import org.eclipse.jface.action.IAction; -import org.eclipse.jface.action.IContributionItem; -import org.eclipse.swt.custom.BusyIndicator; -import org.eclipse.ui.PlatformUI; -import org.eclipse.wst.sse.ui.internal.IActionValidator; -import org.eclipse.wst.sse.ui.internal.Logger; -import org.osgi.framework.Bundle; - - -/** - * When 'action' tag is found in the registry, an object of this class is - * created. It creates the appropriate action object and captures information - * that is later used to add this action object into menu/tool bar. This class - * is reused for global (workbench) menu/tool bar, popup menu actions, as well - * as view's pulldown and local tool bar. - */ -public class ActionDescriptor { - public static final String ATT_ACCELERATOR = "accelerator"; //$NON-NLS-1$ - public static final String ATT_CLASS = "class"; //$NON-NLS-1$ - public static final String ATT_DEFINITION_ID = "definitionId"; //$NON-NLS-1$ - public static final String ATT_DESCRIPTION = "description"; //$NON-NLS-1$ - public static final String ATT_DISABLEDICON = "disabledIcon"; //$NON-NLS-1$ - public static final String ATT_HELP_CONTEXT_ID = "helpContextId"; //$NON-NLS-1$ - public static final String ATT_HOVERICON = "hoverIcon"; //$NON-NLS-1$ - public static final String ATT_ICON = "icon"; //$NON-NLS-1$ - - public static final String ATT_ID = "id"; //$NON-NLS-1$ - public static final String ATT_LABEL = "label"; //$NON-NLS-1$ - public static final String ATT_MENUBAR_PATH = "menubarPath"; //$NON-NLS-1$ - public static final String ATT_POPUPMENU_PATH = "popupmenuPath"; //$NON-NLS-1$ - public static final String ATT_STATE = "state"; //$NON-NLS-1$ - public static final String ATT_TOOLBAR_PATH = "toolbarPath"; //$NON-NLS-1$ - public static final String ATT_TOOLTIP = "tooltip"; //$NON-NLS-1$ - - /** - * Creates an extension. If the extension plugin has not been loaded a - * busy cursor will be activated during the duration of the load. - * - * @param element - * the config element defining the extension - * @param classAttribute - * the name of the attribute carrying the class - * @returns the extension object if successful. If an error occurs when - * createing executable extension, the exception is logged, and - * null returned. - */ - public static Object createExtension(final IConfigurationElement element, final String classAttribute) { - final Object[] result = new Object[1]; - // If plugin has been loaded create extension. - // Otherwise, show busy cursor then create extension. - String pluginId = element.getDeclaringExtension().getNamespace(); - Bundle bundle = Platform.getBundle(pluginId); - if (bundle.getState() == Bundle.ACTIVE) { - try { - result[0] = element.createExecutableExtension(classAttribute); - } catch (Exception e) { - // catch and log ANY exception from extension point - handleCreateExecutableException(result, e); - } - } else { - BusyIndicator.showWhile(null, new Runnable() { - public void run() { - try { - result[0] = element.createExecutableExtension(classAttribute); - } catch (Exception e) { - // catch and log ANY exception from extension point - handleCreateExecutableException(result, e); - } - } - }); - } - return result[0]; - } - - private static void handleCreateExecutableException(final Object[] result, Throwable e) { - Logger.logException(e); - result[0] = null; - } - - private String id; - - private ActionContributionItem item; - private String menuGroup; - private String menuPath; - private String popupmenuGroup; - private String popupmenuPath; - private String toolbarGroup; - private String toolbarPath; - - /** - * Creates a new descriptor with the targetType - */ - public ActionDescriptor(IConfigurationElement actionElement) throws CoreException { - - // Calculate menu and toolbar paths. - String mpath = actionElement.getAttribute(ATT_MENUBAR_PATH); - String mgroup = null; - if (mpath != null) { - int loc = mpath.lastIndexOf('/'); - if (loc != -1) { - mgroup = mpath.substring(loc + 1); - mpath = mpath.substring(0, loc); - } else { - mgroup = mpath; - mpath = null; - } - } - menuPath = mpath; - menuGroup = mgroup; - - String ppath = actionElement.getAttribute(ATT_POPUPMENU_PATH); - String pgroup = null; - if (ppath != null) { - int loc = ppath.lastIndexOf('/'); - if (loc != -1) { - pgroup = ppath.substring(loc + 1); - ppath = ppath.substring(0, loc); - } else { - pgroup = ppath; - ppath = null; - } - } - popupmenuPath = ppath; - popupmenuGroup = pgroup; - - String tpath = actionElement.getAttribute(ATT_TOOLBAR_PATH); - String tgroup = null; - if (tpath != null) { - int loc = tpath.lastIndexOf('/'); - if (loc != -1) { - tgroup = tpath.substring(loc + 1); - tpath = tpath.substring(0, loc); - } else { - tgroup = tpath; - tpath = null; - } - } - toolbarPath = tpath; - toolbarGroup = tgroup; - - // Create action. - IAction action = createAction(actionElement); - if (action == null) - return; - - String label = actionElement.getAttribute(ATT_LABEL); - if (label != null) - action.setText(label); - - id = actionElement.getAttribute(ATT_ID); - if (id == null) { - id = actionElement.getAttribute(ATT_CLASS); - } - if (id != null) - action.setId(id); - - String defId = actionElement.getAttribute(ATT_DEFINITION_ID); - if (defId != null && defId.length() != 0) { - action.setActionDefinitionId(defId); - } - - String tooltip = actionElement.getAttribute(ATT_TOOLTIP); - if (tooltip != null) - action.setToolTipText(tooltip); - - String helpContextId = actionElement.getAttribute(ATT_HELP_CONTEXT_ID); - if (helpContextId != null) { - String fullID = helpContextId; - if (helpContextId.indexOf(".") == -1) //$NON-NLS-1$ - // For backward compatibility we auto qualify the id if it is - // not qualified) - fullID = actionElement.getDeclaringExtension().getNamespace() + "." + helpContextId; //$NON-NLS-1$ - PlatformUI.getWorkbench().getHelpSystem().setHelp(action, fullID); - } - - String description = actionElement.getAttribute(ATT_DESCRIPTION); - if (description != null) - action.setDescription(description); - - String state = actionElement.getAttribute(ATT_STATE); - if (state != null) { - action.setChecked(state.equals("true")); //$NON-NLS-1$ - } - - String icon = actionElement.getAttribute(ATT_ICON); - if (icon != null) { - action.setImageDescriptor(ImageUtil.getImageDescriptorFromExtension(actionElement.getDeclaringExtension(), icon)); - } - - String hoverIcon = actionElement.getAttribute(ATT_HOVERICON); - if (hoverIcon != null) { - action.setHoverImageDescriptor(ImageUtil.getImageDescriptorFromExtension(actionElement.getDeclaringExtension(), hoverIcon)); - } - - String disabledIcon = actionElement.getAttribute(ATT_DISABLEDICON); - if (disabledIcon != null) { - action.setDisabledImageDescriptor(ImageUtil.getImageDescriptorFromExtension(actionElement.getDeclaringExtension(), disabledIcon)); - } - - String accelerator = actionElement.getAttribute(ATT_ACCELERATOR); - if (accelerator != null) - processAccelerator(action, accelerator); - - item = new ActionContributionItem(action); - } - - /** - * Parses the given accelerator text, and converts it to an accelerator - * key code. - * - * @param acceleratorText - * the accelerator text - * @result the SWT key code, or 0 if there is no accelerator - */ - private int convertAccelerator(String acceleratorText) { - int accelerator = 0; - StringTokenizer stok = new StringTokenizer(acceleratorText, "+"); //$NON-NLS-1$ - - int keyCode = -1; - - boolean hasMoreTokens = stok.hasMoreTokens(); - while (hasMoreTokens) { - String token = stok.nextToken(); - hasMoreTokens = stok.hasMoreTokens(); - // Every token except the last must be one of the modifiers - // Ctrl, Shift, or Alt. - if (hasMoreTokens) { - int modifier = Action.findModifier(token); - if (modifier != 0) { - accelerator |= modifier; - } else { //Leave if there are none - return 0; - } - } else { - keyCode = Action.findKeyCode(token); - } - } - if (keyCode != -1) { - accelerator |= keyCode; - } - return accelerator; - } - - /** - */ - private IAction createAction(IConfigurationElement actionElement) { - Object action = new ExtendedEditorActionProxyForDelayLoading(actionElement, ATT_CLASS); - if (action == null) - return null; - if (action instanceof IActionValidator) { - if (!((IActionValidator) action).isValidAction()) - return null; - } - return (action instanceof IAction ? (IAction) ExtendedEditorActionProxy.newInstance(action) : null); - } - - /** - * Returns the action object held in this descriptor. - */ - public IAction getAction() { - return (item != null ? item.getAction() : null); - } - - /** - * Returns the IContributionItem object held in this descriptor. - */ - public IContributionItem getContributionItem() { - return item; - } - - /** - * Returns action's id as defined in the registry. - */ - public String getId() { - return id; - } - - /** - * Returns named slot (group) in the menu where this action should be - * added. - */ - public String getMenuGroup() { - return menuGroup; - } - - /** - * Returns menu path where this action should be added. If null, the - * action will not be added into the menu. - */ - - public String getMenuPath() { - return menuPath; - } - - /** - * Returns named slot (group) in the popup menu where this action should - * be added. - */ - public String getPopupMenuGroup() { - return popupmenuGroup; - } - - /** - * Returns popup menu path where this action should be added. If null, the - * action will not be added into the popup menu. - */ - - public String getPopupMenuPath() { - return popupmenuPath; - } - - /** - * Returns the named slot (group) in the tool bar where this action should - * be added. - */ - - public String getToolbarGroup() { - return toolbarGroup; - } - - /** - * Returns path in the tool bar where this action should be added. If - * null, action will not be added to the tool bar. - */ - public String getToolbarPath() { - return toolbarPath; - } - - /** - * Process the accelerator definition. If it is a number then process the - * code directly - if not then parse it and create the code - */ - private void processAccelerator(IAction action, String acceleratorText) { - - if (acceleratorText.length() == 0) - return; - - //Is it a numeric definition? - if (Character.isDigit(acceleratorText.charAt(0))) { - try { - action.setAccelerator(Integer.valueOf(acceleratorText).intValue()); - } catch (NumberFormatException exception) { - Logger.log(Logger.ERROR, "Invalid accelerator declaration: " + id); //$NON-NLS-1$ - } - } else - action.setAccelerator(convertAccelerator(acceleratorText)); - } - - /** - * For debugging only. - */ - public String toString() { - return "ActionDescriptor(" + id + ")"; //$NON-NLS-2$//$NON-NLS-1$ - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/extension/BreakpointProviderBuilder.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/extension/BreakpointProviderBuilder.java deleted file mode 100644 index 2a6f9b2c10..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/extension/BreakpointProviderBuilder.java +++ /dev/null @@ -1,405 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2006 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.extension; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import com.ibm.icu.util.StringTokenizer; - -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IConfigurationElement; -import org.eclipse.core.runtime.IExtensionRegistry; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.content.IContentType; -import org.eclipse.swt.custom.BusyIndicator; -import org.eclipse.ui.IEditorInput; -import org.eclipse.ui.IEditorPart; -import org.eclipse.wst.sse.ui.internal.Logger; -import org.eclipse.wst.sse.ui.internal.provisional.extensions.ISourceEditingTextTools; -import org.eclipse.wst.sse.ui.internal.provisional.extensions.breakpoint.IBreakpointProvider; -import org.osgi.framework.Bundle; - - -/** - * Reads breakpoint extension registory and returns breakpoint provider - * instances - */ -public class BreakpointProviderBuilder extends RegistryReader { - - private static final String ATT_CLASS = "class"; //$NON-NLS-1$ - // private static final String ATT_ID = "id"; //$NON-NLS-1$ - private static final String ATT_CONTENT_TYPES = "contentTypes"; //$NON-NLS-1$ - private static final String ATT_EXTENSIONS = "extensions"; //$NON-NLS-1$ - private static BreakpointProviderBuilder instance; - private static final String PL_BREAKPOINT = "breakpoint"; //$NON-NLS-1$ - - private static final String PLUGIN_ID = "org.eclipse.wst.sse.ui"; //$NON-NLS-1$ - - private static final String TAG_BREAKPOINT_CONTRIBUTION = "breakpointContribution"; //$NON-NLS-1$ - private static final String TAG_PROVIDER = "provider"; //$NON-NLS-1$ - - /* - * Creates an executable extension. @param element the config element - * defining the extension @param classAttribute the name of the attribute - * carrying the class @return the extension object @throws CoreException - */ - static Object createExecutableExtension(final IConfigurationElement element, final String classAttribute) throws CoreException { - return element.createExecutableExtension(classAttribute); - } - - /** - * Creates an extension. If the extension plugin has not been loaded a - * busy cursor will be activated during the duration of the load. - * - * @param element - * the config element defining the extension - * @param classAttribute - * the name of the attribute carrying the class - * @return the extension object - * @throws CoreException - */ - public static Object createExtension(final IConfigurationElement element, final String classAttribute) { - // If plugin has been loaded create extension. - // Otherwise, show busy cursor then create extension. - final Object[] result = new Object[1]; - String pluginId = element.getDeclaringExtension().getNamespace(); - Bundle bundle = Platform.getBundle(pluginId); - if (bundle.getState() == Bundle.ACTIVE) { - try { - result[0] = createExecutableExtension(element, classAttribute); - } - catch (Exception e) { - handleCreateExecutableException(result, e); - } - } - else { - BusyIndicator.showWhile(null, new Runnable() { - public void run() { - try { - result[0] = createExecutableExtension(element, classAttribute); - } - catch (CoreException e) { - handleCreateExecutableException(result, e); - } - } - }); - - } - return result[0]; - } - - /** - * returns singleton instance of BreakpointProviderBuilder - * - * @return BreakpointProviderBuilder - */ - public synchronized static BreakpointProviderBuilder getInstance() { - if (instance == null) { - instance = new BreakpointProviderBuilder(); - } - return instance; - } - - /** - * @param result - * @param e - */ - private static void handleCreateExecutableException(Object[] result, Throwable e) { - Logger.logException(e); - result[0] = null; - - } - - protected List cache; - private Map map = new HashMap(); - - protected String targetContributionTag; - - /* - * Constructor - */ - private BreakpointProviderBuilder() { - super(); - } - - /* - * Creates a breakpoint provider object to given element @param element - * configuration element object @return IBreakpointProvider - */ - protected IBreakpointProvider createBreakpointProvider(IConfigurationElement element) { - Object obj = createExtension(element, ATT_CLASS); - if (obj == null) - return null; - return (obj instanceof IBreakpointProvider) ? (IBreakpointProvider) obj : null; - } - - /* - * Creates an array of breakpoint providers matching the given key to the - * value of the IConfigurationElement attribute "attrName" @return - * IBreakpointProvider[] - */ - protected IBreakpointProvider[] createBreakpointProviders(String attrName, String key) { - if (cache == null) - return new IBreakpointProvider[0]; - - final int num = cache.size(); - if (num == 0) - return new IBreakpointProvider[0]; - - IBreakpointProvider[] bp = new IBreakpointProvider[num]; - int j = 0; - for (int i = 0; i < num; i++) { - Object obj = cache.get(i); - if (!(obj instanceof IConfigurationElement)) - continue; - - IConfigurationElement element = (IConfigurationElement) obj; - if (!TAG_PROVIDER.equals(element.getName())) - continue; - - boolean doCreate = false; - - String attrValues = element.getAttribute(attrName); - - if (attrValues != null) { - StringTokenizer tokenizer = new StringTokenizer(attrValues, ","); //$NON-NLS-1$ - while (tokenizer.hasMoreTokens()) { - String type = tokenizer.nextToken(); - if (type.trim().equalsIgnoreCase(key.trim())) { - doCreate = true; - break; - } - } - } - - if (doCreate) { - IBreakpointProvider b = createBreakpointProvider(element); - if (b != null) { - bp[j] = b; - j++; - } - } - } - - IBreakpointProvider[] bp2 = new IBreakpointProvider[j]; - for (int i = 0; i < j; i++) { - bp2[i] = bp[i]; - } - - return bp2; - } - - /* - * Returns a matching array of extension points matching this key. Doesn't - * cause instantiation of providers. @return IBreakpointProvider[] - */ - protected IConfigurationElement[] findElements(String key) { - initCache(); - - if (cache == null || cache.size() == 0) - return new IConfigurationElement[0]; - - int num = cache.size(); - List elements = new ArrayList(1); - for (int i = 0; i < num; i++) { - Object obj = cache.get(i); - if (!(obj instanceof IConfigurationElement)) - continue; - - IConfigurationElement element = (IConfigurationElement) obj; - if (!TAG_PROVIDER.equals(element.getName())) - continue; - - boolean add = false; - String types = element.getAttribute(ATT_CONTENT_TYPES); - String exts = element.getAttribute(ATT_EXTENSIONS); - - if (types == null && exts == null) { - add = true; - } - - if (!add && types != null && types.length() > 0) { - IContentType testType = Platform.getContentTypeManager().getContentType(key); - StringTokenizer tokenizer = new StringTokenizer(types, ","); //$NON-NLS-1$ - while (tokenizer.hasMoreTokens()) { - String type = tokenizer.nextToken(); - IContentType contentType = Platform.getContentTypeManager().getContentType(type); - if (contentType != null && testType != null && testType.isKindOf(contentType)) { - add = true; - break; - } - } - } - - if (!add && exts != null) { - StringTokenizer tokenizer = new StringTokenizer(exts, ","); //$NON-NLS-1$ - while (tokenizer.hasMoreTokens()) { - String ext = tokenizer.nextToken(); - if (ext.trim().equals(key.trim())) { - add = true; - break; - } - } - } - - if (add) { - elements.add(element); - } - } - return (IConfigurationElement[]) elements.toArray(new IConfigurationElement[0]); - } - - /** - * Returns an array of breakpoint providers for a specified content type - * handler - * - * @param handler - * a content type handler - * @param ext - * file extension - * @return IBreakpointProvider[] - */ - public IBreakpointProvider[] getBreakpointProviders(IEditorPart editorpart, String contentTypeID, String ext) { - initCache(); - - // Get breakpoint providers for this content type handler - IBreakpointProvider[] providers1 = new IBreakpointProvider[0]; - IContentType contentType = Platform.getContentTypeManager().getContentType(contentTypeID); - List holdProviders = new ArrayList(2); - while (contentType != null) { - IBreakpointProvider[] providers = (IBreakpointProvider[]) map.get(contentType.getId()); - if (providers == null) { - providers = createBreakpointProviders(ATT_CONTENT_TYPES, contentType.getId()); - if (providers != null) { - map.put(contentType.getId(), providers); - } - } - // providers were retrieved from cache or newly created - if(providers != null) { - holdProviders.addAll(Arrays.asList(providers)); - } - contentType = contentType.getBaseType(); - } - providers1 = (IBreakpointProvider[]) holdProviders.toArray(new IBreakpointProvider[holdProviders.size()]); - - // Get breakpoint providers for this extension - IBreakpointProvider[] providers2 = new IBreakpointProvider[0]; - if (ext != null) { - providers2 = (IBreakpointProvider[]) map.get(ext); - if (providers2 == null) { - providers2 = createBreakpointProviders(ATT_EXTENSIONS, ext); - if (providers2 != null) { - map.put(ext, providers2); - } - } - } - - // create single hash set to remove duplication - Set s = new HashSet(); - s.addAll(Arrays.asList(providers1)); - s.addAll(Arrays.asList(providers2)); - - // create IBreakpointProvider[] to return - IBreakpointProvider[] providers = new IBreakpointProvider[s.size()]; - Iterator itr = s.iterator(); - int i = 0; - ISourceEditingTextTools tools = null; - if (editorpart != null && itr.hasNext()) - tools = (ISourceEditingTextTools) editorpart.getAdapter(ISourceEditingTextTools.class); - while (itr.hasNext()) { - providers[i] = (IBreakpointProvider) itr.next(); - providers[i].setSourceEditingTextTools(tools); - i++; - } - return providers; - } - - /** - * Returns corresponding resource from given parameters - * - * @param input - * @param handler - * @param ext - * @return IResource - */ - public IResource getResource(IEditorInput input, String contentType, String ext) { - IBreakpointProvider[] providers = getBreakpointProviders(null, contentType, ext); - IResource res = null; - for (int i = 0; i < providers.length; i++) { - res = providers[i].getResource(input); - if (res != null) { - break; - } - } - return res; - } - - private void initCache() { - if (cache == null) { - cache = new ArrayList(); - readContributions(TAG_BREAKPOINT_CONTRIBUTION, PL_BREAKPOINT); - } - } - - /** - * Returns an array of breakpoint providers for a specified content type - * handler - * - * @param contentType - * a content type ID or null - * @param ext - * a filename extension or null - * @return boolean - */ - public boolean isAvailable(String contentType, String ext) { - boolean available = false; - if (ext != null) - available = findElements(ext).length > 0; - if (!available && contentType != null) - available = findElements(contentType).length > 0; - return available; - } - - /** - * Reads the contributions from the registry for the provided workbench - * part and the provided extension point ID. - * - * @param tag - * @param extensionPoint - */ - protected void readContributions(String tag, String extensionPoint) { - targetContributionTag = tag; - IExtensionRegistry registry = Platform.getExtensionRegistry(); - readRegistry(registry, PLUGIN_ID, extensionPoint); - } - - protected boolean readElement(IConfigurationElement element) { - String tag = element.getName(); - if (tag.equals(targetContributionTag)) { - readElementChildren(element); - return true; - } - else if (tag.equals(TAG_PROVIDER)) { - cache.add(element); - return true; // just cache the element - don't go into it - } - return false; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/extension/DropActionProxy.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/extension/DropActionProxy.java deleted file mode 100644 index 104f49abb1..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/extension/DropActionProxy.java +++ /dev/null @@ -1,149 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.extension; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; - -import org.eclipse.jface.action.IAction; -import org.eclipse.jface.text.IDocument; -import org.eclipse.ui.texteditor.ITextEditor; -import org.eclipse.ui.texteditor.ITextEditorExtension2; -import org.eclipse.wst.sse.core.StructuredModelManager; -import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel; -import org.eclipse.wst.sse.core.internal.undo.IStructuredTextUndoManager; -import org.eclipse.wst.sse.ui.internal.IExtendedSimpleEditor; -import org.eclipse.wst.sse.ui.internal.Logger; -import org.eclipse.wst.sse.ui.internal.provisional.extensions.ISelfValidateEditAction; - - -/** - */ -public class DropActionProxy implements InvocationHandler { - public static Object newInstance(Object obj) { - Object instance = null; - try { - Set set = new HashSet(); - Class clazz = obj.getClass(); - while (clazz != null) { - Class[] interfaces = clazz.getInterfaces(); - for (int i = 0; i < interfaces.length; i++) { - set.add(interfaces[i]); - } - clazz = clazz.getSuperclass(); - } - Class[] classes = new Class[set.size()]; - Iterator itr = set.iterator(); - int i = 0; - while (itr.hasNext()) { - classes[i] = (Class) itr.next(); - i++; - } - instance = Proxy.newProxyInstance(obj.getClass().getClassLoader(), classes, new DropActionProxy(obj)); - } catch (Error e) { - Logger.logException("Exception while proxying a drop action", e); //$NON-NLS-1$ - instance = obj; - } - return instance; - } - - private IExtendedSimpleEditor editor = null; - private IStructuredModel fRecorder; - private Object obj; - - private DropActionProxy(Object obj) { - this.obj = obj; - } - - private void beginRecording() { - IDocument document = null; - if (editor != null) { - document = editor.getDocument(); - if (document != null) - fRecorder = StructuredModelManager.getModelManager().getExistingModelForEdit(document); - // Prepare for Undo - if (fRecorder != null) { - IStructuredTextUndoManager um = fRecorder.getUndoManager(); - if (um != null) { - if (this.obj instanceof IAction) - um.beginRecording(this, ((IAction) this.obj).getText(), ((IAction) this.obj).getDescription()); - else - um.beginRecording(this); - } - } - } - } - - private void endRecording() { - if (fRecorder != null) { - IStructuredTextUndoManager um = fRecorder.getUndoManager(); - if (um != null) - um.endRecording(this); - fRecorder.releaseFromEdit(); - fRecorder = null; - } - } - - /** - * @see java.lang.reflect.InvocationHandler#invoke(Object, Method, - * Object[]) - */ - public Object invoke(Object proxy, Method m, Object[] args) throws Throwable { - Object result; - String name = m.getName(); - try { - if (name.equals("equals")) { //$NON-NLS-1$ - // Workaround for JDK's bug 4652876 - // "equals" always returns false even if both - // InvocationHandler - // class - // hold the same objects - // See - // http://developer.java.sun.com/developer/bugParade/bugs/4652876.html - // This problem is in the IBM SDK 1.3.1 - // but I don't see the bug in Sun's JDK 1.4.1 (beta) - Object arg = args[0]; - return (proxy.getClass() == arg.getClass() && equals(Proxy.getInvocationHandler(arg))) ? Boolean.TRUE : Boolean.FALSE; - } else if (name.equals("run")) { //$NON-NLS-1$ - if (args[1] instanceof IExtendedSimpleEditor) { - editor = (IExtendedSimpleEditor) args[1]; - } - beginRecording(); - if ((args[1] instanceof ITextEditor) && !(obj instanceof ISelfValidateEditAction) && !isEditable((ITextEditor) args[1])) { - return Boolean.FALSE; - } - } - result = m.invoke(obj, args); - } catch (InvocationTargetException e) { - throw e.getTargetException(); - } catch (Exception e) { - throw new RuntimeException(e.getMessage()); - } finally { - if (name.equals("run")) { //$NON-NLS-1$ - endRecording(); - } - } - return result; - } - - private boolean isEditable(ITextEditor editor) { - if (editor instanceof ITextEditorExtension2) - return ((ITextEditorExtension2) editor).validateEditorInputState(); - return editor.isEditable(); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/extension/ExtendedEditorActionProxy.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/extension/ExtendedEditorActionProxy.java deleted file mode 100644 index b11c7b901d..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/extension/ExtendedEditorActionProxy.java +++ /dev/null @@ -1,149 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2006 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.extension; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; - -import org.eclipse.jface.action.IAction; -import org.eclipse.jface.text.IDocument; -import org.eclipse.wst.sse.core.StructuredModelManager; -import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel; -import org.eclipse.wst.sse.core.internal.undo.IStructuredTextUndoManager; -import org.eclipse.wst.sse.ui.internal.IExtendedSimpleEditor; -import org.eclipse.wst.sse.ui.internal.Logger; -import org.eclipse.wst.sse.ui.internal.provisional.extensions.ISelfValidateEditAction; - - -/** - * Begins and ends UndoManager recording around run() and runWithEvent(...) - */ -public class ExtendedEditorActionProxy implements InvocationHandler { - public static Object newInstance(Object obj) { - Set set = new HashSet(); - Class clazz = obj.getClass(); - while (clazz != null) { - Class[] interfaces = clazz.getInterfaces(); - for (int i = 0; i < interfaces.length; i++) { - set.add(interfaces[i]); - } - clazz = clazz.getSuperclass(); - } - Class[] classes = new Class[set.size()]; - Iterator itr = set.iterator(); - int i = 0; - while (itr.hasNext()) { - classes[i] = (Class) itr.next(); - i++; - } - return Proxy.newProxyInstance(obj.getClass().getClassLoader(), classes, new ExtendedEditorActionProxy(obj)); - } - - private IExtendedSimpleEditor editor = null; - private IStructuredModel fRecorder; - private Object obj; - - private ExtendedEditorActionProxy(Object obj) { - this.obj = obj; - } - - private void beginRecording() { - IDocument document = null; - if (editor != null) { - document = editor.getDocument(); - if (document != null) - fRecorder = StructuredModelManager.getModelManager().getExistingModelForEdit(document); - // Prepare for Undo - if (fRecorder != null) { - IStructuredTextUndoManager um = fRecorder.getUndoManager(); - if (um != null) { - um.beginRecording(this, ((IAction) this.obj).getText(), ((IAction) this.obj).getDescription()); - } - } - } - } - - private void endRecording() { - if (fRecorder != null) { - IStructuredTextUndoManager um = fRecorder.getUndoManager(); - if (um != null) { - um.endRecording(this); - } - fRecorder.releaseFromEdit(); - fRecorder = null; - } - } - - /** - * @see java.lang.reflect.InvocationHandler#invoke(Object, Method, - * Object[]) - */ - public Object invoke(Object proxy, Method m, Object[] args) throws Throwable { - Object result = null; - String name = m.getName(); - try { - if (name.equals("equals")) { //$NON-NLS-1$ - // Workaround for JDK's bug 4652876 - // "equals" always returns false even if both - // InvocationHandler - // class - // hold the same objects - // See - // http://developer.java.sun.com/developer/bugParade/bugs/4652876.html - // This problem is in the IBM SDK 1.3.1 - // but I don't see the bug in Sun's JDK 1.4.1 (beta) - Object arg = args[0]; - return (proxy.getClass() == arg.getClass() && equals(Proxy.getInvocationHandler(arg))) ? Boolean.TRUE : Boolean.FALSE; - } else if (name.equals("runWithEvent") || name.equals("run")) { //$NON-NLS-1$ //$NON-NLS-2$ - beginRecording(); - if ((editor != null) && !(this.obj instanceof ISelfValidateEditAction)) { - - // TODO: cleanup validateEdit - // just leaving this check and following code here for transition. - // I assume we'll remove all need for 'validateEdit' - // or move to platform editor's validateState - -// IStatus status = editor.validateEdit(getDisplay().getActiveShell()); -// if (!status.isOK()) { -// return null; -// } - } - } else if (name.equals("setActiveExtendedEditor")) { //$NON-NLS-1$ - if (args[0] instanceof IExtendedSimpleEditor) { - editor = (IExtendedSimpleEditor) args[0]; - } - } - result = m.invoke(this.obj, args); - } catch (InvocationTargetException e) { - Logger.logException(e.getTargetException()); - //throw e.getTargetException(); - } catch (Exception e) { - Logger.logException(e); - if (name.equals("runWithEvent") || name.equals("run")) { //$NON-NLS-1$ //$NON-NLS-2$ - // only expose user-driven exceptions from "running" to the - // user - throw new RuntimeException(e.getMessage()); - } - } finally { - if (name.equals("runWithEvent") || name.equals("run")) { //$NON-NLS-1$ //$NON-NLS-2$ - endRecording(); - } - } - return result; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/extension/ExtendedEditorActionProxyForDelayLoading.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/extension/ExtendedEditorActionProxyForDelayLoading.java deleted file mode 100644 index 067629271f..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/extension/ExtendedEditorActionProxyForDelayLoading.java +++ /dev/null @@ -1,771 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.extension; - -import org.eclipse.core.runtime.IConfigurationElement; -import org.eclipse.core.runtime.Platform; -import org.eclipse.jface.action.Action; -import org.eclipse.jface.action.IAction; -import org.eclipse.jface.action.IMenuCreator; -import org.eclipse.jface.resource.ImageDescriptor; -import org.eclipse.jface.util.IPropertyChangeListener; -import org.eclipse.jface.util.ListenerList; -import org.eclipse.swt.custom.BusyIndicator; -import org.eclipse.swt.events.HelpListener; -import org.eclipse.swt.widgets.Event; -import org.eclipse.ui.texteditor.IUpdate; -import org.eclipse.wst.sse.ui.internal.IExtendedEditorAction; -import org.eclipse.wst.sse.ui.internal.IExtendedSimpleEditor; -import org.eclipse.wst.sse.ui.internal.Logger; -import org.osgi.framework.Bundle; - -public class ExtendedEditorActionProxyForDelayLoading implements IExtendedEditorAction, IExtendedEditorActionProxyForDelayLoading, IAction { - private IAction proxy; - private IAction dummy = new Action() { // this is for mainly its property change notify... - }; - // proxy'ed properties - private String p_id; - private boolean set_p_id; - private String p_text; - private String p_description; - private boolean set_p_text; - private boolean set_p_description; - private String p_toolTipText; - private boolean set_p_toolTipText; - private String p_actionDefinitionId; - private boolean set_p_actionDefinitionId; - private ImageDescriptor p_image; - private boolean set_p_image; - private ImageDescriptor p_hoverImage; - private boolean set_p_hoverImage; - private ImageDescriptor p_disabledImage; - private boolean set_p_disabledImage; - private int p_accelerator; - private boolean set_p_accelerator; - private int p_style = AS_PUSH_BUTTON; - //private boolean set_p_style; - private HelpListener p_helpListener; - private boolean set_p_helpListener; - private boolean p_enabled = true; // should be same as what is done in - private boolean set_p_enabled; - private ListenerList p_listeners = new ListenerList(3); - private boolean set_p_listeners; - private boolean p_checked; - private boolean set_p_checked; - private IExtendedSimpleEditor p_targetEditor; - private boolean set_p_targetEditor; - private boolean p_isvisible = true; // should be true - - private IConfigurationElement element; - private String classAttribute; - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.action.IAction#addPropertyChangeListener(org.eclipse.jface.util.IPropertyChangeListener) - */ - public void addPropertyChangeListener(IPropertyChangeListener listener) { - p_listeners.add(listener); - set_p_listeners = true; - // don't realize class. - // realize(); - if (proxy != null) { - proxy.addPropertyChangeListener(listener); - } else { - dummy.addPropertyChangeListener(listener); - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.action.IAction#getAccelerator() - */ - public int getAccelerator() { - // don't realize class. - // realize(); - if (proxy != null) { - return proxy.getAccelerator(); - } - return p_accelerator; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.action.IAction#getActionDefinitionId() - */ - public String getActionDefinitionId() { - // don't realize class. - // realize(); - if (proxy != null) { - return proxy.getActionDefinitionId(); - } - return p_actionDefinitionId; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.action.IAction#getDescription() - */ - public String getDescription() { - // System.out.println(p_id + ": getDescription"); - // System.out.flush(); - if (proxy != null) { - return proxy.getDescription(); - } - return p_description; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.action.IAction#getDisabledImageDescriptor() - */ - public ImageDescriptor getDisabledImageDescriptor() { - // don't realize class. - // realize(); - if (proxy != null) { - return proxy.getDisabledImageDescriptor(); - } - return p_disabledImage; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.action.IAction#getHelpListener() - */ - public HelpListener getHelpListener() { - // don't realize class. - // realize(); - if (proxy != null) { - return proxy.getHelpListener(); - } - return p_helpListener; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.action.IAction#getHoverImageDescriptor() - */ - public ImageDescriptor getHoverImageDescriptor() { - // don't realize class. - // realize(); - if (proxy != null) { - return proxy.getHoverImageDescriptor(); - } - return p_hoverImage; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.action.IAction#getId() - */ - public String getId() { - // don't realize class. - // realize(); - if (proxy != null) { - return proxy.getId(); - } - return p_id; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.action.IAction#getImageDescriptor() - */ - public ImageDescriptor getImageDescriptor() { - // don't realize class. - // realize(); - if (proxy != null) { - return proxy.getImageDescriptor(); - } - return p_image; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.action.IAction#getMenuCreator() - */ - public IMenuCreator getMenuCreator() { - // System.out.println(p_id + ": getMenuCreator"); - // System.out.flush(); - realize(); - if (proxy != null) { - return proxy.getMenuCreator(); - } - return null; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.action.IAction#getStyle() - */ - public int getStyle() { - // don't realize class. - // realize(); - if (proxy != null) { - return proxy.getStyle(); - } - return p_style; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.action.IAction#getText() - */ - public String getText() { - // don't realize class. - // realize(); - if (proxy != null) { - return proxy.getText(); - } - if (p_text != null) { - return p_text; - } - return ""; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.action.IAction#getToolTipText() - */ - public String getToolTipText() { - // don't realize class. - // realize(); - if (proxy != null) { - return proxy.getToolTipText(); - } - return p_toolTipText; - } - - /** - * Check if the contributing bundle is active - */ - public boolean isBundleActive() { - Bundle bundle = Platform.getBundle(element.getDeclaringExtension().getNamespace()); - if (bundle != null && bundle.getState() != Bundle.ACTIVE) { - return false; - } - return true; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.action.IAction#isChecked() - */ - public boolean isChecked() { - // don't realize class. - // realize(); - if (proxy != null) { - return proxy.isChecked(); - } - return p_checked; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.action.IAction#isEnabled() - */ - public boolean isEnabled() { - // don't realize class. - // realize(); - if (proxy != null) { - return proxy.isEnabled(); - } - return p_enabled; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.action.IAction#removePropertyChangeListener(org.eclipse.jface.util.IPropertyChangeListener) - */ - public void removePropertyChangeListener(IPropertyChangeListener listener) { - p_listeners.remove(listener); - // don't realize class. - // realize(); - if (proxy != null) { - proxy.removePropertyChangeListener(listener); - } - dummy.removePropertyChangeListener(listener); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.action.IAction#run() - */ - public void run() { - realize(); - if (proxy != null) { - // if this has a key accelerator, first update this action and to - // see if this action is enabled or not. - if ((proxy.getAccelerator() > 0) || (proxy.getActionDefinitionId() != null)) { - update(); - if (isEnabled() == true) { - proxy.run(); - } - } else { - proxy.run(); - } - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.action.IAction#runWithEvent(org.eclipse.swt.widgets.Event) - */ - public void runWithEvent(Event event) { - realize(); - if (proxy != null) { - // same as run() - if ((proxy.getAccelerator() > 0) || (proxy.getActionDefinitionId() != null)) { - update(); - if (isEnabled() == true) { - proxy.runWithEvent(event); - } - } else { - proxy.runWithEvent(event); - } - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.action.IAction#setActionDefinitionId(java.lang.String) - */ - public void setActionDefinitionId(String id) { - p_actionDefinitionId = id; - set_p_actionDefinitionId = true; - // don't realize class. - // realize(); - if (proxy != null) { - proxy.setActionDefinitionId(id); - } else { - dummy.setActionDefinitionId(id); - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.action.IAction#setChecked(boolean) - */ - public void setChecked(boolean checked) { - p_checked = checked; - set_p_checked = true; - // don't realize class. - // realize(); - if (proxy != null) { - proxy.setChecked(checked); - } else { - dummy.setChecked(checked); - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.action.IAction#setDescription(java.lang.String) - */ - public void setDescription(String description) { - p_description = description; - set_p_description = true; - // don't realize class. - // realize(); - if (proxy != null) { - proxy.setDescription(description); - } else { - dummy.setDescription(description); - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.action.IAction#setDisabledImageDescriptor(org.eclipse.jface.resource.ImageDescriptor) - */ - public void setDisabledImageDescriptor(ImageDescriptor newImage) { - p_disabledImage = newImage; - set_p_disabledImage = true; - // don't realize class. - // realize(); - if (proxy != null) { - proxy.setDisabledImageDescriptor(newImage); - } else { - dummy.setDisabledImageDescriptor(newImage); - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.action.IAction#setEnabled(boolean) - */ - public void setEnabled(boolean enabled) { - p_enabled = enabled; - set_p_enabled = true; - // don't realize class. - // realize(); - if (proxy != null) { - proxy.setEnabled(enabled); - } else { - dummy.setEnabled(enabled); - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.action.IAction#setHelpListener(org.eclipse.swt.events.HelpListener) - */ - public void setHelpListener(HelpListener listener) { - p_helpListener = listener; - set_p_helpListener = true; - // don't realize class. - // realize(); - if (proxy != null) { - proxy.setHelpListener(listener); - } else { - dummy.setHelpListener(listener); - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.action.IAction#setHoverImageDescriptor(org.eclipse.jface.resource.ImageDescriptor) - */ - public void setHoverImageDescriptor(ImageDescriptor newImage) { - p_hoverImage = newImage; - set_p_hoverImage = true; - // don't realize class. - // realize(); - if (proxy != null) { - proxy.setHoverImageDescriptor(newImage); - } else { - dummy.setHoverImageDescriptor(newImage); - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.action.IAction#setId(java.lang.String) - */ - public void setId(String id) { - p_id = id; - set_p_id = true; - // don't realize class. - // realize(); - if (proxy != null) { - proxy.setId(id); - } else { - dummy.setId(id); - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.action.IAction#setImageDescriptor(org.eclipse.jface.resource.ImageDescriptor) - */ - public void setImageDescriptor(ImageDescriptor newImage) { - p_image = newImage; - set_p_image = true; - // don't realize class. - // realize(); - if (proxy != null) { - proxy.setImageDescriptor(newImage); - } else { - dummy.setImageDescriptor(newImage); - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.action.IAction#setMenuCreator(org.eclipse.jface.action.IMenuCreator) - */ - public void setMenuCreator(IMenuCreator creator) { - // System.out.println(p_id + ": setMenuCreator"); - // System.out.flush(); - realize(); - if (proxy != null) { - proxy.setMenuCreator(creator); - } else { - dummy.setMenuCreator(creator); - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.action.IAction#setText(java.lang.String) - */ - public void setText(String text) { - p_text = text; - set_p_text = true; - // don't realize class. - // realize(); - if (proxy != null) { - proxy.setText(text); - } else { - dummy.setText(text); - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.action.IAction#setToolTipText(java.lang.String) - */ - public void setToolTipText(String text) { - p_toolTipText = text; - set_p_toolTipText = true; - // don't realize class. - // realize(); - if (proxy != null) { - proxy.setToolTipText(text); - } else { - dummy.setToolTipText(text); - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.action.IAction#setAccelerator(int) - */ - public void setAccelerator(int keycode) { - p_accelerator = keycode; - set_p_accelerator = true; - // don't realize class. - // realize(); - if (proxy != null) { - proxy.setAccelerator(keycode); - } else { - dummy.setAccelerator(keycode); - } - } - - - /* (non-Javadoc) - * @see org.eclipse.wst.sse.ui.internal.IExtendedEditorAction#setActiveExtendedEditor(com.ibm.sse.editor.extension.IExtendedSimpleEditor) - */ - public void setActiveExtendedEditor(IExtendedSimpleEditor targetEditor) { - p_targetEditor = targetEditor; - set_p_targetEditor = true; - // don't realize class. - // realize(); - if ((proxy != null) && (proxy instanceof IExtendedEditorAction)) { - ((IExtendedEditorAction)proxy).setActiveExtendedEditor(targetEditor); - } - } - - /* (non-Javadoc) - * @see com.ibm.sse.editor.extension.IExtendedEditorAction#isVisible() - */ - public boolean isVisible() { - // don't realize class. - // realize(); - if ((proxy != null) && (proxy instanceof IExtendedEditorAction)) { - return ((IExtendedEditorAction)proxy).isVisible(); - } - return p_isvisible; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.action.IAction#isHandled - */ - public boolean isHandled() { - return false; - } - - // see ActionDescriptor#createExtension - private static IAction newInstance(final IConfigurationElement elm, final String cla) { - final Object[] result = new Object[1]; - // If plugin has been loaded create extension. - // Otherwise, show busy cursor then create extension. - Bundle bundle= Platform.getBundle(elm.getDeclaringExtension().getNamespace()); - if (bundle != null && bundle.getState() == Bundle.ACTIVE) { - try { - result[0] = elm.createExecutableExtension(cla); - } - catch (Exception e) { - // catch and log ANY exception from extension point - handleCreateExecutableException(result, e, elm.getAttribute(cla)); - } - } - else { - BusyIndicator.showWhile(null, new Runnable() { - public void run() { - try { - result[0] = elm.createExecutableExtension(cla); - } - catch (Exception e) { - // catch and log ANY exception from extension point - handleCreateExecutableException(result, e, elm.getAttribute(cla)); - } - } - }); - } - if ((result[0] != null) && (result[0] instanceof IAction)) { - return (IAction)result[0]; - } - return null; - } - - private static void handleCreateExecutableException(final Object[] result, Throwable e, String classname) { - Logger.logException("Unable to create proxy action for " + classname, e); - result[0] = null; - } - - /** - * Instantiate a real class here - */ - public void realize() { - if ((proxy == null) && (element != null) && (classAttribute != null)) { - proxy = newInstance(element, classAttribute); - if (proxy != null) { - // propagate proxy'ed properties - if (set_p_listeners == true) { - if (p_listeners.size() > 0) { - Object[] l = p_listeners.getListeners(); - int ls = l.length; - for (int i = 0; i < ls; i++) { - IPropertyChangeListener pl = (IPropertyChangeListener) l[i]; - proxy.addPropertyChangeListener(pl); - dummy.removePropertyChangeListener(pl); // remove listener from dymmy so that we don't send notifications twice anymore - } - } - } - if (set_p_accelerator == true) { - proxy.setAccelerator(p_accelerator); - } - if (set_p_actionDefinitionId == true) { - if (p_actionDefinitionId != null) { - proxy.setActionDefinitionId(p_actionDefinitionId); - } - } - if (set_p_checked == true) { - proxy.setChecked(p_checked); - } - if (set_p_disabledImage == true) { - if (p_disabledImage != null) { - proxy.setDisabledImageDescriptor(p_disabledImage); - } - } - if (set_p_enabled == true) { - proxy.setEnabled(p_enabled); - } - if (set_p_helpListener == true) { - if (p_helpListener != null) { - proxy.setHelpListener(p_helpListener); - } - } - if (set_p_hoverImage == true) { - if (p_hoverImage != null) { - proxy.setHoverImageDescriptor(p_hoverImage); - } - } - if (set_p_id == true) { - if (p_id != null) { - proxy.setId(p_id); - } - } - if (set_p_image == true) { - if (p_image != null) { - proxy.setImageDescriptor(p_image); - } - } - if (set_p_text == true) { - if (p_text != null) { - proxy.setText(p_text); - } - } - if (set_p_description == true) { - if (p_description != null) { - proxy.setDescription(p_description); - } - } - if (set_p_toolTipText == true) { - if (p_toolTipText != null) { - proxy.setToolTipText(p_toolTipText); - } - } - if (set_p_targetEditor == true) { - if (p_targetEditor != null) { - if (proxy instanceof IExtendedEditorAction) { - ((IExtendedEditorAction)proxy).setActiveExtendedEditor(p_targetEditor); - } - } - } - } - } - } - - public boolean isRealized() { - return (proxy != null); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.IUpdate#update() - */ - public void update() { - // don't realize class. - // realize(); - if ((proxy != null) && (proxy instanceof IUpdate)) { - ((IUpdate) proxy).update(); - } - } - - /** - * get a real action class - */ - public IAction getAction() { - realize(); - return proxy; - } - - - /** - * These are Actions's constructors - */ - ExtendedEditorActionProxyForDelayLoading() { - super(); - } - public ExtendedEditorActionProxyForDelayLoading(final IConfigurationElement element, final String classAttribute) { - super(); - this.element = element; - this.classAttribute = classAttribute; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/extension/IExtendedEditorActionProxyForDelayLoading.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/extension/IExtendedEditorActionProxyForDelayLoading.java deleted file mode 100644 index 773858b295..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/extension/IExtendedEditorActionProxyForDelayLoading.java +++ /dev/null @@ -1,25 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2007 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.extension; - -import org.eclipse.jface.action.IAction; - -/** - * @deprecated - */ -public interface IExtendedEditorActionProxyForDelayLoading { - public IAction getAction(); - public boolean isRealized(); - public void realize(); - boolean isBundleActive(); -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/extension/ImageUtil.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/extension/ImageUtil.java deleted file mode 100644 index aefc562c41..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/extension/ImageUtil.java +++ /dev/null @@ -1,84 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.extension; - - - -import java.net.MalformedURLException; -import java.net.URL; - -import org.eclipse.core.runtime.IExtension; -import org.eclipse.core.runtime.Platform; -import org.eclipse.jface.resource.ImageDescriptor; -import org.osgi.framework.Bundle; - -public class ImageUtil { - - - /** - * Convenience Method. Returns an ImageDescriptor whose path, relative to - * the plugin containing the <code>extension</code> is - * <code>subdirectoryAndFilename</code>. If there isn't any value - * associated with the name then <code>null - * </code> is returned. - * - * This method is convenience and only intended for use by the workbench - * because it explicitly uses the workbench's registry for - * caching/retrieving images from other extensions -- other plugins must - * user their own registry. This convenience method is subject to removal. - * - * Note: subdirectoryAndFilename must not have any leading "." or path - * separators / or \ ISV's should use icons/mysample.gif and not - * ./icons/mysample.gif - * - * Note: This consults the plugin for extension and obtains its - * installation location. all requested images are assumed to be in a - * directory below and relative to that plugins installation directory. - */ - public static ImageDescriptor getImageDescriptorFromExtension(IExtension extension, String subdirectoryAndFilename) { - String pluginId = extension.getNamespace(); - Bundle bundle = Platform.getBundle(pluginId); - return getImageDescriptorFromBundle(bundle, subdirectoryAndFilename); - } - - /** - * Convenience Method. Return an ImageDescriptor whose path relative to - * the plugin described by <code>bundle</code> is - * <code>subdirectoryAndFilename</code>. Returns <code>null</code> if - * no image could be found. - * - * This method is convenience and only intended for use by the workbench - * because it explicitly uses the workbench's registry for - * caching/retrieving images from other extensions -- other plugins must - * user their own registry. This convenience method is subject to removal. - * - * Note: subdirectoryAndFilename must not have any leading "." or path - * separators / or \ ISV's should use icons/mysample.gif and not - * ./icons/mysample.gif - * - * Note: This consults the plugin for extension and obtains its - * installation location. all requested images are assumed to be in a - * directory below and relative to that plugins installation directory. - */ - public static ImageDescriptor getImageDescriptorFromBundle(Bundle bundle, String subdirectoryAndFilename) { - - URL path = bundle.getEntry("/"); //$NON-NLS-1$ - URL fullPathString = null; - try { - fullPathString = new URL(path, subdirectoryAndFilename); - return ImageDescriptor.createFromURL(fullPathString); - } catch (MalformedURLException e) { - } - return null; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/extension/RegistryReader.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/extension/RegistryReader.java deleted file mode 100644 index a36e8ba1dc..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/extension/RegistryReader.java +++ /dev/null @@ -1,176 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.extension; - - - -import org.eclipse.core.runtime.IConfigurationElement; -import org.eclipse.core.runtime.IExtension; -import org.eclipse.core.runtime.IExtensionPoint; -import org.eclipse.core.runtime.IExtensionRegistry; -import org.eclipse.core.runtime.IPluginRegistry; -import org.eclipse.wst.sse.ui.internal.Logger; -import org.eclipse.wst.sse.ui.internal.util.Sorter; - - -/** - * Template implementation of a registry reader that creates objects - * representing registry contents. Typically, an extension contains one - * element, but this reader handles multiple elements per extension. - * - * To start reading the extensions from the registry for an extension point, - * call the method <code>readRegistry</code>. - * - * To read children of an IConfigurationElement, call the method - * <code>readElementChildren</code> from your implementation of the method - * <code>readElement</code>, as it will not be done by default. - */ -public abstract class RegistryReader { - - - protected static final String TAG_DESCRIPTION = "description"; //$NON-NLS-1$ - - /** - * The constructor. - */ - protected RegistryReader() { - } - - /** - * This method extracts description as a subelement of the given element. - * - * @return description string if defined, or empty string if not. - */ - protected String getDescription(IConfigurationElement config) { - IConfigurationElement[] children = config.getChildren(TAG_DESCRIPTION); - if (children.length >= 1) { - return children[0].getValue(); - } - return ""; //$NON-NLS-1$ - } - - /** - * Logs the error in the workbench log using the provided text and the - * information in the configuration element. - */ - protected void logError(IConfigurationElement element, String text) { - IExtension extension = element.getDeclaringExtension(); - StringBuffer buf = new StringBuffer(); - buf.append("Plugin " + extension.getNamespace() + ", extension " + extension.getExtensionPointUniqueIdentifier()); //$NON-NLS-2$//$NON-NLS-1$ - buf.append("\n" + text); //$NON-NLS-1$ - Logger.log(Logger.ERROR, buf.toString()); - } - - /** - * Logs a very common registry error when a required attribute is missing. - */ - protected void logMissingAttribute(IConfigurationElement element, String attributeName) { - logError(element, "Required attribute '" + attributeName + "' not defined"); //$NON-NLS-2$//$NON-NLS-1$ - } - - /** - * Logs a registry error when the configuration element is unknown. - */ - protected void logUnknownElement(IConfigurationElement element) { - logError(element, "Unknown extension tag found: " + element.getName()); //$NON-NLS-1$ - } - - /** - * Apply a reproducable order to the list of extensions provided, such - * that the order will not change as extensions are added or removed. - */ - protected IExtension[] orderExtensions(IExtension[] extensions) { - // By default, the order is based on plugin id sorted - // in ascending order. The order for a plugin providing - // more than one extension for an extension point is - // dependent in the order listed in the XML file. - Sorter sorter = new Sorter() { - public boolean compare(Object extension1, Object extension2) { - String s1 = ((IExtension) extension1).getNamespace().toUpperCase(); - String s2 = ((IExtension) extension2).getNamespace().toUpperCase(); - //Return true if elementTwo is 'greater than' elementOne - return s2.compareTo(s1) > 0; - } - }; - - Object[] sorted = sorter.sort(extensions); - IExtension[] sortedExtension = new IExtension[sorted.length]; - System.arraycopy(sorted, 0, sortedExtension, 0, sorted.length); - return sortedExtension; - } - - /** - * Implement this method to read element's attributes. If children should - * also be read, then implementor is responsible for calling - * <code>readElementChildren</code>. Implementor is also responsible - * for logging missing attributes. - * - * @return true if element was recognized, false if not. - */ - protected abstract boolean readElement(IConfigurationElement element); - - /** - * Read the element's children. This is called by the subclass' - * readElement method when it wants to read the children of the element. - */ - protected void readElementChildren(IConfigurationElement element) { - readElements(element.getChildren()); - } - - /** - * Read each element one at a time by calling the subclass implementation - * of <code>readElement</code>. - * - * Logs an error if the element was not recognized. - */ - protected void readElements(IConfigurationElement[] elements) { - for (int i = 0; i < elements.length; i++) { - if (!readElement(elements[i])) - logUnknownElement(elements[i]); - } - } - - /** - * Read one extension by looping through its configuration elements. - */ - protected void readExtension(IExtension extension) { - readElements(extension.getConfigurationElements()); - } - - /** - * @deprecated use readRegistry(IExtensionRegistry registry, String pluginId, String extensionPoint) - */ - protected void readRegistry(IPluginRegistry registry, String pluginId, String extensionPoint) { - IExtensionPoint point = registry.getExtensionPoint(pluginId, extensionPoint); - if (point != null) { - IExtension[] extensions = point.getExtensions(); - extensions = orderExtensions(extensions); - for (int i = 0; i < extensions.length; i++) - readExtension(extensions[i]); - } - } - - /** - * Start the registry reading process using the supplied plugin ID and - * extension point. - */ - protected void readRegistry(IExtensionRegistry registry, String pluginId, String extensionPoint) { - IExtensionPoint point = registry.getExtensionPoint(pluginId, extensionPoint); - if (point != null) { - IExtension[] extensions = point.getExtensions(); - extensions = orderExtensions(extensions); - for (int i = 0; i < extensions.length; i++) - readExtension(extensions[i]); - } - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/filter/OutlineCustomFiltersDialog.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/filter/OutlineCustomFiltersDialog.java deleted file mode 100644 index 714c68010e..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/filter/OutlineCustomFiltersDialog.java +++ /dev/null @@ -1,417 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.filter; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; -import java.util.Stack; -import java.util.StringTokenizer; - -import org.eclipse.core.runtime.Assert; -import org.eclipse.jface.dialogs.IDialogConstants; -import org.eclipse.jface.viewers.ArrayContentProvider; -import org.eclipse.jface.viewers.CheckStateChangedEvent; -import org.eclipse.jface.viewers.CheckboxTableViewer; -import org.eclipse.jface.viewers.ICheckStateListener; -import org.eclipse.jface.viewers.ILabelProvider; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.ISelectionChangedListener; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.viewers.LabelProvider; -import org.eclipse.jface.viewers.SelectionChangedEvent; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.events.SelectionListener; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.swt.widgets.Text; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.dialogs.SelectionDialog; -import org.eclipse.wst.sse.ui.internal.SSEUIPlugin; -import org.eclipse.wst.sse.ui.internal.util.SWTUtil; - - -public class OutlineCustomFiltersDialog extends SelectionDialog { - - private static final String SEPARATOR= ","; //$NON-NLS-1$ - - private String fViewId; - private boolean fEnablePatterns; - private String[] fPatterns; - private String[] fEnabledFilterIds; - - private OutlineFilterDescriptor[] fBuiltInFilters; - - private CheckboxTableViewer fCheckBoxList; - private Button fEnableUserDefinedPatterns; - private Text fUserDefinedPatterns; - - private Stack fFilterDescriptorChangeHistory; - - - /** - * Creates a dialog to customize Java element filters. - * - * @param shell the parent shell - * @param viewId the id of the view - * @param enablePatterns <code>true</code> if pattern filters are enabled - * @param patterns the filter patterns - * @param enabledFilterIds the Ids of the enabled filters - */ - public OutlineCustomFiltersDialog( - Shell shell, - String viewId, - boolean enablePatterns, - String[] patterns, - String[] enabledFilterIds) { - - super(shell); - Assert.isNotNull(viewId); - Assert.isNotNull(patterns); - Assert.isNotNull(enabledFilterIds); - - fViewId= viewId; - fPatterns= patterns; - fEnablePatterns= enablePatterns; - fEnabledFilterIds= enabledFilterIds; - - fBuiltInFilters= OutlineFilterDescriptor.getFilterDescriptors(fViewId); - fFilterDescriptorChangeHistory= new Stack(); - } - public static final String CUSTOM_FILTERS_DIALOG= SSEUIPlugin.ID + "." + "open_custom_filters_dialog_context"; //$NON-NLS-1$ - protected void configureShell(Shell shell) { - setTitle(OutlineFilterMessages.CustomFiltersDialog_title); - setMessage(OutlineFilterMessages.CustomFiltersDialog_filterList_label); - super.configureShell(shell); - PlatformUI.getWorkbench().getHelpSystem().setHelp(shell, CUSTOM_FILTERS_DIALOG); - } - - /** - * Overrides method in Dialog - * - * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(Composite) - */ - protected Control createDialogArea(Composite parent) { - initializeDialogUnits(parent); - // create a composite with standard margins and spacing - Composite composite= new Composite(parent, SWT.NONE); - GridLayout layout= new GridLayout(); - layout.marginHeight= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); - layout.marginWidth= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); - layout.verticalSpacing= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING); - layout.horizontalSpacing= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); - composite.setLayout(layout); - composite.setLayoutData(new GridData(GridData.FILL_BOTH)); - composite.setFont(parent.getFont()); - Composite group= composite; - - // Checkbox - fEnableUserDefinedPatterns= new Button(group, SWT.CHECK); - fEnableUserDefinedPatterns.setFocus(); - fEnableUserDefinedPatterns.setText(OutlineFilterMessages.CustomFiltersDialog_enableUserDefinedPattern); - - // Pattern field - fUserDefinedPatterns= new Text(group, SWT.SINGLE | SWT.BORDER); - GridData data= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL); - data.widthHint= convertWidthInCharsToPixels(59); - fUserDefinedPatterns.setLayoutData(data); - String patterns= convertToString(fPatterns, SEPARATOR); - fUserDefinedPatterns.setText(patterns); - SWTUtil.setAccessibilityText(fUserDefinedPatterns, OutlineFilterMessages.CustomFiltersDialog_name_filter_pattern_description); - - // Info text - final Label info= new Label(group, SWT.LEFT); - info.setText(OutlineFilterMessages.CustomFiltersDialog_patternInfo); - - // Enabling / disabling of pattern group - fEnableUserDefinedPatterns.setSelection(fEnablePatterns); - fUserDefinedPatterns.setEnabled(fEnablePatterns); - info.setEnabled(fEnablePatterns); - fEnableUserDefinedPatterns.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent e) { - boolean state= fEnableUserDefinedPatterns.getSelection(); - fUserDefinedPatterns.setEnabled(state); - info.setEnabled(fEnableUserDefinedPatterns.getSelection()); - if (state) - fUserDefinedPatterns.setFocus(); - } - }); - - // Filters provided by extension point - if (fBuiltInFilters.length > 0) - createCheckBoxList(group); - - applyDialogFont(parent); - return parent; - } - - private void createCheckBoxList(Composite parent) { - // Filler - new Label(parent, SWT.NONE); - - Label info= new Label(parent, SWT.LEFT); - info.setText(OutlineFilterMessages.CustomFiltersDialog_filterList_label); - - fCheckBoxList= CheckboxTableViewer.newCheckList(parent, SWT.BORDER); - GridData data= new GridData(GridData.FILL_BOTH); - data.heightHint= fCheckBoxList.getTable().getItemHeight() * 10; - fCheckBoxList.getTable().setLayoutData(data); - - fCheckBoxList.setLabelProvider(createLabelPrivder()); - fCheckBoxList.setContentProvider(new ArrayContentProvider()); - Arrays.sort(fBuiltInFilters); - fCheckBoxList.setInput(fBuiltInFilters); - setInitialSelections(getEnabledFilterDescriptors()); - - List initialSelection= getInitialElementSelections(); - if (initialSelection != null && !initialSelection.isEmpty()) - checkInitialSelections(); - - // Description - info= new Label(parent, SWT.LEFT); - info.setText(OutlineFilterMessages.CustomFiltersDialog_description_label); - final Text description= new Text(parent, SWT.LEFT | SWT.WRAP | SWT.MULTI | SWT.READ_ONLY | SWT.BORDER | SWT.V_SCROLL); - data = new GridData(GridData.FILL_HORIZONTAL); - data.heightHint= convertHeightInCharsToPixels(3); - description.setLayoutData(data); - fCheckBoxList.addSelectionChangedListener(new ISelectionChangedListener() { - public void selectionChanged(SelectionChangedEvent event) { - ISelection selection= event.getSelection(); - if (selection instanceof IStructuredSelection) { - Object selectedElement= ((IStructuredSelection)selection).getFirstElement(); - if (selectedElement instanceof OutlineFilterDescriptor) - description.setText(((OutlineFilterDescriptor)selectedElement).getDescription()); - } - } - }); - fCheckBoxList.addCheckStateListener(new ICheckStateListener() { - /* - * @see org.eclipse.jface.viewers.ICheckStateListener#checkStateChanged(org.eclipse.jface.viewers.CheckStateChangedEvent) - */ - public void checkStateChanged(CheckStateChangedEvent event) { - Object element= event.getElement(); - if (element instanceof OutlineFilterDescriptor) { - // renew if already touched - if (fFilterDescriptorChangeHistory.contains(element)) - fFilterDescriptorChangeHistory.remove(element); - fFilterDescriptorChangeHistory.push(element); - } - }}); - - addSelectionButtons(parent); - } - - private void addSelectionButtons(Composite composite) { - Composite buttonComposite= new Composite(composite, SWT.RIGHT); - GridLayout layout= new GridLayout(); - layout.numColumns= 2; - buttonComposite.setLayout(layout); - GridData data= new GridData(GridData.HORIZONTAL_ALIGN_END | GridData.GRAB_HORIZONTAL); - data.grabExcessHorizontalSpace= true; - composite.setData(data); - - // Select All button - String label= OutlineFilterMessages.CustomFiltersDialog_SelectAllButton_label; - Button selectButton= createButton(buttonComposite, IDialogConstants.SELECT_ALL_ID, label, false); - SWTUtil.setButtonDimensionHint(selectButton); - SelectionListener listener= new SelectionAdapter() { - public void widgetSelected(SelectionEvent e) { - fCheckBoxList.setAllChecked(true); - fFilterDescriptorChangeHistory.clear(); - for (int i= 0; i < fBuiltInFilters.length; i++) - fFilterDescriptorChangeHistory.push(fBuiltInFilters[i]); - } - }; - selectButton.addSelectionListener(listener); - - // De-select All button - label= OutlineFilterMessages.CustomFiltersDialog_DeselectAllButton_label; - Button deselectButton= createButton(buttonComposite, IDialogConstants.DESELECT_ALL_ID, label, false); - SWTUtil.setButtonDimensionHint(deselectButton); - listener= new SelectionAdapter() { - public void widgetSelected(SelectionEvent e) { - fCheckBoxList.setAllChecked(false); - fFilterDescriptorChangeHistory.clear(); - for (int i= 0; i < fBuiltInFilters.length; i++) - fFilterDescriptorChangeHistory.push(fBuiltInFilters[i]); - } - }; - deselectButton.addSelectionListener(listener); - } - - private void checkInitialSelections() { - Iterator itemsToCheck= getInitialElementSelections().iterator(); - while (itemsToCheck.hasNext()) - fCheckBoxList.setChecked(itemsToCheck.next(),true); - } - - protected void okPressed() { - if (fBuiltInFilters != null) { - ArrayList result= new ArrayList(); - for (int i= 0; i < fBuiltInFilters.length; ++i) { - if (fCheckBoxList.getChecked(fBuiltInFilters[i])) - result.add(fBuiltInFilters[i]); - } - setResult(result); - } - super.okPressed(); - } - - private ILabelProvider createLabelPrivder() { - return - new LabelProvider() { - public Image getImage(Object element) { - return null; - } - public String getText(Object element) { - if (element instanceof OutlineFilterDescriptor) - return ((OutlineFilterDescriptor)element).getName(); - else - return null; - } - }; - } - - // ---------- result handling ---------- - - protected void setResult(List newResult) { - super.setResult(newResult); - if (fUserDefinedPatterns.getText().length() > 0) { - fEnablePatterns= fEnableUserDefinedPatterns.getSelection(); - fPatterns= convertFromString(fUserDefinedPatterns.getText(), SEPARATOR); - } else { - fEnablePatterns= false; - fPatterns= new String[0]; - } - } - - - /** - * @return the patterns which have been entered by the user - */ - public String[] getUserDefinedPatterns() { - return fPatterns; - } - - /** - * @return the Ids of the enabled built-in filters - */ - public String[] getEnabledFilterIds() { - Object[] result= getResult(); - Set enabledIds= new HashSet(result.length); - for (int i= 0; i < result.length; i++) - enabledIds.add(((OutlineFilterDescriptor)result[i]).getId()); - return (String[]) enabledIds.toArray(new String[enabledIds.size()]); - } - - /** - * @return <code>true</code> if the user-defined patterns are disabled - */ - public boolean areUserDefinedPatternsEnabled() { - return fEnablePatterns; - } - - /** - * @return a stack with the filter descriptor check history - */ - public Stack getFilterDescriptorChangeHistory() { - return fFilterDescriptorChangeHistory; - } - - private OutlineFilterDescriptor[] getEnabledFilterDescriptors() { - OutlineFilterDescriptor[] filterDescs= fBuiltInFilters; - List result= new ArrayList(filterDescs.length); - List enabledFilterIds= Arrays.asList(fEnabledFilterIds); - for (int i= 0; i < filterDescs.length; i++) { - String id= filterDescs[i].getId(); - if (enabledFilterIds.contains(id)) - result.add(filterDescs[i]); - } - return (OutlineFilterDescriptor[])result.toArray(new OutlineFilterDescriptor[result.size()]); - } - - - public static String[] convertFromString(String patterns, String separator) { - StringTokenizer tokenizer= new StringTokenizer(patterns, separator, true); - int tokenCount= tokenizer.countTokens(); - List result= new ArrayList(tokenCount); - boolean escape= false; - boolean append= false; - while (tokenizer.hasMoreTokens()) { - String token= tokenizer.nextToken().trim(); - if (separator.equals(token)) { - if (!escape) - escape= true; - else { - addPattern(result, separator); - append= true; - } - } else { - if (!append) - result.add(token); - else - addPattern(result, token); - append= false; - escape= false; - } - } - return (String[])result.toArray(new String[result.size()]); - } - - private static void addPattern(List list, String pattern) { - if (list.isEmpty()) - list.add(pattern); - else { - int index= list.size() - 1; - list.set(index, ((String)list.get(index)) + pattern); - } - } - - public static String convertToString(String[] patterns, String separator) { - int length= patterns.length; - StringBuffer strBuf= new StringBuffer(); - if (length > 0) - strBuf.append(escapeSeparator(patterns[0], separator)); - else - return ""; //$NON-NLS-1$ - int i= 1; - while (i < length) { - strBuf.append(separator); - strBuf.append(" "); //$NON-NLS-1$ - strBuf.append(escapeSeparator(patterns[i++], separator)); - } - return strBuf.toString(); - } - - private static String escapeSeparator(String pattern, String separator) { - int length= pattern.length(); - StringBuffer buf= new StringBuffer(length); - for (int i= 0; i < length; i++) { - char ch= pattern.charAt(i); - if (separator.equals(String.valueOf(ch))) - buf.append(ch); - buf.append(ch); - } - return buf.toString(); - - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/filter/OutlineFilterDescriptor.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/filter/OutlineFilterDescriptor.java deleted file mode 100644 index fd6b24e21e..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/filter/OutlineFilterDescriptor.java +++ /dev/null @@ -1,277 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.filter; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import com.ibm.icu.text.Collator; - -import org.eclipse.core.runtime.Assert; -import org.eclipse.core.runtime.IConfigurationElement; -import org.eclipse.core.runtime.IExtensionRegistry; -import org.eclipse.core.runtime.ISafeRunnable; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.SafeRunner; - -import org.eclipse.jface.util.SafeRunnable; -import org.eclipse.jface.viewers.ViewerFilter; - -import org.eclipse.ui.IPluginContribution; -import org.eclipse.ui.activities.WorkbenchActivityHelper; -import org.eclipse.wst.sse.ui.internal.SSEUIPlugin; - - - -/** - * Represents a custom filter which is provided by the - * "org.eclipse.sse.ui.outlineFilters" extension point. - * - */ -public class OutlineFilterDescriptor implements Comparable, IPluginContribution { - - private static String PATTERN_FILTER_ID_PREFIX= "_patternFilterId_"; //$NON-NLS-1$ - - - private static final String EXTENSION_POINT_NAME= "outlineFilters"; //$NON-NLS-1$ - - private static final String FILTER_TAG= "filter"; //$NON-NLS-1$ - - private static final String PATTERN_ATTRIBUTE= "pattern"; //$NON-NLS-1$ - private static final String ID_ATTRIBUTE= "id"; //$NON-NLS-1$ - private static final String TARGET_ID_ATTRIBUTE= "targetId"; //$NON-NLS-1$ - private static final String CLASS_ATTRIBUTE= "class"; //$NON-NLS-1$ - private static final String NAME_ATTRIBUTE= "name"; //$NON-NLS-1$ - private static final String ENABLED_ATTRIBUTE= "enabled"; //$NON-NLS-1$ - private static final String DESCRIPTION_ATTRIBUTE= "description"; //$NON-NLS-1$ - - private static OutlineFilterDescriptor[] fgFilterDescriptors; - - - private IConfigurationElement fElement; - - /** - * Returns all contributed Java element filters. - * @return all contributed Java element filters - */ - public static OutlineFilterDescriptor[] getFilterDescriptors() { - if (fgFilterDescriptors == null) { - IExtensionRegistry registry= Platform.getExtensionRegistry(); - IConfigurationElement[] elements= registry.getConfigurationElementsFor(SSEUIPlugin.ID, EXTENSION_POINT_NAME); - fgFilterDescriptors= createFilterDescriptors(elements); - } - return fgFilterDescriptors; - } - /** - * Returns all Java element filters which - * are contributed to the given view. - * @param targetId the target id - * @return all contributed Java element filters for the given view - */ - public static OutlineFilterDescriptor[] getFilterDescriptors(String targetId) { - OutlineFilterDescriptor[] filterDescs= OutlineFilterDescriptor.getFilterDescriptors(); - List result= new ArrayList(filterDescs.length); - for (int i= 0; i < filterDescs.length; i++) { - String tid= filterDescs[i].getTargetId(); - if (WorkbenchActivityHelper.filterItem(filterDescs[i])) - continue; - if (tid == null || tid.equals(targetId)) - result.add(filterDescs[i]); - } - return (OutlineFilterDescriptor[])result.toArray(new OutlineFilterDescriptor[result.size()]); - } - - /** - * Creates a new filter descriptor for the given configuration element. - * @param element configuration element - */ - private OutlineFilterDescriptor(IConfigurationElement element) { - fElement= element; - // it is either a pattern filter or a custom filter - Assert.isTrue(isPatternFilter() ^ isCustomFilter(), "An extension for extension-point org.eclipse.sse.ui.outlineFilters does not specify a correct filter"); //$NON-NLS-1$ - Assert.isNotNull(getId(), "An extension for extension-point org.eclipse.sse.ui.outlineFilters does not provide a valid ID"); //$NON-NLS-1$ - Assert.isNotNull(getName(), "An extension for extension-point org.eclipse.sse.ui.outlineFilters does not provide a valid name"); //$NON-NLS-1$ - } - - /** - * Creates a new <code>ViewerFilter</code>. - * This method is only valid for viewer filters. - * @return a new <code>ViewerFilter</code> - */ - public ViewerFilter createViewerFilter() { - if (!isCustomFilter()) - return null; - - final ViewerFilter[] result= new ViewerFilter[1]; - String message = OutlineFilterMessages.FilterDescriptor_filterCreationError_message; - ISafeRunnable code= new SafeRunnable(message) { - /* - * @see org.eclipse.core.runtime.ISafeRunnable#run() - */ - public void run() throws Exception { - result[0]= (ViewerFilter)fElement.createExecutableExtension(CLASS_ATTRIBUTE); - } - - }; - SafeRunner.run(code); - return result[0]; - } - - //---- XML Attribute accessors --------------------------------------------- - - /** - * Returns the filter's id. - * <p> - * This attribute is mandatory for custom filters. - * The ID for pattern filters is - * PATTERN_FILTER_ID_PREFIX plus the pattern itself. - * </p> - * @return the filter id - */ - public String getId() { - if (isPatternFilter()) { - String targetId= getTargetId(); - if (targetId == null) - return PATTERN_FILTER_ID_PREFIX + getPattern(); - else - return targetId + PATTERN_FILTER_ID_PREFIX + getPattern(); - } else - return fElement.getAttribute(ID_ATTRIBUTE); - } - - /** - * Returns the filter's name. - * <p> - * If the name of a pattern filter is missing - * then the pattern is used as its name. - * </p> - * @return the filter's name - */ - public String getName() { - String name= fElement.getAttribute(NAME_ATTRIBUTE); - if (name == null && isPatternFilter()) - name= getPattern(); - return name; - } - - /** - * Returns the filter's pattern. - * - * @return the pattern string or <code>null</code> if it's not a pattern filter - */ - public String getPattern() { - return fElement.getAttribute(PATTERN_ATTRIBUTE); - } - - /** - * Returns the filter's viewId. - * - * @return the view ID or <code>null</code> if the filter is for all views - */ - public String getTargetId() { - String tid= fElement.getAttribute(TARGET_ID_ATTRIBUTE); - - if (tid != null) - return tid; - - // Backwards compatibility code - return null; - - } - - /** - * Returns the filter's description. - * - * @return the description or <code>null</code> if no description is provided - */ - public String getDescription() { - String description= fElement.getAttribute(DESCRIPTION_ATTRIBUTE); - if (description == null) - description= ""; //$NON-NLS-1$ - return description; - } - - /** - * @return <code>true</code> if this filter is a custom filter. - */ - public boolean isPatternFilter() { - return getPattern() != null; - } - - /** - * @return <code>true</code> if this filter is a pattern filter. - */ - public boolean isCustomFilter() { - return fElement.getAttribute(CLASS_ATTRIBUTE) != null; - } - - /** - * Returns <code>true</code> if the filter - * is initially enabled. - * - * This attribute is optional and defaults to <code>true</code>. - * @return returns <code>true</code> if the filter is initially enabled - */ - public boolean isEnabled() { - String strVal= fElement.getAttribute(ENABLED_ATTRIBUTE); - return strVal == null || Boolean.valueOf(strVal).booleanValue(); - } - - /* - * Implements a method from IComparable - */ - public int compareTo(Object o) { - if (o instanceof OutlineFilterDescriptor) - return Collator.getInstance().compare(getName(), ((OutlineFilterDescriptor)o).getName()); - else - return Integer.MIN_VALUE; - } - - //---- initialization --------------------------------------------------- - - /** - * Creates the filter descriptors. - * @param elements the configuration elements - * @return new filter descriptors - */ - private static OutlineFilterDescriptor[] createFilterDescriptors(IConfigurationElement[] elements) { - List result= new ArrayList(5); - Set descIds= new HashSet(5); - for (int i= 0; i < elements.length; i++) { - final IConfigurationElement element= elements[i]; - if (FILTER_TAG.equals(element.getName())) { - - final OutlineFilterDescriptor[] desc= new OutlineFilterDescriptor[1]; - SafeRunner.run(new SafeRunnable(OutlineFilterMessages.FilterDescriptor_filterDescriptionCreationError_message) { - public void run() throws Exception { - desc[0]= new OutlineFilterDescriptor(element); - } - }); - - if (desc[0] != null && !descIds.contains(desc[0].getId())) { - result.add(desc[0]); - descIds.add(desc[0].getId()); - } - } - } - return (OutlineFilterDescriptor[])result.toArray(new OutlineFilterDescriptor[result.size()]); - } - - public String getLocalId() { - return fElement.getAttribute(ID_ATTRIBUTE); - } - - public String getPluginId() { - return fElement.getContributor().getName(); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/filter/OutlineFilterMessages.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/filter/OutlineFilterMessages.java deleted file mode 100644 index 9926e00e12..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/filter/OutlineFilterMessages.java +++ /dev/null @@ -1,38 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.filter; - -import org.eclipse.osgi.util.NLS; - -public final class OutlineFilterMessages extends NLS { - - private static final String BUNDLE_NAME= "org.eclipse.wst.sse.ui.internal.filter.OutlineFilterMessages";//$NON-NLS-1$ - - private OutlineFilterMessages() { - // Do not instantiate - } - - public static String CustomFiltersDialog_title; - public static String CustomFiltersDialog_patternInfo; - public static String CustomFiltersDialog_enableUserDefinedPattern; - public static String CustomFiltersDialog_filterList_label; - public static String CustomFiltersDialog_description_label; - public static String CustomFiltersDialog_SelectAllButton_label; - public static String CustomFiltersDialog_DeselectAllButton_label; - public static String CustomFiltersDialog_name_filter_pattern_description; - public static String OpenCustomFiltersDialogAction_text; - public static String FilterDescriptor_filterDescriptionCreationError_message; - public static String FilterDescriptor_filterCreationError_message; - - static { - NLS.initializeMessages(BUNDLE_NAME, OutlineFilterMessages.class); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/filter/OutlineFilterMessages.properties b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/filter/OutlineFilterMessages.properties deleted file mode 100644 index 9ebc024134..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/filter/OutlineFilterMessages.properties +++ /dev/null @@ -1,24 +0,0 @@ -############################################################################### -# Copyright (c) 2011 IBM Corporation and others. -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Eclipse Public License v1.0 -# which accompanies this distribution, and is available at -# http://www.eclipse.org/legal/epl-v10.html -# -# Contributors: -# IBM Corporation - initial API and implementation -############################################################################### - -CustomFiltersDialog_title= Outline Element Filters -CustomFiltersDialog_patternInfo= The patterns are separated by a comma, where\n* = any string, ? = any character, ,, = , -CustomFiltersDialog_enableUserDefinedPattern= &Name filter patterns (matching names will be hidden): -CustomFiltersDialog_filterList_label= S&elect the elements to exclude from the view: -CustomFiltersDialog_description_label= Filter description: -CustomFiltersDialog_SelectAllButton_label= &Select All -CustomFiltersDialog_DeselectAllButton_label= &Deselect All -CustomFiltersDialog_name_filter_pattern_description=Name filter patterns. The patterns are separated by a comma, where star is any string - -OpenCustomFiltersDialogAction_text= &Filters... - -FilterDescriptor_filterDescriptionCreationError_message= One of the extensions for extension-point org.eclipse.wst.sse.ui.outlineFilters is incorrect. -FilterDescriptor_filterCreationError_message= The org.eclipse.wst.sse.ui.outlineFilters plug-in extension "{0}" specifies a viewer filter class which does not exist. diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/filter/OutlineNamePatternFilter.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/filter/OutlineNamePatternFilter.java deleted file mode 100644 index 37ba7d5f48..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/filter/OutlineNamePatternFilter.java +++ /dev/null @@ -1,85 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.filter; - -import org.eclipse.jface.viewers.ContentViewer; -import org.eclipse.jface.viewers.IBaseLabelProvider; -import org.eclipse.jface.viewers.ILabelProvider; -import org.eclipse.jface.viewers.Viewer; -import org.eclipse.jface.viewers.ViewerFilter; - -/** - * The NamePatternFilter selects the elements which - * match the given string patterns. - * <p> - * The following characters have special meaning: - * ? => any character - * * => any string - * </p> - * - */ -public class OutlineNamePatternFilter extends ViewerFilter { - private String[] fPatterns; - private StringMatcher[] fMatchers; - - - /** - * Gets the patterns for the receiver. - * @return returns the patterns to be filtered for - */ - public String[] getPatterns() { - return fPatterns; - } - - - /* (non-Javadoc) - * Method declared on ViewerFilter. - */ - public boolean select(Viewer viewer, Object parentElement, Object element) { - if (getPatterns().length == 0) { - return true; - } - String matchName= null; - if (viewer instanceof ContentViewer){ - final IBaseLabelProvider labelProvider = ((ContentViewer) viewer).getLabelProvider(); - if (labelProvider instanceof ILabelProvider) { - matchName = ((ILabelProvider) labelProvider).getText(element); - } - } - if (matchName != null && matchName.length() > 0) { - String[] fPatterns = getPatterns(); - for (int i = 0; i < fPatterns.length; i++) { - if (new StringMatcher(fPatterns[i], true, false).match(matchName)) - return false; - } - return true; - } - return true; - } - - /** - * Sets the patterns to filter out for the receiver. - * <p> - * The following characters have special meaning: - * ? => any character - * * => any string - * </p> - * @param newPatterns the new patterns - */ - public void setPatterns(String[] newPatterns) { - fPatterns = newPatterns; - fMatchers = new StringMatcher[newPatterns.length]; - for (int i = 0; i < newPatterns.length; i++) { - //Reset the matchers to prevent constructor overhead - fMatchers[i]= new StringMatcher(newPatterns[i], true, false); - } - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/filter/StringMatcher.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/filter/StringMatcher.java deleted file mode 100644 index d7dfdd696e..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/filter/StringMatcher.java +++ /dev/null @@ -1,384 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.filter; - -import java.util.Vector; - -/** - * A string pattern matcher. Supports '*' and '?' wildcards. - */ -public class StringMatcher { - protected String fPattern; - protected int fLength; // pattern length - protected boolean fIgnoreWildCards; - protected boolean fIgnoreCase; - protected boolean fHasLeadingStar; - protected boolean fHasTrailingStar; - protected String fSegments[]; //the given pattern is split into * separated segments - - /* boundary value beyond which we don't need to search in the text */ - protected int fBound= 0; - - - protected static final char fSingleWildCard= '\u0000'; - - public static class Position { - int start; //inclusive - int end; //exclusive - public Position(int start, int end) { - this.start= start; - this.end= end; - } - public int getStart() { - return start; - } - public int getEnd() { - return end; - } - } - /** - * StringMatcher constructor takes in a String object that is a simple - * pattern. The pattern may contain '*' for 0 and many characters and - * '?' for exactly one character. - * - * Literal '*' and '?' characters must be escaped in the pattern - * e.g., "\*" means literal "*", etc. - * - * Escaping any other character (including the escape character itself), - * just results in that character in the pattern. - * e.g., "\a" means "a" and "\\" means "\" - * - * If invoking the StringMatcher with string literals in Java, don't forget - * escape characters are represented by "\\". - * - * @param pattern the pattern to match text against - * @param ignoreCase if true, case is ignored - * @param ignoreWildCards if true, wild cards and their escape sequences are ignored - * (everything is taken literally). - */ - public StringMatcher(String pattern, boolean ignoreCase, boolean ignoreWildCards) { - if (pattern == null) - throw new IllegalArgumentException(); - fIgnoreCase= ignoreCase; - fIgnoreWildCards= ignoreWildCards; - fPattern= pattern; - fLength= pattern.length(); - - if (fIgnoreWildCards) { - parseNoWildCards(); - } else { - parseWildCards(); - } - } - /** - * Find the first occurrence of the pattern between <code>start</code)(inclusive) - * and <code>end</code>(exclusive). - * @param text the String object to search in - * @param start the starting index of the search range, inclusive - * @param end the ending index of the search range, exclusive - * @return an <code>StringMatcher.Position</code> object that keeps the starting - * (inclusive) and ending positions (exclusive) of the first occurrence of the - * pattern in the specified range of the text; return null if not found or subtext - * is empty (start==end). A pair of zeros is returned if pattern is empty string - * Note that for pattern like "*abc*" with leading and trailing stars, position of "abc" - * is returned. For a pattern like"*??*" in text "abcdf", (1,3) is returned - */ - public StringMatcher.Position find(String text, int start, int end) { - if (text == null) - throw new IllegalArgumentException(); - - int tlen= text.length(); - if (start < 0) - start= 0; - if (end > tlen) - end= tlen; - if (end < 0 ||start >= end ) - return null; - if (fLength == 0) - return new Position(start, start); - if (fIgnoreWildCards) { - int x= posIn(text, start, end); - if (x < 0) - return null; - return new Position(x, x+fLength); - } - - int segCount= fSegments.length; - if (segCount == 0)//pattern contains only '*'(s) - return new Position (start, end); - - int curPos= start; - int matchStart= -1; - int i; - for (i= 0; i < segCount && curPos < end; ++i) { - String current= fSegments[i]; - int nextMatch= regExpPosIn(text, curPos, end, current); - if (nextMatch < 0 ) - return null; - if(i == 0) - matchStart= nextMatch; - curPos= nextMatch + current.length(); - } - if (i < segCount) - return null; - return new Position(matchStart, curPos); - } - /** - * match the given <code>text</code> with the pattern - * @return true if matched eitherwise false - * @param text a String object - */ - public boolean match(String text) { - return match(text, 0, text.length()); - } - /** - * Given the starting (inclusive) and the ending (exclusive) positions in the - * <code>text</code>, determine if the given substring matches with aPattern - * @return true if the specified portion of the text matches the pattern - * @param text a String object that contains the substring to match - * @param start marks the starting position (inclusive) of the substring - * @param end marks the ending index (exclusive) of the substring - */ - public boolean match(String text, int start, int end) { - if (null == text) - throw new IllegalArgumentException(); - - if (start > end) - return false; - - if (fIgnoreWildCards) - return (end - start == fLength) && fPattern.regionMatches(fIgnoreCase, 0, text, start, fLength); - int segCount= fSegments.length; - if (segCount == 0 && (fHasLeadingStar || fHasTrailingStar)) // pattern contains only '*'(s) - return true; - if (start == end) - return fLength == 0; - if (fLength == 0) - return start == end; - - int tlen= text.length(); - if (start < 0) - start= 0; - if (end > tlen) - end= tlen; - - int tCurPos= start; - int bound= end - fBound; - if ( bound < 0) - return false; - int i=0; - String current= fSegments[i]; - int segLength= current.length(); - - /* process first segment */ - if (!fHasLeadingStar){ - if(!regExpRegionMatches(text, start, current, 0, segLength)) { - return false; - } else { - ++i; - tCurPos= tCurPos + segLength; - } - } - if ((fSegments.length == 1) && (!fHasLeadingStar) && (!fHasTrailingStar)) { - // only one segment to match, no wildcards specified - return tCurPos == end; - } - /* process middle segments */ - while (i < segCount) { - current= fSegments[i]; - int currentMatch; - int k= current.indexOf(fSingleWildCard); - if (k < 0) { - currentMatch= textPosIn(text, tCurPos, end, current); - if (currentMatch < 0) - return false; - } else { - currentMatch= regExpPosIn(text, tCurPos, end, current); - if (currentMatch < 0) - return false; - } - tCurPos= currentMatch + current.length(); - i++; - } - - /* process final segment */ - if (!fHasTrailingStar && tCurPos != end) { - int clen= current.length(); - return regExpRegionMatches(text, end - clen, current, 0, clen); - } - return i == segCount ; - } - - /** - * This method parses the given pattern into segments seperated by wildcard '*' characters. - * Since wildcards are not being used in this case, the pattern consists of a single segment. - */ - private void parseNoWildCards() { - fSegments= new String[1]; - fSegments[0]= fPattern; - fBound= fLength; - } - /** - * Parses the given pattern into segments seperated by wildcard '*' characters. - */ - private void parseWildCards() { - if(fPattern.startsWith("*"))//$NON-NLS-1$ - fHasLeadingStar= true; - if(fPattern.endsWith("*")) {//$NON-NLS-1$ - /* make sure it's not an escaped wildcard */ - if (fLength > 1 && fPattern.charAt(fLength - 2) != '\\') { - fHasTrailingStar= true; - } - } - - Vector temp= new Vector(); - - int pos= 0; - StringBuffer buf= new StringBuffer(); - while (pos < fLength) { - char c= fPattern.charAt(pos++); - switch (c) { - case '\\': - if (pos >= fLength) { - buf.append(c); - } else { - char next= fPattern.charAt(pos++); - /* if it's an escape sequence */ - if (next == '*' || next == '?' || next == '\\') { - buf.append(next); - } else { - /* not an escape sequence, just insert literally */ - buf.append(c); - buf.append(next); - } - } - break; - case '*': - if (buf.length() > 0) { - /* new segment */ - temp.addElement(buf.toString()); - fBound += buf.length(); - buf.setLength(0); - } - break; - case '?': - /* append special character representing single match wildcard */ - buf.append(fSingleWildCard); - break; - default: - buf.append(c); - } - } - - /* add last buffer to segment list */ - if (buf.length() > 0) { - temp.addElement(buf.toString()); - fBound += buf.length(); - } - - fSegments= new String[temp.size()]; - temp.copyInto(fSegments); - } - /** - * @param text a string which contains no wildcard - * @param start the starting index in the text for search, inclusive - * @param end the stopping point of search, exclusive - * @return the starting index in the text of the pattern , or -1 if not found - */ - protected int posIn(String text, int start, int end) {//no wild card in pattern - int max= end - fLength; - - if (!fIgnoreCase) { - int i= text.indexOf(fPattern, start); - if (i == -1 || i > max) - return -1; - return i; - } - - for (int i= start; i <= max; ++i) { - if (text.regionMatches(true, i, fPattern, 0, fLength)) - return i; - } - - return -1; - } - /** - * @param text a simple regular expression that may only contain '?'(s) - * @param start the starting index in the text for search, inclusive - * @param end the stopping point of search, exclusive - * @param p a simple regular expression that may contains '?' - * @return the starting index in the text of the pattern , or -1 if not found - */ - protected int regExpPosIn(String text, int start, int end, String p) { - int plen= p.length(); - - int max= end - plen; - for (int i= start; i <= max; ++i) { - if (regExpRegionMatches(text, i, p, 0, plen)) - return i; - } - return -1; - } - - - protected boolean regExpRegionMatches(String text, int tStart, String p, int pStart, int plen) { - while (plen-- > 0) { - char tchar= text.charAt(tStart++); - char pchar= p.charAt(pStart++); - - /* process wild cards */ - if (!fIgnoreWildCards) { - /* skip single wild cards */ - if (pchar == fSingleWildCard) { - continue; - } - } - if (pchar == tchar) - continue; - if (fIgnoreCase) { - if (Character.toUpperCase(tchar) == Character.toUpperCase(pchar)) - continue; - // comparing after converting to upper case doesn't handle all cases; - // also compare after converting to lower case - if (Character.toLowerCase(tchar) == Character.toLowerCase(pchar)) - continue; - } - return false; - } - return true; - } - /** - * @param text the string to match - * @param start the starting index in the text for search, inclusive - * @param end the stopping point of search, exclusive - * @param p a string that has no wildcard - * @return the starting index in the text of the pattern , or -1 if not found - */ - protected int textPosIn(String text, int start, int end, String p) { - - int plen= p.length(); - int max= end - plen; - - if (!fIgnoreCase) { - int i= text.indexOf(p, start); - if (i == -1 || i > max) - return -1; - return i; - } - - for (int i= start; i <= max; ++i) { - if (text.regionMatches(true, i, p, 0, plen)) - return i; - } - - return -1; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/format/StructuredFormattingStrategy.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/format/StructuredFormattingStrategy.java deleted file mode 100644 index 40e5d7deca..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/format/StructuredFormattingStrategy.java +++ /dev/null @@ -1,91 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.format; - -import java.io.IOException; -import java.util.LinkedList; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.TypedPosition; -import org.eclipse.jface.text.formatter.ContextBasedFormattingStrategy; -import org.eclipse.jface.text.formatter.FormattingContextProperties; -import org.eclipse.jface.text.formatter.IFormattingContext; -import org.eclipse.wst.sse.core.internal.format.IStructuredFormatProcessor; -import org.eclipse.wst.sse.ui.internal.Logger; - - -public class StructuredFormattingStrategy extends ContextBasedFormattingStrategy { - - /** Documents to be formatted by this strategy */ - private final LinkedList fDocuments = new LinkedList(); - private IStructuredFormatProcessor fFormatProcessor; - /** Partitions to be formatted by this strategy */ - private final LinkedList fPartitions = new LinkedList(); - private IRegion fRegion; - - /** - * @param formatProcessor - */ - public StructuredFormattingStrategy(IStructuredFormatProcessor formatProcessor) { - super(); - - fFormatProcessor = formatProcessor; - } - - /* - * @see org.eclipse.jface.text.formatter.ContextBasedFormattingStrategy#format() - */ - public void format() { - super.format(); - - final IDocument document = (IDocument) fDocuments.removeFirst(); - final TypedPosition partition = (TypedPosition) fPartitions.removeFirst(); - - if (document != null && partition != null && fRegion != null && fFormatProcessor != null) { - try { - fFormatProcessor.formatDocument(document, fRegion.getOffset(), fRegion.getLength()); - } - catch (IOException e) { - // log for now, unless we find reason not to - Logger.log(Logger.INFO, e.getMessage()); - } - catch (CoreException e) { - // log for now, unless we find reason not to - Logger.log(Logger.INFO, e.getMessage()); - } - } - } - - /* - * @see org.eclipse.jface.text.formatter.ContextBasedFormattingStrategy#formatterStarts(org.eclipse.jface.text.formatter.IFormattingContext) - */ - public void formatterStarts(final IFormattingContext context) { - super.formatterStarts(context); - - fPartitions.addLast(context.getProperty(FormattingContextProperties.CONTEXT_PARTITION)); - fDocuments.addLast(context.getProperty(FormattingContextProperties.CONTEXT_MEDIUM)); - fRegion = (IRegion) context.getProperty(FormattingContextProperties.CONTEXT_REGION); - } - - /* - * @see org.eclipse.jface.text.formatter.ContextBasedFormattingStrategy#formatterStops() - */ - public void formatterStops() { - super.formatterStops(); - - fPartitions.clear(); - fDocuments.clear(); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/handlers/AbstractCommentHandler.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/handlers/AbstractCommentHandler.java deleted file mode 100644 index eab9187962..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/handlers/AbstractCommentHandler.java +++ /dev/null @@ -1,96 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.handlers; - -import org.eclipse.core.commands.AbstractHandler; -import org.eclipse.core.commands.ExecutionEvent; -import org.eclipse.core.commands.ExecutionException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.ITextSelection; -import org.eclipse.jface.text.TextSelection; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.ISelectionProvider; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.handlers.HandlerUtil; -import org.eclipse.ui.texteditor.ITextEditor; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument; - -/** - * This class contains all of the shared functionality for comment handlers - */ -public abstract class AbstractCommentHandler extends AbstractHandler { - - /** - * <p>Default constructor must exist because sub classes are created by java reflection</p> - */ - public AbstractCommentHandler() { - super(); - } - - /** - * <p>Gets the important information out of the event and passes it onto - * the internal method {@link #processAction}</p> - * - * @see org.eclipse.wst.xml.ui.internal.handlers.CommentHandler#execute(org.eclipse.core.commands.ExecutionEvent) - */ - public final Object execute(ExecutionEvent event) throws ExecutionException { - IEditorPart editor = HandlerUtil.getActiveEditor(event); - ITextEditor textEditor = null; - if (editor instanceof ITextEditor) - textEditor = (ITextEditor) editor; - else { - Object o = editor.getAdapter(ITextEditor.class); - if (o != null) - textEditor = (ITextEditor) o; - } - if (textEditor != null) { - IDocument document = textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput()); - if (document != null && document instanceof IStructuredDocument) { - // get current text selection - ITextSelection textSelection = getCurrentSelection(textEditor); - if (!textSelection.isEmpty()) { - //call the implementers code to deal with the event - processAction(textEditor, (IStructuredDocument)document, textSelection); - } - } - } - return null; - } - - /** - * <p>This method is called by the public {@link #execute} method whenever - * the comment handler is invoked. This method should be used for the - * logic of handling the structured comment event.</p> - * - * @param textEditor the text editor the initiating event was caused in - * @param document the document the text editor is editing - * @param textSelection the user selection when the event was caused - */ - protected abstract void processAction(ITextEditor textEditor, IStructuredDocument document, ITextSelection textSelection); - - /** - * <p>Gets the current user selection in the given {@link ITextEditor}</p> - * - * @param textEditor get the user selection from here - * @return the current user selection in <code>textEdtior</code> - */ - private static ITextSelection getCurrentSelection(ITextEditor textEditor) { - ISelectionProvider provider = textEditor.getSelectionProvider(); - if (provider != null) { - ISelection selection = provider.getSelection(); - if (selection instanceof ITextSelection) { - return (ITextSelection) selection; - } - } - return TextSelection.emptySelection(); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/handlers/AbstractStructuredSelectHandler.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/handlers/AbstractStructuredSelectHandler.java deleted file mode 100644 index 4579700cf3..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/handlers/AbstractStructuredSelectHandler.java +++ /dev/null @@ -1,106 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.handlers; - -import org.eclipse.core.commands.AbstractHandler; -import org.eclipse.core.commands.ExecutionEvent; -import org.eclipse.core.commands.ExecutionException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.ITextSelection; -import org.eclipse.jface.text.Region; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.handlers.HandlerUtil; -import org.eclipse.ui.texteditor.ITextEditor; -import org.eclipse.wst.sse.core.StructuredModelManager; -import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel; -import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion; -import org.eclipse.wst.sse.ui.internal.selection.SelectionHistory; - -abstract public class AbstractStructuredSelectHandler extends AbstractHandler { - - public Object execute(ExecutionEvent event) throws ExecutionException { - IEditorPart editor = HandlerUtil.getActiveEditor(event); - ITextEditor textEditor = null; - if (editor instanceof ITextEditor) - textEditor = (ITextEditor) editor; - else { - Object o = editor.getAdapter(ITextEditor.class); - if (o != null) - textEditor = (ITextEditor) o; - } - if (textEditor != null) { - ISelection selection = textEditor.getSelectionProvider().getSelection(); - IDocument document = textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput()); - // determine current text selection - if (selection instanceof ITextSelection && document != null) { - ITextSelection textSelection = (ITextSelection) selection; - - if (textSelection.getLength() < document.getLength()) { - // get current indexed region - IndexedRegion cursorIndexedRegion = getCursorIndexedRegion(document, textSelection); - - // determine new selection based on current indexed region - Region newSelectionRegion = getNewSelectionRegion(cursorIndexedRegion, textSelection); - - // select new selection - if (newSelectionRegion != null) { - SelectionHistory history = (SelectionHistory) editor.getAdapter(SelectionHistory.class); - if (history != null) { - history.remember(new Region(textSelection.getOffset(), textSelection.getLength())); - try { - history.ignoreSelectionChanges(); - textEditor.selectAndReveal(newSelectionRegion.getOffset(), newSelectionRegion.getLength()); - } - finally { - history.listenToSelectionChanges(); - } - } - } - } - } - } - return null; - } - - /** - * This method will probably be removed and replaced by using new - * selection provider - * - * @param document - * @param offset - * @return - */ - protected IndexedRegion getIndexedRegion(IDocument document, int offset) { - IndexedRegion indexedRegion = null; - - int lastOffset = offset; - IStructuredModel model = StructuredModelManager.getModelManager().getExistingModelForRead(document); - if (model != null) { - try { - indexedRegion = model.getIndexedRegion(lastOffset); - while (indexedRegion == null && lastOffset >= 0) { - lastOffset--; - indexedRegion = model.getIndexedRegion(lastOffset); - } - } - finally { - model.releaseFromRead(); - } - } - - return indexedRegion; - } - - abstract protected IndexedRegion getCursorIndexedRegion(IDocument document, ITextSelection textSelection); - - abstract protected Region getNewSelectionRegion(IndexedRegion indexedRegion, ITextSelection textSelection); -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/handlers/AddBlockCommentHandler.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/handlers/AddBlockCommentHandler.java deleted file mode 100644 index 97f999ebc3..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/handlers/AddBlockCommentHandler.java +++ /dev/null @@ -1,80 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.handlers; - -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.DocumentRewriteSession; -import org.eclipse.jface.text.DocumentRewriteSessionType; -import org.eclipse.jface.text.IDocumentExtension4; -import org.eclipse.jface.text.ITextSelection; -import org.eclipse.jface.text.ITypedRegion; -import org.eclipse.ui.texteditor.ITextEditor; -import org.eclipse.wst.sse.core.StructuredModelManager; -import org.eclipse.wst.sse.core.internal.Logger; -import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; -import org.eclipse.wst.sse.ui.internal.comment.CommentingStrategy; -import org.eclipse.wst.sse.ui.internal.comment.CommentingStrategyRegistry; - -/** - * <p>A comment handler to add block comments</p> - */ -public final class AddBlockCommentHandler extends - AbstractCommentHandler { - - /** - * @see org.eclipse.wst.sse.ui.internal.handlers.AbstractCommentHandler#processAction( - * org.eclipse.ui.texteditor.ITextEditor, org.eclipse.jface.text.IDocument, org.eclipse.jface.text.ITextSelection) - */ - protected void processAction(ITextEditor textEditor, IStructuredDocument document, ITextSelection textSelection) { - IStructuredModel model = null; - boolean changed = false; - DocumentRewriteSession session = null; - - try { - model = StructuredModelManager.getModelManager().getModelForEdit(document); - if(model != null) { - //makes it so one undo will undo all the edits to the document - model.beginRecording(this, SSEUIMessages.AddBlockComment_label, SSEUIMessages.AddBlockComment_description); - - //keeps listeners from doing anything until updates are all done - model.aboutToChangeModel(); - if(document instanceof IDocumentExtension4) { - session = ((IDocumentExtension4)document).startRewriteSession(DocumentRewriteSessionType.UNRESTRICTED); - } - changed = true; - - ITypedRegion[] typedRegions = document.computePartitioning(textSelection.getOffset(), textSelection.getLength()); - CommentingStrategy commentType = CommentingStrategyRegistry.getDefault().getBlockCommentingStrategy(model.getContentTypeIdentifier(), typedRegions); - - if(commentType != null) { - commentType.apply(document, textSelection.getOffset(), textSelection.getLength()); - } - } - } catch (BadLocationException e) { - Logger.logException("The given selection " + textSelection + " must be invalid", e); //$NON-NLS-1$ //$NON-NLS-2$ - } finally { - //clean everything up - if(session != null && document instanceof IDocumentExtension4) { - ((IDocumentExtension4)document).stopRewriteSession(session); - } - - if(model != null) { - model.endRecording(this); - if(changed) { - model.changedModel(); - } - model.releaseFromEdit(); - } - } - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/handlers/CustomFilterHandler.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/handlers/CustomFilterHandler.java deleted file mode 100644 index baaa020b0b..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/handlers/CustomFilterHandler.java +++ /dev/null @@ -1,32 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.handlers; - -import org.eclipse.core.commands.AbstractHandler; -import org.eclipse.core.commands.ExecutionEvent; -import org.eclipse.core.commands.ExecutionException; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.handlers.HandlerUtil; -import org.eclipse.ui.views.contentoutline.IContentOutlinePage; -import org.eclipse.wst.sse.ui.internal.contentoutline.ConfigurableContentOutlinePage; - -public class CustomFilterHandler extends AbstractHandler { - public Object execute(ExecutionEvent event) throws ExecutionException { - - IEditorPart editor = HandlerUtil.getActiveEditor(event); - ConfigurableContentOutlinePage page = (ConfigurableContentOutlinePage) editor.getAdapter(IContentOutlinePage.class); - if (page != null) { - page.getOutlineFilterProcessor().openDialog(); - } - return null; - } - -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/handlers/FindOccurrencesHandler.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/handlers/FindOccurrencesHandler.java deleted file mode 100644 index e8a5add803..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/handlers/FindOccurrencesHandler.java +++ /dev/null @@ -1,140 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.handlers; - -import java.util.Iterator; -import java.util.List; - -import org.eclipse.core.commands.AbstractHandler; -import org.eclipse.core.commands.ExecutionEvent; -import org.eclipse.core.commands.ExecutionException; -import org.eclipse.core.resources.IFile; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.ITextSelection; -import org.eclipse.jface.text.ITypedRegion; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.IFileEditorInput; -import org.eclipse.ui.handlers.HandlerUtil; -import org.eclipse.ui.texteditor.ITextEditor; -import org.eclipse.wst.sse.ui.StructuredTextEditor; -import org.eclipse.wst.sse.ui.internal.ExtendedConfigurationBuilder; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; -import org.eclipse.wst.sse.ui.internal.search.FindOccurrencesProcessor; -import org.eclipse.wst.sse.ui.internal.util.PlatformStatusLineUtil; - -public abstract class FindOccurrencesHandler extends AbstractHandler { - - public Object execute(ExecutionEvent event) throws ExecutionException { - IEditorPart editorPart = HandlerUtil.getActiveEditor(event); - ITextEditor textEditor = null; - if (editorPart instanceof ITextEditor) - textEditor = (ITextEditor) editorPart; - else { - Object o = editorPart.getAdapter(ITextEditor.class); - if (o != null) - textEditor = (ITextEditor) o; - } - boolean okay = false; - if (textEditor != null) { - IDocument document = textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput()); - if (document != null) { - ITextSelection textSelection = getTextSelection(textEditor); - FindOccurrencesProcessor findOccurrenceProcessor = getProcessorForCurrentSelection(document, textSelection); - if (findOccurrenceProcessor != null) { - if (textEditor.getEditorInput() instanceof IFileEditorInput) { - IFile file = ((IFileEditorInput) textEditor.getEditorInput()).getFile(); - okay = findOccurrenceProcessor.findOccurrences(document, textSelection, file); - } - } - } - } - if (okay) { - // clear status message - PlatformStatusLineUtil.clearStatusLine(); - } - else { - String errorMessage = SSEUIMessages.FindOccurrencesActionProvider_0; //$NON-NLS-1$ - if (textEditor instanceof StructuredTextEditor) { - PlatformStatusLineUtil.displayTemporaryErrorMessage(((StructuredTextEditor) textEditor).getTextViewer(), errorMessage); - - } - else { - PlatformStatusLineUtil.displayErrorMessage(errorMessage); - PlatformStatusLineUtil.addOneTimeClearListener(); - } - } - return null; - } - - /** - * Get the appropriate find occurrences processor - * - * @param document - - * assumes not null - * @param textSelection - * @return - */ - private FindOccurrencesProcessor getProcessorForCurrentSelection(IDocument document, ITextSelection textSelection) { - // check if we have an action that's enabled on the current partition - ITypedRegion tr = getPartition(document, textSelection); - String partition = tr != null ? tr.getType() : ""; //$NON-NLS-1$ - - Iterator it = getProcessors().iterator(); - FindOccurrencesProcessor processor = null; - while (it.hasNext()) { - processor = (FindOccurrencesProcessor) it.next(); - // we just choose the first action that can handle the partition - if (processor.enabledForParitition(partition)) - return processor; - } - - List extendedFindOccurrencesProcessors = ExtendedConfigurationBuilder.getInstance().getConfigurations(FindOccurrencesProcessor.class.getName(), partition); - for (int i = 0; i < extendedFindOccurrencesProcessors.size(); i++) { - Object o = extendedFindOccurrencesProcessors.get(i); - if (o instanceof FindOccurrencesProcessor) { - /* - * We just choose the first registered processor that - * explicitly says it can handle the partition - */ - processor = (FindOccurrencesProcessor) o; - if (processor.enabledForParitition(partition)) - return processor; - } - } - return null; - } - - private ITypedRegion getPartition(IDocument document, ITextSelection textSelection) { - ITypedRegion region = null; - if (textSelection != null) { - try { - region = document.getPartition(textSelection.getOffset()); - } - catch (BadLocationException e) { - region = null; - } - } - return region; - } - - private ITextSelection getTextSelection(ITextEditor textEditor) { - ITextSelection textSelection = null; - ISelection selection = textEditor.getSelectionProvider().getSelection(); - if (selection instanceof ITextSelection && !selection.isEmpty()) { - textSelection = (ITextSelection) selection; - } - return textSelection; - } - - abstract protected List getProcessors(); -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/handlers/FormatHandler.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/handlers/FormatHandler.java deleted file mode 100644 index 6b1b815528..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/handlers/FormatHandler.java +++ /dev/null @@ -1,326 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008 Standards for Technology in Automotive Retail and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * David Carver - initial API and implementation - bug 212330 - - * Based off FormatActionDelegate.java - *******************************************************************************/ - -package org.eclipse.wst.sse.ui.internal.handlers; - -import java.io.IOException; - -import org.eclipse.core.commands.AbstractHandler; -import org.eclipse.core.commands.ExecutionEvent; -import org.eclipse.core.commands.ExecutionException; -import org.eclipse.core.commands.IHandler; -import org.eclipse.core.filebuffers.FileBuffers; -import org.eclipse.core.filebuffers.ITextFileBuffer; -import org.eclipse.core.filebuffers.ITextFileBufferManager; -import org.eclipse.core.filebuffers.LocationKind; -import org.eclipse.core.resources.IContainer; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.MultiStatus; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.SubProgressMonitor; -import org.eclipse.core.runtime.content.IContentDescription; -import org.eclipse.core.runtime.content.IContentType; -import org.eclipse.core.runtime.jobs.Job; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.osgi.util.NLS; -import org.eclipse.swt.widgets.Display; -import org.eclipse.ui.IWorkbenchPage; -import org.eclipse.ui.IWorkbenchPart; -import org.eclipse.ui.IWorkbenchWindow; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.handlers.HandlerUtil; -import org.eclipse.ui.progress.IWorkbenchSiteProgressService; -import org.eclipse.wst.sse.core.internal.exceptions.MalformedInputExceptionWithDetail; -import org.eclipse.wst.sse.core.internal.format.IStructuredFormatProcessor; -import org.eclipse.wst.sse.ui.internal.FormatProcessorsExtensionReader; -import org.eclipse.wst.sse.ui.internal.Logger; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; -import org.eclipse.wst.sse.ui.internal.SSEUIPlugin; - -public class FormatHandler extends AbstractHandler implements IHandler { - - protected IStructuredSelection fSelection; - - public void dispose() { - // nulling out just in case - } - - private IWorkbenchSiteProgressService getActiveProgressService() { - IWorkbenchSiteProgressService service = null; - if (PlatformUI.isWorkbenchRunning()) { - IWorkbenchWindow activeWorkbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); - if (activeWorkbenchWindow != null) { - IWorkbenchPage activePage = activeWorkbenchWindow.getActivePage(); - if (activePage != null) { - IWorkbenchPart activePart = activePage.getActivePart(); - if (activePart != null) { - service = (IWorkbenchSiteProgressService) activePart.getSite().getAdapter(IWorkbenchSiteProgressService.class); - } - } - } - } - return service; - } - - - - - public Object execute(ExecutionEvent event) throws ExecutionException { - - ISelection selection = HandlerUtil.getActiveWorkbenchWindow(event).getSelectionService().getSelection(); - - if (selection instanceof IStructuredSelection) { - fSelection = (IStructuredSelection) selection; - boolean available = false; - - Object[] elements = fSelection.toArray(); - for (int i = 0; i < elements.length; i++) { - if (elements[i] instanceof IResource) { - available = processorAvailable((IResource) elements[i]); - - if (available) - break; - } - } - } - - if (fSelection != null && !fSelection.isEmpty()) { - Job job = getJob(); - if (job != null) { - IWorkbenchSiteProgressService progressService = getActiveProgressService(); - if (progressService != null) { - progressService.schedule(job); - } - else { - job.schedule(); - } - } - } - - return null; - } - - - class FormatJob extends Job { - - public FormatJob(String name) { - super(name); - } - - protected IStatus run(IProgressMonitor monitor) { - IStatus status = Status.OK_STATUS; - - Object[] elements = fSelection.toArray(); - monitor.beginTask("", elements.length); //$NON-NLS-1$ - for (int i = 0; i < elements.length; i++) { - if (elements[i] instanceof IResource) { - process(new SubProgressMonitor(monitor, 1), (IResource) elements[i]); - } - else { - monitor.worked(1); - } - } - monitor.done(); - - if (fErrorStatus.getChildren().length > 0) { - status = fErrorStatus; - fErrorStatus = new MultiStatus(SSEUIPlugin.ID, IStatus.ERROR, SSEUIMessages.FormatActionDelegate_errorStatusMessage, null); //$NON-NLS-1$ - } - - return status; - } - - } - - private MultiStatus fErrorStatus = new MultiStatus(SSEUIPlugin.ID, IStatus.ERROR, SSEUIMessages.FormatActionDelegate_errorStatusMessage, null); //$NON-NLS-1$ - - protected void format(IProgressMonitor monitor, IFile file) { - if(monitor == null || monitor.isCanceled()) - return; - - try { - monitor.beginTask("", 100); - IContentDescription contentDescription = file.getContentDescription(); - monitor.worked(5); - if (contentDescription != null) { - IContentType contentType = contentDescription.getContentType(); - IStructuredFormatProcessor formatProcessor = getFormatProcessor(contentType.getId()); - if (formatProcessor != null && (monitor == null || !monitor.isCanceled())) { - String message = NLS.bind(SSEUIMessages.FormatActionDelegate_3, new String[]{file.getFullPath().toString().substring(1)}); monitor.subTask(message); - formatProcessor.setProgressMonitor(new SubProgressMonitor(monitor, 95)); - formatProcessor.formatFile(file); - } - } - monitor.done(); - } catch (MalformedInputExceptionWithDetail e) { - String message = NLS.bind(SSEUIMessages.FormatActionDelegate_5, new String[]{file.getFullPath().toString()}); - fErrorStatus.add(new Status(IStatus.ERROR, SSEUIPlugin.ID, IStatus.ERROR, message, e)); - } catch (IOException e) { - String message = NLS.bind(SSEUIMessages.FormatActionDelegate_4, new String[]{file.getFullPath().toString()}); - fErrorStatus.add(new Status(IStatus.ERROR, SSEUIPlugin.ID, IStatus.ERROR, message, e)); - } catch (CoreException e) { - String message = NLS.bind(SSEUIMessages.FormatActionDelegate_4, new String[]{file.getFullPath().toString()}); - fErrorStatus.add(new Status(IStatus.ERROR, SSEUIPlugin.ID, IStatus.ERROR, message, e)); - } - } - - protected void format(final IProgressMonitor monitor, IResource resource) { - if (resource instanceof IFile) { - final IFile file = (IFile) resource; - - // BUG 178598 - If the resource is shared, and it's possible to - // get the workbench Display, the UI thread is asked to execute the - // format of the file when it can - monitor.beginTask("", 20); //$NON-NLS-1$ - try { - ITextFileBufferManager manager= FileBuffers.getTextFileBufferManager(); - ITextFileBuffer buffer = null; - - try { - if(manager != null) { - manager.connect(file.getFullPath(), LocationKind.IFILE, new SubProgressMonitor(monitor, 1)); - buffer = manager.getTextFileBuffer(resource.getFullPath(), LocationKind.IFILE); - } - - if(buffer != null && buffer.isShared()) { - Display display = getDisplay(); - if (display != null) { - display.syncExec(new Runnable() { - public void run() { - format(new SubProgressMonitor(monitor, 18), file); - } - }); - } - } - else - format(new SubProgressMonitor(monitor, 18), file); - } - finally { - if(manager != null) - manager.disconnect(file.getFullPath(), LocationKind.IFILE, new SubProgressMonitor(monitor, 1)); - } - monitor.done(); - } - catch(CoreException e) { - String message = NLS.bind(SSEUIMessages.FormatActionDelegate_4, new String[]{file.getFullPath().toString()}); - fErrorStatus.add(new Status(IStatus.ERROR, SSEUIPlugin.ID, IStatus.ERROR, message, e)); - } - finally { - if(monitor != null) - monitor.done(); - } - - - } else if (resource instanceof IContainer) { - IContainer container = (IContainer) resource; - - try { - IResource[] members = container.members(); - monitor.beginTask("", members.length); //$NON-NLS-1$ - for (int i = 0; i < members.length; i++) { - if (monitor != null && !monitor.isCanceled()) - format(new SubProgressMonitor(monitor, 1), members[i]); - } - monitor.done(); - } catch (CoreException e) { - String message = NLS.bind(SSEUIMessages.FormatActionDelegate_4, new String[]{resource.getFullPath().toString()}); - fErrorStatus.add(new Status(IStatus.ERROR, SSEUIPlugin.ID, IStatus.ERROR, message, e)); - } - } - } - - private Display getDisplay() { - - // Note: the workbench should always have a display - // (unless running headless), whereas Display.getCurrent() - // only returns the display if the currently executing thread - // has one. - if (PlatformUI.isWorkbenchRunning()) - return PlatformUI.getWorkbench().getDisplay(); - else - return null; - } - - protected IStructuredFormatProcessor getFormatProcessor(String contentTypeId) { - return FormatProcessorsExtensionReader.getInstance().getFormatProcessor(contentTypeId); - } - - protected Job getJob() { - return new FormatJob(SSEUIMessages.FormatActionDelegate_jobName); //$NON-NLS-1$ - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.sse.ui.edit.util.ResourceActionDelegate#process(org.eclipse.core.runtime.IProgressMonitor, - * org.eclipse.core.resources.IResource) - */ - protected void process(IProgressMonitor monitor, IResource resource) { - monitor.beginTask("", 100); - format(new SubProgressMonitor(monitor, 98), resource); - - try { - resource.refreshLocal(IResource.DEPTH_INFINITE, new SubProgressMonitor(monitor, 2)); - } catch (CoreException e) { - String message = NLS.bind(SSEUIMessages.FormatActionDelegate_4, new String[]{resource.getFullPath().toString()}); - fErrorStatus.add(new Status(IStatus.ERROR, SSEUIPlugin.ID, IStatus.ERROR, message, e)); - } - monitor.done(); - } - - /* (non-Javadoc) - * @see org.eclipse.wst.sse.ui.internal.actions.ResourceActionDelegate#processorAvailable(org.eclipse.core.resources.IResource) - */ - protected boolean processorAvailable(IResource resource) { - boolean result = false; - if (resource.isAccessible()) { - try { - if (resource instanceof IFile) { - IFile file = (IFile) resource; - - IStructuredFormatProcessor formatProcessor = null; - IContentDescription contentDescription = file.getContentDescription(); - if (contentDescription != null) { - IContentType contentType = contentDescription.getContentType(); - formatProcessor = getFormatProcessor(contentType.getId()); - } - if (formatProcessor != null) - result = true; - } - else if (resource instanceof IContainer) { - IContainer container = (IContainer) resource; - IResource[] members; - members = container.members(); - for (int i = 0; i < members.length; i++) { - boolean available = processorAvailable(members[i]); - - if (available) { - result = true; - break; - } - } - } - } - catch (CoreException e) { - Logger.logException(e); - } - } - - return result; - } - -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/handlers/RemoveBlockCommentHandler.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/handlers/RemoveBlockCommentHandler.java deleted file mode 100644 index 5cf0beb99b..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/handlers/RemoveBlockCommentHandler.java +++ /dev/null @@ -1,84 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.handlers; - -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.DocumentRewriteSession; -import org.eclipse.jface.text.DocumentRewriteSessionType; -import org.eclipse.jface.text.IDocumentExtension4; -import org.eclipse.jface.text.ITextSelection; -import org.eclipse.jface.text.ITypedRegion; -import org.eclipse.ui.texteditor.ITextEditor; -import org.eclipse.wst.sse.core.StructuredModelManager; -import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument; -import org.eclipse.wst.sse.ui.internal.Logger; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; -import org.eclipse.wst.sse.ui.internal.comment.CommentingStrategy; -import org.eclipse.wst.sse.ui.internal.comment.CommentingStrategyRegistry; - -/** - * <p>A comment handler to remove block comments</p> - */ -public final class RemoveBlockCommentHandler extends - AbstractCommentHandler { - - /** - * @see org.eclipse.wst.sse.ui.internal.handlers.AbstractCommentHandler#processAction(org.eclipse.ui.texteditor.ITextEditor, org.eclipse.jface.text.IDocument, org.eclipse.jface.text.ITextSelection) - */ - protected void processAction(ITextEditor textEditor, IStructuredDocument document, ITextSelection textSelection) { - - IStructuredModel model = null; - boolean changed = false; - DocumentRewriteSession session = null; - try { - model = StructuredModelManager.getModelManager().getModelForEdit(document); - - if(model != null) { - //makes it so one undo will undo all the edits to the document - model.beginRecording(this, SSEUIMessages.RemoveBlockComment_label, - SSEUIMessages.RemoveBlockComment_label); - - //keeps listeners from doing anything until updates are all done - model.aboutToChangeModel(); - if(document instanceof IDocumentExtension4) { - session = ((IDocumentExtension4)document).startRewriteSession( - DocumentRewriteSessionType.UNRESTRICTED); - } - changed = true; - - ITypedRegion[] typedRegions = document.computePartitioning( - textSelection.getOffset(), textSelection.getLength()); - CommentingStrategy commentType = CommentingStrategyRegistry.getDefault().getBlockCommentingStrategy( - model.getContentTypeIdentifier(), typedRegions); - - if(commentType != null) { - commentType.remove(document, textSelection.getOffset(), textSelection.getLength(), true); - } - } - } catch (BadLocationException e) { - Logger.logException("The given selection " + textSelection + " must be invalid", e); //$NON-NLS-1$ //$NON-NLS-2$ - } finally { - //clean everything up - if(session != null && document instanceof IDocumentExtension4) { - ((IDocumentExtension4)document).stopRewriteSession(session); - } - - if(model != null) { - model.endRecording(this); - if(changed) { - model.changedModel(); - } - model.releaseFromEdit(); - } - } - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/handlers/StructuredSelectHistoryHandler.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/handlers/StructuredSelectHistoryHandler.java deleted file mode 100644 index 13c552864a..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/handlers/StructuredSelectHistoryHandler.java +++ /dev/null @@ -1,51 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.handlers; - -import org.eclipse.core.commands.AbstractHandler; -import org.eclipse.core.commands.ExecutionEvent; -import org.eclipse.core.commands.ExecutionException; -import org.eclipse.jface.text.IRegion; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.handlers.HandlerUtil; -import org.eclipse.ui.texteditor.ITextEditor; -import org.eclipse.wst.sse.ui.internal.selection.SelectionHistory; - -public class StructuredSelectHistoryHandler extends AbstractHandler { - - public Object execute(ExecutionEvent event) throws ExecutionException { - IEditorPart editor = HandlerUtil.getActiveEditor(event); - SelectionHistory history = (SelectionHistory) editor.getAdapter(SelectionHistory.class); - if (history != null) { - IRegion old = history.getLast(); - if (old != null) { - try { - history.ignoreSelectionChanges(); - - ITextEditor textEditor = null; - if (editor instanceof ITextEditor) - textEditor = (ITextEditor) editor; - else { - Object o = editor.getAdapter(ITextEditor.class); - if (o != null) - textEditor = (ITextEditor) o; - } - if (textEditor != null) - textEditor.selectAndReveal(old.getOffset(), old.getLength()); - } - finally { - history.listenToSelectionChanges(); - } - } - } - return null; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/handlers/ToggleLineCommentHandler.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/handlers/ToggleLineCommentHandler.java deleted file mode 100644 index 7ab64bd157..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/handlers/ToggleLineCommentHandler.java +++ /dev/null @@ -1,287 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010, 2011 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.handlers; - -import java.lang.reflect.InvocationTargetException; - -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.jface.dialogs.ProgressMonitorDialog; -import org.eclipse.jface.operation.IRunnableWithProgress; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.DocumentRewriteSession; -import org.eclipse.jface.text.DocumentRewriteSessionType; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IDocumentExtension4; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ITextSelection; -import org.eclipse.jface.text.ITypedRegion; -import org.eclipse.jface.text.Position; -import org.eclipse.swt.widgets.Display; -import org.eclipse.ui.texteditor.ITextEditor; -import org.eclipse.wst.sse.core.StructuredModelManager; -import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument; -import org.eclipse.wst.sse.ui.StructuredTextEditor; -import org.eclipse.wst.sse.ui.internal.Logger; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; -import org.eclipse.wst.sse.ui.internal.StructuredTextViewer; -import org.eclipse.wst.sse.ui.internal.comment.BlockCommentingStrategy; -import org.eclipse.wst.sse.ui.internal.comment.CommentingStrategy; -import org.eclipse.wst.sse.ui.internal.comment.CommentingStrategyRegistry; -import org.eclipse.wst.sse.ui.internal.comment.LineCommentingStrategy; - -/** - * <p>A comment handler to toggle line comments, this means that if a - * comment already exists on a line then toggling it will remove the comment, - * if the line in question is not already commented then it will not be commented. - * If multiple lines are selected each will be commented separately. The handler - * first attempts to find a {@link LineCommentingStrategy} for a line, if it can - * not find one then it will try and find a {@link BlockCommentingStrategy} to - * wrap just that line in.</p> - * - * <p>If a great number of lines are being toggled then a progress dialog will be - * displayed because this can be a timely process</p> - */ -public final class ToggleLineCommentHandler extends AbstractCommentHandler { - /** if toggling more then this many lines then use a busy indicator */ - private static final int TOGGLE_LINES_MAX_NO_BUSY_INDICATOR = 10; - - /** - * @see org.eclipse.wst.sse.ui.internal.handlers.AbstractCommentHandler#processAction( - * org.eclipse.ui.texteditor.ITextEditor, org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument, - * org.eclipse.jface.text.ITextSelection) - */ - protected void processAction(ITextEditor textEditor, - final IStructuredDocument document, ITextSelection textSelection) { - - IStructuredModel model = null; - DocumentRewriteSession session = null; - boolean changed = false; - - try { - // get text selection lines info - int selectionStartLine = textSelection.getStartLine(); - int selectionEndLine = textSelection.getEndLine(); - - int selectionEndLineOffset = document.getLineOffset(selectionEndLine); - int selectionEndOffset = textSelection.getOffset() + textSelection.getLength(); - - // adjust selection end line - if ((selectionEndLine > selectionStartLine) && (selectionEndLineOffset == selectionEndOffset)) { - selectionEndLine--; - } - - // save the selection position since it will be changing - Position selectionPosition = null; - selectionPosition = new Position(textSelection.getOffset(), textSelection.getLength()); - document.addPosition(selectionPosition); - - - model = StructuredModelManager.getModelManager().getModelForEdit(document); - if (model != null) { - //makes it so one undo will undo all the edits to the document - model.beginRecording(this, SSEUIMessages.ToggleComment_label, SSEUIMessages.ToggleComment_description); - - //keeps listeners from doing anything until updates are all done - model.aboutToChangeModel(); - if(document instanceof IDocumentExtension4) { - session = ((IDocumentExtension4)document).startRewriteSession(DocumentRewriteSessionType.UNRESTRICTED); - } - changed = true; - - //get the display for the editor if we can - Display display = null; - if(textEditor instanceof StructuredTextEditor) { - StructuredTextViewer viewer = ((StructuredTextEditor)textEditor).getTextViewer(); - if(viewer != null) { - display = viewer.getControl().getDisplay(); - } - } - - //create the toggling operation - IRunnableWithProgress toggleCommentsRunnable = new ToggleLinesRunnable( - model.getContentTypeIdentifier(), document, selectionStartLine, selectionEndLine, display); - - //if toggling lots of lines then use progress monitor else just run the operation - if((selectionEndLine - selectionStartLine) > TOGGLE_LINES_MAX_NO_BUSY_INDICATOR && display != null) { - ProgressMonitorDialog dialog = new ProgressMonitorDialog(display.getActiveShell()); - dialog.run(false, true, toggleCommentsRunnable); - } else { - toggleCommentsRunnable.run(new NullProgressMonitor()); - } - } - } catch (InvocationTargetException e) { - Logger.logException("Problem running toggle comment progess dialog.", e); //$NON-NLS-1$ - } catch (InterruptedException e) { - Logger.logException("Problem running toggle comment progess dialog.", e); //$NON-NLS-1$ - } catch (BadLocationException e) { - Logger.logException("The given selection " + textSelection + " must be invalid", e); //$NON-NLS-1$ //$NON-NLS-2$ - } finally { - //clean everything up - if(session != null && document instanceof IDocumentExtension4) { - ((IDocumentExtension4)document).stopRewriteSession(session); - } - - if(model != null) { - model.endRecording(this); - if(changed) { - model.changedModel(); - } - model.releaseFromEdit(); - } - } - } - - /** - * <p>The actual line toggling takes place in a runnable so it can be - * run as part of a progress dialog if there are many lines to toggle - * and thus the operation will take a noticeable amount of time the user - * should be aware of, this also allows for the operation to be canceled - * by the user</p> - * - */ - private static class ToggleLinesRunnable implements IRunnableWithProgress { - /** the content type for the document being commented */ - private String fContentType; - - /** the document that the lines will be toggled on */ - private IStructuredDocument fDocument; - - /** the first line in the document to toggle */ - private int fSelectionStartLine; - - /** the last line in the document to toggle */ - private int fSelectionEndLine; - - /** the display, so that it can be updated during a long operation */ - private Display fDisplay; - - /** - * @param model {@link IStructuredModel} that the lines will be toggled on - * @param document {@link IDocument} that the lines will be toggled on - * @param selectionStartLine first line in the document to toggle - * @param selectionEndLine last line in the document to toggle - * @param display {@link Display}, so that it can be updated during a long operation - */ - protected ToggleLinesRunnable(String contentTypeIdentifier, IStructuredDocument document, - int selectionStartLine, int selectionEndLine, Display display) { - - this.fContentType = contentTypeIdentifier; - this.fDocument = document; - this.fSelectionStartLine = selectionStartLine; - this.fSelectionEndLine = selectionEndLine; - this.fDisplay = display; - } - - /** - * @see org.eclipse.jface.operation.IRunnableWithProgress#run(org.eclipse.core.runtime.IProgressMonitor) - */ - public void run(IProgressMonitor monitor) { - //start work - monitor.beginTask(SSEUIMessages.ToggleComment_progress, - this.fSelectionEndLine-this.fSelectionStartLine); - try { - final CommentingStrategy[] strategies = new CommentingStrategy[fSelectionEndLine - fSelectionStartLine + 1]; - final int[] regions = new int[fSelectionEndLine - fSelectionStartLine + 1]; - boolean shouldComment = false; - int strategyCount = 0; - //toggle each line so long as task not canceled - for (int line = this.fSelectionStartLine; - line <= this.fSelectionEndLine && !monitor.isCanceled(); ++line) { - - //allows the user to be able to click the cancel button - readAndDispatch(this.fDisplay); - - //get the line region - IRegion lineRegion = this.fDocument.getLineInformation(line); - - //don't toggle empty lines - String content = this.fDocument.get(lineRegion.getOffset(), lineRegion.getLength()); - if (content.trim().length() > 0) { - //try to get a line comment type - ITypedRegion[] lineTypedRegions = - this.fDocument.computePartitioning(lineRegion.getOffset(), lineRegion.getLength()); - CommentingStrategy commentType = CommentingStrategyRegistry.getDefault().getLineCommentingStrategy( - this.fContentType, lineTypedRegions); - - //could not find line comment type so find block comment type to use on line - if(commentType == null) { - commentType = CommentingStrategyRegistry.getDefault().getBlockCommentingStrategy( - this.fContentType, lineTypedRegions); - } - - //toggle the comment on the line - if(commentType != null) { - strategies[strategyCount] = commentType; - regions[strategyCount++] = line; - if (!shouldComment && !commentType.alreadyCommenting(this.fDocument, lineTypedRegions)) { - shouldComment = true; - } - } - } - monitor.worked(1); - } - for (int i = 0; i < strategyCount; i++) { - final IRegion lineRegion = fDocument.getLineInformation( regions[i] ); - if (shouldComment) { - strategies[i].apply(this.fDocument, lineRegion.getOffset(), lineRegion.getLength()); - } - else { - strategies[i].remove(this.fDocument, lineRegion.getOffset(), lineRegion.getLength(), true); - } - monitor.worked(1); - } - } catch(BadLocationException e) { - Logger.logException("Bad location while toggling comments.", e); //$NON-NLS-1$ - } - //done work - monitor.done(); - } - - /** - * <p>When calling {@link Display#readAndDispatch()} the game is off as to whose code you maybe - * calling into because of event handling/listeners/etc. The only important thing is that - * the UI has been given a chance to react to user clicks. Thus the logging of most {@link Exception}s - * and {@link Error}s as caused by {@link Display#readAndDispatch()} because they are not caused - * by this code and do not effect it.</p> - * - * @param display the {@link Display} to call <code>readAndDispatch</code> - * on with exception/error handling. - */ - private void readAndDispatch(Display display) { - try { - display.readAndDispatch(); - } - catch (Exception e) { - Logger.log(Logger.WARNING, - "Exception caused by readAndDispatch, not caused by or fatal to caller", e); - } - catch (LinkageError e) { - Logger.log(Logger.WARNING, - "LinkageError caused by readAndDispatch, not caused by or fatal to caller", e); - } - catch (VirtualMachineError e) { - // re-throw these - throw e; - } - catch (ThreadDeath e) { - // re-throw these - throw e; - } - catch (Error e) { - // catch every error, except for a few that we don't want to handle - Logger.log(Logger.WARNING, - "Error caused by readAndDispatch, not caused by or fatal to caller", e); - } - } - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/hyperlink/HighlighterHyperlinkPresenter.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/hyperlink/HighlighterHyperlinkPresenter.java deleted file mode 100644 index 5085fa4c43..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/hyperlink/HighlighterHyperlinkPresenter.java +++ /dev/null @@ -1,468 +0,0 @@ -package org.eclipse.wst.sse.ui.internal.hyperlink; - -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.preference.PreferenceConverter; -import org.eclipse.jface.text.Assert; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.DocumentEvent; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IDocumentListener; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ITextInputListener; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.ITextViewerExtension2; -import org.eclipse.jface.text.ITextViewerExtension5; -import org.eclipse.jface.text.Position; -import org.eclipse.jface.text.Region; -import org.eclipse.jface.text.hyperlink.IHyperlink; -import org.eclipse.jface.text.hyperlink.IHyperlinkPresenter; -import org.eclipse.jface.util.IPropertyChangeListener; -import org.eclipse.jface.util.PropertyChangeEvent; -import org.eclipse.swt.SWT; -import org.eclipse.swt.custom.StyleRange; -import org.eclipse.swt.custom.StyledText; -import org.eclipse.swt.events.PaintEvent; -import org.eclipse.swt.events.PaintListener; -import org.eclipse.swt.graphics.Color; -import org.eclipse.swt.graphics.Cursor; -import org.eclipse.swt.graphics.GC; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.graphics.RGB; -import org.eclipse.swt.graphics.Rectangle; -import org.eclipse.swt.widgets.Display; - - -/** - * The is almost an exact copy of DefaultHyperlinkPresenter. However this - * hyperlink presenter works with the StructuredTextEditor's Highlighter - * instead of TextPresentation. - * - * The main difference is <code>text.redrawRange(offset, length, true);</code> - * is called instead of passing false for clearBackground. Also all mention of - * TextPresentation was removed since it does not really apply. - * - * @see org.eclipse.jface.text.hyperlink.DefaultHyperlinkPresenter - */ -public class HighlighterHyperlinkPresenter implements IHyperlinkPresenter, PaintListener, ITextInputListener, IDocumentListener, IPropertyChangeListener { - - /** - * A named preference that holds the color used for hyperlinks. - * <p> - * Value is of type <code>String</code>. A RGB color value encoded as a - * string using class <code>PreferenceConverter</code> - * </p> - * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String HYPERLINK_COLOR = "hyperlinkColor"; //$NON-NLS-1$ - - - /** The text viewer. */ - private ITextViewer fTextViewer; - /** The hand cursor. */ - private Cursor fCursor; - /** The link color. */ - private Color fColor; - /** Tells whether to dispose the color on uninstall. */ - private boolean fDisposeColor; - /** The currently active region. */ - private IRegion fActiveRegion; - /** The currently active style range as position. */ - private Position fRememberedPosition; - /** The optional preference store */ - private IPreferenceStore fPreferenceStore; - - - /** - * Creates a new default hyperlink presenter which uses - * {@link #HYPERLINK_COLOR}to read the color from the given preference - * store. - * - * @param store - * the preference store - */ - public HighlighterHyperlinkPresenter(IPreferenceStore store) { - fPreferenceStore = store; - fDisposeColor = true; - } - - /** - * Creates a new default hyperlink presenter. - * - * @param color - * the hyperlink color, to be disposed by the caller - */ - public HighlighterHyperlinkPresenter(Color color) { - fDisposeColor = false; - fColor = color; - } - - public boolean canShowMultipleHyperlinks() { - return false; - } - - public void showHyperlinks(IHyperlink[] hyperlinks) { - Assert.isLegal(hyperlinks != null && hyperlinks.length == 1); - highlightRegion(hyperlinks[0].getHyperlinkRegion()); - activateCursor(); - } - - public void hideHyperlinks() { - repairRepresentation(); - fRememberedPosition = null; - } - - public void install(ITextViewer textViewer) { - Assert.isNotNull(textViewer); - fTextViewer = textViewer; - fTextViewer.addTextInputListener(this); - - StyledText text = fTextViewer.getTextWidget(); - if (text != null && !text.isDisposed()) { - text.addPaintListener(this); - if (fPreferenceStore != null) - fColor = createColor(fPreferenceStore, HYPERLINK_COLOR, text.getDisplay()); - } - - if (fPreferenceStore != null) - fPreferenceStore.addPropertyChangeListener(this); - } - - public void uninstall() { - fTextViewer.removeTextInputListener(this); - - if (fColor != null) { - if (fDisposeColor) - fColor.dispose(); - fColor = null; - } - - if (fCursor != null) { - fCursor.dispose(); - fCursor = null; - } - - StyledText text = fTextViewer.getTextWidget(); - if (text != null && !text.isDisposed()) - text.removePaintListener(this); - - fTextViewer = null; - - if (fPreferenceStore != null) - fPreferenceStore.removePropertyChangeListener(this); - } - - public void setColor(Color color) { - Assert.isNotNull(fTextViewer); - fColor = color; - } - - private void highlightRegion(IRegion region) { - - if (region.equals(fActiveRegion)) - return; - - repairRepresentation(); - - StyledText text = fTextViewer.getTextWidget(); - if (text == null || text.isDisposed()) - return; - - - // Underline - int offset = 0; - int length = 0; - if (fTextViewer instanceof ITextViewerExtension5) { - ITextViewerExtension5 extension = (ITextViewerExtension5) fTextViewer; - IRegion widgetRange = extension.modelRange2WidgetRange(region); - if (widgetRange == null) - return; - - offset = widgetRange.getOffset(); - length = widgetRange.getLength(); - - } - else { - offset = region.getOffset() - fTextViewer.getVisibleRegion().getOffset(); - length = region.getLength(); - } - - // needs to clean background due to StructuredTextEditor's highlighter - text.redrawRange(offset, length, true); - - // Invalidate region ==> apply text presentation - fActiveRegion = region; - - if (fTextViewer instanceof ITextViewerExtension2) - ((ITextViewerExtension2) fTextViewer).invalidateTextPresentation(region.getOffset(), region.getLength()); - else - fTextViewer.invalidateTextPresentation(); - } - - private void activateCursor() { - StyledText text = fTextViewer.getTextWidget(); - if (text == null || text.isDisposed()) - return; - Display display = text.getDisplay(); - if (fCursor == null) - fCursor = new Cursor(display, SWT.CURSOR_HAND); - text.setCursor(fCursor); - } - - private void resetCursor() { - StyledText text = fTextViewer.getTextWidget(); - if (text != null && !text.isDisposed()) - text.setCursor(null); - - if (fCursor != null) { - fCursor.dispose(); - fCursor = null; - } - } - - private void repairRepresentation() { - - if (fActiveRegion == null) - return; - - int offset = fActiveRegion.getOffset(); - int length = fActiveRegion.getLength(); - fActiveRegion = null; - - resetCursor(); - - // Invalidate ==> remove applied text presentation - if (fTextViewer instanceof ITextViewerExtension2) - ((ITextViewerExtension2) fTextViewer).invalidateTextPresentation(offset, length); - else - fTextViewer.invalidateTextPresentation(); - - // Remove underline - if (fTextViewer instanceof ITextViewerExtension5) { - ITextViewerExtension5 extension = (ITextViewerExtension5) fTextViewer; - offset = extension.modelOffset2WidgetOffset(offset); - } - else { - offset -= fTextViewer.getVisibleRegion().getOffset(); - } - try { - StyledText text = fTextViewer.getTextWidget(); - - // needs to clean background due to StructuredTextEditor's - // highlighter - text.redrawRange(offset, length, true); - - } - catch (IllegalArgumentException x) { - // ignore - do not log - } - } - - /* - * @see PaintListener#paintControl(PaintEvent) - */ - public void paintControl(PaintEvent event) { - if (fActiveRegion == null) - return; - - StyledText text = fTextViewer.getTextWidget(); - if (text == null || text.isDisposed()) - return; - - int offset = 0; - int length = 0; - - if (fTextViewer instanceof ITextViewerExtension5) { - - ITextViewerExtension5 extension = (ITextViewerExtension5) fTextViewer; - IRegion widgetRange = extension.modelRange2WidgetRange(fActiveRegion); - if (widgetRange == null) - return; - - offset = widgetRange.getOffset(); - length = widgetRange.getLength(); - - } - else { - - IRegion region = fTextViewer.getVisibleRegion(); - if (!includes(region, fActiveRegion)) - return; - - offset = fActiveRegion.getOffset() - region.getOffset(); - length = fActiveRegion.getLength(); - } - - // support for BIDI - Point minLocation = getMinimumLocation(text, offset, length); - Point maxLocation = getMaximumLocation(text, offset, length); - - int x1 = minLocation.x; - int x2 = maxLocation.x - 1; - int y = minLocation.y + text.getLineHeight() - 1; - - GC gc = event.gc; - if (fColor != null && !fColor.isDisposed()) - gc.setForeground(fColor); - else if (fColor == null && !(offset < 0 && offset >= text.getCharCount())) { - StyleRange style = text.getStyleRangeAtOffset(offset); - if (style != null) - gc.setForeground(style.foreground); - } - gc.drawLine(x1, y, x2, y); - } - - private Point getMinimumLocation(StyledText text, int offset, int length) { - int max = text.getCharCount(); - Rectangle bounds = text.getBounds(); - Point minLocation = new Point(bounds.width, bounds.height); - for (int i = 0; i <= length; i++) { - int k = offset + i; - if (k < 0 || k > max) - break; - - Point location = text.getLocationAtOffset(k); - if (location.x < minLocation.x) - minLocation.x = location.x; - if (location.y < minLocation.y) - minLocation.y = location.y; - } - - return minLocation; - } - - private Point getMaximumLocation(StyledText text, int offset, int length) { - Point maxLocation = new Point(0, 0); - - for (int i = 0; i <= length; i++) { - int k = offset + i; - if (k < 0 || k > text.getCharCount()) - break; - - Point location = text.getLocationAtOffset(k); - if (location.x > maxLocation.x) - maxLocation.x = location.x; - if (location.y > maxLocation.y) - maxLocation.y = location.y; - } - - return maxLocation; - } - - private boolean includes(IRegion region, IRegion position) { - return position.getOffset() >= region.getOffset() && position.getOffset() + position.getLength() <= region.getOffset() + region.getLength(); - } - - /* - * @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent) - */ - public void documentAboutToBeChanged(DocumentEvent event) { - if (fActiveRegion != null) { - fRememberedPosition = new Position(fActiveRegion.getOffset(), fActiveRegion.getLength()); - try { - event.getDocument().addPosition(fRememberedPosition); - } - catch (BadLocationException x) { - fRememberedPosition = null; - } - } - } - - /* - * @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent) - */ - public void documentChanged(DocumentEvent event) { - if (fRememberedPosition != null) { - if (!fRememberedPosition.isDeleted()) { - - event.getDocument().removePosition(fRememberedPosition); - fActiveRegion = new Region(fRememberedPosition.getOffset(), fRememberedPosition.getLength()); - fRememberedPosition = null; - - StyledText widget = fTextViewer.getTextWidget(); - if (widget != null && !widget.isDisposed()) { - widget.getDisplay().asyncExec(new Runnable() { - public void run() { - hideHyperlinks(); - } - }); - } - - } - else { - fActiveRegion = null; - fRememberedPosition = null; - hideHyperlinks(); - } - } - } - - /* - * @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) - return; - hideHyperlinks(); - oldInput.removeDocumentListener(this); - } - - /* - * @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) - return; - newInput.addDocumentListener(this); - } - - /** - * Creates a color from the information stored in the given preference - * store. - * - * @param store - * the preference store - * @param key - * the key - * @param display - * the display - * @return the color or <code>null</code> if there is no such - * information available - */ - private Color createColor(IPreferenceStore store, String key, Display display) { - - RGB rgb = null; - - if (store.contains(key)) { - - if (store.isDefault(key)) - rgb = PreferenceConverter.getDefaultColor(store, key); - else - rgb = PreferenceConverter.getColor(store, key); - - if (rgb != null) - return new Color(display, rgb); - } - - return null; - } - - /* - * @see org.eclipse.jface.util.IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent) - */ - public void propertyChange(PropertyChangeEvent event) { - if (!HYPERLINK_COLOR.equals(event.getProperty())) - return; - - if (fDisposeColor && fColor != null && !fColor.isDisposed()) - fColor.dispose(); - fColor = null; - - StyledText textWidget = fTextViewer.getTextWidget(); - if (textWidget != null && !textWidget.isDisposed()) - fColor = createColor(fPreferenceStore, HYPERLINK_COLOR, textWidget.getDisplay()); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/hyperlink/OpenHyperlinkAction.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/hyperlink/OpenHyperlinkAction.java deleted file mode 100644 index 35a6e555f8..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/hyperlink/OpenHyperlinkAction.java +++ /dev/null @@ -1,81 +0,0 @@ -package org.eclipse.wst.sse.ui.internal.hyperlink; - -import java.util.ResourceBundle; - -import org.eclipse.core.runtime.SafeRunner; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ITextSelection; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.Region; -import org.eclipse.jface.text.hyperlink.IHyperlink; -import org.eclipse.jface.text.hyperlink.IHyperlinkDetector; -import org.eclipse.jface.util.SafeRunnable; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.ui.texteditor.ITextEditor; -import org.eclipse.ui.texteditor.TextEditorAction; - -/** - * Open hyperlink action - */ -public class OpenHyperlinkAction extends TextEditorAction { - private IHyperlinkDetector[] fHyperlinkDetectors; - private ITextViewer fTextViewer; - - public OpenHyperlinkAction(ResourceBundle bundle, String prefix, ITextEditor editor, ITextViewer viewer) { - super(bundle, prefix, editor); - fTextViewer = viewer; - } - - public void setHyperlinkDetectors(IHyperlinkDetector[] detectors) { - fHyperlinkDetectors = detectors; - } - - public void run() { - if (fHyperlinkDetectors == null) - return; - ISelection selection = getTextEditor().getSelectionProvider().getSelection(); - if (selection == null || !(selection instanceof ITextSelection)) { - return; - } - - ITextSelection textSelection = (ITextSelection) selection; - final IRegion region = new Region(textSelection.getOffset(), textSelection.getLength()); - IHyperlink hyperlink = null; - - synchronized (fHyperlinkDetectors) { - for (int i = 0, length = fHyperlinkDetectors.length; i < length && hyperlink == null; i++) { - final IHyperlinkDetector detector = fHyperlinkDetectors[i]; - if (detector == null) - continue; - - /* The array is final, but its contents aren't */ - final IHyperlink[][] hyperlinks = new IHyperlink[1][]; - - /* - * Detect from within a SafeRunnable since the list of - * detectors is extensible - */ - SafeRunnable detectorRunnable = new SafeRunnable() { - public void run() throws Exception { - hyperlinks[0] = detector.detectHyperlinks(fTextViewer, region, false); - } - }; - SafeRunner.run(detectorRunnable); - - if (hyperlinks[0] == null) - continue; - - if (hyperlinks.length > 0) - hyperlink = hyperlinks[0][0]; - } - } - if (hyperlink != null) { - /** - * Force the highlight range to change when the hyperlink is - * opened by altering the highlighted range beforehand. - */ - getTextEditor().setHighlightRange(Math.max(0, region.getOffset() - 1), 0, false); - hyperlink.open(); - } - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/openon/AbstractOpenOn.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/openon/AbstractOpenOn.java deleted file mode 100644 index 72fb2a68b0..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/openon/AbstractOpenOn.java +++ /dev/null @@ -1,271 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2006 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.openon; - -import java.io.File; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.Path; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IRegion; -import org.eclipse.swt.program.Program; -import org.eclipse.ui.IEditorDescriptor; -import org.eclipse.ui.IEditorInput; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.IEditorRegistry; -import org.eclipse.ui.IWorkbench; -import org.eclipse.ui.IWorkbenchPage; -import org.eclipse.ui.PartInitException; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.editors.text.EditorsUI; -import org.eclipse.ui.ide.IDE; -import org.eclipse.wst.sse.core.StructuredModelManager; -import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel; -import org.eclipse.wst.sse.core.internal.util.URIResolver; -import org.eclipse.wst.sse.ui.internal.Logger; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; -import org.eclipse.wst.sse.ui.internal.util.PlatformStatusLineUtil; - - -/** - * This action class retrieves the link/file selected by the cursor and - * attempts to open the link/file in the default editor or web browser - * - * @deprecated Use base support for hyperlink navigation - */ -abstract public class AbstractOpenOn implements IOpenOn { - protected final String CANNOT_OPEN = SSEUIMessages.AbstractOpenOn_0; //$NON-NLS-1$ - // document currently associated with open - private IDocument fDocument; - protected final String FILE_PROTOCOL = "file:/";//$NON-NLS-1$ - private final String HTTP_PROTOCOL = "http://";//$NON-NLS-1$ - - abstract protected IRegion doGetOpenOnRegion(int offset); - - abstract protected void doOpenOn(IRegion region); - - /** - * Returns the current document associated with open on - * - * @return IDocument - */ - public IDocument getDocument() { - return fDocument; - } - - /** - * Determines the editor associated with the given file name - * - * @param filename - * @return editor id of the editor associated with the given file name - */ - private String getEditorId(String filename) { - IWorkbench workbench = PlatformUI.getWorkbench(); - IEditorRegistry editorRegistry = workbench.getEditorRegistry(); - IEditorDescriptor descriptor = editorRegistry.getDefaultEditor(filename); - if (descriptor != null) - return descriptor.getId(); - return EditorsUI.DEFAULT_TEXT_EDITOR_ID; - } - - /** - * Returns an IFile from the given uri if possible, null if cannot find - * file from uri. - * - * @param fileString - * file system path - * @return returns IFile if fileString exists in the workspace - */ - protected IFile getFile(String fileString) { - IStructuredModel model = null; - IFile file = null; - try { - model = StructuredModelManager.getModelManager().getExistingModelForRead(getDocument()); - if (model != null) { - // use the base location to obtain the in-workspace IFile - IFile modelFile = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(model.getBaseLocation())); - if (modelFile != null) { - // find the referenced file's location on disk - URIResolver resolver = model.getResolver(); - if (resolver != null) { - String filesystemLocation = resolver.getLocationByURI(fileString); - if (filesystemLocation != null) { - IFile[] workspaceFiles = ResourcesPlugin.getWorkspace().getRoot().findFilesForLocation(new Path(filesystemLocation)); - // favor a workspace file in the same project - for (int i = 0; i < workspaceFiles.length && file == null; i++) { - if (workspaceFiles[i].getProject().equals(modelFile.getProject())) { - file = workspaceFiles[i]; - } - } - // if none were in the same project, just pick one - if (file == null && workspaceFiles.length > 0) { - file = workspaceFiles[0]; - } - } - } - } - } - } - catch (Exception e) { - Logger.log(Logger.WARNING, e.getMessage()); - } - finally { - if (model != null) { - model.releaseFromRead(); - } - } - if (file == null && fileString.startsWith("/")) { //$NON-NLS-1$ - file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(fileString)); - } - return file; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.sse.ui.IOpenOn#getOpenOnRegion(org.eclipse.jface.text.IDocument, - * int) - */ - public IRegion getOpenOnRegion(IDocument doc, int offset) { - IRegion region; - // set the document for this action - setDocument(doc); - region = doGetOpenOnRegion(offset); - // reset the document back to null for this action - setDocument(null); - return region; - } - - /** - * Try to open the external file, fileString in its default editor - * - * @param fileString - * @return IEditorPart editor opened or null if editor could not be opened - */ - protected IEditorPart openExternalFile(String fileString) { - // file does not exist in workspace so try to open using system editor - File file = new File(fileString); - // try to open existing external file if it exists - if (file.exists()) { - IEditorInput input = new ExternalFileEditorInput(file); - String editorId = getEditorId(fileString); - - try { - IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); - return page.openEditor(input, editorId, true); - } - catch (PartInitException pie) { - Logger.log(Logger.WARNING_DEBUG, pie.getMessage(), pie); - } - } - return null; - } - - /** - * Notifies user that open on selection action could not successfully open - * the selection (writes message on status bar and beeps) - */ - protected void openFileFailed() { - PlatformStatusLineUtil.displayErrorMessage(CANNOT_OPEN); - PlatformStatusLineUtil.addOneTimeClearListener(); - } - - /** - * Opens the IFile, input in its default editor, if possible, and returns - * the editor opened. Possible reasons for failure: input cannot be found, - * input does not exist in workbench, editor cannot be opened. - * - * @return IEditorPart editor opened or null if input == null or does not - * exist, external editor was opened, editor could not be opened - */ - protected IEditorPart openFileInEditor(IFile input) { - if (input != null && input.exists()) { - try { - IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); - return IDE.openEditor(page, input, true); - } - catch (PartInitException pie) { - Logger.log(Logger.WARNING_DEBUG, pie.getMessage(), pie); - } - } - return null; - } - - // on - - /** - * Opens the appropriate editor for fileString - * - * @param fileString - */ - protected void openFileInEditor(String fileString) { - IEditorPart editor = null; - if (fileString != null) { - // open web browser if this is a web address - String temp = fileString.toLowerCase(); - if (temp.startsWith(HTTP_PROTOCOL)) { - Program.launch(fileString); // launches web browser/executable - // associated with uri - return; - } - // chop off the file protocol - if (temp.startsWith(FILE_PROTOCOL)) { - fileString = fileString.substring(FILE_PROTOCOL.length()); - } - - // try to locate the file in the workspace and return an IFile if - // found - IFile file = getFile(fileString); - if (file != null) { - // file exists in workspace - editor = openFileInEditor(file); - } - else { - // file does not exist in workspace - editor = openExternalFile(fileString); - } - } - // no editor was opened - if (editor == null) { - openFileFailed(); - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.sse.ui.IOpenOn#openOn(org.eclipse.jface.text.IDocument, - * org.eclipse.jface.text.IRegion) - */ - public void openOn(IDocument doc, IRegion region) { - // set the document for this action - setDocument(doc); - // if no region was given this action fails - if (region == null) - openFileFailed(); - else - doOpenOn(region); - // reset the document back to null for this action - setDocument(null); - } - - /** - * Sets current document associated with open on - * - * @param document - */ - public void setDocument(IDocument document) { - fDocument = document; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/openon/ExternalFileEditorInput.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/openon/ExternalFileEditorInput.java deleted file mode 100644 index 51d0a83ebf..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/openon/ExternalFileEditorInput.java +++ /dev/null @@ -1,116 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.openon; - -import java.io.File; - -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.Path; -import org.eclipse.core.runtime.Platform; -import org.eclipse.jface.resource.ImageDescriptor; -import org.eclipse.ui.IEditorInput; -import org.eclipse.ui.IPersistableElement; -import org.eclipse.ui.editors.text.ILocationProvider; - -/** - * EditorInput for external files. Copied from - * org.eclipse.ui.internal.editors.text.JavaFileEditorInput - * - * @deprecated Use org.eclipse.ui.ide.FileStoreEditorInput and EFS.getLocalFileSystem().fromLocalFile() - */ -public class ExternalFileEditorInput implements IEditorInput, ILocationProvider { - - private File fFile; - - public ExternalFileEditorInput(File file) { - super(); - fFile = file; - } - - /* - * @see java.lang.Object#equals(java.lang.Object) - */ - public boolean equals(Object o) { - if (o == this) - return true; - - if (o instanceof ExternalFileEditorInput) { - ExternalFileEditorInput input = (ExternalFileEditorInput) o; - return fFile.equals(input.fFile); - } - - return false; - } - - /* - * @see org.eclipse.ui.IEditorInput#exists() - */ - public boolean exists() { - return fFile.exists(); - } - - /* - * @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class) - */ - public Object getAdapter(Class adapter) { - if (ILocationProvider.class.equals(adapter)) - return this; - return Platform.getAdapterManager().getAdapter(this, adapter); - } - - /* - * @see org.eclipse.ui.IEditorInput#getImageDescriptor() - */ - public ImageDescriptor getImageDescriptor() { - return null; - } - - /* - * @see org.eclipse.ui.IEditorInput#getName() - */ - public String getName() { - return fFile.getName(); - } - - /* - * @see org.eclipse.ui.editors.text.ILocationProvider#getPath(java.lang.Object) - */ - public IPath getPath(Object element) { - if (element instanceof ExternalFileEditorInput) { - ExternalFileEditorInput input = (ExternalFileEditorInput) element; - return new Path(input.fFile.getAbsolutePath()); - } - return null; - } - - /* - * @see org.eclipse.ui.IEditorInput#getPersistable() - */ - public IPersistableElement getPersistable() { - return null; - } - - /* - * @see org.eclipse.ui.IEditorInput#getToolTipText() - */ - public String getToolTipText() { - return fFile.getAbsolutePath(); - } - - /* - * @see java.lang.Object#hashCode() - */ - public int hashCode() { - return fFile.hashCode(); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/openon/IOpenOn.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/openon/IOpenOn.java deleted file mode 100644 index fb67c386c4..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/openon/IOpenOn.java +++ /dev/null @@ -1,46 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.openon; - -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IRegion; - -/** - * Interface for Open On... navigation - * - * @author amywu - */ -public interface IOpenOn { - /** - * Returns the entire region relevant to the current offset where an - * openable source region is found. null if offset does not contain an - * openable source. - * - * @param document - * IDocument - * @param offset - * int - * @return IRegion entire region of openable source - */ - public IRegion getOpenOnRegion(IDocument document, int offset); - - /** - * Opens the file/source relevant to region if possible. - * - * @param viewer - * ITextViewer - * @param region - * Region to examine - */ - public void openOn(IDocument document, IRegion region); -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/openon/OpenFileHyperlinkTracker.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/openon/OpenFileHyperlinkTracker.java deleted file mode 100644 index 372a62008c..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/openon/OpenFileHyperlinkTracker.java +++ /dev/null @@ -1,660 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2006 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.openon; - -import com.ibm.icu.util.StringTokenizer; - -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.preference.PreferenceConverter; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.DocumentEvent; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IDocumentListener; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ITextInputListener; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.ITextViewerExtension5; -import org.eclipse.jface.text.Position; -import org.eclipse.jface.text.Region; -import org.eclipse.jface.util.IPropertyChangeListener; -import org.eclipse.jface.util.PropertyChangeEvent; -import org.eclipse.swt.SWT; -import org.eclipse.swt.custom.StyledText; -import org.eclipse.swt.events.FocusEvent; -import org.eclipse.swt.events.FocusListener; -import org.eclipse.swt.events.KeyEvent; -import org.eclipse.swt.events.KeyListener; -import org.eclipse.swt.events.MouseEvent; -import org.eclipse.swt.events.MouseListener; -import org.eclipse.swt.events.MouseMoveListener; -import org.eclipse.swt.events.PaintEvent; -import org.eclipse.swt.events.PaintListener; -import org.eclipse.swt.graphics.Color; -import org.eclipse.swt.graphics.Cursor; -import org.eclipse.swt.graphics.GC; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.graphics.RGB; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Display; -import org.eclipse.wst.sse.ui.internal.Logger; -import org.eclipse.wst.sse.ui.internal.util.EditorUtility; - - -/** - * @deprecated Use org.eclipse.jface.text.hyperlink.HyperlinkManager - */ -public class OpenFileHyperlinkTracker implements KeyListener, MouseListener, MouseMoveListener, FocusListener, PaintListener, IPropertyChangeListener, IDocumentListener, ITextInputListener { - - /** The session is active. */ - private boolean fActive; - - /** The currently active style range. */ - private IRegion fActiveRegion; - /** Preference key for browser-like links to be enabled */ - private String fBrowserLikeLinksKeyModifierKey; - - /** The link color. */ - private Color fColor; - /** The hand cursor. */ - private Cursor fCursor; - /** The key modifier mask. */ - private int fKeyModifierMask; - /** Preference key for hyperlink underline color */ - private String fLinkColorKey; - /** The preference store */ - private IPreferenceStore fPreferenceStore; - /** The currently active style range as position. */ - private Position fRememberedPosition; - - /** The text viewer this hyperlink tracker is associated with */ - private ITextViewer fTextViewer; - - /** - * - */ - public OpenFileHyperlinkTracker(ITextViewer textViewer) { - fTextViewer = textViewer; - } - - private void activateCursor(ITextViewer viewer) { - StyledText text = viewer.getTextWidget(); - if (text == null || text.isDisposed()) - return; - Display display = text.getDisplay(); - if (fCursor == null) - fCursor = new Cursor(display, SWT.CURSOR_HAND); - text.setCursor(fCursor); - } - - private int computeStateMask(String modifiers) { - if (modifiers == null) - return -1; - - if (modifiers.length() == 0) - return SWT.NONE; - - int stateMask = 0; - StringTokenizer modifierTokenizer = new StringTokenizer(modifiers, ",;.:+-* "); //$NON-NLS-1$ - while (modifierTokenizer.hasMoreTokens()) { - int modifier = EditorUtility.findLocalizedModifier(modifierTokenizer.nextToken()); - if (modifier == 0 || (stateMask & modifier) == modifier) - return -1; - stateMask = stateMask | modifier; - } - return stateMask; - } - - /** - * Creates a color from the information stored in the given preference - * store. Returns <code>null</code> if there is no such information - * available. - */ - private Color createColor(IPreferenceStore store, String key, Display display) { - - RGB rgb = null; - - if (store.contains(key)) { - - if (store.isDefault(key)) - rgb = PreferenceConverter.getDefaultColor(store, key); - else - rgb = PreferenceConverter.getColor(store, key); - } - - return EditorUtility.getColor(rgb); - } - - public void deactivate() { - deactivate(false); - } - - public void deactivate(boolean redrawAll) { - if (!fActive) - return; - - repairRepresentation(redrawAll); - fActive = false; - } - - /* - * @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent) - */ - public void documentAboutToBeChanged(DocumentEvent event) { - if (fActive && fActiveRegion != null) { - fRememberedPosition = new Position(fActiveRegion.getOffset(), fActiveRegion.getLength()); - try { - event.getDocument().addPosition(fRememberedPosition); - } catch (BadLocationException x) { - fRememberedPosition = null; - } - } - } - - /* - * @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent) - */ - public void documentChanged(DocumentEvent event) { - if (fRememberedPosition != null) { - if (!fRememberedPosition.isDeleted()) { - - event.getDocument().removePosition(fRememberedPosition); - fActiveRegion = new Region(fRememberedPosition.getOffset(), fRememberedPosition.getLength()); - fRememberedPosition = null; - - ITextViewer viewer = getTextViewer(); - if (viewer != null) { - StyledText widget = viewer.getTextWidget(); - if (widget != null && !widget.isDisposed()) { - widget.getDisplay().asyncExec(new Runnable() { - public void run() { - deactivate(); - } - }); - } - } - - } else { - fActiveRegion = null; - fRememberedPosition = null; - deactivate(); - } - } - } - - /* - * @see org.eclipse.swt.events.FocusListener#focusGained(org.eclipse.swt.events.FocusEvent) - */ - public void focusGained(FocusEvent e) { - } - - /* - * @see org.eclipse.swt.events.FocusListener#focusLost(org.eclipse.swt.events.FocusEvent) - */ - public void focusLost(FocusEvent event) { - deactivate(); - } - - private int getCurrentTextOffset() { - try { - StyledText text = getTextViewer().getTextWidget(); - if (text == null || text.isDisposed()) - return -1; - - Display display = text.getDisplay(); - Point absolutePosition = display.getCursorLocation(); - Point relativePosition = text.toControl(absolutePosition); - - int widgetOffset = text.getOffsetAtLocation(relativePosition); - if (getTextViewer() instanceof ITextViewerExtension5) { - ITextViewerExtension5 extension = (ITextViewerExtension5) getTextViewer(); - return extension.widgetOffset2ModelOffset(widgetOffset); - } else { - return widgetOffset + getTextViewer().getVisibleRegion().getOffset(); - } - - } catch (IllegalArgumentException e) { - return -1; - } - } - - private Point getMaximumLocation(StyledText text, int offset, int length) { - Point maxLocation = new Point(Integer.MIN_VALUE, Integer.MIN_VALUE); - - for (int i = 0; i <= length; i++) { - Point location = text.getLocationAtOffset(offset + i); - - if (location.x > maxLocation.x) - maxLocation.x = location.x; - if (location.y > maxLocation.y) - maxLocation.y = location.y; - } - - return maxLocation; - } - - private Point getMinimumLocation(StyledText text, int offset, int length) { - Point minLocation = new Point(Integer.MAX_VALUE, Integer.MAX_VALUE); - - for (int i = 0; i <= length; i++) { - Point location = text.getLocationAtOffset(offset + i); - - if (location.x < minLocation.x) - minLocation.x = location.x; - if (location.y < minLocation.y) - minLocation.y = location.y; - } - - return minLocation; - } - - private IPreferenceStore getNewPreferenceStore() { - return fPreferenceStore; - } - - private ITextViewer getTextViewer() { - return fTextViewer; - } - - private void highlightRegion(ITextViewer viewer, IRegion region) { - - if (region.equals(fActiveRegion)) - return; - - repairRepresentation(); - - StyledText text = viewer.getTextWidget(); - if (text == null || text.isDisposed()) - return; - - - // Underline - int offset = 0; - int length = 0; - if (viewer instanceof ITextViewerExtension5) { - ITextViewerExtension5 extension = (ITextViewerExtension5) viewer; - IRegion widgetRange = extension.modelRange2WidgetRange(new Region(region.getOffset(), region.getLength())); - if (widgetRange == null) - return; - - offset = widgetRange.getOffset(); - length = widgetRange.getLength(); - - } else { - offset = region.getOffset() - viewer.getVisibleRegion().getOffset(); - length = region.getLength(); - } - // need clearBackground to be true for paint event to be fired - text.redrawRange(offset, length, true); - - fActiveRegion = region; - } - - private boolean includes(IRegion region, IRegion position) { - return position.getOffset() >= region.getOffset() && position.getOffset() + position.getLength() <= region.getOffset() + region.getLength(); - } - - /* - * @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) - return; - deactivate(); - oldInput.removeDocumentListener(this); - } - - /* - * @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) - return; - newInput.addDocumentListener(this); - } - - public void install(IPreferenceStore store) { - fPreferenceStore = store; - ITextViewer textViewer = getTextViewer(); - if (textViewer == null) - return; - - StyledText text = textViewer.getTextWidget(); - if (text == null || text.isDisposed()) - return; - - updateColor(textViewer); - - textViewer.addTextInputListener(this); - - IDocument document = textViewer.getDocument(); - if (document != null) - document.addDocumentListener(this); - - text.addKeyListener(this); - text.addMouseListener(this); - text.addMouseMoveListener(this); - text.addFocusListener(this); - text.addPaintListener(this); - - updateKeyModifierMask(); - - fPreferenceStore.addPropertyChangeListener(this); - } - - /* - * @see org.eclipse.swt.events.KeyListener#keyPressed(org.eclipse.swt.events.KeyEvent) - */ - public void keyPressed(KeyEvent event) { - - if (fActive) { - deactivate(); - return; - } - - if (event.keyCode != fKeyModifierMask) { - deactivate(); - return; - } - - fActive = true; - - // removed for #25871 - // - // ISourceViewer viewer= getSourceViewer(); - // if (viewer == null) - // return; - // - // IRegion region= getCurrentTextRegion(viewer); - // if (region == null) - // return; - // - // highlightRegion(viewer, region); - // activateCursor(viewer); - } - - /* - * @see org.eclipse.swt.events.KeyListener#keyReleased(org.eclipse.swt.events.KeyEvent) - */ - public void keyReleased(KeyEvent event) { - - if (!fActive) - return; - - deactivate(); - } - - /* - * @see org.eclipse.swt.events.MouseListener#mouseDoubleClick(org.eclipse.swt.events.MouseEvent) - */ - public void mouseDoubleClick(MouseEvent e) { - } - - /* - * @see org.eclipse.swt.events.MouseListener#mouseDown(org.eclipse.swt.events.MouseEvent) - */ - public void mouseDown(MouseEvent event) { - - if (!fActive) - return; - - if (event.stateMask != fKeyModifierMask) { - deactivate(); - return; - } - - if (event.button != 1) { - deactivate(); - return; - } - } - - /* - * @see org.eclipse.swt.events.MouseMoveListener#mouseMove(org.eclipse.swt.events.MouseEvent) - */ - public void mouseMove(MouseEvent event) { - - if (event.widget instanceof Control && !((Control) event.widget).isFocusControl()) { - deactivate(); - return; - } - - if (!fActive) { - if (event.stateMask != fKeyModifierMask) - return; - // modifier was already pressed - fActive = true; - } - - ITextViewer viewer = getTextViewer(); - if (viewer == null) { - deactivate(); - return; - } - - StyledText text = viewer.getTextWidget(); - if (text == null || text.isDisposed()) { - deactivate(); - return; - } - - if ((event.stateMask & SWT.BUTTON1) != 0 && text.getSelectionCount() != 0) { - deactivate(); - return; - } - - IRegion region = null; - int offset = getCurrentTextOffset(); - IOpenOn openOn = OpenOnProvider.getInstance().getOpenOn(getTextViewer().getDocument(), offset); - if (openOn != null) { - region = openOn.getOpenOnRegion(getTextViewer().getDocument(), offset); - } - if (region == null || region.getLength() == 0) { - repairRepresentation(); - return; - } - - highlightRegion(viewer, region); - activateCursor(viewer); - } - - /* - * @see org.eclipse.swt.events.MouseListener#mouseUp(org.eclipse.swt.events.MouseEvent) - */ - public void mouseUp(MouseEvent e) { - - if (!fActive) - return; - - if (e.button != 1) { - deactivate(); - return; - } - - boolean wasActive = fCursor != null; - IRegion previousRegion = fActiveRegion; - - deactivate(); - - if (wasActive) { - IOpenOn openOn = OpenOnProvider.getInstance().getOpenOn(getTextViewer().getDocument(), previousRegion.getOffset()); - if (openOn != null) { - openOn.openOn(getTextViewer().getDocument(), previousRegion); - } - } - } - - /* - * @see PaintListener#paintControl(PaintEvent) - */ - public void paintControl(PaintEvent event) { - if (fActiveRegion == null) - return; - - ITextViewer viewer = getTextViewer(); - if (viewer == null) - return; - - StyledText text = viewer.getTextWidget(); - if (text == null || text.isDisposed()) - return; - - - int offset = 0; - int length = 0; - - if (viewer instanceof ITextViewerExtension5) { - - ITextViewerExtension5 extension = (ITextViewerExtension5) viewer; - IRegion widgetRange = extension.modelRange2WidgetRange(fActiveRegion); - if (widgetRange == null) - return; - - offset = widgetRange.getOffset(); - length = widgetRange.getLength(); - - } else { - - IRegion region = viewer.getVisibleRegion(); - if (!includes(region, fActiveRegion)) - return; - - offset = fActiveRegion.getOffset() - region.getOffset(); - length = fActiveRegion.getLength(); - } - - // support for bidi - Point minLocation = getMinimumLocation(text, offset, length); - Point maxLocation = getMaximumLocation(text, offset, length); - - int x1 = minLocation.x; - int x2 = minLocation.x + maxLocation.x - minLocation.x - 1; - int y = minLocation.y + text.getLineHeight() - 1; - - GC gc = event.gc; - if (fColor != null && !fColor.isDisposed()) - gc.setForeground(fColor); - gc.drawLine(x1, y, x2, y); - } - - /* - * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent) - */ - public void propertyChange(PropertyChangeEvent event) { - if (event.getProperty().equals(fLinkColorKey)) { - ITextViewer viewer = getTextViewer(); - if (viewer != null) - updateColor(viewer); - } else if (event.getProperty().equals(fBrowserLikeLinksKeyModifierKey)) { - updateKeyModifierMask(); - } - } - - private void repairRepresentation() { - repairRepresentation(false); - } - - private void repairRepresentation(boolean redrawAll) { - - if (fActiveRegion == null) - return; - - int offset = fActiveRegion.getOffset(); - int length = fActiveRegion.getLength(); - fActiveRegion = null; - - ITextViewer viewer = getTextViewer(); - if (viewer != null) { - - resetCursor(viewer); - - // Remove underline - if (viewer instanceof ITextViewerExtension5) { - ITextViewerExtension5 extension = (ITextViewerExtension5) viewer; - offset = extension.modelOffset2WidgetOffset(offset); - } else { - offset -= viewer.getVisibleRegion().getOffset(); - } - try { - StyledText text = viewer.getTextWidget(); - - // need clearBackground to be true for paint event to be fired - text.redrawRange(offset, length, true); - } catch (IllegalArgumentException x) { - Logger.logException(x); - } - } - } - - private void resetCursor(ITextViewer viewer) { - StyledText text = viewer.getTextWidget(); - if (text != null && !text.isDisposed()) - text.setCursor(null); - - if (fCursor != null) { - fCursor.dispose(); - fCursor = null; - } - } - - public void setHyperlinkPreferenceKeys(String linkColorKey, String browserLikeLinksKeyModifierKey) { - fLinkColorKey = linkColorKey; - fBrowserLikeLinksKeyModifierKey = browserLikeLinksKeyModifierKey; - } - - public void uninstall() { - if (fCursor != null) { - fCursor.dispose(); - fCursor = null; - } - - ITextViewer textViewer = getTextViewer(); - if (textViewer == null) - return; - - textViewer.removeTextInputListener(this); - - IDocument document = textViewer.getDocument(); - if (document != null) - document.removeDocumentListener(this); - - IPreferenceStore preferenceStore = getNewPreferenceStore(); - if (preferenceStore != null) - preferenceStore.removePropertyChangeListener(this); - - StyledText text = textViewer.getTextWidget(); - if (text == null || text.isDisposed()) - return; - - text.removeKeyListener(this); - text.removeMouseListener(this); - text.removeMouseMoveListener(this); - text.removeFocusListener(this); - text.removePaintListener(this); - } - - private void updateColor(ITextViewer viewer) { - StyledText text = viewer.getTextWidget(); - if (text == null || text.isDisposed()) - return; - - Display display = text.getDisplay(); - fColor = createColor(getNewPreferenceStore(), fLinkColorKey, display); - } - - private void updateKeyModifierMask() { - String modifiers = getNewPreferenceStore().getString(fBrowserLikeLinksKeyModifierKey); - fKeyModifierMask = computeStateMask(modifiers); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/openon/OpenOnAction.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/openon/OpenOnAction.java deleted file mode 100644 index fe7702c7ce..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/openon/OpenOnAction.java +++ /dev/null @@ -1,74 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.openon; - -import java.util.ResourceBundle; - -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.ITextSelection; -import org.eclipse.jface.text.Region; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.swt.custom.BusyIndicator; -import org.eclipse.ui.texteditor.ITextEditor; -import org.eclipse.ui.texteditor.TextEditorAction; -import org.eclipse.wst.sse.ui.internal.IExtendedSimpleEditor; -import org.eclipse.wst.sse.ui.internal.provisional.extensions.ISourceEditingTextTools; - - -/** - * Determines the appropriate IOpenFileAction to call based on current - * partition. - * - * @deprecated Use base support for hyperlink navigation - */ -public class OpenOnAction extends TextEditorAction { - public OpenOnAction(ResourceBundle bundle, String prefix, ITextEditor editor) { - super(bundle, prefix, editor); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.action.IAction#run() - */ - public void run() { - BusyIndicator.showWhile(getTextEditor().getEditorSite().getShell().getDisplay(), new Runnable() { - public void run() { - ITextEditor editor = getTextEditor(); - - // figure out current offset - int offset = -1; - ISourceEditingTextTools textTools = (ISourceEditingTextTools) getTextEditor().getAdapter(ISourceEditingTextTools.class); - if (textTools != null) { - offset = textTools.getCaretOffset(); - } - else if (editor instanceof IExtendedSimpleEditor) { - offset = ((IExtendedSimpleEditor) editor).getCaretPosition(); - } - else { - if (editor.getSelectionProvider() != null) { - ISelection sel = editor.getSelectionProvider().getSelection(); - if (sel instanceof ITextSelection) { - offset = ((ITextSelection) sel).getOffset(); - } - } - } - IDocument document = editor.getDocumentProvider().getDocument(editor.getEditorInput()); - IOpenOn openOn = OpenOnProvider.getInstance().getOpenOn(document, offset); - if (openOn != null) { - openOn.openOn(document, new Region(offset, 0)); - } - } - }); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/openon/OpenOnBuilder.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/openon/OpenOnBuilder.java deleted file mode 100644 index 3e02958bbb..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/openon/OpenOnBuilder.java +++ /dev/null @@ -1,267 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.openon; - -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.core.runtime.IConfigurationElement; -import org.eclipse.core.runtime.IExtensionRegistry; -import org.eclipse.core.runtime.Platform; -import org.eclipse.wst.sse.ui.internal.extension.RegistryReader; - - -/** - * Reads extensions for open on extension point, - * org.eclipse.wst.sse.ui.extensions.openon - * - * @deprecated Use base support for hyperlink navigation - */ -public class OpenOnBuilder extends RegistryReader { - public static final String ATT_CLASS = "class"; //$NON-NLS-1$ - - public static final String ATT_ID = "id"; //$NON-NLS-1$ - - private static OpenOnBuilder fInstance; - // extension point ID - public static final String PL_OPENON = "openon"; //$NON-NLS-1$ - - public static final String PLUGIN_ID = "org.eclipse.wst.sse.ui"; //$NON-NLS-1$ - public static final String TAG_CONTENT_TYPE_IDENTIFIER = "contenttypeidentifier"; //$NON-NLS-1$ - - public static final String TAG_OPENON = "openon"; //$NON-NLS-1$ - public static final String TAG_PARTITION_TYPE = "partitiontype"; //$NON-NLS-1$ - - /** - * returns singleton instance of OpenOnBuilder - * - * @return OpenOnBuilder - */ - public synchronized static OpenOnBuilder getInstance() { - if (fInstance == null) { - fInstance = new OpenOnBuilder(); - } - return fInstance; - } - - private String fCurrentContentType; - private OpenOnDefinition fCurrentOpenOnDefinition = null; - - private List fOpenOnDefs = null; - - protected String targetContributionTag; - - /** - * Returns the name of the part ID attribute that is expected in the - * target extension. - * - * @param element - * @return String - */ - protected String getId(IConfigurationElement element) { - String value = element.getAttribute(ATT_ID); - return value; - } - - protected String getOpenOnClass(IConfigurationElement element) { - String value = element.getAttribute(ATT_CLASS); - return value; - } - - /** - * Returns all the open on definition objects - * - * @return - */ - public OpenOnDefinition[] getOpenOnDefinitions() { - initCache(); - return (OpenOnDefinition[]) fOpenOnDefs.toArray(new OpenOnDefinition[fOpenOnDefs.size()]); - } - - /** - * Returns all the open on definition objects valid for - * contentType/partitionType - * - * @param contentType - * @param partitionType - * @return if either contentType or partitionType is null, null is - * returned - */ - public OpenOnDefinition[] getOpenOnDefinitions(String contentType, String partitionType) { - if (contentType == null || partitionType == null) { - // should not be able to define an openon without a content type - // but if it were possible then would need to search all openon - // definitions for - // definitions with empty contentType list - return null; - } - - // entire list of openon definition objects - OpenOnDefinition[] allDefs = getOpenOnDefinitions(); - // current list of open on definitions valid for - // contentType/partitionType - List defs = new ArrayList(); - // default definitions that should be added to end of list of open on - // definitions - List lastDefs = new ArrayList(); - - for (int i = 0; i < allDefs.length; ++i) { - // for each one check if it contains contentType - List partitions = (List) allDefs[i].getContentTypes().get(contentType); - if (partitions != null) { - // this openon definition is valid for all partition types for - // this content type - if (partitions.isEmpty()) { - // this will be added to end of list because this is - // considered a default openon - lastDefs.add(allDefs[i]); - } else { - // examine the partition types of this openon - int j = 0; // current index in list of partitions - boolean added = false; // openon has been added to list - while (j < partitions.size() && !added) { - // this openon definition applies to partitionType so - // add to list of valid openons - if (partitionType.equals(partitions.get(j))) { - defs.add(allDefs[i]); - added = true; - } else { - // continue checking to see if this openon - // definition is valid for current partitionType - ++j; - } - } - } - } - } - // append the default openon definitions - defs.addAll(lastDefs); - - // return the list - return (OpenOnDefinition[]) defs.toArray(new OpenOnDefinition[defs.size()]); - } - - private void initCache() { - if (fOpenOnDefs == null) { - fOpenOnDefs = new ArrayList(0); - readContributions(TAG_OPENON, PL_OPENON); - } - } - - /** - * Processes element which should be a configuration element specifying a - * content type for the current open on tag. Assumes that there is a valid - * current open on definition object. - * - * @param element - * contenttypeidentifier configuration element - */ - private void processContentTypeTag(IConfigurationElement element) { - // add to current openOnDefinition - String theId = getId(element); - - if (theId != null) { - fCurrentContentType = theId; - fCurrentOpenOnDefinition.addContentTypeId(fCurrentContentType); - } else { - fCurrentContentType = null; - } - } - - /** - * Processes element which should be a configuration element specifying an - * open on object. Creates a new open on definition object and adds it to - * the list of open on definition objects - * - * @param element - * openon configuration element - */ - private void processOpenOnTag(IConfigurationElement element) { - String theId = getId(element); - String theClass = getOpenOnClass(element); - - if (theId != null && theClass != null) { - // start building new OpenOnDefinition - fCurrentOpenOnDefinition = new OpenOnDefinition(theId, theClass, element); - fOpenOnDefs.add(fCurrentOpenOnDefinition); - } else { - fCurrentOpenOnDefinition = null; - } - } - - /** - * Processes element which should be a configuration element specifying a - * partition type for the current open on/content type tag. Assumes that - * there is a valid current open on/content type tag. - * - * @param element - * partitiontype configuration element - */ - private void processPartitionTypeTag(IConfigurationElement element) { - // add to current openOnDefinition/contentType - String theId = getId(element); - - if (theId != null) { - fCurrentOpenOnDefinition.addPartitionType(fCurrentContentType, theId); - } - } - - /** - * Reads the contributions from the registry for the provided workbench - * part and the provided extension point ID. - * - * @param tag - * @param extensionPoint - */ - protected void readContributions(String tag, String extensionPoint) { - targetContributionTag = tag; - IExtensionRegistry registry = Platform.getExtensionRegistry(); - readRegistry(registry, PLUGIN_ID, extensionPoint); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.sse.ui.internal.extension.RegistryReader#readElement(org.eclipse.core.runtime.IConfigurationElement) - */ - protected boolean readElement(IConfigurationElement element) { - String tag = element.getName(); - - if (tag.equals(targetContributionTag)) { - processOpenOnTag(element); - - // make sure processing of current open on tag resulted in a - // current open on definition - // before continue reading the children - if (fCurrentOpenOnDefinition != null) { - readElementChildren(element); - } - return true; - } else if (tag.equals(TAG_CONTENT_TYPE_IDENTIFIER)) { - processContentTypeTag(element); - - // make sure processing of current content type resulted in a - // valid content type - // before reading the children - if (fCurrentContentType != null) { - readElementChildren(element); - } - return true; - } else if (tag.equals(TAG_PARTITION_TYPE)) { - processPartitionTypeTag(element); - return true; - } - - return false; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/openon/OpenOnDefinition.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/openon/OpenOnDefinition.java deleted file mode 100644 index 5a60d601d8..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/openon/OpenOnDefinition.java +++ /dev/null @@ -1,157 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.openon; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IConfigurationElement; -import org.eclipse.core.runtime.Platform; -import org.eclipse.swt.custom.BusyIndicator; -import org.eclipse.wst.sse.ui.internal.Logger; -import org.osgi.framework.Bundle; - - -/** - * Open on definition object - * - * @deprecated Use base support for hyperlink navigation - */ -public class OpenOnDefinition { - private String fClassName = null; - - private IConfigurationElement fConfigurationElement = null; - - // a hash map of content type Ids (String) that points to lists of - // parition types (List of Strings) - // contentTypeId -> List(paritionType, paritionType, partitionType, ...) - // contentTypeId2 -> List(partitionType, partitionType, ...) - // ... - private HashMap fContentTypes = null; - private String fId = null; - - /** - * @param id - * @param class1 - * @param configurationElement - */ - public OpenOnDefinition(String id, String class1, IConfigurationElement configurationElement) { - super(); - fId = id; - fClassName = class1; - fConfigurationElement = configurationElement; - fContentTypes = new HashMap(); - } - - public void addContentTypeId(String contentTypeId) { - if (!fContentTypes.containsKey(contentTypeId)) - fContentTypes.put(contentTypeId, new ArrayList()); - } - - public void addPartitionType(String contentTypeId, String partitionType) { - if (!fContentTypes.containsKey(contentTypeId)) - fContentTypes.put(contentTypeId, new ArrayList()); - - List partitionList = (List) fContentTypes.get(contentTypeId); - partitionList.add(partitionType); - } - - /** - * Creates an extension. If the extension plugin has not been loaded a - * busy cursor will be activated during the duration of the load. - * - * @param propertyName - * @return Object - */ - private Object createExtension(String propertyName) { - // If plugin has been loaded create extension. - // Otherwise, show busy cursor then create extension. - final IConfigurationElement element = getConfigurationElement(); - final String name = propertyName; - - final Object[] result = new Object[1]; - String pluginId = element.getDeclaringExtension().getNamespace(); - Bundle bundle = Platform.getBundle(pluginId); - if (bundle.getState() == Bundle.ACTIVE) { - try { - return element.createExecutableExtension(name); - } catch (CoreException e) { - handleCreateExecutableException(result, e); - } - } else { - BusyIndicator.showWhile(null, new Runnable() { - public void run() { - try { - result[0] = element.createExecutableExtension(name); - } catch (Exception e) { - handleCreateExecutableException(result, e); - } - } - }); - } - return result[0]; - } - - /** - * @return IOpenOn for this definition - */ - public IOpenOn createOpenOn() { - IOpenOn openOn = null; - - if (getClassName() != null) { - openOn = (IOpenOn) createExtension(OpenOnBuilder.ATT_CLASS); - } - - return openOn; - } - - /** - * @return Returns the fClass. - */ - public String getClassName() { - return fClassName; - } - - /** - * @return Returns the fConfigurationElement. - */ - public IConfigurationElement getConfigurationElement() { - return fConfigurationElement; - } - - /** - * @return Returns the fContentTypes. - */ - public HashMap getContentTypes() { - return fContentTypes; - } - - /** - * @return Returns the fId. - */ - public String getId() { - return fId; - } - - /** - * @param result - * @param e - */ - private void handleCreateExecutableException(Object[] result, Throwable e) { - Logger.logException("Unable to create open on: " + getId(), e); //$NON-NLS-1$ - e.printStackTrace(); - result[0] = null; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/openon/OpenOnProvider.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/openon/OpenOnProvider.java deleted file mode 100644 index 4609ff9d98..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/openon/OpenOnProvider.java +++ /dev/null @@ -1,143 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2006 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.openon; - - - -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.content.IContentType; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.ITypedRegion; -import org.eclipse.jface.text.TextUtilities; -import org.eclipse.wst.sse.core.StructuredModelManager; -import org.eclipse.wst.sse.core.internal.provisional.IModelManager; -import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredPartitioning; - - -/** - * Determines the appropriate IOpenOn to call based on current partition. - * - * @deprecated Use base support for hyperlink navigation - */ -public class OpenOnProvider { - private static OpenOnProvider fInstance; - - /** - * returns singleton instance of OpenOnProvider - * - * @return OpenOnProvider - */ - public synchronized static OpenOnProvider getInstance() { - if (fInstance == null) { - fInstance = new OpenOnProvider(); - } - return fInstance; - } - - - /** - * Returns the content type of document - * - * @param document - - * assumes document is not null - * @return String content type of given document - */ - protected String getContentType(IDocument document) { - String type = null; - - IModelManager mgr = StructuredModelManager.getModelManager(); - IStructuredModel model = null; - try { - model = mgr.getExistingModelForRead(document); - if (model != null) { - type = model.getContentTypeIdentifier(); - } - } - finally { - if (model != null) { - model.releaseFromRead(); - } - } - return type; - } - - /** - * Returns the appropriate IOpenOn for the current partition - * - * @return - */ - public IOpenOn getOpenOn(IDocument document, int offset) { - IOpenOn openOn = null; - - // determine the current partition - if (document != null) { - String contentTypeID = getContentType(document); - String partitionType = getPartitionType(document, offset); - - IContentType contentType = Platform.getContentTypeManager().getContentType(contentTypeID); - - while (openOn == null && contentType != null) { - // Query OpenOnBuilder and get the list of OpenOns for the - // current partition - OpenOnDefinition[] defs = OpenOnBuilder.getInstance().getOpenOnDefinitions(contentType.getId(), partitionType); - contentType = contentType.getBaseType(); - - // If more than 1 openon is returned, need to further check - // which OpenOn is the appropriate one to return - // for now just returning the first one - if (defs != null && defs.length > 0) { - openOn = defs[0].createOpenOn(); - } - } - } - - return openOn; - } - - /** - * Returns the partition type located at offset in the document - * - * @param document - - * assumes document is not null - * @param offset - * @return String partition type - */ - protected String getPartitionType(IDocument document, int offset) { - String type = null; - try { - // TODO: provide partitioning information so we're not using a default like this - if (document instanceof IStructuredDocument) { - type = TextUtilities.getContentType(document, IStructuredPartitioning.DEFAULT_STRUCTURED_PARTITIONING, offset, false); - } - } - catch (BadLocationException e1) { - } - finally { - if (type == null) { - try { - ITypedRegion region = document.getPartition(offset); - if (region != null) { - type = region.getType(); - } - } - catch (BadLocationException e) { - type = null; - } - } - } - return type; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/EditorPreferenceNames.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/EditorPreferenceNames.java deleted file mode 100644 index 5ce3447929..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/EditorPreferenceNames.java +++ /dev/null @@ -1,156 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.preferences; - - -/** - * Preference keys for SSE UI - */ -public class EditorPreferenceNames { - /** - * A named preference that controls on-the-fly validation - * <p> - * Value is of type <code>Boolean</code>. - * </p> - */ - public static final String EVALUATE_TEMPORARY_PROBLEMS = getEvaluateTemporaryProblemsKey(); - - private static String getEvaluateTemporaryProblemsKey() { - return "evaluateTemporaryProblems"; //$NON-NLS-1$ - } - - /** - * A named preference that controls whether bracket matching highlighting - * is turned on or off. - * <p> - * Value is of type <code>Boolean</code>. - * </p> - */ - public final static String MATCHING_BRACKETS = getMatchingBracketsKey(); - - private static String getMatchingBracketsKey() { - return "matchingBrackets"; //$NON-NLS-1$ - } - - /** - * A named preference that holds the color used to highlight matching - * brackets. - * <p> - * Value is of type <code>String</code>. A RGB color value encoded as a - * string using class <code>PreferenceConverter</code> - * </p> - */ - public final static String MATCHING_BRACKETS_COLOR = getMatchingBracketsColorKey(); - - private static String getMatchingBracketsColorKey() { - return "matchingBracketsColor"; //$NON-NLS-1$ - } - - /** - * A named preference that defines the key for the hover modifiers. - * <p> - * Value is of type <code>String</code>. - * </p> - */ - public static final String EDITOR_TEXT_HOVER_MODIFIERS = getTextHoverModifiersKey(); - - private static String getTextHoverModifiersKey() { - return "hoverModifiers"; //$NON-NLS-1$ - } - - /** - * A named preference that defines read only contrast scale. - * <p> - * Value is of type <code>Integer</code>. - * </p> - */ - public static final String READ_ONLY_FOREGROUND_SCALE = getReadOnlyForegroundScaleKey(); - - private static String getReadOnlyForegroundScaleKey() { - return "readOnlyForegroundScale"; //$NON-NLS-1$ - } - - /** - * A named preference that defines whether or not to show a message dialog - * informing user of unknown content type in editor. - */ - public static final String SHOW_UNKNOWN_CONTENT_TYPE_MSG = "showUnknownContentTypeMsg"; //$NON-NLS-1$ - - /** - * A name preference that holds the auto activation delay time in - * milliseconds. - * <p> - * Value is of type <code>Integer</code>. - * </p> - */ - public final static String CODEASSIST_AUTOACTIVATION_DELAY = "content_assist_autoactivation_delay"; //$NON-NLS-1$ - - /** - * A named preference that holds the background color used in the code - * assist selection dialog. - * <p> - * Value is of type <code>String</code>. A RGB color value encoded as a - * string using class <code>PreferenceConverter</code> - * </p> - * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String CODEASSIST_PROPOSALS_BACKGROUND = "content_assist_proposals_background"; //$NON-NLS-1$ - - /** - * A named preference that holds the foreground color used in the code - * assist selection dialog. - * <p> - * Value is of type <code>String</code>. A RGB color value encoded as a - * string using class <code>PreferenceConverter</code> - * </p> - * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String CODEASSIST_PROPOSALS_FOREGROUND = "content_assist_proposals_foreground"; //$NON-NLS-1$ - - /** - * A named preference that holds the background color used for parameter - * hints. - * <p> - * Value is of type <code>String</code>. A RGB color value encoded as a - * string using class <code>PreferenceConverter</code> - * </p> - * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String CODEASSIST_PARAMETERS_BACKGROUND = "content_assist_parameters_background"; //$NON-NLS-1$ - - /** - * A named preference that holds the foreground color used in the code - * assist selection dialog. - * <p> - * Value is of type <code>String</code>. A RGB color value encoded as a - * string using class <code>PreferenceConverter</code> - * </p> - * - * @see org.eclipse.jface.resource.StringConverter - * @see org.eclipse.jface.preference.PreferenceConverter - */ - public final static String CODEASSIST_PARAMETERS_FOREGROUND = "content_assist_parameters_foreground"; //$NON-NLS-1$ - - /** - * A named preference that controls whether semantic highlighting is turned on or off - * <p> - * Value is of type <code>Boolean</code>. - * </p> - */ - public final static String SEMANTIC_HIGHLIGHTING = "semanticHighlighting"; //$NON-NLS-1$ -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/OverlayPreferenceStore.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/OverlayPreferenceStore.java deleted file mode 100644 index 16eb14cde7..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/OverlayPreferenceStore.java +++ /dev/null @@ -1,486 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.preferences; - -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.preference.PreferenceStore; -import org.eclipse.jface.text.Assert; -import org.eclipse.jface.util.IPropertyChangeListener; -import org.eclipse.jface.util.PropertyChangeEvent; - -/** - * An overlaying preference store. copied from JDT - */ -public class OverlayPreferenceStore implements IPreferenceStore { - - public static class OverlayKey { - - TypeDescriptor fDescriptor; - String fKey; - - public OverlayKey(TypeDescriptor descriptor, String key) { - fDescriptor = descriptor; - fKey = key; - } - } - - private class PropertyListener implements IPropertyChangeListener { - - /* - * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent) - */ - public void propertyChange(PropertyChangeEvent event) { - OverlayKey key = findOverlayKey(event.getProperty()); - if (key != null) - propagateProperty(fParent, key, fStore); - } - } - - - public static final class TypeDescriptor { - private TypeDescriptor() { - } - } - - public static final TypeDescriptor BOOLEAN = new TypeDescriptor(); - public static final TypeDescriptor DOUBLE = new TypeDescriptor(); - public static final TypeDescriptor FLOAT = new TypeDescriptor(); - public static final TypeDescriptor INT = new TypeDescriptor(); - public static final TypeDescriptor LONG = new TypeDescriptor(); - public static final TypeDescriptor STRING = new TypeDescriptor(); - private boolean fLoaded; - private OverlayKey[] fOverlayKeys; - - - IPreferenceStore fParent; - - private PropertyListener fPropertyListener; - IPreferenceStore fStore; - - - public OverlayPreferenceStore(IPreferenceStore parent, OverlayKey[] overlayKeys) { - fParent = parent; - fOverlayKeys = overlayKeys; - fStore = new PreferenceStore(); - } - - /** - * The keys to add to the list of overlay keys. - * <p> - * Note: This method must be called before {@link #load()}is called. - * </p> - * - * @param keys - * @plannedfor 3.0 - */ - public void addKeys(OverlayKey[] keys) { - Assert.isTrue(!fLoaded); - Assert.isNotNull(keys); - - int overlayKeysLength = fOverlayKeys.length; - OverlayKey[] result = new OverlayKey[keys.length + overlayKeysLength]; - - for (int i = 0, length = overlayKeysLength; i < length; i++) - result[i] = fOverlayKeys[i]; - - for (int i = 0, length = keys.length; i < length; i++) - result[overlayKeysLength + i] = keys[i]; - - fOverlayKeys = result; - - if (fLoaded) - load(); - } - - /* - * @see IPreferenceStore#addPropertyChangeListener(IPropertyChangeListener) - */ - public void addPropertyChangeListener(IPropertyChangeListener listener) { - fStore.addPropertyChangeListener(listener); - } - - /* - * @see IPreferenceStore#contains(String) - */ - public boolean contains(String name) { - return fStore.contains(name); - } - - private boolean covers(String key) { - return (findOverlayKey(key) != null); - } - - OverlayKey findOverlayKey(String key) { - for (int i = 0; i < fOverlayKeys.length; i++) { - if (fOverlayKeys[i].fKey.equals(key)) - return fOverlayKeys[i]; - } - return null; - } - - /* - * @see IPreferenceStore#firePropertyChangeEvent(String, Object, Object) - */ - public void firePropertyChangeEvent(String name, Object oldValue, Object newValue) { - fStore.firePropertyChangeEvent(name, oldValue, newValue); - } - - /* - * @see IPreferenceStore#getBoolean(String) - */ - public boolean getBoolean(String name) { - return fStore.getBoolean(name); - } - - /* - * @see IPreferenceStore#getDefaultBoolean(String) - */ - public boolean getDefaultBoolean(String name) { - return fStore.getDefaultBoolean(name); - } - - /* - * @see IPreferenceStore#getDefaultDouble(String) - */ - public double getDefaultDouble(String name) { - return fStore.getDefaultDouble(name); - } - - /* - * @see IPreferenceStore#getDefaultFloat(String) - */ - public float getDefaultFloat(String name) { - return fStore.getDefaultFloat(name); - } - - /* - * @see IPreferenceStore#getDefaultInt(String) - */ - public int getDefaultInt(String name) { - return fStore.getDefaultInt(name); - } - - /* - * @see IPreferenceStore#getDefaultLong(String) - */ - public long getDefaultLong(String name) { - return fStore.getDefaultLong(name); - } - - /* - * @see IPreferenceStore#getDefaultString(String) - */ - public String getDefaultString(String name) { - return fStore.getDefaultString(name); - } - - /* - * @see IPreferenceStore#getDouble(String) - */ - public double getDouble(String name) { - return fStore.getDouble(name); - } - - /* - * @see IPreferenceStore#getFloat(String) - */ - public float getFloat(String name) { - return fStore.getFloat(name); - } - - /* - * @see IPreferenceStore#getInt(String) - */ - public int getInt(String name) { - return fStore.getInt(name); - } - - /* - * @see IPreferenceStore#getLong(String) - */ - public long getLong(String name) { - return fStore.getLong(name); - } - - /* - * @see IPreferenceStore#getString(String) - */ - public String getString(String name) { - return fStore.getString(name); - } - - /* - * @see IPreferenceStore#isDefault(String) - */ - public boolean isDefault(String name) { - return fStore.isDefault(name); - } - - public void load() { - for (int i = 0; i < fOverlayKeys.length; i++) - loadProperty(fParent, fOverlayKeys[i], fStore, true); - - fLoaded = true; - - } - - public void loadDefaults() { - for (int i = 0; i < fOverlayKeys.length; i++) - setToDefault(fOverlayKeys[i].fKey); - } - - private void loadProperty(IPreferenceStore orgin, OverlayKey key, IPreferenceStore target, boolean forceInitialization) { - TypeDescriptor d = key.fDescriptor; - if (BOOLEAN == d) { - - if (forceInitialization) - target.setValue(key.fKey, true); - target.setValue(key.fKey, orgin.getBoolean(key.fKey)); - target.setDefault(key.fKey, orgin.getDefaultBoolean(key.fKey)); - - } else if (DOUBLE == d) { - - if (forceInitialization) - target.setValue(key.fKey, 1.0D); - target.setValue(key.fKey, orgin.getDouble(key.fKey)); - target.setDefault(key.fKey, orgin.getDefaultDouble(key.fKey)); - - } else if (FLOAT == d) { - - if (forceInitialization) - target.setValue(key.fKey, 1.0F); - target.setValue(key.fKey, orgin.getFloat(key.fKey)); - target.setDefault(key.fKey, orgin.getDefaultFloat(key.fKey)); - - } else if (INT == d) { - - if (forceInitialization) - target.setValue(key.fKey, 1); - target.setValue(key.fKey, orgin.getInt(key.fKey)); - target.setDefault(key.fKey, orgin.getDefaultInt(key.fKey)); - - } else if (LONG == d) { - - if (forceInitialization) - target.setValue(key.fKey, 1L); - target.setValue(key.fKey, orgin.getLong(key.fKey)); - target.setDefault(key.fKey, orgin.getDefaultLong(key.fKey)); - - } else if (STRING == d) { - - if (forceInitialization) - target.setValue(key.fKey, "1"); //$NON-NLS-1$ - target.setValue(key.fKey, orgin.getString(key.fKey)); - target.setDefault(key.fKey, orgin.getDefaultString(key.fKey)); - - } - } - - /* - * @see IPreferenceStore#needsSaving() - */ - public boolean needsSaving() { - return fStore.needsSaving(); - } - - public void propagate() { - for (int i = 0; i < fOverlayKeys.length; i++) - propagateProperty(fStore, fOverlayKeys[i], fParent); - } - - void propagateProperty(IPreferenceStore orgin, OverlayKey key, IPreferenceStore target) { - - if (orgin.isDefault(key.fKey)) { - if (!target.isDefault(key.fKey)) - target.setToDefault(key.fKey); - return; - } - - TypeDescriptor d = key.fDescriptor; - if (BOOLEAN == d) { - - boolean originValue = orgin.getBoolean(key.fKey); - boolean targetValue = target.getBoolean(key.fKey); - if (targetValue != originValue) - target.setValue(key.fKey, originValue); - - } else if (DOUBLE == d) { - - double originValue = orgin.getDouble(key.fKey); - double targetValue = target.getDouble(key.fKey); - if (targetValue != originValue) - target.setValue(key.fKey, originValue); - - } else if (FLOAT == d) { - - float originValue = orgin.getFloat(key.fKey); - float targetValue = target.getFloat(key.fKey); - if (targetValue != originValue) - target.setValue(key.fKey, originValue); - - } else if (INT == d) { - - int originValue = orgin.getInt(key.fKey); - int targetValue = target.getInt(key.fKey); - if (targetValue != originValue) - target.setValue(key.fKey, originValue); - - } else if (LONG == d) { - - long originValue = orgin.getLong(key.fKey); - long targetValue = target.getLong(key.fKey); - if (targetValue != originValue) - target.setValue(key.fKey, originValue); - - } else if (STRING == d) { - - String originValue = orgin.getString(key.fKey); - String targetValue = target.getString(key.fKey); - if (targetValue != null && originValue != null && !targetValue.equals(originValue)) - target.setValue(key.fKey, originValue); - - } - } - - /* - * @see IPreferenceStore#putValue(String, String) - */ - public void putValue(String name, String value) { - if (covers(name)) - fStore.putValue(name, value); - } - - /* - * @see IPreferenceStore#removePropertyChangeListener(IPropertyChangeListener) - */ - public void removePropertyChangeListener(IPropertyChangeListener listener) { - fStore.removePropertyChangeListener(listener); - } - - /* - * @see IPreferenceStore#setDefault(String, boolean) - */ - public void setDefault(String name, boolean value) { - if (covers(name)) - fStore.setDefault(name, value); - } - - /* - * @see IPreferenceStore#setDefault(String, double) - */ - public void setDefault(String name, double value) { - if (covers(name)) - fStore.setDefault(name, value); - } - - /* - * @see IPreferenceStore#setDefault(String, float) - */ - public void setDefault(String name, float value) { - if (covers(name)) - fStore.setDefault(name, value); - } - - /* - * @see IPreferenceStore#setDefault(String, int) - */ - public void setDefault(String name, int value) { - if (covers(name)) - fStore.setDefault(name, value); - } - - /* - * @see IPreferenceStore#setDefault(String, long) - */ - public void setDefault(String name, long value) { - if (covers(name)) - fStore.setDefault(name, value); - } - - /* - * @see IPreferenceStore#setDefault(String, String) - */ - public void setDefault(String name, String value) { - if (covers(name)) - fStore.setDefault(name, value); - } - - /* - * @see IPreferenceStore#setToDefault(String) - */ - public void setToDefault(String name) { - fStore.setToDefault(name); - } - - /* - * @see IPreferenceStore#setValue(String, boolean) - */ - public void setValue(String name, boolean value) { - if (covers(name)) - fStore.setValue(name, value); - } - - /* - * @see IPreferenceStore#setValue(String, double) - */ - public void setValue(String name, double value) { - if (covers(name)) - fStore.setValue(name, value); - } - - /* - * @see IPreferenceStore#setValue(String, float) - */ - public void setValue(String name, float value) { - if (covers(name)) - fStore.setValue(name, value); - } - - /* - * @see IPreferenceStore#setValue(String, int) - */ - public void setValue(String name, int value) { - if (covers(name)) - fStore.setValue(name, value); - } - - /* - * @see IPreferenceStore#setValue(String, long) - */ - public void setValue(String name, long value) { - if (covers(name)) - fStore.setValue(name, value); - } - - /* - * @see IPreferenceStore#setValue(String, String) - */ - public void setValue(String name, String value) { - if (covers(name)) - fStore.setValue(name, value); - } - - public void start() { - if (fPropertyListener == null) { - fPropertyListener = new PropertyListener(); - fParent.addPropertyChangeListener(fPropertyListener); - } - } - - public void stop() { - if (fPropertyListener != null) { - fParent.removePropertyChangeListener(fPropertyListener); - fPropertyListener = null; - } - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/TabFolderLayout.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/TabFolderLayout.java deleted file mode 100644 index b1b8903bea..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/TabFolderLayout.java +++ /dev/null @@ -1,61 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.preferences; - -import org.eclipse.swt.SWT; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.graphics.Rectangle; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Layout; - -/** - * Copied from JDT - * - * @author pavery - */ -public class TabFolderLayout extends Layout { - - protected Point computeSize(Composite composite, int wHint, int hHint, boolean flushCache) { - if (wHint != SWT.DEFAULT && hHint != SWT.DEFAULT) - return new Point(wHint, hHint); - - Control[] children = composite.getChildren(); - int count = children.length; - int maxWidth = 0, maxHeight = 0; - for (int i = 0; i < count; i++) { - Control child = children[i]; - Point pt = child.computeSize(SWT.DEFAULT, SWT.DEFAULT, flushCache); - maxWidth = Math.max(maxWidth, pt.x); - maxHeight = Math.max(maxHeight, pt.y); - } - - if (wHint != SWT.DEFAULT) - maxWidth = wHint; - if (hHint != SWT.DEFAULT) - maxHeight = hHint; - - return new Point(maxWidth, maxHeight); - - } - - protected void layout(Composite composite, boolean flushCache) { - Rectangle rect = composite.getClientArea(); - - Control[] children = composite.getChildren(); - for (int i = 0; i < children.length; i++) { - children[i].setBounds(rect); - } - } -} - diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/AbstractColorPage.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/AbstractColorPage.java deleted file mode 100644 index 14e3b06a8b..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/AbstractColorPage.java +++ /dev/null @@ -1,282 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2007 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.preferences.ui; - -import org.eclipse.swt.SWT; -import org.eclipse.swt.custom.ScrolledComposite; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Group; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.Text; -import org.eclipse.ui.IWorkbench; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; -import org.eclipse.wst.sse.ui.internal.preferences.OverlayPreferenceStore; - -/** - * @deprecated - */ -public abstract class AbstractColorPage extends org.eclipse.jface.preference.PreferencePage implements org.eclipse.ui.IWorkbenchPreferencePage { - protected OverlayPreferenceStore fOverlayStore; - protected StyledTextColorPicker fPicker = null; - - /** - * Creates the coloring group used in createContents This method can be - * overwritten to set the text of the group or provide an infopop - */ - protected Composite createColoringComposite(Composite parent) { - Composite coloringComposite = createComposite(parent, 1); - return coloringComposite; - } - - /** - * Creates composite control and sets the default layout data. - */ - protected Composite createComposite(Composite parent, int numColumns) { - Composite composite = new Composite(parent, SWT.NULL); - - //GridLayout - GridLayout layout = new GridLayout(); - layout.numColumns = numColumns; - layout.marginHeight = 0; - layout.marginWidth = 0; - composite.setLayout(layout); - - //GridData - GridData data = new GridData(GridData.FILL); - data.verticalAlignment = GridData.FILL; - data.horizontalAlignment = GridData.FILL; - composite.setLayoutData(data); - return composite; - } - - protected Control createContents(Composite parent) { - // create scrollbars for this preference page when needed - final ScrolledComposite sc1 = new ScrolledComposite(parent, SWT.H_SCROLL | SWT.V_SCROLL); - sc1.setLayoutData(new GridData(GridData.FILL_BOTH)); - Composite pageComponent = createComposite(sc1, 1); - sc1.setContent(pageComponent); - setSize(pageComponent); - - Label descLabel = createDescriptionLabel(pageComponent, SSEUIMessages.AbstractColorPageDescription); //$NON-NLS-1$ - Composite coloringComposite = createColoringComposite(pageComponent); - createContentsForPicker(coloringComposite); - - GridData gd = (GridData) descLabel.getLayoutData(); - gd.widthHint = (coloringComposite.computeSize(SWT.DEFAULT, SWT.DEFAULT)).x; - setSize(pageComponent); - return pageComponent; - } - - /** - * Creates the StyledTextColorPicker used in createContents This method - * can be overwritten to set up StyledTextColorPicker differently - */ - protected void createContentsForPicker(Composite parent) { - // create the color picker - fPicker = new StyledTextColorPicker(parent, SWT.NULL); - GridData data = new GridData(GridData.FILL_BOTH); - fPicker.setLayoutData(data); - - fPicker.setPreferenceStore(fOverlayStore); - setupPicker(fPicker); - - fPicker.setText(getSampleText()); - } - - /** - * Create description label displayed at top of preference page. This - * method/label is used instead of PreferencePage's description label - * because the ScrolledComposite contained in this page will not fully - * work (horizontal scrolling) with PreferencePage's description label. - */ - protected Label createDescriptionLabel(Composite parent, String description) { - Label label = new Label(parent, SWT.LEFT | SWT.WRAP); - label.setText(description); - - GridData data = new GridData(GridData.FILL_HORIZONTAL); - data.grabExcessHorizontalSpace = true; - label.setLayoutData(data); - - return label; - } - - /** - * Creates composite control and sets the default layout data. - */ - - protected Group createGroup(Composite parent, int numColumns) { - Group group = new Group(parent, SWT.NULL); - - //GridLayout - GridLayout layout = new GridLayout(); - layout.numColumns = numColumns; - group.setLayout(layout); - - //GridData - GridData data = new GridData(GridData.FILL); - data.verticalAlignment = GridData.FILL; - data.horizontalAlignment = GridData.FILL; - data.grabExcessHorizontalSpace = true; - group.setLayoutData(data); - - return group; - } - - /** - * Utility method that creates a label instance and sets the default - * layout data. - */ - protected Label createLabel(Composite parent, String text) { - Label label = new Label(parent, SWT.LEFT); - label.setText(text); - GridData data = new GridData(GridData.FILL); - data.horizontalAlignment = GridData.FILL; - label.setLayoutData(data); - return label; - } - - protected OverlayPreferenceStore.OverlayKey[] createOverlayStoreKeys() { - return null; - } - - protected Button createPushButton(Composite parent, String label) { - Button button = new Button(parent, SWT.PUSH); - button.setText(label); - GridData data = new GridData(GridData.FILL); - data.horizontalAlignment = GridData.FILL; - button.setLayoutData(data); - return button; - } - - /** - * Utility method that creates a text instance and sets the default layout - * data. - */ - protected Text createTextField(Composite parent, String text) { - Text textfield = new Text(parent, SWT.LEFT); - textfield.setText(text); - GridData data = new GridData(GridData.FILL); - data.horizontalAlignment = GridData.FILL; - textfield.setLayoutData(data); - return textfield; - } - - public void dispose() { - super.dispose(); - if (fPicker != null && !fPicker.isDisposed()) - fPicker.releasePickerResources(); - if (fOverlayStore != null) { - fOverlayStore.stop(); - } - } - - public StyledTextColorPicker getPicker() { - return fPicker; - } - - public abstract String getSampleText(); - - /** - * Initializes this preference page for the given workbench. - * <p> - * This method is called automatically as the preference page is being - * created and initialized. Clients must not call this method. - * </p> - * - * @param workbench - * the workbench - */ - public void init(IWorkbench workbench) { - fOverlayStore = new OverlayPreferenceStore(getPreferenceStore(), createOverlayStoreKeys()); - fOverlayStore.load(); - fOverlayStore.start(); - } - - /** - * Initializes states of the controls using default values in the - * preference store. - */ - protected void performDefaults() { - fOverlayStore.loadDefaults(); - fPicker.refresh(); - } - - public boolean performOk() { - fOverlayStore.propagate(); - savePreferences(); - return true; - } - - protected void savePreferences() { - // save plugin preferences here - } - - /** - * Sets the size of composite to the default value - */ - protected void setSize(Composite composite) { - if (composite != null) { - // Note: The font is set here in anticipation that the class inheriting - // this base class may add widgets to the dialog. setSize - // is assumed to be called just before we go live. - applyDialogFont(composite); - Point minSize = composite.computeSize(SWT.DEFAULT, SWT.DEFAULT); - composite.setSize(minSize); - // set scrollbar composite's min size so page is expandable but - // has scrollbars when needed - if (composite.getParent() instanceof ScrolledComposite) { - ScrolledComposite sc1 = (ScrolledComposite) composite.getParent(); - sc1.setMinSize(minSize); - sc1.setExpandHorizontal(true); - sc1.setExpandVertical(true); - } - } - } - - protected abstract void setupPicker(StyledTextColorPicker picker); - - public void setVisible(boolean visible) { - boolean doShrink = false; - // limiter, for the really huge fonts - if (visible) { - getPicker().refresh(); - int x = Math.min(getControl().getShell().getSize().x, getControl().getDisplay().getClientArea().width * 9 / 10); - int y = Math.min(getControl().getShell().getSize().y, getControl().getDisplay().getClientArea().height * 9 / 10); - boolean shrinkWidth = (x != getControl().getShell().getSize().x); - boolean shrinkHeight = (y != getControl().getShell().getSize().y); - doShrink = shrinkWidth || shrinkHeight; - if (doShrink) { - // modify just the height - if (shrinkHeight && !shrinkWidth) - getShell().setBounds(getShell().getLocation().x, 0, getShell().getSize().x, getControl().getDisplay().getClientArea().height); - // modify just the width - else if (!shrinkHeight && shrinkWidth) - getShell().setBounds(0, getShell().getLocation().y, getControl().getDisplay().getClientArea().width, getShell().getSize().y); - // change the entire shell size to only fill the display, and - // move it to the origin - else - getShell().setBounds(0, 0, getControl().getDisplay().getClientArea().width, getControl().getDisplay().getClientArea().height); - } - } - super.setVisible(visible); - if (doShrink) { - getControl().getShell().redraw(); - getControl().getShell().update(); - } - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/AbstractPreferencePage.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/AbstractPreferencePage.java deleted file mode 100644 index 0e69c18b91..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/AbstractPreferencePage.java +++ /dev/null @@ -1,296 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2006 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.preferences.ui; - -import org.eclipse.core.runtime.Preferences; -import org.eclipse.jface.preference.PreferencePage; -import org.eclipse.osgi.util.NLS; -import org.eclipse.swt.SWT; -import org.eclipse.swt.custom.BusyIndicator; -import org.eclipse.swt.custom.ScrolledComposite; -import org.eclipse.swt.events.ModifyEvent; -import org.eclipse.swt.events.ModifyListener; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.events.SelectionListener; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.widgets.Combo; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Group; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.Text; -import org.eclipse.ui.IWorkbench; -import org.eclipse.ui.IWorkbenchPreferencePage; -import org.eclipse.wst.sse.core.internal.SSECorePlugin; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; -import org.eclipse.wst.sse.ui.internal.SSEUIPlugin; - -/** - * (pa) why is this class abstract if there are no abstract methods? - */ -public abstract class AbstractPreferencePage extends PreferencePage implements ModifyListener, SelectionListener, IWorkbenchPreferencePage { - - protected final static int WIDTH_VALIDATION_LOWER_LIMIT = 0; //$NON-NLS-1$ - protected final static int WIDTH_VALIDATION_UPPER_LIMIT = 999; //$NON-NLS-1$ - - protected Button createCheckBox(Composite group, String label) { - Button button = new Button(group, SWT.CHECK | SWT.LEFT); - button.setText(label); - - //GridData - GridData data = new GridData(GridData.FILL); - data.verticalAlignment = GridData.CENTER; - data.horizontalAlignment = GridData.FILL; - button.setLayoutData(data); - - return button; - } - - protected void initCheckbox(Button box, String key) { - if(box != null && key != null) { - box.setSelection(getPreferenceStore().getBoolean(key)); - } - } - - protected void defaultCheckbox(Button box, String key) { - if(box != null && key != null) { - box.setSelection(getPreferenceStore().getDefaultBoolean(key)); - } - } - - protected Composite createComposite(Composite parent, int numColumns) { - Composite composite = new Composite(parent, SWT.NULL); - - //GridLayout - GridLayout layout = new GridLayout(); - layout.numColumns = numColumns; - composite.setLayout(layout); - - //GridData - GridData data = new GridData(GridData.FILL); - data.horizontalIndent = 0; - data.verticalAlignment = GridData.FILL; - data.horizontalAlignment = GridData.FILL; - composite.setLayoutData(data); - - return composite; - } - - protected Control createContents(Composite parent) { - return createScrolledComposite(parent); - } - - protected Combo createDropDownBox(Composite parent) { - Combo comboBox = new Combo(parent, SWT.DROP_DOWN | SWT.READ_ONLY); - - //GridData - GridData data = new GridData(); - data.verticalAlignment = GridData.CENTER; - data.horizontalAlignment = GridData.FILL; - data.grabExcessHorizontalSpace = true; - comboBox.setLayoutData(data); - - return comboBox; - } - - protected Group createGroup(Composite parent, int numColumns) { - Group group = new Group(parent, SWT.NULL); - - //GridLayout - GridLayout layout = new GridLayout(); - layout.numColumns = numColumns; - group.setLayout(layout); - - //GridData - GridData data = new GridData(GridData.FILL); - data.horizontalIndent = 0; - data.verticalAlignment = GridData.FILL; - data.horizontalAlignment = GridData.FILL; - data.grabExcessHorizontalSpace = true; - group.setLayoutData(data); - - return group; - } - - protected Label createLabel(Composite parent, String text) { - Label label = new Label(parent, SWT.LEFT); - label.setText(text); - - - //GridData - GridData data = new GridData(GridData.FILL); - data.verticalAlignment = GridData.CENTER; - data.horizontalAlignment = GridData.FILL; - label.setLayoutData(data); - - return label; - } - - protected Button createRadioButton(Composite group, String label) { - Button button = new Button(group, SWT.RADIO); - button.setText(label); - - //GridData - GridData data = new GridData(GridData.FILL); - data.verticalAlignment = GridData.CENTER; - data.horizontalAlignment = GridData.FILL; - button.setLayoutData(data); - - return button; - } - - protected Composite createScrolledComposite(Composite parent) { - // create scrollbars for this parent when needed - final ScrolledComposite sc1 = new ScrolledComposite(parent, SWT.H_SCROLL | SWT.V_SCROLL); - sc1.setLayoutData(new GridData(GridData.FILL_BOTH)); - Composite composite = createComposite(sc1, 1); - sc1.setContent(composite); - - // not calling setSize for composite will result in a blank composite, - // so calling it here initially - // setSize actually needs to be called after all controls are created, - // so scrolledComposite - // has correct minSize - setSize(composite); - return composite; - } - - protected Label createSeparator(Composite parent, int columnSpan) { - // Create a spacer line - Label separator = new Label(parent, SWT.SEPARATOR | SWT.HORIZONTAL); - - //GridData - GridData data = new GridData(GridData.FILL); - data.verticalAlignment = GridData.CENTER; - data.horizontalAlignment = GridData.FILL; - data.horizontalSpan = columnSpan; - - separator.setLayoutData(data); - return separator; - } - - protected Text createTextField(Composite parent) { - Text text = new Text(parent, SWT.SINGLE | SWT.BORDER); - - //GridData - GridData data = new GridData(); - data.verticalAlignment = GridData.CENTER; - data.horizontalAlignment = GridData.FILL; - data.grabExcessHorizontalSpace = true; - text.setLayoutData(data); - - return text; - } - - protected void enableValues() { - } - - protected Preferences getModelPreferences() { - return SSECorePlugin.getDefault().getPluginPreferences(); - } - - public void init(IWorkbench workbench) { - } - - protected void initializeValues() { - } - - protected boolean loadPreferences() { - BusyIndicator.showWhile(getControl().getDisplay(), new Runnable() { - public void run() { - initializeValues(); - validateValues(); - enableValues(); - } - }); - return true; - } - - public void modifyText(ModifyEvent e) { - // If we are called too early, i.e. before the controls are created - // then return - // to avoid null pointer exceptions - if (e.widget != null && e.widget.isDisposed()) - return; - - validateValues(); - enableValues(); - } - - protected void performDefaults() { - super.performDefaults(); - } - - public boolean performOk() { - savePreferences(); - return true; - } - - protected boolean savePreferences() { - BusyIndicator.showWhile(getControl().getDisplay(), new Runnable() { - public void run() { - storeValues(); - } - }); - return true; - } - - protected void setInvalidInputMessage(String widthText) { - String msg = NLS.bind(SSEUIMessages._4concat, (new Object[]{widthText})); - setErrorMessage(msg); - } - - protected void setSize(Composite composite) { - if (composite != null) { - // Note: The font is set here in anticipation that the class inheriting - // this base class may add widgets to the dialog. setSize - // is assumed to be called just before we go live. - applyDialogFont(composite); - Point minSize = composite.computeSize(SWT.DEFAULT, SWT.DEFAULT); - composite.setSize(minSize); - // set scrollbar composite's min size so page is expandable but - // has scrollbars when needed - if (composite.getParent() instanceof ScrolledComposite) { - ScrolledComposite sc1 = (ScrolledComposite) composite.getParent(); - sc1.setMinSize(minSize); - sc1.setExpandHorizontal(true); - sc1.setExpandVertical(true); - } - } - } - - protected void storeValues() { - SSEUIPlugin.getDefault().savePluginPreferences(); - } - - protected void validateValues() { - } - - public void widgetDefaultSelected(SelectionEvent e) { - widgetSelected(e); - } - - public void widgetSelected(SelectionEvent e) { - // If we are called too early, i.e. before the controls are created - // then return - // to avoid null pointer exceptions - if (e.widget != null && e.widget.isDisposed()) - return; - - validateValues(); - enableValues(); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/AbstractPreferenceTab.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/AbstractPreferenceTab.java deleted file mode 100644 index 4af18ad307..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/AbstractPreferenceTab.java +++ /dev/null @@ -1,266 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.preferences.ui; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import org.eclipse.core.runtime.IStatus; -import org.eclipse.jface.dialogs.Dialog; -import org.eclipse.jface.dialogs.IMessageProvider; -import org.eclipse.jface.preference.PreferencePage; -import org.eclipse.jface.resource.JFaceResources; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.ModifyEvent; -import org.eclipse.swt.events.ModifyListener; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.events.SelectionListener; -import org.eclipse.swt.graphics.FontMetrics; -import org.eclipse.swt.graphics.GC; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.Text; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; -import org.eclipse.wst.sse.ui.internal.preferences.OverlayPreferenceStore; - -/** - * Generic preference tab page that contains helpful methods - * - * @author amywu - */ -abstract public class AbstractPreferenceTab implements IPreferenceTab { - - Map fCheckBoxes = new HashMap(); - private SelectionListener fCheckBoxListener = new SelectionListener() { - public void widgetDefaultSelected(SelectionEvent e) { - } - - public void widgetSelected(SelectionEvent e) { - Button button = (Button) e.widget; - fOverlayStore.setValue((String) fCheckBoxes.get(button), button.getSelection()); - } - }; - private PreferencePage fMainPreferencePage; - private ModifyListener fNumberFieldListener = new ModifyListener() { - public void modifyText(ModifyEvent e) { - numberFieldChanged((Text) e.widget); - } - }; - private ArrayList fNumberFields = new ArrayList(); - OverlayPreferenceStore fOverlayStore; - private ModifyListener fTextFieldListener = new ModifyListener() { - public void modifyText(ModifyEvent e) { - Text text = (Text) e.widget; - fOverlayStore.setValue((String) fTextFields.get(text), text.getText()); - } - }; - Map fTextFields = new HashMap(); - - protected Button addCheckBox(Composite parent, String label, String key, int indentation) { - Button checkBox = new Button(parent, SWT.CHECK); - checkBox.setText(label); - - GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); - gd.horizontalIndent = indentation; - gd.horizontalSpan = 2; - checkBox.setLayoutData(gd); - checkBox.addSelectionListener(fCheckBoxListener); - - fCheckBoxes.put(checkBox, key); - - return checkBox; - } - - /** - * Returns an array of size 2: - first element is of type - * <code>Label</code>- second element is of type <code>Text</code> - * Use <code>getLabelControl</code> and <code>getTextControl</code> to - * get the 2 controls. - */ - private Control[] addLabelledTextField(Composite composite, String label, String key, int textLimit, int indentation, boolean isNumber) { - Label labelControl = new Label(composite, SWT.NONE); - labelControl.setText(label); - GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); - gd.horizontalIndent = indentation; - labelControl.setLayoutData(gd); - - Text textControl = new Text(composite, SWT.BORDER | SWT.SINGLE); - gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); - gd.widthHint = convertWidthInCharsToPixels(textControl, textLimit + 1); - textControl.setLayoutData(gd); - textControl.setTextLimit(textLimit); - fTextFields.put(textControl, key); - if (isNumber) { - fNumberFields.add(textControl); - textControl.addModifyListener(fNumberFieldListener); - } else { - textControl.addModifyListener(fTextFieldListener); - } - - return new Control[]{labelControl, textControl}; - } - - protected Text addTextField(Composite composite, String label, String key, int textLimit, int indentation, boolean isNumber) { - return getTextControl(addLabelledTextField(composite, label, key, textLimit, indentation, isNumber)); - } - - /** - * Applies the status to the status line of a dialog page. - */ - private void applyToStatusLine(IStatus status) { - String message = status.getMessage(); - switch (status.getSeverity()) { - case IStatus.OK : - fMainPreferencePage.setMessage(message, IMessageProvider.NONE); - fMainPreferencePage.setErrorMessage(null); - break; - case IStatus.WARNING : - fMainPreferencePage.setMessage(message, IMessageProvider.WARNING); - fMainPreferencePage.setErrorMessage(null); - break; - case IStatus.INFO : - fMainPreferencePage.setMessage(message, IMessageProvider.INFORMATION); - fMainPreferencePage.setErrorMessage(null); - break; - default : - if (message.length() == 0) { - message = null; - } - fMainPreferencePage.setMessage(null); - fMainPreferencePage.setErrorMessage(message); - break; - } - } - - /** - * Returns the number of pixels corresponding to the width of the given - * number of characters. This method was copied from - * org.eclipse.jface.dialogs.DialogPage - * <p> - * - * @param a - * control in the page - * @param chars - * the number of characters - * @return the number of pixels - */ - private int convertWidthInCharsToPixels(Control testControl, int chars) { - // Compute and store a font metric - GC gc = new GC(testControl); - gc.setFont(JFaceResources.getDialogFont()); - FontMetrics fontMetrics = gc.getFontMetrics(); - gc.dispose(); - - // test for failure to initialize for backward compatibility - if (fontMetrics == null) - return 0; - return Dialog.convertWidthInCharsToPixels(fontMetrics, chars); - } - - /** - * @return Returns the fMainPreferencePage. - */ - protected PreferencePage getMainPreferencePage() { - return fMainPreferencePage; - } - - /** - * @return Returns the fOverlayStore. - */ - protected OverlayPreferenceStore getOverlayStore() { - return fOverlayStore; - } - - private Text getTextControl(Control[] labelledTextField) { - return (Text) labelledTextField[1]; - } - - protected void initializeFields() { - Iterator e = fCheckBoxes.keySet().iterator(); - while (e.hasNext()) { - Button b = (Button) e.next(); - String key = (String) fCheckBoxes.get(b); - b.setSelection(fOverlayStore.getBoolean(key)); - } - - e = fTextFields.keySet().iterator(); - while (e.hasNext()) { - Text t = (Text) e.next(); - String key = (String) fTextFields.get(t); - t.setText(fOverlayStore.getString(key)); - } - } - - void numberFieldChanged(Text textControl) { - String number = textControl.getText(); - IStatus status = validatePositiveNumber(number); - if (!status.matches(IStatus.ERROR)) - fOverlayStore.setValue((String) fTextFields.get(textControl), number); - updateStatus(status); - } - - /** - * @param mainPreferencePage - * The fMainPreferencePage to set. - */ - protected void setMainPreferencePage(PreferencePage mainPreferencePage) { - fMainPreferencePage = mainPreferencePage; - } - - /** - * @param overlayStore - * The fOverlayStore to set. - */ - protected void setOverlayStore(OverlayPreferenceStore overlayStore) { - fOverlayStore = overlayStore; - } - - /** - * Update status of main preference page - * - * @param status - */ - protected void updateStatus(IStatus status) { - if (!status.matches(IStatus.ERROR)) { - for (int i = 0; i < fNumberFields.size(); i++) { - Text text = (Text) fNumberFields.get(i); - IStatus s = validatePositiveNumber(text.getText()); - status = s.getSeverity() > status.getSeverity() ? s : status; - } - } - - fMainPreferencePage.setValid(!status.matches(IStatus.ERROR)); - applyToStatusLine(status); - } - - private IStatus validatePositiveNumber(String number) { - StatusInfo status = new StatusInfo(); - if (number.length() == 0) { - status.setError(SSEUIMessages.StructuredTextEditorPreferencePage_37); - } else { - try { - int value = Integer.parseInt(number); - if (value < 0) - status.setError(number + SSEUIMessages.StructuredTextEditorPreferencePage_38); - } catch (NumberFormatException e) { - status.setError(number + SSEUIMessages.StructuredTextEditorPreferencePage_38); - } - } - return status; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/AbstractSyntaxColoringPage.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/AbstractSyntaxColoringPage.java deleted file mode 100644 index ea182194f6..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/AbstractSyntaxColoringPage.java +++ /dev/null @@ -1,170 +0,0 @@ -/****************************************************************************** - * Copyright (c) 2011 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - ******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.preferences.ui; - -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.preference.PreferenceConverter; -import org.eclipse.jface.preference.PreferencePage; -import org.eclipse.jface.text.source.ISourceViewer; -import org.eclipse.jface.util.IPropertyChangeListener; -import org.eclipse.jface.util.PropertyChangeEvent; -import org.eclipse.swt.custom.StyledText; -import org.eclipse.swt.graphics.Color; -import org.eclipse.swt.graphics.RGB; -import org.eclipse.swt.widgets.Display; -import org.eclipse.ui.editors.text.EditorsUI; -import org.eclipse.ui.texteditor.AbstractTextEditor; - -public abstract class AbstractSyntaxColoringPage extends PreferencePage { - - private Color fForegroundColor; - private Color fBackgroundColor; - private Color fSelectionForegroundColor; - private Color fSelectionBackgroundColor; - - final private IPropertyChangeListener fListener = new IPropertyChangeListener() { - - public void propertyChange(PropertyChangeEvent event) { - final String property = event.getProperty(); - if (AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND.equals(property) || AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND_SYSTEM_DEFAULT.equals(property) || AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND.equals(property) || AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT.equals(property) || AbstractTextEditor.PREFERENCE_COLOR_SELECTION_FOREGROUND.equals(property) || AbstractTextEditor.PREFERENCE_COLOR_SELECTION_FOREGROUND_SYSTEM_DEFAULT.equals(property) || AbstractTextEditor.PREFERENCE_COLOR_SELECTION_BACKGROUND.equals(property) || AbstractTextEditor.PREFERENCE_COLOR_SELECTION_BACKGROUND_SYSTEM_DEFAULT.equals(property)) { - initializeSourcePreviewColors(getSourcePreviewViewer()); - } - } - }; - - public AbstractSyntaxColoringPage() { - final IPreferenceStore store = EditorsUI.getPreferenceStore(); - if (store != null) { - store.addPropertyChangeListener(fListener); - } - } - - /** - * Initializes the colors of the source preview window based on the values in the Editors' UI preference store - * - * @param viewer the {@link ISourceViewer} used as the source preview - */ - protected void initializeSourcePreviewColors(ISourceViewer viewer) { - final IPreferenceStore store = EditorsUI.getPreferenceStore(); - if (store != null && viewer != null) { - - final StyledText styledText = viewer.getTextWidget(); - - // ----------- foreground color -------------------- - Color color = store.getBoolean(AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND_SYSTEM_DEFAULT) ? null : createColor(store, AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND, styledText.getDisplay()); - styledText.setForeground(color); - - if (fForegroundColor != null) - fForegroundColor.dispose(); - - fForegroundColor = color; - - // ---------- background color ---------------------- - color = store.getBoolean(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT) ? null : createColor(store, AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND, styledText.getDisplay()); - styledText.setBackground(color); - - if (fBackgroundColor != null) - fBackgroundColor.dispose(); - - fBackgroundColor = color; - - // ----------- selection foreground color -------------------- - color = store.getBoolean(AbstractTextEditor.PREFERENCE_COLOR_SELECTION_FOREGROUND_SYSTEM_DEFAULT) ? null : createColor(store, AbstractTextEditor.PREFERENCE_COLOR_SELECTION_FOREGROUND, styledText.getDisplay()); - styledText.setSelectionForeground(color); - - if (fSelectionForegroundColor != null) - fSelectionForegroundColor.dispose(); - - fSelectionForegroundColor = color; - - // ---------- selection background color ---------------------- - color = store.getBoolean(AbstractTextEditor.PREFERENCE_COLOR_SELECTION_BACKGROUND_SYSTEM_DEFAULT) ? null : createColor(store, AbstractTextEditor.PREFERENCE_COLOR_SELECTION_BACKGROUND, styledText.getDisplay()); - styledText.setSelectionBackground(color); - - if (fSelectionBackgroundColor != null) - fSelectionBackgroundColor.dispose(); - - fSelectionBackgroundColor = color; - } - } - - /** - * Provides the {@link ISourceViewer} that is acting as the source preview - * @return - */ - protected ISourceViewer getSourcePreviewViewer() { - return null; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.dialogs.DialogPage#dispose() - */ - public void dispose() { - if (fForegroundColor != null) { - fForegroundColor.dispose(); - fForegroundColor = null; - } - if (fBackgroundColor != null) { - fBackgroundColor.dispose(); - fBackgroundColor = null; - } - if (fSelectionForegroundColor != null) { - fSelectionForegroundColor.dispose(); - fSelectionForegroundColor = null; - } - if (fSelectionBackgroundColor != null) { - fSelectionBackgroundColor.dispose(); - fSelectionBackgroundColor = null; - } - if (fListener != null) { - final IPreferenceStore store = EditorsUI.getPreferenceStore(); - if (store != null) { - store.removePropertyChangeListener(fListener); - } - } - super.dispose(); - } - - /** - * Creates a color from the information stored in the given preference - * store. Returns <code>null</code> if there is no such information - * available. - * - * @param store - * the store to read from - * @param key - * the key used for the lookup in the preference store - * @param display - * the display used create the color - * @return the created color according to the specification in the - * preference store - * @since 2.0 - */ - private Color createColor(IPreferenceStore store, String key, Display display) { - - RGB rgb = null; - - if (store.contains(key)) { - - if (store.isDefault(key)) - rgb = PreferenceConverter.getDefaultColor(store, key); - else - rgb = PreferenceConverter.getColor(store, key); - - if (rgb != null) - return new Color(display, rgb); - } - - return null; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/AbstractValidationSettingsPage.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/AbstractValidationSettingsPage.java deleted file mode 100644 index 32fbb58198..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/AbstractValidationSettingsPage.java +++ /dev/null @@ -1,421 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.preferences.ui; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.ProjectScope; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.jobs.Job; -import org.eclipse.core.runtime.preferences.DefaultScope; -import org.eclipse.core.runtime.preferences.IEclipsePreferences; -import org.eclipse.core.runtime.preferences.IPreferencesService; -import org.eclipse.core.runtime.preferences.IScopeContext; -import org.eclipse.jface.dialogs.IDialogSettings; -import org.eclipse.jface.resource.JFaceResources; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.events.SelectionListener; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Combo; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.MessageBox; -import org.eclipse.swt.widgets.Widget; -import org.eclipse.ui.forms.events.ExpansionAdapter; -import org.eclipse.ui.forms.events.ExpansionEvent; -import org.eclipse.ui.forms.widgets.ExpandableComposite; -import org.eclipse.wst.sse.core.internal.validate.ValidationMessage; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; -import org.eclipse.wst.validation.ValidationFramework; -import org.osgi.service.prefs.BackingStoreException; - -/** - * Based on org.eclipse.jdt.internal.ui.preferences.OptionsConfigurationBlock - */ -public abstract class AbstractValidationSettingsPage extends PropertyPreferencePage { - - private List fCombos; - protected List fExpandables; - - private SelectionListener fSelectionListener; - - private IPreferencesService fPreferencesService = null; - - private static final String SETTINGS_EXPANDED = "expanded"; //$NON-NLS-1$ - - private ValidationFramework fValidation; - - private class ComboData { - private String fKey; - private int[] fSeverities; - private int fIndex; - int originalSeverity = -2; - - public ComboData(String key, int[] severities, int index) { - fKey = key; - fSeverities = severities; - fIndex = index; - } - - public String getKey() { - return fKey; - } - - public void setIndex(int index) { - fIndex = index; - } - - public int getIndex() { - return fIndex; - } - - /** - * Sets the severity index based on <code>severity</code>. - * If the severity doesn't exist, the index is set to -1. - * - * @param severity the severity level - */ - public void setSeverity(int severity) { - for(int i = 0; fSeverities != null && i < fSeverities.length; i++) { - if(fSeverities[i] == severity) { - fIndex = i; - return; - } - } - - fIndex = -1; - } - - public int getSeverity() { - return (fIndex >= 0 && fSeverities != null && fIndex < fSeverities.length) ? fSeverities[fIndex] : -1; - } - - boolean isChanged() { - return fSeverities[fIndex] != originalSeverity; - } - } - - public AbstractValidationSettingsPage() { - super(); - fCombos = new ArrayList(); - fExpandables = new ArrayList(); - fPreferencesService = Platform.getPreferencesService(); - fValidation = ValidationFramework.getDefault(); - } - - /** - * Creates a Combo widget in the composite <code>parent</code>. The data - * in the Combo is associated with <code>key</code>. The Combo data is - * generated based on the integer <code>values</code> where the index - * of <code>values</code> corresponds to the index of <code>valueLabels</code> - * - * @param parent the composite to create the combo box in - * @param label the label to give the combo box - * @param key the unique key to identify the combo box - * @param values the values represented by the combo options - * @param valueLabels the calues displayed in the combo box - * @param indent how far to indent the combo box label - * - * @return the generated combo box - */ - protected Combo addComboBox(Composite parent, String label, String key, int[] values, String[] valueLabels, int indent) { - GridData gd= new GridData(GridData.FILL, GridData.CENTER, true, false, 2, 1); - gd.horizontalIndent= indent; - - Label labelControl= new Label(parent, SWT.LEFT); - labelControl.setFont(JFaceResources.getDialogFont()); - labelControl.setText(label); - labelControl.setLayoutData(gd); - - Combo comboBox= newComboControl(parent, key, values, valueLabels); - comboBox.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); - - return comboBox; - } - - /** - * Creates a combo box and associates the combo data with the - * combo box. - * - * @param composite the composite to create the combo box in - * @param key the unique key to identify the combo box - * @param values the values represented by the combo options - * @param valueLabels the values displayed in the combo box - * - * @return the generated combo box - */ - protected Combo newComboControl(Composite composite, String key, int[] values, String[] valueLabels) { - ComboData data = new ComboData(key, values, -1); - - Combo comboBox= new Combo(composite, SWT.READ_ONLY); - comboBox.setItems(valueLabels); - comboBox.setData(data); - comboBox.addSelectionListener(getSelectionListener()); - comboBox.setFont(JFaceResources.getDialogFont()); - - makeScrollableCompositeAware(comboBox); - - int severity = -1; - if(key != null) - severity = fPreferencesService.getInt(getPreferenceNodeQualifier(), key, ValidationMessage.WARNING, createPreferenceScopes()); - - if (severity == ValidationMessage.ERROR || severity == ValidationMessage.WARNING || severity == ValidationMessage.IGNORE) { - data.setSeverity(severity); - data.originalSeverity = severity; - } - - if(data.getIndex() >= 0) - comboBox.select(data.getIndex()); - - fCombos.add(comboBox); - return comboBox; - } - - protected SelectionListener getSelectionListener() { - if (fSelectionListener == null) { - fSelectionListener= new SelectionListener() { - public void widgetDefaultSelected(SelectionEvent e) {} - - public void widgetSelected(SelectionEvent e) { - controlChanged(e.widget); - } - }; - } - return fSelectionListener; - } - - protected void controlChanged(Widget widget) { - ComboData data= (ComboData) widget.getData(); - if (widget instanceof Combo) { - data.setIndex(((Combo)widget).getSelectionIndex()); - } else { - return; - } - } - - /* - * (non-Javadoc) - * @see org.eclipse.wst.sse.ui.internal.preferences.ui.AbstractSettingsPage#storeValues() - */ - protected void storeValues() { - if(fCombos == null || fCombos.size() == 0) - return; - - Iterator it = fCombos.iterator(); - - IScopeContext[] contexts = createPreferenceScopes(); - - while(it.hasNext()) { - ComboData data = (ComboData) ((Combo)it.next()).getData(); - if(data.getKey() != null) { - contexts[0].getNode(getPreferenceNodeQualifier()).putInt(data.getKey(), data.getSeverity()); - } - } - - for(int i = 0; i < contexts.length; i++) { - try { - contexts[i].getNode(getPreferenceNodeQualifier()).flush(); - } - catch (BackingStoreException e) { - - } - } - } - - protected ExpandableComposite getParentExpandableComposite(Control control) { - Control parent= control.getParent(); - while (!(parent instanceof ExpandableComposite) && parent != null) { - parent= parent.getParent(); - } - if (parent instanceof ExpandableComposite) { - return (ExpandableComposite) parent; - } - return null; - } - - protected ExpandableComposite createStyleSection(Composite parent, String label, int nColumns) { - ExpandableComposite excomposite= new ExpandableComposite(parent, SWT.NONE, ExpandableComposite.TWISTIE | ExpandableComposite.CLIENT_INDENT); - excomposite.setText(label); - excomposite.setExpanded(false); - excomposite.setFont(JFaceResources.getFontRegistry().getBold(JFaceResources.DIALOG_FONT)); - excomposite.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false, nColumns, 1)); - excomposite.addExpansionListener(new ExpansionAdapter() { - public void expansionStateChanged(ExpansionEvent e) { - expandedStateChanged((ExpandableComposite) e.getSource()); - } - }); - fExpandables.add(excomposite); - makeScrollableCompositeAware(excomposite); - return excomposite; - } - - protected Composite createStyleSectionWithContentComposite(Composite parent, String label, int nColumns) { - ExpandableComposite excomposite = new ExpandableComposite(parent, SWT.NONE, ExpandableComposite.TWISTIE | ExpandableComposite.CLIENT_INDENT); - excomposite.setText(label); - excomposite.setExpanded(false); - excomposite.setFont(JFaceResources.getFontRegistry().getBold(JFaceResources.DIALOG_FONT)); - excomposite.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false, nColumns, 1)); - excomposite.addExpansionListener(new ExpansionAdapter() { - public void expansionStateChanged(ExpansionEvent e) { - expandedStateChanged((ExpandableComposite) e.getSource()); - } - }); - fExpandables.add(excomposite); - makeScrollableCompositeAware(excomposite); - - Composite inner = new Composite(excomposite, SWT.NONE); - inner.setFont(excomposite.getFont()); - inner.setLayout(new GridLayout(nColumns, false)); - excomposite.setClient(inner); - return inner; - } - - protected final void expandedStateChanged(ExpandableComposite expandable) { - ScrolledPageContent parentScrolledComposite= getParentScrolledComposite(expandable); - if (parentScrolledComposite != null) { - parentScrolledComposite.reflow(true); - } - } - - protected void makeScrollableCompositeAware(Control control) { - ScrolledPageContent parentScrolledComposite= getParentScrolledComposite(control); - if (parentScrolledComposite != null) { - parentScrolledComposite.adaptChild(control); - } - } - - protected ScrolledPageContent getParentScrolledComposite(Control control) { - Control parent= control.getParent(); - while (!(parent instanceof ScrolledPageContent) && parent != null) { - parent= parent.getParent(); - } - if (parent instanceof ScrolledPageContent) { - return (ScrolledPageContent) parent; - } - return null; - } - - protected void storeSectionExpansionStates(IDialogSettings section) { - for(int i = 0; i < fExpandables.size(); i++) { - ExpandableComposite comp = (ExpandableComposite) fExpandables.get(i); - section.put(SETTINGS_EXPANDED + String.valueOf(i), comp.isExpanded()); - } - } - - protected void restoreSectionExpansionStates(IDialogSettings settings) { - for (int i= 0; i < fExpandables.size(); i++) { - ExpandableComposite excomposite= (ExpandableComposite) fExpandables.get(i); - if (settings == null) { - excomposite.setExpanded(i == 0); // only expand the first node by default - } else { - excomposite.setExpanded(settings.getBoolean(SETTINGS_EXPANDED + String.valueOf(i))); - } - } - } - - protected void resetSeverities() { - IEclipsePreferences defaultContext = new DefaultScope().getNode(getPreferenceNodeQualifier()); - for(int i = 0; i < fCombos.size(); i++) { - ComboData data = (ComboData)((Combo)fCombos.get(i)).getData(); - int severity = defaultContext.getInt(data.getKey(), ValidationMessage.WARNING); - data.setSeverity(severity); - ((Combo)fCombos.get(i)).select(data.getIndex()); - } - } - - protected boolean shouldRevalidateOnSettingsChange() { - Iterator it = fCombos.iterator(); - - while (it.hasNext()) { - ComboData data = (ComboData) ((Combo) it.next()).getData(); - if (data.isChanged()) - return true; - } - return false; - } - - public boolean performOk() { - if(super.performOk() && shouldRevalidateOnSettingsChange()) { - MessageBox mb = new MessageBox(this.getShell(), SWT.APPLICATION_MODAL | SWT.YES | SWT.NO | SWT.CANCEL | SWT.ICON_INFORMATION | SWT.RIGHT); - mb.setText(SSEUIMessages.Validation_Title); - /* Choose which message to use based on if its project or workspace settings */ - String msg = (getProject() == null) ? SSEUIMessages.Validation_Workspace : SSEUIMessages.Validation_Project; - mb.setMessage(msg); - switch(mb.open()) { - case SWT.CANCEL: - return false; - case SWT.YES: - storeValues(); - ValidateJob job = new ValidateJob(SSEUIMessages.Validation_jobName); - job.schedule(); - case SWT.NO: - storeValues(); - default: - return true; - } - } - return true; - } - - /** - * Performs validation after validation preferences have been modified. - */ - private class ValidateJob extends Job { - - public ValidateJob(String name) { - super(name); - } - - protected IStatus run(IProgressMonitor monitor) { - IStatus status = Status.OK_STATUS; - try { - IProject[] projects = null; - /* Changed preferences for a single project, only validate it */ - if(getProject() != null) - projects = new IProject[] {getProject()}; - /* Workspace-wide preferences changed */ - else { - /* Get all of the projects in the workspace */ - projects = ResourcesPlugin.getWorkspace().getRoot().getProjects(); - IEclipsePreferences prefs = null; - List projectList = new ArrayList(); - - /* Filter out projects that use project-specific settings or have been closed */ - for(int i = 0; i < projects.length; i++) { - prefs = new ProjectScope(projects[i]).getNode(getPreferenceNodeQualifier()); - if(projects[i].isAccessible() && !prefs.getBoolean(getProjectSettingsKey(), false)) - projectList.add(projects[i]); - } - projects = (IProject[]) projectList.toArray(new IProject[projectList.size()]); - } - fValidation.validate(projects, true, false, monitor); - } - catch (CoreException ce) { - status = Status.CANCEL_STATUS; - } - - return status; - } - - } - -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/ColorEditor.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/ColorEditor.java deleted file mode 100644 index fc1d168202..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/ColorEditor.java +++ /dev/null @@ -1,142 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.preferences.ui; - -import org.eclipse.jface.resource.JFaceResources; -import org.eclipse.swt.SWT; -import org.eclipse.swt.accessibility.ACC; -import org.eclipse.swt.accessibility.AccessibleControlAdapter; -import org.eclipse.swt.accessibility.AccessibleControlEvent; -import org.eclipse.swt.events.DisposeEvent; -import org.eclipse.swt.events.DisposeListener; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.graphics.Color; -import org.eclipse.swt.graphics.Font; -import org.eclipse.swt.graphics.GC; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.graphics.RGB; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.widgets.ColorDialog; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Display; - -/** - * A "button" of a certain color determined by the color picker. - */ -public class ColorEditor { - Button fButton; - Color fColor; - RGB fColorValue; - - private Point fExtent; - Image fImage; - - public ColorEditor(Composite parent) { - - fButton = new Button(parent, SWT.PUSH); - fExtent = computeImageSize(parent); - fImage = new Image(parent.getDisplay(), fExtent.x, fExtent.y); - - GC gc = new GC(fImage); - gc.setBackground(fButton.getBackground()); - gc.fillRectangle(0, 0, fExtent.x, fExtent.y); - gc.dispose(); - - fButton.setImage(fImage); - - // bug2541 - associate color value to button's value field - fButton.getAccessible().addAccessibleControlListener(new AccessibleControlAdapter() { - /** - * @see org.eclipse.swt.accessibility.AccessibleControlAdapter#getValue(AccessibleControlEvent) - */ - public void getValue(AccessibleControlEvent e) { - if (e.childID == ACC.CHILDID_SELF) { - if (getColorValue() != null) - e.result = getColorValue().toString(); - else - e.result = null; - } - } - }); - - fButton.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent event) { - ColorDialog colorDialog = new ColorDialog(fButton.getShell()); - colorDialog.setRGB(fColorValue); - RGB newColor = colorDialog.open(); - if (newColor != null) { - fColorValue = newColor; - updateColorImage(); - } - } - }); - - fButton.addDisposeListener(new DisposeListener() { - public void widgetDisposed(DisposeEvent event) { - if (fImage != null) { - fImage.dispose(); - fImage = null; - } - if (fColor != null) { - fColor.dispose(); - fColor = null; - } - } - }); - } - - protected Point computeImageSize(Control window) { - GC gc = new GC(window); - Font f = JFaceResources.getFontRegistry().get(JFaceResources.DEFAULT_FONT); - gc.setFont(f); - int height = gc.getFontMetrics().getHeight(); - gc.dispose(); - Point p = new Point(height * 3 - 6, height); - return p; - } - - public Button getButton() { - return fButton; - } - - public RGB getColorValue() { - return fColorValue; - } - - public void setColorValue(RGB rgb) { - fColorValue = rgb; - updateColorImage(); - } - - protected void updateColorImage() { - - Display display = fButton.getDisplay(); - - GC gc = new GC(fImage); - gc.setForeground(display.getSystemColor(SWT.COLOR_BLACK)); - gc.drawRectangle(0, 2, fExtent.x - 1, fExtent.y - 4); - - if (fColor != null) - fColor.dispose(); - - fColor = new Color(display, fColorValue); - gc.setBackground(fColor); - gc.fillRectangle(1, 3, fExtent.x - 2, fExtent.y - 5); - gc.dispose(); - - fButton.setImage(fImage); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/ColorHelper.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/ColorHelper.java deleted file mode 100644 index 684da7b995..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/ColorHelper.java +++ /dev/null @@ -1,230 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.preferences.ui; - - - -import org.eclipse.jface.resource.ColorRegistry; -import org.eclipse.swt.graphics.RGB; -import org.eclipse.wst.sse.ui.internal.Logger; - -import com.ibm.icu.util.StringTokenizer; - - -public class ColorHelper { - public final static String BACKGROUND = "background";//$NON-NLS-1$ - public final static String BOLD = "bold";//$NON-NLS-1$ - public final static String FOREGROUND = "foreground";//$NON-NLS-1$ - public final static String NAME = "name";//$NON-NLS-1$ - private final static String STYLE_SEPARATOR = "|"; //$NON-NLS-1$ - private final static String NULL = "null"; //$NON-NLS-1$ - - /** - * Return an RGB String given the int r, g, b values - */ - public static String getColorString(int r, int g, int b) { - return "#" + getHexString(r, 2) + getHexString(g, 2) + getHexString(b, 2);//$NON-NLS-1$ - } - - private static String getHexString(int value, int minWidth) { - String hexString = Integer.toHexString(value); - for (int i = hexString.length(); i < minWidth; i++) { - hexString = "0" + hexString;//$NON-NLS-1$ - } - return hexString; - } - - /** - * Generates a preference string to be placed in preferences from the - * given String array. - * - * @param stylePrefs - * assumes not null and should be in the form of String[0] = - * Foreground RGB String, String[1] = Background RGB String, - * String[2] = Bold true/false - * - * @return String in the form of Foreground RGB String | Background RGB - * String | Bold true/false - */ - public static String packStylePreferences(String[] stylePrefs) { - StringBuffer styleString = new StringBuffer(); - - for (int i = 0; i < stylePrefs.length; ++i) { - String s = stylePrefs[i]; - if (i < 2) { - if (s != null) { - styleString.append(s); - } - else { - styleString.append(NULL); - } - } - else { - styleString.append(Boolean.valueOf(s)); - } - - // add in the separator (except on last iteration) - if (i < stylePrefs.length - 1) { - styleString.append(" " + STYLE_SEPARATOR + " "); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - - return styleString.toString(); - } - - /** - * @return org.eclipse.swt.graphics.RGB - * @param anRGBString - * java.lang.String - */ - public static RGB toRGB(String anRGBString) { - RGB result = null; - if (anRGBString.length() > 6 && anRGBString.charAt(0) == '#') { - int r = 0; - int g = 0; - int b = 0; - try { - r = Integer.valueOf(anRGBString.substring(1, 3), 16).intValue(); - g = Integer.valueOf(anRGBString.substring(3, 5), 16).intValue(); - b = Integer.valueOf(anRGBString.substring(5, 7), 16).intValue(); - result = new RGB(r, g, b); - } catch (NumberFormatException nfExc) { - Logger.logException("Could not load highlighting preference for color " + anRGBString, nfExc);//$NON-NLS-1$ - } - } - return result; - } - - /** - * @return java.lang.String - * @param anRGB - * org.eclipse.swt.graphics.RGB - */ - public static String toRGBString(RGB anRGB) { - if (anRGB == null) - return "#000000";//$NON-NLS-1$ - String red = Integer.toHexString(anRGB.red); - while (red.length() < 2) - red = "0" + red;//$NON-NLS-1$ - String green = Integer.toHexString(anRGB.green); - while (green.length() < 2) - green = "0" + green;//$NON-NLS-1$ - String blue = Integer.toHexString(anRGB.blue); - while (blue.length() < 2) - blue = "0" + blue;//$NON-NLS-1$ - return "#" + red + green + blue;//$NON-NLS-1$ - } - - /** - * Extracts the foreground (RGB String), background (RGB String), bold - * (boolean String) from the given preference string. - * - * @param preference - * should be in the form of Foreground RGB String | Background - * RGB String | Bold true/false | Italic true/false | Strikethrough true/false | Underline true/false - * @return String[] where String[0] = Foreground RGB String, String[1] = - * Background RGB String, String[2] = Bold true/false, 3 = Italic - * true/false, 4 = Strikethrough true/false, 5 = Underline - * true/false; indexes 2-4 may be null if we ran into problems - * extracting - */ - public static String[] unpackStylePreferences(String preference) { - String[] stylePrefs = new String[6]; - if (preference != null) { - StringTokenizer st = new StringTokenizer(preference, STYLE_SEPARATOR); - if (st.hasMoreTokens()) { - String foreground = st.nextToken().trim(); - stylePrefs[0] = foreground; - } - else { - stylePrefs[0] = NULL; - } - if (st.hasMoreTokens()) { - String background = st.nextToken().trim(); - stylePrefs[1] = background; - } - else { - stylePrefs[1] = NULL; - } - - if (st.hasMoreTokens()) { - String bold = st.nextToken().trim(); - stylePrefs[2] = Boolean.valueOf(bold).toString(); - } - else { - stylePrefs[2] = Boolean.FALSE.toString(); - } - if (st.hasMoreTokens()) { - String italic = st.nextToken().trim(); - stylePrefs[3] = Boolean.valueOf(italic).toString(); - } - else { - stylePrefs[3] = Boolean.FALSE.toString(); - } - if (st.hasMoreTokens()) { - String strikethrough = st.nextToken().trim(); - stylePrefs[4] = Boolean.valueOf(strikethrough).toString(); - } - else { - stylePrefs[4] = Boolean.FALSE.toString(); - } - if (st.hasMoreTokens()) { - String underline = st.nextToken().trim(); - stylePrefs[5] = Boolean.valueOf(underline).toString(); - } - else { - stylePrefs[5] = Boolean.FALSE.toString(); - } - } - - return stylePrefs; - } - - /** - * Attempts to lookup the RGB value for <code>key</code> from the color - * registry. If one is not found, the <code>defaultRGB</code> is used. - * @param registry The ColorRegistry to search for the RGB value - * @param key The key that the RGB value is stored under in the registry - * @param defaultRGB The default RGB value to return in the absence of one - * from the color registry - * - * @return The RGB value from the color registry for a given key, if it exists. - * Otherwise, return the default RGB value. - */ - public static RGB findRGB(ColorRegistry registry, String key, RGB defaultRGB) { - if(registry.hasValueFor(key)) - return registry.getRGB(key); - return defaultRGB; - } - - /** - * Attempts to find the RGB string for <code>key</code> from the color registry. - * If one is not found, an RGB string is generated from the parameters <code>r,g,b</code>. - * - * @param registry The ColorRegistry to search for the RGB value - * @param key The key that the RGB value is stored under in the registry - * @param r The default red value - * @param g The default green value - * @param b The default blue value - * - * @return The String RGB value from the color registry for a given key, if it exists. - * Otherwise, return the string RGB value created from the default r,g,b parameters. - * - */ - public static String findRGBString(ColorRegistry registry, String key, int r, int g, int b) { - if(registry.hasValueFor(key)) - return toRGBString(registry.getRGB(key)); - return getColorString(r, g, b); - } - -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/ColorNames.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/ColorNames.java deleted file mode 100644 index 2d0c99344b..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/ColorNames.java +++ /dev/null @@ -1,27 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.preferences.ui; - - - -public interface ColorNames { - String BACKGROUND = "background"; //$NON-NLS-1$ - String BOLD = "bold"; //$NON-NLS-1$ - String COLOR = "color"; //$NON-NLS-1$ - - String COLORS = "colors"; //$NON-NLS-1$ - String FOREGROUND = "foreground"; //$NON-NLS-1$ - String ITALIC = "italic"; //$NON-NLS-1$ - - String NAME = "name"; //$NON-NLS-1$ -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/EmptyFilePreferencePage.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/EmptyFilePreferencePage.java deleted file mode 100644 index 6536e9a5d9..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/EmptyFilePreferencePage.java +++ /dev/null @@ -1,100 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2006 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.preferences.ui; - -import org.eclipse.jface.preference.PreferencePage; -import org.eclipse.swt.SWT; -import org.eclipse.swt.custom.ScrolledComposite; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Text; -import org.eclipse.ui.IWorkbench; -import org.eclipse.ui.IWorkbenchPreferencePage; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; - -public class EmptyFilePreferencePage extends PreferencePage implements IWorkbenchPreferencePage { - - private Composite createComposite(Composite parent, int numColumns) { - noDefaultAndApplyButton(); - - Composite composite = new Composite(parent, SWT.NULL); - - // GridLayout - GridLayout layout = new GridLayout(); - layout.numColumns = numColumns; - composite.setLayout(layout); - - // GridData - GridData data = new GridData(GridData.FILL); - data.horizontalIndent = 0; - data.verticalAlignment = GridData.FILL; - data.horizontalAlignment = GridData.FILL; - composite.setLayoutData(data); - - return composite; - } - - protected Control createContents(Composite parent) { - Composite composite = createScrolledComposite(parent); - - String description = SSEUIMessages.EmptyFilePreferencePage_0; //$NON-NLS-1$ - Text text = new Text(composite, SWT.READ_ONLY); - // some themes on GTK have different background colors for Text and Labels - text.setBackground(composite.getBackground()); - text.setText(description); - - setSize(composite); - return composite; - } - - private Composite createScrolledComposite(Composite parent) { - // create scrollbars for this parent when needed - final ScrolledComposite sc1 = new ScrolledComposite(parent, SWT.H_SCROLL | SWT.V_SCROLL); - sc1.setLayoutData(new GridData(GridData.FILL_BOTH)); - Composite composite = createComposite(sc1, 1); - sc1.setContent(composite); - - // not calling setSize for composite will result in a blank composite, - // so calling it here initially - // setSize actually needs to be called after all controls are created, - // so scrolledComposite - // has correct minSize - setSize(composite); - return composite; - } - - public void init(IWorkbench workbench) { - } - - private void setSize(Composite composite) { - if (composite != null) { - // Note: The font is set here in anticipation that the class inheriting - // this base class may add widgets to the dialog. setSize - // is assumed to be called just before we go live. - applyDialogFont(composite); - Point minSize = composite.computeSize(SWT.DEFAULT, SWT.DEFAULT); - composite.setSize(minSize); - // set scrollbar composite's min size so page is expandable but - // has scrollbars when needed - if (composite.getParent() instanceof ScrolledComposite) { - ScrolledComposite sc1 = (ScrolledComposite) composite.getParent(); - sc1.setMinSize(minSize); - sc1.setExpandHorizontal(true); - sc1.setExpandVertical(true); - } - } - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/FilePreferencePage.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/FilePreferencePage.java deleted file mode 100644 index 6c86535850..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/FilePreferencePage.java +++ /dev/null @@ -1,132 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.preferences.ui; - -import org.eclipse.jface.preference.PreferencePage; -import org.eclipse.swt.SWT; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.TabFolder; -import org.eclipse.swt.widgets.TabItem; -import org.eclipse.ui.IWorkbench; -import org.eclipse.ui.IWorkbenchPreferencePage; -import org.eclipse.wst.sse.core.internal.SSECorePlugin; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; -import org.eclipse.wst.sse.ui.internal.preferences.TabFolderLayout; - -public class FilePreferencePage extends PreferencePage implements IWorkbenchPreferencePage { - - private IPreferenceTab[] fTabs = null; - - protected Composite createComposite(Composite parent, int numColumns) { - Composite composite = new Composite(parent, SWT.NULL); - - //GridLayout - GridLayout layout = new GridLayout(); - layout.numColumns = numColumns; - composite.setLayout(layout); - - //GridData - GridData data = new GridData(GridData.FILL); - data.horizontalIndent = 0; - data.verticalAlignment = GridData.FILL_VERTICAL; - data.horizontalAlignment = GridData.FILL_HORIZONTAL; - composite.setLayoutData(data); - - return composite; - } - - protected Control createContents(Composite parent) { - Composite composite = createComposite(parent, 1); - - String description = SSEUIMessages.FilePreferencePage_0; //$NON-NLS-1$ - createLabel(composite, description); - createLabel(composite, ""); //$NON-NLS-1$ - - TabFolder folder = new TabFolder(composite, SWT.NONE); - folder.setLayout(new TabFolderLayout()); - folder.setLayoutData(new GridData(GridData.FILL_BOTH)); - -// TabItem taskItem = new TabItem(folder, SWT.NONE); -// IPreferenceTab tasksTab = new TaskTagPreferenceTab(); -// taskItem.setText(tasksTab.getTitle()); -// Control taskTags = tasksTab.createContents(folder); -// taskItem.setControl(taskTags); - - TabItem translucenceItem = new TabItem(folder, SWT.NONE); - IPreferenceTab translucenceTab = new TranslucencyPreferenceTab(this); - translucenceItem.setText(translucenceTab.getTitle()); - Control translucenceControl = translucenceTab.createContents(folder); - translucenceItem.setControl(translucenceControl); - - fTabs = new IPreferenceTab[]{/*tasksTab,*/ translucenceTab}; - - return composite; - } - - protected Label createLabel(Composite parent, String text) { - Label label = new Label(parent, SWT.LEFT); - label.setText(text); - - //GridData - GridData data = new GridData(GridData.FILL); - data.horizontalAlignment = GridData.HORIZONTAL_ALIGN_FILL; - label.setLayoutData(data); - - return label; - } - - public void init(IWorkbench desktop) { - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.preference.PreferencePage#performApply() - */ - protected void performApply() { - super.performApply(); - for (int i = 0; i < fTabs.length; i++) { - fTabs[i].performApply(); - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.preference.PreferencePage#performDefaults() - */ - protected void performDefaults() { - super.performDefaults(); - for (int i = 0; i < fTabs.length; i++) { - fTabs[i].performDefaults(); - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.preference.IPreferencePage#performOk() - */ - public boolean performOk() { - boolean ok = super.performOk(); - for (int i = 0; i < fTabs.length; i++) { - fTabs[i].performOk(); - } - SSECorePlugin.getDefault().savePluginPreferences(); - return ok; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/IPreferenceTab.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/IPreferenceTab.java deleted file mode 100644 index 2ccb563c9d..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/IPreferenceTab.java +++ /dev/null @@ -1,29 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.preferences.ui; - -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; - -public interface IPreferenceTab { - - Control createContents(Composite tabFolder); - - String getTitle(); - - void performApply(); - - void performDefaults(); - - void performOk(); -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/ScrolledPageContent.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/ScrolledPageContent.java deleted file mode 100644 index e1f9c43514..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/ScrolledPageContent.java +++ /dev/null @@ -1,49 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.preferences.ui; - -import org.eclipse.swt.SWT; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.ui.forms.widgets.FormToolkit; -import org.eclipse.ui.forms.widgets.SharedScrolledComposite; -import org.eclipse.wst.sse.ui.internal.SSEUIPlugin; - -public class ScrolledPageContent extends SharedScrolledComposite { - - private FormToolkit fToolkit; - - public ScrolledPageContent(Composite parent) { - this(parent, SWT.V_SCROLL | SWT.H_SCROLL); - } - - public ScrolledPageContent(Composite parent, int style) { - super(parent, style); - - setExpandHorizontal(true); - setExpandVertical(true); - - fToolkit = SSEUIPlugin.getInstance().getDialogsFormToolkit(); - - Composite body= new Composite(this, SWT.NONE); - body.setFont(parent.getFont()); - setContent(body); - } - - public void adaptChild(Control childControl) { - fToolkit.adapt(childControl, true, true); - } - - public Composite getBody() { - return (Composite) getContent(); - } - -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/StatusInfo.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/StatusInfo.java deleted file mode 100644 index c783131970..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/StatusInfo.java +++ /dev/null @@ -1,202 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.preferences.ui; - -import org.eclipse.core.runtime.IStatus; -import org.eclipse.jface.util.Assert; -import org.eclipse.ui.editors.text.EditorsUI; - -/** - * A settable IStatus. Can be an error, warning, info or ok. For error, info - * and warning states, a message describes the problem. - * - * This class was copied from other StatusInfo classes that are located in - * internal packages - */ -class StatusInfo implements IStatus { - /** The severity of this status. */ - private int fSeverity; - - /** The message of this status. */ - private String fStatusMessage; - - /** - * Creates a status set to OK (no message). - */ - public StatusInfo() { - this(OK, null); - } - - /** - * Creates a status with the given severity and message. - * - * @param severity - * the severity of this status: ERROR, WARNING, INFO and OK. - * @param message - * the message of this status. Applies only for ERROR, WARNING - * and INFO. - */ - public StatusInfo(int severity, String message) { - fStatusMessage = message; - fSeverity = severity; - } - - /** - * Returns always <code>null</code>. - * - * @see IStatus#getChildren() - */ - public IStatus[] getChildren() { - return new IStatus[0]; - } - - /** - * Returns always the error severity. - * - * @see IStatus#getCode() - */ - public int getCode() { - return fSeverity; - } - - /** - * Returns always <code>null</code>. - * - * @see IStatus#getException() - */ - public Throwable getException() { - return null; - } - - /* - * @see IStatus#getMessage() - */ - public String getMessage() { - return fStatusMessage; - } - - /* - * @see IStatus#getPlugin() - */ - public String getPlugin() { - return EditorsUI.PLUGIN_ID; - } - - /* - * @see IStatus#getSeverity() - */ - public int getSeverity() { - return fSeverity; - } - - /** - * Returns whether this status indicates an error. - * - * @return <code>true</code> if this status has severity - * {@link IStatus#ERROR}and <code>false</code> otherwise - */ - public boolean isError() { - return fSeverity == IStatus.ERROR; - } - - /** - * Returns whether this status indicates an info. - * - * @return <code>true</code> if this status has severity - * {@link IStatus#INFO}and <code>false</code> otherwise - */ - public boolean isInfo() { - return fSeverity == IStatus.INFO; - } - - /** - * Returns always <code>false</code>. - * - * @see IStatus#isMultiStatus() - */ - public boolean isMultiStatus() { - return false; - } - - /* - * @see org.eclipse.core.runtime.IStatus#isOK() - */ - public boolean isOK() { - return fSeverity == IStatus.OK; - } - - /** - * Returns whether this status indicates a warning. - * - * @return <code>true</code> if this status has severity - * {@link IStatus#WARNING}and <code>false</code> otherwise - */ - public boolean isWarning() { - return fSeverity == IStatus.WARNING; - } - - /* - * @see IStatus#matches(int) - */ - public boolean matches(int severityMask) { - return (fSeverity & severityMask) != 0; - } - - /** - * Sets the status to ERROR. - * - * @param errorMessage - * the error message which can be an empty string, but not - * <code>null</code> - */ - public void setError(String errorMessage) { - Assert.isNotNull(errorMessage); - fStatusMessage = errorMessage; - fSeverity = IStatus.ERROR; - } - - /** - * Sets the status to INFO. - * - * @param infoMessage - * the info message which can be an empty string, but not - * <code>null</code> - */ - public void setInfo(String infoMessage) { - Assert.isNotNull(infoMessage); - fStatusMessage = infoMessage; - fSeverity = IStatus.INFO; - } - - /** - * Sets the status to OK. - */ - public void setOK() { - fStatusMessage = null; - fSeverity = IStatus.OK; - } - - /** - * Sets the status to WARNING. - * - * @param warningMessage - * the warning message which can be an empty string, but not - * <code>null</code> - */ - public void setWarning(String warningMessage) { - Assert.isNotNull(warningMessage); - fStatusMessage = warningMessage; - fSeverity = IStatus.WARNING; - } - -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/StructuredTextEditorPreferencePage.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/StructuredTextEditorPreferencePage.java deleted file mode 100644 index dd9ee295ea..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/StructuredTextEditorPreferencePage.java +++ /dev/null @@ -1,461 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.preferences.ui; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import org.eclipse.core.runtime.IStatus; -import org.eclipse.jface.dialogs.Dialog; -import org.eclipse.jface.dialogs.DialogPage; -import org.eclipse.jface.dialogs.IMessageProvider; -import org.eclipse.jface.preference.PreferenceConverter; -import org.eclipse.jface.preference.PreferencePage; -import org.eclipse.swt.SWT; -import org.eclipse.swt.accessibility.ACC; -import org.eclipse.swt.accessibility.AccessibleAdapter; -import org.eclipse.swt.accessibility.AccessibleEvent; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.events.SelectionListener; -import org.eclipse.swt.graphics.RGB; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.List; -import org.eclipse.swt.widgets.TabFolder; -import org.eclipse.swt.widgets.TabItem; -import org.eclipse.swt.widgets.Text; -import org.eclipse.ui.IWorkbench; -import org.eclipse.ui.IWorkbenchPreferencePage; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.dialogs.PreferenceLinkArea; -import org.eclipse.ui.preferences.IWorkbenchPreferenceContainer; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; -import org.eclipse.wst.sse.ui.internal.SSEUIPlugin; -import org.eclipse.wst.sse.ui.internal.editor.IHelpContextIds; -import org.eclipse.wst.sse.ui.internal.preferences.EditorPreferenceNames; -import org.eclipse.wst.sse.ui.internal.preferences.OverlayPreferenceStore; -import org.eclipse.wst.sse.ui.internal.preferences.TabFolderLayout; -import org.eclipse.wst.sse.ui.internal.projection.AbstractStructuredFoldingStrategy; -import org.eclipse.wst.sse.ui.internal.provisional.preferences.CommonEditorPreferenceNames; - -/** - * Gutted version of JavaEditorPreferencePage - * - * @author pavery - */ -public class StructuredTextEditorPreferencePage extends PreferencePage implements IWorkbenchPreferencePage { - private ColorEditor fAppearanceColorEditor; - private List fAppearanceColorList; - - private final String[][] fAppearanceColorListModel = new String[][]{{SSEUIMessages.StructuredTextEditorPreferencePage_2, EditorPreferenceNames.MATCHING_BRACKETS_COLOR}, {SSEUIMessages.StructuredTextEditorPreferencePage_41, EditorPreferenceNames.CODEASSIST_PROPOSALS_BACKGROUND}, {SSEUIMessages.StructuredTextEditorPreferencePage_42, EditorPreferenceNames.CODEASSIST_PROPOSALS_FOREGROUND}, {SSEUIMessages.StructuredTextEditorPreferencePage_43, EditorPreferenceNames.CODEASSIST_PARAMETERS_BACKGROUND}, {SSEUIMessages.StructuredTextEditorPreferencePage_44, EditorPreferenceNames.CODEASSIST_PARAMETERS_FOREGROUND}}; //$NON-NLS-1$ - private Map fCheckBoxes = new HashMap(); - private SelectionListener fCheckBoxListener = new SelectionListener() { - public void widgetDefaultSelected(SelectionEvent e) { - } - - public void widgetSelected(SelectionEvent e) { - Button button = (Button) e.widget; - fOverlayStore.setValue((String) fCheckBoxes.get(button), button.getSelection()); - } - }; - - private Map fColorButtons = new HashMap(); - - private ArrayList fNumberFields = new ArrayList(); - private OverlayPreferenceStore fOverlayStore; - /** Button controlling default setting of the selected reference provider. */ - // TODO: private field never read locally - Button fSetDefaultButton; - private IPreferenceTab[] fTabs = null; - private Map fTextFields = new HashMap(); - - public StructuredTextEditorPreferencePage() { - setDescription(SSEUIMessages.StructuredTextEditorPreferencePage_6); //$NON-NLS-1$ - setPreferenceStore(SSEUIPlugin.getDefault().getPreferenceStore()); - - fOverlayStore = new OverlayPreferenceStore(getPreferenceStore(), createOverlayStoreKeys()); - } - - private Button addCheckBox(Composite parent, String label, String key, int indentation) { - Button checkBox = new Button(parent, SWT.CHECK); - checkBox.setText(label); - - GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); - gd.horizontalIndent = indentation; - gd.horizontalSpan = 2; - checkBox.setLayoutData(gd); - checkBox.addSelectionListener(fCheckBoxListener); - - fCheckBoxes.put(checkBox, key); - - return checkBox; - } - - /** - * Applies the status to the status line of a dialog page. - */ - public void applyToStatusLine(DialogPage page, IStatus status) { - String message = status.getMessage(); - switch (status.getSeverity()) { - case IStatus.OK : - page.setMessage(message, IMessageProvider.NONE); - page.setErrorMessage(null); - break; - case IStatus.WARNING : - page.setMessage(message, IMessageProvider.WARNING); - page.setErrorMessage(null); - break; - case IStatus.INFO : - page.setMessage(message, IMessageProvider.INFORMATION); - page.setErrorMessage(null); - break; - default : - if (message.length() == 0) { - message = null; - } - page.setMessage(null); - page.setErrorMessage(message); - break; - } - } - - private Control createAppearancePage(Composite parent) { - Composite appearanceComposite = new Composite(parent, SWT.NONE); - GridLayout layout = new GridLayout(); - layout.numColumns = 2; - appearanceComposite.setLayout(layout); - - String label = SSEUIMessages.StructuredTextEditorPreferencePage_20; //$NON-NLS-1$ - addCheckBox(appearanceComposite, label, EditorPreferenceNames.MATCHING_BRACKETS, 0); - - label = SSEUIMessages.StructuredTextEditorPreferencePage_30; //$NON-NLS-1$ - addCheckBox(appearanceComposite, label, CommonEditorPreferenceNames.EVALUATE_TEMPORARY_PROBLEMS, 0); - - PreferenceLinkArea contentTypeArea = new PreferenceLinkArea(appearanceComposite, SWT.NONE, "ValidationPreferencePage", SSEUIMessages.StructuredTextEditorPreferencePage_40, (IWorkbenchPreferenceContainer) getContainer(), null); //$NON-NLS-1$ - - GridData data = new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL); - data.horizontalIndent = 20; - contentTypeArea.getControl().setLayoutData(data); - - label = SSEUIMessages.StructuredTextEditorPreferencePage_39; - addCheckBox(appearanceComposite, label, EditorPreferenceNames.SHOW_UNKNOWN_CONTENT_TYPE_MSG, 0); - - label = SSEUIMessages.StructuredTextEditorPreferencePage_3; - addCheckBox(appearanceComposite, label, AbstractStructuredFoldingStrategy.FOLDING_ENABLED, 0); - - label = SSEUIMessages.StructuredTextEditorPreferencePage_1; - addCheckBox(appearanceComposite, label, EditorPreferenceNames.SEMANTIC_HIGHLIGHTING, 0); - - Label l = new Label(appearanceComposite, SWT.LEFT); - GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); - gd.horizontalSpan = 2; - gd.heightHint = convertHeightInCharsToPixels(1) / 2; - l.setLayoutData(gd); - - l = new Label(appearanceComposite, SWT.LEFT); - l.setText(SSEUIMessages.StructuredTextEditorPreferencePage_23); //$NON-NLS-1$ - gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); - gd.horizontalSpan = 2; - l.setLayoutData(gd); - - Composite editorComposite = new Composite(appearanceComposite, SWT.NONE); - layout = new GridLayout(); - layout.numColumns = 2; - layout.marginHeight = 0; - layout.marginWidth = 0; - editorComposite.setLayout(layout); - gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.FILL_VERTICAL); - gd.horizontalSpan = 2; - editorComposite.setLayoutData(gd); - - fAppearanceColorList = new List(editorComposite, SWT.SINGLE | SWT.V_SCROLL | SWT.BORDER); - gd = new GridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL); - gd.heightHint = convertHeightInCharsToPixels(7); - fAppearanceColorList.setLayoutData(gd); - - Composite stylesComposite = new Composite(editorComposite, SWT.NONE); - layout = new GridLayout(); - layout.marginHeight = 0; - layout.marginWidth = 0; - layout.numColumns = 2; - stylesComposite.setLayout(layout); - stylesComposite.setLayoutData(new GridData(GridData.FILL_BOTH)); - - l = new Label(stylesComposite, SWT.LEFT); - // needs to be made final so label can be set in - // foregroundcolorbutton's acc listener - final String buttonLabel = SSEUIMessages.StructuredTextEditorPreferencePage_24; //$NON-NLS-1$ - l.setText(buttonLabel); - gd = new GridData(); - gd.horizontalAlignment = GridData.BEGINNING; - l.setLayoutData(gd); - - fAppearanceColorEditor = new ColorEditor(stylesComposite); - Button foregroundColorButton = fAppearanceColorEditor.getButton(); - gd = new GridData(GridData.FILL_HORIZONTAL); - gd.horizontalAlignment = GridData.BEGINNING; - foregroundColorButton.setLayoutData(gd); - - fAppearanceColorList.addSelectionListener(new SelectionListener() { - public void widgetDefaultSelected(SelectionEvent e) { - // do nothing - } - - public void widgetSelected(SelectionEvent e) { - handleAppearanceColorListSelection(); - } - }); - foregroundColorButton.addSelectionListener(new SelectionListener() { - public void widgetDefaultSelected(SelectionEvent e) { - // do nothing - } - - public void widgetSelected(SelectionEvent e) { - int i = fAppearanceColorList.getSelectionIndex(); - String key = fAppearanceColorListModel[i][1]; - - PreferenceConverter.setValue(fOverlayStore, key, fAppearanceColorEditor.getColorValue()); - } - }); - - // bug2541 - associate color label to button's label field - foregroundColorButton.getAccessible().addAccessibleListener(new AccessibleAdapter() { - public void getName(AccessibleEvent e) { - if (e.childID == ACC.CHILDID_SELF) - e.result = buttonLabel; - } - }); - - PlatformUI.getWorkbench().getHelpSystem().setHelp(appearanceComposite, IHelpContextIds.PREFSTE_APPEARANCE_HELPID); - return appearanceComposite; - } - - /* - * @see PreferencePage#createContents(Composite) - */ - protected Control createContents(Composite parent) { - // need to create tabs before loading/starting overlaystore in case - // tabs also add values - IPreferenceTab hoversTab = new TextHoverPreferenceTab(this, fOverlayStore); - - fOverlayStore.load(); - fOverlayStore.start(); - - TabFolder folder = new TabFolder(parent, SWT.NONE); - folder.setLayout(new TabFolderLayout()); - folder.setLayoutData(new GridData(GridData.FILL_BOTH)); - - TabItem item = new TabItem(folder, SWT.NONE); - item.setText(SSEUIMessages.StructuredTextEditorPreferencePage_0); //$NON-NLS-1$ - item.setControl(createAppearancePage(folder)); - - item = new TabItem(folder, SWT.NONE); - item.setText(hoversTab.getTitle()); - item.setControl(hoversTab.createContents(folder)); - - fTabs = new IPreferenceTab[]{hoversTab}; - - initialize(); - - Dialog.applyDialogFont(folder); - return folder; - } - - /* - * @see PreferencePage#createControl(Composite) - */ - public void createControl(Composite parent) { - super.createControl(parent); - // WorkbenchHelp.setHelp(getControl(), - // IJavaHelpContextIds.JAVA_EDITOR_PREFERENCE_PAGE); - } - - private OverlayPreferenceStore.OverlayKey[] createOverlayStoreKeys() { - ArrayList overlayKeys = new ArrayList(); - - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, EditorPreferenceNames.MATCHING_BRACKETS_COLOR)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, EditorPreferenceNames.MATCHING_BRACKETS)); - - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, CommonEditorPreferenceNames.EVALUATE_TEMPORARY_PROBLEMS)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, EditorPreferenceNames.SHOW_UNKNOWN_CONTENT_TYPE_MSG)); - - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, AbstractStructuredFoldingStrategy.FOLDING_ENABLED)); - - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, EditorPreferenceNames.SEMANTIC_HIGHLIGHTING)); - - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, EditorPreferenceNames.CODEASSIST_PROPOSALS_BACKGROUND)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, EditorPreferenceNames.CODEASSIST_PROPOSALS_FOREGROUND)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, EditorPreferenceNames.CODEASSIST_PARAMETERS_BACKGROUND)); - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, EditorPreferenceNames.CODEASSIST_PARAMETERS_FOREGROUND)); - - OverlayPreferenceStore.OverlayKey[] keys = new OverlayPreferenceStore.OverlayKey[overlayKeys.size()]; - overlayKeys.toArray(keys); - return keys; - } - - /* - * @see DialogPage#dispose() - */ - public void dispose() { - if (fOverlayStore != null) { - fOverlayStore.stop(); - fOverlayStore = null; - } - - super.dispose(); - } - - private void handleAppearanceColorListSelection() { - int i = fAppearanceColorList.getSelectionIndex(); - String key = fAppearanceColorListModel[i][1]; - RGB rgb = PreferenceConverter.getColor(fOverlayStore, key); - fAppearanceColorEditor.setColorValue(rgb); - } - - /* - * @see IWorkbenchPreferencePage#init() - */ - public void init(IWorkbench workbench) { - // nothing to do - } - - private void initialize() { - initializeFields(); - - for (int i = 0; i < fAppearanceColorListModel.length; i++) - fAppearanceColorList.add(fAppearanceColorListModel[i][0]); - fAppearanceColorList.getDisplay().asyncExec(new Runnable() { - public void run() { - if (fAppearanceColorList != null && !fAppearanceColorList.isDisposed()) { - fAppearanceColorList.select(0); - handleAppearanceColorListSelection(); - } - } - }); - } - - private void initializeFields() { - Iterator e = fColorButtons.keySet().iterator(); - while (e.hasNext()) { - ColorEditor c = (ColorEditor) e.next(); - String key = (String) fColorButtons.get(c); - RGB rgb = PreferenceConverter.getColor(fOverlayStore, key); - c.setColorValue(rgb); - } - - e = fCheckBoxes.keySet().iterator(); - while (e.hasNext()) { - Button b = (Button) e.next(); - String key = (String) fCheckBoxes.get(b); - b.setSelection(fOverlayStore.getBoolean(key)); - } - - e = fTextFields.keySet().iterator(); - while (e.hasNext()) { - Text t = (Text) e.next(); - String key = (String) fTextFields.get(t); - t.setText(fOverlayStore.getString(key)); - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.preference.PreferencePage#performApply() - */ - protected void performApply() { - for (int i = 0; i < fTabs.length; i++) { - fTabs[i].performApply(); - } - super.performApply(); - } - - /* - * @see PreferencePage#performDefaults() - */ - protected void performDefaults() { - fOverlayStore.loadDefaults(); - - initializeFields(); - - handleAppearanceColorListSelection(); - - for (int i = 0; i < fTabs.length; i++) { - fTabs[i].performDefaults(); - } - - super.performDefaults(); - - // there is currently no need for a viewer - // fPreviewViewer.invalidateTextPresentation(); - } - - /* - * @see PreferencePage#performOk() - */ - public boolean performOk() { - for (int i = 0; i < fTabs.length; i++) { - fTabs[i].performOk(); - } - - fOverlayStore.propagate(); - SSEUIPlugin.getDefault().savePluginPreferences(); - - // tab width is also a model-side preference so need to set it - // TODO need to handle tab width for formatter somehow - // int tabWidth = - // getPreferenceStore().getInt(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH); - // ModelPlugin.getDefault().getPluginPreferences().setValue(CommonModelPreferenceNames.TAB_WIDTH, - // tabWidth); - // ModelPlugin.getDefault().savePluginPreferences(); - - return true; - } - - void updateStatus(IStatus status) { - if (!status.matches(IStatus.ERROR)) { - for (int i = 0; i < fNumberFields.size(); i++) { - Text text = (Text) fNumberFields.get(i); - IStatus s = validatePositiveNumber(text.getText()); - status = s.getSeverity() > status.getSeverity() ? s : status; - } - } - - setValid(!status.matches(IStatus.ERROR)); - applyToStatusLine(this, status); - } - - private IStatus validatePositiveNumber(String number) { - StatusInfo status = new StatusInfo(); - if (number.length() == 0) { - status.setError(SSEUIMessages.StructuredTextEditorPreferencePage_37); - } - else { - try { - int value = Integer.parseInt(number); - if (value < 0) - status.setError(number + SSEUIMessages.StructuredTextEditorPreferencePage_38); - } - catch (NumberFormatException e) { - status.setError(number + SSEUIMessages.StructuredTextEditorPreferencePage_38); - } - } - return status; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/StyledTextColorPicker.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/StyledTextColorPicker.java deleted file mode 100644 index e69bf0d4db..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/StyledTextColorPicker.java +++ /dev/null @@ -1,905 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2006 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.preferences.ui; - -import java.io.CharArrayReader; -import java.util.Dictionary; -import java.util.List; - -import org.eclipse.jface.preference.ColorSelector; -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.resource.JFaceResources; -import org.eclipse.jface.text.TextAttribute; -import org.eclipse.jface.util.IPropertyChangeListener; -import org.eclipse.jface.util.PropertyChangeEvent; -import org.eclipse.swt.SWT; -import org.eclipse.swt.accessibility.ACC; -import org.eclipse.swt.accessibility.AccessibleAdapter; -import org.eclipse.swt.accessibility.AccessibleControlAdapter; -import org.eclipse.swt.accessibility.AccessibleControlEvent; -import org.eclipse.swt.accessibility.AccessibleControlListener; -import org.eclipse.swt.accessibility.AccessibleEvent; -import org.eclipse.swt.custom.StyleRange; -import org.eclipse.swt.custom.StyledText; -import org.eclipse.swt.events.KeyEvent; -import org.eclipse.swt.events.KeyListener; -import org.eclipse.swt.events.MouseEvent; -import org.eclipse.swt.events.MouseListener; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.events.SelectionListener; -import org.eclipse.swt.events.TraverseEvent; -import org.eclipse.swt.events.TraverseListener; -import org.eclipse.swt.graphics.Color; -import org.eclipse.swt.graphics.Font; -import org.eclipse.swt.graphics.RGB; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.widgets.Combo; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Label; -import org.eclipse.wst.sse.core.internal.ltk.parser.RegionParser; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion; -import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegion; -import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegionList; -import org.eclipse.wst.sse.core.internal.util.Debug; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; -import org.eclipse.wst.sse.ui.internal.util.EditorUtility; -import org.w3c.dom.Node; - -import com.ibm.icu.text.Collator; - -/** - * This class is configurable by setting 3 properties: 1) an array of Strings - * as the styleNames; one unique entry for every style type meant to be - * configurable by the user 2) a Dictionary of descriptions, mapping the - * styleNames to unique descriptions - meant for use within the selection - * ComboBox TODO (pa) this should probably be working off document partitions - * now (2.1+) 3) a Dictionary mapping parsed ITextRegion contexts (strings) to - * the locally defined styleNames - * - */ -public class StyledTextColorPicker extends Composite { - protected class DescriptionSorter extends org.eclipse.wst.sse.ui.internal.util.Sorter { - Collator collator = Collator.getInstance(); - - public boolean compare(Object elementOne, Object elementTwo) { - /** - * Returns true if elementTwo is 'greater than' elementOne This is - * the 'ordering' method of the sort operation. Each subclass - * overides this method with the particular implementation of the - * 'greater than' concept for the objects being sorted. - */ - return (collator.compare(elementOne.toString(), elementTwo.toString())) < 0; - } - } - - public static final String BACKGROUND = "background"; //$NON-NLS-1$ - public static final String BOLD = "bold"; //$NON-NLS-1$ - public static final String COLOR = "color"; //$NON-NLS-1$ - - // names for preference elements ... non-NLS - public static final String FOREGROUND = "foreground"; //$NON-NLS-1$ - public static final String ITALIC = "italic"; //$NON-NLS-1$ - public static final String NAME = "name"; //$NON-NLS-1$ - - protected static final boolean showItalic = false; - protected AccessibleControlListener backgroundAccListener = new AccessibleControlAdapter() { - /** - * @see org.eclipse.swt.accessibility.AccessibleControlAdapter#getValue(AccessibleControlEvent) - */ - public void getValue(AccessibleControlEvent e) { - if (e.childID == ACC.CHILDID_SELF) { - e.result = fBackground.getColorValue().toString(); - } - } - }; - protected SelectionListener buttonListener = new SelectionListener() { - - public void widgetDefaultSelected(SelectionEvent e) { - widgetSelected(e); - } - - public void widgetSelected(SelectionEvent e) { - String namedStyle = getStyleName(fStyleCombo.getItem(fStyleCombo.getSelectionIndex())); - if (namedStyle == null) - return; - if (e.widget == fBold) { - // get current (newly old) style - String prefString = getPreferenceStore().getString(namedStyle); - String[] stylePrefs = ColorHelper.unpackStylePreferences(prefString); - if (stylePrefs != null) { - String oldValue = stylePrefs[2]; - String newValue = String.valueOf(fBold.getSelection()); - if (!newValue.equals(oldValue)) { - stylePrefs[2] = newValue; - String newPrefString = ColorHelper.packStylePreferences(stylePrefs); - getPreferenceStore().setValue(namedStyle, newPrefString); - refresh(); - } - } - } else if (showItalic && e.widget == fItalic) { - // get current (newly old) style - String prefString = getPreferenceStore().getString(namedStyle); - String[] stylePrefs = ColorHelper.unpackStylePreferences(prefString); - if (stylePrefs != null) { - String oldValue = stylePrefs[3]; - String newValue = String.valueOf(fItalic.getSelection()); - if (!newValue.equals(oldValue)) { - stylePrefs[3] = newValue; - String newPrefString = ColorHelper.packStylePreferences(stylePrefs); - getPreferenceStore().setValue(namedStyle, newPrefString); - refresh(); - } - } - } else if (e.widget == fClearStyle) { - getPreferenceStore().setToDefault(namedStyle); - refresh(); - } - } - }; - - protected SelectionListener comboListener = new SelectionListener() { - - public void widgetDefaultSelected(SelectionEvent e) { - widgetSelected(e); - } - - public void widgetSelected(SelectionEvent e) { - int selectedIndex = fStyleCombo.getSelectionIndex(); - String description = selectedIndex >= 0 ? fStyleCombo.getItem(selectedIndex) : null; - activate(getStyleName(description)); - } - }; - protected ColorSelector fBackground; - protected Label fBackgroundLabel; - protected Button fBold; - protected Button fClearStyle; - // Dictionary mapping the ITextRegion types above to color names, which - // are, in turn, attributes - protected Dictionary fContextStyleMap = null; - protected Color fDefaultBackground = getDisplay().getSystemColor(SWT.COLOR_LIST_BACKGROUND); - - protected Color fDefaultForeground = getDisplay().getSystemColor(SWT.COLOR_LIST_FOREGROUND); - // Dictionary mapping the ITextRegion types above to display strings, for - // use in the combo box - protected Dictionary fDescriptions = null; - protected ColorSelector fForeground; - protected Label fForegroundLabel; -// private String fGeneratorKey; - protected String fInput = ""; //$NON-NLS-1$ - protected Button fItalic; - - private IStructuredDocumentRegion fNodes = null; - // defect 200764 - ACC:display values for color buttons - protected AccessibleControlListener foregroundAccListener = new AccessibleControlAdapter() { - /** - * @see org.eclipse.swt.accessibility.AccessibleControlAdapter#getValue(AccessibleControlEvent) - */ - public void getValue(AccessibleControlEvent e) { - if (e.childID == ACC.CHILDID_SELF) { - e.result = fForeground.getColorValue().toString(); - } - } - }; - // A RegionParser, which will turn the input into - // IStructuredDocumentRegion(s) and Regions - protected RegionParser fParser = null; - - private IPreferenceStore fPreferenceStore; - protected Combo fStyleCombo = null; - // The list of supported ITextRegion types [Strings] - protected List fStyleList = null; - - // controls in picker - protected StyledText fText = null; - - /** - * XMLTextColorPicker constructor comment. - * - * @param parent - * org.eclipse.swt.widgets.Composite - * @param style - * int - */ - public StyledTextColorPicker(Composite parent, int style) { - super(parent, style); - //GridLayout - GridLayout layout = new GridLayout(); - layout.numColumns = 1; - setLayout(layout); - createControls(this); - } - - // activate controls based on the given local color type - protected void activate(String namedStyle) { - if (namedStyle == null) { - fForeground.setEnabled(false); - fBackground.setEnabled(false); - fClearStyle.setEnabled(false); - fBold.setEnabled(false); - if (showItalic) - fItalic.setEnabled(false); - fForegroundLabel.setEnabled(false); - fBackgroundLabel.setEnabled(false); - } - else { - fForeground.setEnabled(true); - fBackground.setEnabled(true); - fClearStyle.setEnabled(true); - fBold.setEnabled(true); - if (showItalic) - fItalic.setEnabled(true); - fForegroundLabel.setEnabled(true); - fBackgroundLabel.setEnabled(true); - - } - TextAttribute attribute = getAttribute(namedStyle); - Color color = attribute.getForeground(); - if (color == null) { - color = fDefaultForeground; - } - fForeground.setColorValue(color.getRGB()); - - color = attribute.getBackground(); - if (color == null) { - color = fDefaultBackground; - } - fBackground.setColorValue(color.getRGB()); - - fBold.setSelection((attribute.getStyle() & SWT.BOLD) != 0); - if (showItalic) - fItalic.setSelection((attribute.getStyle() & SWT.ITALIC) != 0); - } - - protected void applyStyles() { - if (fText == null || fText.isDisposed() || fInput == null || fInput.length() == 0) - return; - // List regions = fParser.getRegions(); - IStructuredDocumentRegion node = fNodes; - while (node != null) { - ITextRegionList regions = node.getRegions(); - for (int i = 0; i < regions.size(); i++) { - ITextRegion currentRegion = regions.get(i); - // lookup the local coloring type and apply it - String namedStyle = (String) getContextStyleMap().get(currentRegion.getType()); - if (namedStyle == null) - continue; - TextAttribute attribute = getAttribute(namedStyle); - if (attribute == null) - continue; - StyleRange style = new StyleRange(node.getStartOffset(currentRegion), currentRegion.getLength(), attribute.getForeground(), attribute.getBackground(), attribute.getStyle()); - fText.setStyleRange(style); - } - node = node.getNext(); - } - } - - protected void close() { - } - - /** - * Creates an new checkbox instance and sets the default layout data. - * - * @param group - * the composite in which to create the checkbox - * @param label - * the string to set into the checkbox - * @return the new checkbox - */ - private Button createCheckBox(Composite group, String label) { - Button button = new Button(group, SWT.CHECK | SWT.CENTER); - if (label != null) - button.setText(label); - GridData data = new GridData(GridData.FILL_BOTH); - data.horizontalAlignment = GridData.HORIZONTAL_ALIGN_END; - // data.verticalAlignment = GridData.VERTICAL_ALIGN_FILL; - button.setLayoutData(data); - return button; - } - - private Combo createCombo(Composite parent, String[] labels, int selectedItem) { - Combo combo = new Combo(parent, SWT.DROP_DOWN | SWT.READ_ONLY); - combo.setItems(labels); - if (selectedItem >= 0) - combo.select(selectedItem); - GridData data = new GridData(GridData.FILL_HORIZONTAL); - data.horizontalAlignment = GridData.HORIZONTAL_ALIGN_FILL; - combo.setLayoutData(data); - return combo; - } - - /** - * Creates composite control and sets the default layout data. - */ - private Composite createComposite(Composite parent, int numColumns) { - Composite composite = new Composite(parent, SWT.NULL); - //GridLayout - GridLayout layout = new GridLayout(); - layout.numColumns = numColumns; - layout.horizontalSpacing = 5; - layout.makeColumnsEqualWidth = false; - composite.setLayout(layout); - //GridData - GridData data = new GridData(GridData.FILL_VERTICAL); - data.grabExcessVerticalSpace = false; - data.verticalAlignment = GridData.VERTICAL_ALIGN_CENTER; - composite.setLayoutData(data); - return composite; - } - - protected void createControls(Composite parent) { - Composite styleRow = createComposite(parent, 3); - // row 1 - content type label, combo box, restore defaults - createLabel(styleRow, SSEUIMessages.Content_type__UI_); //$NON-NLS-1$ = "Content type:" - // Contexts combo box - fStyleCombo = createCombo(styleRow, new String[0], -1); - fClearStyle = createPushButton(styleRow, SSEUIMessages.Restore_Default_UI_); //$NON-NLS-1$ = "Restore Default" - Composite styleRow2; - if (showItalic) - styleRow2 = createComposite(parent, 7); - else - styleRow2 = createComposite(parent, 6); - // row 2 - foreground label, button, background label, button, bold, - // italics? - fForegroundLabel = createLabel(styleRow2, SSEUIMessages.Foreground_UI_); //$NON-NLS-1$ = "Foreground" - fForeground = new ColorSelector(styleRow2); - fForeground.getButton().setLayoutData(new GridData()); - setAccessible(fForeground.getButton(), fForegroundLabel.getText()); - fForeground.getButton().getAccessible().addAccessibleControlListener(foregroundAccListener); // defect - // 200764 - // - - // ACC:display - // values - // for - // color - // buttons - ((GridData) fForeground.getButton().getLayoutData()).minimumWidth = 20; - fBackgroundLabel = createLabel(styleRow2, SSEUIMessages.Background_UI_); //$NON-NLS-1$ = "Background" - fBackground = new ColorSelector(styleRow2); - fBackground.getButton().setLayoutData(new GridData()); - setAccessible(fBackground.getButton(), fBackgroundLabel.getText()); - fBackground.getButton().getAccessible().addAccessibleControlListener(backgroundAccListener); // defect - // 200764 - // - - // ACC:display - // values - // for - // color - // buttons - ((GridData) fBackground.getButton().getLayoutData()).minimumWidth = 20; - createLabel(styleRow2, ""); //$NON-NLS-1$ - fBold = createCheckBox(styleRow2, SSEUIMessages.Bold_UI_); - if (showItalic) - fItalic = createCheckBox(styleRow2, SSEUIMessages.Italics_UI); - // // Defaults checkbox - fForeground.setEnabled(false); - fBackground.setEnabled(false); - fClearStyle.setEnabled(false); - fBold.setEnabled(false); - if (showItalic) - fItalic.setEnabled(false); - fForegroundLabel.setEnabled(false); - fBackgroundLabel.setEnabled(false); - Composite sample = createComposite(parent, 1); - createLabel(sample, SSEUIMessages.Sample_text__UI_); //$NON-NLS-1$ = "&Sample text:" - // BUG141089 - make sure text is left-aligned - fText = new StyledText(sample, SWT.LEFT_TO_RIGHT | SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER | SWT.READ_ONLY); - GridData data = new GridData(GridData.FILL_BOTH); - fText.setLayoutData(data); - fText.setEditable(false); - fText.setBackground(fDefaultBackground); - fText.setFont(JFaceResources.getTextFont()); - fText.addKeyListener(getTextKeyListener()); - fText.addSelectionListener(getTextSelectionListener()); - fText.addMouseListener(getTextMouseListener()); - fText.addTraverseListener(getTraverseListener()); // defect 220377 - - // Provide tab - // traversal for - // fText widget - setAccessible(fText, SSEUIMessages.Sample_text__UI_); //$NON-NLS-1$ = "&Sample text:" - fForeground.addListener(new IPropertyChangeListener() { - public void propertyChange(PropertyChangeEvent event) { - if (event.getProperty().equals(ColorSelector.PROP_COLORCHANGE)) { - // get current (newly old) style - String namedStyle = getStyleName(fStyleCombo.getItem(fStyleCombo.getSelectionIndex())); - String prefString = getPreferenceStore().getString(namedStyle); - String[] stylePrefs = ColorHelper.unpackStylePreferences(prefString); - if (stylePrefs != null) { - String oldValue = stylePrefs[0]; - String newValue = "null"; //$NON-NLS-1$ - Object newValueObject = event.getNewValue(); - if (newValueObject instanceof RGB) { - newValue = ColorHelper.toRGBString((RGB)newValueObject); - } - - if (!newValue.equals(oldValue)) { - stylePrefs[0] = newValue; - String newPrefString = ColorHelper.packStylePreferences(stylePrefs); - getPreferenceStore().setValue(namedStyle, newPrefString); - refresh(); - } - } - } - } - }); - fBackground.addListener(new IPropertyChangeListener() { - public void propertyChange(PropertyChangeEvent event) { - if (event.getProperty().equals(ColorSelector.PROP_COLORCHANGE)) { - // get current (newly old) style - String namedStyle = getStyleName(fStyleCombo.getItem(fStyleCombo.getSelectionIndex())); - String prefString = getPreferenceStore().getString(namedStyle); - String[] stylePrefs = ColorHelper.unpackStylePreferences(prefString); - if (stylePrefs != null) { - String oldValue = stylePrefs[1]; - - String newValue = "null"; //$NON-NLS-1$ - Object newValueObject = event.getNewValue(); - if (newValueObject instanceof RGB) { - newValue = ColorHelper.toRGBString((RGB)newValueObject); - } - - if (!newValue.equals(oldValue)) { - stylePrefs[1] = newValue; - String newPrefString = ColorHelper.packStylePreferences(stylePrefs); - getPreferenceStore().setValue(namedStyle, newPrefString); - refresh(); - } - } - } - } - }); - - fClearStyle.addSelectionListener(buttonListener); - fBold.addSelectionListener(buttonListener); - if (showItalic) - fItalic.addSelectionListener(buttonListener); - fStyleCombo.addSelectionListener(comboListener); - } - - /** - * Utility method that creates a label instance and sets the default - * layout data. - */ - private Label createLabel(Composite parent, String text) { - Label label = new Label(parent, SWT.LEFT); - label.setText(text); - GridData data = new GridData(); - data.horizontalAlignment = GridData.FILL; - label.setLayoutData(data); - return label; - } - - private Button createPushButton(Composite parent, String label) { - Button button = new Button(parent, SWT.PUSH); - button.setText(label); - GridData data = new GridData(GridData.FILL_BOTH); - // data.horizontalAlignment = GridData.FILL; - button.setLayoutData(data); - return button; - } - - protected TextAttribute getAttribute(String namedStyle) { - TextAttribute ta = new TextAttribute(getDefaultForeground(), getDefaultBackground(), SWT.NORMAL); - - if (namedStyle != null && getPreferenceStore() != null) { - String prefString = getPreferenceStore().getString(namedStyle); - String[] stylePrefs = ColorHelper.unpackStylePreferences(prefString); - if (stylePrefs != null) { - RGB foreground = ColorHelper.toRGB(stylePrefs[0]); - RGB background = ColorHelper.toRGB(stylePrefs[1]); - - int fontModifier = SWT.NORMAL; - boolean bold = Boolean.valueOf(stylePrefs[2]).booleanValue(); - if (bold) - fontModifier = fontModifier | SWT.BOLD; - - if (showItalic) { - boolean italic = Boolean.valueOf(stylePrefs[3]).booleanValue(); - if (italic) - fontModifier = fontModifier | SWT.ITALIC; - } - - ta = new TextAttribute((foreground != null) ? EditorUtility.getColor(foreground) : null, (background != null) ? EditorUtility.getColor(background) : null, fontModifier); - } - } - return ta; - } - - // defect 200764 - ACC:display values for color buttons - /** - * @return String - color Button b's current RBG value - */ -// private String getColorButtonValue(Button b) { -// if ((b == null) || (b.getImage() == null) || (b.getImage().getImageData() == null) || (b.getImage().getImageData().getRGBs() == null) || (b.getImage().getImageData().getRGBs()[0] == null)) -// return null; -// String val = b.getImage().getImageData().getRGBs()[0].toString(); -// return val; -// } - - /** - * @deprecated use getPreferenceStore instead left for legacy clients, - * delete by WTP M4 - */ - public Node getColorsNode() { - //return fColorsNode; - return null; - } - - /** - * @return java.util.Dictionary - */ - public Dictionary getContextStyleMap() { - return fContextStyleMap; - } - - /** - * @return org.eclipse.swt.graphics.Color - */ - public Color getDefaultBackground() { - return fDefaultBackground; - } - - /** - * @return org.eclipse.swt.graphics.Color - */ - public Color getDefaultForeground() { - return fDefaultForeground; - } - - /** - * @return java.util.Dictionary - */ - public Dictionary getDescriptions() { - return fDescriptions; - } - - public Font getFont() { - return fText.getFont(); - } - - protected String getNamedStyleAtOffset(int offset) { - // ensure the offset is clean - if (offset >= fInput.length()) - return getNamedStyleAtOffset(fInput.length() - 1); - else if (offset < 0) - return getNamedStyleAtOffset(0); - // find the ITextRegion at this offset - if (fNodes == null) - return null; - IStructuredDocumentRegion aNode = fNodes; - while (aNode != null && !aNode.containsOffset(offset)) - aNode = aNode.getNext(); - if (aNode != null) { - // find the ITextRegion's Context at this offset - ITextRegion interest = aNode.getRegionAtCharacterOffset(offset); - if (interest == null) - return null; - if (offset > aNode.getTextEndOffset(interest)) - return null; - String regionContext = interest.getType(); - if (regionContext == null) - return null; - // find the named style (internal/selectable name) for that - // context - String namedStyle = (String) getContextStyleMap().get(regionContext); - if (namedStyle != null) { - return namedStyle; - } - } - return null; - } - - - public RegionParser getParser() { - return fParser; - } - - private IPreferenceStore getPreferenceStore() { - return fPreferenceStore; - } - - /** - * @return String[] - */ - public List getStyleList() { - return fStyleList; - } - - private String getStyleName(String description) { - if (description == null) - return null; - String styleName = null; - java.util.Enumeration keys = getDescriptions().keys(); - while (keys.hasMoreElements()) { - String test = keys.nextElement().toString(); - if (getDescriptions().get(test).equals(description)) { - styleName = test; - break; - } - } - return styleName; - } - - public String getText() { - return fInput; - } - - private KeyListener getTextKeyListener() { - return new KeyListener() { - public void keyPressed(KeyEvent e) { - if (e.widget instanceof StyledText) { - int x = ((StyledText) e.widget).getCaretOffset(); - selectColorAtOffset(x); - } - } - - public void keyReleased(KeyEvent e) { - if (e.widget instanceof StyledText) { - int x = ((StyledText) e.widget).getCaretOffset(); - selectColorAtOffset(x); - } - } - }; - } - - private MouseListener getTextMouseListener() { - return new MouseListener() { - public void mouseDoubleClick(MouseEvent e) { - } - - public void mouseDown(MouseEvent e) { - } - - public void mouseUp(MouseEvent e) { - if (e.widget instanceof StyledText) { - int x = ((StyledText) e.widget).getCaretOffset(); - selectColorAtOffset(x); - } - } - }; - } - - private SelectionListener getTextSelectionListener() { - return new SelectionListener() { - public void widgetDefaultSelected(SelectionEvent e) { - selectColorAtOffset(e.x); - if (e.widget instanceof StyledText) { - ((StyledText) e.widget).setSelection(e.x); - } - } - -// Commented out when moving to RC2 to remove "unused" error/warning -// public void widgetDoubleSelected(SelectionEvent e) { -// selectColorAtOffset(e.x); -// if (e.widget instanceof StyledText) { -// ((StyledText) e.widget).setSelection(e.x); -// } -// } - - public void widgetSelected(SelectionEvent e) { - selectColorAtOffset(e.x); - if (e.widget instanceof StyledText) { - ((StyledText) e.widget).setSelection(e.x); - } - } - }; - } - - // defect 220377 - Provide tab traversal for fText widget - private TraverseListener getTraverseListener() { - return new TraverseListener() { - /** - * @see org.eclipse.swt.events.TraverseListener#keyTraversed(TraverseEvent) - */ - public void keyTraversed(TraverseEvent e) { - if (e.widget instanceof StyledText) { - if ((e.detail == SWT.TRAVERSE_TAB_NEXT) || (e.detail == SWT.TRAVERSE_TAB_PREVIOUS)) - e.doit = true; - } - } - }; - } - - // refresh the GUI after a color change - public void refresh() { - fText.setRedraw(false); - int selectedIndex = fStyleCombo.getSelectionIndex(); - String description = selectedIndex >= 0 ? fStyleCombo.getItem(selectedIndex) : null; - activate(getStyleName(description)); - // update Font - fText.setFont(JFaceResources.getTextFont()); - // reapplyStyles - applyStyles(); - fText.setRedraw(true); - } - - public void releasePickerResources() { -// if (fForeground != null && !fForeground.isDisposed() && fForeground.getImage() != null) -// fForeground.getImage().dispose(); -// if (fBackground != null && !fBackground.isDisposed() && fBackground.getImage() != null) -// fBackground.getImage().dispose(); - } - - private void selectColorAtOffset(int offset) { - String namedStyle = getNamedStyleAtOffset(offset); - if (namedStyle == null) { - fStyleCombo.deselectAll(); - activate(null); - return; - } - String description = (String) getDescriptions().get(namedStyle); - if (description == null) - return; - int itemCount = fStyleCombo.getItemCount(); - for (int i = 0; i < itemCount; i++) { - if (fStyleCombo.getItem(i).equals(description)) { - fStyleCombo.select(i); - break; - } - } - activate(namedStyle); - } - - /** - * Specifically set the reporting name of a control for accessibility - */ - private void setAccessible(Control control, String name) { - if (control == null) - return; - final String n = name; - control.getAccessible().addAccessibleListener(new AccessibleAdapter() { - public void getName(AccessibleEvent e) { - if (e.childID == ACC.CHILDID_SELF) - e.result = n; - } - }); - } - - /** - * @deprecated use setPreferenceStore instead left for legacy clients, - * delete by WTP M4 - */ - public void setColorsNode(Node newColorsNode) { - //fColorsNode = newColorsNode; - } - - /** - * @param newContextStyleMap - * java.util.Dictionary - */ - public void setContextStyleMap(Dictionary newContextStyleMap) { - fContextStyleMap = newContextStyleMap; - } - - /** - * @param newDefaultBackground - * org.eclipse.swt.graphics.Color - */ - public void setDefaultBackground(Color newDefaultBackground) { - fDefaultBackground = newDefaultBackground; - } - - /** - * @deprecated use setPreferenceStore instead left for legacy clients, - * delete by WTP M4 - */ - public void setDefaultColorsNode(Node newDefaultColorsNode) { - //fDefaultColorsNode = newDefaultColorsNode; - } - - /** - * @param newDefaultForeground - * org.eclipse.swt.graphics.Color - */ - public void setDefaultForeground(Color newDefaultForeground) { - fDefaultForeground = newDefaultForeground; - } - - /** - * @param newDescriptions - * java.util.Dictionary - */ - public void setDescriptions(Dictionary newDescriptions) { - fDescriptions = newDescriptions; - updateStyleList(); - } - - public void setFont(Font font) { - fText.setFont(font); - fText.redraw(); - } - - /** - * @deprecated generator key should no longer be needed - */ - public void setGeneratorKey(String key) { -// fGeneratorKey = key; - } - - /** - * @param newParser - */ - public void setParser(RegionParser newParser) { - fParser = newParser; - } - - public void setPreferenceStore(IPreferenceStore store) { - fPreferenceStore = store; - } - - /** - * @param newStyleList - * String[] - */ - public void setStyleList(List newStyleList) { - fStyleList = newStyleList; - updateStyleList(); - } - - public void setText(String s) { - fInput = s; - getParser().reset(new CharArrayReader(fInput.toCharArray())); - fNodes = getParser().getDocumentRegions(); - if (Debug.displayInfo) - System.out.println("Length of input: " //$NON-NLS-1$ - //$NON-NLS-1$ - + s.length() + ", " //$NON-NLS-1$ - + getParser().getRegions().size() + " regions."); //$NON-NLS-1$ - if (fText != null) - fText.setText(s); - applyStyles(); - } - - - - /** - * @return org.eclipse.swt.graphics.RGB - * @param anRGBString - * java.lang.String - * @param defaultRGB - * org.eclipse.swt.graphics.RGB - */ - // TODO: never used - RGB toRGB(String anRGBString, RGB defaultRGB) { - RGB result = ColorHelper.toRGB(anRGBString); - if (result == null) - return defaultRGB; - return result; - } - - private void updateStyleList() { - if (fStyleList == null || fDescriptions == null) - return; - String[] descriptions = new String[fStyleList.size()]; - for (int i = 0; i < fStyleList.size(); i++) { - if (fStyleList.get(i) != null) - descriptions[i] = (String) getDescriptions().get(fStyleList.get(i)); - else - descriptions[i] = (String) fStyleList.get(i); - } - Object[] sortedObjects = new DescriptionSorter().sort(descriptions); - String[] sortedDescriptions = new String[descriptions.length]; - for (int i = 0; i < descriptions.length; i++) { - sortedDescriptions[i] = sortedObjects[i].toString(); - } - fStyleCombo.setItems(sortedDescriptions); - fStyleCombo.select(0); //defect 219855 - initially select first item - // in comboBox - // fStyleCombo.deselectAll(); - } - - - -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/TextHoverPreferenceTab.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/TextHoverPreferenceTab.java deleted file mode 100644 index 100904a54b..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/TextHoverPreferenceTab.java +++ /dev/null @@ -1,453 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.preferences.ui; - -import java.util.ArrayList; -import java.util.HashMap; - -import org.eclipse.core.runtime.IStatus; -import org.eclipse.jface.action.Action; -import org.eclipse.jface.dialogs.Dialog; -import org.eclipse.jface.preference.PreferencePage; -import org.eclipse.jface.text.Assert; -import org.eclipse.jface.viewers.ArrayContentProvider; -import org.eclipse.jface.viewers.CheckStateChangedEvent; -import org.eclipse.jface.viewers.CheckboxTableViewer; -import org.eclipse.jface.viewers.ColumnWeightData; -import org.eclipse.jface.viewers.ICheckStateListener; -import org.eclipse.jface.viewers.ITableLabelProvider; -import org.eclipse.jface.viewers.LabelProvider; -import org.eclipse.jface.viewers.StructuredSelection; -import org.eclipse.jface.viewers.TableLayout; -import org.eclipse.jface.viewers.TableViewer; -import org.eclipse.osgi.util.NLS; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.KeyEvent; -import org.eclipse.swt.events.KeyListener; -import org.eclipse.swt.events.ModifyEvent; -import org.eclipse.swt.events.ModifyListener; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.events.SelectionListener; -import org.eclipse.swt.graphics.FontMetrics; -import org.eclipse.swt.graphics.GC; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.Table; -import org.eclipse.swt.widgets.TableColumn; -import org.eclipse.swt.widgets.Text; -import org.eclipse.ui.PlatformUI; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; -import org.eclipse.wst.sse.ui.internal.SSEUIPlugin; -import org.eclipse.wst.sse.ui.internal.editor.IHelpContextIds; -import org.eclipse.wst.sse.ui.internal.preferences.EditorPreferenceNames; -import org.eclipse.wst.sse.ui.internal.preferences.OverlayPreferenceStore; -import org.eclipse.wst.sse.ui.internal.taginfo.TextHoverManager; -import org.eclipse.wst.sse.ui.internal.taginfo.TextHoverManager.TextHoverDescriptor; -import org.eclipse.wst.sse.ui.internal.util.EditorUtility; - -/** - * Preference tab for Structured text editor hover help preferences - * - * @author amywu - */ -public class TextHoverPreferenceTab extends AbstractPreferenceTab { - - private class InternalTableLabelProvider extends LabelProvider implements ITableLabelProvider { - public InternalTableLabelProvider() { - super(); - } - - public Image getColumnImage(Object element, int columnIndex) { - return null; - } - - public String getColumnText(Object element, int columnIndex) { - switch (columnIndex) { - case 0 : // text hover label - return ((TextHoverManager.TextHoverDescriptor) element).getLabel(); - - case 1 : // text hover state mask - return ((TextHoverManager.TextHoverDescriptor) element).getModifierString(); - - default : - break; - } - - return null; - } - } - - private static final String DELIMITER = SSEUIMessages.TextHoverPreferenceTab_delimiter; //$NON-NLS-1$ - private Text fDescription; - private Table fHoverTable; - private TableViewer fHoverTableViewer; - private TableColumn fModifierColumn; - // for this preference page - private Text fModifierEditor; - private TableColumn fNameColumn; - - private TextHoverDescriptor[] fTextHovers; // current list of text hovers - - public TextHoverPreferenceTab(PreferencePage mainPreferencePage, OverlayPreferenceStore store) { - Assert.isNotNull(mainPreferencePage); - Assert.isNotNull(store); - setMainPreferencePage(mainPreferencePage); - setOverlayStore(store); - getOverlayStore().addKeys(createOverlayStoreKeys()); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.sse.ui.preferences.ui.IPreferenceTab#createContents(org.eclipse.swt.widgets.Composite) - */ - public Control createContents(Composite tabFolder) { - Composite hoverComposite = new Composite(tabFolder, SWT.NONE); - GridLayout layout = new GridLayout(); - layout.numColumns = 2; - hoverComposite.setLayout(layout); - GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); - hoverComposite.setLayoutData(gd); - - // commented out until these preferences are actually handled in some - // way - // String rollOverLabel= - // ResourceHandler.getString("TextHoverPreferenceTab.annotationRollover"); - // //$NON-NLS-1$ - // addCheckBox(hoverComposite, rollOverLabel, - // CommonEditorPreferenceNames.EDITOR_ANNOTATION_ROLL_OVER, 0); - // - // // Affordance checkbox - // String showAffordanceLabel = - // ResourceHandler.getString("TextHoverPreferenceTab.showAffordance"); - // //$NON-NLS-1$ - // addCheckBox(hoverComposite, showAffordanceLabel, - // CommonEditorPreferenceNames.EDITOR_SHOW_TEXT_HOVER_AFFORDANCE, 0); - - Label label = new Label(hoverComposite, SWT.NONE); - label.setText(SSEUIMessages.TextHoverPreferenceTab_hoverPreferences); //$NON-NLS-1$ - gd = new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1); - gd.horizontalAlignment = GridData.BEGINNING; - label.setLayoutData(gd); - - fHoverTableViewer = CheckboxTableViewer.newCheckList(hoverComposite, SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI | SWT.BORDER | SWT.FULL_SELECTION); - // Hover table - fHoverTable = fHoverTableViewer.getTable(); - fHoverTable.setHeaderVisible(true); - fHoverTable.setLinesVisible(true); - - gd = new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1); - // https://bugs.eclipse.org/bugs/show_bug.cgi?id=104507 - GC gc = new GC(fHoverTable); - gc.setFont(fHoverTable.getFont()); - FontMetrics fontMetrics = gc.getFontMetrics(); - gc.dispose(); - int heightHint = Dialog.convertHeightInCharsToPixels(fontMetrics, 7); - gd.heightHint = heightHint; - - fHoverTable.setLayoutData(gd); - - TableLayout tableLayout = new TableLayout(); - tableLayout.addColumnData(new ColumnWeightData(1, 140, true)); - tableLayout.addColumnData(new ColumnWeightData(1, 140, true)); - fHoverTable.setLayout(tableLayout); - - fHoverTable.addSelectionListener(new SelectionListener() { - - public void widgetDefaultSelected(SelectionEvent e) { - } - - public void widgetSelected(SelectionEvent e) { - handleHoverListSelection(); - } - }); - - fNameColumn = new TableColumn(fHoverTable, SWT.NONE); - fNameColumn.setText(SSEUIMessages.TextHoverPreferenceTab_nameColumnTitle); //$NON-NLS-1$ - fNameColumn.setResizable(true); - - fModifierColumn = new TableColumn(fHoverTable, SWT.NONE); - fModifierColumn.setText(SSEUIMessages.TextHoverPreferenceTab_modifierColumnTitle); //$NON-NLS-1$ - fModifierColumn.setResizable(true); - - fHoverTableViewer.setUseHashlookup(true); - fHoverTableViewer.setContentProvider(new ArrayContentProvider()); - fHoverTableViewer.setLabelProvider(new InternalTableLabelProvider()); - ((CheckboxTableViewer) fHoverTableViewer).addCheckStateListener(new ICheckStateListener() { - /* - * @see org.eclipse.jface.viewers.ICheckStateListener#checkStateChanged(org.eclipse.jface.viewers.CheckStateChangedEvent) - */ - public void checkStateChanged(CheckStateChangedEvent event) { - String id = ((TextHoverDescriptor) event.getElement()).getId(); - if (id == null) - return; - - TextHoverManager.TextHoverDescriptor[] descriptors = getTextHoverManager().getTextHovers(); - TextHoverManager.TextHoverDescriptor hoverConfig = null; - int i = 0, length = fTextHovers.length; - while (i < length) { - if (id.equals(descriptors[i].getId())) { - hoverConfig = fTextHovers[i]; - hoverConfig.setEnabled(event.getChecked()); - fModifierEditor.setEnabled(event.getChecked()); - fHoverTableViewer.setSelection(new StructuredSelection(descriptors[i])); - } - i++; - } - - handleHoverListSelection(); - updateStatus(hoverConfig); - } - }); - - // Text field for modifier string - label = new Label(hoverComposite, SWT.LEFT); - label.setText(SSEUIMessages.TextHoverPreferenceTab_keyModifier); //$NON-NLS-1$ - fModifierEditor = new Text(hoverComposite, SWT.BORDER); - gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL); - fModifierEditor.setLayoutData(gd); - - fModifierEditor.addKeyListener(new KeyListener() { - private boolean isModifierCandidate; - - public void keyPressed(KeyEvent e) { - isModifierCandidate = e.keyCode > 0 && e.character == 0 && e.stateMask == 0; - } - - public void keyReleased(KeyEvent e) { - if (isModifierCandidate && e.stateMask > 0 && e.stateMask == e.stateMask && e.character == 0) {// && - // e.time - // -time - // < - // 1000) - // { - String text = fModifierEditor.getText(); - Point selection = fModifierEditor.getSelection(); - int i = selection.x - 1; - while (i > -1 && Character.isWhitespace(text.charAt(i))) { - i--; - } - boolean needsPrefixDelimiter = i > -1 && !String.valueOf(text.charAt(i)).equals(DELIMITER); - - i = selection.y; - while (i < text.length() && Character.isWhitespace(text.charAt(i))) { - i++; - } - boolean needsPostfixDelimiter = i < text.length() && !String.valueOf(text.charAt(i)).equals(DELIMITER); - - String insertString; - - if (needsPrefixDelimiter && needsPostfixDelimiter) - insertString = NLS.bind(SSEUIMessages.TextHoverPreferenceTab_insertDelimiterAndModifierAndDelimiter, new String[]{Action.findModifierString(e.stateMask)}); - else if (needsPrefixDelimiter) - insertString = NLS.bind(SSEUIMessages.TextHoverPreferenceTab_insertDelimiterAndModifier, new String[]{Action.findModifierString(e.stateMask)}); - else if (needsPostfixDelimiter) - insertString = NLS.bind(SSEUIMessages.TextHoverPreferenceTab_insertModifierAndDelimiter, new String[]{Action.findModifierString(e.stateMask)}); - else - insertString = Action.findModifierString(e.stateMask); - - if (insertString != null) - fModifierEditor.insert(insertString); - } - } - }); - - fModifierEditor.addModifyListener(new ModifyListener() { - public void modifyText(ModifyEvent e) { - handleModifierModified(); - } - }); - - // Description - Label descriptionLabel = new Label(hoverComposite, SWT.LEFT); - descriptionLabel.setText(SSEUIMessages.TextHoverPreferenceTab_description); //$NON-NLS-1$ - gd = new GridData(GridData.VERTICAL_ALIGN_BEGINNING); - gd.horizontalSpan = 2; - descriptionLabel.setLayoutData(gd); - fDescription = new Text(hoverComposite, SWT.LEFT | SWT.WRAP | SWT.MULTI | SWT.READ_ONLY | SWT.BORDER); - gd = new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1); - gd.horizontalSpan = 2; - fDescription.setLayoutData(gd); - - initialize(); - - Dialog.applyDialogFont(hoverComposite); - - PlatformUI.getWorkbench().getHelpSystem().setHelp(hoverComposite, IHelpContextIds.PREFSTE_HOVERS_HELPID); - return hoverComposite; - } - - private OverlayPreferenceStore.OverlayKey[] createOverlayStoreKeys() { - ArrayList overlayKeys = new ArrayList(); - - overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, EditorPreferenceNames.EDITOR_TEXT_HOVER_MODIFIERS)); - - OverlayPreferenceStore.OverlayKey[] keys = new OverlayPreferenceStore.OverlayKey[overlayKeys.size()]; - overlayKeys.toArray(keys); - return keys; - } - - private String generateTextHoverString() { - StringBuffer buf = new StringBuffer(); - - for (int i = 0; i < fTextHovers.length; i++) { - buf.append(fTextHovers[i].getId()); - buf.append(TextHoverManager.HOVER_ATTRIBUTE_SEPARATOR); - buf.append(Boolean.toString(fTextHovers[i].isEnabled())); - buf.append(TextHoverManager.HOVER_ATTRIBUTE_SEPARATOR); - String modifier = fTextHovers[i].getModifierString(); - if (modifier == null || modifier.length() == 0) - modifier = TextHoverManager.NO_MODIFIER; - buf.append(modifier); - buf.append(TextHoverManager.HOVER_SEPARATOR); - } - return buf.toString(); - } - - private TextHoverManager getTextHoverManager() { - return SSEUIPlugin.getDefault().getTextHoverManager(); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.sse.ui.preferences.ui.IPreferenceTab#getTitle() - */ - public String getTitle() { - return SSEUIMessages.TextHoverPreferenceTab_title; //$NON-NLS-1$ - } - - void handleHoverListSelection() { - int i = fHoverTable.getSelectionIndex(); - - if (i == -1) { - if (fHoverTable.getSelectionCount() == 0) - fModifierEditor.setEnabled(false); - return; - } - - boolean enabled = fTextHovers[i].isEnabled(); - fModifierEditor.setEnabled(enabled); - fModifierEditor.setText(fTextHovers[i].getModifierString()); - String description = fTextHovers[i].getDescription(); - if (description == null) - description = ""; //$NON-NLS-1$ - fDescription.setText(description); - } - - private void handleModifierModified() { - int i = fHoverTable.getSelectionIndex(); - if (i == -1) - return; - - String modifiers = fModifierEditor.getText(); - fTextHovers[i].setModifierString(modifiers); - - // update table - fHoverTableViewer.refresh(fTextHovers[i]); - - updateStatus(fTextHovers[i]); - } - - private void initialize() { - restoreFromOverlay(); - fHoverTableViewer.setInput(fTextHovers); - - initializeFields(); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.sse.ui.preferences.ui.AbstractPreferenceTab#initializeFields() - */ - protected void initializeFields() { - super.initializeFields(); - - fModifierEditor.setEnabled(false); - // initialize checkboxes in hover table - for (int i = 0; i < fTextHovers.length; i++) - fHoverTable.getItem(i).setChecked(fTextHovers[i].isEnabled()); - fHoverTableViewer.refresh(); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.sse.ui.preferences.ui.IPreferenceTab#performApply() - */ - public void performApply() { - performOk(); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.sse.ui.preferences.ui.IPreferenceTab#performDefaults() - */ - public void performDefaults() { - initialize(); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.sse.ui.preferences.ui.IPreferenceTab#performOk() - */ - public void performOk() { - String textHoverString = generateTextHoverString(); - getOverlayStore().setValue(EditorPreferenceNames.EDITOR_TEXT_HOVER_MODIFIERS, textHoverString); - getTextHoverManager().resetTextHovers(); // notify text hover manager - // it should reset to get - // latest preferences - } - - /** - * Populates fTextHovers with text hover description from the overlay - * store (which is the preferences) - */ - private void restoreFromOverlay() { - String descriptorsString = getOverlayStore().getString(EditorPreferenceNames.EDITOR_TEXT_HOVER_MODIFIERS); - fTextHovers = getTextHoverManager().generateTextHoverDescriptors(descriptorsString); - } - - void updateStatus(TextHoverManager.TextHoverDescriptor hoverConfig) { - IStatus status = new StatusInfo(); - - if (hoverConfig != null && hoverConfig.isEnabled() && EditorUtility.computeStateMask(hoverConfig.getModifierString()) == -1) - status = new StatusInfo(IStatus.ERROR, NLS.bind(SSEUIMessages.TextHoverPreferenceTab_modifierIsNotValid, new String[]{hoverConfig.getModifierString()})); - - int i = 0; - HashMap stateMasks = new HashMap(fTextHovers.length); - while (status.isOK() && i < fTextHovers.length) { - if (fTextHovers[i].isEnabled()) { - String label = fTextHovers[i].getLabel(); - Integer stateMask = new Integer(EditorUtility.computeStateMask(fTextHovers[i].getModifierString())); - if (stateMask.intValue() == -1) - status = new StatusInfo(IStatus.ERROR, NLS.bind(SSEUIMessages.TextHoverPreferenceTab_modifierIsNotValidForHover, new String[]{fTextHovers[i].getModifierString(), label})); - else if (stateMasks.containsKey(stateMask)) - status = new StatusInfo(IStatus.ERROR, NLS.bind(SSEUIMessages.TextHoverPreferenceTab_duplicateModifier, new String[]{label, (String) stateMasks.get(stateMask)})); - else - stateMasks.put(stateMask, label); - } - i++; - } - - updateStatus(status); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/TranslucencyPreferenceTab.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/TranslucencyPreferenceTab.java deleted file mode 100644 index 808a99b183..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/TranslucencyPreferenceTab.java +++ /dev/null @@ -1,149 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.preferences.ui; - -import org.eclipse.jface.preference.FieldEditor; -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.preference.IntegerFieldEditor; -import org.eclipse.jface.preference.PreferencePage; -import org.eclipse.jface.preference.StringFieldEditor; -import org.eclipse.jface.resource.JFaceResources; -import org.eclipse.jface.text.Assert; -import org.eclipse.jface.util.IPropertyChangeListener; -import org.eclipse.jface.util.PropertyChangeEvent; -import org.eclipse.swt.SWT; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; -import org.eclipse.wst.sse.ui.internal.SSEUIPlugin; -import org.eclipse.wst.sse.ui.internal.preferences.EditorPreferenceNames; - -public class TranslucencyPreferenceTab implements IPreferenceTab { - - private PreferencePage fMainPreferencePage; - private IntegerFieldEditor fTranslucencyScale = null; - private final int MAX_PERCENTAGE = 100; - - private IPropertyChangeListener validityChangeListener = new IPropertyChangeListener() { - public void propertyChange(PropertyChangeEvent event) { - if (event.getProperty().equals(FieldEditor.IS_VALID)) - updateValidState(); - } - }; - - /** - * - */ - public TranslucencyPreferenceTab() { - super(); - } - - public TranslucencyPreferenceTab(PreferencePage mainPreferencePage) { - Assert.isNotNull(mainPreferencePage); - setMainPreferencePage(mainPreferencePage); - } - - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.sse.ui.preferences.ui.IPreferenceTab#createContents(org.eclipse.swt.widgets.Composite) - */ - public Control createContents(Composite tabFolder) { - Composite composite = new Composite(tabFolder, SWT.NULL); - GridLayout layout = new GridLayout(); - layout.numColumns = 2; - composite.setLayout(layout); - - String text = SSEUIMessages.TranslucencyPreferenceTab_1; //$NON-NLS-1$ - fTranslucencyScale = new IntegerFieldEditor(EditorPreferenceNames.READ_ONLY_FOREGROUND_SCALE, text, composite); - - fTranslucencyScale.setErrorMessage(JFaceResources.getString("StringFieldEditor.errorMessage"));//$NON-NLS-1$ - fTranslucencyScale.setPreferenceStore(getPreferenceStore()); - fTranslucencyScale.setPreferencePage(getMainPreferencePage()); - fTranslucencyScale.setTextLimit(Integer.toString(MAX_PERCENTAGE).length()); - fTranslucencyScale.setValidateStrategy(StringFieldEditor.VALIDATE_ON_KEY_STROKE); - fTranslucencyScale.setValidRange(0, MAX_PERCENTAGE); - fTranslucencyScale.load(); - fTranslucencyScale.setPropertyChangeListener(validityChangeListener); - -// PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IHelpContextIds.PREFWEBX_READONLY_HELPID); - return composite; - } - - /** - * @return Returns the fMainPreferencePage. - */ - private PreferencePage getMainPreferencePage() { - return fMainPreferencePage; - } - - /** - * @return Returns the preference store used in this tab - */ - private IPreferenceStore getPreferenceStore() { - return SSEUIPlugin.getDefault().getPreferenceStore(); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.sse.ui.preferences.ui.IPreferenceTab#getTitle() - */ - public String getTitle() { - return SSEUIMessages.TranslucencyPreferenceTab_0; //$NON-NLS-1$ - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.sse.ui.preferences.ui.IPreferenceTab#performApply() - */ - public void performApply() { - fTranslucencyScale.store(); - SSEUIPlugin.getDefault().savePluginPreferences(); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.sse.ui.preferences.ui.IPreferenceTab#performDefaults() - */ - public void performDefaults() { - fTranslucencyScale.loadDefault(); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.sse.ui.preferences.ui.IPreferenceTab#performOk() - */ - public void performOk() { - performApply(); - } - - /** - * @param mainPreferencePage - * The fMainPreferencePage to set. - */ - private void setMainPreferencePage(PreferencePage mainPreferencePage) { - fMainPreferencePage = mainPreferencePage; - } - - private void updateValidState() { - if (getMainPreferencePage() != null) { - getMainPreferencePage().setValid(fTranslucencyScale.isValid()); - } - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/projection/AbstractStructuredCommentFoldingPosition.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/projection/AbstractStructuredCommentFoldingPosition.java deleted file mode 100644 index f34665319a..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/projection/AbstractStructuredCommentFoldingPosition.java +++ /dev/null @@ -1,130 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.projection; - -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.Position; -import org.eclipse.jface.text.Region; -import org.eclipse.jface.text.source.projection.IProjectionPosition; - -/** - * Represents a folding position for an XML comment - */ -public abstract class AbstractStructuredCommentFoldingPosition extends Position implements IProjectionPosition { - - /** - * Default constructor - * - * @param offset the offset of the folding position - * @param length the length of the folidng position - */ - public AbstractStructuredCommentFoldingPosition(int offset, int length) { - super(offset, length); - } - - /** - * @see org.eclipse.jface.text.source.projection.IProjectionPosition#computeCaptionOffset(org.eclipse.jface.text.IDocument) - */ - public int computeCaptionOffset(IDocument document) throws BadLocationException { - return findFirstContent(document.get(offset, length)); - } - - /** - * @see org.eclipse.jface.text.source.projection.IProjectionPosition#computeProjectionRegions(org.eclipse.jface.text.IDocument) - */ - public IRegion[] computeProjectionRegions(IDocument document) throws BadLocationException { - //get the content of the comment - String content = document.get(offset, length); - int contentStart = findFirstContent(content); - - //find the start line of the comment - //find the end line of the comment - //find the first line of text in the comment - int startLineNum = document.getLineOfOffset(getStartOffset()); - IRegion startLine = document.getLineInformation(startLineNum); - int endLineNum = document.getLineOfOffset(getEndOffset()) +1; - IRegion endLine = document.getLineInformation(endLineNum); - int captionLineNum = document.getLineOfOffset(getStartOffset() + contentStart); - - int foldOffset; - int foldEndOffset; - - synchronized (this) { - foldOffset = startLine.getOffset(); - if(foldOffset < offset) { - offset = foldOffset; - } - - foldEndOffset = endLine.getOffset(); - - if((foldEndOffset-offset) > length) { - length = foldEndOffset-offset; - } - } - - //fold before the first line of text in the comment - IRegion preRegion = null; - IRegion postRegion = null; - if(startLineNum < captionLineNum) { - IRegion captionLine = document.getLineInformation(captionLineNum); - preRegion = new Region(foldOffset, captionLine.getOffset()-foldOffset); - } - - //fold after the first line of text in the comment - if(captionLineNum < endLineNum) { - int postRegionOffset = document.getLineOffset(captionLineNum+1); - postRegion = new Region(postRegionOffset, foldEndOffset-postRegionOffset); - } - - IRegion[] regions = null; - if(preRegion != null && postRegion != null) { - regions = new IRegion[] {preRegion, postRegion}; - } else if(preRegion != null) { - regions = new IRegion[] {preRegion}; - } else if(postRegion != null) { - regions = new IRegion[] {postRegion}; - } - - return regions; - } - - /** - * Finds the offset of the first identifier part within <code>content</code>. - * Returns 0 if none is found. - * - * @param content the content to search - * @param prefixEnd the end of the prefix - * @return the first index of a unicode identifier part, or zero if none can - * be found - */ - private int findFirstContent(final CharSequence content) { - int lenght= content.length(); - for (int i= 0; i < lenght; i++) { - if (Character.isUnicodeIdentifierPart(content.charAt(i))) - return i; - } - return 0; - } - - /** - * @return the start offset of the folding position - */ - protected abstract int getStartOffset(); - - /** - * @return the end offset of the folding position - */ - protected abstract int getEndOffset(); - -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/projection/AbstractStructuredFoldingPosition.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/projection/AbstractStructuredFoldingPosition.java deleted file mode 100644 index 3ddb47a7d4..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/projection/AbstractStructuredFoldingPosition.java +++ /dev/null @@ -1,82 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.projection; - -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.Position; -import org.eclipse.jface.text.Region; -import org.eclipse.jface.text.source.projection.IProjectionPosition; - -/** - * Represents a single folding position in an <code>IStructuredDocument</code> - */ -public abstract class AbstractStructuredFoldingPosition extends Position implements IProjectionPosition { - - /** - * Default constructor - * - * @param offset the offset of the folding position - * @param length the length of the folidng position - */ - public AbstractStructuredFoldingPosition(int offset, int length) { - super(offset, length); - } - - /** - * @see org.eclipse.jface.text.source.projection.IProjectionPosition#computeCaptionOffset(org.eclipse.jface.text.IDocument) - */ - public int computeCaptionOffset(IDocument document) throws BadLocationException { - - return 0; - } - - /** - * @see org.eclipse.jface.text.source.projection.IProjectionPosition#computeProjectionRegions(org.eclipse.jface.text.IDocument) - */ - public IRegion[] computeProjectionRegions(IDocument document) throws BadLocationException { - - int startLineNum = document.getLineOfOffset(getStartOffset()) + 1; - IRegion startLine = document.getLineInformation(startLineNum); - int endLineNum = document.getLineOfOffset(getEndOffset()) + 1; - IRegion endLine = document.getLineInformation(endLineNum); - - int foldOffset; - int foldEndOffset; - - synchronized (this) { - foldOffset = startLine.getOffset(); - if(foldOffset < offset) { - offset = foldOffset; - } - - foldEndOffset = endLine.getOffset(); - - if((foldEndOffset-offset) > length) { - length = foldEndOffset-offset; - } - } - - return new IRegion[] {new Region(foldOffset, foldEndOffset-foldOffset)}; - } - - /** - * @return the start offset of the folding position - */ - protected abstract int getStartOffset(); - - /** - * @return the end offset of the folding position - */ - protected abstract int getEndOffset(); -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/projection/AbstractStructuredFoldingStrategy.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/projection/AbstractStructuredFoldingStrategy.java deleted file mode 100644 index f71629ae35..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/projection/AbstractStructuredFoldingStrategy.java +++ /dev/null @@ -1,522 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009, 2011 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.projection; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.Position; -import org.eclipse.jface.text.reconciler.DirtyRegion; -import org.eclipse.jface.text.reconciler.IReconcileStep; -import org.eclipse.jface.text.source.Annotation; -import org.eclipse.jface.text.source.projection.IProjectionListener; -import org.eclipse.jface.text.source.projection.ProjectionAnnotation; -import org.eclipse.jface.text.source.projection.ProjectionAnnotationModel; -import org.eclipse.jface.text.source.projection.ProjectionViewer; -import org.eclipse.swt.graphics.FontMetrics; -import org.eclipse.swt.graphics.GC; -import org.eclipse.swt.graphics.Rectangle; -import org.eclipse.swt.widgets.Canvas; -import org.eclipse.wst.sse.core.StructuredModelManager; -import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel; -import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion; -import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegionList; -import org.eclipse.wst.sse.ui.internal.reconcile.AbstractStructuredTextReconcilingStrategy; -import org.eclipse.wst.sse.ui.internal.reconcile.StructuredReconcileStep; - -/** - * <p>This class has the default implementation for a structured editor folding strategy. - * Each content type that the structured editor supports should create an extension point - * specifying a child class of this class as its folding strategy, if that content type - * should have folding.</p> - * - * <p>EX:<br /> - * <code><extension point="org.eclipse.wst.sse.ui.editorConfiguration"><br /> - * <provisionalConfiguration<br /> - * type="foldingstrategy"<br /> - * class="org.eclipse.wst.xml.ui.internal.projection.XMLFoldingStrategy"<br /> - * target="org.eclipse.core.runtime.xml, org.eclipse.wst.xml.core.xmlsource" /><br /> - * </extension></code></p> - * - * <p>Different content types can use the same folding strategy if it makes sense to do so, - * such as with HTML/XML/JSP.</p> - * - * <p>This strategy is based on the Reconciler paradigm and thus runs in the background, - * this means that even for very large documents requiring the calculation of 1000s of - * folding annotations the user will not be effected except for the annotations may take - * some time to first appear.</p> - */ -public abstract class AbstractStructuredFoldingStrategy - extends AbstractStructuredTextReconcilingStrategy implements IProjectionListener { - - /** - * The org.eclipse.wst.sse.ui.editorConfiguration provisionalConfiguration type - */ - public static final String ID = "foldingstrategy"; //$NON-NLS-1$ - - /** - * A named preference that controls whether folding is enabled in the - * Structured Text editor. - */ - public final static String FOLDING_ENABLED = "foldingEnabled"; //$NON-NLS-1$ - - /** - * The annotation model associated with this folding strategy - */ - protected ProjectionAnnotationModel fProjectionAnnotationModel; - - /** - * The structured text viewer this folding strategy is associated with - */ - private ProjectionViewer fViewer; - - /** - * these are not used but needed to implement abstract methods - */ - private IReconcileStep fFoldingStep; - - /** - * Default constructor for the folding strategy, can not take any parameters - * because subclasses instances of this class are created using reflection - * based on plugin settings - */ - public AbstractStructuredFoldingStrategy() { - super(); - } - - /** - * The folding strategy must be associated with a viewer for it to function - * - * @param viewer the viewer to associate this folding strategy with - */ - public void setViewer(ProjectionViewer viewer) { - super.setViewer(viewer); - - if(fViewer != null) { - fViewer.removeProjectionListener(this); - } - fViewer = viewer; - fViewer.addProjectionListener(this); - fProjectionAnnotationModel = fViewer.getProjectionAnnotationModel(); - } - - public void uninstall() { - setDocument(null); - - if(fViewer != null) { - fViewer.removeProjectionListener(this); - fViewer = null; - } - - fFoldingStep = null; - - projectionDisabled(); - } - - /* - * (non-Javadoc) - * @see org.eclipse.wst.sse.ui.internal.reconcile.AbstractStructuredTextReconcilingStrategy#setDocument(org.eclipse.jface.text.IDocument) - */ - public void setDocument(IDocument document) { - super.setDocument(document); - } - - /* - * (non-Javadoc) - * @see org.eclipse.jface.text.source.projection.IProjectionListener#projectionDisabled() - */ - public void projectionDisabled() { - fProjectionAnnotationModel = null; - } - - /* - * (non-Javadoc) - * @see org.eclipse.jface.text.source.projection.IProjectionListener#projectionEnabled() - */ - public void projectionEnabled() { - if(fViewer != null) { - fProjectionAnnotationModel = fViewer.getProjectionAnnotationModel(); - } - } - - /** - * <p><b>NOTE 1:</b> This implementation of reconcile ignores the given {@link IRegion} and instead gets all of the - * structured document regions effected by the range of the given {@link DirtyRegion}.</p> - * - * <p><b>NOTE 2:</b> In cases where multiple {@link IRegion} maybe dirty it is more efficient to pass one - * {@link DirtyRegion} contain all of the {@link IRegion}s then one {@link DirtyRegion} for each IRegion. - * Case in point, when processing the entire document it is <b>recommended</b> that this function be - * called only <b>once</b> with one {@link DirtyRegion} that spans the entire document.</p> - * - * @param dirtyRegion the region that needs its folding annotations processed - * @param subRegion ignored - * - * @see org.eclipse.wst.sse.ui.internal.reconcile.AbstractStructuredTextReconcilingStrategy#reconcile(org.eclipse.jface.text.reconciler.DirtyRegion, org.eclipse.jface.text.IRegion) - */ - public void reconcile(DirtyRegion dirtyRegion, IRegion subRegion) { - IStructuredModel model = null; - if(fProjectionAnnotationModel != null) { - try { - model = StructuredModelManager.getModelManager().getExistingModelForRead(getDocument()); - if(model != null) { - //use the structured doc to get all of the regions effected by the given dirty region - IStructuredDocument structDoc = model.getStructuredDocument(); - IStructuredDocumentRegion[] structRegions = structDoc.getStructuredDocumentRegions(dirtyRegion.getOffset(), dirtyRegion.getLength()); - Set indexedRegions = getIndexedRegions(model, structRegions); - - //these are what are passed off to the annotation model to - //actually create and maintain the annotations - List modifications = new ArrayList(); - List deletions = new ArrayList(); - Map additions = new HashMap(); - boolean isInsert = dirtyRegion.getType().equals(DirtyRegion.INSERT); - boolean isRemove = dirtyRegion.getType().equals(DirtyRegion.REMOVE); - - //find and mark all folding annotations with length 0 for deletion - markInvalidAnnotationsForDeletion(dirtyRegion, deletions); - - //reconcile each effected indexed region - Iterator indexedRegionsIter = indexedRegions.iterator(); - while(indexedRegionsIter.hasNext() && fProjectionAnnotationModel != null) { - IndexedRegion indexedRegion = (IndexedRegion)indexedRegionsIter.next(); - - //only try to create an annotation if the index region is a valid type - if(indexedRegionValidType(indexedRegion)) { - FoldingAnnotation annotation = new FoldingAnnotation(indexedRegion, false); - - // if INSERT calculate new addition position or modification - // else if REMOVE add annotation to the deletion list - if(isInsert) { - Annotation existingAnno = getExistingAnnotation(indexedRegion); - //if projection has been disabled the iter could be null - //if annotation does not already exist for this region create a new one - //else modify an old one, which could include deletion - if(existingAnno == null) { - Position newPos = calcNewFoldPosition(indexedRegion); - - if(newPos != null && newPos.length > 0) { - additions.put(annotation, newPos); - } - } else { - updateAnnotations(existingAnno, indexedRegion, additions, modifications, deletions); - } - } else if (isRemove) { - deletions.add(annotation); - } - } - } - - //be sure projection has not been disabled - if(fProjectionAnnotationModel != null) { - //send the calculated updates to the annotations to the annotation model - fProjectionAnnotationModel.modifyAnnotations((Annotation[])deletions.toArray(new Annotation[1]), additions, (Annotation[])modifications.toArray(new Annotation[0])); - } - } - } finally { - if(model != null) { - model.releaseFromRead(); - } - } - } - } - - /** - * <p>Every implementation of the folding strategy calculates the position for a given - * IndexedRegion differently. Also this calculation often relies on casting to internal classes - * only available in the implementing classes plugin</p> - * - * @param indexedRegion the IndexedRegion to calculate a new annotation position for - * @return the calculated annotation position or NULL if none can be calculated based on the given region - */ - abstract protected Position calcNewFoldPosition(IndexedRegion indexedRegion); - - /** - * This is the default behavior for updating a dirtied IndexedRegion. This function - * can be overridden if slightly different functionality is required in a specific instance - * of this class. - * - * @param existingAnnotationsIter the existing annotations that need to be updated - * based on the given dirtied IndexRegion - * @param dirtyRegion the IndexedRegion that caused the annotations need for updating - * @param modifications the list of annotations to be modified - * @param deletions the list of annotations to be deleted - */ - protected void updateAnnotations(Annotation existingAnnotation, IndexedRegion dirtyRegion, Map additions, List modifications, List deletions) { - if(existingAnnotation instanceof FoldingAnnotation) { - FoldingAnnotation foldingAnnotation = (FoldingAnnotation)existingAnnotation; - Position newPos = calcNewFoldPosition(foldingAnnotation.getRegion()); - - //if a new position can be calculated then update the position of the annotation, - //else the annotation needs to be deleted - if(newPos != null && newPos.length > 0 && fProjectionAnnotationModel != null) { - Position oldPos = fProjectionAnnotationModel.getPosition(foldingAnnotation); - //only update the position if we have to - if(!newPos.equals(oldPos)) { - oldPos.setOffset(newPos.offset); - oldPos.setLength(newPos.length); - modifications.add(foldingAnnotation); - } - } else { - deletions.add(foldingAnnotation); - } - } - } - - /** - * <p>Searches the given {@link DirtyRegion} for annotations that now have a length of 0. - * This is caused when something that was being folded has been deleted. These {@link FoldingAnnotation}s - * are then added to the {@link List} of {@link FoldingAnnotation}s to be deleted</p> - * - * @param dirtyRegion find the now invalid {@link FoldingAnnotation}s in this {@link DirtyRegion} - * @param deletions the current list of {@link FoldingAnnotation}s marked for deletion that the - * newly found invalid {@link FoldingAnnotation}s will be added to - */ - protected void markInvalidAnnotationsForDeletion(DirtyRegion dirtyRegion, List deletions) { - Iterator iter = getAnnotationIterator(dirtyRegion); - if (iter != null) { - while(iter.hasNext()) { - Annotation anno = (Annotation)iter.next(); - if(anno instanceof FoldingAnnotation) { - Position pos = fProjectionAnnotationModel.getPosition(anno); - if(pos.length == 0) { - deletions.add(anno); - } - } - } - } - } - - /** - * Should return true if the given IndexedRegion is one that this strategy pays attention to - * when calculating new and updated annotations - * - * @param indexedRegion the IndexedRegion to check the type of - * @return true if the IndexedRegion is of a valid type, false otherwise - */ - abstract protected boolean indexedRegionValidType(IndexedRegion indexedRegion); - - /** - * Steps are not used in this strategy - * - * @see org.eclipse.wst.sse.ui.internal.reconcile.AbstractStructuredTextReconcilingStrategy#containsStep(org.eclipse.jface.text.reconciler.IReconcileStep) - */ - protected boolean containsStep(IReconcileStep step) { - return fFoldingStep.equals(step); - } - - /** - * Steps are not used in this strategy - * - * @see org.eclipse.wst.sse.ui.internal.reconcile.AbstractStructuredTextReconcilingStrategy#createReconcileSteps() - */ - public void createReconcileSteps() { - fFoldingStep = new StructuredReconcileStep() { }; - } - - /** - * A FoldingAnnotation is a ProjectionAnnotation in a structured document. - * Its extended functionality include storing the <code>IndexedRegion</code> it is folding - * and overriding the paint method (in a hacky type way) to prevent one line folding - * annotations to be drawn. - */ - protected class FoldingAnnotation extends ProjectionAnnotation { - private boolean fIsVisible; /* workaround for BUG85874 */ - - /** - * The IndexedRegion this annotation is folding - */ - private IndexedRegion fRegion; - - /** - * Creates a new FoldingAnnotation that is associated with the given IndexedRegion - * - * @param region the IndexedRegion this annotation is associated with - * @param isCollapsed true if this annotation should be collapsed, false otherwise - */ - public FoldingAnnotation(IndexedRegion region, boolean isCollapsed) { - super(isCollapsed); - - fIsVisible = false; - fRegion = region; - } - - /** - * Returns the IndexedRegion this annotation is associated with - * - * @return the IndexedRegion this annotation is associated with - */ - public IndexedRegion getRegion() { - return fRegion; - } - - public void setRegion(IndexedRegion region) { - fRegion = region; - } - - /** - * Does not paint hidden annotations. Annotations are hidden when they - * only span one line. - * - * @see ProjectionAnnotation#paint(org.eclipse.swt.graphics.GC, - * org.eclipse.swt.widgets.Canvas, - * org.eclipse.swt.graphics.Rectangle) - */ - public void paint(GC gc, Canvas canvas, Rectangle rectangle) { - /* workaround for BUG85874 */ - /* - * only need to check annotations that are expanded because hidden - * annotations should never have been given the chance to - * collapse. - */ - if (!isCollapsed()) { - // working with rectangle, so line height - FontMetrics metrics = gc.getFontMetrics(); - if (metrics != null) { - // do not draw annotations that only span one line and - // mark them as not visible - if ((rectangle.height / metrics.getHeight()) <= 1) { - fIsVisible = false; - return; - } - } - } - fIsVisible = true; - super.paint(gc, canvas, rectangle); - } - - /** - * @see org.eclipse.jface.text.source.projection.ProjectionAnnotation#markCollapsed() - */ - public void markCollapsed() { - /* workaround for BUG85874 */ - // do not mark collapsed if annotation is not visible - if (fIsVisible) - super.markCollapsed(); - } - - /** - * Two FoldingAnnotations are equal if their IndexedRegions are equal - * - * @see java.lang.Object#equals(java.lang.Object) - */ - public boolean equals(Object obj) { - boolean equal = false; - - if(obj instanceof FoldingAnnotation) { - equal = fRegion.equals(((FoldingAnnotation)obj).fRegion); - } - - return equal; - } - - /** - * Returns the hash code of the IndexedRegion this annotation is associated with - * - * @see java.lang.Object#hashCode() - */ - public int hashCode() { - return fRegion.hashCode(); - } - - /** - * Returns the toString of the aIndexedRegion this annotation is associated with - * - * @see java.lang.Object#toString() - */ - public String toString() { - return fRegion.toString(); - } - } - - /** - * Given a {@link DirtyRegion} returns an {@link Iterator} of the already existing - * annotations in that region. - * - * @param dirtyRegion the {@link DirtyRegion} to check for existing annotations in - * - * @return an {@link Iterator} over the annotations in the given {@link DirtyRegion}. - * The iterator could have no annotations in it. Or <code>null</code> if projection has - * been disabled. - */ - private Iterator getAnnotationIterator(DirtyRegion dirtyRegion) { - Iterator annoIter = null; - //be sure project has not been disabled - if(fProjectionAnnotationModel != null) { - //workaround for Platform Bug 299416 - int offset = dirtyRegion.getOffset(); - if(offset > 0) { - offset--; - } - annoIter = fProjectionAnnotationModel.getAnnotationIterator(offset, dirtyRegion.getLength(), false, false); - } - return annoIter; - } - - /** - * <p>Gets the first {@link Annotation} at the start offset of the given {@link IndexedRegion}.</p> - * - * @param indexedRegion get the first {@link Annotation} at this {@link IndexedRegion} - * @return the first {@link Annotation} at the start offset of the given {@link IndexedRegion} - */ - private Annotation getExistingAnnotation(IndexedRegion indexedRegion) { - Iterator iter = fProjectionAnnotationModel.getAnnotationIterator(indexedRegion.getStartOffset(), 1, false, true); - Annotation anno = null; - if(iter.hasNext()) { - anno = (Annotation)iter.next(); - } - - return anno; - } - - /** - * <p>Gets all of the {@link IndexedRegion}s from the given {@link IStructuredModel} spanned by the given - * {@link IStructuredDocumentRegion}s.</p> - * - * @param model the {@link IStructuredModel} used to get the {@link IndexedRegion}s - * @param structRegions get the {@link IndexedRegion}s spanned by these {@link IStructuredDocumentRegion}s - * @return the {@link Set} of {@link IndexedRegion}s from the given {@link IStructuredModel} spanned by the - * given {@link IStructuredDocumentRegion}s. - */ - private Set getIndexedRegions(IStructuredModel model, IStructuredDocumentRegion[] structRegions) { - Set indexedRegions = new HashSet(structRegions.length); - - //for each text region in each structured document region find the indexed region it spans/is in - for (int structRegionIndex = 0; structRegionIndex < structRegions.length && fProjectionAnnotationModel != null; ++structRegionIndex) { - IStructuredDocumentRegion structuredDocumentRegion = structRegions[structRegionIndex]; - - int offset = structuredDocumentRegion.getStartOffset(); - IndexedRegion indexedRegion = model.getIndexedRegion(offset); - indexedRegions.add(indexedRegion); - if (structuredDocumentRegion.getEndOffset() <= indexedRegion.getEndOffset()) - continue; - - ITextRegionList textRegions = structuredDocumentRegion.getRegions(); - int textRegionCount = textRegions.size(); - for (int textRegionIndex = 1; textRegionIndex < textRegionCount; ++textRegionIndex) { - offset = structuredDocumentRegion.getStartOffset(textRegions.get(textRegionIndex)); - indexedRegion = model.getIndexedRegion(offset); - indexedRegions.add(indexedRegion); - } - } - - return indexedRegions; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/properties/AdapterPropertySheetEntryLabelProvider.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/properties/AdapterPropertySheetEntryLabelProvider.java deleted file mode 100644 index 18f919c3f7..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/properties/AdapterPropertySheetEntryLabelProvider.java +++ /dev/null @@ -1,51 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.properties; - - - -import org.eclipse.jface.viewers.LabelProvider; -import org.eclipse.swt.graphics.Image; -import org.eclipse.ui.views.properties.IPropertySheetEntry; -import org.eclipse.wst.sse.core.internal.provisional.INodeNotifier; - - -public class AdapterPropertySheetEntryLabelProvider extends LabelProvider { - public Image getImage(Object element) { - if (element == null) - return null; - if (element instanceof IPropertySheetEntry) { - return ((IPropertySheetEntry) element).getImage(); - } - if (element instanceof INodeNotifier) { - IPropertySheetEntry entry = (IPropertySheetEntry) ((INodeNotifier) element).getAdapterFor(IPropertySheetEntry.class); - if (entry != null) - return entry.getImage(); - } - return super.getImage(element); - } - - public String getText(Object element) { - if (element == null) - return null; - if (element instanceof IPropertySheetEntry) { - return ((IPropertySheetEntry) element).getValueAsString(); - } - if (element instanceof INodeNotifier) { - IPropertySheetEntry entry = (IPropertySheetEntry) ((INodeNotifier) element).getAdapterFor(IPropertySheetEntry.class); - if (entry != null) - return entry.getValueAsString(); - } - return super.getText(element); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/properties/ConfigurablePropertySheetPage.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/properties/ConfigurablePropertySheetPage.java deleted file mode 100644 index 881cb2faee..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/properties/ConfigurablePropertySheetPage.java +++ /dev/null @@ -1,207 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.properties; - -import org.eclipse.core.runtime.Platform; -import org.eclipse.jface.action.IMenuManager; -import org.eclipse.jface.action.IStatusLineManager; -import org.eclipse.jface.action.IToolBarManager; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.ui.IWorkbenchPart; -import org.eclipse.ui.part.IPageSite; -import org.eclipse.ui.part.PageBookView; -import org.eclipse.ui.views.properties.IPropertySheetEntry; -import org.eclipse.ui.views.properties.IPropertySheetPage; -import org.eclipse.ui.views.properties.IPropertySource; -import org.eclipse.ui.views.properties.IPropertySourceProvider; -import org.eclipse.ui.views.properties.PropertySheetPage; -import org.eclipse.wst.sse.ui.views.properties.IPropertySourceExtension; -import org.eclipse.wst.sse.ui.views.properties.PropertySheetConfiguration; - - -/** - * A configurable IPropertySheetPage since the standard PropertySheetPage does - * not expose its viewer field. - */ - -public class ConfigurablePropertySheetPage extends PropertySheetPage { - private class NullPropertySheetConfiguration extends PropertySheetConfiguration { - public IPropertySourceProvider getPropertySourceProvider(IPropertySheetPage page) { - return null; - } - } - - private static final boolean _DEBUG = "true".equalsIgnoreCase(Platform.getDebugOption("org.eclipse.wst.sse.ui/propertySheet")); //$NON-NLS-1$ //$NON-NLS-2$;; - - private long _DEBUG_TIME = 0; - - private PropertySheetConfiguration fConfiguration; - private Object[] fSelectedEntries = null; - private ISelection fInput = null; - private IMenuManager fMenuManager; - - private RemoveAction fRemoveAction; - - private IStatusLineManager fStatusLineManager; - - private IToolBarManager fToolBarManager; - - private final PropertySheetConfiguration NULL_CONFIGURATION = new NullPropertySheetConfiguration(); - - public ConfigurablePropertySheetPage() { - super(); - } - - public void createControl(Composite parent) { - setPropertySourceProvider(getConfiguration().getPropertySourceProvider(this)); - super.createControl(parent); - } - - public void dispose() { - setConfiguration(null); - getSite().getWorkbenchWindow().getSelectionService().removePostSelectionListener(this); - fSelectedEntries = null; - fInput = null; - super.dispose(); - } - - public PropertySheetConfiguration getConfiguration() { - if (fConfiguration == null) - fConfiguration = NULL_CONFIGURATION; - return fConfiguration; - } - - public void handleEntrySelection(ISelection selection) { - if (getControl() != null && !getControl().isDisposed() && selection != null) { - super.handleEntrySelection(selection); - if (selection instanceof IStructuredSelection) { - fSelectedEntries = ((IStructuredSelection) selection).toArray(); - } - else { - fSelectedEntries = null; - } - fRemoveAction.setEnabled(!selection.isEmpty()); - } - } - - public void init(IPageSite pageSite) { - super.init(pageSite); - pageSite.getWorkbenchWindow().getSelectionService().addPostSelectionListener(this); - } - - public void makeContributions(IMenuManager menuManager, IToolBarManager toolBarManager, IStatusLineManager statusLineManager) { - super.makeContributions(menuManager, toolBarManager, statusLineManager); - fMenuManager = menuManager; - fToolBarManager = toolBarManager; - fStatusLineManager = statusLineManager; - - fRemoveAction = new RemoveAction(this); - toolBarManager.add(fRemoveAction); - menuManager.add(fRemoveAction); - getConfiguration().addContributions(menuManager, toolBarManager, statusLineManager); - - menuManager.update(true); - } - - void remove() { - if (fSelectedEntries != null) { - Object[] entries = fSelectedEntries; - ISelection selection = fInput; - boolean needsRefresh = false; - if (selection != null && !selection.isEmpty() && selection instanceof IStructuredSelection) { - IPropertySource source = getConfiguration().getPropertySourceProvider(this).getPropertySource(((IStructuredSelection) selection).getFirstElement()); - if (source != null && source instanceof IPropertySourceExtension) { - for (int i = 0; i < entries.length; i++) { - if (entries[i] instanceof IPropertySheetEntry) { - IPropertySheetEntry entry = (IPropertySheetEntry) entries[i]; - needsRefresh = true; - ((IPropertySourceExtension) source).removeProperty(entry.getDisplayName()); - } - } - } - } - if (needsRefresh) { - refresh(); - } - } - } - - /* - * Filter the selection through the current Configuration. Not every - * selection received is a Structured selection nor are the Structured - * selection's elements all to be displayed. - * - * @see org.eclipse.ui.ISelectionListener#selectionChanged(org.eclipse.ui.IWorkbenchPart, - * org.eclipse.jface.viewers.ISelection) - */ - public void selectionChanged(IWorkbenchPart part, ISelection selection) { - if (_DEBUG) { - _DEBUG_TIME = System.currentTimeMillis(); - } - // skip if we're the source of this selection - if (part != null && part instanceof PageBookView) { - if (((PageBookView) part).getCurrentPage() == this) - return; - } - if (getControl() != null && getControl().isVisible()) { - ISelection preferredSelection = getConfiguration().getInputSelection(part, selection); - /* - * Do some minor caching of the selection. - * - * As a PropertySheetPage, we've always notified of selection - * changes, but we've also subscribed to post selection - * notification so we can track caret movements in source viewers. - * When selecting a block of text, we're thus notified of the new - * selection twice. Remembering what our last *effective* - * selection was allows us to cut out most of the - * double-notification penalty. - */ - if (!preferredSelection.equals(fInput)) { - fInput = preferredSelection; - fSelectedEntries = null; - super.selectionChanged(part, preferredSelection); - } - - if (_DEBUG) { - System.out.println("(P:service " + (System.currentTimeMillis() - _DEBUG_TIME) + "ms) " + part + " : " + ((IStructuredSelection) preferredSelection).getFirstElement()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } - } - else if (_DEBUG) { - System.out.println("[skipped] (P:" + (System.currentTimeMillis() - _DEBUG_TIME) + "ms) " + part + " : " + selection); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } - } - - /** - * @param configuration - * The configuration to set. - */ - public void setConfiguration(PropertySheetConfiguration configuration) { - if (fConfiguration != null) { - fConfiguration.removeContributions(fMenuManager, fToolBarManager, fStatusLineManager); - fConfiguration.unconfigure(); - } - - fConfiguration = configuration; - - if (fConfiguration != null) { - setPropertySourceProvider(fConfiguration.getPropertySourceProvider(this)); - fConfiguration.addContributions(fMenuManager, fToolBarManager, fStatusLineManager); - } - } - - public void setFocus() { - super.setFocus(); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/properties/CustomPropertyDescriptor.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/properties/CustomPropertyDescriptor.java deleted file mode 100644 index 154861b1e6..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/properties/CustomPropertyDescriptor.java +++ /dev/null @@ -1,89 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.properties; - - - -import org.eclipse.jface.viewers.CellEditor; -import org.eclipse.jface.viewers.TextCellEditor; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.ui.views.properties.PropertyDescriptor; - -public class CustomPropertyDescriptor extends PropertyDescriptor { - - protected Class cellEditorClass = null; - - /** - * Returns a property descriptor with a unique name and a display name. - * - * @param id - * the id for the property - * @param displayName - * the name to display for the property - */ - public CustomPropertyDescriptor(Object id, String newDisplayName, Class editorClass) { - super(id, newDisplayName); - setDescription((String) id); - setCellEditorClass(editorClass); - } - - /** - * Returns a property descriptor with a unique name and a display name. - * - * @param uniqueName - * the unique name of the property - * @param displayName - * the name to display for the property - */ - public CustomPropertyDescriptor(String uniqueName, String newDisplayName) { - this(uniqueName, newDisplayName, TextCellEditor.class); - } - - public CellEditor createPropertyEditor(Composite parent) { - return getPropertyEditor(parent); - } - - public Class getCellEditorClass() { - return cellEditorClass; - } - - /** - * Returns the editor used to edit the property. - * - * @return an editor for the property - */ - protected CellEditor getPropertyEditor(Composite parent) { - if (getCellEditorClass() == null) - return null; - - java.lang.reflect.Constructor constructor = null; - try { - constructor = getCellEditorClass().getDeclaredConstructor(new Class[]{Composite.class}); - } catch (NoSuchMethodException nsme) { - return new TextCellEditor(parent); - } - if (constructor != null) { - try { - return (CellEditor) constructor.newInstance(new Object[]{parent}); - } catch (InstantiationException ie) { - } catch (java.lang.reflect.InvocationTargetException ite) { - } catch (IllegalAccessException iae) { - } - } - return new TextCellEditor(parent); - } - - public void setCellEditorClass(Class newCellEditorClass) { - cellEditorClass = newCellEditorClass; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/properties/RemoveAction.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/properties/RemoveAction.java deleted file mode 100644 index a02a1209e3..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/properties/RemoveAction.java +++ /dev/null @@ -1,45 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.properties; - -import org.eclipse.jface.action.Action; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; -import org.eclipse.wst.sse.ui.internal.editor.EditorPluginImageHelper; -import org.eclipse.wst.sse.ui.internal.editor.EditorPluginImages; - -public class RemoveAction extends Action { - private ConfigurablePropertySheetPage fPage; - - public RemoveAction(ConfigurablePropertySheetPage page) { - super(); - fPage = page; - setText(getText()); - setToolTipText(getText()); - setImageDescriptor(EditorPluginImageHelper.getInstance().getImageDescriptor(EditorPluginImages.IMG_ELCL_DELETE)); - setDisabledImageDescriptor(EditorPluginImageHelper.getInstance().getImageDescriptor(EditorPluginImages.IMG_DLCL_DELETE)); - } - - /** - * @see org.eclipse.jface.action.Action#getText() - */ - public String getText() { - return SSEUIMessages.RemoveAction_0; //$NON-NLS-1$ - } - - /** - * @see org.eclipse.jface.action.IAction#run() - */ - public void run() { - fPage.remove(); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/properties/ShowPropertiesAction.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/properties/ShowPropertiesAction.java deleted file mode 100644 index 38b0551b0c..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/properties/ShowPropertiesAction.java +++ /dev/null @@ -1,69 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.properties; - -import org.eclipse.jface.viewers.ISelectionProvider; -import org.eclipse.ui.ISelectionListener; -import org.eclipse.ui.IViewPart; -import org.eclipse.ui.IWorkbenchPage; -import org.eclipse.ui.IWorkbenchPart; -import org.eclipse.ui.IWorkbenchWindow; -import org.eclipse.ui.PlatformUI; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; -import org.eclipse.wst.sse.ui.internal.SSEUIPlugin; -import org.eclipse.wst.sse.ui.internal.ShowViewAction; -import org.eclipse.wst.sse.ui.internal.editor.EditorPluginImageHelper; -import org.eclipse.wst.sse.ui.internal.editor.EditorPluginImages; -import org.eclipse.wst.sse.ui.internal.editor.IHelpContextIds; - -/** - * Surfaces the Properties view - */ -public class ShowPropertiesAction extends ShowViewAction { - private final static String VIEW_ID = "org.eclipse.ui.views.PropertySheet"; //$NON-NLS-1$ - private ISelectionProvider fSelectionProvider; - private IWorkbenchPart fPart; - - public ShowPropertiesAction() { - super(SSEUIMessages.ShowPropertiesAction_0, EditorPluginImageHelper.getInstance().getImageDescriptor(EditorPluginImages.IMG_OBJ_PROP_PS)); //$NON-NLS-1$ - PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IHelpContextIds.CONTMNU_PROPERTIES_HELPID); - } - - public ShowPropertiesAction(IWorkbenchPart part, ISelectionProvider provider) { - this(); - fSelectionProvider = provider; - fPart = part; - } - - protected String getViewID() { - return VIEW_ID; - } - - public void run() { - super.run(); - - if (fSelectionProvider != null) { - IWorkbenchWindow window = SSEUIPlugin.getDefault().getWorkbench().getActiveWorkbenchWindow(); - IWorkbenchPage page = window.getActivePage(); - if (page != null) { - IViewPart findView = page.findView(getViewID()); - if (findView instanceof ISelectionListener && fPart != null) { - ((ISelectionListener) findView).selectionChanged(fPart, fSelectionProvider.getSelection()); - } - else { - findView.getViewSite().getSelectionProvider().setSelection(fSelectionProvider.getSelection()); - } - } - } - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/provisional/preferences/CommonEditorPreferenceNames.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/provisional/preferences/CommonEditorPreferenceNames.java deleted file mode 100644 index 3eaa30d143..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/provisional/preferences/CommonEditorPreferenceNames.java +++ /dev/null @@ -1,35 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ - -package org.eclipse.wst.sse.ui.internal.provisional.preferences; - -import org.eclipse.wst.sse.ui.internal.preferences.EditorPreferenceNames; - -/** - * Common editor preference keys used by the Structured Text Editor. - * - * @plannedfor 1.0 - */ -public class CommonEditorPreferenceNames { - private CommonEditorPreferenceNames() { - // empty private constructor so users cannot instantiate class - } - - /** - * A named preference that controls as-you-type validation - * <p> - * Value is of type <code>Boolean</code>. - * </p> - */ - public static final String EVALUATE_TEMPORARY_PROBLEMS = EditorPreferenceNames.EVALUATE_TEMPORARY_PROBLEMS; -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/provisional/registry/AdapterFactoryProvider.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/provisional/registry/AdapterFactoryProvider.java deleted file mode 100644 index e2bf0d49c9..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/provisional/registry/AdapterFactoryProvider.java +++ /dev/null @@ -1,33 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.provisional.registry; - -import org.eclipse.wst.sse.core.internal.ltk.modelhandler.IDocumentTypeHandler; -import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel; - - -public interface AdapterFactoryProvider { - - public void addAdapterFactories(IStructuredModel structuredModel); - - // TODO_issue: IDocumentTypeHandler doesn't seem correct in this API. - // reexamine and see if should be ModelHandler, or ContentTypeIdentifer - // instead. - public boolean isFor(IDocumentTypeHandler contentTypeDescription); - - /** - * This method should only add those factories related to embedded content - * type - */ - public void reinitializeFactories(IStructuredModel structuredModel); -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/provisional/registry/AdapterFactoryRegistry.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/provisional/registry/AdapterFactoryRegistry.java deleted file mode 100644 index 0a04339f39..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/provisional/registry/AdapterFactoryRegistry.java +++ /dev/null @@ -1,32 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.provisional.registry; - -import java.util.Iterator; - -/** - * This is basically a "factory for factories". It is to used to associate - * "edit time" AdapterFactories with a StructuredModel, based on the - * IStructuredModel's ContentTypeDescription. In plugin.xml files, there - * should be an AdapterFactoryProvider defined for every definition of - * ContentTypeDescription. - */ -public interface AdapterFactoryRegistry { - - /** - * Returns an Iterator over a Collection of AdapterFactoryProviders - * - * @return - */ - public Iterator getAdapterFactories(); -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/provisional/registry/AdapterFactoryRegistryExtension.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/provisional/registry/AdapterFactoryRegistryExtension.java deleted file mode 100644 index bc47269fd4..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/provisional/registry/AdapterFactoryRegistryExtension.java +++ /dev/null @@ -1,22 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.provisional.registry; - -import java.util.Iterator; -import java.util.List; - -public interface AdapterFactoryRegistryExtension { - Iterator getAdapterFactories(String contentTypeID); - - List getAdapterFactoriesAsList(String contentTypeID); -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/provisional/registry/AdapterFactoryRegistryImpl.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/provisional/registry/AdapterFactoryRegistryImpl.java deleted file mode 100644 index 78ebf475bc..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/provisional/registry/AdapterFactoryRegistryImpl.java +++ /dev/null @@ -1,210 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.provisional.registry; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IConfigurationElement; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.content.IContentType; -import org.eclipse.core.runtime.content.IContentTypeManager; -import org.eclipse.wst.sse.ui.internal.Logger; - - -public class AdapterFactoryRegistryImpl implements AdapterFactoryRegistry, AdapterFactoryRegistryExtension { - - protected final static String ATT_CLASS = "class"; //$NON-NLS-1$ - - private static AdapterFactoryRegistry instance = null; - - static synchronized public AdapterFactoryRegistry getInstance() { - if (instance == null) { - instance = new AdapterFactoryRegistryImpl(); - } - return instance; - } - - // this map exists so there is only one provider - // instance not duplicate providers for different content types - private HashMap adapterProviders = null; - - private boolean DEBUG = false; - /** - * This HashMap contains: [contentTypeId -> element2providerMap] | V - * [configurationElement -> AdapterFactoryProvider] - * - */ - private HashMap hashMap = null; - - // providers with no content type associated - // just added through the add(...) method - private HashSet unassociatedProviders = null; - - private AdapterFactoryRegistryImpl() { - super(); - this.hashMap = new HashMap(); - this.unassociatedProviders = new HashSet(); - this.adapterProviders = new HashMap(); - - // doesn't instantiate classes, just stores configuration elements - AdapterFactoryRegistryReader.readRegistry(hashMap); - } - - void add(AdapterFactoryProvider adapterFactoryProvider) { - this.unassociatedProviders.add(adapterFactoryProvider); - } - - public Iterator getAdapterFactories() { - if (DEBUG) { - System.out.println("===================================================================================="); //$NON-NLS-1$ - System.out.println("GETTING ALL ADAPTER FACTORIES"); //$NON-NLS-1$ - } - - List results = new ArrayList(); - - // add providers that have no content type specification - results.addAll(this.unassociatedProviders); - Iterator it = this.hashMap.keySet().iterator(); - String contentTypeId = null; - while (it.hasNext()) { - contentTypeId = (String) it.next(); - - if (DEBUG) - System.out.println(" + for: " + contentTypeId); //$NON-NLS-1$ - - results.addAll(getAdapterFactoriesAsList(contentTypeId)); - } - - if (DEBUG) { - System.out.println("===================================================================================="); //$NON-NLS-1$ - } - - return results.iterator(); - } - - public Iterator getAdapterFactories(String contentTypeID) { - if (DEBUG) { - System.out.println("===================================================================================="); //$NON-NLS-1$ - System.out.println("GETTING ADAPTER FACTORIES for: " + contentTypeID); //$NON-NLS-1$ - } - - List results = new ArrayList(); - - // add providers that have no content type specification - results.addAll(unassociatedProviders); - - // add unknown content type providers (for backwards compatability) - results.addAll(getAdapterFactoriesAsList(AdapterFactoryRegistryReader.UNKNOWN_CONTENT_TYPE)); - - // add providers for specific content type - results.addAll(getAdapterFactoriesAsList(Platform.getContentTypeManager().getContentType(contentTypeID))); - - - if (DEBUG) { - System.out.println("===================================================================================="); //$NON-NLS-1$ - } - - return results.iterator(); - } - - public List getAdapterFactoriesAsList(IContentType contentType) { - IContentType type = contentType; - List results = new ArrayList(); - while (type != null && !type.getId().equals(IContentTypeManager.CT_TEXT)) { - results.addAll(getAdapterFactoriesAsList(type.getId())); - type = type.getBaseType(); - } - return results; - } - - /** - * Using this new API, only AdapterFactoryProviders for a certain content - * type are instantiated. This will allow for the minimum number of - * plugins to be loaded rather than all that implement the adapter factory - * extension point. - * - * @param contentTypeID - * @return - */ - public List getAdapterFactoriesAsList(String contentTypeID) { - - List results = new ArrayList(); - - // get element2Provider map for specified content type - Object o = hashMap.get(contentTypeID); - if (o != null) { - // instantiate if necessary from - // element2adapterFactoryProvider - // map - Map element2Provider = (Map) o; - Iterator it = element2Provider.keySet().iterator(); - IConfigurationElement element = null; - String classname = null; - Object existing = null; - AdapterFactoryProvider p = null; - while (it.hasNext()) { - element = (IConfigurationElement) it.next(); - o = element2Provider.get(element); - if (o != null) { - // this provider has already been created - if (DEBUG) - System.out.println("already created: " + element.getAttribute(ATT_CLASS)); //$NON-NLS-1$ - - results.add(o); - } - else { - // need to create the provider - try { - classname = element.getAttribute(ATT_CLASS); - - if (DEBUG) - System.out.println("about to create: " + classname); //$NON-NLS-1$ - - // check if we created one already - existing = this.adapterProviders.get(classname); - if (existing == null) { - // this is the only place - // AdapterFactoryProviders - // are created - p = (AdapterFactoryProvider) element.createExecutableExtension(ATT_CLASS); // $NON-NLS-1$ - this.adapterProviders.put(classname, p); - } - else { - p = (AdapterFactoryProvider) existing; - } - - // add to element2Provider for this contentType - element2Provider.put(element, p); - // add to results to return for this method - results.add(p); - - } - catch (CoreException e) { - // if the provider throws any exception, just log - // and - // continue - Logger.logException(e); - } - } - } - } - - return results; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/provisional/registry/AdapterFactoryRegistryReader.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/provisional/registry/AdapterFactoryRegistryReader.java deleted file mode 100644 index 383e5e0b48..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/provisional/registry/AdapterFactoryRegistryReader.java +++ /dev/null @@ -1,142 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.provisional.registry; - -import java.util.HashMap; - -import org.eclipse.core.runtime.IConfigurationElement; -import org.eclipse.core.runtime.IExtensionPoint; -import org.eclipse.core.runtime.IExtensionRegistry; -import org.eclipse.core.runtime.Platform; -import org.eclipse.wst.sse.ui.internal.Logger; - - -/** - * This class just converts what's in the plugins registry into a form more - * easily useable by others, the ContentTypeRegistry. - */ -class AdapterFactoryRegistryReader { - protected final static String ATT_CLASS = "class"; //$NON-NLS-1$ - - protected final static String ATT_ID = "id"; //$NON-NLS-1$ - - private static boolean DEBUG = false; - protected final static String EXTENSION_POINT_ID = "adapterFactoryDescription"; //$NON-NLS-1$ - // - protected final static String PLUGIN_ID = "org.eclipse.wst.sse.ui"; //$NON-NLS-1$ - protected final static String TAG_CONTENT_TYPE = "contentType"; //$NON-NLS-1$ - - protected final static String TAG_NAME = "adapterFactoryDescription"; //$NON-NLS-1$ - - public final static String UNKNOWN_CONTENT_TYPE = "unknown"; //$NON-NLS-1$ - - /** - * adds configuration element to contentTypeId map [contentTypeId -> - * element2providerMap] | V [element -> provider] - * - * NOTE: this doesn't create the provider yet, that must be done on demand - * and stored in the appropriate element2provider - * - * @param map - * @param contentTypeId - * @param element - */ - private static void addElementForContentType(HashMap map, String contentTypeId, IConfigurationElement element) { - - Object o = map.get(contentTypeId); - if (o == null) { - HashMap element2provider = new HashMap(); - // don't create the executable extension yet - element2provider.put(element, null); - map.put(contentTypeId, element2provider); - - if (DEBUG) - System.out.println("added " + element.getAttribute(ATT_CLASS) + ", but didn't create exec extension"); //$NON-NLS-1$ //$NON-NLS-2$ - } else { - // add element to unknown list (not executable ext yet...) - HashMap element2provider = (HashMap) o; - element2provider.put(element, null); - - if (DEBUG) - System.out.println("added " + element.getAttribute(ATT_CLASS) + " to unknown list, but didn't create exec extension"); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - - /** - * the map passed in: [contentTypeId -> element2providerMap] | V [element -> - * provider] - * - * @param element - * @param map - * @return - */ - protected static AdapterFactoryProvider readElement(IConfigurationElement element, HashMap map) { - - AdapterFactoryProvider adapterFactoryProvider = null; - if (element.getName().equals(TAG_NAME)) { - try { - IConfigurationElement[] children = element.getChildren(); - boolean specifiedContentType = false; - if (children != null && children.length > 0) { - // content types are specified - for (int i = 0; i < children.length; i++) { - if (children[i].getName().equals(TAG_CONTENT_TYPE)) { - // it's possible to have non-contentType childrent - specifiedContentType = true; - String contentType = children[i].getAttribute(ATT_ID); - addElementForContentType(map, contentType, element); - } - } - } - if (!specifiedContentType) { - // no content type association - addElementForContentType(map, UNKNOWN_CONTENT_TYPE, element); - } - } catch (Exception e) { - // if the provider throws any exception, just log and continue - Logger.logException(e); - } - } - return adapterFactoryProvider; - } - - /** - * We simply require an 'add' method, of what ever it is we are to read - * into - */ - static void readRegistry(HashMap map) { - IExtensionRegistry registry = Platform.getExtensionRegistry(); - IExtensionPoint point = registry.getExtensionPoint(PLUGIN_ID, EXTENSION_POINT_ID); - if (point != null) { - IConfigurationElement[] elements = point.getConfigurationElements(); - for (int i = 0; i < elements.length; i++) { - readElement(elements[i], map); - } - } - } - - protected IConfigurationElement configElement = null; - - // protected final static String ADAPTER_CLASS = "adapterClass"; - // //$NON-NLS-1$ - // protected final static String DOC_TYPE_ID = "docTypeId"; //$NON-NLS-1$ - // protected final static String MIME_TYPE_LIST = "mimeTypeList"; - // //$NON-NLS-1$ - // - /** - * ContentTypeRegistryReader constructor comment. - */ - AdapterFactoryRegistryReader() { - super(); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/provisional/style/AbstractLineStyleProvider.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/provisional/style/AbstractLineStyleProvider.java deleted file mode 100644 index 2b80125bf4..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/provisional/style/AbstractLineStyleProvider.java +++ /dev/null @@ -1,405 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.provisional.style; - -import java.util.Collection; -import java.util.HashMap; - -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.text.ITypedRegion; -import org.eclipse.jface.text.TextAttribute; -import org.eclipse.jface.text.source.ISourceViewer; -import org.eclipse.jface.util.IPropertyChangeListener; -import org.eclipse.jface.util.PropertyChangeEvent; -import org.eclipse.swt.SWT; -import org.eclipse.swt.custom.StyleRange; -import org.eclipse.swt.graphics.RGB; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion; -import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegion; -import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegionCollection; -import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegionList; -import org.eclipse.wst.sse.core.internal.util.Debug; -import org.eclipse.wst.sse.ui.internal.preferences.ui.ColorHelper; -import org.eclipse.wst.sse.ui.internal.util.EditorUtility; - - -public abstract class AbstractLineStyleProvider { - private class PropertyChangeListener implements IPropertyChangeListener { - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.util.IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent) - */ - public void propertyChange(PropertyChangeEvent event) { - // have to do it this way so others can override the method - handlePropertyChange(event); - } - } - - protected IStructuredDocument fDocument; - protected Highlighter fHighlighter; - private boolean fInitialized; - protected PropertyChangeListener fPreferenceListener = new PropertyChangeListener(); - - //private ISourceViewer fSourceViewer = null; - protected ReconcilerHighlighter fRecHighlighter = null; - - /** Contains all text attributes pertaining to this line style provider */ - private HashMap fTextAttributes = null; - - // we keep track of LogMessage to avoid writing hundreds of messages, - // but still give a hint that something is wrong with attributeProviders - // and/or regions. - // It's only written in the case of a program error, but there's no use - // adding - // salt to the wound. - // private boolean wroteOneLogMessage; - /** - */ - protected AbstractLineStyleProvider() { - } - - /** - * Looks up the colorKey in the preference store and adds the style - * information to list of TextAttributes - * - * @param colorKey - */ - protected void addTextAttribute(String colorKey) { - if (getColorPreferences() != null) { - String prefString = getColorPreferences().getString(colorKey); - String[] stylePrefs = ColorHelper.unpackStylePreferences(prefString); - if (stylePrefs != null) { - RGB foreground = ColorHelper.toRGB(stylePrefs[0]); - RGB background = ColorHelper.toRGB(stylePrefs[1]); - boolean bold = Boolean.valueOf(stylePrefs[2]).booleanValue(); - boolean italic = Boolean.valueOf(stylePrefs[3]).booleanValue(); - boolean strikethrough = Boolean.valueOf(stylePrefs[4]).booleanValue(); - boolean underline = Boolean.valueOf(stylePrefs[5]).booleanValue(); - int style = SWT.NORMAL; - if (bold) { - style = style | SWT.BOLD; - } - if (italic) { - style = style | SWT.ITALIC; - } - if (strikethrough) { - style = style | TextAttribute.STRIKETHROUGH; - } - if (underline) { - style = style | TextAttribute.UNDERLINE; - } - - TextAttribute createTextAttribute = createTextAttribute(foreground, background, style); - getTextAttributes().put(colorKey, createTextAttribute); - } - } - } - - protected void commonInit(IStructuredDocument document, Highlighter highlighter) { - - fDocument = document; - fHighlighter = highlighter; - } - - /** - * this version does "trim" regions to match request - */ - private StyleRange createStyleRange(ITextRegionCollection flatNode, ITextRegion region, TextAttribute attr, int startOffset, int length) { - int start = flatNode.getStartOffset(region); - if (start < startOffset) - start = startOffset; - - // Base the text end offset off of the, possibly adjusted, start - int textEnd = start + region.getTextLength(); - int maxOffset = startOffset + length; - - int end = flatNode.getEndOffset(region); - // Use the end of the text in the region to avoid applying background color to trailing whitespace - if(textEnd < end) - end = textEnd; - // instead of end-start? - if (end > maxOffset) - end = maxOffset; - StyleRange result = new StyleRange(start, end - start, attr.getForeground(), attr.getBackground(), attr.getStyle()); - if((attr.getStyle() & TextAttribute.STRIKETHROUGH) != 0) { - result.strikeout = true; - } - if((attr.getStyle() & TextAttribute.UNDERLINE) != 0) { - result.underline = true; - } - return result; - - } - - protected TextAttribute createTextAttribute(RGB foreground, RGB background, boolean bold) { - return new TextAttribute((foreground != null) ? EditorUtility.getColor(foreground) : null, (background != null) ? EditorUtility.getColor(background) : null, bold ? SWT.BOLD : SWT.NORMAL); - } - - protected TextAttribute createTextAttribute(RGB foreground, RGB background, int style) { - return new TextAttribute((foreground != null) ? EditorUtility.getColor(foreground) : null, (background != null) ? EditorUtility.getColor(background) : null, style); - } - - abstract protected TextAttribute getAttributeFor(ITextRegion region); - - protected TextAttribute getAttributeFor(ITextRegionCollection collection, ITextRegion region) { - return getAttributeFor(region); - } - - abstract protected IPreferenceStore getColorPreferences(); - - protected IStructuredDocument getDocument() { - return fDocument; - } - - public void setDocument(IStructuredDocument document) { - fDocument = document; - } - - /** - */ - protected Highlighter getHighlighter() { - return fHighlighter; - } - - /** - * Returns the hashtable containing all the text attributes for this line - * style provider. Lazily creates a hashtable if one has not already been - * created. - * - * @return - */ - protected HashMap getTextAttributes() { - if (fTextAttributes == null) { - fTextAttributes = new HashMap(); - loadColors(); - } - return fTextAttributes; - } - - protected void handlePropertyChange(PropertyChangeEvent event) { - // force a full update of the text viewer - if(fRecHighlighter != null) - fRecHighlighter.refreshDisplay(); - } - - public void init(IStructuredDocument structuredDocument, Highlighter highlighter) { - - commonInit(structuredDocument, highlighter); - - if (isInitialized()) - return; - - registerPreferenceManager(); - - setInitialized(true); - } - - public void init(IStructuredDocument structuredDocument, ISourceViewer sourceViewer) { - init(structuredDocument, (Highlighter) null); - } - - public void init(IStructuredDocument structuredDocument, ReconcilerHighlighter highlighter) { - fDocument = structuredDocument; - fRecHighlighter = highlighter; - - if(isInitialized()) - return; - - registerPreferenceManager(); - - setInitialized(true); - } - - /** - * @deprecated - left because it's public, but we aren't adapters any more - */ - public boolean isAdapterForType(java.lang.Object type) { - return type == LineStyleProvider.class; - } - - /** - * Returns the initialized. - * - * @return boolean - */ - public boolean isInitialized() { - return fInitialized; - } - - abstract protected void loadColors(); - - public boolean prepareRegions(ITypedRegion typedRegion, int lineRequestStart, int lineRequestLength, Collection holdResults) { - final int partitionStartOffset = typedRegion.getOffset(); - final int partitionLength = typedRegion.getLength(); - IStructuredDocumentRegion structuredDocumentRegion = getDocument().getRegionAtCharacterOffset(partitionStartOffset); - boolean handled = false; - - handled = prepareTextRegions(structuredDocumentRegion, partitionStartOffset, partitionLength, holdResults); - - return handled; - } - - /** - * @param region - * @param start - * @param length - * @param holdResults - * @return - */ - private boolean prepareTextRegion(ITextRegionCollection blockedRegion, int partitionStartOffset, int partitionLength, Collection holdResults) { - boolean handled = false; - final int partitionEndOffset = partitionStartOffset + partitionLength - 1; - ITextRegion region = null; - ITextRegionList regions = blockedRegion.getRegions(); - int nRegions = regions.size(); - StyleRange styleRange = null; - for (int i = 0; i < nRegions; i++) { - region = regions.get(i); - TextAttribute attr = null; - TextAttribute previousAttr = null; - if (blockedRegion.getStartOffset(region) > partitionEndOffset) - break; - if (blockedRegion.getEndOffset(region) <= partitionStartOffset) - continue; - - if (region instanceof ITextRegionCollection) { - handled = prepareTextRegion((ITextRegionCollection) region, partitionStartOffset, partitionLength, holdResults); - } else { - - attr = getAttributeFor(blockedRegion, region); - if (attr != null) { - handled = true; - // if this region's attr is the same as previous one, then - // just adjust the previous style range - // instead of creating a new instance of one - // note: to use 'equals' in this case is important, since - // sometimes - // different instances of attributes are associated with a - // region, even the - // the attribute has the same values. - // TODO: this needs to be improved to handle readonly - // regions correctly - if ((styleRange != null) && (previousAttr != null) && (previousAttr.equals(attr))) { - styleRange.length += region.getLength(); - } else { - styleRange = createStyleRange(blockedRegion, region, attr, partitionStartOffset, partitionLength); - holdResults.add(styleRange); - // technically speaking, we don't need to update - // previousAttr - // in the other case, because the other case is when - // it hasn't changed - previousAttr = attr; - } - } else { - previousAttr = null; - } - } - } - return handled; - } - - private boolean prepareTextRegions(IStructuredDocumentRegion structuredDocumentRegion, int partitionStartOffset, int partitionLength, Collection holdResults) { - boolean handled = false; - final int partitionEndOffset = partitionStartOffset + partitionLength - 1; - while (structuredDocumentRegion != null && structuredDocumentRegion.getStartOffset() <= partitionEndOffset) { - ITextRegion region = null; - ITextRegionList regions = structuredDocumentRegion.getRegions(); - int nRegions = regions.size(); - StyleRange styleRange = null; - for (int i = 0; i < nRegions; i++) { - region = regions.get(i); - TextAttribute attr = null; - TextAttribute previousAttr = null; - if (structuredDocumentRegion.getStartOffset(region) > partitionEndOffset) - break; - if (structuredDocumentRegion.getEndOffset(region) <= partitionStartOffset) - continue; - - if (region instanceof ITextRegionCollection) { - boolean handledCollection = (prepareTextRegion((ITextRegionCollection) region, partitionStartOffset, partitionLength, holdResults)); - handled = (!handled) ? handledCollection : handled; - } else { - - attr = getAttributeFor(structuredDocumentRegion, region); - if (attr != null) { - handled = true; - // if this region's attr is the same as previous one, - // then just adjust the previous style range - // instead of creating a new instance of one - // note: to use 'equals' in this case is important, - // since sometimes - // different instances of attributes are associated - // with a region, even the - // the attribute has the same values. - // TODO: this needs to be improved to handle readonly - // regions correctly - if ((styleRange != null) && (previousAttr != null) && (previousAttr.equals(attr))) { - styleRange.length += region.getLength(); - } else { - styleRange = createStyleRange(structuredDocumentRegion, region, attr, partitionStartOffset, partitionLength); - holdResults.add(styleRange); - // technically speaking, we don't need to update - // previousAttr - // in the other case, because the other case is - // when it hasn't changed - previousAttr = attr; - } - } else { - previousAttr = null; - } - } - - if (Debug.syntaxHighlighting && !handled) { - System.out.println("not handled in prepareRegions"); //$NON-NLS-1$ - } - } - structuredDocumentRegion = structuredDocumentRegion.getNext(); - } - return handled; - } - - protected void registerPreferenceManager() { - IPreferenceStore pref = getColorPreferences(); - if (pref != null) { - pref.addPropertyChangeListener(fPreferenceListener); - } - } - - public void release() { - unRegisterPreferenceManager(); - if (fTextAttributes != null) { - fTextAttributes.clear(); - fTextAttributes = null; - } - setInitialized(false); - } - - /** - * Sets the initialized. - * - * @param initialized - * The initialized to set - */ - private void setInitialized(boolean initialized) { - this.fInitialized = initialized; - } - - protected void unRegisterPreferenceManager() { - IPreferenceStore pref = getColorPreferences(); - if (pref != null) { - pref.removePropertyChangeListener(fPreferenceListener); - } - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/provisional/style/CompatibleHighlighter.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/provisional/style/CompatibleHighlighter.java deleted file mode 100644 index a54398bf78..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/provisional/style/CompatibleHighlighter.java +++ /dev/null @@ -1,128 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.provisional.style; - -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.swt.custom.LineStyleEvent; -import org.eclipse.swt.custom.StyleRange; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument; - -/** - * https://bugs.eclipse.org/bugs/show_bug.cgi?id=224209 - * - * Created to provide compatibility with refreshDisplay() and getTextViewer() - * methods on the superclass that might be called by LineStyleProviders. - */ -public final class CompatibleHighlighter extends Highlighter { - - private ITextViewer textViewer; - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.sse.ui.internal.provisional.style.Highlighter#addProvider(java.lang.String, - * org.eclipse.wst.sse.ui.internal.provisional.style.LineStyleProvider) - */ - public void addProvider(String partitionType, LineStyleProvider provider) { - super.addProvider(partitionType, provider); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.sse.ui.internal.provisional.style.Highlighter#getTextViewer() - */ - public ITextViewer getTextViewer() { - return super.getTextViewer(); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.sse.ui.internal.provisional.style.Highlighter#install(org.eclipse.jface.text.ITextViewer) - */ - public void install(ITextViewer newTextViewer) { - textViewer = newTextViewer; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.sse.ui.internal.provisional.style.Highlighter#lineGetStyle(int, - * int) - */ - public StyleRange[] lineGetStyle(int eventLineOffset, int eventLineLength) { - return new StyleRange[0]; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.sse.ui.internal.provisional.style.Highlighter#lineGetStyle(org.eclipse.swt.custom.LineStyleEvent) - */ - public void lineGetStyle(LineStyleEvent event) { - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.sse.ui.internal.provisional.style.Highlighter#refreshDisplay() - */ - public void refreshDisplay() { - if (textViewer != null) - textViewer.invalidateTextPresentation(); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.sse.ui.internal.provisional.style.Highlighter#refreshDisplay(int, - * int) - */ - public void refreshDisplay(int start, int length) { - refreshDisplay(); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.sse.ui.internal.provisional.style.Highlighter#removeProvider(java.lang.String) - */ - public void removeProvider(String partitionType) { - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.sse.ui.internal.provisional.style.Highlighter#setDocument(org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument) - */ - public void setDocument(IStructuredDocument structuredDocument) { - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.sse.ui.internal.provisional.style.Highlighter#setDocumentPartitioning(java.lang.String) - */ - public void setDocumentPartitioning(String partitioning) { - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.sse.ui.internal.provisional.style.Highlighter#uninstall() - */ - public void uninstall() { - super.uninstall(); - textViewer = null; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/provisional/style/Highlighter.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/provisional/style/Highlighter.java deleted file mode 100644 index b47107d67c..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/provisional/style/Highlighter.java +++ /dev/null @@ -1,904 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2006 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.provisional.style; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.text.IDocumentExtension3; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.ITextViewerExtension5; -import org.eclipse.jface.text.ITypedRegion; -import org.eclipse.jface.text.Region; -import org.eclipse.jface.text.TextUtilities; -import org.eclipse.jface.util.IPropertyChangeListener; -import org.eclipse.jface.util.PropertyChangeEvent; -import org.eclipse.swt.custom.LineStyleEvent; -import org.eclipse.swt.custom.StyleRange; -import org.eclipse.swt.custom.StyledText; -import org.eclipse.swt.graphics.Color; -import org.eclipse.swt.graphics.RGB; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument; -import org.eclipse.wst.sse.core.internal.util.Debug; -import org.eclipse.wst.sse.ui.internal.ExtendedConfigurationBuilder; -import org.eclipse.wst.sse.ui.internal.Logger; -import org.eclipse.wst.sse.ui.internal.SSEUIPlugin; -import org.eclipse.wst.sse.ui.internal.preferences.EditorPreferenceNames; -import org.eclipse.wst.sse.ui.internal.util.EditorUtility; - -/** - * This class is to directly mediate between the Structured Document data - * structure and the text widget's text and events. It assumes there only the - * model is interested in text events, and all other views will work from that - * model. Changes to the text widgets input can cause changes in the model, - * which in turn cause changes to the widget's display. - * - */ -public class Highlighter implements IHighlighter { - - /** - * A utility class to do various color manipulations - */ - private class YUV_RGBConverter { - /** - * This class "holds" the YUV values corresponding to RGB color - */ - private class YUV { - - class NormalizedRGB { - double blue; - double green; - private final double maxRGB = 256.0; - double red; - - public NormalizedRGB(RGB rgb) { - // first normalize to between 0 - 1 - red = rgb.red / maxRGB; - green = rgb.green / maxRGB; - blue = rgb.blue / maxRGB; - - red = gammaNormalized(red); - green = gammaNormalized(green); - blue = gammaNormalized(blue); - - } - } - - private NormalizedRGB normalizedRGB; - - private double u = -1; - private double v = -1; - private double y = -1; - - private YUV() { - super(); - } - - public YUV(double y, double u, double v) { - this(); - this.y = y; - this.u = u; - this.v = v; - } - - public YUV(RGB rgb) { - this(); - normalizedRGB = new NormalizedRGB(rgb); - // force calculations - getY(); - getV(); - getU(); - } - - /** - * normalize to "average" gamma 2.2222 or 1/0.45 - */ - double gammaNormalized(double colorComponent) { - if (colorComponent < 0.018) { - return colorComponent * 0.45; - } - else { - return 1.099 * Math.pow(colorComponent, 0.45) - 0.099; - } - } - - /** - * @return RGB based on original RGB and current YUV values; - */ - public RGB getRGB() { - RGB result = null; - double r = getY() + 1.14 * getV(); - double g = getY() - 0.395 * getU() - 0.58 * getV(); - double b = getY() + 2.032 * getU(); - - int red = (int) (inverseGammaNormalized(r) * 256); - int green = (int) (inverseGammaNormalized(g) * 256); - int blue = (int) (inverseGammaNormalized(b) * 256); - if (red < 0) - red = 0; - else if (red > 255) - red = 255; - if (green < 0) - green = 0; - else if (green > 255) - green = 255; - if (blue < 0) - blue = 0; - else if (blue > 255) - blue = 255; - - result = new RGB(red, green, blue); - return result; - } - - public double getU() { - if (u == -1) { - u = 0.4949 * (normalizedRGB.blue - getY()); - } - return u; - - } - - public double getV() { - if (v == -1) { - v = 0.877 * (normalizedRGB.red - getY()); - } - return v; - } - - public double getY() { - if (y == -1) { - y = 0.299 * normalizedRGB.red + 0.587 * normalizedRGB.green + 0.114 * normalizedRGB.blue; - } - return y; - } - - double inverseGammaNormalized(double colorComponent) { - if (colorComponent < 0.018) { - return colorComponent * .222; - } - else { - return Math.pow(((.9099 * colorComponent + 0.09)), 2.22); - } - } - - } - - public YUV_RGBConverter() { - super(); - } - - public double calculateYComponent(Color targetColor) { - return new YUV(targetColor.getRGB()).getY(); - } - - public RGB transformRGB(RGB originalRGB, double scaleFactor, double target) { - RGB transformedRGB = null; - // CCIR601 yuv = new CCIR601(originalRGB); - YUV yuv = new YUV(originalRGB); - double y = yuv.getY(); - // zero is black, one is white - if (y < target) { - // is "dark" make lighter - y = y + ((target - y) * scaleFactor); - } - else { - // is "light" make darker - y = y - ((y - target) * scaleFactor); - } - // yuv.setY(y); - YUV newYUV = new YUV(y, yuv.getU(), yuv.getV()); - // CCIR601 newYUV = new CCIR601(y, yuv.getCb601(), - // yuv.getCr601()); - transformedRGB = newYUV.getRGB(); - return transformedRGB; - } - - public RGB transformRGBToGrey(RGB originalRGB, double scaleFactor, double target) { - RGB transformedRGB = null; - // we left the "full" API method signature, but this - // version does not take into account originalRGB, though - // it might someday. - // for now, we'll simply make the new RGB grey, either a little - // lighter, or a little darker than background. - double y = 0; - double mid = 0.5; - // zero is black, one is white - if (target < mid) { - // is "dark" make lighter - y = target + scaleFactor; - } - else { - // is "light" make darker - y = target - scaleFactor; - } - int c = (int) Math.round(y * 255); - // just to gaurd against mis-use, or scale's values greater - // than mid point (and possibly rounding error) - if (c > 255) - c = 255; - if (c < 0) - c = 0; - transformedRGB = new RGB(c, c, c); - return transformedRGB; - } - } - - private final boolean DEBUG = false; - private final StyleRange[] EMPTY_STYLE_RANGE = new StyleRange[0]; - static final String LINE_STYLE_PROVIDER_EXTENDED_ID = "linestyleprovider"; //$NON-NLS-1$ - private static final int MAX_NUMBER_STYLES = 500; - private static final int LEFT_STYLES_SIZE = 200; - private static final int RIGHT_STYLES_SIZE = 200; - private static final int MIDDLE_STYLES_SIZE = 1; - - private IPropertyChangeListener fForegroundScaleListener = new IPropertyChangeListener() { - public void propertyChange(PropertyChangeEvent event) { - if (EditorPreferenceNames.READ_ONLY_FOREGROUND_SCALE.equals(event.getProperty())) { - IPreferenceStore editorStore = SSEUIPlugin.getDefault().getPreferenceStore(); - readOnlyForegroundScaleFactor = editorStore.getInt(EditorPreferenceNames.READ_ONLY_FOREGROUND_SCALE); - disposeColorTable(); - refreshDisplay(); - } - } - }; - private List fHoldStyleResults; - private String fPartitioning = IDocumentExtension3.DEFAULT_PARTITIONING; - - private int fSavedLength = -1; - private int fSavedOffset = -1; - private StyleRange[] fSavedRanges = null; - - private IStructuredDocument fStructuredDocument; - private Map fTableOfProviders; - - private Map fExtendedProviders; - - protected final LineStyleProvider NOOP_PROVIDER = new LineStyleProviderForNoOp(); - - private double readOnlyBackgroundScaleFactor = 10; - private Hashtable readOnlyColorTable; - double readOnlyForegroundScaleFactor = 30; - - private YUV_RGBConverter rgbConverter; - private ITextViewer textViewer; - private StyledText textWidget; - - public Highlighter() { - super(); - - // in the 'limitSize' method, we make this strong assumption, so, will check here, - // so if tweaked in future, we'll get a quick reminder. - if (LEFT_STYLES_SIZE + MIDDLE_STYLES_SIZE + RIGHT_STYLES_SIZE > MAX_NUMBER_STYLES) { - throw new IllegalStateException("Highligher constants are not defined correctly"); //$NON-NLS-1$ - } - } - - protected void addEmptyRange(int start, int length, Collection holdResults) { - StyleRange result = new StyleRange(); - result.start = start; - result.length = length; - holdResults.add(result); - } - - /** - * Registers a given line style provider for a particular partition type. - * If there is already a line style provider registered for this type, the - * new line style provider is registered instead of the old one. - * - * @param partitionType - * the partition type under which to register - * @param the - * line style provider to register, or <code>null</code> to - * remove an existing one - */ - public void addProvider(String partitionType, LineStyleProvider provider) { - getTableOfProviders().put(partitionType, provider); - } - - /** - * Adjust the style ranges' start and length so that they refer to the - * textviewer widget's range instead of the textviewer's document range. - * - * @param ranges - * @param adjustment - */ - protected void adjust(StyleRange[] ranges, int adjustment) { - ITextViewer viewer = getTextViewer(); - - if (adjustment != 0) { - // just use the adjustment value - // convert document regions back to widget regions - for (int i = 0; i < ranges.length; i++) { - // just adjust the range using the given adjustment - ranges[i].start += adjustment; - } - } - else if (viewer instanceof ITextViewerExtension5) { - // use ITextViewerExtension5 - ITextViewerExtension5 extension = (ITextViewerExtension5) viewer; - - // convert document regions back to widget regions - for (int i = 0; i < ranges.length; i++) { - // get document range, taking into account folding - // regions in viewer - IRegion region = extension.modelRange2WidgetRange(new Region(ranges[i].start, ranges[i].length)); - if (region != null) { - ranges[i].start = region.getOffset(); - ranges[i].length = region.getLength(); - } // else what happens if region is not found?! - } - } - } - - - /** - * @deprecated - Read Only areas have unchanged background colors - */ - void adjustBackground(StyleRange styleRange) { - RGB oldRGB = null; - Color oldColor = styleRange.background; - if (oldColor == null) { - oldColor = getTextWidget().getBackground(); - } - oldRGB = oldColor.getRGB(); - Color newColor = getCachedColorFor(oldRGB); - if (newColor == null) { - double target = getRGBConverter().calculateYComponent(oldColor); - // if background is "light" make it darker, and vice versa - if (target < 0.5) - target = 1.0; - else - target = 0.0; - RGB newRGB = getRGBConverter().transformRGB(oldRGB, readOnlyBackgroundScaleFactor / 100.0, target); - - cacheColor(oldRGB, newRGB); - newColor = getCachedColorFor(oldRGB); - } - styleRange.background = newColor; - } - - private void adjustForeground(StyleRange styleRange) { - RGB oldRGB = null; - // Color oldColor = styleRange.foreground; - Color oldColor = styleRange.background; - if (oldColor == null) { - // oldRGB = getTextWidget().getForeground().getRGB(); - oldColor = getTextWidget().getBackground(); - oldRGB = oldColor.getRGB(); - } - else { - oldRGB = oldColor.getRGB(); - } - Color newColor = getCachedColorFor(oldRGB); - if (newColor == null) { - // make text "closer to" background lumanence - double target = getRGBConverter().calculateYComponent(oldColor); - RGB newRGB = getRGBConverter().transformRGBToGrey(oldRGB, readOnlyForegroundScaleFactor / 100.0, target); - - // save conversion, so calculations only need to be done once - cacheColor(oldRGB, newRGB); - newColor = getCachedColorFor(oldRGB); - } - styleRange.foreground = newColor; - } - - /** - * Cache read-only color. - * - * @param oldRGB - * @param newColor - */ - private void cacheColor(RGB oldRGB, RGB newColor) { - if (readOnlyColorTable == null) { - readOnlyColorTable = new Hashtable(); - } - readOnlyColorTable.put(oldRGB, newColor); - } - - /** - * @param result - * @return - */ - private StyleRange[] convertReadOnlyRegions(StyleRange[] result, int start, int length) { - IStructuredDocument structuredDocument = getDocument(); - - /** - * (dmw) For client/provider simplicity (and consistent look and feel) - * we'll handle readonly regions in one spot, here in the Highlighter. - * Currently it is a fair assumption that each readonly region will be - * on an ITextRegion boundary, so we combine consecutive styles when - * found to be equivalent. Plus, for now, we'll just adjust - * foreground. Eventually will use a "dimming" algrorithm to adjust - * color's satuation/brightness. - */ - if (structuredDocument.containsReadOnly(start, length)) { - // something is read-only in the line, so go through each style, - // and adjust - for (int i = 0; i < result.length; i++) { - StyleRange styleRange = result[i]; - if (structuredDocument.containsReadOnly(styleRange.start, styleRange.length)) { - adjustForeground(styleRange); - } - } - } - return result; - } - - /** - * Clear out the readOnlyColorTable - */ - void disposeColorTable() { - if (readOnlyColorTable != null) { - readOnlyColorTable.clear(); - } - readOnlyColorTable = null; - } - - /** - * This method is just to get existing read-only colors. - */ - private Color getCachedColorFor(RGB oldRGB) { - Color result = null; - - if (readOnlyColorTable != null) { - RGB readOnlyRGB = (RGB) readOnlyColorTable.get(oldRGB); - result = EditorUtility.getColor(readOnlyRGB); - } - - return result; - } - - protected IStructuredDocument getDocument() { - return fStructuredDocument; - } - - /** - * Adjust the given widget offset and length so that they are the - * textviewer document's offset and length, taking into account what is - * actually visible in the document. - * - * @param offset - * @param length - * @return a region containing the offset and length within the - * textviewer's document or null if the offset is not within the - * document - */ - private IRegion getDocumentRangeFromWidgetRange(int offset, int length) { - IRegion styleRegion = null; - ITextViewer viewer = getTextViewer(); - if (viewer instanceof ITextViewerExtension5) { - // get document range, taking into account folding regions in - // viewer - ITextViewerExtension5 extension = (ITextViewerExtension5) viewer; - styleRegion = extension.widgetRange2ModelRange(new Region(offset, length)); - } - else { - // get document range, taking into account viewer visible region - // get visible region in viewer - IRegion vr = null; - if (viewer != null) - vr = viewer.getVisibleRegion(); - else - vr = new Region(0, getDocument().getLength()); - - // if offset is not within visible region, then we don't really - // care - if (offset <= vr.getLength()) { - // Adjust the offset to be within visible region - styleRegion = new Region(offset + vr.getOffset(), length); - } - } - return styleRegion; - } - - - private Map getExtendedProviders() { - if (fExtendedProviders == null) { - fExtendedProviders = new HashMap(3); - } - return fExtendedProviders; - } - - /** - * Method getProviderFor. - * - * @param typedRegion - * @return LineStyleProvider - */ - private LineStyleProvider getProviderFor(ITypedRegion typedRegion) { - String type = typedRegion.getType(); - LineStyleProvider result = (LineStyleProvider) fTableOfProviders.get(type); - if (result == null) { - // NOT YET FINALIZED - DO NOT CONSIDER AS API - synchronized (getExtendedProviders()) { - if (!getExtendedProviders().containsKey(type)) { - LineStyleProvider provider = (LineStyleProvider) ExtendedConfigurationBuilder.getInstance().getConfiguration(LINE_STYLE_PROVIDER_EXTENDED_ID, type); - getExtendedProviders().put(type, provider); - if (provider != null) { - provider.init(getDocument(), this); - } - result = provider; - } - else { - result = (LineStyleProvider) getExtendedProviders().get(type); - } - } - } - if (result == null) { - result = NOOP_PROVIDER; - } - return result; - } - - private YUV_RGBConverter getRGBConverter() { - if (rgbConverter == null) { - rgbConverter = new YUV_RGBConverter(); - } - return rgbConverter; - } - - private Map getTableOfProviders() { - if (fTableOfProviders == null) { - fTableOfProviders = new HashMap(); - } - return fTableOfProviders; - } - - /** - * Returns the textViewer. - * - * @return ITextViewer - */ - public ITextViewer getTextViewer() { - return textViewer; - } - - /** - * @return - */ - protected StyledText getTextWidget() { - return textWidget; - } - - /** - * Installs highlighter support on the given text viewer. - * - * @param textViewer - * the text viewer on which content assist will work - */ - public void install(ITextViewer newTextViewer) { - this.textViewer = newTextViewer; - - IPreferenceStore editorStore = SSEUIPlugin.getDefault().getPreferenceStore(); - editorStore.addPropertyChangeListener(fForegroundScaleListener); - readOnlyForegroundScaleFactor = editorStore.getInt(EditorPreferenceNames.READ_ONLY_FOREGROUND_SCALE); - - if (textWidget != null) { - textWidget.removeLineStyleListener(this); - } - textWidget = newTextViewer.getTextWidget(); - if (textWidget != null) { - textWidget.addLineStyleListener(this); - } - - refreshDisplay(); - } - - public StyleRange[] lineGetStyle(int eventLineOffset, int eventLineLength) { - StyleRange[] eventStyles = EMPTY_STYLE_RANGE; - try { - if (getDocument() == null || eventLineLength == 0) { - // getDocument() == null - // during initialization, this is sometimes called before our - // structured - // is set, in which case we set styles to be the empty style - // range - // (event.styles can not be null) - - // eventLineLength == 0 - // we sometimes get odd requests from the very last CRLF in - // the - // document - // it has no length, and there is no node for it! - eventStyles = EMPTY_STYLE_RANGE; - } - else { - /* - * LineStyleProviders work using absolute document offsets. To - * support visible regions, adjust the requested range up to - * the full document offsets. - */ - IRegion styleRegion = getDocumentRangeFromWidgetRange(eventLineOffset, eventLineLength); - if (styleRegion != null) { - int start = styleRegion.getOffset(); - int length = styleRegion.getLength(); - - ITypedRegion[] partitions = TextUtilities.computePartitioning(getDocument(), fPartitioning, start, length, false); - eventStyles = prepareStyleRangesArray(partitions, start, length); - - /* - * If there is a subtext offset, the style ranges must be - * adjusted to the expected offsets just check if - * eventLineOffset is different than start then adjust, - * otherwise u can leave it alone unless there is special - * handling for itextviewerextension5? - */ - if (start != eventLineOffset) { - int offset = 0; - // figure out visible region to use for adjustment - // only adjust if need to - if (!(getTextViewer() instanceof ITextViewerExtension5)) { - IRegion vr = getTextViewer().getVisibleRegion(); - if (vr != null) { - offset = vr.getOffset(); - } - } - adjust(eventStyles, -offset); - } - - eventStyles = limitSize(eventStyles); - - // for debugging only - if (DEBUG) { - if (!valid(eventStyles, eventLineOffset, eventLineLength)) { - Logger.log(Logger.WARNING, "Highlighter::lineGetStyle found invalid styles at offset " + eventLineOffset); //$NON-NLS-1$ - } - } - } - - } - - } - catch (Exception e) { - // if ANY exception occurs during highlighting, - // just return "no highlighting" - eventStyles = EMPTY_STYLE_RANGE; - if (Debug.syntaxHighlighting) { - System.out.println("Exception during highlighting!"); //$NON-NLS-1$ - } - } - - return eventStyles; - } - - /** - * This method is to centralize the logic in limiting the overall number of style ranges - * that make it to the styled text widget. - * - * Too many styles sent to StyledText results in apparent, but not real, - * hangs of Eclipse Display thread. See - * https://bugs.eclipse.org/bugs/show_bug.cgi?id=108806 - * - * @param eventStyles - * @return - */ - private StyleRange[] limitSize(StyleRange[] eventStyles) { - - // quick return with same object if not modification needed - if (eventStyles.length < MAX_NUMBER_STYLES) { - return eventStyles; - } - else { - // we could just take the easy way out and truncate, but will - // be much better appearing if both the start of the line and the - // end of the line are displayed with styles. Since these are both - // the parts of the line a user is likely to look at. The middle of the - // line will still be "plain". Presumably, the user would re-format the - // file to avoid long lines, so unlikely to see the middle. - StyleRange[] newRanges = new StyleRange[LEFT_STYLES_SIZE + RIGHT_STYLES_SIZE + MIDDLE_STYLES_SIZE]; - System.arraycopy(eventStyles, 0, newRanges, 0, LEFT_STYLES_SIZE); - // - // do end, before we do middle - System.arraycopy(eventStyles, eventStyles.length-RIGHT_STYLES_SIZE, newRanges, LEFT_STYLES_SIZE + MIDDLE_STYLES_SIZE, RIGHT_STYLES_SIZE); - // - // technically, we should compute the exact middle as one big style range, - // with default colors and styles, so if someone does actually type or work with - // documnet as is, will still be correct. - // - StyleRange allBlank = new StyleRange(); - StyleRange lastKnown = newRanges[LEFT_STYLES_SIZE - 1]; - allBlank.start = lastKnown.start + lastKnown.length; - StyleRange nextKnown = newRanges[LEFT_STYLES_SIZE + MIDDLE_STYLES_SIZE + 1]; - allBlank.length = nextKnown.start - allBlank.start; - newRanges[LEFT_STYLES_SIZE] = allBlank; - return newRanges; - } - } - - /** - * A passthrough method that extracts relevant data from the - * LineStyleEvent and passes it along. This method was separated for - * performance testing purposes. - * - * @see org.eclipse.swt.custom.LineStyleListener#lineGetStyle(LineStyleEvent) - */ - public void lineGetStyle(LineStyleEvent event) { - int offset = event.lineOffset; - int length = event.lineText.length(); - - /* - * For some reason, we are sometimes asked for the same style range - * over and over again. This was found to happen during 'revert' of a - * file with one line in it that is 40K long! So, while we don't know - * root cause, caching the styled ranges in case the exact same - * request is made multiple times seems like cheap insurance. - */ - if (offset == fSavedOffset && length == fSavedLength && fSavedRanges != null) { - event.styles = fSavedRanges; - } - else { - // need to assign this array here, or else the field won't get - // updated - event.styles = lineGetStyle(offset, length); - // now saved "cached data" for repeated requests which are exaclty - // same - fSavedOffset = offset; - fSavedLength = length; - fSavedRanges = event.styles; - } - } - - /** - * Note: its very important this method never return null, which is why - * the final null check is in a finally clause - */ - - protected StyleRange[] prepareStyleRangesArray(ITypedRegion[] partitions, int start, int length) { - - StyleRange[] result = EMPTY_STYLE_RANGE; - - if (fHoldStyleResults == null) { - fHoldStyleResults = new ArrayList(partitions.length); - } - else { - fHoldStyleResults.clear(); - } - - // TODO: make some of these instance variables to prevent creation on - // stack - LineStyleProvider currentLineStyleProvider = null; - boolean handled = false; - for (int i = 0; i < partitions.length; i++) { - ITypedRegion currentPartition = partitions[i]; - currentLineStyleProvider = getProviderFor(currentPartition); - currentLineStyleProvider.init(getDocument(), this); - handled = currentLineStyleProvider.prepareRegions(currentPartition, currentPartition.getOffset(), currentPartition.getLength(), fHoldStyleResults); - if (Debug.syntaxHighlighting && !handled) { - System.out.println("Did not handle highlighting in Highlighter inner while"); //$NON-NLS-1$ - } - } - - int resultSize = fHoldStyleResults.size(); - if (resultSize > 0) { - result = (StyleRange[]) fHoldStyleResults.toArray(new StyleRange[fHoldStyleResults.size()]); - } - else { - result = EMPTY_STYLE_RANGE; - } - result = convertReadOnlyRegions(result, start, length); - return result; - } - - public void refreshDisplay() { - if (textWidget != null && !textWidget.isDisposed()) - textWidget.redraw(); - } - - /** - */ - public void refreshDisplay(int start, int length) { - if (textWidget != null && !textWidget.isDisposed()) - textWidget.redrawRange(start, length, true); - } - - public void removeProvider(String partitionType) { - getTableOfProviders().remove(partitionType); - } - - public void setDocument(IStructuredDocument structuredDocument) { - fStructuredDocument = structuredDocument; - } - - public void setDocumentPartitioning(String partitioning) { - if (partitioning != null) { - fPartitioning = partitioning; - } - else { - fPartitioning = IDocumentExtension3.DEFAULT_PARTITIONING; - } - } - - /** - * Uninstalls highlighter support from the text viewer it has previously - * be installed on. - */ - public void uninstall() { - if (textWidget != null && !textWidget.isDisposed()) { - textWidget.removeLineStyleListener(this); - } - textWidget = null; - - Collection providers = getTableOfProviders().values(); - Iterator iterator = providers.iterator(); - while (iterator.hasNext()) { - LineStyleProvider lineStyleProvider = (LineStyleProvider) iterator.next(); - lineStyleProvider.release(); - // this remove probably isn't strictly needed, since - // typically highlighter instance as a whole will go - // away ... but in case that ever changes, this seems like - // a better style. - iterator.remove(); - } - - synchronized (getExtendedProviders()) { - providers = new ArrayList(getExtendedProviders().values()); - getExtendedProviders().clear(); - } - iterator = providers.iterator(); - while (iterator.hasNext()) { - LineStyleProvider lineStyleProvider = (LineStyleProvider) iterator.next(); - if (lineStyleProvider != null) { - lineStyleProvider.release(); - iterator.remove(); - } - } - - IPreferenceStore editorStore = SSEUIPlugin.getDefault().getPreferenceStore(); - editorStore.removePropertyChangeListener(fForegroundScaleListener); - disposeColorTable(); - - // clear out cached variables (d282894) - fSavedOffset = -1; - fSavedLength = -1; - fSavedRanges = null; - } - - /** - * Purely a debugging aide. - */ - private boolean valid(StyleRange[] eventStyles, int startOffset, int lineLength) { - boolean result = false; - if (eventStyles != null) { - if (eventStyles.length > 0) { - StyleRange first = eventStyles[0]; - StyleRange last = eventStyles[eventStyles.length - 1]; - if (startOffset > first.start) { - result = false; - } - else { - int lineEndOffset = startOffset + lineLength; - int lastOffset = last.start + last.length; - if (lastOffset > lineEndOffset) { - result = false; - } - else { - result = true; - } - } - } - else { - // a zero length array is ok - result = true; - } - } - return result; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/provisional/style/IHighlighter.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/provisional/style/IHighlighter.java deleted file mode 100644 index caf37d0b22..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/provisional/style/IHighlighter.java +++ /dev/null @@ -1,34 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ - -package org.eclipse.wst.sse.ui.internal.provisional.style; - -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.swt.custom.LineStyleListener; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument; - -/** - * @author davidw - * - */ -public interface IHighlighter extends LineStyleListener { - void addProvider(String partitionType, LineStyleProvider provider); - - void install(ITextViewer viewer); - - void removeProvider(String partitionType); - - void setDocument(IStructuredDocument structuredDocument); - - void uninstall(); -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/provisional/style/LineStyleProvider.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/provisional/style/LineStyleProvider.java deleted file mode 100644 index ff81827d98..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/provisional/style/LineStyleProvider.java +++ /dev/null @@ -1,59 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.provisional.style; - -import java.util.Collection; - -import org.eclipse.jface.text.ITypedRegion; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument; - -/** - * This interface is not intended to be implemented by clients. Clients - * should instead subclass AbstractLineStyleProvider - * - */ -public interface LineStyleProvider { - - /** - * Initializes this provider for the given Highlighter and document. This - * method will be called at least once before prepareRegions is called. - * - * @param document - * @param highlighter - */ - void init(IStructuredDocument document, Highlighter highlighter); - - /** - * Optionally appends StyleRanges to the styleRanges Collection, in order, - * and only covering the given range within the document. StyleRanges added - * to the collection should not expand outside of the range of the currentRegion - * ITypedRegion. - * - * @param currentRegion - - * the current document partition - * @param start - * @param length - * @param styleRanges - * @return whether this LineStyleProvider handled the request; handling - * includes not adding StyleRanges if that is still the correct - * behavior - */ - boolean prepareRegions(ITypedRegion currentRegion, int start, int length, Collection styleRanges); - - /** - * Instructs this provider to free up any "resources" it might be holding - * on to (such as listening for preference changes). It is only called - * once in the lifetime of this provider. - */ - void release(); -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/provisional/style/LineStyleProviderForNoOp.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/provisional/style/LineStyleProviderForNoOp.java deleted file mode 100644 index 3d609293be..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/provisional/style/LineStyleProviderForNoOp.java +++ /dev/null @@ -1,48 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.provisional.style; - - - -import java.util.Collection; - -import org.eclipse.jface.text.ITypedRegion; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument; - -/** - * This class can be used by default, if no attribute provider is found for a - * certain region type. Its probably an error in a factory somewhere if an - * adapter is not found, but this class allows the logic to proceed basically - * simply providing default colored syntax highlighting. - * - * Not to be subclassed. - */ -final public class LineStyleProviderForNoOp implements LineStyleProvider { - - public void init(IStructuredDocument document, Highlighter highlighter) { - // nothing to do - } - - /** - * @see org.eclipse.wst.sse.ui.internal.provisional.style.AbstractLineStyleProvider#prepareRegions(org.eclipse.jface.text.ITypedRegion, - * int, int, java.util.Collection) - */ - public boolean prepareRegions(ITypedRegion currentRegion, int start, int length, Collection holdResults) { - // add nothing, but say handled. - return true; - } - - public void release() { - // nothing to do - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/provisional/style/ReconcilerHighlighter.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/provisional/style/ReconcilerHighlighter.java deleted file mode 100644 index 1a39d4b7ae..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/provisional/style/ReconcilerHighlighter.java +++ /dev/null @@ -1,157 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.provisional.style; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import org.eclipse.core.runtime.Platform; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument; -import org.eclipse.wst.sse.ui.internal.ExtendedConfigurationBuilder; -import org.eclipse.wst.sse.ui.internal.Logger; - -public class ReconcilerHighlighter { - - private static final String LINE_STYLE_PROVIDER_EXTENDED_ID = Highlighter.LINE_STYLE_PROVIDER_EXTENDED_ID; - - private Map fTableOfProviders = null; - - private Map fExtendedProviders = null; - - private ITextViewer fTextViewer = null; - - private final static boolean _trace = Boolean.valueOf(Platform.getDebugOption("org.eclipse.wst.sse.ui/structuredPresentationReconciler")).booleanValue(); //$NON-NLS-1$ - private final static String TRACE_PREFIX = "StructuredPresentationReconciler: "; //$NON-NLS-1$ - private long time0; - - /** - * instance for older LineStyleProviders loaded by extension point, - * created if needed - */ - private CompatibleHighlighter fCompatibleHighlighter = null; - - public void refreshDisplay() { - if (_trace) { - time0 = System.currentTimeMillis(); - } - if (fTextViewer != null) - fTextViewer.invalidateTextPresentation(); - if (_trace) { - System.out.println(TRACE_PREFIX + "ReconcilerHighlighter refreshDisplay took " + (System.currentTimeMillis() - time0) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ - System.out.flush(); - } - } - - /** - * Registers a given line style provider for a particular partition type. - * If there is already a line style provider registered for this type, the - * new line style provider is registered instead of the old one. - * - * @param partitionType - * the partition type under which to register - * @param the - * line style provider to register, or <code>null</code> to - * remove an existing one - */ - public void addProvider(String partitionType, LineStyleProvider provider) { - getTableOfProviders().put(partitionType, provider); - } - - public void removeProvider(String partitionType) { - getTableOfProviders().remove(partitionType); - } - - public LineStyleProvider getProvider(String partitionType) { - LineStyleProvider result = (LineStyleProvider) getTableOfProviders().get(partitionType); - - // The provider was not within the default set of providers. Use the - // extended configuration - // to look up additional providers - if (result == null) { - // NOT YET FINALIZED - DO NOT CONSIDER AS API - synchronized (getExtendedProviders()) { - if (!getExtendedProviders().containsKey(partitionType)) { - result = (LineStyleProvider) ExtendedConfigurationBuilder.getInstance().getConfiguration(LINE_STYLE_PROVIDER_EXTENDED_ID, partitionType); - getExtendedProviders().put(partitionType, result); - - if (result != null && fTextViewer != null && fTextViewer.getDocument() instanceof IStructuredDocument) { - if (result instanceof AbstractLineStyleProvider) { - ((AbstractLineStyleProvider) result).init((IStructuredDocument) fTextViewer.getDocument(), this); - } - else { - Logger.log(Logger.INFO_DEBUG, "CompatibleHighlighter installing compatibility for " + result.getClass()); //$NON-NLS-1$ - if (fCompatibleHighlighter == null) { - fCompatibleHighlighter = new CompatibleHighlighter(); - fCompatibleHighlighter.install(fTextViewer); - } - result.init((IStructuredDocument) fTextViewer.getDocument(), fCompatibleHighlighter); - } - } - } - else { - result = (LineStyleProvider) getExtendedProviders().get(partitionType); - } - } - } - return result; - } - - private Map getTableOfProviders() { - if (fTableOfProviders == null) { - fTableOfProviders = new HashMap(); - } - return fTableOfProviders; - } - - private Map getExtendedProviders() { - if (fExtendedProviders == null) { - fExtendedProviders = new HashMap(3); - } - return fExtendedProviders; - } - - public void install(ITextViewer textViewer) { - fTextViewer = textViewer; - if (fCompatibleHighlighter != null) { - fCompatibleHighlighter.uninstall(); - fCompatibleHighlighter.install(fTextViewer); - } - refreshDisplay(); - } - - public void uninstall() { - Iterator it = getTableOfProviders().values().iterator(); - - while (it.hasNext()) { - LineStyleProvider provider = (LineStyleProvider) it.next(); - if (provider != null) - provider.release(); - } - - it = getExtendedProviders().values().iterator(); - while (it.hasNext()) { - LineStyleProvider provider = (LineStyleProvider) it.next(); - if (provider != null) - provider.release(); - } - - getTableOfProviders().clear(); - getExtendedProviders().clear(); - fTableOfProviders = null; - if (fCompatibleHighlighter != null) { - fCompatibleHighlighter.uninstall(); - } - fTextViewer = null; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/provisional/style/StructuredPresentationReconciler.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/provisional/style/StructuredPresentationReconciler.java deleted file mode 100644 index 1001ad5b9c..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/provisional/style/StructuredPresentationReconciler.java +++ /dev/null @@ -1,934 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.wst.sse.ui.internal.provisional.style; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.eclipse.core.runtime.Assert; -import org.eclipse.core.runtime.Platform; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.BadPositionCategoryException; -import org.eclipse.jface.text.DefaultPositionUpdater; -import org.eclipse.jface.text.DocumentEvent; -import org.eclipse.jface.text.DocumentPartitioningChangedEvent; -import org.eclipse.jface.text.DocumentRewriteSessionEvent; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IDocumentExtension3; -import org.eclipse.jface.text.IDocumentExtension4; -import org.eclipse.jface.text.IDocumentListener; -import org.eclipse.jface.text.IDocumentPartitioningListener; -import org.eclipse.jface.text.IDocumentPartitioningListenerExtension; -import org.eclipse.jface.text.IDocumentPartitioningListenerExtension2; -import org.eclipse.jface.text.IDocumentRewriteSessionListener; -import org.eclipse.jface.text.IPositionUpdater; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ITextInputListener; -import org.eclipse.jface.text.ITextListener; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.ITextViewerExtension5; -import org.eclipse.jface.text.ITypedRegion; -import org.eclipse.jface.text.Region; -import org.eclipse.jface.text.TextEvent; -import org.eclipse.jface.text.TextPresentation; -import org.eclipse.jface.text.TextUtilities; -import org.eclipse.jface.text.TypedPosition; -import org.eclipse.jface.text.presentation.IPresentationDamager; -import org.eclipse.jface.text.presentation.IPresentationReconciler; -import org.eclipse.jface.text.presentation.IPresentationReconcilerExtension; -import org.eclipse.jface.text.presentation.IPresentationRepairer; -import org.eclipse.swt.custom.StyleRange; -import org.eclipse.wst.sse.core.internal.provisional.events.IStructuredDocumentListener; -import org.eclipse.wst.sse.core.internal.provisional.events.NewDocumentEvent; -import org.eclipse.wst.sse.core.internal.provisional.events.NoChangeEvent; -import org.eclipse.wst.sse.core.internal.provisional.events.RegionChangedEvent; -import org.eclipse.wst.sse.core.internal.provisional.events.RegionsReplacedEvent; -import org.eclipse.wst.sse.core.internal.provisional.events.StructuredDocumentRegionsReplacedEvent; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegionList; -import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegion; -import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegionList; - -public class StructuredPresentationReconciler implements IPresentationReconciler, IPresentationReconcilerExtension { - - /** Prefix of the name of the position category for tracking damage regions. */ - final static String TRACKED_PARTITION= "__reconciler_tracked_partition"; //$NON-NLS-1$ - - private final static boolean _trace = Boolean.valueOf(Platform.getDebugOption("org.eclipse.wst.sse.ui/structuredPresentationReconciler")).booleanValue(); //$NON-NLS-1$ - private final static boolean _traceTime = Boolean.valueOf(Platform.getDebugOption("org.eclipse.wst.sse.ui/structuredPresentationReconciler/time")).booleanValue(); //$NON-NLS-1$ - private static final String TRACE_PREFIX = "StructuredPresentationReconciler: "; - private long time0; - private long time1; - - /** - * Internal listener class. - */ - class InternalListener implements - ITextInputListener, IDocumentListener, ITextListener, IStructuredDocumentListener, - IDocumentPartitioningListener, IDocumentPartitioningListenerExtension, IDocumentPartitioningListenerExtension2, IDocumentRewriteSessionListener { - - /** Set to <code>true</code> if between a document about to be changed and a changed event. */ - private boolean fDocumentChanging= false; - - /** Flag for the document being in a rewrite session */ - private boolean fInRewriteSession = false; - - /** Flag for some kind of changes being applied during a document rewrite session */ - private boolean fHasIncomingChanges = false; - - /** - * The cached redraw state of the text viewer. - * @since 3.0 - */ - private boolean fCachedRedrawState= true; - - public void newModel(NewDocumentEvent structuredDocumentEvent) { - if(fInRewriteSession) { - fHasIncomingChanges = true; - return; - } - if (_trace) { - time1 = System.currentTimeMillis(); - } - int length = structuredDocumentEvent.getLength(); - recordDamage(new Region(0, length), structuredDocumentEvent.getDocument()); - if (_trace) { - System.out.println("\n" + TRACE_PREFIX + "calculated damage for NewDocumentEvent: (length=" + length + ")"); //$NON-NLS-1$ //$NON-NLS-2$ - System.out.flush(); - } - if (_trace && _traceTime) { - System.out.println(TRACE_PREFIX + "calculated damage for NewDocumentEvent in " + (System.currentTimeMillis()-time1) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ - System.out.flush(); - } - } - - public void noChange(NoChangeEvent structuredDocumentEvent) { - if(fInRewriteSession) { - fHasIncomingChanges = true; - return; - } - if (_trace) { - time1 = System.currentTimeMillis(); - } - if (structuredDocumentEvent.reason == NoChangeEvent.NO_CONTENT_CHANGE ) { - IRegion damage = new Region(structuredDocumentEvent.fOffset, structuredDocumentEvent.fLength); - recordDamage(damage, structuredDocumentEvent.fDocument); - } - if (_trace && _traceTime) { - System.out.println("\n" + TRACE_PREFIX + "calculated damage for NoChangeEvent in " + (System.currentTimeMillis()-time1) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ - System.out.flush(); - } - } - - public void nodesReplaced(StructuredDocumentRegionsReplacedEvent structuredDocumentEvent) { - if(fInRewriteSession) { - fHasIncomingChanges = true; - return; - } - if (_trace) { - time1 = System.currentTimeMillis(); - } - IRegion damage; - IStructuredDocumentRegionList newDocumentRegions = structuredDocumentEvent.getNewStructuredDocumentRegions(); - if (newDocumentRegions.getLength() > 0) { - int startOffset = newDocumentRegions.item(0).getStartOffset(); - int length = newDocumentRegions.item(newDocumentRegions.getLength() - 1).getEndOffset() - startOffset; - damage = new Region(startOffset, length); - - } - else { - damage = new Region(structuredDocumentEvent.fOffset, structuredDocumentEvent.getLength()); - } - recordDamage(damage, structuredDocumentEvent.fDocument); - if (_trace) { - System.out.println("\n" + TRACE_PREFIX + "calculated damage for StructuredDocumentRegionsReplacedEvent: [" + damage.getOffset() + ":" + damage.getLength() + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$//$NON-NLS-4$ - System.out.flush(); - } - if (_trace && _traceTime) { - System.out.println(TRACE_PREFIX + "calculated damage for StructuredDocumentRegionsReplacedEvent in " + (System.currentTimeMillis()-time1) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ - System.out.flush(); - } - } - - public void regionChanged(RegionChangedEvent structuredDocumentEvent) { - if(fInRewriteSession) { - fHasIncomingChanges = true; - return; - } - if (_trace) { - time1 = System.currentTimeMillis(); - } - IStructuredDocumentRegion documentRegion = structuredDocumentEvent.getStructuredDocumentRegion(); - ITextRegion changedRegion = structuredDocumentEvent.getRegion(); - int startOffset = documentRegion.getStartOffset(changedRegion); - int length = changedRegion.getLength(); - IRegion damage = new Region(startOffset, length); - - recordDamage(damage, structuredDocumentEvent.fDocument); - if (_trace) { - System.out.println("\n" + TRACE_PREFIX + "calculated damage for RegionChangedEvent: [" + damage.getOffset() + ":" + damage.getLength() + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$//$NON-NLS-4$ - System.out.flush(); - } - if (_trace && _traceTime) { - System.out.println(TRACE_PREFIX + "calculated damage for RegionChangedEvent in " + (System.currentTimeMillis()-time1) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ - System.out.flush(); - } - } - - public void regionsReplaced(RegionsReplacedEvent structuredDocumentEvent) { - if(fInRewriteSession) { - fHasIncomingChanges = true; - return; - } - if (_trace) { - time1 = System.currentTimeMillis(); - } - IRegion damage; - IStructuredDocumentRegion documentRegion = structuredDocumentEvent.getStructuredDocumentRegion(); - ITextRegionList newRegions = structuredDocumentEvent.getNewRegions(); - if (newRegions.size() > 0) { - ITextRegion firstChangedRegion = newRegions.get(0); - ITextRegion lastChangedRegion = newRegions.get(newRegions.size() - 1); - int startOffset = documentRegion.getStartOffset(firstChangedRegion); - int length = documentRegion.getEndOffset(lastChangedRegion) - startOffset; - damage = new Region(startOffset, length); - } - else { - damage = new Region(documentRegion.getStartOffset(), documentRegion.getLength()); - } - recordDamage(damage, structuredDocumentEvent.fDocument); - if (_trace) { - System.out.println("\n" + TRACE_PREFIX + "calculated damage for RegionsReplacedEvent: [" + damage.getOffset() + ":" + damage.getLength() + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$//$NON-NLS-4$ - System.out.flush(); - } - if (_trace && _traceTime) { - System.out.println(TRACE_PREFIX + "calculated damage for RegionsReplacedEvent in " + (System.currentTimeMillis()-time1) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ - System.out.flush(); - } - } - - /* - * @see ITextInputListener#inputDocumentAboutToBeChanged(IDocument, IDocument) - */ - public void inputDocumentAboutToBeChanged(IDocument oldDocument, IDocument newDocument) { - if (oldDocument != null) { - try { - - fViewer.removeTextListener(this); - oldDocument.removeDocumentListener(this); - oldDocument.removeDocumentPartitioningListener(this); - if (oldDocument instanceof IStructuredDocument) { - ((IStructuredDocument) oldDocument).removeDocumentChangedListener(this); - } - - oldDocument.removePositionUpdater(fPositionUpdater); - oldDocument.removePositionCategory(fPositionCategory); - - } catch (BadPositionCategoryException x) { - // should not happened for former input documents; - } - } - } - - /* - * @see ITextInputListener#inputDocumenChanged(IDocument, IDocument) - */ - public void inputDocumentChanged(IDocument oldDocument, IDocument newDocument) { - if (_trace || _traceTime) { - time1 = System.currentTimeMillis(); - } - - fDocumentChanging= false; - fCachedRedrawState= true; - - if (newDocument != null) { - newDocument.addPositionCategory(fPositionCategory); - newDocument.addPositionUpdater(fPositionUpdater); - - if (newDocument instanceof IStructuredDocument) { - newDocument.addDocumentPartitioningListener(this); - newDocument.addDocumentListener(this); - ((IStructuredDocument)newDocument).addDocumentChangedListener(this); - } - fViewer.addTextListener(this); - - if (newDocument instanceof IStructuredDocument) { - setDocumentToDamagers(newDocument); - setDocumentToRepairers(newDocument); - processDamage(new Region(0, newDocument.getLength()), newDocument); - } - } - if (_trace) { - System.out.println(TRACE_PREFIX + "processed damage for inputDocumentChanged in " + (System.currentTimeMillis() - time1) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - - /* - * @see IDocumentPartitioningListener#documentPartitioningChanged(IDocument) - */ - public void documentPartitioningChanged(IDocument document) { - if (_traceTime) { - time0 = System.currentTimeMillis(); - } - if (!fDocumentChanging && fCachedRedrawState) - processDamage(new Region(0, document.getLength()), document); - else - fDocumentPartitioningChanged= true; - if (_trace) { - System.out.println(TRACE_PREFIX + "processed damage for documentPartitioningChanged [full document]"); //$NON-NLS-1$ - } - if (_trace && _traceTime) { - System.out.println(TRACE_PREFIX + "processed damage for documentPartitioningChanged in " + (System.currentTimeMillis() - time0) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - - /* - * @see IDocumentPartitioningListenerExtension#documentPartitioningChanged(IDocument, IRegion) - * @since 2.0 - */ - public void documentPartitioningChanged(IDocument document, IRegion changedRegion) { - if (_traceTime) { - time0 = System.currentTimeMillis(); - } - if (!fDocumentChanging && fCachedRedrawState) { - processDamage(new Region(changedRegion.getOffset(), changedRegion.getLength()), document); - } else { - fDocumentPartitioningChanged= true; - fChangedDocumentPartitions= changedRegion; - } - if (_trace) { - System.out.println(TRACE_PREFIX + "processed damage for documentPartitioningChanged [" + changedRegion.getOffset() + ":" + changedRegion.getLength() + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } - if (_trace && _traceTime) { - System.out.println(TRACE_PREFIX + "processed damage for documentPartitioningChanged in " + (System.currentTimeMillis() - time0) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - - /* - * @see org.eclipse.jface.text.IDocumentPartitioningListenerExtension2#documentPartitioningChanged(org.eclipse.jface.text.DocumentPartitioningChangedEvent) - * @since 3.0 - */ - public void documentPartitioningChanged(DocumentPartitioningChangedEvent event) { - IRegion changedRegion= event.getChangedRegion(getDocumentPartitioning()); - if (changedRegion != null) - documentPartitioningChanged(event.getDocument(), changedRegion); - } - - /* - * @see IDocumentListener#documentAboutToBeChanged(DocumentEvent) - */ - public void documentAboutToBeChanged(DocumentEvent e) { - - fDocumentChanging= true; - if (fCachedRedrawState) { - try { - int offset= e.getOffset() + e.getLength(); - ITypedRegion region= getPartition(e.getDocument(), offset); - fRememberedPosition= new TypedPosition(region); - e.getDocument().addPosition(fPositionCategory, fRememberedPosition); - } catch (BadLocationException x) { - // can not happen - } catch (BadPositionCategoryException x) { - // should not happen on input elements - } - } - } - - /* - * @see IDocumentListener#documentChanged(DocumentEvent) - */ - public void documentChanged(DocumentEvent e) { - if (fCachedRedrawState) { - try { - e.getDocument().removePosition(fPositionCategory, fRememberedPosition); - } catch (BadPositionCategoryException x) { - // can not happen on input documents - } - } - fDocumentChanging= false; - } - - /* - * @see ITextListener#textChanged(TextEvent) - */ - public void textChanged(TextEvent e) { - if(fInRewriteSession) { - fHasIncomingChanges = true; - return; - } - fCachedRedrawState= e.getViewerRedrawState(); - if (!fCachedRedrawState) { - if (_trace) { - System.out.println("\n" + TRACE_PREFIX + "returned early from textChanged(TextEvent)"); //$NON-NLS-1$ //$NON-NLS-2$ - } - return; - } - if (_trace) { - System.out.println("\n" + TRACE_PREFIX + "entering textChanged(TextEvent)"); //$NON-NLS-1$ //$NON-NLS-2$ - time0 = System.currentTimeMillis(); - } - - IRegion damage= null; - IDocument document= null; - - if (e.getDocumentEvent() == null) { - document= fViewer.getDocument(); - if (document != null) { - if (e.getOffset() == 0 && e.getLength() == 0 && e.getText() == null) { - // redraw state change, damage the whole document - damage= new Region(0, document.getLength()); - } else { - IRegion region= widgetRegion2ModelRegion(e); - try { - String text= document.get(region.getOffset(), region.getLength()); - DocumentEvent de= new DocumentEvent(document, region.getOffset(), region.getLength(), text); - damage= getDamage(de, false); - } catch (BadLocationException x) { - /* ignored in platform PresentationReconciler, too */ - } - } - } - } else { - DocumentEvent de= e.getDocumentEvent(); - document= de.getDocument(); - damage= getDamage(de, true); - } - if(_trace && _traceTime) { - System.out.println(TRACE_PREFIX + "calculated simple text damage at " + (System.currentTimeMillis() - time0) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ - System.out.flush(); - } - - boolean damageOverlaps = processRecordedDamages(damage, document); - if(_trace && _traceTime) { - System.out.println(TRACE_PREFIX + "processed recorded structured text damage at " + (System.currentTimeMillis() - time0) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ - } - - if (damage != null && document != null && !damageOverlaps) { - processDamage(damage, document); - if(_trace && _traceTime) { - System.out.println(TRACE_PREFIX + "processed simple text damage at " + (System.currentTimeMillis() - time0) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ - System.out.flush(); - } - } - - fDocumentPartitioningChanged= false; - fChangedDocumentPartitions= null; - if(_trace) { - System.out.println(TRACE_PREFIX + "finished textChanged(TextEvent) in " + (System.currentTimeMillis() - time0) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - - /** - * Translates the given text event into the corresponding range of the viewer's document. - * - * @param e the text event - * @return the widget region corresponding the region of the given event - * @since 2.1 - */ - protected IRegion widgetRegion2ModelRegion(TextEvent e) { - - String text= e.getText(); - int length= text == null ? 0 : text.length(); - - if (fViewer instanceof ITextViewerExtension5) { - ITextViewerExtension5 extension= (ITextViewerExtension5) fViewer; - return extension.widgetRange2ModelRange(new Region(e.getOffset(), length)); - } - - IRegion visible= fViewer.getVisibleRegion(); - IRegion region= new Region(e.getOffset() + visible.getOffset(), length); - return region; - } - - public void documentRewriteSessionChanged(DocumentRewriteSessionEvent event) { - fInRewriteSession = (event != null && event.fChangeType == DocumentRewriteSessionEvent.SESSION_START); - if(!fInRewriteSession && fHasIncomingChanges && event != null) { - if (_trace) - time0 = System.currentTimeMillis(); - processDamage(new Region(0, event.fDocument.getLength()), event.fDocument); - if(_trace && _traceTime) - System.out.println(TRACE_PREFIX + " processed damaged after ending document rewrite session at " + (System.currentTimeMillis() - time0) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ - fHasIncomingChanges = false; - } - } - - } - - private static class RecordedDamage { - IRegion damage; - IDocument document; - RecordedDamage(IRegion damage, IDocument document) { - this.damage = damage; - this.document = document; - } - } - - /** The map of presentation damagers. */ - private Map fDamagers; - /** The map of presentation repairers. */ - private Map fRepairers; - /** The target viewer. */ - private ITextViewer fViewer; - /** The internal listener. */ - private InternalListener fInternalListener= new InternalListener(); - /** The name of the position category to track damage regions. */ - private String fPositionCategory; - /** The position updated for the damage regions' position category. */ - private IPositionUpdater fPositionUpdater; - /** The positions representing the damage regions. */ - private TypedPosition fRememberedPosition; - /** Flag indicating the receipt of a partitioning changed notification. */ - private boolean fDocumentPartitioningChanged= false; - /** The range covering the changed partitioning. */ - private IRegion fChangedDocumentPartitions= null; - - /** - * Because structured document events fire before textChanged(), it's - * possible the widget isn't fully aware of the changes to its contents. - * "Record" the damage to process after textChanged() has been fired. - */ - private List fRecordedDamages = new ArrayList(2); - - /** - * The partitioning used by this presentation reconciler. - * @since 3.0 - */ - private String fPartitioning; - - private IDocument fLastDocument; - - /** - * Creates a new presentation reconciler. There are no damagers or repairers - * registered with this reconciler by default. The default partitioning - * <code>IDocumentExtension3.DEFAULT_PARTITIONING</code> is used. - */ - public StructuredPresentationReconciler() { - super(); - fPartitioning= IDocumentExtension3.DEFAULT_PARTITIONING; - fPositionCategory= TRACKED_PARTITION + hashCode(); - fPositionUpdater= new DefaultPositionUpdater(fPositionCategory); - } - - /** - * Sets the document partitioning for this presentation reconciler. - * - * @param partitioning the document partitioning for this presentation reconciler. - * @since 3.0 - */ - public void setDocumentPartitioning(String partitioning) { - Assert.isNotNull(partitioning); - fPartitioning= partitioning; - } - - /* - * @see org.eclipse.jface.text.presentation.IPresentationReconcilerExtension#geDocumenttPartitioning() - * @since 3.0 - */ - public String getDocumentPartitioning() { - return fPartitioning; - } - - /** - * Registers the given presentation damager for a particular content type. - * If there is already a damager registered for this type, the old damager - * is removed first. - * - * @param damager the presentation damager to register, or <code>null</code> to remove an existing one - * @param contentType the content type under which to register - */ - public void setDamager(IPresentationDamager damager, String contentType) { - - Assert.isNotNull(contentType); - - if (fDamagers == null) - fDamagers= new HashMap(); - - if (damager == null) - fDamagers.remove(contentType); - else - fDamagers.put(contentType, damager); - } - - /** - * Registers the given presentation repairer for a particular content type. - * If there is already a repairer registered for this type, the old repairer - * is removed first. - * - * @param repairer the presentation repairer to register, or <code>null</code> to remove an existing one - * @param contentType the content type under which to register - */ - public void setRepairer(IPresentationRepairer repairer, String contentType) { - - Assert.isNotNull(contentType); - - if (fRepairers == null) - fRepairers= new HashMap(); - - if (repairer == null) - fRepairers.remove(contentType); - else - fRepairers.put(contentType, repairer); - } - - /* - * @see IPresentationReconciler#install(ITextViewer) - */ - public void install(ITextViewer viewer) { - if(_trace) { - time0 = System.currentTimeMillis(); - } - Assert.isNotNull(viewer); - - fViewer= viewer; - fViewer.addTextInputListener(fInternalListener); - - IDocument document= viewer.getDocument(); - if (document != null) { - fInternalListener.inputDocumentChanged(null, document); - if(document instanceof IStructuredDocument) { - ((IStructuredDocument) document).addDocumentChangedListener(fInternalListener); - } - if(document instanceof IDocumentExtension4) { - ((IDocumentExtension4) document).addDocumentRewriteSessionListener(fInternalListener); - } - } - if(_trace) { - System.out.println(TRACE_PREFIX + "installed to text viewer in " + (System.currentTimeMillis() - time0) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - - /* - * @see IPresentationReconciler#uninstall() - */ - public void uninstall() { - if(_trace) { - time0 = System.currentTimeMillis(); - } - fViewer.removeTextInputListener(fInternalListener); - - IDocument document = null; - if(( document = fViewer.getDocument()) instanceof IStructuredDocument) { - ((IStructuredDocument) document).removeDocumentChangedListener(fInternalListener); - } - if(document instanceof IDocumentExtension4) { - ((IDocumentExtension4) document).removeDocumentRewriteSessionListener(fInternalListener); - } - // Ensure we uninstall all listeners - fInternalListener.inputDocumentAboutToBeChanged(fViewer.getDocument(), null); - if(_trace) { - System.out.println(TRACE_PREFIX + "uninstalled from text viewer in " + (System.currentTimeMillis() - time0) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - - /* - * @see IPresentationReconciler#getDamager(String) - */ - public IPresentationDamager getDamager(String contentType) { - - if (fDamagers == null) - return null; - - return (IPresentationDamager) fDamagers.get(contentType); - } - - /* - * @see IPresentationReconciler#getRepairer(String) - */ - public IPresentationRepairer getRepairer(String contentType) { - - if (fRepairers == null) - return null; - - return (IPresentationRepairer) fRepairers.get(contentType); - } - - /** - * Informs all registered damagers about the document on which they will work. - * - * @param document the document on which to work - */ - protected void setDocumentToDamagers(IDocument document) { - if (fDamagers != null) { - Iterator e= fDamagers.values().iterator(); - while (e.hasNext()) { - IPresentationDamager damager= (IPresentationDamager) e.next(); - damager.setDocument(document); - } - } - } - - /** - * Informs all registered repairers about the document on which they will work. - * - * @param document the document on which to work - */ - protected void setDocumentToRepairers(IDocument document) { - if (fRepairers != null) { - Iterator e= fRepairers.values().iterator(); - while (e.hasNext()) { - IPresentationRepairer repairer= (IPresentationRepairer) e.next(); - repairer.setDocument(document); - } - } - } - - /** - * Constructs a "repair description" for the given damage and returns this - * description as a text presentation. For this, it queries the partitioning - * of the damage region and asks the appropriate presentation repairer for - * each partition to construct the "repair description" for this partition. - * - * @param damage the damage to be repaired - * @param document the document whose presentation must be repaired - * @return the presentation repair description as text presentation or - * <code>null</code> if the partitioning could not be computed - */ - protected TextPresentation createPresentation(IRegion damage, IDocument document) { - try { - int validLength = Math.min(damage.getLength(), document.getLength() - damage.getOffset()); - - if (fRepairers == null || fRepairers.isEmpty()) { - TextPresentation presentation= new TextPresentation(damage, 1); - presentation.setDefaultStyleRange(new StyleRange(damage.getOffset(), validLength, null, null)); - return presentation; - } - - TextPresentation presentation= new TextPresentation(damage, 1000); - - ITypedRegion[] partitions= TextUtilities.computePartitioning(document, getDocumentPartitioning(), damage.getOffset(), validLength, false); - for (int i= 0; i < partitions.length; i++) { - ITypedRegion r= partitions[i]; - IPresentationRepairer repairer= getRepairer(r.getType()); - if (repairer != null) - repairer.createPresentation(presentation, r); - } - - return presentation; - - } catch (BadLocationException x) { - /* ignored in platform PresentationReconciler, too */ - } - - return null; - } - - - /** - * Checks for the first and the last affected partition affected by a - * document event and calls their damagers. Invalidates everything from the - * start of the damage for the first partition until the end of the damage - * for the last partition. - * - * @param e the event describing the document change - * @param optimize <code>true</code> if partition changes should be - * considered for optimization - * @return the damaged caused by the change or <code>null</code> if - * computing the partitioning failed - * @since 3.0 - */ - IRegion getDamage(DocumentEvent e, boolean optimize) { - int length= e.getText() == null ? 0 : e.getText().length(); - - if (fDamagers == null || fDamagers.isEmpty()) { - length= Math.max(e.getLength(), length); - length= Math.min(e.getDocument().getLength() - e.getOffset(), length); - return new Region(e.getOffset(), length); - } - - boolean isDeletion= length == 0; - IRegion damage= null; - try { - int offset= e.getOffset(); - if (isDeletion) - offset= Math.max(0, offset - 1); - ITypedRegion partition= getPartition(e.getDocument(), offset); - IPresentationDamager damager= getDamager(partition.getType()); - if (damager == null) - return null; - - IRegion r= damager.getDamageRegion(partition, e, fDocumentPartitioningChanged); - - if (!fDocumentPartitioningChanged && optimize && !isDeletion) { - damage= r; - } else { - - int damageEnd= getDamageEndOffset(e); - - int parititionDamageEnd= -1; - if (fChangedDocumentPartitions != null) - parititionDamageEnd= fChangedDocumentPartitions.getOffset() + fChangedDocumentPartitions.getLength(); - - int end= Math.max(damageEnd, parititionDamageEnd); - - damage= end == -1 ? r : new Region(r.getOffset(), end - r.getOffset()); - } - - } catch (BadLocationException x) { - /* ignored in platform PresentationReconciler, too */ - } - - return damage; - } - - /** - * Returns the end offset of the damage. If a partition has been split by - * the given document event also the second half of the original - * partition must be considered. This is achieved by using the remembered - * partition range. - * - * @param e the event describing the change - * @return the damage end offset (excluding) - * @exception BadLocationException if method accesses invalid offset - */ - int getDamageEndOffset(DocumentEvent e) throws BadLocationException { - - IDocument d= e.getDocument(); - - int length= 0; - if (e.getText() != null) { - length= e.getText().length(); - if (length > 0) - -- length; - } - - ITypedRegion partition= getPartition(d, e.getOffset() + length); - int endOffset= partition.getOffset() + partition.getLength(); - if (endOffset == e.getOffset()) - return -1; - - int end= fRememberedPosition == null ? -1 : fRememberedPosition.getOffset() + fRememberedPosition.getLength(); - if (endOffset < end && end < d.getLength()) - partition= getPartition(d, end); - - //if there is not damager for the partition then use the endOffset of the partition - IPresentationDamager damager= getDamager(partition.getType()); - if (damager != null) { - IRegion r= damager.getDamageRegion(partition, e, fDocumentPartitioningChanged); - endOffset = r.getOffset() + r.getLength(); - } - - return endOffset; - } - - void processRecordedDamages() { - processRecordedDamages(null, null); - } - - boolean processRecordedDamages(IRegion damage, IDocument document) { - RecordedDamage[] recordings = null; - boolean recordingOverlaps = false; - synchronized (fRecordedDamages) { - recordings = (RecordedDamage[]) fRecordedDamages.toArray(new RecordedDamage[fRecordedDamages.size()]); - fRecordedDamages.clear(); - } - for (int i = 0; i < recordings.length; i++) { - if (isOverlappingRegion(damage, recordings[i].damage) && document == recordings[i].document) - recordingOverlaps = true; - processDamage(recordings[i].damage, recordings[i].document); - } - return recordingOverlaps; - } - - private boolean isOverlappingRegion(IRegion base, IRegion damage) { - if(base == null || damage == null) - return false; - - int baseEnd = base.getOffset() + base.getLength(); - int damageEnd = damage.getOffset() + damage.getLength(); - - return damage.getOffset() <= base.getOffset() && (damageEnd >= baseEnd); - } - - /** - * Processes the given damage. - * @param damage the damage to be repaired - * @param document the document whose presentation must be repaired - */ - void processDamage(IRegion damage, IDocument document) { - if (damage != null && damage.getLength() > 0) { - TextPresentation p = createPresentation(damage, document); - if (p != null) { - /** - * 229749 - Read-Only highlighting support missing - * 272981 - Read-only highlighting moved to semantic highlighting - */ - applyTextRegionCollection(p); - } - } - } - - /** - * Processes the given damage. - * @param damage the damage to be repaired - * @param document the document whose presentation must be repaired - */ - void recordDamage(IRegion damage, IDocument document) { - if (damage != null && damage.getLength() > 0) { - synchronized (fRecordedDamages) { - fRecordedDamages.add(new RecordedDamage(damage, document)); - } - } - } - - /** - * Applies the given text presentation to the text viewer the presentation - * reconciler is installed on. - * - * @param presentation the text presentation to be applied to the text viewer - */ - void applyTextRegionCollection(TextPresentation presentation) { - fViewer.changeTextPresentation(presentation, false); - } - - /** - * Returns the partition for the given offset in the given document. - * - * @param document the document - * @param offset the offset - * @return the partition - * @throws BadLocationException if offset is invalid in the given document - * @since 3.0 - */ - ITypedRegion getPartition(IDocument document, int offset) throws BadLocationException { - return TextUtilities.getPartition(document, getDocumentPartitioning(), offset, false); - } - - /** - * Constructs a "repair description" for the given damage and returns this - * description as a text presentation, essentially making - * {@link #createPresentation(IRegion, IDocument)} publicly callable. - * <p> - * NOTE: Should not be used if this reconciler is installed on a viewer. - * This method is considered EXPERIMENTAL and may not be available in - * subsequent versions. - * </p> - * - * @param damage - * the damage to be repaired - * @param document - * the document whose presentation must be repaired - * @return the presentation repair description as text presentation - */ - public TextPresentation createRepairDescription(IRegion damage, IDocument document) { - if (document != fLastDocument) { - setDocumentToDamagers(document); - setDocumentToRepairers(document); - fLastDocument= document; - } - return createPresentation(damage, document); - } - -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/quickoutline/QuickOutlineHandler.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/quickoutline/QuickOutlineHandler.java deleted file mode 100644 index 1fa7e13775..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/quickoutline/QuickOutlineHandler.java +++ /dev/null @@ -1,42 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.quickoutline; - -import org.eclipse.core.commands.AbstractHandler; -import org.eclipse.core.commands.ExecutionEvent; -import org.eclipse.core.commands.ExecutionException; -import org.eclipse.jface.text.information.IInformationPresenter; - -public class QuickOutlineHandler extends AbstractHandler { - - IInformationPresenter fPresenter; - - /* (non-Javadoc) - * @see org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.ExecutionEvent) - */ - public Object execute(ExecutionEvent event) throws ExecutionException { - if (fPresenter != null) - fPresenter.showInformation(); - return null; - } - - public void configure(IInformationPresenter presenter) { - fPresenter = presenter; - } - - public void dispose() { - super.dispose(); - if (fPresenter != null) { - fPresenter.uninstall(); - fPresenter = null; - } - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/quickoutline/QuickOutlinePopupDialog.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/quickoutline/QuickOutlinePopupDialog.java deleted file mode 100644 index f5db0f4da1..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/quickoutline/QuickOutlinePopupDialog.java +++ /dev/null @@ -1,435 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010, 2011 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.quickoutline; - -import org.eclipse.jface.action.IMenuManager; -import org.eclipse.jface.dialogs.Dialog; -import org.eclipse.jface.dialogs.IDialogSettings; -import org.eclipse.jface.dialogs.PopupDialog; -import org.eclipse.jface.text.IInformationControl; -import org.eclipse.jface.text.IInformationControlExtension; -import org.eclipse.jface.text.IInformationControlExtension2; -import org.eclipse.jface.viewers.ILabelProvider; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.viewers.ITreeContentProvider; -import org.eclipse.jface.viewers.StructuredSelection; -import org.eclipse.jface.viewers.TreeViewer; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.DisposeEvent; -import org.eclipse.swt.events.DisposeListener; -import org.eclipse.swt.events.FocusListener; -import org.eclipse.swt.events.KeyEvent; -import org.eclipse.swt.events.KeyListener; -import org.eclipse.swt.events.ModifyEvent; -import org.eclipse.swt.events.ModifyListener; -import org.eclipse.swt.events.MouseAdapter; -import org.eclipse.swt.events.MouseEvent; -import org.eclipse.swt.events.MouseMoveListener; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.events.SelectionListener; -import org.eclipse.swt.graphics.Color; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.graphics.Rectangle; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Item; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.swt.widgets.Text; -import org.eclipse.swt.widgets.Tree; -import org.eclipse.swt.widgets.TreeItem; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.IWorkbench; -import org.eclipse.ui.IWorkbenchPage; -import org.eclipse.ui.IWorkbenchWindow; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.texteditor.ITextEditor; -import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel; -import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion; -import org.eclipse.wst.sse.ui.IContentSelectionProvider; -import org.eclipse.wst.sse.ui.internal.SSEUIPlugin; -import org.eclipse.wst.sse.ui.internal.filter.StringMatcher; -import org.eclipse.wst.sse.ui.quickoutline.AbstractQuickOutlineConfiguration; - -/** - * Popup dialog that contains the filtering input and the outline - * view of the editor's input. - * - * <p> - * Based on {@link org.eclipse.jdt.internal.ui.text.AbstractInformationControl} - * </p> - * - */ -public class QuickOutlinePopupDialog extends PopupDialog implements IInformationControl, IInformationControlExtension, IInformationControlExtension2, DisposeListener { - - /** Section used for storing the dialog's size and position settings */ - private static final String DIALOG_SECTION = "org.eclipse.wst.sse.ui.quick_outline"; //$NON-NLS-1$ - - /** Text field for entering filter patterns */ - private Text fFilterText; - - /** Tree for presenting the information outline */ - private TreeViewer fTreeViewer; - - /** The model to be outlined */ - private IStructuredModel fModel; - - private ILabelProvider fLabelProvider; - private ITreeContentProvider fContentProvider; - - private IContentSelectionProvider fSelectionProvider; - - private StringPatternFilter fFilter; - - public QuickOutlinePopupDialog(Shell parent, int shellStyle, IStructuredModel model, AbstractQuickOutlineConfiguration configuration) { - super(parent, shellStyle, true, true, true, true, true, null, null); - fContentProvider = configuration.getContentProvider(); - fLabelProvider = configuration.getLabelProvider(); - fSelectionProvider = configuration.getContentSelectionProvider(); - fModel = model; - create(); - } - - protected Control createDialogArea(Composite parent) { - createTreeViewer(parent, SWT.H_SCROLL | SWT.V_SCROLL); - addListeners(fTreeViewer.getTree()); - - installFilter(); - return fTreeViewer.getControl(); - } - - protected Control createTitleControl(Composite parent) { - createFilterText(parent); - - return fFilterText; - } - - protected void createTreeViewer(Composite parent, int style) { - Tree tree = new Tree(parent, style); - GridData gd = new GridData(GridData.FILL_BOTH); - gd.heightHint = tree.getItemHeight() * 12; - tree.setLayoutData(gd); - - fTreeViewer = new TreeViewer(tree); - fTreeViewer.setContentProvider(fContentProvider); - fTreeViewer.setLabelProvider(fLabelProvider); - fTreeViewer.setAutoExpandLevel(2); - fTreeViewer.setUseHashlookup(true); - fTreeViewer.setInput(fModel); - } - - protected void createFilterText(Composite parent) { - fFilterText = new Text(parent, SWT.NONE); - Dialog.applyDialogFont(fFilterText); - - GridData data= new GridData(GridData.FILL_HORIZONTAL); - data.horizontalAlignment= GridData.FILL; - data.verticalAlignment= GridData.CENTER; - fFilterText.setLayoutData(data); - fFilterText.addKeyListener(new KeyListener() { - public void keyPressed(KeyEvent e) { - if (e.keyCode == 0x0D) // return - gotoSelectedElement(); - if (e.keyCode == SWT.ARROW_DOWN) - fTreeViewer.getTree().setFocus(); - if (e.keyCode == SWT.ARROW_UP) - fTreeViewer.getTree().setFocus(); - if (e.character == 0x1B) // ESC - dispose(); - } - public void keyReleased(KeyEvent e) { - // do nothing - } - }); - } - - protected void installFilter() { - fFilter = new StringPatternFilter(); - fTreeViewer.addFilter(fFilter); - fFilterText.addModifyListener(new ModifyListener() { - public void modifyText(ModifyEvent e) { - String text = ((Text) e.widget).getText(); - int length = text.length(); - if (length > 0 && text.charAt(length -1 ) != '*') { - text = text + '*'; - } - setMatcherString(text, true); - } - }); - } - - protected void setMatcherString(String pattern, boolean update) { - fFilter.updatePattern(pattern); - if (update) - stringMatcherUpdated(); - } - /** - * The string matcher has been modified. The default implementation - * refreshes the view and selects the first matched element - */ - protected void stringMatcherUpdated() { - // refresh viewer to re-filter - fTreeViewer.getControl().setRedraw(false); - fTreeViewer.refresh(); - fTreeViewer.expandAll(); - selectFirstMatch(); - fTreeViewer.getControl().setRedraw(true); - } - - private void selectFirstMatch() { - TreeItem item = findItem(fTreeViewer.getTree().getItems(), fFilter.getStringMatcher()); - if (item != null) { - fTreeViewer.getTree().setSelection(item); - } - else { - fTreeViewer.setSelection(StructuredSelection.EMPTY); - } - } - - private TreeItem findItem(TreeItem[] items, StringMatcher matcher) { - if (matcher == null) - return items.length > 0 ? items[0] : null; - int length = items.length; - TreeItem result = null; - for (int i = 0; i < length; i++) { - if (matcher.match(items[i].getText())) - return items[i]; - if (items[i].getItemCount() > 0) { - result = findItem(items[i].getItems(), matcher); - if (result != null) - return result; - } - - } - return result; - } - - protected IDialogSettings getDialogSettings() { - IDialogSettings settings= SSEUIPlugin.getDefault().getDialogSettings().getSection(DIALOG_SECTION); - if (settings == null) - settings = SSEUIPlugin.getDefault().getDialogSettings().addNewSection(DIALOG_SECTION); - - return settings; - } - - private void gotoSelectedElement() { - Object element = getSelectedElement(); - dispose(); - ITextEditor editor = getActiveTextEditor(); - if (editor != null) { - editor.selectAndReveal(((IndexedRegion) element).getStartOffset(), ((IndexedRegion) element).getEndOffset() - ((IndexedRegion) element).getStartOffset()); - } - } - - private ITextEditor getActiveTextEditor() { - IWorkbench wb = PlatformUI.getWorkbench(); - ITextEditor editor = null; - if (wb != null) { - IWorkbenchWindow ww = wb.getActiveWorkbenchWindow(); - IWorkbenchPage page = ww.getActivePage(); - if (page != null) { - IEditorPart part = page.getActiveEditor(); - if (part instanceof ITextEditor) - editor = (ITextEditor) part; - else - editor = part != null ? (ITextEditor) part.getAdapter(ITextEditor.class) : null; - } - } - return editor; - } - - private Object getSelectedElement() { - if (fTreeViewer == null) - return null; - - return ((IStructuredSelection) fTreeViewer.getSelection()).getFirstElement(); - } - - private void addListeners(final Tree tree) { - tree.addKeyListener(new KeyListener() { - public void keyPressed(KeyEvent e) { - if (e.character == 0x1B) // ESC - dispose(); - } - public void keyReleased(KeyEvent e) { - // do nothing - } - }); - - tree.addSelectionListener(new SelectionListener() { - public void widgetSelected(SelectionEvent e) { - // do nothing - } - public void widgetDefaultSelected(SelectionEvent e) { - gotoSelectedElement(); - } - }); - - /* Mouse hover */ - tree.addMouseMoveListener(new MouseMoveListener() { - TreeItem fLastItem= null; - public void mouseMove(MouseEvent e) { - if (tree.equals(e.getSource())) { - Object o= tree.getItem(new Point(e.x, e.y)); - if (o instanceof TreeItem) { - Rectangle clientArea = tree.getClientArea(); - if (!o.equals(fLastItem)) { - fLastItem= (TreeItem)o; - tree.setSelection(new TreeItem[] { fLastItem }); - } else if (e.y - clientArea.y < tree.getItemHeight() / 4) { - // Scroll up - Point p= tree.toDisplay(e.x, e.y); - Item item= fTreeViewer.scrollUp(p.x, p.y); - if (item instanceof TreeItem) { - fLastItem= (TreeItem)item; - tree.setSelection(new TreeItem[] { fLastItem }); - } - } else if (clientArea.y + clientArea.height - e.y < tree.getItemHeight() / 4) { - // Scroll down - Point p= tree.toDisplay(e.x, e.y); - Item item= fTreeViewer.scrollDown(p.x, p.y); - if (item instanceof TreeItem) { - fLastItem= (TreeItem)item; - tree.setSelection(new TreeItem[] { fLastItem }); - } - } - } - } - } - }); - - tree.addMouseListener(new MouseAdapter() { - public void mouseUp(MouseEvent e) { - - if (tree.getSelectionCount() < 1) - return; - - if (e.button != 1) - return; - - if (tree.equals(e.getSource())) { - Object o= tree.getItem(new Point(e.x, e.y)); - TreeItem selection= tree.getSelection()[0]; - if (selection.equals(o)) - gotoSelectedElement(); - } - } - }); - } - public void addDisposeListener(DisposeListener listener) { - getShell().addDisposeListener(listener); - } - - public void addFocusListener(FocusListener listener) { - getShell().addFocusListener(listener); - } - - public Point computeSizeHint() { - return getShell().getSize(); - } - - public void dispose() { - close(); - } - - public boolean isFocusControl() { - return getShell().getDisplay().getActiveShell() == getShell(); - } - - public void removeDisposeListener(DisposeListener listener) { - getShell().removeDisposeListener(listener); - } - - public void removeFocusListener(FocusListener listener) { - getShell().removeFocusListener(listener); - } - - public void setBackgroundColor(Color background) { - applyBackgroundColor(background, getContents()); - } - - public void setFocus() { - getShell().forceFocus(); - fFilterText.setFocus(); - } - - public void setForegroundColor(Color foreground) { - applyForegroundColor(foreground, getContents()); - } - - public void setInformation(String information) { - // nothing to do - } - - public void setLocation(Point location) { - /* - * If the location is persisted, it gets managed by PopupDialog - fine. Otherwise, the location is - * computed in Window#getInitialLocation, which will center it in the parent shell / main - * monitor, which is wrong for two reasons: - * - we want to center over the editor / subject control, not the parent shell - * - the center is computed via the initalSize, which may be also wrong since the size may - * have been updated since via min/max sizing of AbstractInformationControlManager. - * In that case, override the location with the one computed by the manager. Note that - * the call to constrainShellSize in PopupDialog.open will still ensure that the shell is - * entirely visible. - */ - if (!getPersistLocation() || getDialogSettings() == null) - getShell().setLocation(location); - } - - public void setSize(int width, int height) { - getShell().setSize(width, height); - } - - public void setSizeConstraints(int maxWidth, int maxHeight) { - } - - public void setVisible(boolean visible) { - if (visible) { - open(); - } else { - saveDialogBounds(getShell()); - getShell().setVisible(false); - } - } - - public boolean hasContents() { - return fTreeViewer != null && fTreeViewer.getInput() != null; - } - - public void setInput(Object input) { - if (!(input instanceof ISelection)) { - fTreeViewer.setSelection(new StructuredSelection(input)); - } - else { - if (fSelectionProvider != null) { - ISelection selection = fSelectionProvider.getSelection(fTreeViewer, (ISelection) input); - fTreeViewer.setSelection(selection); - } - else { - fTreeViewer.setSelection((ISelection) input); - } - } - } - - public void widgetDisposed(DisposeEvent e) { - fTreeViewer = null; - fFilterText = null; - fModel = null; - } - - protected void fillDialogMenu(IMenuManager dialogMenu) { - // Add custom actions - super.fillDialogMenu(dialogMenu); - } - -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/quickoutline/StringPatternFilter.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/quickoutline/StringPatternFilter.java deleted file mode 100644 index fb191eb4bf..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/quickoutline/StringPatternFilter.java +++ /dev/null @@ -1,70 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010, 2011 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.quickoutline; - -import org.eclipse.jface.viewers.ILabelProvider; -import org.eclipse.jface.viewers.ITreeContentProvider; -import org.eclipse.jface.viewers.TreeViewer; -import org.eclipse.jface.viewers.Viewer; -import org.eclipse.jface.viewers.ViewerFilter; -import org.eclipse.osgi.util.TextProcessor; -import org.eclipse.wst.sse.ui.internal.filter.StringMatcher; - -/** - * Default Viewer Filter to be used by the {@link QuickOutlinePopupDialog} - * <p> - * Based on {@link org.eclipse.jdt.internal.ui.text.AbstractInformationControl.NamePatternFilter} - * </p> - */ -public class StringPatternFilter extends ViewerFilter { - - private StringMatcher fStringMatcher; - - /* - * @see org.eclipse.jface.viewers.ViewerFilter#select(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object) - */ - public boolean select(Viewer viewer, Object parentElement, Object element) { - StringMatcher matcher = fStringMatcher; - if (matcher == null || !(viewer instanceof TreeViewer)) - return true; - TreeViewer treeViewer = (TreeViewer) viewer; - - String matchName = ((ILabelProvider) treeViewer.getLabelProvider()).getText(element); - matchName = TextProcessor.deprocess(matchName); - if (matchName != null && matcher.match(matchName)) - return true; - - return hasUnfilteredChild(treeViewer, element); - } - - private boolean hasUnfilteredChild(TreeViewer viewer, Object element) { - Object[] children= ((ITreeContentProvider) viewer.getContentProvider()).getChildren(element); - for (int i= 0; i < children.length; i++) - if (select(viewer, element, children[i])) - return true; - return false; - } - - public void updatePattern(String pattern) { - if (pattern.length() == 0) { - fStringMatcher = null; - } - else { - fStringMatcher = new StringMatcher(pattern, pattern.toLowerCase().equals(pattern), false); - } - - } - - public StringMatcher getStringMatcher() { - return fStringMatcher; - } - -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/AbstractStructuredTextReconcilingStrategy.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/AbstractStructuredTextReconcilingStrategy.java deleted file mode 100644 index d5cc519334..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/AbstractStructuredTextReconcilingStrategy.java +++ /dev/null @@ -1,543 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2006 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.reconcile; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.eclipse.core.resources.IMarker; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.Platform; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.reconciler.DirtyRegion; -import org.eclipse.jface.text.reconciler.IReconcileResult; -import org.eclipse.jface.text.reconciler.IReconcileStep; -import org.eclipse.jface.text.reconciler.IReconcilingStrategy; -import org.eclipse.jface.text.reconciler.IReconcilingStrategyExtension; -import org.eclipse.jface.text.source.IAnnotationModel; -import org.eclipse.jface.text.source.IAnnotationModelExtension; -import org.eclipse.jface.text.source.ISourceViewer; -import org.eclipse.jface.text.source.SourceViewer; -import org.eclipse.wst.sse.ui.internal.IReleasable; -import org.eclipse.wst.sse.ui.internal.ITemporaryAnnotation; -import org.eclipse.wst.sse.ui.internal.Logger; -import org.eclipse.wst.sse.ui.internal.StructuredMarkerAnnotation; - - -/** - * A base ReconcilingStrategy. Subclasses must implement - * createReconcileSteps(). This class should not know about - * IStructuredDocument, only IDocument. - * - * @author pavery - */ -public abstract class AbstractStructuredTextReconcilingStrategy implements IReconcilingStrategy, IReconcilingStrategyExtension, IReleasable { - - /** debug flag */ - protected static final boolean DEBUG; - static { - String value = Platform.getDebugOption("org.eclipse.wst.sse.ui/debug/reconcilerjob"); //$NON-NLS-1$ - DEBUG = value != null && value.equalsIgnoreCase("true"); //$NON-NLS-1$ - } - - // these limits are safetys for "runaway" validation cases - // should be used to safeguard potentially dangerous loops or potentially - // long annotations - // (since the painter seems to affect performance when painting long - // annotations) - public static final int ANNOTATION_LENGTH_LIMIT = 25; - public static final int ELEMENT_ERROR_LIMIT = 25; - - private IDocument fDocument = null; - private IProgressMonitor fProgressMonitor = null; - private ISourceViewer fSourceViewer = null; - - // list of "validator" annotations - // for gray/un-gray capability - private HashSet fMarkerAnnotations = null; - - /** - * Creates a new strategy. The source viewer must be set manually - * after creation before a reconciler using this constructor will work. - */ - public AbstractStructuredTextReconcilingStrategy() { - init(); - } - - /** - * Creates a new strategy. - * - * @param editor - */ - public AbstractStructuredTextReconcilingStrategy(ISourceViewer sourceViewer) { - fSourceViewer = sourceViewer; - init(); - } - - /** - * This is where we add results to the annotationModel, doing any special - * "extra" processing. - */ - protected void addResultToAnnotationModel(IReconcileResult result) { - if (!(result instanceof TemporaryAnnotation)) - return; - // can be null when closing the editor - if (getAnnotationModel() != null) { - TemporaryAnnotation tempAnnotation = (TemporaryAnnotation) result; - - StructuredMarkerAnnotation sma = getCorrespondingMarkerAnnotation(tempAnnotation); - if (sma != null) { - // un-gray out the marker annotation - sma.setGrayed(false); - } - - getAnnotationModel().addAnnotation(tempAnnotation, tempAnnotation.getPosition()); - } - } - - /** - * @param object - * @return if this strategy is responisble for adding this type of key - */ - protected boolean canHandlePartition(String partition) { - // String[] haystack = getPartitionTypes(); - // for (int i = 0; i < haystack.length; i++) { - // if (haystack[i].equals(partition)) - // return true; - // } - // return false; - return false; - } - - // /** - // * @param step - // * @return - // */ - // protected boolean containsStep(IReconcileStep step) { - // if (fFirstStep instanceof StructuredReconcileStep) - // return ((StructuredReconcileStep) fFirstStep).isSiblingStep(step); - // return false; - // } - - /** - * This is where you should create the steps for this strategy - */ - abstract public void createReconcileSteps(); - - /** - * Remove ALL temporary annotations that this strategy can handle. - */ - protected TemporaryAnnotation[] getAllAnnotationsToRemove() { - List removals = new ArrayList(); - IAnnotationModel annotationModel = getAnnotationModel(); - if (annotationModel != null) { - Iterator i = annotationModel.getAnnotationIterator(); - while (i.hasNext()) { - Object obj = i.next(); - if (!(obj instanceof ITemporaryAnnotation)) - continue; - - ITemporaryAnnotation annotation = (ITemporaryAnnotation) obj; - ReconcileAnnotationKey key = (ReconcileAnnotationKey) annotation.getKey(); - // then if this strategy knows how to add/remove this - // partition type - if (canHandlePartition(key.getPartitionType()) /* - * && - * containsStep(key.getStep()) - */) - removals.add(annotation); - } - } - return (TemporaryAnnotation[]) removals.toArray(new TemporaryAnnotation[removals.size()]); - } - - protected IAnnotationModel getAnnotationModel() { - IAnnotationModel model = null; - if (fSourceViewer != null) { - model = fSourceViewer.getAnnotationModel(); - } - return model; - } - - protected TemporaryAnnotation[] getAnnotationsToRemove(DirtyRegion dr, List stepsRun) { - - List remove = new ArrayList(); - IAnnotationModel annotationModel = getAnnotationModel(); - // can be null when closing the editor - if (getAnnotationModel() != null) { - - // clear validator annotations - getMarkerAnnotations().clear(); - - Iterator i = annotationModel.getAnnotationIterator(); - while (i.hasNext()) { - - Object obj = i.next(); - - // check if it's a validator marker annotation - // if it is save it for comparision later (to "gray" icons) - if (obj instanceof StructuredMarkerAnnotation) { - StructuredMarkerAnnotation sma = (StructuredMarkerAnnotation) obj; - - if (sma.getAnnotationType() == TemporaryAnnotation.ANNOT_ERROR || sma.getAnnotationType() == TemporaryAnnotation.ANNOT_WARNING) - fMarkerAnnotations.add(sma); - } - - if (!(obj instanceof TemporaryAnnotation)) - continue; - - TemporaryAnnotation annotation = (TemporaryAnnotation) obj; - ReconcileAnnotationKey key = (ReconcileAnnotationKey) annotation.getKey(); - - // then if this strategy knows how to add/remove this - // partition type - if (canHandlePartition(key.getPartitionType()) && stepsRun.contains(key.getStep())) { - if (key.getScope() == ReconcileAnnotationKey.PARTIAL && annotation.getPosition().overlapsWith(dr.getOffset(), dr.getLength())) { - remove.add(annotation); - } - else if (key.getScope() == ReconcileAnnotationKey.TOTAL) { - remove.add(annotation); - } - } - } - } - return (TemporaryAnnotation[]) remove.toArray(new TemporaryAnnotation[remove.size()]); - } - - - protected abstract boolean containsStep(IReconcileStep step); - - /** - * Gets partition types from all steps in this strategy. - * - * @return parition types from all steps - */ - // public String[] getPartitionTypes() { - // if (fFirstStep instanceof StructuredReconcileStep) - // return ((StructuredReconcileStep) fFirstStep).getPartitionTypes(); - // return new String[0]; - // } - public void init() { - createReconcileSteps(); - } - - /** - * @see org.eclipse.jface.text.reconciler.IReconcilingStrategyExtension#initialReconcile() - */ - public void initialReconcile() { - // do nothing - } - - /** - * @return - */ - protected boolean isCanceled() { - if (DEBUG && (fProgressMonitor != null && fProgressMonitor.isCanceled())) - System.out.println("** STRATEGY CANCELED **:" + this.getClass().getName()); //$NON-NLS-1$ - return fProgressMonitor != null && fProgressMonitor.isCanceled(); - } - - /** - * Process the results from the reconcile steps in this strategy. - * - * @param results - */ - private void process(final IReconcileResult[] results) { - if (DEBUG) - System.out.println("[trace reconciler] > STARTING PROCESS METHOD with (" + results.length + ") results"); //$NON-NLS-1$ //$NON-NLS-2$ - - if (results == null) - return; - - for (int i = 0; i < results.length && i < ELEMENT_ERROR_LIMIT && !isCanceled(); i++) { - - if (isCanceled()) { - if (DEBUG) - System.out.println("[trace reconciler] >** PROCESS (adding) WAS CANCELLED **"); //$NON-NLS-1$ - return; - } - addResultToAnnotationModel(results[i]); - } - - if (DEBUG) { - StringBuffer traceString = new StringBuffer(); - for (int j = 0; j < results.length; j++) - traceString.append("\n (+) :" + results[j] + ":\n"); //$NON-NLS-1$ //$NON-NLS-2$ - System.out.println("[trace reconciler] > PROCESSING (" + results.length + ") results in AbstractStructuredTextReconcilingStrategy " + traceString); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - - /** - * @see org.eclipse.jface.text.reconciler.IReconcilingStrategy#reconcile(org.eclipse.jface.text.reconciler.DirtyRegion, - * org.eclipse.jface.text.IRegion) - */ - public void reconcile(DirtyRegion dirtyRegion, IRegion subRegion) { - // not used - // we only have validator strategy now - - // // external files may be null - // if (isCanceled() || fFirstStep == null) - // return; - // - // TemporaryAnnotation[] annotationsToRemove = new - // TemporaryAnnotation[0]; - // IReconcileResult[] annotationsToAdd = new IReconcileResult[0]; - // StructuredReconcileStep structuredStep = (StructuredReconcileStep) - // fFirstStep; - // - // annotationsToRemove = getAnnotationsToRemove(dirtyRegion); - // annotationsToAdd = structuredStep.reconcile(dirtyRegion, - // subRegion); - // - // smartProcess(annotationsToRemove, annotationsToAdd); - } - - /** - * @param partition - * @see org.eclipse.jface.text.reconciler.IReconcilingStrategy#reconcile(org.eclipse.jface.text.IRegion) - */ - public void reconcile(IRegion partition) { - // not used, we use: - // reconcile(DirtyRegion dirtyRegion, IRegion subRegion) - } - - /** - * Calls release() on all the steps in this strategy. Currently done in - * StructuredRegionProcessor.SourceWidgetDisposeListener#widgetDisposed(...) - */ - public void release() { - // release steps (each step calls release on the next) - // if (fFirstStep != null && fFirstStep instanceof IReleasable) - // ((IReleasable) fFirstStep).release(); - // we don't to null out the steps, in case - // it's reconfigured later - } - - private void removeAnnotations(TemporaryAnnotation[] annotationsToRemove) { - - IAnnotationModel annotationModel = getAnnotationModel(); - // can be null when closing the editor - if (annotationModel != null) { - for (int i = 0; i < annotationsToRemove.length; i++) { - if (isCanceled()) { - if (DEBUG) - System.out.println("[trace reconciler] >** REMOVAL WAS CANCELLED **"); //$NON-NLS-1$ - return; - } - StructuredMarkerAnnotation sma = getCorrespondingMarkerAnnotation(annotationsToRemove[i]); - if (sma != null) { - // gray out the marker annotation - sma.setGrayed(true); - } - // remove the temp one - annotationModel.removeAnnotation(annotationsToRemove[i]); - - } - } - - if (DEBUG) { - StringBuffer traceString = new StringBuffer(); - for (int i = 0; i < annotationsToRemove.length; i++) - traceString.append("\n (-) :" + annotationsToRemove[i] + ":\n"); //$NON-NLS-1$ //$NON-NLS-2$ - System.out.println("[trace reconciler] > REMOVED (" + annotationsToRemove.length + ") annotations in AbstractStructuredTextReconcilingStrategy :" + traceString); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - - private StructuredMarkerAnnotation getCorrespondingMarkerAnnotation(TemporaryAnnotation tempAnnotation) { - - Iterator it = getMarkerAnnotations().iterator(); - while (it.hasNext()) { - StructuredMarkerAnnotation markerAnnotation = (StructuredMarkerAnnotation) it.next(); - String message = ""; //$NON-NLS-1$ - try { - message = (String) markerAnnotation.getMarker().getAttribute(IMarker.MESSAGE); - } - catch (CoreException e) { - if (DEBUG) - Logger.logException(e); - } - // it would be nice to check line number here... - if (message != null && message.equals(tempAnnotation.getText())) - return markerAnnotation; - } - return null; - } - - private void removeAllAnnotations() { - removeAnnotations(getAllAnnotationsToRemove()); - } - - /** - * The user needs to manually set the viewer if the default - * constructor was used. - * - * @param viewer - */ - public void setViewer(SourceViewer viewer) { - fSourceViewer = viewer; - } - - /** - * Set the document for this strategy. - * - * @param document - * @see org.eclipse.jface.text.reconciler.IReconcilingStrategy#setDocument(org.eclipse.jface.text.IDocument) - */ - public void setDocument(IDocument document) { - - // remove all old annotations since it's a new document - removeAllAnnotations(); - - if (document == null) - release(); - - // if (getFirstStep() != null) - // getFirstStep().setInputModel(new DocumentAdapter(document)); - - fDocument = document; - } - - public IDocument getDocument() { - return fDocument; - } - - /** - * @param monitor - * @see org.eclipse.jface.text.reconciler.IReconcilingStrategyExtension#setProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) - */ - public void setProgressMonitor(IProgressMonitor monitor) { - // fProgressMonitor = monitor; - // if (fFirstStep != null) - // fFirstStep.setProgressMonitor(fProgressMonitor); - } - - /** - * Check if the annotation is already there, if it is, no need to remove - * or add again. This will avoid a lot of "flickering" behavior. - * - * @param annotationsToRemove - * @param annotationsToAdd - */ - protected void smartProcess(TemporaryAnnotation[] annotationsToRemove, IReconcileResult[] annotationsToAdd) { -// Comparator comp = getTemporaryAnnotationComparator(); -// List sortedRemovals = Arrays.asList(annotationsToRemove); -// Collections.sort(sortedRemovals, comp); -// -// List sortedAdditions = Arrays.asList(annotationsToAdd); -// Collections.sort(sortedAdditions, comp); -// -// List filteredRemovals = new ArrayList(sortedRemovals); -// List filteredAdditions = new ArrayList(sortedAdditions); -// -// boolean ignore = false; -// int lastFoundAdded = 0; -// for (int i = 0; i < sortedRemovals.size(); i++) { -// TemporaryAnnotation removal = (TemporaryAnnotation) sortedRemovals.get(i); -// for (int j = lastFoundAdded; j < sortedAdditions.size(); j++) { -// TemporaryAnnotation addition = (TemporaryAnnotation) sortedAdditions.get(j); -// // quick position check here -// if (removal.getPosition().equals(addition.getPosition())) { -// lastFoundAdded = j; -// // remove performs TemporaryAnnotation.equals() -// // which checks text as well -// filteredAdditions.remove(addition); -// ignore = true; -// if (DEBUG) -// System.out.println(" ~ smart process ignoring: " + removal.getPosition().getOffset()); //$NON-NLS-1$ -// break; -// } -// } -// if (ignore) { -// filteredRemovals.remove(removal); -// } -// ignore = false; -// } - if (getAnnotationModel() instanceof IAnnotationModelExtension) { -// TemporaryAnnotation[] filteredRemovalArray = (TemporaryAnnotation[]) filteredRemovals.toArray(new TemporaryAnnotation[filteredRemovals.size()]); -// // apply "grey"-ness -// for (int i = 0; i < filteredRemovalArray.length; i++) { -// if (isCanceled()) { -// if (DEBUG) -// System.out.println("[trace reconciler] >** replacing WAS CANCELLED **"); //$NON-NLS-1$ -// return; -// } -// StructuredMarkerAnnotation sma = getCorrespondingMarkerAnnotation(filteredRemovalArray[i]); -// if (sma != null) { -// // gray out the marker annotation -// sma.setGrayed(true); -// } -// } -// Map annotationsToAddMap = new HashMap(); -// for (int i = 0; i < filteredAdditions.size(); i++) { -// TemporaryAnnotation temporaryAnnotation = (TemporaryAnnotation) filteredAdditions.get(i); -// annotationsToAddMap.put(temporaryAnnotation, temporaryAnnotation.getPosition()); -// } -// if (isCanceled()) { -// if (DEBUG) -// System.out.println("[trace reconciler] >** PROCESS (replacing) WAS CANCELLED **"); //$NON-NLS-1$ -// return; -// } -// /* -// * Using the extension means we can't enforce the -// * ELEMENT_ERROR_LIMIT limit. -// */ -// ((IAnnotationModelExtension) getAnnotationModel()).replaceAnnotations(filteredRemovalArray, annotationsToAddMap); - - Map annotationsToAddMap = new HashMap(); - for (int i = 0; i < annotationsToAdd.length; i++) { - TemporaryAnnotation temporaryAnnotation = (TemporaryAnnotation) annotationsToAdd[i]; - annotationsToAddMap.put(temporaryAnnotation, temporaryAnnotation.getPosition()); - } - if (isCanceled()) { - if (DEBUG) - System.out.println("[trace reconciler] >** PROCESS (replacing) WAS CANCELLED **"); //$NON-NLS-1$ - return; - } - ((IAnnotationModelExtension) getAnnotationModel()).replaceAnnotations(annotationsToRemove, annotationsToAddMap); - } - else { -// removeAnnotations((TemporaryAnnotation[]) filteredRemovals.toArray(new TemporaryAnnotation[filteredRemovals.size()])); -// process((IReconcileResult[]) filteredAdditions.toArray(new IReconcileResult[filteredAdditions.size()])); - removeAnnotations(annotationsToRemove); - process(annotationsToAdd); - } - } - -// private Comparator getTemporaryAnnotationComparator() { -// if (fComparator == null) { -// fComparator = new Comparator() { -// public int compare(Object arg0, Object arg1) { -// TemporaryAnnotation ta1 = (TemporaryAnnotation) arg0; -// TemporaryAnnotation ta2 = (TemporaryAnnotation) arg1; -// int result = ta1.getPosition().getOffset() - ta2.getPosition().getOffset(); -// if(result != 0) -// return result; -// return Collator.getInstance().compare(ta1.getText(), ta2.getText()); -// } -// }; -// } -// return fComparator; -// } - - public HashSet getMarkerAnnotations() { - if (fMarkerAnnotations == null) - fMarkerAnnotations = new HashSet(); - return fMarkerAnnotations; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/DirtyRegionProcessor.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/DirtyRegionProcessor.java deleted file mode 100644 index 2a1cf02051..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/DirtyRegionProcessor.java +++ /dev/null @@ -1,847 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2011 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.reconcile; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.eclipse.core.runtime.Platform; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.DocumentEvent; -import org.eclipse.jface.text.DocumentRewriteSessionEvent; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IDocumentExtension3; -import org.eclipse.jface.text.IDocumentExtension4; -import org.eclipse.jface.text.IDocumentListener; -import org.eclipse.jface.text.IDocumentRewriteSessionListener; -import org.eclipse.jface.text.ITextInputListener; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.ITypedRegion; -import org.eclipse.jface.text.TextUtilities; -import org.eclipse.jface.text.reconciler.DirtyRegion; -import org.eclipse.jface.text.reconciler.IReconciler; -import org.eclipse.jface.text.reconciler.IReconcilerExtension; -import org.eclipse.jface.text.reconciler.IReconcilingStrategy; -import org.eclipse.wst.sse.ui.internal.Logger; - -/** - * This Job holds a queue of updates from the editor (DirtyRegions) to - * process. When a new request comes in, the current run is canceled, the new - * request is added to the queue, then the job is re-scheduled. - * - * @author pavery - */ -public class DirtyRegionProcessor implements IReconciler, IReconcilerExtension, IConfigurableReconciler { - class DocumentListener implements IDocumentListener { - public void documentAboutToBeChanged(DocumentEvent event) { - /* - * if in rewrite session and already going to reprocess entire - * document after rewrite session, do nothing - */ - if (isInRewriteSession() && fReprocessAfterRewrite) - return; - // save partition type (to see if it changes in documentChanged()) - fLastPartitions = getPartitionRegions(event.getOffset(), event.getLength()); - } - - public void documentChanged(DocumentEvent event) { - /* - * if in rewrite session and already going to reprocess entire - * document after rewrite session, do nothing - */ - if (isInRewriteSession() && fReprocessAfterRewrite) - return; - - if (partitionsChanged(event)) { - // pa_TODO - // this is a simple way to ensure old - // annotations are removed when partition changes - - // it might be a performance hit though - setEntireDocumentDirty(getDocument()); - } - else { - /* - * Note that creating DirtyRegions *now* means that the wrong - * text may be included - */ - DirtyRegion dr = null; - if (event.getLength() == 0) { - /* - * It's an insert-- we use text length though so that the - * new region gets validated... - */ - dr = createDirtyRegion(event.getOffset(), 0, DirtyRegion.INSERT); - } - else { - if ("".equals(event.getText())) { //$NON-NLS-1$ - // it's a delete - dr = createDirtyRegion(event.getOffset(), event.getLength(), DirtyRegion.REMOVE); - } - else { - // it's a replace - dr = createDirtyRegion(event.getOffset(), event.getLength(), DirtyRegion.INSERT); - } - } - if (isInRewriteSession()) { - /* - * while in rewrite session, found a dirty region, so flag - * that entire document needs to be reprocesed after - * rewrite session - */ - if (!fReprocessAfterRewrite && (dr != null)) { - fReprocessAfterRewrite = true; - } - } - else { - processDirtyRegion(dr); - } - } - } - - /** - * Checks previous partitions from the span of the event w/ the new - * partitions from the span of the event. If partitions changed, - * return true, else return false - * - * @param event - * @return - */ - private boolean partitionsChanged(DocumentEvent event) { - boolean changed = false; - int length = event.getLength(); - - if (event.getLength() == 0 && event.getText().length() > 0) { - // it's an insert, we want partitions of the new text - length = event.getText().length(); - } - - ITypedRegion[] newPartitions = getPartitionRegions(event.getOffset(), length); - if (fLastPartitions != null) { - if (fLastPartitions.length != newPartitions.length) { - changed = true; - } - else { - for (int i = 0; i < fLastPartitions.length; i++) { - if (!fLastPartitions[i].getType().equals(newPartitions[i].getType())) { - changed = true; - break; - } - } - } - } - return changed; - } - - - } - - /** - * Reconciles the entire document when the document in the viewer is - * changed. This happens when the document is initially opened, as well as - * after a save-as. - * - * Also see processPostModelEvent(...) for similar behavior when document - * for the model is changed. - */ - class TextInputListener implements ITextInputListener { - public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) { - // do nothing - } - - public void inputDocumentChanged(IDocument oldInput, IDocument newInput) { - handleInputDocumentChanged(oldInput, newInput); - - startReconciling(); - } - } - - class DocumentRewriteSessionListener implements IDocumentRewriteSessionListener { - long time0 = 0; - - public void documentRewriteSessionChanged(DocumentRewriteSessionEvent event) { - boolean oldValue = fInRewriteSession; - fInRewriteSession = event != null && event.getChangeType().equals(DocumentRewriteSessionEvent.SESSION_START); - - if (event.getChangeType().equals(DocumentRewriteSessionEvent.SESSION_START)) { - if (DEBUG) { - time0 = System.currentTimeMillis(); - } - // bug 235446 - source validation annotations lost after rewrite session - if (!getDirtyRegionQueue().isEmpty()) { - flushDirtyRegionQueue(); - fReprocessAfterRewrite = true; - } else { - fReprocessAfterRewrite = false; - } - } - else if (event.getChangeType().equals(DocumentRewriteSessionEvent.SESSION_STOP)) { - if (fInRewriteSession ^ oldValue && fDocument != null) { - if (DEBUG) { - Logger.log(Logger.INFO, "Rewrite session lasted " + (System.currentTimeMillis() - time0) + "ms"); - time0 = System.currentTimeMillis(); - } - if (fReprocessAfterRewrite) { - DirtyRegion entireDocument = createDirtyRegion(0, fDocument.getLength(), DirtyRegion.INSERT); - processDirtyRegion(entireDocument); - } - if (DEBUG) { - Logger.log(Logger.INFO, "Full document reprocess took " + (System.currentTimeMillis() - time0) + "ms"); - } - fReprocessAfterRewrite = false; - } - } - } - } - - /** debug flag */ - protected static final boolean DEBUG; - private static final long UPDATE_DELAY = 500; - - static { - String value = Platform.getDebugOption("org.eclipse.wst.sse.ui/debug/reconcilerjob"); //$NON-NLS-1$ - DEBUG = value != null && value.equalsIgnoreCase("true"); //$NON-NLS-1$ - } - - private long fDelay; - - - /** local queue of dirty regions (created here) to be reconciled */ - private List fDirtyRegionQueue = Collections.synchronizedList(new ArrayList()); - - /** document that this reconciler works on */ - private IDocument fDocument = null; - - private IDocumentListener fDocumentListener = new DocumentListener(); - private IDocumentRewriteSessionListener fDocumentRewriteSessionListener = new DocumentRewriteSessionListener(); - - /** - * set true after first install to prevent duplicate work done in the - * install method (since install gets called multiple times) - */ - private boolean fIsInstalled = false; - - /** - * so we can tell if a partition changed after the last edit - */ - ITypedRegion[] fLastPartitions; - - List fNonIncrementalStrategiesAlreadyProcessed = new ArrayList(1); - - /** - * The partitioning this reconciler uses. - */ - private String fPartitioning; - - Map fReconcilingStrategies = null; - - /** for initial reconcile when document is opened */ - private TextInputListener fTextInputListener = null; - /** the text viewer */ - private ITextViewer fViewer; - boolean fInRewriteSession = false; - /** - * true if entire document needs to be reprocessed after rewrite session - */ - boolean fReprocessAfterRewrite = false; - - /** The job should be reset because of document changes */ - private boolean fReset = false; - private boolean fIsCanceled = false; - private boolean fHasReconciled = false; - private Object LOCK = new Object(); - - private BackgroundThread fThread; - - /** - * Creates a new StructuredRegionProcessor - */ - public DirtyRegionProcessor() { - // init reconciler stuff - setDelay(UPDATE_DELAY); - fReconcilingStrategies = new HashMap(); - } - - /** - * Adds the given resource to the set of resources that need refreshing. - * Synchronized in order to protect the collection during add. - * - * @param resource - */ - private synchronized void addRequest(DirtyRegion newDirtyRegion) { - // NOTE: This method is called a lot so make sure it's fast - List dirtyRegionQueue = getDirtyRegionQueue(); - synchronized (dirtyRegionQueue) { - for (Iterator it = dirtyRegionQueue.iterator(); it.hasNext();) { - // go through list of existing dirty regions and check if any - // dirty regions need to be discarded - DirtyRegion currentExisting = (DirtyRegion) it.next(); - DirtyRegion outer = getOuterRegion(currentExisting, newDirtyRegion); - // if we already have a request which contains the new request, - // discard the new request - if (outer == currentExisting) - return; - // if new request contains any existing requests, - // remove those - if (outer == newDirtyRegion) - it.remove(); - } - dirtyRegionQueue.add(newDirtyRegion); - } - } - - /** - * Notifies subclasses that processing of multiple dirty regions has begun - */ - protected void beginProcessing() { - // do nothing by default - } - - /** - * @param dirtyRegion - * @return - */ - protected ITypedRegion[] computePartitioning(DirtyRegion dirtyRegion) { - int drOffset = dirtyRegion.getOffset(); - int drLength = dirtyRegion.getLength(); - - return computePartitioning(drOffset, drLength); - } - - protected ITypedRegion[] computePartitioning(int drOffset, int drLength) { - ITypedRegion[] tr = new ITypedRegion[0]; - IDocument doc = getDocument(); - if (doc != null){ - int docLength = doc.getLength(); - - if (drOffset > docLength) { - drOffset = docLength; - drLength = 0; - } - else if (drOffset + drLength > docLength) { - drLength = docLength - drOffset; - } - - try { - // dirty region may span multiple partitions - tr = TextUtilities.computePartitioning(doc, getDocumentPartitioning(), drOffset, drLength, true); - } - catch (BadLocationException e) { - String info = "dr: [" + drOffset + ":" + drLength + "] doc: [" + docLength + "] "; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ - Logger.logException(info, e); - tr = new ITypedRegion[0]; - } - } - return tr; - } - - /** - * Used to determine if one dirty region contains the other and if so, - * which is the one that contains it. - * - * @param root - * @param possible - * @return the outer dirty region if it contains the other dirty region, - * null otherwise - */ - protected DirtyRegion getOuterRegion(DirtyRegion root, DirtyRegion possible) { - DirtyRegion outer = null; - if (isContained(root, possible)) - outer = root; - else if (isContained(possible, root)) - outer = possible; - return outer; - } - - /** - * Used to determine of a "possible" dirty region can be discarded in - * favor of using just the "root" dirty region. - * - * @return if the root dirty region contains possible, return true, - * otherwise return false - */ - private boolean isContained(DirtyRegion root, DirtyRegion possible) { - int rootStart = root.getOffset(); - int rootEnd = rootStart + root.getLength(); - int possStart = possible.getOffset(); - int possEnd = possStart + possible.getLength(); - if (rootStart <= possStart && rootEnd >= possEnd) - return true; - return false; - } - - protected DirtyRegion createDirtyRegion(int offset, int length, String type) { - DirtyRegion durty = null; - IDocument doc = getDocument(); - - if (doc != null) { - // safety for BLE - int docLen = doc.getLength(); - if (offset > docLen) { - offset = docLen; - length = 0; - } - else if (offset + length >= docLen) - length = docLen - offset; - try { - durty = new DirtyRegion(offset, length, type, doc.get(offset, length)); - } - catch (BadLocationException e) { - String info = "dr: [" + offset + ":" + length + "] doc: [" + docLen + "] "; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ - Logger.logException(info, e); - } - } - return durty; - } - - protected DirtyRegion createDirtyRegion(ITypedRegion tr, String type) { - return createDirtyRegion(tr.getOffset(), tr.getLength(), type); - } - - protected void flushDirtyRegionQueue() { - synchronized (fDirtyRegionQueue) { - fDirtyRegionQueue.clear(); - } - } - - /** - * Notifies subclasses that processing of multiple dirty regions has - * ended, for now - */ - protected void endProcessing() { - // do nothing by default - } - - /** - * Delay between processing of DirtyRegions. - * - * @return - */ - long getDelay() { - return fDelay; - } - - List getDirtyRegionQueue() { - return fDirtyRegionQueue; - } - - /** - * The IDocument on which this reconciler operates - * - * @return - */ - protected IDocument getDocument() { - return fDocument; - } - - public String getDocumentPartitioning() { - if (fPartitioning == null) - return IDocumentExtension3.DEFAULT_PARTITIONING; - return fPartitioning; - } - - protected String[] getPartitions(int drOffset, int drLength) { - - ITypedRegion[] regions = new ITypedRegion[0]; - int docLength = getDocument().getLength(); - - if (drOffset > docLength) { - drOffset = docLength; - drLength = 0; - } - else if (drOffset + drLength > docLength) { - drLength = docLength - drOffset; - } - - try { - regions = TextUtilities.computePartitioning(getDocument(), getDocumentPartitioning(), drOffset, drLength, true); - } - catch (BadLocationException e) { - Logger.logException(e); - regions = new ITypedRegion[0]; - } - String[] partitions = new String[regions.length]; - for (int i = 0; i < regions.length; i++) - partitions[i] = regions[i].getType(); - return partitions; - } - - ITypedRegion[] getPartitionRegions(int drOffset, int drLength) { - ITypedRegion[] regions = new ITypedRegion[0]; - int docLength = getDocument().getLength(); - - if (drOffset > docLength) { - drOffset = docLength; - drLength = 0; - } - else if (drOffset + drLength > docLength) { - drLength = docLength - drOffset; - } - - try { - regions = TextUtilities.computePartitioning(getDocument(), getDocumentPartitioning(), drOffset, drLength, true); - } - catch (BadLocationException e) { - Logger.logException(e); - regions = new ITypedRegion[0]; - } - return regions; - } - - - /** - * Returns the reconciling strategy registered with the reconciler for the - * specified partition type. - * - * @param partitionType - * the partition type for which to determine the reconciling - * strategy - * - * @return the reconciling strategy registered for the given partition - * type, or <code>null</code> if there is no such strategy - * - * @see org.eclipse.jface.text.reconciler.IReconciler#getReconcilingStrategy(java.lang.String) - */ - public IReconcilingStrategy getReconcilingStrategy(String partitionType) { - if (partitionType == null) - return null; - return (IReconcilingStrategy) fReconcilingStrategies.get(partitionType); - } - - /** - * This method also synchronized because it accesses the fRequests queue - * - * @return an array of the currently requested Nodes to refresh - */ - private synchronized DirtyRegion[] getRequests() { - synchronized (fDirtyRegionQueue) { - DirtyRegion[] toRefresh = (DirtyRegion[]) fDirtyRegionQueue.toArray(new DirtyRegion[fDirtyRegionQueue.size()]); - flushDirtyRegionQueue(); - return toRefresh; - } - } - - /** - * Returns the text viewer this reconciler is installed on. - * - * @return the text viewer this reconciler is installed on - */ - protected ITextViewer getTextViewer() { - return fViewer; - } - - /** - * - * @param oldInput - * @param newInput - */ - void handleInputDocumentChanged(IDocument oldInput, IDocument newInput) { - // don't bother if reconciler not installed - if (isInstalled()) { - setDocument(newInput); - } - } - - /** - * @see org.eclipse.jface.text.reconciler.IReconciler#install(ITextViewer) - */ - public void install(ITextViewer textViewer) { - // we might be called multiple times with the same viewe.r, - // maybe after being uninstalled as well, so track separately - if (!isInstalled()) { - fViewer = textViewer; - fTextInputListener = new TextInputListener(); - textViewer.addTextInputListener(fTextInputListener); - setInstalled(true); - } - synchronized (this) { - if (fThread == null) - fThread = new BackgroundThread(getClass().getName()); - } - } - - /** - * The viewer has been set on this Reconciler. - * - * @return true if the viewer has been set on this Reconciler, false - * otherwise. - */ - public boolean isInstalled() { - return fIsInstalled; - } - - boolean isInRewriteSession() { - return fInRewriteSession; - } - - /** - * Subclasses should implement for specific handling of dirty regions. The - * method is invoked for each dirty region in the Job's queue. - * - * @param dirtyRegion - */ - protected void process(DirtyRegion dirtyRegion) { - if (!isInstalled() || isInRewriteSession() || dirtyRegion == null || getDocument() == null || fIsCanceled) { - return; - } - /* - * Break the dirty region into a sequence of partitions and find the - * corresponding strategy to reconcile those partitions. If a strategy - * implements INonIncrementalReconcilingStrategy, only call it once - * regardless of the number and types of partitions. - */ - ITypedRegion[] partitions = computePartitioning(dirtyRegion); - for (int i = 0; i < partitions.length && !fIsCanceled; i++) { - IReconcilingStrategy strategy = getReconcilingStrategy(partitions[i].getType()); - if (strategy != null) { - strategy.reconcile(partitions[i]); - } - } - } - - /** - * Invoke dirty region processing. - * - * @param node - */ - public final void processDirtyRegion(DirtyRegion dr) { - if (dr == null || !isInstalled()) - return; - - addRequest(dr); - synchronized (LOCK) { - fReset = true; - } - - if (DEBUG) { - System.out.println("added request for: [" + dr.getText() + "]"); //$NON-NLS-1$ //$NON-NLS-2$ - System.out.println("queue size is now: " + getDirtyRegionQueue().size()); //$NON-NLS-1$ - } - } - - /** - * Based on {@link org.eclipse.jface.text.reconciler.AbstractReconciler.BackgroundThread} - * - */ - class BackgroundThread extends Thread { - - public BackgroundThread(String name) { - super(name); - setPriority(Thread.MIN_PRIORITY); - setDaemon(true); - } - - public void cancel() { - synchronized (fDirtyRegionQueue) { - fDirtyRegionQueue.notifyAll(); - } - } - - public void run() { - synchronized (fDirtyRegionQueue) { - try { - fDirtyRegionQueue.wait(getDelay()); - } catch (InterruptedException e) {} - } - - if (fIsCanceled) - return; - - if (!fHasReconciled) { - initialReconcile(); - fHasReconciled = true; - } - - while (!fIsCanceled) { - synchronized (fDirtyRegionQueue) { - try { - fDirtyRegionQueue.wait(getDelay()); - } catch (InterruptedException e) {} - } - - if (fIsCanceled) - return; - - synchronized (LOCK) { - if (fReset) { - fReset = false; - continue; - } - } - - boolean processed = false; - try { - DirtyRegion[] toRefresh = getRequests(); - if (toRefresh.length > 0) { - processed = true; - beginProcessing(); - } - - for (int i = 0; i < toRefresh.length && fDocument != null; i++) { - if (fIsCanceled) - return; - process(toRefresh[i]); - } - } - finally { - if (processed) - endProcessing(); - } - - } - } - } - - public void setDelay(long delay) { - fDelay = delay; - } - - public void setDocument(IDocument doc) { - if (fDocument != null) { - // unhook old document listener - fDocument.removeDocumentListener(fDocumentListener); - if (fDocument instanceof IDocumentExtension4) { - ((IDocumentExtension4) fDocument).removeDocumentRewriteSessionListener(fDocumentRewriteSessionListener); - } - } - - fDocument = doc; - - if (fDocument != null) { - if (fDocument instanceof IDocumentExtension4) { - ((IDocumentExtension4) fDocument).addDocumentRewriteSessionListener(fDocumentRewriteSessionListener); - } - // hook up new document listener - fDocument.addDocumentListener(fDocumentListener); - - setEntireDocumentDirty(doc); - } - } - - /** - * This method is called before the initial reconciling of the document. - */ - protected void initialReconcile() { - } - - /** - * Sets the document partitioning for this reconciler. - * - * @param partitioning - * the document partitioning for this reconciler - */ - public void setDocumentPartitioning(String partitioning) { - fPartitioning = partitioning; - } - - /** - * Forces reconciling of the entire document. - */ - protected void forceReconciling() { - if (!fHasReconciled) - return; - - setEntireDocumentDirty(getDocument()); - } - - /** - * Basically means process the entire document. - * - * @param document - */ - protected void setEntireDocumentDirty(IDocument document) { - - // make the entire document dirty - // this also happens on a "save as" - if (document != null && isInstalled()) { - - // since we're marking the entire doc dirty - flushDirtyRegionQueue(); - - /** - * https://bugs.eclipse.org/bugs/show_bug.cgi?id=199053 - * - * Process the strategies for the last known-good partitions to - * ensure all problem annotations are cleared if needed. - */ - if (fLastPartitions != null && document.getLength() == 0) { - for (int i = 0; i < fLastPartitions.length; i++) { - IReconcilingStrategy strategy = getReconcilingStrategy(fLastPartitions[i].getType()); - if (strategy != null) { - strategy.reconcile(fLastPartitions[i]); - } - } - } - else { - DirtyRegion entireDocument = createDirtyRegion(0, document.getLength(), DirtyRegion.INSERT); - processDirtyRegion(entireDocument); - } - } - } - - /** - * @param isInstalled - * The isInstalled to set. - */ - void setInstalled(boolean isInstalled) { - fIsInstalled = isInstalled; - } - - public void setReconcilingStrategy(String partitionType, IReconcilingStrategy strategy) { - if (partitionType == null) { - throw new IllegalArgumentException(); - } - - if (strategy == null) { - fReconcilingStrategies.remove(partitionType); - } - else { - fReconcilingStrategies.put(partitionType, strategy); - } - } - - /** - * @see org.eclipse.jface.text.reconciler.IReconciler#uninstall() - */ - public void uninstall() { - if (isInstalled()) { - // removes widget listener - getTextViewer().removeTextInputListener(fTextInputListener); - setInstalled(false); - fIsCanceled = true; - synchronized (this) { - BackgroundThread bt = fThread; - fThread= null; - bt.cancel(); - } - } - synchronized (fDirtyRegionQueue) { - fDirtyRegionQueue.clear(); - } - setDocument(null); - } - - protected synchronized void startReconciling() { - if (fThread == null) - return; - if (!fThread.isAlive()) { - try { - fThread.start(); - } catch (IllegalThreadStateException e) { } - } - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/DocumentAdapter.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/DocumentAdapter.java deleted file mode 100644 index d2557462a1..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/DocumentAdapter.java +++ /dev/null @@ -1,43 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.reconcile; - -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.reconciler.IReconcilableModel; - -/** - * Adapts an <code>IDocument</code> to a <code>IReconcilableModel</code>. - * - */ -public class DocumentAdapter implements IReconcilableModel { - - private IDocument fDocument; - - /** - * Creates a text model adapter for the given document. - * - * @param document - */ - public DocumentAdapter(IDocument document) { - fDocument = document; - } - - /** - * Returns this model's document. - * - * @return the model's input document - */ - public IDocument getDocument() { - return fDocument; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/DocumentRegionProcessor.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/DocumentRegionProcessor.java deleted file mode 100644 index 5f4bd9f30f..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/DocumentRegionProcessor.java +++ /dev/null @@ -1,442 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2006, 2011 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * David Carver (Intalio) - bug 307323 - remove extraneous call to spell check strategy - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.reconcile; - -import java.io.IOException; -import java.io.StringReader; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.content.IContentDescription; -import org.eclipse.core.runtime.content.IContentType; -import org.eclipse.core.runtime.content.IContentTypeManager; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.ITypedRegion; -import org.eclipse.jface.text.Region; -import org.eclipse.jface.text.reconciler.DirtyRegion; -import org.eclipse.jface.text.reconciler.IReconcilingStrategy; -import org.eclipse.jface.text.source.IAnnotationModel; -import org.eclipse.jface.text.source.ISourceViewer; -import org.eclipse.jface.text.source.projection.ProjectionViewer; -import org.eclipse.wst.sse.core.internal.ltk.parser.RegionParser; -import org.eclipse.wst.sse.core.internal.ltk.parser.StructuredDocumentRegionHandler; -import org.eclipse.wst.sse.core.internal.ltk.parser.StructuredDocumentRegionParser; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion; -import org.eclipse.wst.sse.ui.internal.ExtendedConfigurationBuilder; -import org.eclipse.wst.sse.ui.internal.IReleasable; -import org.eclipse.wst.sse.ui.internal.Logger; -import org.eclipse.wst.sse.ui.internal.SSEUIPlugin; -import org.eclipse.wst.sse.ui.internal.projection.AbstractStructuredFoldingStrategy; -import org.eclipse.wst.sse.ui.internal.provisional.preferences.CommonEditorPreferenceNames; -import org.eclipse.wst.sse.ui.internal.reconcile.validator.ValidatorBuilder; -import org.eclipse.wst.sse.ui.internal.reconcile.validator.ValidatorMetaData; -import org.eclipse.wst.sse.ui.internal.reconcile.validator.ValidatorStrategy; -import org.eclipse.wst.sse.ui.internal.spelling.SpellcheckStrategy; -import org.eclipse.wst.sse.ui.reconcile.ISourceReconcilingListener; - -/** - * Adds to DirtyRegionProcessor Job: - IDocumentListener - ValidatorStrategy - - * Text viewer(dispose, input changed) listeners. - default, spelling, and - * validator strategies - DirtyRegion processing logic. - */ -public class DocumentRegionProcessor extends DirtyRegionProcessor { - private static final boolean DEBUG_VALIDATORS = Boolean.TRUE.toString().equalsIgnoreCase(Platform.getDebugOption("org.eclipse.wst.sse.ui/debug/reconcilerValidators")); //$NON-NLS-1$ - - /** - * Marks the entire document dirty when a parser-level change is notified - * that might affect the entire document - */ - class DirtyRegionParseHandler implements StructuredDocumentRegionHandler { - public void nodeParsed(IStructuredDocumentRegion aCoreStructuredDocumentRegion) { - } - - public void resetNodes() { - setEntireDocumentDirty(getDocument()); - } - } - private DirtyRegionParseHandler fResetHandler = new DirtyRegionParseHandler(); - /** - * A strategy to use the defined default Spelling service. - */ - private IReconcilingStrategy fSpellcheckStrategy; - - /** - * The strategy that runs validators contributed via - * <code>org.eclipse.wst.sse.ui.extensions.sourcevalidation</code> - * extension point - */ - private ValidatorStrategy fValidatorStrategy; - - private ISourceReconcilingListener[] fReconcileListeners = new ISourceReconcilingListener[0]; - - private IReconcilingStrategy fSemanticHighlightingStrategy; - - /** - * The folding strategy for this processor - */ - private AbstractStructuredFoldingStrategy fFoldingStrategy; - - private final String SSE_UI_ID = "org.eclipse.wst.sse.ui"; //$NON-NLS-1$ - - /** - * true if as you type validation is enabled, - * false otherwise - */ - private boolean fValidationEnabled; - - public void addReconcilingListener(ISourceReconcilingListener listener) { - Set listeners = new HashSet(Arrays.asList(fReconcileListeners)); - listeners.add(listener); - fReconcileListeners = (ISourceReconcilingListener[]) listeners.toArray(new ISourceReconcilingListener[listeners.size()]); - } - - protected void beginProcessing() { - super.beginProcessing(); - ValidatorStrategy validatorStrategy = getValidatorStrategy(); - if (validatorStrategy != null) { - validatorStrategy.beginProcessing(); - } - if ((getTextViewer() instanceof ISourceViewer)) { - for (int i = 0; i < fReconcileListeners.length; i++) { - fReconcileListeners[i].aboutToBeReconciled(); - } - } - } - - protected void endProcessing() { - super.endProcessing(); - ValidatorStrategy validatorStrategy = getValidatorStrategy(); - if (validatorStrategy != null) { - validatorStrategy.endProcessing(); - } - /* single spell-check for everything to ensure that SpellingProblem offsets are correct */ - IReconcilingStrategy spellingStrategy = getSpellcheckStrategy(); - IDocument document = getDocument(); - if (spellingStrategy != null && document != null) { - spellingStrategy.reconcile(new Region(0, document.getLength())); - } - - IReconcilingStrategy semanticHighlightingStrategy = getSemanticHighlightingStrategy(); - if (semanticHighlightingStrategy != null && document != null) { - semanticHighlightingStrategy.reconcile(new Region(0, document.getLength())); - } - - if ((getTextViewer() instanceof ISourceViewer)) { - ISourceViewer sourceViewer = (ISourceViewer) getTextViewer(); - IAnnotationModel annotationModel = sourceViewer.getAnnotationModel(); - for (int i = 0; i < fReconcileListeners.length; i++) { - fReconcileListeners[i].reconciled(document, annotationModel, false, new NullProgressMonitor()); - } - } - } - - public void forceReconciling() { - super.forceReconciling(); - } - - protected String getContentType(IDocument doc) { - if (doc == null) - return null; - - String contentTypeId = null; - - IContentType ct = null; - try { - IContentDescription desc = Platform.getContentTypeManager().getDescriptionFor(new StringReader(doc.get()), null, IContentDescription.ALL); - if (desc != null) { - ct = desc.getContentType(); - if (ct != null) - contentTypeId = ct.getId(); - } - } - catch (IOException e) { - // just bail - } - return contentTypeId; - } - - protected IReconcilingStrategy getSpellcheckStrategy() { - if (fSpellcheckStrategy == null && getDocument() != null) { - String contentTypeId = getContentType(getDocument()); - if (contentTypeId == null) { - contentTypeId = IContentTypeManager.CT_TEXT; - } - if (getTextViewer() instanceof ISourceViewer) { - ISourceViewer viewer = (ISourceViewer) getTextViewer(); - fSpellcheckStrategy = new SpellcheckStrategy(viewer, contentTypeId); - fSpellcheckStrategy.setDocument(getDocument()); - } - } - return fSpellcheckStrategy; - } - - /** - * <p>Get the folding strategy for this processor. Retrieved from the - * extended configuration builder. The processor chosen is set by the plugin.</p> - * - * <p>EX:<br /> - * <code><extension point="org.eclipse.wst.sse.ui.editorConfiguration"><br /> - * <provisionalConfiguration<br /> - * type="foldingstrategy"<br /> - * class="org.eclipse.wst.xml.ui.internal.projection.XMLFoldingStrategy"<br /> - * target="org.eclipse.core.runtime.xml, org.eclipse.wst.xml.core.xmlsource" /><br /> - * </extension></code></p> - * - * <p>The type must be equal to <code>AbstractFoldingStrategy.ID</code> (AKA: foldingstrategy) - * and the class must extend <code>org.eclipse.wst.sse.ui.internal.projection.AbstractFoldingStrategy</code> - * and the target must be a structured editor content type ID</p> - * - * @return the requested folding strategy or null if none can be found - */ - protected IReconcilingStrategy getFoldingStrategy() { - if(fFoldingStrategy == null && getDocument() != null) { - String contentTypeId = getContentType(getDocument()); - if (contentTypeId == null) { - contentTypeId = IContentTypeManager.CT_TEXT; - } - - ITextViewer viewer = getTextViewer(); - if(viewer instanceof ProjectionViewer) { - ExtendedConfigurationBuilder builder = ExtendedConfigurationBuilder.getInstance(); - - IContentType type = Platform.getContentTypeManager().getContentType(contentTypeId); - while(fFoldingStrategy == null && type != null) { - fFoldingStrategy =(AbstractStructuredFoldingStrategy) builder.getConfiguration( - AbstractStructuredFoldingStrategy.ID, type.getId()); - - type = type.getBaseType(); - } - - if(fFoldingStrategy != null) { - fFoldingStrategy.setViewer((ProjectionViewer)viewer); - fFoldingStrategy.setDocument(getDocument()); - } - } - } - - return fFoldingStrategy; - } - - /** - * Enable or disable as you type validation. Typically set by a user preference - * - * @param enable true to enable as you type validation, false to disable - */ - public void setValidatorStrategyEnabled(boolean enable) { - fValidationEnabled = enable; - } - - /** - * @return Returns the ValidatorStrategy. - */ - protected ValidatorStrategy getValidatorStrategy() { - ValidatorStrategy validatorStrategy = null; - if (fValidatorStrategy == null && fValidationEnabled) { - if (getTextViewer() instanceof ISourceViewer) { - ISourceViewer viewer = (ISourceViewer) getTextViewer(); - String contentTypeId = null; - - IDocument doc = viewer.getDocument(); - contentTypeId = getContentType(doc); - - if (contentTypeId != null) { - validatorStrategy = new ValidatorStrategy(viewer, contentTypeId); - ValidatorBuilder vBuilder = new ValidatorBuilder(); - ValidatorMetaData[] vmds = vBuilder.getValidatorMetaData(SSE_UI_ID); - List enabledValidators = new ArrayList(1); - /* if any "must" handle this content type, just add them */ - boolean foundSpecificContentTypeValidators = false; - for (int i = 0; i < vmds.length; i++) { - if (vmds[i].mustHandleContentType(contentTypeId)) { - if (DEBUG_VALIDATORS) - Logger.log(Logger.INFO, contentTypeId + " using specific validator " + vmds[i].getValidatorId()); //$NON-NLS-1$ - foundSpecificContentTypeValidators = true; - enabledValidators.add(vmds[i]); - } - } - if (!foundSpecificContentTypeValidators) { - for (int i = 0; i < vmds.length; i++) { - if (vmds[i].canHandleContentType(contentTypeId)) { - if (DEBUG_VALIDATORS) - Logger.log(Logger.INFO, contentTypeId + " using inherited(?) validator " + vmds[i].getValidatorId()); //$NON-NLS-1$ - enabledValidators.add(vmds[i]); - } - } - } - for (int i = 0; i < enabledValidators.size(); i++) { - validatorStrategy.addValidatorMetaData((ValidatorMetaData) enabledValidators.get(i)); - } - } - } - fValidatorStrategy = validatorStrategy; - } else if(fValidatorStrategy != null && fValidationEnabled) { - validatorStrategy = fValidatorStrategy; - } - return validatorStrategy; - } - - public void setSemanticHighlightingStrategy(IReconcilingStrategy semanticHighlightingStrategy) { - fSemanticHighlightingStrategy = semanticHighlightingStrategy; - fSemanticHighlightingStrategy.setDocument(getDocument()); - } - - protected IReconcilingStrategy getSemanticHighlightingStrategy() { - return fSemanticHighlightingStrategy; - } - - /** - * @param dirtyRegion - */ - protected void process(DirtyRegion dirtyRegion) { - if (!isInstalled() || isInRewriteSession() || dirtyRegion == null || getDocument() == null) - return; - - super.process(dirtyRegion); - - ITypedRegion[] partitions = computePartitioning(dirtyRegion); - - // call the validator strategy once for each effected partition - DirtyRegion dirty = null; - for (int i = 0; i < partitions.length; i++) { - dirty = createDirtyRegion(partitions[i], DirtyRegion.INSERT); - - // [source]validator (extension) for this partition - if (getValidatorStrategy() != null) { - getValidatorStrategy().reconcile(partitions[i], dirty); - } - } - - /* if there is a folding strategy then reconcile it for the - * entire dirty region. - * NOTE: the folding strategy does not care about the sub regions. - */ - if(getFoldingStrategy() != null) { - getFoldingStrategy().reconcile(dirtyRegion, null); - } - } - - public void removeReconcilingListener(ISourceReconcilingListener listener) { - Set listeners = new HashSet(Arrays.asList(fReconcileListeners)); - listeners.remove(listener); - fReconcileListeners = (ISourceReconcilingListener[]) listeners.toArray(new ISourceReconcilingListener[listeners.size()]); - } - - - public void setDocument(IDocument doc) { - if (getDocument() instanceof IStructuredDocument) { - RegionParser parser = ((IStructuredDocument) getDocument()).getParser(); - if (parser instanceof StructuredDocumentRegionParser) { - ((StructuredDocumentRegionParser) parser).removeStructuredDocumentRegionHandler(fResetHandler); - } - } - - super.setDocument(doc); - - IReconcilingStrategy validatorStrategy = getValidatorStrategy(); - if (validatorStrategy != null) { - validatorStrategy.setDocument(doc); - } - if (fSemanticHighlightingStrategy != null) { - fSemanticHighlightingStrategy.setDocument(doc); - } - - fSpellcheckStrategy = null; - if(fFoldingStrategy != null) { - fFoldingStrategy.uninstall(); - } - fFoldingStrategy = null; - - if (getDocument() instanceof IStructuredDocument) { - RegionParser parser = ((IStructuredDocument) doc).getParser(); - if (parser instanceof StructuredDocumentRegionParser) { - ((StructuredDocumentRegionParser) parser).addStructuredDocumentRegionHandler(fResetHandler); - } - } - } - - protected void setEntireDocumentDirty(IDocument document) { - super.setEntireDocumentDirty(document); - - // make the entire document dirty - // this also happens on a "save as" - if (document != null && isInstalled() && fLastPartitions != null && document.getLength() == 0) { - /** - * https://bugs.eclipse.org/bugs/show_bug.cgi?id=199053 - * - * Process the strategies for the last known-good partitions. - */ - for (int i = 0; i < fLastPartitions.length; i++) { - ValidatorStrategy validatorStrategy = getValidatorStrategy(); - if (validatorStrategy != null) { - validatorStrategy.reconcile(fLastPartitions[i], createDirtyRegion(fLastPartitions[i], DirtyRegion.REMOVE)); - } - } - IReconcilingStrategy spellingStrategy = getSpellcheckStrategy(); - if (spellingStrategy != null) { - spellingStrategy.reconcile(new Region(0, document.getLength())); - } - - //if there is a folding strategy then reconcile it - if(getFoldingStrategy() != null) { - getFoldingStrategy().reconcile(new Region(0, document.getLength())); - } - } - } - - /** - * @see org.eclipse.wst.sse.ui.internal.reconcile.DirtyRegionProcessor#install(org.eclipse.jface.text.ITextViewer) - */ - public void install(ITextViewer textViewer) { - super.install(textViewer); - - //determine if validation is enabled - this.fValidationEnabled = SSEUIPlugin.getInstance().getPreferenceStore().getBoolean( - CommonEditorPreferenceNames.EVALUATE_TEMPORARY_PROBLEMS); - } - - /** - * @see org.eclipse.wst.sse.ui.internal.reconcile.DirtyRegionProcessor#uninstall() - */ - public void uninstall() { - if (isInstalled()) { - - IReconcilingStrategy validatorStrategy = getValidatorStrategy(); - - if (validatorStrategy != null) { - if (validatorStrategy instanceof IReleasable) - ((IReleasable) validatorStrategy).release(); - } - - if (fSpellcheckStrategy != null) { - fSpellcheckStrategy.setDocument(null); - fSpellcheckStrategy = null; - } - - fReconcileListeners = new ISourceReconcilingListener[0]; - - if (getDocument() instanceof IStructuredDocument) { - RegionParser parser = ((IStructuredDocument) getDocument()).getParser(); - if (parser instanceof StructuredDocumentRegionParser) { - ((StructuredDocumentRegionParser) parser).removeStructuredDocumentRegionHandler(fResetHandler); - } - } - } - super.uninstall(); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/IConfigurableReconciler.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/IConfigurableReconciler.java deleted file mode 100644 index 6f8b28f06d..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/IConfigurableReconciler.java +++ /dev/null @@ -1,35 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2006 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.reconcile; - -import org.eclipse.jface.text.reconciler.IReconcilingStrategy; - -/** - * A reconciler that allows IReconcilingStrategies to be assigned to partition - * types. The reconciler will call the registered IReconcilingStrategy when - * dirty regions which contain partitions of a specific type need to be - * reconciled. - * - * @since 1.1 - */ -public interface IConfigurableReconciler { - /** - * Sets the reconciling strategy for the reconciler to use for the - * specified content type. - * - * @param partitionType - * the partition type - * @param strategy - * the reconciling strategy - */ - void setReconcilingStrategy(String partitionType, IReconcilingStrategy strategy); -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/IReconcileAnnotationKey.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/IReconcileAnnotationKey.java deleted file mode 100644 index e3b02b23e7..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/IReconcileAnnotationKey.java +++ /dev/null @@ -1,35 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.reconcile; - -import org.eclipse.jface.text.reconciler.IReconcileStep; - -/** - * Defines an annotation key that the - * <code>AbstractStructuredTextReconcilingStrategy</code> knows how to - * remove appropriately. - * - * @deprecated not API, this will probably just become an abstract class - * - * @author pavery - */ -public interface IReconcileAnnotationKey { - static final int PARTIAL = 1; - static final int TOTAL = 0; - - String getPartitionType(); - - //int getScope(); - - IReconcileStep getStep(); -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/IStructuredReconcileStep.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/IStructuredReconcileStep.java deleted file mode 100644 index d51bc9931e..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/IStructuredReconcileStep.java +++ /dev/null @@ -1,66 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.reconcile; - -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.reconciler.DirtyRegion; -import org.eclipse.jface.text.reconciler.IReconcileResult; -import org.eclipse.jface.text.reconciler.IReconcileStep; - -/** - * @author pavery - * @deprecated still working out API (or if anything here should be API) - * - * Interface for a step in StructuredRegionProcessor framework. - */ -public interface IStructuredReconcileStep extends IReconcileStep { - /** - * Partitions for which this step can add/remove annotions - * - * @return an array of the partitions for which this step can add/remove - * annotions - */ - String[] getPartitionTypes(); - - /** - * Returns the scope for which this step adds annotations. - * - * @return the scope for which this step adds annotations - */ - //int getScope(); - - /** - * Tells you if the step is equal to this step or any of the sibling - * steps. - * - * @return - */ - boolean isSiblingStep(IReconcileStep step); - - /** - * Adds awareness that the Reconciler is reconciling the entire document - * this call. - * - * @param dirtyRegion - * @param subRegion - * @param refreshAll - * @return - */ - IReconcileResult[] reconcile(DirtyRegion dirtyRegion, IRegion subRegion, boolean refreshAll); - - /** - * Used to reset the state of the Strategy. For example: any flags that - * need to be reset after a long running operation like processAll(). - */ - void reset(); -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/IStructuredReconcilingStrategy.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/IStructuredReconcilingStrategy.java deleted file mode 100644 index 5b02f88117..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/IStructuredReconcilingStrategy.java +++ /dev/null @@ -1,43 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.reconcile; - -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.reconciler.DirtyRegion; -import org.eclipse.jface.text.reconciler.IReconcilingStrategy; - - -/** - * Interface for structured reconciling strategies. - * - * @deprecated doesn't need to be API and might go away - * - * @author pavery - */ -public interface IStructuredReconcilingStrategy extends IReconcilingStrategy { - /** - * Adds awareness that the reconciler is processing the entire document - * via refreshAll flag. - * - * @param dirtyRegion - * @param subRegion - * @param refreshAll - */ - public void reconcile(DirtyRegion dirtyRegion, IRegion subRegion, boolean refreshAll); - - /** - * Used to reset the state of the Strategy. For example: any flags that - * need to be reset after a long running operation like processAll(). - */ - public void reset(); -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/ReconcileAnnotationKey.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/ReconcileAnnotationKey.java deleted file mode 100644 index e9284a3db7..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/ReconcileAnnotationKey.java +++ /dev/null @@ -1,56 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.reconcile; - -import org.eclipse.jface.text.reconciler.IReconcileStep; - - -/** - * Implementation of <code>IReconcileAnnotationKey</code> note: clients - * should use the method StructuredReconcileStep#createKey(String - * partitionType, int scope) - * - * @author pavery - */ -public class ReconcileAnnotationKey { - - public static final int PARTIAL = 1; - public static final int TOTAL = 0; - - private String fPartitionType = null; - - private IReconcileStep fReconcileStep = null; - private int fScope; - - public ReconcileAnnotationKey(IReconcileStep step, String partitionType, int scope) { - fReconcileStep = step; - fPartitionType = partitionType; - fScope = scope; - } - - public String getPartitionType() { - return fPartitionType; - } - - public int getScope() { - return fScope; - } - - public IReconcileStep getStep() { - return fReconcileStep; - } - - public String toString() { - return this.getClass() + "\r\nid: " + fPartitionType; //$NON-NLS-1$ - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/StructuredReconcileStep.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/StructuredReconcileStep.java deleted file mode 100644 index bd8b0b7813..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/StructuredReconcileStep.java +++ /dev/null @@ -1,193 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2006 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.reconcile; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; - -import org.eclipse.core.runtime.Platform; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ITypedRegion; -import org.eclipse.jface.text.TextUtilities; -import org.eclipse.jface.text.reconciler.AbstractReconcileStep; -import org.eclipse.jface.text.reconciler.DirtyRegion; -import org.eclipse.jface.text.reconciler.IReconcilableModel; -import org.eclipse.jface.text.reconciler.IReconcileResult; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredPartitioning; -import org.eclipse.wst.sse.core.text.IStructuredPartitions; -import org.eclipse.wst.sse.ui.internal.IReleasable; -import org.eclipse.wst.sse.ui.internal.Logger; - - -/** - * ReconcileStep that knows about the annotation that it adds to the - * AnnotationModel. It knows how to create an annotation key (for smart - * removal later) It knows the partition types on which it can operate. It - * knows the scope on which it operates (for short circuiting) It knows if the - * Reconciler is reconciling the entire document. - * - * Clients must subclass this class. - * - * @author pavery - */ -public abstract class StructuredReconcileStep extends AbstractReconcileStep implements IReleasable { - - /** debug flag */ - protected static final boolean DEBUG; - static { - String value = Platform.getDebugOption("org.eclipse.wst.sse.ui/debug/reconcilerjob"); //$NON-NLS-1$ - DEBUG = value != null && value.equalsIgnoreCase("true"); //$NON-NLS-1$ - } - - protected final IReconcileResult[] EMPTY_RECONCILE_RESULT_SET = new IReconcileResult[0]; - - /** - * It's possible for a partial step to get called on the same area twice - * (as w/ a full document reconcile) this list keeps track of area already - * covered. Should be reset() after the "batch" of reconciling is - * finished. - */ - private HashSet fPartitionTypes = null; - - public StructuredReconcileStep() { - super(); - fPartitionTypes = new HashSet(); - } - - public ReconcileAnnotationKey createKey(IStructuredDocumentRegion sdRegion, int scope) { - - ITypedRegion tr = getPartition(sdRegion); - String partitionType = (tr != null) ? tr.getType() : IStructuredPartitions.UNKNOWN_PARTITION; - return createKey(partitionType, scope); - } - - /** - * @param sdRegion - * @return - */ - protected ITypedRegion getPartition(IStructuredDocumentRegion sdRegion) { - ITypedRegion tr = null; - if (!sdRegion.isDeleted()) - tr = getPartition(sdRegion.getParentDocument(), sdRegion.getStartOffset()); - return tr; - } - - private ITypedRegion getPartition(IDocument doc, int offset) { - ITypedRegion tr = null; - // not sure why document would ever be null, but put in this - // guard for - // https://bugs.eclipse.org/bugs/show_bug.cgi?id=86069 - if (doc != null) { - try { - tr = TextUtilities.getPartition(doc, IStructuredPartitioning.DEFAULT_STRUCTURED_PARTITIONING, offset, false); - } catch (BadLocationException e) { - if (DEBUG) - Logger.logException("problem getting partition at: " + offset, e); //$NON-NLS-1$ - } - } - return tr; - } - - /** - * Clients should use this method to create annotation keys as it - * registers the key for removal later. - * - * @param partitionType - * @param scope - * @return - */ - public ReconcileAnnotationKey createKey(String partitionType, int scope) { - fPartitionTypes.add(partitionType); - return new ReconcileAnnotationKey(this, partitionType, scope); - } - - protected IDocument getDocument() { - IDocument doc = null; - IReconcilableModel rModel = getModel(); - if (rModel instanceof DocumentAdapter) { - doc = ((DocumentAdapter) rModel).getDocument(); - } - return doc; - } - - public IReconcilableModel getModel() { - return getInputModel(); - } - - public String getPartitionType(IDocument doc, int offset) { - ITypedRegion tr = getPartition(doc, offset); - return (tr != null) ? tr.getType() : IStructuredPartitions.UNKNOWN_PARTITION; - } - - public String[] getPartitionTypes() { - // using hash set to automatically get rid of dupes - HashSet tempResults = new HashSet(); - // add these partition types - tempResults.addAll(fPartitionTypes); - return (String[]) tempResults.toArray(new String[tempResults.size()]); - } - - protected IStructuredDocument getStructuredDocument() { - IStructuredDocument sDoc = null; - IDocument doc = getDocument(); - if (doc instanceof IStructuredDocument) - sDoc = (IStructuredDocument) getDocument(); - return sDoc; - } - - /** - * Removes duplicates. - * - * @param results1 - * @param results2 - * @return - */ - protected IReconcileResult[] merge(IReconcileResult[] results1, IReconcileResult[] results2) { - if (results1 == null) - return results2; - if (results2 == null) - return results1; - - List results = new ArrayList(); - results.addAll(Arrays.asList(results1)); - for (int i = 0; i < results2.length; i++) { - results.add(results2[i]); - } - return (IReconcileResult[]) results.toArray(new IReconcileResult[results.size()]); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.text.reconciler.AbstractReconcileStep#reconcileModel(org.eclipse.jface.text.reconciler.DirtyRegion, - * org.eclipse.jface.text.IRegion) - */ - protected IReconcileResult[] reconcileModel(DirtyRegion dirtyRegion, IRegion subRegion) { - return EMPTY_RECONCILE_RESULT_SET; - } - - /** - * Release resources used by the step here as needed. Be sure to call - * super.release() when you override this method as to propagate the - * release through all steps. - */ - public void release() { - // - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/StructuredRegionProcessor.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/StructuredRegionProcessor.java deleted file mode 100644 index 03b2dde56d..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/StructuredRegionProcessor.java +++ /dev/null @@ -1,310 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.reconcile; - -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.reconciler.DirtyRegion; -import org.eclipse.wst.sse.core.StructuredModelManager; -import org.eclipse.wst.sse.core.internal.model.ModelLifecycleEvent; -import org.eclipse.wst.sse.core.internal.provisional.IModelLifecycleListener; -import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel; -import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument; - -/** - * An IStructuredModel aware Region Processor. Adds ModelLifecycle listener. - * ModelLifecycle listener notifies us that some reinitialization needs to - * take place. - * - * Model aware "process()" Implements a IndexedRegion-based "contains()" - * method using IStructuredModel. - * - */ -public class StructuredRegionProcessor extends DocumentRegionProcessor { - class ModelLifecycleListener implements IModelLifecycleListener { - IStructuredModel changing = null; - /** - * @see org.eclipse.wst.sse.core.internal.provisional.IModelLifecycleListener#processPostModelEvent(org.eclipse.wst.sse.core.internal.model.ModelLifecycleEvent) - */ - public void processPostModelEvent(ModelLifecycleEvent event) { - - // if underlying StructuredDocument changed, need to reconnect it - // here... - // ex. file is modified outside the workbench - if (event.getType() == ModelLifecycleEvent.MODEL_DOCUMENT_CHANGED) { - if (changing != null && event.getModel() == changing) { - IStructuredDocument sDoc = event.getModel().getStructuredDocument(); - - if (DEBUG) { - System.out.println("======================================================"); //$NON-NLS-1$ - System.out.println("StructuredRegionProcessor: DOCUMENT MODEL CHANGED TO: "); //$NON-NLS-1$ - System.out.println(sDoc.get()); - System.out.println("======================================================"); //$NON-NLS-1$ - } - setDocument(sDoc); - } - changing = null; - } - } - - /** - * @see org.eclipse.wst.sse.core.internal.provisional.IModelLifecycleListener#processPreModelEvent(org.eclipse.wst.sse.core.internal.model.ModelLifecycleEvent) - */ - public void processPreModelEvent(ModelLifecycleEvent event) { - if(fCurrentDoc != null) { - IStructuredModel model = null; - try { - model = getStructuredModelForRead(fCurrentDoc); - if (event.getType() == ModelLifecycleEvent.MODEL_DOCUMENT_CHANGED && event.getModel() == model) { - changing = event.getModel(); - flushDirtyRegionQueue(); - // note: old annotations are removed via the strategies on - // AbstractStructuredTextReconcilingStrategy#setDocument(...) - } - } finally { - if(model != null) { - model.releaseFromRead(); - } - } - } - } - } - - /** - * The life cycle listener used to listen to the current documents model even though - * this class does not hold onto a reference to the model. - */ - private IModelLifecycleListener fLifeCycleListener = new ModelLifecycleListener(); - /** Used to get the current model on demand so a model does not need to be held by permanently */ - private IDocument fCurrentDoc = null; - - /** Only to be used for content type and IModelLifecycleListener registration. All other uses should "get" the model. */ - private IStructuredModel fCurrentModel = null; - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.sse.ui.internal.reconcile.DirtyRegionProcessor#getOuterRegion(org.eclipse.jface.text.reconciler.DirtyRegion, - * org.eclipse.jface.text.reconciler.DirtyRegion) - */ - protected DirtyRegion getOuterRegion(DirtyRegion root, DirtyRegion possible) { - // first try simple region check if one region contains the other - DirtyRegion outer = super.getOuterRegion(root, possible); - if (outer == null && fCurrentDoc != null) { - IStructuredModel sModel = null; - try { - sModel = getStructuredModelForRead(fCurrentDoc); - if (sModel != null) { - // now compare nodes - IndexedRegion rootRegion = sModel.getIndexedRegion(root.getOffset()); - IndexedRegion possRegion = sModel.getIndexedRegion(possible.getOffset()); - if (rootRegion != null && possRegion != null) { - int rootStart = rootRegion.getStartOffset(); - int possStart = possRegion.getStartOffset(); - // first just check if rootregion starts before - // possregion - if (rootStart <= possStart) { - // check if possregion is inside rootregion - outer = _getOuterRegion(root, possible, sModel, rootStart, possStart); - } - else { - // otherwise if rootregion is inside possregion - outer = _getOuterRegion(possible, root, sModel, possStart, rootStart); - } - } - } - - } finally { - if(sModel != null) { - sModel.releaseFromRead(); - } - } - } - return outer; - } - - /** - * Assumes that when this method is called, region1's node start offset >= - * region2's node start offset. Determines if region1 contains region2 or - * vice versa. Returns region1 if: - * <ul> - * <li>region1's node region == region2's node region</li> - * <li>region1's node region contains region2's node region</li> - * </ul> - * Returns region2 if: - * <ul> - * <li>region1's node region and region2's node region starts at same - * offset but region2's node region is longer</li> - * </ul> - * Returns null otherwise. - * - * @param region1 - * @param region2 - * @param sModel - * @param region1NodeStart - * @param region2NodeStart - * @return outer dirty region or null if none exists. - */ - private DirtyRegion _getOuterRegion(DirtyRegion region1, DirtyRegion region2, IStructuredModel sModel, int region1NodeStart, int region2NodeStart) { - DirtyRegion outer = null; - int region1NodeEnd = -1; - int region2NodeEnd = -1; - // then check if region1's end appears after - // region2's end - IndexedRegion region1EndNode = sModel.getIndexedRegion(region1.getOffset() + region1.getLength()); - if (region1EndNode == null) { - // if no end, just assume region spans all the - // way to the end so it includes other region - outer = region1; - } - else { - region1NodeEnd = region1EndNode.getEndOffset(); - IndexedRegion region2EndNode = sModel.getIndexedRegion(region2.getOffset() + region2.getLength()); - region2NodeEnd = region2EndNode != null ? region2EndNode.getEndOffset() : getDocument().getLength(); - if (region1NodeEnd >= region2NodeEnd) { - // root contains or is equal to possible - outer = region1; - } - else if (region1NodeStart == region2NodeStart && region2NodeEnd >= region1NodeEnd) { - // possible contains root because they - // both start at same place but possible - // is longer - outer = region2; - } - } - if (DEBUG) { - if (outer != null) - System.out.println("checking if [" + region1NodeStart + ":" + region1NodeEnd + "] contains [" + region2NodeStart + ":" + region2NodeEnd + "] ... " + outer.toString()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ - else - System.out.println("checking if [" + region1NodeStart + ":" + region1NodeEnd + "] contains [" + region2NodeStart + ":" + region2NodeEnd + "] ... NO CONTAIN"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ - } - return outer; - } - - /** - * We already know content type from when we created the model, so just - * use that. - */ - protected String getContentType(IDocument doc) { - if (fCurrentModel != null && doc == fCurrentModel.getStructuredDocument()) { - /* - * Avoid "get"ting a model if we can, it may require lock - * acquisition - */ - return fCurrentModel.getContentTypeIdentifier(); - } - - String contentTypeId = null; - IStructuredModel sModel = null; - try { - sModel = getStructuredModelForRead(doc); - if (sModel != null) { - contentTypeId = sModel.getContentTypeIdentifier(); - } - } - finally { - if (sModel != null) - sModel.releaseFromRead(); - } - return contentTypeId; - } - - - /** - * Remember to release model after use!! - * - * @return - */ - private IStructuredModel getStructuredModelForRead(IDocument doc) { - IStructuredModel sModel = null; - if (doc != null && doc instanceof IStructuredDocument) - sModel = StructuredModelManager.getModelManager().getModelForRead((IStructuredDocument) doc); - return sModel; - } - - protected void process(DirtyRegion dirtyRegion) { - if (!isInstalled() || isInRewriteSession() || dirtyRegion == null || getDocument() == null) - return; - - // unhook old lifecycle listener - if(fCurrentDoc != null) { - IStructuredModel sModel = null; - try { - sModel = getStructuredModelForRead(fCurrentDoc); - - // use structured model to determine area to process - if (sModel != null) { - int start = dirtyRegion.getOffset(); - int end = start + dirtyRegion.getLength(); - IndexedRegion irStart = sModel.getIndexedRegion(start); - IndexedRegion irEnd = sModel.getIndexedRegion(end); - - if (irStart != null) { - start = Math.min(start, irStart.getStartOffset()); - } - if (irEnd != null) { - end = Math.max(end, irEnd.getEndOffset()); - } - super.process(createDirtyRegion(start, end - start, DirtyRegion.INSERT)); - } else { - super.process(dirtyRegion); - } - } finally { - if(sModel != null) { - sModel.releaseFromRead(); - } - } - } else { - super.process(dirtyRegion); - } - } - - /** - * Reinitializes listeners and sets new document onall strategies. - * - * @see org.eclipse.jface.text.reconciler.AbstractReconciler#reconcilerDocumentChanged(IDocument) - */ - protected void reconcilerDocumentChanged(IDocument newDocument) { - setDocument(newDocument); - } - - public void setDocument(IDocument newDocument) { - /* - * unhook old lifecycle listener; it is important not to re-get the - * model at this point as we may be shutting down - */ - if (fCurrentModel != null) { - fCurrentModel.removeModelLifecycleListener(fLifeCycleListener); - fCurrentModel = null; - } - - // set the new document - super.setDocument(newDocument); - fCurrentDoc = newDocument; - - // add new lifecycle listener - if (fCurrentDoc != null) { - try { - fCurrentModel = getStructuredModelForRead(fCurrentDoc); - if (fCurrentModel != null) { - fCurrentModel.addModelLifecycleListener(fLifeCycleListener); - } - } - finally { - if (fCurrentModel != null) { - fCurrentModel.releaseFromRead(); - } - } - } - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/StructuredTextReconcilingStrategy.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/StructuredTextReconcilingStrategy.java deleted file mode 100644 index f995d23d38..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/StructuredTextReconcilingStrategy.java +++ /dev/null @@ -1,75 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2006 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.reconcile; - -import org.eclipse.jface.text.Position; -import org.eclipse.jface.text.source.ISourceViewer; -import org.eclipse.wst.sse.core.StructuredModelManager; -import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel; -import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion; - -/** - * Uses IStructuredModel nodes to check "overlaps()" when getting annotations to remove. - */ -public abstract class StructuredTextReconcilingStrategy extends AbstractStructuredTextReconcilingStrategy { - - - public StructuredTextReconcilingStrategy(ISourceViewer sourceViewer) { - super(sourceViewer); - } - - /** - * Checks if this position overlaps any of the StructuredDocument regions' - * correstponding IndexedRegion. - * - * @param pos - * @param dr - * @return true if the position overlaps any of the regions, otherwise - * false. - */ - protected boolean overlaps(Position pos, IStructuredDocumentRegion[] sdRegions) { - int start = -1; - int end = -1; - for (int i = 0; i < sdRegions.length; i++) { - if(!sdRegions[i].isDeleted()) { - IndexedRegion corresponding = getCorrespondingNode(sdRegions[i]); - if(corresponding != null) { - if (start == -1 || start > corresponding.getStartOffset()) - start = corresponding.getStartOffset(); - if (end == -1 || end < corresponding.getEndOffset()) - end = corresponding.getEndOffset(); - } - } - } - return pos.overlapsWith(start, end - start); - } - - /** - * Returns the corresponding node for the StructuredDocumentRegion. - * - * @param sdRegion - * @return the corresponding node for sdRegion - */ - protected IndexedRegion getCorrespondingNode(IStructuredDocumentRegion sdRegion) { - IStructuredModel sModel = StructuredModelManager.getModelManager().getExistingModelForRead(getDocument()); - IndexedRegion indexedRegion = null; - try { - if (sModel != null) - indexedRegion = sModel.getIndexedRegion(sdRegion.getStart()); - } finally { - if (sModel != null) - sModel.releaseFromRead(); - } - return indexedRegion; - } - -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/TemporaryAnnotation.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/TemporaryAnnotation.java deleted file mode 100644 index 4f7ea9b0de..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/TemporaryAnnotation.java +++ /dev/null @@ -1,258 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2006 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.reconcile; - -import java.util.Map; - -import org.eclipse.jface.text.Position; -import org.eclipse.jface.text.quickassist.IQuickFixableAnnotation; -import org.eclipse.jface.text.reconciler.IReconcileResult; -import org.eclipse.jface.text.source.Annotation; -import org.eclipse.jface.text.source.IAnnotationAccessExtension; -import org.eclipse.jface.text.source.IAnnotationPresentation; -import org.eclipse.jface.text.source.ImageUtilities; -import org.eclipse.swt.SWT; -import org.eclipse.swt.graphics.GC; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.graphics.Rectangle; -import org.eclipse.swt.widgets.Canvas; -import org.eclipse.ui.editors.text.EditorsUI; -import org.eclipse.ui.texteditor.AnnotationPreference; -import org.eclipse.ui.texteditor.AnnotationPreferenceLookup; -import org.eclipse.wst.sse.ui.internal.ITemporaryAnnotation; - - -/** - * An implementation of ITemporaryAnnotation @ - * @author pavery - */ -public class TemporaryAnnotation extends Annotation implements ITemporaryAnnotation, IReconcileResult, IAnnotationPresentation, IQuickFixableAnnotation { - // remember to change these if it changes in the extension point - // may need a different home for them in the future, but they're here for - // now - public final static String ANNOT_ERROR = "org.eclipse.wst.sse.ui.temp.error"; //$NON-NLS-1$ - public final static String ANNOT_INFO = "org.eclipse.wst.sse.ui.temp.info"; //$NON-NLS-1$ - - // pa_TODO what should the ID be for this? - public final static String ANNOT_UNKNOWN = Annotation.TYPE_UNKNOWN; - public final static String ANNOT_WARNING = "org.eclipse.wst.sse.ui.temp.warning"; //$NON-NLS-1$ - - // copied from CompilationUnitDocumentProvider.ProblemAnnotation - //XXX: To be fully correct these constants should be non-static - - private static final int INFO_LAYER; - - private static final int WARNING_LAYER; - - private static final int ERROR_LAYER; - - static { - AnnotationPreferenceLookup lookup= EditorsUI.getAnnotationPreferenceLookup(); - INFO_LAYER= computeLayer("org.eclipse.wst.sse.ui.temp.info", lookup); //$NON-NLS-1$ - WARNING_LAYER= computeLayer("org.eclipse.wst.sse.ui.temp.warning", lookup); //$NON-NLS-1$ - ERROR_LAYER= computeLayer("org.eclipse.wst.sse.ui.temp.error", lookup); //$NON-NLS-1$ - } - - private static int computeLayer(String annotationType, AnnotationPreferenceLookup lookup) { - Annotation annotation= new Annotation(annotationType, false, null); - AnnotationPreference preference= lookup.getAnnotationPreference(annotation); - if (preference != null) - return preference.getPresentationLayer() + 1; - else - return IAnnotationAccessExtension.DEFAULT_LAYER + 1; - } - - - private Object fAdditionalFixInfo = null; - - private Object fKey = null; - private Position fPosition = null; - private Map fAttributes = null; - private boolean fIsQuickFixable = false; - private boolean fIsQuickFixableStateSet = false; - - private int fProblemID; - - private int fLayer = DEFAULT_LAYER; - - private Image fImage = null; - - public TemporaryAnnotation(Position p, String type, String message, ReconcileAnnotationKey key) { - super(); - fPosition = p; - setType(type); - fKey = key; - setText(message); - initLayer(); - initImage(); - } - - public TemporaryAnnotation(Position p, String type, String message, ReconcileAnnotationKey key, int problemId) { - super(); - fPosition = p; - fKey = key; - setType(type); - setText(message); - fProblemID = problemId; - initLayer(); - initImage(); - } - - private void initLayer() { - - String type = getType(); - if(type.equals(ANNOT_ERROR)) { - fLayer = ERROR_LAYER; - } - else if(type.equals(ANNOT_WARNING)) { - fLayer = WARNING_LAYER; - } - else if(type.equals(ANNOT_INFO)) { - fLayer = INFO_LAYER; - } - } - - private void initImage() { - // later we can add support for quick fix images. - String type = getType(); - if(type.equals(ANNOT_ERROR)) { - fImage = null; - } - else if(type.equals(ANNOT_WARNING)) { - fImage = null; - } - else if(type.equals(ANNOT_INFO)) { - fImage = null; - } - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - public boolean equals(Object obj) { - // this check doesn't take into consideration that annotation - // positions that change from a text edit before it - // we should be checking if the annotation is still on the same line, - // and the distance from the start of the line is the same - if (obj instanceof TemporaryAnnotation) { - - TemporaryAnnotation ta = (TemporaryAnnotation) obj; - - boolean samePosition = ta.getPosition().equals(this.getPosition()); - boolean sameText = false; - - if(ta.getText() != null && this.getText() != null && ta.getText().equals(this.getText())) - sameText = true; - else if(ta.getText( )== null && this.getText() == null) - sameText = true; - - return sameText && samePosition; - } - return super.equals(obj); - } - - /** - * Additional info required to fix this problem. - * - * @return an Object that contains additional info on how to fix this - * problem, or null if there is none - */ - public Object getAdditionalFixInfo() { - return fAdditionalFixInfo; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.sse.ui.ITemporaryAnnotation#getDescription() - */ - public String getDescription() { - return getText(); - } - - public Object getKey() { - return fKey; - } - - public Position getPosition() { - return fPosition; - } - - /** - * @return Returns the problemID. - */ - public int getProblemID() { - return fProblemID; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.text.source.Annotation#isPersistent() - */ - public boolean isPersistent() { - return false; - } - - /** - * Sets additional information useful to fixing this problem. - * - * @param an - * Object that contains additional info on how to fix this - * problem - */ - public void setAdditionalFixInfo(Object info) { - fAdditionalFixInfo = info; - setQuickFixable(true); - } - - public int getLayer() { - return fLayer; - } - - /* - * @see Annotation#paint - */ - public void paint(GC gc, Canvas canvas, Rectangle r) { - //initializeImages(); - if (fImage != null) - ImageUtilities.drawImage(fImage, gc, canvas, r, SWT.CENTER, SWT.TOP); - } - - public String toString() { - return "" + fPosition.getOffset() + ':' + fPosition.getLength() + ": " + getText(); //$NON-NLS-1$ //$NON-NLS-2$ - } - - public Map getAttributes() { - return fAttributes; - } - - public void setAttributes(Map attributes) { - fAttributes = attributes; - } - - public boolean isQuickFixable() { - return fIsQuickFixable; - } - - public void setQuickFixable(boolean state) { - fIsQuickFixable = state; - fIsQuickFixableStateSet = true; - } - - public boolean isQuickFixableStateSet() { - return fIsQuickFixableStateSet; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/validator/AnnotationInfo.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/validator/AnnotationInfo.java deleted file mode 100644 index 609420e136..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/validator/AnnotationInfo.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.eclipse.wst.sse.ui.internal.reconcile.validator; - -import org.eclipse.wst.validation.internal.provisional.core.IMessage; - -/** - * Holds info to create a TemporaryAnnotation. - * - * @since 1.0 - */ -public class AnnotationInfo { - - public static final int NO_PROBLEM_ID = -1; - private IMessage fMessage = null; - private Object fAdditionalFixInfo = null; - private int fProblemId = NO_PROBLEM_ID; - - public AnnotationInfo(IMessage message) { - fMessage = message; - - } - public AnnotationInfo(IMessage message, int problemId, Object additionalFixInfo) { - this(message); - fProblemId = problemId; - fAdditionalFixInfo = additionalFixInfo; - } - - public final IMessage getMessage() { - return fMessage; - } - - public final Object getAdditionalFixInfo() { - return fAdditionalFixInfo; - } - - public final int getProblemId() { - return fProblemId; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/validator/ISourceValidator.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/validator/ISourceValidator.java deleted file mode 100644 index 1e09976ca9..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/validator/ISourceValidator.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.eclipse.wst.sse.ui.internal.reconcile.validator; - -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IRegion; -import org.eclipse.wst.validation.internal.provisional.core.IReporter; -import org.eclipse.wst.validation.internal.provisional.core.IValidationContext; - -/** - * Interface to allow for "partial document" as you type validation. - * - */ -public interface ISourceValidator { - - /** - * As you type validation is getting "hooked up" to this IDocument. - * This is the instance of IDocument that the validator should - * operate on for each validate call. - * - * @param document - */ - void connect(IDocument document); - - /** - * The same IDocument passed in from the connect() method. - * This indicates that as you type validation is "shutting down" - * for this IDocument. - * - * @param document - */ - void disconnect(IDocument document); - - /** - * Like IValidator#validate(IValidationContext helper, IReporter reporter) - * except passes the dirty region, so document validation can be better - * optimized. - * - * @param dirtyRegion - * @param helper - * @param reporter - */ - void validate(IRegion dirtyRegion, IValidationContext helper, IReporter reporter); -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/validator/IncrementalHelper.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/validator/IncrementalHelper.java deleted file mode 100644 index 9615163b08..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/validator/IncrementalHelper.java +++ /dev/null @@ -1,57 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.reconcile.validator; - -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.jface.text.IDocument; -import org.eclipse.wst.validation.internal.provisional.core.IValidationContext; - - - -public class IncrementalHelper implements IValidationContext { - private IProject fProject; - - private String fURI = null; - - public IncrementalHelper(IDocument sourceDocument, IProject project) { - super(); - fProject = project; - } - - public String getPortableName(IResource resource) { - return resource.getProjectRelativePath().toString(); - } - - public IProject getProject() { - return fProject; - } - - public Object loadModel(String symbolicName) { - return null; - } - - public Object loadModel(String symbolicName, Object[] parms) { - return null; - } - - public void setURI(String uri) { - fURI = uri; - } - - public String[] getURIs() { - if(fURI != null) - return new String[]{fURI}; - return new String[0]; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/validator/IncrementalReporter.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/validator/IncrementalReporter.java deleted file mode 100644 index d1c8e2cb5e..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/validator/IncrementalReporter.java +++ /dev/null @@ -1,111 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.reconcile.validator; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; - -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.wst.validation.internal.provisional.core.IMessage; -import org.eclipse.wst.validation.internal.provisional.core.IReporter; -import org.eclipse.wst.validation.internal.provisional.core.IValidator; - - -/** - * Right now we'll only use one reporter per validator. - */ -public class IncrementalReporter implements IReporter { - private IProgressMonitor fProgressMonitor; - private HashMap messages = new HashMap(); - - public IncrementalReporter(IProgressMonitor progressMonitor) { - super(); - fProgressMonitor = progressMonitor; - } - - public void addMessage(IValidator validator, IMessage message) { - AnnotationInfo info = new AnnotationInfo(message); - addAnnotationInfo(validator, info); - } - - public final void addAnnotationInfo(IValidator validator, AnnotationInfo info) { - Object existingValue = messages.get(validator); - if (existingValue != null) { - ((HashSet) existingValue).add(info); - } - else { - HashSet newValue = new HashSet(1); - newValue.add(info); - messages.put(validator, newValue); - } - } - - public void displaySubtask(IValidator validator, IMessage message) { - if ((message == null) || (message.equals(""))) { //$NON-NLS-1$ - return; - } - if (fProgressMonitor != null) { - fProgressMonitor.subTask(message.getText(validator.getClass().getClassLoader())); - } - } - - public List getMessages() { - List result = new ArrayList(); - // messages is a list of: - // validators => HashSet(AnnotationInfo1, AnnotationInfo2, ...) - // (one HashSet per validator...) - Object[] lists = messages.values().toArray(); - for (int i = 0; i < lists.length; i++) { - Iterator it = ((HashSet)lists[i]).iterator(); - while (it.hasNext()) { - AnnotationInfo info = (AnnotationInfo) it.next(); - result.add(info.getMessage()); - } - } - return result; - } - - public AnnotationInfo[] getAnnotationInfo() { - List result = new ArrayList(); - Object[] infos = messages.values().toArray(); - for (int i = 0; i < infos.length; i++) { - result.addAll((HashSet)infos[i]); - } - return (AnnotationInfo[])result.toArray(new AnnotationInfo[result.size()]); - } - - public boolean isCancelled() { - if (fProgressMonitor == null) - return false; - return fProgressMonitor.isCanceled(); - } - - public void removeAllMessages(IValidator validator) { - Object o = messages.get(validator); - if(o != null && o instanceof HashSet) { - ((HashSet)o).clear(); - } - } - - public void removeAllMessages(IValidator validator, Object object) { - removeAllMessages(validator); - } - - // group names are unsupported - public void removeMessageSubset(IValidator validator, Object obj, String groupName) { - removeAllMessages(validator); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/validator/ReconcileStepForValidator.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/validator/ReconcileStepForValidator.java deleted file mode 100644 index 9aad1c6054..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/validator/ReconcileStepForValidator.java +++ /dev/null @@ -1,398 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2011 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.reconcile.validator; - -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.Path; -import org.eclipse.core.runtime.Platform; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.Position; -import org.eclipse.jface.text.Region; -import org.eclipse.jface.text.quickassist.IQuickAssistProcessor; -import org.eclipse.jface.text.reconciler.DirtyRegion; -import org.eclipse.jface.text.reconciler.IReconcilableModel; -import org.eclipse.jface.text.reconciler.IReconcileResult; -import org.eclipse.wst.sse.core.StructuredModelManager; -import org.eclipse.wst.sse.core.internal.provisional.IModelManager; -import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel; -import org.eclipse.wst.sse.ui.internal.Logger; -import org.eclipse.wst.sse.ui.internal.reconcile.DocumentAdapter; -import org.eclipse.wst.sse.ui.internal.reconcile.IReconcileAnnotationKey; -import org.eclipse.wst.sse.ui.internal.reconcile.ReconcileAnnotationKey; -import org.eclipse.wst.sse.ui.internal.reconcile.StructuredReconcileStep; -import org.eclipse.wst.sse.ui.internal.reconcile.TemporaryAnnotation; -import org.eclipse.wst.validation.internal.provisional.core.IMessage; -import org.eclipse.wst.validation.internal.provisional.core.IValidator; - - -/** - * A reconcile step for an IValidator for reconcile. Used the reconcile - * framework to create TemporaryAnnotations from the validator messages. - * - * @author pavery - */ -public class ReconcileStepForValidator extends StructuredReconcileStep { - - /** debug flag */ - protected static final boolean DEBUG; - static { - String value = Platform.getDebugOption("org.eclipse.wst.sse.ui/debug/reconcilerjob"); //$NON-NLS-1$ - DEBUG = value != null && value.equalsIgnoreCase("true"); //$NON-NLS-1$ - } - - private final IReconcileResult[] EMPTY_RECONCILE_RESULT_SET = new IReconcileResult[0]; - private IncrementalHelper fHelper = null; - private IncrementalReporter fReporter = null; - - /** - * Declared scope of this validator, either ReconcileAnnotationKey.TOTAL - * or ReconcileAnnotationKey.PARTIAL - */ - private int fScope = -1; - private IValidator fValidator = null; - private final String QUICKASSISTPROCESSOR = IQuickAssistProcessor.class.getName(); - - - public ReconcileStepForValidator(IValidator v, int scope) { - super(); - - if (v == null) - throw new IllegalArgumentException("validator cannot be null"); //$NON-NLS-1$ - - fValidator = v; - fScope = scope; - } - - /** - * Converts a map of IValidatorForReconcile to List to annotations based - * on those messages - * - * @param messages - * @return - */ - // protected IReconcileResult[] createAnnotations(List messageList) { - // List annotations = new ArrayList(); - // for (int i = 0; i < messageList.size(); i++) { - // IMessage validationMessage = (IMessage) messageList.get(i); - // - // int offset = validationMessage.getOffset(); - // - // if (offset < 0) - // continue; - // - // String messageText = null; - // try { - // messageText = - // validationMessage.getText(validationMessage.getClass().getClassLoader()); - // } - // catch (Exception t) { - // Logger.logException("exception reporting message from validator", t); - // //$NON-NLS-1$ - // continue; - // } - // - // String type = getSeverity(validationMessage); - // // this position seems like it would be possibly be the wrong - // // length - // int length = validationMessage.getLength(); - // if (length >= 0) { - // Position p = new Position(offset, length); - // ReconcileAnnotationKey key = createKey(getPartitionType(getDocument(), - // offset), getScope()); - // annotations.add(new TemporaryAnnotation(p, type, messageText, key)); - // } - // } - // - // return (IReconcileResult[]) annotations.toArray(new - // IReconcileResult[annotations.size()]); - // } - /** - * Converts a map of IValidatorForReconcile to List to annotations based - * on those messages - * - * @param messages - * @return - */ - protected IReconcileResult[] createAnnotations(AnnotationInfo[] infos) { - - - List annotations = new ArrayList(); - for (int i = 0; i < infos.length; i++) { - - AnnotationInfo info = infos[i]; - - IMessage validationMessage = info.getMessage(); - int offset = validationMessage.getOffset(); - if (offset < 0) - continue; - - String messageText = null; - try { - messageText = validationMessage.getText(validationMessage.getClass().getClassLoader()); - } - catch (Exception t) { - Logger.logException("exception reporting message from validator", t); //$NON-NLS-1$ - continue; - } - String type = getSeverity(validationMessage); - // this position seems like it would be possibly be the wrong - // length - int length = validationMessage.getLength(); - if (length >= 0) { - - Position p = new Position(offset, length); - ReconcileAnnotationKey key = createKey(getPartitionType(getDocument(), offset), getScope()); - - // create an annotation w/ problem ID and fix info - TemporaryAnnotation annotation = new TemporaryAnnotation(p, type, messageText, key); - Object extraInfo = info.getAdditionalFixInfo(); - // https://bugs.eclipse.org/bugs/show_bug.cgi?id=170988 - // add quick fix information - if (extraInfo == null) { - extraInfo = validationMessage.getAttribute(QUICKASSISTPROCESSOR); - } - annotation.setAdditionalFixInfo(extraInfo); - annotation.setAttributes(validationMessage.getAttributes()); - annotations.add(annotation); - } - } - return (IReconcileResult[]) annotations.toArray(new IReconcileResult[annotations.size()]); - } - - private String getSeverity(IMessage validationMessage) { - String type = TemporaryAnnotation.ANNOT_INFO; - switch (validationMessage.getSeverity()) { - case IMessage.HIGH_SEVERITY : - type = TemporaryAnnotation.ANNOT_ERROR; - break; - case IMessage.NORMAL_SEVERITY : - type = TemporaryAnnotation.ANNOT_WARNING; - break; - case IMessage.LOW_SEVERITY : - type = TemporaryAnnotation.ANNOT_WARNING; - break; - case IMessage.ERROR_AND_WARNING : - type = TemporaryAnnotation.ANNOT_WARNING; - break; - } - return type; - } - - private IFile getFile() { - IModelManager modelManager = StructuredModelManager.getModelManager(); - IStructuredModel model = null; - IFile file = null; - if(modelManager != null) { - try { - model = modelManager.getExistingModelForRead(getDocument()); - if (model != null) { - String baseLocation = model.getBaseLocation(); - // The baseLocation may be a path on disk or relative to the - // workspace root. Don't translate on-disk paths to - // in-workspace resources. - IPath basePath = new Path(baseLocation); - if (basePath.segmentCount() > 1 && !basePath.toFile().exists()) { - file = ResourcesPlugin.getWorkspace().getRoot().getFile(basePath); - } - } - } - finally { - if (model != null) { - model.releaseFromRead(); - } - } - } - return file; - } - - private IncrementalHelper getHelper(IProject project) { - if (fHelper == null) - fHelper = new IncrementalHelper(getDocument(), project); - return fHelper; - } - - private IncrementalReporter getReporter() { - if (fReporter == null) - fReporter = new IncrementalReporter(getProgressMonitor()); - return fReporter; - } - - /** - * If this validator is partial or total - * - * @return - */ - public int getScope() { - return fScope; - } - - public void initialReconcile() { - // do nothing - } - - protected IReconcileResult[] reconcileModel(DirtyRegion dirtyRegion, IRegion subRegion) { - if (DEBUG) - System.out.println("[trace reconciler] > reconciling model in VALIDATOR step w/ dirty region: [" + dirtyRegion.getText() + "]"); //$NON-NLS-1$ //$NON-NLS-2$ - - IReconcileResult[] results = EMPTY_RECONCILE_RESULT_SET; - if (dirtyRegion != null) { - try { - // https://bugs.eclipse.org/bugs/show_bug.cgi?id=247714 - if (fValidator instanceof ISourceValidator && getScope() == ReconcileAnnotationKey.PARTIAL) { - results = validate(dirtyRegion, subRegion); - } - else { - results = validate(); - } - } - catch (Exception ex) { - Logger.logException("EXEPTION IN RECONCILE STEP FOR VALIDATOR", ex); //$NON-NLS-1$ - } - } - - if (DEBUG) - System.out.println("[trace reconciler] > VALIDATOR step done"); //$NON-NLS-1$ - - return results; - } - - public String toString() { - StringBuffer debugString = new StringBuffer("ValidatorStep: "); //$NON-NLS-1$ - if (fValidator != null) - debugString.append(fValidator.toString()); - return debugString.toString(); - } - - protected IReconcileResult[] validate() { - IReconcileResult[] results = EMPTY_RECONCILE_RESULT_SET; - - IFile file = getFile(); - IncrementalReporter reporter = null; - - try { - IncrementalHelper helper = getHelper(file != null ? file.getProject() : null); - - if (file != null && file.isAccessible()) { - helper.setURI(file.getFullPath().toString()); - } - else { - String uri = getURI(); - if (uri != null) { - helper.setURI(uri); - } - } - - reporter = getReporter(); - fValidator.validate(helper, reporter); - - // results = createAnnotations(reporter.getMessages()); - results = createAnnotations(reporter.getAnnotationInfo()); - reporter.removeAllMessages(fValidator); - - } - catch (Exception e) { - Logger.logException(e); - } - finally { - fValidator.cleanup(reporter); - } - return results; - } - - /** - * @return - */ - private String getURI() { - IStructuredModel model = null; - try { - model = StructuredModelManager.getModelManager().getExistingModelForRead(getDocument()); - if (model != null && !(IModelManager.UNMANAGED_MODEL.equals(model.getBaseLocation()))) { - return model.getBaseLocation(); - } - } - finally { - if (model != null) { - model.releaseFromRead(); - } - } - return null; - } - - public void setInputModel(IReconcilableModel inputModel) { - if (inputModel instanceof DocumentAdapter) { - IDocument document = ((DocumentAdapter) inputModel).getDocument(); - if (document != null) { - if (fValidator instanceof ISourceValidator) { - // notify that document connecting - ((ISourceValidator) fValidator).connect(document); - } - } - } - super.setInputModel(inputModel); - } - - public void release() { - if (fValidator instanceof ISourceValidator) { - IDocument document = getDocument(); - if (document != null) { - // notify that document disconnecting - ((ISourceValidator) fValidator).disconnect(document); - } - fValidator.cleanup(getReporter()); - } - super.release(); - } - - protected IReconcileResult[] validate(DirtyRegion dirtyRegion, IRegion subRegion) { - IReconcileResult[] results = EMPTY_RECONCILE_RESULT_SET; - - IFile file = getFile(); - - try { - IncrementalHelper helper = getHelper(file != null ? file.getProject() : null); - /* - * Setting the URI isn't necessary for all source validators, we - * can still continue without it - */ - if (file != null && file.exists()) { - helper.setURI(file.getFullPath().toString()); - } - - if (fValidator instanceof ISourceValidator) { - IncrementalReporter reporter = getReporter(); - if (getScope() == IReconcileAnnotationKey.PARTIAL) - ((ISourceValidator) fValidator).validate(dirtyRegion, helper, reporter); - else - ((ISourceValidator) fValidator).validate(new Region(0, getDocument().getLength()), helper, reporter); - /* - * call IValidator.cleanup() during release() because this - * validator might be called again on a different region - */ - // results = createAnnotations(reporter.getMessages()); - results = createAnnotations(reporter.getAnnotationInfo()); - reporter.removeAllMessages(fValidator); - } - } - catch (Exception e) { - Logger.logException(e); - } - return results; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/validator/ValidatorBuilder.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/validator/ValidatorBuilder.java deleted file mode 100644 index e1f6ccee48..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/validator/ValidatorBuilder.java +++ /dev/null @@ -1,139 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.reconcile.validator; - -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.core.runtime.IConfigurationElement; -import org.eclipse.core.runtime.IExtensionRegistry; -import org.eclipse.core.runtime.Platform; -import org.eclipse.wst.sse.ui.internal.Logger; -import org.eclipse.wst.sse.ui.internal.extension.RegistryReader; - - -/** - * Based off of TransferBuilder. Reads the extension point for - * <code>org.eclipse.wst.sse.ui.extensions.sourcevalidation</code> - */ -public class ValidatorBuilder extends RegistryReader { - - public static final String ATT_CLASS = "class"; //$NON-NLS-1$ - public static final String ATT_ID = "id"; //$NON-NLS-1$ - public static final String ATT_SCOPE = "scope"; //$NON-NLS-1$ - - public static final ValidatorMetaData[] EMTPY_VMD_ARRAY = new ValidatorMetaData[0]; - - // extension point ID - public static final String PL_SOURCE_VALIDATION = "sourcevalidation"; //$NON-NLS-1$ - - public static final String PLUGIN_ID = "org.eclipse.wst.sse.ui"; //$NON-NLS-1$ - public static final String TAG_CONTENT_TYPE_IDENTIFIER = "contentTypeIdentifier"; //$NON-NLS-1$ - public static final String TAG_PARTITION_TYPE = "partitionType"; //$NON-NLS-1$ - - public static final String TAG_VALIDATOR = "validator"; //$NON-NLS-1$ - - public static final String TRACE_FILTER = "reconcile_validator"; //$NON-NLS-1$ - - public static final String TRUE = "true"; //$NON-NLS-1$ - private String fCurrentCTID; - private ValidatorMetaData fCurrentVMD = null; - private List fVmds = new ArrayList(); - protected String targetContributionTag; - protected String targetID; - - private final String UNKNOWN = "???"; //$NON-NLS-1$ - - /** - * Returns the name of the part ID attribute that is expected in the - * target extension. - * - * @param element - * @return String - */ - protected String getID(IConfigurationElement element) { - String value = element.getAttribute(ATT_ID); - return value != null ? value : UNKNOWN; //$NON-NLS-1$ - } - - protected String getValidatorClass(IConfigurationElement element) { - String value = element.getAttribute(ATT_CLASS); - return value != null ? value : UNKNOWN; //$NON-NLS-1$ - } - - /** - * @param editorId - * @return Transfer[] - */ - public ValidatorMetaData[] getValidatorMetaData(String editorId) { - readContributions(editorId, TAG_VALIDATOR, PL_SOURCE_VALIDATION); - return (ValidatorMetaData[]) fVmds.toArray(new ValidatorMetaData[fVmds.size()]); - } - - protected String getValidatorScope(IConfigurationElement element) { - String value = element.getAttribute(ATT_SCOPE); - return value != null ? value : UNKNOWN; //$NON-NLS-1$ - } - - /** - * Reads the contributions from the registry for the provided workbench - * part and the provided extension point ID. - * - * @param id - * @param tag - * @param extensionPoint - */ - protected void readContributions(String id, String tag, String extensionPoint) { - targetID = id; - targetContributionTag = tag; - IExtensionRegistry registry = Platform.getExtensionRegistry(); - readRegistry(registry, PLUGIN_ID, extensionPoint); - } - - protected boolean readElement(IConfigurationElement element) { - String tag = element.getName(); - //ie. targetContributionTag == validator - if (tag.equals(targetContributionTag)) { - String vId = getID(element); - String vClass = getValidatorClass(element); - String vScope = getValidatorScope(element); - - if (vId == null) { - // This is not of interest to us - don't go deeper - return true; - } - // start building a VMD - fCurrentVMD = new ValidatorMetaData(element, vId, vClass, vScope); - fVmds.add(fCurrentVMD); - - if (Logger.isTracing(ValidatorBuilder.TRACE_FILTER)) - System.out.println("added reconcile validator: " + vId + ":" + vClass + ":" + vScope); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } else if (tag.equals(TAG_CONTENT_TYPE_IDENTIFIER)) { - // add to current VMD - fCurrentCTID = getID(element); - fCurrentVMD.addContentTypeId(fCurrentCTID); - } else if (tag.equals(TAG_PARTITION_TYPE)) { - // add to current VMD - String partitionType = getID(element); - fCurrentVMD.addParitionType(fCurrentCTID, partitionType); - - return true; - } else { - return false; - } - - readElementChildren(element); - return true; - } -} - diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/validator/ValidatorMetaData.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/validator/ValidatorMetaData.java deleted file mode 100644 index 8a412c1d54..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/validator/ValidatorMetaData.java +++ /dev/null @@ -1,241 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2006 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.reconcile.validator; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IConfigurationElement; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.content.IContentType; -import org.eclipse.core.runtime.content.IContentTypeManager; -import org.eclipse.swt.custom.BusyIndicator; -import org.eclipse.wst.sse.ui.internal.Logger; -import org.eclipse.wst.sse.ui.internal.reconcile.ReconcileAnnotationKey; -import org.eclipse.wst.validation.internal.provisional.core.IValidator; -import org.osgi.framework.Bundle; - - -/** - * Object that holds information relevant to the creation of a validator for - * the reconciling framework. - * - * @author pavery,nitind - */ -public class ValidatorMetaData { - private String fClass = null; - private IConfigurationElement fConfigurationElement = null; - private String fId = null; - private String fScope; - - // a hash map of explicitly declared content type Ids (String) that points to lists of - // partition types (List of Strings) - // contentTypeId -> List(paritionType, paritionType, partitionType, ...) - // contentTypeId2 -> List(partitionType, partitionType, ...) - // ... - private HashMap fMatrix = null; - - public ValidatorMetaData(IConfigurationElement element, String vId, String vClass, String vScope) { - fId = vId; - fClass = vClass; - fConfigurationElement = element; - fScope = vScope; - fMatrix = new HashMap(); - } - - /** - * TODO: This exact method is also in ValidatorStrategy. Should be in a common place. - * - * @param contentTypeId - * @return - */ - private String[] calculateParentContentTypeIds(String contentTypeId) { - - Set parentTypes = new HashSet(); - - IContentTypeManager ctManager = Platform.getContentTypeManager(); - IContentType ct = ctManager.getContentType(contentTypeId); - String id = contentTypeId; - - while(ct != null && id != null) { - - parentTypes.add(id); - ct = ctManager.getContentType(id); - if(ct != null) { - IContentType baseType = ct.getBaseType(); - id = (baseType != null) ? baseType.getId() : null; - } - } - return (String[])parentTypes.toArray(new String[parentTypes.size()]); - } - - public void addContentTypeId(String contentTypeId) { - if (!fMatrix.containsKey(contentTypeId)) - fMatrix.put(contentTypeId, new ArrayList()); - } - - public void addParitionType(String contentTypeId, String partitionType) { - if (!fMatrix.containsKey(contentTypeId)) - fMatrix.put(contentTypeId, new ArrayList()); - - List partitionList = (List) fMatrix.get(contentTypeId); - partitionList.add(partitionType); - } - - /** - * @param contentType - * @return whether this validator explicitly declared that it could handle - * this content type or any of its parent content types - */ - public boolean canHandleContentType(String contentType) { - // need to iterate hierarchy - String[] contentHierarchy = calculateParentContentTypeIds(contentType); - for (int i = 0; i < contentHierarchy.length; i++) { - if(fMatrix.containsKey(contentHierarchy[i])) - return true; - } - return false; - } - - /** - * @param contentType - * @return whether this validator explicitly declared that it could handle - * this content type - */ - public boolean mustHandleContentType(String contentType) { - return fMatrix.containsKey(contentType); - } - - /** - * @param contentTypeIds - * @param partitionType - * @return whether this validator declared that it could handle this - * content type, or one of its parent content types, and partition - * type - */ - public boolean canHandlePartitionType(String contentTypeIds[], String paritionType) { - for(int i=0; i<contentTypeIds.length; i++) { - List partitions = (List) fMatrix.get(contentTypeIds[i]); - if (partitions != null) { - for (int j = 0; j < partitions.size(); j++) { - if (paritionType.equals(partitions.get(j))) - return true; - } - } - } - return false; - } - - /** - * @param element - * @param classAttribute - * @return Object - * @throws CoreException - */ - Object createExecutableExtension(final IConfigurationElement element, final String classAttribute) throws CoreException { - Object obj = null; - obj = element.createExecutableExtension(classAttribute); - return obj; - } - - /** - * Creates an extension. If the extension plugin has not been loaded a - * busy cursor will be activated during the duration of the load. - * - * @param element - * @param classAttribute - * @return Object - * @throws CoreException - */ - public Object createExtension() { - // If plugin has been loaded create extension. - // Otherwise, show busy cursor then create extension. - final IConfigurationElement element = getConfigurationElement(); - final Object[] result = new Object[1]; - String pluginId = element.getDeclaringExtension().getNamespace(); - Bundle bundle = Platform.getBundle(pluginId); - if (bundle.getState() == Bundle.ACTIVE) { - try { - return createExecutableExtension(element, "class"); //$NON-NLS-1$ - } catch (CoreException e) { - handleCreateExecutableException(result, e); - } - } else { - BusyIndicator.showWhile(null, new Runnable() { - public void run() { - try { - result[0] = createExecutableExtension(element, "class"); //$NON-NLS-1$ - } catch (Exception e) { - handleCreateExecutableException(result, e); - } - } - }); - } - return result[0]; - } - - /** - * @return a validator instance based on this ValidatorMetaData instance - */ - public IValidator createValidator() { - Object obj = null; - obj = createExtension(); - if (obj == null) { - return null; - } - return (obj instanceof IValidator) ? (IValidator) obj : null; - } - - public IConfigurationElement getConfigurationElement() { - return fConfigurationElement; - } - - public String getValidatorClass() { - return fClass; - } - - public String getValidatorId() { - return fId; - } - - /** - * @param result - * @param e - */ - void handleCreateExecutableException(Object[] result, Throwable e) { - Logger.logException(e); - e.printStackTrace(); - result[0] = null; - } - /** - * ReconcileAnnotationKey.TOTAL or ReconcileAnnotationKey.PARTIAL - * @return - */ - public int getValidatorScope() { - return fScope.equalsIgnoreCase("total") ? ReconcileAnnotationKey.TOTAL : ReconcileAnnotationKey.PARTIAL; //$NON-NLS-1$ - } - - /** - * @see java.lang.Object#toString() - */ - public String toString() { - StringBuffer debugString = new StringBuffer("ValidatorMetaData:"); //$NON-NLS-1$ - if (fId != null) - debugString.append(" [id:" + fId + "]"); //$NON-NLS-1$ //$NON-NLS-2$ - return debugString.toString(); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/validator/ValidatorStrategy.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/validator/ValidatorStrategy.java deleted file mode 100644 index 6ce02c0f58..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/validator/ValidatorStrategy.java +++ /dev/null @@ -1,363 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2011 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.reconcile.validator; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import org.eclipse.core.filebuffers.FileBuffers; -import org.eclipse.core.filebuffers.ITextFileBuffer; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.content.IContentType; -import org.eclipse.core.runtime.content.IContentTypeManager; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.ITypedRegion; -import org.eclipse.jface.text.reconciler.DirtyRegion; -import org.eclipse.jface.text.reconciler.IReconcileResult; -import org.eclipse.jface.text.reconciler.IReconcileStep; -import org.eclipse.jface.text.source.ISourceViewer; -import org.eclipse.wst.sse.core.utils.StringUtils; -import org.eclipse.wst.sse.ui.internal.IReleasable; -import org.eclipse.wst.sse.ui.internal.Logger; -import org.eclipse.wst.sse.ui.internal.reconcile.DocumentAdapter; -import org.eclipse.wst.sse.ui.internal.reconcile.ReconcileAnnotationKey; -import org.eclipse.wst.sse.ui.internal.reconcile.StructuredTextReconcilingStrategy; -import org.eclipse.wst.sse.ui.internal.reconcile.TemporaryAnnotation; -import org.eclipse.wst.validation.ValidationFramework; -import org.eclipse.wst.validation.Validator; -import org.eclipse.wst.validation.internal.provisional.core.IValidator; - - -/** - * Special validator strategy. Runs validator steps contributed via the - * <code>org.eclipse.wst.sse.ui.extensions.sourcevalidation</code> extension - * point - * - * @author pavery - */ -public class ValidatorStrategy extends StructuredTextReconcilingStrategy { - - private static final boolean DEBUG_VALIDATION_CAPABLE_BUT_DISABLED = Boolean.valueOf(Platform.getDebugOption("org.eclipse.wst.sse.ui/debug/reconcilerValidatorEnablement")).booleanValue(); - private static final boolean DEBUG_VALIDATION_UNSUPPORTED = Boolean.valueOf(Platform.getDebugOption("org.eclipse.wst.sse.ui/debug/reconcilerValidatorSupported")).booleanValue(); - private static final Object NO_FILE = new Object(); - - private String[] fContentTypeIds = null; - private List fMetaData = null; - /** validator id (as declared in ext point) -> ReconcileStepForValidator * */ - private HashMap fVidToVStepMap = null; - - /* - * List of ValidatorMetaDatas of total scope validators that have been run - * since beginProcessing() was called. - */ - private List fTotalScopeValidatorsAlreadyRun = new ArrayList(); - - /* - * Whether the Validation Framework has indicated that validation is - * suspended for the current resource - */ - private boolean fValidatorsSuspended = false; - private Object fFile; - private boolean fIsCancelled = false; - - public ValidatorStrategy(ISourceViewer sourceViewer, String contentType) { - super(sourceViewer); - fMetaData = new ArrayList(); - fContentTypeIds = calculateParentContentTypeIds(contentType); - fVidToVStepMap = new HashMap(); - } - - public void addValidatorMetaData(ValidatorMetaData vmd) { - fMetaData.add(vmd); - } - - public void beginProcessing() { - fTotalScopeValidatorsAlreadyRun.clear(); - } - - /** - * The content type passed in should be the most specific one. TODO: This - * exact method is also in ValidatorMetaData. Should be in a common place. - * - * @param contentType - * @return - */ - private String[] calculateParentContentTypeIds(String contentTypeId) { - - Set parentTypes = new HashSet(); - - IContentTypeManager ctManager = Platform.getContentTypeManager(); - IContentType ct = ctManager.getContentType(contentTypeId); - String id = contentTypeId; - - while (ct != null && id != null) { - - parentTypes.add(id); - ct = ctManager.getContentType(id); - if (ct != null) { - IContentType baseType = ct.getBaseType(); - id = (baseType != null) ? baseType.getId() : null; - } - } - return (String[]) parentTypes.toArray(new String[parentTypes.size()]); - } - - protected boolean canHandlePartition(String partitionType) { - ValidatorMetaData vmd = null; - for (int i = 0; i < fMetaData.size(); i++) { - vmd = (ValidatorMetaData) fMetaData.get(i); - if (vmd.canHandlePartitionType(getContentTypeIds(), partitionType)) - return true; - } - return false; - } - - protected boolean containsStep(IReconcileStep step) { - return fVidToVStepMap.containsValue(step); - } - - /** - * @see org.eclipse.wst.sse.ui.internal.provisional.reconcile.AbstractStructuredTextReconcilingStrategy#createReconcileSteps() - */ - public void createReconcileSteps() { - // do nothing, steps are created - } - - public void endProcessing() { - fTotalScopeValidatorsAlreadyRun.clear(); - } - - /** - * All content types on which this ValidatorStrategy can run - * - * @return - */ - public String[] getContentTypeIds() { - return fContentTypeIds; - } - - /** - * @param tr - * Partition of the region to reconcile. - * @param dr - * Dirty region representation of the typed region - */ - public void reconcile(ITypedRegion tr, DirtyRegion dr) { - /* - * Abort if no workspace file is known (new validation framework does - * not support that scenario) or no validators have been specified - */ - if (isCanceled() || fMetaData.isEmpty() || fValidatorsSuspended) - return; - - IDocument doc = getDocument(); - // for external files, this can be null - if (doc == null) - return; - - String partitionType = tr.getType(); - - ValidatorMetaData vmd = null; - List annotationsToAdd = new ArrayList(); - List stepsRanOnThisDirtyRegion = new ArrayList(1); - - /* - * Keep track of the disabled validators by source id for the V2 - * validators. - */ - Set disabledValsBySourceId = new HashSet(20); - - /* - * Keep track of the disabled validators by class id for the v1 - * validators. - */ - Set disabledValsByClass = new HashSet(20); - IFile file = getFile(); - if (file != null) { - if(!file.isAccessible()) - return; - - Collection disabledValidators = null; - try { - /* - * Take extra care when calling this external code, as it - * can indirectly cause bundles to start - */ - disabledValidators = ValidationFramework.getDefault().getDisabledValidatorsFor(file); - } - catch (Exception e) { - Logger.logException(e); - } - - if (disabledValidators != null) { - for (Iterator it = disabledValidators.iterator(); it.hasNext();) { - Validator v = (Validator) it.next(); - Validator.V1 v1 = null; - try { - v1 = v.asV1Validator(); - } - catch (Exception e) { - Logger.logException(e); - } - if (v1 != null) - disabledValsByClass.add(v1.getId()); - // not a V1 validator - else if (v.getSourceId() != null) { - //could be more then one sourceid per batch validator - String[] sourceIDs = StringUtils.unpack(v.getSourceId()); - disabledValsBySourceId.addAll(Arrays.asList(sourceIDs)); - } - } - } - } - - /* - * Loop through all of the relevant validator meta data to find - * supporting validators for this partition type. Don't check - * this.canHandlePartition() before-hand since it just loops through - * and calls vmd.canHandlePartitionType()...which we're already doing - * here anyway to find the right vmd. - */ - for (int i = 0; i < fMetaData.size() && !isCanceled(); i++) { - vmd = (ValidatorMetaData) fMetaData.get(i); - if (vmd.canHandlePartitionType(getContentTypeIds(), partitionType)) { - /* - * Check if validator is enabled according to validation - * preferences before attempting to create/use it - */ - if (!disabledValsBySourceId.contains(vmd.getValidatorId()) && !disabledValsByClass.contains(vmd.getValidatorClass())) { - if (DEBUG_VALIDATION_UNSUPPORTED) { - Logger.log(Logger.INFO, "Source validator "+vmd.getValidatorId()+" handling (content types:[" + StringUtils.pack(getContentTypeIds()) + "] partition type:" + partitionType); - } - int validatorScope = vmd.getValidatorScope(); - ReconcileStepForValidator validatorStep = null; - // get step for partition type - Object o = fVidToVStepMap.get(vmd.getValidatorId()); - if (o != null) { - validatorStep = (ReconcileStepForValidator) o; - } - else { - // if doesn't exist, create one - IValidator validator = vmd.createValidator(); - - validatorStep = new ReconcileStepForValidator(validator, validatorScope); - validatorStep.setInputModel(new DocumentAdapter(doc)); - - fVidToVStepMap.put(vmd.getValidatorId(), validatorStep); - } - - if (!fTotalScopeValidatorsAlreadyRun.contains(vmd) && !fIsCancelled) { - annotationsToAdd.addAll(Arrays.asList(validatorStep.reconcile(dr, dr))); - stepsRanOnThisDirtyRegion.add(validatorStep); - - if (validatorScope == ReconcileAnnotationKey.TOTAL) { - // mark this validator as "run" - fTotalScopeValidatorsAlreadyRun.add(vmd); - } - } - } - else if (DEBUG_VALIDATION_CAPABLE_BUT_DISABLED) { - String message = "Source validator able (id:" + vmd.getValidatorId() + " class:" + vmd.getValidatorClass() + " but skipped because it was reported as disabled"; - Logger.log(Logger.INFO, message); - } - } - else if (DEBUG_VALIDATION_UNSUPPORTED) { - Logger.log(Logger.INFO, "Source validator "+vmd.getValidatorId()+" can not handle (content types:[" + StringUtils.pack(getContentTypeIds()) + "] partition type:" + partitionType); - } - } - - TemporaryAnnotation[] annotationsToRemove = getAnnotationsToRemove(dr, stepsRanOnThisDirtyRegion); - if (annotationsToRemove.length + annotationsToAdd.size() > 0 && !fIsCancelled) - smartProcess(annotationsToRemove, (IReconcileResult[]) annotationsToAdd.toArray(new IReconcileResult[annotationsToAdd.size()])); - } - - public void release() { - super.release(); - fIsCancelled = true; - Iterator it = fVidToVStepMap.values().iterator(); - IReconcileStep step = null; - while (it.hasNext()) { - step = (IReconcileStep) it.next(); - if (step instanceof IReleasable) - ((IReleasable) step).release(); - } - fFile = null; - } - - /** - * @see org.eclipse.wst.sse.ui.internal.reconcile.AbstractStructuredTextReconcilingStrategy#setDocument(org.eclipse.jface.text.IDocument) - */ - public void setDocument(IDocument document) { - super.setDocument(document); - - fFile = null; - - try { - fValidatorsSuspended = false; - if (document != null) { - IFile file = getFile(); - if (file != null) { - // Validation is suspended for this resource, do nothing - fValidatorsSuspended = !file.isAccessible() || ValidationFramework.getDefault().isSuspended(file.getProject()) || ValidationFramework.getDefault().getProjectSettings(file.getProject()).getSuspend(); - } - } - } - catch (Exception e) { - fValidatorsSuspended = true; - Logger.logException(e); - } - - // validator steps are in "fVIdToVStepMap" (as opposed to fFirstStep > - // next step etc...) - Iterator it = fVidToVStepMap.values().iterator(); - IReconcileStep step = null; - while (it.hasNext()) { - step = (IReconcileStep) it.next(); - step.setInputModel(new DocumentAdapter(document)); - } - } - - /** - * Gets IFile from current document - * - * @return IFile the IFile, null if no such file exists - */ - private IFile getFile() { - if (fFile == null) { - fFile = NO_FILE; - ITextFileBuffer buffer = FileBuffers.getTextFileBufferManager().getTextFileBuffer(getDocument()); - if (buffer != null && buffer.getLocation() != null) { - IPath path = buffer.getLocation(); - if (path.segmentCount() > 1) { - IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(path); - if (file.isAccessible()) { - fFile = file; - } - } - } - } - - if (fFile != NO_FILE) - return (IFile) fFile; - return null; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/rules/PresentationCollector.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/rules/PresentationCollector.java deleted file mode 100644 index e79a989ff4..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/rules/PresentationCollector.java +++ /dev/null @@ -1,86 +0,0 @@ -/*******************************************************************************
- * Copyright (c) 2009, 2011 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.wst.sse.ui.internal.rules;
-
-import java.util.AbstractCollection;
-import java.util.Iterator;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.text.TextPresentation;
-import org.eclipse.swt.custom.StyleRange;
-import org.eclipse.wst.sse.ui.internal.Logger;
-
-/**
- * Passed to LineStyleProviders as the Collection for which StyleRanges are to
- * be added. This class provides additional sanity checks on the incoming
- * StyleRanges so that we do not rely upon SWT to report Errors with no record
- * of the StyleRange or contributing LineStyleProvider, as well as a slight
- * performance increase by not allocating a redundant collection for the
- * StyleRanges.
- *
- * This class intentionally violates the contract for java.util.Collection.
- */
-
-class PresentationCollector extends AbstractCollection {
- private final TextPresentation fPresentation;
- private int lastOffset;
-
- /**
- * @param presentation
- * - the Presentation being added to
- * @param applyOnAdd
- */
- PresentationCollector(TextPresentation presentation) {
- super();
- Assert.isNotNull(presentation);
- fPresentation = presentation;
- lastOffset = 0;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see java.util.Collection#add(java.lang.Object)
- */
- public boolean add(Object o) {
- StyleRange range = (StyleRange) o;
- if (lastOffset > range.start) {
- Logger.log(Logger.ERROR, "Overlapping start in StyleRange " + range.start + ":" + range.length); //$NON-NLS-1$ //$NON-NLS-2$
- return false;
- }
- else if (range.length < 0) {
- Logger.log(Logger.ERROR, "StyleRange with negative length" + range.start + ":" + range.length); //$NON-NLS-1$ //$NON-NLS-2$
- return false;
- }
- lastOffset = range.start + range.length;
- fPresentation.addStyleRange(range);
- return true;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see java.util.AbstractCollection#iterator()
- */
- public Iterator iterator() {
- return fPresentation.getNonDefaultStyleRangeIterator();
- }
-
- /*
- * (non-Javadoc)
- *
- * @see java.util.AbstractCollection#size()
- */
- public int size() {
- throw new UnsupportedOperationException();
- }
-}
\ No newline at end of file diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/rules/StructuredDocumentDamagerRepairer.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/rules/StructuredDocumentDamagerRepairer.java deleted file mode 100644 index f5973d8858..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/rules/StructuredDocumentDamagerRepairer.java +++ /dev/null @@ -1,56 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.wst.sse.ui.internal.rules; - -import org.eclipse.core.runtime.Assert; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.ITypedRegion; -import org.eclipse.jface.text.TextPresentation; -import org.eclipse.jface.text.rules.DefaultDamagerRepairer; -import org.eclipse.jface.text.rules.RuleBasedScanner; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument; -import org.eclipse.wst.sse.ui.internal.provisional.style.AbstractLineStyleProvider; -import org.eclipse.wst.sse.ui.internal.provisional.style.LineStyleProvider; - -/** - * An implementation of a presentation damager and presentation repairer. - * It uses a LineStyleProvider to retrieve the style ranges associated with - * the calculated damaged region. - * - * @see LineStyleProvider - */ -public class StructuredDocumentDamagerRepairer extends DefaultDamagerRepairer { - - private LineStyleProvider fProvider = null; - - public StructuredDocumentDamagerRepairer(LineStyleProvider provider) { - super(new RuleBasedScanner()); - Assert.isNotNull(provider); - fProvider = provider; - } - - public void createPresentation(TextPresentation presentation, ITypedRegion region) { - PresentationCollector collector = new PresentationCollector(presentation); - fProvider.prepareRegions(region, region.getOffset(), region.getLength(), collector); - } - - public void setProvider(LineStyleProvider provider) { - fProvider = provider; - } - - public void setDocument(IDocument document) { - super.setDocument(document); - if (fProvider instanceof AbstractLineStyleProvider) - ((AbstractLineStyleProvider) fProvider).setDocument( (IStructuredDocument) document); - } - -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/search/BasicSearchLabelProvider.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/search/BasicSearchLabelProvider.java deleted file mode 100644 index c20f38ae65..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/search/BasicSearchLabelProvider.java +++ /dev/null @@ -1,154 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.search; - -import org.eclipse.jface.resource.JFaceResources; -import org.eclipse.jface.viewers.LabelProvider; -import org.eclipse.jface.viewers.StyledString; -import org.eclipse.jface.viewers.DelegatingStyledCellLabelProvider.IStyledLabelProvider; -import org.eclipse.jface.viewers.StyledString.Styler; -import org.eclipse.search.ui.text.AbstractTextSearchViewPage; -import org.eclipse.search.ui.text.Match; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.graphics.RGB; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; -import org.eclipse.wst.sse.ui.internal.editor.EditorPluginImageHelper; -import org.eclipse.wst.sse.ui.internal.editor.EditorPluginImages; - -import com.ibm.icu.text.MessageFormat; - -/** - * <p>The label provider designed for use with <code>BasicSearchMatchElement</code><p> - * - * <p>Displays in the format of:<br/> - * lineNum: Message (# matches)</br> - * 1: <a></a> (2 matches)</p> - */ -public class BasicSearchLabelProvider extends LabelProvider implements IStyledLabelProvider { - /** - * ID of match highlighting background color - */ - private static final String MATCH_BG_ID = "org.eclipse.wst.sse.ui.search.MATCH_BG"; - - //register the match highlighting background color once - static { - JFaceResources.getColorRegistry().put(MATCH_BG_ID, new RGB(206, 204, 247)); - } - - /** - * Match highlighting background color styler - */ - private static final Styler HIGHLIGHT_WRITE_STYLE= StyledString.createColorRegistryStyler(null, MATCH_BG_ID); - - - /** - * Need the page if want to determine the number of matches, but this can be <code>null</code> - */ - private AbstractTextSearchViewPage fPage; - - /** - * <p>Construct the provider without a <code>AbstractTextSearchViewPage</code><p> - * <p><b>NOTE:</b>If this constructor is used then the provider will not be able to determine - * the number of matches that are all on the same line for a given element</p> - */ - public BasicSearchLabelProvider() { - this(null); - } - - /** - * <p>Construct the provider with a <code>AbstractTextSearchViewPage</code> so that the - * number of matches that are all on the same line for a given element can be determined.</p> - * - * @param page Will be used to determine the number of matches that are all on the same line - */ - public BasicSearchLabelProvider(AbstractTextSearchViewPage page) { - fPage= page; - } - - /** - * @see org.eclipse.jface.viewers.LabelProvider#getImage(java.lang.Object) - */ - public Image getImage(Object element) { - return EditorPluginImageHelper.getInstance().getImage(EditorPluginImages.IMG_OBJ_OCC_MATCH); - } - - /** - * <p><b>Note:</b> Because this class implements <code>IStyledLabelProvider</code> the <code>getStyledText</code> - * function should be being called and not this one, but better save then sorry</p> - * - * @see org.eclipse.jface.viewers.LabelProvider#getText(java.lang.Object) - * @see org.eclipse.wst.sse.ui.internal.search.BasicSearchLabelProvider#getStyledText(Object) - */ - public final String getText(Object element) { - return getStyledText(element).getString(); - } - - /** - * <p>Given a <code>Match</code> object containing a <code>BasicSearchMatchElement</code> element - * returns a <code>StyledString</code> in the form of:</p> - * - * <p>lineNum: Message (# matches)</br> - * 1: <a></a> (2 matches)</p> - * - * @see org.eclipse.jface.viewers.DelegatingStyledCellLabelProvider.IStyledLabelProvider#getStyledText(java.lang.Object) - */ - public StyledString getStyledText(Object obj) { - StyledString styledText = new StyledString(); - BasicSearchMatchElement element = null; - if (obj instanceof Match) { - Match match = (Match) obj; - - if(match.getElement() instanceof BasicSearchMatchElement) { - element = (BasicSearchMatchElement) match.getElement(); - } - } else if(obj instanceof BasicSearchMatchElement) { - element = (BasicSearchMatchElement)obj; - } - - //get the match count if possible - int matchCount = 0; - Match[] matches = new Match[0]; - if(fPage != null) { - matches = fPage.getInput().getMatches(obj); - matchCount = matches.length; - } - - //if everything was of the right type create our formated message, - //else use the toString of the given object for the message - if(element != null) { - String message = element.getLine().trim(); //$NON-NLS-1$ - int trimedAmount = element.getLine().indexOf(message); - String lineNum = element.getLineNum() + 1 + ": "; //$NON-NLS-1$ - - styledText.append(lineNum, StyledString.QUALIFIER_STYLER); - styledText.append(message); - - //get the match count if possible - for(int i = 0; i < matchCount; ++i) { - int offset = matches[i].getOffset() - element.geLineOffset() + lineNum.length() - trimedAmount; - styledText.setStyle(offset, matches[i].getLength(), HIGHLIGHT_WRITE_STYLE); - } - - } else { - styledText.append(obj.toString()); - } - - //append the match count if its worth appending - if (matchCount > 1) { - String matchesMsg = " " + MessageFormat.format( - SSEUIMessages.TextSearchLabelProvider_matchCountFormat, - new Object[] { new Integer(matchCount) }); - styledText.append(matchesMsg, StyledString.COUNTER_STYLER); - } - - return styledText; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/search/BasicSearchMatchElement.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/search/BasicSearchMatchElement.java deleted file mode 100644 index 425c06ae4e..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/search/BasicSearchMatchElement.java +++ /dev/null @@ -1,116 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.search; - -import org.eclipse.core.resources.IFile; - -/** - * This is used as the element for a <code>Match</code> object by - * <code>BasicSearchQuery</code>. It contains all the needed information - * for use by the query, result providers, and label providers. - * - * @see org.eclipse.search.ui.text.Match - * @see org.eclipse.wst.sse.ui.internal.search.BasicSearchQuery - */ -public class BasicSearchMatchElement { - /** - * The file this element is a match on - */ - private IFile fFile; - - /** - * The line number this element is a match on - */ - private int fLineNumber; - - /** - * The offset of the line in the file - */ - private int fLineOffset; - - /** - * The line this match is on - */ - private String fLine; - - /** - * Constructor - * - * @param file The file this element is a match on - * @param lineNumber The line number this element is a match on - * @param lineOffset The offset of the line in the file - * @param message The message associated with this element - */ - public BasicSearchMatchElement(IFile file, int lineNumber, int lineOffset, String message) { - this.fFile = file; - this.fLineNumber = lineNumber; - this.fLineOffset = lineOffset; - this.fLine = message; - } - - /** - * @return The file this element is a match on - */ - public IFile getFile() { - return this.fFile; - } - - /** - * @return The line number this element is a match on - */ - public int getLineNum() { - return this.fLineNumber; - } - - /** - * @return the offset of the line the match is on in the file - */ - public int geLineOffset() { - return this.fLineOffset; - } - - /** - * @return The line this match is on - */ - public String getLine() { - return this.fLine; - } - - /** - * <p>Two <code>BasicSearchMatchElement</code> are equal if they are - * both on the same line. This helps with determining how many matches - * are all on the same line which is automatically taken care of by - * internal Eclipse search APIs so long as this equal method is structured - * thusly.</p> - * - * @see java.lang.Object#equals(java.lang.Object) - */ - public boolean equals(Object obj) { - boolean equal = false; - - if(obj instanceof BasicSearchMatchElement) { - equal = getLineNum() == ((BasicSearchMatchElement)obj).getLineNum(); - } - - return equal; - } - - /** - * Like the <code>#equals</code> method this function is needed so - * that the internal Eclipse search APIs can keep track of matches - * that are on the same line. - * - * @see java.lang.Object#hashCode() - */ - public int hashCode() { - return getLineNum() + getLine().hashCode(); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/search/BasicSearchQuery.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/search/BasicSearchQuery.java deleted file mode 100644 index 008eb336c4..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/search/BasicSearchQuery.java +++ /dev/null @@ -1,207 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2011 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.search; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Status; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.search.ui.ISearchQuery; -import org.eclipse.search.ui.ISearchResult; -import org.eclipse.search.ui.text.AbstractTextSearchResult; -import org.eclipse.search.ui.text.Match; -import org.eclipse.wst.sse.ui.internal.Logger; - - -/** - * Defines a basic search query. This query does not do anything, it needs to be extended - * and the <code>{@link #doQuery()}</code> method needs to be overridden to make the query - * actually be functional. - * - */ -public class BasicSearchQuery implements ISearchQuery { - /** - * the file we're searching - */ - private IFile fFile = null; - - /** - * The result of this query - */ - private AbstractTextSearchResult fResult = null; - - /** - * The progress monitor for the query - */ - private IProgressMonitor fProgressMonitor = null; - - /** - * <p>Construct a new basic query.</p> - * - * <p><b>IMPORTANT: </b>It is very important that after - * creating the query and <b>before</b> running the query - * that you call {@link #setResult(AbstractTextSearchResult)}. - * This is not a parameter because typically a search result needs - * a reference to its query and thus the query needs to be constructed - * before its result object can be set.</p> - * - * @param file the file this query will take place on - */ - public BasicSearchQuery(IFile file) { - this.fFile = file; - } - - /** - * Runs the query - * - * @see org.eclipse.search.ui.ISearchQuery#run(org.eclipse.core.runtime.IProgressMonitor) - */ - public IStatus run(IProgressMonitor monitor) { - fProgressMonitor = monitor; - return doQuery(); - } - - /** - * public to avoid synthetic method access from inner class - * - * @return - */ - public IFile getFile() { - return this.fFile; - } - - /** - * There is no default label for a basic query, - * this should be overridden by implementing classes - * - * @see org.eclipse.search.ui.ISearchQuery#getLabel() - */ - public String getLabel() { - return ""; //$NON-NLS-1$ - } - - /** - * <p>This will be <code>null</code> if {@link #setResult(AbstractTextSearchResult)} - * has not been called yet.</p> - * - * @see org.eclipse.search.ui.ISearchQuery#getSearchResult() - */ - public ISearchResult getSearchResult() { - return fResult; - } - - /** - * Adds a match to the results of this query. - * - * <p><b>IMPORTANT: </b>It is very important that after - * creating the query and <b>before</b> running the query - * that you call {@link #setResult(AbstractTextSearchResult)}. - * This is not a parameter because typically a search result needs - * a reference to its query and thus the query needs to be constructed - * before its result object can be set.</p> - * - * @param document the document the match is being added too - * @param matchStart the start character of the match - * @param matchEnd the end character of the match - */ - public void addMatch(IDocument document, int matchStart, int matchEnd) { - - try { - int lineNumber = document.getLineOfOffset(matchStart); - int lineStart = document.getLineOffset(lineNumber); - int lineLength = document.getLineLength(lineNumber); - - String elementMessage = document.get().substring(lineStart, lineStart + lineLength); - - //add the match to the result - BasicSearchMatchElement element = new BasicSearchMatchElement(fFile, lineNumber, lineStart, elementMessage); - fResult.addMatch(new Match(element, Match.UNIT_CHARACTER, matchStart, matchEnd - matchStart)); - - } catch (BadLocationException e) { - Logger.logException(e); - } - } - - /** - * <p><i>Note: </i> as of yet no testing has gone into whether this query - * can be re-run or not or what that even entails.<p> - * - * @see org.eclipse.search.ui.ISearchQuery#canRerun() - */ - public boolean canRerun() { - return false; - } - - /** - * <p>This query can be run in the background</p> - * - * @see org.eclipse.search.ui.ISearchQuery#canRunInBackground() - */ - public boolean canRunInBackground() { - return true; - } - - /** - * <p>The actual work of the query, called by {@link #run(IProgressMonitor)}</p> - * <p><i>Note: </i>This method should be overridden by implementers so that their query - * will actually do something</p> - * - * @return the status of the query when it has finished - * - * @deprecated use {@link #doQuery(IProgressMonitor)} so that the operation is cancelable - */ - protected IStatus doQuery() { - return doQuery(fProgressMonitor); - } - - /** - * <p>The actual work of the query, called by {@link #run(IProgressMonitor)}</p> - * <p><i>Note: </i>This method should be overridden by implementers so that their query - * will actually do something</p> - * - * @param monitor {@link IProgressMonitor} used to track progress and cancel the operation - * - * @return the status of the query when it has finished - */ - protected IStatus doQuery(IProgressMonitor monitor) { - return Status.OK_STATUS; - } - - /** - * @return the total number of matches this query found - */ - protected int getMatchCount() { - return fResult.getMatchCount(); - } - - /** - * <p>used in search result display labels, should be overridden by implementers</p> - * - * @return - */ - protected String getSearchText() { - return ""; //$NON-NLS-1$ - } - - /** - * <p>This <b>needs</b> to be called after constructing - * the query but before running it, see note on {@link #BasicSearchQuery(IFile)}</p> - * - * @param result the result this query will use to store its results - */ - protected void setResult(AbstractTextSearchResult result) { - this.fResult = result; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/search/FindOccurrencesActionDelegate.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/search/FindOccurrencesActionDelegate.java deleted file mode 100644 index ebc74e4d8f..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/search/FindOccurrencesActionDelegate.java +++ /dev/null @@ -1,168 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * - *******************************************************************************/ - -package org.eclipse.wst.sse.ui.internal.search; - -import java.util.Iterator; -import java.util.List; - -import org.eclipse.core.resources.IFile; -import org.eclipse.jface.action.IAction; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.ITextSelection; -import org.eclipse.jface.text.ITypedRegion; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.swt.widgets.Event; -import org.eclipse.ui.IActionDelegate2; -import org.eclipse.ui.IEditorActionDelegate; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.IFileEditorInput; -import org.eclipse.ui.IViewActionDelegate; -import org.eclipse.ui.IViewPart; -import org.eclipse.ui.texteditor.ITextEditor; -import org.eclipse.wst.sse.ui.StructuredTextEditor; -import org.eclipse.wst.sse.ui.internal.ExtendedConfigurationBuilder; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; -import org.eclipse.wst.sse.ui.internal.util.PlatformStatusLineUtil; - -/** - * Performs the appropriate FindOccurrencesProcessor action call based on - * selection. Clients can add processors for different partitions via - * <code>getProcessors</code> - * - */ -abstract public class FindOccurrencesActionDelegate implements IEditorActionDelegate, IActionDelegate2, IViewActionDelegate { - private IEditorPart fEditor; - - public void setActiveEditor(IAction action, IEditorPart targetEditor) { - fEditor = targetEditor; - } - - public void dispose() { - // nulling out just in case - fEditor = null; - } - - public void init(IAction action) { - if (action != null) { - action.setText(SSEUIMessages.FindOccurrences_label); - } - } - - public void runWithEvent(IAction action, Event event) { - run(action); - } - - public void run(IAction action) { - boolean okay = false; - if (fEditor instanceof ITextEditor) { - ITextEditor textEditor = (ITextEditor) fEditor; - IDocument document = textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput()); - if (document != null) { - ITextSelection textSelection = getTextSelection(textEditor); - FindOccurrencesProcessor findOccurrenceProcessor = getProcessorForCurrentSelection(document, textSelection); - if (findOccurrenceProcessor != null) { - if (textEditor.getEditorInput() instanceof IFileEditorInput) { - IFile file = ((IFileEditorInput) textEditor.getEditorInput()).getFile(); - okay = findOccurrenceProcessor.findOccurrences(document, textSelection, file); - } - } - } - } - if (okay) { - // clear status message - PlatformStatusLineUtil.clearStatusLine(); - } - else { - String errorMessage = SSEUIMessages.FindOccurrencesActionProvider_0; //$NON-NLS-1$ - if (fEditor instanceof StructuredTextEditor) { - PlatformStatusLineUtil.displayTemporaryErrorMessage(((StructuredTextEditor) fEditor).getTextViewer(), errorMessage); - - } - else { - PlatformStatusLineUtil.displayErrorMessage(errorMessage); - PlatformStatusLineUtil.addOneTimeClearListener(); - } - } - } - - public void init(IViewPart view) { - // do nothing - } - - public void selectionChanged(IAction action, ISelection selection) { - // clear status message - PlatformStatusLineUtil.clearStatusLine(); - } - - /** - * Get the appropriate find occurrences processor - * - * @param document - - * assumes not null - * @param textSelection - * @return - */ - private FindOccurrencesProcessor getProcessorForCurrentSelection(IDocument document, ITextSelection textSelection) { - // check if we have an action that's enabled on the current partition - ITypedRegion tr = getPartition(document, textSelection); - String partition = tr != null ? tr.getType() : ""; //$NON-NLS-1$ - - Iterator it = getProcessors().iterator(); - FindOccurrencesProcessor processor = null; - while (it.hasNext()) { - processor = (FindOccurrencesProcessor) it.next(); - // we just choose the first action that can handle the partition - if (processor.enabledForParitition(partition)) - return processor; - } - List extendedFindOccurrencesProcessors = ExtendedConfigurationBuilder.getInstance().getConfigurations(FindOccurrencesProcessor.class.getName(), partition); - for (int i = 0; i < extendedFindOccurrencesProcessors.size(); i++) { - Object o = extendedFindOccurrencesProcessors.get(i); - if (o instanceof FindOccurrencesProcessor) { - /* - * We just choose the first registered processor that - * explicitly says it can handle the partition - */ - processor = (FindOccurrencesProcessor) o; - if (processor.enabledForParitition(partition)) - return processor; - } - } - return null; - } - - private ITypedRegion getPartition(IDocument document, ITextSelection textSelection) { - ITypedRegion region = null; - if (textSelection != null) { - try { - region = document.getPartition(textSelection.getOffset()); - } - catch (BadLocationException e) { - region = null; - } - } - return region; - } - - private ITextSelection getTextSelection(ITextEditor textEditor) { - ITextSelection textSelection = null; - ISelection selection = textEditor.getSelectionProvider().getSelection(); - if (selection instanceof ITextSelection && !selection.isEmpty()) { - textSelection = (ITextSelection) selection; - } - return textSelection; - } - - abstract protected List getProcessors(); -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/search/FindOccurrencesProcessor.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/search/FindOccurrencesProcessor.java deleted file mode 100644 index dfe0917007..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/search/FindOccurrencesProcessor.java +++ /dev/null @@ -1,121 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * - *******************************************************************************/ - -package org.eclipse.wst.sse.ui.internal.search; - -import org.eclipse.core.resources.IFile; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.ITextSelection; -import org.eclipse.search.ui.ISearchQuery; -import org.eclipse.search.ui.NewSearchUI; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion; -import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegion; - -/** - * <p> - * Finds occurrences of a specified region type w/ region text in an - * IStructuredDocument. Clients must implement getPartitionTypes() and - * getRegionTypes() to indicate which partition types and region types it can - * operate on. - * </p> - * - * <p> - * Clients should override <code>getSearchQuery()</code> in order to provide - * their own type of "search" (eg. searching for XML start tags, searching for - * Java elements, etc...) - * </p> - * - */ -abstract public class FindOccurrencesProcessor { - public boolean findOccurrences(IDocument document, ITextSelection textSelection, IFile file) { - boolean findOccurrences = false; - - // determine if action should be enabled or not - if (document instanceof IStructuredDocument) { - IStructuredDocument structuredDocument = (IStructuredDocument) document; - IStructuredDocumentRegion sdRegion = structuredDocument.getRegionAtCharacterOffset(textSelection.getOffset()); - if (sdRegion != null) { - ITextRegion r = sdRegion.getRegionAtCharacterOffset(textSelection.getOffset()); - if (r != null) { - String type = r.getType(); - if (enabledForRegionType(type)) { - String matchText = sdRegion.getText(r); - - // first of all activate the view - NewSearchUI.activateSearchResultView(); - - if (matchText != null && type != null) { - ISearchQuery searchQuery = getSearchQuery(file, structuredDocument, matchText, type, textSelection); - if (searchQuery != null) { - if (searchQuery.canRunInBackground()) - NewSearchUI.runQueryInBackground(searchQuery); - else - NewSearchUI.runQueryInForeground(null, searchQuery); - } - findOccurrences = true; - } - } - } - } - } - return findOccurrences; - } - - /** - * @param regionType - * @return <code>true</code> if this action can operate on this region - * type (ITextRegion), otherwise false. - */ - protected boolean enabledForRegionType(String regionType) { - - String[] accept = getRegionTypes(); - for (int i = 0; i < accept.length; i++) { - if (regionType.equals(accept[i])) - return true; - } - return false; - } - - /** - * Clients should override this to enable find occurrences on certain - * partition(s). - */ - abstract protected String[] getPartitionTypes(); - - /** - * Clients should override this to enable find occurrences on different - * region type(s). - */ - abstract protected String[] getRegionTypes(); - - /** - * Clients should override to provide their own search for the file. - */ - protected ISearchQuery getSearchQuery(IFile file, IStructuredDocument document, String regionText, String regionType, ITextSelection textSelection) { - return new OccurrencesSearchQuery(file, document, regionText, regionType); - } - - /** - * @param partitionType - * @return <code>true</code> if this action can operate on this type of - * partition, otherwise <code>false</code>. - */ - public boolean enabledForParitition(String partitionType) { - String[] accept = getPartitionTypes(); - for (int i = 0; i < accept.length; i++) { - if (partitionType.equals(accept[i])) - return true; - } - return false; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/search/OccurrencesContentProvider.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/search/OccurrencesContentProvider.java deleted file mode 100644 index 7a8f26a607..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/search/OccurrencesContentProvider.java +++ /dev/null @@ -1,83 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.search; - -import org.eclipse.jface.viewers.IStructuredContentProvider; -import org.eclipse.jface.viewers.TableViewer; -import org.eclipse.jface.viewers.Viewer; - -/** - * @author pavery - */ -public class OccurrencesContentProvider implements IStructuredContentProvider { - - protected final Object[] EMPTY_ARRAY = new Object[0]; - private OccurrencesSearchResult fResult = null; - private TableViewer fTableViewer = null; - - public void clear() { - if (this.fTableViewer != null) - this.fTableViewer.refresh(); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.viewers.IContentProvider#dispose() - */ - public void dispose() { - // do nothing - } - - public void elementsChanged(Object[] updatedElements) { - - //TODO: copied from JavaSearchTableContentProvider - for (int i = 0; i < updatedElements.length; i++) { - if (this.fResult.getMatchCount(updatedElements[i]) > 0) { - if (this.fTableViewer.testFindItem(updatedElements[i]) != null) - this.fTableViewer.refresh(updatedElements[i]); - else - this.fTableViewer.add(updatedElements[i]); - } else { - this.fTableViewer.remove(updatedElements[i]); - } - } - } - - - /** - * @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object) - */ - public Object[] getElements(Object inputElement) { - - this.fResult = (OccurrencesSearchResult) inputElement; - return this.fResult.getElements(); - } - - /** - * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer, - * java.lang.Object, java.lang.Object) - */ - public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { - - if (viewer instanceof TableViewer) - this.fTableViewer = (TableViewer) viewer; - this.fResult = (OccurrencesSearchResult) newInput; - } - - public void refresh() { - - if (this.fTableViewer != null) - this.fTableViewer.refresh(); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/search/OccurrencesSearchQuery.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/search/OccurrencesSearchQuery.java deleted file mode 100644 index d5c8e0fa83..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/search/OccurrencesSearchQuery.java +++ /dev/null @@ -1,172 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2011 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.search; - -import java.text.MessageFormat; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IWorkspace; -import org.eclipse.core.resources.IWorkspaceRunnable; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.jobs.ISchedulingRule; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion; -import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegion; -import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegionList; -import org.eclipse.wst.sse.ui.internal.Logger; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; -import org.eclipse.wst.sse.ui.internal.SSEUIPlugin; - -/** - * Basic ISearchQuery that finds matches of region type and region text. - * - * @author pavery - */ -public class OccurrencesSearchQuery extends BasicSearchQuery { - - /** - * We need a runnable so that the search markers show up in the live - * document. - */ - private class FindRegions implements IWorkspaceRunnable { - - private IStructuredDocument fFindRegionsDocument = null; - private String fMatchName = null; - private String fMatchRegionType = null; - - public FindRegions(IStructuredDocument document, String matchText, String matchRegionType) { - - this.fFindRegionsDocument = document; - this.fMatchName = matchText; - this.fMatchRegionType = matchRegionType; - } - - private void findOccurrences(IProgressMonitor monitor) { - - if (!isCanceled(monitor)) { - - int matchStart = -1; - int matchEnd = -1; - String findRegionText = ""; //$NON-NLS-1$ - - ITextRegion r = null; - ITextRegionList regions = null; - IStructuredDocumentRegion current = this.fFindRegionsDocument.getFirstStructuredDocumentRegion(); - - // this is the main loop that iterates the document - while (current != null && !isCanceled(monitor)) { - regions = current.getRegions(); - for (int i = 0; i < regions.size() && !isCanceled(monitor); i++) { - - r = regions.get(i); - - // maybe this is the equals check where some valid - // matches are failing (like searching on end tag) - if (r.getType().equals(this.fMatchRegionType) && current.getText(r).equals(this.fMatchName)) { - - findRegionText = current.getText(r); - - // region found - matchStart = current.getStartOffset(r); - matchEnd = matchStart + findRegionText.trim().length(); - - addMatch(this.fFindRegionsDocument, matchStart, matchEnd); - } - } - current = current.getNext(); - } - } - } - - private boolean isCanceled(IProgressMonitor monitor) { - return monitor != null && monitor.isCanceled(); - } - - public void run(IProgressMonitor monitor) throws CoreException { - - try { - findOccurrences(monitor); - } catch (Exception e) { - Logger.logException(e); - } - } - }// end inner class FindRegions - - - private IStructuredDocument fDocument = null; - private String fRegionText = null; - private String fRegionType = null; - - public OccurrencesSearchQuery(IFile file, IStructuredDocument document, String regionText, String regionType) { - super(file); - super.setResult(new OccurrencesSearchResult(this)); - this.fDocument = document; - this.fRegionText = regionText; - this.fRegionType = regionType; - } - - /** - * <p><i>Note: </i>Some investigation needs to be put into how to do this safely</p> - * - * @see org.eclipse.wst.sse.ui.internal.search.BasicSearchQuery#canRunInBackground() - */ - public boolean canRunInBackground() { - return false; - } - - /** - * <p>The label format is:<br/> - * searchText - # occurrences in file</p> - * - * @see org.eclipse.wst.sse.ui.internal.search.BasicSearchQuery#getLabel() - */ - public String getLabel() { - String label = SSEUIMessages.OccurrencesSearchQuery_0; //$NON-NLS-1$ - String[] args = {getSearchText(), "" + super.getMatchCount(), getFilename()}; - return MessageFormat.format(label, args); - } - - /** - * This query looks for all occurrences of the selected string - * - * @see org.eclipse.wst.sse.ui.internal.search.BasicSearchQuery#doQuery() - */ - protected IStatus doQuery(IProgressMonitor monitor) { - IStatus status = Status.OK_STATUS; - FindRegions findRegions = new FindRegions(this.fDocument, this.fRegionText, this.fRegionType); - try { - // BUG158846 - deadlock if lock up entire workspace, so only lock - // up the file we are searching on - ISchedulingRule markerRule = ResourcesPlugin.getWorkspace().getRuleFactory().markerRule(getFile()); - ResourcesPlugin.getWorkspace().run(findRegions, markerRule, IWorkspace.AVOID_UPDATE, monitor); - } catch (CoreException e) { - status = new Status(IStatus.ERROR, SSEUIPlugin.ID, IStatus.OK, "", null); //$NON-NLS-1$ - } - return status; - } - - protected String getSearchText() { - return this.fRegionText; - } - - private String getFilename() { - String filename = SSEUIMessages.OccurrencesSearchQuery_2; //$NON-NLS-1$ "file" - if (getFile() != null) - filename = getFile().getName().toString(); - return filename; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/search/OccurrencesSearchResult.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/search/OccurrencesSearchResult.java deleted file mode 100644 index 8082773c7f..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/search/OccurrencesSearchResult.java +++ /dev/null @@ -1,156 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.search; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IMarker; -import org.eclipse.core.resources.IResource; -import org.eclipse.jface.resource.ImageDescriptor; -import org.eclipse.search.ui.ISearchQuery; -import org.eclipse.search.ui.text.AbstractTextSearchResult; -import org.eclipse.search.ui.text.IEditorMatchAdapter; -import org.eclipse.search.ui.text.IFileMatchAdapter; -import org.eclipse.search.ui.text.Match; -import org.eclipse.ui.IEditorInput; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.IFileEditorInput; -import org.eclipse.wst.sse.ui.internal.editor.EditorPluginImageHelper; -import org.eclipse.wst.sse.ui.internal.editor.EditorPluginImages; - - -/** - * @author pavery - */ -public class OccurrencesSearchResult extends AbstractTextSearchResult implements IEditorMatchAdapter, IFileMatchAdapter { - - private ISearchQuery fQuery = null; - private final Match[] NO_MATCHES = new Match[0]; - - public OccurrencesSearchResult(ISearchQuery query) { - this.fQuery = query; - } - - /** - * @see org.eclipse.search.ui.text.IEditorMatchAdapter#computeContainedMatches(org.eclipse.search.ui.text.AbstractTextSearchResult, - * org.eclipse.ui.IEditorPart) - */ - public Match[] computeContainedMatches(AbstractTextSearchResult result, IEditorPart editor) { - - IEditorInput editorInput = editor.getEditorInput(); - if (editorInput instanceof IFileEditorInput) { - IFileEditorInput fileEditorInput = (IFileEditorInput) editorInput; - return computeContainedMatches(result, fileEditorInput.getFile()); - } - return this.NO_MATCHES; - } - - /** - * @see org.eclipse.search.ui.text.IFileMatchAdapter#computeContainedMatches(org.eclipse.search.ui.text.AbstractTextSearchResult, - * org.eclipse.core.resources.IFile) - */ - public Match[] computeContainedMatches(AbstractTextSearchResult result, IFile file) { - Match[] matches = this.getMatches(); - Match[] containedMatches = new Match[0]; - - /* only contains matches if the file for one of the matches is the - * same as the given file. - * Note: all matches in a result are related to the same file - */ - if(matches.length > 0 && - matches[0].getElement() instanceof BasicSearchMatchElement && - ((BasicSearchMatchElement)matches[0].getElement()).getFile().equals(file)) { - - containedMatches = matches; - } - return containedMatches; - } - - /** - * @see org.eclipse.search.ui.text.AbstractTextSearchResult#getEditorMatchAdapter() - */ - public IEditorMatchAdapter getEditorMatchAdapter() { - return this; - } - - /** - * @see org.eclipse.search.ui.text.IFileMatchAdapter#getFile(java.lang.Object) - */ - public IFile getFile(Object element) { - // return the file for the match - IFile file = null; - //System.out.println("get file for:"+element); - if (element instanceof IMarker) { - IResource r = ((IMarker) element).getResource(); - if (r instanceof IFile) { - file = (IFile) r; - } - } - return file; - } - - public IFileMatchAdapter getFileMatchAdapter() { - return this; - } - - public ImageDescriptor getImageDescriptor() { - return EditorPluginImageHelper.getInstance().getImageDescriptor(EditorPluginImages.IMG_OBJ_OCC_MATCH); - } - - /** - * This label shows up in the search history - */ - public String getLabel() { - return getQuery().getLabel(); - } - - /** - * @return the matches associated with this result - */ - public Match[] getMatches() { - return collectMatches(getElements()); - } - - public ISearchQuery getQuery() { - return this.fQuery; - } - - public String getTooltip() { - return getLabel(); - } - - /** - * @see org.eclipse.search.ui.text.IEditorMatchAdapter#isShownInEditor(org.eclipse.search.ui.text.Match, - * org.eclipse.ui.IEditorPart) - */ - public boolean isShownInEditor(Match match, IEditorPart editor) { - return true; - } - - /** - * <p>Taken from {@link org.eclipse.jdt.internal.ui.search.OccurrencesSearchResult#collectMatches}</p> - * - * @param elements get the matches for these elements - * @return the matches associated with this result - */ - private Match[] collectMatches(Object[] elements) { - Match[] matches= new Match[getMatchCount()]; - int writeIndex= 0; - for (int i= 0; i < elements.length; i++) { - Match[] perElement= getMatches(elements[i]); - for (int j= 0; j < perElement.length; j++) { - matches[writeIndex++]= perElement[j]; - } - } - return matches; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/search/OccurrencesSearchViewPage.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/search/OccurrencesSearchViewPage.java deleted file mode 100644 index 2e619804d4..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/search/OccurrencesSearchViewPage.java +++ /dev/null @@ -1,127 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.search; - -import org.eclipse.jface.text.TextSelection; -import org.eclipse.jface.viewers.DelegatingStyledCellLabelProvider; -import org.eclipse.jface.viewers.TableViewer; -import org.eclipse.jface.viewers.TreeViewer; -import org.eclipse.jface.viewers.Viewer; -import org.eclipse.jface.viewers.ViewerComparator; -import org.eclipse.search.ui.text.AbstractTextSearchViewPage; -import org.eclipse.search.ui.text.Match; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.IWorkbench; -import org.eclipse.ui.IWorkbenchPage; -import org.eclipse.ui.IWorkbenchWindow; -import org.eclipse.ui.PartInitException; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.ide.IDE; -import org.eclipse.wst.sse.ui.internal.Logger; - - -/** - * Base page for Occurrences in file search results. - * - * @author pavery - */ -public class OccurrencesSearchViewPage extends AbstractTextSearchViewPage { - - private OccurrencesContentProvider fContentProvider = null; - - public OccurrencesSearchViewPage() { - super(AbstractTextSearchViewPage.FLAG_LAYOUT_FLAT); - } - - /** - * @see org.eclipse.search.ui.text.AbstractTextSearchViewPage#clear() - */ - protected void clear() { - if (this.fContentProvider != null) - this.fContentProvider.clear(); - } - - /** - * @see org.eclipse.search.ui.text.AbstractTextSearchViewPage#configureTableViewer(org.eclipse.jface.viewers.TableViewer) - */ - protected void configureTableViewer(TableViewer viewer) { - - //sort results by line number, low to high - viewer.setComparator(new ViewerComparator() { - public int compare(Viewer v, Object obj1, Object obj2) { - BasicSearchMatchElement elem1= (BasicSearchMatchElement) obj1; - BasicSearchMatchElement elem2= (BasicSearchMatchElement) obj2; - return elem1.getLineNum() - elem2.getLineNum(); - } - }); - - //allow for formated labels - viewer.setLabelProvider(new DelegatingStyledCellLabelProvider(new BasicSearchLabelProvider(this))); - this.fContentProvider = new OccurrencesContentProvider(); - viewer.setContentProvider(this.fContentProvider); - } - - /** - * @see org.eclipse.search.ui.text.AbstractTextSearchViewPage#configureTreeViewer(org.eclipse.jface.viewers.TreeViewer) - */ - protected void configureTreeViewer(TreeViewer viewer) { - // not supported at the moment - } - - /** - * @see org.eclipse.search.ui.text.AbstractTextSearchViewPage#elementsChanged(java.lang.Object[]) - */ - protected void elementsChanged(Object[] objects) { - if (this.fContentProvider != null) { - this.fContentProvider.elementsChanged(objects); - } - } - - public void forceRefresh() { - this.fContentProvider.refresh(); - } - - private IWorkbenchPage getActivePage() { - - IWorkbench workbench = PlatformUI.getWorkbench(); - IWorkbenchWindow window = workbench.getActiveWorkbenchWindow(); - if (window == null) - return null; - return workbench.getActiveWorkbenchWindow().getActivePage(); - } - - /** - * @see org.eclipse.search.ui.text.AbstractTextSearchViewPage#showMatch(org.eclipse.search.ui.text.Match, - * int, int) - */ - protected void showMatch(Match match, int currentOffset, int currentLength, boolean activate) throws PartInitException { - BasicSearchMatchElement element = (BasicSearchMatchElement) match.getElement(); - - IWorkbenchPage activePage = getActivePage(); - try { - if (activePage != null) { - // open editor if needed - IDE.openEditor(getActivePage(), element.getFile()); - //set the selection in the open editor - IEditorPart editor = activePage.getActiveEditor(); - if (activate) - editor.getSite().getPage().activate(editor); - editor.getEditorSite().getSelectionProvider().setSelection( - new TextSelection(currentOffset, currentLength)); - } - } catch (PartInitException e) { - // possible exception trying to open editor - Logger.logException(e); - } - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/selection/SelectionHistory.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/selection/SelectionHistory.java deleted file mode 100644 index 79a8857923..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/selection/SelectionHistory.java +++ /dev/null @@ -1,117 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.selection; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.eclipse.jface.action.IAction; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.util.Assert; -import org.eclipse.jface.viewers.ISelectionChangedListener; -import org.eclipse.jface.viewers.SelectionChangedEvent; -import org.eclipse.ui.texteditor.ITextEditor; - -public class SelectionHistory { - private ITextEditor fEditor; - private List fHistory; - private List fHistoryActions; - private int fSelectionChangeListenerCounter; - private ISelectionChangedListener fSelectionListener; - - public SelectionHistory(ITextEditor editor) { - Assert.isNotNull(editor); - fEditor = editor; - fHistory = new ArrayList(3); - fSelectionListener = new ISelectionChangedListener() { - public void selectionChanged(SelectionChangedEvent event) { - if (fSelectionChangeListenerCounter == 0) - flush(); - } - }; - fEditor.getSelectionProvider().addSelectionChangedListener(fSelectionListener); - } - - public void dispose() { - fEditor.getSelectionProvider().removeSelectionChangedListener(fSelectionListener); - fEditor = null; - if (fHistory != null && !fHistory.isEmpty()) { - fHistory.clear(); - } - if (fHistoryActions != null && !fHistoryActions.isEmpty()) { - fHistoryActions.clear(); - } - } - - public void flush() { - if (fHistory.isEmpty()) - return; - fHistory.clear(); - updateHistoryAction(); - } - - public IRegion getLast() { - if (isEmpty()) - return null; - int size = fHistory.size(); - IRegion result = (IRegion) fHistory.remove(size - 1); - updateHistoryAction(); - return result; - } - - public void ignoreSelectionChanges() { - fSelectionChangeListenerCounter++; - } - - public boolean isEmpty() { - return fHistory.isEmpty(); - } - - public void listenToSelectionChanges() { - fSelectionChangeListenerCounter--; - } - - public void remember(IRegion region) { - fHistory.add(region); - updateHistoryAction(); - } - - public void setHistoryAction(IAction action) { - Assert.isNotNull(action); - - if (fHistoryActions == null) - fHistoryActions = new ArrayList(); - if (!fHistoryActions.contains(action)) - fHistoryActions.add(action); - - // update action - if (fHistory != null && !fHistory.isEmpty()) - action.setEnabled(true); - else - action.setEnabled(false); - } - - private void updateHistoryAction() { - if (fHistoryActions != null && !fHistoryActions.isEmpty()) { - boolean enabled = false; - if (fHistory != null && !fHistory.isEmpty()) - enabled = true; - - Iterator iter = fHistoryActions.iterator(); - while (iter.hasNext()) { - ((IAction)iter.next()).setEnabled(enabled); - } - } - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/selection/StructureSelectAction.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/selection/StructureSelectAction.java deleted file mode 100644 index fc27d39906..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/selection/StructureSelectAction.java +++ /dev/null @@ -1,110 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2006 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.selection; - -import org.eclipse.jface.action.Action; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.Region; -import org.eclipse.jface.util.Assert; -import org.eclipse.wst.sse.core.StructuredModelManager; -import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel; -import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion; -import org.eclipse.wst.sse.ui.StructuredTextEditor; -import org.eclipse.wst.sse.ui.internal.StructuredTextViewer; -import org.w3c.dom.Node; - -/** - * @deprecated use StructuredSelectActionDelegate instead - */ - -public abstract class StructureSelectAction extends Action { - protected StructuredTextEditor fEditor = null; - protected SelectionHistory fHistory; - protected IStructuredModel fModel = null; - protected StructuredTextViewer fViewer = null; - - public StructureSelectAction(StructuredTextEditor editor) { - super(); - - Assert.isNotNull(editor); - fEditor = editor; - fHistory = (SelectionHistory) editor.getAdapter(SelectionHistory.class); - fViewer = editor.getTextViewer(); - fModel = editor.getModel(); - Assert.isNotNull(fViewer); - } - - abstract protected IndexedRegion getCursorIndexedRegion(); - - protected IndexedRegion getIndexedRegion(int offset) { - IndexedRegion indexedRegion = null; - - int lastOffset = offset; - IDocument document = fEditor.getDocumentProvider().getDocument(fEditor.getEditorInput()); - IStructuredModel model = StructuredModelManager.getModelManager().getExistingModelForRead(document); - if (model != null) { - try { - indexedRegion = model.getIndexedRegion(lastOffset); - while (indexedRegion == null && lastOffset >= 0) { - lastOffset--; - indexedRegion = model.getIndexedRegion(lastOffset); - } - } - finally { - model.releaseFromRead(); - } - } - - return indexedRegion; - } - - abstract protected Region getNewSelectionRegion(Node node, Region region); - - public void run() { - Region currentRegion = new Region(fViewer.getSelectedRange().x, fViewer.getSelectedRange().y); - if (currentRegion.getLength() == fViewer.getDocument().getLength()) - return; - - IndexedRegion cursorIndexedRegion = getCursorIndexedRegion(); - if (cursorIndexedRegion instanceof Node) { - Node cursorNode = (Node) cursorIndexedRegion; - - // use parent node for empty text node - if (cursorNode.getNodeType() == Node.TEXT_NODE && cursorNode.getNodeValue().trim().length() == 0) { - cursorNode = cursorNode.getParentNode(); - - if (cursorNode instanceof IndexedRegion) - cursorIndexedRegion = (IndexedRegion) cursorNode; - } - - Region cursorNodeRegion = new Region(cursorIndexedRegion.getStartOffset(), cursorIndexedRegion.getEndOffset() - cursorIndexedRegion.getStartOffset()); - - Region newRegion = null; - if (cursorNodeRegion.getOffset() >= currentRegion.getOffset() && cursorNodeRegion.getOffset() <= currentRegion.getOffset() + currentRegion.getLength() && cursorNodeRegion.getOffset() + cursorNodeRegion.getLength() >= currentRegion.getOffset() && cursorNodeRegion.getOffset() + cursorNodeRegion.getLength() <= currentRegion.getOffset() + currentRegion.getLength()) - newRegion = getNewSelectionRegion(cursorNode, currentRegion); - else - newRegion = cursorNodeRegion; - - if (newRegion != null) { - fHistory.remember(currentRegion); - try { - fHistory.ignoreSelectionChanges(); - fEditor.selectAndReveal(newRegion.getOffset(), newRegion.getLength()); - } - finally { - fHistory.listenToSelectionChanges(); - } - } - } - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/selection/StructureSelectHistoryAction.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/selection/StructureSelectHistoryAction.java deleted file mode 100644 index 8037c527b8..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/selection/StructureSelectHistoryAction.java +++ /dev/null @@ -1,56 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.selection; - -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.Region; -import org.eclipse.ui.texteditor.IUpdate; -import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion; -import org.eclipse.wst.sse.ui.StructuredTextEditor; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; -import org.w3c.dom.Node; - -public class StructureSelectHistoryAction extends StructureSelectAction implements IUpdate { - public StructureSelectHistoryAction(StructuredTextEditor editor) { - super(editor); - setText(SSEUIMessages.StructureSelectHistory_label); //$NON-NLS-1$ - setToolTipText(SSEUIMessages.StructureSelectHistory_tooltip); //$NON-NLS-1$ - setDescription(SSEUIMessages.StructureSelectHistory_description); //$NON-NLS-1$ - - update(); - } - - protected IndexedRegion getCursorIndexedRegion() { - return null; - } - - protected Region getNewSelectionRegion(Node node, Region region) { - return null; - } - - public void run() { - IRegion old = fHistory.getLast(); - if (old != null) { - try { - fHistory.ignoreSelectionChanges(); - fEditor.selectAndReveal(old.getOffset(), old.getLength()); - } finally { - fHistory.listenToSelectionChanges(); - } - } - } - - public void update() { - setEnabled(!fHistory.isEmpty()); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/selection/StructuredSelectActionDelegate.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/selection/StructuredSelectActionDelegate.java deleted file mode 100644 index dbdf4ae1f4..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/selection/StructuredSelectActionDelegate.java +++ /dev/null @@ -1,124 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2006 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * - *******************************************************************************/ - -package org.eclipse.wst.sse.ui.internal.selection; - -import org.eclipse.jface.action.IAction; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.ITextSelection; -import org.eclipse.jface.text.Region; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.swt.widgets.Event; -import org.eclipse.ui.IActionDelegate2; -import org.eclipse.ui.IEditorActionDelegate; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.IViewActionDelegate; -import org.eclipse.ui.IViewPart; -import org.eclipse.ui.texteditor.ITextEditor; -import org.eclipse.wst.sse.core.StructuredModelManager; -import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel; -import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion; - -abstract public class StructuredSelectActionDelegate implements IEditorActionDelegate, IActionDelegate2, IViewActionDelegate { - private IEditorPart fEditor; - private SelectionHistory fHistory; - - public void dispose() { - fEditor = null; - fHistory = null; - } - - public void init(IViewPart view) { - // do nothing - } - - public void runWithEvent(IAction action, Event event) { - run(action); - } - - public void run(IAction action) { - if (fEditor instanceof ITextEditor) { - ITextEditor textEditor = (ITextEditor) fEditor; - - ISelection selection = textEditor.getSelectionProvider().getSelection(); - IDocument document = textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput()); - // determine current text selection - if (selection instanceof ITextSelection && document != null) { - ITextSelection textSelection = (ITextSelection) selection; - - if (textSelection.getLength() < document.getLength()) { - // get current indexed region - IndexedRegion cursorIndexedRegion = getCursorIndexedRegion(document, textSelection); - - // determine new selection based on current indexed region - Region newSelectionRegion = getNewSelectionRegion(cursorIndexedRegion, textSelection); - - // select new selection - if (newSelectionRegion != null) { - fHistory.remember(new Region(textSelection.getOffset(), textSelection.getLength())); - try { - fHistory.ignoreSelectionChanges(); - textEditor.selectAndReveal(newSelectionRegion.getOffset(), newSelectionRegion.getLength()); - } - finally { - fHistory.listenToSelectionChanges(); - } - } - } - } - } - } - - public void selectionChanged(IAction action, ISelection selection) { - // do nothing - } - - public void setActiveEditor(IAction action, IEditorPart targetEditor) { - fEditor = targetEditor; - if (fEditor != null) - fHistory = (SelectionHistory) fEditor.getAdapter(SelectionHistory.class); - else - fHistory = null; - } - - abstract protected IndexedRegion getCursorIndexedRegion(IDocument document, ITextSelection textSelection); - - abstract protected Region getNewSelectionRegion(IndexedRegion indexedRegion, ITextSelection textSelection); - - /** - * This method will probably be removed and replaced by using new selection provider - * @param document - * @param offset - * @return - */ - protected IndexedRegion getIndexedRegion(IDocument document, int offset) { - IndexedRegion indexedRegion = null; - - int lastOffset = offset; - IStructuredModel model = StructuredModelManager.getModelManager().getExistingModelForRead(document); - if (model != null) { - try { - indexedRegion = model.getIndexedRegion(lastOffset); - while (indexedRegion == null && lastOffset >= 0) { - lastOffset--; - indexedRegion = model.getIndexedRegion(lastOffset); - } - } - finally { - model.releaseFromRead(); - } - } - - return indexedRegion; - } - -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/selection/StructuredSelectHistoryActionDelegate.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/selection/StructuredSelectHistoryActionDelegate.java deleted file mode 100644 index 47dc5c8964..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/selection/StructuredSelectHistoryActionDelegate.java +++ /dev/null @@ -1,83 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * - *******************************************************************************/ - -package org.eclipse.wst.sse.ui.internal.selection; - -import org.eclipse.jface.action.IAction; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.swt.widgets.Event; -import org.eclipse.ui.IActionDelegate2; -import org.eclipse.ui.IEditorActionDelegate; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.IViewActionDelegate; -import org.eclipse.ui.IViewPart; -import org.eclipse.ui.texteditor.ITextEditor; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; - -/** - * Selection history action delegate. Keeps track of selection within editor. - */ -public class StructuredSelectHistoryActionDelegate implements IEditorActionDelegate, IActionDelegate2, IViewActionDelegate { - private IEditorPart fEditor; - private SelectionHistory fHistory; - - public void dispose() { - fEditor = null; - fHistory = null; - } - - public void init(IAction action) { - if (action != null) { - action.setText(SSEUIMessages.StructureSelectHistory_label); - action.setToolTipText(SSEUIMessages.StructureSelectHistory_tooltip); - action.setDescription(SSEUIMessages.StructureSelectHistory_description); - } - } - - public void init(IViewPart view) { - // do nothing - } - - public void run(IAction action) { - IRegion old = fHistory.getLast(); - if (old != null) { - try { - fHistory.ignoreSelectionChanges(); - if (fEditor instanceof ITextEditor) - ((ITextEditor) fEditor).selectAndReveal(old.getOffset(), old.getLength()); - } - finally { - fHistory.listenToSelectionChanges(); - } - } - } - - public void runWithEvent(IAction action, Event event) { - run(action); - } - - public void selectionChanged(IAction action, ISelection selection) { - // do nothing - } - - public void setActiveEditor(IAction action, IEditorPart targetEditor) { - fEditor = targetEditor; - if (fEditor != null) - fHistory = (SelectionHistory) fEditor.getAdapter(SelectionHistory.class); - else - fHistory = null; - if (fHistory != null) { - fHistory.setHistoryAction(action); - } - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/spelling/ISpellcheckDelegate.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/spelling/ISpellcheckDelegate.java deleted file mode 100644 index ce55c8fa2d..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/spelling/ISpellcheckDelegate.java +++ /dev/null @@ -1,32 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.spelling; - -import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel; - -/** - * <p>Defines an interface for deciding if an offset in an <code>IStructuredModel</code> - * should be spell checked. Created so that content type specific decisions - * could be made as to whether a region should be spell-checked or not. - * This is done using the <code>IAdapterFactory</code> framework.</p> - */ -public interface ISpellcheckDelegate { - - /** - * Decide if the <code>offset</code> in <code>model</code> should be spell checked or not. - * - * @param offset decide if this offset in the given <code>model</code> should be spell-checked - * @param model used to decide if the given <code>offset</code> should be spell-checked - * @return <code>true</code> if the given <code>offset</code> in the given <code>model</code> - * should be spell checked, <code>false</code> otherwise. - */ - public boolean shouldSpellcheck(int offset, IStructuredModel model); -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/spelling/SpellcheckStrategy.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/spelling/SpellcheckStrategy.java deleted file mode 100644 index d95c9c3bad..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/spelling/SpellcheckStrategy.java +++ /dev/null @@ -1,415 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2006, 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.spelling; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.content.IContentType; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.Position; -import org.eclipse.jface.text.Region; -import org.eclipse.jface.text.reconciler.DirtyRegion; -import org.eclipse.jface.text.reconciler.IReconcileStep; -import org.eclipse.jface.text.source.Annotation; -import org.eclipse.jface.text.source.IAnnotationModel; -import org.eclipse.jface.text.source.IAnnotationModelExtension; -import org.eclipse.jface.text.source.IAnnotationModelExtension2; -import org.eclipse.jface.text.source.ISourceViewer; -import org.eclipse.jface.util.IPropertyChangeListener; -import org.eclipse.jface.util.PropertyChangeEvent; -import org.eclipse.ui.editors.text.EditorsUI; -import org.eclipse.ui.texteditor.spelling.ISpellingProblemCollector; -import org.eclipse.ui.texteditor.spelling.SpellingAnnotation; -import org.eclipse.ui.texteditor.spelling.SpellingContext; -import org.eclipse.ui.texteditor.spelling.SpellingProblem; -import org.eclipse.ui.texteditor.spelling.SpellingService; -import org.eclipse.wst.sse.core.StructuredModelManager; -import org.eclipse.wst.sse.core.internal.parser.ForeignRegion; -import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion; -import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegion; -import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegionCollection; -import org.eclipse.wst.sse.core.utils.StringUtils; -import org.eclipse.wst.sse.ui.internal.ExtendedConfigurationBuilder; -import org.eclipse.wst.sse.ui.internal.Logger; -import org.eclipse.wst.sse.ui.internal.reconcile.ReconcileAnnotationKey; -import org.eclipse.wst.sse.ui.internal.reconcile.StructuredReconcileStep; -import org.eclipse.wst.sse.ui.internal.reconcile.StructuredTextReconcilingStrategy; -import org.eclipse.wst.sse.ui.internal.reconcile.TemporaryAnnotation; - -/** - * A reconciling strategy that queries the SpellingService using its default - * engine. Results are show as temporary annotations. - * - * @since 1.1 - */ -public class SpellcheckStrategy extends StructuredTextReconcilingStrategy { - - class SpellCheckPreferenceListener implements IPropertyChangeListener { - private boolean isInterestingProperty(Object property) { - return SpellingService.PREFERENCE_SPELLING_ENABLED.equals(property) || SpellingService.PREFERENCE_SPELLING_ENGINE.equals(property); - } - - public void propertyChange(PropertyChangeEvent event) { - if (isInterestingProperty(event.getProperty())) { - if (event.getOldValue() == null || event.getNewValue() == null || !event.getNewValue().equals(event.getOldValue())) { - reconcile(); - } - } - } - } - - private class SpellingProblemCollector implements ISpellingProblemCollector { - List annotations = new ArrayList(); - - public void accept(SpellingProblem problem) { - if (isInterestingProblem(problem)) { - TemporaryAnnotation annotation = new TemporaryAnnotation(new Position(problem.getOffset(), problem.getLength()), SpellingAnnotation.TYPE, problem.getMessage(), fReconcileAnnotationKey); - - SpellingQuickAssistProcessor quickAssistProcessor = new SpellingQuickAssistProcessor(); - quickAssistProcessor.setSpellingProblem(problem); - annotation.setAdditionalFixInfo(quickAssistProcessor); - annotations.add(annotation); - if (_DEBUG_SPELLING_PROBLEMS) { - Logger.log(Logger.INFO, problem.getMessage()); - } - } - } - - public void beginCollecting() { - } - - void clear() { - annotations.clear(); - } - - public void endCollecting() { - } - - Annotation[] getAnnotations() { - return (Annotation[]) annotations.toArray(new Annotation[annotations.size()]); - } - } - - private static final boolean _DEBUG_SPELLING = Boolean.valueOf(Platform.getDebugOption("org.eclipse.wst.sse.ui/debug/reconcilerSpelling")).booleanValue(); //$NON-NLS-1$ - private static final boolean _DEBUG_SPELLING_PROBLEMS = Boolean.valueOf(Platform.getDebugOption("org.eclipse.wst.sse.ui/debug/reconcilerSpelling/showProblems")).booleanValue(); //$NON-NLS-1$ - - private static final String EXTENDED_BUILDER_TYPE_CONTEXTS = "spellingregions"; //$NON-NLS-1$ - private static final String KEY_CONTENT_TYPE = "org.eclipse.wst.sse.ui.temp.spelling"; //$NON-NLS-1$ - - private String fContentTypeId = null; - - private SpellingProblemCollector fProblemCollector = new SpellingProblemCollector(); - - IStructuredModel structuredModel = null; - - /* - * Keying our Temporary Annotations based on the partition doesn't help - * this strategy to only remove its own TemporaryAnnotations since it's - * possibly run on all partitions. Instead, set the key to use an - * arbitrary partition type that we can check for using our own - * implementation of getAnnotationsToRemove(DirtyRegion). - */ - ReconcileAnnotationKey fReconcileAnnotationKey; - - private IPropertyChangeListener fSpellCheckPreferenceListener; - - private SpellingContext fSpellingContext; - - private String[] fSupportedTextRegionContexts; - private IReconcileStep fSpellingStep = new StructuredReconcileStep() { - }; - - public SpellcheckStrategy(ISourceViewer viewer, String contentTypeId) { - super(viewer); - fContentTypeId = contentTypeId; - - fSpellingContext = new SpellingContext(); - IContentType contentType = Platform.getContentTypeManager().getContentType(fContentTypeId); - fSpellingContext.setContentType(contentType); - fReconcileAnnotationKey = new ReconcileAnnotationKey(fSpellingStep, KEY_CONTENT_TYPE, ReconcileAnnotationKey.PARTIAL); - - /** - * Inherit spelling region rules - */ - List contexts = new ArrayList(); - IContentType testType = contentType; - while (testType != null) { - String[] textRegionContexts = ExtendedConfigurationBuilder.getInstance().getDefinitions(EXTENDED_BUILDER_TYPE_CONTEXTS, testType.getId()); - for (int j = 0; j < textRegionContexts.length; j++) { - contexts.addAll(Arrays.asList(StringUtils.unpack(textRegionContexts[j]))); - } - testType = testType.getBaseType(); - } - fSupportedTextRegionContexts = (String[]) contexts.toArray(new String[contexts.size()]); - - fSpellCheckPreferenceListener = new SpellCheckPreferenceListener(); - } - - protected boolean containsStep(IReconcileStep step) { - return fSpellingStep.equals(step); - } - - public void createReconcileSteps() { - - } - - private TemporaryAnnotation[] getSpellingAnnotationsToRemove(IRegion region) { - List toRemove = new ArrayList(); - IAnnotationModel annotationModel = getAnnotationModel(); - // can be null when closing the editor - if (annotationModel != null) { - Iterator i = null; - boolean annotationOverlaps = false; - if (annotationModel instanceof IAnnotationModelExtension2) { - i = ((IAnnotationModelExtension2) annotationModel).getAnnotationIterator(region.getOffset(), region.getLength(), true, true); - annotationOverlaps = true; - } - else { - i = annotationModel.getAnnotationIterator(); - } - - while (i.hasNext()) { - Object obj = i.next(); - if (!(obj instanceof TemporaryAnnotation)) - continue; - - TemporaryAnnotation annotation = (TemporaryAnnotation) obj; - ReconcileAnnotationKey key = (ReconcileAnnotationKey) annotation.getKey(); - - // then if this strategy knows how to add/remove this - // partition type - if (key != null && key.equals(fReconcileAnnotationKey)) { - if (key.getScope() == ReconcileAnnotationKey.PARTIAL && (annotationOverlaps || annotation.getPosition().overlapsWith(region.getOffset(), region.getLength()))) { - toRemove.add(annotation); - } - else if (key.getScope() == ReconcileAnnotationKey.TOTAL) { - toRemove.add(annotation); - } - } - } - } - - return (TemporaryAnnotation[]) toRemove.toArray(new TemporaryAnnotation[toRemove.size()]); - } - - /** - * Judge whether a spelling problem is "interesting". Accept any regions - * that are explicitly allowed, and since valid prose areas are rarely in - * a complicated document region, accept any document region with more - * than one text region and reject any document regions containing foreign - * text regions. - * - * @param problem - * a SpellingProblem - * @return whether the collector should accept the given SpellingProblem - */ - protected boolean isInterestingProblem(SpellingProblem problem) { - IDocument document = getDocument(); - if (document instanceof IStructuredDocument) { - /* - * If the error is in a read-only section, ignore it. The user - * won't be able to correct it. - */ - if (((IStructuredDocument) document).containsReadOnly(problem.getOffset(), problem.getLength())) - return false; - - IStructuredDocumentRegion documentRegion = ((IStructuredDocument) document).getRegionAtCharacterOffset(problem.getOffset()); - if (documentRegion != null) { - ITextRegion textRegion = documentRegion.getRegionAtCharacterOffset(problem.getOffset()); - //if the region is not null, and is a supported context and is not a collection of regions, - // and it should be spell-checked, then spell check it. - if (textRegion != null && isSupportedContext(textRegion.getType()) && !(textRegion instanceof ITextRegionCollection) && shouldSpellcheck(problem.getOffset())) { - return true; - } - if (documentRegion.getFirstRegion() instanceof ForeignRegion) - return false; -// [192572] Simple regions were being spellchecked just for the sake of them being simple -// if (documentRegion.getRegions().size() == 1) -// return true; - return false; - } - } - return true; - } - - - private boolean isSupportedContext(String type) { - boolean isSupported = false; - if (fSupportedTextRegionContexts.length > 0) { - for (int i = 0; i < fSupportedTextRegionContexts.length; i++) { - if (type.equals(fSupportedTextRegionContexts[i])) { - isSupported = true; - break; - } - } - } - else { - isSupported = true; - } - return isSupported; - } - - public void reconcile() { - IDocument document = getDocument(); - if (document != null) { - IAnnotationModel annotationModel = getAnnotationModel(); - if (annotationModel != null) { - IRegion documentRegion = new Region(0, document.getLength()); - spellCheck(documentRegion, documentRegion, annotationModel); - } - } - } - - /** - * @see org.eclipse.jface.text.reconciler.IReconcilingStrategy#reconcile(org.eclipse.jface.text.reconciler.DirtyRegion, - * org.eclipse.jface.text.IRegion) - */ - public void reconcile(DirtyRegion dirtyRegion, IRegion subRegion) { - if (isCanceled()) - return; - - IAnnotationModel annotationModel = getAnnotationModel(); - - IDocument document = getDocument(); - if (document != null) { - long time0 = 0; - if (_DEBUG_SPELLING) { - time0 = System.currentTimeMillis(); - } - /** - * Apparently the default spelling engine has noticeable overhead - * when called multiple times in rapid succession. It's faster to - * check the entire dirty region at once since we know that we're - * not differentiating by partition. - * - * https://bugs.eclipse.org/bugs/show_bug.cgi?id=192530 - */ - if (_DEBUG_SPELLING) { - Logger.log(Logger.INFO, "Spell Checking [" + dirtyRegion.getOffset() + ":" + dirtyRegion.getLength() + "] : " + (System.currentTimeMillis() - time0)); - } - if (annotationModel != null) { - spellCheck(dirtyRegion, dirtyRegion, annotationModel); - } - } - } - - private void spellCheck(IRegion dirtyRegion, IRegion regionToBeChecked, IAnnotationModel annotationModel) { - if (annotationModel == null) - return; - - TemporaryAnnotation[] annotationsToRemove; - Annotation[] annotationsToAdd; - annotationsToRemove = getSpellingAnnotationsToRemove(regionToBeChecked); - - if (_DEBUG_SPELLING_PROBLEMS) { - Logger.log(Logger.INFO, "Spell checking [" + regionToBeChecked.getOffset() + "-" + (regionToBeChecked.getOffset() + regionToBeChecked.getLength()) + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } - if (getDocument() != null) { - try { - EditorsUI.getSpellingService().check(getDocument(), new IRegion[]{regionToBeChecked}, fSpellingContext, fProblemCollector, null); - } - finally { - // corresponding "get" is in #shouldSpellCheck(int) - if (structuredModel != null) { - structuredModel.releaseFromRead(); - structuredModel = null; - } - } - } - annotationsToAdd = fProblemCollector.getAnnotations(); - fProblemCollector.clear(); - - - if (annotationModel instanceof IAnnotationModelExtension) { - IAnnotationModelExtension modelExtension = (IAnnotationModelExtension) annotationModel; - Map annotationsToAddMap = new HashMap(); - for (int i = 0; i < annotationsToAdd.length; i++) { - annotationsToAddMap.put(annotationsToAdd[i], ((TemporaryAnnotation) annotationsToAdd[i]).getPosition()); - } - modelExtension.replaceAnnotations(annotationsToRemove, annotationsToAddMap); - } - - else { - for (int j = 0; j < annotationsToAdd.length; j++) { - annotationModel.addAnnotation(annotationsToAdd[j], ((TemporaryAnnotation) annotationsToAdd[j]).getPosition()); - } - for (int j = 0; j < annotationsToRemove.length; j++) { - annotationModel.removeAnnotation(annotationsToRemove[j]); - } - } - } - - /** - * @param partition - * @see org.eclipse.jface.text.reconciler.IReconcilingStrategy#reconcile(org.eclipse.jface.text.IRegion) - */ - - public void reconcile(IRegion partition) { - IDocument document = getDocument(); - if (document != null) { - IAnnotationModel annotationModel = getAnnotationModel(); - if (annotationModel != null) { - spellCheck(partition, partition, annotationModel); - } - } - } - - public void setDocument(IDocument document) { - if (getDocument() != null) { - EditorsUI.getPreferenceStore().removePropertyChangeListener(fSpellCheckPreferenceListener); - } - - super.setDocument(document); - - if (getDocument() != null) { - EditorsUI.getPreferenceStore().addPropertyChangeListener(fSpellCheckPreferenceListener); - } - } - - /** - * Decides if the given offset should be spell-checked using an <code>IAdapterFactory</code> - * - * @param offset Decide if this offset should be spell-checked - * @return <code>true</code> if the given <code>offset</code> should be spell-checked, - * <code>false</code> otherwise. - */ - private boolean shouldSpellcheck(int offset) { - boolean decision = true; - - if (structuredModel == null) - structuredModel = StructuredModelManager.getModelManager().getExistingModelForRead(getDocument()); - - if (structuredModel != null) { - /* - * use an an adapter factory to get a spell-check decision maker, - * and ask it if the offset should be spell-checked. It is done - * this way so content type specific decisions can be made without - * this plugin being aware of any content type specifics. - */ - ISpellcheckDelegate delegate = (ISpellcheckDelegate) Platform.getAdapterManager().getAdapter(structuredModel, ISpellcheckDelegate.class); - if (delegate != null) { - decision = delegate.shouldSpellcheck(offset, structuredModel); - } - } - - return decision; - } -}
\ No newline at end of file diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/spelling/SpellingQuickAssistProcessor.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/spelling/SpellingQuickAssistProcessor.java deleted file mode 100644 index f8e4ddd2c0..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/spelling/SpellingQuickAssistProcessor.java +++ /dev/null @@ -1,52 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.spelling; - -import org.eclipse.jface.text.contentassist.ICompletionProposal; -import org.eclipse.jface.text.quickassist.IQuickAssistInvocationContext; -import org.eclipse.jface.text.quickassist.IQuickAssistProcessor; -import org.eclipse.jface.text.source.Annotation; -import org.eclipse.ui.texteditor.spelling.SpellingProblem; - -/** - * Spelling correction processor used to show quick fixes for spelling - * problems. - * - * @since 2.0 - */ -class SpellingQuickAssistProcessor implements IQuickAssistProcessor { - private SpellingProblem fSpellingProblem = null; - - public boolean canAssist(IQuickAssistInvocationContext invocationContext) { - return false; - } - - public boolean canFix(Annotation annotation) { - return !annotation.isMarkedDeleted(); - } - - public ICompletionProposal[] computeQuickAssistProposals(IQuickAssistInvocationContext quickAssistContext) { - ICompletionProposal[] proposals = null; - - if (fSpellingProblem != null) { - proposals = fSpellingProblem.getProposals(quickAssistContext); - } - return proposals; - } - - public String getErrorMessage() { - return null; - } - - void setSpellingProblem(SpellingProblem spellingProblem) { - fSpellingProblem = spellingProblem; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/style/SemanticHighlightingManager.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/style/SemanticHighlightingManager.java deleted file mode 100644 index edd6877559..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/style/SemanticHighlightingManager.java +++ /dev/null @@ -1,771 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009, 2011 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.style; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IConfigurationElement; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.content.IContentType; -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.text.Position; -import org.eclipse.jface.text.Region; -import org.eclipse.jface.text.TextAttribute; -import org.eclipse.jface.text.reconciler.IReconciler; -import org.eclipse.jface.text.source.ISourceViewer; -import org.eclipse.jface.text.source.SourceViewerConfiguration; -import org.eclipse.jface.util.IPropertyChangeListener; -import org.eclipse.jface.util.PropertyChangeEvent; -import org.eclipse.swt.SWT; -import org.eclipse.swt.custom.StyleRange; -import org.eclipse.swt.graphics.Color; -import org.eclipse.swt.graphics.RGB; -import org.eclipse.wst.sse.core.utils.StringUtils; -import org.eclipse.wst.sse.ui.ISemanticHighlighting; -import org.eclipse.wst.sse.ui.ISemanticHighlightingExtension2; -import org.eclipse.wst.sse.ui.internal.Logger; -import org.eclipse.wst.sse.ui.internal.SSEUIPlugin; -import org.eclipse.wst.sse.ui.internal.preferences.EditorPreferenceNames; -import org.eclipse.wst.sse.ui.internal.preferences.ui.ColorHelper; -import org.eclipse.wst.sse.ui.internal.provisional.style.StructuredPresentationReconciler; -import org.eclipse.wst.sse.ui.internal.reconcile.DocumentRegionProcessor; -import org.eclipse.wst.sse.ui.internal.util.EditorUtility; - -/** - * Semantic highlighting manager. Responsible for maintaining the semantic highlightings - * and the associated styles. Semantic highlighting preference changes are handled - * through listeners in this class. Based on org.eclipse.jdt.internal.ui.javaeditor.SemanticHighlightingManager - * - * @since 3.1 - */ -public class SemanticHighlightingManager implements IPropertyChangeListener { - - /** - * HighlightingStyle. - */ - static class HighlightingStyle { - - /** Text attribute */ - private TextAttribute fTextAttribute; - /** Enabled state */ - private boolean fIsEnabled; - - /** - * Initialize with the given text attribute. - * @param textAttribute The text attribute - * @param isEnabled the enabled state - */ - public HighlightingStyle(TextAttribute textAttribute, boolean isEnabled) { - setTextAttribute(textAttribute); - setEnabled(isEnabled); - } - - /** - * @return Returns the text attribute. - */ - public TextAttribute getTextAttribute() { - return fTextAttribute; - } - - /** - * @param textAttribute The background to set. - */ - public void setTextAttribute(TextAttribute textAttribute) { - fTextAttribute = textAttribute; - } - - /** - * @return the enabled state - */ - public boolean isEnabled() { - return fIsEnabled; - } - - /** - * @param isEnabled the new enabled state - */ - public void setEnabled(boolean isEnabled) { - fIsEnabled = isEnabled; - } - } - - /** - * Highlighted Positions. - */ - static class HighlightedPosition extends Position { - - /** Highlighting of the position */ - private HighlightingStyle fStyle; - - private boolean fReadOnly; - - /** Lock object */ - private Object fLock; - - /** - * Initialize the styled positions with the given offset, length and foreground color. - * - * @param offset The position offset - * @param length The position length - * @param highlighting The position's highlighting - * @param lock The lock object - */ - public HighlightedPosition(int offset, int length, HighlightingStyle highlighting, Object lock, boolean isReadOnly) { - super(offset, length); - fStyle = highlighting; - fLock = lock; - fReadOnly = isReadOnly; - } - - public HighlightedPosition(int offset, int length, HighlightingStyle highlighting, Object lock) { - this(offset, length, highlighting, lock, false); - } - - public HighlightedPosition(Position position, HighlightingStyle highlighting, Object lock) { - this(position.offset, position.length, highlighting, lock, false); - } - - public HighlightedPosition(Position position, HighlightingStyle highlighting, Object lock, boolean isReadOnly) { - this(position.offset, position.length, highlighting, lock, isReadOnly); - } - - /** - * @return Returns a corresponding style range. - */ - public StyleRange createStyleRange() { - int len= 0; - if (fStyle.isEnabled()) - len= getLength(); - - TextAttribute textAttribute = fStyle.getTextAttribute(); - int style = textAttribute.getStyle(); - int fontStyle = style & (SWT.ITALIC | SWT.BOLD | SWT.NORMAL); - StyleRange styleRange = new StyleRange(getOffset(), len, textAttribute.getForeground(), textAttribute.getBackground(), fontStyle); - styleRange.strikeout = (style & TextAttribute.STRIKETHROUGH) != 0; - styleRange.underline = (style & TextAttribute.UNDERLINE) != 0; - - return styleRange; - } - - /** - * Uses reference equality for the highlighting. - * - * @param off The offset - * @param len The length - * @param highlighting The highlighting - * @return <code>true</code> iff the given offset, length and highlighting are equal to the internal ones. - */ - public boolean isEqual(int off, int len, HighlightingStyle highlighting) { - synchronized (fLock) { - return !isDeleted() && getOffset() == off && getLength() == len && fStyle == highlighting; - } - } - - /** - * Uses reference equality for the highlighting. - * - * @param pos The position - * @param highlighting The highlighting - * @return <code>true</code> iff the given offset, length and highlighting are equal to the internal ones. - */ - public boolean isEqual(Position pos, HighlightingStyle highlighting) { - synchronized (fLock) { - return !isDeleted() && getOffset() == pos.getOffset() && getLength() == pos.getLength() && fStyle == highlighting; - } - } - - /** - * Is this position contained in the given range (inclusive)? Synchronizes on position updater. - * - * @param off The range offset - * @param len The range length - * @return <code>true</code> iff this position is not delete and contained in the given range. - */ - public boolean isContained(int off, int len) { - synchronized (fLock) { - return !isDeleted() && off <= getOffset() && off + len >= getOffset() + getLength(); - } - } - - public void update(int off, int len) { - synchronized (fLock) { - super.setOffset(off); - super.setLength(len); - } - } - - /* - * @see org.eclipse.jface.text.Position#setLength(int) - */ - public void setLength(int length) { - synchronized (fLock) { - super.setLength(length); - } - } - - /* - * @see org.eclipse.jface.text.Position#setOffset(int) - */ - public void setOffset(int offset) { - synchronized (fLock) { - super.setOffset(offset); - } - } - - /* - * @see org.eclipse.jface.text.Position#delete() - */ - public void delete() { - synchronized (fLock) { - super.delete(); - } - } - - /* - * @see org.eclipse.jface.text.Position#undelete() - */ - public void undelete() { - synchronized (fLock) { - super.undelete(); - } - } - - /** - * @return Returns the highlighting. - */ - public HighlightingStyle getHighlighting() { - return fStyle; - } - - public boolean isReadOnly() { - return fReadOnly; - } - } - - /** - * Highlighted ranges. - */ - public static class HighlightedRange extends Region { - /** The highlighting key as returned by {@link ISemanticHighlighting#getPreferenceKey()}. */ - private String fKey; - - /** - * Initialize with the given offset, length and highlighting key. - * - * @param offset - * @param length - * @param key the highlighting key as returned by {@link ISemanticHighlighting#getPreferenceKey()} - */ - public HighlightedRange(int offset, int length, String key) { - super(offset, length); - fKey = key; - } - - /** - * @return the highlighting key as returned by {@link ISemanticHighlighting#getPreferenceKey()} - */ - public String getKey() { - return fKey; - } - - /* - * @see org.eclipse.jface.text.Region#equals(java.lang.Object) - */ - public boolean equals(Object o) { - return super.equals(o) && o instanceof HighlightedRange && fKey.equals(((HighlightedRange)o).getKey()); - } - - /* - * @see org.eclipse.jface.text.Region#hashCode() - */ - public int hashCode() { - return super.hashCode() | fKey.hashCode(); - } - } - - private static final String SEMANTIC_HIGHLIGHTING_EXTENSION_POINT = "semanticHighlighting"; //$NON-NLS-1$ - private static final String TARGET_ATTR = "target"; //$NON-NLS-1$ - private static final String CLASS_ATTR = "class"; //$NON-NLS-1$ - private static final String STYLE_KEY_ATTR = "styleStringKey"; //$NON-NLS-1$ - - private ISourceViewer fSourceViewer; - private IPreferenceStore fPreferenceStore; - private SourceViewerConfiguration fConfiguration; - private StructuredPresentationReconciler fPresentationReconciler; - private String fContentTypeId; - - private SemanticHighlightingPresenter fPresenter; - private SemanticHighlightingReconciler fReconciler; - - /** The semantic highlightings for the content type */ - private ISemanticHighlighting[] fHighlightings; - /** The semantic highlighting styles associated with the semantic highlightings */ - private HighlightingStyle[] fHighlightingStyles; - /** The semantic highlighting style string preference keys. null of the highlighting doesn't support it */ - private String[] fHighlightingStyleStringKeys; - - private IPropertyChangeListener fHighlightingChangeListener = new IPropertyChangeListener() { - - public void propertyChange(PropertyChangeEvent event) { - handleHighlightingPropertyChange(event); - } - }; - - public void propertyChange(PropertyChangeEvent event) { - handlePropertyChange(event); - } - - public void install(ISourceViewer sourceViewer, IPreferenceStore preferenceStore, SourceViewerConfiguration configuration, String contentTypeId) { - fSourceViewer = sourceViewer; - fPreferenceStore = preferenceStore; - fConfiguration = configuration; - fContentTypeId = contentTypeId; - - fPreferenceStore.addPropertyChangeListener(this); - fPresentationReconciler = (StructuredPresentationReconciler) fConfiguration.getPresentationReconciler(fSourceViewer); - - if (isEnabled()) { - enable(); - } - } - - /** - * Load the semantic highlightings defined for this content type. - */ - private void loadSemanticHighlightings() { - List semantics = new ArrayList(0); - - ISemanticHighlighting highlighting = null; - String styleKey = null; - IConfigurationElement[] elements = Platform.getExtensionRegistry().getConfigurationElementsFor(SSEUIPlugin.ID, SEMANTIC_HIGHLIGHTING_EXTENSION_POINT); - - IContentType contentType = Platform.getContentTypeManager().getContentType(fContentTypeId); - - for (int i = 0; i < elements.length; i++) { - String[] targets = StringUtils.unpack(elements[i].getAttribute(TARGET_ATTR)); - for (int j = 0; j < targets.length; j++) { - IContentType targetContentType = Platform.getContentTypeManager().getContentType(targets[j]); - /* Apply semantic highlighting to kinds of targetContentType */ - if (contentType.isKindOf(targetContentType)) { - try { - highlighting = (ISemanticHighlighting) elements[i].createExecutableExtension(CLASS_ATTR); - styleKey = elements[i].getAttribute(STYLE_KEY_ATTR); - } catch (CoreException e) { - Logger.logException(e); - } - if (highlighting != null) - semantics.add(new SemanticContent(targetContentType, highlighting, styleKey)); - - break; - } - } - } - /* Sort the semantics, so that styles will be applied from general to specific */ - Collections.sort(semantics); - fHighlightings = new ISemanticHighlighting[semantics.size()]; - fHighlightingStyles = new HighlightingStyle[semantics.size()]; - fHighlightingStyleStringKeys = new String[semantics.size()]; - - for (int i = 0; i < semantics.size(); i++) { - fHighlightings[i] = ((SemanticContent) semantics.get(i)).getHighlighting(); - styleKey = ((SemanticContent) semantics.get(i)).getStyleKey(); - fHighlightingStyles[i] = createHighlightingStyle(((SemanticContent) semantics.get(i)).getHighlighting(), styleKey); - fHighlightingStyleStringKeys[i] = styleKey; - } - } - - /** - * This class is used for relating a semantic highlighting to a content type. - * The content type is used in the sorting algorithm. Content types that are more specific - * to the file's content type will cause styles to be applied from general to specific - */ - private class SemanticContent implements Comparable { - public IContentType type; - public ISemanticHighlighting highlighting; - public String styleKey; - - public SemanticContent(IContentType type, ISemanticHighlighting highlighting, String styleKey) { - this.type = type; - this.highlighting = highlighting; - this.styleKey = styleKey; - } - - public int compareTo(Object arg0) { - SemanticContent other = (SemanticContent) arg0; - /* Equal weighting for the same types */ - if (this.type.equals(other.type)) - return 0; - /* Subtypes have more weight than base types */ - if (this.type.isKindOf(other.type)) - return 1; - return -1; - } - - public ISemanticHighlighting getHighlighting() { - return highlighting; - } - - public String getStyleKey() { - return styleKey; - } - } - - /** - * Creates a highlighting style based on the preferences defined in the semantic highlighting - * @param highlighting the semantic highlighting - * @return a highlighting style based on the preferences of the semantic highlighting - */ - private HighlightingStyle createHighlightingStyle(ISemanticHighlighting highlighting, String styleKey) { - IPreferenceStore store = highlighting.getPreferenceStore(); - HighlightingStyle highlightingStyle = null; - if (store != null) { - TextAttribute attribute = null; - // A style string is used instead of separate attribute keys - if (styleKey != null) { - attribute = createTextAttribute(store.getString(styleKey)); - } - else { - int style = getBoolean(store, highlighting.getBoldPreferenceKey()) ? SWT.BOLD : SWT.NORMAL; - - if (getBoolean(store, highlighting.getItalicPreferenceKey())) - style |= SWT.ITALIC; - if (getBoolean(store, highlighting.getStrikethroughPreferenceKey())) - style |= TextAttribute.STRIKETHROUGH; - if (getBoolean(store, highlighting.getUnderlinePreferenceKey())) - style |= TextAttribute.UNDERLINE; - - String rgbString = getString(store, highlighting.getColorPreferenceKey()); - Color color = null; - Color bgColor = null; - - if (rgbString != null) - color = EditorUtility.getColor(ColorHelper.toRGB(rgbString)); - if (highlighting instanceof ISemanticHighlightingExtension2) { - rgbString = getString(store, ((ISemanticHighlightingExtension2) highlighting).getBackgroundColorPreferenceKey()); - if (rgbString != null) { - bgColor = EditorUtility.getColor(ColorHelper.toRGB(rgbString)); - } - } - attribute = new TextAttribute(color, bgColor, style); - } - - store.addPropertyChangeListener(fHighlightingChangeListener); - boolean isEnabled = getBoolean(store, highlighting.getEnabledPreferenceKey()); - highlightingStyle = new HighlightingStyle(attribute, isEnabled); - } - return highlightingStyle; - } - - /** - * Creates a text attribute from the style string - * - * @param styleValue style string in the form: <code>RGB foreground (#rrggbb) | RGB background (#rrggbb) | bold (true/false) | italic (true/false) | strikethrough (true/false) | underline (true/false)</code> - * @return text attribute created from the <code>styleValue</code> or null if the <code>styleValue</code> is invalid - */ - private TextAttribute createTextAttribute(String styleValue) { - String[] values = ColorHelper.unpackStylePreferences(styleValue); - if (values.length < 6) - return null; - - RGB foreground = ColorHelper.toRGB(values[0]); - RGB background = ColorHelper.toRGB(values[1]); - boolean bold = Boolean.valueOf(values[2]).booleanValue(); - boolean italic = Boolean.valueOf(values[3]).booleanValue(); - boolean strikethrough = Boolean.valueOf(values[4]).booleanValue(); - boolean underline = Boolean.valueOf(values[5]).booleanValue(); - - int style = SWT.NORMAL; - if (bold) - style = style | SWT.BOLD; - if (italic) - style = style | SWT.ITALIC; - if (strikethrough) - style = style | TextAttribute.STRIKETHROUGH; - if (underline) - style = style | TextAttribute.UNDERLINE; - - return createTextAttribute(foreground, background, style); - } - - private TextAttribute createTextAttribute(RGB foreground, RGB background, int style) { - return new TextAttribute((foreground != null) ? EditorUtility.getColor(foreground) : null, (background != null) ? EditorUtility.getColor(background) : null, style); - } - - /** - * Looks up a boolean preference by <code>key</code> from the preference store - * @param store the preference store to lookup the preference from - * @param key the key the preference is stored under - * @return the preference value from the preference store iff key is not null - */ - private boolean getBoolean(IPreferenceStore store, String key) { - return (key == null) ? false : store.getBoolean(key); - } - - /** - * Looks up a String preference by <code>key</code> from the preference store - * @param store the preference store to lookup the preference from - * @param key the key the preference is stored under - * @return the preference value from the preference store iff key is not null - */ - private String getString(IPreferenceStore store, String key) { - return (key == null) ? null : store.getString(key); - } - - /** - * Enable semantic highlighting. - */ - private void enable() { - - loadSemanticHighlightings(); - - fPresenter = new SemanticHighlightingPresenter(); - fPresenter.install(fSourceViewer, fPresentationReconciler); -// if (fEditor != null) { - fReconciler = new SemanticHighlightingReconciler(); - fReconciler.install(fSourceViewer, fPresenter, fHighlightings, fHighlightingStyles); - IReconciler reconciler = fConfiguration.getReconciler(fSourceViewer); - if (reconciler instanceof DocumentRegionProcessor) - ((DocumentRegionProcessor) reconciler).setSemanticHighlightingStrategy(fReconciler); -// } else { -// fPresenter.updatePresentation(null, createHardcodedPositions(), new HighlightedPosition[0]); -// } - } - - /** - * Disable semantic highlighting - */ - private void disable() { - if (fReconciler != null) { - fReconciler.uninstall(); - fReconciler = null; - } - - if (fPresenter != null) { - fPresenter.uninstall(); - fPresenter = null; - } - - if (fHighlightings != null) - disposeHighlightings(); - } - - private void disposeHighlightings() { - /* Remove the property change listener before clearing the lists */ - if (fHighlightings != null) { - for (int i = 0; i < fHighlightings.length; i++) { - IPreferenceStore store = fHighlightings[i].getPreferenceStore(); - if (store != null) - store.removePropertyChangeListener(fHighlightingChangeListener); - } - } - - fHighlightings = null; - fHighlightingStyles = null; - fHighlightingStyleStringKeys = null; - } - - /** - * Handles property change events for individual semantic highlightings. - * @param event - */ - private void handleHighlightingPropertyChange(PropertyChangeEvent event) { - String property = event.getProperty(); - if (property == null) - return; - - boolean refreshRequired = false; - - for (int i = 0; i < fHighlightings.length; i++) { - ISemanticHighlighting highlighting = fHighlightings[i]; - - if (fHighlightingStyleStringKeys[i] != null) { - if (property.equals(fHighlightingStyleStringKeys[i])) { - adaptToStyleChange(fHighlightingStyles[i], event); - fPresenter.highlightingStyleChanged(fHighlightingStyles[i]); - refreshRequired = true; - continue; - } - } - - if (property.equals(highlighting.getBoldPreferenceKey())) { - adaptToTextStyleChange(fHighlightingStyles[i], event, SWT.BOLD); - fPresenter.highlightingStyleChanged(fHighlightingStyles[i]); - refreshRequired = true; - continue; - } - - if (property.equals(highlighting.getColorPreferenceKey())) { - adaptToTextForegroundChange(fHighlightingStyles[i], event); - fPresenter.highlightingStyleChanged(fHighlightingStyles[i]); - refreshRequired = true; - continue; - } - - if (property.equals(highlighting.getEnabledPreferenceKey())) { - adaptToEnablementChange(fHighlightingStyles[i], event); - fPresenter.highlightingStyleChanged(fHighlightingStyles[i]); - refreshRequired = true; - continue; - } - - if (property.equals(highlighting.getItalicPreferenceKey())) { - adaptToTextStyleChange(fHighlightingStyles[i], event, SWT.ITALIC); - fPresenter.highlightingStyleChanged(fHighlightingStyles[i]); - refreshRequired = true; - continue; - } - - if (property.equals(highlighting.getStrikethroughPreferenceKey())) { - adaptToTextStyleChange(fHighlightingStyles[i], event, TextAttribute.STRIKETHROUGH); - fPresenter.highlightingStyleChanged(fHighlightingStyles[i]); - refreshRequired = true; - continue; - } - - if (property.equals(highlighting.getUnderlinePreferenceKey())) { - adaptToTextStyleChange(fHighlightingStyles[i], event, TextAttribute.UNDERLINE); - fPresenter.highlightingStyleChanged(fHighlightingStyles[i]); - refreshRequired = true; - continue; - } - - if (highlighting instanceof ISemanticHighlightingExtension2 && property.equals(((ISemanticHighlightingExtension2) highlighting).getBackgroundColorPreferenceKey())) { - adaptToTextBackgroundChange(fHighlightingStyles[i], event); - fPresenter.highlightingStyleChanged(fHighlightingStyles[i]); - refreshRequired = true; - continue; - } - } - - if (refreshRequired && fReconciler != null) - fReconciler.refresh(); - } - - /** - * Handles property changes for enabling and disabling semantic highlighting for - * Structured Source Editors - * @param event - */ - private void handlePropertyChange(PropertyChangeEvent event) { - String property = event.getProperty(); - if (property == null || !property.equals(EditorPreferenceNames.SEMANTIC_HIGHLIGHTING)) - return; - - Object newValue = event.getNewValue(); - if (newValue instanceof Boolean) { - if (((Boolean) newValue).booleanValue()) - enable(); - else - disable(); - } - - if (fReconciler != null) - fReconciler.refresh(); - } - - private void adaptToEnablementChange(HighlightingStyle highlighting, PropertyChangeEvent event) { - Object value = event.getNewValue(); - boolean eventValue; - if (value instanceof Boolean) - eventValue = ((Boolean) value).booleanValue(); - else if (IPreferenceStore.TRUE.equals(value)) - eventValue = true; - else - eventValue = false; - highlighting.setEnabled(eventValue); - } - - private void adaptToTextForegroundChange(HighlightingStyle highlighting, PropertyChangeEvent event) { - RGB rgb = null; - - Object value = event.getNewValue(); - if (value instanceof RGB) - rgb= (RGB) value; - else if (value instanceof String) - rgb= ColorHelper.toRGB( (String) value); - - if (rgb != null) { - Color color= EditorUtility.getColor(rgb); - TextAttribute oldAttr= highlighting.getTextAttribute(); - highlighting.setTextAttribute(new TextAttribute(color, oldAttr.getBackground(), oldAttr.getStyle())); - } - } - - private void adaptToTextBackgroundChange(HighlightingStyle highlighting, PropertyChangeEvent event) { - RGB rgb = null; - - Object value = event.getNewValue(); - if (value instanceof RGB) - rgb = (RGB) value; - else if (value instanceof String) - rgb = ColorHelper.toRGB( (String) value); - - if (rgb != null) { - Color color= EditorUtility.getColor(rgb); - TextAttribute oldAttr= highlighting.getTextAttribute(); - highlighting.setTextAttribute(new TextAttribute(oldAttr.getForeground(), color, oldAttr.getStyle())); - } - } - - private void adaptToTextStyleChange(HighlightingStyle highlighting, PropertyChangeEvent event, int styleAttribute) { - boolean eventValue = false; - Object value = event.getNewValue(); - if (value instanceof Boolean) - eventValue = ((Boolean) value).booleanValue(); - else if (IPreferenceStore.TRUE.equals(value)) - eventValue = true; - - TextAttribute oldAttr = highlighting.getTextAttribute(); - boolean activeValue = (oldAttr.getStyle() & styleAttribute) == styleAttribute; - - if (activeValue != eventValue) - highlighting.setTextAttribute(new TextAttribute(oldAttr.getForeground(), oldAttr.getBackground(), eventValue ? oldAttr.getStyle() | styleAttribute : oldAttr.getStyle() & ~styleAttribute)); - } - - /** - * Adapts to a style string change - * - * @param highlighting the highlighting style to update - * @param event the event that triggered the change - */ - private void adaptToStyleChange(HighlightingStyle highlighting, PropertyChangeEvent event) { - Object value = event.getNewValue(); - if (value instanceof String) { - TextAttribute attr = createTextAttribute((String) value); - if (attr != null) - highlighting.setTextAttribute(attr); - } - } - - /** - * @return <code>true</code> iff semantic highlighting is enabled in the preferences - */ - private boolean isEnabled() { - return (fPreferenceStore != null) ? fPreferenceStore.getBoolean(EditorPreferenceNames.SEMANTIC_HIGHLIGHTING) : false; - } - - public void uninstall() { - disable(); - - if (fPreferenceStore != null) { - fPreferenceStore.removePropertyChangeListener(this); - fPreferenceStore = null; - } - - fSourceViewer = null; - fConfiguration = null; - fPresentationReconciler = null; - } - -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/style/SemanticHighlightingPresenter.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/style/SemanticHighlightingPresenter.java deleted file mode 100644 index 093ec05b77..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/style/SemanticHighlightingPresenter.java +++ /dev/null @@ -1,1067 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009, 2011 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.style; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.BadPositionCategoryException; -import org.eclipse.jface.text.DocumentEvent; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IDocumentListener; -import org.eclipse.jface.text.IPositionUpdater; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ISynchronizable; -import org.eclipse.jface.text.ITextInputListener; -import org.eclipse.jface.text.ITextPresentationListener; -import org.eclipse.jface.text.ITextViewerExtension2; -import org.eclipse.jface.text.ITextViewerExtension4; -import org.eclipse.jface.text.Position; -import org.eclipse.jface.text.Region; -import org.eclipse.jface.text.TextPresentation; -import org.eclipse.jface.text.source.ISourceViewer; -import org.eclipse.swt.custom.StyleRange; -import org.eclipse.swt.graphics.Color; -import org.eclipse.swt.graphics.RGB; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument; -import org.eclipse.wst.sse.ui.internal.Logger; -import org.eclipse.wst.sse.ui.internal.SSEUIPlugin; -import org.eclipse.wst.sse.ui.internal.StructuredTextViewer; -import org.eclipse.wst.sse.ui.internal.preferences.EditorPreferenceNames; -import org.eclipse.wst.sse.ui.internal.provisional.style.StructuredPresentationReconciler; -import org.eclipse.wst.sse.ui.internal.style.SemanticHighlightingManager.HighlightedPosition; -import org.eclipse.wst.sse.ui.internal.style.SemanticHighlightingManager.HighlightingStyle; -import org.eclipse.wst.sse.ui.internal.util.EditorUtility; - -/** - * Semantic highlighting presenter - UI thread implementation. Based on - * org.eclipse.jdt.internal.ui.javaeditor.SemanticHighlightingPresenter - * - * @since 3.1 - */ -public class SemanticHighlightingPresenter implements ITextPresentationListener, ITextInputListener, IDocumentListener { - - /** - * Semantic highlighting position updater. - */ - private class HighlightingPositionUpdater implements IPositionUpdater { - - /** The position category. */ - private final String fCategory; - - /** - * Creates a new updater for the given <code>category</code>. - * - * @param category the new category. - */ - public HighlightingPositionUpdater(String category) { - fCategory= category; - } - - /* - * @see org.eclipse.jface.text.IPositionUpdater#update(org.eclipse.jface.text.DocumentEvent) - */ - public void update(DocumentEvent event) { - - int eventOffset= event.getOffset(); - int eventOldLength= event.getLength(); - int eventEnd= eventOffset + eventOldLength; - - try { - Position[] positions= event.getDocument().getPositions(fCategory); - - for (int i= 0; i != positions.length; i++) { - - HighlightedPosition position= (HighlightedPosition) positions[i]; - - // Also update deleted positions because they get deleted by the background thread and removed/invalidated only in the UI runnable -// if (position.isDeleted()) -// continue; - - int offset= position.getOffset(); - int length= position.getLength(); - int end= offset + length; - - if (offset > eventEnd) - updateWithPrecedingEvent(position, event); - else if (end < eventOffset) { - // do nothing - // updateWithSucceedingEvent(position, event); - } - else if (offset <= eventOffset && end >= eventEnd) { - // Previous region updated to overlap the beginning of this one; just bump the start. - if (i > 0 && positions[i - 1].offset + positions[i - 1].length > offset) - updateWithPrecedingEvent(position, event); - else - updateWithIncludedEvent(position, event); - } - else if (offset <= eventOffset) - updateWithOverEndEvent(position, event); - else if (end >= eventEnd) - updateWithOverStartEvent(position, event); - else - updateWithIncludingEvent(position, event); - } - } catch (BadPositionCategoryException e) { - // ignore and return - } - } - - /** - * Update the given position with the given event. The event precedes the position. - * - * @param position The position - * @param event The event - */ - private void updateWithPrecedingEvent(HighlightedPosition position, DocumentEvent event) { - String newText= event.getText(); - int eventNewLength= newText != null ? newText.length() : 0; - int deltaLength= eventNewLength - event.getLength(); - - position.setOffset(position.getOffset() + deltaLength); - } - - /** - * Update the given position with the given event. The event succeeds the position. - * - * @param position The position - * @param event The event - */ -// private void updateWithSucceedingEvent(HighlightedPosition position, DocumentEvent event) { -// } - - /** - * Update the given position with the given event. The event is included by the position. - * - * @param position The position - * @param event The event - */ - private void updateWithIncludedEvent(HighlightedPosition position, DocumentEvent event) { - int eventOffset= event.getOffset(); - String newText= event.getText(); - if (newText == null) - newText= ""; //$NON-NLS-1$ - int eventNewLength= newText.length(); - - int deltaLength= eventNewLength - event.getLength(); - - int offset= position.getOffset(); - int length= position.getLength(); - int end= offset + length; - - int includedLength= 0; - while (includedLength < eventNewLength && !Character.isWhitespace(newText.charAt(includedLength))) - includedLength++; - if (includedLength == eventNewLength) - position.setLength(length + deltaLength); - else { - int newLeftLength= eventOffset - offset + includedLength; - - int excludedLength= eventNewLength; - while (excludedLength > 0 && !Character.isWhitespace(newText.charAt(excludedLength - 1))) - excludedLength--; - int newRightOffset= eventOffset + excludedLength; - int newRightLength= end + deltaLength - newRightOffset; - - if (newRightLength == 0) { - position.setLength(newLeftLength); - } else { - if (newLeftLength == 0) { - position.update(newRightOffset, newRightLength); - } else { - position.setLength(newLeftLength); - addPositionFromUI(position); - } - } - } - } - - /** - * Update the given position with the given event. The event overlaps with the end of the position. - * - * @param position The position - * @param event The event - */ - private void updateWithOverEndEvent(HighlightedPosition position, DocumentEvent event) { - String newText= event.getText(); - if (newText == null) - newText= ""; //$NON-NLS-1$ - int eventNewLength= newText.length(); - - int includedLength= 0; - while (includedLength < eventNewLength && !Character.isWhitespace(newText.charAt(includedLength))) - includedLength++; - position.setLength(event.getOffset() - position.getOffset() + includedLength); - } - - /** - * Update the given position with the given event. The event overlaps with the start of the position. - * - * @param position The position - * @param event The event - */ - private void updateWithOverStartEvent(HighlightedPosition position, DocumentEvent event) { - int eventOffset= event.getOffset(); - int eventEnd= eventOffset + event.getLength(); - - String newText= event.getText(); - if (newText == null) - newText= ""; //$NON-NLS-1$ - int eventNewLength= newText.length(); - - int excludedLength= eventNewLength; - while (excludedLength > 0 && !Character.isWhitespace(newText.charAt(excludedLength - 1))) - excludedLength--; - int deleted= eventEnd - position.getOffset(); - int inserted= eventNewLength - excludedLength; - position.update(eventOffset + excludedLength, position.getLength() - deleted + inserted); - } - - /** - * Update the given position with the given event. The event includes the position. - * - * @param position The position - * @param event The event - */ - private void updateWithIncludingEvent(HighlightedPosition position, DocumentEvent event) { - position.delete(); - position.update(event.getOffset(), 0); - } - } - - /** Position updater */ - private IPositionUpdater fPositionUpdater= new HighlightingPositionUpdater(getPositionCategory()); - - /** The source viewer this semantic highlighting reconciler is installed on */ - private ISourceViewer fSourceViewer; - /** The background presentation reconciler */ - private StructuredPresentationReconciler fPresentationReconciler; - - /** UI's current highlighted positions - can contain <code>null</code> elements */ - private List fPositions= new ArrayList(); - /** UI position lock */ - private Object fPositionLock= new Object(); - - /** <code>true</code> iff the current reconcile is canceled. */ - private boolean fIsCanceled= false; - - /** Read-only color support */ - private YUV_RGBConverter rgbConverter; - private Map readOnlyColorTable; - double readOnlyForegroundScaleFactor = 30; - - public SemanticHighlightingPresenter() { - // no listener for now since there's no UI to change the value - IPreferenceStore editorStore = SSEUIPlugin.getDefault().getPreferenceStore(); - readOnlyForegroundScaleFactor = editorStore.getInt(EditorPreferenceNames.READ_ONLY_FOREGROUND_SCALE); - } - - /** - * Creates and returns a new highlighted position with the given offset, length and highlighting. - * <p> - * NOTE: Also called from background thread. - * </p> - * - * @param offset The offset - * @param length The length - * @param highlighting The highlighting - * @return The new highlighted position - */ - public HighlightedPosition createHighlightedPosition(int offset, int length, HighlightingStyle highlighting) { - // TODO: reuse deleted positions - return new HighlightedPosition(offset, length, highlighting, fPositionUpdater); - } - - /** - * Creates and returns a new highlighted position from the given position and highlighting. - * <p> - * NOTE: Also called from background thread. - * </p> - * - * @param position The position - * @param highlighting The highlighting - * @return The new highlighted position - */ - public HighlightedPosition createHighlightedPosition(Position position, HighlightingStyle highlighting) { - // TODO: reuse deleted positions - return new HighlightedPosition(position, highlighting, fPositionUpdater); - } - - /** - * Creates and returns a new highlighted position from the given position and highlighting. - * <p> - * NOTE: Also called from background thread. - * </p> - * - * @param position The position - * @param highlighting The highlighting - * @param isReadOnly Is this a read-only position - * @return The new highlighted position - */ - public HighlightedPosition createHighlightedPosition(Position position, HighlightingStyle highlighting, boolean isReadOnly) { - // TODO: reuse deleted positions - return new HighlightedPosition(position, highlighting, fPositionUpdater, isReadOnly); - } - - /** - * Adds all current positions to the given list. - * <p> - * NOTE: Called from background thread. - * </p> - * - * @param list The list - */ - public void addAllPositions(List list) { - synchronized (fPositionLock) { - list.addAll(fPositions); - } - } - - /** - * Create a text presentation in the background. - * <p> - * NOTE: Called from background thread. - * </p> - * - * @param addedPositions the added positions - * @param removedPositions the removed positions - * @return the text presentation or <code>null</code>, if reconciliation should be canceled - */ - public TextPresentation createPresentation(List addedPositions, List removedPositions) { - ISourceViewer sourceViewer= fSourceViewer; - StructuredPresentationReconciler presentationReconciler= fPresentationReconciler; - if (sourceViewer == null || presentationReconciler == null) - return null; - - if (isCanceled()) - return null; - - IDocument document= sourceViewer.getDocument(); - if (document == null) - return null; - - int minStart= Integer.MAX_VALUE; - int maxEnd= Integer.MIN_VALUE; - for (int i= 0, n= removedPositions.size(); i < n; i++) { - Position position= (Position) removedPositions.get(i); - int offset= position.getOffset(); - minStart= Math.min(minStart, offset); - maxEnd= Math.max(maxEnd, offset + position.getLength()); - } - for (int i= 0, n= addedPositions.size(); i < n; i++) { - Position position= (Position) addedPositions.get(i); - int offset= position.getOffset(); - minStart= Math.min(minStart, offset); - maxEnd= Math.max(maxEnd, offset + position.getLength()); - } - - if (minStart < maxEnd) - try { - return presentationReconciler.createRepairDescription(new Region(minStart, maxEnd - minStart), document); - } catch (RuntimeException e) { - // Assume concurrent modification from UI thread - } - - return null; - } - - /** - * Create a runnable for updating the presentation. - * <p> - * NOTE: Called from background thread. - * </p> - * @param textPresentation the text presentation - * @param addedPositions the added positions - * @param removedPositions the removed positions - * @return the runnable or <code>null</code>, if reconciliation should be canceled - */ - public Runnable createUpdateRunnable(final TextPresentation textPresentation, List addedPositions, List removedPositions) { - if (fSourceViewer == null || textPresentation == null) - return null; - - // TODO: do clustering of positions and post multiple fast runnables - final HighlightedPosition[] added= new SemanticHighlightingManager.HighlightedPosition[addedPositions.size()]; - addedPositions.toArray(added); - final SemanticHighlightingManager.HighlightedPosition[] removed= new SemanticHighlightingManager.HighlightedPosition[removedPositions.size()]; - removedPositions.toArray(removed); - - if (isCanceled()) - return null; - - Runnable runnable= new Runnable() { - public void run() { - updatePresentation(textPresentation, added, removed); - } - }; - return runnable; - } - - /** - * Invalidate the presentation of the positions based on the given added positions and the existing deleted positions. - * Also unregisters the deleted positions from the document and patches the positions of this presenter. - * <p> - * NOTE: Indirectly called from background thread by UI runnable. - * </p> - * @param textPresentation the text presentation or <code>null</code>, if the presentation should computed in the UI thread - * @param addedPositions the added positions - * @param removedPositions the removed positions - */ - public void updatePresentation(TextPresentation textPresentation, HighlightedPosition[] addedPositions, HighlightedPosition[] removedPositions) { - if (fSourceViewer == null) - return; - -// checkOrdering("added positions: ", Arrays.asList(addedPositions)); //$NON-NLS-1$ -// checkOrdering("removed positions: ", Arrays.asList(removedPositions)); //$NON-NLS-1$ -// checkOrdering("old positions: ", fPositions); //$NON-NLS-1$ - - // TODO: double-check consistency with document.getPositions(...) - // TODO: reuse removed positions - if (isCanceled()) - return; - - IDocument document= fSourceViewer.getDocument(); - if (document == null) - return; - - String positionCategory= getPositionCategory(); - - List removedPositionsList= Arrays.asList(removedPositions); - - try { - synchronized (fPositionLock) { - List oldPositions= fPositions; - int newSize= Math.max(fPositions.size() + addedPositions.length - removedPositions.length, 10); - - /* - * The following loop is a kind of merge sort: it merges two List<Position>, each - * sorted by position.offset, into one new list. The first of the two is the - * previous list of positions (oldPositions), from which any deleted positions get - * removed on the fly. The second of two is the list of added positions. The result - * is stored in newPositions. - */ - List newPositions= new ArrayList(newSize); - Position position= null; - Position addedPosition= null; - for (int i= 0, j= 0, n= oldPositions.size(), m= addedPositions.length; i < n || position != null || j < m || addedPosition != null;) { - // loop variant: i + j < old(i + j) - - // a) find the next non-deleted Position from the old list - while (position == null && i < n) { - position= (Position) oldPositions.get(i++); - if (position.isDeleted() || contain(removedPositionsList, position)) { - document.removePosition(positionCategory, position); - position= null; - } - } - - // b) find the next Position from the added list - if (addedPosition == null && j < m) { - addedPosition= addedPositions[j++]; - document.addPosition(positionCategory, addedPosition); - } - - // c) merge: add the next of position/addedPosition with the lower offset - if (position != null) { - if (addedPosition != null) - if (position.getOffset() <= addedPosition.getOffset()) { - newPositions.add(position); - position= null; - } else { - newPositions.add(addedPosition); - addedPosition= null; - } - else { - newPositions.add(position); - position= null; - } - } else if (addedPosition != null) { - newPositions.add(addedPosition); - addedPosition= null; - } - } - fPositions= newPositions; - Collections.sort(fPositions, new Comparator() { - - public int compare(Object arg0, Object arg1) { - Position p1 = (Position) arg0; - Position p2 = (Position) arg1; - return p1.offset - p2.offset; - } - }); - } - } catch (BadPositionCategoryException e) { - // Should not happen - Logger.logException(e); - } catch (BadLocationException e) { - // Should not happen - Logger.logException(e); - } -// checkOrdering("new positions: ", fPositions); //$NON-NLS-1$ - - if (textPresentation != null) - fSourceViewer.changeTextPresentation(textPresentation, false); - else - fSourceViewer.invalidateTextPresentation(); - } - -// private void checkOrdering(String s, List positions) { -// Position previous= null; -// for (int i= 0, n= positions.size(); i < n; i++) { -// Position current= (Position) positions.get(i); -// if (previous != null && previous.getOffset() + previous.getLength() > current.getOffset()) -// return; -// } -// } - - /** - * Returns <code>true</code> iff the positions contain the position. - * @param positions the positions, must be ordered by offset but may overlap - * @param position the position - * @return <code>true</code> iff the positions contain the position - */ - private boolean contain(List positions, Position position) { - return indexOf(positions, position) != -1; - } - - /** - * Returns index of the position in the positions, <code>-1</code> if not found. - * @param positions the positions, must be ordered by offset but may overlap - * @param position the position - * @return the index - */ - private int indexOf(List positions, Position position) { - int index= computeIndexAtOffset(positions, position.getOffset()); - int size= positions.size(); - while (index < size) { - if (positions.get(index) == position) - return index; - index++; - } - return -1; - } - - /** - * Insert the given position in <code>fPositions</code>, s.t. the offsets remain in linear order. - * - * @param position The position for insertion - */ - private void insertPosition(Position position) { - int i= computeIndexAfterOffset(fPositions, position.getOffset()); - fPositions.add(i, position); - } - - /** - * Returns the index of the first position with an offset greater than the given offset. - * - * @param positions the positions, must be ordered by offset and must not overlap - * @param offset the offset - * @return the index of the last position with an offset greater than the given offset - */ - private int computeIndexAfterOffset(List positions, int offset) { - int i= -1; - int j= positions.size(); - while (j - i > 1) { - int k= (i + j) >> 1; - Position position= (Position) positions.get(k); - if (position.getOffset() > offset) - j= k; - else - i= k; - } - return j; - } - - /** - * Returns the index of the first position with an offset equal or greater than the given offset. - * - * @param positions the positions, must be ordered by offset and must not overlap - * @param offset the offset - * @return the index of the last position with an offset equal or greater than the given offset - */ - private int computeIndexAtOffset(List positions, int offset) { - int i= -1; - int j= positions.size(); - while (j - i > 1) { - int k= (i + j) >> 1; - Position position= (Position) positions.get(k); - if (position.getOffset() >= offset) - j= k; - else - i= k; - } - return j; - } - - /* - * @see org.eclipse.jface.text.ITextPresentationListener#applyTextPresentation(org.eclipse.jface.text.TextPresentation) - */ - public void applyTextPresentation(TextPresentation textPresentation) { - IRegion region= textPresentation.getExtent(); - int minStart= Integer.MAX_VALUE; - int maxEnd= Integer.MIN_VALUE; - int i= computeIndexAtOffset(fPositions, region.getOffset()), n= computeIndexAtOffset(fPositions, region.getOffset() + region.getLength()); - if (n - i > 2) { - List ranges= new ArrayList(n - i); - for (; i < n; i++) { - HighlightedPosition position= (HighlightedPosition) fPositions.get(i); - if (!position.isDeleted()) { - if (!position.isReadOnly()) - ranges.add(position.createStyleRange()); - else { - int offset= position.getOffset(); - minStart= Math.min(minStart, offset); - maxEnd= Math.max(maxEnd, offset + position.getLength()); - } - - } - } - StyleRange[] array= new StyleRange[ranges.size()]; - array= (StyleRange[]) ranges.toArray(array); - textPresentation.replaceStyleRanges(array); - } else { - for (; i < n; i++) { - HighlightedPosition position= (HighlightedPosition) fPositions.get(i); - if (!position.isDeleted()) { - if (!position.isReadOnly()) - textPresentation.replaceStyleRange(position.createStyleRange()); - else { - int offset= position.getOffset(); - minStart= Math.min(minStart, offset); - maxEnd= Math.max(maxEnd, offset + position.getLength()); - } - } - } - } - if (minStart < maxEnd) { - IStructuredDocument document = (IStructuredDocument) fSourceViewer.getDocument(); - if (document.containsReadOnly(minStart, maxEnd)) { - Iterator nonDefaultStyleRangeIterator = textPresentation.getNonDefaultStyleRangeIterator(); - while (nonDefaultStyleRangeIterator.hasNext()) { - StyleRange styleRange = (StyleRange) nonDefaultStyleRangeIterator.next(); - if (document.containsReadOnly(styleRange.start, styleRange.length)) { - adjustForeground(styleRange); - } - } - } - } - } - - /* - * @see org.eclipse.jface.text.ITextInputListener#inputDocumentAboutToBeChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument) - */ - public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) { - setCanceled(true); - releaseDocument(oldInput); - resetState(); - } - - /* - * @see org.eclipse.jface.text.ITextInputListener#inputDocumentChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument) - */ - public void inputDocumentChanged(IDocument oldInput, IDocument newInput) { - manageDocument(newInput); - } - - /* - * @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent) - */ - public void documentAboutToBeChanged(DocumentEvent event) { - setCanceled(true); - } - - /* - * @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent) - */ - public void documentChanged(DocumentEvent event) { - } - - /** - * @return Returns <code>true</code> iff the current reconcile is canceled. - * <p> - * NOTE: Also called from background thread. - * </p> - */ - public boolean isCanceled() { - IDocument document= fSourceViewer != null ? fSourceViewer.getDocument() : null; - if (document == null) - return fIsCanceled; - - synchronized (getLockObject(document)) { - return fIsCanceled; - } - } - - /** - * Set whether or not the current reconcile is canceled. - * - * @param isCanceled <code>true</code> iff the current reconcile is canceled - */ - public void setCanceled(boolean isCanceled) { - IDocument document= fSourceViewer != null ? fSourceViewer.getDocument() : null; - if (document == null) { - fIsCanceled= isCanceled; - return; - } - - synchronized (getLockObject(document)) { - fIsCanceled= isCanceled; - } - } - - /** - * @param document the document - * @return the document's lock object - */ - private Object getLockObject(IDocument document) { - if (document instanceof ISynchronizable) { - Object lock= ((ISynchronizable)document).getLockObject(); - if (lock != null) - return lock; - } - return document; - } - - /** - * Install this presenter on the given source viewer and background presentation - * reconciler. - * - * @param sourceViewer the source viewer - * @param backgroundPresentationReconciler the background presentation reconciler, - * can be <code>null</code>, in that case {@link SemanticHighlightingPresenter#createPresentation(List, List)} - * should not be called - */ - public void install(ISourceViewer sourceViewer, StructuredPresentationReconciler backgroundPresentationReconciler) { - fSourceViewer= sourceViewer; - fPresentationReconciler= backgroundPresentationReconciler; - - if (fSourceViewer instanceof StructuredTextViewer) - ((StructuredTextViewer) fSourceViewer).prependTextPresentationListener(this); - else if(fSourceViewer instanceof ITextViewerExtension4) - ((ITextViewerExtension4)fSourceViewer).addTextPresentationListener(this); - - fSourceViewer.addTextInputListener(this); - manageDocument(fSourceViewer.getDocument()); - } - - /** - * Uninstall this presenter. - */ - public void uninstall() { - setCanceled(true); - - if (fSourceViewer != null) { - if (fSourceViewer instanceof ITextViewerExtension4) - ((ITextViewerExtension4) fSourceViewer).addTextPresentationListener(this); - releaseDocument(fSourceViewer.getDocument()); - invalidateTextPresentation(); - resetState(); - - fSourceViewer.removeTextInputListener(this); - fSourceViewer= null; - } - } - - /** - * Invalidate text presentation of positions with the given highlighting. - * - * @param highlighting The highlighting - */ - public void highlightingStyleChanged(HighlightingStyle highlighting) { - for (int i= 0, n= fPositions.size(); i < n; i++) { - HighlightedPosition position= (HighlightedPosition) fPositions.get(i); - if (position.getHighlighting() == highlighting && fSourceViewer instanceof ITextViewerExtension2) - ((ITextViewerExtension2) fSourceViewer).invalidateTextPresentation(position.getOffset(), position.getLength()); - else - fSourceViewer.invalidateTextPresentation(); - } - } - - /** - * Invalidate text presentation of all positions. - */ - private void invalidateTextPresentation() { - if (fSourceViewer instanceof ITextViewerExtension2) { - for (int i = 0, n = fPositions.size(); i < n; i++) { - Position position = (Position) fPositions.get(i); - ((ITextViewerExtension2) fSourceViewer).invalidateTextPresentation(position.getOffset(), position.getLength()); - } - } - else { - fSourceViewer.invalidateTextPresentation(); - } - } - - /** - * Add a position with the given range and highlighting unconditionally, only from UI thread. - * The position will also be registered on the document. The text presentation is not invalidated. - * - * @param uiPosition the highlighted position to add from the UI - */ - private void addPositionFromUI(HighlightedPosition uiPosition) { - Position position= createHighlightedPosition(uiPosition, uiPosition.getHighlighting(), uiPosition.isReadOnly()); - synchronized (fPositionLock) { - insertPosition(position); - } - - IDocument document= fSourceViewer.getDocument(); - if (document == null) - return; - String positionCategory= getPositionCategory(); - try { - document.addPosition(positionCategory, position); - } catch (BadLocationException e) { - // Should not happen - Logger.logException(e); - } catch (BadPositionCategoryException e) { - // Should not happen - Logger.logException(e); - } - } - - /** - * Reset to initial state. - */ - private void resetState() { - synchronized (fPositionLock) { - fPositions.clear(); - } - } - - /** - * Start managing the given document. - * - * @param document The document - */ - private void manageDocument(IDocument document) { - if (document != null) { - document.addPositionCategory(getPositionCategory()); - document.addPositionUpdater(fPositionUpdater); - document.addDocumentListener(this); - } - } - - /** - * Stop managing the given document. - * - * @param document The document - */ - private void releaseDocument(IDocument document) { - if (document != null) { - document.removeDocumentListener(this); - document.removePositionUpdater(fPositionUpdater); - try { - document.removePositionCategory(getPositionCategory()); - } catch (BadPositionCategoryException e) { - // Should not happen - Logger.logException(e); - } - } - } - - /** - * @return The semantic reconciler position's category. - */ - private String getPositionCategory() { - return toString(); - } - - private void adjustForeground(StyleRange styleRange) { - RGB oldRGB = null; - // Color oldColor = styleRange.foreground; - Color oldColor = styleRange.background; - if (oldColor == null) { - // oldRGB = getTextWidget().getForeground().getRGB(); - oldColor = fSourceViewer.getTextWidget().getBackground(); - oldRGB = oldColor.getRGB(); - } - else { - oldRGB = oldColor.getRGB(); - } - Color newColor = getCachedColorFor(oldRGB); - if (newColor == null) { - // make text "closer to" background lumanence - double target = getRGBConverter().calculateYComponent(oldColor); - RGB newRGB = getRGBConverter().transformRGBToGrey(oldRGB, readOnlyForegroundScaleFactor / 100.0, target); - - // save conversion, so calculations only need to be done once - cacheColor(oldRGB, newRGB); - newColor = getCachedColorFor(oldRGB); - } - styleRange.foreground = newColor; - } - - private YUV_RGBConverter getRGBConverter() { - if (rgbConverter == null) { - rgbConverter = new YUV_RGBConverter(); - } - return rgbConverter; - } - - /** - * Cache read-only color. - * - * @param oldRGB - * @param newColor - */ - private void cacheColor(RGB oldRGB, RGB newColor) { - if (readOnlyColorTable == null) { - readOnlyColorTable = new HashMap(); - } - readOnlyColorTable.put(oldRGB, newColor); - } - - /** - * This method is just to get existing read-only colors. - */ - private Color getCachedColorFor(RGB oldRGB) { - Color result = null; - - if (readOnlyColorTable != null) { - RGB readOnlyRGB = (RGB) readOnlyColorTable.get(oldRGB); - result = EditorUtility.getColor(readOnlyRGB); - } - - return result; - } - - /** - * A utility class to do various color manipulations - */ - private class YUV_RGBConverter { - /** - * This class "holds" the YUV values corresponding to RGB color - */ - private class YUV { - - class NormalizedRGB { - double blue; - double green; - private final double maxRGB = 256.0; - double red; - - public NormalizedRGB(RGB rgb) { - // first normalize to between 0 - 1 - red = rgb.red / maxRGB; - green = rgb.green / maxRGB; - blue = rgb.blue / maxRGB; - - red = gammaNormalized(red); - green = gammaNormalized(green); - blue = gammaNormalized(blue); - - } - } - - private NormalizedRGB normalizedRGB; - - private double u = -1; - private double v = -1; - private double y = -1; - - private YUV() { - super(); - } - - public YUV(RGB rgb) { - this(); - normalizedRGB = new NormalizedRGB(rgb); - // force calculations - getY(); - getV(); - getU(); - } - - /** - * normalize to "average" gamma 2.2222 or 1/0.45 - */ - double gammaNormalized(double colorComponent) { - if (colorComponent < 0.018) { - return colorComponent * 0.45; - } - else { - return 1.099 * Math.pow(colorComponent, 0.45) - 0.099; - } - } - - /** - * @return RGB based on original RGB and current YUV values; - */ - - public double getU() { - if (u == -1) { - u = 0.4949 * (normalizedRGB.blue - getY()); - } - return u; - - } - - public double getV() { - if (v == -1) { - v = 0.877 * (normalizedRGB.red - getY()); - } - return v; - } - - public double getY() { - if (y == -1) { - y = 0.299 * normalizedRGB.red + 0.587 * normalizedRGB.green + 0.114 * normalizedRGB.blue; - } - return y; - } - - } - - public YUV_RGBConverter() { - super(); - } - - public double calculateYComponent(Color targetColor) { - return new YUV(targetColor.getRGB()).getY(); - } - - public RGB transformRGBToGrey(RGB originalRGB, double scaleFactor, double target) { - RGB transformedRGB = null; - // we left the "full" API method signature, but this - // version does not take into account originalRGB, though - // it might someday. - // for now, we'll simply make the new RGB grey, either a little - // lighter, or a little darker than background. - double y = 0; - double mid = 0.5; - // zero is black, one is white - if (target < mid) { - // is "dark" make lighter - y = target + scaleFactor; - } - else { - // is "light" make darker - y = target - scaleFactor; - } - int c = (int) Math.round(y * 255); - // just to gaurd against mis-use, or scale's values greater - // than mid point (and possibly rounding error) - if (c > 255) - c = 255; - if (c < 0) - c = 0; - transformedRGB = new RGB(c, c, c); - return transformedRGB; - } - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/style/SemanticHighlightingReconciler.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/style/SemanticHighlightingReconciler.java deleted file mode 100644 index 8318c97b90..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/style/SemanticHighlightingReconciler.java +++ /dev/null @@ -1,296 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009, 2011 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.style; - -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.jobs.Job; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.Position; -import org.eclipse.jface.text.Region; -import org.eclipse.jface.text.TextPresentation; -import org.eclipse.jface.text.reconciler.DirtyRegion; -import org.eclipse.jface.text.reconciler.IReconcilingStrategy; -import org.eclipse.jface.text.reconciler.IReconcilingStrategyExtension; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Display; -import org.eclipse.wst.sse.core.internal.model.ModelManagerImpl; -import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion; -import org.eclipse.wst.sse.ui.ISemanticHighlighting; -import org.eclipse.wst.sse.ui.ISemanticHighlightingExtension; -import org.eclipse.wst.sse.ui.internal.Logger; -import org.eclipse.wst.sse.ui.internal.style.SemanticHighlightingManager.HighlightedPosition; -import org.eclipse.wst.sse.ui.internal.style.SemanticHighlightingManager.HighlightingStyle; - -/** - * Semantic highlighting reconciler for Structured Source Editors. Based on - * org.eclipse.jdt.internal.ui.javaeditor.SemanticHighlightingReconciler - * - * @since 3.1 - */ -public class SemanticHighlightingReconciler implements IReconcilingStrategy, IReconcilingStrategyExtension { - - private IDocument fDocument; - - private ITextViewer fViewer; - private SemanticHighlightingPresenter fPresenter; - private ISemanticHighlighting[] fSemanticHighlightings; - private HighlightingStyle[] fHighlightings; - - private List fAddedPositions = new ArrayList(); - private List fRemovedPositions = new ArrayList(); - /** Number of removed positions */ - private int fNOfRemovedPositions; - - /** Background job */ - private Job fJob; - /** Background job lock */ - private final Object fJobLock = new Object(); - - /** Reconcile operation lock. */ - private final Object fReconcileLock = new Object(); - private boolean fIsReconciling = false; - /** The semantic highlighting presenter - cache for background thread, only valid during {@link #reconcile(IRegion)} */ - private SemanticHighlightingPresenter fJobPresenter; - /** Semantic highlightings - cache for background thread, only valid during {@link #reconcile(IRegion)} */ - private ISemanticHighlighting[] fJobSemanticHighlightings; - /** HighlightingStyle - cache for background thread, only valid during {@link #reconcile(IRegion)} */ - private HighlightingStyle[] fJobHighlightings; - - private boolean fIsInstalled; - - public void install(ITextViewer sourceViewer, SemanticHighlightingPresenter presenter, ISemanticHighlighting[] semanticHighlightings, HighlightingStyle[] highlightings) { - fViewer = sourceViewer; - fPresenter = presenter; - fSemanticHighlightings = semanticHighlightings; - fHighlightings = highlightings; - fIsInstalled = true; - } - - public void uninstall() { - fIsInstalled = false; - fViewer = null; - fPresenter = null; - fSemanticHighlightings = null; - fHighlightings = null; - } - - public void reconcile(IRegion partition) { - // ensure at most one thread can be reconciling at any time - synchronized (fReconcileLock) { - if (fIsReconciling) - return; - else - fIsReconciling= true; - } - fJobPresenter = fPresenter; - fJobSemanticHighlightings = fSemanticHighlightings; - fJobHighlightings = fHighlightings; - IStructuredModel model = null; - try { - if (fJobPresenter == null || fJobSemanticHighlightings == null || fJobHighlightings == null || fDocument == null) - return; - - fJobPresenter.setCanceled(false); - - startReconcilingPositions(); - IStructuredDocument document = (IStructuredDocument) fDocument; - model = ModelManagerImpl.getInstance().getModelForRead(document); - IStructuredDocumentRegion[] regions = document.getStructuredDocumentRegions(partition.getOffset(), partition.getLength()); - for (int i = 0; i < regions.length && fIsInstalled; i++) { - if (document.containsReadOnly(regions[i].getStartOffset(), regions[i].getLength())) - addPosition(new Position(regions[i].getStartOffset(), regions[i].getLength()), null, true); - else { - for (int j = 0; j < fJobSemanticHighlightings.length && fIsInstalled; j++) { - if (fJobHighlightings[j].isEnabled()) { - Position[] consumes = null; - if (fJobSemanticHighlightings[j] instanceof ISemanticHighlightingExtension && model != null) { - consumes = ((ISemanticHighlightingExtension) fJobSemanticHighlightings[j]).consumes(regions[i], model.getIndexedRegion(regions[i].getStartOffset())); - } - else { - consumes = fJobSemanticHighlightings[j].consumes(regions[i]); - } - if (consumes != null) { - for (int k = 0; k < consumes.length; k++) - addPosition(consumes[k], fJobHighlightings[j]); - } - } - } - } - } - - if (fIsInstalled) { - List oldPositions = fRemovedPositions; - List newPositions = new ArrayList(fNOfRemovedPositions); - for (int i = 0, n = oldPositions.size(); i < n && fIsInstalled; i++) { - Object current = oldPositions.get(i); - if (current != null) - newPositions.add(current); - } - fRemovedPositions = newPositions; - - TextPresentation presentation = null; - if (!fJobPresenter.isCanceled()) - presentation = fJobPresenter.createPresentation(fAddedPositions, fRemovedPositions); - if (!fJobPresenter.isCanceled()) - updatePresentation(presentation, fAddedPositions, fRemovedPositions); - } - stopReconcilingPositions(); - } - finally { - fJobPresenter= null; - fJobSemanticHighlightings= null; - fJobHighlightings= null; - if (model != null) - model.releaseFromRead(); - synchronized (fReconcileLock) { - fIsReconciling= false; - } - } - } - - private void addPosition(Position position, HighlightingStyle highlighting) { - addPosition(position, highlighting, false); - } - - private void addPosition(Position position, HighlightingStyle highlighting, boolean isReadOnly) { - boolean isExisting = false; - // TODO: use binary search - for (int i = 0, n = fRemovedPositions.size(); i < n; i++) { - HighlightedPosition highlightedPosition = (HighlightedPosition) fRemovedPositions.get(i); - if (highlightedPosition == null) - continue; - if (highlightedPosition.isEqual(position, highlighting)) { - isExisting = true; - fRemovedPositions.set(i, null); - fNOfRemovedPositions--; - break; - } - } - if (!isExisting) { - fAddedPositions.add(fJobPresenter.createHighlightedPosition(position, highlighting, isReadOnly)); - } - } - - /** - * Update the presentation. - * - * @param textPresentation - * the text presentation - * @param addedPositions - * the added positions - * @param removedPositions - * the removed positions - */ - private void updatePresentation(TextPresentation textPresentation, List addedPositions, List removedPositions) { - Runnable runnable = fJobPresenter.createUpdateRunnable(textPresentation, addedPositions, removedPositions); - if (runnable == null) - return; - - if (fViewer == null) - return; - - Control viewerControl = fViewer.getTextWidget(); - if (viewerControl == null) - return; - - Display display = viewerControl.getDisplay(); - if (display == null || display.isDisposed()) - return; - - display.asyncExec(runnable); - } - - /** - * Start reconciling positions. - */ - private void startReconcilingPositions() { - fJobPresenter.addAllPositions(fRemovedPositions); - fNOfRemovedPositions = fRemovedPositions.size(); - } - - /** - * Stop reconciling positions. - */ - private void stopReconcilingPositions() { - fRemovedPositions.clear(); - fNOfRemovedPositions = 0; - fAddedPositions.clear(); - } - - public void reconcile(DirtyRegion dirtyRegion, IRegion subRegion) { - reconcile(dirtyRegion); - } - - public void setDocument(IDocument document) { - fDocument = document; -// refresh(); - } - - public void initialReconcile() { - // Do nothing - } - - public void setProgressMonitor(IProgressMonitor monitor) { - } - - /** - * Schedule a background job for reconciling the Semantic Highlighting model. - */ - private void scheduleJob() { - synchronized (fJobLock) { - final Job oldJob= fJob; - if (fJob != null) { - fJob.cancel(); - fJob= null; - } - - fJob= new Job("Semantic Highlighting Job") { - protected IStatus run(IProgressMonitor monitor) { - if (oldJob != null) { - try { - oldJob.join(); - } catch (InterruptedException e) { - Logger.logException(e); - return Status.CANCEL_STATUS; - } - } - if (monitor.isCanceled()) - return Status.CANCEL_STATUS; - - reconcile(new Region(0, fDocument.getLength())); - synchronized (fJobLock) { - // allow the job to be gc'ed - if (fJob == this) - fJob= null; - } - return Status.OK_STATUS; - } - }; - fJob.setSystem(true); - fJob.setPriority(Job.DECORATE); - fJob.schedule(); - } - } - - public void refresh() { - if (fDocument != null) - scheduleJob(); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/taginfo/AbstractHoverProcessor.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/taginfo/AbstractHoverProcessor.java deleted file mode 100644 index 6f330615f0..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/taginfo/AbstractHoverProcessor.java +++ /dev/null @@ -1,44 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2006, 2007 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.taginfo; - -import org.eclipse.jface.text.DefaultInformationControl; -import org.eclipse.jface.text.IInformationControl; -import org.eclipse.jface.text.IInformationControlCreator; -import org.eclipse.jface.text.ITextHover; -import org.eclipse.jface.text.ITextHoverExtension; -import org.eclipse.swt.SWT; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.editors.text.EditorsUI; -import org.eclipse.wst.sse.ui.internal.derived.HTMLTextPresenter; - -/** - * Abstract class for providing hover information for Source editor. Includes - * a hover control creator which has the "Press F2 for focus" message built - * in. - * - * @since WTP 1.5 - */ -abstract public class AbstractHoverProcessor implements ITextHover, ITextHoverExtension { - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.text.ITextHoverExtension#getHoverControlCreator() - */ - public IInformationControlCreator getHoverControlCreator() { - return new IInformationControlCreator() { - public IInformationControl createInformationControl(Shell parent) { - return new DefaultInformationControl(parent, SWT.NONE, new HTMLTextPresenter(true), EditorsUI.getTooltipAffordanceString()); - } - }; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/taginfo/AnnotationHoverProcessor.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/taginfo/AnnotationHoverProcessor.java deleted file mode 100644 index 39082c923a..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/taginfo/AnnotationHoverProcessor.java +++ /dev/null @@ -1,204 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.taginfo; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.Position; -import org.eclipse.jface.text.Region; -import org.eclipse.jface.text.source.Annotation; -import org.eclipse.jface.text.source.IAnnotationModel; -import org.eclipse.jface.text.source.SourceViewer; -import org.eclipse.ui.editors.text.EditorsUI; -import org.eclipse.ui.texteditor.AnnotationPreference; -import org.eclipse.ui.texteditor.ChainedPreferenceStore; -import org.eclipse.wst.sse.core.utils.StringUtils; -import org.eclipse.wst.sse.ui.internal.ITemporaryAnnotation; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; -import org.eclipse.wst.sse.ui.internal.SSEUIPlugin; - -/** - * Hover help that displays annotations shown in text of editor. Currently, - * this text hover is used in conjunction with AbstractTextHoverProcessor. - * - * @author amywu - */ -public class AnnotationHoverProcessor extends AbstractHoverProcessor { - private final static String LIST_BEGIN = "<ul>"; //$NON-NLS-1$ - private final static String LIST_ELEMENT = "<li>"; //$NON-NLS-1$ - private final static String PARAGRAPH_END = "</p>"; //$NON-NLS-1$ - private final static String PARAGRAPH_START = "<p>"; //$NON-NLS-1$ - - private IPreferenceStore fPreferenceStore = null; - - /** - * - */ - public AnnotationHoverProcessor() { - super(); - } - - /** - * Formats a msg to a proper html message - * - * @param msg - - * assumes msg is neither null nor empty string - * @return - */ - private String formatMessage(String msg) { - StringBuffer buf = new StringBuffer(); - buf.append(PARAGRAPH_START); - buf.append(StringUtils.convertToHTMLContent(msg)); - buf.append(PARAGRAPH_END); - return buf.toString(); - } - - /** - * Formats multiple messages into proper html message - * - * @param messages - * @return - */ - private String formatMessages(List messages) { - StringBuffer buffer = new StringBuffer(); - buffer.append(PARAGRAPH_START); - buffer.append(SSEUIMessages.Multiple_errors); //$NON-NLS-1$ - buffer.append(LIST_BEGIN); - - Iterator e = messages.iterator(); - while (e.hasNext()) { - buffer.append(LIST_ELEMENT); - buffer.append(StringUtils.convertToHTMLContent((String) e.next())); - } - buffer.append(PARAGRAPH_END); - return buffer.toString(); - } - - /** - * Returns the annotation preference for the given annotation. (copied - * from org.eclipse.jdt.internal.ui.text.java.hover.AnnotationHover) - * - * @param annotation - * the annotation - * @return the annotation preference or <code>null</code> if none - */ - private AnnotationPreference getAnnotationPreference(Annotation annotation) { - - if (annotation.isMarkedDeleted()) - return null; - return EditorsUI.getAnnotationPreferenceLookup().getAnnotationPreference(annotation); - } - - public String getHoverInfo(ITextViewer viewer, IRegion hoverRegion) { - IAnnotationModel model = ((SourceViewer) viewer).getAnnotationModel(); - if (model != null) { - List messages = new ArrayList(); - Iterator e = model.getAnnotationIterator(); - while (e.hasNext()) { - Annotation a = (Annotation) e.next(); - if (!isAnnotationValid(a)) - continue; - - Position p = model.getPosition(a); - // check if this is an annotation in the region we are - // concerned with - if (p.overlapsWith(hoverRegion.getOffset(), hoverRegion.getLength())) { - String msg = a.getText(); - if ((msg != null) && msg.trim().length() > 0) { - // it is possible for temporary annotations to - // duplicate other annotations so make sure not to add - // dups - if (a instanceof ITemporaryAnnotation) { - boolean duplicated = false; - int j = 0; - while (j < messages.size() && !duplicated) { - duplicated = messages.get(j).equals(msg); - ++j; - } - if (!duplicated) { - messages.add(msg); - } - } - else { - messages.add(msg); - } - } - } - } - if (messages.size() > 1) { - return formatMessages(messages); - } - else if (messages.size() > 0) { - return formatMessage(messages.get(0).toString()); - } - } - return null; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.text.ITextHover#getHoverRegion(org.eclipse.jface.text.ITextViewer, - * int) - */ - public IRegion getHoverRegion(ITextViewer textViewer, int offset) { - IAnnotationModel model = ((SourceViewer) textViewer).getAnnotationModel(); - Region hoverRegion = null; - - if (model != null) { - Iterator e = model.getAnnotationIterator(); - while (e.hasNext()) { - Annotation a = (Annotation) e.next(); - if (!isAnnotationValid(a)) - continue; - Position p = model.getPosition(a); - if (p != null && p.includes(offset)) { - // find the smallest region containing offset - if ((hoverRegion == null) || (hoverRegion.getLength() > p.getLength())) { - hoverRegion = new Region(p.getOffset(), p.getLength()); - } - } - } - } - return hoverRegion; - } - - /** - * Retreives the preference store If no preference store is currently - * stored, retreive the appropriate preference store - */ - private IPreferenceStore getPreferenceStore() { - if (fPreferenceStore == null) { - IPreferenceStore sseEditorPrefs = SSEUIPlugin.getDefault().getPreferenceStore(); - IPreferenceStore baseEditorPrefs = EditorsUI.getPreferenceStore(); - fPreferenceStore = new ChainedPreferenceStore(new IPreferenceStore[]{sseEditorPrefs, baseEditorPrefs}); - } - return fPreferenceStore; - } - - boolean isAnnotationValid(Annotation a) { - AnnotationPreference preference = getAnnotationPreference(a); - if (preference == null) - return false; - String textPreferenceKey = preference.getTextPreferenceKey(); - String highlightPreferenceKey = preference.getHighlightPreferenceKey(); - if (textPreferenceKey == null || !(getPreferenceStore().getBoolean(textPreferenceKey)) || highlightPreferenceKey == null || getPreferenceStore().getBoolean(highlightPreferenceKey)) - return false; - return true; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/taginfo/BestMatchHover.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/taginfo/BestMatchHover.java deleted file mode 100644 index d105f91e7e..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/taginfo/BestMatchHover.java +++ /dev/null @@ -1,154 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2011 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.taginfo; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.eclipse.jface.text.IInformationControlCreator; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ITextHover; -import org.eclipse.jface.text.ITextHoverExtension; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.wst.sse.ui.internal.ExtendedConfigurationBuilder; -import org.eclipse.wst.sse.ui.internal.Logger; - -/** - * Provides the best hover help documentation (by using other hover help - * processors) Priority of hover help processors is: ProblemHoverProcessor, - * TagInfoProcessor, AnnotationHoverProcessor - */ -public class BestMatchHover implements ITextHover, ITextHoverExtension { - /** Current best match text hover */ - private ITextHover fBestMatchHover; - /** - * Documentation / Information hovers - */ - private ITextHover[] fTagInfoHovers; - /** List of text hovers to consider in best match */ - private List fTextHovers; - /** - * Partition type for which to create text hovers (when deferred for - * performance) - */ - private String fPartitionType; - - public BestMatchHover(ITextHover infoTagHover) { - this(new ITextHover[]{infoTagHover}); - } - - public BestMatchHover(ITextHover[] infoTagHovers) { - fTagInfoHovers = infoTagHovers; - } - - public BestMatchHover(String partitionType) { - fPartitionType = partitionType; - } - - /** - * Create a list of text hovers applicable to this best match hover - * processor - * - * @return List of ITextHover - in abstract class this is empty list - */ - private List createTextHoversList() { - List hoverList = new ArrayList(); - // if currently debugging, then add the debug hover to the list of - // best match - if (Logger.isTracing(DebugInfoHoverProcessor.TRACEFILTER)) { - hoverList.add(new DebugInfoHoverProcessor()); - } - - hoverList.add(new ProblemAnnotationHoverProcessor()); - - if (fPartitionType != null && fTagInfoHovers == null) { - List extendedTextHover = ExtendedConfigurationBuilder.getInstance().getConfigurations(ExtendedConfigurationBuilder.DOCUMENTATIONTEXTHOVER, fPartitionType); - fTagInfoHovers = (ITextHover[]) extendedTextHover.toArray(new ITextHover[extendedTextHover.size()]); - } - if (fTagInfoHovers != null) { - for (int i = 0; i < fTagInfoHovers.length; i++) { - hoverList.add(fTagInfoHovers[i]); - } - } - hoverList.add(new AnnotationHoverProcessor()); - return hoverList; - } - - public IInformationControlCreator getHoverControlCreator() { - IInformationControlCreator creator = null; - - if (fBestMatchHover instanceof ITextHoverExtension) { - creator = ((ITextHoverExtension) fBestMatchHover).getHoverControlCreator(); - } - return creator; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.text.ITextHover#getHoverInfo(org.eclipse.jface.text.ITextViewer, - * org.eclipse.jface.text.IRegion) - */ - public String getHoverInfo(ITextViewer viewer, IRegion hoverRegion) { - String displayText = null; - - // already have a best match hover picked out from getHoverRegion call - if (fBestMatchHover != null) { - displayText = fBestMatchHover.getHoverInfo(viewer, hoverRegion); - } - // either had no best match hover or best match hover returned null - if (displayText == null) { - // go through list of text hovers and return first display string - Iterator i = getTextHovers().iterator(); - while ((i.hasNext()) && (displayText == null)) { - ITextHover hover = (ITextHover) i.next(); - displayText = hover.getHoverInfo(viewer, hoverRegion); - } - } - return displayText; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.text.ITextHover#getHoverRegion(org.eclipse.jface.text.ITextViewer, - * int) - */ - public IRegion getHoverRegion(ITextViewer viewer, int offset) { - IRegion hoverRegion = null; - - // go through list of text hovers and return first hover region - ITextHover hover = null; - Iterator i = getTextHovers().iterator(); - while ((i.hasNext()) && (hoverRegion == null)) { - hover = (ITextHover) i.next(); - hoverRegion = hover.getHoverRegion(viewer, offset); - } - - // store the text hover processor that found region - if (hoverRegion != null) - fBestMatchHover = hover; - else - fBestMatchHover = null; - - return hoverRegion; - } - - private List getTextHovers() { - if (fTextHovers == null) { - fTextHovers = createTextHoversList(); - } - return fTextHovers; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/taginfo/DebugInfoHoverProcessor.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/taginfo/DebugInfoHoverProcessor.java deleted file mode 100644 index ea9db05d4b..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/taginfo/DebugInfoHoverProcessor.java +++ /dev/null @@ -1,94 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2006 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.taginfo; - - - -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.ITypedRegion; - -/** - * Provides debug hover help - * - * @see org.eclipse.jface.text.ITextHover - */ -public class DebugInfoHoverProcessor extends AbstractHoverProcessor { - public static final String TRACEFILTER = "debuginfohover"; //$NON-NLS-1$ - protected IPreferenceStore fPreferenceStore = null; - - public DebugInfoHoverProcessor() { - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.text.ITextHover#getHoverInfo(org.eclipse.jface.text.ITextViewer, - * org.eclipse.jface.text.IRegion) - */ - public String getHoverInfo(ITextViewer viewer, IRegion hoverRegion) { - String displayText = null; - if ((hoverRegion == null) || (viewer == null) || (viewer.getDocument() == null)) { - displayText = null; - } - else { - int offset = hoverRegion.getOffset(); - - ITypedRegion region; - try { - region = viewer.getDocument().getPartition(offset); - if (region != null) { - displayText = region.getType(); - } - else { - displayText = "Null Region was returned?!"; //$NON-NLS-1$ - } - } - catch (BadLocationException e) { - displayText = "BadLocationException Occurred!?"; //$NON-NLS-1$ - } - - } - return displayText; - } - - /** - * Returns the region to hover the text over based on the offset. - * - * @param textViewer - * @param offset - * - * @return IRegion region to hover over if offset is not over invalid - * whitespace. otherwise, returns <code>null</code> - * - * @see org.eclipse.jface.text.ITextHover#getHoverRegion(ITextViewer, int) - */ - public IRegion getHoverRegion(ITextViewer textViewer, int offset) { - ITypedRegion region = null; - if ((textViewer == null) || (textViewer.getDocument() == null)) { - region = null; - } - else { - - try { - region = textViewer.getDocument().getPartition(offset); - } - catch (BadLocationException e) { - region = null; - } - } - return region; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/taginfo/ProblemAnnotationHoverProcessor.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/taginfo/ProblemAnnotationHoverProcessor.java deleted file mode 100644 index d601231ef8..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/taginfo/ProblemAnnotationHoverProcessor.java +++ /dev/null @@ -1,52 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2007 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.taginfo; - -import org.eclipse.jface.text.source.Annotation; -import org.eclipse.ui.texteditor.DefaultMarkerAnnotationAccess; - -/** - * Hover help that displays problem annotations when shown in text of editor. - * - * @author amywu - */ -public class ProblemAnnotationHoverProcessor extends AnnotationHoverProcessor { - - // these strings are derived from the annotationTypes extension in - // org.eclipse.ui.editors plugin - // if those strings change, then these strings need to change as well - // https://bugs.eclipse.org/bugs/show_bug.cgi?id=198584 - final private String ANNOTATION_ERROR = "org.eclipse.ui.workbench.texteditor.error"; //$NON-NLS-1$ - final private String ANNOTATION_WARNING = "org.eclipse.ui.workbench.texteditor.warning"; //$NON-NLS-1$ - private DefaultMarkerAnnotationAccess fAnnotationAccess = new DefaultMarkerAnnotationAccess(); - - /** - * - */ - public ProblemAnnotationHoverProcessor() { - super(); - } - - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.sse.ui.taginfo.AnnotationHoverProcessor#isAnnotationValid(org.eclipse.jface.text.source.Annotation) - */ - protected boolean isAnnotationValid(Annotation a) { - String type = a.getType(); - if (fAnnotationAccess.isSubtype(type, ANNOTATION_ERROR) || fAnnotationAccess.isSubtype(type, ANNOTATION_WARNING)) - return super.isAnnotationValid(a); - return false; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/taginfo/TextHoverManager.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/taginfo/TextHoverManager.java deleted file mode 100644 index 428b1a0209..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/taginfo/TextHoverManager.java +++ /dev/null @@ -1,243 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2006 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.taginfo; - -import java.util.HashMap; - -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.text.ITextHover; -import org.eclipse.wst.sse.ui.internal.Logger; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; -import org.eclipse.wst.sse.ui.internal.SSEUIPlugin; -import org.eclipse.wst.sse.ui.internal.preferences.EditorPreferenceNames; - -import com.ibm.icu.util.StringTokenizer; - -/** - * Manages text hovers for Structured Text editors - */ -public class TextHoverManager { - /** - * Contains description of a text hover - */ - public class TextHoverDescriptor { - private String fDescription; - private boolean fEnabled; - private String fId; - private String fLabel; - private String fModifierString; - - /** - * @param id - * @param label - * @param desc - */ - public TextHoverDescriptor(String id, String label, String desc) { - fId = id; - fLabel = label; - fDescription = desc; - } - - /** - * @param id - * @param label - * @param desc - * @param enabled - * @param modifierString - */ - public TextHoverDescriptor(String id, String label, String desc, boolean enabled, String modifierString) { - fId = id; - fLabel = label; - fDescription = desc; - fEnabled = enabled; - fModifierString = modifierString; - } - - /** - * @return Returns the fDescription. - */ - public String getDescription() { - return fDescription; - } - - /** - * @return Returns the fId. - */ - public String getId() { - return fId; - } - - /** - * @return Returns the fLabel - */ - public String getLabel() { - return fLabel; - } - - /** - * @return Returns the fModifierString. - */ - public String getModifierString() { - return fModifierString; - } - - /** - * @return Returns the fEnabled. - */ - public boolean isEnabled() { - return fEnabled; - } - - /** - * @param enabled - * The fEnabled to set. - */ - public void setEnabled(boolean enabled) { - fEnabled = enabled; - } - - /** - * @param modifierString - * The fModifierString to set. - */ - public void setModifierString(String modifierString) { - fModifierString = modifierString; - } - } - - public static final String ANNOTATION_HOVER = "annotationHover"; //$NON-NLS-1$ - - // list of different types of Source editor hovers - public static final String COMBINATION_HOVER = "combinationHover"; //$NON-NLS-1$ - // hover descriptions are in .properties file with the key in the form of - // "[id]_desc" - private static final String DESCRIPTION_KEY = "_desc"; //$NON-NLS-1$ - public static final String DOCUMENTATION_HOVER = "documentationHover"; //$NON-NLS-1$ - public static final String HOVER_ATTRIBUTE_SEPARATOR = "|"; //$NON-NLS-1$ - public static final String HOVER_SEPARATOR = ";"; //$NON-NLS-1$ - - // hover labels are in .properties file with the key in the form of - // "[id]_label" - private static final String LABEL_KEY = "_label"; //$NON-NLS-1$ - - public static final String NO_MODIFIER = "0"; //$NON-NLS-1$ - public static final String PROBLEM_HOVER = "problemHover"; //$NON-NLS-1$ - public static final String[] TEXT_HOVER_IDS = new String[]{COMBINATION_HOVER, PROBLEM_HOVER, DOCUMENTATION_HOVER, ANNOTATION_HOVER}; - /** - * Current list of Structured Text editor text hovers - */ - private TextHoverDescriptor[] fTextHovers; - - public TextHoverManager() { - super(); - } - - /** - * Create a best match hover with the give text hover as the documentation - * hover - * - * @param infoHover - * @return ITextHover - * @deprecated as of WTP 3.0 M3 - */ - public ITextHover createBestMatchHover(ITextHover infoHover) { - return new BestMatchHover(infoHover); - } - - /** - * Generate a list of text hover descriptors from the given delimited - * string - * - * @param textHoverStrings - * @return - */ - public TextHoverDescriptor[] generateTextHoverDescriptors(String textHoverStrings) { - StringTokenizer st = new StringTokenizer(textHoverStrings, HOVER_SEPARATOR); - - // read from preference and load id-descriptor mapping to a hash table - HashMap idToModifier = new HashMap(st.countTokens()); - while (st.hasMoreTokens()) { - String textHoverString = st.nextToken(); - StringTokenizer st2 = new StringTokenizer(textHoverString, HOVER_ATTRIBUTE_SEPARATOR); - if (st2.countTokens() == 3) { - String id = st2.nextToken(); - boolean enabled = Boolean.valueOf(st2.nextToken()).booleanValue(); - String modifierString = st2.nextToken(); - if (modifierString.equals(NO_MODIFIER)) - modifierString = ""; //$NON-NLS-1$ - - String label = null; - String description = null; - try { - label = SSEUIMessages.getResourceBundle().getString(id + LABEL_KEY); - description = SSEUIMessages.getResourceBundle().getString(id + DESCRIPTION_KEY); - } - catch (Exception e) { - Logger.log(Logger.WARNING_DEBUG, e.getMessage(), e); - } - TextHoverDescriptor descriptor = new TextHoverDescriptor(id, label, description, enabled, modifierString); - // should check to see if ids appear more than once - idToModifier.put(id, descriptor); - } - } - - // go through all defined text hovers and match with their preference - TextHoverDescriptor[] descriptors = new TextHoverDescriptor[TEXT_HOVER_IDS.length]; - for (int i = 0; i < TEXT_HOVER_IDS.length; i++) { - TextHoverDescriptor desc = (TextHoverDescriptor) idToModifier.get(TEXT_HOVER_IDS[i]); - if (desc != null) { - descriptors[i] = desc; - } - else { - String label = null; - String description = null; - try { - label = SSEUIMessages.getResourceBundle().getString(TEXT_HOVER_IDS[i] + LABEL_KEY); - description = SSEUIMessages.getResourceBundle().getString(TEXT_HOVER_IDS[i] + DESCRIPTION_KEY); - } - catch (Exception e) { - Logger.log(Logger.WARNING_DEBUG, e.getMessage(), e); - } - descriptors[i] = new TextHoverDescriptor(TEXT_HOVER_IDS[i], label, description); - } - } - return descriptors; - } - - private IPreferenceStore getPreferenceStore() { - return SSEUIPlugin.getDefault().getPreferenceStore(); - } - - - /** - * Returns the text hovers for Structured Text editor. If fTextHover has - * not been initialied, it will be initialized. - * - * @return Returns the fTextHovers. - */ - public TextHoverDescriptor[] getTextHovers() { - if (fTextHovers == null) { - String textHoverStrings = getPreferenceStore().getString(EditorPreferenceNames.EDITOR_TEXT_HOVER_MODIFIERS); - fTextHovers = generateTextHoverDescriptors(textHoverStrings); - } - return fTextHovers; - } - - /** - * Sets fTextHovers to null so that next time getTextHovers is called, - * fTextHovers will be populated with the latest preferences. - */ - public void resetTextHovers() { - fTextHovers = null; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/text/DocumentRegionEdgeMatcher.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/text/DocumentRegionEdgeMatcher.java deleted file mode 100644 index 6cc018d5ec..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/text/DocumentRegionEdgeMatcher.java +++ /dev/null @@ -1,159 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2011 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.text; - -import java.util.Arrays; -import java.util.List; - -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.Region; -import org.eclipse.jface.text.source.ICharacterPairMatcher; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion; -import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegion; - - -/** - * Matches the start and ending characters of IStructuredDocumentRegions with - * the given allowed types. Note that Eclipse R3M8 only paints single - * character-wide matches and this isn't true pair matching behavior. See RFE - * #56836 at https://bugs.eclipse.org/bugs/show_bug.cgi?id=56836. - */ -public class DocumentRegionEdgeMatcher implements ICharacterPairMatcher { - - public static final String ID = "characterpairmatcher"; //$NON-NLS-1$ - - protected int fAnchor; - - protected ICharacterPairMatcher fNextMatcher; - - protected List fRegionTypes; - - public DocumentRegionEdgeMatcher(String[] validContexts, ICharacterPairMatcher nextMatcher) { - fRegionTypes = Arrays.asList(validContexts); - fNextMatcher = nextMatcher; - } - - /* - * @see org.eclipse.jface.text.source.ICharacterPairMatcher#clear() - */ - public void clear() { - if (fNextMatcher != null) - fNextMatcher.clear(); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.text.source.ICharacterPairMatcher#dispose() - */ - public void dispose() { - if (fNextMatcher != null) - fNextMatcher.dispose(); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.text.source.ICharacterPairMatcher#getAnchor() - */ - public int getAnchor() { - if (fAnchor < 0 && fNextMatcher != null) - return fNextMatcher.getAnchor(); - return fAnchor; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.text.source.ICharacterPairMatcher#match(org.eclipse.jface.text.IDocument, - * int) - */ - public IRegion match(IDocument document, int offset) { - if (offset < 0 || offset >= document.getLength()) - return null; - - IRegion match = null; - if (!fRegionTypes.isEmpty() && document instanceof IStructuredDocument) { - IStructuredDocumentRegion docRegion = ((IStructuredDocument) document).getRegionAtCharacterOffset(offset); - if (docRegion != null) { - // look at the previous document region first since its end == - // this one's start - if (docRegion.getPrevious() != null && docRegion.getPrevious().getEndOffset() == offset && fRegionTypes.contains(docRegion.getPrevious().getType())) { - fAnchor = ICharacterPairMatcher.RIGHT; - match = new Region(docRegion.getPrevious().getStartOffset(), 1); - } - // check for offset in the last text region for a match to - // document region start offset - else if (fRegionTypes.contains(docRegion.getType()) && docRegion.getStartOffset(docRegion.getLastRegion()) <= offset && offset <= docRegion.getEndOffset(docRegion.getLastRegion())) { - fAnchor = ICharacterPairMatcher.RIGHT; - match = new Region(docRegion.getStartOffset(), 1); - } - // check for offset in the first text region for a match to - // document region end offset - else if (fRegionTypes.contains(docRegion.getType())) { - if (docRegion.getStartOffset(docRegion.getFirstRegion()) <= offset && offset <= docRegion.getEndOffset(docRegion.getFirstRegion())) { - fAnchor = ICharacterPairMatcher.LEFT; - match = new Region(docRegion.getEndOffset() - 1, 1); - } - } - - if (match == null) { - /* Now check the text region */ - ITextRegion currentTextRegion = docRegion.getRegionAtCharacterOffset(offset); - if (currentTextRegion != null && currentTextRegion.getTextLength() > 1) { - int offsetAtNearEdge = offset; - if (offset == docRegion.getTextEndOffset(currentTextRegion)) { - offsetAtNearEdge = offset-1; - } - else if (offset == docRegion.getStartOffset(currentTextRegion)+1) { - offsetAtNearEdge = offset-1; - } - - if (offsetAtNearEdge == docRegion.getStartOffset(currentTextRegion)) { - int end = docRegion.getTextEndOffset(currentTextRegion); - try { - if (!Character.isWhitespace(document.getChar(offsetAtNearEdge)) && document.getChar(offsetAtNearEdge) == document.getChar(end - 1)) { - fAnchor = ICharacterPairMatcher.LEFT; - match = new Region(end - 1, 1); - } - } - catch (BadLocationException e) { - // nothing, not important enough - } - } - else if (offsetAtNearEdge == docRegion.getTextEndOffset(currentTextRegion)-1) { - int start = docRegion.getStartOffset(currentTextRegion); - try { - if (!Character.isWhitespace(document.getChar(offsetAtNearEdge)) && (document.getChar(offsetAtNearEdge) == document.getChar(start))) { - fAnchor = ICharacterPairMatcher.RIGHT; - match = new Region(start, 1); - } - } - catch (BadLocationException e) { - // nothing, not important enough - } - } - } - } - } - } - if (match == null && fNextMatcher != null) { - fAnchor = -1; - match = fNextMatcher.match(document, offset); - } - return match; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/text/SourceInfoProvider.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/text/SourceInfoProvider.java deleted file mode 100644 index 0b7a4f9410..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/text/SourceInfoProvider.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.eclipse.wst.sse.ui.internal.text; - -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.Region; -import org.eclipse.jface.text.information.IInformationProvider; -import org.eclipse.jface.text.information.IInformationProviderExtension; -import org.eclipse.ui.texteditor.ITextEditor; - -public class SourceInfoProvider implements IInformationProvider, IInformationProviderExtension { - - private ITextEditor fEditor; - - public SourceInfoProvider(ITextEditor editor) { - fEditor = editor; - } - public String getInformation(ITextViewer textViewer, IRegion subject) { - return getInformation2(textViewer, subject).toString(); - } - - public IRegion getSubject(ITextViewer textViewer, int offset) { - if (textViewer != null && fEditor != null) { - IRegion region= WordFinder.findWord(textViewer.getDocument(), offset); - if (region != null) - return region; - else - return new Region(offset, 0); - } - return null; - } - - public Object getInformation2(ITextViewer textViewer, IRegion subject) { - if (fEditor == null) - return null; - - Object selection = fEditor.getSelectionProvider().getSelection(); - if (selection == null) - selection = new Object(); - return selection; - } - -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/text/WordFinder.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/text/WordFinder.java deleted file mode 100644 index 4e708c59bf..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/text/WordFinder.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.eclipse.wst.sse.ui.internal.text; - -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.Region; - -public class WordFinder { - - /* Copied from org.eclipse.jdt.internal.ui.text.JavaWordFinder */ - public static IRegion findWord(IDocument document, int offset) { - - int start= -2; - int end= -1; - - try { - int pos= offset; - char c; - - while (pos >= 0) { - c= document.getChar(pos); - if (!Character.isJavaIdentifierPart(c)) - break; - --pos; - } - start= pos; - - pos= offset; - int length= document.getLength(); - - while (pos < length) { - c= document.getChar(pos); - if (!Character.isJavaIdentifierPart(c)) - break; - ++pos; - } - end= pos; - - } catch (BadLocationException x) { - } - - if (start >= -1 && end > -1) { - if (start == offset && end == offset) - return new Region(offset, 0); - else if (start == offset) - return new Region(start, end - start); - else - return new Region(start + 1, end - start - 1); - } - - return null; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/ui/OffsetStatusLineContributionItem.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/ui/OffsetStatusLineContributionItem.java deleted file mode 100644 index 22504ddb5b..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/ui/OffsetStatusLineContributionItem.java +++ /dev/null @@ -1,1235 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2007 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.ui; - -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Comparator; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.jobs.Job; -import org.eclipse.jface.action.Action; -import org.eclipse.jface.action.IAction; -import org.eclipse.jface.dialogs.Dialog; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IDocumentExtension3; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ITextSelection; -import org.eclipse.jface.text.ITypedRegion; -import org.eclipse.jface.text.Position; -import org.eclipse.jface.text.Region; -import org.eclipse.jface.text.TextUtilities; -import org.eclipse.jface.text.reconciler.IReconcileStep; -import org.eclipse.jface.text.source.Annotation; -import org.eclipse.jface.text.source.IAnnotationModel; -import org.eclipse.jface.viewers.ArrayContentProvider; -import org.eclipse.jface.viewers.CellEditor; -import org.eclipse.jface.viewers.ColumnWeightData; -import org.eclipse.jface.viewers.ILabelProviderListener; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.ISelectionChangedListener; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.viewers.ITableLabelProvider; -import org.eclipse.jface.viewers.ITreeContentProvider; -import org.eclipse.jface.viewers.LabelProvider; -import org.eclipse.jface.viewers.SelectionChangedEvent; -import org.eclipse.jface.viewers.TableLayout; -import org.eclipse.jface.viewers.TableViewer; -import org.eclipse.jface.viewers.TreeViewer; -import org.eclipse.jface.viewers.Viewer; -import org.eclipse.jface.viewers.ViewerComparator; -import org.eclipse.jface.viewers.ViewerSorter; -import org.eclipse.swt.SWT; -import org.eclipse.swt.custom.SashForm; -import org.eclipse.swt.custom.StyledText; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.layout.FormAttachment; -import org.eclipse.swt.layout.FormData; -import org.eclipse.swt.layout.FormLayout; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Combo; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.Event; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.Sash; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.swt.widgets.TabFolder; -import org.eclipse.swt.widgets.TabItem; -import org.eclipse.swt.widgets.TableColumn; -import org.eclipse.swt.widgets.Text; -import org.eclipse.ui.IEditorInput; -import org.eclipse.ui.IEditorSite; -import org.eclipse.ui.ISelectionService; -import org.eclipse.ui.IWorkbenchWindow; -import org.eclipse.ui.texteditor.ITextEditor; -import org.eclipse.ui.texteditor.MarkerAnnotation; -import org.eclipse.ui.texteditor.MarkerUtilities; -import org.eclipse.ui.texteditor.SimpleMarkerAnnotation; -import org.eclipse.ui.texteditor.StatusLineContributionItem; -import org.eclipse.ui.views.properties.IPropertyDescriptor; -import org.eclipse.ui.views.properties.IPropertySource; -import org.eclipse.ui.views.properties.IPropertySourceProvider; -import org.eclipse.ui.views.properties.PropertySheetPage; -import org.eclipse.ui.views.properties.TextPropertyDescriptor; -import org.eclipse.wst.sse.core.StructuredModelManager; -import org.eclipse.wst.sse.core.internal.provisional.INodeAdapter; -import org.eclipse.wst.sse.core.internal.provisional.INodeNotifier; -import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel; -import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredPartitioning; -import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegion; -import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegionCollection; -import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegionContainer; -import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegionList; -import org.eclipse.wst.sse.core.internal.util.Utilities; -import org.eclipse.wst.sse.core.utils.StringUtils; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; -import org.eclipse.wst.sse.ui.internal.contentoutline.IJFaceNodeAdapter; -import org.eclipse.wst.sse.ui.internal.reconcile.ReconcileAnnotationKey; -import org.eclipse.wst.sse.ui.internal.reconcile.TemporaryAnnotation; - -import com.ibm.icu.text.NumberFormat; - -/** - * @author nsd A Status Line contribution intended to display the selected - * offsets in an editor. Double-clicking shows information about - * partitions, document regions, annotations, and selection. - */ -public class OffsetStatusLineContributionItem extends StatusLineContributionItem { - - class AnnotationPropertySource implements IPropertySource { - Annotation fAnnotation = null; - IPropertyDescriptor[] fDescriptors = null; - String[] TEMPORARY_ANNOTATION_KEYS = new String[]{"Partition Type", "Step", "Scope", "Offset", "Length", "Description"}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ - - public AnnotationPropertySource(Annotation annotation) { - super(); - fAnnotation = annotation; - } - - public Object getEditableValue() { - return null; - } - - public IPropertyDescriptor[] getPropertyDescriptors() { - if (fDescriptors == null) { - try { - if (fAnnotation instanceof SimpleMarkerAnnotation) { - Map attrs = ((SimpleMarkerAnnotation) fAnnotation).getMarker().getAttributes(); - Object[] keys = attrs.keySet().toArray(); - - fDescriptors = new IPropertyDescriptor[keys.length]; - for (int i = 0; i < keys.length; i++) { - TextPropertyDescriptor descriptor = new TextPropertyDescriptor(keys[i].toString(), keys[i].toString()); - fDescriptors[i] = descriptor; - } - } - else if (fAnnotation instanceof TemporaryAnnotation) { - Object key = ((TemporaryAnnotation) fAnnotation).getKey(); - if (key != null && key instanceof ReconcileAnnotationKey) { - String[] keys = TEMPORARY_ANNOTATION_KEYS; - fDescriptors = new IPropertyDescriptor[keys.length]; - for (int i = 0; i < keys.length; i++) { - TextPropertyDescriptor descriptor = new TextPropertyDescriptor(keys[i].toString(), keys[i].toString()); - fDescriptors[i] = descriptor; - } - } - } - } - catch (CoreException e) { - e.printStackTrace(); - } - } - if (fDescriptors == null) - fDescriptors = new IPropertyDescriptor[0]; - return fDescriptors; - } - - public Object getPropertyValue(Object id) { - String value = null; - if (fAnnotation instanceof SimpleMarkerAnnotation) { - Object o; - try { - o = ((SimpleMarkerAnnotation) fAnnotation).getMarker().getAttributes().get(id); - if (o != null) { - value = o.toString(); - } - } - catch (CoreException e) { - } - } - else if (fAnnotation instanceof TemporaryAnnotation) { - if (TEMPORARY_ANNOTATION_KEYS[0].equals(id)) { - Object key = ((TemporaryAnnotation) fAnnotation).getKey(); - if (key != null && key instanceof ReconcileAnnotationKey) { - value = ((ReconcileAnnotationKey) key).getPartitionType(); - } - } - else if (TEMPORARY_ANNOTATION_KEYS[1].equals(id)) { - Object key = ((TemporaryAnnotation) fAnnotation).getKey(); - if (key != null && key instanceof ReconcileAnnotationKey) { - IReconcileStep step = ((ReconcileAnnotationKey) key).getStep(); - if (step != null) { - value = step.toString(); - } - } - } - else if (TEMPORARY_ANNOTATION_KEYS[2].equals(id)) { - Object key = ((TemporaryAnnotation) fAnnotation).getKey(); - if (key != null && key instanceof ReconcileAnnotationKey) { - int scope = ((ReconcileAnnotationKey) key).getScope(); - if (scope == ReconcileAnnotationKey.PARTIAL) { - value = "PARTIAL"; //$NON-NLS-1$ - } - if (scope == ReconcileAnnotationKey.TOTAL) { - value = "TOTAL"; //$NON-NLS-1$ - } - } - } - else if (TEMPORARY_ANNOTATION_KEYS[3].equals(id)) { - IAnnotationModel annotationModel = fTextEditor.getDocumentProvider().getAnnotationModel(fTextEditor.getEditorInput()); - Position p = annotationModel.getPosition(fAnnotation); - if (p != null) { - value = String.valueOf(p.getOffset()); - } - } - else if (TEMPORARY_ANNOTATION_KEYS[4].equals(id)) { - IAnnotationModel annotationModel = fTextEditor.getDocumentProvider().getAnnotationModel(fTextEditor.getEditorInput()); - Position p = annotationModel.getPosition(fAnnotation); - if (p != null) { - value = String.valueOf(p.getLength()); - } - } - else if (TEMPORARY_ANNOTATION_KEYS[5].equals(id)) { - value = ((TemporaryAnnotation) fAnnotation).getDescription(); - } - } - return value; - } - - public boolean isPropertySet(Object id) { - return false; - } - - public void resetPropertyValue(Object id) { - try { - if (fAnnotation instanceof SimpleMarkerAnnotation) { - ((SimpleMarkerAnnotation) fAnnotation).getMarker().getAttributes().remove(id); - } - else if (fAnnotation instanceof TemporaryAnnotation) { - } - } - catch (CoreException e) { - e.printStackTrace(); - } - } - - public void setPropertyValue(Object id, Object value) { - try { - if (fAnnotation instanceof SimpleMarkerAnnotation) { - ((MarkerAnnotation) fAnnotation).getMarker().setAttribute(id.toString(), value); - } - else if (fAnnotation instanceof TemporaryAnnotation) { - } - } - catch (CoreException e) { - e.printStackTrace(); - } - } - } - - class InformationDialog extends Dialog { - - IDocument fDocument = fTextEditor.getDocumentProvider().getDocument(fTextEditor.getEditorInput()); - - public InformationDialog(Shell parentShell) { - super(parentShell); - setShellStyle(getShellStyle() | SWT.RESIZE); - } - - private void createAnnotationTabContents(Composite annotationsTabComposite) { - annotationsTabComposite.setLayout(new GridLayout()); - annotationsTabComposite.setLayoutData(new GridData()); - - final Composite annotationsComposite = new Composite(annotationsTabComposite, SWT.NONE); - annotationsComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); - - final TableViewer annotationsTable = new TableViewer(annotationsComposite, SWT.SINGLE | SWT.FULL_SELECTION | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER); - annotationsTable.setComparator(new ViewerComparator(new Comparator() { - public int compare(Object o1, Object o2) { - Annotation annotation1 = (Annotation) o1; - Annotation annotation2 = (Annotation) o2; - String line1 = getLineNumber(annotation1); - String line2 = getLineNumber(annotation2); - return Integer.parseInt(line1) - Integer.parseInt(line2); - } - })); - annotationsTable.setContentProvider(new ArrayContentProvider()); - annotationsTable.getTable().setHeaderVisible(true); - annotationsTable.getTable().setLinesVisible(true); - String[] columns = new String[]{"Line", "Owner", "Type", "Class", "Message"}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ - annotationsTable.setLabelProvider(new ITableLabelProvider() { - public void addListener(ILabelProviderListener listener) { - } - - public void dispose() { - } - - public Image getColumnImage(Object element, int columnIndex) { - return null; - } - - public String getColumnText(Object element, int columnIndex) { - Annotation annotation = (Annotation) element; - String text = null; - switch (columnIndex) { - case 0 : - text = getLineNumber(annotation); - break; - case 1 : - text = getOwner(annotation); - break; - case 2 : - text = getType(annotation); //$NON-NLS-1$ - break; - case 3 : - text = annotation.getClass().getName(); - break; - case 4 : - text = annotation.getText(); - break; - } - if (text == null) - text = ""; //$NON-NLS-1$ - return text; - } - - - private String getOwner(Annotation annotation) { - String owner = null; - if (annotation instanceof MarkerAnnotation) { - owner = ((MarkerAnnotation) annotation).getMarker().getAttribute("owner", ""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } - else if (annotation instanceof TemporaryAnnotation) { - Object key = ((TemporaryAnnotation) annotation).getKey(); - if (key != null) { - if (key instanceof ReconcileAnnotationKey) { - key = key.getClass().getName(); - } - if (key != null) - owner = key.toString(); - } - } - return owner; - } - - private String getType(Annotation annotation) { - String type = null; - if (annotation instanceof MarkerAnnotation) { - type = "M:"+MarkerUtilities.getMarkerType(((MarkerAnnotation) annotation).getMarker()); //$NON-NLS-1$ - } - else { - type = "A:"+annotation.getType(); //$NON-NLS-1$ - } - if (type == null) - type = ""; //$NON-NLS-1$ - return type; - } - - public boolean isLabelProperty(Object element, String property) { - return true; - } - - public void removeListener(ILabelProviderListener listener) { - } - }); - - TableLayout tlayout = new TableLayout(); - CellEditor[] cellEditors = new CellEditor[columns.length]; - int columnWidths[] = new int[]{Display.getCurrent().getBounds().width / 14, Display.getCurrent().getBounds().width / 7, Display.getCurrent().getBounds().width / 7, Display.getCurrent().getBounds().width / 14, Display.getCurrent().getBounds().width / 7}; - for (int i = 0; i < columns.length; i++) { - tlayout.addColumnData(new ColumnWeightData(1)); - TableColumn tc = new TableColumn(annotationsTable.getTable(), SWT.NONE); - tc.setText(columns[i]); - tc.setResizable(true); - tc.setWidth(columnWidths[i]); - } - annotationsTable.setCellEditors(cellEditors); - annotationsTable.setColumnProperties(columns); - List matchingAnnotations = new ArrayList(0); - if (fTextEditor != null) { - IAnnotationModel annotationModel = fTextEditor.getDocumentProvider().getAnnotationModel(fTextEditor.getEditorInput()); - if (annotationModel != null) { - Iterator iterator = annotationModel.getAnnotationIterator(); - while (iterator.hasNext()) { - Annotation element = (Annotation) iterator.next(); - if (true) { - matchingAnnotations.add(element); - } - } - } - } - annotationsTable.setSorter(new ViewerSorter()); - annotationsTable.setInput(matchingAnnotations); - - final Sash sash = new Sash(annotationsComposite, SWT.HORIZONTAL); - - final PropertySheetPage propertySheet = new PropertySheetPage(); - propertySheet.createControl(annotationsComposite); - propertySheet.setPropertySourceProvider(new IPropertySourceProvider() { - public IPropertySource getPropertySource(Object object) { - if (object instanceof Annotation) { - IPropertySource annotationPropertySource = new AnnotationPropertySource(((Annotation) object)); - return annotationPropertySource; - } - return null; - } - }); - - annotationsTable.addSelectionChangedListener(new ISelectionChangedListener() { - public void selectionChanged(SelectionChangedEvent event) { - propertySheet.selectionChanged(null, event.getSelection()); - } - }); - - final FormLayout form = new FormLayout(); - annotationsComposite.setLayout(form); - - FormData tableData = new FormData(); - tableData.top = new FormAttachment(0, 0); - tableData.bottom = new FormAttachment(sash, 2); - tableData.left = new FormAttachment(0, 0); - tableData.right = new FormAttachment(100, 0); - annotationsTable.getControl().setLayoutData(tableData); - - FormData propertiesData = new FormData(); - propertiesData.top = new FormAttachment(sash, 2); - propertiesData.left = new FormAttachment(0, 0); - propertiesData.right = new FormAttachment(100, 0); - propertiesData.bottom = new FormAttachment(100, 0); - propertySheet.getControl().setLayoutData(propertiesData); - - final FormData sashData = new FormData(); - sashData.top = new FormAttachment(60, 0); - sashData.left = new FormAttachment(0, 0); - sashData.right = new FormAttachment(100, 0); - sash.setLayoutData(sashData); - sash.addListener(SWT.Selection, new org.eclipse.swt.widgets.Listener() { - public void handleEvent(Event e) { - sashData.top = new FormAttachment(0, e.y); - annotationsComposite.layout(); - } - }); - annotationsComposite.pack(true); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite) - */ - protected Control createDialogArea(Composite parent) { - ISelection selection = fTextEditor.getSelectionProvider().getSelection(); - ITextSelection textSelection = (ITextSelection) selection; - IStructuredSelection structuredSelection = null; - if (selection instanceof IStructuredSelection) - structuredSelection = (IStructuredSelection) selection; - - parent.getShell().setText(SSEUIMessages.OffsetStatusLineContributionItem_0 + textSelection.getOffset() + "-" + (textSelection.getOffset() + textSelection.getLength())); //$NON-NLS-1$ //$NON-NLS-2$ - Composite composite = (Composite) super.createDialogArea(parent); - - Text documentTypeLabel = new Text(composite, SWT.SINGLE | SWT.READ_ONLY); - GridData gd = new GridData(SWT.FILL, SWT.FILL, true, false); - gd.horizontalSpan = 2; - documentTypeLabel.setLayoutData(gd); - documentTypeLabel.setText(SSEUIMessages.OffsetStatusLineContributionItem_6 + fDocument.getClass().getName()); //$NON-NLS-1$ - - Text documentProviderLabel = new Text(composite, SWT.SINGLE | SWT.READ_ONLY); - gd = new GridData(SWT.FILL, SWT.FILL, true, false); - gd.horizontalSpan = 2; - documentProviderLabel.setLayoutData(gd); - documentProviderLabel.setText(SSEUIMessages.OffsetStatusLineContributionItem_7 + fTextEditor.getDocumentProvider().getClass().getName()); //$NON-NLS-1$ - - Text editorInputLabel = new Text(composite, SWT.SINGLE | SWT.READ_ONLY); - gd = new GridData(SWT.FILL, SWT.FILL, true, false); - gd.horizontalSpan = 2; - editorInputLabel.setLayoutData(gd); - editorInputLabel.setText(SSEUIMessages.OffsetStatusLineContributionItem_12 + fTextEditor.getEditorInput().getClass().getName()); //$NON-NLS-1$ - - final Text bomLabel = new Text(composite, SWT.SINGLE | SWT.READ_ONLY); - gd = new GridData(SWT.FILL, SWT.FILL, true, false); - gd.horizontalSpan = 2; - bomLabel.setLayoutData(gd); - bomLabel.setEnabled(false); - bomLabel.setText("Byte Order Mark: "); - - IStructuredModel model = StructuredModelManager.getModelManager().getExistingModelForRead(fDocument); - if (model != null) { - Text modelIdLabel = new Text(composite, SWT.SINGLE | SWT.READ_ONLY); - gd = new GridData(SWT.FILL, SWT.FILL, true, false); - gd.horizontalSpan = 2; - modelIdLabel.setLayoutData(gd); - modelIdLabel.setText("ID: " + model.getId()); //$NON-NLS-1$ - - Text modelBaseLocationLabel = new Text(composite, SWT.SINGLE | SWT.READ_ONLY); - gd = new GridData(SWT.FILL, SWT.FILL, true, false); - gd.horizontalSpan = 2; - modelBaseLocationLabel.setLayoutData(gd); - modelBaseLocationLabel.setText("Base Location: " + model.getBaseLocation()); //$NON-NLS-1$ - - Text modelContentTypeLabel = new Text(composite, SWT.SINGLE | SWT.READ_ONLY); - gd = new GridData(SWT.FILL, SWT.FILL, true, false); - gd.horizontalSpan = 2; - modelContentTypeLabel.setLayoutData(gd); - modelContentTypeLabel.setText(SSEUIMessages.OffsetStatusLineContributionItem_4 + model.getContentTypeIdentifier()); //$NON-NLS-1$ - - Text modelHandlerContentTypeLabel = new Text(composite, SWT.MULTI | SWT.WRAP | SWT.READ_ONLY); - gd = new GridData(SWT.FILL, SWT.FILL, true, false); - gd.horizontalSpan = 2; - modelHandlerContentTypeLabel.setLayoutData(gd); - modelHandlerContentTypeLabel.setText(SSEUIMessages.OffsetStatusLineContributionItem_5 + model.getModelHandler().getAssociatedContentTypeId() + " (" + model.getModelHandler() + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - - final Text counts = new Text(composite, SWT.MULTI | SWT.WRAP | SWT.READ_ONLY); - gd = new GridData(SWT.FILL, SWT.FILL, true, false); - gd.horizontalSpan = 2; - counts.setLayoutData(gd); - counts.setText("Counting..."); - counts.setEnabled(false); - final IStructuredModel finalModel = model; - final Display display = Display.getCurrent(); - Job counter = new Job("Counting regions") { - protected IStatus run(IProgressMonitor monitor) { - IStructuredDocumentRegion[] structuredDocumentRegions = finalModel.getStructuredDocument().getStructuredDocumentRegions(); - int length = finalModel.getStructuredDocument().getLength(); - int regionCount = 0; - for (int i = 0; i < structuredDocumentRegions.length; i++) { - regionCount += structuredDocumentRegions[i].getNumberOfRegions(); - } - NumberFormat formatter = NumberFormat.getIntegerInstance(); - final String regioncount = "Count: " + formatter.format(structuredDocumentRegions.length) + " document regions containing " + formatter.format(regionCount) + " text regions representing " + formatter.format(length) + " characters";//$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ - display.asyncExec(new Runnable() { - public void run() { - if (!counts.isDisposed()) { - counts.setText(regioncount); - counts.setEnabled(true); - } - if (!bomLabel.isDisposed()) { - bomLabel.setText("Byte Order Mark: " + getBOMText(fTextEditor.getEditorInput())); //$NON-NLS-1$ - bomLabel.setEnabled(true); - } - } - }); - return Status.OK_STATUS; - } - }; - counter.schedule(1000); - - Label blankRow = new Label(composite, SWT.NONE); - gd = new GridData(SWT.FILL, SWT.FILL, true, false); - gd.horizontalSpan = 2; - blankRow.setLayoutData(gd); - } - if (model != null) { - model.releaseFromRead(); - } - - TabFolder tabfolder = new TabFolder(composite, SWT.NONE); - tabfolder.setLayoutData(new GridData(GridData.FILL_BOTH)); - - TabItem partitionTab = new TabItem(tabfolder, SWT.BORDER); - partitionTab.setText(SSEUIMessages.OffsetStatusLineContributionItem_2); //$NON-NLS-1$ - SashForm partitions = new SashForm(tabfolder, SWT.NONE); - partitions.setOrientation(SWT.VERTICAL); - partitionTab.setControl(partitions); - createPartitionTabContents(partitions); - partitions.setWeights(new int[]{2, 1}); - - TabItem annotationsTab = new TabItem(tabfolder, SWT.BORDER); - annotationsTab.setText("Annotations"); //$NON-NLS-1$ - Composite annotations = new Composite(tabfolder, SWT.NONE); - annotationsTab.setControl(annotations); - createAnnotationTabContents(annotations); - - // only create the ITextRegions tab for IStructuredDocuments - if (fDocument instanceof IStructuredDocument) { - TabItem regionTab = new TabItem(tabfolder, SWT.BORDER); - regionTab.setText(SSEUIMessages.OffsetStatusLineContributionItem_3); //$NON-NLS-1$ - SashForm regions = new SashForm(tabfolder, SWT.NONE); - regions.setOrientation(SWT.HORIZONTAL); - regionTab.setControl(regions); - createRegionTabContents(regions); - regions.setWeights(new int[]{3, 2}); - } - - if (structuredSelection != null) { - TabItem editorSelectionTab = new TabItem(tabfolder, SWT.BORDER); - editorSelectionTab.setText(SSEUIMessages.OffsetStatusLineContributionItem_14); - Composite editorSelectionComposite = new Composite(tabfolder, SWT.NONE); - editorSelectionTab.setControl(editorSelectionComposite); - fillSelectionTabContents(editorSelectionComposite, structuredSelection.toList(), "Class: " + structuredSelection.getClass().getName()); //$NON-NLS-1$ - } - - model = StructuredModelManager.getModelManager().getExistingModelForRead(fDocument); - if (model != null) { - TabItem overlappingIndexedRegionsTab = new TabItem(tabfolder, SWT.BORDER); - overlappingIndexedRegionsTab.setText(SSEUIMessages.OffsetStatusLineContributionItem_20); - Composite overlappingIndexedRegionsTabComposite = new Composite(tabfolder, SWT.NONE); - overlappingIndexedRegionsTab.setControl(overlappingIndexedRegionsTabComposite); - fillSelectionTabContents(overlappingIndexedRegionsTabComposite, getIndexedRegions(textSelection), "All IndexedRegions overlapping text selection"); //$NON-NLS-1$ - model.releaseFromRead(); - } - - IEditorSite site = fTextEditor.getEditorSite(); - if (site != null) { - IWorkbenchWindow window = site.getWorkbenchWindow(); - if (window != null) { - ISelectionService service = window.getSelectionService(); - ISelection selectionFromService = service.getSelection(); - if (service != null && !selectionFromService.equals(structuredSelection) && selectionFromService instanceof IStructuredSelection) { - TabItem selectionServiceTab = new TabItem(tabfolder, SWT.BORDER); - selectionServiceTab.setText(SSEUIMessages.OffsetStatusLineContributionItem_19); - Composite selectionServiceComposite = new Composite(tabfolder, SWT.NONE); - selectionServiceTab.setControl(selectionServiceComposite); - fillSelectionTabContents(selectionServiceComposite, ((IStructuredSelection) selectionFromService).toList(), "Class: " + selectionFromService.getClass().getName()); //$NON-NLS-1$ - } - } - } - - return composite; - } - - /** - * @param editorInput - * @return - */ - private String getBOMText(IEditorInput editorInput) { - IFile file = (IFile) editorInput.getAdapter(IFile.class); - String detectedBOM = "none"; //$NON-NLS-1$ - if (file != null) { - InputStream s = null; - try { - s = file.getContents(true); - if (s != null) { - int b1 = s.read() & 0xFF; - int b2 = s.read() & 0xFF; - if (b1 == 0xFE && b2 == 0xFF) { - detectedBOM = "FE FF (UTF-16BE)"; //$NON-NLS-1$ - } - else if (b1 == 0xFF && b2 == 0xFE) { - detectedBOM = "FF FE (UTF-16LE)"; //$NON-NLS-1$ - } - else { - int b3 = s.read() & 0xFF; - if (b1 == 0xEF && b2 == 0xBB && b3 == 0xBF) { - detectedBOM = "EF BB BF (UTF-8)"; //$NON-NLS-1$ - } - } - } - } - catch (Exception e) { - detectedBOM = e.getMessage(); - } - finally { - if (s != null) - try { - s.close(); - } - catch (IOException e) { - } - } - } - else { - detectedBOM = "N/A"; //$NON-NLS-1$ - } - return detectedBOM; - } - - private List getIndexedRegions(ITextSelection textSelection) { - Set overlappingIndexedRegions = new HashSet(2); - int start = textSelection.getOffset(); - int end = start + textSelection.getLength(); - IStructuredModel model = StructuredModelManager.getModelManager().getExistingModelForRead(fDocument); - if (model != null) { - for (int i = start; i <= end; i++) { - IndexedRegion r = model.getIndexedRegion(i); - if (r != null) { - overlappingIndexedRegions.add(r); - } - } - model.releaseFromRead(); - } - - return Arrays.asList(overlappingIndexedRegions.toArray()); - } - - /** - * @param sash - */ - private void createPartitionTabContents(SashForm sash) { - Composite partioningComposite = new Composite(sash, SWT.NONE); - partioningComposite.setLayout(new GridLayout(2, false)); - partioningComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); - - Label label = new Label(partioningComposite, SWT.SINGLE); - label.setText(SSEUIMessages.OffsetStatusLineContributionItem_8); //$NON-NLS-1$ - label.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false)); - final Combo partitioningCombo = new Combo(partioningComposite, SWT.READ_ONLY); - partitioningCombo.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); - - final Label partitionerInstanceLabel = new Label(partioningComposite, SWT.SINGLE); - GridData gd = new GridData(SWT.FILL, SWT.FILL, true, false); - gd.horizontalSpan = 2; - partitionerInstanceLabel.setLayoutData(gd); - - final TableViewer fPartitionTable = new TableViewer(partioningComposite, SWT.FULL_SELECTION); - gd = new GridData(SWT.FILL, SWT.FILL, true, true); - gd.horizontalSpan = 2; - fPartitionTable.getControl().setLayoutData(gd); - fPartitionTable.setContentProvider(new ArrayContentProvider()); - fPartitionTable.getTable().setHeaderVisible(true); - fPartitionTable.getTable().setLinesVisible(true); - String[] columns = new String[]{SSEUIMessages.OffsetStatusLineContributionItem_9, SSEUIMessages.OffsetStatusLineContributionItem_10, SSEUIMessages.OffsetStatusLineContributionItem_11}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - fPartitionTable.setLabelProvider(new ITableLabelProvider() { - public void addListener(ILabelProviderListener listener) { - } - - public void dispose() { - } - - public Image getColumnImage(Object element, int columnIndex) { - return null; - } - - public String getColumnText(Object element, int columnIndex) { - ITypedRegion partition = (ITypedRegion) element; - String text = null; - switch (columnIndex) { - case 0 : - text = Integer.toString(partition.getOffset()); - break; - case 1 : - text = Integer.toString(partition.getLength()); - break; - case 2 : - text = partition.getType(); - break; - } - if (text == null) - text = ""; //$NON-NLS-1$ - return text; - } - - public boolean isLabelProperty(Object element, String property) { - return false; - } - - public void removeListener(ILabelProviderListener listener) { - } - }); - TableLayout tlayout = new TableLayout(); - CellEditor[] cellEditors = new CellEditor[columns.length]; - int columnWidths[] = new int[]{Display.getCurrent().getBounds().width / 14, Display.getCurrent().getBounds().width / 14, Display.getCurrent().getBounds().width / 5}; - for (int i = 0; i < columns.length; i++) { - tlayout.addColumnData(new ColumnWeightData(1)); - TableColumn tc = new TableColumn(fPartitionTable.getTable(), SWT.NONE); - tc.setText(columns[i]); - tc.setResizable(true); - tc.setWidth(columnWidths[i]); - } - fPartitionTable.setCellEditors(cellEditors); - fPartitionTable.setColumnProperties(columns); - final String[] partitionings = (fDocument instanceof IDocumentExtension3) ? ((IDocumentExtension3) fDocument).getPartitionings() : new String[]{IDocumentExtension3.DEFAULT_PARTITIONING}; - partitioningCombo.setItems(partitionings); - partitioningCombo.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent e) { - ISelection sel = fTextEditor.getSelectionProvider().getSelection(); - ITextSelection textSelection = (ITextSelection) sel; - try { - String partitionerText = fDocument instanceof IDocumentExtension3 ? ((IDocumentExtension3) fDocument).getDocumentPartitioner(partitioningCombo.getItem(partitioningCombo.getSelectionIndex())).toString() : ("" + fDocument.getDocumentPartitioner()); //$NON-NLS-1$ - partitionerInstanceLabel.setText(SSEUIMessages.OffsetStatusLineContributionItem_13 + partitionerText); //$NON-NLS-1$ - fPartitionTable.setInput(TextUtilities.computePartitioning(fDocument, partitioningCombo.getItem(partitioningCombo.getSelectionIndex()), textSelection.getOffset(), textSelection.getLength(), true)); - } - catch (BadLocationException e1) { - fPartitionTable.setInput(new ITypedRegion[0]); - } - } - }); - try { - if (partitionings.length > 0) { - String selectedPartitioning = partitioningCombo.getItem(0); - if (Utilities.contains(partitionings, IStructuredPartitioning.DEFAULT_STRUCTURED_PARTITIONING)) { - selectedPartitioning = IStructuredPartitioning.DEFAULT_STRUCTURED_PARTITIONING; - for (int i = 0; i < partitionings.length; i++) { - if (partitionings[i].equals(IStructuredPartitioning.DEFAULT_STRUCTURED_PARTITIONING)) { - partitioningCombo.select(i); - } - } - } - else { - partitioningCombo.select(0); - } - ISelection sel = fTextEditor.getSelectionProvider().getSelection(); - ITextSelection textSelection = (ITextSelection) sel; - ITypedRegion[] partitions = TextUtilities.computePartitioning(fDocument, selectedPartitioning, textSelection.getOffset(), textSelection.getLength(), true); - fPartitionTable.setInput(partitions); - String partitionerText = fDocument instanceof IDocumentExtension3 ? ((IDocumentExtension3) fDocument).getDocumentPartitioner(partitioningCombo.getItem(partitioningCombo.getSelectionIndex())).toString() : ("" + fDocument.getDocumentPartitioner()); //$NON-NLS-1$ - partitionerInstanceLabel.setText(SSEUIMessages.OffsetStatusLineContributionItem_13 + partitionerText); //$NON-NLS-1$ - } - else { - ISelection sel = fTextEditor.getSelectionProvider().getSelection(); - ITextSelection textSelection = (ITextSelection) sel; - fPartitionTable.setInput(fDocument.computePartitioning(textSelection.getOffset(), textSelection.getLength())); - } - } - catch (BadLocationException e1) { - fPartitionTable.setInput(new ITypedRegion[0]); - } - partitioningCombo.setFocus(); - - - final StyledText text = new StyledText(sash, SWT.MULTI | SWT.READ_ONLY); - fPartitionTable.addSelectionChangedListener(new ISelectionChangedListener() { - public void selectionChanged(SelectionChangedEvent event) { - if (event.getSelection() instanceof IStructuredSelection) { - IRegion partition = (IRegion) ((IStructuredSelection) event.getSelection()).getFirstElement(); - IDocument document = fTextEditor.getDocumentProvider().getDocument(fTextEditor.getEditorInput()); - String source; - try { - source = document.get(partition.getOffset(), partition.getLength()); - text.setEnabled(true); - text.setText(source); - } - catch (BadLocationException e) { - e.printStackTrace(); - } - } - } - }); - text.setEnabled(false); - } - - /** - * @param composite - * @return - */ - private Composite createRegionTabContents(SashForm sashForm) { - ISelection sel = fTextEditor.getSelectionProvider().getSelection(); - final ITextSelection textSelection = (ITextSelection) sel; - final List documentRegions = new ArrayList(); - if (fDocument instanceof IStructuredDocument) { - IStructuredDocument structuredDocument = (IStructuredDocument) fDocument; - int pos = textSelection.getOffset(); - int end = textSelection.getOffset() + textSelection.getLength(); - IStructuredDocumentRegion docRegion = structuredDocument.getRegionAtCharacterOffset(pos); - IStructuredDocumentRegion endRegion = structuredDocument.getRegionAtCharacterOffset(end); - if (pos < end) { - while (docRegion != endRegion) { - documentRegions.add(docRegion); - docRegion = docRegion.getNext(); - } - } - documentRegions.add(docRegion); - } - - final TreeViewer tree = new TreeViewer(sashForm, SWT.V_SCROLL | SWT.H_SCROLL); - final String START = SSEUIMessages.OffsetStatusLineContributionItem_15; //$NON-NLS-1$ - final String LENGTH = SSEUIMessages.OffsetStatusLineContributionItem_16; //$NON-NLS-1$ - final String TEXTLENGTH = SSEUIMessages.OffsetStatusLineContributionItem_17; //$NON-NLS-1$ - final String CONTEXT = SSEUIMessages.OffsetStatusLineContributionItem_18; //$NON-NLS-1$ - tree.setContentProvider(new ITreeContentProvider() { - public void dispose() { - } - - public Object[] getChildren(Object parentElement) { - List children = new ArrayList(0); - if (parentElement instanceof ITextSelection) { - children.addAll(documentRegions); - } - if (parentElement instanceof ITextRegionCollection) { - children.add(((ITextRegionCollection) parentElement).getRegions().toArray()); - } - if (parentElement instanceof ITextRegion) { - children.add(new KeyValuePair(CONTEXT, ((ITextRegion) parentElement).getType())); - children.add(new KeyValuePair(START, Integer.toString(((ITextRegion) parentElement).getStart()))); - children.add(new KeyValuePair(TEXTLENGTH, Integer.toString(((ITextRegion) parentElement).getTextLength()))); - children.add(new KeyValuePair(LENGTH, Integer.toString(((ITextRegion) parentElement).getLength()))); - } - if (parentElement instanceof ITextRegionList) { - children.add(Arrays.asList(((ITextRegionList) parentElement).toArray())); - } - if (parentElement instanceof Collection) { - children.addAll((Collection) parentElement); - } - if (parentElement instanceof Object[]) { - children.addAll(Arrays.asList((Object[]) parentElement)); - } - return children.toArray(); - } - - public Object[] getElements(Object inputElement) { - return documentRegions.toArray(); - } - - public Object getParent(Object element) { - if (element instanceof IStructuredDocumentRegion) - return ((IStructuredDocumentRegion) element).getParentDocument(); - if (element instanceof ITextRegionContainer) { - return ((ITextRegionContainer) element).getParent(); - } - return fDocument; - } - - public boolean hasChildren(Object element) { - return !(element instanceof KeyValuePair); - } - - public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { - } - }); - tree.setLabelProvider(new LabelProvider() { - public String getText(Object element) { - if (element instanceof KeyValuePair) - return ((KeyValuePair) element).fKey.toString().toLowerCase() + ": " + ((KeyValuePair) element).fValue; //$NON-NLS-1$ - if (element instanceof IStructuredDocumentRegion) { - IStructuredDocumentRegion documentRegion = (IStructuredDocumentRegion) element; - int packageNameLength = documentRegion.getClass().getPackage().getName().length(); - if (packageNameLength > 0) - packageNameLength++; - String name = documentRegion.getClass().getName().substring(packageNameLength); - String text = "[" + documentRegion.getStartOffset() + "-" + documentRegion.getEndOffset() + "] " + name + "@" + element.hashCode() + " " + documentRegion.getType(); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ - return text; - } - if (element instanceof ITextRegion) { - ITextRegion textRegion = (ITextRegion) element; - int packageNameLength = textRegion.getClass().getPackage().getName().length(); - if (packageNameLength > 0) - packageNameLength++; - String name = textRegion.getClass().getName().substring(packageNameLength); - String text = "[" + textRegion.getStart() + "-" + textRegion.getEnd() + "] " + name + "@" + element.hashCode() + " " + textRegion.getType(); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ - return text; - } - return super.getText(element); - } - }); - tree.setInput(fDocument); - - - final Text displayText = new Text(sashForm, SWT.V_SCROLL | SWT.H_SCROLL | SWT.READ_ONLY | SWT.BORDER); - displayText.setBackground(sashForm.getDisplay().getSystemColor(SWT.COLOR_LIST_BACKGROUND)); - tree.addSelectionChangedListener(new ISelectionChangedListener() { - public void selectionChanged(SelectionChangedEvent event) { - if (event.getSelection() instanceof IStructuredSelection) { - Object o = ((IStructuredSelection) event.getSelection()).getFirstElement(); - if (o instanceof KeyValuePair) - displayText.setText(((KeyValuePair) o).fValue.toString()); - else if (o instanceof ITextSelection) { - ITextSelection text = (ITextSelection) o; - try { - displayText.setText(fDocument.get(text.getOffset(), text.getLength())); - } - catch (BadLocationException e) { - displayText.setText(""); //$NON-NLS-1$ - } - } - else if (o instanceof ITextRegionCollection) { - ITextRegionCollection region = (ITextRegionCollection) o; - displayText.setText(region.getFullText()); - } - else - displayText.setText("" + o); //$NON-NLS-1$ - } - } - }); - return sashForm; - } - - private void fillSelectionTabContents(Composite area, List selection, String description) { - area.setLayout(new GridLayout()); - area.setLayoutData(new GridData()); - - Label typeName = new Label(area, SWT.WRAP); - typeName.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); - typeName.setText(description); //$NON-NLS-1$ - - (new Label(area, SWT.NONE)).setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false)); - SashForm structuredSashForm = new SashForm(area, SWT.NONE); - structuredSashForm.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); - structuredSashForm.setOrientation(SWT.VERTICAL); - - final TableViewer structuredSelectionTable = new TableViewer(structuredSashForm, SWT.FULL_SELECTION | SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER); - - structuredSelectionTable.getTable().setHeaderVisible(true); - structuredSelectionTable.getTable().setLinesVisible(true); - structuredSelectionTable.setSorter(new ViewerSorter() { - public int category(Object element) { - if (element instanceof IndexedRegion) - return ((IndexedRegion) element).getStartOffset(); - return super.category(element); - } - }); - - structuredSelectionTable.setLabelProvider(new ITableLabelProvider() { - public void addListener(ILabelProviderListener listener) { - } - - public void dispose() { - } - - public Image getColumnImage(Object element, int columnIndex) { - if (element instanceof INodeNotifier) { - INodeAdapter adapterFor = ((INodeNotifier) element).getAdapterFor(IJFaceNodeAdapter.class); - if (columnIndex == 2 && adapterFor != null && adapterFor instanceof IJFaceNodeAdapter) { - IJFaceNodeAdapter adapter = (IJFaceNodeAdapter) adapterFor; - return adapter.getLabelImage((element)); - } - } - return null; - } - - public String getColumnText(Object element, int columnIndex) { - String text = null; - if (element != null) { - switch (columnIndex) { - case 0 : { - text = String.valueOf(((List) structuredSelectionTable.getInput()).indexOf(element)); - } - break; - case 1 : { - text = element.getClass().getName(); - } - break; - case 2 : { - text = StringUtils.firstLineOf(element.toString()); - } - break; - default : - text = ""; //$NON-NLS-1$ - } - } - return text; - } - - public boolean isLabelProperty(Object element, String property) { - return false; - } - - public void removeListener(ILabelProviderListener listener) { - } - }); - - TableLayout tlayout = new TableLayout(); - tlayout.addColumnData(new ColumnWeightData(7, true)); - tlayout.addColumnData(new ColumnWeightData(28, true)); - tlayout.addColumnData(new ColumnWeightData(50, true)); - structuredSelectionTable.getTable().setLayout(tlayout); - - TableColumn tc = new TableColumn(structuredSelectionTable.getTable(), SWT.NONE); - tc.setText("Item"); //$NON-NLS-1$ - tc.setResizable(true); - tc.setWidth(40); - - tc = new TableColumn(structuredSelectionTable.getTable(), SWT.NONE); - tc.setText("Class"); //$NON-NLS-1$ - tc.setResizable(true); - tc.setWidth(40); - - tc = new TableColumn(structuredSelectionTable.getTable(), SWT.NONE); - tc.setText("Value"); //$NON-NLS-1$ - tc.setResizable(true); - tc.setWidth(40); - - structuredSelectionTable.setContentProvider(new ArrayContentProvider()); - final List input = selection; - structuredSelectionTable.setInput(input); - - final TreeViewer infoTree = new TreeViewer(structuredSashForm, SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER); - infoTree.setLabelProvider(new LabelProvider() { - public Image getImage(Object element) { - if (element instanceof TreeViewer && infoTree.getInput() instanceof INodeNotifier) { - INodeAdapter adapterFor = ((INodeNotifier) infoTree.getInput()).getAdapterFor(IJFaceNodeAdapter.class); - if (adapterFor != null && adapterFor instanceof IJFaceNodeAdapter) { - IJFaceNodeAdapter adapter = (IJFaceNodeAdapter) adapterFor; - return adapter.getLabelImage((infoTree.getInput())); - } - } - return super.getImage(element); - } - - public String getText(Object element) { - if (element instanceof Class) { - return "Class: " + ((Class) element).getName(); //$NON-NLS-1$ - } - if (element instanceof Collection) { - return "Registered Adapters:"; //$NON-NLS-1$ - } - if (element instanceof IRegion) { - return "Indexed Region offset span: [" + ((IRegion) element).getOffset() + "-" + ((IRegion) element).getLength() + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } - if (element instanceof TreeViewer && infoTree.getInput() instanceof INodeNotifier) { - IJFaceNodeAdapter adapter = (IJFaceNodeAdapter) ((INodeNotifier) infoTree.getInput()).getAdapterFor(IJFaceNodeAdapter.class); - if (adapter != null) { - return adapter.getLabelText((infoTree.getInput())); - } - } - return super.getText(element); - } - }); - infoTree.setContentProvider(new ITreeContentProvider() { - public void dispose() { - } - - public Object[] getChildren(Object parentElement) { - if (parentElement instanceof Collection) - return ((Collection) parentElement).toArray(); - return new Object[0]; - } - - public Object[] getElements(Object inputElement) { - List elements = new ArrayList(4); - if (inputElement != null) { - if (inputElement instanceof INodeNotifier && ((INodeNotifier) inputElement).getAdapterFor(IJFaceNodeAdapter.class) != null) { - elements.add(infoTree); - } - elements.add(inputElement.getClass()); - if (inputElement instanceof IndexedRegion) { - elements.add(new Region(((IndexedRegion) inputElement).getStartOffset(), ((IndexedRegion) inputElement).getEndOffset())); - } - if (inputElement instanceof INodeNotifier) { - elements.add(((INodeNotifier) inputElement).getAdapters()); - } - } - return elements.toArray(); - } - - public Object getParent(Object element) { - return null; - } - - public boolean hasChildren(Object element) { - return element instanceof Collection; - } - - public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { - } - }); - - structuredSelectionTable.addSelectionChangedListener(new ISelectionChangedListener() { - public void selectionChanged(SelectionChangedEvent event) { - int selectionIndex = structuredSelectionTable.getTable().getSelectionIndex(); - if (selectionIndex != -1) { - infoTree.setInput(structuredSelectionTable.getElementAt(selectionIndex)); - } - else { - infoTree.setInput(event.getSelectionProvider().getSelection()); - } - infoTree.expandToLevel(2); - } - }); - - structuredSashForm.setWeights(new int[]{3, 2}); - } - - private String getLineNumber(Annotation annotation) { - int line = -1; - if (annotation instanceof MarkerAnnotation) { - line = MarkerUtilities.getLineNumber(((MarkerAnnotation) annotation).getMarker());//$NON-NLS-1$ - } - else { - IAnnotationModel annotationModel = fTextEditor.getDocumentProvider().getAnnotationModel(fTextEditor.getEditorInput()); - Position p = annotationModel.getPosition(annotation); - if (p != null && !p.isDeleted()) { - try { - // don't forget the +1 - line = fDocument.getLineOfOffset(p.getOffset()) + 1; - } - catch (BadLocationException e) { - return e.getMessage(); - } - } - } - return Integer.toString(line); - } - } - - static class KeyValuePair { - Object fKey; - String fValue; - - public KeyValuePair(Object key, String value) { - fKey = key; - fValue = value; - } - } - - class ShowEditorInformationAction extends Action { - public ShowEditorInformationAction() { - super(); - } - - public void run() { - /** - * TODO: Provide a more useful control, maybe a table where the - * selection shows you the partition's text in a StyledText pane - * beneath it. - */ - super.run(); - new InformationDialog(((Control) fTextEditor.getAdapter(Control.class)).getShell()).open(); - } - } - - IAction fShowEditorInformationAction = new ShowEditorInformationAction(); - - ITextEditor fTextEditor = null; - - /** - * @param id - */ - public OffsetStatusLineContributionItem(String id) { - super(id); - setToolTipText("Double-click for more information"); - } - - /** - * @param id - * @param visible - * @param widthInChars - */ - public OffsetStatusLineContributionItem(String id, boolean visible, int widthInChars) { - super(id, visible, widthInChars); - setToolTipText("Double-click for more information"); - } - - public void setActiveEditor(ITextEditor textEditor) { - fTextEditor = textEditor; - setActionHandler(fShowEditorInformationAction); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/ui/StructuredTextAnnotationImageProvider.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/ui/StructuredTextAnnotationImageProvider.java deleted file mode 100644 index 4d4923ac4c..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/ui/StructuredTextAnnotationImageProvider.java +++ /dev/null @@ -1,56 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.ui; - -import org.eclipse.jface.resource.ImageDescriptor; -import org.eclipse.jface.text.source.Annotation; -import org.eclipse.swt.graphics.Image; -import org.eclipse.ui.texteditor.IAnnotationImageProvider; - -/** - * Image provider for structured text editor annotations. - * - * @author pavery - */ -public class StructuredTextAnnotationImageProvider implements IAnnotationImageProvider { - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.IAnnotationImageProvider#getImageDescriptor(java.lang.String) - */ - public ImageDescriptor getImageDescriptor(String imageDescritporId) { - return null; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.IAnnotationImageProvider#getImageDescriptorId(org.eclipse.jface.text.source.Annotation) - */ - public String getImageDescriptorId(Annotation annotation) { - return null; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.IAnnotationImageProvider#getManagedImage(org.eclipse.jface.text.source.Annotation) - */ - public Image getManagedImage(Annotation annotation) { - // future return different types of managed images as JDT does - // eg. overlay icon images, "grayed" images, quick fixable, etc... - return null; - } - -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/util/Assert.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/util/Assert.java deleted file mode 100644 index d04eaed87f..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/util/Assert.java +++ /dev/null @@ -1,120 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.util; - - -/** - * <code>Assert</code> is useful for for embedding runtime sanity checks in - * code. The predicate methods all test a condition and throw some type of - * unchecked exception if the condition does not hold. - * <p> - * Assertion failure exceptions, like most runtime exceptions, are thrown when - * something is misbehaving. Assertion failures are invariably unspecified - * behavior; consequently, clients should never rely on these being thrown - * (and certainly should not being catching them specifically). - * </p> - */ -public final class Assert { - - /** - * <code>AssertionFailedException</code> is a runtime exception thrown - * by some of the methods in <code>Assert</code>. - * <p> - * This class is not declared public to prevent some misuses; programs - * that catch or otherwise depend on assertion failures are susceptible to - * unexpected breakage when assertions in the code are added or removed. - * </p> - */ - class AssertionFailedException extends RuntimeException { - /** - * Comment for <code>serialVersionUID</code> - */ - private static final long serialVersionUID = 1L; - - /** - * Constructs a new exception. - */ - public AssertionFailedException() { - super(); - } - - /** - * Constructs a new exception with the given message. - */ - public AssertionFailedException(String detail) { - super(detail); - } - } - - /** - * Asserts that an argument is legal. If the given boolean is not - * <code>true</code>, an <code>IllegalArgumentException</code> is - * thrown. The given message is included in that exception, to aid - * debugging. - * - * @param expression - * the outcode of the check - * @param message - * the message to include in the exception - * @return <code>true</code> if the check passes (does not return if the - * check fails) - * @exception IllegalArgumentException - * if the legality test failed - */ - public static boolean isLegal(boolean expression, String message) { - if (!expression) - throw new IllegalArgumentException(message); - return expression; - } - - /** - * Asserts that the given object is not <code>null</code>. If this is - * not the case, some kind of unchecked exception is thrown. The given - * message is included in that exception, to aid debugging. - * - * @param object - * the value to test - * @param message - * the message to include in the exception - * @exception IllegalArgumentException - * if the object is <code>null</code> - */ - public static void isNotNull(Object object, String message) { - if (object == null) { - throw new Assert().new AssertionFailedException(message); - } - } - - /** - * Asserts that the given boolean is <code>true</code>. If this is not - * the case, some kind of unchecked exception is thrown. The given message - * is included in that exception, to aid debugging. - * - * @param expression - * the outcode of the check - * @param message - * the message to include in the exception - * @return <code>true</code> if the check passes (does not return if the - * check fails) - */ - public static boolean isTrue(boolean expression, String message) { - if (!expression) { - throw new Assert().new AssertionFailedException(message); - } - return expression; - } - - /* This class is not intended to be instantiated. */ - private Assert() { - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/util/EditorUtility.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/util/EditorUtility.java deleted file mode 100644 index 8a26343395..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/util/EditorUtility.java +++ /dev/null @@ -1,142 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2006 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.util; - - -import com.ibm.icu.util.StringTokenizer; - -import org.eclipse.jface.action.Action; -import org.eclipse.jface.resource.JFaceResources; -import org.eclipse.swt.SWT; -import org.eclipse.swt.graphics.Color; -import org.eclipse.swt.graphics.RGB; - -/** - * Helpful methods to be used with the Source Editor - */ -public class EditorUtility { - - /** - * Appends to modifier string of the given SWT modifier bit to the given - * modifierString. - * - * @param modifierString - * the modifier string - * @param modifier - * an int with SWT modifier bit - * @return the concatenated modifier string - */ - private static String appendModifierString(String modifierString, int modifier) { - if (modifierString == null) - modifierString = ""; //$NON-NLS-1$ - String newModifierString = Action.findModifierString(modifier); - if (modifierString.length() == 0) - return newModifierString; - return modifierString + " + " + newModifierString; //$NON-NLS-1$ - } - - /** - * Computes the state mask for the given modifier string. - * - * @param modifiers - * the string with the modifiers, separated by '+', '-', ';', - * ',' or '.' - * @return the state mask or -1 if the input is invalid - */ - public static int computeStateMask(String modifiers) { - if (modifiers == null) - return -1; - - if (modifiers.length() == 0) - return SWT.NONE; - - int stateMask = 0; - StringTokenizer modifierTokenizer = new StringTokenizer(modifiers, ",;.:+-* "); //$NON-NLS-1$ - while (modifierTokenizer.hasMoreTokens()) { - int modifier = EditorUtility.findLocalizedModifier(modifierTokenizer.nextToken()); - if (modifier == 0 || (stateMask & modifier) == modifier) - return -1; - stateMask = stateMask | modifier; - } - return stateMask; - } - - /** - * Maps the localized modifier name to a code in the same manner as - * #findModifier. - * - * @return the SWT modifier bit, or <code>0</code> if no match was found - * @see findModifier - */ - public static int findLocalizedModifier(String token) { - if (token == null) - return 0; - - if (token.equalsIgnoreCase(Action.findModifierString(SWT.CTRL))) - return SWT.CTRL; - if (token.equalsIgnoreCase(Action.findModifierString(SWT.SHIFT))) - return SWT.SHIFT; - if (token.equalsIgnoreCase(Action.findModifierString(SWT.ALT))) - return SWT.ALT; - if (token.equalsIgnoreCase(Action.findModifierString(SWT.COMMAND))) - return SWT.COMMAND; - - return 0; - } - - /** - * Temporary method to help migrate from using StructuredTextColors to - * using base ColorRegistry. Instead of using symbolic names in the color - * registry, we are currently mapping the rgb.toString value to - * corresponding color. - * - * @param rgb - * @return Color - */ - public static Color getColor(RGB rgb) { - if (rgb == null) - return null; - - // get the color from the platform color registry - Color color = JFaceResources.getColorRegistry().get(rgb.toString()); - - // if the platform color registry does not have this color yet, add to - // the registry - if (color == null) { - JFaceResources.getColorRegistry().put(rgb.toString(), rgb); - color = JFaceResources.getColorRegistry().get(rgb.toString()); - } - return color; - } - - /** - * Returns the modifier string for the given SWT modifier modifier bits. - * - * @param stateMask - * the SWT modifier bits - * @return the modifier string - */ - public static String getModifierString(int stateMask) { - String modifierString = ""; //$NON-NLS-1$ - if ((stateMask & SWT.CTRL) == SWT.CTRL) - modifierString = appendModifierString(modifierString, SWT.CTRL); - if ((stateMask & SWT.ALT) == SWT.ALT) - modifierString = appendModifierString(modifierString, SWT.ALT); - if ((stateMask & SWT.SHIFT) == SWT.SHIFT) - modifierString = appendModifierString(modifierString, SWT.SHIFT); - if ((stateMask & SWT.COMMAND) == SWT.COMMAND) - modifierString = appendModifierString(modifierString, SWT.COMMAND); - - return modifierString; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/util/PixelConverter.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/util/PixelConverter.java deleted file mode 100644 index a12e28cebc..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/util/PixelConverter.java +++ /dev/null @@ -1,29 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.util; - -import org.eclipse.swt.graphics.Font; -import org.eclipse.swt.widgets.Control; - - -/** - * @deprecated - use {@link org.eclipse.jface.layout.PixelConverter} - */ -public class PixelConverter extends org.eclipse.jface.layout.PixelConverter { - - public PixelConverter(Control control) { - super(control); - } - - public PixelConverter(Font font) { - super(font); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/util/PlatformStatusLineUtil.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/util/PlatformStatusLineUtil.java deleted file mode 100644 index c71017e837..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/util/PlatformStatusLineUtil.java +++ /dev/null @@ -1,238 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.util; - -import org.eclipse.jface.action.IStatusLineManager; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.swt.custom.StyledText; -import org.eclipse.swt.custom.VerifyKeyListener; -import org.eclipse.swt.events.FocusAdapter; -import org.eclipse.swt.events.FocusEvent; -import org.eclipse.swt.events.MouseEvent; -import org.eclipse.swt.events.MouseListener; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.events.SelectionListener; -import org.eclipse.swt.events.VerifyEvent; -import org.eclipse.swt.widgets.Control; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.IWorkbenchPage; -import org.eclipse.ui.IWorkbenchWindow; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.texteditor.ITextEditor; -import org.eclipse.wst.sse.ui.StructuredTextEditor; - -/** - * Utility to display (and/or clear) messages on the status line. - * - * @author pavery - */ -public class PlatformStatusLineUtil { - - private static class ClearMessage implements Runnable { - public void run() { - displayMessage(null); - } - } - - private static class ClearStatusLine implements Runnable { - private IStatusLineManager fManager; - private boolean fIsError; - - ClearStatusLine(IStatusLineManager statusLineManager, boolean isError) { - fManager = statusLineManager; - fIsError = isError; - } - - public void run() { - if (fIsError) { - fManager.setErrorMessage(null); - } - else { - fManager.setMessage(null); - } - } - } - - /** - * Used to clear message on focus loss, change of selection, key type, - * etc... - */ - private static class OneTimeListener extends FocusAdapter implements VerifyKeyListener, SelectionListener, MouseListener { - private Runnable fRunner = null; - private StyledText fStyledText; - - OneTimeListener(StyledText target, Runnable r) { - fStyledText = target; - fRunner = r; - fStyledText.addVerifyKeyListener(this); - fStyledText.addFocusListener(this); - fStyledText.addSelectionListener(this); - fStyledText.addMouseListener(this); - } - - public void focusLost(FocusEvent e) { - unhookAndRun(); - } - - public void mouseDoubleClick(MouseEvent e) { - unhookAndRun(); - } - - public void mouseDown(MouseEvent e) { - unhookAndRun(); - } - - public void mouseUp(MouseEvent e) { - // - } - - private void unhookAndRun() { - fStyledText.removeVerifyKeyListener(this); - fStyledText.removeFocusListener(this); - fStyledText.removeSelectionListener(this); - fStyledText.removeMouseListener(this); - fStyledText.getDisplay().asyncExec(fRunner); - } - - public void verifyKey(VerifyEvent event) { - unhookAndRun(); - } - - public void widgetDefaultSelected(SelectionEvent e) { - unhookAndRun(); - } - - public void widgetSelected(SelectionEvent e) { - unhookAndRun(); - } - } - - /** - * Status line error message will be cleared w/ key type or selection change - * - * @deprecated - */ - public static void addOneTimeClearListener() { - IEditorPart editor = getActiveEditor(); - boolean added = false; - if (editor != null) { - Control control = (Control) editor.getAdapter(Control.class); - if (control instanceof StyledText) { - new OneTimeListener((StyledText) control, new ClearMessage()); - added = true; - } - } - if (!added) { - // clear the error message immediately - displayMessage(null); - } - } - - /** - * Clears the status line immediately - * @deprecated - */ - public static void clearStatusLine() { - displayMessage(null); - } - - /** - * Display a message on the status line (with a beep) - * @deprecated - * @param msg - */ - public static void displayErrorMessage(String msg) { - displayMessage(msg); - PlatformUI.getWorkbench().getDisplay().beep(); - } - - /** - * Display a message on the status line (no beep) - * @deprecated - * @param msg - */ - public static void displayMessage(String msg) { - IEditorPart editor = getActiveEditor(); - if (editor != null) { - editor.getEditorSite().getActionBars().getStatusLineManager().setErrorMessage(msg); - } - - } - - private static IEditorPart getActiveEditor() { - IEditorPart editor = null; - IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); - if (window == null) { - IWorkbenchWindow[] windows = PlatformUI.getWorkbench().getWorkbenchWindows(); - if (windows.length > 0) { - window = windows[0]; - } - } - if (window != null) { - IWorkbenchPage page = window.getActivePage(); - if (page != null) - editor = page.getActiveEditor(); - } - return editor; - } - - private PlatformStatusLineUtil() { - // force use of singleton - } - - /** - * Display an error message on the status line - * - * @param viewer - * @param msg - */ - public static boolean displayTemporaryErrorMessage(ITextViewer viewer, String msg) { - return _displayTemporaryMessage(viewer, msg, true); - } - - /** - * Display a message on the status line - * - * @param viewer - * @param msg - */ - public static boolean displayTemporaryMessage(ITextViewer viewer, String msg) { - return _displayTemporaryMessage(viewer, msg, false); - } - - static boolean _displayTemporaryMessage(ITextViewer viewer, String msg, boolean isError) { - boolean messageShown = false; - IEditorPart editor = getActiveEditor(); - if (editor != null) { - ITextEditor textEditor = (ITextEditor) editor.getAdapter(ITextEditor.class); - if (textEditor != null && textEditor instanceof StructuredTextEditor) { - if (((StructuredTextEditor) textEditor).getTextViewer() == viewer) { - IStatusLineManager statusLineManager = editor.getEditorSite().getActionBars().getStatusLineManager(); - if (isError) - statusLineManager.setErrorMessage(msg); - else - statusLineManager.setMessage(msg); - new OneTimeListener(viewer.getTextWidget(), new ClearStatusLine(statusLineManager, isError)); - messageShown = true; - } - } - } - - if (!messageShown) { - displayErrorMessage(msg); - addOneTimeClearListener(); - } - - return messageShown; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/util/RegistryReader.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/util/RegistryReader.java deleted file mode 100644 index 6fc895b29c..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/util/RegistryReader.java +++ /dev/null @@ -1,175 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.util; - - - -import org.eclipse.core.runtime.IConfigurationElement; -import org.eclipse.core.runtime.IExtension; -import org.eclipse.core.runtime.IExtensionPoint; -import org.eclipse.core.runtime.IExtensionRegistry; -import org.eclipse.core.runtime.IPluginRegistry; -import org.eclipse.wst.sse.ui.internal.Logger; - - -/** - * Template implementation of a registry reader that creates objects - * representing registry contents. Typically, an extension contains one - * element, but this reader handles multiple elements per extension. - * - * To start reading the extensions from the registry for an extension point, - * call the method <code>readRegistry</code>. - * - * To read children of an IConfigurationElement, call the method - * <code>readElementChildren</code> from your implementation of the method - * <code>readElement</code>, as it will not be done by default. - */ -public abstract class RegistryReader { - - - protected static final String TAG_DESCRIPTION = "description"; //$NON-NLS-1$ - - /** - * The constructor. - */ - protected RegistryReader() { - } - - /** - * This method extracts description as a subelement of the given element. - * - * @return description string if defined, or empty string if not. - */ - protected String getDescription(IConfigurationElement config) { - IConfigurationElement[] children = config.getChildren(TAG_DESCRIPTION); - if (children.length >= 1) { - return children[0].getValue(); - } - return ""; //$NON-NLS-1$ - } - - /** - * Logs the error in the workbench log using the provided text and the - * information in the configuration element. - */ - protected void logError(IConfigurationElement element, String text) { - IExtension extension = element.getDeclaringExtension(); - StringBuffer buf = new StringBuffer(); - buf.append("Plugin " + extension.getNamespace() + ", extension " + extension.getExtensionPointUniqueIdentifier()); //$NON-NLS-2$//$NON-NLS-1$ - buf.append("\n" + text); //$NON-NLS-1$ - Logger.log(Logger.ERROR, buf.toString()); - } - - /** - * Logs a very common registry error when a required attribute is missing. - */ - protected void logMissingAttribute(IConfigurationElement element, String attributeName) { - logError(element, "Required attribute '" + attributeName + "' not defined"); //$NON-NLS-2$//$NON-NLS-1$ - } - - /** - * Logs a registry error when the configuration element is unknown. - */ - protected void logUnknownElement(IConfigurationElement element) { - logError(element, "Unknown extension tag found: " + element.getName()); //$NON-NLS-1$ - } - - /** - * Apply a reproducable order to the list of extensions provided, such - * that the order will not change as extensions are added or removed. - */ - protected IExtension[] orderExtensions(IExtension[] extensions) { - // By default, the order is based on plugin id sorted - // in ascending order. The order for a plugin providing - // more than one extension for an extension point is - // dependent in the order listed in the XML file. - Sorter sorter = new Sorter() { - public boolean compare(Object extension1, Object extension2) { - String s1 = ((IExtension) extension1).getNamespace().toUpperCase(); - String s2 = ((IExtension) extension2).getNamespace().toUpperCase(); - //Return true if elementTwo is 'greater than' elementOne - return s2.compareTo(s1) > 0; - } - }; - - Object[] sorted = sorter.sort(extensions); - IExtension[] sortedExtension = new IExtension[sorted.length]; - System.arraycopy(sorted, 0, sortedExtension, 0, sorted.length); - return sortedExtension; - } - - /** - * Implement this method to read element's attributes. If children should - * also be read, then implementor is responsible for calling - * <code>readElementChildren</code>. Implementor is also responsible - * for logging missing attributes. - * - * @return true if element was recognized, false if not. - */ - protected abstract boolean readElement(IConfigurationElement element); - - /** - * Read the element's children. This is called by the subclass' - * readElement method when it wants to read the children of the element. - */ - protected void readElementChildren(IConfigurationElement element) { - readElements(element.getChildren()); - } - - /** - * Read each element one at a time by calling the subclass implementation - * of <code>readElement</code>. - * - * Logs an error if the element was not recognized. - */ - protected void readElements(IConfigurationElement[] elements) { - for (int i = 0; i < elements.length; i++) { - if (!readElement(elements[i])) - logUnknownElement(elements[i]); - } - } - - /** - * Read one extension by looping through its configuration elements. - */ - protected void readExtension(IExtension extension) { - readElements(extension.getConfigurationElements()); - } - - /** - * @deprecated use readRegistry(IExtensionRegistry registry, String pluginId, String extensionPoint) - */ - protected void readRegistry(IPluginRegistry registry, String pluginId, String extensionPoint) { - IExtensionPoint point = registry.getExtensionPoint(pluginId, extensionPoint); - if (point != null) { - IExtension[] extensions = point.getExtensions(); - extensions = orderExtensions(extensions); - for (int i = 0; i < extensions.length; i++) - readExtension(extensions[i]); - } - } - - /** - * Start the registry reading process using the supplied plugin ID and - * extension point. - */ - protected void readRegistry(IExtensionRegistry registry, String pluginId, String extensionPoint) { - IExtensionPoint point = registry.getExtensionPoint(pluginId, extensionPoint); - if (point != null) { - IExtension[] extensions = point.getExtensions(); - extensions = orderExtensions(extensions); - for (int i = 0; i < extensions.length; i++) - readExtension(extensions[i]); - } - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/util/SWTUtil.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/util/SWTUtil.java deleted file mode 100644 index aeb7dd77c3..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/util/SWTUtil.java +++ /dev/null @@ -1,156 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010, 2011 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.util; - -import org.eclipse.core.runtime.Assert; -import org.eclipse.jface.dialogs.IDialogConstants; -import org.eclipse.jface.layout.PixelConverter; -import org.eclipse.jface.resource.JFaceResources; -import org.eclipse.swt.SWT; -import org.eclipse.swt.accessibility.AccessibleAdapter; -import org.eclipse.swt.accessibility.AccessibleEvent; -import org.eclipse.swt.dnd.DragSource; -import org.eclipse.swt.dnd.DropTarget; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.widgets.Caret; -import org.eclipse.swt.widgets.Combo; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.Menu; -import org.eclipse.swt.widgets.ScrollBar; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.swt.widgets.Table; -import org.eclipse.swt.widgets.Widget; - - -/** - * <p>Utility class to simplify access to some SWT resources.</p> - * - * @base org.eclipse.jdt.internal.ui.util.SWTUtil - */ -public class SWTUtil { - - - public static final int COMBO_VISIBLE_ITEM_COUNT= 30; - - /** - * Returns the standard display to be used. The method first checks, if - * the thread calling this method has an associated display. If so, this - * display is returned. Otherwise the method returns the default display. - * @return returns the standard display to be used - */ - public static Display getStandardDisplay() { - Display display; - display= Display.getCurrent(); - if (display == null) - display= Display.getDefault(); - return display; - } - - /** - * Returns the shell for the given widget. If the widget doesn't represent - * a SWT object that manage a shell, <code>null</code> is returned. - * @param widget the widget - * - * @return the shell for the given widget - */ - public static Shell getShell(Widget widget) { - if (widget instanceof Control) - return ((Control)widget).getShell(); - if (widget instanceof Caret) - return ((Caret)widget).getParent().getShell(); - if (widget instanceof DragSource) - return ((DragSource)widget).getControl().getShell(); - if (widget instanceof DropTarget) - return ((DropTarget)widget).getControl().getShell(); - if (widget instanceof Menu) - return ((Menu)widget).getParent().getShell(); - if (widget instanceof ScrollBar) - return ((ScrollBar)widget).getParent().getShell(); - - return null; - } - - - /** - * Returns a width hint for a button control. - * @param button the button - * @return the width hint - */ - public static int getButtonWidthHint(Button button) { - button.setFont(JFaceResources.getDialogFont()); - PixelConverter converter= new PixelConverter(button); - int widthHint= converter.convertHorizontalDLUsToPixels(IDialogConstants.BUTTON_WIDTH); - return Math.max(widthHint, button.computeSize(SWT.DEFAULT, SWT.DEFAULT, true).x); - } - - /** - * Sets width and height hint for the button control. - * <b>Note:</b> This is a NOP if the button's layout data is not - * an instance of <code>GridData</code>. - * - * @param button the button for which to set the dimension hint - */ - public static void setButtonDimensionHint(Button button) { - Assert.isNotNull(button); - Object gd= button.getLayoutData(); - if (gd instanceof GridData) { - ((GridData)gd).widthHint= getButtonWidthHint(button); - ((GridData)gd).horizontalAlignment = GridData.FILL; - } - } - - public static int getTableHeightHint(Table table, int rows) { - if (table.getFont().equals(JFaceResources.getDefaultFont())) - table.setFont(JFaceResources.getDialogFont()); - int result= table.getItemHeight() * rows + table.getHeaderHeight(); - if (table.getLinesVisible()) - result+= table.getGridLineWidth() * (rows - 1); - return result; - } - - /** - * Adds an accessibility listener returning the given fixed name. - * - * @param control the control to add the accessibility support to - * @param text the name - */ - public static void setAccessibilityText(Control control, final String text) { - control.getAccessible().addAccessibleListener(new AccessibleAdapter() { - public void getName(AccessibleEvent e) { - e.result= text; - } - }); - } - - /** - * - * @param combo the combo - * - * @see Combo#setVisibleItemCount(int) - * @see #COMBO_VISIBLE_ITEM_COUNT - * - */ - public static void setDefaultVisibleItemCount(Combo combo) { - combo.setVisibleItemCount(COMBO_VISIBLE_ITEM_COUNT); - } - - public static GridLayout newLayoutNoMargins(int columns) { - GridLayout layout= new GridLayout(columns, false); - layout.marginWidth= 0; - layout.marginHeight= 0; - return layout; - } - - -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/util/Sorter.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/util/Sorter.java deleted file mode 100644 index 3a895d3d1b..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/util/Sorter.java +++ /dev/null @@ -1,77 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.util; - - - -/** - * The SortOperation takes a collection of objects and returns a sorted - * collection of these objects. Concrete instances of this class provide the - * criteria for the sorting of the objects based on the type of the objects. - */ -public abstract class Sorter { - - /** - * Returns true if elementTwo is 'greater than' elementOne This is the - * 'ordering' method of the sort operation. Each subclass overides this - * method with the particular implementation of the 'greater than' concept - * for the objects being sorted. - */ - public abstract boolean compare(Object elementOne, Object elementTwo); - - /** - * Sort the objects in sorted collection and return that collection. - */ - private Object[] quickSort(Object[] sortedCollection, int left, int right) { - int originalLeft = left; - int originalRight = right; - Object mid = sortedCollection[(left + right) / 2]; - - do { - while (compare(sortedCollection[left], mid)) - left++; - while (compare(mid, sortedCollection[right])) - right--; - if (left <= right) { - Object tmp = sortedCollection[left]; - sortedCollection[left] = sortedCollection[right]; - sortedCollection[right] = tmp; - left++; - right--; - } - } while (left <= right); - - if (originalLeft < right) - sortedCollection = quickSort(sortedCollection, originalLeft, right); - if (left < originalRight) - sortedCollection = quickSort(sortedCollection, left, originalRight); - - return sortedCollection; - } - - /** - * Return a new sorted collection from this unsorted collection. Sort - * using quick sort. - */ - public Object[] sort(Object[] unSortedCollection) { - int size = unSortedCollection.length; - Object[] sortedCollection = new Object[size]; - - //copy the array so can return a new sorted collection - System.arraycopy(unSortedCollection, 0, sortedCollection, 0, size); - if (size > 1) - quickSort(sortedCollection, 0, size - 1); - - return sortedCollection; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/view/events/CaretEvent.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/view/events/CaretEvent.java deleted file mode 100644 index e9078342ee..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/view/events/CaretEvent.java +++ /dev/null @@ -1,52 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.view.events; - -/** - * @deprecated - use base selection notification - * - * Simply holds data to be passed to CaretEventListeners - */ -public class CaretEvent extends java.util.EventObject { - - /** - * Comment for <code>serialVersionUID</code> - */ - private static final long serialVersionUID = 1L; - // initialize to impossible location - int fPosition = -1; - - /** - * doesnt't make sense to have a CaretEvent without the Caret postion, so - * use other constructor - */ - protected CaretEvent(Object source) { - super(source); - } - - /** - * This is the preferred constructor. - */ - public CaretEvent(Object source, int position) { - super(source); - setPosition(position); - } - - public int getPosition() { - return fPosition; - } - - void setPosition(int newPosition) { - fPosition = newPosition; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/view/events/ICaretListener.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/view/events/ICaretListener.java deleted file mode 100644 index 695e72b051..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/view/events/ICaretListener.java +++ /dev/null @@ -1,20 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.view.events; - -/** - * @deprecated - use base selection notification - */ -public interface ICaretListener extends java.util.EventListener { - public void caretMoved(CaretEvent event); -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/view/events/INodeSelectionListener.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/view/events/INodeSelectionListener.java deleted file mode 100644 index 94fd9a6789..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/view/events/INodeSelectionListener.java +++ /dev/null @@ -1,22 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.view.events; - - -/** - * @deprecated - use base selection notification - */ - -public interface INodeSelectionListener { - void nodeSelectionChanged(NodeSelectionChangedEvent event); -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/view/events/ITextSelectionListener.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/view/events/ITextSelectionListener.java deleted file mode 100644 index f241bfb687..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/view/events/ITextSelectionListener.java +++ /dev/null @@ -1,20 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.view.events; - -/** - * @deprecated - use base selection notification - */ -public interface ITextSelectionListener { - void textSelectionChanged(TextSelectionChangedEvent event); -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/view/events/NodeSelectionChangedEvent.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/view/events/NodeSelectionChangedEvent.java deleted file mode 100644 index 579d753baa..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/view/events/NodeSelectionChangedEvent.java +++ /dev/null @@ -1,43 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.view.events; - -import java.util.List; - -/** - * @deprecated - use base selection notification - */ -public class NodeSelectionChangedEvent extends java.util.EventObject { - /** - * Comment for <code>serialVersionUID</code> - */ - private static final long serialVersionUID = 1L; - - int fCaretPosition; - - List fSelectedNodes; - - public NodeSelectionChangedEvent(Object source, List selectedNodes, int caretPosition) { - super(source); - fSelectedNodes = selectedNodes; - fCaretPosition = caretPosition; - } - - public int getCaretPosition() { - return fCaretPosition; - } - - public List getSelectedNodes() { - return fSelectedNodes; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/view/events/TextSelectionChangedEvent.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/view/events/TextSelectionChangedEvent.java deleted file mode 100644 index d7807e5cca..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/view/events/TextSelectionChangedEvent.java +++ /dev/null @@ -1,41 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.view.events; - -/** - * @deprecated - use base selection notification - */ -public class TextSelectionChangedEvent extends java.util.EventObject { - /** - * Comment for <code>serialVersionUID</code> - */ - private static final long serialVersionUID = 1L; - - int fTextSelectionEnd; - - int fTextSelectionStart; - - public TextSelectionChangedEvent(Object source, int textSelectionStart, int textSelectionEnd) { - super(source); - fTextSelectionStart = textSelectionStart; - fTextSelectionEnd = textSelectionEnd; - } - - public int getTextSelectionEnd() { - return fTextSelectionEnd; - } - - public int getTextSelectionStart() { - return fTextSelectionStart; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/preferences/AbstractCompletionProposalCategoriesConfiguration.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/preferences/AbstractCompletionProposalCategoriesConfiguration.java deleted file mode 100644 index b6c171f8db..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/preferences/AbstractCompletionProposalCategoriesConfiguration.java +++ /dev/null @@ -1,392 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.preferences; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.wst.sse.ui.internal.contentassist.CompletionProposalCategory; - -import com.ibm.icu.util.StringTokenizer; - -/** - * <p>Implements a completion proposal categories configuration - * reader and writer using an {@link IPreferenceStore}</p> - * - * <p>This class is meant to be subclasses by implementers of the - * <code>org.eclipse.wst.sse.ui.completionProposalCategoriesConfiguration</code> - * extension point as a convince rather then implementing - * {@link ICompletionProposalCategoriesConfigurationReader} and - * {@link ICompletionProposalCategoriesConfigurationWriter} from scratch.</p> - */ -public abstract class AbstractCompletionProposalCategoriesConfiguration - implements ICompletionProposalCategoriesConfigurationReader, - ICompletionProposalCategoriesConfigurationWriter { - - /** Separator used between preferences stored in the same key */ - private static final String PREFERENCE_CATEGORY_SEPERATOR = "\0"; //$NON-NLS-1$ - - /** - * <p>{@link CompletionProposalCategory} IDs sorted by the order they should - * be listed on the default page if they are being displayed there</p> - * - * <code>{@link List}<{@link String}></code> - * <ul><li><b>values:</b> {@link CompletionProposalCategory} IDs</li></ul> - */ - private List fDefaultPageSortOrder; - - /** - * <p>{@link CompletionProposalCategory} IDs sorted by the order they should - * be cycled through</p> - * - * <code>{@link List}<{@link String}></code> - * <ul><li><b>values:</b> {@link CompletionProposalCategory} IDs</li></ul> - */ - private List fOwnPageSortOrder; - - /** - * <p>{@link CompletionProposalCategory} IDs that should not be displayed on - * their own page</p> - * - * <code>{@link Set}<{@link String}></code> - * <ul><li><b>values:</b> {@link CompletionProposalCategory} IDs</li></ul> - */ - private Set fShouldNotDisplayOnOwnPage; - - /** - * <p>{@link CompletionProposalCategory} IDs that should not be displayed on - * on the default page</p> - * - * <code>{@link Set}<{@link String}></code> - * <ul><li><b>values:</b> {@link CompletionProposalCategory} IDs</li></ul> - */ - private Set fShouldNotDisplayOnDefaultPage; - - /** - * <p>Create a new configuration by loading from the associated {@link IPreferenceStore}</p> - */ - public AbstractCompletionProposalCategoriesConfiguration() { - this.fOwnPageSortOrder = new ArrayList(); - this.fDefaultPageSortOrder = new ArrayList(); - this.fShouldNotDisplayOnOwnPage = new HashSet(); - this.fShouldNotDisplayOnDefaultPage = new HashSet(); - - this.loadUserConfiguration(); - } - - /** - * @return {@link IPreferenceStore} to read and write the configuration to and from - */ - protected abstract IPreferenceStore getPreferenceStore(); - - /** - * @return Preference key to use in the {@link IPreferenceStore} for the category sort order - * when cycling through the pages - */ - protected abstract String getPageSortOrderPrefKey(); - - /** - * @return Preference key to use in the {@link IPreferenceStore} for the category sort order - * on the default page - */ - protected abstract String getDefaultPageSortOrderPrefKey(); - - /** - * @return Preference key to use in the {@link IPreferenceStore} for which - * categories not to display on their own page - */ - protected abstract String getShouldNotDisplayOnOwnPagePrefKey(); - - /** - * @return Preference key to use in the {@link IPreferenceStore} for which - * categories not to display on the default page - */ - protected abstract String getShouldNotDisplayOnDefaultPagePrefKey(); - - /** - * @see org.eclipse.wst.sse.ui.preferences.ICompletionProposalCategoriesConfigurationReader#getPageSortOrder(java.lang.String) - */ - public int getPageSortOrder(String categoryID) { - int sortOrder = this.fOwnPageSortOrder.indexOf(categoryID); - if(sortOrder == -1) { - sortOrder = DEFAULT_SORT_ORDER; - } - - return sortOrder; - } - - /** - * @see org.eclipse.wst.sse.ui.preferences.ICompletionProposalCategoriesConfigurationReader#getDefaultPageSortOrder(java.lang.String) - */ - public int getDefaultPageSortOrder(String categoryID) { - int sortOrder = this.fDefaultPageSortOrder.indexOf(categoryID); - if(sortOrder == -1) { - sortOrder = DEFAULT_SORT_ORDER; - } - - return sortOrder; - } - - /** - * @see org.eclipse.wst.sse.ui.preferences.ICompletionProposalCategoriesConfigurationReader#shouldDisplayOnDefaultPage(java.lang.String) - */ - public boolean shouldDisplayOnDefaultPage(String categoryID) { - return !fShouldNotDisplayOnDefaultPage.contains(categoryID); - } - - /** - * @see org.eclipse.wst.sse.ui.preferences.ICompletionProposalCategoriesConfigurationReader#shouldDisplayOnOwnPage(java.lang.String) - */ - public boolean shouldDisplayOnOwnPage(String categoryID) { - return !this.fShouldNotDisplayOnOwnPage.contains(categoryID); - } - - /** - * <p> Loads defaults from the associated {@link IPreferenceStore}</p> - * @see org.eclipse.wst.sse.ui.preferences.ICompletionProposalCategoriesConfigurationWriter#loadDefaults() - */ - public void loadDefaults() { - this.loadDefaultPagePreference(true); - this.loadPageSortOrder(true); - this.loadDefaultPageSortOrder(true); - this.loadShouldNotDisplayOnOwnPage(true); - } - - /** - * <p>Saves to the associated {@link IPreferenceStore}</p> - * - * @see org.eclipse.wst.sse.ui.preferences.ICompletionProposalCategoriesConfigurationWriter#saveConfiguration() - */ - public boolean saveConfiguration() { - this.saveShouldDisplayOnDefaultPageConfiguration(); - this.saveShouldDisplayOnOwnPageConfiguration(); - this.saveDefaultPageSortOrderConfiguration(); - this.savePageSortOrderConfiguration(); - - return true; - } - - /** - * @see org.eclipse.wst.sse.ui.preferences.ICompletionProposalCategoriesConfigurationWriter#setShouldDisplayOnDefaultPage(java.lang.String, boolean) - */ - public void setShouldDisplayOnDefaultPage(String categoryID, - boolean shouldDisplay) { - - if(shouldDisplay) { - this.fShouldNotDisplayOnDefaultPage.remove(categoryID); - } else { - this.fShouldNotDisplayOnDefaultPage.add(categoryID); - } - } - - /** - * @see org.eclipse.wst.sse.ui.preferences.ICompletionProposalCategoriesConfigurationWriter#setShouldDisplayOnOwnPage(java.lang.String, boolean) - */ - public void setShouldDisplayOnOwnPage(String categoryID, boolean shouldDisplay) { - - if(shouldDisplay) { - this.fShouldNotDisplayOnOwnPage.remove(categoryID); - } else { - this.fShouldNotDisplayOnOwnPage.add(categoryID); - } - } - - /** - * @see org.eclipse.wst.sse.ui.preferences.ICompletionProposalCategoriesConfigurationWriter#setPageOrder(java.util.List) - */ - public void setPageOrder(List order) { - this.fOwnPageSortOrder = order; - } - - /** - * @see org.eclipse.wst.sse.ui.preferences.ICompletionProposalCategoriesConfigurationWriter#setDefaultPageOrder(java.util.List) - */ - public void setDefaultPageOrder(List order) { - this.fDefaultPageSortOrder = order; - } - - /** - * <p>Loads the user configuration from the associated {@link IPreferenceStore}</p> - */ - private void loadUserConfiguration() { - this.loadDefaultPagePreference(false); - this.loadPageSortOrder(false); - this.loadDefaultPageSortOrder(false); - this.loadShouldNotDisplayOnOwnPage(false); - } - - /** - * <p>Loads the user preferences for which categories to - * display on the default content assist page</p> - * - * @param useDefaults if <code>true</code> then use the {@link IPreferenceStore} defaults, - * otherwise use the user specified preferences - */ - private void loadDefaultPagePreference(boolean useDefaults) { - //clear the current display on default page configuration - this.fShouldNotDisplayOnDefaultPage.clear(); - - //parse either the default or user configuration preference - String displayOnDefaultPage; - if(useDefaults) { - displayOnDefaultPage = getPreferenceStore().getDefaultString(getShouldNotDisplayOnDefaultPagePrefKey()); - } else { - displayOnDefaultPage = getPreferenceStore().getString(getShouldNotDisplayOnDefaultPagePrefKey()); - } - StringTokenizer defaultPageTokenizer = new StringTokenizer(displayOnDefaultPage, PREFERENCE_CATEGORY_SEPERATOR); - while (defaultPageTokenizer.hasMoreTokens()) { - fShouldNotDisplayOnDefaultPage.add(defaultPageTokenizer.nextToken()); - } - } - - /** - * <p>Loads the user preferences for the sort order of the content assist pages</p> - * - * @param useDefaults if <code>true</code> then use the {@link IPreferenceStore} defaults, - * otherwise use the user specified preferences - */ - private void loadPageSortOrder(boolean useDefaults){ - //clear the current sort order - this.fOwnPageSortOrder.clear(); - - //parse either the default or user configuration preference - String sortOrder; - if(useDefaults) { - sortOrder = getPreferenceStore().getDefaultString(getPageSortOrderPrefKey()); - } else { - sortOrder = getPreferenceStore().getString(getPageSortOrderPrefKey()); - } - StringTokenizer tokenizer = new StringTokenizer(sortOrder, PREFERENCE_CATEGORY_SEPERATOR); - while (tokenizer.hasMoreTokens()) { - String categoryID = tokenizer.nextToken(); - this.fOwnPageSortOrder.add(categoryID); - } - } - - /** - * <p>Loads the user preferences for the sort order of the content assist pages</p> - * - * @param useDefaults if <code>true</code> then use the {@link IPreferenceStore} defaults, - * otherwise use the user specified preferences - */ - private void loadDefaultPageSortOrder(boolean useDefaults){ - //clear the current sort order - this.fDefaultPageSortOrder.clear(); - - //parse either the default or user configuration preference - String sortOrder; - if(useDefaults) { - sortOrder = getPreferenceStore().getDefaultString(getDefaultPageSortOrderPrefKey()); - } else { - sortOrder = getPreferenceStore().getString(getDefaultPageSortOrderPrefKey()); - } - StringTokenizer tokenizer = new StringTokenizer(sortOrder, PREFERENCE_CATEGORY_SEPERATOR); - while (tokenizer.hasMoreTokens()) { - String categoryID = tokenizer.nextToken(); - this.fDefaultPageSortOrder.add(categoryID); - } - } - - /** - * <p>Loads the user preferences for which categories should not be displayed on their own - * content assist page</p> - * - * @param useDefaults if <code>true</code> then use the {@link IPreferenceStore} defaults, - * otherwise use the user specified preferences - */ - private void loadShouldNotDisplayOnOwnPage(boolean useDefaults){ - //clear the current sort order - this.fShouldNotDisplayOnOwnPage.clear(); - - //parse either the default or user configuration preference - String preference; - if(useDefaults) { - preference = getPreferenceStore().getDefaultString(getShouldNotDisplayOnOwnPagePrefKey()); - } else { - preference = getPreferenceStore().getString(getShouldNotDisplayOnOwnPagePrefKey()); - } - StringTokenizer tokenizer = new StringTokenizer(preference, PREFERENCE_CATEGORY_SEPERATOR); - while (tokenizer.hasMoreTokens()) { - String categoryID = tokenizer.nextToken(); - this.fShouldNotDisplayOnOwnPage.add(categoryID); - } - } - - /** - * <p>Saves the user preferences for which categories to - * display on the default content assist page</p> - */ - private void saveShouldDisplayOnDefaultPageConfiguration() { - //create the preference string - StringBuffer defaultPageBuff = new StringBuffer(); - Iterator defaultPageIter = this.fShouldNotDisplayOnDefaultPage.iterator(); - while(defaultPageIter.hasNext()) { - String categoryID = (String)defaultPageIter.next(); - defaultPageBuff.append(categoryID + PREFERENCE_CATEGORY_SEPERATOR); - } - - //save the preference - this.getPreferenceStore().setValue(this.getShouldNotDisplayOnDefaultPagePrefKey(), defaultPageBuff.toString()); - } - - /** - * <p>Saves the user preferences for the sort order of the content assist pages</p> - */ - private void savePageSortOrderConfiguration() { - //create the preference string - StringBuffer orderBuff = new StringBuffer(); - for(int i = 0; i < this.fOwnPageSortOrder.size(); ++i) { - if(this.fOwnPageSortOrder.get(i) != null) { - orderBuff.append(this.fOwnPageSortOrder.get(i) + PREFERENCE_CATEGORY_SEPERATOR); - } - } - - //save the preference - this.getPreferenceStore().setValue(this.getPageSortOrderPrefKey(), orderBuff.toString()); - } - - /** - * <p>Saves the user preferences for the sort order of the categories on the default page</p> - */ - private void saveDefaultPageSortOrderConfiguration() { - //create the preference string - StringBuffer orderBuff = new StringBuffer(); - for(int i = 0; i < this.fDefaultPageSortOrder.size(); ++i) { - if(this.fDefaultPageSortOrder.get(i) != null) { - orderBuff.append(this.fDefaultPageSortOrder.get(i) + PREFERENCE_CATEGORY_SEPERATOR); - } - } - - //save the preference - this.getPreferenceStore().setValue(this.getDefaultPageSortOrderPrefKey(), orderBuff.toString()); - } - - /** - * <p>Saves the user preferences for which categories should not be displayed on their own - * content assist page</p> - */ - private void saveShouldDisplayOnOwnPageConfiguration() { - //create the preference string - StringBuffer buff = new StringBuffer(); - Iterator iter = this.fShouldNotDisplayOnOwnPage.iterator(); - while(iter.hasNext()) { - String categoryID = (String)iter.next(); - buff.append(categoryID + PREFERENCE_CATEGORY_SEPERATOR); - } - - //save the preference - this.getPreferenceStore().setValue(this.getShouldNotDisplayOnOwnPagePrefKey(), buff.toString()); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/preferences/CodeAssistCyclingConfigurationBlock.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/preferences/CodeAssistCyclingConfigurationBlock.java deleted file mode 100644 index e1cfeadda0..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/preferences/CodeAssistCyclingConfigurationBlock.java +++ /dev/null @@ -1,891 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.preferences; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.eclipse.core.commands.Command; -import org.eclipse.core.commands.CommandManager; -import org.eclipse.core.commands.ParameterizedCommand; -import org.eclipse.core.commands.common.NotDefinedException; -import org.eclipse.core.commands.contexts.ContextManager; -import org.eclipse.core.runtime.Assert; -import org.eclipse.jface.bindings.BindingManager; -import org.eclipse.jface.bindings.Scheme; -import org.eclipse.jface.bindings.TriggerSequence; -import org.eclipse.jface.layout.PixelConverter; -import org.eclipse.jface.resource.ImageDescriptor; -import org.eclipse.jface.resource.JFaceResources; -import org.eclipse.jface.viewers.ArrayContentProvider; -import org.eclipse.jface.viewers.CheckStateChangedEvent; -import org.eclipse.jface.viewers.CheckboxTableViewer; -import org.eclipse.jface.viewers.ICheckStateListener; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.viewers.ITableLabelProvider; -import org.eclipse.jface.viewers.LabelProvider; -import org.eclipse.jface.viewers.Viewer; -import org.eclipse.jface.viewers.ViewerComparator; -import org.eclipse.osgi.util.NLS; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.graphics.GC; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Group; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.Table; -import org.eclipse.swt.widgets.TableColumn; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.commands.ICommandService; -import org.eclipse.ui.keys.IBindingService; -import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds; -import org.eclipse.wst.sse.ui.internal.Logger; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; -import org.eclipse.wst.sse.ui.internal.contentassist.CompletionProposalCategory; -import org.eclipse.wst.sse.ui.internal.contentassist.CompletionProposalComputerRegistry; -import org.eclipse.wst.sse.ui.internal.util.SWTUtil; - - -/** - * <p>A helpful preference configuration block implementation for allowing a user to - * set their preferences for which content assist categories to show on the default - * content assist page as well as on their own separate page and page ordering for - * a specific content type</p> - * - * @base org.eclipse.jdt.internal.ui.preferences.CodeAssistAdvancedConfigurationBlock - */ -public final class CodeAssistCyclingConfigurationBlock { - - /** - * <p>Used to compare categories based on their assigned page rank</p> - */ - private final Comparator fCategoryPageComparator = new Comparator() { - private int getRank(Object o) { - return ((ModelElement) o).getOwnPageRank(); - } - - public int compare(Object o1, Object o2) { - int result = getRank(o1) - getRank(o2); - if(result == 0) { - result = ((ModelElement) o1).getId().compareTo(((ModelElement) o2).getId()); - } - return result; - } - }; - - /** - * <p>Used to compare categories based on their assigned default page rank</p> - */ - private final Comparator fCategoryDefaultPageComparator = new Comparator() { - private int getRank(Object o) { - return ((ModelElement) o).getDefaultPageRank(); - } - - public int compare(Object o1, Object o2) { - int result = getRank(o1) - getRank(o2); - if(result == 0) { - result = ((ModelElement) o1).getId().compareTo(((ModelElement) o2).getId()); - } - return result; - } - }; - - /** the preference model for this block */ - private final PreferenceModel fModel; - - /** - * <code>{@link Map}<{@link ImageDescriptor}, {@link Image}></code> - */ - private final Map fImages= new HashMap(); - - /** table viewer to configure which categories are displayed on the default page */ - private CheckboxTableViewer fDefaultPageViewer; - - /** - * table viewer to configure which categories are displayed - * on their own page, as well as their ordering - */ - private CheckboxTableViewer fOwnPageViewer; - - /** categories pages sort order up button */ - private Button fPageOrderUpButton; - - /** categories pages sort order down button */ - private Button fPageOrderDownButton; - - /** categories default page sort order up button */ - private Button fDefaultPageOrderUpButton; - - /** categories default page sort order down button */ - private Button fDefaultPageOrderDownButton; - - /** The content type ID this configuration block is for */ - private String fContentTypeID; - - /** The writable categories configuration */ - private ICompletionProposalCategoriesConfigurationWriter fConfigurationWriter; - - /** - * <p>Creates a new content assist preference block for the given content type - * using the given configuration writer</p> - * - * @param contentTypeID content type this content assist preference block is for - * @param configurationWriter {@link ICompletionProposalCategoriesConfigurationWriter} used - * to read and write the user preferences - */ - public CodeAssistCyclingConfigurationBlock(String contentTypeID, ICompletionProposalCategoriesConfigurationWriter configurationWriter) { - this.fContentTypeID = contentTypeID; - this.fConfigurationWriter = configurationWriter; - - List categories = CompletionProposalComputerRegistry.getDefault().getProposalCategories(this.fContentTypeID); - this.fModel = new PreferenceModel(categories); - } - - /** - * <p>Saves the user configuration</p> - * @return <code>true</code> if store was successful, <code>false</code> otherwise - */ - public boolean storeValues() { - return this.fConfigurationWriter.saveConfiguration(); - } - - /** - * <p>Loads the preference defaults</p> - */ - public void performDefaults() { - this.fConfigurationWriter.loadDefaults(); - this.initializeValues(); - this.fModel.performDefaults(); - } - - /** - * <p>Disposes of this preference block</p> - */ - public void dispose() { - for (Iterator it= fImages.values().iterator(); it.hasNext();) { - Image image= (Image) it.next(); - image.dispose(); - } - } - - /** - * <p>Creates the contents of this configuration block using a {@link Group} if - * the given <code>groupTitle</code> is not <code>null</code> else creates it - * as a composite and in either case adds itself to the given parent</p> - * - * @param parent {@link Composite} parent to add this configuration block to - * @param groupTitle Title to use for the configuration block group, if - * <code>null</code> then a {@link Composite} will be used instead of a - * {@link Group} - * - * @return the created configuration block that has already been added to the parent - */ - public Control createContents(Composite parent, String groupTitle) { - Composite container; - if(groupTitle != null) { - container = new Group(parent, SWT.NULL); - ((Group)container).setText(groupTitle); - } else { - container = new Composite(parent, SWT.NULL); - } - int columns= 2; - GridLayout layout= new GridLayout(columns, false); - container.setLayout(layout); - - GridData data = new GridData(GridData.FILL); - data.horizontalIndent = 0; - data.verticalAlignment = GridData.FILL; - data.horizontalAlignment = GridData.FILL; - data.grabExcessHorizontalSpace = true; - container.setLayoutData(data); - - createDefaultPageLabel(container, columns); - createDefaultPageSection(container); - - createFiller(container, columns); - - createOwnPageLabel(container, columns); - createOwnPageSection(container); - - createFiller(container, columns); - - if (fModel.pageElements.size() > 0) { - fDefaultPageViewer.getTable().select(0); - fOwnPageViewer.getTable().select(0); - handleOwnPageTableSelection(); - handleDefaultPageTableSelection(); - } - - return container; - } - - /** - * <p>Initialize the values of the configuration block</p> - */ - public void initializeValues() { - updateCheckedState(); - fDefaultPageViewer.refresh(); - fOwnPageViewer.refresh(); - handleOwnPageTableSelection(); - handleDefaultPageTableSelection(); - } - - private void createDefaultPageSection(Composite composite) { - createDefaultPageViewer(composite); - createDefaultPageButtonList(composite); - } - - private void createDefaultPageLabel(Composite composite, int h_span) { - final ICommandService commandSvc= (ICommandService) PlatformUI.getWorkbench().getAdapter(ICommandService.class); - final Command command= commandSvc.getCommand(ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS); - ParameterizedCommand pCmd= new ParameterizedCommand(command, null); - String key= getKeyboardShortcut(pCmd); - if (key == null) { - key= SSEUIMessages.CodeAssistAdvancedConfigurationBlock_no_shortcut; - } - - PixelConverter pixelConverter= new PixelConverter(composite); - int width= pixelConverter.convertWidthInCharsToPixels(40); - - Label label= new Label(composite, SWT.NONE | SWT.WRAP); - label.setText(NLS.bind(SSEUIMessages.CodeAssistAdvancedConfigurationBlock_page_description, new Object[] { key })); - GridData gd= new GridData(GridData.FILL, GridData.FILL, true, false, h_span, 1); - gd.widthHint= width; - label.setLayoutData(gd); - - createFiller(composite, h_span); - - label= new Label(composite, SWT.NONE | SWT.WRAP); - label.setText(SSEUIMessages.CodeAssistAdvancedConfigurationBlock_default_table_description); - gd= new GridData(GridData.FILL, GridData.FILL, true, false, h_span, 1); - gd.widthHint= width; - label.setLayoutData(gd); - } - - private void createDefaultPageViewer(Composite composite) { - fDefaultPageViewer= CheckboxTableViewer.newCheckList(composite, SWT.SINGLE | SWT.BORDER); - Table table= fDefaultPageViewer.getTable(); - table.setHeaderVisible(true); - table.setLinesVisible(false); - table.setLayoutData(new GridData(GridData.FILL, GridData.BEGINNING, false, false, 1, 1)); - - TableColumn nameColumn= new TableColumn(table, SWT.NONE); - nameColumn.setText(SSEUIMessages.CodeAssistAdvancedConfigurationBlock_default_table_category_column_title); - nameColumn.setResizable(false); - - fDefaultPageViewer.addCheckStateListener(new ICheckStateListener() { - public void checkStateChanged(CheckStateChangedEvent event) { - boolean checked= event.getChecked(); - ModelElement element= (ModelElement) event.getElement(); - element.setShouldDisplayOnDefaultPage(checked); - } - }); - - fDefaultPageViewer.setContentProvider(new ArrayContentProvider()); - - DefaultPageTableLabelProvider labelProvider= new DefaultPageTableLabelProvider(); - fDefaultPageViewer.setLabelProvider(labelProvider); - fDefaultPageViewer.setInput(fModel.defaultPageElements); - fDefaultPageViewer.setComparator(new ModelViewerComparator(fCategoryDefaultPageComparator)); - - final int ICON_AND_CHECKBOX_WITH= 50; - final int HEADER_MARGIN= 20; - int minNameWidth= computeWidth(table, nameColumn.getText()) + HEADER_MARGIN; - for (int i= 0; i < fModel.defaultPageElements.size(); i++) { - minNameWidth= Math.max(minNameWidth, computeWidth(table, labelProvider.getColumnText(fModel.defaultPageElements.get(i), 0)) + ICON_AND_CHECKBOX_WITH); - } - - nameColumn.setWidth(minNameWidth); - - table.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent e) { - handleDefaultPageTableSelection(); - } - }); - } - - /** - * <p>Create the Up and Down buttons for the default page viewer</p> - * @param parent {@link Composite} to add the button list to - */ - private void createDefaultPageButtonList(Composite parent) { - Composite composite= new Composite(parent, SWT.NONE); - composite.setLayoutData(new GridData(SWT.BEGINNING, SWT.BEGINNING, false, false)); - - GridLayout layout= new GridLayout(); - layout.marginWidth= 0; - layout.marginHeight= 0; - composite.setLayout(layout); - - fDefaultPageOrderUpButton= new Button(composite, SWT.PUSH | SWT.CENTER); - fDefaultPageOrderUpButton.setText(SSEUIMessages.CodeAssistAdvancedConfigurationBlock_Up); - fDefaultPageOrderUpButton.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent e) { - int index = fDefaultPageViewer.getTable().getSelectionIndex(); - if (index != -1) { - fModel.moveDefaultPageCategoryUp(index); - fDefaultPageViewer.refresh(); - handleDefaultPageTableSelection(); - } - } - }); - fDefaultPageOrderUpButton.setLayoutData(new GridData()); - - SWTUtil.setButtonDimensionHint(fDefaultPageOrderUpButton); - - fDefaultPageOrderDownButton= new Button(composite, SWT.PUSH | SWT.CENTER); - fDefaultPageOrderDownButton.setText(SSEUIMessages.CodeAssistAdvancedConfigurationBlock_Down); - fDefaultPageOrderDownButton.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent e) { - int index= fDefaultPageViewer.getTable().getSelectionIndex(); - if (index != -1) { - fModel.moveDefaultPageCategoryDown(index); - fDefaultPageViewer.refresh(); - handleDefaultPageTableSelection(); - } - } - }); - fDefaultPageOrderDownButton.setLayoutData(new GridData()); - SWTUtil.setButtonDimensionHint(fDefaultPageOrderDownButton); - } - - private void createFiller(Composite composite, int h_span) { - Label filler= new Label(composite, SWT.NONE); - filler.setVisible(false); - filler.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, h_span, 1)); - } - - private void createOwnPageLabel(Composite composite, int h_span) { - PixelConverter pixelConverter= new PixelConverter(composite); - int width= pixelConverter.convertWidthInCharsToPixels(40); - - Label label= new Label(composite, SWT.NONE | SWT.WRAP); - label.setText(SSEUIMessages.CodeAssistAdvancedConfigurationBlock_separate_table_description); - GridData gd= new GridData(GridData.FILL, GridData.FILL, false, false, h_span, 1); - gd.widthHint= width; - label.setLayoutData(gd); - } - - private void createOwnPageSection(Composite composite) { - createOwnPageViewer(composite); - createOwnPageButtonList(composite); - } - - private void createOwnPageViewer(Composite composite) { - fOwnPageViewer= CheckboxTableViewer.newCheckList(composite, SWT.SINGLE | SWT.BORDER); - Table table= fOwnPageViewer.getTable(); - table.setHeaderVisible(true); - table.setLinesVisible(false); - table.setLayoutData(new GridData(GridData.FILL, GridData.BEGINNING, true, false, 1, 1)); - - TableColumn nameColumn= new TableColumn(table, SWT.NONE); - nameColumn.setText(SSEUIMessages.CodeAssistAdvancedConfigurationBlock_separate_table_category_column_title); - nameColumn.setResizable(false); - - fOwnPageViewer.setContentProvider(new ArrayContentProvider()); - - ITableLabelProvider labelProvider= new OwnPageTableLabelProvider(); - fOwnPageViewer.setLabelProvider(labelProvider); - fOwnPageViewer.setInput(fModel.pageElements); - fOwnPageViewer.setComparator(new ModelViewerComparator(fCategoryPageComparator)); - - final int ICON_AND_CHECKBOX_WITH= 50; - final int HEADER_MARGIN= 20; - int minNameWidth= computeWidth(table, nameColumn.getText()) + HEADER_MARGIN; - for (int i= 0; i < fModel.pageElements.size(); i++) { - minNameWidth= Math.max(minNameWidth, computeWidth(table, labelProvider.getColumnText(fModel.pageElements.get(i), 0)) + ICON_AND_CHECKBOX_WITH); - } - - nameColumn.setWidth(minNameWidth); - - fOwnPageViewer.addCheckStateListener(new ICheckStateListener() { - public void checkStateChanged(CheckStateChangedEvent event) { - boolean checked= event.getChecked(); - ModelElement element= (ModelElement) event.getElement(); - element.setShouldDisplayOnOwnPage(checked); - } - }); - - table.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent e) { - handleOwnPageTableSelection(); - } - }); - - } - - /** - * <p>Create the Up and Down buttons for the own page viewer</p> - * @param parent {@link Composite} to add the button list to - */ - private void createOwnPageButtonList(Composite parent) { - Composite composite= new Composite(parent, SWT.NONE); - composite.setLayoutData(new GridData(SWT.BEGINNING, SWT.BEGINNING, false, false)); - - GridLayout layout= new GridLayout(); - layout.marginWidth= 0; - layout.marginHeight= 0; - composite.setLayout(layout); - - fPageOrderUpButton= new Button(composite, SWT.PUSH | SWT.CENTER); - fPageOrderUpButton.setText(SSEUIMessages.CodeAssistAdvancedConfigurationBlock_PagesUp); - fPageOrderUpButton.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent e) { - int index = fOwnPageViewer.getTable().getSelectionIndex(); - if (index != -1) { - fModel.movePageUp(index); - fOwnPageViewer.refresh(); - handleOwnPageTableSelection(); - } - } - }); - fPageOrderUpButton.setLayoutData(new GridData()); - - SWTUtil.setButtonDimensionHint(fPageOrderUpButton); - - fPageOrderDownButton= new Button(composite, SWT.PUSH | SWT.CENTER); - fPageOrderDownButton.setText(SSEUIMessages.CodeAssistAdvancedConfigurationBlock_PagesDown); - fPageOrderDownButton.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent e) { - int index= fOwnPageViewer.getTable().getSelectionIndex(); - if (index != -1) { - fModel.movePageDown(index); - fOwnPageViewer.refresh(); - handleOwnPageTableSelection(); - } - } - }); - fPageOrderDownButton.setLayoutData(new GridData()); - SWTUtil.setButtonDimensionHint(fPageOrderDownButton); - } - - /** - * <p>Update the enablement of the Up and Down buttons for the own page table viewer</p> - */ - private void handleOwnPageTableSelection() { - ModelElement item= (ModelElement) ((IStructuredSelection) fOwnPageViewer.getSelection()).getFirstElement(); - if (item != null) { - int index= fOwnPageViewer.getTable().getSelectionIndex(); - fPageOrderUpButton.setEnabled(index > 0); - fPageOrderDownButton.setEnabled(index < fModel.pageElements.size() - 1); - } else { - fPageOrderUpButton.setEnabled(false); - fPageOrderDownButton.setEnabled(false); - } - } - - /** - * <p>Update the enablement of the Up and Down buttons for the default page table viewer</p> - */ - private void handleDefaultPageTableSelection() { - ModelElement item= (ModelElement) ((IStructuredSelection) fDefaultPageViewer.getSelection()).getFirstElement(); - if (item != null) { - int index = fDefaultPageViewer.getTable().getSelectionIndex(); - fDefaultPageOrderUpButton.setEnabled(index > 0); - fDefaultPageOrderDownButton.setEnabled(index < fModel.defaultPageElements.size() - 1); - } else { - fDefaultPageOrderUpButton.setEnabled(false); - fDefaultPageOrderDownButton.setEnabled(false); - } - } - - private void updateCheckedState() { - /* does not matter which set of elements we use here - * because order does not matter in this case - */ - final int size= fModel.pageElements.size(); - List defaultChecked= new ArrayList(size); - List separateChecked= new ArrayList(size); - - for (Iterator it= fModel.pageElements.iterator(); it.hasNext();) { - ModelElement element= (ModelElement) it.next(); - if (element.shouldDisplayOnDefaultPage()) - defaultChecked.add(element); - if (element.shouldDisplayOnOwnPage()) - separateChecked.add(element); - } - - fDefaultPageViewer.setCheckedElements(defaultChecked.toArray(new Object[defaultChecked.size()])); - fOwnPageViewer.setCheckedElements(separateChecked.toArray(new Object[separateChecked.size()])); - } - - private int computeWidth(Control control, String name) { - if (name == null) - return 0; - GC gc= new GC(control); - try { - gc.setFont(JFaceResources.getDialogFont()); - return gc.stringExtent(name).x + 10; - } finally { - gc.dispose(); - } - } - - private static BindingManager fgLocalBindingManager; - static { - fgLocalBindingManager= new BindingManager(new ContextManager(), new CommandManager()); - final IBindingService bindingService= (IBindingService)PlatformUI.getWorkbench().getService(IBindingService.class); - final Scheme[] definedSchemes= bindingService.getDefinedSchemes(); - if (definedSchemes != null) { - try { - for (int i = 0; i < definedSchemes.length; i++) { - final Scheme scheme= definedSchemes[i]; - final Scheme copy= fgLocalBindingManager.getScheme(scheme.getId()); - copy.define(scheme.getName(), scheme.getDescription(), scheme.getParentId()); - } - } catch (final NotDefinedException e) { - Logger.logException(e); - } - } - fgLocalBindingManager.setLocale(bindingService.getLocale()); - fgLocalBindingManager.setPlatform(bindingService.getPlatform()); - } - - private static String getKeyboardShortcut(ParameterizedCommand command) { - IBindingService bindingService= (IBindingService) PlatformUI.getWorkbench().getAdapter(IBindingService.class); - fgLocalBindingManager.setBindings(bindingService.getBindings()); - try { - Scheme activeScheme= bindingService.getActiveScheme(); - if (activeScheme != null) - fgLocalBindingManager.setActiveScheme(activeScheme); - } catch (NotDefinedException e) { - Logger.logException(e); - } - - TriggerSequence[] bindings= fgLocalBindingManager.getActiveBindingsDisregardingContextFor(command); - if (bindings.length > 0) - return bindings[0].format(); - return null; - } - - /** - * <p>Gets and image based on an image descriptor, and stores the image so it - * does not have to be created more then once</p> - * - * @param imgDesc {@link ImageDescriptor} to get the {@link Image} for - * @return {@link Image} created from the {@link ImageDescriptor}, or stored - * {@link Image} associated with the given {@link ImageDescriptor} if an - * {@link Image} had already been created for the given {@link ImageDescriptor} - */ - private Image getImage(ImageDescriptor imgDesc) { - if (imgDesc == null) - return null; - - Image img= (Image) fImages.get(imgDesc); - if (img == null) { - img= imgDesc.createImage(false); - fImages.put(imgDesc, img); - } - return img; - } - - /** - * <p>Label provider for the table for configuring which categories should be displayed on the - * default assist page</p> - */ - private final class DefaultPageTableLabelProvider extends LabelProvider implements ITableLabelProvider { - /** - * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnImage(java.lang.Object, int) - */ - public Image getColumnImage(Object element, int columnIndex) { - if (columnIndex == 0) - return ((ModelElement) element).getImage(); - return null; - } - - /** - * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnText(java.lang.Object, int) - */ - public String getColumnText(Object element, int columnIndex) { - switch (columnIndex) { - case 0: - return ((ModelElement) element).getName(); - default: - Assert.isTrue(false); - return null; - } - } - - /** - * @see org.eclipse.jface.viewers.LabelProvider#getText(java.lang.Object) - */ - public String getText(Object element) { - return getColumnText(element, 0); // needed to make the sorter work - } - } - - /** - * <p>Label provider for the table for configuring which categories should be displayed on their - * own content assist page</p> - */ - private final class OwnPageTableLabelProvider extends LabelProvider implements ITableLabelProvider { - /** - * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnImage(java.lang.Object, int) - */ - public Image getColumnImage(Object element, int columnIndex) { - if (columnIndex == 0) - return ((ModelElement) element).getImage(); - return null; - } - - /** - * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnText(java.lang.Object, int) - */ - public String getColumnText(Object element, int columnIndex) { - switch (columnIndex) { - case 0: - return ((ModelElement) element).getName(); - default: - Assert.isTrue(false); - return null; - } - } - } - - /** - * <p>PreferenceModel used to read and write the user preferences - * using the {@link ICompletionProposalCategoriesConfigurationWriter}</p> - */ - private final class PreferenceModel { - /** private modifiable page element list */ - private final List fPageElements; - - /** public unmodifiable page element list */ - final List pageElements; - - /** private modifiable default page element list */ - private final List fDefaultPageElements; - - /** public unmodifiable default page element list */ - final List defaultPageElements; - - /** - * <p>Create the preference model for the given categories</p> - * - * @param categories <code>{@link List}<{@link CompletionProposalCategory}></code> - */ - public PreferenceModel(List categories) { - //need separate lists because they will be ordered differently - this.fPageElements = new ArrayList(); - this.fDefaultPageElements = new ArrayList(); - for (Iterator it= categories.iterator(); it.hasNext();) { - CompletionProposalCategory category= (CompletionProposalCategory) it.next(); - if (category.hasComputers()) { - ModelElement elem = new ModelElement(category); - fPageElements.add(elem); - fDefaultPageElements.add(elem); - } - } - //sort the lists - this.performDefaults(); - - pageElements = Collections.unmodifiableList(fPageElements); - defaultPageElements = Collections.unmodifiableList(fDefaultPageElements); - } - - /** - * <p>Move the model element specified by the given index - * up in the content assist page order</p> - * - * @param elementIndex the index of the model element to move up - */ - public void movePageUp(int elementIndex) { - Object removed = fPageElements.remove(elementIndex); - fPageElements.add(elementIndex-1, removed); - - fConfigurationWriter.setPageOrder(getPageOrderedCategoryIDs()); - } - - /** - * <p>Move the model element specified by the given index - * down in the content assist page order</p> - * - * @param elementIndex the index of the model element to move up - */ - public void movePageDown(int elementIndex) { - Object removed = fPageElements.remove(elementIndex); - fPageElements.add(elementIndex+1, removed); - - fConfigurationWriter.setPageOrder(getPageOrderedCategoryIDs()); - } - - /** - * <p>Move the model element specified by the given index - * up in the content assist page order</p> - * - * @param elementIndex the index of the model element to move up - */ - public void moveDefaultPageCategoryUp(int elementIndex) { - Object removed = fDefaultPageElements.remove(elementIndex); - fDefaultPageElements.add(elementIndex-1, removed); - - fConfigurationWriter.setDefaultPageOrder(getDefaultPageOrderedCategoryIDs()); - } - - /** - * <p>Move the model element specified by the given index - * down in the content assist page order</p> - * - * @param elementIndex the index of the model element to move up - */ - public void moveDefaultPageCategoryDown(int elementIndex) { - Object removed = fDefaultPageElements.remove(elementIndex); - fDefaultPageElements.add(elementIndex+1, removed); - - fConfigurationWriter.setDefaultPageOrder(getDefaultPageOrderedCategoryIDs()); - } - - /** - * @return <code>{@link List}<{@link String}></code> - - * List of category IDs by page order - */ - private List getPageOrderedCategoryIDs() { - List ordered = new ArrayList(pageElements.size()); - for(int i = 0; i < pageElements.size(); ++i) { - ordered.add(((ModelElement)pageElements.get(i)).getId()); - } - - return ordered; - } - - /** - * @return <code>{@link List}<{@link String}></code> - - * List of category IDs by default page order - */ - private List getDefaultPageOrderedCategoryIDs() { - List ordered = new ArrayList(defaultPageElements.size()); - for(int i = 0; i < defaultPageElements.size(); ++i) { - ordered.add(((ModelElement)defaultPageElements.get(i)).getId()); - } - - return ordered; - } - - /** - * <p>need to re-sort the lists after performing defaults</p> - */ - public void performDefaults() { - Collections.sort(fPageElements, fCategoryPageComparator); - Collections.sort(fDefaultPageElements, fCategoryDefaultPageComparator); - } - } - - /** - * <p>Wraps a {@link CompletionProposalCategory} for use in the {@link PreferenceModel}</p> - */ - private final class ModelElement { - /** The wrapped category */ - private final CompletionProposalCategory fCategory; - - /** - * <p>Create a new model element wrapping the given category</p> - * - * @param category {@link CompletionProposalCategory} to be wrapped by this model element - * for use in the {@link PreferenceModel} - */ - ModelElement(CompletionProposalCategory category) { - fCategory= category; - } - - /** - * @return {@link Image} associated with the wrapped category - */ - Image getImage() { - return CodeAssistCyclingConfigurationBlock.this.getImage(fCategory.getImageDescriptor()); - } - - /** - * @return name of the wrapped category - */ - String getName() { - return fCategory.getDisplayName(); - } - - String getId() { - return fCategory.getId(); - } - - /** - * @return <code>true</code> if the wrapped category should be displayed on the - * default content assist page, <code>false</code> otherwise - */ - boolean shouldDisplayOnDefaultPage() { - return fConfigurationWriter.shouldDisplayOnDefaultPage(this.getId()); - } - - /** - * @param included <code>true</code> if the wrapped category should be displayed on the - * default content assist page, <code>false</code> otherwise - */ - void setShouldDisplayOnDefaultPage(boolean included) { - fConfigurationWriter.setShouldDisplayOnDefaultPage(this.getId(), included); - } - - /** - * @return <code>true</code> if the wrapped category should be displayed on the - * its own content assist page, <code>false</code> otherwise - */ - boolean shouldDisplayOnOwnPage() { - return fConfigurationWriter.shouldDisplayOnOwnPage(this.getId()); - } - - /** - * @param shouldDisplay <code>true</code> if the wrapped category should be displayed on the - * its own content assist page, <code>false</code> otherwise - */ - void setShouldDisplayOnOwnPage(boolean shouldDisplay) { - fConfigurationWriter.setShouldDisplayOnOwnPage(this.getId(), shouldDisplay); - } - - /** - * @return the wrapped categories content assist page sort rank compared to the - * other categories - */ - int getOwnPageRank() { - return fConfigurationWriter.getPageSortOrder(this.getId()); - } - - /** - * @return the wrapped categories content assist page sort rank compared to the - * other categories - */ - int getDefaultPageRank() { - return fConfigurationWriter.getDefaultPageSortOrder(this.getId()); - } - } - - private class ModelViewerComparator extends ViewerComparator { - /** - * - */ - public ModelViewerComparator(Comparator comparator) { - super(comparator); - } - - /** - * @see org.eclipse.jface.viewers.ViewerComparator#compare(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object) - */ - public int compare(Viewer viewer, Object e1, Object e2) { - return this.getComparator().compare(e1, e2); - } - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/preferences/ICompletionProposalCategoriesConfigurationReader.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/preferences/ICompletionProposalCategoriesConfigurationReader.java deleted file mode 100644 index 74c95df1cf..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/preferences/ICompletionProposalCategoriesConfigurationReader.java +++ /dev/null @@ -1,82 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.preferences; - -/** - * <p>Implementers of the <code>org.eclipse.wst.sse.ui.completionProposalCategoriesConfiguration</code> - * extension will need an implementation of this interface for their extension</p> - * - * <p><b>NOTE: </b>Implementers must have a 0 argument constructor so class can be instantiated by - * extension.</p> - * - * @see ICompletionProposalCategoriesConfigurationWriter - */ -public interface ICompletionProposalCategoriesConfigurationReader { - /** - * The default is to display a category on its own page - * if not otherwise defined by a property. - */ - boolean DEFAULT_DISPLAY_ON_OWN_PAGE = true; - - /** The default is to display a category on the default content assist page. */ - boolean DEFAULT_INCLUDE_ON_DEFAULTS_PAGE = true; - - /** the default sort order if none is defined by a properties extension */ - int DEFAULT_SORT_ORDER = Integer.MAX_VALUE; - - /** - * <p>Determines if the given category should be displayed on its own content - * assist page</p> - * - * @param categoryID determine if this category should be displayed on its own - * content assist page - * - * @return <code>true</code> if the given category should be displayed on its - * own content assist page, <code>false</code> otherwise - */ - boolean shouldDisplayOnOwnPage(String categoryID); - - /** - * <p>Determines if the given category should be displayed on the default - * content assist page</p> - * - * @param categoryID determine if this category should be displayed on the - * default content assist page - * - * @return <code>true</code> if the given category should be displayed on the - * default content assist page, <code>false</code> otherwise - */ - boolean shouldDisplayOnDefaultPage(String categoryID); - - /** - * <p>Determines the sort order ranking of the given category when compared - * to the other categories, this is used to determine the order in which - * the separate content assist pages should be displayed</p> - * - * @param categoryID determine the sort order ranking of this category - * - * @return the sort order ranking of the given category when compared - * to the other categories - */ - int getPageSortOrder(String categoryID); - - /** - * <p>Determines the sort order ranking of the given category when compared - * to the other categories, this is used to determine the order in which - * categories should be listed on the default page</p> - * - * @param categoryID determine the sort order ranking of this category - * - * @return the sort order ranking of the given category when compared - * to the other categories - */ - int getDefaultPageSortOrder(String categoryID); -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/preferences/ICompletionProposalCategoriesConfigurationWriter.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/preferences/ICompletionProposalCategoriesConfigurationWriter.java deleted file mode 100644 index 0462819a28..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/preferences/ICompletionProposalCategoriesConfigurationWriter.java +++ /dev/null @@ -1,119 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.preferences; - -import java.util.List; - -import org.eclipse.wst.sse.ui.internal.contentassist.CompletionProposalCategory; - -/** - * <p>Implementers of the <code>org.eclipse.wst.sse.ui.completionProposalCategoriesConfiguration</code> - * extension can implement this interface if their configuration should be user edible and thus - * needs writing capabilities</p> - * - * <p><b>NOTE: </b>Implementers must have a 0 argument constructor so class can be instantiated by - * extension.</p> - * - * @see ICompletionProposalCategoriesConfigurationReader - */ -public interface ICompletionProposalCategoriesConfigurationWriter extends - ICompletionProposalCategoriesConfigurationReader { - - /** - * <p>If a writer has a known associated properties page then that properties - * page ID can be used so that error messages during the content assist process - * can link to that preference page to allow the user to change the settings</p> - * - * @return <code>true</code> if this writer has a known associated properties - * preference page, <code>false</code> otherwise - */ - boolean hasAssociatedPropertiesPage(); - - /** - * @return If {@link #hasAssociatedPropertiesPage()} returns <code>true</code> then - * this method must return a valid properties page ID where the user can edit the - * content assist configuration, else it can return <code>null</code> - */ - String getPropertiesPageID(); - - /** - * <p>Sets whether or not the given category should be displayed on its own content - * assist page.<p> - * - * <p><b>NOTE: </b>This preference should <b>NOT</b> be saved permanently here, that action - * should wait until {@link #saveConfiguration()} is called</p> - * - * @param categoryID the category that should either be displayed on its own content - * assist page or not - * @param shouldDisplay <code>true</code> if the given category should be displayed - * on its own content assist page, <code>false</code> otherwise - */ - void setShouldDisplayOnDefaultPage(String categoryID, boolean shouldDisplay); - - /** - * <p>Sets whether or not the given category should be displayed on the default content - * assist page.<p> - * - * <p><b>NOTE: </b>This preference should <b>NOT</b> be saved permanently here, that action - * should wait until {@link #saveConfiguration()} is called</p> - * - * @param categoryID the category that should either be displayed on the default content - * assist page or not - * @param shouldDisplay <code>true</code> if the given category should be displayed - * on the default content assist page, <code>false</code> otherwise - */ - void setShouldDisplayOnOwnPage(String categoryID, boolean shouldDisplay); - - /** - * <p>Sets the order in which the categories should be cycled when invoking content - * assist multiple times. Event categories that are not activated to display on their - * own content assist page can be listed here so that when activated to display on their - * own page they have a rank. The entire order needs to be re-set each time one category - * moves because the writer has no way of knowing how to move just one category in the order</p> - * - * <p><b>NOTE: </b>This preference should <b>NOT</b> be saved permanently here, that action - * should wait until {@link #saveConfiguration()} is called</p> - * - * @param order <code>{@link List}<{@link String}></code> - * <ul><li><b>values:</b> {@link CompletionProposalCategory} IDs</li></ul> - */ - void setPageOrder(List order); - - /** - * <p>Sets the order in which the categories should be listed on the default page. - * Event categories that are not activated to display on the default content assist - * page can be listed here so that when activated to display on the default page - * they have a rank. The entire order needs to be re-set each time one category - * moves because the writer has no way of knowing how to move just one category in the order</p> - * - * <p><b>NOTE: </b>This preference should <b>NOT</b> be saved permanently here, that action - * should wait until {@link #saveConfiguration()} is called</p> - * - * @param order <code>{@link List}<{@link String}></code> - * <ul><li><b>values:</b> {@link CompletionProposalCategory} IDs</li></ul> - */ - void setDefaultPageOrder(List order); - - /** - * <p>Should load the default settings from wherever they are being stored</p> - */ - void loadDefaults(); - - /** - * <p>Should save the configuration permanently. Typically called after the user - * changes some preferences using a preference page and then applies them, but if they do - * not apply the changes then this function should not be called. This is the reason why the - * various <code>set*</code> methods should not permanently save the configuration</p> - * - * @return <code>true</code> if the save was successful, <code>false</code> otherwise - */ - boolean saveConfiguration(); -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/quickoutline/AbstractQuickOutlineConfiguration.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/quickoutline/AbstractQuickOutlineConfiguration.java deleted file mode 100644 index 33ff2d8741..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/quickoutline/AbstractQuickOutlineConfiguration.java +++ /dev/null @@ -1,47 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.quickoutline; - -import org.eclipse.jface.viewers.ILabelProvider; -import org.eclipse.jface.viewers.ITreeContentProvider; -import org.eclipse.wst.sse.ui.IContentSelectionProvider; - -/** - * Base class that provides configuration for a quick outline. - * - */ -public abstract class AbstractQuickOutlineConfiguration { - - /** - * Provides the label provider to be used by the quick outline - * - * @return an <code>ILabelProvider</code> to be used by the quick outline - */ - public abstract ILabelProvider getLabelProvider(); - - /** - * Provides the content provider to be used by the quick outline - * - * @return a <code>ITreeContentProvider</code> to be used when providing the content of the quick outline - */ - public abstract ITreeContentProvider getContentProvider(); - - /** - * Provides the content selection provider to be used by the quick outline. This allows - * for adjusting the selection to be displayed in the outline based on the editor's selection - * - * @return an <code>IContentSelectionProvider</code> used by the quick outline. By default, returns - * null indicating that the selection in the editor translates to the selection in the outline. - */ - public IContentSelectionProvider getContentSelectionProvider() { - return null; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/reconcile/ISourceReconcilingListener.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/reconcile/ISourceReconcilingListener.java deleted file mode 100644 index 11093865b7..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/reconcile/ISourceReconcilingListener.java +++ /dev/null @@ -1,44 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.wst.sse.ui.reconcile; - -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.source.IAnnotationModel; - -/** - * A course listener for source viewer "reconciling" of a document - * - */ -public interface ISourceReconcilingListener { - - /** - * Called before reconciling is started. - */ - void aboutToBeReconciled(); - - /** - * Called after reconciling has been finished. - * - * @param document - * the text document or <code>null</code> if reconciliation has - * been cancelled - * @param model - * the annotation model that was changed or <code>null</code> - * if reconciliation has been cancelled - * @param forced - * <code>true</code> iff this reconciliation was forced - * @param progressMonitor - * the progress monitor - */ - void reconciled(IDocument document, IAnnotationModel model, boolean forced, IProgressMonitor progressMonitor); -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/typing/AbstractCharacterPairInserter.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/typing/AbstractCharacterPairInserter.java deleted file mode 100644 index 653965b727..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/typing/AbstractCharacterPairInserter.java +++ /dev/null @@ -1,148 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009, 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.typing; - -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.link.ILinkedModeListener; -import org.eclipse.jface.text.link.LinkedModeModel; -import org.eclipse.jface.text.link.LinkedModeUI; -import org.eclipse.jface.text.link.LinkedPosition; -import org.eclipse.jface.text.link.LinkedPositionGroup; -import org.eclipse.jface.text.link.LinkedModeUI.ExitFlags; -import org.eclipse.jface.text.link.LinkedModeUI.IExitPolicy; -import org.eclipse.jface.text.source.ISourceViewer; -import org.eclipse.swt.events.VerifyEvent; -import org.eclipse.swt.graphics.Point; -import org.eclipse.wst.sse.ui.internal.Logger; - -abstract public class AbstractCharacterPairInserter { - - class ExitPolicy implements IExitPolicy { - - private char fExit; - private char fEscape; - private IDocument fDocument; - - public ExitPolicy(char exit, char escape, IDocument document) { - fExit = exit; - fEscape = escape; - fDocument = document; - } - - public ExitFlags doExit(LinkedModeModel model, VerifyEvent event, int offset, int length) { - if(!isMasked(offset)) { - if (event.character == fExit) - return new ExitFlags(ILinkedModeListener.UPDATE_CARET, false); - } - return null; - } - - private boolean isMasked(int offset) { - try { - return fEscape == fDocument.getChar(offset - 1); - } catch (BadLocationException e) { - } - return false; - } - } - - /** - * Pair the character <code>c</code> in the source viewer <code>viewer</code>. - * Positions are linked before and after the inserted character. - * - * @param viewer the source viewer to add the linked mode to - * @param c the character to pair with - * @return true if the character was successfully paired; false otherwise - */ - public boolean pair(final ISourceViewer viewer, final char c) { - if (!shouldPair(viewer, c)) - return false; - - final char mc = getPair(c); - final char[] chars = new char[2]; - chars[0] = c; - chars[1] = mc; - - IDocument document = viewer.getDocument(); - - final Point selection= viewer.getSelectedRange(); - final int offset= selection.x; - final int length= selection.y; - - boolean paired = false; - try { - document.replace(offset, length, new String(chars)); - LinkedModeModel model = new LinkedModeModel(); - LinkedPositionGroup group = new LinkedPositionGroup(); - group.addPosition(new LinkedPosition(document, offset + 1, 0, LinkedPositionGroup.NO_STOP)); - model.addGroup(group); - model.forceInstall(); - - LinkedModeUI ui = new LinkedModeUI(model, viewer); - ui.setCyclingMode(LinkedModeUI.CYCLE_NEVER); - ui.setExitPosition(viewer, offset + 2, 0, Integer.MAX_VALUE); - ui.setExitPolicy(getExitPolicy(mc, getEscapeChar(c), document)); - ui.setSimpleMode(true); - ui.enter(); - - paired = true; - } catch (BadLocationException e) { - Logger.logException(e); - } - return paired; - } - - /** - * Hook to evaluate if the character should be paired. Clients may override - * to evaluate the case. - * @param viewer the source viewer where the character would be paired - * @param c the character to pair - * @return true if the character should have its pair character inserted; false otherwise - */ - protected boolean shouldPair(ISourceViewer viewer, char c) { - return true; - } - - /** - * Can the character be paired by the inserter - * @param c the character of interest - * @return true if the character can be paired by the inserter; false otherwise - */ - abstract public boolean hasPair(char c); - - /** - * Get the paired character for <code>c</code> - * @param c the character to find the pair of - * @return the pair character - */ - abstract protected char getPair(char c); - - /** - * Gets the escape character for <code>c</code> in case <code>c</code> is to be used - * within the paired characters - * @param c the character to find the escape character of - * @return the escape character - */ - protected char getEscapeChar(char c) { - return 0; - } - - public void initialize() { - } - - public void dispose() { - } - - protected IExitPolicy getExitPolicy(char exit, char escape, IDocument document) { - return new ExitPolicy(exit, escape, document); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/views/contentoutline/ContentOutlineConfiguration.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/views/contentoutline/ContentOutlineConfiguration.java deleted file mode 100644 index 6b461113a2..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/views/contentoutline/ContentOutlineConfiguration.java +++ /dev/null @@ -1,338 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2011 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.views.contentoutline; - -import org.eclipse.jface.action.Action; -import org.eclipse.jface.action.ActionContributionItem; -import org.eclipse.jface.action.IContributionItem; -import org.eclipse.jface.action.IMenuListener; -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.resource.ImageDescriptor; -import org.eclipse.jface.util.TransferDragSourceListener; -import org.eclipse.jface.util.TransferDropTargetListener; -import org.eclipse.jface.viewers.IContentProvider; -import org.eclipse.jface.viewers.ILabelProvider; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.LabelProvider; -import org.eclipse.jface.viewers.TreeViewer; -import org.eclipse.swt.events.KeyListener; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; -import org.eclipse.wst.sse.ui.internal.SSEUIPlugin; -import org.eclipse.wst.sse.ui.internal.contentoutline.PropertyChangeUpdateAction; -import org.eclipse.wst.sse.ui.internal.contentoutline.PropertyChangeUpdateActionContributionItem; -import org.eclipse.wst.sse.ui.internal.editor.EditorPluginImageHelper; -import org.eclipse.wst.sse.ui.internal.editor.EditorPluginImages; - -/** - * Basic Configuration class for Outline Pages - * - * @since 1.0 - */ -public abstract class ContentOutlineConfiguration { - - /** - * Add a collapse action to help with navigation. - */ - private class CollapseTreeAction extends Action { - private TreeViewer fTreeViewer = null; - - public CollapseTreeAction(TreeViewer viewer) { - super(SSEUIMessages.ContentOutlineConfiguration_0, AS_PUSH_BUTTON); //$NON-NLS-1$ - setImageDescriptor(COLLAPSE_E); - setDisabledImageDescriptor(COLLAPSE_D); - setToolTipText(getText()); - fTreeViewer = viewer; - } - - public void run() { - super.run(); - fTreeViewer.collapseAll(); - } - } - - /** - * Toggles whether incoming selection notification affects us - */ - private class ToggleLinkAction extends PropertyChangeUpdateAction { - public ToggleLinkAction(IPreferenceStore store, String preference) { - super(SSEUIMessages.ContentOutlineConfiguration_1, store, preference, true); //$NON-NLS-1$ - setToolTipText(getText()); - setDisabledImageDescriptor(SYNCED_D); - setImageDescriptor(SYNCED_E); - update(); - } - - public void update() { - super.update(); - setLinkWithEditor(isChecked()); - } - } - - ImageDescriptor COLLAPSE_D = EditorPluginImageHelper.getInstance().getImageDescriptor(EditorPluginImages.IMG_DLCL_COLLAPSEALL); - ImageDescriptor COLLAPSE_E = EditorPluginImageHelper.getInstance().getImageDescriptor(EditorPluginImages.IMG_ELCL_COLLAPSEALL); - - private boolean fIsLinkWithEditor = false; - - private ILabelProvider fLabelProvider; - private IContributionItem[] fMenuContributions = null; - private IContributionItem[] fToolbarContributions = null; - private final String OUTLINE_LINK_PREF = "outline-link-editor"; //$NON-NLS-1$ - private static final String OUTLINE_FILTER_PREF = "org.eclipse.wst.sse.ui.OutlinePage"; //$NON-NLS-1$ - ImageDescriptor SYNCED_D = EditorPluginImageHelper.getInstance().getImageDescriptor(EditorPluginImages.IMG_DLCL_SYNCED); - ImageDescriptor SYNCED_E = EditorPluginImageHelper.getInstance().getImageDescriptor(EditorPluginImages.IMG_ELCL_SYNCED); - - /** - * Create new instance of ContentOutlineConfiguration - */ - public ContentOutlineConfiguration() { - // Must have empty constructor to createExecutableExtension - super(); - } - - /** - * Creates the contributions for the view's local menu. Subclasses should - * merge their contributions with these. - * - * @param viewer - * the TreeViewer associated with this configuration - * @return menu contributions - */ - protected IContributionItem[] createMenuContributions(TreeViewer viewer) { - IContributionItem toggleLinkItem = new PropertyChangeUpdateActionContributionItem(new ToggleLinkAction(getPreferenceStore(), OUTLINE_LINK_PREF)); - IContributionItem[] items = new IContributionItem[]{toggleLinkItem}; - return items; - } - - /** - * Creates the toolbar contributions. Subclasses should merge their - * contributions with these. - * - * @param viewer - * the TreeViewer associated with this configuration - * @return toolbar contributions - */ - protected IContributionItem[] createToolbarContributions(TreeViewer viewer) { - IContributionItem collapseAllItem = new ActionContributionItem(new CollapseTreeAction(viewer)); - IContributionItem[] items = new IContributionItem[]{collapseAllItem}; - return items; - } - - /** - * Returns the ContentProvider to use with the given viewer. - * - * @param viewer - * the TreeViewer associated with this configuration - * @return the IContentProvider to use with this viewer - */ - public abstract IContentProvider getContentProvider(TreeViewer viewer); - - /** - * Returns an array of KeyListeners to attach to the given viewer's - * control or null. - * - * @param viewer - * the TreeViewer associated with this configuration - * @return an array of KeyListeners to attach to the TreeViewer's Control, - * or null. The listeners should adhere to the KeyEvent.doit field - * to ensure proper behaviors. Ordering of the event notifications - * is dependent on the Control in the TreeViewer. - */ - public KeyListener[] getKeyListeners(TreeViewer viewer) { - return null; - } - - /** - * Returns the LabelProvider for the items within the given viewer. - * - * @param viewer - * the TreeViewer associated with this configuration - * @return the ILabelProvider for items within the viewer - */ - public ILabelProvider getLabelProvider(TreeViewer viewer) { - if (fLabelProvider == null) - fLabelProvider = new LabelProvider(); - return fLabelProvider; - } - - /** - * Returns the menu contribution items for the local menu in the outline. - * - * @param viewer - * the TreeViewer associated with this configuration - * @return IContributionItem[] for the local menu - */ - public final IContributionItem[] getMenuContributions(TreeViewer viewer) { - if (fMenuContributions == null && (viewer.getControl() != null && !viewer.getControl().isDisposed())) { - fMenuContributions = createMenuContributions(viewer); - } - return fMenuContributions; - } - - /** - * Returns the menu listener to notify when the given viewer's context - * menu is about to be shown or null. - * - * @param viewer - * the TreeViewer associated with this configuration - * @return the IMenuListener to notify when the viewer's context menu is - * about to be shown, or null - */ - public IMenuListener getMenuListener(TreeViewer viewer) { - return null; - } - - /** - * Returns the PreferenceStore to use for this configuration. - * - * @return the preference store in which to remember preferences (such as - * the link-with-editor toggle state) - */ - protected IPreferenceStore getPreferenceStore() { - return SSEUIPlugin.getInstance().getPreferenceStore(); - } - - /** - * Returns the (filtered) selection from the given selection. - * - * @param selection - * model selection - * @param viewer - * the TreeViewer associated with this configuration - * @return The (filtered) selection from this event. Uses include mapping - * model selection onto elements provided by the content provider. - * Should only return elements that will be shown in the Tree - * Control. - */ - public ISelection getSelection(TreeViewer viewer, ISelection selection) { - return selection; - } - - /** - * @since 2.0 - * @param treeViewer - * @return a label provider providing the status line contents - */ - public ILabelProvider getStatusLineLabelProvider(TreeViewer treeViewer) { - return null; - } - - /** - * Returns contribution items for the local toolbar in the outline. - * - * @param viewer - * the TreeViewer associated with this configuration - * @return IContributionItem[] for the local toolbar - */ - public final IContributionItem[] getToolbarContributions(TreeViewer viewer) { - if (fToolbarContributions == null && (viewer.getControl() != null && !viewer.getControl().isDisposed())) { - fToolbarContributions = createToolbarContributions(viewer); - } - return fToolbarContributions; - } - - /** - * Adopted since you can't easily removeDragSupport from - * StructuredViewers. - * - * @param treeViewer - * the TreeViewer associated with this configuration - * @return an array of TransferDragSourceListeners - */ - public TransferDragSourceListener[] getTransferDragSourceListeners(TreeViewer treeViewer) { - return new TransferDragSourceListener[0]; - } - - /** - * Adopted since you can't easily removeDropSupport from - * StructuredViewers. - * - * @param treeViewer - * the TreeViewer associated with this configuration - * @return an array of TransferDropTargetListeners - */ - public TransferDropTargetListener[] getTransferDropTargetListeners(TreeViewer treeViewer) { - return new TransferDropTargetListener[0]; - } - - /** - * Returns true if node selection changes affect selection in the - * TreeViewer. - * - * @param treeViewer - * the TreeViewer associated with this configuration - * @return true if outline is currently linked to selection in editor, - * false otherwise - */ - public boolean isLinkedWithEditor(TreeViewer treeViewer) { - return fIsLinkWithEditor; - } - - /** - * Sets whether or not outline view should be linked with selection in - * editor. - * - * @param isLinkWithEditor - * The isLinkWithEditor to set. - */ - void setLinkWithEditor(boolean isLinkWithEditor) { - fIsLinkWithEditor = isLinkWithEditor; - } - - /** - * General hook for resource releasing and listener removal when - * configurations change or the viewer is disposed of. This implementation - * stops of any remaining PropertyChangeUpdateActionContributionItem from - * preference listening. - * - * @param viewer - * the TreeViewer associated with this configuration - */ - public void unconfigure(TreeViewer viewer) { - if (fToolbarContributions != null) { - for (int i = 0; i < fToolbarContributions.length; i++) { - if (fToolbarContributions[i] instanceof PropertyChangeUpdateActionContributionItem) { - ((PropertyChangeUpdateActionContributionItem) fToolbarContributions[i]).disconnect(); - } - } - fToolbarContributions = null; - } - if (fMenuContributions != null) { - for (int i = 0; i < fMenuContributions.length; i++) { - if (fMenuContributions[i] instanceof PropertyChangeUpdateActionContributionItem) { - ((PropertyChangeUpdateActionContributionItem) fMenuContributions[i]).disconnect(); - } - } - fMenuContributions = null; - } - } - - /** - * Provides the target used when associating filters to the outline - * - * @return The target id used when associating filters to the outline - */ - protected String getOutlineFilterTarget() { - return OUTLINE_FILTER_PREF ; - } - - /** - * Returns the content outline filter processor for this configuration - * - * @param viewer the {@link TreeViewer} that is associated with the filter - * - * @return A {@link ContentOutlineFilterProcessor} to filter nodes in the outline - */ - public ContentOutlineFilterProcessor getOutlineFilterProcessor(TreeViewer viewer){ - return new ContentOutlineFilterProcessor(getPreferenceStore(), getOutlineFilterTarget(), viewer); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/views/contentoutline/ContentOutlineFilterProcessor.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/views/contentoutline/ContentOutlineFilterProcessor.java deleted file mode 100644 index b1b61e3e33..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/views/contentoutline/ContentOutlineFilterProcessor.java +++ /dev/null @@ -1,318 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.sse.ui.views.contentoutline; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Map; - -import org.eclipse.core.runtime.Assert; -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.viewers.StructuredViewer; -import org.eclipse.jface.viewers.ViewerFilter; -import org.eclipse.jface.window.Window; -import org.eclipse.wst.sse.ui.internal.filter.OutlineCustomFiltersDialog; -import org.eclipse.wst.sse.ui.internal.filter.OutlineFilterDescriptor; -import org.eclipse.wst.sse.ui.internal.filter.OutlineNamePatternFilter; - -/** - * Action group to add the filter action to a view part's tool bar menu. - * <p> - * This class may be instantiated; it is not intended to be subclassed. - * </p> - * - * @noextend This class is not intended to be subclassed by clients. - */ -public class ContentOutlineFilterProcessor { - - private static final String SEPARATOR = ","; //$NON-NLS-1$ - private final String TAG_USER_DEFINED_PATTERNS_ENABLED = "userDefinedPatternsEnabled"; //$NON-NLS-1$ - private final String TAG_USER_DEFINED_PATTERNS = "userDefinedPatterns"; //$NON-NLS-1$ - - private static class FilterItem { - boolean enabled; - boolean previouslyEnabled; - OutlineFilterDescriptor descriptor; - String id; - - private ViewerFilter filterInstance = null; - - public FilterItem(OutlineFilterDescriptor descriptor) { - this.descriptor = descriptor; - this.id = descriptor.getId(); - this.previouslyEnabled = false; - this.enabled = descriptor.isEnabled(); - } - - public ViewerFilter getFilterInstance() { - if (filterInstance == null) { - filterInstance = descriptor.createViewerFilter(); - } - return filterInstance; - - } - } - - private final StructuredViewer fViewer; - private final OutlineNamePatternFilter fPatternFilter; - - private boolean fUserDefinedPatternsEnabled; - private String[] fUserDefinedPatterns; - - private String[] fPreviousPatterns; - - private final Map fFilterItems; - - private final String fTargetId; - private IPreferenceStore fStore; - - /** - * Creates a new <code>CustomFilterAction</code>. - * - * @param store - * the preference Store - * @param ownerId - * the id of this action group's owner - * @param viewer - * the viewer to be filtered - */ - public ContentOutlineFilterProcessor(IPreferenceStore store, String ownerId, StructuredViewer viewer) { - Assert.isNotNull(ownerId); - Assert.isNotNull(viewer); - fStore = store; - fTargetId = ownerId; - fViewer = viewer; - fPatternFilter = new OutlineNamePatternFilter(); - - fUserDefinedPatterns = new String[0]; - fUserDefinedPatternsEnabled = false; - fPreviousPatterns = new String[0]; - - fFilterItems = new HashMap(); - OutlineFilterDescriptor[] filterDescriptors = OutlineFilterDescriptor.getFilterDescriptors(fTargetId); - for (int i = 0; i < filterDescriptors.length; i++) { - FilterItem item = new FilterItem(filterDescriptors[i]); - fFilterItems.put(item.id, item); - - } - - initializeWithViewDefaults(); - - updateViewerFilters(); - - } - - /* - * @see org.eclipse.jface.action.IContributionItem#isDynamic() - */ - public boolean isDynamic() { - return true; - } - - /** - * Returns a list of currently enabled filters. The filter is identified by - * its id. - * <p> - * This method is for internal use only and should not be called by clients - * outside of JDT/UI. - * </p> - * - * @return a list of currently enabled filters - * - * @noreference This method is not intended to be referenced by clients. - */ - public String[] internalGetEnabledFilterIds() { - ArrayList enabledFilterIds = new ArrayList(); - for (Iterator iterator = fFilterItems.values().iterator(); iterator.hasNext();) { - FilterItem item = (FilterItem) iterator.next(); - if (item.enabled) { - enabledFilterIds.add(item.id); - } - } - return (String[]) enabledFilterIds.toArray(new String[enabledFilterIds.size()]); - } - - private void setEnabledFilterIds(String[] enabledIds) { - // set all to false - fUserDefinedPatternsEnabled = false; - for (Iterator iterator = fFilterItems.values().iterator(); iterator.hasNext();) { - FilterItem item = (FilterItem) iterator.next(); - item.enabled = false; - } - // set enabled to true - for (int i = 0; i < enabledIds.length; i++) { - FilterItem item = (FilterItem) fFilterItems.get(enabledIds[i]); - if (item != null) { - item.enabled = true; - } - if (fPatternFilter.getClass().getName().equals(enabledIds[i])) - fUserDefinedPatternsEnabled = true; - } - } - - private void setUserDefinedPatterns(String[] patterns) { - fUserDefinedPatterns = patterns; - } - - private boolean areUserDefinedPatternsEnabled() { - return fUserDefinedPatternsEnabled; - } - - private void setUserDefinedPatternsEnabled(boolean state) { - fUserDefinedPatternsEnabled = state; - } - - // ---------- viewer filter handling ---------- - - private boolean updateViewerFilters() { - ViewerFilter[] installedFilters = fViewer.getFilters(); - ArrayList viewerFilters = new ArrayList(installedFilters.length); - - HashSet patterns = new HashSet(); - - boolean hasChange = false; - boolean patternChange = false; - - for (Iterator iterator = fFilterItems.values().iterator(); iterator.hasNext();) { - FilterItem item = (FilterItem) iterator.next(); - if (item.descriptor.isCustomFilter()) { - if (item.enabled != item.previouslyEnabled) { - hasChange = true; - } - if (item.enabled) { - ViewerFilter filter = item.getFilterInstance(); // only - // create - // when - // changed - if (filter != null) { - viewerFilters.add(filter); - } - } - } else if (item.descriptor.isPatternFilter()) { - if (item.enabled) { - patterns.add(item.descriptor.getPattern()); - } - patternChange |= (item.enabled != item.previouslyEnabled); - } - item.previouslyEnabled = item.enabled; - } - - if (areUserDefinedPatternsEnabled()) { - for (int i = 0; i < fUserDefinedPatterns.length; i++) { - patterns.add(fUserDefinedPatterns[i]); - } - } - if (!patternChange) { // no pattern change so far, test if the user - // patterns made a difference - patternChange = hasChanges(patterns, fPreviousPatterns); - } - - fPreviousPatterns = (String[]) patterns.toArray(new String[patterns.size()]); - if (patternChange || hasChange) { - fPatternFilter.setPatterns(fPreviousPatterns); - if (patterns.isEmpty()) { - viewerFilters.remove(fPatternFilter); - } else if (!viewerFilters.contains(fPatternFilter)) { - boolean contains = false; - for (int i = 0; i < viewerFilters.size(); i++) { - if (viewerFilters.get(i) instanceof OutlineNamePatternFilter) { - OutlineNamePatternFilter filter = (OutlineNamePatternFilter) viewerFilters.get(i); - String[] a1 = filter.getPatterns(); - String[] a2 = fPatternFilter.getPatterns(); - if (a1[0].equals(a2[0])) - contains = true; - else { - viewerFilters.remove(i); - } - break; - } - } - if (!contains) - viewerFilters.add(fPatternFilter); - } - hasChange = true; - } - if (hasChange) { - fViewer.setFilters((ViewerFilter[]) viewerFilters.toArray(new ViewerFilter[viewerFilters.size()])); // will - // refresh - } - return hasChange; - } - - private boolean hasChanges(HashSet patterns, String[] oldPatterns) { - HashSet copy = (HashSet) patterns.clone(); - for (int i = 0; i < oldPatterns.length; i++) { - boolean found = copy.remove(oldPatterns[i]); - if (!found) - return true; - } - return !copy.isEmpty(); - } - - // ---------- view kind/defaults persistency ---------- - - private void initializeWithViewDefaults() { - // get default values for view - - fUserDefinedPatternsEnabled = fStore.getBoolean(getPreferenceKey(TAG_USER_DEFINED_PATTERNS_ENABLED)); - setUserDefinedPatterns(OutlineCustomFiltersDialog.convertFromString(fStore.getString(getPreferenceKey(TAG_USER_DEFINED_PATTERNS)), SEPARATOR)); - - for (Iterator iterator = fFilterItems.values().iterator(); iterator.hasNext();) { - FilterItem item = (FilterItem) iterator.next(); - String id = item.id; - // set default to value from plugin contributions (fixes - // https://bugs.eclipse.org/bugs/show_bug.cgi?id=73991 ): - fStore.setDefault(id, item.descriptor.isEnabled()); - item.enabled = fStore.getBoolean(id); - } - - } - - private void storeViewDefaults() { - // get default values for view - - fStore.setValue(getPreferenceKey(TAG_USER_DEFINED_PATTERNS_ENABLED), fUserDefinedPatternsEnabled); - fStore.setValue(getPreferenceKey(TAG_USER_DEFINED_PATTERNS), OutlineCustomFiltersDialog.convertToString(fUserDefinedPatterns, SEPARATOR)); - - boolean fFilterSelected = false; - for (Iterator iterator = fFilterItems.values().iterator(); iterator.hasNext();) { - FilterItem item = (FilterItem) iterator.next(); - fStore.setValue(item.id, item.enabled); - if (item.enabled) - fFilterSelected = true; - } - - fStore.setValue(fTargetId, fUserDefinedPatternsEnabled || fFilterSelected); - - } - - private String getPreferenceKey(String tag) { - return "CustomFiltersActionGroup." + fTargetId + '.' + tag; //$NON-NLS-1$ - } - - public void openDialog() { - OutlineCustomFiltersDialog dialog = new OutlineCustomFiltersDialog(fViewer.getControl().getShell(), fTargetId, areUserDefinedPatternsEnabled(), fUserDefinedPatterns, internalGetEnabledFilterIds()); - - if (dialog.open() == Window.OK) { - - setEnabledFilterIds(dialog.getEnabledFilterIds()); - setUserDefinedPatternsEnabled(dialog.areUserDefinedPatternsEnabled()); - setUserDefinedPatterns(dialog.getUserDefinedPatterns()); - storeViewDefaults(); - - updateViewerFilters(); - } else { - storeViewDefaults(); - } - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/views/properties/IPropertySourceExtension.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/views/properties/IPropertySourceExtension.java deleted file mode 100644 index d74eee9c90..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/views/properties/IPropertySourceExtension.java +++ /dev/null @@ -1,41 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.views.properties; - -/** - * Declares that this IPropertySource might support outright removal of a - * property - * - * @since 1.0 - */ -public interface IPropertySourceExtension { - - /** - * Returns true if the property matching the given name can be removed, - * false otherwise. - * - * @param name - * the name of the property - * @return whether the property matching this name can be removed - */ - boolean isPropertyRemovable(Object name); - - /** - * Removes the property with the given displayed name. If no such property - * exists, nothing is done. - * - * @param name - * the displayed name of the property - */ - void removeProperty(Object name); -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/views/properties/PropertySheetConfiguration.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/views/properties/PropertySheetConfiguration.java deleted file mode 100644 index f89e38d8af..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/views/properties/PropertySheetConfiguration.java +++ /dev/null @@ -1,104 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.views.properties; - -import org.eclipse.jface.action.IMenuManager; -import org.eclipse.jface.action.IStatusLineManager; -import org.eclipse.jface.action.IToolBarManager; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.viewers.StructuredSelection; -import org.eclipse.ui.IWorkbenchPart; -import org.eclipse.ui.views.properties.IPropertySheetPage; -import org.eclipse.ui.views.properties.IPropertySourceProvider; - - -/** - * Configuration class for Property Sheet Pages. Not finalized. - * - * @since 1.0 - */ -public abstract class PropertySheetConfiguration { - /** - * Create new instance of PropertySheetConfiguration - */ - public PropertySheetConfiguration() { - // Must have empty constructor to createExecutableExtension - super(); - } - - /** - * Adds contribution menu items to the given menuManager, toolbarManager, - * statusLineManager. - * - * @param menuManager - * the local menu manager of the property sheet - * @param toolBarManager - * the local toolbar manager of the property sheet - * @param statusLineManager - * the status line manager of the property sheet - */ - public void addContributions(IMenuManager menuManager, IToolBarManager toolBarManager, IStatusLineManager statusLineManager) { - // do nothing - } - - /** - * Allows for filteration of selection before being sent to the viewer. - * - * @param selectingPart - * may be null - * @param selection - * model selection - * @return the (filtered) selection to be sent to the viewer - */ - public ISelection getInputSelection(IWorkbenchPart selectingPart, ISelection selection) { - ISelection preferredSelection = selection; - if (selection instanceof IStructuredSelection) { - // don't support more than one selected node - if (((IStructuredSelection) selection).size() > 1) - preferredSelection = StructuredSelection.EMPTY; - } - return preferredSelection; - } - - /** - * Returns the correct IPropertySourceProvider. - * - * @param page - * the page to be configured by this configuration - * @return the IPropertySourceProvider for the given page - */ - public abstract IPropertySourceProvider getPropertySourceProvider(IPropertySheetPage page); - - /** - * Removes contribution menu items from the given menuManager, - * toolbarManager, statusLineManager. - * - * @param menuManager - * the local menu manager of the property sheet - * @param toolBarManager - * the local toolbar manager of the property sheet - * @param statusLineManager - * the status line manager of the property sheet - */ - public void removeContributions(IMenuManager menuManager, IToolBarManager toolBarManager, IStatusLineManager statusLineManager) { - // do nothing - } - - /** - * General hook for resource releasing and listener removal when - * configurations change. - */ - public void unconfigure() { - } -} |