diff options
author | nitind | 2005-04-13 19:12:49 +0000 |
---|---|---|
committer | nitind | 2005-04-13 19:12:49 +0000 |
commit | 292ded1b4de2f6030e4038b92a37ea5914d3ea7d (patch) | |
tree | 44e67d379b97f7e2b353212e4103815636679fec /bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal | |
parent | 20cb84d3fe65f82e36498d9946b3b951273a4a4d (diff) | |
download | webtools.sourceediting-20050413_1525.tar.gz webtools.sourceediting-20050413_1525.tar.xz webtools.sourceediting-20050413_1525.zip |
This commit was manufactured by cvs2svn to create tag 'v20050413_1525'.v20050413_1525
Diffstat (limited to 'bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal')
127 files changed, 0 insertions, 25597 deletions
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 4c345c2f2f..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/CaretMediator.java +++ /dev/null @@ -1,282 +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; - -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.view.events.CaretEvent; -import org.eclipse.wst.sse.ui.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. - */ -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/GotoAnnotationAction.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/GotoAnnotationAction.java deleted file mode 100644 index d138ff1af9..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/GotoAnnotationAction.java +++ /dev/null @@ -1,362 +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; - -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.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.MarkerAnnotation; -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. - * - */ -public class GotoAnnotationAction extends TextEditorAction { - - /** - * 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); - 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 - * @since 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 MarkerAnnotation) - marker = ((MarkerAnnotation) 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); - } - // 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/IModelProvider.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/IModelProvider.java deleted file mode 100644 index 6d7ab5a52c..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, 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; - -import org.eclipse.ui.texteditor.IDocumentProvider; -import org.eclipse.wst.sse.core.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/IReleasable.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/IReleasable.java deleted file mode 100644 index 5806815fcc..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, 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; - -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 04255823c7..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, 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; - - - -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/ITemporaryAnnotation.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/ITemporaryAnnotation.java deleted file mode 100644 index fc256319cf..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, 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; - -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 dfb1edc033..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/Logger.java +++ /dev/null @@ -1,161 +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; - - - -import java.util.StringTokenizer; - -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.Status; -import org.osgi.framework.Bundle; - -/** - * 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); - 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); - } - - 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/NullModelProvider.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/NullModelProvider.java deleted file mode 100644 index 5fb0eb63b7..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/NullModelProvider.java +++ /dev/null @@ -1,121 +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; - -import java.util.HashMap; - -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.jface.operation.IRunnableContext; -import org.eclipse.jface.text.Document; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.source.AnnotationModel; -import org.eclipse.jface.text.source.IAnnotationModel; -import org.eclipse.ui.texteditor.AbstractDocumentProvider; -import org.eclipse.wst.sse.core.IStructuredModel; - - -/** - * An IModelProvider that builds StructuredModels on top of IDocuments. A - * prototype for "any IEditorInput" support - * - * *** VERY UNTESTED *** TODO: Currently BROKEN - * - * @deprecated - */ -public class NullModelProvider extends AbstractDocumentProvider implements IModelProvider { - - private static NullModelProvider _instance = null; - - public static synchronized NullModelProvider getInstance() { - if (_instance == null) { - _instance = new NullModelProvider(); - } - return _instance; - } - - private HashMap fModelMap = new HashMap(1); - - public NullModelProvider() { - super(); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.AbstractDocumentProvider#createAnnotationModel(java.lang.Object) - */ - protected IAnnotationModel createAnnotationModel(Object element) { - return new AnnotationModel(); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.AbstractDocumentProvider#createDocument(java.lang.Object) - */ - protected IDocument createDocument(Object element) { - // return getModel(element).getStructuredDocument(); - return new Document(); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.AbstractDocumentProvider#createElementInfo(java.lang.Object) - */ - // protected ElementInfo createElementInfo(Object element) throws - // CoreException { - // if (fModelMap.get(element) != null) - // fModelMap.put(element, - // getModelManager().createUnManagedStructuredModelFor(ContentTypeIdentifierForXML.ContentTypeID_XML)); - // return super.createElementInfo(element); - // } - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.AbstractDocumentProvider#disposeElementInfo(java.lang.Object, - * org.eclipse.ui.texteditor.AbstractDocumentProvider.ElementInfo) - */ - protected void disposeElementInfo(Object element, ElementInfo info) { - fModelMap.remove(element); - super.disposeElementInfo(element, info); - } - - /* - * (non-Javadoc) - * - * @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) { - return; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.sse.ui.IModelProvider#getModel(java.lang.Object) - */ - public IStructuredModel getModel(Object element) { - return (IStructuredModel) fModelMap.get(element); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.AbstractDocumentProvider#getOperationRunner(org.eclipse.core.runtime.IProgressMonitor) - */ - protected IRunnableContext getOperationRunner(IProgressMonitor monitor) { - return null; - } -} 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 aa5698daf9..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/PreferenceInitializer.java +++ /dev/null @@ -1,77 +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 - * - *******************************************************************************/ -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.swt.SWT; -import org.eclipse.swt.graphics.RGB; -import org.eclipse.ui.editors.text.EditorsUI; -import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants; -import org.eclipse.wst.sse.core.internal.preferences.CommonModelPreferenceNames; -import org.eclipse.wst.sse.ui.internal.preferences.EditorPreferenceNames; -import org.eclipse.wst.sse.ui.internal.projection.IStructuredTextFoldingProvider; -import org.eclipse.wst.sse.ui.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(); - - // 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); - - // 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$ - - // tab width is also a model-side preference so need to load default - // from there - store.setDefault(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH, CommonModelPreferenceNames.DEFAULT_TAB_WIDTH); - - // set default read-only foreground color scale value - store.setDefault(EditorPreferenceNames.READ_ONLY_FOREGROUND_SCALE, 30); - - // set default enable folding value - store.setDefault(IStructuredTextFoldingProvider.FOLDING_ENABLED, false); - } - - private void setMatchingBracketsPreferences(IPreferenceStore store) { - // matching brackets is not part of base text editor preference - store.setDefault(EditorPreferenceNames.MATCHING_BRACKETS, true); - PreferenceConverter.setDefault(store, 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 a66b67c885..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/ReadOnlyAwareDropTargetAdapter.java +++ /dev/null @@ -1,43 +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; - - -import org.eclipse.jface.text.IDocument; -import org.eclipse.swt.dnd.DND; -import org.eclipse.swt.dnd.DropTargetEvent; -import org.eclipse.wst.sse.core.text.IStructuredDocument; -import org.eclipse.wst.sse.ui.extension.ExtendedEditorDropTargetAdapter; - - -public class ReadOnlyAwareDropTargetAdapter extends ExtendedEditorDropTargetAdapter { - - public ReadOnlyAwareDropTargetAdapter() { - super(); - } - - public void drop(DropTargetEvent event) { - IDocument document = getTextViewer().getDocument(); - if (document instanceof IStructuredDocument) { - if (((IStructuredDocument) document).containsReadOnly(getDropOffset(event), 0)) { - 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 d33ce7a8a2..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/SSEUIMessages.java +++ /dev/null @@ -1,374 +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 - 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 - * - * @since 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 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 FormatMenu_label; - 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 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 ShowTooltipDesc_label; - public static String ShowTooltipDesc_tooltip; - public static String ShowTooltipDesc_image; - public static String ShowTooltipDesc_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 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 _4concat; - public static String Content_type__UI_; - public static String Foreground_UI_; - public static String Background_UI_; - 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 ManageBreakpoints_error_removing_title1; - // public static String ManageBreakpoints_error_removing_message1; - // public static String ManageBreakpoints_error_retrieving_message; - - public static String AbstractColorPageDescription; - // public static String JSPSourcePreferencePageDescription; - public static String EditorModelUtil_0; - public static String EditorModelUtil_1; - - // 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; - - // 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_error_save_message; - // public static String Editor_error_save_title; - // public static String Editor_warning_save_delete; - - // actions - // public static String Previous_annotation; - // public static String Next_annotation; - - // Annotation Types - // 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 Editor_ToggleInsertMode_label; - - public static String EditPreferences_label; - public static String EditPreferences_tooltip; - public static String EditPreferences_description; - // - // These strings are used in Workbench menu bar - // - public static String ExpandSelectionToMenu_label; - public static String SourceMenu_label; - // public static String ConvertLineDelimitersMenu_label; - // public static String FindOccurrences_label; - // - public static String FindOccurrencesActionProvider_0; - public static String RemoveAction_0; - public static String ShowPropertiesAction_0; - public static String StructuredContentOutlineConfiguration_0; - public static String StructuredContentOutlineConfiguration_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 ConvertLineDelimitersToCRLFActionDelegate_jobName; - // public static String - // ConvertLineDelimitersToCRLFActionDelegate_errorStatusMessage; - // public static String ConvertLineDelimitersToCRLFActionDelegate_3; - // public static String ConvertLineDelimitersToCRLFActionDelegate_4; - 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 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_8; - public static String TaskTagPreferenceTab_9; - public static String TaskTagPreferenceTab_10; - 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 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_annotationRollover; - // public static String TextHoverPreferenceTab_showAffordance; - public static String TextHoverPreferenceTab_hoverPreferences; - // public static String TextHoverPreferenceTab_enabled; - 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 BasicFindOccurrencesAction_0; - // public static String BasicSearchLabelProvider_0; - public static String PreferenceManager_0; - // public static String NavigationPreferenceTab_0; - public static String OccurrencesSearchQuery_0; - // public static String OccurrencesSearchQuery_1; - public static String OccurrencesSearchQuery_2; - // public static String FileModelProvider_0; - // public static String JFaceNodeAdapter_0; - public static String ShowView_errorTitle; - public static String proc_dirty_regions_0; - // Encoding - public static String EncodingPreferencePage_0; - public static String EncodingPreferencePage_1; - - public static String busy; - 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_8; - public static String OffsetStatusLineContributionItem_9; - public static String OffsetStatusLineContributionItem_10; - public static String OffsetStatusLineContributionItem_11; - 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; - - static { - // load message values from bundle file - NLS.initializeMessages(BUNDLE_NAME, SSEUIMessages.class); - } - - private SSEUIMessages() { - // cannot create new instance - } - - public static ResourceBundle getResourceBundle() { - try { - if (fResourceBundle == null) - fResourceBundle = ResourceBundle.getBundle(BUNDLE_NAME); - } - catch (MissingResourceException x) { - fResourceBundle = null; - } - return fResourceBundle; - } -} 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 37b5885697..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/SSEUIPlugin.java +++ /dev/null @@ -1,66 +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; - - - -import org.eclipse.ui.plugin.AbstractUIPlugin; -import org.eclipse.wst.sse.ui.registry.AdapterFactoryRegistry; -import org.eclipse.wst.sse.ui.registry.AdapterFactoryRegistryImpl; -import org.eclipse.wst.sse.ui.registry.embedded.EmbeddedAdapterFactoryRegistryImpl; -import org.eclipse.wst.sse.ui.taginfo.TextHoverManager; - - -public class SSEUIPlugin extends AbstractUIPlugin { - - public final static String ID = "org.eclipse.wst.sse.ui"; //$NON-NLS-1$ - - static SSEUIPlugin instance = null; - - 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(); - - } - - public AdapterFactoryRegistry getEmbeddedAdapterFactoryRegistry() { - return EmbeddedAdapterFactoryRegistryImpl.getInstance(); - - } - - /** - * Return text hover manager - * - * @return TextHoverManager - */ - public TextHoverManager getTextHoverManager() { - if (fTextHoverManager == null) { - fTextHoverManager = new TextHoverManager(); - } - return fTextHoverManager; - } -} 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 4a39fe83f0..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/SSEUIPluginResources.properties +++ /dev/null @@ -1,343 +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 -# -############################################################################### -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 @Ctrl+Z -Undo_Text_Change__UI_=Undo Text Change. -_Undo__0___Ctrl_Z_UI_=&Undo {0} @Ctrl+Z -Undo___0___UI_=Undo: {0}. -_Redo_Text_Change__Ctrl_Y_UI_=&Redo Text Change @Ctrl+Y -Redo_Text_Change__UI_=Redo Text Change. -_Redo__0___Ctrl_Y_UI_=&Redo {0} @Ctrl+Y -Redo___0___UI_=Redo: {0}. -FormatMenu_label=F&ormat -Format_Document_UI_=Format Document -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@Ctrl+X -Editor_Cut_tooltip=Cut -Editor_Cut_image= -Editor_Cut_description=Cut - -Editor_Copy_label=&Copy@Ctrl+C -Editor_Copy_tooltip=Copy -Editor_Copy_image= -Editor_Copy_description=Copy - -Editor_Paste_label=&Paste@Ctrl+V -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 -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=&Document -FormatDocument_tooltip=Format Document -FormatDocument_image= -FormatDocument_description=Format Document -FormatActiveElements_label=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 -ShowTooltipDesc_label=Show &Tooltip Description -ShowTooltipDesc_tooltip=Displays the hover help for the selected element -ShowTooltipDesc_image= -ShowTooltipDesc_description=Displays the hover help for the selected element -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 -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. - -_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: -Background_UI_=&Background: -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 -ManageBreakpoints_error_removing_title1=Remove Breakpoint -ManageBreakpoints_error_removing_message1=Cannot remove breakpoint -ManageBreakpoints_error_retrieving_message=Retrieving markers failed: - -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 -JSPSourcePreferencePageDescription=Embedded content type\'s source preferences will be used. Select the file type for customization -## -EditorModelUtil_0=model in invalid state -EditorModelUtil_1=There was a problem adding adapter factories - -## 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 - -# web content settings -UI_Default_HTML_DOCTYPE_ID___1=&Document type: -UI_CSS_profile___2=&CSS profile: -UI_Target_Device___3=&Target device: -# -# 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 - -Editor_ToggleInsertMode_label=Sma&rt Insert Mode - -########################################################################## -# These strings are used in Workbench menu bar -########################################################################## -ExpandSelectionToMenu_label=E&xpand Selection To -SourceMenu_label=&Source -ConvertLineDelimitersMenu_label=Co&nvert Line Delimiters to -FindOccurrences_label=O&ccurrences in File -# -FindOccurrencesActionProvider_0=Current selection does not resolve to a searchable element -RemoveAction_0=Remove Property -ShowPropertiesAction_0=P&roperties -StructuredContentOutlineConfiguration_0=Collapse All -StructuredContentOutlineConfiguration_1=Link with Editor -AbstractOpenOn_0=Current text selection does not resolve to a file -FormatActionDelegate_jobName=Formatting documents -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} -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} -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=A&nalyze annotations while typing -StructuredTextEditorPreferencePage_37=Empty input -StructuredTextEditorPreferencePage_38=is not a valid input. -TaskTagPreferenceTab_0=High -TaskTagPreferenceTab_1=Low -TaskTagPreferenceTab_2=Normal -TaskTagPreferenceTab_3=N/A -TaskTagPreferenceTab_5=Task Tag -TaskTagPreferenceTab_6=Tag -TaskTagPreferenceTab_7=Priority -TaskTagPreferenceTab_8=High -TaskTagPreferenceTab_9=Normal -TaskTagPreferenceTab_10=Low -TaskTagPreferenceTab_12=Tag -TaskTagPreferenceTab_13=Priority -TaskTagPreferenceTab_14=New... -TaskTagPreferenceTab_15=Edit... -TaskTagPreferenceTab_16=Remove -TaskTagPreferenceTab_17=Move Up -TaskTagPreferenceTab_18=Move Down -TaskTagPreferenceTab_19=Note: changes may not be visible until the workspace is rebuilt -TaskTagPreferenceTab_20=Task Tags -TaskTagPreferenceTab_22=Task Tags Settings Changed -TaskTagPreferenceTab_23=The task tags settings have changed. A full rebuild is required to make changes effective. Do the full build now? -TaskTagPreferenceTab_24=Yes -TaskTagPreferenceTab_25=No -TaskTagPreferenceTab_26=Cancel -TaskTagPreferenceTab_27=Detecting tasks for task tags -TaskTagPreferenceTab_28=build aborted -TaskTagPreferenceTab_29=build completed -TaskTagPreferenceTab_30=build had errors -TaskTagPreferenceTab_31=Search for Task Tags -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_annotationRollover=&Enable annotation roll-over (on new editors) -TextHoverPreferenceTab_showAffordance=&Show affordance in hover on how to make it sticky -TextHoverPreferenceTab_hoverPreferences=Text &Hover key modifier preferences: -TextHoverPreferenceTab_enabled=&Enabled -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 -BasicFindOccurrencesAction_0=region match: -BasicSearchLabelProvider_0=line -PreferenceManager_0=Original Error: -NavigationPreferenceTab_0=Modifier ''{0}'' is not valid. -OccurrencesSearchQuery_0={0} - {1} Occurrences in {2} -OccurrencesSearchQuery_1={0} - 1 Occurrence in {1} -OccurrencesSearchQuery_2=file -FileModelProvider_0=Error reloading {0} -JFaceNodeAdapter_0=Update Outline -ShowView_errorTitle=Problems Showing View -proc_dirty_regions_0 = Processing Dirty Regions -## 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 -busy=busy -caret_update=caret update -EmptyFilePreferencePage_0=Expand the tree to edit preferences for a specific content type. -OffsetStatusLineContributionItem_0=Selection Information: -OffsetStatusLineContributionItem_2=Partitions -OffsetStatusLineContributionItem_3=ITextRegions -OffsetStatusLineContributionItem_4=Content-Type: -OffsetStatusLineContributionItem_5=Model Handler: -OffsetStatusLineContributionItem_8=Partitioning: -OffsetStatusLineContributionItem_9=Start -OffsetStatusLineContributionItem_10=Length -OffsetStatusLineContributionItem_11=Type -OffsetStatusLineContributionItem_13=Partitioner: -OffsetStatusLineContributionItem_14=Partitioner: -OffsetStatusLineContributionItem_15=Start -OffsetStatusLineContributionItem_16=Length -OffsetStatusLineContributionItem_17=Text Length -OffsetStatusLineContributionItem_18=Context 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 6e43f030c9..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, 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; - -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 89ff5ba9ea..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/StorageModelProvider.java +++ /dev/null @@ -1,648 +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; - -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.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.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.IStorageEditorInput; -import org.eclipse.ui.editors.text.FileDocumentProvider; -import org.eclipse.ui.editors.text.StorageDocumentProvider; -import org.eclipse.ui.texteditor.IElementStateListener; -import org.eclipse.wst.sse.core.IStructuredModel; -import org.eclipse.wst.sse.core.StructuredModelManager; -import org.eclipse.wst.sse.core.exceptions.SourceEditingRuntimeException; -import org.eclipse.wst.sse.core.internal.encoding.CodedReaderCreator; -import org.eclipse.wst.sse.core.internal.util.Utilities; -import org.eclipse.wst.sse.core.text.IStructuredDocument; -import org.eclipse.wst.sse.ui.extensions.breakpoint.IExtendedStorageEditorInput; -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; - -/** - * 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); - - /** - * 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 != null && 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 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; - boolean addHash = false; - try { - IStorage storage = input.getStorage(); - if (storage != null) { - IPath storagePath = storage.getFullPath(); - String name = storage.getName(); - // if either the name or storage path are null or they are - // identical, add a hash to it to guarantee uniqueness - addHash = storagePath == null || storagePath.toString().equals(name); - 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 = ""; //$NON-NLS-1$ - } - if (addHash) - path = input.hashCode() + path; - 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) - 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 SourceEditingRuntimeException(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(); - // } - } - - } - if (document == null) { - 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 { - new FileDocumentProvider().saveDocument(monitor, element, document, overwrite); - } - - 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(input.getName()); - } - 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/StructuredDocumentCommand.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/StructuredDocumentCommand.java deleted file mode 100644 index 51ed0e35b3..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/StructuredDocumentCommand.java +++ /dev/null @@ -1,500 +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; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import java.util.NoSuchElementException; - -import org.eclipse.jface.text.Assert; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.BadPositionCategoryException; -import org.eclipse.jface.text.DefaultPositionUpdater; -import org.eclipse.jface.text.DocumentCommand; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IDocumentListener; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.Position; -import org.eclipse.swt.events.VerifyEvent; - -/** - * TODO Temporary subclass to workaround BUG44665 - * - * Algorithm for intersects() methods changed. - */ -/** - * Represents a text modification as a document replace command. The text - * modification is given as a <code>VerifyEvent</code> and translated into a - * document replace command relative to a given offset. A document command can - * also be used to initialize a given <code>VerifyEvent</code>. - * <p> - * A document command can also represent a list of related changes. - */ -public class StructuredDocumentCommand extends DocumentCommand { - - /** - * A command which is added to document commands. - * - * @since 2.1 - */ - private static class Command implements Comparable { - /** The length of the range to be replaced. */ - final int fLength; - /** The offset of the range to be replaced */ - final int fOffset; - /** The listern who owns this command */ - private final IDocumentListener fOwner; - /** The replacement text */ - private final String fText; - - /** - * Creates a new command with the given specification. - * - * @param offset - * the offset of the replace command - * @param length - * the length of the replace command - * @param text - * the text to replace with, may be <code>null</code> - * @param owner - * the document command owner, may be <code>null</code> - * @since 3.0 - */ - public Command(int offset, int length, String text, IDocumentListener owner) { - if (offset < 0 || length < 0) - throw new IllegalArgumentException(); - fOffset = offset; - fLength = length; - fText = text; - fOwner = owner; - } - - /* - * @see java.util.Comparator#compare(java.lang.Object, - * java.lang.Object) - */ - public int compareTo(final Object object) { - if (equals(object)) - return 0; - - final Command command = (Command) object; - - // diff middle points if not intersecting - if (fOffset + fLength <= command.fOffset || command.fOffset + command.fLength <= fOffset) { - int value = (2 * fOffset + fLength) - (2 * command.fOffset + command.fLength); - if (value != 0) - return value; - } - // the answer - return 42; - } - - /* - * @see java.lang.Object#equals(java.lang.Object) - */ - public boolean equals(Object object) { - if (object == this) - return true; - if (!(object instanceof Command)) - return false; - final Command command = (Command) object; - return command.fOffset == fOffset && command.fLength == fLength; - } - - /** - * Executes the document command on the specified document. - * - * @param document - * the document on which to execute the command. - * @throws BadLocationException - * in case this commands cannot be executed - */ - public void execute(IDocument document) throws BadLocationException { - - if (fLength == 0 && fText == null) - return; - - if (fOwner != null) - document.removeDocumentListener(fOwner); - - document.replace(fOffset, fLength, fText); - - if (fOwner != null) - document.addDocumentListener(fOwner); - } - - /** - * Returns the length delta for this command. - * - * @return the length delta for this command - */ - public int getDeltaLength() { - return (fText == null ? 0 : fText.length()) - fLength; - } - } - - /** - * A command iterator. - */ - private static class CommandIterator implements Iterator { - - /** The original command. */ - private Command fCommand; - - /** A flag indicating the direction of iteration. */ - private boolean fForward; - - /** The command iterator. */ - private final Iterator fIterator; - - /** - * Creates a command iterator. - * - * @param commands - * an ascending ordered list of commands - * @param command - * the original command - * @param forward - * the direction - */ - public CommandIterator(final List commands, final Command command, final boolean forward) { - if (commands == null || command == null) - throw new IllegalArgumentException(); - fIterator = forward ? commands.iterator() : new ReverseListIterator(commands.listIterator(commands.size())); - fCommand = command; - fForward = forward; - } - - /* - * @see java.util.Iterator#hasNext() - */ - public boolean hasNext() { - return fCommand != null || fIterator.hasNext(); - } - - /* - * @see java.util.Iterator#next() - */ - public Object next() { - - if (!hasNext()) - throw new NoSuchElementException(); - - if (fCommand == null) - return fIterator.next(); - - if (!fIterator.hasNext()) { - final Command tempCommand = fCommand; - fCommand = null; - return tempCommand; - } - - final Command command = (Command) fIterator.next(); - final int compareValue = command.compareTo(fCommand); - - if ((compareValue < 0) ^ !fForward) { - return command; - - } else if ((compareValue > 0) ^ !fForward) { - final Command tempCommand = fCommand; - fCommand = command; - return tempCommand; - - } else { - throw new IllegalArgumentException(); - } - } - - /* - * @see java.util.Iterator#remove() - */ - public void remove() { - throw new UnsupportedOperationException(); - } - } - - /** - * An iterator, which iterates in reverse over a list. - */ - private static class ReverseListIterator implements Iterator { - - /** The list iterator. */ - private final ListIterator fListIterator; - - /** - * Creates a reverse list iterator. - * - * @param listIterator - * the iterator that this reverse iterator is based upon - */ - public ReverseListIterator(ListIterator listIterator) { - if (listIterator == null) - throw new IllegalArgumentException(); - fListIterator = listIterator; - } - - /* - * @see java.util.Iterator#hasNext() - */ - public boolean hasNext() { - return fListIterator.hasPrevious(); - } - - /* - * @see java.util.Iterator#next() - */ - public Object next() { - return fListIterator.previous(); - } - - /* - * @see java.util.Iterator#remove() - */ - public void remove() { - throw new UnsupportedOperationException(); - } - } - - /** - * Additional document commands. - * - * @since 2.1 - */ - private final List fCommands = new ArrayList(); - - /** - * Adds an additional replace command. The added replace command must not - * overlap with existing ones. If the document command owner is not - * <code>null</code>, it will not get document change notifications for - * the particular command. - * - * @param offset - * the offset of the region to replace - * @param length - * the length of the region to replace - * @param text - * the text to replace with, may be <code>null</code> - * @param owner - * the command owner, may be <code>null</code> - * @throws BadLocationException - * if the added command intersects with an existing one - * @since 2.1 - */ - public void addCommand(int offsetParameter, int lengthParameter, String textParameter, IDocumentListener ownerParameter) throws BadLocationException { - final Command command = new Command(offsetParameter, lengthParameter, textParameter, ownerParameter); - - internalAddCommand(command); - } - - /** - * @param command - * @throws BadLocationException - */ - private void internalAddCommand(final Command command) throws BadLocationException { - if (intersects(command)) - throw new BadLocationException(); - - final int index = Collections.binarySearch(fCommands, command); - - // a command with exactly the same ranges exists already - if (index >= 0) - throw new BadLocationException(); - - // binary search result is defined as (-(insertionIndex) - 1) - final int insertionIndex = -(index + 1); - - // overlaps to the right? - if (insertionIndex != fCommands.size() && intersects((Command) fCommands.get(insertionIndex), command)) - throw new BadLocationException(); - - // overlaps to the left? - if (insertionIndex != 0 && intersects((Command) fCommands.get(insertionIndex - 1), command)) - throw new BadLocationException(); - - fCommands.add(insertionIndex, command); - } - - /** - * Executes the document commands on a document. - * - * @param document - * the document on which to execute the commands - * @since 2.1 - */ - void executeStructuredDocumentCommand(IDocument document) throws BadLocationException { - - if (length == 0 && text == null && fCommands.size() == 0) - return; - - DefaultPositionUpdater updater = new DefaultPositionUpdater(getCategory()); - Position caretPosition = null; - try { - if (updateCaret()) { - document.addPositionCategory(getCategory()); - document.addPositionUpdater(updater); - caretPosition = new Position(caretOffset); - document.addPosition(getCategory(), caretPosition); - } - - final Command originalCommand = new Command(offset, length, text, owner); - for (final Iterator iterator = new CommandIterator(fCommands, originalCommand, false); iterator.hasNext();) - ((Command) iterator.next()).execute(document); - - } catch (BadLocationException e) { - // ignore - } catch (BadPositionCategoryException e) { - // ignore - } finally { - if (updateCaret()) { - document.removePositionUpdater(updater); - try { - document.removePositionCategory(getCategory()); - } catch (BadPositionCategoryException e) { - Assert.isTrue(false); - } - caretOffset = caretPosition.getOffset(); - } - } - } - - /** - * Fills the given verify event with the replace text and the doit flag of - * this document command. Returns whether the document command covers the - * same range as the verify event considering the given offset. - * - * @param event - * the event to be changed - * @param modelRange - * to be considered for range comparison - * @return <code>true</code> if this command and the event cover the - * same range - */ - public boolean fillEventStructuredDocumentCommand(VerifyEvent event, IRegion modelRange) { - event.text = text; - event.doit = (offset == modelRange.getOffset() && length == modelRange.getLength() && doit && caretOffset == -1); - return event.doit; - } - - /** - * Returns the position category for the caret offset position. - * - * @return the position category for the caret offset position - * @since 3.0 - */ - private String getCategory() { - return toString(); - } - - /** - * Returns the number of commands including the original document command. - * - * @return returns the number of commands - * @since 2.1 - */ - public int getCommandCount() { - return 1 + fCommands.size(); - } - - /** - * Returns an iterator over the commands in ascending position order. The - * iterator includes the original document command. Commands cannot be - * removed. - * - * @return returns the command iterator - */ - public Iterator getCommandIterator() { - Command command = new Command(offset, length, text, owner); - return new CommandIterator(fCommands, command, true); - } - - /** - * Returns whether the given command intersects with this command. - * - * @param command - * the command - * @return <code>true</code> if the command intersects with this command - * @since 2.1 - */ - private boolean intersects(Command command) { - boolean result = false; - // diff middle points if not intersecting - if (offset + length <= command.fOffset || command.fOffset + command.fLength <= offset) - // return (2 * offset + length) - (2 * command.fOffset + - // command.fLength) == 0; - result = false; - else - result = true; - return result; - } - - /** - * Returns whether the two given commands intersect. - * - * @param command0 - * the first command - * @param command1 - * the second command - * @return <code>true</code> if the commands intersect - * @since 2.1 - */ - private boolean intersects(Command command0, Command command1) { - boolean result = false; - // diff middle points if not intersecting - if (command0.fOffset + command0.fLength <= command1.fOffset || command1.fOffset + command1.fLength <= command0.fOffset) - // return (2 * command0.fOffset + command0.fLength) - (2 * - // command1.fOffset + command1.fLength) == 0; - result = false; - else - result = true; - return result; - } - - /** - * Translates a verify event into a document replace command using the - * given offset. - * - * @param event - * the event to be translated - * @param modelRange - * the event range as model range - */ - public void setEventStructuredDocumentEvent(VerifyEvent event, IRegion modelRange) { - - doit = true; - text = event.text; - - offset = modelRange.getOffset(); - length = modelRange.getLength(); - - owner = null; - caretOffset = -1; - shiftsCaret = true; - fCommands.clear(); - } - - /** - * Returns <code>true</code> if the caret offset should be updated, - * <code>false</code> otherwise. - * - * @return <code>true</code> if the caret offset should be updated, - * <code>false</code> otherwise - * @since 3.0 - */ - private boolean updateCaret() { - return shiftsCaret && caretOffset != -1; - } - -} 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 34766d5941..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, 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; - -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.events.IStructuredDocumentListener; -import org.eclipse.wst.sse.core.events.NewDocumentEvent; -import org.eclipse.wst.sse.core.events.NoChangeEvent; -import org.eclipse.wst.sse.core.events.RegionChangedEvent; -import org.eclipse.wst.sse.core.events.RegionsReplacedEvent; -import org.eclipse.wst.sse.core.events.StructuredDocumentEvent; -import org.eclipse.wst.sse.core.events.StructuredDocumentRegionsReplacedEvent; -import org.eclipse.wst.sse.core.exceptions.SourceEditingRuntimeException; -import org.eclipse.wst.sse.core.internal.ILockable; -import org.eclipse.wst.sse.core.internal.util.Debug; -import org.eclipse.wst.sse.core.internal.util.Utilities; -import org.eclipse.wst.sse.core.text.IStructuredDocument; -import org.eclipse.wst.sse.core.text.IStructuredDocumentRegion; -import org.eclipse.wst.sse.core.text.IStructuredDocumentRegionList; -import org.eclipse.wst.sse.core.text.ITextRegion; -import org.eclipse.wst.sse.core.text.ITextRegionList; -import org.eclipse.wst.sse.ui.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); - 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() - * @since 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) { - throw new SourceEditingRuntimeException(e); - } - } - - /** - * 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 x) { - throw new SourceEditingRuntimeException(x); - } - } - - /** - * @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 - * com.ibm.sed.structuredDocument.IStructuredDocument - */ - 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 fa5dc3366a..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, 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; - -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...) - * - * @author pavery - */ -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 f4974990bc..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/StructuredMarkerAnnotation.java +++ /dev/null @@ -1,130 +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; - - -import org.eclipse.core.resources.IMarker; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.debug.core.model.IBreakpoint; -import org.eclipse.debug.ui.DebugUITools; -import org.eclipse.debug.ui.IDebugModelPresentation; -import org.eclipse.search.ui.SearchUI; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.widgets.Display; -import org.eclipse.ui.texteditor.MarkerAnnotation; -import org.eclipse.ui.texteditor.MarkerUtilities; -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 { - // private static final int ORIGINAL_MARKER_IMAGE= 1; - // private static final int QUICKFIX_IMAGE= 2; - // private static final int QUICKFIX_ERROR_IMAGE= 3; - // private static final int OVERLAY_IMAGE= 4; - // private static final int GRAY_IMAGE= 5; - private static final int BREAKPOINT_IMAGE = 6; - - private static final int NO_IMAGE = 0; - private int fImageType; - private IDebugModelPresentation fPresentation; - - // TODO: private field never read loacally - String fType = null; - - /** - * Constructor - * - * @param marker - */ - StructuredMarkerAnnotation(IMarker marker) { - super(marker); - // sets fType, for use w/ StructuredAnnotationAccess - initAnnotationType(); - } - - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.MarkerAnnotation#getImage(org.eclipse.swt.widgets.Display) - */ - protected Image getImage(Display display) { - if (fImageType == BREAKPOINT_IMAGE) { - Image result = super.getImage(display); - if (result == null) { - IMarker marker = getMarker(); - if (marker != null && marker.exists()) { - result = fPresentation.getImage(getMarker()); - setImage(result); - } - } - return result; - } - return super.getImage(display); - } - - /** - * Initializes the annotation's icon representation and its drawing layer - * based upon the properties of the underlying marker. - */ - protected void initAnnotationType() { - // fQuickFixIconEnabled= - // PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_CORRECTION_INDICATION); - fImageType = NO_IMAGE; - IMarker marker = getMarker(); - if (MarkerUtilities.isMarkerType(marker, IBreakpoint.BREAKPOINT_MARKER)) { - - if (fPresentation == null) - fPresentation = DebugUITools.newDebugModelPresentation(); - - setImage(null); // see bug 32469 - setLayer(4); - fImageType = BREAKPOINT_IMAGE; - - fType = TemporaryAnnotation.ANNOT_UNKNOWN; - - } else { - fType = TemporaryAnnotation.ANNOT_UNKNOWN; - try { - if (marker.isSubtypeOf(IMarker.PROBLEM)) { - int severity = marker.getAttribute(IMarker.SEVERITY, -1); - switch (severity) { - case IMarker.SEVERITY_ERROR : - fType = TemporaryAnnotation.ANNOT_ERROR; - break; - case IMarker.SEVERITY_WARNING : - fType = TemporaryAnnotation.ANNOT_WARNING; - break; - case IMarker.SEVERITY_INFO : - fType = TemporaryAnnotation.ANNOT_INFO; - break; - } - } else if (marker.isSubtypeOf(IMarker.TASK)) - fType = TemporaryAnnotation.ANNOT_TASK; - else if (marker.isSubtypeOf(SearchUI.SEARCH_MARKER)) { - fType = TemporaryAnnotation.ANNOT_SEARCH; - } else if (marker.isSubtypeOf(IMarker.BOOKMARK)) - fType = TemporaryAnnotation.ANNOT_BOOKMARK; - - } 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 febbc05a48..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/StructuredResourceMarkerAnnotationModel.java +++ /dev/null @@ -1,97 +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; - -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.ResourceMarkerAnnotationModel; -import org.eclipse.wst.sse.ui.extensions.breakpoint.IBreakpointConstants; - - -/** - * Source editor resource marker annotation model implementation - */ -public class StructuredResourceMarkerAnnotationModel extends ResourceMarkerAnnotationModel { - 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) { - return new StructuredMarkerAnnotation(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) attr).equals(Boolean.TRUE)) - 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 4844776495..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, 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; - -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 5fb26f61e3..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/StructuredTextAnnotationHover.java +++ /dev/null @@ -1,382 +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; - -import java.io.IOException; -import java.io.Reader; -import java.io.StringReader; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.eclipse.core.resources.IMarker; -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.DebugUITools; -import org.eclipse.debug.ui.IDebugModelPresentation; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.Position; -import org.eclipse.jface.text.source.Annotation; -import org.eclipse.jface.text.source.IAnnotationHover; -import org.eclipse.jface.text.source.IAnnotationModel; -import org.eclipse.jface.text.source.ISourceViewer; -import org.eclipse.swt.graphics.GC; -import org.eclipse.swt.graphics.Rectangle; -import org.eclipse.swt.widgets.Display; -import org.eclipse.ui.texteditor.MarkerAnnotation; -import org.eclipse.wst.sse.core.internal.util.StringUtils; - -public class StructuredTextAnnotationHover implements IAnnotationHover, IReleasable { - - /** - * Provides a set of convenience methods for creating HTML pages. Taken - * from org.eclipse.jdt.internal.ui.text.HTMLPrinter - */ - protected class HTMLPrinter { - - public HTMLPrinter() { - } - - public void addBullet(StringBuffer buffer, String bullet) { - if (bullet != null) { - buffer.append("<li>"); //$NON-NLS-1$ - buffer.append(bullet); - buffer.append("</li>"); //$NON-NLS-1$ - } - } - - public void addPageEpilog(StringBuffer buffer) { - buffer.append("</font></body></html>"); //$NON-NLS-1$ - } - - public void addPageProlog(StringBuffer buffer) { - insertPageProlog(buffer, buffer.length()); - } - - public void addParagraph(StringBuffer buffer, Reader paragraphReader) { - if (paragraphReader != null) - addParagraph(buffer, read(paragraphReader)); - } - - public void addParagraph(StringBuffer buffer, String paragraph) { - if (paragraph != null) { - buffer.append("<p>"); //$NON-NLS-1$ - buffer.append(paragraph); - } - } - - public void addSmallHeader(StringBuffer buffer, String header) { - if (header != null) { - buffer.append("<h5>"); //$NON-NLS-1$ - buffer.append(header); - buffer.append("</h5>"); //$NON-NLS-1$ - } - } - - public String convertToHTMLContent(String content) { - content = replace(content, '<', "<"); //$NON-NLS-1$ - return replace(content, '>', ">"); //$NON-NLS-1$ - } - - public void endBulletList(StringBuffer buffer) { - buffer.append("</ul>"); //$NON-NLS-1$ - } - - public void insertPageProlog(StringBuffer buffer, int position) { - buffer.insert(position, "<html><body text=\"#000000\" bgcolor=\"#FFFF88\"><font size=-1>"); //$NON-NLS-1$ - } - - public String read(Reader rd) { - - StringBuffer buffer = new StringBuffer(); - char[] readBuffer = new char[2048]; - - try { - int n = rd.read(readBuffer); - while (n > 0) { - buffer.append(readBuffer, 0, n); - n = rd.read(readBuffer); - } - return buffer.toString(); - } catch (IOException x) { - } - - return null; - } - - private String replace(String text, char c, String s) { - - int previous = 0; - int current = text.indexOf(c, previous); - - if (current == -1) - return text; - - StringBuffer buffer = new StringBuffer(); - while (current > -1) { - buffer.append(text.substring(previous, current)); - buffer.append(s); - previous = current + 1; - current = text.indexOf(c, previous); - } - buffer.append(text.substring(previous)); - - return buffer.toString(); - } - - public void startBulletList(StringBuffer buffer) { - buffer.append("<ul>"); //$NON-NLS-1$ - } - } - - private IDebugModelPresentation fDebugModelPresentation; - - protected HTMLPrinter printer = new HTMLPrinter(); - - /** - * Returns the distance to the ruler line. - */ - protected int compareRulerLine(Position position, IDocument document, int line) { - - if (position.getOffset() > -1 && position.getLength() > -1) { - try { - int markerLine = document.getLineOfOffset(position.getOffset()); - if (line == markerLine) - return 1; - if (markerLine <= line && line <= document.getLineOfOffset(position.getOffset() + position.getLength())) - return 2; - } catch (BadLocationException x) { - } - } - - return 0; - } - - /* - * Formats the message of this hover to fit onto the screen. - */ - private String formatHoverText(String text, ISourceViewer sourceViewer) { - String lineDelim = new String(); - try { - lineDelim = sourceViewer.getDocument().getLineDelimiter(0); - } catch (org.eclipse.jface.text.BadLocationException exception) { - // skip, just use default - } - Display display = sourceViewer.getTextWidget().getDisplay(); - - // replace special characters in text with html entity (like <, >, & - // to <, >, &&;) - text = StringUtils.convertToHTMLContent(text); - - Reader textReader = new StringReader(text); - GC gc = new GC(display); - try { - StringBuffer buf = new StringBuffer(); - - StructuredTextLineBreakingReader reader = new StructuredTextLineBreakingReader(textReader, gc, getHoverWidth(display)); - String line = reader.readLine(); - while (line != null) { - if (buf.length() != 0) { - buf.append(lineDelim); - } - buf.append(line); - line = reader.readLine(); - } - return buf.toString(); - } catch (IOException exception) { - throw new org.eclipse.wst.sse.core.exceptions.SourceEditingRuntimeException(exception); - } finally { - gc.dispose(); - } - } - - /* - * Formats several message as HTML text. - */ - private String formatMultipleHoverText(List messages) { - - StringBuffer buffer = new StringBuffer(); - printer.addPageProlog(buffer); - printer.addParagraph(buffer, SSEUIMessages.Multiple_errors); //$NON-NLS-1$ - - printer.startBulletList(buffer); - Iterator e = messages.iterator(); - while (e.hasNext()) - printer.addBullet(buffer, printer.convertToHTMLContent((String) e.next())); - printer.endBulletList(buffer); - - printer.addPageEpilog(buffer); - return buffer.toString(); - } - - /** - * @see IVerticalRulerHover#getHoverInfo(ISourceViewer, int) - */ - public String getHoverInfo(ISourceViewer sourceViewer, int lineNumber) { - IMarker marker = getMarker(sourceViewer, lineNumber); - List messages = new ArrayList(marker == null ? 0 : 1); - if (marker != null) { - String text = marker.getAttribute(IMarker.MESSAGE, (String) null); - if (text != null) { - messages.add(text); - } else { - try { - if (marker.isSubtypeOf(IBreakpoint.BREAKPOINT_MARKER)) { - IBreakpointManager manager = DebugPlugin.getDefault().getBreakpointManager(); - IBreakpoint[] breakpoints = manager.getBreakpoints(); - for (int i = 0; i < breakpoints.length; i++) { - IBreakpoint breakpoint = breakpoints[i]; - if (breakpoint.getMarker().equals(marker)) { - if (fDebugModelPresentation == null) { - fDebugModelPresentation = DebugUITools.newDebugModelPresentation(); - } - text = fDebugModelPresentation.getText(breakpoint); - if (text != null) { - messages.add(text); - } - } - } - } - } catch (CoreException e) { - Logger.logException(e); - } - } - } - List temporaryAnnotations = getTemporaryAnnotationsForLine(sourceViewer, lineNumber); - for (int i = 0; i < temporaryAnnotations.size(); i++) { - String message = ((Annotation) temporaryAnnotations.get(i)).getText(); - if (message != null) { - boolean duplicated = false; - for (int j = 0; j < messages.size(); j++) - duplicated = duplicated || messages.get(j).equals(message); - if (!duplicated) - messages.add(message); - // else - // System.out.println("duplicated message found: " + - // StringUtils.escape(message)); - } else - messages.add(((ITemporaryAnnotation) temporaryAnnotations.get(i)).toString()); - } - if (messages.size() > 1) - return formatMultipleHoverText(messages); - else if (messages.size() > 0) - return formatHoverText(messages.get(0).toString(), sourceViewer); - else - return null; - } - - private int getHoverWidth(Display display) { - Rectangle displayBounds = display.getBounds(); - int hoverWidth = displayBounds.width - (display.getCursorLocation().x - displayBounds.x); - hoverWidth -= 12; // XXX: Add some space to the border, Revisit - if (hoverWidth < 200) { - hoverWidth = 200; - } - return hoverWidth; - } - - /** - * Returns one marker which includes the ruler's line of activity. - */ - protected IMarker getMarker(ISourceViewer viewer, int line) { - - IDocument document = viewer.getDocument(); - IAnnotationModel model = viewer.getAnnotationModel(); - - if (model == null) - return null; - - List exact = new ArrayList(); - List including = new ArrayList(); - - Iterator e = model.getAnnotationIterator(); - while (e.hasNext()) { - Object o = e.next(); - if (o instanceof MarkerAnnotation) { - MarkerAnnotation a = (MarkerAnnotation) o; - switch (compareRulerLine(model.getPosition(a), document, line)) { - case 1 : - exact.add(a.getMarker()); - break; - case 2 : - including.add(a.getMarker()); - break; - } - } - } - - return select(exact, including); - } - - /** - * Returns one marker which includes the ruler's line of activity. - */ - protected List getTemporaryAnnotationsForLine(ISourceViewer viewer, int line) { - - IDocument document = viewer.getDocument(); - IAnnotationModel model = viewer.getAnnotationModel(); - - if (model == null) - return null; - - List exact = new ArrayList(); - List including = new ArrayList(); - - Iterator e = model.getAnnotationIterator(); - while (e.hasNext()) { - Object o = e.next(); - if (o instanceof ITemporaryAnnotation) { - ITemporaryAnnotation a = (ITemporaryAnnotation) o; - Position position = model.getPosition((Annotation) a); - if (position == null) - continue; - - switch (compareRulerLine(position, document, line)) { - case 1 : - exact.add(a); - break; - case 2 : - including.add(a); - break; - } - } - } - - return exact; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.sse.ui.IReleasable#release() - */ - public void release() { - if (fDebugModelPresentation != null) { - fDebugModelPresentation.dispose(); - } - } - - /** - * Selects one marker from the two lists. - */ - protected IMarker select(List firstChoice, List secondChoice) { - if (!firstChoice.isEmpty()) - return (IMarker) firstChoice.get(0); - if (!secondChoice.isEmpty()) - return (IMarker) secondChoice.get(0); - return null; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/StructuredTextEditor.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/StructuredTextEditor.java deleted file mode 100644 index dd18ffbf4c..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/StructuredTextEditor.java +++ /dev/null @@ -1,2744 +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; - -import java.io.IOException; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.List; -import java.util.ResourceBundle; -import java.util.Timer; -import java.util.TimerTask; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IMarker; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.IStorage; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.ILog; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Path; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.Preferences; -import org.eclipse.core.runtime.Status; -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.GroupMarker; -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.dialogs.ErrorDialog; -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.text.DefaultInformationControl; -import org.eclipse.jface.text.DocumentEvent; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IDocumentListener; -import org.eclipse.jface.text.IInformationControl; -import org.eclipse.jface.text.IInformationControlCreator; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ITextHover; -import org.eclipse.jface.text.ITextOperationTarget; -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.source.Annotation; -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.osgi.util.NLS; -import org.eclipse.swt.custom.StyledText; -import org.eclipse.swt.dnd.DND; -import org.eclipse.swt.dnd.DropTarget; -import org.eclipse.swt.events.DisposeEvent; -import org.eclipse.swt.events.DisposeListener; -import org.eclipse.swt.events.MouseEvent; -import org.eclipse.swt.events.MouseMoveListener; -import org.eclipse.swt.events.MouseTrackAdapter; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Display; -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.IStorageEditorInput; -import org.eclipse.ui.IWorkbenchActionConstants; -import org.eclipse.ui.IWorkbenchPage; -import org.eclipse.ui.IWorkbenchWindow; -import org.eclipse.ui.PartInitException; -import org.eclipse.ui.PlatformUI; -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.help.IWorkbenchHelpSystem; -import org.eclipse.ui.part.EditorActionBarContributor; -import org.eclipse.ui.part.IShowInTargetList; -import org.eclipse.ui.progress.IWorkbenchSiteProgressService; -import org.eclipse.ui.texteditor.AnnotationPreference; -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.IDocumentProviderExtension; -import org.eclipse.ui.texteditor.IElementStateListener; -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.IUpdate; -import org.eclipse.ui.texteditor.IWorkbenchActionDefinitionIds; -import org.eclipse.ui.texteditor.MarkerRulerAction; -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.IModelStateListener; -import org.eclipse.wst.sse.core.INodeNotifier; -import org.eclipse.wst.sse.core.IStructuredModel; -import org.eclipse.wst.sse.core.IndexedRegion; -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.text.IExecutionDelegatable; -import org.eclipse.wst.sse.core.internal.util.StringUtils; -import org.eclipse.wst.sse.core.text.IStructuredDocument; -import org.eclipse.wst.sse.core.text.IStructuredDocumentRegion; -import org.eclipse.wst.sse.core.text.ITextRegion; -import org.eclipse.wst.sse.core.undo.IStructuredTextUndoManager; -import org.eclipse.wst.sse.ui.StructuredTextViewerConfiguration; -import org.eclipse.wst.sse.ui.extension.ExtendedConfigurationBuilder; -import org.eclipse.wst.sse.ui.extension.ExtendedEditorActionBuilder; -import org.eclipse.wst.sse.ui.extension.ExtendedEditorDropTargetAdapter; -import org.eclipse.wst.sse.ui.extension.IExtendedContributor; -import org.eclipse.wst.sse.ui.extension.IExtendedMarkupEditor; -import org.eclipse.wst.sse.ui.extension.IPopupMenuContributor; -import org.eclipse.wst.sse.ui.extensions.ConfigurationPointCalculator; -import org.eclipse.wst.sse.ui.extensions.breakpoint.NullSourceEditingTextTools; -import org.eclipse.wst.sse.ui.extensions.breakpoint.SourceEditingTextTools; -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.StructuredTextEditorContentOutlinePage; -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.editor.EditorExecutionContext; -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.StructuredModelDocumentProvider; -import org.eclipse.wst.sse.ui.internal.extension.BreakpointProviderBuilder; -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.IStructuredTextFoldingProvider; -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.selection.SelectionHistory; -import org.eclipse.wst.sse.ui.internal.selection.StructureSelectEnclosingAction; -import org.eclipse.wst.sse.ui.internal.selection.StructureSelectHistoryAction; -import org.eclipse.wst.sse.ui.internal.selection.StructureSelectNextAction; -import org.eclipse.wst.sse.ui.internal.selection.StructureSelectPreviousAction; -import org.eclipse.wst.sse.ui.text.DocumentRegionEdgeMatcher; -import org.eclipse.wst.sse.ui.util.Assert; -import org.eclipse.wst.sse.ui.views.contentoutline.ContentOutlineConfiguration; -import org.eclipse.wst.sse.ui.views.contentoutline.StructuredContentOutlineConfiguration; -import org.eclipse.wst.sse.ui.views.properties.PropertySheetConfiguration; -import org.eclipse.wst.sse.ui.views.properties.StructuredPropertySheetConfiguration; -import org.w3c.dom.Document; -import org.w3c.dom.Node; - -public class StructuredTextEditor extends TextEditor implements IExtendedMarkupEditor, IDocumentListener { - - class InternalElementStateListener implements IElementStateListener { - - public void elementContentAboutToBeReplaced(Object element) { - // we just forward the event - handleElementContentAboutToBeReplaced(element); - } - - public void elementContentReplaced(Object element) { - // we just forward the event - handleElementContentReplaced(element); - } - - public void elementDeleted(Object element) { - // we just forward the event - handleElementDeleted(element); - } - - public void elementDirtyStateChanged(Object element, boolean isDirty) { - // we just forward the event - handleElementDirtyStateChanged(element, isDirty); - } - - public void elementMoved(Object originalElement, Object movedElement) { - // we just forward the event - handleElementMoved(originalElement, movedElement); - } - } - - 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(); - SourceViewerConfiguration config = getSourceViewerConfiguration(); - if (config instanceof StructuredTextViewerConfiguration) { - ((StructuredTextViewerConfiguration) config).unConfigure(getSourceViewer()); - } - } - } - - public void modelChanged(IStructuredModel model) { - if (getTextViewer() != 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(); - if (cfg != null && cfg instanceof StructuredTextViewerConfiguration) { - initializeSourceViewerConfiguration(((StructuredTextViewerConfiguration) cfg)); - } - 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); - } - } - - // 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); - } - } - } - - class MouseTracker extends MouseTrackAdapter implements MouseMoveListener { - /** The tracker's subject control. */ - private Control fSubjectControl; - - /** - * Creates a new mouse tracker. - */ - public MouseTracker() { - // do nothing - } - - public void mouseHover(MouseEvent event) { - // System.out.println("hover: "+event.x + "x" + event.y); - hoverX = event.x; - hoverY = event.y; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.swt.events.MouseMoveListener#mouseMove(org.eclipse.swt.events.MouseEvent) - */ - public void mouseMove(MouseEvent e) { - hoverX = e.x; - hoverY = e.y; - } - - /** - * Starts this mouse tracker. The given control becomes this tracker's - * subject control. Installs itself as mouse track listener on the - * subject control. - * - * @param subjectControl - * the subject control - */ - public void start(Control subjectControl) { - fSubjectControl = subjectControl; - if (fSubjectControl != null && !fSubjectControl.isDisposed()) { - fSubjectControl.addMouseMoveListener(this); - fSubjectControl.addMouseTrackListener(this); - fSubjectControl.addDisposeListener(new DisposeListener() { - public void widgetDisposed(DisposeEvent e) { - stop(); - } - }); - } - } - - /** - * Stops this mouse tracker. Removes itself as mouse track, mouse - * move, and shell listener from the subject control. - */ - public void stop() { - if (fSubjectControl != null && !fSubjectControl.isDisposed()) { - fSubjectControl.removeMouseMoveListener(this); - fSubjectControl.removeMouseTrackListener(this); - fSubjectControl = null; - } - } - } - - 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; - } - } - - class TimeOutExpired extends TimerTask { - - public void run() { - getDisplay().syncExec(new Runnable() { - public void run() { - if (getDisplay() != null && !getDisplay().isDisposed()) - endBusyStateInternal(); - } - }); - } - - } - - protected final static char[] BRACKETS = {'{', '}', '(', ')', '[', ']'}; - private static final long BUSY_STATE_DELAY = 1000; - public static final String CORE_SSE_ACTIVITY_ID = "com.ibm.wtp.xml.core"; //$NON-NLS-1$ - protected static final String DOT = "."; //$NON-NLS-1$ - private final static String UNDERSCORE = "_"; //$NON-NLS-1$ - private static final String EDITOR_CONTEXT_MENU_ID = "org.eclipse.wst.sse.ui.StructuredTextEditor.context"; //$NON-NLS-1$ - - /** Non-NLS strings */ - private static final String EDITOR_KEYBINDING_SCOPE_ID = "org.eclipse.wst.sse.ui.structuredTextEditorScope"; //$NON-NLS-1$ - public static final String GROUP_NAME_ADDITIONS = "additions"; //$NON-NLS-1$ - public static final String GROUP_NAME_FORMAT = "Format"; //$NON-NLS-1$ - public static final String GROUP_NAME_FORMAT_EXT = "Format.ext"; //$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" - protected static final String SSE_MODEL_ID = "org.eclipse.wst.sse.core"; //$NON-NLS-1$ - /** - * Constant for representing an error status. This is considered a value - * object. - */ - static final protected IStatus STATUS_ERROR = new Status(IStatus.ERROR, SSEUIPlugin.ID, IStatus.INFO, "ERROR", null); //$NON-NLS-1$ - /** - * Constant for representing an ok status. This is considered a value - * object. - */ - static final protected IStatus STATUS_OK = new Status(IStatus.OK, SSEUIPlugin.ID, IStatus.OK, "OK", null); //$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" - - /** - * @param args - * java.lang.String[] - */ - public static void main(String[] args) { - StructuredTextEditor editor = null; - try { - editor = new StructuredTextEditor(); - System.out.println("Created: " + editor); //$NON-NLS-1$ - } catch (Exception e) { - e.printStackTrace(); - } - } - - // development time/debug variables only - private int adapterRequests; - private long adapterTime; - private boolean fBackgroundJobEnded; - private boolean fBusyState; - private Timer fBusyTimer; - Runnable fCurrentRunnable = null; - boolean fDirtyBeforeDocumentEvent = false; - protected ExtendedEditorDropTargetAdapter fDropAdapter; - protected DropTarget fDropTarget; - protected boolean fEditorDisposed = false; - private IEditorPart fEditorPart; - private InternalModelStateListener fInternalModelStateListener; - - protected MouseTracker fMouseTracker; - protected IContentOutlinePage fOutlinePage; - /** This editor's projection model updater */ - private IStructuredTextFoldingProvider fProjectionModelUpdater; - /** This editor's projection support */ - private ProjectionSupport fProjectionSupport; - protected IPropertySheetPage fPropertySheetPage; - private String fRememberTitle; - String[] fShowInTargetIds = new String[]{IPageLayout.ID_RES_NAV}; - private IAction fShowPropertiesAction = null; - private IStructuredModel fStructuredModel; - - private boolean fUpdateMenuTextPending; - protected int hoverX = -1; - protected int hoverY = -1; - private InternalElementStateListener internalElementStateListener = new InternalElementStateListener(); - private boolean shouldClose = false; - private long startPerfTime; - - public StructuredTextEditor() { - - super(); - initializeDocumentProvider(null); - } - - /* - * This method is just to make firePropertyChanged accessbible from some - * (anonomous) inner classes. - */ - protected void _firePropertyChange(int property) { - super.firePropertyChange(property); - } - - protected void abstractTextEditorContextMenuAboutToShow(IMenuManager menu) { - menu.add(new Separator(ITextEditorActionConstants.GROUP_UNDO)); - menu.add(new Separator(ITextEditorActionConstants.GROUP_COPY)); - menu.add(new Separator(ITextEditorActionConstants.GROUP_PRINT)); - menu.add(new Separator(ITextEditorActionConstants.GROUP_EDIT)); - menu.add(new Separator(ITextEditorActionConstants.GROUP_FIND)); - menu.add(new Separator(IWorkbenchActionConstants.GROUP_ADD)); - menu.add(new Separator(ITextEditorActionConstants.GROUP_REST)); - menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); - menu.add(new Separator(ITextEditorActionConstants.GROUP_SAVE)); - - if (isEditable()) { - addAction(menu, ITextEditorActionConstants.GROUP_UNDO, ITextEditorActionConstants.UNDO); - addAction(menu, ITextEditorActionConstants.GROUP_UNDO, ITextEditorActionConstants.REVERT_TO_SAVED); - addAction(menu, ITextEditorActionConstants.GROUP_COPY, ITextEditorActionConstants.CUT); - addAction(menu, ITextEditorActionConstants.GROUP_COPY, ITextEditorActionConstants.COPY); - addAction(menu, ITextEditorActionConstants.GROUP_COPY, ITextEditorActionConstants.PASTE); - addAction(menu, ITextEditorActionConstants.GROUP_SAVE, ITextEditorActionConstants.SAVE); - } else { - addAction(menu, ITextEditorActionConstants.GROUP_COPY, ITextEditorActionConstants.COPY); - } - - // from AbstractDecoratedTextEditor - IAction preferencesAction = getAction(ITextEditorActionConstants.CONTEXT_PREFERENCES); - menu.appendToGroup(IWorkbenchActionConstants.MB_ADDITIONS, new Separator(ITextEditorActionConstants.GROUP_SETTINGS)); - menu.appendToGroup(ITextEditorActionConstants.GROUP_SETTINGS, preferencesAction); - } - - protected void addContextMenuActions(IMenuManager menu) { - // Only offer actions that affect the text if the viewer allows - // modification and supports any of these operations - IAction formatAll = getAction(StructuredTextEditorActionConstants.ACTION_NAME_FORMAT_DOCUMENT); - IAction formatSelection = getAction(StructuredTextEditorActionConstants.ACTION_NAME_FORMAT_ACTIVE_ELEMENTS); - IAction cleanupAll = getAction(StructuredTextEditorActionConstants.ACTION_NAME_CLEANUP_DOCUMENT); - boolean enableFormatMenu = (formatAll != null && formatAll.isEnabled()) || (formatSelection != null && formatSelection.isEnabled()) || (cleanupAll != null && cleanupAll.isEnabled()); - - if (getSourceViewer().isEditable() && enableFormatMenu) { - String label = SSEUIMessages.FormatMenu_label; //$NON-NLS-1$ = "Format" - MenuManager subMenu = new MenuManager(label, GROUP_NAME_FORMAT); - subMenu.add(new GroupMarker(GROUP_NAME_FORMAT_EXT)); - addAction(subMenu, StructuredTextEditorActionConstants.ACTION_NAME_FORMAT_DOCUMENT); - addAction(subMenu, StructuredTextEditorActionConstants.ACTION_NAME_FORMAT_ACTIVE_ELEMENTS); - subMenu.add(new GroupMarker(GROUP_NAME_ADDITIONS)); - addAction(menu, ITextEditorActionConstants.GROUP_EDIT, StructuredTextEditorActionConstants.ACTION_NAME_CLEANUP_DOCUMENT); - menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, subMenu); - } - - // Some Design editors (DTD) rely on this view for their own uses - menu.appendToGroup(IWorkbenchActionConstants.GROUP_ADD, fShowPropertiesAction); - } - - protected 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 - } - - - - /** - * - */ - public 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); - } - - // private void addFindOccurrencesAction(String matchType, String - // matchText, IMenuManager menu) { - // - // AbstractFindOccurrencesAction action = new - // AbstractFindOccurrencesAction(getFileInEditor(), new - // SearchUIConfiguration(), (IStructuredDocument) getDocument(), - // matchType, matchText, getProgressMonitor()); - // action.setText("Occurrences of \"" + matchText + "\" in File"); - // menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, action); - // } - - /** - * Instead of us closing directly, we have to close with our containing - * (multipage) editor, if it exists. - */ - public void close(final boolean save) { - 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); - } - } - } - - /* - * (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 source editor, depending on - * the input. - */ - protected void computeAndSetDoubleClickAction(IStructuredModel model) { - if (model == null) - return; - // If we're editing a breakpoint-supported input, make double-clicking - // on the ruler toggle a breakpoint instead of toggling a bookmark. - String ext = BreakpointRulerAction.getFileExtension(getEditorInput()); - if (BreakpointProviderBuilder.getInstance().isAvailable(model.getContentTypeIdentifier(), ext)) { - 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$ - } - } - - /* - * (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, true); //$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, true); //$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, true); //$NON-NLS-1$ - action.setActionDefinitionId(IWorkbenchActionDefinitionIds.DELETE); - setAction(ITextEditorActionConstants.DELETE, action); - helpSystem.setHelp(action, IAbstractTextEditorHelpContextIds.DELETE_ACTION); - // SourceView Action - requesting information at - // the current insertion - // position - action = new TextOperationAction(SSEUIMessages.getResourceBundle(), StructuredTextEditorActionConstants.ACTION_NAME_INFORMATION + UNDERSCORE, this, ISourceViewer.INFORMATION, true); - action.setActionDefinitionId(ActionDefinitionIds.INFORMATION); - setAction(StructuredTextEditorActionConstants.ACTION_NAME_INFORMATION, action); - markAsStateDependentAction(StructuredTextEditorActionConstants.ACTION_NAME_INFORMATION, true); - // 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, true); - 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 - // correction assist to show - // correction proposals for the current position - action = new TextOperationAction(resourceBundle, StructuredTextEditorActionConstants.ACTION_NAME_QUICK_FIX + UNDERSCORE, this, StructuredTextViewer.QUICK_FIX, true); - action.setActionDefinitionId(ActionDefinitionIds.QUICK_FIX); - setAction(StructuredTextEditorActionConstants.ACTION_NAME_QUICK_FIX, action); - markAsStateDependentAction(StructuredTextEditorActionConstants.ACTION_NAME_QUICK_FIX, 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 - 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); - - fShowPropertiesAction = new ShowPropertiesAction(); - - SelectionHistory selectionHistory = new SelectionHistory(this); - action = new StructureSelectEnclosingAction(this, selectionHistory); - action.setActionDefinitionId(ActionDefinitionIds.STRUCTURE_SELECT_ENCLOSING); - setAction(StructuredTextEditorActionConstants.ACTION_NAME_STRUCTURE_SELECT_ENCLOSING, action); - - action = new StructureSelectNextAction(this, selectionHistory); - action.setActionDefinitionId(ActionDefinitionIds.STRUCTURE_SELECT_NEXT); - setAction(StructuredTextEditorActionConstants.ACTION_NAME_STRUCTURE_SELECT_NEXT, action); - - action = new StructureSelectPreviousAction(this, selectionHistory); - action.setActionDefinitionId(ActionDefinitionIds.STRUCTURE_SELECT_PREVIOUS); - setAction(StructuredTextEditorActionConstants.ACTION_NAME_STRUCTURE_SELECT_PREVIOUS, action); - - action = new StructureSelectHistoryAction(this, selectionHistory); - action.setActionDefinitionId(ActionDefinitionIds.STRUCTURE_SELECT_HISTORY); - setAction(StructuredTextEditorActionConstants.ACTION_NAME_STRUCTURE_SELECT_HISTORY, action); - selectionHistory.setHistoryAction((StructureSelectHistoryAction) action); - } - - protected LineChangeHover createChangeHover() { - return 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 ICharacterPairMatcher() { - - public void clear() { - } - - public void dispose() { - } - - public int getAnchor() { - return ICharacterPairMatcher.LEFT; - } - - public IRegion match(IDocument iDocument, int i) { - return null; - } - }; - } - 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}); - } - - protected 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(ContentOutlineConfiguration.ID, ids[i]); - } - return cfg; - } - - protected void createModelDependentFields() { - // none at this level - } - - /** - * Use StructuredTextViewerConfiguration if a viewerconfiguration has not - * already been set. Also initialize StructuredTextViewer. - * - * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#createPartControl(org.eclipse.swt.widgets.Composite) - */ - public void createPartControl(Composite parent) { - if (getSourceViewerConfiguration() == null) { - StructuredTextViewerConfiguration newViewerConfiguration = createSourceViewerConfiguration(); - setSourceViewerConfiguration(newViewerConfiguration); - } - - super.createPartControl(parent); - - // instead of calling setInput twice, use initializeSourceViewer() to - // handle source viewer initialization previously handled by setInput - initializeSourceViewer(); - } - - 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(PropertySheetConfiguration.ID, 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_OUTLINE)) { - allIds.add(IPageLayout.ID_OUTLINE); - } - return (String[]) allIds.toArray(new String[0]); - } - - /** - * @return - */ - protected SourceEditingTextTools createSourceEditingTextTools() { - SourceEditingTextTools tools = null; - ExtendedConfigurationBuilder builder = ExtendedConfigurationBuilder.getInstance(); - String[] ids = getConfigurationPoints(); - for (int i = 0; tools == null && i < ids.length; i++) { - tools = (SourceEditingTextTools) builder.getConfiguration(NullSourceEditingTextTools.ID, ids[i]); - } - if (tools == null) { - tools = NullSourceEditingTextTools.getInstance(); - } - 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; - } - - protected StructuredTextViewerConfiguration createSourceViewerConfiguration() { - StructuredTextViewerConfiguration cfg = null; - ExtendedConfigurationBuilder builder = ExtendedConfigurationBuilder.getInstance(); - String[] ids = getConfigurationPoints(); - for (int i = 0; cfg == null && i < ids.length; i++) { - cfg = (StructuredTextViewerConfiguration) builder.getConfiguration(StructuredTextViewerConfiguration.ID, ids[i]); - } - if (cfg == null) { - cfg = new StructuredTextViewerConfiguration(); - cfg.setDeclaringID(getClass().getName() + "#default"); //$NON-NLS-1$ - } - initializeSourceViewerConfiguration(cfg); - return cfg; - } - - protected StructuredTextViewer createStructedTextViewer(Composite parent, IVerticalRuler verticalRuler, int styles) { - return new StructuredTextViewer(parent, verticalRuler, getOverviewRuler(), isOverviewRulerVisible(), styles); - } - - /** - * @see DekstopPart#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$ - } - - - int caretOffset = getCaretPosition(); - // safeguard values used in the Position below - if (caretOffset < 0) { - caretOffset = 0; - } - - - // dispose of document folding support - if (fProjectionModelUpdater != null) { - fProjectionModelUpdater.uninstall(); - fProjectionModelUpdater = null; - } - - if (fProjectionSupport != null) { - fProjectionSupport.dispose(); - fProjectionSupport = null; - } - - // subclass may not have mouse tracker created - // need to check for null before stopping - if (fMouseTracker != null) { - fMouseTracker.stop(); - fMouseTracker = null; - } - - // added this 2/19/2004 to match the 'add' in - // intializeDocumentProvider. - if (getDocumentProvider() != null) - getDocumentProvider().removeElementStateListener(internalElementStateListener); - - // 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) { - if (fStructuredModel.getStructuredDocument() != null) - fStructuredModel.getStructuredDocument().removeDocumentListener(this); - fStructuredModel.removeModelStateListener(getInternalModelStateListener()); - } - - if (getDocument() != null) { - IDocument doc = getDocument(); - doc.removeDocumentListener(this); - if (doc instanceof IExecutionDelegatable) { - ((IExecutionDelegatable) doc).setExecutionDelegate(null); - } - } - - fEditorDisposed = true; - disposeModelDependentFields(); - // some things in the configuration need to clean - // up after themselves - SourceViewerConfiguration config = getSourceViewerConfiguration(); - if (config instanceof StructuredTextViewerConfiguration) { - ((StructuredTextViewerConfiguration) config).unConfigure(getSourceViewer()); - } - - if (fDropTarget != null) - fDropTarget.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; - - 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 && !(getDocumentProvider() instanceof IModelProvider)) { - fStructuredModel.releaseFromEdit(); - } - super.disposeDocumentProvider(); - } - - /** - * Disposes model specific editor helpers such as statusLineHelper. - * Basically any code repeated in update() & dispose() should be placed - * here. - */ - protected void disposeModelDependentFields() { - // none at this level - } - - // This is for the IDocumentListener interface - public void documentAboutToBeChanged(DocumentEvent event) { - fDirtyBeforeDocumentEvent = isDirty(); - } - - // This is for the IDocumentListener interface - public void documentChanged(DocumentEvent event) { - if (isEditorInputReadOnly()) { - // stop listening to document event - // caused by the undo after validateEdit - final int offset = event.getOffset() + event.getLength(); - fCurrentRunnable = new Runnable() { - public void run() { - if (!fEditorDisposed) { - IStatus status = validateEdit(getSite().getShell()); - if (status != null && status.isOK()) { - // nothing to do if 'ok' - } else { - getModel().getUndoManager().undo(); - getSourceViewer().setSelectedRange(offset, 0); - if (!fDirtyBeforeDocumentEvent) { - // reset dirty state if - // model not dirty before - // document event - getModel().setDirtyState(false); - } - } - } - fCurrentRunnable = null; - } - }; - /* - * We need to ensure that this is run via 'asyncExec' since these - * notifications can come from a non-ui thread. - * - * The non-ui thread call would occur when creating a new file - * under ClearCase (or other library) control. The creation of the - * new file would trigger a validateEdit call, on another thread, - * that would prompt the user to add the new file to version - * control. - */ - Display display = getDisplay(); - if (display != null) { - if (Thread.currentThread() != display.getThread()) - // future_TODO: there's probably a better - // way than relying on asycnExec - display.asyncExec(fCurrentRunnable); - else - fCurrentRunnable.run(); - } - } - } - - /** - * @see ITextEditor#doRevertToSaved - */ - public void doRevertToSaved() { - super.doRevertToSaved(); - if (fOutlinePage != null && fOutlinePage instanceof IUpdate) - ((IUpdate) fOutlinePage).update(); - // update menu text - updateMenuText(); - } - - public void doSave(IProgressMonitor progressMonitor) { - try { - aboutToSaveModel(); - updateEncodingMemento(); - super.doSave(progressMonitor); - } finally { - savedModel(); - } - } - - private void savedModel() { - if (getModel() != null) { - getModel().changedModel(); - } - } - - private void aboutToSaveModel() { - if (getModel() != null) { - getModel().aboutToChangeModel(); - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.AbstractTextEditor#doSetInput(org.eclipse.ui.IEditorInput) - */ - protected void doSetInput(IEditorInput input) throws CoreException { - try { - // TODO: if opened in more than one editor, this will cause - // problems. - IEditorInput oldInput = getEditorInput(); - if (oldInput != null) { - IDocument olddoc = getDocumentProvider().getDocument(oldInput); - if (olddoc != null && olddoc instanceof IExecutionDelegatable) { - ((IExecutionDelegatable) olddoc).setExecutionDelegate(null); - } - } - - if (fStructuredModel != null) { - fStructuredModel.releaseFromEdit(); - } - - super.doSetInput(input); - - if (getDocument() instanceof IExecutionDelegatable) { - ((IExecutionDelegatable) getDocument()).setExecutionDelegate(new EditorExecutionContext(this)); - } - - IStructuredModel model = null; - // 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 { - IDocument doc = getDocument(); - // IMPL: need to cleanup throughout to avoid any instanceof - // checks - if (doc instanceof IStructuredDocument) { - // corresponding releaseFromEdit occurs in - // disposeDocumentProvider - model = StructuredModelManager.getModelManager().getExistingModelForEdit(doc); - if (model == null) { - model = StructuredModelManager.getModelManager().getModelForEdit((IStructuredDocument) doc); - EditorModelUtil.addFactoriesTo(model); - } - } else { - logUnexpectedDocumentKind(input); - } - } - - if (fStructuredModel != null || model != null) { - setModel(model); - } - - // currently this only works if createpartcontrol has not been called yet - if (getModel() != null) { - String contentType = getModel().getContentTypeIdentifier(); - setEditorContextMenuId(contentType+".source.EditorContext"); //$NON-NLS-1$ - setRulerContextMenuId(contentType+".source.RulerContext"); //$NON-NLS-1$ - setHelpContextId(contentType+".source.HelpId"); //$NON-NLS-1$ - // allows help to be set at any time (not just on AbstractTextEditor's - // creation) - if ((getHelpContextId() != null) && (getSourceViewer() != null) && (getSourceViewer().getTextWidget() != null)) { - IWorkbenchHelpSystem helpSystem = SSEUIPlugin.getDefault().getWorkbench().getHelpSystem(); - helpSystem.setHelp(getSourceViewer().getTextWidget(), getHelpContextId()); - } - } - - if (fProjectionModelUpdater != null) - fProjectionModelUpdater.initialize(); - - // start editor with smart insert mode - setInsertMode(SMART_INSERT); - } catch (CoreException exception) { - // dispose editor - dispose(); - - throw new CoreException(exception.getStatus()); - } - } - - 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; - if (getDocument() != null) { - implClass = getDocument().getClass().toString(); - } else { - implClass = "document was null"; //$NON-NLS-1$ - } - Logger.log(Logger.WARNING, " Document implementation: " + implClass); //$NON-NLS-1$ - } - - /** - * Sets up this editor's context menu before it is made visible. - * - * @param menu - * the menu - */ - public void editorContextMenuAboutToShow(IMenuManager menu) { - // To be consistant with the Java Editor, we want - // to remove - // ShiftRight and ShiftLeft from the context menu. - // - // ShiftRight and ShiftLeft were added in the super - // implemenation of - // this method. We want to skip it and call - // AbstractTextEditor's - // implementation directly. The easiest way is to - // copy the method here. - - // super.editorContextMenuAboutToShow(menu); - abstractTextEditorContextMenuAboutToShow(menu); - - addContextMenuActions(menu); - addExtendedContextMenuActions(menu); - } - - /** - * This is the public method to be called to notifiy us that document is - * being updated by backround job. - */ - public 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. - */ - private void endBusyStateInternal() { - if (fBackgroundJobEnded) { - fBusyTimer.cancel(); - 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. - } - } - - public Object getAdapter(Class required) { - if (org.eclipse.wst.sse.core.internal.util.Debug.perfTestAdapterClassLoading) { - startPerfTime = System.currentTimeMillis(); - } - Object result = null; - // text editor - if (ITextEditor.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) { - if (cfg instanceof StructuredContentOutlineConfiguration) { - ((StructuredContentOutlineConfiguration) cfg).setEditor(this); - } - StructuredTextEditorContentOutlinePage outlinePage = new StructuredTextEditorContentOutlinePage(); - outlinePage.setConfiguration(cfg); - outlinePage.setViewerSelectionManager(getViewerSelectionManager()); - outlinePage.setModel(getModel()); - 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) { - if (cfg instanceof StructuredPropertySheetConfiguration) { - ((StructuredPropertySheetConfiguration) cfg).setEditor(this); - } - ConfigurablePropertySheetPage propertySheetPage = new ConfigurablePropertySheetPage(); - propertySheetPage.setConfiguration(cfg); - propertySheetPage.setViewerSelectionManager(getViewerSelectionManager()); - propertySheetPage.setModel(getModel()); - fPropertySheetPage = propertySheetPage; - } - } - result = fPropertySheetPage; - } else if (ViewerSelectionManager.class.equals(required)) { - result = getViewerSelectionManager(); - } else if (SourceEditingTextTools.class.equals(required)) { - result = createSourceEditingTextTools(); - } else if (IToggleBreakpointsTarget.class.equals(required)) { - result = ToggleBreakpointsTarget.getInstance(); - } else if (IShowInTargetList.class.equals(required)) { - return new ShowInTargetListAdapter(); - } else { - Document document = getDOMDocument(); - if (document != null && document instanceof INodeNotifier) { - result = ((INodeNotifier) document).getAdapterFor(required); - } - if (result == null) { - if (getModel() != null) { - result = getModel().getAdapter(required); - } else { - result = super.getAdapter(required); - } - } - // others - if (result == null) - result = super.getAdapter(required); - } - 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; - } - - /** - * IExtendedMarkupEditor method - */ - public Node getCaretNode() { - IStructuredModel model = getModel(); - if (model == null) - return null; - int pos = getCaretPosition(); - IndexedRegion inode = model.getIndexedRegion(pos); - if (inode == null) - inode = model.getIndexedRegion(pos - 1); - return (inode instanceof Node) ? (Node) inode : null; - } - - /** - * IExtendedSimpleEditor method - */ - public int getCaretPosition() { - ViewerSelectionManager vsm = getViewerSelectionManager(); - if (vsm == null) - return -1; - // nsd_TODO: are we being overly paranoid? - StructuredTextViewer stv = getTextViewer(); - if (stv != null && stv.getControl() != null && !stv.getControl().isDisposed()) { - return stv.widgetOffset2ModelOffset(vsm.getCaretPosition()); - } - return vsm.getCaretPosition(); - } - - protected String[] getConfigurationPoints() { - String contentTypeIdentifierID = null; - if (getModel() != null) - contentTypeIdentifierID = getModel().getContentTypeIdentifier(); - return ConfigurationPointCalculator.getConfigurationPoints(this, contentTypeIdentifierID, ConfigurationPointCalculator.SOURCE, StructuredTextEditor.class); - } - - /** - * @deprecated - will be removed in M4 - */ - public Node getCursorNode() { - if (getModel() != null) - return (Node) getModel().getIndexedRegion(getCursorOffset()); - else - return null; - } - - /** - * @deprecated - will be removed in M4 - */ - public int getCursorOffset() { - if (hoverX >= 0 && hoverY >= 0) - return getOffsetAtLocation(hoverX, hoverY); - return getCaretPosition(); - } - - /** - * 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(); - } - - /** - * IExtendedSimpleEditor method - */ - public IDocument getDocument() { - // ITextViewer tv = getTextViewer(); - // return (tv != null) ? tv.getDocument() : null; - // The TextViewer may not be available at init - // time. - // The right way to get the document is thru - // DocumentProvider. - IDocumentProvider dp = getDocumentProvider(); - return (dp != null) ? dp.getDocument(getEditorInput()) : null; - } - - /** - * IExtendedMarkupEditor method - */ - public Document getDOMDocument() { - IStructuredModel model = getModel(); - if (model != null) { - return (Document) model.getAdapter(Document.class); - } - return null; - } - - /** - * @see com.ibm.sed.edit.extension.IExtendedSimpleEditor#getEditorPart() - */ - public IEditorPart getEditorPart() { - if (fEditorPart == null) - return this; - return fEditorPart; - } - - /** - * @deprecated - will be removed in M4 - * - * used only by Search and there are alternate means besides making this - * API - * @return the IFile from the currently active editor - */ - public IFile getFileInEditor() { - IStructuredModel model = getModel(); - return ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(model.getBaseLocation())); - // (pa) this changed because FileBuffers don't use absolute location - // plain old getFile(...) should work now (for the relative URL) - // return - // ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(new - // Path(model.getBaseLocation())); - } - - /** - * @deprecated - will be removed in M4 - * @return - */ - protected String[] getFindOccurrencesRegionTypes() { - return new String[0]; - } - - private InternalModelStateListener getInternalModelStateListener() { - if (fInternalModelStateListener == null) { - fInternalModelStateListener = new InternalModelStateListener(); - } - return fInternalModelStateListener; - } - - /** - * @deprecated - may be made protected in M4 This value is set in - * initialize from input - */ - public IStructuredModel getModel() { - if (getDocumentProvider() == 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$ - } - boolean initialModelNull = false; - if (fStructuredModel == null) - initialModelNull = true; - if (fStructuredModel == null) { - if (getDocumentProvider() instanceof IModelProvider) { - fStructuredModel = ((IModelProvider) getDocumentProvider()).getModel(getEditorInput()); - } - else { - IDocument doc = getDocument(); - if (doc instanceof IStructuredDocument) { - IStructuredModel model = StructuredModelManager.getModelManager().getExistingModelForEdit(doc); - if (model == null) { - model = StructuredModelManager.getModelManager().getModelForEdit((IStructuredDocument) doc); - } - EditorModelUtil.addFactoriesTo(model); - fStructuredModel = model; - } - } - 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; - } - - /** - * Computes the document offset underlying the given text widget graphics - * coordinates. - * - * @deprecated - only used by methods meant to be removed in M4 - * - * this method will be removed in M4 - * - * @param x - * the x coordinate inside the text widget - * @param y - * the y coordinate inside the text widget - * @return the document offset corresponding to the given point - */ - protected int getOffsetAtLocation(int x, int y) { - StyledText styledText = getSourceViewer().getTextWidget(); - if (styledText != null && !styledText.isDisposed()) { - try { - int widgetOffset = styledText.getOffsetAtLocation(new Point(x, y)); - if (getSourceViewer() instanceof ITextViewerExtension5) { - ITextViewerExtension5 extension = (ITextViewerExtension5) getSourceViewer(); - return extension.widgetOffset2ModelOffset(widgetOffset); - } - return widgetOffset + getSourceViewer().getVisibleRegion().getOffset(); - } catch (IllegalArgumentException e) { - return getSourceViewer().getVisibleRegion().getLength(); - } - } - return getCaretPosition(); - } - - /** - * @deprecated - will be removed in M4 - * - * used only by Search and there are alternate means besides making this - * API - * - * @return the IStructuredDocumentRegion that the text selection in the - * editor resolves to, or <code>null</code> if the range covers - * more than one region. - */ - public IStructuredDocumentRegion getSelectedDocumentRegion() { - Point p = getSelectionRange(); - int start = p.x; - int end = p.x + p.y; - - IDocument doc = getDocument(); - if (doc instanceof IStructuredDocument) { - IStructuredDocument structuredDocument = (IStructuredDocument) doc; - IStructuredDocumentRegion firstSdRegion = structuredDocument.getRegionAtCharacterOffset(start); - IStructuredDocumentRegion secondSdRegion = structuredDocument.getRegionAtCharacterOffset(end); - if (firstSdRegion != null && secondSdRegion != null) { - if (firstSdRegion.equals(secondSdRegion) || firstSdRegion.getEndOffset() == end) { - // the selection is on the same region or - // the selection ends right on the end of the first region - return firstSdRegion; - } - } - } - return null; - } - - /** - * IExtendedMarkupEditor method - */ - public List getSelectedNodes() { - ViewerSelectionManager vsm = getViewerSelectionManager(); - return (vsm != null) ? vsm.getSelectedNodes() : null; - } - - /** - * @deprecated - * - * used only by Search and there are alternate means besides making this - * API - * - * will be removed in M4 - * - * @param sdRegion - * the IStructuredDocumentRegion that you want to check - * selection on - * @return the ITextRegion that the text selection in the editor resolves - * to, or <code>null</code> if the range covers more than one - * region or none. - */ - public ITextRegion getSelectedTextRegion(IStructuredDocumentRegion sdRegion) { - Assert.isNotNull(sdRegion); - - Point p = getSelectionRange(); - int start = p.x; - int end = p.x + p.y; - - ITextRegion first = sdRegion.getRegionAtCharacterOffset(start); - ITextRegion second = sdRegion.getRegionAtCharacterOffset(end); - if (first != null && second != null) { - if (first.equals(second) || sdRegion.getEndOffset(first) == end) { - // the selection is on the same region - // the selection ends right on the end of the first region - return first; - } - } - return null; - } - - /** - * IExtendedSimpleEditor method - */ - public Point getSelectionRange() { - ITextViewer tv = getSourceViewer(); - if (tv == null) - return new Point(-1, -1); - else - return tv.getSelectedRange(); - } - - private IStatusLineManager getStatusLineManager() { - 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; - } - - /** - * Returns the editor's source viewer. This method was created to expose - * the protected final getSourceViewer() method. - * - * @return the editor's source viewer - */ - public StructuredTextViewer getTextViewer() { - return (StructuredTextViewer) getSourceViewer(); - } - - /** - * @deprecated - * - * will be made protected or removed in M4 - * - * @return - */ - public ViewerSelectionManager getViewerSelectionManager() { - if (getTextViewer() != null) - return getTextViewer().getViewerSelectionManager(); - return null; - } - - protected void handleCursorPositionChanged() { - super.handleCursorPositionChanged(); - updateStatusField(StructuredTextEditorActionConstants.STATUS_CATEGORY_OFFSET); - } - - protected void handleElementContentAboutToBeReplaced(Object element) { - // do nothing - } - - protected void handleElementContentReplaced(Object element) { - // do nothing, the model provider should reload the - // model - } - - protected void handleElementDeleted(Object element) { - // do nothing, the superclass will close() us - } - - protected void handleElementDirtyStateChanged(Object element, boolean isDirty) { - // do nothing, the superclass will fire a proeprty - // change - } - - protected void handleElementMoved(Object oldElement, Object newElement) { - // do nothing, the editor input will be changed - } - - /* - * (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(); - } - - if (IStructuredTextFoldingProvider.FOLDING_ENABLED.equals(property)) { - if (getSourceViewer() instanceof ProjectionViewer) { - // install projection support if it has not even been - // installed yet - if (isFoldingEnabled() && (fProjectionSupport == null) && (fProjectionModelUpdater == null)) { - installProjectionSupport(); - } - ProjectionViewer pv = (ProjectionViewer) getSourceViewer(); - if (pv.isProjectionMode() != isFoldingEnabled()) { - if (pv.canDoOperation(ProjectionViewer.TOGGLE)) - pv.doOperation(ProjectionViewer.TOGGLE); - } - } - return; - } - super.handlePreferenceStoreChanged(event); - } - - /** - * @return - */ - private boolean inBusyState() { - return fBusyState; - } - - 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); - } - } - - public void initializeDocumentProvider(IDocumentProvider documentProvider) { - if (getDocumentProvider() != null) - getDocumentProvider().removeElementStateListener(internalElementStateListener); - if (documentProvider != null) { - setDocumentProvider(documentProvider); - } - if (documentProvider != null) - documentProvider.addElementStateListener(internalElementStateListener); - } - - protected void initializeDrop(ITextViewer textViewer) { - int operations = DND.DROP_COPY | DND.DROP_MOVE; - fDropTarget = new DropTarget(textViewer.getTextWidget(), operations); - fDropAdapter = new ReadOnlyAwareDropTargetAdapter(); - fDropAdapter.setTargetEditor(this); - fDropAdapter.setTargetIDs(getConfigurationPoints()); - fDropAdapter.setTextViewer(textViewer); - fDropTarget.setTransfer(fDropAdapter.getTransfers()); - fDropTarget.addDropListener(fDropAdapter); - } - - protected void initializeEditor() { - super.initializeEditor(); - // FIXME: here's where to add back in our custom encoding support - fEncodingSupport = null; - 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() { - if (getViewerSelectionManager() != null) - getViewerSelectionManager().setModel(getModel()); - - computeAndSetDoubleClickAction(getModel()); - - IAction contentAssistAction = getAction(StructuredTextEditorActionConstants.ACTION_NAME_CONTENTASSIST_PROPOSALS); - if (contentAssistAction instanceof IUpdate) { - ((IUpdate) contentAssistAction).update(); - } - 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(); - } - } - - /** - * Performs any necessary setup for a new or unconfigured - * StructuredTextViewerConfiguration - * - * @param configuration - */ - void initializeSourceViewerConfiguration(StructuredTextViewerConfiguration configuration) { - configuration.setEditorPart(this); - configuration.setPreferenceStore(getPreferenceStore()); - - IResource resource = null; - IFile file = (IFile) getEditorInput().getAdapter(IFile.class); - if (file != null) { - resource = file.getProject(); - } - configuration.configureOn(resource); - } - - protected void initSourceViewer(StructuredTextViewer sourceViewer) { - // ensure decoration support is configured - getSourceViewerDecorationSupport(sourceViewer); - fMouseTracker = new MouseTracker(); - fMouseTracker.start(sourceViewer.getTextWidget()); - initializeDrop(sourceViewer); - } - - - protected void installEncodingSupport() { - // TODO: install our custom support that can - // update document appropriately - // super.installEncodingSupport(); - } - - /** - * 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(); - - IStructuredTextFoldingProvider updater = null; - ExtendedConfigurationBuilder builder = ExtendedConfigurationBuilder.getInstance(); - String[] ids = getConfigurationPoints(); - for (int i = 0; updater == null && i < ids.length; i++) { - updater = (IStructuredTextFoldingProvider) builder.getConfiguration(IStructuredTextFoldingProvider.ID, ids[i]); - } - - fProjectionModelUpdater = updater; - if (fProjectionModelUpdater != null) - fProjectionModelUpdater.install(projectionViewer); - - if (isFoldingEnabled()) - projectionViewer.doOperation(ProjectionViewer.TOGGLE); - } - - /** - * @deprecated - will be removed in M4 - * @param type - * @return - */ - public boolean isFindOccurrencesRegionType(String type) { - String[] accept = getFindOccurrencesRegionTypes(); - for (int i = 0; i < accept.length; i++) { - if (accept[i].equals(type)) - return true; - } - return false; - } - - - /** - * 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(IStructuredTextFoldingProvider.FOLDING_ENABLED) && (System.getProperty("org.eclipse.wst.sse.ui.foldingenabled") != null)); //$NON-NLS-1$ - } - - /** - * Returns whether the given annotation type is configured as a target - * type for the "Go to Next/Previous Annotation" actions. Copied from - * org.eclipse.jdt.internal.ui.javaeditor.JavaEditor - * - * @param type - * the annotation type - * @return <code>true</code> if this is a target type, - * <code>false</code> otherwise - * @since 3.0 - */ - protected boolean isNavigationTargetType(Annotation annotation) { - Preferences preferences = EditorsUI.getPluginPreferences(); - AnnotationPreference preference = 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)); - } - - /* - * @see IEditorPart#isSaveOnCloseNeeded() - */ - public boolean isSaveOnCloseNeeded() { - if (getModel() == null) - return false; - return getModel().isSaveNeeded(); - } - - /* - * @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(); - if (fProjectionModelUpdater != null) - fProjectionModelUpdater.uninstall(); - } - - super.performRevert(); - - if (projectionMode) { - if (fProjectionModelUpdater != null) - fProjectionModelUpdater.install(projectionViewer); - projectionViewer.enableProjection(); - } - - } finally { - projectionViewer.setRedraw(true); - } - } - - /** - * This method was made public for use by editors that use - * StructuredTextEditor (like PageDesigner) - * - * @see org.eclipse.ui.texteditor.AbstractTextEditor#rememberSelection() - */ - public void rememberSelection() { - super.rememberSelection(); - } - - /** - * both starts and resets the busy state timer - */ - private void resetBusyState() { - // reset the "busy" timeout - if (fBusyTimer != null) { - fBusyTimer.cancel(); - } - startBusyTimer(); - } - - /** - * This method was made public for use by editors that use - * StructuredTextEditor (like PageDesigner) - * - * @see org.eclipse.ui.texteditor.AbstractTextEditor#restoreSelection() - */ - public void restoreSelection() { - // catch odd case where source viewer has no text - // widget (defect - // 227670) - if ((getSourceViewer() != null) && (getSourceViewer().getTextWidget() != null)) - super.restoreSelection(); - } - - protected void rulerContextMenuAboutToShow(IMenuManager menu) { - boolean debuggingAvailable = BreakpointProviderBuilder.getInstance().isAvailable(getModel().getContentTypeIdentifier(), BreakpointRulerAction.getFileExtension(getEditorInput())); - if (debuggingAvailable) { - menu.add(getAction(ActionDefinitionIds.TOGGLE_BREAKPOINTS)); - menu.add(getAction(ActionDefinitionIds.MANAGE_BREAKPOINTS)); - menu.add(getAction(ActionDefinitionIds.EDIT_BREAKPOINTS)); - menu.add(new Separator()); - } - super.rulerContextMenuAboutToShow(menu); - addExtendedRulerContextMenuActions(menu); - } - - /** - * Overridden to expose part activation handling for multi-page editors - * - * @see org.eclipse.ui.texteditor.AbstractTextEditor#safelySanityCheckState(org.eclipse.ui.IEditorInput) - */ - public void safelySanityCheckState(IEditorInput input) { - super.safelySanityCheckState(input); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.texteditor.AbstractTextEditor#selectAndReveal(int, - * int, int, int) - */ - protected void selectAndReveal(int selectionStart, int selectionLength, int revealStart, int revealLength) { - super.selectAndReveal(selectionStart, selectionLength, revealStart, revealLength); - getTextViewer().notifyViewerSelectionManager(selectionStart, selectionLength); - } - - /** - * 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); - } - } - - public void setEditorPart(IEditorPart editorPart) { - fEditorPart = editorPart; - } - - /** - * @deprecated - Clients should use .getAdapter(Control) to get the text - * viewer control and set its help context. Will be removed in - * M4. - * - * We expose this normally protected method so clients can provide their - * own help. - * - * @param helpContextId - * the help context id - */ - public void setHelpContextId(String helpContextId) { - // used by (requested by) WSED - super.setHelpContextId(helpContextId); - // allows help to be set at any time (not just on AbstractTextEditor's - // creation) - if ((getHelpContextId() != null) && (getSourceViewer() != null) && (getSourceViewer().getTextWidget() != null)) { - IWorkbenchHelpSystem helpSystem = SSEUIPlugin.getDefault().getWorkbench().getHelpSystem(); - helpSystem.setHelp(getSourceViewer().getTextWidget(), getHelpContextId()); - } - } - - /** - * @deprecated - use setInput as if we were a text editor - * - * Note: this weird API, setModel which takes input as parameter. Is - * provided for those editors which don't otherwise have to know about - * models's. (Is hard/impossible to override the setInput method.) - */ - public void setModel(IFileEditorInput input) { - // Assert.isNotNull(getDocumentProvider()); - // if (fStructuredModel != null) { - // if (getDocument() != null) { - // getDocument().removeDocumentListener(this); - // fStructuredModel.removeModelStateListener(getInternalModelStateListener()); - // } - // } - // if (!(getDocumentProvider() instanceof FileModelProvider)) { - // initializeDocumentProvider(FileModelProvider.getInstance()); - // } - // // ((FileModelProvider) - // // getDocumentProvider()).createModelInfo(input); - // // fStructuredModel = ((FileModelProvider) - // // getDocumentProvider()).getModel(input); - // // model will be null in some error conditions. - // if (fStructuredModel == null) { - // close(false); - // } - // // DMW: checked for site after moving to 3/22 - // // (2.1M4) Eclipse base. - // /// Later code in super classes were causing NPE's - // // because site, etc., - // // hasn't been - // // initialized yet. If site is still null at this - // // point, we are - // // assuming - // // setInput and update are called later, perhaps - // // elsewhere. - // // But if site is not null (such as in DTD Editor) - // // then setInput and - // // update must - // // be called here. - // // if (getSite() != null) { - // setInput(input); - // fStructuredModel = ((FileModelProvider) - // getDocumentProvider()).getModel(input); - // if (fStructuredModel != null) { - // getDocument().addDocumentListener(this); - // fStructuredModel.addModelStateListener(getInternalModelStateListener()); - // } - // // update() should be called whenever the model is - // // set or changed - // update(); - // // } - setInput(input); - } - - /** - * Sets the model field within this editor, use only when: 1) there is no - * IEditorInput (very special case, not well tested) 2) there is an - * IEditorInput but the corresponding model needs to be set separately - * - * @deprecated - this is a laregely untested usage - */ - public void setModel(IStructuredModel newModel) { - Assert.isNotNull(getDocumentProvider()); - if (fStructuredModel != null) { - if (fStructuredModel.getStructuredDocument() != null) { - fStructuredModel.getStructuredDocument().removeDocumentListener(this); - } - fStructuredModel.removeModelStateListener(getInternalModelStateListener()); - } - fStructuredModel = newModel; - if (fStructuredModel != null) { - if (fStructuredModel.getStructuredDocument() != null) { - fStructuredModel.getStructuredDocument().addDocumentListener(this); - } - fStructuredModel.addModelStateListener(getInternalModelStateListener()); - } - // update() should be called whenever the model is - // set or changed - update(); - } - - /** - * @deprecated - initialize with a document provider and use setInput or - * setModel(IStructuredModel) - * @param newModel - * @param input - */ - public void setModel(IStructuredModel newModel, IFileEditorInput input) { - // _setAnnotationModel(input); - // setModel(newModel); - Assert.isNotNull(getDocumentProvider()); - if (fStructuredModel != null) { - fStructuredModel.removeModelStateListener(getInternalModelStateListener()); - if (fStructuredModel.getStructuredDocument() != null) { - fStructuredModel.getStructuredDocument().removeDocumentListener(this); - } - } - fStructuredModel = newModel; - // setInput in super will allow titles to be - // updated, etc. - setInput(input); - if (fStructuredModel != null) { - if (fStructuredModel.getStructuredDocument() != null) { - fStructuredModel.getStructuredDocument().addDocumentListener(this); - } - 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) { - 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 - stv.unconfigure(); - stv.configure(config); - } - } - - /** - * Overridden to allow custom tab title for multi-page editors - * - * @see org.eclipse.ui.part.WorkbenchPart#setTitle(java.lang.String) - */ - public void setTitle(String title) { - super.setTitle(title); - } - - public void showBusy(boolean busy) { - if (busy) { - fRememberTitle = getPartName(); - // update title and/or fonts and/or background - // - // temp solution, for testing, uses "busy" - setPartName(SSEUIMessages.busy); //$NON-NLS-1$ - } else { - // reset to what it was - setPartName(fRememberTitle); - } - } - - private void startBusyTimer() { - // TODO: we need a resetable timer, so not so - // many created - fBusyTimer = new Timer(true); - fBusyTimer.schedule(new TimeOutExpired(), BUSY_STATE_DELAY); - } - - - private void statusError(IStatus status) { - statusError(status.getMessage()); - ErrorDialog.openError(getSite().getShell(), null, null, status); - } - - private void statusError(String message) { - IStatusLineManager manager = getStatusLineManager(); - if (manager == null) - return; - manager.setErrorMessage(message); - getSite().getShell().getDisplay().beep(); - } - - /** - * update() should be called whenever the model is set or changed (as in - * swapped) - */ - public void update() { - if (fOutlinePage != null && fOutlinePage instanceof StructuredTextEditorContentOutlinePage) { - ContentOutlineConfiguration cfg = createContentOutlineConfiguration(); - if (cfg instanceof StructuredContentOutlineConfiguration) { - ((StructuredContentOutlineConfiguration) cfg).setEditor(this); - } - ((StructuredTextEditorContentOutlinePage) fOutlinePage).setModel(getModel()); - ((StructuredTextEditorContentOutlinePage) fOutlinePage).setViewerSelectionManager(getViewerSelectionManager()); - ((StructuredTextEditorContentOutlinePage) fOutlinePage).setConfiguration(cfg); - } - if (fPropertySheetPage != null && fPropertySheetPage instanceof ConfigurablePropertySheetPage) { - PropertySheetConfiguration cfg = createPropertySheetConfiguration(); - if (cfg instanceof StructuredPropertySheetConfiguration) { - ((StructuredPropertySheetConfiguration) cfg).setEditor(this); - } - ((ConfigurablePropertySheetPage) fPropertySheetPage).setModel(getModel()); - ((ConfigurablePropertySheetPage) fPropertySheetPage).setViewerSelectionManager(getViewerSelectionManager()); - ((ConfigurablePropertySheetPage) fPropertySheetPage).setConfiguration(cfg); - } - if (getViewerSelectionManager() != null) - getViewerSelectionManager().setModel(getModel()); - disposeModelDependentFields(); - - fShowInTargetIds = createShowInTargetIds(); - - // setSourceViewerConfiguration() was called once - // in - // StructuredTextMultiPageEditorPart.createSourcePage() - // to set the SourceViewerConfiguration first so - // the text editor won't - // use the default configuration first - // and switch to the - // StructuredTextViewerConfiguration later. - // However, the source viewer was not created yet - // at the time. Need to - // call setSourceViewerConfiguration() again here - // so getSourceViewer().configure(configuration) in - // setSourceViewerConfiguration() will be called. - // DMW: removed setSouceViewerConfiguration since - // shouldn't need the - // general case - // an longer, but added 'updateConfiguration' so it - // can still be - // sensitive - // to resource/model changes. - // setSourceViewerConfiguration(); - updateSourceViewerConfiguration(); - // (nsd) we never change it, so why null it out? - // else { - // super.setPreferenceStore(null); - // } - createModelDependentFields(); - computeAndSetDoubleClickAction(getModel()); - } - - /** - * 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(); - } - - private void updateEncodingMemento() { - boolean failed = false; - if (getModel() != null) { - IStructuredDocument doc = getModel().getStructuredDocument(); - EncodingMemento memento = doc.getEncodingMemento(); - IDocumentCharsetDetector detector = getModel().getModelHandler().getEncodingDetector(); - if (memento != null && detector != null) - detector.set(doc); - try { - detector.getEncoding(); - } catch (IOException e) { - failed = true; - } - // be sure to use the new instance - // but only if no exception occurred. - // (we may find cases we need to do more error recover there) - // should be near impossible to get IOException from processing - // the - // *document* - if (!failed) { - doc.setEncodingMemento(memento); - } - } - } - - /* - * 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); - } - } - - - protected void updateMenuText() { - if (fStructuredModel != null && !fStructuredModel.isModelStateChanging() && getTextViewer().getTextWidget() != null) { - // 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 - 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 - 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(); - } - } - } - } - - protected void updateSourceViewerConfiguration() { - SourceViewerConfiguration configuration = getSourceViewerConfiguration(); - // no need to update source viewer configuration if one does not exist - // yet - if (configuration == null) { - return; - } - - // structuredtextviewer only works with - // structuredtextviewerconfiguration - if (!(configuration instanceof StructuredTextViewerConfiguration)) { - configuration = createSourceViewerConfiguration(); - setSourceViewerConfiguration(configuration); - } else { - StructuredTextViewerConfiguration newViewerConfiguration = createSourceViewerConfiguration(); - if (!((StructuredTextViewerConfiguration) configuration).getDeclaringID().equals(newViewerConfiguration.getDeclaringID())) { - // d282894 use newViewerConfiguration - configuration = newViewerConfiguration; - setSourceViewerConfiguration(configuration); - } - - // update the configuration's resource - IResource resource = null; - if (getEditorInput() instanceof IFileEditorInput) { - resource = ((IFileEditorInput) getEditorInput()).getFile(); - if (resource.getType() != IResource.PROJECT) - resource = resource.getProject(); - ((StructuredTextViewerConfiguration) configuration).configureOn(resource); - } - } - - if (getSourceViewer() != null) { - getSourceViewer().configure(configuration); - IAction contentAssistAction = getAction(StructuredTextEditorActionConstants.ACTION_NAME_CONTENTASSIST_PROPOSALS); - if (contentAssistAction instanceof IUpdate) { - ((IUpdate) contentAssistAction).update(); - } - IAction openHyperlinkAction = getAction(StructuredTextEditorActionConstants.ACTION_NAME_OPEN_FILE); - if (openHyperlinkAction instanceof OpenHyperlinkAction) { - ((OpenHyperlinkAction) openHyperlinkAction).setHyperlinkDetectors(getSourceViewerConfiguration().getHyperlinkDetectors(getSourceViewer())); - } - } - // eventually will replace above with something - // like what follows - // it, but some of our "processors" require too - // much initialization - // during configuration. - // SourceViewerConfiguration configuration = - // getSourceViewerConfiguration(); - // - // // should always be an instance of our special - // configuration, but - // just in case - // // not, we'll do nothing if it isn't. - // if (configuration!= null && configuration - // instanceof - // StructuredTextViewerConfiguration) { - // - // IResource resource = null; - // if (getEditorInput() instanceof - // IFileEditorInput) { - // resource = ((IFileEditorInput) - // getEditorInput()).getFile(); - // if (resource.getType() != IResource.PROJECT) - // resource = resource.getProject(); - // // note: configureOn is responsible for updating - // what ever - // // in our configuration is sensitive to resource - // ((StructuredTextViewerConfiguration) - // configuration).configureOn(resource); - // } - // - // } - } - - protected void updateStatusField(String category) { - super.updateStatusField(category); - - if (category == null) - return; - - if (StructuredTextEditorActionConstants.STATUS_CATEGORY_OFFSET.equals(category)) { - IStatusField field = getStatusField(category); - if (field != null) { - Point selection = getTextViewer().getTextWidget().getSelection(); - int offset1 = widgetOffset2ModelOffset(getSourceViewer(), selection.x); - int offset2 = widgetOffset2ModelOffset(getSourceViewer(), 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); - } - } - } - - /** - * @deprecated - will be removed in M4 Use getDocumentProvider and - * IDocumentProviderExtension instead - */ - public IStatus validateEdit(Shell context) { - IStatus status = STATUS_OK; - IEditorInput input = getEditorInput(); - if (input instanceof IFileEditorInput) { - if (input == null) { - String msg = SSEUIMessages.Error_opening_file_UI_; //$NON-NLS-1$ - status = new Status(IStatus.ERROR, SSEUIPlugin.ID, IStatus.INFO, msg, null); - } else { - validateState(input); - sanityCheckState(input); - if (isEditorInputReadOnly()) { - String fname = input.getName(); - if (input instanceof IStorageEditorInput) { - try { - IStorage s = ((IStorageEditorInput) input).getStorage(); - if (s != null) { - IPath path = s.getFullPath(); - if (path != null) { - fname += path.toString(); - } else { - fname += s.getName(); - } - } - } catch (CoreException e) { // IStorage is just for - // file name, - // and it's an optional, - // therefore - // it is safe to ignore this - // exception. - } - } - String msg = NLS.bind(SSEUIMessages._UI_File_is_read_only, new Object[]{fname}); - status = new Status(IStatus.ERROR, SSEUIPlugin.ID, IStatus.INFO, msg, null); - } - } - } - return status; - } - - protected void validateState(IEditorInput input) { - IDocumentProvider provider = getDocumentProvider(); - if (provider instanceof IDocumentProviderExtension) { - IDocumentProviderExtension extension = (IDocumentProviderExtension) provider; - try { - boolean wasReadOnly = isEditorInputReadOnly(); - extension.validateState(input, getSite().getShell()); - if (getSourceViewer() != null) - getSourceViewer().setEditable(isEditable()); - if (wasReadOnly != isEditorInputReadOnly()) - updateStateDependentActions(); - } catch (CoreException x) { - ILog log = Platform.getLog(Platform.getBundle(PlatformUI.PLUGIN_ID)); - log.log(x.getStatus()); - statusError(x.getStatus()); - } - } - } -} 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 1140fab5e1..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, 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; - - - -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 1b1dfe03c4..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, 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; - - - -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 12a7f28531..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/StructuredTextViewer.java +++ /dev/null @@ -1,1120 +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; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Vector; - -import org.eclipse.core.runtime.IStatus; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IAutoEditStrategy; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IDocumentAdapter; -import org.eclipse.jface.text.IRegion; -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.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.reconciler.IReconciler; -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.jface.viewers.ContentViewer; -import org.eclipse.jface.viewers.DoubleClickEvent; -import org.eclipse.jface.viewers.IDoubleClickListener; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.events.VerifyEvent; -import org.eclipse.swt.events.VerifyListener; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Event; -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.IEditorStatusLine; -import org.eclipse.ui.views.contentoutline.IContentOutlinePage; -import org.eclipse.wst.sse.core.IndexedRegion; -import org.eclipse.wst.sse.core.internal.cleanup.StructuredContentCleanupHandler; -import org.eclipse.wst.sse.core.text.IStructuredDocument; -import org.eclipse.wst.sse.core.undo.IDocumentSelectionMediator; -import org.eclipse.wst.sse.core.undo.IStructuredTextUndoManager; -import org.eclipse.wst.sse.core.undo.UndoDocumentEvent; -import org.eclipse.wst.sse.ui.StructuredTextViewerConfiguration; -import org.eclipse.wst.sse.ui.extension.IExtendedSimpleEditor; -import org.eclipse.wst.sse.ui.internal.reconcile.StructuredRegionProcessor; -import org.eclipse.wst.sse.ui.style.IHighlighter; -import org.eclipse.wst.sse.ui.util.PlatformStatusLineUtil; -import org.eclipse.wst.sse.ui.view.events.INodeSelectionListener; -import org.eclipse.wst.sse.ui.view.events.NodeSelectionChangedEvent; -import org.w3c.dom.Attr; -import org.w3c.dom.Node; - -public class StructuredTextViewer extends ProjectionViewer implements IDocumentSelectionMediator { - - /** - * Internal verify listener. - */ - class TextVerifyListener implements VerifyListener { - - /** - * Indicates whether verify events are forwarded or ignored. - * - * @since 2.0 - */ - private boolean fForward = true; - - /** - * Tells the listener to forward received events. - * - * @param forward - * <code>true</code> if forwarding should be enabled. - * @since 2.0 - */ - public void forward(boolean forward) { - fForward = forward; - } - - /* - * @see VerifyListener#verifyText(VerifyEvent) - */ - public void verifyText(VerifyEvent e) { - if (fForward) { - handleVerifyEvent(e); - } - } - } - - /** - * A private delegate class to move INodeSelectionListener and - * IDoubleClickListener off of the viewer's APIs - */ - private class InternalSelectionListener implements INodeSelectionListener, IDoubleClickListener { - public void doubleClick(DoubleClickEvent event) { - handleDoubleClick(event); - } - - public void nodeSelectionChanged(NodeSelectionChangedEvent event) { - handleNodeSelectionChanged(event); - } - } - - /** Text operation codes */ - private static final int BASE = ProjectionViewer.EXPAND_ALL; // see - // ProjectionViewer.EXPAND_ALL - public static final int CLEANUP_DOCUMENT = BASE + 1; - 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$ - public static final int QUICK_FIX = BASE + 4; - 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 boolean fBackgroundupdateInProgress; - protected StructuredContentCleanupHandler fContentCleanupHandler = null; - protected IContentAssistant fCorrectionAssistant; - protected boolean fCorrectionAssistantInstalled; - private IDocumentAdapter fDocAdapter; - - private InternalSelectionListener fSelectionListener = null; - - /** - * TODO Temporary workaround for BUG44665 - */ - /** The most recent widget modification as document command */ - private StructuredDocumentCommand fDocumentCommand = new StructuredDocumentCommand(); - private IHighlighter fHighlighter; - // TODO: never read locally - boolean fRememberedStateContentAssistInstalled; - - /** - * TODO Temporary workaround for BUG44665 - */ - /** Verify listener */ - private TextVerifyListener fVerifyListener = new TextVerifyListener(); - - private ViewerSelectionManager fViewerSelectionManager; - - /** - * @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); - fSelectionListener = new InternalSelectionListener(); - } - - /** - * - */ - private void beep() { - getTextWidget().getDisplay().beep(); - } - - void beginBackgroundUpdate() { - fBackgroundupdateInProgress = true; - disableRedrawing(); - } - - /* - * (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 QUICK_FIX : { - return isEditable(); - } - case CLEANUP_DOCUMENT : { - return (fContentCleanupHandler != null && isEditable()); - } - case FORMAT_DOCUMENT : - case FORMAT_ACTIVE_ELEMENTS : { - return (fContentFormatter != null && isEditable()); - } - } - return super.canDoOperation(operation); - } - - /** - * Should be identical to superclass version. Also, we get the tab width - * from the preference manager. 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)); - - if (configuration instanceof StructuredTextViewerConfiguration) { - if (fHighlighter != null) { - fHighlighter.uninstall(); - } - fHighlighter = ((StructuredTextViewerConfiguration) configuration).getHighlighter(this); - fHighlighter.install(this); - } - - // install content type independent plugins - if (fPresentationReconciler != null) - fPresentationReconciler.uninstall(); - fPresentationReconciler = configuration.getPresentationReconciler(this); - if (fPresentationReconciler != null) - fPresentationReconciler.install(this); - - 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) - ((StructuredRegionProcessor) fReconciler).setDocument(getDocument()); - } - } - - if (fContentAssistant != null) - fContentAssistant.uninstall(); - fContentAssistant = configuration.getContentAssistant(this); - if (fContentAssistant != null) { - fContentAssistant.install(this); - fContentAssistantInstalled = true; - } else { - // 248036 - // disable the content assist operation if no content assistant - enableOperation(CONTENTASSIST_PROPOSALS, false); - } - - // correction assistant - if (configuration instanceof StructuredTextViewerConfiguration) { - if (fCorrectionAssistant != null) - fCorrectionAssistant.uninstall(); - fCorrectionAssistant = ((StructuredTextViewerConfiguration) configuration).getCorrectionAssistant(this); - if (fCorrectionAssistant != null) { - fCorrectionAssistant.install(this); - fCorrectionAssistantInstalled = true; - } else { - // disable the correction assist operation if no correction - // assistant - enableOperation(QUICK_FIX, 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)); - - // TODO: compare with ?new? V2 configure re: - // getTextWidget().setTabs(configuration.getTabWidth(this)); - // see if it can replace following - // Set tab width to configuration setting first. - // Then override if model type is XML or HTML. - getTextWidget().setTabs(configuration.getTabWidth(this)); - setAnnotationHover(configuration.getAnnotationHover(this)); - setOverviewRulerAnnotationHover(configuration.getOverviewRulerAnnotationHover(this)); - // added for V2 - 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); - - // install content type specific plugins - 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); - // removed 'defaultPrefix' for Eclipse V2 replaced with - // defaultPrefixes - /* - * String prefix = configuration.getDefaultPrefix(this, t); if - * (prefix != null && prefix.length() > 0) - * setDefaultPrefix(prefix, t); - */ - prefixes = configuration.getDefaultPrefixes(this, t); - if (prefixes != null && prefixes.length > 0) - setDefaultPrefixes(prefixes, t); - } - activatePlugins(); - } - - /** - * @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); - } - } - - protected IDocumentAdapter createDocumentAdapter() { - - fDocAdapter = new StructuredDocumentToTextAdapter(getTextWidget()); - return fDocAdapter; - } - - /** - * TODO Temporary workaround for BUG44665 - */ - protected void customizeDocumentCommand(StructuredDocumentCommand command) { - if (isIgnoringAutoEditStrategies()) - return; - - List strategies = (List) selectContentTypePlugin(command.offset, fAutoIndentStrategies); - if (strategies == null) - return; - - switch (strategies.size()) { - // optimization - case 0 : - break; - - case 1 : - ((IAutoEditStrategy) strategies.iterator().next()).customizeDocumentCommand(getDocument(), command); - break; - - // make iterator robust against adding/removing strategies from - // within - // strategies - default : - strategies = new ArrayList(strategies); - - IDocument document = getDocument(); - for (final Iterator iterator = strategies.iterator(); iterator.hasNext();) - ((IAutoEditStrategy) iterator.next()).customizeDocumentCommand(document, command); - - break; - } - } - - /* - * (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 UNDO : { - IExtendedSimpleEditor editor = getActiveExtendedSimpleEditor(); - if (editor != null) { - IStatus status = editor.validateEdit(getControl().getShell()); - if (status != null && status.isOK()) - undo(); - } else - undo(); - break; - } - case REDO : { - IExtendedSimpleEditor editor = getActiveExtendedSimpleEditor(); - if (editor != null) { - IStatus status = editor.validateEdit(getControl().getShell()); - if (status != null && status.isOK()) - redo(); - } else - redo(); - break; - } - 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.displayErrorMessage(err); - } - PlatformStatusLineUtil.addOneTimeClearListener(); - } else - beep(); - } - break; - case CONTENTASSIST_CONTEXT_INFORMATION : - if (fContentAssistant != null) { - String err = fContentAssistant.showContextInformation(); - PlatformStatusLineUtil.displayErrorMessage(err); - PlatformStatusLineUtil.addOneTimeClearListener(); - // setErrorMessage(err); - // new OneTimeListener(getTextWidget(), new - // ClearErrorMessage()); - } - break; - case QUICK_FIX : - if (isEditable()) { - String msg = fCorrectionAssistant.showPossibleCompletions(); - setErrorMessage(msg); - } - break; - case SHIFT_RIGHT : - beginRecording(TEXT_SHIFT_RIGHT, TEXT_SHIFT_RIGHT, cursorPosition, selectionLength); - 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); - super.doOperation(SHIFT_LEFT); - selection = getTextWidget().getSelection(); - cursorPosition = selection.x; - selectionLength = selection.y - selection.x; - endRecording(cursorPosition, selectionLength); - break; - case FORMAT_DOCUMENT : - try { - // begin recording - beginRecording(FORMAT_DOCUMENT_TEXT, FORMAT_DOCUMENT_TEXT, cursorPosition, selectionLength); - - // format - IRegion region = getModelCoverage(); - if (fContentFormatter instanceof IContentFormatterExtension) { - IContentFormatterExtension extension = (IContentFormatterExtension) fContentFormatter; - IFormattingContext context = new FormattingContext(); - context.setProperty(FormattingContextProperties.CONTEXT_DOCUMENT, Boolean.TRUE); - context.setProperty(FormattingContextProperties.CONTEXT_REGION, region); - extension.format(getDocument(), context); - } else { - fContentFormatter.format(getDocument(), region); - } - } finally { - // end recording - selection = getTextWidget().getSelection(); - cursorPosition = selection.x; - selectionLength = selection.y - selection.x; - endRecording(cursorPosition, selectionLength); - } - break; - case FORMAT_ACTIVE_ELEMENTS : - try { - // begin recording - beginRecording(FORMAT_ACTIVE_ELEMENTS_TEXT, FORMAT_ACTIVE_ELEMENTS_TEXT, cursorPosition, selectionLength); - - // format - Point s = getSelectedRange(); - IRegion region = new Region(s.x, s.y); - fContentFormatter.format(getDocument(), region); - } 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(); - undoManager.endRecording(this, cursorPosition, selectionLength); - } 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(); - undoManager.beginRecording(this, label, description, cursorPosition, selectionLength); - } else { - // TODO: how to handle other document types? - } - } - - void endBackgroundUpdate() { - fBackgroundupdateInProgress = false; - enabledRedrawing(); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.text.TextViewer#findAndSelect(int, - * java.lang.String, boolean, boolean, boolean, boolean) - */ - protected int findAndSelect(int startPosition, String findString, boolean forwardSearch, boolean caseSensitive, boolean wholeWord, boolean regExSearch) { - int result = super.findAndSelect(startPosition, findString, forwardSearch, caseSensitive, wholeWord, regExSearch); - - // findAndSelect calls fTextWidget.setSelectionRange(widgetPos, - // length) to set selection, - // which does not fire text widget selection event. - // Need to notify ViewerSelectionManager here. - notifyViewerSelectionManager(getSelectedRange().x, getSelectedRange().y); - - return result; - } - - protected IExtendedSimpleEditor getActiveExtendedSimpleEditor() { - IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); - if (window != null) { - IWorkbenchPage page = window.getActivePage(); - if (page != null) { - IEditorPart editor = page.getActiveEditor(); - if (editor != null && editor instanceof IExtendedSimpleEditor) { - return (IExtendedSimpleEditor) editor; - } - } - } - return null; - } - - - protected ViewerSelectionManager getDefaultViewerSelectionManager() { - return new ViewerSelectionManagerImpl(this); - } - - /** - * @deprecated - * @return the current ViewerSelectionManager - */ - public ViewerSelectionManager getViewerSelectionManager() { - if (fViewerSelectionManager == null) { - ViewerSelectionManager viewerSelectionManager = getDefaultViewerSelectionManager(); - // use setter instead of field directly, so it get initialized - // properly - setViewerSelectionManager(viewerSelectionManager); - } - return fViewerSelectionManager; - } - - 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 (fViewerSelectionManager != null) { - fViewerSelectionManager.removeNodeDoubleClickListener(fSelectionListener); - fViewerSelectionManager.removeNodeSelectionListener(fSelectionListener); - fViewerSelectionManager.release(); - } - - if (fHighlighter != null) { - fHighlighter.uninstall(); - } - super.handleDispose(); - - Logger.trace("Source Editor", "StructuredTextViewer::handleDispose exit"); //$NON-NLS-1$ //$NON-NLS-2$ - } - - void handleDoubleClick(DoubleClickEvent event) { - - IStructuredSelection selection = (IStructuredSelection) event.getSelection(); - int selectionSize = selection.size(); - List selectedNodes = selection.toList(); - IndexedRegion doubleClickedNode = null; - int selectionStart = 0; - int selectionEnd = 0; - if (selectionSize > 0) { - // something selected - // only one node can be double-clicked at a time - // so, we get the first one - doubleClickedNode = (IndexedRegion) selectedNodes.get(0); - selectionStart = doubleClickedNode.getStartOffset(); - selectionEnd = doubleClickedNode.getEndOffset(); - // set new selection - setSelectedRange(selectionStart, selectionEnd - selectionStart); - } - } - - void handleNodeSelectionChanged(NodeSelectionChangedEvent event) { - - // Skip NodeSelectionChanged processing if this is the source of the - // event. - if (event.getSource().equals(this)) - return; - List selectedNodes = new Vector(event.getSelectedNodes()); - boolean attrOrTextNodeSelected = false; - int attrOrTextNodeStartOffset = 0; - for (int i = 0; i < selectedNodes.size(); i++) { - Object eachNode = selectedNodes.get(i); - // replace attribute node with its parent - if (eachNode instanceof Attr) { - attrOrTextNodeSelected = true; - attrOrTextNodeStartOffset = ((IndexedRegion) eachNode).getStartOffset(); - selectedNodes.set(i, ((Attr) eachNode).getOwnerElement()); - } - // replace TextNode with its parent - if ((eachNode instanceof Node) && (((Node) eachNode).getNodeType() == Node.TEXT_NODE)) { - attrOrTextNodeSelected = true; - attrOrTextNodeStartOffset = ((IndexedRegion) eachNode).getStartOffset(); - selectedNodes.set(i, ((Node) eachNode).getParentNode()); - } - } - if (nothingToSelect(selectedNodes)) { - removeRangeIndication(); - } else { - IndexedRegion startNode = (IndexedRegion) selectedNodes.get(0); - IndexedRegion endNode = (IndexedRegion) selectedNodes.get(selectedNodes.size() - 1); - int startOffset = startNode.getStartOffset(); - int endOffset = endNode.getEndOffset(); - // if end node is a child node of start node - if (startNode.getEndOffset() > endNode.getEndOffset()) { - endOffset = startNode.getEndOffset(); - } - int length = endOffset - startOffset; - // Move cursor only if the original source really came from - // a ContentViewer (for example, the SourceEditorTreeViewer or the - // XMLTableTreeViewer) - // or a ContentOutlinePage (for example, the XSDTreeViewer). - // Do not move the cursor if the source is a textWidget (which - // means the selection came from the text viewer) or - // if the source is the ViewerSelectionManager (which means the - // selection was set programmatically). - boolean moveCursor = (event.getSource() instanceof ContentViewer) || (event.getSource() instanceof IContentOutlinePage); - // 20031012 (pa) - // Changed moveCursor to "false" because it was causing the cursor - // to jump to the beginning of the parent node in the case that a - // child of the parent is deleted. - // We really only want to set the range indicator on the left to - // the range of the parent, but not move the cursor - // setRangeIndication(startOffset, length, false); - // 20040714 (nsd) Chnaged back to tru given that selection - // problems - // caused by the Outline view appear fixed. - setRangeIndication(startOffset, length, moveCursor); - if ((moveCursor) && (attrOrTextNodeSelected)) { - setSelectedRange(attrOrTextNodeStartOffset, 0); - revealRange(attrOrTextNodeStartOffset, 0); - } - // if(moveCursor) { - // System.out.print("moving"); - // } - // else { - // System.out.print("not moving"); - // } - // System.out.println(" on NodeSelectionEvent: " + - // event.getSource()); - } - } - - /** - * TODO Temporary workaround for BUG44665 - */ - /** - * @see VerifyListener#verifyText(VerifyEvent) - */ - 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; - } - - fDocumentCommand.setEventStructuredDocumentEvent(e, modelRange); - customizeDocumentCommand(fDocumentCommand); - int widgetCaret = 0; - if (!fDocumentCommand.fillEventStructuredDocumentCommand(e, modelRange)) { - - boolean compoundChange = fDocumentCommand.getCommandCount() > 1; - try { - - fVerifyListener.forward(false); - - if (compoundChange && fUndoManager != null) - fUndoManager.beginCompoundChange(); - - if (getSlaveDocumentManager() != null) { - IDocument visible = getVisibleDocument(); - try { - getSlaveDocumentManager().setAutoExpandMode(visible, true); - fDocumentCommand.executeStructuredDocumentCommand(getDocument()); - } finally { - getSlaveDocumentManager().setAutoExpandMode(visible, false); - } - } else { - fDocumentCommand.executeStructuredDocumentCommand(getDocument()); - } - - if (getTextWidget() != null) { - int documentCaret = fDocumentCommand.caretOffset; - if (documentCaret == -1) { - // old behavior of document command - documentCaret = fDocumentCommand.offset + (fDocumentCommand.text == null ? 0 : fDocumentCommand.text.length()); - } - - widgetCaret = modelOffset2WidgetOffset(documentCaret); - if (widgetCaret == -1) { - // try to move it to the closest spot - IRegion region = getModelCoverage(); - if (documentCaret <= region.getOffset()) - widgetCaret = 0; - else if (documentCaret >= region.getOffset() + region.getLength()) - widgetCaret = getVisibleRegion().getLength(); - } - - } - } catch (BadLocationException x) { - - if (TRACE_ERRORS) - System.out.println("TextViewer.error.bad_location.verifyText"); //$NON-NLS-1$ - - } finally { - - if (compoundChange && fUndoManager != null) - fUndoManager.endCompoundChange(); - - if (widgetCaret != -1) { - // there is a valid widget caret - getTextWidget().setCaretOffset(widgetCaret); - } - - getTextWidget().showSelection(); - - fVerifyListener.forward(true); - - } - } - } - - 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); - } - - /** - * TODO Temporary workaround for BUG44665 - */ - /** - * overridden for read-only support - */ - /* - * protected void handleVerifyEvent(VerifyEvent e) { // for now, we'll let - * super have a shot first // (may mess up undo stack, or something?) - * - * super.handleVerifyEvent(e); if (containsReadOnly(getVisibleDocument(), - * e.start, e.end)) { e.doit = false; beep(); } } - */ - - /** - * @param selectedNodes - * @return whether the IndexedNodes within the list should form a - * selectionrange - */ - private boolean nothingToSelect(List selectedNodes) { - if (selectedNodes == null || selectedNodes.isEmpty() || selectedNodes.get(0) == null) // empty - // selections - return true; - if (getDocument() == null) // viewer shutdown - return true; - // if the range would be the entire document's length, there's nothing - // to show - IndexedRegion firstIndexedNode = (IndexedRegion) selectedNodes.get(0); - return firstIndexedNode.getEndOffset() - firstIndexedNode.getStartOffset() >= getDocument().getLength(); - } - - /** - * Notify the ViewerSelectionManager when text is selected - * programmatically, for example, by double-click processing or an editor - * action like Edit->SelectAll - */ - protected void notifyViewerSelectionManager(int offset, int length) { - if (fViewerSelectionManager != null) { - Event event = new Event(); - event.widget = getTextWidget(); - // sometimes null while closing - if (event.widget != null) { - SelectionEvent selectionEvent = new SelectionEvent(event); - selectionEvent.x = offset; - selectionEvent.y = offset + length; - fViewerSelectionManager.widgetSelected(selectionEvent); - } - } - } - - private void redo() { - ignoreAutoEditStrategies(true); - fUndoManager.redo(); - ignoreAutoEditStrategies(false); - } - - /* - * (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 - if (fHighlighter != null) { - fHighlighter.setDocument(structuredDocument); - } - - // 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); - } - } - - /** - * Use the active editor to set a status line message - * - * @param msg - */ - protected void setErrorMessage(String msg) { - IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); - if (window != null) { - IWorkbenchPage page = window.getActivePage(); - if (page != null) { - IEditorPart editor = page.getActiveEditor(); - if (editor != null) { - IEditorStatusLine statusLine = (IEditorStatusLine) editor.getAdapter(IEditorStatusLine.class); - if (statusLine != null) - statusLine.setMessage(true, msg, null); - } - } - } - } - - public void setViewerSelectionManager(ViewerSelectionManager viewerSelectionManager) { - // disconnect from old one - if (fViewerSelectionManager != null) { - fViewerSelectionManager.removeNodeDoubleClickListener(fSelectionListener); - fViewerSelectionManager.removeNodeSelectionListener(fSelectionListener); - fViewerSelectionManager.release(); - // No need to removeSelectionChangedListener here. Done when - // editor - // calls "new ViewerSelectionManagerImpl(ITextViewer)". - // removeSelectionChangedListener(fViewerSelectionManager); - } - fViewerSelectionManager = viewerSelectionManager; - // connect to new one - if (fViewerSelectionManager != null) { - fViewerSelectionManager.addNodeDoubleClickListener(fSelectionListener); - fViewerSelectionManager.addNodeSelectionListener(fSelectionListener); - // No need to addSelectionChangedListener here. Done when editor - // calls "new ViewerSelectionManagerImpl(ITextViewer)". - // addSelectionChangedListener(fViewerSelectionManager); - } - } - - /** - * 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(); - } - - // presentationreconciler, reconciler, contentassist, infopresenter - // are all unconfigured in superclass so think about removing from - // here - if (fPresentationReconciler != null) { - fPresentationReconciler.uninstall(); - fPresentationReconciler = null; - } - if (fReconciler != null) { - fReconciler.uninstall(); - fReconciler = null; - } - if (fContentAssistant != null) { - fContentAssistant.uninstall(); - fContentAssistantInstalled = false; - } - if (fInformationPresenter != null) - fInformationPresenter.uninstall(); - - setHyperlinkDetectors(null, SWT.NONE); - - // doesn't seem to be handled elsewhere, so we'll be sure error - // messages's are cleared. - setErrorMessage(null); - - // unconfigure recently added to super class?! - super.unconfigure(); - Logger.trace("Source Editor", "StructuredTextViewer::unconfigure exit"); //$NON-NLS-1$ //$NON-NLS-2$ - } - - private void undo() { - ignoreAutoEditStrategies(true); - fUndoManager.undo(); - ignoreAutoEditStrategies(false); - } - - /* - * (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())) - setSelectedRange(event.getOffset(), event.getLength()); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/ViewerSelectionManager.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/ViewerSelectionManager.java deleted file mode 100644 index 658ff9f4b8..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/ViewerSelectionManager.java +++ /dev/null @@ -1,52 +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; - - - -import java.util.List; - -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.viewers.IDoubleClickListener; -import org.eclipse.jface.viewers.ISelectionChangedListener; -import org.eclipse.swt.events.SelectionListener; -import org.eclipse.wst.sse.core.IStructuredModel; -import org.eclipse.wst.sse.ui.view.events.ICaretListener; -import org.eclipse.wst.sse.ui.view.events.INodeSelectionListener; -import org.eclipse.wst.sse.ui.view.events.ITextSelectionListener; - - -public interface ViewerSelectionManager extends ICaretListener, IDoubleClickListener, ISelectionChangedListener, SelectionListener { - - void addNodeDoubleClickListener(IDoubleClickListener listener); - - void addNodeSelectionListener(INodeSelectionListener listener); - - void addTextSelectionListener(ITextSelectionListener listener); - - int getCaretPosition(); - - List getSelectedNodes(); - - void release(); - - void removeNodeDoubleClickListener(IDoubleClickListener listener); - - void removeNodeSelectionListener(INodeSelectionListener listener); - - void removeTextSelectionListener(ITextSelectionListener listener); - - void setModel(IStructuredModel newModel); - - void setTextViewer(ITextViewer newTextViewer); -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/ViewerSelectionManagerImpl.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/ViewerSelectionManagerImpl.java deleted file mode 100644 index 97989794e0..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/ViewerSelectionManagerImpl.java +++ /dev/null @@ -1,638 +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; - -import java.util.ArrayList; -import java.util.List; -import java.util.Vector; - -import org.eclipse.jface.text.ITextSelection; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.util.SafeRunnable; -import org.eclipse.jface.viewers.DoubleClickEvent; -import org.eclipse.jface.viewers.IDoubleClickListener; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.viewers.SelectionChangedEvent; -import org.eclipse.swt.custom.StyledText; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.widgets.Event; -import org.eclipse.wst.sse.core.IModelStateListener; -import org.eclipse.wst.sse.core.IStructuredModel; -import org.eclipse.wst.sse.core.IndexedRegion; -import org.eclipse.wst.sse.core.internal.util.Debug; -import org.eclipse.wst.sse.core.internal.util.Utilities; -import org.eclipse.wst.sse.ui.view.events.CaretEvent; -import org.eclipse.wst.sse.ui.view.events.INodeSelectionListener; -import org.eclipse.wst.sse.ui.view.events.ITextSelectionListener; -import org.eclipse.wst.sse.ui.view.events.NodeSelectionChangedEvent; -import org.eclipse.wst.sse.ui.view.events.TextSelectionChangedEvent; - - -public class ViewerSelectionManagerImpl implements ViewerSelectionManager { - - class InternalModelStateListener implements IModelStateListener { - - public void modelAboutToBeChanged(IStructuredModel model) { - setModelChanging(true); - } - - public void modelChanged(IStructuredModel model) { - setModelChanging(false); - } - - public void modelDirtyStateChanged(IStructuredModel model, boolean isDirty) { - } - - public void modelResourceDeleted(IStructuredModel model) { - } - - public void modelResourceMoved(IStructuredModel originalmodel, IStructuredModel movedmodel) { - } - - public void modelAboutToBeReinitialized(IStructuredModel structuredModel) { - } - - public void modelReinitialized(IStructuredModel structuredModel) { - } - - } - - private CaretMediator fCaretMeditator; - private int fCaretPosition = 0; - protected IStructuredModel fModel; - private boolean fModelChanging = false; - - private IDoubleClickListener[] fNodeDoubleClickListeners; - private INodeSelectionListener[] fNodeSelectionListeners; - private List fSelectedNodes; - - private int fTextSelectionEnd; - private ITextSelectionListener[] fTextSelectionListeners; - private int fTextSelectionStart; - private ITextViewer fTextViewer; - private InternalModelStateListener internalModelStateListener; - private boolean isFiringNodeSelectionChanged = false; - - public ViewerSelectionManagerImpl() { - internalModelStateListener = new InternalModelStateListener(); - } - - public ViewerSelectionManagerImpl(ITextViewer textViewer) { - setTextViewer(textViewer); - - internalModelStateListener = new InternalModelStateListener(); - } - - public synchronized void addNodeDoubleClickListener(IDoubleClickListener listener) { - // since its most certainly an error if someone is trying to add a - // null listner, - // we'll flag it explicitly and ignore - if (listener == null) { - Logger.log(Logger.WARNING, "Likely error in ViewerSelectionManagerImpl::addNodeDoubleClickListener should not be called with null listener"); //$NON-NLS-1$ - return; - } - // make sure listlistener not already in listening array - // (and if it is, print a warning to aid debugging, if needed) - if (Utilities.contains(fNodeDoubleClickListeners, listener)) { - if (Debug.displayWarnings) { - System.out.println("ViewerSelectionManager::addNodeDoubleClickListener. listener " + listener + " was added more than once. "); //$NON-NLS-2$//$NON-NLS-1$ - } - } - else { - if (Debug.debugStructuredDocument) { - System.out.println("ViewerSelectionManager::addNodeDoubleClickListener. Adding an instance of " + listener.getClass() + " as a listener on ViewerSelectionManager."); //$NON-NLS-2$//$NON-NLS-1$ - } - int oldSize = 0; - if (fNodeDoubleClickListeners != null) { - // normally won't be null, but we need to be sure, for first - // time through - oldSize = fNodeDoubleClickListeners.length; - } - int newSize = oldSize + 1; - IDoubleClickListener[] newListeners = new IDoubleClickListener[newSize]; - if (fNodeDoubleClickListeners != null) { - System.arraycopy(fNodeDoubleClickListeners, 0, newListeners, 0, oldSize); - } - // add listener to last position - newListeners[newSize - 1] = listener; - // - // now switch new for old - fNodeDoubleClickListeners = newListeners; - - } - } - - public synchronized void addNodeSelectionListener(INodeSelectionListener listener) { - // since its most certainly an error if someone is trying to add a - // null listner, - // we'll flag it explicitly and ignore - if (listener == null) { - Logger.log(Logger.WARNING, "Likely error in ViewerSelectionManagerImpl::addNodeSelectionListener should not but called with null listener"); //$NON-NLS-1$ - return; - } - // make sure listener is not already in listening array - // (and if it is, print a warning to aid debugging, if needed) - if (Utilities.contains(fNodeSelectionListeners, listener)) { - if (Debug.displayWarnings) { - System.out.println("ViewerSelectionManager::addNodeSelectionListener. listener " + listener + " was added more than once. "); //$NON-NLS-2$//$NON-NLS-1$ - } - } - else { - if (Debug.debugStructuredDocument) { - System.out.println("ViewerSelectionManager::addNodeSelectionListener. Adding an instance of " + listener.getClass() + " as a listener on ViewerSelectionManager."); //$NON-NLS-2$//$NON-NLS-1$ - } - int oldSize = 0; - if (fNodeSelectionListeners != null) { - // normally won't be null, but we need to be sure, for first - // time through - oldSize = fNodeSelectionListeners.length; - } - int newSize = oldSize + 1; - INodeSelectionListener[] newListeners = new INodeSelectionListener[newSize]; - if (fNodeSelectionListeners != null) { - System.arraycopy(fNodeSelectionListeners, 0, newListeners, 0, oldSize); - } - // add listener to last position - newListeners[newSize - 1] = listener; - // - // now switch new for old - fNodeSelectionListeners = newListeners; - - } - } - - public synchronized void addTextSelectionListener(ITextSelectionListener listener) { - // since its most certainly an error if someone is trying to add a - // null listner, - // we'll flag it explicitly and ignore - if (listener == null) { - Logger.log(Logger.WARNING, "Likely error in ViewerSelectionManagerImpl::addTextSelectionListener should not but called with null listener"); //$NON-NLS-1$ - return; - } - // make sure listener is not already in listening array - // (and if it is, print a warning to aid debugging, if needed) - if (Utilities.contains(fTextSelectionListeners, listener)) { - if (Debug.displayWarnings) { - System.out.println("ViewerSelectionManager::addTextSelectionListener. listener " + listener + " was added more than once. "); //$NON-NLS-2$//$NON-NLS-1$ - } - } - else { - if (Debug.debugStructuredDocument) { - System.out.println("ViewerSelectionManager::addTextSelectionListener. Adding an instance of " + listener.getClass() + " as a listener on ViewerSelectionManager."); //$NON-NLS-2$//$NON-NLS-1$ - } - int oldSize = 0; - if (fTextSelectionListeners != null) { - // normally won't be null, but we need to be sure, for first - // time through - oldSize = fTextSelectionListeners.length; - } - int newSize = oldSize + 1; - ITextSelectionListener[] newListeners = new ITextSelectionListener[newSize]; - if (fTextSelectionListeners != null) { - System.arraycopy(fTextSelectionListeners, 0, newListeners, 0, oldSize); - } - // add listener to last position - newListeners[newSize - 1] = listener; - // - // now switch new for old - fTextSelectionListeners = newListeners; - - } - } - - /** - * This method listens to text widget caret movements. This method is - * called when a caret (insertion point) move occurs that is NOT the - * result of the text changing. Specifcally, as a result of mouse clicks, - * PAGE_UP, RIGHT_ARROW, etc. - */ - public void caretMoved(final CaretEvent event) { - if (!isModelChanging()) { - List selectedNodes = getTextWidgetSelectedNodes(event.getPosition()); - int caretPosition = event.getPosition(); - processSelectionChanged(event.getSource(), selectedNodes, caretPosition, caretPosition); - } - } - - protected void currentNodeChanged(Object source, List newSelectedNodes, int caretPosition) { - // save current node; make sure to clone the selected nodes list, or - // else there may be a side effect when listeners modify the list - fSelectedNodes = new Vector(newSelectedNodes); - // save current caret position - fCaretPosition = caretPosition; - // generate and fire event - NodeSelectionChangedEvent nodeSelectionChangedEvent = new NodeSelectionChangedEvent(source, newSelectedNodes, caretPosition); - fireNodeSelectionChangedEvent(nodeSelectionChangedEvent); - } - - /** - * Notifies of a double click. - * - * @param event - * event object describing the double-click - */ - public void doubleClick(DoubleClickEvent event) { - if (!isModelChanging()) - fireNodeDoubleClickEvent(event); - } - - protected void fireNodeDoubleClickEvent(final DoubleClickEvent event) { - if ((fNodeDoubleClickListeners != null) && (!isModelChanging())) { - /* - * We must assign listeners to a local variable to be thread safe, - * since the add and remove listener 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 further) - */ - final IDoubleClickListener[] holdListeners = fNodeDoubleClickListeners; - - for (int i = 0; i < holdListeners.length; i++) { - final IDoubleClickListener currentListener = holdListeners[i]; - SafeRunnable.run(new SafeRunnable() { - public void run() throws Exception { - currentListener.doubleClick(event); - } - }); - } - } - } - - protected void fireNodeSelectionChangedEvent(final NodeSelectionChangedEvent event) { - if ((fNodeSelectionListeners != null) && (!isModelChanging())) { - isFiringNodeSelectionChanged = true; - /* - * We must assign listeners to a local variable to be thread safe, - * since the add and remove listener 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 further) - */ - final INodeSelectionListener[] holdListeners = fNodeSelectionListeners; - - try { - for (int i = 0; i < holdListeners.length; i++) { - final INodeSelectionListener currentListener = holdListeners[i]; - SafeRunnable.run(new SafeRunnable() { - public void run() throws Exception { - currentListener.nodeSelectionChanged(event); - } - }); - } - } - finally { - isFiringNodeSelectionChanged = false; - } - } - } - - protected void fireTextSelectionChangedEvent(final TextSelectionChangedEvent event) { - if ((fTextSelectionListeners != null) && (!isModelChanging())) { - /* - * We must assign listeners to a local variable to be thread safe, - * since the add and remove listener 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 further) - */ - final ITextSelectionListener[] holdListeners = fTextSelectionListeners; - - for (int i = 0; i < holdListeners.length; i++) { - final ITextSelectionListener currentListener = holdListeners[i]; - SafeRunnable.run(new SafeRunnable() { - public void run() throws Exception { - currentListener.textSelectionChanged(event); - } - }); - } - } - } - - public int getCaretPosition() { - return fCaretPosition; - } - - public List getSelectedNodes() { - return fSelectedNodes; - } - - public ITextViewer getTextViewer() { - return fTextViewer; - } - - protected List getTextWidgetSelectedNodes(int offset) { - if (fModel == null) - return new ArrayList(0); - - IndexedRegion firstSelectedNode = fModel.getIndexedRegion(offset); - - // Never send a "null" in the selection - List selectedNodes = null; - if (firstSelectedNode != null) { - selectedNodes = new ArrayList(1); - selectedNodes.add(firstSelectedNode); - } - else { - selectedNodes = new ArrayList(0); - } - return selectedNodes; - } - - protected boolean isCurrentNodeChanged(List newSelectedNodes) { - return !newSelectedNodes.equals(fSelectedNodes); - } - - protected boolean isModelChanging() { - return fModelChanging; - } - - protected boolean isTextSelectionChanged(int textSelectionStart, int textSelectionEnd) { - return ((fTextSelectionStart != textSelectionStart) || (fTextSelectionEnd != textSelectionEnd)); - } - - protected void processSelectionChanged(Object source, List selectedNodes, int selectionStart, int selectionEnd) { - if (source == null) { - // source should not be null. - // log this and ignore this selection changed event. - // DMW: I "shortened" this log message by removing stack trace, - // after receiving log - // from support showing this error. It made the log file - // confusing. - // Not clear why the source was null, but probably only related to - // initialization, or 'startup' with file open. - Logger.log(Logger.ERROR, "ViewerSelectionManager::processSelectionChanged. Unexpected null source"); //$NON-NLS-1$ - } - else { - if (isTextSelectionChanged(selectionStart, selectionEnd)) - textSelectionChanged(source, selectionStart, selectionEnd); - - if (isCurrentNodeChanged(selectedNodes)) - currentNodeChanged(source, selectedNodes, selectionEnd); - } - } - - public void release() { - setTextViewer(null); - - // remove this viewer selection manager from the old model's list of - // model state listeners - if (fModel != null) - fModel.removeModelStateListener(internalModelStateListener); - - // make sure the CaretMediator we created is released as well - fCaretMeditator.release(); - } - - public synchronized void removeNodeDoubleClickListener(IDoubleClickListener listener) { - if ((fNodeDoubleClickListeners != null) && (listener != null)) { - // if its not in the listeners, we'll ignore the request - if (Utilities.contains(fNodeDoubleClickListeners, listener)) { - int oldSize = fNodeDoubleClickListeners.length; - int newSize = oldSize - 1; - IDoubleClickListener[] newListeners = new IDoubleClickListener[newSize]; - int index = 0; - for (int i = 0; i < oldSize; i++) { - if (fNodeDoubleClickListeners[i] == listener) { // ignore - } - else { - // copy old to new if its not the one we are removing - newListeners[index++] = fNodeDoubleClickListeners[i]; - } - } - // now that we have a new array, let's switch it for the old - // one - fNodeDoubleClickListeners = newListeners; - } - } - } - - public synchronized void removeNodeSelectionListener(INodeSelectionListener listener) { - if ((fNodeSelectionListeners != null) && (listener != null)) { - // if its not in the listeners, we'll ignore the request - if (Utilities.contains(fNodeSelectionListeners, listener)) { - int oldSize = fNodeSelectionListeners.length; - int newSize = oldSize - 1; - INodeSelectionListener[] newListeners = new INodeSelectionListener[newSize]; - int index = 0; - for (int i = 0; i < oldSize; i++) { - if (fNodeSelectionListeners[i] == listener) { // ignore - } - else { - // copy old to new if its not the one we are removing - newListeners[index++] = fNodeSelectionListeners[i]; - } - } - // now that we have a new array, let's switch it for the old - // one - fNodeSelectionListeners = newListeners; - } - } - } - - public synchronized void removeTextSelectionListener(ITextSelectionListener listener) { - if ((fTextSelectionListeners != null) && (listener != null)) { - // if its not in the listeners, we'll ignore the request - if (Utilities.contains(fTextSelectionListeners, listener)) { - int oldSize = fTextSelectionListeners.length; - int newSize = oldSize - 1; - ITextSelectionListener[] newListeners = new ITextSelectionListener[newSize]; - int index = 0; - for (int i = 0; i < oldSize; i++) { - if (fTextSelectionListeners[i] == listener) { // ignore - } - else { - // copy old to new if its not the one we are removing - newListeners[index++] = fTextSelectionListeners[i]; - } - } - // now that we have a new array, let's switch it for the old - // one - fTextSelectionListeners = newListeners; - } - } - } - - public void selectionChanged(SelectionChangedEvent event) { - // If selection is fired as a result of processing a node change - // event, then ignore the selection. - if (isFiringNodeSelectionChanged || isModelChanging()) - return; - - ISelection eventSelection = event.getSelection(); - // handle Structured selections - if (eventSelection instanceof IStructuredSelection) { - IStructuredSelection selection = (IStructuredSelection) eventSelection; - // the selection we were given - List selectionNodes = selection.toList(); - // the selected nodes we'll actually propagate - List selectNodes = null; - - int selectionStart = 0; - int selectionEnd = 0; - - /* - * Find the first IndexedNode in the selection and compute a text - * selection from it - */ - int l = selectionNodes.size(); - for (int i = 0; i < l; i++) { - Object o = selectionNodes.get(i); - if (o instanceof IndexedRegion) { - IndexedRegion firstSelectedNode = (IndexedRegion) o; - selectionStart = firstSelectedNode.getStartOffset(); - selectionEnd = firstSelectedNode.getEndOffset(); - // only pass along the first selected node - selectNodes = new Vector(1); - selectNodes.add(firstSelectedNode); - } - } - if (selectNodes == null) { - selectNodes = selectionNodes; - } - - processSelectionChanged(event.getSource(), selectNodes, selectionStart, selectionEnd); - } - // handle text selection changes - else if (eventSelection instanceof ITextSelection) { - ITextSelection selection = (ITextSelection) eventSelection; - // System.out.println("selection: " + event.getSource() + " (" + - // selection.getOffset() + "+=" + selection.getLength() + ")"); - int selectionStart = selection.getOffset(); - setCaretPosition(selectionStart); - int selectionEnd = selection.getOffset() + selection.getLength(); - if (true) { - // option 1: works great for Source Page editors and the XML - // and XSL Editors - List selectedNodes = getTextWidgetSelectedNodes(selection.getOffset()); - processSelectionChanged(event.getSource(), selectedNodes, selectionStart, selectionEnd); - } - else { - // option 2: works with all of the above plus Page Designer, - // but not as clean nor perfectly - Event selectionEvent = new Event(); - selectionEvent.widget = fTextViewer.getTextWidget(); - selectionEvent.display = fTextViewer.getTextWidget().getDisplay(); - selectionEvent.x = selectionStart; - selectionEvent.y = selectionEnd; - fTextViewer.getTextWidget().setSelection(selectionStart, selectionEnd); - widgetDefaultSelected(new SelectionEvent(selectionEvent)); - } - } - } - - protected void setCaretPosition(int caretPosition) { - fCaretPosition = caretPosition; - } - - public void setModel(IStructuredModel newModel) { - if (newModel != fModel) { - // remove this viewer selection manager from the old model's list - // of model state listeners - if (fModel != null) - fModel.removeModelStateListener(internalModelStateListener); - - fModel = newModel; - - // add this viewer selection manager to the new model's list of - // model state listeners - fModel.addModelStateListener(internalModelStateListener); - } - } - - protected void setModelChanging(boolean modelChanging) { - fModelChanging = modelChanging; - } - - /** - * This is the viewer who's caret postion we monitor to determine when to - * check if the node has changed. We don't actually need, or save, the - * viewer, but do need its text widget, and will register this viewer - * selection manager as a listener of the text widget's text selection. - */ - public void setTextViewer(ITextViewer newTextViewer) { - // unhook from previous, if any - if (fCaretMeditator != null) { - fCaretMeditator.removeCaretListener(this); - fCaretMeditator.setTextWidget(null); - } - if (fTextViewer != null) { - // fTextViewer.getSelectionProvider().removeSelectionChangedListener(this); - StyledText textWidget = fTextViewer.getTextWidget(); - if (textWidget != null) { - // listen to text selections - textWidget.removeSelectionListener(this); - } - } - - fTextViewer = newTextViewer; - - if (fTextViewer != null) { - // fTextViewer.getSelectionProvider().addSelectionChangedListener(this); - StyledText textWidget = fTextViewer.getTextWidget(); - if (textWidget != null) { - // create new caret mediator, if it doesn't exist yet - if (fCaretMeditator == null) { - fCaretMeditator = new CaretMediator(textWidget); - } - else { - fCaretMeditator.setTextWidget(textWidget); - } - // and register as a listener - fCaretMeditator.addCaretListener(this); - - // listen to text selections - textWidget.addSelectionListener(this); - } - } - } - - protected void textSelectionChanged(Object source, int textSelectionStart, int textSelectionEnd) { - // save current text selection - fTextSelectionStart = textSelectionStart; - fTextSelectionEnd = textSelectionEnd; - // save current caret position - fCaretPosition = fTextSelectionEnd; - // generate and fire event - TextSelectionChangedEvent textSelectionChangedEvent = new TextSelectionChangedEvent(source, fTextSelectionStart, fTextSelectionEnd); - fireTextSelectionChangedEvent(textSelectionChangedEvent); - } - - /** - * This method listens to text widget default selection changes. This - * method is called when default selection occurs in the control. For - * example, on some platforms default selection occurs in a List when the - * user double-clicks an item or types return in a Text. - */ - public void widgetDefaultSelected(SelectionEvent event) { - if (!isModelChanging()) { - List selectedNodes = getTextWidgetSelectedNodes(event.x); - int selectionStart = event.x; - int selectionEnd = event.y; - processSelectionChanged(event.getSource(), selectedNodes, selectionStart, selectionEnd); - } - } - - /** - * This method listens to text widget text selection changes. This method - * is called when the text selection in a text widget has changed. - */ - public void widgetSelected(SelectionEvent event) { - // If selection is fired as a result of processing a node change - // event, then ignore the selection. - if (isFiringNodeSelectionChanged || isModelChanging()) - return; - - widgetDefaultSelected(event); - } -} 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 307191b6e9..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/actions/ActionContributor.java +++ /dev/null @@ -1,377 +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.actions; - -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.ui.IActionBars; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.IWorkbenchActionConstants; -import org.eclipse.ui.IWorkbenchPage; -import org.eclipse.ui.actions.ActionFactory; -import org.eclipse.ui.editors.text.TextEditorActionContributor; -import org.eclipse.ui.ide.IDEActionFactory; -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.extension.ExtendedEditorActionBuilder; -import org.eclipse.wst.sse.ui.extension.IExtendedContributor; -import org.eclipse.wst.sse.ui.internal.GotoAnnotationAction; -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")); //$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; - - public ActionContributor() { - super(); - - ResourceBundle resourceBundle = SSEUIMessages.getResourceBundle(); - - fCommandsSeparator = new Separator(); - - // edit commands - fStructureSelectEnclosingAction = new RetargetTextEditorAction(resourceBundle, StructuredTextEditorActionConstants.ACTION_NAME_STRUCTURE_SELECT_ENCLOSING + StructuredTextEditorActionConstants.DOT); - fStructureSelectEnclosingAction.setActionDefinitionId(ActionDefinitionIds.STRUCTURE_SELECT_ENCLOSING); - - fStructureSelectNextAction = new RetargetTextEditorAction(resourceBundle, StructuredTextEditorActionConstants.ACTION_NAME_STRUCTURE_SELECT_NEXT + StructuredTextEditorActionConstants.DOT); - fStructureSelectNextAction.setActionDefinitionId(ActionDefinitionIds.STRUCTURE_SELECT_NEXT); - - fStructureSelectPreviousAction = new RetargetTextEditorAction(resourceBundle, StructuredTextEditorActionConstants.ACTION_NAME_STRUCTURE_SELECT_PREVIOUS + StructuredTextEditorActionConstants.DOT); - fStructureSelectPreviousAction.setActionDefinitionId(ActionDefinitionIds.STRUCTURE_SELECT_PREVIOUS); - - fStructureSelectHistoryAction = new RetargetTextEditorAction(resourceBundle, StructuredTextEditorActionConstants.ACTION_NAME_STRUCTURE_SELECT_HISTORY + StructuredTextEditorActionConstants.DOT); - 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.DOT); - fShiftRight.setActionDefinitionId(ITextEditorActionDefinitionIds.SHIFT_RIGHT); - - fShiftLeft = new RetargetTextEditorAction(resourceBundle, ITextEditorActionConstants.SHIFT_LEFT + StructuredTextEditorActionConstants.DOT); - fShiftLeft.setActionDefinitionId(ITextEditorActionDefinitionIds.SHIFT_LEFT); - - fToggleComment = new RetargetTextEditorAction(resourceBundle, StructuredTextEditorActionConstants.ACTION_NAME_TOGGLE_COMMENT + StructuredTextEditorActionConstants.DOT); - fToggleComment.setActionDefinitionId(ActionDefinitionIds.TOGGLE_COMMENT); - - fAddBlockComment = new RetargetTextEditorAction(resourceBundle, StructuredTextEditorActionConstants.ACTION_NAME_ADD_BLOCK_COMMENT + StructuredTextEditorActionConstants.DOT); - fAddBlockComment.setActionDefinitionId(ActionDefinitionIds.ADD_BLOCK_COMMENT); - - fRemoveBlockComment = new RetargetTextEditorAction(resourceBundle, StructuredTextEditorActionConstants.ACTION_NAME_REMOVE_BLOCK_COMMENT + StructuredTextEditorActionConstants.DOT); - 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$ - - // 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); - } - } - - 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); - - 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); - - 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) { - 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 b26dae1cf0..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/actions/ActionDefinitionIds.java +++ /dev/null @@ -1,42 +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.actions; - - - -/** - * 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 INFORMATION = "org.eclipse.wst.sse.ui.show.javadoc";//$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 QUICK_FIX = "org.eclipse.wst.sse.ui.edit.text.java.correction.assist.proposals";//$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$ -} 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 0c34e0169d..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/actions/ActiveEditorActionHandler.java +++ /dev/null @@ -1,284 +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.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; - -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 17979a9581..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, 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.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.IStructuredModel; -import org.eclipse.wst.sse.core.internal.cleanup.IStructuredCleanupProcessor; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; -import org.eclipse.wst.sse.ui.internal.StructuredTextEditor; - -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 32f140a390..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/actions/FormatActionDelegate.java +++ /dev/null @@ -1,227 +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.actions; - -import java.io.IOException; - -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.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.wst.sse.core.internal.exceptions.MalformedInputExceptionWithDetail; -import org.eclipse.wst.sse.core.internal.format.IStructuredFormatProcessor; -import org.eclipse.wst.sse.ui.extension.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); - } - - /** - * @param container - * @return - */ - private int getResourceCount(IResource[] members) { - int count = 0; - - for (int i = 0; i < members.length; i++) { - if (members[i] instanceof IContainer) { - IContainer container = (IContainer) members[i]; - try { - count += getResourceCount(container.members()); - } catch (CoreException e) { - // skip counting - } - } else - count++; - } - - return count; - } - - /** - * @param elements - * @return - */ - private int getResourceCount(Object[] elements) { - int count = 0; - - for (int i = 0; i < elements.length; i++) { - if (elements[i] instanceof IContainer) { - IContainer container = (IContainer) elements[i]; - try { - count += getResourceCount(container.members()); - } catch (CoreException e) { - // skip counting - } - } else - count++; - } - - return count; - } - - protected IStatus run(IProgressMonitor monitor) { - IStatus status = Status.OK_STATUS; - - Object[] elements = fSelection.toArray(); - int resourceCount = getResourceCount(elements); - monitor.beginTask("", resourceCount); //$NON-NLS-1$ - for (int i = 0; i < elements.length; i++) { - if (elements[i] instanceof IResource) { - process(monitor, (IResource) elements[i]); - 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) { - try { - monitor.worked(1); - IContentDescription contentDescription = file.getContentDescription(); - if (contentDescription == null) - return; - - 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()}); - monitor.subTask(message); - formatProcessor.setProgressMonitor(monitor); - formatProcessor.formatFile(file); - } - } 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(IProgressMonitor monitor, IResource resource) { - if (resource instanceof IFile) { - IFile file = (IFile) resource; - - if (monitor == null || !monitor.isCanceled()) - format(monitor, file); - } else if (resource instanceof IContainer) { - IContainer container = (IContainer) resource; - - try { - IResource[] members = container.members(); - for (int i = 0; i < members.length; i++) { - if (monitor == null || !monitor.isCanceled()) - format(monitor, members[i]); - } - } 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) { - format(monitor, resource); - - try { - resource.refreshLocal(IResource.DEPTH_INFINITE, null); - } 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)); - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.sse.ui.edit.util.ResourceActionDelegate#processorAvailable(org.eclipse.core.resources.IResource) - */ - protected boolean processorAvailable(IResource resource) { - boolean result = false; - 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 3e2686a313..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/actions/ResourceActionDelegate.java +++ /dev/null @@ -1,75 +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.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; - -public class ResourceActionDelegate implements IActionDelegate { - protected IStructuredSelection fSelection; - - 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) - 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 8d411b1484..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/actions/StructuredTextEditorActionConstants.java +++ /dev/null @@ -1,44 +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.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_INFORMATION = "ShowTooltipDesc";//$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_QUICK_FIX = "QuickFix";//$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 DOT = ".";//$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/autoedit/BasicAutoEditStrategy.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/autoedit/BasicAutoEditStrategy.java deleted file mode 100644 index 08e9db5e01..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/autoedit/BasicAutoEditStrategy.java +++ /dev/null @@ -1,47 +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.autoedit; - -import org.eclipse.jface.text.IAutoEditStrategy; -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; - -public abstract class BasicAutoEditStrategy implements IAutoEditStrategy { - /** - * Return the active text editor if possible, otherwise the active editor - * part. - * - * @return - */ - protected Object getActiveTextEditor() { - IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); - if (window != null) { - IWorkbenchPage page = window.getActivePage(); - if (page != null) { - IEditorPart editor = page.getActiveEditor(); - if (editor != null) { - if (editor instanceof ITextEditor) - return editor; - ITextEditor textEditor = (ITextEditor) editor.getAdapter(ITextEditor.class); - if (textEditor != null) - return textEditor; - return editor; - } - } - } - return null; - } -} 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 79f672b448..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentassist/ContentAssistUtils.java +++ /dev/null @@ -1,92 +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; - -import org.eclipse.wst.sse.core.IModelManager; -import org.eclipse.wst.sse.core.IStructuredModel; -import org.eclipse.wst.sse.core.IndexedRegion; -import org.eclipse.wst.sse.core.StructuredModelManager; -import org.eclipse.wst.sse.core.text.IStructuredDocument; -import org.eclipse.wst.sse.core.text.IStructuredDocumentRegion; -import org.eclipse.wst.sse.ui.internal.StructuredTextViewer; - - -/** - * @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(StructuredTextViewer 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(StructuredTextViewer 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; - } - -} 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 9872fb219a..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentassist/CustomCompletionProposal.java +++ /dev/null @@ -1,315 +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; - -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 Image fImage; - - private int fOriginalReplacementLength; - - 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) { - fReplacementString = replacementString; - fReplacementOffset = replacementOffset; - fReplacementLength = replacementLength; - fCursorPosition = cursorPosition; - fImage = image; - fDisplayString = displayString; - fContextInformation = contextInformation; - fAdditionalProposalInfo = additionalProposalInfo; - fRelevance = relevance; - fUpdateLengthOnValidate = updateReplacementLengthOnValidate; - fOriginalReplacementLength = fReplacementLength; - } - - 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 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() { - return getCursorPosition(); - } - - public int getCursorPosition() { - return fCursorPosition; - } - - public void setCursorPosition(int pos) { - fCursorPosition = pos; - } - - public String getDisplayString() { - // return fProposal.getDisplayString(); - return fDisplayString; - } - - public Image getImage() { - // return fProposal.getImage(); - return fImage; - } - - public int getRelevance() { - return fRelevance; - } - - 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.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); - // CMVC 269884 - if (fUpdateLengthOnValidate) { - int newLength = offset - getReplacementOffset(); - int delta = newLength - fOriginalReplacementLength; - fReplacementLength = delta + fOriginalReplacementLength; - } - 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 d67b10e63e..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, 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; - - -/** - * 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/IResourceDependentProcessor.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentassist/IResourceDependentProcessor.java deleted file mode 100644 index 8e3e21245a..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentassist/IResourceDependentProcessor.java +++ /dev/null @@ -1,25 +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; - -import org.eclipse.core.resources.IResource; - -/** - * Interface for classes that require an IResource to operate properly (eg. - * some ContentAssistProcessors) - * - * @author pavery - */ -public interface IResourceDependentProcessor { - void initialize(IResource resource); -} 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 5301077d94..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentoutline/IJFaceNodeAdapter.java +++ /dev/null @@ -1,44 +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.contentoutline; - - - -import org.eclipse.swt.graphics.Image; -import org.eclipse.wst.sse.core.INodeAdapter; - - -public interface IJFaceNodeAdapter extends INodeAdapter { - - 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 2a47fe1456..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, 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.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 3a538c2d01..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, 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.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 5c642ea2ac..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, 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.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/contentoutline/SourceEditorTreeViewer.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentoutline/SourceEditorTreeViewer.java deleted file mode 100644 index 86692dddb9..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentoutline/SourceEditorTreeViewer.java +++ /dev/null @@ -1,238 +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.contentoutline; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.SelectionChangedEvent; -import org.eclipse.jface.viewers.StructuredSelection; -import org.eclipse.jface.viewers.TreeViewer; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Item; -import org.eclipse.swt.widgets.Tree; -import org.eclipse.swt.widgets.Widget; -import org.eclipse.ui.ISelectionListener; -import org.eclipse.wst.sse.core.IStructuredModel; -import org.eclipse.wst.sse.ui.internal.StructuredTextSelectionChangedEvent; - - -public class SourceEditorTreeViewer extends TreeViewer { - private int fCaretPosition; - private ISelectionListener[] fInvalidSelectionListeners = null; - - /** - * SourceEditorTreeViewer constructor comment. - * - * @param parent - * org.eclipse.swt.widgets.Composite - */ - public SourceEditorTreeViewer(Composite parent) { - super(parent); - } - - /** - * SourceEditorTreeViewer constructor comment. - * - * @param tree - * org.eclipse.swt.widgets.Tree - */ - public SourceEditorTreeViewer(Tree tree) { - super(tree); - } - - public synchronized void addInvalidSelectionListener(ISelectionListener listener) { - ISelectionListener[] newListeners = fInvalidSelectionListeners; - if (fInvalidSelectionListeners != null && fInvalidSelectionListeners.length > 0) { - List oldListeners = new ArrayList(Arrays.asList(fInvalidSelectionListeners)); - if (!oldListeners.contains(listener)) { - oldListeners.add(listener); - newListeners = (ISelectionListener[]) oldListeners.toArray(new ISelectionListener[0]); - } - } else { - newListeners = new ISelectionListener[]{listener}; - } - fInvalidSelectionListeners = newListeners; - } - - /** - * @param newSelection - */ - private void fireInvalidSelection(ISelection newSelection) { - if (fInvalidSelectionListeners != null) { - ISelectionListener[] listeners = fInvalidSelectionListeners; - for (int i = 0; i < listeners.length; i++) { - listeners[i].selectionChanged(null, newSelection); - } - } - } - - protected void handleInvalidSelection(ISelection invalidSelection, ISelection newSelection) { - IStructuredModel model = (IStructuredModel) getInput(); - Object selectedNode = model.getIndexedRegion(fCaretPosition); - if (selectedNode != null) - newSelection = new StructuredSelection(selectedNode); - // notify listeners that the TreeViewer has received an invalid - // selection - fireInvalidSelection(newSelection); - setSelectionToWidget(newSelection, true); - super.handleInvalidSelection(invalidSelection, newSelection); - } - - protected void handleSelect(SelectionEvent event) { - // handle case where an earlier selection listener disposed the - // control. - Control control = getControl(); - if (control != null && !control.isDisposed()) { - updateStructuredTextSelection(getSelection()); - } - } - - /* - * (non-Javadoc) Method declared on StructuredViewer. - */ - public void internalRefresh(Object element) { - // If the input object is null just return. - if (element == null) - return; - - // The following skip refresh logic tries to optimize performance of - // the content outliner. - // However, when there is a structure change to the model, even if the - // selection is the same - // we should refresh the tree in case the structure change is in the - // children of the current selection. - // The following logic commented out for 178731. - // - // Skip refresh if new selection equals old selection. - //org.eclipse.jface.viewers.ISelection selection = getSelection(); - //if (selection instanceof - // org.eclipse.jface.viewers.IStructuredSelection) - // if (((org.eclipse.jface.viewers.IStructuredSelection) - // selection).size() == 1) - // if (((org.eclipse.jface.viewers.IStructuredSelection) - // selection).getFirstElement().equals(element)) - // return; - - Widget item = findItem(element); - if (item != null) { - // pick up structure changes too - internalRefresh(item, element, true); - } - } - - /** - * Refreshes the tree starting at the given widget. - * - * @param widget - * the widget - * @param element - * the element - * @param doStruct - * <code>true</code> if structural changes are to be picked - * up, and <code>false</code> if only label provider changes - * are of interest - */ - private void internalRefresh(Widget widget, Object element, boolean doStruct) { - // To avoid flashing, set repaint off while updating the tree. - //getControl().setRedraw(false); - - if (widget instanceof Item) { - if (doStruct) { - updatePlus((Item) widget, element); - } - updateItem(widget, element); - } - - if (doStruct) { - Object[] children = getSortedChildren(element); - updateChildren(widget, element, children); - } - // recurse - Item[] children = getChildren(widget); - if (children != null) { - for (int i = 0; i < children.length; i++) { - Widget item = children[i]; - Object data = item.getData(); - if (data != null) - internalRefresh(item, data, doStruct); - } - } - - // The purpose of the following line of code was to minimize the - // number of items in the tree needed to be repainted. - // Expanding/collapsing the tree for the user is a little confusing. - // Also, with new improvements to cut down unnesessary - // notifications to the tree, this may not be needed. - //expandToLevel(element, 1); - - //getControl().setRedraw(true); - } - - public synchronized void removeInvalidSelectionListener(ISelectionListener listener) { - ISelectionListener[] newListeners = fInvalidSelectionListeners; - if (fInvalidSelectionListeners != null && fInvalidSelectionListeners.length > 1) { - List oldListeners = new ArrayList(Arrays.asList(fInvalidSelectionListeners)); - if (oldListeners.contains(listener)) { - oldListeners.remove(listener); - newListeners = (ISelectionListener[]) oldListeners.toArray(new ISelectionListener[0]); - } - } - // there was only 1, remove the entire array - else { - newListeners = null; - } - fInvalidSelectionListeners = newListeners; - } - - /** - * Runs the given updateCode while selection changed notification is - * turned off. This ensures that no selection changes are fired as a side - * effect of updating the SWT control. - */ - - /* - * protected void preservingSelection(Runnable updateCode) { // This - * method is overridden to get rid of the selection handling // that the - * super classes do after the update. We have added our own // selection - * handling in here. IStructuredModel model = (IStructuredModel) - * getInput(); IndexedRegion node = null; - * - * if (model != null) node = model.getIndexedRegion(fCaretPosition); - * - * updateCode.run(); - * - * if (model != null) if (node == null) setSelection(new - * StructuredSelection()); else setSelection(new - * StructuredSelection(node)); } - */ - public void setCaretPosition(int caretPosition) { - fCaretPosition = caretPosition; - } - - public void setSelection(ISelection selection, boolean reveal) { - if (reveal) - updateStructuredTextSelection(selection); - - super.setSelection(selection, reveal); - } - - protected void updateStructuredTextSelection(ISelection selection) { - SelectionChangedEvent event = new StructuredTextSelectionChangedEvent(this, selection); - fireSelectionChanged(event); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentoutline/StructuredTextEditorContentOutlinePage.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentoutline/StructuredTextEditorContentOutlinePage.java deleted file mode 100644 index 9c2a08ead5..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/contentoutline/StructuredTextEditorContentOutlinePage.java +++ /dev/null @@ -1,586 +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.contentoutline; - -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.core.runtime.IAdaptable; -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.MenuManager; -import org.eclipse.jface.util.DelegatingDragAdapter; -import org.eclipse.jface.util.DelegatingDropAdapter; -import org.eclipse.jface.util.TransferDragSourceListener; -import org.eclipse.jface.util.TransferDropTargetListener; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.viewers.SelectionChangedEvent; -import org.eclipse.jface.viewers.StructuredSelection; -import org.eclipse.jface.viewers.TreeViewer; -import org.eclipse.swt.SWT; -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.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.Tree; -import org.eclipse.ui.IActionBars; -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.actions.ActionFactory; -import org.eclipse.ui.part.IShowInTarget; -import org.eclipse.ui.part.ShowInContext; -import org.eclipse.ui.texteditor.IUpdate; -import org.eclipse.ui.views.contentoutline.ContentOutlinePage; -import org.eclipse.wst.sse.core.IModelStateListener; -import org.eclipse.wst.sse.core.IStructuredModel; -import org.eclipse.wst.sse.core.internal.model.FactoryRegistry; -import org.eclipse.wst.sse.ui.internal.ViewerSelectionManager; -import org.eclipse.wst.sse.ui.internal.actions.ActiveEditorActionHandler; -import org.eclipse.wst.sse.ui.view.events.INodeSelectionListener; -import org.eclipse.wst.sse.ui.view.events.ITextSelectionListener; -import org.eclipse.wst.sse.ui.view.events.NodeSelectionChangedEvent; -import org.eclipse.wst.sse.ui.view.events.TextSelectionChangedEvent; -import org.eclipse.wst.sse.ui.views.contentoutline.ContentOutlineConfiguration; - - -public class StructuredTextEditorContentOutlinePage extends ContentOutlinePage implements INodeSelectionListener, ITextSelectionListener, IUpdate, IAdaptable { - /** - * @deprecated - */ - // Disables Tree redraw during large model changes - protected class ControlRedrawEnabler implements IModelStateListener { - public void modelAboutToBeChanged(IStructuredModel model) { - setControlRedraw(false); - } - - public void modelChanged(IStructuredModel model) { - setControlRedraw(true); - } - - public void modelDirtyStateChanged(IStructuredModel model, boolean isDirty) { - } - - public void modelResourceDeleted(IStructuredModel model) { - } - - public void modelResourceMoved(IStructuredModel originalmodel, IStructuredModel movedmodel) { - } - - private void setControlRedraw(boolean doRedraw) { - // check if we're on a Display Thread - if (Display.getCurrent() != null) { - setRedraw(doRedraw); - } - else { - final boolean redrawOrNot = doRedraw; - Runnable modifyRedraw = new Runnable() { - public void run() { - setRedraw(redrawOrNot); - } - }; - /* - * This may not result in the enablement change happening - * "soon enough", but better to do it later than to cause a - * deadlock - */ - Display.getDefault().asyncExec(modifyRedraw); - } - } - - public void modelAboutToBeReinitialized(IStructuredModel structuredModel) { - } - - public void modelReinitialized(IStructuredModel structuredModel) { - } - } - - class ShowInTarget implements IShowInTarget { - /* - * @see org.eclipse.ui.part.IShowInTarget#show(org.eclipse.ui.part.ShowInContext) - */ - public boolean show(ShowInContext context) { - if (getViewerSelectionManager() == null) { - return false; - } - boolean shown = false; - List selectedNodes = getViewerSelectionManager().getSelectedNodes(); - if (selectedNodes == null) { - selectedNodes = new ArrayList(0); - } - ISelection selection = new StructuredSelection(getConfiguration().getNodes(selectedNodes)); - if (!selection.isEmpty()) { - setSelection(selection, true); - shown = selection.equals(fSelection); - } - return shown; - } - } - - /* - * Menu listener to create the additions group; 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)); - } - } - } - - protected static ContentOutlineConfiguration NULL_CONFIGURATION = new ContentOutlineConfiguration(); - private TransferDragSourceListener[] fActiveDragListeners; - private TransferDropTargetListener[] fActiveDropListeners; - private ContentOutlineConfiguration fConfiguration; - - private MenuManager fContextMenuManager; - private boolean fContextMenuRegistered = false; - private DelegatingDragAdapter fDragAdapter; - private DragSource fDragSource; - private DelegatingDropAdapter fDropAdapter; - private DropTarget fDropTarget; - protected IStructuredModel fModel; - // Current selection, maintained so selection doesn't bounce back from the - // Tree - ISelection fSelection; - protected SourceEditorTreeViewer fTreeViewer; - protected ViewerSelectionManager fViewerSelectionManager; - private IMenuListener fGroupAdder = null; - - public StructuredTextEditorContentOutlinePage() { - super(); - fSelection = StructuredSelection.EMPTY; - fGroupAdder = new AdditionGroupAdder(); - } - - /** - * @see ContentOutlinePage#createControl - */ - public void createControl(Composite parent) { - fTreeViewer = new SourceEditorTreeViewer(new Tree(parent, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL)); - // create the context menu - fContextMenuManager = new MenuManager("#popup"); //$NON-NLS-1$ - fContextMenuManager.setRemoveAllWhenShown(true); - Menu menu = fContextMenuManager.createContextMenu(fTreeViewer.getControl()); - fTreeViewer.getControl().setMenu(menu); - fDragAdapter = new DelegatingDragAdapter(); - fDragSource = new DragSource(fTreeViewer.getControl(), DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK); - fDropAdapter = new DelegatingDropAdapter(); - fDropTarget = new DropTarget(fTreeViewer.getControl(), DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK); - setConfiguration(getConfiguration()); - fTreeViewer.setInput(getModel()); - IJFaceNodeAdapterFactory adapterFactory = getViewerRefreshFactory(); - if (adapterFactory != null) { - adapterFactory.addListener(fTreeViewer); - } - // update local selection on invalid selection to prevent bounces - fTreeViewer.addInvalidSelectionListener(new ISelectionListener() { - public void selectionChanged(IWorkbenchPart part, ISelection selection) { - fSelection = selection; - } - }); - fTreeViewer.addPostSelectionChangedListener(this); - } - - public void dispose() { - super.dispose(); - // disconnect from the ViewerSelectionManager - if (fViewerSelectionManager != null) { - fViewerSelectionManager.removeNodeSelectionListener(this); - } - IJFaceNodeAdapterFactory adapterFactory = getViewerRefreshFactory(); - if (adapterFactory != null) { - adapterFactory.removeListener(fTreeViewer); - } - setConfiguration(NULL_CONFIGURATION); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class) - */ - public Object getAdapter(Class key) { - Object adapter = getConfiguration().getAdapter(key); - if (adapter == null) { - if (key.equals(IShowInTarget.class)) { - adapter = new ShowInTarget(); - } - } - return adapter; - } - - /** - * @return - */ - public ContentOutlineConfiguration getConfiguration() { - if (fConfiguration == null) - return NULL_CONFIGURATION; - return fConfiguration; - } - - public Control getControl() { - if (getTreeViewer() == null) - return null; - return getTreeViewer().getControl(); - } - - /** - * @return com.ibm.sed.treemodel.IStructuredModel - */ - protected IStructuredModel getModel() { - return fModel; - } - - protected List getSelectedNodes(NodeSelectionChangedEvent event) { - return getConfiguration().getSelectedNodes(event); - } - - public ISelection getSelection() { - if (getTreeViewer() == null) - return StructuredSelection.EMPTY; - return getTreeViewer().getSelection(); - } - - /** - * Returns this page's tree viewer. - * - * @return this page's tree viewer, or <code>null</code> if - * <code>createControl</code> has not been called yet - */ - protected TreeViewer getTreeViewer() { - return fTreeViewer; - } - - protected IJFaceNodeAdapterFactory getViewerRefreshFactory() { - if (getModel() == null) - return null; - FactoryRegistry factoryRegistry = getModel().getFactoryRegistry(); - IJFaceNodeAdapterFactory adapterFactory = (IJFaceNodeAdapterFactory) factoryRegistry.getFactoryFor(IJFaceNodeAdapter.class); - return adapterFactory; - } - - /** - * Returns this page's viewer selection manager. - * - * @return this page's viewer selection manager, or <code>null</code> if - * <code>setViewerSelectionManager</code> has not been called - * yet - */ - public ViewerSelectionManager getViewerSelectionManager() { - return fViewerSelectionManager; - } - - public void nodeSelectionChanged(NodeSelectionChangedEvent event) { - if (getTreeViewer() != null && getConfiguration().isLinkedWithEditor(getTreeViewer())) { - List selectedNodes = getSelectedNodes(event); - if (selectedNodes != null) { - StructuredSelection selection = new StructuredSelection(selectedNodes); - setSelection(selection); - int caretPosition = event.getCaretPosition(); - ((SourceEditorTreeViewer) getTreeViewer()).setCaretPosition(caretPosition); - } - } - } - - void registerContextMenu() { - if (!fContextMenuRegistered && getTreeViewer() != null && getTreeViewer().getControl() != null) { - IWorkbenchPage page = getSite().getWorkbenchWindow().getActivePage(); - if (page != null) { - IEditorPart ownerEditor = page.getActiveEditor(); - if (ownerEditor != null) { - fContextMenuRegistered = true; - if (getModel() != null) - getSite().registerContextMenu(getModel().getContentTypeIdentifier()+".source.OutlineContext", fContextMenuManager, this); //$NON-NLS-1$ - else - getSite().registerContextMenu(ownerEditor.getSite().getId()+".OutlineContext", fContextMenuManager, this); //$NON-NLS-1$ - } - } - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.views.contentoutline.ContentOutlinePage#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent) - */ - public void selectionChanged(SelectionChangedEvent event) { - if (!fSelection.equals(event.getSelection())) { - super.selectionChanged(event); - } - } - - public void setActionBars(IActionBars actionBars) { - super.setActionBars(actionBars); - getSite().getActionBars().setGlobalActionHandler(ActionFactory.UNDO.getId(), new ActiveEditorActionHandler(getSite(), ActionFactory.UNDO.getId())); - getSite().getActionBars().setGlobalActionHandler(ActionFactory.REDO.getId(), new ActiveEditorActionHandler(getSite(), ActionFactory.REDO.getId())); - } - - /** - * @param configuration - */ - public void setConfiguration(ContentOutlineConfiguration configuration) { - // intentionally do not check to see if the new configuration != old - // configuration - if (fTreeViewer != null) { - // remove the key listeners - if (fTreeViewer.getControl() != null && !fTreeViewer.getControl().isDisposed()) { - KeyListener[] listeners = getConfiguration().getKeyListeners(fTreeViewer); - for (int i = 0; i < listeners.length; i++) { - fTreeViewer.getControl().removeKeyListener(listeners[i]); - } - } - // remove any menu listeners - if (fContextMenuManager != null) { - IMenuListener listener = getConfiguration().getMenuListener(fTreeViewer); - if (listener != null) - fContextMenuManager.removeMenuListener(listener); - fContextMenuManager.removeMenuListener(fGroupAdder); - } - // clear the selection changed and double click listeners from the - // configuration - if (getConfiguration().getSelectionChangedListener(fTreeViewer) != null) - removeSelectionChangedListener(getConfiguration().getSelectionChangedListener(fTreeViewer)); - if (getConfiguration().getDoubleClickListener(fTreeViewer) != null) - fTreeViewer.removeDoubleClickListener(getConfiguration().getDoubleClickListener(fTreeViewer)); - IContributionItem[] toolbarItems = getConfiguration().getToolbarContributions(fTreeViewer); - if (toolbarItems.length > 0 && getSite() != null && getSite().getActionBars() != null && getSite().getActionBars().getToolBarManager() != null) { - IContributionManager toolbar = getSite().getActionBars().getToolBarManager(); - for (int i = 0; i < toolbarItems.length; i++) { - toolbar.remove(toolbarItems[i]); - } - toolbar.update(false); - } - IContributionItem[] menuItems = getConfiguration().getMenuContributions(fTreeViewer); - if (menuItems.length > 0 && getSite().getActionBars().getMenuManager() != null) { - IContributionManager menubar = getSite().getActionBars().getMenuManager(); - 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.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.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]); - } - // release any ties to this tree viewer - getConfiguration().unconfigure(fTreeViewer); - } - - fConfiguration = configuration; - if (fConfiguration == null) - fConfiguration = NULL_CONFIGURATION; - fSelection = StructuredSelection.EMPTY; - - if (fTreeViewer != null && fTreeViewer.getControl() != null && !fTreeViewer.getControl().isDisposed()) { - // add a menu listener if one is provided - IMenuListener listener = getConfiguration().getMenuListener(fTreeViewer); - if (listener != null) - fContextMenuManager.addMenuListener(listener); - fContextMenuManager.addMenuListener(fGroupAdder); - // (re)set the providers - fTreeViewer.setLabelProvider(getConfiguration().getLabelProvider(fTreeViewer)); - fTreeViewer.setContentProvider(getConfiguration().getContentProvider(fTreeViewer)); - if (getConfiguration().getSelectionChangedListener(fTreeViewer) != null) - addSelectionChangedListener(getConfiguration().getSelectionChangedListener(fTreeViewer)); - if (getConfiguration().getDoubleClickListener(fTreeViewer) != null) - fTreeViewer.addDoubleClickListener(getConfiguration().getDoubleClickListener(fTreeViewer)); - - // view toolbar - IContributionItem[] toolbarItems = getConfiguration().getToolbarContributions(fTreeViewer); - if (toolbarItems.length > 0 && getSite() != null && getSite().getActionBars() != null && getSite().getActionBars().getToolBarManager() != null) { - IContributionManager toolbar = getSite().getActionBars().getToolBarManager(); - 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(fTreeViewer); - if (menuItems.length > 0) { - 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 = fConfiguration.getTransferDragSourceListeners(fTreeViewer); - 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 = fConfiguration.getTransferDropTargetListeners(fTreeViewer); - 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(fTreeViewer); - for (int i = 0; i < listeners.length; i++) { - fTreeViewer.getControl().addKeyListener(listeners[i]); - } - } - registerContextMenu(); - } - - /** - * Sets focus to a part in the page. - */ - public void setFocus() { - getTreeViewer().getControl().setFocus(); - } - - /** - * Sets the input of the outline page - */ - public void setModel(IStructuredModel newModel) { - if (newModel != fModel) { - // if (fModel != null) { - // fModel.removeModelStateListener(fInternalModelStateListener); - // } - IJFaceNodeAdapterFactory adapterFactory = getViewerRefreshFactory(); - if (adapterFactory != null) { - adapterFactory.removeListener(fTreeViewer); - } - fModel = newModel; - if (getTreeViewer() != null && getControl() != null && !getControl().isDisposed()) { - setConfiguration(getConfiguration()); - fTreeViewer.setInput(fModel); - update(); - } - // fModel.addModelStateListener(fInternalModelStateListener); - adapterFactory = getViewerRefreshFactory(); - if (adapterFactory != null) { - adapterFactory.addListener(fTreeViewer); - } - } - } - - void setRedraw(boolean doRedraw) { - Control control = getControl(); - if ((control != null) && (!control.isDisposed())) { - control.setRedraw(doRedraw); - } - } - - public void setSelection(ISelection selection) { - setSelection(selection, getConfiguration().isLinkedWithEditor(getTreeViewer())); - } - - protected void setSelection(ISelection selection, boolean reveal) { - if (getTreeViewer() != null && selection instanceof IStructuredSelection) { - /** - * Selection sent to the Tree widget comes back as a - * selectionChanged event. To avoid bouncing an externally set - * selection back to our listeners, track the last selection that - * originated elsewhere so we can skip sending it back out. If - * selection came from the Tree widget (by user interaction), it - * will be different. - */ - if (!fSelection.equals(selection)) { - if (selection == null || ((IStructuredSelection) selection).getFirstElement() == null) { - fSelection = StructuredSelection.EMPTY; - } - else { - fSelection = selection; - } - getTreeViewer().setSelection(fSelection, reveal); - } - } - } - - public void setViewerSelectionManager(ViewerSelectionManager viewerSelectionManager) { - // disconnect from old one - if (fViewerSelectionManager != null) { - fViewerSelectionManager.removeNodeSelectionListener(this); - fViewerSelectionManager.removeTextSelectionListener(this); - } - fViewerSelectionManager = viewerSelectionManager; - // connect to new one - if (fViewerSelectionManager != null) { - fViewerSelectionManager.addNodeSelectionListener(this); - fViewerSelectionManager.addTextSelectionListener(this); - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.sse.ui.view.events.ITextSelectionListener#textSelectionChanged(org.eclipse.wst.sse.ui.view.events.TextSelectionChangedEvent) - */ - public void textSelectionChanged(TextSelectionChangedEvent event) { - if (getConfiguration().isLinkedWithEditor(getTreeViewer())) { - int caretPosition = event.getTextSelectionStart(); - ((SourceEditorTreeViewer) getTreeViewer()).setCaretPosition(caretPosition); - } - } - - /** - * redraws the tree - */ - public void update() { - if (getTreeViewer() != null) { - Control control = getTreeViewer().getControl(); - control.setRedraw(false); - getTreeViewer().refresh(); - control.setRedraw(true); - } - } -} 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 be6df0f2fd..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/correction/ContributedProcessorDescriptor.java +++ /dev/null @@ -1,35 +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.correction; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IConfigurationElement; - -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/IQuickAssistProcessor.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/correction/IQuickAssistProcessor.java deleted file mode 100644 index 444e0923ce..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/correction/IQuickAssistProcessor.java +++ /dev/null @@ -1,31 +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.correction; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.jface.text.contentassist.ICompletionProposal; -import org.eclipse.wst.sse.ui.internal.StructuredTextViewer; - - -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 77441acf0b..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/correction/IQuickFixProcessor.java +++ /dev/null @@ -1,30 +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.correction; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.jface.text.contentassist.ICompletionProposal; -import org.eclipse.jface.text.source.Annotation; - -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 c98bb53b8e..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, 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.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/StructuredCorrectionProcessor.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/correction/StructuredCorrectionProcessor.java deleted file mode 100644 index a5287d7695..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, 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.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.ui.IEditorInput; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.texteditor.ITextEditor; -import org.eclipse.wst.sse.core.exceptions.SourceEditingRuntimeException; -import org.eclipse.wst.sse.ui.internal.StructuredTextViewer; - - -public class StructuredCorrectionProcessor implements IContentAssistProcessor { - protected IAnnotationModel fAnnotationModel; - protected IQuickAssistProcessor fQuickAssistProcessor; - protected IQuickFixProcessor fQuickFixProcessor; - - public StructuredCorrectionProcessor(ITextEditor editor) { - IEditorInput input = ((IEditorPart) editor).getEditorInput(); - IAnnotationModel annotationModel = editor.getDocumentProvider().getAnnotationModel(input); - - fAnnotationModel = annotationModel; - } - - 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 (Exception e) { - throw new SourceEditingRuntimeException(); - } - } - - 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) { - throw new SourceEditingRuntimeException(); - } - } - } - } - } - - /* - * (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 00b0d6d078..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/debug/BreakpointRulerAction.java +++ /dev/null @@ -1,304 +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.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.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.IUpdate; -import org.eclipse.wst.sse.core.IStructuredModel; -import org.eclipse.wst.sse.core.StructuredModelManager; -import org.eclipse.wst.sse.ui.extensions.breakpoint.IBreakpointProvider; -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; - - -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; - - public BreakpointRulerAction(ITextEditor editor, IVerticalRulerInfo rulerInfo) { - super(); - fTextEditor = editor; - if(rulerInfo != null) { - fRulerInfo = rulerInfo; - fMouseListener = new MouseUpdater(); - rulerInfo.getControl().addMouseListener(fMouseListener); - } - } - - /** - * 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 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 ef1f9b759a..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/debug/DebugTextEditor.java +++ /dev/null @@ -1,421 +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.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.internal.util.StringUtils; -import org.eclipse.wst.sse.ui.extension.ExtendedConfigurationBuilder; -import org.eclipse.wst.sse.ui.extension.ExtendedEditorActionBuilder; -import org.eclipse.wst.sse.ui.extension.IExtendedContributor; -import org.eclipse.wst.sse.ui.extension.IPopupMenuContributor; -import org.eclipse.wst.sse.ui.extensions.ConfigurationPointCalculator; -import org.eclipse.wst.sse.ui.extensions.breakpoint.IExtendedStorageEditorInput; -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; - - -/** - * @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) - id = storageInput.getStorage().getFullPath().toString(); - 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 843666e349..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, 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.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().getShell(), 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 ddc7ac653f..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, 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.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 ab70ef841b..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/debug/ToggleBreakpointAction.java +++ /dev/null @@ -1,170 +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.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.debug.core.DebugPlugin; -import org.eclipse.debug.core.IBreakpointManager; -import org.eclipse.debug.core.model.IBreakpoint; -import org.eclipse.jface.dialogs.ErrorDialog; -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.texteditor.ITextEditor; -import org.eclipse.wst.sse.core.IModelManager; -import org.eclipse.wst.sse.core.IStructuredModel; -import org.eclipse.wst.sse.core.StructuredModelManager; -import org.eclipse.wst.sse.core.internal.util.Debug; -import org.eclipse.wst.sse.ui.extension.IExtendedMarkupEditor; -import org.eclipse.wst.sse.ui.extension.IExtendedSimpleEditor; -import org.eclipse.wst.sse.ui.extensions.breakpoint.IBreakpointProvider; -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.w3c.dom.Document; -import org.w3c.dom.Node; - -/** - * ToggleBreakpointAction - */ -public class ToggleBreakpointAction extends BreakpointRulerAction { - /** - * @param editor - * @param rulerInfo - */ - public ToggleBreakpointAction(ITextEditor editor, IVerticalRulerInfo rulerInfo) { - super(editor, rulerInfo); - setText(SSEUIMessages.ToggleBreakpointAction_0); //$NON-NLS-1$ - } - - 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)); - - Document doc = null; - Node node = null; - if (editor instanceof IExtendedMarkupEditor) { - doc = ((IExtendedMarkupEditor) editor).getDOMDocument(); - node = ((IExtendedMarkupEditor) editor).getCaretNode(); - } - - int pos = -1; - if (editor instanceof IExtendedSimpleEditor) { - pos = ((IExtendedSimpleEditor) editor).getCaretPosition(); - } - - 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(doc, document, input, node, 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$ - } - } - - if (errors.size() > 0) { - Shell shell = editor.getSite().getShell(); - MultiStatus allStatus = new MultiStatus(SSEUIPlugin.ID, IStatus.INFO, (IStatus[]) errors.toArray(new IStatus[0]), SSEUIMessages.ManageBreakpoints_error_adding_message1, null); //$NON-NLS-1$ - // show for conditions more severe than INFO or when no - // breakpoints were created - if (allStatus.getSeverity() > IStatus.INFO || getBreakpoints(getMarkers()).length < 1) { - ErrorDialog.openError(shell, SSEUIMessages.ManageBreakpoints_error_adding_title1, SSEUIMessages.ManageBreakpoints_error_adding_message1, allStatus); //$NON-NLS-1$ //$NON-NLS-2$ - return false; - } - } - return true; - } - - protected String getContentType(IDocument document) { - IModelManager mgr = StructuredModelManager.getModelManager(); - String 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 { - breakpoints[i].getMarker().delete(); - 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() { - ITextEditor editor = getTextEditor(); - IEditorInput input = editor.getEditorInput(); - IDocument document = editor.getDocumentProvider().getDocument(input); - if (document != null) { - String contentType = getContentType(document); - setEnabled(BreakpointProviderBuilder.getInstance().isAvailable(contentType, getFileExtension(input))); - } else { - setEnabled(false); - } - } -} 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 cae4d926d0..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/debug/ToggleBreakpointsTarget.java +++ /dev/null @@ -1,187 +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 - * - *******************************************************************************/ -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()); - 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/editor/EditorExecutionContext.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/editor/EditorExecutionContext.java deleted file mode 100644 index 719f3ad83c..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/editor/EditorExecutionContext.java +++ /dev/null @@ -1,86 +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 org.eclipse.swt.widgets.Display; -import org.eclipse.ui.IWorkbench; -import org.eclipse.ui.PlatformUI; -import org.eclipse.wst.sse.core.internal.IExecutionDelegate; -import org.eclipse.wst.sse.ui.internal.StructuredTextEditor; - - - -public class EditorExecutionContext implements IExecutionDelegate { - - - StructuredTextEditor fEditor; - - public EditorExecutionContext(StructuredTextEditor editor) { - super(); - fEditor = editor; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.sse.core.internal.document.IExecutionDelegate#execute(java.lang.Runnable) - */ - public void execute(final Runnable runnable) { - IWorkbench workbench = PlatformUI.getWorkbench(); - final Display display = workbench.getDisplay(); - if (display.getThread() == Thread.currentThread()) { - // if already in display thread, we can simply run, "as usual" - runnable.run(); - } else { - // this is the part that's really new, that - // accomidate's a change in a document - // from background thread, by forcing it on - // the display thread. - final StructuredTextEditor editor = fEditor; - // if not in display thread, we "force" to run on display thread. - // see editors begin/end background job for other - // activities to best accomidate (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 - display.syncExec(new Runnable() { - public void run() { - if (display != null && !display.isDisposed()) { - editor.beginBackgroundOperation(); - try { - // here's where the document update/modification - // occurs - runnable.run(); - - // for future, possibly explore solutions such as - // this - // IWorkbenchSiteProgressService jobService = - // (IWorkbenchSiteProgressService) - // editor.getEditorPart().getSite().getAdapter(IWorkbenchSiteProgressService.class); - // jobService.runInUI(xxxxx) - } 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(); - } - } - } - }); - } - } -} - 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 0d493b877a..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/editor/EditorModelUtil.java +++ /dev/null @@ -1,74 +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.Iterator; - -import org.eclipse.core.runtime.Platform; -import org.eclipse.jface.util.SafeRunnable; -import org.eclipse.wst.sse.core.IStructuredModel; -import org.eclipse.wst.sse.core.internal.model.FactoryRegistry; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; -import org.eclipse.wst.sse.ui.internal.SSEUIPlugin; -import org.eclipse.wst.sse.ui.internal.Logger; -import org.eclipse.wst.sse.ui.registry.AdapterFactoryProvider; -import org.eclipse.wst.sse.ui.registry.AdapterFactoryRegistry; -import org.eclipse.wst.sse.ui.registry.AdapterFactoryRegistryExtension; -import org.eclipse.wst.sse.ui.util.Assert; - - -/** - * INTERNAL USAGE ONLY - * - * @author nsd - */ -public class EditorModelUtil { - - public static void addFactoriesTo(final IStructuredModel structuredModel) { - 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())) { - Platform.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/HTML2TextReader.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/editor/HTML2TextReader.java deleted file mode 100644 index a35f11c43b..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/editor/HTML2TextReader.java +++ /dev/null @@ -1,304 +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.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 - */ -/** - * 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("h5"); //$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$ - - 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 fBold = 0; - - private int fCounter = 0; - private boolean fInParagraph = false; - private boolean fIsPreformattedText = false; - private int fStartOffset = -1; - private TextPresentation fTextPresentation; - - /** - * 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; - } - - /** - * @see SubstitutionTextReader#computeSubstitution(char) - */ - protected String computeSubstitution(int c) throws IOException { - - if (c == '<') - return processHTMLTag(); - else if (c == '&') - return processEntity(); - else if (fIsPreformattedText) - return processPreformattedText(c); - - return null; - } - - 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) { - } - } else { - String str = (String) fgEntityLookup.get(symbol); - if (str != null) { - return str; - } - } - return "&" + symbol; // not found //$NON-NLS-1$ - } - - 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); - - if (!fgTags.contains(tag)) - return EMPTY_STRING; - - 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 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(); - } - - /* - * 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 - 3)))) { //$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; - } - - 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 stopBold() { - --fBold; - if (fBold == 0) { - if (fTextPresentation != null) { - fTextPresentation.addStyleRange(new StyleRange(fStartOffset, fCounter - fStartOffset, null, null, SWT.BOLD)); - } - fStartOffset = -1; - } - } - - protected void stopPreformattedText() { - fIsPreformattedText = false; - setSkipWhitespace(true); - } - - - private void unread(int ch) throws IOException { - ((PushbackReader) getReader()).unread(ch); - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/editor/HTMLTextPresenter.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/editor/HTMLTextPresenter.java deleted file mode 100644 index c3a1faa504..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/editor/HTMLTextPresenter.java +++ /dev/null @@ -1,198 +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.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.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 sed Logger to log exception, and the - * ellipses constant - */ -public class HTMLTextPresenter implements DefaultInformationControl.IInformationPresenter { - 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() { - this(true); - } - - public HTMLTextPresenter(boolean enforceUpperLineLimit) { - super(); - fEnforceUpperLineLimit = enforceUpperLineLimit; - } - - 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; - } - - protected Reader createReader(String hoverInfo, TextPresentation presentation) { - return new HTML2TextReader(new StringReader(hoverInfo), presentation); - } - - 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$ - } - - 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(); - } - - /* - * @see IHoverInformationPresenter#updatePresentation(Display display, - * String, TextPresentation, int, int) - */ - public String updatePresentation(Display display, String hoverInfo, TextPresentation presentation, int maxWidth, int maxHeight) { - - if (hoverInfo == null) - return null; - - GC gc = new GC(display); - 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) { - append(buffer, LINE_DELIM, lineFormatted ? presentation : null); - append(buffer, ELLIPSES, presentation); //$NON-NLS-1$ - } - - return trim(buffer, presentation); - - } catch (IOException e) { - Logger.logException(e); // log exception - return null; - - } finally { - gc.dispose(); - } - } -} 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 8066d0f6d2..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/editor/IHelpContextIds.java +++ /dev/null @@ -1,60 +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 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$ - // Preferences - public static final String CONTMNU_PREFERENCES_HELPID = PREFIX + "xmlm1060"; //$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$ - // Navigation - public static final String PREFSTE_NAVIGATION_HELPID = PREFIX + "sted0002"; //$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/LineBreakingReader.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/editor/LineBreakingReader.java deleted file mode 100644 index 655f23ce9e..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/editor/LineBreakingReader.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.editor; - - - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.Reader; -import java.text.BreakIterator; - -import org.eclipse.swt.graphics.GC; - -/** - * Copied from org.eclipse.jdt.internal.ui.text.LineBreakingReader No - * modifications were made - */ -/* - * 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; - } else { - 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/editor/SingleCharReader.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/editor/SingleCharReader.java deleted file mode 100644 index df16ceca3d..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/editor/SingleCharReader.java +++ /dev/null @@ -1,67 +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.io.IOException; -import java.io.Reader; - -/** - * Copied from org.eclipse.jdt.internal.corext.javadoc.SingleCharReader - * Also copied in org.eclipse.wst.javascript.common.ui.contentassist.javadoc.SingleCharReader No - * modifications were made - */ -public abstract class SingleCharReader extends Reader { - - /** - * 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(); - } - - /** - * @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; - } else { - return i - off; - } - } - cbuf[i] = (char) ch; - } - return len; - } - - /** - * @see Reader#ready() - */ - public boolean ready() throws IOException { - return true; - } -} 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 19fc440a98..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/editor/StructuredModelDocumentProvider.java +++ /dev/null @@ -1,253 +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.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.Status; -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.IElementStateListener; -import org.eclipse.wst.sse.core.IStructuredModel; - - -/** - * @author nitin - */ -public class StructuredModelDocumentProvider implements IDocumentProvider, IDocumentProviderExtension { - 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 { - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/editor/SubstitutionTextReader.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/editor/SubstitutionTextReader.java deleted file mode 100644 index 0ff800f433..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/editor/SubstitutionTextReader.java +++ /dev/null @@ -1,177 +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.io.IOException; -import java.io.Reader; - -/** - * Copied from org.eclipse.jdt.internal.ui.text.SubstitutionTextReader - * Also copied in org.eclipse.wst.javascript.common.ui.contentassist.javadoc.SubstitutionTextReader - * Modifications were made to read() to allow whitespaces - */ -/** - * 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 StringBuffer fBuffer; - private int fCharAfterWhiteSpace; - private int fIndex; - - private Reader fReader; - - private boolean fReadFromBuffer; - - /** - * Tells whether white space characters are skipped. - */ - private boolean fSkipWhiteSpace = true; - private boolean fWasWhiteSpace; - - - protected SubstitutionTextReader(Reader reader) { - fReader = reader; - fBuffer = new StringBuffer(); - fIndex = 0; - fReadFromBuffer = false; - fCharAfterWhiteSpace = -1; - fWasWhiteSpace = true; - } - - /** - * @see Reader#close() - */ - public void close() throws IOException { - fReader.close(); - } - - /** - * 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; - } - - protected final boolean isSkippingWhitespace() { - return fSkipWhiteSpace; - } - - /** - * 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; - } else { - 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)); // AFW - // - if - // whitespace - // is - // from - // buffer, - // then - // it - // should - // be - // read - fWasWhiteSpace = ((c == ' ' && !fReadFromBuffer) || c == '\r' || c == '\n'); // AFW - // - if - // whitespace - // is - // from - // buffer, - // then - // it - // should - // be - // read - return c; - } - - /** - * @see Reader#ready() - */ - public boolean ready() throws IOException { - return fReader.ready(); - } - - /** - * @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; - } -} 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 5648b9647a..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/extension/ActionDescriptor.java +++ /dev/null @@ -1,379 +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.extension; - - - -import java.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.help.WorkbenchHelp; -import org.eclipse.wst.sse.ui.extension.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$ - WorkbenchHelp.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 = createExtension(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 c6d45c69a9..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/extension/BreakpointProviderBuilder.java +++ /dev/null @@ -1,406 +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.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 java.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.extensions.breakpoint.IBreakpointProvider; -import org.eclipse.wst.sse.ui.extensions.breakpoint.SourceEditingTextTools; -import org.eclipse.wst.sse.ui.internal.Logger; -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 && contentType.isKindOf(testType)) { - 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; - SourceEditingTextTools tools = null; - if (editorpart != null && itr.hasNext()) - tools = (SourceEditingTextTools) editorpart.getAdapter(SourceEditingTextTools.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 handler - * a content type handler - * @param ext - * file extension - * @return boolean - */ - public boolean isAvailable(String contentType, String ext) { - boolean 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); - } - - /* - * @see com.ibm.sed.edit.internal.extension.RegistryReader#readElement(org.eclipse.core.runtime.IConfigurationElement) - */ - 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 6ac39abad0..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/extension/DropActionProxy.java +++ /dev/null @@ -1,151 +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.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.core.runtime.IStatus; -import org.eclipse.jface.action.IAction; -import org.eclipse.jface.text.IDocument; -import org.eclipse.swt.widgets.Display; -import org.eclipse.ui.PlatformUI; -import org.eclipse.wst.sse.core.IStructuredModel; -import org.eclipse.wst.sse.core.StructuredModelManager; -import org.eclipse.wst.sse.core.undo.IStructuredTextUndoManager; -import org.eclipse.wst.sse.ui.extension.IExtendedSimpleEditor; -import org.eclipse.wst.sse.ui.extensions.ISelfValidateEditAction; -import org.eclipse.wst.sse.ui.internal.Logger; - - -/** - */ -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; - } - } - - private Display getDisplay() { - return PlatformUI.getWorkbench().getDisplay(); - } - - /** - * @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 ((editor != null) && !(obj instanceof ISelfValidateEditAction)) { - IStatus status = editor.validateEdit(getDisplay().getActiveShell()); - if (!status.isOK()) { - return null; - } - } - } - 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; - } -} 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 64b0d289cb..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/extension/ExtendedEditorActionProxy.java +++ /dev/null @@ -1,150 +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.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.core.runtime.IStatus; -import org.eclipse.jface.action.IAction; -import org.eclipse.jface.text.IDocument; -import org.eclipse.swt.widgets.Display; -import org.eclipse.ui.PlatformUI; -import org.eclipse.wst.sse.core.IStructuredModel; -import org.eclipse.wst.sse.core.StructuredModelManager; -import org.eclipse.wst.sse.core.undo.IStructuredTextUndoManager; -import org.eclipse.wst.sse.ui.extension.IExtendedSimpleEditor; -import org.eclipse.wst.sse.ui.extensions.ISelfValidateEditAction; -import org.eclipse.wst.sse.ui.internal.Logger; - - -/** - * 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; - } - } - - private Display getDisplay() { - return PlatformUI.getWorkbench().getDisplay(); - } - - /** - * @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)) { - 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/ImageUtil.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/extension/ImageUtil.java deleted file mode 100644 index b4ec6938ff..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, 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.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 578df540ec..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, 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.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.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/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 9994523a7b..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/hyperlink/OpenHyperlinkAction.java +++ /dev/null @@ -1,66 +0,0 @@ -package org.eclipse.wst.sse.ui.internal.hyperlink; - -import java.util.ResourceBundle; - -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.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; - 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++) { - IHyperlinkDetector detector = fHyperlinkDetectors[i]; - if (detector == null) - continue; - - IHyperlink[] hyperlinks = detector.detectHyperlinks(fTextViewer, region, false); - if (hyperlinks == null) - continue; - - if (hyperlinks.length > 0) - hyperlink = hyperlinks[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/ExternalFileEditorInput.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/openon/ExternalFileEditorInput.java deleted file mode 100644 index 58eb65861f..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, 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.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 base support for hyperlink navigation - */ -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/OpenFileHyperlinkTracker.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/openon/OpenFileHyperlinkTracker.java deleted file mode 100644 index 159d9dce11..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/openon/OpenFileHyperlinkTracker.java +++ /dev/null @@ -1,662 +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.openon; - -import java.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.extensions.openon.IOpenOn; -import org.eclipse.wst.sse.ui.internal.Logger; -import org.eclipse.wst.sse.ui.openon.OpenOnProvider; -import org.eclipse.wst.sse.ui.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 9804db2d25..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/openon/OpenOnAction.java +++ /dev/null @@ -1,70 +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.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.extension.IExtendedSimpleEditor; -import org.eclipse.wst.sse.ui.extensions.openon.IOpenOn; -import org.eclipse.wst.sse.ui.openon.OpenOnProvider; - - -/** - * 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; - 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 b62de63f8f..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, 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.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 8c7d611b9c..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/openon/OpenOnDefinition.java +++ /dev/null @@ -1,158 +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.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.extensions.openon.IOpenOn; -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/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 b5efd88433..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/EditorPreferenceNames.java +++ /dev/null @@ -1,80 +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.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$ - } -} 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 77b4a17942..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, 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.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 - * @since 3.0 - */ - public void addKeys(OverlayKey[] keys) { - Assert.isTrue(!fLoaded); - Assert.isNotNull(keys); - - int overlayKeysLength = fOverlayKeys.length; - OverlayKey[] result = new OverlayKey[keys.length + overlayKeysLength]; - - for (int i = 0, length = overlayKeysLength; i < length; i++) - result[i] = fOverlayKeys[i]; - - for (int i = 0, length = keys.length; i < length; i++) - result[overlayKeysLength + i] = keys[i]; - - fOverlayKeys = result; - - if (fLoaded) - load(); - } - - /* - * @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/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 79ea1493d0..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/preferences/ui/EmptyFilePreferencePage.java +++ /dev/null @@ -1,104 +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 - * 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.Label; -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) { - 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$ - createLabel(composite, description); - - setSize(composite); - return composite; - } - - private 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; - } - - 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) { - 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/projection/IStructuredTextFoldingProvider.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/projection/IStructuredTextFoldingProvider.java deleted file mode 100644 index 76d9af2629..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/projection/IStructuredTextFoldingProvider.java +++ /dev/null @@ -1,45 +0,0 @@ -package org.eclipse.wst.sse.ui.internal.projection; - -import org.eclipse.jface.text.source.projection.ProjectionViewer; - -/** - * Implementors of this interface which will create and maintain - * {@link org.eclipse.jface.text.source.projection.ProjectionAnnotation} - * objects that define folded regions in the the - * {@link org.eclipse.jface.text.source.projection.ProjectionViewer}for a - * structured model. - */ -public interface IStructuredTextFoldingProvider { - public static final String ID = "structuredtextfoldingprovider"; //$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$ - - // copied interface from - // org.eclipse.jdt.ui.text.folding.IJavaFoldingStructureProvider - /** - * Installs this structure provider on the given viewer. Implementations - * should listen to the projection events generated by <code>viewer</code> - * and enable / disable generation of projection structure accordingly. - * - * @param viewer - * the projection viewer that displays the annotations created - * by this structure provider - */ - public void install(ProjectionViewer viewer); - - /** - * Uninstalls this structure provider. Any references to viewers should be - * cleared. - */ - public void uninstall(); - - /** - * Initialize this provider with the correct document. Assumes projection - * is enabled. (otherwise, only install would have been called) - */ - public void initialize(); -} 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 d022d0dafa..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, 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.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.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/AdapterPropertySourceProvider.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/properties/AdapterPropertySourceProvider.java deleted file mode 100644 index 4c77355d05..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/properties/AdapterPropertySourceProvider.java +++ /dev/null @@ -1,34 +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.properties; - - - -import org.eclipse.ui.views.properties.IPropertySource; -import org.eclipse.ui.views.properties.IPropertySourceProvider; -import org.eclipse.wst.sse.core.INodeNotifier; - - -public class AdapterPropertySourceProvider implements IPropertySourceProvider { - - public AdapterPropertySourceProvider() { - super(); - } - - public IPropertySource getPropertySource(Object object) { - if (object instanceof INodeNotifier) { - return (IPropertySource) ((INodeNotifier) object).getAdapterFor(IPropertySource.class); - } - return null; - } -} 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 6430f1a6ca..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/properties/ConfigurablePropertySheetPage.java +++ /dev/null @@ -1,279 +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.properties; - -import java.util.List; - -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.swt.widgets.Composite; -import org.eclipse.swt.widgets.Tree; -import org.eclipse.swt.widgets.TreeItem; -import org.eclipse.ui.IActionBars; -import org.eclipse.ui.IWorkbenchPart; -import org.eclipse.ui.actions.ActionFactory; -import org.eclipse.ui.part.PageBook; -import org.eclipse.ui.views.properties.IPropertySheetEntry; -import org.eclipse.ui.views.properties.IPropertySource; -import org.eclipse.ui.views.properties.PropertySheetPage; -import org.eclipse.wst.sse.core.IStructuredModel; -import org.eclipse.wst.sse.core.internal.model.FactoryRegistry; -import org.eclipse.wst.sse.ui.internal.ViewerSelectionManager; -import org.eclipse.wst.sse.ui.internal.actions.ActiveEditorActionHandler; -import org.eclipse.wst.sse.ui.internal.contentoutline.IJFaceNodeAdapter; -import org.eclipse.wst.sse.ui.internal.contentoutline.IJFaceNodeAdapterFactory; -import org.eclipse.wst.sse.ui.view.events.INodeSelectionListener; -import org.eclipse.wst.sse.ui.view.events.NodeSelectionChangedEvent; -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 implements INodeSelectionListener { - - private PropertySheetConfiguration fConfiguration; - // has the widget been created? - private boolean fIsRealized = false; - private IMenuManager fMenuManager; - - protected PageBook fParentPageBook = null; - // are we refreshing the contents? - protected boolean fRefreshing = false; - - protected RemoveAction fRemoveAction; - private IStatusLineManager fStatusLineManager; - - protected IStructuredModel fStructuredModel = null; - private IToolBarManager fToolBarManager; - - private ViewerSelectionManager fViewerSelectionManager; - - private final PropertySheetConfiguration NULL_CONFIGURATION = new PropertySheetConfiguration(); - - public ConfigurablePropertySheetPage() { - super(); - } - - public void createControl(Composite parent) { - setPropertySourceProvider(getConfiguration().getPropertySourceProvider()); - super.createControl(parent); - if (parent instanceof PageBook) - fParentPageBook = (PageBook) parent; - } - - public void dispose() { - // disconnect from the ViewerSelectionManager - if (getViewerSelectionManager() != null) { - getViewerSelectionManager().removeNodeSelectionListener(this); - } - setModel(null); - setConfiguration(null); - super.dispose(); - } - - /** - * @return - */ - public PropertySheetConfiguration getConfiguration() { - if (fConfiguration == null) - fConfiguration = NULL_CONFIGURATION; - return fConfiguration; - } - - public IStructuredModel getModel() { - return fStructuredModel; - } - - protected IJFaceNodeAdapterFactory getViewerRefreshFactory() { - if (getModel() == null) - return null; - FactoryRegistry factoryRegistry = getModel().getFactoryRegistry(); - IJFaceNodeAdapterFactory adapterFactory = (IJFaceNodeAdapterFactory) factoryRegistry.getFactoryFor(IJFaceNodeAdapter.class); - return adapterFactory; - } - - /** - * @return Returns the viewerSelectionManager. - */ - public ViewerSelectionManager getViewerSelectionManager() { - return fViewerSelectionManager; - } - - /* - * @see PropertySheetPage#handleEntrySelection(ISelection) - */ - public void handleEntrySelection(ISelection selection) { - // Useful for enabling/disabling actions based on the - // selection (or lack thereof). Also, ensure that the - // control exists before sending selection to it. - if (fIsRealized && selection != null) { - super.handleEntrySelection(selection); - fRemoveAction.setEnabled(!selection.isEmpty()); - // if (selection != null && !selection.isEmpty() && selection - // instanceof IStructuredSelection) { - // IPropertySheetEntry entry = (IPropertySheetEntry) - // ((IStructuredSelection) selection).getFirstElement(); - // } - } - } - - /** - * @return Returns the isRealized. - */ - public boolean isRealized() { - return fIsRealized; - } - - 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); - fIsRealized = true; - } - - public void nodeSelectionChanged(NodeSelectionChangedEvent event) { - selectionChanged(null, new StructuredSelection(event.getSelectedNodes())); - } - - /** - * @see org.eclipse.ui.views.properties.PropertySheetPage#refresh() - */ - public void refresh() { - /** - * Avoid refreshing the property sheet if it is already doing so. A - * refresh can prompt an active cell editor to close, applying the - * value and altering the selected node. In that case, a loop could - * occur. - */ - - if (!fRefreshing) { - fRefreshing = true; - super.refresh(); - fRefreshing = false; - } else { - // detected a loop in the property sheet (shouldn't happen) - } - } - - public void remove() { - if (getControl() instanceof Tree) { - TreeItem[] items = ((Tree) getControl()).getSelection(); - List selectedNodes = getViewerSelectionManager().getSelectedNodes(); - if (items != null && items.length == 1 && selectedNodes != null) { - Object data = items[0].getData(); - if (data instanceof IPropertySheetEntry) { - IPropertySheetEntry entry = (IPropertySheetEntry) data; - ISelection selection = getConfiguration().getSelection(null, new StructuredSelection(selectedNodes)); - if (selection != null && !selection.isEmpty() && selection instanceof IStructuredSelection) { - IPropertySource source = getConfiguration().getPropertySourceProvider().getPropertySource(((IStructuredSelection) selection).getFirstElement()); - if (source != null && source instanceof IPropertySourceExtension) { - ((IPropertySourceExtension) source).removeProperty(entry.getDisplayName()); - } - } - } - } - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.ISelectionListener#selectionChanged(org.eclipse.ui.IWorkbenchPart, - * org.eclipse.jface.viewers.ISelection) - */ - public void selectionChanged(IWorkbenchPart part, ISelection selection) { - super.selectionChanged(part, getConfiguration().getSelection(part, selection)); - } - - public void setActionBars(IActionBars actionBars) { - super.setActionBars(actionBars); - getSite().getActionBars().setGlobalActionHandler(ActionFactory.UNDO.getId(), new ActiveEditorActionHandler(getSite(), ActionFactory.UNDO.getId())); - getSite().getActionBars().setGlobalActionHandler(ActionFactory.REDO.getId(), new ActiveEditorActionHandler(getSite(), ActionFactory.REDO.getId())); - } - - /** - * @param configuration - * The configuration to set. - */ - public void setConfiguration(PropertySheetConfiguration configuration) { - if (fConfiguration != null && isRealized()) { - fConfiguration.removeContributions(fMenuManager, fToolBarManager, fStatusLineManager); - fConfiguration.unconfigure(); - } - - fConfiguration = configuration; - - if (fConfiguration != null) { - setPropertySourceProvider(fConfiguration.getPropertySourceProvider()); - if (isRealized()) - fConfiguration.addContributions(fMenuManager, fToolBarManager, fStatusLineManager); - } - } - - /** - * Asks this page to take focus within its pagebook view. - */ - public void setFocus() { - super.setFocus(); - if (fParentPageBook != null) - fParentPageBook.showPage(getControl()); - } - - /** - * Sets the model. - * - * @param model - * The model to set - */ - public void setModel(IStructuredModel model) { - if (model != fStructuredModel) { - IJFaceNodeAdapterFactory refresher = getViewerRefreshFactory(); - if (refresher != null) - refresher.removeListener(this); - fStructuredModel = model; - refresher = getViewerRefreshFactory(); - if (refresher != null) - refresher.addListener(this); - } - } - - public void setViewerSelectionManager(ViewerSelectionManager viewerSelectionManager) { - // disconnect from old one - if (fViewerSelectionManager != null) { - fViewerSelectionManager.removeNodeSelectionListener(this); - } - - fViewerSelectionManager = viewerSelectionManager; - - // connect to new one - if (fViewerSelectionManager != null) { - fViewerSelectionManager.addNodeSelectionListener(this); - } - } -} 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 5c6904b963..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, 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.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 488b2414a1..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, 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.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 4a859344d0..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/properties/ShowPropertiesAction.java +++ /dev/null @@ -1,38 +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.properties; - -import org.eclipse.ui.help.WorkbenchHelp; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; -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 - * - * @author Nitin Dahyabhai - */ -public class ShowPropertiesAction extends ShowViewAction { - private final static String VIEW_ID = "org.eclipse.ui.views.PropertySheet"; //$NON-NLS-1$ - - public ShowPropertiesAction() { - super(SSEUIMessages.ShowPropertiesAction_0, EditorPluginImageHelper.getInstance().getImageDescriptor(EditorPluginImages.IMG_OBJ_PROP_PS)); //$NON-NLS-1$ - WorkbenchHelp.setHelp(this, IHelpContextIds.CONTMNU_PROPERTIES_HELPID); - } - - protected String getViewID() { - return VIEW_ID; - } -} 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 f41c020db4..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/AbstractStructuredTextReconcilingStrategy.java +++ /dev/null @@ -1,493 +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.reconcile; - -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.resources.IFile; -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.Position; -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.ui.IEditorInput; -import org.eclipse.ui.IFileEditorInput; -import org.eclipse.ui.texteditor.ITextEditor; -import org.eclipse.wst.sse.core.IStructuredModel; -import org.eclipse.wst.sse.core.IndexedRegion; -import org.eclipse.wst.sse.core.StructuredModelManager; -import org.eclipse.wst.sse.core.text.IStructuredDocument; -import org.eclipse.wst.sse.core.text.IStructuredDocumentRegion; -import org.eclipse.wst.sse.ui.internal.IReleasable; -import org.eclipse.wst.sse.ui.internal.ITemporaryAnnotation; - - -/** - * A base ReconcilingStrategy. Subclasses must implement - * createReconcileSteps(). - * - * @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$ - } - - protected IDocument fDocument = null; - protected IReconcileStep fFirstStep = null; - protected IProgressMonitor fProgressMonitor = null; - protected ITextEditor fTextEditor = null; - private Comparator fComparator; - - /** - * Creates a new strategy. The editor parameter is for access to the - * annotation model. - * - * @param editor - */ - public AbstractStructuredTextReconcilingStrategy(ITextEditor editor) { - fTextEditor = editor; - 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; - 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; - } - - /** - * @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 (fTextEditor != null && fTextEditor.getEditorInput() != null) { - model = fTextEditor.getDocumentProvider().getAnnotationModel(fTextEditor.getEditorInput()); - } - return model; - } - - protected TemporaryAnnotation[] getAnnotationsToRemove(DirtyRegion dr) { - IStructuredDocumentRegion[] sdRegions = getStructuredDocumentRegions(dr); - List remove = new ArrayList(); - IAnnotationModel annotationModel = getAnnotationModel(); - // can be null when closing the editor - if (getAnnotationModel() != null) { - Iterator 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 (canHandlePartition(key.getPartitionType()) && containsStep(key.getStep())) { - if (key.getScope() == ReconcileAnnotationKey.PARTIAL && overlaps(annotation.getPosition(), sdRegions)) { - remove.add(annotation); - } - else if (key.getScope() == ReconcileAnnotationKey.TOTAL) { - remove.add(annotation); - } - } - } - } - return (TemporaryAnnotation[]) remove.toArray(new TemporaryAnnotation[remove.size()]); - } - - /** - * 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(fDocument); - IndexedRegion indexedRegion = null; - try { - if (sModel != null) - indexedRegion = sModel.getIndexedRegion(sdRegion.getStart()); - } finally { - if (sModel != null) - sModel.releaseFromRead(); - } - return indexedRegion; - } - - /** - * The IFile that this strategy is operating on (the file input for the - * TextEditor) - * - * @return the IFile that this strategy is operating on - */ - protected IFile getFile() { - if (fTextEditor == null) - return null; - IEditorInput input = fTextEditor.getEditorInput(); - if (!(input instanceof IFileEditorInput)) - return null; - return ((IFileEditorInput) input).getFile(); - } - - /** - * 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]; - } - - /** - * Returns the appropriate (first) IStructuredDocumentRegion for the given - * dirtyRegion. - * - * @param dirtyRegion - * @return the appropriate StructuredDocumentRegion for the given - * dirtyRegion. - */ - private IStructuredDocumentRegion getStructuredDocumentRegion(int offset) { - IStructuredDocumentRegion sdRegion = null; - if (fDocument instanceof IStructuredDocument) { - sdRegion = ((IStructuredDocument) fDocument).getRegionAtCharacterOffset(offset); - } - return sdRegion; - } - - private IStructuredDocumentRegion[] getStructuredDocumentRegions(DirtyRegion dr) { - int offset = dr.getOffset(); - int end = offset + dr.getLength(); - List regions = new ArrayList(); - IStructuredDocumentRegion r = getStructuredDocumentRegion(offset); - while (r != null && r.getStartOffset() <= end) { - if (!r.isDeleted()) - regions.add(r); - r = r.getNext(); - } - return (IStructuredDocumentRegion[]) regions.toArray(new IStructuredDocumentRegion[regions.size()]); - } - - 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(); - } - - /** - * Checks if this position overlaps any of the StructuredDocument regions' - * correstponding IndexedRegion. - * - * @param pos - * @param sdRegions - * @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); - } - - /** - * 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++) { - 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) { - - // 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; - } - 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 void removeAllAnnotations() { - removeAnnotations(getAllAnnotationsToRemove()); - } - - /** - * 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(); - - fDocument = document; - if (fFirstStep != null) - fFirstStep.setInputModel(new DocumentAdapter(document)); - } - - /** - * @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) { - - // TODO: investigate a better algorithm, - // also see if this is a bad performance hit. - - Comparator comp = getAnnotationComparator(); - 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; - } - - removeAnnotations((TemporaryAnnotation[])filteredRemovals.toArray(new TemporaryAnnotation[filteredRemovals.size()])); - process((IReconcileResult[])filteredAdditions.toArray(new IReconcileResult[filteredAdditions.size()])); - } - - private Comparator getAnnotationComparator() { - if(fComparator == null) { - fComparator = new Comparator( ) { - public int compare(Object arg0, Object arg1) { - TemporaryAnnotation ta1 = (TemporaryAnnotation)arg0; - TemporaryAnnotation ta2 = (TemporaryAnnotation)arg1; - return ta1.getPosition().getOffset() - ta2.getPosition().getOffset(); - } - }; - } - return fComparator; - } - - public boolean isTotalScope() { - return false; - } -} 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 bc1cf2131e..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/DirtyRegionProcessor.java +++ /dev/null @@ -1,516 +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.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.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.core.runtime.OperationCanceledException; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.jobs.Job; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IDocumentExtension3; -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.IReconcilingStrategy; -import org.eclipse.jface.text.reconciler.IReconcilingStrategyExtension; -import org.eclipse.wst.sse.core.events.NewDocumentEvent; -import org.eclipse.wst.sse.core.events.NoChangeEvent; -import org.eclipse.wst.sse.ui.internal.Logger; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; - -/** - * 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 extends Job implements IReconciler { - /** debug flag */ - protected static final boolean DEBUG; - - private static final long UPDATE_DELAY = 750; - 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; - - /** - * set true after first install to prevent duplicate work done in the - * install method (since install gets called multiple times) - */ - private boolean fIsInstalled = false; - - private IProgressMonitor fLocalProgressMonitor = null; - - /** - * The partitioning this reconciler uses. - */ - private String fPartitioning; - - /** The map of reconciling strategies. */ - private Map fStrategies = new HashMap(); - - /** the list of partition types for which there are strategies */ - private List fStrategyTypes = new ArrayList(); - - /** the text viewer */ - private ITextViewer fViewer; - - /** - * Creates a new StructuredRegionProcessor - */ - public DirtyRegionProcessor() { - - // init job stuff - super(SSEUIMessages.proc_dirty_regions_0); //$NON-NLS-1$ - setPriority(Job.LONG); - setSystem(true); - setLocalProgressMonitor(new NullProgressMonitor()); - - // init reconciler stuff - setDelay(UPDATE_DELAY); - } - - /** - * 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 dr) { - - List drq = getDirtyRegionQueue(); - // if we already have a request which contains the new request, - // discare the new request - int size = drq.size(); - for (int i = 0; i < size; i++) { - if (contains((DirtyRegion) drq.get(i), dr)) - return; - } - // if new request is contains any existing requests, - // remove those - for (Iterator it = drq.iterator(); it.hasNext();) { - if (contains(dr, (DirtyRegion) it.next())) - it.remove(); - } - drq.add(dr); - } - - /** - * @param dirtyRegion - * @return - */ - protected ITypedRegion[] computePartitioning(DirtyRegion dirtyRegion) { - IDocument doc = getDocument(); - ITypedRegion tr[] = null; - - int drOffset = dirtyRegion.getOffset(); - int drLength = dirtyRegion.getLength(); - 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; - } - - /** - * @return if the root is parent of possible, return true, otherwise - * return false - */ - protected boolean contains(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); - } - - /** - * Delay between processing of DirtyRegions. - * - * @return - */ - protected long getDelay() { - return fDelay; - } - - protected List getDirtyRegionQueue() { - return fDirtyRegionQueue; - } - - /** - * The IDocument on which this reconciler operates - * - * @return - */ - protected IDocument getDocument() { - return fDocument; - } - - /** - * @see org.eclipse.jface.text.reconciler.IReconcilerExtension#getDocumentPartitioning() - * @since 3.0 - */ - public String getDocumentPartitioning() { - if (fPartitioning == null) - return IDocumentExtension3.DEFAULT_PARTITIONING; - return fPartitioning; - } - - /** - * We use our own local progress monitor to cancel long running - * strategies/steps. Currently used when widget is disposed (user is - * trying to close the editor), and on uninstall. - * - * @return the local progress monitor - */ - IProgressMonitor getLocalProgressMonitor() { - return fLocalProgressMonitor; - } - - /** - * Utility method to get partitions of a dirty region - * - * @param dirtyRegion - * @return - */ - protected String[] getPartitions(DirtyRegion dirtyRegion) { - ITypedRegion regions[] = null; - - int drOffset = dirtyRegion.getOffset(); - int drLength = dirtyRegion.getLength(); - 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(), dirtyRegion.getOffset(), dirtyRegion.getLength(), 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; - } - - /** - * contentType is actually partitionType - * @see IReconciler#getReconcilingStrategy(String) - */ - public IReconcilingStrategy getReconcilingStrategy(String contentType) { - if (fStrategies == null) - return null; - return (IReconcilingStrategy) fStrategies.get(contentType); - } - - /** - * This method also synchronized because it accesses the fRequests queue - * - * @return an array of the currently requested Nodes to refresh - */ - private synchronized DirtyRegion[] getRequests() { - DirtyRegion[] toRefresh = (DirtyRegion[]) fDirtyRegionQueue.toArray(new DirtyRegion[fDirtyRegionQueue.size()]); - fDirtyRegionQueue.clear(); - return toRefresh; - } - - /** - * Gets a strategy that is made to handle the given dirtyRegion. - * - * @param dirtyRegion - * @return a strategy that is made to handle the given dirtyRegion, or the - * default strategy for this reconciler if there isn't one - */ - protected IReconcilingStrategy getStrategy(DirtyRegion dirtyRegion) { - String[] partitions = getPartitions(dirtyRegion); - // for now just grab first partition type in dirty region - IReconcilingStrategy rs = null; - if (partitions.length > 0) - rs = getReconcilingStrategy(partitions[0]); - return rs; - } - - /** - * A list of strategy types (keys) for this reconciler. Each strategy - * should have a unique key. - * - * @return - */ - public List getStrategyTypes() { - return fStrategyTypes; - } - - /** - * Returns the text viewer this reconciler is installed on. - * - * @return the text viewer this reconciler is installed on - */ - protected ITextViewer getTextViewer() { - return fViewer; - } - - /** - * @see org.eclipse.jface.text.reconciler.IReconciler#install(ITextViewer) - */ - public void install(ITextViewer textViewer) { - // we might be called multiple times with the same viewer, - // maybe after being uninstalled as well, so track separately - if (!isInstalled()) { - fViewer = textViewer; - getLocalProgressMonitor().setCanceled(false); - setInstalled(true); - } - } - - /** - * 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; - } - - public void newModel(NewDocumentEvent structuredDocumentEvent) { - // do nothing - } - - public void noChange(NoChangeEvent structuredDocumentEvent) { - // do nothing - } - - /** - * Subclasses should implement for specific handling of dirty regions. - * - * @param dr - */ - protected void process(DirtyRegion dr) { - // subclasses should implement - } - - /** - * Invoke dirty region processing. - * - * @param node - */ - public final void processDirtyRegion(DirtyRegion dr) { - if (dr == null) - return; - - cancel(); - addRequest(dr); - schedule(getDelay()); - - 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$ - } - } - - /** - * Reinitializes listeners and sets new document on all strategies. - * - * @see org.eclipse.jface.text.reconciler.AbstractReconciler#reconcilerDocumentChanged(IDocument) - */ - protected void reconcilerDocumentChanged(IDocument document) { - setDocument(document); - setDocumentOnAllStrategies(document); - } - - protected IStatus run(IProgressMonitor monitor) { - IStatus status = Status.OK_STATUS; - try { - DirtyRegion[] toRefresh = getRequests(); - for (int i = 0; i < toRefresh.length; i++) { - if (monitor.isCanceled()) - throw new OperationCanceledException(); - process(toRefresh[i]); - } - } - finally { - monitor.done(); - } - return status; - } - - protected void setDelay(long delay) { - fDelay = delay; - } - - public void setDocument(IDocument doc) { - fDocument = doc; - setDocumentOnAllStrategies(doc); - } - - /** - * Propagates a new document to all strategies and steps. - * - * @param document - */ - protected void setDocumentOnAllStrategies(IDocument document) { - if (isInstalled()) { - // set document on all regular strategies - if (fStrategies != null) { - Iterator e = fStrategies.values().iterator(); - while (e.hasNext()) { - IReconcilingStrategy strategy = (IReconcilingStrategy) e.next(); - strategy.setDocument(document); - } - } - } - } - - /** - * Sets the document partitioning for this reconciler. - * - * @param partitioning - * the document partitioning for this reconciler - * @since 3.0 - */ - public void setDocumentPartitioning(String partitioning) { - fPartitioning = partitioning; - } - - /** - * @param isInstalled - * The isInstalled to set. - */ - public void setInstalled(boolean isInstalled) { - fIsInstalled = isInstalled; - } - - private void setLocalProgressMonitor(IProgressMonitor pm) { - fLocalProgressMonitor = pm; - List strategyTypes = getStrategyTypes(); - // set on all other strategies - if (!strategyTypes.isEmpty()) { - Iterator it = strategyTypes.iterator(); - String type = null; - while (it.hasNext()) { - type = (String) it.next(); - if (getReconcilingStrategy(type) instanceof IReconcilingStrategyExtension) - ((IReconcilingStrategyExtension) getReconcilingStrategy(type)).setProgressMonitor(pm); - } - } - } - - /** - * Sets the strategy for a given contentType (partitionType) - * - * @see org.eclipse.jface.text.reconciler.Reconciler#setReconcilingStrategy(org.eclipse.jface.text.reconciler.IReconcilingStrategy, - * java.lang.String) - */ - public void setReconcilingStrategy(IReconcilingStrategy strategy, String contentType) { - - if (strategy == null) { - fStrategies.remove(contentType); - } - else { - fStrategies.put(contentType, strategy); - if (strategy instanceof IReconcilingStrategyExtension && getLocalProgressMonitor() != null) { - ((IReconcilingStrategyExtension)strategy).setProgressMonitor(getLocalProgressMonitor()); - } - strategy.setDocument(fDocument); - } - getStrategyTypes().add(contentType); - } - - /** - * @see org.eclipse.jface.text.reconciler.IReconciler#uninstall() - */ - public void uninstall() { - if (isInstalled()) { - setInstalled(false); - getLocalProgressMonitor().setCanceled(true); - } - setDocument(null); - } -}
\ No newline at end of file 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 80af4e31bf..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/DocumentAdapter.java +++ /dev/null @@ -1,44 +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.reconcile; - -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.reconciler.IReconcilableModel; - -/** - * Adapts an <code>IDocument</code> to a <code>IReconcilableModel</code>. - * - * @since 3.0 - */ -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/IReconcileAnnotationKey.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/IReconcileAnnotationKey.java deleted file mode 100644 index 052df0a46b..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, 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.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/IReconcileStepAdapter.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/IReconcileStepAdapter.java deleted file mode 100644 index b2df897172..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/IReconcileStepAdapter.java +++ /dev/null @@ -1,52 +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.reconcile; - -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.jface.text.reconciler.IReconcileResult; -import org.eclipse.wst.sse.core.INodeAdapter; -import org.eclipse.wst.sse.core.IndexedRegion; -import org.eclipse.wst.sse.ui.internal.IReleasable; - - -/** - * This interface is for reconcile steps that need to "work" off of - * StructuredDocument events, as well as the ReconcilerThread. - * - * @deprecated don't need this now that content model strategy will go away - */ -public interface IReconcileStepAdapter extends INodeAdapter, IReleasable { - - /** - * Partition types for which this step can add annootations. - * - * @return partition types for which this step can add annootations. - */ - String[] getPartitionTypes(); - - /** - * Marks a node for reconciling. - * - * @param o - */ - void markForReconciling(Object o); - - /** - * Reconcile call seeded with an indexedNode. - * - * @param monitor - * @param xmlNode - * @return - */ - IReconcileResult[] reconcile(IProgressMonitor monitor, IndexedRegion indexedNode); -} 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 3abb5f99e0..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, 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.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 8b441519e8..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, 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.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 fa89e2d4ba..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, 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.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 cf8bf163c2..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/StructuredReconcileStep.java +++ /dev/null @@ -1,237 +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.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.jface.text.reconciler.IReconcileStep; -import org.eclipse.wst.sse.core.text.IStructuredDocument; -import org.eclipse.wst.sse.core.text.IStructuredDocumentRegion; -import org.eclipse.wst.sse.core.text.IStructuredPartitionTypes; -import org.eclipse.wst.sse.core.text.IStructuredPartitioning; -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$ - } - - // 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 = 100; - public static final int ELEMENT_ERROR_LIMIT = 100; - - protected final IReconcileResult[] EMPTY_RECONCILE_RESULT_SET = new IReconcileResult[0]; - - private StructuredReconcileStep fNextStructuredStep = null; - /** - * 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 StructuredReconcileStep(IReconcileStep step) { - super(step); - if (step instanceof StructuredReconcileStep) - fNextStructuredStep = (StructuredReconcileStep) step; - fPartitionTypes = new HashSet(); - } - - public ReconcileAnnotationKey createKey(IStructuredDocumentRegion sdRegion, int scope) { - - ITypedRegion tr = getPartition(sdRegion); - String partitionType = (tr != null) ? tr.getType() : IStructuredPartitionTypes.UNKNOWN_PARTITION; - return createKey(partitionType, scope); - } - - /** - * @param sdRegion - * @return - */ - private 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() : IStructuredPartitionTypes.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); - // add next step's partition types - if (fNextStructuredStep != null) { - String[] nextResults = fNextStructuredStep.getPartitionTypes(); - for (int i = 0; i < nextResults.length; i++) - tempResults.add(nextResults[i]); - } - 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; - } - - /** - * If step passed in is found somewhere in the chain of steps. - * - * @return true if step passed in is found somewhere in the chain of - * steps, else false - */ - public boolean isSiblingStep(IReconcileStep step) { - if (step == null) - return false; - else if (step.equals(this)) - return true; - else if (isLastStep()) - return false; - else - return fNextStructuredStep.isSiblingStep(step); - } - - /** - * 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() { - if (fNextStructuredStep != null) - fNextStructuredStep.release(); - // we don't to null out the steps, in case - // it's reconfigured later - // fNextStructuredStep = null; - } -}
\ No newline at end of file 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 42d12ff61f..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/StructuredRegionProcessor.java +++ /dev/null @@ -1,524 +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.reconcile; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; - -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IDocumentPartitioner; -import org.eclipse.jface.text.ITextInputListener; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.ITypedRegion; -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.events.DisposeEvent; -import org.eclipse.swt.events.DisposeListener; -import org.eclipse.wst.sse.core.IModelLifecycleListener; -import org.eclipse.wst.sse.core.IStructuredModel; -import org.eclipse.wst.sse.core.IndexedRegion; -import org.eclipse.wst.sse.core.StructuredModelManager; -import org.eclipse.wst.sse.core.events.IStructuredDocumentListener; -import org.eclipse.wst.sse.core.events.NewDocumentEvent; -import org.eclipse.wst.sse.core.events.NoChangeEvent; -import org.eclipse.wst.sse.core.events.RegionChangedEvent; -import org.eclipse.wst.sse.core.events.RegionsReplacedEvent; -import org.eclipse.wst.sse.core.events.StructuredDocumentRegionsReplacedEvent; -import org.eclipse.wst.sse.core.internal.model.ModelLifecycleEvent; -import org.eclipse.wst.sse.core.text.IStructuredDocument; -import org.eclipse.wst.sse.core.text.IStructuredDocumentRegion; -import org.eclipse.wst.sse.core.text.IStructuredDocumentRegionList; -import org.eclipse.wst.sse.ui.internal.IReleasable; -import org.eclipse.wst.sse.ui.internal.reconcile.validator.ValidatorStrategy; - -/** - * Adds StructuredDocument and StructuredModel listeners. Adds Text viewer - * (dispose, input changed) listeners. - * - * Implements a smarter "contains" method. - * - * Adds default and validator strategies. Adds DirtyRegion processing logic. - */ -public class StructuredRegionProcessor extends DirtyRegionProcessor implements IStructuredDocumentListener, IModelLifecycleListener { - - /** - * Reconclies 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. - */ - private class SourceTextInputListener implements ITextInputListener { - - public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) { - // do nothing - } - - public void inputDocumentChanged(IDocument oldInput, IDocument newInput) { - handleInputDocumentChanged(oldInput, newInput); - } - } - - /** - * Cancels any running reconcile operations via progress monitor. Ensures - * that strategies are released on close of the editor. - */ - private class SourceWidgetDisposeListener implements DisposeListener { - - public void widgetDisposed(DisposeEvent e) { - handleWidgetDisposed(); - } - } - - /** to cancel any long running reconciles if someone closes the editor */ - private SourceWidgetDisposeListener fDisposeListener = null; - /** for initital reconcile when document is opened */ - private SourceTextInputListener fTextInputListener = null; - - - /** strategy called for unmapped partitions */ - private IReconcilingStrategy fDefaultStrategy; - - /** - * The strategy that runs validators contributed via - * <code>org.eclipse.wst.sse.ui.extensions.sourcevalidation</code> - * extension point - */ - private ValidatorStrategy fValidatorStrategy; - - /** - * @return Returns the fDefaultStrategy. - */ - public IReconcilingStrategy getDefaultStrategy() { - return fDefaultStrategy; - } - - /** - * @see org.eclipse.wst.sse.ui.internal.reconcile.DirtyRegionProcessor#getAppropriateStrategy(org.eclipse.jface.text.reconciler.DirtyRegion) - */ - protected IReconcilingStrategy getStrategy(DirtyRegion dirtyRegion) { - IReconcilingStrategy strategy = super.getStrategy(dirtyRegion); - if (strategy == null) - strategy = getDefaultStrategy(); - return strategy; - } - - /** - * @return Returns the fValidatorStrategy. - */ - public ValidatorStrategy getValidatorStrategy() { - return fValidatorStrategy; - } - - /** - * @param dirtyRegion - */ - protected void process(DirtyRegion dirtyRegion) { - if (!isInstalled()) - return; - - ITypedRegion[] unfiltered = computePartitioning(dirtyRegion); - - // remove duplicate typed regions - // that are handled by the same "total scope" strategy - ITypedRegion[] filtered = filterTotalScopeRegions(unfiltered); - - IReconcilingStrategy s; - DirtyRegion dirty = null; - for (int i = 0; i < filtered.length; i++) { - - dirty = createDirtyRegion(filtered[i], DirtyRegion.INSERT); - s = getReconcilingStrategy(filtered[i].getType()); - if (s != null && dirty != null) { - s.reconcile(dirty, dirty); - } - - // validator for this partition - if (fValidatorStrategy != null) - fValidatorStrategy.reconcile(filtered[i], dirty); - } - } - - /** - * Removed multiple "total-scope" regions (and leaves one) - * for a each partitionType. This improves performance - * by preventing unnecessary full document validations. - * - * @param unfiltered - * @return - */ - private ITypedRegion[] filterTotalScopeRegions(ITypedRegion[] unfiltered) { - IReconcilingStrategy s = null; - // ensure there is only one typed region in the list - // for regions handled by "total scope" strategies - HashMap totalScopeRegions = new HashMap(); - List allRegions = new ArrayList(); - for (int i = 0; i < unfiltered.length; i++) { - String partitionType = unfiltered[i].getType(); - s = getReconcilingStrategy(partitionType); - if(s instanceof AbstractStructuredTextReconcilingStrategy) { - // only allow one dirty region for a strategy - // that has "total scope" - if(((AbstractStructuredTextReconcilingStrategy)s).isTotalScope()) - totalScopeRegions.put(partitionType, unfiltered[i]); - else - allRegions.add(unfiltered[i]); - } - else - allRegions.add(unfiltered[i]); - } - allRegions.addAll(totalScopeRegions.values()); - ITypedRegion[] filtered = (ITypedRegion[])allRegions.toArray(new ITypedRegion[allRegions.size()]); - - if(DEBUG) - System.out.println("filtered out this many 'total-scope' regions: " + (unfiltered.length - filtered.length)); - - return filtered; - } - - /** - * @param defaultStrategy - * The fDefaultStrategy to set. - */ - public void setDefaultStrategy(IReconcilingStrategy defaultStrategy) { - fDefaultStrategy = defaultStrategy; - if (fDefaultStrategy != null) { - fDefaultStrategy.setDocument(getDocument()); - if (fDefaultStrategy instanceof IReconcilingStrategyExtension) - ((IReconcilingStrategyExtension) fDefaultStrategy).setProgressMonitor(getLocalProgressMonitor()); - } - } - - /** - * @see org.eclipse.wst.sse.ui.internal.reconcile.DirtyRegionProcessor#setDocumentOnAllStrategies(org.eclipse.jface.text.IDocument) - */ - protected void setDocumentOnAllStrategies(IDocument document) { - - super.setDocumentOnAllStrategies(document); - - IReconcilingStrategy defaultStrategy = getDefaultStrategy(); - IReconcilingStrategy validatorStrategy = getValidatorStrategy(); - - // default strategies - if (defaultStrategy != null) - defaultStrategy.setDocument(document); - - // external validator strategy - if (validatorStrategy != null) - validatorStrategy.setDocument(document); - } - - /** - * @param validatorStrategy - * The fValidatorStrategy to set. - */ - public void setValidatorStrategy(ValidatorStrategy validatorStrategy) { - fValidatorStrategy = validatorStrategy; - if (fValidatorStrategy != null) { - fValidatorStrategy.setDocument(getDocument()); - fValidatorStrategy.setProgressMonitor(getLocalProgressMonitor()); - } - } - - /** - * @see org.eclipse.wst.sse.ui.internal.reconcile.DirtyRegionProcessor#contains(org.eclipse.jface.text.reconciler.DirtyRegion, - * org.eclipse.jface.text.reconciler.DirtyRegion) - */ - protected boolean contains(DirtyRegion root, DirtyRegion possible) { - - // this method is a performance hit - // look for alternatives - - boolean contains = false; - IStructuredModel sModel = getStructuredModelForRead(getDocument()); - try { - IndexedRegion rootRegion = sModel.getIndexedRegion(root.getOffset()); - IndexedRegion possRegion = sModel.getIndexedRegion(possible.getOffset()); - if (rootRegion != null && possRegion != null) { - int rootStart = rootRegion.getStartOffset(); - int rootEnd = rootRegion.getEndOffset(); - int possStart = possRegion.getStartOffset(); - int possEnd = possRegion.getEndOffset(); - - if (rootStart <= possStart && rootEnd >= possEnd) - contains = true; - - if (DEBUG) - System.out.println("checking if [" + rootStart + ":" + rootEnd + "] contains [" + possStart + ":" + possEnd + "] ... " + contains); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ - } - } - finally { - if (sModel != null) - sModel.releaseFromRead(); - } - return contains; - } - - /** - * Remember to release model after use!! - * - * @return - */ - public IStructuredModel getStructuredModelForRead(IDocument doc) { - - IStructuredModel sModel = null; - if (doc != null) - sModel = StructuredModelManager.getModelManager().getExistingModelForRead(doc); - return sModel; - } - - /** - * - * @param oldInput - * @param newInput - */ - public void handleInputDocumentChanged(IDocument oldInput, IDocument newInput) { - // don't bother if reconciler not installed - if (isInstalled()) { - - reconcilerDocumentChanged(newInput); - - setDocument(newInput); - setDocumentOnAllStrategies(newInput); - setEntireDocumentDirty(newInput); - } - } - - public void handleWidgetDisposed() { - - getLocalProgressMonitor().setCanceled(true); - - List strategyTypes = getStrategyTypes(); - if (!strategyTypes.isEmpty()) { - Iterator it = strategyTypes.iterator(); - IReconcilingStrategy strategy = null; - while (it.hasNext()) { - strategy = getReconcilingStrategy((String) it.next()); - if (strategy instanceof IReleasable) { - ((IReleasable) strategy).release(); - strategy = null; - } - } - } - } - - /** - * @param document - */ - private void hookUpModelLifecycleListener(IDocument document) { - IStructuredModel sModel = getStructuredModelForRead(document); - try { - if (sModel != null) { - sModel.addModelLifecycleListener(this); - } - } - finally { - if (sModel != null) - sModel.releaseFromRead(); - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.sse.ui.internal.reconcile.DirtyRegionProcessor#install(org.eclipse.jface.text.ITextViewer) - */ - public void install(ITextViewer textViewer) { - - super.install(textViewer); - fDisposeListener = new SourceWidgetDisposeListener(); - fTextInputListener = new SourceTextInputListener(); - textViewer.getTextWidget().addDisposeListener(fDisposeListener); - textViewer.addTextInputListener(fTextInputListener); - } - - public void newModel(NewDocumentEvent structuredDocumentEvent) { - // happens on a revert - reconcilerDocumentChanged(structuredDocumentEvent.getDocument()); - } - - public void noChange(NoChangeEvent structuredDocumentEvent) { - // do nothing - } - - public void nodesReplaced(StructuredDocumentRegionsReplacedEvent structuredDocumentEvent) { - if (DEBUG) - System.out.println("[trace reconciler] >StructuredRegionProcessor: *NODES REPLACED"); //$NON-NLS-1$ - - DirtyRegion dr = partitionChanged(structuredDocumentEvent) ? createDirtyRegion(0, getDocument().getLength(), DirtyRegion.INSERT) : createDirtyRegion(structuredDocumentEvent.getOffset(), structuredDocumentEvent.getLength(), DirtyRegion.INSERT); - processDirtyRegion(dr); - } - - /** - * Checks if the StructuredDocumentEvent involved a partition change. If - * there's a partition change, we know we should run all strategies just - * to be sure we cover the new regions and remove obsolete annotations. - * - * A primitive check for now. - * - * @param structuredDocumentEvent - * @return - */ - private boolean partitionChanged(StructuredDocumentRegionsReplacedEvent structuredDocumentEvent) { - boolean changed = false; - - IDocumentPartitioner partitioner = structuredDocumentEvent.getStructuredDocument().getDocumentPartitioner(); - if (partitioner != null) { - IStructuredDocumentRegionList oldNodes = structuredDocumentEvent.getOldStructuredDocumentRegions(); - IStructuredDocumentRegionList newNodes = structuredDocumentEvent.getNewStructuredDocumentRegions(); - - IStructuredDocumentRegion oldNode = (oldNodes.getLength() > 0) ? oldNode = oldNodes.item(0) : null; - IStructuredDocumentRegion newNode = (newNodes.getLength() > 0) ? newNodes.item(0) : null; - - if (oldNode != null && newNode != null) - changed = partitioner.getContentType(oldNode.getStartOffset()).equals(partitioner.getContentType(newNode.getStartOffset())); - } - return changed; - } - - /** - * @see org.eclipse.wst.sse.core.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) { - - // check that it's this model that changed - IStructuredModel thisModel = getStructuredModelForRead(getDocument()); - try { - if (thisModel != null && event.getModel().equals(thisModel)) { - - 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); - // propagate document change - setDocumentOnAllStrategies(sDoc); - // ensure that the document is re-reconciled - setEntireDocumentDirty(sDoc); - } - } - finally { - if (thisModel != null) - thisModel.releaseFromRead(); - } - } - } - - /** - * @see org.eclipse.wst.sse.core.IModelLifecycleListener#processPreModelEvent(org.eclipse.wst.sse.core.internal.model.ModelLifecycleEvent) - */ - public void processPreModelEvent(ModelLifecycleEvent event) { - - if (event.getType() == ModelLifecycleEvent.MODEL_DOCUMENT_CHANGED) { - - getDirtyRegionQueue().clear(); - // note: old annotations are removed via the strategies on - // AbstractStructuredTextReconcilingStrategy#setDocument(...) - } - } - - /** - * Reinitializes listeners and sets new document onall strategies. - * - * @see org.eclipse.jface.text.reconciler.AbstractReconciler#reconcilerDocumentChanged(IDocument) - */ - protected void reconcilerDocumentChanged(IDocument newDocument) { - - IDocument currentDoc = getDocument(); - - // unhook old lifecycle listner - unhookModelLifecycleListener(currentDoc); - // add new lifecycle listener - hookUpModelLifecycleListener(newDocument); - - // unhook old document listener - if (currentDoc != null && currentDoc instanceof IStructuredDocument) - ((IStructuredDocument) currentDoc).removeDocumentChangedListener(this); - // hook up new document listener - if (newDocument != null && newDocument instanceof IStructuredDocument) - ((IStructuredDocument) newDocument).addDocumentChangedListener(this); - - // sets document on all strategies - super.reconcilerDocumentChanged(newDocument); - } - - public void regionChanged(RegionChangedEvent structuredDocumentEvent) { - if (DEBUG) - System.out.println("[trace reconciler] >StructuredRegionProcessor: *REGION CHANGED: \r\n\r\n created dirty region from flat model event >> :" + structuredDocumentEvent.getOffset() + ":" + structuredDocumentEvent.getLength() + "\r\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - - String dirtyRegionType = structuredDocumentEvent.getDeletedText().equals("") ? DirtyRegion.INSERT : DirtyRegion.REMOVE; //$NON-NLS-1$ - DirtyRegion dr = createDirtyRegion(structuredDocumentEvent.getOffset(), structuredDocumentEvent.getLength(), dirtyRegionType); - processDirtyRegion(dr); - } - - public void regionsReplaced(RegionsReplacedEvent structuredDocumentEvent) { - if (DEBUG) - System.out.println("[trace reconciler] >StructuredRegionProcessor: *REGIONS REPLACED: \r\n\r\n created dirty region from flat model event >> :" + structuredDocumentEvent.getOffset() + ":" + structuredDocumentEvent.getLength() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - - DirtyRegion dr = createDirtyRegion(structuredDocumentEvent.getOffset(), structuredDocumentEvent.getLength(), DirtyRegion.INSERT); - processDirtyRegion(dr); - } - - 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 - getDirtyRegionQueue().clear(); - DirtyRegion entireDocument = createDirtyRegion(0, document.getLength(), DirtyRegion.INSERT); - processDirtyRegion(entireDocument); - } - } - - /** - * @param document - */ - private void unhookModelLifecycleListener(IDocument document) { - IStructuredModel sModel = getStructuredModelForRead(document); - try { - if (sModel != null) - sModel.removeModelLifecycleListener(this); - - } - finally { - if (sModel != null) - sModel.releaseFromRead(); - } - } - - /** - * @see org.eclipse.wst.sse.ui.internal.reconcile.DirtyRegionProcessor#uninstall() - */ - public void uninstall() { - if (isInstalled()) { - getTextViewer().removeTextInputListener(fTextInputListener); - getTextViewer().getTextWidget().removeDisposeListener(fDisposeListener); - } - super.uninstall(); - } -} 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 906e02134f..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/TemporaryAnnotation.java +++ /dev/null @@ -1,262 +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.reconcile; - -import org.eclipse.jface.text.Position; -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 { - - public final static String ANNOT_BOOKMARK = "org.eclipse.ui.workbench.texteditor.bookmark"; //$NON-NLS-1$ - - // 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_SEARCH = Annotation.TYPE_UNKNOWN; - public final static String ANNOT_TASK = "org.eclipse.ui.workbench.texteditor.task"; //$NON-NLS-1$ - 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 TASK_LAYER; - - private static final int INFO_LAYER; - - private static final int WARNING_LAYER; - - private static final int ERROR_LAYER; - - private static final int BOOKMARK_LAYER; - - private static final int SEARCH_LAYER; - - static { - AnnotationPreferenceLookup lookup= EditorsUI.getAnnotationPreferenceLookup(); - TASK_LAYER= computeLayer("org.eclipse.ui.workbench.texteditor.task", lookup); //$NON-NLS-1$ - 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$ - BOOKMARK_LAYER= computeLayer("org.eclipse.ui.workbench.texteditor.bookmark", lookup); //$NON-NLS-1$ - SEARCH_LAYER= computeLayer("org.eclipse.search.results", 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 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; - } - else if(type.equals(ANNOT_BOOKMARK)) { - fLayer = BOOKMARK_LAYER; - } - else if(type.equals(ANNOT_SEARCH)) { - fLayer = SEARCH_LAYER; - } - else if(type.equals(ANNOT_TASK)) { - fLayer = TASK_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; - } - else if(type.equals(ANNOT_BOOKMARK)) { - fImage = null; - } - else if(type.equals(ANNOT_SEARCH)) { - fImage = null; - } - else if(type.equals(ANNOT_TASK)) { - 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; - } - - 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$ - } -} 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 7b3ce3402a..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, 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.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; - } - - 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 0a67a4b148..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/validator/IncrementalReporter.java +++ /dev/null @@ -1,90 +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.reconcile.validator; - -import java.util.ArrayList; -import java.util.HashMap; -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) { - Object existingValue = messages.get(validator); - if (existingValue != null) { - ((List) existingValue).add(message); - } - else { - List newValue = new ArrayList(1); - newValue.add(message); - 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 lists - // (one list per validator...) - Object[] lists = messages.values().toArray(); - for (int i = 0; i < lists.length; i++) { - result.addAll((List)lists[i]); - } - return result; - } - - 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 List) { - ((List)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 b65811f406..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/validator/ReconcileStepForValidator.java +++ /dev/null @@ -1,245 +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.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.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.reconciler.DirtyRegion; -import org.eclipse.jface.text.reconciler.IReconcileResult; -import org.eclipse.jface.text.reconciler.IReconcileStep; -import org.eclipse.wst.sse.core.IStructuredModel; -import org.eclipse.wst.sse.core.StructuredModelManager; -import org.eclipse.wst.sse.core.internal.util.URIResolver; -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.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; - private int fScope = -1; - private IValidator fValidator = null; - - - public ReconcileStepForValidator(IValidator v, int scope) { - super(); - - if(v == null) - throw new IllegalArgumentException("validator cannot be null"); //$NON-NLS-1$ - - fValidator = v; - fScope = scope; - } - - public ReconcileStepForValidator(IValidator v, IReconcileStep step, int scope) { - super(step); - 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 = 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; - } - Position p = new Position(offset, validationMessage.getLength()); - ReconcileAnnotationKey key = createKey(getPartitionType(getDocument(), offset), getScope()); - annotations.add(new TemporaryAnnotation(p, type, messageText, key)); - } - - return (IReconcileResult[]) annotations.toArray(new IReconcileResult[annotations.size()]); - } - - private IFile getFile(IProject project) { - - IFile file = null; - if (project != null) { - - IDocument doc = getDocument(); - // document may be null inbetween model/document swap - if (doc != null) { - IStructuredModel model = null; - try { - model = StructuredModelManager.getModelManager().getExistingModelForRead(doc); - // (pa) with FileBuffers, model base location is relative - // so we need to use the getFile(...) call - // file = - // project.getWorkspace().getRoot().getFileForLocation(new - // Path(model.getBaseLocation())); - file = project.getWorkspace().getRoot().getFile(new Path(model.getBaseLocation())); - } finally { - if (model != null) - model.releaseFromRead(); - } - } - } - return file; - } - - private IncrementalHelper getHelper(IProject project) { - if (fHelper == null) - fHelper = new IncrementalHelper(getStructuredDocument(), project); - return fHelper; - } - - private IProject getProject() { - - URIResolver resolver = null; - IDocument doc = getDocument(); - - if (doc != null) { - IStructuredModel model = StructuredModelManager.getModelManager().getExistingModelForRead(doc); - try { - if (model != null) - resolver = model.getResolver(); - } finally { - if (model != null) - model.releaseFromRead(); - } - } - return (resolver != null) ? resolver.getProject() : null; - } - - private IncrementalReporter getReporter() { - if (fReporter == null) - fReporter = new IncrementalReporter(getProgressMonitor()); - return fReporter; - } - - /** - * remove from extension point - * - * @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$ - - // pa_TODO need to use dirty region if Validators can ever handle - // partial file validation - IReconcileResult[] results = EMPTY_RECONCILE_RESULT_SET; - if (dirtyRegion != null) { - try { - 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.getClass().toString()); - return debugString.toString(); - } - - protected IReconcileResult[] validate() { - IReconcileResult[] results = EMPTY_RECONCILE_RESULT_SET; - - IProject project = getProject(); - IFile file = getFile(project); - - if (file != null) { - try { - IncrementalHelper helper = getHelper(project); - IncrementalReporter reporter = getReporter(); - - helper.setURI(file.getFullPath().toString()); - - fValidator.validate(helper, reporter); - - results = createAnnotations(reporter.getMessages()); - 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 75708f0eb0..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/validator/ValidatorBuilder.java +++ /dev/null @@ -1,144 +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.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); - } - - /* - * (non-Javadoc) - * - * @see com.ibm.sed.edit.internal.extension.RegistryReader#readElement(org.eclipse.core.runtime.IConfigurationElement) - */ - 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 6b3d65c375..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/validator/ValidatorMetaData.java +++ /dev/null @@ -1,217 +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.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 - */ -public class ValidatorMetaData { - private String fClass = null; - private IConfigurationElement fConfigurationElement = null; - private String fId = null; - private String fScope; - - // a hash map of 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); - } - - 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; - } - - public boolean canHandleParitionType(String contentTypeIds[], String paritionType) { - for(int i=0; i<contentTypeIds.length; i++) { - if (fMatrix.containsKey(contentTypeIds[i])) { - List partitions = (List) fMatrix.get(contentTypeIds[i]); - 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]; - } - - /** - * @param element - * @return Transfer - */ - 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; - } - - 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 555f0afd49..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/reconcile/validator/ValidatorStrategy.java +++ /dev/null @@ -1,200 +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.reconcile.validator; - -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.Set; - -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.ui.texteditor.ITextEditor; -import org.eclipse.wst.sse.ui.internal.reconcile.AbstractStructuredTextReconcilingStrategy; -import org.eclipse.wst.sse.ui.internal.reconcile.DocumentAdapter; -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.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 AbstractStructuredTextReconcilingStrategy { - - private String[] fContentTypeIds = null; - /** validator id (as declared in ext point) -> ReconcileStepForValidator **/ - private HashMap fVidToVStepMap = null; - private List fMetaData = null; - - public ValidatorStrategy(ITextEditor editor, String contentType) { - super(editor); - fMetaData = new ArrayList(); - fContentTypeIds = calculateParentContentTypeIds(contentType); - fVidToVStepMap = new HashMap(); - } - - /** - * 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()]); - } - - public void addValidatorMetaData(ValidatorMetaData vmd) { - fMetaData.add(vmd); - } - - /** - * - * @param partitionType - * @return true if the strategy contains at least one ValidatorMetaData - * that says it can handle the partition type (for a given content type) - */ - public boolean canValidatePartition(String partitionType) { - ValidatorMetaData vmd = null; - for (int i = 0; i < fMetaData.size(); i++) { - vmd = (ValidatorMetaData) fMetaData.get(i); - if (vmd.canHandleParitionType(getContentTypeIds(), partitionType)) - return true; - } - return false; - } - - /* - * so that removal will work properly - * - * @see org.eclipse.wst.sse.ui.reconcile.AbstractStructuredTextReconcilingStrategy#containsStep(org.eclipse.jface.text.reconciler.IReconcileStep) - */ - protected boolean containsStep(IReconcileStep step) { - return step != null ? fVidToVStepMap.values().contains(step) : false; - } - - /** - * @see org.eclipse.wst.sse.ui.reconcile.AbstractStructuredTextReconcilingStrategy#createReconcileSteps() - */ - public void createReconcileSteps() { - // do nothing, steps are created - } - - public String[] getContentTypeIds() { - return fContentTypeIds; - } - - /* - * so that removal will work properly - * - * @see org.eclipse.wst.sse.ui.reconcile.AbstractStructuredTextReconcilingStrategy#getPartitionTypes() - */ - public String[] getPartitionTypes() { - List partitionTypes = new ArrayList(); - Iterator keys = fVidToVStepMap.keySet().iterator(); - String key = null; - while (keys.hasNext()) { - key = (String) keys.next(); - StructuredReconcileStep step = (StructuredReconcileStep) fVidToVStepMap.get(key); - partitionTypes.addAll(Arrays.asList(step.getPartitionTypes())); - } - return (String[]) partitionTypes.toArray(new String[partitionTypes.size()]); - } - - public void reconcile(ITypedRegion tr, DirtyRegion dr) { - - // for external files, this can be null - if (getFile() != null) { - - String partitionType = tr.getType(); - if (canValidatePartition(partitionType)) { - ValidatorMetaData vmd = null; - - - // IReconcileResult[] - ArrayList annotationsToAdd = new ArrayList(); - // loop all of the relevant validator meta data - // to find new annotations - for (int i = 0; i < fMetaData.size(); i++) { - vmd = (ValidatorMetaData) fMetaData.get(i); - if (vmd.canHandleParitionType(getContentTypeIds(), partitionType)) { - // get step for partition type - Object o = fVidToVStepMap.get(vmd.getValidatorId()); - ReconcileStepForValidator validatorStep = null; - if (o != null) { - validatorStep = (ReconcileStepForValidator) o; - } else { - // if doesn't exist, create one - IValidator validator = vmd.createValidator(); - validatorStep = new ReconcileStepForValidator(validator, vmd.getValidatorScope()); - validatorStep.setInputModel(new DocumentAdapter(fDocument)); - - fVidToVStepMap.put(vmd.getValidatorId(), validatorStep); - } - annotationsToAdd.addAll(Arrays.asList(validatorStep.reconcile(dr, dr))); - } - } - - TemporaryAnnotation[] annotationsToRemove= getAnnotationsToRemove(dr); - if (annotationsToRemove.length + annotationsToAdd.size() > 0) - smartProcess(annotationsToRemove, (IReconcileResult[]) annotationsToAdd.toArray(new IReconcileResult[annotationsToAdd.size()])); - - } - } - } - - /** - * @see org.eclipse.wst.sse.ui.internal.reconcile.AbstractStructuredTextReconcilingStrategy#setDocument(org.eclipse.jface.text.IDocument) - */ - public void setDocument(IDocument document) { - - super.setDocument(document); - // 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)); - } - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/search/BasicFindOccurrencesAction.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/search/BasicFindOccurrencesAction.java deleted file mode 100644 index 6ef810cd02..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/search/BasicFindOccurrencesAction.java +++ /dev/null @@ -1,165 +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 java.util.ResourceBundle; - -import org.eclipse.core.resources.IFile; -import org.eclipse.search.ui.ISearchQuery; -import org.eclipse.search.ui.NewSearchUI; -import org.eclipse.ui.texteditor.ITextEditor; -import org.eclipse.ui.texteditor.TextEditorAction; -import org.eclipse.wst.sse.core.text.IStructuredDocument; -import org.eclipse.wst.sse.core.text.IStructuredDocumentRegion; -import org.eclipse.wst.sse.core.text.ITextRegion; -import org.eclipse.wst.sse.ui.internal.StructuredTextEditor; - - -/** - * <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> - * - * @author pavery - */ -public class BasicFindOccurrencesAction extends TextEditorAction { - private IStructuredDocument fDocument = null; - - private IFile fFile = null; - private String fMatchRegionType = null; - private String fMatchText = null; - - public BasicFindOccurrencesAction(ResourceBundle bundle, String prefix, ITextEditor editor) { - super(bundle, prefix, editor); - } - - /** - * @param editor - * @param sdRegion - * @param r - * @param type - */ - private void configure(StructuredTextEditor editor, IStructuredDocumentRegion sdRegion, ITextRegion r, String type) { - - this.fFile = editor.getFileInEditor(); - this.fDocument = (IStructuredDocument) editor.getDocument(); - this.fMatchText = sdRegion.getText(r); - this.fMatchRegionType = type; - } - - /** - * @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; - } - - /** - * @param regionType - * @return <code>true</code> if this action can operate on this region - * type (ITextRegion), otherwise false. - */ - public 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). - */ - protected String[] getPartitionTypes() { - return new String[0]; - } - - /** - * Clients should override this to enable find occurrences on different - * region type(s). - */ - protected String[] getRegionTypes() { - return new String[0]; - } - - /** - * Clients should override to provide their own search for the file. - * - */ - public ISearchQuery getSearchQuery() { - return new OccurrencesSearchQuery(this.fFile, this.fDocument, this.fMatchText, this.fMatchRegionType); - } - - public void run() { - - if (this.fDocument != null && this.fMatchText != null && this.fMatchRegionType != null) - NewSearchUI.runQuery(getSearchQuery()); - - unconfigure(); - } - - private void unconfigure() { - - this.fFile = null; - this.fDocument = null; - } - - /** - * Enables and initialzies the action, or disables. - * - * @see org.eclipse.ui.texteditor.TextEditorAction#update() - */ - public void update() { - - super.update(); - - // determine if action should be enabled or not - StructuredTextEditor editor = (StructuredTextEditor) getTextEditor(); - IStructuredDocumentRegion sdRegion = editor.getSelectedDocumentRegion(); - if (sdRegion != null) { - - ITextRegion r = editor.getSelectedTextRegion(sdRegion); - if (r != null) { - - String type = r.getType(); - if (enabledForRegionType(type)) { - configure(editor, sdRegion, r, type); - setEnabled(true); - } else { - unconfigure(); - setEnabled(false); - } - } - } - } -} 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 3c3d540adb..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/search/BasicSearchLabelProvider.java +++ /dev/null @@ -1,75 +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.core.resources.IMarker; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.jface.viewers.ILabelProvider; -import org.eclipse.jface.viewers.ILabelProviderListener; -import org.eclipse.search.ui.text.Match; -import org.eclipse.swt.graphics.Image; -import org.eclipse.wst.sse.ui.internal.Logger; -import org.eclipse.wst.sse.ui.internal.editor.EditorPluginImageHelper; -import org.eclipse.wst.sse.ui.internal.editor.EditorPluginImages; - - - -/** - * Basic label provider that just provides an image and default text. - * - * @author pavery - */ -public class BasicSearchLabelProvider implements ILabelProvider { - - public void addListener(ILabelProviderListener listener) { - // do nothing - } - - public void dispose() { - // do nothing - } - - public Image getImage(Object element) { - return EditorPluginImageHelper.getInstance().getImage(EditorPluginImages.IMG_OBJ_OCC_MATCH); - } - - public String getText(Object element) { - - StringBuffer text = new StringBuffer(); - if (element instanceof Match) { - Match m = (Match) element; - - IMarker marker = (IMarker) m.getElement(); - if (marker.exists()) { - String resultText = ""; //$NON-NLS-1$ - try { - resultText = (String) marker.getAttribute(IMarker.MESSAGE); - } catch (CoreException e) { - Logger.logException(e); - } - text.append(resultText); - } - } else { - text.append(element.toString()); - } - return text.toString(); - } - - public boolean isLabelProperty(Object element, String property) { - return false; - } - - public void removeListener(ILabelProviderListener listener) { - // do nothing - } -} 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 16bb7eba80..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/search/BasicSearchQuery.java +++ /dev/null @@ -1,210 +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 java.util.ArrayList; -import java.util.HashMap; -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.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.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.NewSearchUI; -import org.eclipse.search.ui.text.Match; -import org.eclipse.ui.texteditor.MarkerUtilities; -import org.eclipse.wst.sse.ui.internal.Logger; - - -/** - * @author pavery - */ -public class BasicSearchQuery implements ISearchQuery { - - /** attribute to identify markers added by find occurrences */ - public static final String ATTR_OCCURRENCES_MARKER = "occurrences_marker"; //$NON-NLS-1$ - - private static int LINE_LENGTH_LIMIT = 200; - - /** the file we're searching * */ - private IFile fFile = null; - /** occurrence search matches * */ - private List fMatches = null; - - public BasicSearchQuery(IFile file) { - this.fFile = file; - this.fMatches = new ArrayList(); - } - - 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 searchResultString = document.get().substring(lineStart, lineStart + lineLength).trim(); - - // create search marker (so annotations show up in editor) - IMarker marker = createSearchMarker(matchStart, matchEnd, lineNumber, searchResultString); - - addMatch(new Match(marker, Match.UNIT_CHARACTER, matchStart, matchStart + matchEnd)); - - } catch (BadLocationException e) { - Logger.logException(e); - } - } - - private void addMatch(Match match) { - if (match != null) - this.fMatches.add(match); - } - - /** - * @see org.eclipse.search.ui.ISearchQuery#canRerun() - */ - public boolean canRerun() { - return false; - } - - /** - * @see org.eclipse.search.ui.ISearchQuery#canRunInBackground() - */ - public boolean canRunInBackground() { - return true; - } - - public void clearMatches() { - this.fMatches.clear(); - } - - protected IMarker createSearchMarker(int matchStart, int matchEnd, int lineNumber, String searchResultString) { - - IMarker marker = null; - try { - if (getFile() != null) { - - marker = getFile().createMarker(NewSearchUI.SEARCH_MARKER); - HashMap attributes = new HashMap(6); - - MarkerUtilities.setCharStart(attributes, matchStart); - MarkerUtilities.setCharEnd(attributes, matchEnd); - MarkerUtilities.setLineNumber(attributes, lineNumber); - - // this might be bad if line of text is VERY long? - if (searchResultString.length() > LINE_LENGTH_LIMIT) - searchResultString = searchResultString.substring(0, LINE_LENGTH_LIMIT) + "..."; //$NON-NLS-1$ - MarkerUtilities.setMessage(attributes, searchResultString); - - // so we can remove them later - attributes.put(ATTR_OCCURRENCES_MARKER, new Boolean(true)); - - marker.setAttributes(attributes); - } - } catch (CoreException e) { - Logger.logException(e); - } - return marker; - } - - private void deleteOccurrencesMarkers() { - - final List removals = new ArrayList(); - try { - // clear all old find occurrences markers - IMarker[] searchMarkers = fFile.findMarkers(NewSearchUI.SEARCH_MARKER, false, IResource.DEPTH_ZERO); - for (int i = 0; i < searchMarkers.length; i++) { - Object o = searchMarkers[i].getAttribute(BasicSearchQuery.ATTR_OCCURRENCES_MARKER); - if (o != null && ((Boolean) o).booleanValue() == true) - removals.add(searchMarkers[i]); - - } - - if (removals.size() > 0) { - IWorkspaceRunnable runnable = new IWorkspaceRunnable() { - public void run(IProgressMonitor monitor) throws CoreException { - for (int i = 0; i < removals.size(); i++) - ((IMarker) removals.get(i)).delete(); - } - }; - ResourcesPlugin.getWorkspace().run(runnable, null); - } - } catch (CoreException e) { - Logger.logException(e); - } - } - - /** - * The acutal work of the query. Will be run in a background Job - * automatically if canRunInBackground(..) returns true. - * - * @return - */ - protected IStatus doQuery() { - return Status.OK_STATUS; - } - - /* - * public to avoid synthetic method access from inner class - */ - public IFile getFile() { - return this.fFile; - } - - /** - * @see org.eclipse.search.ui.ISearchQuery#getLabel() - */ - public String getLabel() { - return ""; //$NON-NLS-1$ - } - - public Match[] getMatches() { - // get rid of the old markers - deleteOccurrencesMarkers(); - doQuery(); - return (Match[]) this.fMatches.toArray(new Match[this.fMatches.size()]); - } - - /** - * @see org.eclipse.search.ui.ISearchQuery#getSearchResult() - */ - public ISearchResult getSearchResult() { - return null; - } - - /** - * used in search result display labels - * - * @return - */ - protected String getSearchText() { - return ""; //$NON-NLS-1$ - } - - /** - * @see org.eclipse.search.ui.ISearchQuery#run(org.eclipse.core.runtime.IProgressMonitor) - */ - public IStatus run(IProgressMonitor monitor) { - // defer to "get(...)" - return Status.OK_STATUS; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/search/FindOccurrencesActionProvider.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/search/FindOccurrencesActionProvider.java deleted file mode 100644 index 58597b33fc..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/search/FindOccurrencesActionProvider.java +++ /dev/null @@ -1,147 +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 java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.ResourceBundle; - -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.search.ui.NewSearchUI; -import org.eclipse.ui.texteditor.ITextEditor; -import org.eclipse.ui.texteditor.TextEditorAction; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; -import org.eclipse.wst.sse.ui.util.PlatformStatusLineUtil; - -/** - * Performs the appropriate FindOccurrences action call based on selection. - * Clients can add actions for different partitions via - * <code>addAction(BasicFindOccurrencesAction action)</code> - * - * @author pavery - */ -public class FindOccurrencesActionProvider extends TextEditorAction { - - private List fActions = null; - - public FindOccurrencesActionProvider(ResourceBundle bundle, String prefix, ITextEditor editor) { - - super(bundle, prefix, editor); - } - - public void addAction(BasicFindOccurrencesAction action) { - - getActions().add(action); - } - - private BasicFindOccurrencesAction getActionForCurrentSelection() { - - // check if we have an action that's enabled on the current partition - ITypedRegion tr = getPartition(); - String partition = tr != null ? tr.getType() : ""; //$NON-NLS-1$ - - Iterator it = getActions().iterator(); - BasicFindOccurrencesAction action = null; - while (it.hasNext()) { - action = (BasicFindOccurrencesAction) it.next(); - // we just choose the first action that can handle the partition - if (action.enabledForParitition(partition)) - return action; - } - return null; - } - - private List getActions() { - if (this.fActions == null) - this.fActions = new ArrayList(); - return this.fActions; - } - - private IDocument getDocument() { - return getTextEditor().getDocumentProvider().getDocument(getTextEditor().getEditorInput()); - } - - private ITypedRegion getPartition() { - ITextSelection sel = getTextSelection(); - ITypedRegion region = null; - if (sel != null) { - try { - region = getDocument().getPartition(sel.getOffset()); - } catch (BadLocationException e) { - region = null; - } - } - return region; - } - - private ITextSelection getTextSelection() { - ISelection selection = getTextEditor().getSelectionProvider().getSelection(); - if (selection instanceof ITextSelection && !selection.isEmpty()) { - ITextSelection textSel = (ITextSelection) selection; - return textSel; - } - return null; - } - - /** - * @see org.eclipse.jface.action.Action#isEnabled() - */ - public boolean isEnabled() { - // always enabled - return true; - } - - - /** - * @see org.eclipse.jface.action.Action#run() - */ - public void run() { - - BasicFindOccurrencesAction action = getActionForCurrentSelection(); - String errorMessage = SSEUIMessages.FindOccurrencesActionProvider_0; //$NON-NLS-1$ - if (action != null) { - action.update(); - if (action.isEnabled()) { - // first of all activate the view - NewSearchUI.activateSearchResultView(); - - // run the action - action.run(); - - // clear status message - PlatformStatusLineUtil.clearStatusLine(); - } else { - PlatformStatusLineUtil.displayErrorMessage(errorMessage); - PlatformStatusLineUtil.addOneTimeClearListener(); - } - } else { - PlatformStatusLineUtil.displayErrorMessage(errorMessage); - PlatformStatusLineUtil.addOneTimeClearListener(); - } - } - - /** - * @see org.eclipse.ui.texteditor.TextEditorAction#update() - */ - public void update() { - - super.update(); - // clear status message - PlatformStatusLineUtil.clearStatusLine(); - } -} 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 11251fd321..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/search/OccurrencesContentProvider.java +++ /dev/null @@ -1,89 +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.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.fResult != null) - this.fResult.clearMatches(); - 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 - int addCount = 0; - int removeCount = 0; - 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]); - addCount++; - } else { - this.fTableViewer.remove(updatedElements[i]); - removeCount++; - } - } - } - - - /** - * @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object) - */ - public Object[] getElements(Object inputElement) { - - this.fResult = (OccurrencesSearchResult) inputElement; - return this.fResult.getMatches(); - } - - /** - * @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 edba23d4df..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/search/OccurrencesSearchQuery.java +++ /dev/null @@ -1,179 +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 java.text.MessageFormat; - -import org.eclipse.core.resources.IFile; -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.search.ui.ISearchResult; -import org.eclipse.wst.sse.core.text.IStructuredDocument; -import org.eclipse.wst.sse.core.text.IStructuredDocumentRegion; -import org.eclipse.wst.sse.core.text.ITextRegion; -import org.eclipse.wst.sse.core.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); - this.fDocument = document; - this.fRegionText = regionText; - this.fRegionType = regionType; - } - - public boolean canRerun() { - return false; - } - - public boolean canRunInBackground() { - // pa_TODO investigate what is required to do this safely - return false; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.sse.ui.internal.search.BasicSearchQuery#doQuery() - */ - protected IStatus doQuery() { - - clearMatches(); - - IStatus status = Status.OK_STATUS; - FindRegions findRegions = new FindRegions(this.fDocument, this.fRegionText, this.fRegionType); - try { - ResourcesPlugin.getWorkspace().run(findRegions, null); - } catch (CoreException e) { - status = new Status(IStatus.ERROR, SSEUIPlugin.ID, IStatus.OK, "", null); //$NON-NLS-1$ - } - return status; - } - - private String getFilename() { - String filename = SSEUIMessages.OccurrencesSearchQuery_2; //$NON-NLS-1$ "file" - if (getFile() != null) - filename = getFile().getName().toString(); - return filename; - } - - public String getLabel() { - String label = SSEUIMessages.OccurrencesSearchQuery_0; //$NON-NLS-1$ - String[] args = {getSearchText(), getOccurrencesCountText(), getFilename()}; - return MessageFormat.format(label, args); - } - - /** - * @return - */ - private String getOccurrencesCountText() { - String count = ""; //$NON-NLS-1$ - // pa_TODO dynamically change count - return count; - } - - public ISearchResult getSearchResult() { - return new OccurrencesSearchResult(this); - } - - protected String getSearchText() { - return this.fRegionText; - } -} 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 2f7f7129a4..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/search/OccurrencesSearchResult.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.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; - } - - public void clearMatches() { - if (getQuery() instanceof OccurrencesSearchQuery) - ((OccurrencesSearchQuery) getQuery()).clearMatches(); - } - - /** - * @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) { - return getMatches(); - } - - 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(); - } - - public Match[] getMatches() { - // ensure that query is done running - return ((OccurrencesSearchQuery) getQuery()).getMatches(); - } - - public ISearchQuery getQuery() { - return this.fQuery; - } - - public String getTooltip() { - return getLabel(); - } - - /* - * (non-Javadoc) - * - * @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; - } -} 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 2d54131c92..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/search/OccurrencesSearchViewPage.java +++ /dev/null @@ -1,140 +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.core.resources.IMarker; -import org.eclipse.core.resources.IResource; -import org.eclipse.jface.viewers.TableViewer; -import org.eclipse.jface.viewers.TreeViewer; -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.ui.ide.IGotoMarker; -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) { - - // pa_TODO need sorter? - viewer.setLabelProvider(new BasicSearchLabelProvider()); - 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#getDisplayedMatches(java.lang.Object) - */ - public Match[] getDisplayedMatches(Object element) { - // https://w3.opensource.ibm.com/bugzilla/show_bug.cgi?id=2640 - // we only ever show one at a time, the element passed in is the match - // super was returning null - return new Match[]{(Match) element}; - } - - private void show(IMarker marker) { - - IResource resource = marker.getResource(); - if (resource == null || !resource.exists()) - return; - - IWorkbenchPage activePage = getActivePage(); - try { - if (activePage != null) { - - // open editor if needed - IDE.openEditor(getActivePage(), marker); - - IEditorPart editor = activePage.getActiveEditor(); - if (editor != null) { - IGotoMarker gotoMarker = (IGotoMarker) editor.getAdapter(IGotoMarker.class); - if (gotoMarker != null) - gotoMarker.gotoMarker(marker); - } - - } - } catch (PartInitException e) { - // possible exception trying to open editor - Logger.logException(e); - } - } - - /** - * @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) throws PartInitException { - Object o = match.getElement(); - if (o instanceof IMarker) { - show((IMarker) o); - } - } -} 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 7bafc46e1b..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/selection/SelectionHistory.java +++ /dev/null @@ -1,86 +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.selection; - -import java.util.ArrayList; -import java.util.List; - -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 StructureSelectHistoryAction fHistoryAction; - 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); - } - - public void flush() { - if (fHistory.isEmpty()) - return; - fHistory.clear(); - fHistoryAction.update(); - } - - public IRegion getLast() { - if (isEmpty()) - return null; - int size = fHistory.size(); - IRegion result = (IRegion) fHistory.remove(size - 1); - fHistoryAction.update(); - return result; - } - - public void ignoreSelectionChanges() { - fSelectionChangeListenerCounter++; - } - - public boolean isEmpty() { - return fHistory.isEmpty(); - } - - public void listenToSelectionChanges() { - fSelectionChangeListenerCounter--; - } - - public void remember(IRegion region) { - fHistory.add(region); - fHistoryAction.update(); - } - - public void setHistoryAction(StructureSelectHistoryAction action) { - Assert.isNotNull(action); - fHistoryAction = action; - } -} 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 0f8407b0f4..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/selection/StructureSelectAction.java +++ /dev/null @@ -1,97 +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.selection; - -import org.eclipse.jface.action.Action; -import org.eclipse.jface.text.Region; -import org.eclipse.jface.util.Assert; -import org.eclipse.wst.sse.core.IStructuredModel; -import org.eclipse.wst.sse.core.IndexedRegion; -import org.eclipse.wst.sse.ui.internal.StructuredTextEditor; -import org.eclipse.wst.sse.ui.internal.StructuredTextViewer; -import org.w3c.dom.Node; - - -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, SelectionHistory history) { - super(); - - Assert.isNotNull(editor); - Assert.isNotNull(history); - fEditor = editor; - fHistory = history; - fViewer = editor.getTextViewer(); - fModel = editor.getModel(); - Assert.isNotNull(fViewer); - //Assert.isNotNull(fModel); - } - - abstract protected IndexedRegion getCursorIndexedRegion(); - - protected IndexedRegion getIndexedRegion(int offset) { - IndexedRegion indexedRegion = null; - - int lastOffset = offset; - indexedRegion = fModel.getIndexedRegion(lastOffset); - while (indexedRegion == null && lastOffset >= 0) { - lastOffset--; - indexedRegion = fModel.getIndexedRegion(lastOffset); - } - - 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/StructureSelectEnclosingAction.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/selection/StructureSelectEnclosingAction.java deleted file mode 100644 index c914463c35..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/selection/StructureSelectEnclosingAction.java +++ /dev/null @@ -1,45 +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.selection; - -import org.eclipse.jface.text.Region; -import org.eclipse.wst.sse.core.IndexedRegion; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; -import org.eclipse.wst.sse.ui.internal.StructuredTextEditor; -import org.w3c.dom.Node; - -public class StructureSelectEnclosingAction extends StructureSelectAction { - public StructureSelectEnclosingAction(StructuredTextEditor editor, SelectionHistory history) { - super(editor, history); - setText(SSEUIMessages.StructureSelectEnclosing_label); //$NON-NLS-1$ - setToolTipText(SSEUIMessages.StructureSelectEnclosing_tooltip); //$NON-NLS-1$ - setDescription(SSEUIMessages.StructureSelectEnclosing_description); //$NON-NLS-1$ - } - - protected IndexedRegion getCursorIndexedRegion() { - return getIndexedRegion(fViewer.getSelectedRange().x); - } - - protected Region getNewSelectionRegion(Node node, Region region) { - Region newRegion = null; - - Node newNode = node.getParentNode(); - - if (newNode instanceof IndexedRegion) { - IndexedRegion newIndexedRegion = (IndexedRegion) newNode; - newRegion = new Region(newIndexedRegion.getStartOffset(), newIndexedRegion.getEndOffset() - newIndexedRegion.getStartOffset()); - } - - return newRegion; - } -} 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 405c856b87..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, 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.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.IndexedRegion; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; -import org.eclipse.wst.sse.ui.internal.StructuredTextEditor; -import org.w3c.dom.Node; - -public class StructureSelectHistoryAction extends StructureSelectAction implements IUpdate { - public StructureSelectHistoryAction(StructuredTextEditor editor, SelectionHistory history) { - super(editor, history); - 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/StructureSelectNextAction.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/selection/StructureSelectNextAction.java deleted file mode 100644 index cf969bf491..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/selection/StructureSelectNextAction.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.selection; - -import org.eclipse.jface.text.Region; -import org.eclipse.wst.sse.core.IndexedRegion; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; -import org.eclipse.wst.sse.ui.internal.StructuredTextEditor; -import org.w3c.dom.Node; - -public class StructureSelectNextAction extends StructureSelectAction { - public StructureSelectNextAction(StructuredTextEditor editor, SelectionHistory history) { - super(editor, history); - setText(SSEUIMessages.StructureSelectNext_label); //$NON-NLS-1$ - setToolTipText(SSEUIMessages.StructureSelectNext_tooltip); //$NON-NLS-1$ - setDescription(SSEUIMessages.StructureSelectNext_description); //$NON-NLS-1$ - } - - protected IndexedRegion getCursorIndexedRegion() { - int offset = fViewer.getSelectedRange().x + fViewer.getSelectedRange().y - 1; - - if (offset < 0) - offset = 0; - - return getIndexedRegion(offset); - } - - protected Region getNewSelectionRegion(Node node, Region region) { - Region newRegion = null; - - Node newNode = node.getNextSibling(); - if (newNode == null) { - newNode = node.getParentNode(); - - if (newNode instanceof IndexedRegion) { - IndexedRegion newIndexedRegion = (IndexedRegion) newNode; - newRegion = new Region(newIndexedRegion.getStartOffset(), newIndexedRegion.getEndOffset() - newIndexedRegion.getStartOffset()); - } - } else { - if (newNode instanceof IndexedRegion) { - IndexedRegion newIndexedRegion = (IndexedRegion) newNode; - newRegion = new Region(region.getOffset(), newIndexedRegion.getEndOffset() - region.getOffset()); - - if (newNode.getNodeType() == Node.TEXT_NODE) - newRegion = getNewSelectionRegion(newNode, newRegion); - } - } - - return newRegion; - } -} diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/selection/StructureSelectPreviousAction.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/selection/StructureSelectPreviousAction.java deleted file mode 100644 index 92c2505a5e..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/selection/StructureSelectPreviousAction.java +++ /dev/null @@ -1,56 +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.selection; - -import org.eclipse.jface.text.Region; -import org.eclipse.wst.sse.core.IndexedRegion; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; -import org.eclipse.wst.sse.ui.internal.StructuredTextEditor; -import org.w3c.dom.Node; - -public class StructureSelectPreviousAction extends StructureSelectAction { - public StructureSelectPreviousAction(StructuredTextEditor editor, SelectionHistory history) { - super(editor, history); - setText(SSEUIMessages.StructureSelectPrevious_label); //$NON-NLS-1$ - setToolTipText(SSEUIMessages.StructureSelectPrevious_tooltip); //$NON-NLS-1$ - setDescription(SSEUIMessages.StructureSelectPrevious_description); //$NON-NLS-1$ - } - - protected IndexedRegion getCursorIndexedRegion() { - return getIndexedRegion(fViewer.getSelectedRange().x); - } - - protected Region getNewSelectionRegion(Node node, Region region) { - Region newRegion = null; - - Node newNode = node.getPreviousSibling(); - if (newNode == null) { - newNode = node.getParentNode(); - - if (newNode instanceof IndexedRegion) { - IndexedRegion newIndexedRegion = (IndexedRegion) newNode; - newRegion = new Region(newIndexedRegion.getStartOffset(), newIndexedRegion.getEndOffset() - newIndexedRegion.getStartOffset()); - } - } else { - if (newNode instanceof IndexedRegion) { - IndexedRegion newIndexedRegion = (IndexedRegion) newNode; - newRegion = new Region(newIndexedRegion.getStartOffset(), region.getOffset() + region.getLength() - newIndexedRegion.getStartOffset()); - - if (newNode.getNodeType() == Node.TEXT_NODE) - newRegion = getNewSelectionRegion(newNode, newRegion); - } - } - - return newRegion; - } -} 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 e96ee19a89..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/taginfo/DebugInfoHoverProcessor.java +++ /dev/null @@ -1,91 +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.taginfo; - - - -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.ITextHover; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.ITypedRegion; - -/** - * Provides debug hover help - * - * @author amywu - * @see org.eclipse.jface.text.ITextHover - */ -public class DebugInfoHoverProcessor implements ITextHover { - 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 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/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 19180a3e3c..0000000000 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/ui/OffsetStatusLineContributionItem.java +++ /dev/null @@ -1,447 +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 - * - *******************************************************************************/ -package org.eclipse.wst.sse.ui.internal.ui; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; - -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.ITextSelection; -import org.eclipse.jface.text.ITypedRegion; -import org.eclipse.jface.text.TextUtilities; -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.swt.SWT; -import org.eclipse.swt.custom.SashForm; -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.Combo; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.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.texteditor.ITextEditor; -import org.eclipse.ui.texteditor.StatusLineContributionItem; -import org.eclipse.wst.sse.core.IStructuredModel; -import org.eclipse.wst.sse.core.StructuredModelManager; -import org.eclipse.wst.sse.core.internal.util.Utilities; -import org.eclipse.wst.sse.core.text.IStructuredDocument; -import org.eclipse.wst.sse.core.text.IStructuredDocumentRegion; -import org.eclipse.wst.sse.core.text.IStructuredPartitioning; -import org.eclipse.wst.sse.core.text.ITextRegion; -import org.eclipse.wst.sse.core.text.ITextRegionCollection; -import org.eclipse.wst.sse.core.text.ITextRegionContainer; -import org.eclipse.wst.sse.core.text.ITextRegionList; -import org.eclipse.wst.sse.ui.internal.SSEUIMessages; - -/** - * @author nsd A Status Line contribution intended to display the selected - * offsets in an editor. Double-clicking shows information about - * partitions and the Structured Document regions. - */ -public class OffsetStatusLineContributionItem extends StatusLineContributionItem { - - class InformationDialog extends Dialog { - IDocument fDocument = fTextEditor.getDocumentProvider().getDocument(fTextEditor.getEditorInput()); - - public InformationDialog(Shell parentShell) { - super(parentShell); - setShellStyle(getShellStyle() | SWT.RESIZE); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite) - */ - protected Control createDialogArea(Composite parent) { - ISelection sel = fTextEditor.getSelectionProvider().getSelection(); - ITextSelection textSelection = (ITextSelection) sel; - parent.getShell().setText(SSEUIMessages.OffsetStatusLineContributionItem_0 + textSelection.getOffset() + "-" + (textSelection.getOffset() + textSelection.getLength())); //$NON-NLS-1$ //$NON-NLS-2$ - Composite composite = (Composite) super.createDialogArea(parent); - - 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$ - Composite partitions = new Composite(tabfolder, SWT.NONE); - partitionTab.setControl(partitions); - createPartitionContents(partitions); - - // 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); - createRegionsContents(regions); - } - - return composite; - } - - /** - * @param area - */ - private void createPartitionContents(Composite area) { - area.setLayout(new GridLayout()); - area.setLayoutData(new GridData()); - - Composite partioningComposite = new Composite(area, SWT.NONE); - partioningComposite.setLayout(new GridLayout(2, false)); - partioningComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); - - IStructuredModel model = StructuredModelManager.getModelManager().getExistingModelForRead(fDocument); - if (model != null) { - Text modelContentTypeLabel = new Text(partioningComposite, SWT.SINGLE | SWT.READ_ONLY); - GridData 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(partioningComposite, 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() + " (" + model.getModelHandler().getAssociatedContentTypeId() + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - - Label blankRow = new Label(partioningComposite, SWT.NONE); - gd = new GridData(SWT.FILL, SWT.FILL, true, false); - gd.horizontalSpan = 2; - blankRow.setLayoutData(gd); - } - if (model != null) { - model.releaseFromRead(); - } - - Text label = new Text(partioningComposite, SWT.SINGLE | SWT.READ_ONLY); - 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 Text partitionerInstanceLabel = new Text(partioningComposite, SWT.SINGLE | SWT.READ_ONLY); - 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().toString(); - 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 { - 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; - fPartitionTable.setInput(TextUtilities.computePartitioning(fDocument, selectedPartitioning, textSelection.getOffset(), textSelection.getLength(), true)); - String partitionerText = fDocument instanceof IDocumentExtension3 ? ((IDocumentExtension3) fDocument).getDocumentPartitioner(partitioningCombo.getItem(partitioningCombo.getSelectionIndex())).toString() : fDocument.getDocumentPartitioner().toString(); - partitionerInstanceLabel.setText(SSEUIMessages.OffsetStatusLineContributionItem_14 + partitionerText); //$NON-NLS-1$ - } - catch (BadLocationException e1) { - fPartitionTable.setInput(new ITypedRegion[0]); - } - partitioningCombo.setFocus(); - } - - /** - * @param composite - * @return - */ - private Composite createRegionsContents(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 Pair(CONTEXT, ((ITextRegion) parentElement).getType())); - children.add(new Pair(START, Integer.toString(((ITextRegion) parentElement).getStart()))); - children.add(new Pair(TEXTLENGTH, Integer.toString(((ITextRegion) parentElement).getTextLength()))); - children.add(new Pair(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 new Object[]{textSelection}; - } - - public Object getParent(Object element) { - if (element instanceof IStructuredDocumentRegion) - return ((IStructuredDocumentRegion) element).getParentDocument(); - if (element instanceof ITextRegionContainer) { - return ((ITextRegionContainer) element).getParent(); - } - return null; - } - - public boolean hasChildren(Object element) { - return !(element instanceof Pair); - } - - public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { - } - }); - tree.setLabelProvider(new LabelProvider() { - public String getText(Object element) { - if (element instanceof Pair) - return ((Pair) element).fKey.toString().toLowerCase() + ": " + ((Pair) 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 Pair) - displayText.setText(((Pair) 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 - displayText.setText("" + o); //$NON-NLS-1$ - } - } - }); - sashForm.setWeights(new int[]{3, 2}); - return sashForm; - } - } - - static class Pair { - Object fKey; - String fValue; - - public Pair(Object key, String value) { - fKey = key; - fValue = value; - } - } - - class ShowPartitionAction extends Action { - public ShowPartitionAction() { - 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 fShowPartitionAction = new ShowPartitionAction(); - - ITextEditor fTextEditor = null; - - /** - * @param id - */ - public OffsetStatusLineContributionItem(String id) { - super(id); - } - - /** - * @param id - * @param visible - * @param widthInChars - */ - public OffsetStatusLineContributionItem(String id, boolean visible, int widthInChars) { - super(id, visible, widthInChars); - } - - public void setActiveEditor(ITextEditor textEditor) { - fTextEditor = textEditor; - setActionHandler(fShowPartitionAction); - } -} 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 b835eda0e0..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, 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.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; - } - -} |